🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@bufbuild/protobuf

Package Overview
Dependencies
Maintainers
5
Versions
76
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bufbuild/protobuf - npm Package Compare versions

Comparing version
2.12.0
to
2.12.1
+6
dist/commonjs/clone.d.ts
import type { MessageShape } from "./types.js";
import { type DescMessage } from "./descriptors.js";
/**
* Create a deep copy of a message, including extensions and unknown fields.
*/
export declare function clone<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>): MessageShape<Desc>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.clone = clone;
const descriptors_js_1 = require("./descriptors.js");
const reflect_js_1 = require("./reflect/reflect.js");
const guard_js_1 = require("./reflect/guard.js");
/**
* Create a deep copy of a message, including extensions and unknown fields.
*/
function clone(schema, message) {
return cloneReflect((0, reflect_js_1.reflect)(schema, message)).message;
}
function cloneReflect(i) {
const o = (0, reflect_js_1.reflect)(i.desc);
for (const f of i.fields) {
if (!i.isSet(f)) {
continue;
}
switch (f.fieldKind) {
case "list":
const list = o.get(f);
for (const item of i.get(f)) {
list.add(cloneSingular(f, item));
}
break;
case "map":
const map = o.get(f);
for (const entry of i.get(f).entries()) {
map.set(entry[0], cloneSingular(f, entry[1]));
}
break;
default: {
o.set(f, cloneSingular(f, i.get(f)));
break;
}
}
}
const unknown = i.getUnknown();
if (unknown && unknown.length > 0) {
o.setUnknown([...unknown]);
}
return o;
}
function cloneSingular(field, value) {
if (field.message !== undefined && (0, guard_js_1.isReflectMessage)(value)) {
return cloneReflect(value);
}
if (field.scalar == descriptors_js_1.ScalarType.BYTES && value instanceof Uint8Array) {
// @ts-expect-error T cannot extend Uint8Array in practice
return value.slice();
}
return value;
}
export { boot } from "../codegenv2/boot.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.boot = void 0;
var boot_js_1 = require("../codegenv2/boot.js");
Object.defineProperty(exports, "boot", { enumerable: true, get: function () { return boot_js_1.boot; } });
import type { DescFile } from "../descriptors.js";
import type { GenEnum } from "./types.js";
import type { JsonValue } from "../json-value.js";
export { tsEnum } from "../codegenv2/enum.js";
/**
* Hydrate an enum descriptor.
*
* @private
*/
export declare function enumDesc<Shape extends number, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenEnum<Shape, JsonType>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.tsEnum = void 0;
exports.enumDesc = enumDesc;
var enum_js_1 = require("../codegenv2/enum.js");
Object.defineProperty(exports, "tsEnum", { enumerable: true, get: function () { return enum_js_1.tsEnum; } });
/**
* Hydrate an enum descriptor.
*
* @private
*/
function enumDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.enums[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedEnums[e];
}
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenExtension } from "./types.js";
/**
* Hydrate an extension descriptor.
*
* @private
*/
export declare function extDesc<Extendee extends Message, Value>(file: DescFile, path: number, ...paths: number[]): GenExtension<Extendee, Value>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.extDesc = extDesc;
/**
* Hydrate an extension descriptor.
*
* @private
*/
function extDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.extensions[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedExtensions[e];
}
export { fileDesc } from "../codegenv2/file.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileDesc = void 0;
var file_js_1 = require("../codegenv2/file.js");
Object.defineProperty(exports, "fileDesc", { enumerable: true, get: function () { return file_js_1.fileDesc; } });
export * from "../codegenv2/boot.js";
export * from "../codegenv2/embed.js";
export * from "./enum.js";
export * from "./extension.js";
export * from "./file.js";
export * from "./message.js";
export * from "./service.js";
export * from "./symbols.js";
export * from "../codegenv2/scalar.js";
export * from "./types.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("../codegenv2/boot.js"), exports);
__exportStar(require("../codegenv2/embed.js"), exports);
__exportStar(require("./enum.js"), exports);
__exportStar(require("./extension.js"), exports);
__exportStar(require("./file.js"), exports);
__exportStar(require("./message.js"), exports);
__exportStar(require("./service.js"), exports);
__exportStar(require("./symbols.js"), exports);
__exportStar(require("../codegenv2/scalar.js"), exports);
__exportStar(require("./types.js"), exports);
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenMessage } from "./types.js";
import type { JsonValue } from "../json-value.js";
/**
* Hydrate a message descriptor.
*
* @private
*/
export declare function messageDesc<Shape extends Message, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenMessage<Shape, JsonType>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.messageDesc = messageDesc;
/**
* Hydrate a message descriptor.
*
* @private
*/
function messageDesc(file, path, ...paths) {
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]);
}
import type { GenService, GenServiceMethods } from "./types.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a service descriptor.
*
* @private
*/
export declare function serviceDesc<T extends GenServiceMethods>(file: DescFile, path: number, ...paths: number[]): GenService<T>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceDesc = serviceDesc;
/**
* Hydrate a service descriptor.
*
* @private
*/
function serviceDesc(file, path, ...paths) {
if (paths.length > 0) {
throw new Error();
}
return file.services[path];
}
/**
* @private
*/
export declare const packageName = "@bufbuild/protobuf";
/**
* @private
*/
export declare const wktPublicImportPaths: Readonly<Record<string, string>>;
/**
* @private
*/
export declare const symbols: {
readonly codegen: {
readonly boot: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/boot.js";
readonly from: string;
};
readonly fileDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/file.js";
readonly from: string;
};
readonly enumDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/enum.js";
readonly from: string;
};
readonly extDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/extension.js";
readonly from: string;
};
readonly messageDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/message.js";
readonly from: string;
};
readonly serviceDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/service.js";
readonly from: string;
};
readonly tsEnum: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/enum.js";
readonly from: string;
};
readonly GenFile: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenEnum: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenExtension: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenMessage: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenService: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
};
readonly isMessage: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../is-message.js";
readonly from: "@bufbuild/protobuf";
};
readonly Message: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../types.js";
readonly from: "@bufbuild/protobuf";
};
readonly create: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../create.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly protoInt64: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../proto-int64.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonValue: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonObject: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../json-value.js";
readonly from: "@bufbuild/protobuf";
};
};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.symbols = exports.wktPublicImportPaths = exports.packageName = void 0;
const symbols_js_1 = require("../codegenv2/symbols.js");
/**
* @private
*/
exports.packageName = symbols_js_1.packageName;
/**
* @private
*/
exports.wktPublicImportPaths = symbols_js_1.wktPublicImportPaths;
/**
* @private
*/
// biome-ignore format: want this to read well
exports.symbols = Object.assign(Object.assign({}, symbols_js_1.symbols), { codegen: {
boot: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/boot.js", from: exports.packageName + "/codegenv1" },
fileDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/file.js", from: exports.packageName + "/codegenv1" },
enumDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/enum.js", from: exports.packageName + "/codegenv1" },
extDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/extension.js", from: exports.packageName + "/codegenv1" },
messageDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/message.js", from: exports.packageName + "/codegenv1" },
serviceDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/service.js", from: exports.packageName + "/codegenv1" },
tsEnum: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/enum.js", from: exports.packageName + "/codegenv1" },
GenFile: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenEnum: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenExtension: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenMessage: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenService: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
} });
import type { Message } from "../types.js";
import type { DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescService } from "../descriptors.js";
import type { JsonValue } from "../json-value.js";
/**
* Describes a protobuf source file.
*
* @private
*/
export type GenFile = DescFile;
/**
* Describes a message declaration in a protobuf source file.
*
* This type is identical to DescMessage, but carries additional type
* information.
*
* @private
*/
export type GenMessage<RuntimeShape extends Message, JsonType = JsonValue> = Omit<DescMessage, "field" | "typeName"> & {
field: Record<MessageFieldNames<RuntimeShape>, DescField>;
typeName: RuntimeShape["$typeName"];
} & brandv1<RuntimeShape, JsonType>;
/**
* Describes an enumeration in a protobuf source file.
*
* This type is identical to DescEnum, but carries additional type
* information.
*
* @private
*/
export type GenEnum<RuntimeShape extends number, JsonType extends JsonValue = JsonValue> = Omit<DescEnum, "value"> & {
value: Record<RuntimeShape, DescEnumValue>;
} & brandv1<RuntimeShape, JsonType>;
/**
* Describes an extension in a protobuf source file.
*
* This type is identical to DescExtension, but carries additional type
* information.
*
* @private
*/
export type GenExtension<Extendee extends Message = Message, RuntimeShape = unknown> = DescExtension & brandv1<Extendee, RuntimeShape>;
/**
* Describes a service declaration in a protobuf source file.
*
* This type is identical to DescService, but carries additional type
* information.
*
* @private
*/
export type GenService<RuntimeShape extends GenServiceMethods> = Omit<DescService, "method"> & {
method: {
[K in keyof RuntimeShape]: RuntimeShape[K] & DescMethod;
};
};
/**
* @private
*/
export type GenServiceMethods = Record<string, Pick<DescMethod, "input" | "output" | "methodKind">>;
type brandv1<A, B = unknown> = {
/**
* @internal
*/
readonly $codegenv1: {
a: A;
b: B;
};
};
/**
* Union of the property names of all fields, including oneof members.
* For an anonymous message (no generated message shape), it's simply a string.
*/
type MessageFieldNames<T extends Message> = Message extends T ? string : Exclude<keyof {
[P in keyof T as P extends ("$typeName" | "$unknown") ? never : T[P] extends Oneof<infer K> ? K : P]-?: true;
}, number | symbol>;
type Oneof<K extends string> = {
case: K | undefined;
value?: unknown;
};
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
import type { DescriptorProto_ExtensionRange, FieldDescriptorProto_Label, FieldDescriptorProto_Type, FieldOptions_OptionRetention, FieldOptions_OptionTargetType, FieldOptions_EditionDefault, EnumValueDescriptorProto, FileDescriptorProto } from "../wkt/gen/google/protobuf/descriptor_pb.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a file descriptor for google/protobuf/descriptor.proto from a plain
* object.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export declare function boot(boot: FileDescriptorProtoBoot): DescFile;
/**
* An object literal for initializing the message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export type FileDescriptorProtoBoot = {
name: "google/protobuf/descriptor.proto";
package: "google.protobuf";
messageType: DescriptorProtoBoot[];
enumType: EnumDescriptorProtoBoot[];
};
export type DescriptorProtoBoot = {
name: string;
field?: FieldDescriptorProtoBoot[];
nestedType?: DescriptorProtoBoot[];
enumType?: EnumDescriptorProtoBoot[];
extensionRange?: Pick<DescriptorProto_ExtensionRange, "start" | "end">[];
};
export type FieldDescriptorProtoBoot = {
name: string;
number: number;
label?: FieldDescriptorProto_Label;
type: FieldDescriptorProto_Type;
typeName?: string;
extendee?: string;
defaultValue?: string;
options?: FieldOptionsBoot;
};
export type FieldOptionsBoot = {
packed?: boolean;
deprecated?: boolean;
retention?: FieldOptions_OptionRetention;
targets?: FieldOptions_OptionTargetType[];
editionDefaults?: FieldOptions_EditionDefaultBoot[];
};
export type FieldOptions_EditionDefaultBoot = Pick<FieldOptions_EditionDefault, "edition" | "value">;
export type EnumDescriptorProtoBoot = {
name: string;
value: EnumValueDescriptorProtoBoot[];
};
export type EnumValueDescriptorProtoBoot = Pick<EnumValueDescriptorProto, "name" | "number">;
/**
* Creates the message google.protobuf.FileDescriptorProto from an object literal.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export declare function bootFileDescriptorProto(init: FileDescriptorProtoBoot): FileDescriptorProto;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.boot = boot;
exports.bootFileDescriptorProto = bootFileDescriptorProto;
const restore_json_names_js_1 = require("./restore-json-names.js");
const registry_js_1 = require("../registry.js");
/**
* Hydrate a file descriptor for google/protobuf/descriptor.proto from a plain
* object.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
function boot(boot) {
const root = bootFileDescriptorProto(boot);
root.messageType.forEach(restore_json_names_js_1.restoreJsonNames);
const reg = (0, registry_js_1.createFileRegistry)(root, () => undefined);
// biome-ignore lint/style/noNonNullAssertion: non-null assertion because we just created the registry from the file we look up
return reg.getFile(root.name);
}
/**
* Creates the message google.protobuf.FileDescriptorProto from an object literal.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
function bootFileDescriptorProto(init) {
const proto = Object.create({
syntax: "",
edition: 0,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FileDescriptorProto", dependency: [], publicDependency: [], weakDependency: [], optionDependency: [], service: [], extension: [] }, init), { messageType: init.messageType.map(bootDescriptorProto), enumType: init.enumType.map(bootEnumDescriptorProto) }));
}
function bootDescriptorProto(init) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const proto = Object.create({
visibility: 0,
});
return Object.assign(proto, {
$typeName: "google.protobuf.DescriptorProto",
name: init.name,
field: (_b = (_a = init.field) === null || _a === void 0 ? void 0 : _a.map(bootFieldDescriptorProto)) !== null && _b !== void 0 ? _b : [],
extension: [],
nestedType: (_d = (_c = init.nestedType) === null || _c === void 0 ? void 0 : _c.map(bootDescriptorProto)) !== null && _d !== void 0 ? _d : [],
enumType: (_f = (_e = init.enumType) === null || _e === void 0 ? void 0 : _e.map(bootEnumDescriptorProto)) !== null && _f !== void 0 ? _f : [],
extensionRange: (_h = (_g = init.extensionRange) === null || _g === void 0 ? void 0 : _g.map((e) => (Object.assign({ $typeName: "google.protobuf.DescriptorProto.ExtensionRange" }, e)))) !== null && _h !== void 0 ? _h : [],
oneofDecl: [],
reservedRange: [],
reservedName: [],
});
}
function bootFieldDescriptorProto(init) {
const proto = Object.create({
label: 1,
typeName: "",
extendee: "",
defaultValue: "",
oneofIndex: 0,
jsonName: "",
proto3Optional: false,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FieldDescriptorProto" }, init), { options: init.options ? bootFieldOptions(init.options) : undefined }));
}
function bootFieldOptions(init) {
var _a, _b, _c;
const proto = Object.create({
ctype: 0,
packed: false,
jstype: 0,
lazy: false,
unverifiedLazy: false,
deprecated: false,
weak: false,
debugRedact: false,
retention: 0,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FieldOptions" }, init), { targets: (_a = init.targets) !== null && _a !== void 0 ? _a : [], editionDefaults: (_c = (_b = init.editionDefaults) === null || _b === void 0 ? void 0 : _b.map((e) => (Object.assign({ $typeName: "google.protobuf.FieldOptions.EditionDefault" }, e)))) !== null && _c !== void 0 ? _c : [], uninterpretedOption: [] }));
}
function bootEnumDescriptorProto(init) {
const proto = Object.create({
visibility: 0,
});
return Object.assign(proto, {
$typeName: "google.protobuf.EnumDescriptorProto",
name: init.name,
reservedName: [],
reservedRange: [],
value: init.value.map((e) => (Object.assign({ $typeName: "google.protobuf.EnumValueDescriptorProto" }, e))),
});
}
import type { DescEnum, DescExtension, DescMessage, DescService } from "../descriptors.js";
import { type FileDescriptorProto } from "../wkt/gen/google/protobuf/descriptor_pb.js";
import type { FileDescriptorProtoBoot } from "./boot.js";
type EmbedUnknown = {
bootable: false;
proto(): FileDescriptorProto;
base64(): string;
};
type EmbedDescriptorProto = Omit<EmbedUnknown, "bootable"> & {
bootable: true;
boot(): FileDescriptorProtoBoot;
};
/**
* Create necessary information to embed a file descriptor in
* generated code.
*
* @private
*/
export declare function embedFileDesc(file: FileDescriptorProto): EmbedUnknown | EmbedDescriptorProto;
/**
* Compute the path to a message, enumeration, extension, or service in a
* file descriptor.
*
* @private
*/
export declare function pathInFileDesc(desc: DescMessage | DescEnum | DescExtension | DescService): number[];
/**
* The file descriptor for google/protobuf/descriptor.proto cannot be embedded
* in serialized form, since it is required to parse itself.
*
* This function takes an instance of the message, and returns a plain object
* that can be hydrated to the message again via bootFileDescriptorProto().
*
* This function only works with a message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto, and only supports features that are
* relevant for the specific use case. For example, it discards file options,
* reserved ranges and reserved names, and field options that are unused in
* descriptor.proto.
*
* @private
*/
export declare function createFileDescriptorProtoBoot(proto: FileDescriptorProto): FileDescriptorProtoBoot;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.embedFileDesc = embedFileDesc;
exports.pathInFileDesc = pathInFileDesc;
exports.createFileDescriptorProtoBoot = createFileDescriptorProtoBoot;
const names_js_1 = require("../reflect/names.js");
const fields_js_1 = require("../fields.js");
const base64_encoding_js_1 = require("../wire/base64-encoding.js");
const to_binary_js_1 = require("../to-binary.js");
const clone_js_1 = require("../clone.js");
const descriptor_pb_js_1 = require("../wkt/gen/google/protobuf/descriptor_pb.js");
/**
* Create necessary information to embed a file descriptor in
* generated code.
*
* @private
*/
function embedFileDesc(file) {
const embed = {
bootable: false,
proto() {
const stripped = (0, clone_js_1.clone)(descriptor_pb_js_1.FileDescriptorProtoSchema, file);
(0, fields_js_1.clearField)(stripped, descriptor_pb_js_1.FileDescriptorProtoSchema.field.dependency);
(0, fields_js_1.clearField)(stripped, descriptor_pb_js_1.FileDescriptorProtoSchema.field.sourceCodeInfo);
stripped.messageType.map(stripJsonNames);
return stripped;
},
base64() {
const bytes = (0, to_binary_js_1.toBinary)(descriptor_pb_js_1.FileDescriptorProtoSchema, this.proto());
return (0, base64_encoding_js_1.base64Encode)(bytes, "std_raw");
},
};
return file.name == "google/protobuf/descriptor.proto"
? Object.assign(Object.assign({}, embed), { bootable: true, boot() {
return createFileDescriptorProtoBoot(this.proto());
} }) : embed;
}
function stripJsonNames(d) {
for (const f of d.field) {
if (f.jsonName === (0, names_js_1.protoCamelCase)(f.name)) {
(0, fields_js_1.clearField)(f, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.jsonName);
}
}
for (const n of d.nestedType) {
stripJsonNames(n);
}
}
/**
* Compute the path to a message, enumeration, extension, or service in a
* file descriptor.
*
* @private
*/
function pathInFileDesc(desc) {
if (desc.kind == "service") {
return [desc.file.services.indexOf(desc)];
}
const parent = desc.parent;
if (parent == undefined) {
switch (desc.kind) {
case "enum":
return [desc.file.enums.indexOf(desc)];
case "message":
return [desc.file.messages.indexOf(desc)];
case "extension":
return [desc.file.extensions.indexOf(desc)];
}
}
function findPath(cur) {
const nested = [];
for (let parent = cur.parent; parent;) {
const idx = parent.nestedMessages.indexOf(cur);
nested.unshift(idx);
cur = parent;
parent = cur.parent;
}
nested.unshift(cur.file.messages.indexOf(cur));
return nested;
}
const path = findPath(parent);
switch (desc.kind) {
case "extension":
return [...path, parent.nestedExtensions.indexOf(desc)];
case "message":
return [...path, parent.nestedMessages.indexOf(desc)];
case "enum":
return [...path, parent.nestedEnums.indexOf(desc)];
}
}
/**
* The file descriptor for google/protobuf/descriptor.proto cannot be embedded
* in serialized form, since it is required to parse itself.
*
* This function takes an instance of the message, and returns a plain object
* that can be hydrated to the message again via bootFileDescriptorProto().
*
* This function only works with a message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto, and only supports features that are
* relevant for the specific use case. For example, it discards file options,
* reserved ranges and reserved names, and field options that are unused in
* descriptor.proto.
*
* @private
*/
function createFileDescriptorProtoBoot(proto) {
var _a;
assert(proto.name == "google/protobuf/descriptor.proto");
assert(proto.package == "google.protobuf");
assert(!proto.dependency.length);
assert(!proto.publicDependency.length);
assert(!proto.weakDependency.length);
assert(!proto.optionDependency.length);
assert(!proto.service.length);
assert(!proto.extension.length);
assert(proto.sourceCodeInfo === undefined);
assert(proto.syntax == "" || proto.syntax == "proto2");
assert(!((_a = proto.options) === null || _a === void 0 ? void 0 : _a.features)); // we're dropping file options
assert(proto.edition === descriptor_pb_js_1.Edition.EDITION_UNKNOWN);
return {
name: proto.name,
package: proto.package,
messageType: proto.messageType.map(createDescriptorBoot),
enumType: proto.enumType.map(createEnumDescriptorBoot),
};
}
function createDescriptorBoot(proto) {
assert(proto.extension.length == 0);
assert(!proto.oneofDecl.length);
assert(!proto.options);
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.DescriptorProtoSchema.field.visibility));
const b = {
name: proto.name,
};
if (proto.field.length) {
b.field = proto.field.map(createFieldDescriptorBoot);
}
if (proto.nestedType.length) {
b.nestedType = proto.nestedType.map(createDescriptorBoot);
}
if (proto.enumType.length) {
b.enumType = proto.enumType.map(createEnumDescriptorBoot);
}
if (proto.extensionRange.length) {
b.extensionRange = proto.extensionRange.map((r) => {
assert(!r.options);
return { start: r.start, end: r.end };
});
}
return b;
}
function createFieldDescriptorBoot(proto) {
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.name));
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.number));
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.type));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.oneofIndex));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.jsonName) ||
proto.jsonName === (0, names_js_1.protoCamelCase)(proto.name));
const b = {
name: proto.name,
number: proto.number,
type: proto.type,
};
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.label)) {
b.label = proto.label;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.typeName)) {
b.typeName = proto.typeName;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.extendee)) {
b.extendee = proto.extendee;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.defaultValue)) {
b.defaultValue = proto.defaultValue;
}
if (proto.options) {
b.options = createFieldOptionsBoot(proto.options);
}
return b;
}
function createFieldOptionsBoot(proto) {
const b = {};
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.ctype));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.packed)) {
b.packed = proto.packed;
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.jstype));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.lazy));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.unverifiedLazy));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.deprecated)) {
b.deprecated = proto.deprecated;
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.weak));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.debugRedact));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.retention)) {
b.retention = proto.retention;
}
if (proto.targets.length) {
b.targets = proto.targets;
}
if (proto.editionDefaults.length) {
b.editionDefaults = proto.editionDefaults.map((d) => ({
value: d.value,
edition: d.edition,
}));
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.features));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.uninterpretedOption));
return b;
}
function createEnumDescriptorBoot(proto) {
assert(!proto.options);
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.EnumDescriptorProtoSchema.field.visibility));
return {
name: proto.name,
value: proto.value.map((v) => {
assert(!v.options);
return {
name: v.name,
number: v.number,
};
}),
};
}
/**
* Assert that condition is truthy or throw error.
*/
function assert(condition) {
if (!condition) {
throw new Error();
}
}
import type { DescEnum, DescFile } from "../descriptors.js";
import type { GenEnum } from "./types.js";
import type { JsonValue } from "../json-value.js";
/**
* Hydrate an enum descriptor.
*
* @private
*/
export declare function enumDesc<Shape extends number, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenEnum<Shape, JsonType>;
/**
* Construct a TypeScript enum object at runtime from a descriptor.
*/
export declare function tsEnum(desc: DescEnum): enumObject;
type enumObject = {
[key: number]: string;
[k: string]: number | string;
};
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.enumDesc = enumDesc;
exports.tsEnum = tsEnum;
/**
* Hydrate an enum descriptor.
*
* @private
*/
function enumDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.enums[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedEnums[e];
}
/**
* Construct a TypeScript enum object at runtime from a descriptor.
*/
function tsEnum(desc) {
const enumObject = {};
for (const value of desc.values) {
enumObject[value.localName] = value.number;
enumObject[value.number] = value.localName;
}
return enumObject;
}
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenExtension } from "./types.js";
/**
* Hydrate an extension descriptor.
*
* @private
*/
export declare function extDesc<Extendee extends Message, Value>(file: DescFile, path: number, ...paths: number[]): GenExtension<Extendee, Value>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.extDesc = extDesc;
/**
* Hydrate an extension descriptor.
*
* @private
*/
function extDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.extensions[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedExtensions[e];
}
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a file descriptor.
*
* @private
*/
export declare function fileDesc(b64: string, imports?: DescFile[]): DescFile;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileDesc = fileDesc;
const base64_encoding_js_1 = require("../wire/base64-encoding.js");
const descriptor_pb_js_1 = require("../wkt/gen/google/protobuf/descriptor_pb.js");
const registry_js_1 = require("../registry.js");
const restore_json_names_js_1 = require("./restore-json-names.js");
const from_binary_js_1 = require("../from-binary.js");
/**
* Hydrate a file descriptor.
*
* @private
*/
function fileDesc(b64, imports) {
var _a;
const root = (0, from_binary_js_1.fromBinary)(descriptor_pb_js_1.FileDescriptorProtoSchema, (0, base64_encoding_js_1.base64Decode)(b64));
root.messageType.forEach(restore_json_names_js_1.restoreJsonNames);
root.dependency = (_a = imports === null || imports === void 0 ? void 0 : imports.map((f) => f.proto.name)) !== null && _a !== void 0 ? _a : [];
const reg = (0, registry_js_1.createFileRegistry)(root, (protoFileName) => imports === null || imports === void 0 ? void 0 : imports.find((f) => f.proto.name === protoFileName));
// biome-ignore lint/style/noNonNullAssertion: non-null assertion because we just created the registry from the file we look up
return reg.getFile(root.name);
}
export * from "./boot.js";
export * from "./embed.js";
export * from "./enum.js";
export * from "./extension.js";
export * from "./file.js";
export * from "./message.js";
export * from "./service.js";
export * from "./symbols.js";
export * from "./scalar.js";
export * from "./types.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./boot.js"), exports);
__exportStar(require("./embed.js"), exports);
__exportStar(require("./enum.js"), exports);
__exportStar(require("./extension.js"), exports);
__exportStar(require("./file.js"), exports);
__exportStar(require("./message.js"), exports);
__exportStar(require("./service.js"), exports);
__exportStar(require("./symbols.js"), exports);
__exportStar(require("./scalar.js"), exports);
__exportStar(require("./types.js"), exports);
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenMessage } from "./types.js";
/**
* Hydrate a message descriptor.
*
* @private
*/
export declare function messageDesc<Shape extends Message, Opt extends {
jsonType?: unknown;
validType?: unknown;
} = {
jsonType: undefined;
validType: undefined;
}>(file: DescFile, path: number, ...paths: number[]): GenMessage<Shape, Opt>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.messageDesc = messageDesc;
/**
* Hydrate a message descriptor.
*
* @private
*/
function messageDesc(file, path, ...paths) {
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]);
}
import type { DescriptorProto } from "../wkt/gen/google/protobuf/descriptor_pb.js";
/**
* @private
*/
export declare function restoreJsonNames(message: DescriptorProto): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.restoreJsonNames = restoreJsonNames;
const names_js_1 = require("../reflect/names.js");
const unsafe_js_1 = require("../reflect/unsafe.js");
/**
* @private
*/
function restoreJsonNames(message) {
for (const f of message.field) {
if (!(0, unsafe_js_1.unsafeIsSetExplicit)(f, "jsonName")) {
f.jsonName = (0, names_js_1.protoCamelCase)(f.name);
}
}
message.nestedType.forEach(restoreJsonNames);
}
import { ScalarType } from "../descriptors.js";
/**
* Return the TypeScript type (as a string) for the given scalar type.
*/
export declare function scalarTypeScriptType(scalar: ScalarType, longAsString: boolean): "string" | "boolean" | "bigint" | "bigint | string" | "Uint8Array" | "number";
/**
* Return the JSON type (as a string) for the given scalar type.
*/
export declare function scalarJsonType(scalar: ScalarType): "string" | "boolean" | "number" | `number | "NaN" | "Infinity" | "-Infinity"`;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.scalarTypeScriptType = scalarTypeScriptType;
exports.scalarJsonType = scalarJsonType;
const descriptors_js_1 = require("../descriptors.js");
/**
* Return the TypeScript type (as a string) for the given scalar type.
*/
function scalarTypeScriptType(scalar, longAsString) {
switch (scalar) {
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.INT64:
return longAsString ? "string" : "bigint";
case descriptors_js_1.ScalarType.BYTES:
return "Uint8Array";
default:
return "number";
}
}
/**
* Return the JSON type (as a string) for the given scalar type.
*/
function scalarJsonType(scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
return `number | "NaN" | "Infinity" | "-Infinity"`;
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.INT64:
return "string";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
return "number";
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.BYTES:
return "string";
}
}
import type { GenService, GenServiceMethods } from "./types.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a service descriptor.
*
* @private
*/
export declare function serviceDesc<T extends GenServiceMethods>(file: DescFile, path: number, ...paths: number[]): GenService<T>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceDesc = serviceDesc;
/**
* Hydrate a service descriptor.
*
* @private
*/
function serviceDesc(file, path, ...paths) {
if (paths.length > 0) {
throw new Error();
}
return file.services[path];
}
/**
* @private
*/
export declare const packageName = "@bufbuild/protobuf";
/**
* @private
*/
export declare const wktPublicImportPaths: Readonly<Record<string, string>>;
/**
* @private
*/
export declare const symbols: {
readonly isMessage: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../is-message.js";
readonly from: "@bufbuild/protobuf";
};
readonly Message: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../types.js";
readonly from: "@bufbuild/protobuf";
};
readonly create: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../create.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly protoInt64: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../proto-int64.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonValue: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonObject: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly codegen: {
readonly boot: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/boot.js";
readonly from: string;
};
readonly fileDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/file.js";
readonly from: string;
};
readonly enumDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/enum.js";
readonly from: string;
};
readonly extDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/extension.js";
readonly from: string;
};
readonly messageDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/message.js";
readonly from: string;
};
readonly serviceDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/service.js";
readonly from: string;
};
readonly tsEnum: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/enum.js";
readonly from: string;
};
readonly GenFile: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
readonly GenEnum: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
readonly GenExtension: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
readonly GenMessage: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
readonly GenService: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
};
};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.symbols = exports.wktPublicImportPaths = exports.packageName = void 0;
/**
* @private
*/
exports.packageName = "@bufbuild/protobuf";
/**
* @private
*/
exports.wktPublicImportPaths = {
"google/protobuf/compiler/plugin.proto": exports.packageName + "/wkt",
"google/protobuf/any.proto": exports.packageName + "/wkt",
"google/protobuf/api.proto": exports.packageName + "/wkt",
"google/protobuf/cpp_features.proto": exports.packageName + "/wkt",
"google/protobuf/descriptor.proto": exports.packageName + "/wkt",
"google/protobuf/duration.proto": exports.packageName + "/wkt",
"google/protobuf/empty.proto": exports.packageName + "/wkt",
"google/protobuf/field_mask.proto": exports.packageName + "/wkt",
"google/protobuf/go_features.proto": exports.packageName + "/wkt",
"google/protobuf/java_features.proto": exports.packageName + "/wkt",
"google/protobuf/source_context.proto": exports.packageName + "/wkt",
"google/protobuf/struct.proto": exports.packageName + "/wkt",
"google/protobuf/timestamp.proto": exports.packageName + "/wkt",
"google/protobuf/type.proto": exports.packageName + "/wkt",
"google/protobuf/wrappers.proto": exports.packageName + "/wkt",
};
/**
* @private
*/
// biome-ignore format: want this to read well
exports.symbols = {
isMessage: { typeOnly: false, bootstrapWktFrom: "../../is-message.js", from: exports.packageName },
Message: { typeOnly: true, bootstrapWktFrom: "../../types.js", from: exports.packageName },
create: { typeOnly: false, bootstrapWktFrom: "../../create.js", from: exports.packageName },
fromJson: { typeOnly: false, bootstrapWktFrom: "../../from-json.js", from: exports.packageName },
fromJsonString: { typeOnly: false, bootstrapWktFrom: "../../from-json.js", from: exports.packageName },
fromBinary: { typeOnly: false, bootstrapWktFrom: "../../from-binary.js", from: exports.packageName },
toBinary: { typeOnly: false, bootstrapWktFrom: "../../to-binary.js", from: exports.packageName },
toJson: { typeOnly: false, bootstrapWktFrom: "../../to-json.js", from: exports.packageName },
toJsonString: { typeOnly: false, bootstrapWktFrom: "../../to-json.js", from: exports.packageName },
protoInt64: { typeOnly: false, bootstrapWktFrom: "../../proto-int64.js", from: exports.packageName },
JsonValue: { typeOnly: true, bootstrapWktFrom: "../../json-value.js", from: exports.packageName },
JsonObject: { typeOnly: true, bootstrapWktFrom: "../../json-value.js", from: exports.packageName },
codegen: {
boot: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/boot.js", from: exports.packageName + "/codegenv2" },
fileDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/file.js", from: exports.packageName + "/codegenv2" },
enumDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/enum.js", from: exports.packageName + "/codegenv2" },
extDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/extension.js", from: exports.packageName + "/codegenv2" },
messageDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/message.js", from: exports.packageName + "/codegenv2" },
serviceDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/service.js", from: exports.packageName + "/codegenv2" },
tsEnum: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/enum.js", from: exports.packageName + "/codegenv2" },
GenFile: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenEnum: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenExtension: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenMessage: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenService: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
},
};
import type { Message } from "../types.js";
import type { DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescService } from "../descriptors.js";
import type { JsonValue } from "../json-value.js";
/**
* Describes a protobuf source file.
*
* @private
*/
export type GenFile = DescFile;
/**
* Describes a message declaration in a protobuf source file.
*
* This type is identical to DescMessage, but carries additional type
* information.
*
* @private
*/
export type GenMessage<RuntimeShape extends Message, Opt extends {
jsonType?: unknown;
validType?: unknown;
} = {
jsonType?: unknown;
validType?: unknown;
}> = Omit<DescMessage, "field" | "typeName"> & {
field: Record<MessageFieldNames<RuntimeShape>, DescField>;
typeName: RuntimeShape["$typeName"];
} & brandv2<RuntimeShape, Opt>;
/**
* Describes an enumeration in a protobuf source file.
*
* This type is identical to DescEnum, but carries additional type
* information.
*
* @private
*/
export type GenEnum<RuntimeShape extends number, JsonType extends JsonValue = JsonValue> = Omit<DescEnum, "value"> & {
value: Record<RuntimeShape, DescEnumValue>;
} & brandv2<RuntimeShape, JsonType>;
/**
* Describes an extension in a protobuf source file.
*
* This type is identical to DescExtension, but carries additional type
* information.
*
* @private
*/
export type GenExtension<Extendee extends Message = Message, RuntimeShape = unknown> = DescExtension & brandv2<Extendee, RuntimeShape>;
/**
* Describes a service declaration in a protobuf source file.
*
* This type is identical to DescService, but carries additional type
* information.
*
* @private
*/
export type GenService<RuntimeShape extends GenServiceMethods> = Omit<DescService, "method"> & {
method: {
[K in keyof RuntimeShape]: RuntimeShape[K] & DescMethod;
};
};
/**
* @private
*/
export type GenServiceMethods = Record<string, Pick<DescMethod, "input" | "output" | "methodKind">>;
type brandv2<A, B = unknown> = {
/**
* @internal
*/
readonly $codegenv2: {
a: A;
b: B;
};
};
/**
* Union of the property names of all fields, including oneof members.
* For an anonymous message (no generated message shape), it's simply a string.
*/
type MessageFieldNames<T extends Message> = Message extends T ? string : Exclude<keyof {
[P in keyof T as P extends ("$typeName" | "$unknown") ? never : T[P] extends Oneof<infer K> ? K : P]-?: true;
}, number | symbol>;
type Oneof<K extends string> = {
case: K | undefined;
value?: unknown;
};
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
import { type DescMessage } from "./descriptors.js";
import type { MessageInitShape, MessageShape } from "./types.js";
/**
* Create a new message instance.
*
* The second argument is an optional initializer object, where all fields are
* optional.
*/
export declare function create<Desc extends DescMessage>(schema: Desc, init?: MessageInitShape<Desc>): MessageShape<Desc>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = create;
const is_message_js_1 = require("./is-message.js");
const descriptors_js_1 = require("./descriptors.js");
const scalar_js_1 = require("./reflect/scalar.js");
const guard_js_1 = require("./reflect/guard.js");
const unsafe_js_1 = require("./reflect/unsafe.js");
const wrappers_js_1 = require("./wkt/wrappers.js");
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name: Edition.$localName = $number;
const EDITION_PROTO3 = 999;
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name: Edition.$localName = $number;
const EDITION_PROTO2 = 998;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
/**
* Create a new message instance.
*
* The second argument is an optional initializer object, where all fields are
* optional.
*/
function create(schema, init) {
if ((0, is_message_js_1.isMessage)(init, schema)) {
return init;
}
const message = createZeroMessage(schema);
if (init !== undefined) {
initMessage(schema, message, init);
}
return message;
}
/**
* Sets field values from a MessageInitShape on a zero message.
*/
function initMessage(messageDesc, message, init) {
for (const member of messageDesc.members) {
let value = init[member.localName];
if (value == null) {
// intentionally ignore undefined and null
continue;
}
let field;
if (member.kind == "oneof") {
const oneofField = (0, unsafe_js_1.unsafeOneofCase)(init, member);
if (!oneofField) {
continue;
}
field = oneofField;
value = (0, unsafe_js_1.unsafeGet)(init, oneofField);
}
else {
field = member;
}
switch (field.fieldKind) {
case "message":
value = toMessage(field, value);
break;
case "scalar":
value = initScalar(field, value);
break;
case "list":
value = initList(field, value);
break;
case "map":
value = initMap(field, value);
break;
}
(0, unsafe_js_1.unsafeSet)(message, field, value);
}
return message;
}
function initScalar(field, value) {
if (field.scalar == descriptors_js_1.ScalarType.BYTES) {
return toU8Arr(value);
}
return value;
}
function initMap(field, value) {
if ((0, guard_js_1.isObject)(value)) {
if (field.scalar == descriptors_js_1.ScalarType.BYTES) {
return convertObjectValues(value, toU8Arr);
}
if (field.mapKind == "message") {
return convertObjectValues(value, (val) => toMessage(field, val));
}
}
return value;
}
function initList(field, value) {
if (Array.isArray(value)) {
if (field.scalar == descriptors_js_1.ScalarType.BYTES) {
return value.map(toU8Arr);
}
if (field.listKind == "message") {
return value.map((item) => toMessage(field, item));
}
}
return value;
}
function toMessage(field, value) {
if (field.fieldKind == "message" &&
!field.oneof &&
(0, wrappers_js_1.isWrapperDesc)(field.message)) {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
return initScalar(field.message.fields[0], value);
}
if ((0, guard_js_1.isObject)(value)) {
if (field.message.typeName == "google.protobuf.Struct" &&
field.parent.typeName !== "google.protobuf.Value") {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
return value;
}
if (!(0, is_message_js_1.isMessage)(value, field.message)) {
return create(field.message, value);
}
}
return value;
}
// converts any ArrayLike<number> to Uint8Array if necessary.
function toU8Arr(value) {
return Array.isArray(value) ? new Uint8Array(value) : value;
}
function convertObjectValues(obj, fn) {
const ret = {};
for (const entry of Object.entries(obj)) {
ret[entry[0]] = fn(entry[1]);
}
return ret;
}
const tokenZeroMessageField = Symbol();
const messagePrototypes = new WeakMap();
/**
* Create a zero message.
*/
function createZeroMessage(desc) {
let msg;
if (!needsPrototypeChain(desc)) {
msg = {
$typeName: desc.typeName,
};
for (const member of desc.members) {
if (member.kind == "oneof" || member.presence == IMPLICIT) {
msg[member.localName] = createZeroField(member);
}
}
}
else {
// Support default values and track presence via the prototype chain
const cached = messagePrototypes.get(desc);
let prototype;
let members;
if (cached) {
({ prototype, members } = cached);
}
else {
prototype = {};
members = new Set();
for (const member of desc.members) {
if (member.kind == "oneof") {
// we can only put immutable values on the prototype,
// oneof ADTs are mutable
continue;
}
if (member.fieldKind != "scalar" && member.fieldKind != "enum") {
// only scalar and enum values are immutable, map, list, and message
// are not
continue;
}
if (member.presence == IMPLICIT) {
// implicit presence tracks field presence by zero values - e.g. 0, false, "", are unset, 1, true, "x" are set.
// message, map, list fields are mutable, and also have IMPLICIT presence.
continue;
}
members.add(member);
prototype[member.localName] = createZeroField(member);
}
messagePrototypes.set(desc, { prototype, members });
}
msg = Object.create(prototype);
msg.$typeName = desc.typeName;
for (const member of desc.members) {
if (members.has(member)) {
continue;
}
if (member.kind == "field") {
if (member.fieldKind == "message") {
continue;
}
if (member.fieldKind == "scalar" || member.fieldKind == "enum") {
if (member.presence != IMPLICIT) {
continue;
}
}
}
msg[member.localName] = createZeroField(member);
}
}
return msg;
}
/**
* Do we need the prototype chain to track field presence?
*/
function needsPrototypeChain(desc) {
switch (desc.file.edition) {
case EDITION_PROTO3:
// proto3 always uses implicit presence, we never need the prototype chain.
return false;
case EDITION_PROTO2:
// proto2 never uses implicit presence, we always need the prototype chain.
return true;
default:
// If a message uses scalar or enum fields with explicit presence, we need
// the prototype chain to track presence. This rule does not apply to fields
// in a oneof group - they use a different mechanism to track presence.
return desc.fields.some((f) => f.presence != IMPLICIT && f.fieldKind != "message" && !f.oneof);
}
}
/**
* Returns a zero value for oneof groups, and for every field kind except
* messages. Scalar and enum fields can have default values.
*/
function createZeroField(field) {
if (field.kind == "oneof") {
return { case: undefined };
}
if (field.fieldKind == "list") {
return [];
}
if (field.fieldKind == "map") {
return {}; // Object.create(null) would be desirable here, but is unsupported by react https://react.dev/reference/react/use-server#serializable-parameters-and-return-values
}
if (field.fieldKind == "message") {
return tokenZeroMessageField;
}
const defaultValue = field.getDefaultValue();
if (defaultValue !== undefined) {
return field.fieldKind == "scalar" && field.longAsString
? defaultValue.toString()
: defaultValue;
}
return field.fieldKind == "scalar"
? (0, scalar_js_1.scalarZeroValue)(field.scalar, field.longAsString)
: field.enum.values[0].number;
}
import type { DescriptorProto, Edition, EnumDescriptorProto, EnumValueDescriptorProto, FeatureSet_FieldPresence, FieldDescriptorProto, FileDescriptorProto, MethodDescriptorProto, MethodOptions_IdempotencyLevel, OneofDescriptorProto, ServiceDescriptorProto } from "./wkt/gen/google/protobuf/descriptor_pb.js";
import type { ScalarValue } from "./reflect/scalar.js";
export type SupportedEdition = Extract<Edition, Edition.EDITION_PROTO2 | Edition.EDITION_PROTO3 | Edition.EDITION_2023 | Edition.EDITION_2024>;
type SupportedFieldPresence = Extract<FeatureSet_FieldPresence, FeatureSet_FieldPresence.EXPLICIT | FeatureSet_FieldPresence.IMPLICIT | FeatureSet_FieldPresence.LEGACY_REQUIRED>;
/**
* Scalar value types. This is a subset of field types declared by protobuf
* enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
* are omitted, but the numerical values are identical.
*/
export declare enum ScalarType {
DOUBLE = 1,
FLOAT = 2,
INT64 = 3,
UINT64 = 4,
INT32 = 5,
FIXED64 = 6,
FIXED32 = 7,
BOOL = 8,
STRING = 9,
BYTES = 12,
UINT32 = 13,
SFIXED32 = 15,
SFIXED64 = 16,
SINT32 = 17,// Uses ZigZag encoding.
SINT64 = 18
}
/**
* A union of all descriptors, discriminated by a `kind` property.
*/
export type AnyDesc = DescFile | DescEnum | DescEnumValue | DescMessage | DescField | DescExtension | DescOneof | DescService | DescMethod;
/**
* Describes a protobuf source file.
*/
export interface DescFile {
readonly kind: "file";
/**
* The edition of the protobuf file. Will be EDITION_PROTO2 for syntax="proto2",
* EDITION_PROTO3 for syntax="proto3";
*/
readonly edition: SupportedEdition;
/**
* The name of the file, excluding the .proto suffix.
* For a protobuf file `foo/bar.proto`, this is `foo/bar`.
*/
readonly name: string;
/**
* Files imported by this file.
*/
readonly dependencies: DescFile[];
/**
* Top-level enumerations declared in this file.
* Note that more enumerations might be declared within message declarations.
*/
readonly enums: DescEnum[];
/**
* Top-level messages declared in this file.
* Note that more messages might be declared within message declarations.
*/
readonly messages: DescMessage[];
/**
* Top-level extensions declared in this file.
* Note that more extensions might be declared within message declarations.
*/
readonly extensions: DescExtension[];
/**
* Services declared in this file.
*/
readonly services: DescService[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: FileDescriptorProto;
toString(): string;
}
/**
* Describes an enumeration in a protobuf source file.
*/
export interface DescEnum {
readonly kind: "enum";
/**
* The fully qualified name of the enumeration. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the enumeration, as declared in the protobuf source.
*/
readonly name: string;
/**
* The file this enumeration was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this enumeration was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* Enumerations can be open or closed.
* See https://protobuf.dev/programming-guides/enum/
*/
readonly open: boolean;
/**
* Values declared for this enumeration.
*/
readonly values: DescEnumValue[];
/**
* All values of this enum by their number.
*/
readonly value: Record<number, DescEnumValue>;
/**
* A prefix shared by all enum values.
* For example, `my_enum_` for `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`
*/
readonly sharedPrefix?: string | undefined;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: EnumDescriptorProto;
toString(): string;
}
/**
* Describes an individual value of an enumeration in a protobuf source file.
*/
export interface DescEnumValue {
readonly kind: "enum_value";
/**
* The name of the enumeration value, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the value in a TypeScript enum.
*/
readonly localName: string;
/**
* The enumeration this value belongs to.
*/
readonly parent: DescEnum;
/**
* The numeric enumeration value, as specified in the protobuf source.
*/
readonly number: number;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: EnumValueDescriptorProto;
toString(): string;
}
/**
* Describes a message declaration in a protobuf source file.
*/
export interface DescMessage {
readonly kind: "message";
/**
* The fully qualified name of the message. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the message, as specified in the protobuf source.
*/
readonly name: string;
/**
* The file this message was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this message was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* Fields declared for this message, including fields declared in a oneof
* group.
*/
readonly fields: DescField[];
/**
* All fields of this message by their "localName".
*/
readonly field: Record<string, DescField>;
/**
* Oneof groups declared for this message.
* This does not include synthetic oneofs for proto3 optionals.
*/
readonly oneofs: DescOneof[];
/**
* Standalone fields and oneof groups for this message, ordered by
* their appearance in the protobuf source.
*/
readonly members: (DescField | DescOneof)[];
/**
* Enumerations declared within the message, if any.
*/
readonly nestedEnums: DescEnum[];
/**
* Messages declared within the message, if any.
* This does not include synthetic messages like map entries.
*/
readonly nestedMessages: DescMessage[];
/**
* Extensions declared within the message, if any.
*/
readonly nestedExtensions: DescExtension[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: DescriptorProto;
toString(): string;
}
/**
* Describes a field declaration in a protobuf source file.
*/
export type DescField = (descFieldScalar & descFieldCommon) | (descFieldList & descFieldCommon) | (descFieldMessage & descFieldCommon) | (descFieldEnum & descFieldCommon) | (descFieldMap & descFieldCommon);
type descFieldCommon = descFieldAndExtensionShared & {
readonly kind: "field";
/**
* The message this field is declared on.
*/
readonly parent: DescMessage;
/**
* A safe and idiomatic name for the field as a property in ECMAScript.
*/
readonly localName: string;
};
/**
* Describes an extension in a protobuf source file.
*/
export type DescExtension = (Omit<descFieldScalar, "oneof"> & descExtensionCommon) | (Omit<descFieldEnum, "oneof"> & descExtensionCommon) | (Omit<descFieldMessage, "oneof"> & descExtensionCommon) | (descFieldList & descExtensionCommon);
type descExtensionCommon = descFieldAndExtensionShared & {
readonly kind: "extension";
/**
* The fully qualified name of the extension.
*/
readonly typeName: string;
/**
* The file this extension was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this extension was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* The message that this extension extends.
*/
readonly extendee: DescMessage;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
};
interface descFieldAndExtensionShared {
/**
* The field name, as specified in the protobuf source
*/
readonly name: string;
/**
* The field number, as specified in the protobuf source.
*/
readonly number: number;
/**
* The field name in JSON.
*/
readonly jsonName: string;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* Presence of the field.
* See https://protobuf.dev/programming-guides/field_presence/
*/
readonly presence: SupportedFieldPresence;
/**
* Whether to reject invalid UTF-8 when reading this field from the binary
* wire format. Reflects the resolved `utf8_validation` feature: true for
* VERIFY (proto3 and editions 2023+ default), false for NONE (proto2
* default).
*/
readonly utf8Validation: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: FieldDescriptorProto;
/**
* Get the edition features for this protobuf element.
*/
toString(): string;
}
type descFieldSingularCommon = {
/**
* The `oneof` group this field belongs to, if any.
*
* This does not include synthetic oneofs for proto3 optionals.
*/
readonly oneof: DescOneof | undefined;
};
type descFieldScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly fieldKind: "scalar";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: T;
/**
* By default, 64-bit integral types (int64, uint64, sint64, fixed64,
* sfixed64) are represented with BigInt.
*
* If the field option `jstype = JS_STRING` is set, this property
* is true, and 64-bit integral types are represented with String.
*/
readonly longAsString: boolean;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): ScalarValue<T> | undefined;
} & descFieldSingularCommon : never;
type descFieldMessage = {
readonly fieldKind: "message";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: DescMessage;
/**
* Encode the message delimited (a.k.a. proto2 group encoding), or
* length-prefixed?
*/
readonly delimitedEncoding: boolean;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): undefined;
} & descFieldSingularCommon;
type descFieldEnum = {
readonly fieldKind: "enum";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: DescEnum;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): number | undefined;
} & descFieldSingularCommon;
type descFieldList = (descFieldListScalar & descFieldListCommon) | (descFieldListEnum & descFieldListCommon) | (descFieldListMessage & descFieldListCommon);
type descFieldListCommon = {
readonly fieldKind: "list";
/**
* Pack this repeated field? Only valid for repeated enum fields, and
* for repeated scalar fields except BYTES and STRING.
*/
readonly packed: boolean;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
};
type descFieldListScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly listKind: "scalar";
/**
* The enum list element type.
*/
readonly enum: undefined;
/**
* The message list element type.
*/
readonly message: undefined;
/**
* Scalar list element type.
*/
readonly scalar: T;
/**
* By default, 64-bit integral types (int64, uint64, sint64, fixed64,
* sfixed64) are represented with BigInt.
*
* If the field option `jstype = JS_STRING` is set, this property
* is true, and 64-bit integral types are represented with String.
*/
readonly longAsString: boolean;
} : never;
type descFieldListEnum = {
readonly listKind: "enum";
/**
* The enum list element type.
*/
readonly enum: DescEnum;
/**
* The message list element type.
*/
readonly message: undefined;
/**
* Scalar list element type.
*/
readonly scalar: undefined;
};
type descFieldListMessage = {
readonly listKind: "message";
/**
* The enum list element type.
*/
readonly enum: undefined;
/**
* The message list element type.
*/
readonly message: DescMessage;
/**
* Scalar list element type.
*/
readonly scalar: undefined;
/**
* Encode the message delimited (a.k.a. proto2 group encoding), or
* length-prefixed?
*/
readonly delimitedEncoding: boolean;
};
type descFieldMap = (descFieldMapScalar & descFieldMapCommon) | (descFieldMapEnum & descFieldMapCommon) | (descFieldMapMessage & descFieldMapCommon);
type descFieldMapCommon<T extends ScalarType = ScalarType> = T extends Exclude<ScalarType, ScalarType.FLOAT | ScalarType.DOUBLE | ScalarType.BYTES> ? {
readonly fieldKind: "map";
/**
* The scalar map key type.
*/
readonly mapKey: T;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
/**
* Encode the map entry message delimited (a.k.a. proto2 group encoding),
* or length-prefixed? As of Edition 2023, this is always false for map fields,
* and also applies to map values, if they are messages.
*/
readonly delimitedEncoding: false;
} : never;
type descFieldMapScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly mapKind: "scalar";
/**
* The enum map value type.
*/
readonly enum: undefined;
/**
* The message map value type.
*/
readonly message: undefined;
/**
* Scalar map value type.
*/
readonly scalar: T;
} : never;
type descFieldMapEnum = {
readonly mapKind: "enum";
/**
* The enum map value type.
*/
readonly enum: DescEnum;
/**
* The message map value type.
*/
readonly message: undefined;
/**
* Scalar map value type.
*/
readonly scalar: undefined;
};
type descFieldMapMessage = {
readonly mapKind: "message";
/**
* The enum map value type.
*/
readonly enum: undefined;
/**
* The message map value type.
*/
readonly message: DescMessage;
/**
* Scalar map value type.
*/
readonly scalar: undefined;
};
/**
* Describes a oneof group in a protobuf source file.
*/
export interface DescOneof {
readonly kind: "oneof";
/**
* The name of the oneof group, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the oneof group as a property in ECMAScript.
*/
readonly localName: string;
/**
* The message this oneof group was declared in.
*/
readonly parent: DescMessage;
/**
* The fields declared in this oneof group.
*/
readonly fields: DescField[];
/**
* Marked as deprecated in the protobuf source.
* Note that oneof groups cannot be marked as deprecated, this property
* only exists for consistency and will always be false.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: OneofDescriptorProto;
toString(): string;
}
/**
* Describes a service declaration in a protobuf source file.
*/
export interface DescService {
readonly kind: "service";
/**
* The fully qualified name of the service. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the service, as specified in the protobuf source.
*/
readonly name: string;
/**
* The file this service was declared in.
*/
readonly file: DescFile;
/**
* The RPCs this service declares.
*/
readonly methods: DescMethod[];
/**
* All methods of this service by their "localName".
*/
readonly method: Record<string, DescMethod>;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: ServiceDescriptorProto;
toString(): string;
}
/**
* Describes an RPC declaration in a protobuf source file.
*/
export interface DescMethod {
readonly kind: "rpc";
/**
* The name of the RPC, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the RPC as a method in ECMAScript.
*/
readonly localName: string;
/**
* The parent service.
*/
readonly parent: DescService;
/**
* One of the four available method types.
*/
readonly methodKind: "unary" | "server_streaming" | "client_streaming" | "bidi_streaming";
/**
* The message type for requests.
*/
readonly input: DescMessage;
/**
* The message type for responses.
*/
readonly output: DescMessage;
/**
* The idempotency level declared in the protobuf source, if any.
*/
readonly idempotency: MethodOptions_IdempotencyLevel;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: MethodDescriptorProto;
toString(): string;
}
/**
* Comments on an element in a protobuf source file.
*/
export interface DescComments {
readonly leadingDetached: readonly string[];
readonly leading?: string | undefined;
readonly trailing?: string | undefined;
readonly sourcePath: readonly number[];
}
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScalarType = void 0;
/**
* Scalar value types. This is a subset of field types declared by protobuf
* enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
* are omitted, but the numerical values are identical.
*/
var ScalarType;
(function (ScalarType) {
// 0 is reserved for errors.
// Order is weird for historical reasons.
ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE";
ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT";
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
// negative values are likely.
ScalarType[ScalarType["INT64"] = 3] = "INT64";
ScalarType[ScalarType["UINT64"] = 4] = "UINT64";
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
// negative values are likely.
ScalarType[ScalarType["INT32"] = 5] = "INT32";
ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64";
ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32";
ScalarType[ScalarType["BOOL"] = 8] = "BOOL";
ScalarType[ScalarType["STRING"] = 9] = "STRING";
// Tag-delimited aggregate.
// Group type is deprecated and not supported in proto3. However, Proto3
// implementations should still be able to parse the group wire format and
// treat group fields as unknown fields.
// TYPE_GROUP = 10,
// TYPE_MESSAGE = 11, // Length-delimited aggregate.
// New in version 2.
ScalarType[ScalarType["BYTES"] = 12] = "BYTES";
ScalarType[ScalarType["UINT32"] = 13] = "UINT32";
// TYPE_ENUM = 14,
ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32";
ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64";
ScalarType[ScalarType["SINT32"] = 17] = "SINT32";
ScalarType[ScalarType["SINT64"] = 18] = "SINT64";
})(ScalarType || (exports.ScalarType = ScalarType = {}));
import type { MessageShape } from "./types.js";
import { type DescMessage } from "./descriptors.js";
import type { Registry } from "./registry.js";
interface EqualsOptions {
/**
* A registry to look up extensions, and messages packed in Any.
*
* @private Experimental API, does not follow semantic versioning.
*/
registry: Registry;
/**
* Unpack google.protobuf.Any before comparing.
* If a type is not in the registry, comparison falls back to comparing the
* fields of Any.
*
* @private Experimental API, does not follow semantic versioning.
*/
unpackAny?: boolean;
/**
* Consider extensions when comparing.
*
* @private Experimental API, does not follow semantic versioning.
*/
extensions?: boolean;
/**
* Consider unknown fields when comparing.
* The registry is used to distinguish between extensions, and unknown fields
* caused by schema changes.
*
* @private Experimental API, does not follow semantic versioning.
*/
unknown?: boolean;
}
/**
* Compare two messages of the same type for equality.
*
* Fields are compared one by one, but only when set: a field set in one message
* but not the other makes them unequal, while fields set in both are compared
* by value. Extensions and unknown fields are disregarded by default.
*
* Float and double values are compared with IEEE semantics: NaN does not equal
* NaN, and -0 equals 0 (with the exception for singular fields with implicit
* presence: -0 is set, +0 is unset).
*/
export declare function equals<Desc extends DescMessage>(schema: Desc, a: MessageShape<Desc>, b: MessageShape<Desc>, options?: EqualsOptions): boolean;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.equals = equals;
const scalar_js_1 = require("./reflect/scalar.js");
const reflect_js_1 = require("./reflect/reflect.js");
const descriptors_js_1 = require("./descriptors.js");
const index_js_1 = require("./wkt/index.js");
const extensions_js_1 = require("./extensions.js");
/**
* Compare two messages of the same type for equality.
*
* Fields are compared one by one, but only when set: a field set in one message
* but not the other makes them unequal, while fields set in both are compared
* by value. Extensions and unknown fields are disregarded by default.
*
* Float and double values are compared with IEEE semantics: NaN does not equal
* NaN, and -0 equals 0 (with the exception for singular fields with implicit
* presence: -0 is set, +0 is unset).
*/
function equals(schema, a, b, options) {
if (a.$typeName != schema.typeName || b.$typeName != schema.typeName) {
return false;
}
if (a === b) {
return true;
}
return reflectEquals((0, reflect_js_1.reflect)(schema, a), (0, reflect_js_1.reflect)(schema, b), options);
}
function reflectEquals(a, b, opts) {
if (a.desc.typeName === "google.protobuf.Any" && (opts === null || opts === void 0 ? void 0 : opts.unpackAny) == true) {
return anyUnpackedEquals(a.message, b.message, opts);
}
for (const f of a.fields) {
if (!fieldEquals(f, a, b, opts)) {
return false;
}
}
if ((opts === null || opts === void 0 ? void 0 : opts.unknown) == true && !unknownEquals(a, b, opts.registry)) {
return false;
}
if ((opts === null || opts === void 0 ? void 0 : opts.extensions) == true && !extensionsEquals(a, b, opts)) {
return false;
}
return true;
}
// TODO(tstamm) add an option to consider NaN equal to NaN?
function fieldEquals(f, a, b, opts) {
if (!a.isSet(f) && !b.isSet(f)) {
return true;
}
if (!a.isSet(f) || !b.isSet(f)) {
return false;
}
switch (f.fieldKind) {
case "scalar":
return (0, scalar_js_1.scalarEquals)(f.scalar, a.get(f), b.get(f));
case "enum":
return a.get(f) === b.get(f);
case "message":
return reflectEquals(a.get(f), b.get(f), opts);
case "map": {
// TODO(tstamm) can't we compare sizes first?
const mapA = a.get(f);
const mapB = b.get(f);
const keys = [];
for (const k of mapA.keys()) {
if (!mapB.has(k)) {
return false;
}
keys.push(k);
}
for (const k of mapB.keys()) {
if (!mapA.has(k)) {
return false;
}
}
for (const key of keys) {
const va = mapA.get(key);
const vb = mapB.get(key);
if (va === vb) {
continue;
}
switch (f.mapKind) {
case "enum":
return false;
case "message":
if (!reflectEquals(va, vb, opts)) {
return false;
}
break;
case "scalar":
if (!(0, scalar_js_1.scalarEquals)(f.scalar, va, vb)) {
return false;
}
break;
}
}
break;
}
case "list": {
const listA = a.get(f);
const listB = b.get(f);
if (listA.size != listB.size) {
return false;
}
for (let i = 0; i < listA.size; i++) {
const va = listA.get(i);
const vb = listB.get(i);
if (va === vb) {
continue;
}
switch (f.listKind) {
case "enum":
return false;
case "message":
if (!reflectEquals(va, vb, opts)) {
return false;
}
break;
case "scalar":
if (!(0, scalar_js_1.scalarEquals)(f.scalar, va, vb)) {
return false;
}
break;
}
}
break;
}
}
return true;
}
function anyUnpackedEquals(a, b, opts) {
if (a.typeUrl !== b.typeUrl) {
return false;
}
const unpackedA = (0, index_js_1.anyUnpack)(a, opts.registry);
const unpackedB = (0, index_js_1.anyUnpack)(b, opts.registry);
if (unpackedA && unpackedB) {
const schema = opts.registry.getMessage(unpackedA.$typeName);
if (schema) {
return equals(schema, unpackedA, unpackedB, opts);
}
}
return (0, scalar_js_1.scalarEquals)(descriptors_js_1.ScalarType.BYTES, a.value, b.value);
}
function unknownEquals(a, b, registry) {
function getTrulyUnknown(msg, registry) {
var _a;
const u = (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : [];
return registry
? u.filter((uf) => !registry.getExtensionFor(msg.desc, uf.no))
: u;
}
const unknownA = getTrulyUnknown(a, registry);
const unknownB = getTrulyUnknown(b, registry);
if (unknownA.length != unknownB.length) {
return false;
}
for (let i = 0; i < unknownA.length; i++) {
const a = unknownA[i];
const b = unknownB[i];
if (a.no != b.no) {
return false;
}
if (a.wireType != b.wireType) {
return false;
}
if (!(0, scalar_js_1.scalarEquals)(descriptors_js_1.ScalarType.BYTES, a.data, b.data)) {
return false;
}
}
return true;
}
function extensionsEquals(a, b, opts) {
function getSetExtensions(msg, registry) {
var _a;
return ((_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : [])
.map((uf) => registry.getExtensionFor(msg.desc, uf.no))
.filter((e) => e != undefined)
.filter((e, index, arr) => arr.indexOf(e) === index);
}
const extensionsA = getSetExtensions(a, opts.registry);
const extensionsB = getSetExtensions(b, opts.registry);
if (extensionsA.length != extensionsB.length ||
extensionsA.some((e) => !extensionsB.includes(e))) {
return false;
}
for (const extension of extensionsA) {
const [containerA, field] = (0, extensions_js_1.createExtensionContainer)(extension, (0, extensions_js_1.getExtension)(a.message, extension));
const [containerB] = (0, extensions_js_1.createExtensionContainer)(extension, (0, extensions_js_1.getExtension)(b.message, extension));
if (!fieldEquals(field, containerA, containerB, opts)) {
return false;
}
}
return true;
}
import type { AnyDesc, DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescOneof, DescService } from "./descriptors.js";
import type { BinaryReadOptions } from "./from-binary.js";
import type { ReflectMessage } from "./reflect/reflect-types.js";
import type { Extendee, ExtensionValueShape } from "./types.js";
import type { EnumOptions, EnumValueOptions, FieldOptions, FileOptions, MessageOptions, MethodOptions, OneofOptions, ServiceOptions } from "./wkt/gen/google/protobuf/descriptor_pb.js";
/**
* Retrieve an extension value from a message.
*
* The function never returns undefined. Use hasExtension() to check whether an
* extension is set. If the extension is not set, this function returns the
* default value (if one was specified in the protobuf source), or the zero value
* (for example `0` for numeric types, `[]` for repeated extension fields, and
* an empty message instance for message fields).
*
* Extensions are stored as unknown fields on a message. To mutate an extension
* value, make sure to store the new value with setExtension() after mutating.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function getExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc, options?: Partial<BinaryReadOptions>): ExtensionValueShape<Desc>;
/**
* Set an extension value on a message. If the message already has a value for
* this extension, the value is replaced.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function setExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc, value: ExtensionValueShape<Desc>): void;
/**
* Remove an extension value from a message.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function clearExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc): void;
/**
* Check whether an extension is set on a message.
*/
export declare function hasExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc): boolean;
/**
* Check whether an option is set on a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls hasExtension().
*/
export declare function hasOption<Ext extends DescExtension, Desc extends DescForOptionExtension<Ext>>(element: Desc, option: Ext): boolean;
/**
* Retrieve an option value from a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls getExtension(). Same as getExtension(), this
* function never returns undefined.
*/
export declare function getOption<Ext extends DescExtension, Desc extends DescForOptionExtension<Ext>>(element: Desc, option: Ext): ExtensionValueShape<Ext>;
type DescForOptionExtension<Ext extends DescExtension> = Extendee<Ext> extends FileOptions ? DescFile : Extendee<Ext> extends EnumOptions ? DescEnum : Extendee<Ext> extends EnumValueOptions ? DescEnumValue : Extendee<Ext> extends MessageOptions ? DescMessage : Extendee<Ext> extends MessageOptions ? DescEnum : Extendee<Ext> extends FieldOptions ? DescField | DescExtension : Extendee<Ext> extends OneofOptions ? DescOneof : Extendee<Ext> extends ServiceOptions ? DescService : Extendee<Ext> extends EnumOptions ? DescEnum : Extendee<Ext> extends MethodOptions ? DescMethod : AnyDesc;
/**
* @private
*/
export declare function createExtensionContainer<Desc extends DescExtension>(extension: Desc, value?: ExtensionValueShape<Desc>): [ReflectMessage, DescField, () => ExtensionValueShape<Desc>];
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.getExtension = getExtension;
exports.setExtension = setExtension;
exports.clearExtension = clearExtension;
exports.hasExtension = hasExtension;
exports.hasOption = hasOption;
exports.getOption = getOption;
exports.createExtensionContainer = createExtensionContainer;
const create_js_1 = require("./create.js");
const from_binary_js_1 = require("./from-binary.js");
const reflect_js_1 = require("./reflect/reflect.js");
const scalar_js_1 = require("./reflect/scalar.js");
const to_binary_js_1 = require("./to-binary.js");
const binary_encoding_js_1 = require("./wire/binary-encoding.js");
const wrappers_js_1 = require("./wkt/wrappers.js");
/**
* Retrieve an extension value from a message.
*
* The function never returns undefined. Use hasExtension() to check whether an
* extension is set. If the extension is not set, this function returns the
* default value (if one was specified in the protobuf source), or the zero value
* (for example `0` for numeric types, `[]` for repeated extension fields, and
* an empty message instance for message fields).
*
* Extensions are stored as unknown fields on a message. To mutate an extension
* value, make sure to store the new value with setExtension() after mutating.
*
* If the extension does not extend the given message, an error is raised.
*/
function getExtension(message, extension, options) {
assertExtendee(extension, message);
const ufs = filterUnknownFields(message.$unknown, extension);
const [container, field, get] = createExtensionContainer(extension);
const ctx = (0, from_binary_js_1.makeReadContext)(options);
for (const uf of ufs) {
(0, from_binary_js_1.readField)(container, new binary_encoding_js_1.BinaryReader(uf.data), field, uf.wireType, ctx);
}
return get();
}
/**
* Set an extension value on a message. If the message already has a value for
* this extension, the value is replaced.
*
* If the extension does not extend the given message, an error is raised.
*/
function setExtension(message, extension, value) {
var _a;
assertExtendee(extension, message);
const ufs = ((_a = message.$unknown) !== null && _a !== void 0 ? _a : []).filter((uf) => uf.no !== extension.number);
const [container, field] = createExtensionContainer(extension, value);
const writer = new binary_encoding_js_1.BinaryWriter();
(0, to_binary_js_1.writeField)(writer, { writeUnknownFields: true }, container, field);
const reader = new binary_encoding_js_1.BinaryReader(writer.finish());
while (reader.pos < reader.len) {
const [no, wireType] = reader.tag();
const data = reader.skip(wireType, no);
ufs.push({ no, wireType, data });
}
message.$unknown = ufs;
}
/**
* Remove an extension value from a message.
*
* If the extension does not extend the given message, an error is raised.
*/
function clearExtension(message, extension) {
assertExtendee(extension, message);
if (message.$unknown === undefined) {
return;
}
message.$unknown = message.$unknown.filter((uf) => uf.no !== extension.number);
}
/**
* Check whether an extension is set on a message.
*/
function hasExtension(message, extension) {
var _a;
return (extension.extendee.typeName === message.$typeName &&
!!((_a = message.$unknown) === null || _a === void 0 ? void 0 : _a.find((uf) => uf.no === extension.number)));
}
/**
* Check whether an option is set on a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls hasExtension().
*/
function hasOption(element, option) {
const message = element.proto.options;
if (!message) {
return false;
}
return hasExtension(message, option);
}
/**
* Retrieve an option value from a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls getExtension(). Same as getExtension(), this
* function never returns undefined.
*/
function getOption(element, option) {
const message = element.proto.options;
if (!message) {
const [, , get] = createExtensionContainer(option);
return get();
}
return getExtension(message, option);
}
function filterUnknownFields(unknownFields, extension) {
if (unknownFields === undefined)
return [];
if (extension.fieldKind === "enum" || extension.fieldKind === "scalar") {
// singular scalar fields do not merge, we pick the last
for (let i = unknownFields.length - 1; i >= 0; --i) {
if (unknownFields[i].no == extension.number) {
return [unknownFields[i]];
}
}
return [];
}
return unknownFields.filter((uf) => uf.no === extension.number);
}
/**
* @private
*/
function createExtensionContainer(extension, value) {
const localName = extension.typeName;
const field = Object.assign(Object.assign({}, extension), { kind: "field", parent: extension.extendee, localName });
const desc = Object.assign(Object.assign({}, extension.extendee), { fields: [field], members: [field], oneofs: [] });
const container = (0, create_js_1.create)(desc, value !== undefined ? { [localName]: value } : undefined);
return [
(0, reflect_js_1.reflect)(desc, container),
field,
() => {
const value = container[localName];
if (value === undefined) {
// biome-ignore lint/style/noNonNullAssertion: Only message fields are undefined, rest will have a zero value.
const desc = extension.message;
if ((0, wrappers_js_1.isWrapperDesc)(desc)) {
return (0, scalar_js_1.scalarZeroValue)(desc.fields[0].scalar, desc.fields[0].longAsString);
}
return (0, create_js_1.create)(desc);
}
return value;
},
];
}
function assertExtendee(extension, message) {
if (extension.extendee.typeName != message.$typeName) {
throw new Error(`extension ${extension.typeName} can only be applied to message ${extension.extendee.typeName}`);
}
}
import type { MessageShape } from "./types.js";
import type { DescField, DescMessage } from "./descriptors.js";
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
export declare function isFieldSet<Desc extends DescMessage>(message: MessageShape<Desc>, field: DescField): boolean;
/**
* Resets the field, so that isFieldSet() will return false.
*/
export declare function clearField<Desc extends DescMessage>(message: MessageShape<Desc>, field: DescField): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFieldSet = isFieldSet;
exports.clearField = clearField;
const unsafe_js_1 = require("./reflect/unsafe.js");
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
function isFieldSet(message, field) {
return (field.parent.typeName == message.$typeName && (0, unsafe_js_1.unsafeIsSet)(message, field));
}
/**
* Resets the field, so that isFieldSet() will return false.
*/
function clearField(message, field) {
if (field.parent.typeName == message.$typeName) {
(0, unsafe_js_1.unsafeClear)(message, field);
}
}
import { type DescField, type DescMessage } from "./descriptors.js";
import type { MessageShape } from "./types.js";
import type { ReflectMessage } from "./reflect/index.js";
import { BinaryReader, WireType } from "./wire/binary-encoding.js";
/**
* Options for parsing binary data.
*/
export interface BinaryReadOptions {
/**
* Retain unknown fields during parsing? The default behavior is to retain
* unknown fields and include them in the serialized output.
*
* For more details see https://developers.google.com/protocol-buffers/docs/proto3#unknowns
*/
readUnknownFields: boolean;
/**
* The maximum depth of nested messages to parse. If a message nests deeper
* than this limit, parsing fails with an error instead of exhausting the
* call stack. Defaults to 100.
*/
recursionLimit: number;
}
interface BinaryReadContext extends BinaryReadOptions {
depth: number;
}
/**
* @private Only exported for getExtension()
*/
export declare function makeReadContext(options?: Partial<BinaryReadOptions>): BinaryReadContext;
/**
* Parse serialized binary data.
*/
export declare function fromBinary<Desc extends DescMessage>(schema: Desc, bytes: Uint8Array, options?: Partial<BinaryReadOptions>): MessageShape<Desc>;
/**
* Parse from binary data, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
export declare function mergeFromBinary<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, bytes: Uint8Array, options?: Partial<BinaryReadOptions>): MessageShape<Desc>;
/**
* @private Only exported for getExtension()
*/
export declare function readField(message: ReflectMessage, reader: BinaryReader, field: DescField, wireType: WireType, ctx: BinaryReadContext): void;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeReadContext = makeReadContext;
exports.fromBinary = fromBinary;
exports.mergeFromBinary = mergeFromBinary;
exports.readField = readField;
const descriptors_js_1 = require("./descriptors.js");
const scalar_js_1 = require("./reflect/scalar.js");
const reflect_js_1 = require("./reflect/reflect.js");
const binary_encoding_js_1 = require("./wire/binary-encoding.js");
const varint_js_1 = require("./wire/varint.js");
/**
* @private Only exported for getExtension()
*/
function makeReadContext(options) {
return Object.assign(Object.assign({ readUnknownFields: true, recursionLimit: 100 }, options), { depth: 0 });
}
/**
* Parse serialized binary data.
*/
function fromBinary(schema, bytes, options) {
const msg = (0, reflect_js_1.reflect)(schema, undefined, false);
readMessage(msg, new binary_encoding_js_1.BinaryReader(bytes), makeReadContext(options), false, bytes.byteLength);
return msg.message;
}
/**
* Parse from binary data, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
function mergeFromBinary(schema, target, bytes, options) {
readMessage((0, reflect_js_1.reflect)(schema, target, false), new binary_encoding_js_1.BinaryReader(bytes), makeReadContext(options), false, bytes.byteLength);
return target;
}
/**
* If `delimited` is false, read the length given in `lengthOrDelimitedFieldNo`.
*
* If `delimited` is true, read until an EndGroup tag. `lengthOrDelimitedFieldNo`
* is the expected field number.
*
* @private
*/
function readMessage(message, reader, ctx, delimited, lengthOrDelimitedFieldNo) {
var _a;
if (++ctx.depth > ctx.recursionLimit) {
throw new Error(`cannot decode ${message.desc} from binary: maximum recursion depth of ${ctx.recursionLimit} reached`);
}
const end = delimited ? reader.len : reader.pos + lengthOrDelimitedFieldNo;
let fieldNo;
let wireType;
const unknownFields = (_a = message.getUnknown()) !== null && _a !== void 0 ? _a : [];
while (reader.pos < end) {
[fieldNo, wireType] = reader.tag();
if (delimited && wireType == binary_encoding_js_1.WireType.EndGroup) {
break;
}
const field = message.findNumber(fieldNo);
if (!field) {
// Use remaining recursion budget for skipping nested groups
const recursionLimit = ctx.recursionLimit - ctx.depth;
const data = reader.skip(wireType, fieldNo, recursionLimit);
if (ctx.readUnknownFields) {
unknownFields.push({ no: fieldNo, wireType, data });
}
continue;
}
readField(message, reader, field, wireType, ctx);
}
if (delimited) {
if (wireType != binary_encoding_js_1.WireType.EndGroup || fieldNo !== lengthOrDelimitedFieldNo) {
throw new Error("invalid end group tag");
}
}
if (unknownFields.length > 0) {
message.setUnknown(unknownFields);
}
ctx.depth--;
}
/**
* @private Only exported for getExtension()
*/
function readField(message, reader, field, wireType, ctx) {
var _a;
switch (field.fieldKind) {
case "scalar":
message.set(field, readScalar(reader, field.scalar, field.utf8Validation));
break;
case "enum":
const val = readScalar(reader, descriptors_js_1.ScalarType.INT32);
if (field.enum.open) {
message.set(field, val);
}
else {
const ok = field.enum.values.some((v) => v.number === val);
if (ok) {
message.set(field, val);
}
else if (ctx.readUnknownFields) {
const bytes = [];
(0, varint_js_1.varint32write)(val, bytes);
const unknownFields = (_a = message.getUnknown()) !== null && _a !== void 0 ? _a : [];
unknownFields.push({
no: field.number,
wireType,
data: new Uint8Array(bytes),
});
message.setUnknown(unknownFields);
}
}
break;
case "message":
message.set(field, readMessageField(reader, ctx, field, message.get(field)));
break;
case "list":
readListField(reader, wireType, message.get(field), ctx);
break;
case "map":
readMapEntry(reader, message.get(field), ctx);
break;
}
}
// Read a map field, expecting key field = 1, value field = 2
function readMapEntry(reader, map, ctx) {
const field = map.field();
let key;
let val;
// Read the length of the map entry, which is a varint.
const len = reader.uint32();
// WARNING: Calculate end AFTER advancing reader.pos (above), so that
// reader.pos is at the start of the map entry.
const end = reader.pos + len;
while (reader.pos < end) {
const [fieldNo] = reader.tag();
switch (fieldNo) {
case 1:
key = readScalar(reader, field.mapKey, field.utf8Validation);
break;
case 2:
switch (field.mapKind) {
case "scalar":
val = readScalar(reader, field.scalar, field.utf8Validation);
break;
case "enum":
val = reader.int32();
break;
case "message":
val = readMessageField(reader, ctx, field);
break;
}
break;
}
}
if (key === undefined) {
key = (0, scalar_js_1.scalarZeroValue)(field.mapKey, false);
}
if (val === undefined) {
switch (field.mapKind) {
case "scalar":
val = (0, scalar_js_1.scalarZeroValue)(field.scalar, false);
break;
case "enum":
val = field.enum.values[0].number;
break;
case "message":
val = (0, reflect_js_1.reflect)(field.message, undefined, false);
break;
}
}
map.set(key, val);
}
function readListField(reader, wireType, list, ctx) {
var _a;
const field = list.field();
if (field.listKind === "message") {
list.add(readMessageField(reader, ctx, field));
return;
}
const scalarType = (_a = field.scalar) !== null && _a !== void 0 ? _a : descriptors_js_1.ScalarType.INT32;
const packed = wireType == binary_encoding_js_1.WireType.LengthDelimited &&
scalarType != descriptors_js_1.ScalarType.STRING &&
scalarType != descriptors_js_1.ScalarType.BYTES;
if (!packed) {
list.add(readScalar(reader, scalarType, field.utf8Validation));
return;
}
const e = reader.uint32() + reader.pos;
while (reader.pos < e) {
list.add(readScalar(reader, scalarType, field.utf8Validation));
}
}
function readMessageField(reader, ctx, field, mergeMessage) {
const delimited = field.delimitedEncoding;
const message = mergeMessage !== null && mergeMessage !== void 0 ? mergeMessage : (0, reflect_js_1.reflect)(field.message, undefined, false);
readMessage(message, reader, ctx, delimited, delimited ? field.number : reader.uint32());
return message;
}
function readScalar(reader, type, validateUtf8 = false) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return reader.string(validateUtf8);
case descriptors_js_1.ScalarType.BOOL:
return reader.bool();
case descriptors_js_1.ScalarType.DOUBLE:
return reader.double();
case descriptors_js_1.ScalarType.FLOAT:
return reader.float();
case descriptors_js_1.ScalarType.INT32:
return reader.int32();
case descriptors_js_1.ScalarType.INT64:
return reader.int64();
case descriptors_js_1.ScalarType.UINT64:
return reader.uint64();
case descriptors_js_1.ScalarType.FIXED64:
return reader.fixed64();
case descriptors_js_1.ScalarType.BYTES:
return reader.bytes();
case descriptors_js_1.ScalarType.FIXED32:
return reader.fixed32();
case descriptors_js_1.ScalarType.SFIXED32:
return reader.sfixed32();
case descriptors_js_1.ScalarType.SFIXED64:
return reader.sfixed64();
case descriptors_js_1.ScalarType.SINT64:
return reader.sint64();
case descriptors_js_1.ScalarType.UINT32:
return reader.uint32();
case descriptors_js_1.ScalarType.SINT32:
return reader.sint32();
}
}
import { type DescEnum, type DescMessage } from "./descriptors.js";
import type { JsonValue } from "./json-value.js";
import type { Registry } from "./registry.js";
import type { EnumJsonType, EnumShape, MessageShape } from "./types.js";
/**
* Options for parsing JSON data.
*/
export interface JsonReadOptions {
/**
* Ignore unknown fields: Proto3 JSON parser should reject unknown fields
* by default. This option ignores unknown fields in parsing, as well as
* unrecognized enum string representations.
*/
ignoreUnknownFields: boolean;
/**
* This option is required to read `google.protobuf.Any` and extensions
* from JSON format.
*/
registry?: Registry | undefined;
/**
* The maximum depth of nested messages to parse. If a message nests deeper
* than this limit, parsing fails with an error instead of exhausting the
* call stack. Defaults to 100.
*/
recursionLimit: number;
}
/**
* Parse a message from a JSON string.
*
* Duplicate keys are rejected.
*/
export declare function fromJsonString<Desc extends DescMessage>(schema: Desc, json: string, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON string, merging fields into the target.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*
* Duplicate keys in the JSON are rejected, as in `fromJsonString`.
*/
export declare function mergeFromJsonString<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, json: string, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON value.
*
* Duplicate keys are rejected, but a value parsed by JSON.parse has already
* dropped duplicates (the last one wins). Use `fromJsonString` for strict
* duplicate-key checking.
*/
export declare function fromJson<Desc extends DescMessage>(schema: Desc, json: JsonValue, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON value, merging fields into the target.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*
* Duplicate keys are rejected as in `fromJson`; use `mergeFromJsonString`
* for strict checking.
*/
export declare function mergeFromJson<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, json: JsonValue, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parses an enum value from JSON.
*/
export declare function enumFromJson<Desc extends DescEnum>(descEnum: Desc, json: EnumJsonType<Desc>): EnumShape<Desc>;
/**
* Is the given value a JSON enum value?
*/
export declare function isEnumJson<Desc extends DescEnum>(descEnum: Desc, value: unknown): value is EnumJsonType<Desc>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJsonString = fromJsonString;
exports.mergeFromJsonString = mergeFromJsonString;
exports.fromJson = fromJson;
exports.mergeFromJson = mergeFromJson;
exports.enumFromJson = enumFromJson;
exports.isEnumJson = isEnumJson;
const descriptors_js_1 = require("./descriptors.js");
const proto_int64_js_1 = require("./proto-int64.js");
const create_js_1 = require("./create.js");
const reflect_js_1 = require("./reflect/reflect.js");
const error_js_1 = require("./reflect/error.js");
const reflect_check_js_1 = require("./reflect/reflect-check.js");
const names_js_1 = require("./reflect/names.js");
const base64_encoding_js_1 = require("./wire/base64-encoding.js");
const index_js_1 = require("./wkt/index.js");
const extensions_js_1 = require("./extensions.js");
function makeReadContext(options) {
return Object.assign(Object.assign({ ignoreUnknownFields: false, recursionLimit: 100 }, options), { depth: 0 });
}
/**
* Parse a message from a JSON string.
*
* Duplicate keys are rejected.
*/
function fromJsonString(schema, json, options) {
return fromJson(schema, parseJsonString(json, schema.typeName), options);
}
/**
* Parse a message from a JSON string, merging fields into the target.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*
* Duplicate keys in the JSON are rejected, as in `fromJsonString`.
*/
function mergeFromJsonString(schema, target, json, options) {
return mergeFromJson(schema, target, parseJsonString(json, schema.typeName), options);
}
/**
* Parse a message from a JSON value.
*
* Duplicate keys are rejected, but a value parsed by JSON.parse has already
* dropped duplicates (the last one wins). Use `fromJsonString` for strict
* duplicate-key checking.
*/
function fromJson(schema, json, options) {
const msg = (0, reflect_js_1.reflect)(schema);
try {
readMessage(msg, json, makeReadContext(options));
}
catch (e) {
if ((0, error_js_1.isFieldError)(e)) {
// @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
throw new Error(`cannot decode ${e.field()} from JSON: ${e.message}`, {
cause: e,
});
}
throw e;
}
return msg.message;
}
/**
* Parse a message from a JSON value, merging fields into the target.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*
* Duplicate keys are rejected as in `fromJson`; use `mergeFromJsonString`
* for strict checking.
*/
function mergeFromJson(schema, target, json, options) {
try {
readMessage((0, reflect_js_1.reflect)(schema, target), json, makeReadContext(options));
}
catch (e) {
if ((0, error_js_1.isFieldError)(e)) {
// @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
throw new Error(`cannot decode ${e.field()} from JSON: ${e.message}`, {
cause: e,
});
}
throw e;
}
return target;
}
/**
* Parses an enum value from JSON.
*/
function enumFromJson(descEnum, json) {
return readEnum(descEnum, json, false);
}
/**
* Is the given value a JSON enum value?
*/
function isEnumJson(descEnum, value) {
return undefined !== descEnum.values.find((v) => v.name === value);
}
const messageJsonFields = new WeakMap();
function getJsonField(desc, jsonKey) {
var _a;
if (!messageJsonFields.has(desc)) {
const jsonNames = new Map();
for (const field of desc.fields) {
jsonNames.set(field.name, field).set(field.jsonName, field);
}
messageJsonFields.set(desc, jsonNames);
}
return (_a = messageJsonFields.get(desc)) === null || _a === void 0 ? void 0 : _a.get(jsonKey);
}
function readMessage(msg, json, ctx) {
var _a;
if (++ctx.depth > ctx.recursionLimit) {
throw new Error(`cannot decode ${msg.desc} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
}
if (tryWktFromJson(msg, json, ctx)) {
ctx.depth--;
return;
}
if (json == null || Array.isArray(json) || typeof json != "object") {
throw new Error(`cannot decode ${msg.desc} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
const oneofSeen = new Map();
const fieldSeen = new Set();
for (const [jsonKey, jsonValue] of Object.entries(json)) {
const field = getJsonField(msg.desc, jsonKey);
if (field) {
if (fieldSeen.has(field)) {
// The same field may be set by its proto name and its JSON name, or by
// a duplicate or unicode-escaped key that JSON.parse already collapsed.
// Checked before the null-skip below so that a null entry still counts.
throw new error_js_1.FieldError(field, "set multiple times");
}
fieldSeen.add(field);
if (field.oneof && jsonValue === null && field.fieldKind == "scalar") {
// see conformance test Required.Proto3.JsonInput.OneofFieldNull{First,Second}
continue;
}
if (field.oneof) {
const seen = oneofSeen.get(field.oneof);
if (seen !== undefined) {
throw new error_js_1.FieldError(field.oneof, `oneof set multiple times by ${seen.name} and ${field.name}`);
}
oneofSeen.set(field.oneof, field);
}
readField(msg, field, jsonValue, ctx);
}
else {
let extension = undefined;
if (jsonKey.startsWith("[") &&
jsonKey.endsWith("]") &&
// biome-ignore lint/suspicious/noAssignInExpressions: no
(extension = (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getExtension(jsonKey.substring(1, jsonKey.length - 1))) &&
extension.extendee.typeName === msg.desc.typeName) {
const [container, field, get] = (0, extensions_js_1.createExtensionContainer)(extension);
readField(container, field, jsonValue, ctx);
(0, extensions_js_1.setExtension)(msg.message, extension, get());
}
if (!extension && !ctx.ignoreUnknownFields) {
throw new Error(`cannot decode ${msg.desc} from JSON: key "${jsonKey}" is unknown`);
}
}
}
ctx.depth--;
}
function readField(msg, field, json, ctx) {
switch (field.fieldKind) {
case "scalar":
readScalarField(msg, field, json);
break;
case "enum":
readEnumField(msg, field, json, ctx);
break;
case "message":
readMessageField(msg, field, json, ctx);
break;
case "list":
readListField(msg.get(field), json, ctx);
break;
case "map":
readMapField(msg.get(field), json, ctx);
break;
}
}
function readListOrMapItem(field, json, ctx) {
if (field.scalar && json !== null) {
return scalarFromJson(field, json);
}
if (field.message && !isResetSentinelNullValue(field, json)) {
const msgValue = (0, reflect_js_1.reflect)(field.message);
readMessage(msgValue, json, ctx);
return msgValue;
}
if (field.enum && !isResetSentinelNullValue(field, json)) {
return readEnum(field.enum, json, ctx.ignoreUnknownFields);
}
throw new error_js_1.FieldError(field, `${field.fieldKind === "list" ? "list item" : "map value"} must not be null`);
}
function readMapField(map, json, ctx) {
if (json === null) {
return;
}
const field = map.field();
if (typeof json != "object" || Array.isArray(json)) {
throw new error_js_1.FieldError(field, "expected object, got " + (0, reflect_check_js_1.formatVal)(json));
}
const seen = new Set();
for (const [jsonMapKey, jsonMapValue] of Object.entries(json)) {
const key = mapKeyFromJson(field.mapKey, jsonMapKey);
if (seen.has(key)) {
throw new error_js_1.FieldError(field, `duplicate map key "${jsonMapKey}"`);
}
seen.add(key);
const value = readListOrMapItem(field, jsonMapValue, ctx);
if (value !== tokenIgnoredUnknownEnum) {
map.set(key, value);
}
}
}
function readListField(list, json, ctx) {
if (json === null) {
return;
}
const field = list.field();
if (!Array.isArray(json)) {
throw new error_js_1.FieldError(field, "expected Array, got " + (0, reflect_check_js_1.formatVal)(json));
}
for (const jsonItem of json) {
const value = readListOrMapItem(field, jsonItem, ctx);
if (value !== tokenIgnoredUnknownEnum) {
list.add(value);
}
}
}
function readMessageField(msg, field, json, ctx) {
if (isResetSentinelNullValue(field, json)) {
msg.clear(field);
return;
}
const msgValue = msg.isSet(field) ? msg.get(field) : (0, reflect_js_1.reflect)(field.message);
readMessage(msgValue, json, ctx);
msg.set(field, msgValue);
}
function readEnumField(msg, field, json, ctx) {
if (isResetSentinelNullValue(field, json)) {
msg.clear(field);
return;
}
const enumValue = readEnum(field.enum, json, ctx.ignoreUnknownFields);
if (enumValue !== tokenIgnoredUnknownEnum) {
msg.set(field, enumValue);
}
}
function readScalarField(msg, field, json) {
if (json === null) {
msg.clear(field);
}
else {
msg.set(field, scalarFromJson(field, json));
}
}
/**
* Indicates whether a value is a sentinel for reseting a field.
*
* For this to be true, the value must be a JSON null and the field must not
* permit a present, Protobuf-serializable null.
*
* Only message google.protobuf.Value and enum google.protobuf.NullValue fields
* permit Protobuf-serializable nulls.
*
* Note that field-resetting sentinel nulls are not permitted in lists and maps.
*/
function isResetSentinelNullValue(field, json) {
var _a, _b;
return (json === null &&
((_a = field.message) === null || _a === void 0 ? void 0 : _a.typeName) != "google.protobuf.Value" &&
((_b = field.enum) === null || _b === void 0 ? void 0 : _b.typeName) != "google.protobuf.NullValue");
}
const tokenIgnoredUnknownEnum = Symbol();
function readEnum(desc, json, ignoreUnknownFields) {
if (json === null) {
return desc.values[0].number;
}
switch (typeof json) {
case "number":
if (Number.isInteger(json)) {
return json;
}
break;
case "string":
const value = desc.values.find((ev) => ev.name === json);
if (value !== undefined) {
return value.number;
}
if (ignoreUnknownFields) {
return tokenIgnoredUnknownEnum;
}
break;
}
throw new Error(`cannot decode ${desc} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
/**
* Try to parse a JSON value to a scalar value for the reflect API.
*
* Returns the input if the JSON value cannot be converted. Raises a FieldError
* if conversion would be ambiguous.
*/
function scalarFromJson(field, json) {
// int64, sfixed64, sint64, fixed64, uint64: Reflect supports string and number.
// string, bool: Supported by reflect.
switch (field.scalar) {
// float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
// Either numbers or strings are accepted. Exponent notation is also accepted.
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
if (json === "NaN")
return NaN;
if (json === "Infinity")
return Number.POSITIVE_INFINITY;
if (json === "-Infinity")
return Number.NEGATIVE_INFINITY;
if (typeof json == "number") {
if (Number.isNaN(json)) {
// NaN must be encoded with string constants
throw new error_js_1.FieldError(field, "unexpected NaN number");
}
if (!Number.isFinite(json)) {
// Infinity must be encoded with string constants
throw new error_js_1.FieldError(field, "unexpected infinite number");
}
break;
}
if (typeof json == "string") {
if (json === "") {
// empty string is not a number
break;
}
if (json.trim().length !== json.length) {
// extra whitespace
break;
}
const float = Number(json);
if (!Number.isFinite(float)) {
// Infinity and NaN must be encoded with string constants
break;
}
return float;
}
break;
// int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.UINT32:
return int32FromJson(json);
// bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
// Either standard or URL-safe base64 encoding with/without paddings are accepted.
case descriptors_js_1.ScalarType.BYTES:
if (typeof json == "string") {
if (json === "") {
return new Uint8Array(0);
}
try {
return (0, base64_encoding_js_1.base64Decode)(json);
}
catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new error_js_1.FieldError(field, message);
}
}
break;
}
return json;
}
/**
* Try to parse a JSON value to a map key for the reflect API.
* Canonicalizes 64-bit integers given as string, so that "01 and "1" are one
* key, and duplicates can raise an error.
* Returns the input if the JSON value cannot be converted.
*/
function mapKeyFromJson(type, jsonString) {
switch (type) {
case descriptors_js_1.ScalarType.BOOL:
switch (jsonString) {
case "true":
return true;
case "false":
return false;
}
return jsonString;
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
return int32FromJson(jsonString);
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
return /^-?0+$/.test(jsonString)
? "0"
: jsonString.replace(/^(-?)0+(?=\d)/, "$1");
default:
return jsonString;
}
}
/**
* Try to parse a JSON value to a 32-bit integer for the reflect API.
*
* Returns the input if the JSON value cannot be converted.
*/
function int32FromJson(json) {
if (typeof json == "string") {
if (json === "") {
// empty string is not a number
return json;
}
if (json.trim().length !== json.length) {
// extra whitespace
return json;
}
const num = Number(json);
if (Number.isNaN(num)) {
// not a number
return json;
}
return num;
}
return json;
}
/**
* Parse a JSON string, rejecting duplicate object keys (which JSON.parse would
* otherwise silently merge).
*/
function parseJsonString(jsonString, typeName) {
let json;
try {
json = JSON.parse(jsonString);
}
catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(`cannot decode message ${typeName} from JSON: ${message}`,
// @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
{ cause: e });
}
checkDuplicateKeys(jsonString, typeName);
return json;
}
/**
* Scan a JSON string for duplicate object member names at any depth, throwing
* if any are found. JSON.parse() silently keeps the last of duplicate keys, so
* this raw-string scan is the only way to reject them. It must only be called
* with a string that JSON.parse() has already accepted, so it can assume the
* input is well-formed.
*/
function checkDuplicateKeys(jsonString, typeName) {
// One Set of seen member names for each open object; arrays push null.
const stack = [];
// Whether the next string token is an object member name.
let expectKey = false;
let i = 0;
while (i < jsonString.length) {
switch (jsonString[i]) {
case "{":
stack.push(new Set());
expectKey = true;
i++;
break;
case "[":
stack.push(null);
expectKey = false;
i++;
break;
case "}":
case "]":
stack.pop();
expectKey = false;
i++;
break;
case ",":
expectKey = stack[stack.length - 1] != null;
i++;
break;
case ":":
expectKey = false;
i++;
break;
case '"': {
const open = i++;
let escaped = false;
while (i < jsonString.length) {
if (jsonString[i] == "\\") {
escaped = true;
i += 2; // skip the backslash and the character it escapes
continue;
}
if (jsonString[i] == '"') {
break;
}
i++;
}
const close = i++;
const seen = stack[stack.length - 1];
if (expectKey && seen) {
// Decode escapes (rare) so that, for example, a key written with a
// unicode escape collides with the same key written literally.
const name = escaped
? JSON.parse(jsonString.substring(open, close + 1))
: jsonString.substring(open + 1, close);
if (seen.has(name)) {
throw new Error(`cannot decode message ${typeName} from JSON: duplicate object key "${name}"`);
}
seen.add(name);
}
expectKey = false;
break;
}
default:
i++;
break;
}
}
}
function tryWktFromJson(msg, jsonValue, ctx) {
if (!msg.desc.typeName.startsWith("google.protobuf.")) {
return false;
}
switch (msg.desc.typeName) {
case "google.protobuf.Any":
anyFromJson(msg.message, jsonValue, ctx);
return true;
case "google.protobuf.Timestamp":
timestampFromJson(msg.message, jsonValue);
return true;
case "google.protobuf.Duration":
durationFromJson(msg.message, jsonValue);
return true;
case "google.protobuf.FieldMask":
fieldMaskFromJson(msg.message, jsonValue);
return true;
case "google.protobuf.Struct":
structFromJson(msg.message, jsonValue, ctx);
return true;
case "google.protobuf.Value":
valueFromJson(msg.message, jsonValue, ctx);
return true;
case "google.protobuf.ListValue":
listValueFromJson(msg.message, jsonValue, ctx);
return true;
default:
if ((0, index_js_1.isWrapperDesc)(msg.desc)) {
const valueField = msg.desc.fields[0];
if (jsonValue === null) {
msg.clear(valueField);
}
else {
msg.set(valueField, scalarFromJson(valueField, jsonValue));
}
return true;
}
return false;
}
}
function anyFromJson(any, json, ctx) {
var _a;
if (json === null || Array.isArray(json) || typeof json != "object") {
throw new Error(`cannot decode message ${any.$typeName} from JSON: expected object but got ${(0, reflect_check_js_1.formatVal)(json)}`);
}
if (Object.keys(json).length == 0) {
return;
}
const typeUrl = json["@type"];
if (typeof typeUrl != "string" || typeUrl == "") {
throw new Error(`cannot decode message ${any.$typeName} from JSON: "@type" is empty`);
}
const typeName = typeUrl.includes("/")
? typeUrl.substring(typeUrl.lastIndexOf("/") + 1)
: typeUrl;
if (!typeName.length) {
throw new Error(`cannot decode message ${any.$typeName} from JSON: "@type" is invalid`);
}
const desc = (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getMessage(typeName);
if (!desc) {
throw new Error(`cannot decode message ${any.$typeName} from JSON: ${typeUrl} is not in the type registry`);
}
const msg = (0, reflect_js_1.reflect)(desc);
if ((0, index_js_1.hasCustomJsonRepresentation)(desc) &&
Object.prototype.hasOwnProperty.call(json, "value")) {
const value = json.value;
readMessage(msg, value, ctx);
}
else {
const copy = Object.assign({}, json);
// biome-ignore lint/performance/noDelete: <explanation>
delete copy["@type"];
readMessage(msg, copy, ctx);
}
(0, index_js_1.anyPack)(msg.desc, msg.message, any);
}
function timestampFromJson(timestamp, json) {
if (typeof json !== "string") {
throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
const matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);
if (!matches) {
throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);
}
const ms = Date.parse(
// biome-ignore format: want this to read well
matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z"));
if (Number.isNaN(ms)) {
throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);
}
if (ms < Date.parse("0001-01-01T00:00:00Z") ||
ms > Date.parse("9999-12-31T23:59:59Z")) {
throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
}
timestamp.seconds = proto_int64_js_1.protoInt64.parse(ms / 1000);
timestamp.nanos = 0;
if (matches[7]) {
timestamp.nanos =
parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) -
1000000000;
}
}
function durationFromJson(duration, json) {
if (typeof json !== "string") {
throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
const match = json.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);
if (match === null) {
throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
const longSeconds = Number(match[1]);
if (longSeconds > 315576000000 || longSeconds < -315576000000) {
throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
duration.seconds = proto_int64_js_1.protoInt64.parse(longSeconds);
if (typeof match[2] !== "string") {
return;
}
const nanosStr = match[2] + "0".repeat(9 - match[2].length);
duration.nanos = parseInt(nanosStr);
if (longSeconds < 0 || Object.is(longSeconds, -0)) {
duration.nanos = -duration.nanos;
}
}
function fieldMaskFromJson(fieldMask, json) {
if (typeof json !== "string") {
throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
if (json === "") {
return;
}
fieldMask.paths = json.split(",").map((path) => {
if (path.includes("_")) {
throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: path names must be lowerCamelCase`);
}
return (0, names_js_1.protoSnakeCase)(path);
});
}
function structFromJson(struct, json, ctx) {
if (typeof json != "object" || json == null || Array.isArray(json)) {
throw new Error(`cannot decode message ${struct.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
}
for (const [k, v] of Object.entries(json)) {
const parsedV = (0, create_js_1.create)(index_js_1.ValueSchema);
valueFromJson(parsedV, v, ctx);
struct.fields[k] = parsedV;
}
}
function valueFromJson(value, json, ctx) {
if (++ctx.depth > ctx.recursionLimit) {
throw new Error(`cannot decode ${value.$typeName} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
}
switch (typeof json) {
case "number":
value.kind = { case: "numberValue", value: json };
break;
case "string":
value.kind = { case: "stringValue", value: json };
break;
case "boolean":
value.kind = { case: "boolValue", value: json };
break;
case "object":
if (json === null) {
value.kind = { case: "nullValue", value: index_js_1.NullValue.NULL_VALUE };
}
else if (Array.isArray(json)) {
const listValue = (0, create_js_1.create)(index_js_1.ListValueSchema);
listValueFromJson(listValue, json, ctx);
value.kind = { case: "listValue", value: listValue };
}
else {
const struct = (0, create_js_1.create)(index_js_1.StructSchema);
structFromJson(struct, json, ctx);
value.kind = { case: "structValue", value: struct };
}
break;
default:
throw new Error(`cannot decode message ${value.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
}
ctx.depth--;
return value;
}
function listValueFromJson(listValue, json, ctx) {
if (!Array.isArray(json)) {
throw new Error(`cannot decode message ${listValue.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
}
for (const e of json) {
const value = (0, create_js_1.create)(index_js_1.ValueSchema);
valueFromJson(value, e, ctx);
listValue.values.push(value);
}
}
export * from "./types.js";
export * from "./is-message.js";
export * from "./create.js";
export * from "./clone.js";
export * from "./descriptors.js";
export * from "./equals.js";
export * from "./fields.js";
export * from "./registry.js";
export type { JsonValue, JsonObject } from "./json-value.js";
export { toBinary } from "./to-binary.js";
export type { BinaryWriteOptions } from "./to-binary.js";
export { fromBinary, mergeFromBinary } from "./from-binary.js";
export type { BinaryReadOptions } from "./from-binary.js";
export * from "./to-json.js";
export * from "./from-json.js";
export * from "./merge.js";
export { hasExtension, getExtension, setExtension, clearExtension, hasOption, getOption, } from "./extensions.js";
export * from "./proto-int64.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOption = exports.hasOption = exports.clearExtension = exports.setExtension = exports.getExtension = exports.hasExtension = exports.mergeFromBinary = exports.fromBinary = exports.toBinary = void 0;
__exportStar(require("./types.js"), exports);
__exportStar(require("./is-message.js"), exports);
__exportStar(require("./create.js"), exports);
__exportStar(require("./clone.js"), exports);
__exportStar(require("./descriptors.js"), exports);
__exportStar(require("./equals.js"), exports);
__exportStar(require("./fields.js"), exports);
__exportStar(require("./registry.js"), exports);
var to_binary_js_1 = require("./to-binary.js");
Object.defineProperty(exports, "toBinary", { enumerable: true, get: function () { return to_binary_js_1.toBinary; } });
var from_binary_js_1 = require("./from-binary.js");
Object.defineProperty(exports, "fromBinary", { enumerable: true, get: function () { return from_binary_js_1.fromBinary; } });
Object.defineProperty(exports, "mergeFromBinary", { enumerable: true, get: function () { return from_binary_js_1.mergeFromBinary; } });
__exportStar(require("./to-json.js"), exports);
__exportStar(require("./from-json.js"), exports);
__exportStar(require("./merge.js"), exports);
var extensions_js_1 = require("./extensions.js");
Object.defineProperty(exports, "hasExtension", { enumerable: true, get: function () { return extensions_js_1.hasExtension; } });
Object.defineProperty(exports, "getExtension", { enumerable: true, get: function () { return extensions_js_1.getExtension; } });
Object.defineProperty(exports, "setExtension", { enumerable: true, get: function () { return extensions_js_1.setExtension; } });
Object.defineProperty(exports, "clearExtension", { enumerable: true, get: function () { return extensions_js_1.clearExtension; } });
Object.defineProperty(exports, "hasOption", { enumerable: true, get: function () { return extensions_js_1.hasOption; } });
Object.defineProperty(exports, "getOption", { enumerable: true, get: function () { return extensions_js_1.getOption; } });
__exportStar(require("./proto-int64.js"), exports);
import type { MessageShape } from "./types.js";
import type { DescMessage } from "./descriptors.js";
/**
* Determine whether the given `arg` is a message.
* If `desc` is set, determine whether `arg` is this specific message.
*/
export declare function isMessage<Desc extends DescMessage>(arg: unknown, schema?: Desc): arg is MessageShape<Desc>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isMessage = isMessage;
/**
* Determine whether the given `arg` is a message.
* If `desc` is set, determine whether `arg` is this specific message.
*/
function isMessage(arg, schema) {
const isMessage = arg !== null &&
typeof arg == "object" &&
"$typeName" in arg &&
typeof arg.$typeName == "string";
if (!isMessage) {
return false;
}
if (schema === undefined) {
return true;
}
return schema.typeName === arg.$typeName;
}
/**
* Represents any possible JSON value:
* - number
* - string
* - boolean
* - null
* - object (with any JSON value as property)
* - array (with any JSON value as element)
*/
export type JsonValue = number | string | boolean | null | JsonObject | JsonValue[];
/**
* Represents a JSON object.
*/
export type JsonObject = {
[k: string]: JsonValue;
};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
import type { MessageShape } from "./types.js";
import type { DescMessage } from "./descriptors.js";
/**
* Merge message `source` into message `target`, following Protobuf semantics.
*
* This is the same as serializing the source message, then deserializing it
* into the target message via `mergeFromBinary()`, with one difference:
* While serialization will create a copy of all values, `merge()` will copy
* the reference for `bytes` and messages.
*
* Also see https://protobuf.com/docs/language-spec#merging-protobuf-messages
*/
export declare function merge<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, source: MessageShape<Desc>): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.merge = merge;
const reflect_js_1 = require("./reflect/reflect.js");
/**
* Merge message `source` into message `target`, following Protobuf semantics.
*
* This is the same as serializing the source message, then deserializing it
* into the target message via `mergeFromBinary()`, with one difference:
* While serialization will create a copy of all values, `merge()` will copy
* the reference for `bytes` and messages.
*
* Also see https://protobuf.com/docs/language-spec#merging-protobuf-messages
*/
function merge(schema, target, source) {
reflectMerge((0, reflect_js_1.reflect)(schema, target), (0, reflect_js_1.reflect)(schema, source));
}
function reflectMerge(target, source) {
var _a;
var _b;
const sourceUnknown = source.message.$unknown;
if (sourceUnknown !== undefined && sourceUnknown.length > 0) {
(_a = (_b = target.message).$unknown) !== null && _a !== void 0 ? _a : (_b.$unknown = []);
target.message.$unknown.push(...sourceUnknown);
}
for (const f of target.fields) {
if (!source.isSet(f)) {
continue;
}
switch (f.fieldKind) {
case "scalar":
case "enum":
target.set(f, source.get(f));
break;
case "message":
if (target.isSet(f)) {
reflectMerge(target.get(f), source.get(f));
}
else {
target.set(f, source.get(f));
}
break;
case "list":
const list = target.get(f);
for (const e of source.get(f)) {
list.add(e);
}
break;
case "map":
const map = target.get(f);
for (const [k, v] of source.get(f)) {
map.set(k, v);
}
break;
}
}
}
{
"type": "commonjs",
"sideEffects": false
}
/**
* Int64Support for the current environment.
*/
export declare const protoInt64: Int64Support;
/**
* We use the `bigint` primitive to represent 64-bit integral types. If bigint
* is unavailable, we fall back to a string representation, which means that
* all values typed as `bigint` will actually be strings.
*
* If your code is intended to run in an environment where bigint may be
* unavailable, it must handle both the bigint and the string representation.
* For presenting values, this is straight-forward with implicit or explicit
* conversion to string:
*
* ```ts
* let el = document.createElement("span");
* el.innerText = message.int64Field; // assuming a protobuf int64 field
*
* console.log(`int64: ${message.int64Field}`);
*
* let str: string = message.int64Field.toString();
* ```
*
* If you need to manipulate 64-bit integral values and are sure the values
* can be safely represented as an IEEE-754 double precision number, you can
* convert to a JavaScript Number:
*
* ```ts
* console.log(message.int64Field.toString())
* let num = Number(message.int64Field);
* num = num + 1;
* message.int64Field = protoInt64.parse(num);
* ```
*
* If you need to manipulate 64-bit integral values that are outside the
* range of safe representation as a JavaScript Number, we recommend you
* use a third party library, for example the npm package "long":
*
* ```ts
* // convert the field value to a Long
* const bits = protoInt64.enc(message.int64Field);
* const longValue = Long.fromBits(bits.lo, bits.hi);
*
* // perform arithmetic
* const longResult = longValue.subtract(1);
*
* // set the result in the field
* message.int64Field = protoInt64.dec(longResult.low, longResult.high);
*
* // Assuming int64Field contains 9223372036854775807:
* console.log(message.int64Field); // 9223372036854775806
* ```
*/
interface Int64Support {
/**
* 0n if bigint is available, "0" if unavailable.
*/
readonly zero: bigint;
/**
* Is bigint available?
*/
readonly supported: boolean;
/**
* Parse a signed 64-bit integer.
* Returns a bigint if available, a string otherwise.
*/
parse(value: string | number | bigint): bigint;
/**
* Parse an unsigned 64-bit integer.
* Returns a bigint if available, a string otherwise.
*/
uParse(value: string | number | bigint): bigint;
/**
* Convert a signed 64-bit integral value to a two's complement.
*/
enc(value: string | number | bigint): {
lo: number;
hi: number;
};
/**
* Convert an unsigned 64-bit integral value to a two's complement.
*/
uEnc(value: string | number | bigint): {
lo: number;
hi: number;
};
/**
* Convert a two's complement to a signed 64-bit integral value.
* Returns a bigint if available, a string otherwise.
*/
dec(lo: number, hi: number): bigint;
/**
* Convert a two's complement to an unsigned 64-bit integral value.
* Returns a bigint if available, a string otherwise.
*/
uDec(lo: number, hi: number): bigint;
}
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.protoInt64 = void 0;
const varint_js_1 = require("./wire/varint.js");
/**
* Int64Support for the current environment.
*/
exports.protoInt64 = makeInt64Support();
function makeInt64Support() {
const dv = new DataView(new ArrayBuffer(8));
// note that Safari 14 implements BigInt, but not the DataView methods
const ok = typeof BigInt === "function" &&
typeof dv.getBigInt64 === "function" &&
typeof dv.getBigUint64 === "function" &&
typeof dv.setBigInt64 === "function" &&
typeof dv.setBigUint64 === "function" &&
(!!globalThis.Deno ||
!!globalThis.Bun ||
typeof process != "object" ||
typeof process.env != "object" ||
process.env.BUF_BIGINT_DISABLE !== "1");
if (ok) {
const MIN = BigInt("-9223372036854775808");
const MAX = BigInt("9223372036854775807");
const UMIN = BigInt("0");
const UMAX = BigInt("18446744073709551615");
return {
zero: BigInt(0),
supported: true,
parse(value) {
const bi = typeof value == "bigint" ? value : BigInt(value);
if (bi > MAX || bi < MIN) {
throw new Error(`invalid int64: ${value}`);
}
return bi;
},
uParse(value) {
const bi = typeof value == "bigint" ? value : BigInt(value);
if (bi > UMAX || bi < UMIN) {
throw new Error(`invalid uint64: ${value}`);
}
return bi;
},
enc(value) {
dv.setBigInt64(0, this.parse(value), true);
return {
lo: dv.getInt32(0, true),
hi: dv.getInt32(4, true),
};
},
uEnc(value) {
dv.setBigInt64(0, this.uParse(value), true);
return {
lo: dv.getInt32(0, true),
hi: dv.getInt32(4, true),
};
},
dec(lo, hi) {
dv.setInt32(0, lo, true);
dv.setInt32(4, hi, true);
return dv.getBigInt64(0, true);
},
uDec(lo, hi) {
dv.setInt32(0, lo, true);
dv.setInt32(4, hi, true);
return dv.getBigUint64(0, true);
},
};
}
return {
zero: "0",
supported: false,
parse(value) {
if (typeof value != "string") {
value = value.toString();
}
assertInt64String(value);
return value;
},
uParse(value) {
if (typeof value != "string") {
value = value.toString();
}
assertUInt64String(value);
return value;
},
enc(value) {
if (typeof value != "string") {
value = value.toString();
}
assertInt64String(value);
return (0, varint_js_1.int64FromString)(value);
},
uEnc(value) {
if (typeof value != "string") {
value = value.toString();
}
assertUInt64String(value);
return (0, varint_js_1.int64FromString)(value);
},
dec(lo, hi) {
return (0, varint_js_1.int64ToString)(lo, hi);
},
uDec(lo, hi) {
return (0, varint_js_1.uInt64ToString)(lo, hi);
},
};
}
function assertInt64String(value) {
if (!/^-?[0-9]+$/.test(value)) {
throw new Error("invalid int64: " + value);
}
}
function assertUInt64String(value) {
if (!/^[0-9]+$/.test(value)) {
throw new Error("invalid uint64: " + value);
}
}
import type { DescField, DescOneof } from "../descriptors.js";
declare const errorNames: string[];
export declare class FieldError extends Error {
readonly name: (typeof errorNames)[number];
constructor(fieldOrOneof: DescField | DescOneof, message: string, name?: (typeof errorNames)[number]);
readonly field: () => DescField | DescOneof;
}
export declare function isFieldError(arg: unknown): arg is FieldError;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldError = void 0;
exports.isFieldError = isFieldError;
const errorNames = [
"FieldValueInvalidError",
"FieldListRangeError",
"ForeignFieldError",
];
class FieldError extends Error {
constructor(fieldOrOneof, message, name = "FieldValueInvalidError") {
super(message);
this.name = name;
this.field = () => fieldOrOneof;
}
}
exports.FieldError = FieldError;
function isFieldError(arg) {
return (arg instanceof Error &&
errorNames.includes(arg.name) &&
"field" in arg &&
typeof arg.field == "function");
}
import type { Message } from "../types.js";
import type { ScalarValue } from "./scalar.js";
import type { ReflectList, ReflectMap, ReflectMessage } from "./reflect-types.js";
import type { DescField, DescMessage } from "../descriptors.js";
export declare function isObject(arg: unknown): arg is Record<string, unknown>;
export declare function isOneofADT(arg: unknown): arg is OneofADT;
export type OneofADT = {
case: undefined;
value?: undefined;
} | {
case: string;
value: Message | ScalarValue;
};
export declare function isReflectList(arg: unknown, field?: DescField & {
fieldKind: "list";
}): arg is ReflectList;
export declare function isReflectMap(arg: unknown, field?: DescField & {
fieldKind: "map";
}): arg is ReflectMap;
export declare function isReflectMessage(arg: unknown, messageDesc?: DescMessage): arg is ReflectMessage;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isObject = isObject;
exports.isOneofADT = isOneofADT;
exports.isReflectList = isReflectList;
exports.isReflectMap = isReflectMap;
exports.isReflectMessage = isReflectMessage;
const unsafe_js_1 = require("./unsafe.js");
function isObject(arg) {
return arg !== null && typeof arg == "object" && !Array.isArray(arg);
}
function isOneofADT(arg) {
return (arg !== null &&
typeof arg == "object" &&
"case" in arg &&
((typeof arg.case == "string" && "value" in arg && arg.value != null) ||
(arg.case === undefined &&
(!("value" in arg) || arg.value === undefined))));
}
function isReflectList(arg, field) {
var _a, _b, _c, _d;
if (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"add" in arg &&
"field" in arg &&
typeof arg.field == "function") {
if (field !== undefined) {
const a = field;
const b = arg.field();
return (a.listKind == b.listKind &&
a.scalar === b.scalar &&
((_a = a.message) === null || _a === void 0 ? void 0 : _a.typeName) === ((_b = b.message) === null || _b === void 0 ? void 0 : _b.typeName) &&
((_c = a.enum) === null || _c === void 0 ? void 0 : _c.typeName) === ((_d = b.enum) === null || _d === void 0 ? void 0 : _d.typeName));
}
return true;
}
return false;
}
function isReflectMap(arg, field) {
var _a, _b, _c, _d;
if (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"has" in arg &&
"field" in arg &&
typeof arg.field == "function") {
if (field !== undefined) {
const a = field, b = arg.field();
return (a.mapKey === b.mapKey &&
a.mapKind == b.mapKind &&
a.scalar === b.scalar &&
((_a = a.message) === null || _a === void 0 ? void 0 : _a.typeName) === ((_b = b.message) === null || _b === void 0 ? void 0 : _b.typeName) &&
((_c = a.enum) === null || _c === void 0 ? void 0 : _c.typeName) === ((_d = b.enum) === null || _d === void 0 ? void 0 : _d.typeName));
}
return true;
}
return false;
}
function isReflectMessage(arg, messageDesc) {
return (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"desc" in arg &&
isObject(arg.desc) &&
arg.desc.kind === "message" &&
(messageDesc === undefined || arg.desc.typeName == messageDesc.typeName));
}
export * from "./error.js";
export * from "./names.js";
export * from "./nested-types.js";
export * from "./reflect.js";
export * from "./reflect-types.js";
export * from "./scalar.js";
export * from "./path.js";
export { isReflectList, isReflectMap, isReflectMessage } from "./guard.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isReflectMessage = exports.isReflectMap = exports.isReflectList = void 0;
__exportStar(require("./error.js"), exports);
__exportStar(require("./names.js"), exports);
__exportStar(require("./nested-types.js"), exports);
__exportStar(require("./reflect.js"), exports);
__exportStar(require("./reflect-types.js"), exports);
__exportStar(require("./scalar.js"), exports);
__exportStar(require("./path.js"), exports);
var guard_js_1 = require("./guard.js");
Object.defineProperty(exports, "isReflectList", { enumerable: true, get: function () { return guard_js_1.isReflectList; } });
Object.defineProperty(exports, "isReflectMap", { enumerable: true, get: function () { return guard_js_1.isReflectMap; } });
Object.defineProperty(exports, "isReflectMessage", { enumerable: true, get: function () { return guard_js_1.isReflectMessage; } });
import type { AnyDesc } from "../descriptors.js";
/**
* Return a fully-qualified name for a Protobuf descriptor.
* For a file descriptor, return the original file path.
*
* See https://protobuf.com/docs/language-spec#fully-qualified-names
*/
export declare function qualifiedName(desc: AnyDesc): string;
/**
* Converts snake_case to protoCamelCase according to the convention
* used by protoc to convert a field name to a JSON name.
*
* See https://protobuf.com/docs/language-spec#default-json-names
*
* The function protoSnakeCase provides the reverse.
*/
export declare function protoCamelCase(snakeCase: string): string;
/**
* Converts protoCamelCase to snake_case.
*
* This function is the reverse of function protoCamelCase. Note that some names
* are not reversible - for example, "foo__bar" -> "fooBar" -> "foo_bar".
*/
export declare function protoSnakeCase(lowerCamelCase: string): string;
/**
* Escapes names that are reserved for ECMAScript built-in object properties.
*
* Also see safeIdentifier() from @bufbuild/protoplugin.
*/
export declare function safeObjectProperty(name: string): string;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.qualifiedName = qualifiedName;
exports.protoCamelCase = protoCamelCase;
exports.protoSnakeCase = protoSnakeCase;
exports.safeObjectProperty = safeObjectProperty;
/**
* Return a fully-qualified name for a Protobuf descriptor.
* For a file descriptor, return the original file path.
*
* See https://protobuf.com/docs/language-spec#fully-qualified-names
*/
function qualifiedName(desc) {
switch (desc.kind) {
case "field":
case "oneof":
case "rpc":
return desc.parent.typeName + "." + desc.name;
case "enum_value": {
const p = desc.parent.parent
? desc.parent.parent.typeName
: desc.parent.file.proto.package;
return p + (p.length > 0 ? "." : "") + desc.name;
}
case "service":
case "message":
case "enum":
case "extension":
return desc.typeName;
case "file":
return desc.proto.name;
}
}
/**
* Converts snake_case to protoCamelCase according to the convention
* used by protoc to convert a field name to a JSON name.
*
* See https://protobuf.com/docs/language-spec#default-json-names
*
* The function protoSnakeCase provides the reverse.
*/
function protoCamelCase(snakeCase) {
let capNext = false;
const b = [];
for (let i = 0; i < snakeCase.length; i++) {
let c = snakeCase.charAt(i);
switch (c) {
case "_":
capNext = true;
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
b.push(c);
capNext = false;
break;
default:
if (capNext) {
capNext = false;
c = c.toUpperCase();
}
b.push(c);
break;
}
}
return b.join("");
}
/**
* Converts protoCamelCase to snake_case.
*
* This function is the reverse of function protoCamelCase. Note that some names
* are not reversible - for example, "foo__bar" -> "fooBar" -> "foo_bar".
*/
function protoSnakeCase(lowerCamelCase) {
return lowerCamelCase.replace(/[A-Z]/g, (letter) => "_" + letter.toLowerCase());
}
/**
* Names that cannot be used for object properties because they are reserved
* by built-in JavaScript properties.
*/
const reservedObjectProperties = new Set([
// names reserved by JavaScript
"constructor",
"toString",
"toJSON",
"valueOf",
]);
/**
* Escapes names that are reserved for ECMAScript built-in object properties.
*
* Also see safeIdentifier() from @bufbuild/protoplugin.
*/
function safeObjectProperty(name) {
return reservedObjectProperties.has(name) ? name + "$" : name;
}
import type { AnyDesc, DescEnum, DescExtension, DescFile, DescMessage, DescService } from "../descriptors.js";
/**
* Iterate over all types - enumerations, extensions, services, messages -
* and enumerations, extensions and messages nested in messages.
*/
export declare function nestedTypes(desc: DescFile | DescMessage): Iterable<DescMessage | DescEnum | DescExtension | DescService>;
/**
* Iterate over types referenced by fields of the given message.
*
* For example:
*
* ```proto
* syntax="proto3";
*
* message Example {
* Msg singular = 1;
* repeated Level list = 2;
* }
*
* message Msg {}
*
* enum Level {
* LEVEL_UNSPECIFIED = 0;
* }
* ```
*
* The message Example references the message Msg, and the enum Level.
*/
export declare function usedTypes(descMessage: DescMessage): Iterable<DescMessage | DescEnum>;
/**
* Returns the ancestors of a given Protobuf element, up to the file.
*/
export declare function parentTypes(desc: AnyDesc): Parent[];
type Parent = DescFile | DescEnum | DescMessage | DescService;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.nestedTypes = nestedTypes;
exports.usedTypes = usedTypes;
exports.parentTypes = parentTypes;
/**
* Iterate over all types - enumerations, extensions, services, messages -
* and enumerations, extensions and messages nested in messages.
*/
function* nestedTypes(desc) {
switch (desc.kind) {
case "file":
for (const message of desc.messages) {
yield message;
yield* nestedTypes(message);
}
yield* desc.enums;
yield* desc.services;
yield* desc.extensions;
break;
case "message":
for (const message of desc.nestedMessages) {
yield message;
yield* nestedTypes(message);
}
yield* desc.nestedEnums;
yield* desc.nestedExtensions;
break;
}
}
/**
* Iterate over types referenced by fields of the given message.
*
* For example:
*
* ```proto
* syntax="proto3";
*
* message Example {
* Msg singular = 1;
* repeated Level list = 2;
* }
*
* message Msg {}
*
* enum Level {
* LEVEL_UNSPECIFIED = 0;
* }
* ```
*
* The message Example references the message Msg, and the enum Level.
*/
function usedTypes(descMessage) {
return usedTypesInternal(descMessage, new Set());
}
function* usedTypesInternal(descMessage, seen) {
var _a, _b;
for (const field of descMessage.fields) {
const ref = (_b = (_a = field.enum) !== null && _a !== void 0 ? _a : field.message) !== null && _b !== void 0 ? _b : undefined;
if (!ref || seen.has(ref.typeName)) {
continue;
}
seen.add(ref.typeName);
yield ref;
if (ref.kind == "message") {
yield* usedTypesInternal(ref, seen);
}
}
}
/**
* Returns the ancestors of a given Protobuf element, up to the file.
*/
function parentTypes(desc) {
const parents = [];
while (desc.kind !== "file") {
const p = parent(desc);
desc = p;
parents.push(p);
}
return parents;
}
function parent(desc) {
var _a;
switch (desc.kind) {
case "enum_value":
case "field":
case "oneof":
case "rpc":
return desc.parent;
case "service":
return desc.file;
case "extension":
case "enum":
case "message":
return (_a = desc.parent) !== null && _a !== void 0 ? _a : desc.file;
}
}
import { type DescExtension, type DescField, type DescMessage, type DescOneof } from "../descriptors.js";
import type { Registry } from "../registry.js";
/**
* A path to a (nested) member of a Protobuf message, such as a field, oneof,
* extension, list element, or map entry.
*
* Note that we may add additional types to this union in the future to support
* more use cases.
*/
export type Path = (DescField | DescExtension | DescOneof | {
kind: "list_sub";
index: number;
} | {
kind: "map_sub";
key: string | number | bigint | boolean;
})[];
/**
* Builds a Path.
*/
export type PathBuilder = {
/**
* The root message of the path.
*/
readonly schema: DescMessage;
/**
* Add field access.
*
* Throws an InvalidPathError if the field cannot be added to the path.
*/
field(field: DescField): PathBuilder;
/**
* Access a oneof.
*
* Throws an InvalidPathError if the oneof cannot be added to the path.
*
*/
oneof(oneof: DescOneof): PathBuilder;
/**
* Access an extension.
*
* Throws an InvalidPathError if the extension cannot be added to the path.
*/
extension(extension: DescExtension): PathBuilder;
/**
* Access a list field by index.
*
* Throws an InvalidPathError if the list access cannot be added to the path.
*/
list(index: number): PathBuilder;
/**
* Access a map field by key.
*
* Throws an InvalidPathError if the map access cannot be added to the path.
*/
map(key: string | number | bigint | boolean): PathBuilder;
/**
* Append a path.
*
* Throws an InvalidPathError if the path cannot be added.
*/
add(path: Path | PathBuilder): PathBuilder;
/**
* Return the path.
*/
toPath(): Path;
/**
* Create a copy of this builder.
*/
clone(): PathBuilder;
/**
* Get the current container - a list, map, or message.
*/
getLeft(): DescMessage | (DescField & {
fieldKind: "list";
}) | (DescField & {
fieldKind: "map";
}) | undefined;
};
/**
* Create a PathBuilder.
*/
export declare function buildPath(schema: DescMessage): PathBuilder;
/**
* Parse a Path from a string.
*
* Throws an InvalidPathError if the path is invalid.
*
* Note that a Registry must be provided via the options argument to parse
* paths that refer to an extension.
*/
export declare function parsePath(schema: DescMessage, path: string, options?: {
registry?: Registry | undefined;
}): Path;
/**
* Stringify a path.
*/
export declare function pathToString(path: Path): string;
/**
* InvalidPathError is thrown for invalid Paths, for example during parsing from
* a string, or when a new Path is built.
*/
export declare class InvalidPathError extends Error {
name: string;
readonly schema: DescMessage;
readonly path: Path | string;
constructor(schema: DescMessage, message: string, path: string | Path);
}
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidPathError = void 0;
exports.buildPath = buildPath;
exports.parsePath = parsePath;
exports.pathToString = pathToString;
const descriptors_js_1 = require("../descriptors.js");
/**
* Create a PathBuilder.
*/
function buildPath(schema) {
return new PathBuilderImpl(schema, schema, []);
}
/**
* Parse a Path from a string.
*
* Throws an InvalidPathError if the path is invalid.
*
* Note that a Registry must be provided via the options argument to parse
* paths that refer to an extension.
*/
function parsePath(schema, path, options) {
var _a, _b;
const builder = new PathBuilderImpl(schema, schema, []);
const err = (message, i) => new InvalidPathError(schema, message + " at column " + (i + 1), path);
for (let i = 0; i < path.length;) {
const token = nextToken(i, path);
const left = builder.getLeft();
let right = undefined;
if ("field" in token) {
right =
(left === null || left === void 0 ? void 0 : left.kind) != "message"
? undefined
: ((_a = left.fields.find((field) => field.name === token.field)) !== null && _a !== void 0 ? _a : left.oneofs.find((oneof) => oneof.name === token.field));
if (!right) {
throw err(`Unknown field "${token.field}"`, i);
}
}
else if ("ext" in token) {
right = (_b = options === null || options === void 0 ? void 0 : options.registry) === null || _b === void 0 ? void 0 : _b.getExtension(token.ext);
if (!right) {
throw err(`Unknown extension "${token.ext}"`, i);
}
}
else if ("val" in token) {
// list or map
right =
(left === null || left === void 0 ? void 0 : left.kind) == "field" &&
left.fieldKind == "list" &&
typeof token.val == "bigint"
? { kind: "list_sub", index: Number(token.val) }
: { kind: "map_sub", key: token.val };
}
else if ("err" in token) {
throw err(token.err, token.i);
}
if (right) {
try {
builder.add([right]);
}
catch (e) {
throw err(e instanceof InvalidPathError ? e.message : String(e), i);
}
}
i = token.i;
}
return builder.toPath();
}
/**
* Stringify a path.
*/
function pathToString(path) {
const str = [];
for (const ele of path) {
switch (ele.kind) {
case "field":
case "oneof":
if (str.length > 0) {
str.push(".");
}
str.push(ele.name);
break;
case "extension":
str.push("[", ele.typeName, "]");
break;
case "list_sub":
str.push("[", ele.index, "]");
break;
case "map_sub":
if (typeof ele.key == "string") {
str.push('["', ele.key
.split("\\")
.join("\\\\")
.split('"')
.join('\\"')
.split("\r")
.join("\\r")
.split("\n")
.join("\\n"), '"]');
}
else {
str.push("[", ele.key, "]");
}
break;
}
}
return str.join("");
}
/**
* InvalidPathError is thrown for invalid Paths, for example during parsing from
* a string, or when a new Path is built.
*/
class InvalidPathError extends Error {
constructor(schema, message, path) {
super(message);
this.name = "InvalidPathError";
this.schema = schema;
this.path = path;
// see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example
Object.setPrototypeOf(this, new.target.prototype);
}
}
exports.InvalidPathError = InvalidPathError;
class PathBuilderImpl {
constructor(schema, left, path) {
this.schema = schema;
this.left = left;
this.path = path;
}
getLeft() {
return this.left;
}
field(field) {
return this.push(field);
}
oneof(oneof) {
return this.push(oneof);
}
extension(extension) {
return this.push(extension);
}
list(index) {
return this.push({ kind: "list_sub", index });
}
map(key) {
return this.push({ kind: "map_sub", key });
}
add(pathOrBuilder) {
const path = Array.isArray(pathOrBuilder)
? pathOrBuilder
: pathOrBuilder.toPath();
const l = this.path.length;
try {
for (const ele of path) {
this.push(ele);
}
}
catch (e) {
// undo pushes
this.path.splice(l);
throw e;
}
return this;
}
toPath() {
return this.path.concat();
}
clone() {
return new PathBuilderImpl(this.schema, this.left, this.path.concat());
}
push(ele) {
switch (ele.kind) {
case "field":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.parent.typeName) {
throw this.err("field access");
}
this.path.push(ele);
this.left =
ele.fieldKind == "message"
? ele.message
: ele.fieldKind == "list" || ele.fieldKind == "map"
? ele
: undefined;
return this;
case "oneof":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.parent.typeName) {
throw this.err("oneof access");
}
this.path.push(ele);
this.left = undefined;
return this;
case "extension":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.extendee.typeName) {
throw this.err("extension access");
}
this.path.push(ele);
this.left = ele.fieldKind == "message" ? ele.message : undefined;
return this;
case "list_sub":
if (!this.left ||
this.left.kind != "field" ||
this.left.fieldKind != "list") {
throw this.err("list access");
}
if (ele.index < 0 || !Number.isInteger(ele.index)) {
throw this.err("list index");
}
this.path.push(ele);
this.left =
this.left.listKind == "message" ? this.left.message : undefined;
return this;
case "map_sub":
if (!this.left ||
this.left.kind != "field" ||
this.left.fieldKind != "map") {
throw this.err("map access");
}
if (!checkKeyType(ele.key, this.left.mapKey)) {
throw this.err("map key");
}
this.path.push(ele);
this.left =
this.left.mapKind == "message" ? this.left.message : undefined;
return this;
}
}
err(what) {
return new InvalidPathError(this.schema, "Invalid " + what, this.path);
}
}
function checkKeyType(key, type) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return typeof key == "string";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.FIXED32:
return typeof key == "number";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
return typeof key == "bigint";
case descriptors_js_1.ScalarType.BOOL:
return typeof key == "boolean";
}
}
function nextToken(i, path) {
const re_extension = /^[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*$/;
const re_field = /^[A-Za-z_][A-Za-z_0-9]*$/;
if (path[i] == "[") {
i++;
while (path[i] == " ") {
// skip leading whitespace
i++;
}
if (i >= path.length) {
return { err: "Premature end", i: path.length - 1 };
}
let token;
if (path[i] == `"`) {
// string literal
i++;
let val = "";
for (;;) {
if (path[i] == `"`) {
// end of string literal
i++;
break;
}
if (path[i] == "\\") {
switch (path[i + 1]) {
case `"`:
case "\\":
val += path[i + 1];
break;
case "r":
val += "\r";
break;
case "n":
val += "\n";
break;
default:
return { err: "Invalid escape sequence", i };
}
i++;
}
else {
val += path[i];
}
if (i >= path.length) {
return { err: "Premature end of string", i: path.length - 1 };
}
i++;
}
token = { val };
}
else if (path[i].match(/\d/)) {
// integer literal
const start = i;
while (i < path.length && /\d/.test(path[i])) {
i++;
}
token = { val: BigInt(path.substring(start, i)) };
}
else if (path[i] == "]") {
return { err: "Premature ]", i };
}
else {
// extension identifier or bool literal
const start = i;
while (i < path.length && path[i] != " " && path[i] != "]") {
i++;
}
const name = path.substring(start, i);
if (name === "true") {
token = { val: true };
}
else if (name === "false") {
token = { val: false };
}
else if (re_extension.test(name)) {
token = { ext: name };
}
else {
return { err: "Invalid ident", i: start };
}
}
while (path[i] == " ") {
// skip trailing whitespace
i++;
}
if (path[i] != "]") {
return { err: "Missing ]", i };
}
i++;
return Object.assign(Object.assign({}, token), { i });
}
// field identifier
if (i > 0) {
if (path[i] != ".") {
return { err: `Expected "."`, i };
}
i++;
}
const start = i;
while (i < path.length && path[i] != "." && path[i] != "[") {
i++;
}
const field = path.substring(start, i);
return re_field.test(field)
? { field, i }
: { err: "Invalid ident", i: start };
}
import { type DescField } from "../descriptors.js";
import { FieldError } from "./error.js";
/**
* Check whether the given field value is valid for the reflect API.
*/
export declare function checkField(field: DescField, value: unknown): FieldError | undefined;
/**
* Check whether the given list item is valid for the reflect API.
*/
export declare function checkListItem(field: DescField & {
fieldKind: "list";
}, index: number, value: unknown): FieldError | undefined;
/**
* Check whether the given map key and value are valid for the reflect API.
*/
export declare function checkMapEntry(field: DescField & {
fieldKind: "map";
}, key: unknown, value: unknown): FieldError | undefined;
export declare function formatVal(val: unknown): string;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkField = checkField;
exports.checkListItem = checkListItem;
exports.checkMapEntry = checkMapEntry;
exports.formatVal = formatVal;
const descriptors_js_1 = require("../descriptors.js");
const is_message_js_1 = require("../is-message.js");
const error_js_1 = require("./error.js");
const guard_js_1 = require("./guard.js");
const binary_encoding_js_1 = require("../wire/binary-encoding.js");
const text_encoding_js_1 = require("../wire/text-encoding.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Check whether the given field value is valid for the reflect API.
*/
function checkField(field, value) {
const check = field.fieldKind == "list"
? (0, guard_js_1.isReflectList)(value, field)
: field.fieldKind == "map"
? (0, guard_js_1.isReflectMap)(value, field)
: checkSingular(field, value);
if (check === true) {
return undefined;
}
let reason;
switch (field.fieldKind) {
case "list":
reason = `expected ${formatReflectList(field)}, got ${formatVal(value)}`;
break;
case "map":
reason = `expected ${formatReflectMap(field)}, got ${formatVal(value)}`;
break;
default: {
reason = reasonSingular(field, value, check);
}
}
return new error_js_1.FieldError(field, reason);
}
/**
* Check whether the given list item is valid for the reflect API.
*/
function checkListItem(field, index, value) {
const check = checkSingular(field, value);
if (check !== true) {
return new error_js_1.FieldError(field, `list item #${index + 1}: ${reasonSingular(field, value, check)}`);
}
return undefined;
}
/**
* Check whether the given map key and value are valid for the reflect API.
*/
function checkMapEntry(field, key, value) {
const checkKey = checkScalarValue(key, field.mapKey);
if (checkKey !== true) {
return new error_js_1.FieldError(field, `invalid map key: ${reasonSingular({ scalar: field.mapKey }, key, checkKey)}`);
}
const checkVal = checkSingular(field, value);
if (checkVal !== true) {
return new error_js_1.FieldError(field, `map entry ${formatVal(key)}: ${reasonSingular(field, value, checkVal)}`);
}
return undefined;
}
function checkSingular(field, value) {
if (field.scalar !== undefined) {
return checkScalarValue(value, field.scalar);
}
if (field.enum !== undefined) {
if (field.enum.open) {
// Open enums accept unrecognized values, but enum values are always
// int32 (see https://protobuf.dev/programming-guides/proto3/#enum).
return checkScalarValue(value, descriptors_js_1.ScalarType.INT32);
}
return field.enum.values.some((v) => v.number === value);
}
return (0, guard_js_1.isReflectMessage)(value, field.message);
}
function checkScalarValue(value, scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.DOUBLE:
return typeof value == "number";
case descriptors_js_1.ScalarType.FLOAT:
if (typeof value != "number") {
return false;
}
if (Number.isNaN(value) || !Number.isFinite(value)) {
return true;
}
if (value > binary_encoding_js_1.FLOAT32_MAX || value < binary_encoding_js_1.FLOAT32_MIN) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
// signed
if (typeof value !== "number" || !Number.isInteger(value)) {
return false;
}
if (value > binary_encoding_js_1.INT32_MAX || value < binary_encoding_js_1.INT32_MIN) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
// unsigned
if (typeof value !== "number" || !Number.isInteger(value)) {
return false;
}
if (value > binary_encoding_js_1.UINT32_MAX || value < 0) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.BOOL:
return typeof value == "boolean";
case descriptors_js_1.ScalarType.STRING:
if (typeof value != "string") {
return false;
}
return (0, text_encoding_js_1.getTextEncoding)().checkUtf8(value) || "invalid UTF8";
case descriptors_js_1.ScalarType.BYTES:
return value instanceof Uint8Array;
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
// signed
if (typeof value == "bigint" ||
typeof value == "number" ||
(typeof value == "string" && value.length > 0)) {
try {
proto_int64_js_1.protoInt64.parse(value);
return true;
}
catch (_) {
return `${value} out of range`;
}
}
return false;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
// unsigned
if (typeof value == "bigint" ||
typeof value == "number" ||
(typeof value == "string" && value.length > 0)) {
try {
proto_int64_js_1.protoInt64.uParse(value);
return true;
}
catch (_) {
return `${value} out of range`;
}
}
return false;
}
}
function reasonSingular(field, val, details) {
details =
typeof details == "string" ? `: ${details}` : `, got ${formatVal(val)}`;
if (field.scalar !== undefined) {
return `expected ${scalarTypeDescription(field.scalar)}` + details;
}
if (field.enum !== undefined) {
return `expected ${field.enum.toString()}` + details;
}
return `expected ${formatReflectMessage(field.message)}` + details;
}
function formatVal(val) {
switch (typeof val) {
case "object":
if (val === null) {
return "null";
}
if (val instanceof Uint8Array) {
return `Uint8Array(${val.length})`;
}
if (Array.isArray(val)) {
return `Array(${val.length})`;
}
if ((0, guard_js_1.isReflectList)(val)) {
return formatReflectList(val.field());
}
if ((0, guard_js_1.isReflectMap)(val)) {
return formatReflectMap(val.field());
}
if ((0, guard_js_1.isReflectMessage)(val)) {
return formatReflectMessage(val.desc);
}
if ((0, is_message_js_1.isMessage)(val)) {
return `message ${val.$typeName}`;
}
return "object";
case "string":
return val.length > 30 ? "string" : `"${val.split('"').join('\\"')}"`;
case "boolean":
return String(val);
case "number":
return String(val);
case "bigint":
return String(val) + "n";
default:
// "symbol" | "undefined" | "object" | "function"
return typeof val;
}
}
function formatReflectMessage(desc) {
return `ReflectMessage (${desc.typeName})`;
}
function formatReflectList(field) {
switch (field.listKind) {
case "message":
return `ReflectList (${field.message.toString()})`;
case "enum":
return `ReflectList (${field.enum.toString()})`;
case "scalar":
return `ReflectList (${descriptors_js_1.ScalarType[field.scalar]})`;
}
}
function formatReflectMap(field) {
switch (field.mapKind) {
case "message":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${field.message.toString()})`;
case "enum":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${field.enum.toString()})`;
case "scalar":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${descriptors_js_1.ScalarType[field.scalar]})`;
}
}
function scalarTypeDescription(scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.SFIXED64:
return "bigint (int64)";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
return "bigint (uint64)";
case descriptors_js_1.ScalarType.BYTES:
return "Uint8Array";
case descriptors_js_1.ScalarType.DOUBLE:
return "number (float64)";
case descriptors_js_1.ScalarType.FLOAT:
return "number (float32)";
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
return "number (uint32)";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
return "number (int32)";
}
}
import type { DescField, DescMessage, DescOneof } from "../descriptors.js";
import { unsafeLocal } from "./unsafe.js";
import type { Message, UnknownField } from "../types.js";
import type { ScalarValue } from "./scalar.js";
/**
* ReflectMessage provides dynamic access and manipulation of a message.
*/
export interface ReflectMessage {
/**
* The underlying message instance.
*/
readonly message: Message;
/**
* The descriptor for the message.
*/
readonly desc: DescMessage;
/**
* The fields of the message. This is a shortcut to message.fields.
*/
readonly fields: readonly DescField[];
/**
* The fields of the message, sorted by field number ascending.
*/
readonly sortedFields: readonly DescField[];
/**
* Oneof groups of the message. This is a shortcut to message.oneofs.
*/
readonly oneofs: readonly DescOneof[];
/**
* Fields and oneof groups for this message. This is a shortcut to message.members.
*/
readonly members: readonly (DescField | DescOneof)[];
/**
* Find a field by number.
*/
findNumber(number: number): DescField | undefined;
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
isSet(field: DescField): boolean;
/**
* Resets the field, so that isSet() will return false.
*/
clear(field: DescField): void;
/**
* Return the selected field of a oneof group.
*/
oneofCase(oneof: DescOneof): DescField | undefined;
/**
* Returns the field value. Values are converted or wrapped to make it easier
* to manipulate messages.
*
* - Scalar fields:
* Returns the value, but converts 64-bit integer fields with the option
* `jstype=JS_STRING` to a bigint value.
* If the field is not set, the default value is returned. If no default
* value is set, the zero value is returned.
*
* - Enum fields:
* Returns the numeric value. If the field is not set, the default value is
* returned. If no default value is set, the zero value is returned.
*
* - Message fields:
* Returns a ReflectMessage. If the field is not set, a new message is
* returned, but not set on the field.
*
* - List fields:
* Returns a ReflectList object.
*
* - Map fields:
* Returns a ReflectMap object.
*
* Note that get() never returns `undefined`. To determine whether a field is
* set, use isSet().
*/
get<Field extends DescField>(field: Field): ReflectMessageGet<Field>;
/**
* Set a field value.
*
* Expects values in the same form that get() returns:
*
* - Scalar fields:
* 64-bit integer fields with the option `jstype=JS_STRING` as a bigint value.
*
* - Message fields:
* ReflectMessage.
*
* - List fields:
* ReflectList.
*
* - Map fields:
* ReflectMap.
*
* Throws an error if the value is invalid for the field. `undefined` is not
* a valid value. To reset a field, use clear().
*/
set<Field extends DescField>(field: Field, value: unknown): void;
/**
* Returns the unknown fields of the message.
*/
getUnknown(): UnknownField[] | undefined;
/**
* Sets the unknown fields of the message, overwriting any previous values.
*/
setUnknown(value: UnknownField[]): void;
[unsafeLocal]: Message;
}
/**
* ReflectList provides dynamic access and manipulation of a list field on a
* message.
*
* ReflectList is iterable - you can loop through all items with a for...of loop.
*
* Values are converted or wrapped to make it easier to manipulate them:
* - Scalar 64-bit integer fields with the option `jstype=JS_STRING` are
* converted to bigint.
* - Messages are wrapped in a ReflectMessage.
*/
export interface ReflectList<V = unknown> extends Iterable<V> {
/**
* Returns the list field.
*/
field(): DescField & {
fieldKind: "list";
};
/**
* The size of the list.
*/
readonly size: number;
/**
* Retrieves the item at the specified index, or undefined if the index
* is out of range.
*/
get(index: number): V | undefined;
/**
* Adds an item at the end of the list.
* Throws an error if an item is invalid for this list.
*/
add(item: V): void;
/**
* Replaces the item at the specified index with the specified item.
* Throws an error if the index is out of range (index < 0 || index >= size).
* Throws an error if the item is invalid for this list.
*/
set(index: number, item: V): void;
/**
* Removes all items from the list.
*/
clear(): void;
[Symbol.iterator](): IterableIterator<V>;
entries(): IterableIterator<[number, V]>;
keys(): IterableIterator<number>;
values(): IterableIterator<V>;
[unsafeLocal]: unknown[];
}
/**
* ReflectMap provides dynamic access and manipulation of a map field on a
* message.
*
* ReflectMap is iterable - you can loop through all entries with a for...of loop.
*
* Keys and values are converted or wrapped to make it easier to manipulate them:
* - A map field is a record object on a message, where keys are always strings.
* ReflectMap converts keys to their closest possible type in TypeScript.
* - Messages are wrapped in a ReflectMessage.
*/
export interface ReflectMap<K = unknown, V = unknown> extends ReadonlyMap<K, V> {
/**
* Returns the map field.
*/
field(): DescField & {
fieldKind: "map";
};
/**
* Removes the entry for the specified key.
* Returns false if the key is unknown.
*/
delete(key: K): boolean;
/**
* Sets or replaces the item at the specified key with the specified value.
* Throws an error if the key or value is invalid for this map.
*/
set(key: K, value: V): this;
/**
* Removes all entries from the map.
*/
clear(): void;
[unsafeLocal]: Record<string, unknown>;
}
/**
* The return type of ReflectMessage.get()
*/
export type ReflectMessageGet<Field extends DescField = DescField> = (Field extends {
fieldKind: "map";
} ? ReflectMap : Field extends {
fieldKind: "list";
} ? ReflectList : Field extends {
fieldKind: "enum";
} ? number : Field extends {
fieldKind: "message";
} ? ReflectMessage : Field extends {
fieldKind: "scalar";
scalar: infer T;
} ? ScalarValue<T> : never);
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
const unsafe_js_1 = require("./unsafe.js");
import { type DescField, type DescMessage } from "../descriptors.js";
import type { MessageShape } from "../types.js";
import type { ReflectList, ReflectMap, ReflectMessage } from "./reflect-types.js";
/**
* Create a ReflectMessage.
*/
export declare function reflect<Desc extends DescMessage>(messageDesc: Desc, message?: MessageShape<Desc>,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectMessage;
/**
* Create a ReflectList.
*/
export declare function reflectList<V>(field: DescField & {
fieldKind: "list";
}, unsafeInput?: unknown[],
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectList<V>;
/**
* Create a ReflectMap.
*/
export declare function reflectMap<K = unknown, V = unknown>(field: DescField & {
fieldKind: "map";
}, unsafeInput?: Record<string, unknown>,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectMap<K, V>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.reflect = reflect;
exports.reflectList = reflectList;
exports.reflectMap = reflectMap;
const descriptors_js_1 = require("../descriptors.js");
const reflect_check_js_1 = require("./reflect-check.js");
const error_js_1 = require("./error.js");
const unsafe_js_1 = require("./unsafe.js");
const create_js_1 = require("../create.js");
const wrappers_js_1 = require("../wkt/wrappers.js");
const scalar_js_1 = require("./scalar.js");
const proto_int64_js_1 = require("../proto-int64.js");
const guard_js_1 = require("./guard.js");
/**
* Create a ReflectMessage.
*/
function reflect(messageDesc, message,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectMessageImpl(messageDesc, message, check);
}
const messageSortedFields = new WeakMap();
class ReflectMessageImpl {
get sortedFields() {
const cached = messageSortedFields.get(this.desc);
if (cached) {
return cached;
}
const sortedFields = this.desc.fields
.concat()
.sort((a, b) => a.number - b.number);
messageSortedFields.set(this.desc, sortedFields);
return sortedFields;
}
constructor(messageDesc, message, check = true) {
this.lists = new Map();
this.maps = new Map();
this.check = check;
this.desc = messageDesc;
this.message = this[unsafe_js_1.unsafeLocal] = message !== null && message !== void 0 ? message : (0, create_js_1.create)(messageDesc);
this.fields = messageDesc.fields;
this.oneofs = messageDesc.oneofs;
this.members = messageDesc.members;
}
findNumber(number) {
if (!this._fieldsByNumber) {
this._fieldsByNumber = new Map(this.desc.fields.map((f) => [f.number, f]));
}
return this._fieldsByNumber.get(number);
}
oneofCase(oneof) {
assertOwn(this.message, oneof);
return (0, unsafe_js_1.unsafeOneofCase)(this.message, oneof);
}
isSet(field) {
assertOwn(this.message, field);
return (0, unsafe_js_1.unsafeIsSet)(this.message, field);
}
clear(field) {
assertOwn(this.message, field);
(0, unsafe_js_1.unsafeClear)(this.message, field);
}
get(field) {
assertOwn(this.message, field);
const value = (0, unsafe_js_1.unsafeGet)(this.message, field);
switch (field.fieldKind) {
case "list":
// eslint-disable-next-line no-case-declarations
let list = this.lists.get(field);
if (!list || list[unsafe_js_1.unsafeLocal] !== value) {
this.lists.set(field,
// biome-ignore lint/suspicious/noAssignInExpressions: no
(list = new ReflectListImpl(field, value, this.check)));
}
return list;
case "map":
let map = this.maps.get(field);
if (!map || map[unsafe_js_1.unsafeLocal] !== value) {
this.maps.set(field,
// biome-ignore lint/suspicious/noAssignInExpressions: no
(map = new ReflectMapImpl(field, value, this.check)));
}
return map;
case "message":
return messageToReflect(field, value, this.check);
case "scalar":
return (value === undefined
? (0, scalar_js_1.scalarZeroValue)(field.scalar, false)
: longToReflect(field, value));
case "enum":
return (value !== null && value !== void 0 ? value : field.enum.values[0].number);
}
}
set(field, value) {
assertOwn(this.message, field);
if (this.check) {
const err = (0, reflect_check_js_1.checkField)(field, value);
if (err) {
throw err;
}
}
let local;
if (field.fieldKind == "message") {
local = messageToLocal(field, value);
}
else if ((0, guard_js_1.isReflectMap)(value) || (0, guard_js_1.isReflectList)(value)) {
local = value[unsafe_js_1.unsafeLocal];
}
else {
local = longToLocal(field, value);
}
(0, unsafe_js_1.unsafeSet)(this.message, field, local);
}
getUnknown() {
return this.message.$unknown;
}
setUnknown(value) {
this.message.$unknown = value;
}
}
function assertOwn(owner, member) {
if (member.parent.typeName !== owner.$typeName) {
throw new error_js_1.FieldError(member, `cannot use ${member.toString()} with message ${owner.$typeName}`, "ForeignFieldError");
}
}
/**
* Create a ReflectList.
*/
function reflectList(field, unsafeInput,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectListImpl(field, unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : [], check);
}
class ReflectListImpl {
field() {
return this._field;
}
get size() {
return this._arr.length;
}
constructor(field, unsafeInput, check) {
this._field = field;
this._arr = this[unsafe_js_1.unsafeLocal] = unsafeInput;
this.check = check;
}
get(index) {
const item = this._arr[index];
return item === undefined
? undefined
: listItemToReflect(this._field, item, this.check);
}
set(index, item) {
if (index < 0 || index >= this._arr.length) {
throw new error_js_1.FieldError(this._field, `list item #${index + 1}: out of range`);
}
if (this.check) {
const err = (0, reflect_check_js_1.checkListItem)(this._field, index, item);
if (err) {
throw err;
}
}
this._arr[index] = listItemToLocal(this._field, item);
}
add(item) {
if (this.check) {
const err = (0, reflect_check_js_1.checkListItem)(this._field, this._arr.length, item);
if (err) {
throw err;
}
}
this._arr.push(listItemToLocal(this._field, item));
return undefined;
}
clear() {
this._arr.splice(0, this._arr.length);
}
[Symbol.iterator]() {
return this.values();
}
keys() {
return this._arr.keys();
}
*values() {
for (const item of this._arr) {
yield listItemToReflect(this._field, item, this.check);
}
}
*entries() {
for (let i = 0; i < this._arr.length; i++) {
yield [i, listItemToReflect(this._field, this._arr[i], this.check)];
}
}
}
/**
* Create a ReflectMap.
*/
function reflectMap(field, unsafeInput,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectMapImpl(field, unsafeInput, check);
}
class ReflectMapImpl {
constructor(field, unsafeInput, check = true) {
this.obj = this[unsafe_js_1.unsafeLocal] = unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : {};
this.check = check;
this._field = field;
}
field() {
return this._field;
}
set(key, value) {
if (this.check) {
const err = (0, reflect_check_js_1.checkMapEntry)(this._field, key, value);
if (err) {
throw err;
}
}
this.obj[mapKeyToLocal(key)] = mapValueToLocal(this._field, value);
return this;
}
delete(key) {
const k = mapKeyToLocal(key);
const has = Object.prototype.hasOwnProperty.call(this.obj, k);
if (has) {
delete this.obj[k];
}
return has;
}
clear() {
for (const key of Object.keys(this.obj)) {
delete this.obj[key];
}
}
get(key) {
let val = this.obj[mapKeyToLocal(key)];
if (val !== undefined) {
val = mapValueToReflect(this._field, val, this.check);
}
return val;
}
has(key) {
return Object.prototype.hasOwnProperty.call(this.obj, mapKeyToLocal(key));
}
*keys() {
for (const objKey of Object.keys(this.obj)) {
yield mapKeyToReflect(objKey, this._field.mapKey);
}
}
*entries() {
for (const objEntry of Object.entries(this.obj)) {
yield [
mapKeyToReflect(objEntry[0], this._field.mapKey),
mapValueToReflect(this._field, objEntry[1], this.check),
];
}
}
[Symbol.iterator]() {
return this.entries();
}
get size() {
return Object.keys(this.obj).length;
}
*values() {
for (const val of Object.values(this.obj)) {
yield mapValueToReflect(this._field, val, this.check);
}
}
forEach(callbackfn, thisArg) {
for (const mapEntry of this.entries()) {
callbackfn.call(thisArg, mapEntry[1], mapEntry[0], this);
}
}
}
function messageToLocal(field, value) {
if (!(0, guard_js_1.isReflectMessage)(value)) {
return value;
}
if ((0, wrappers_js_1.isWrapper)(value.message) &&
!field.oneof &&
field.fieldKind == "message") {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
return value.message.value;
}
if (value.desc.typeName == "google.protobuf.Struct" &&
field.parent.typeName != "google.protobuf.Value") {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
return wktStructToLocal(value.message);
}
return value.message;
}
function messageToReflect(field, value, check) {
if (value !== undefined) {
if ((0, wrappers_js_1.isWrapperDesc)(field.message) &&
!field.oneof &&
field.fieldKind == "message") {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
value = {
$typeName: field.message.typeName,
value: longToReflect(field.message.fields[0], value),
};
}
else if (field.message.typeName == "google.protobuf.Struct" &&
field.parent.typeName != "google.protobuf.Value" &&
(0, guard_js_1.isObject)(value)) {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
value = wktStructToReflect(value);
}
}
return new ReflectMessageImpl(field.message, value, check);
}
function listItemToLocal(field, value) {
if (field.listKind == "message") {
return messageToLocal(field, value);
}
return longToLocal(field, value);
}
function listItemToReflect(field, value, check) {
if (field.listKind == "message") {
return messageToReflect(field, value, check);
}
return longToReflect(field, value);
}
function mapValueToLocal(field, value) {
if (field.mapKind == "message") {
return messageToLocal(field, value);
}
return longToLocal(field, value);
}
function mapValueToReflect(field, value, check) {
if (field.mapKind == "message") {
return messageToReflect(field, value, check);
}
return value;
}
function mapKeyToLocal(key) {
return typeof key == "string" || typeof key == "number" ? key : String(key);
}
/**
* Converts a map key (any scalar value except float, double, or bytes) from its
* representation in a message (string or number, the only possible object key
* types) to the closest possible type in ECMAScript.
*/
function mapKeyToReflect(key, type) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return key;
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32: {
const n = Number.parseInt(key);
if (Number.isFinite(n)) {
return n;
}
break;
}
case descriptors_js_1.ScalarType.BOOL:
switch (key) {
case "true":
return true;
case "false":
return false;
}
break;
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
try {
return proto_int64_js_1.protoInt64.uParse(key);
}
catch (_a) {
//
}
break;
default:
// INT64, SFIXED64, SINT64
try {
return proto_int64_js_1.protoInt64.parse(key);
}
catch (_b) {
//
}
break;
}
return key;
}
function longToReflect(field, value) {
switch (field.scalar) {
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
if ("longAsString" in field &&
field.longAsString &&
typeof value == "string") {
value = proto_int64_js_1.protoInt64.parse(value);
}
break;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
if ("longAsString" in field &&
field.longAsString &&
typeof value == "string") {
value = proto_int64_js_1.protoInt64.uParse(value);
}
break;
}
return value;
}
function longToLocal(field, value) {
switch (field.scalar) {
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
if ("longAsString" in field && field.longAsString) {
value = String(value);
}
else if (typeof value == "string" || typeof value == "number") {
value = proto_int64_js_1.protoInt64.parse(value);
}
break;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
if ("longAsString" in field && field.longAsString) {
value = String(value);
}
else if (typeof value == "string" || typeof value == "number") {
value = proto_int64_js_1.protoInt64.uParse(value);
}
break;
}
return value;
}
function wktStructToReflect(json) {
const struct = {
$typeName: "google.protobuf.Struct",
fields: {},
};
if ((0, guard_js_1.isObject)(json)) {
for (const [k, v] of Object.entries(json)) {
struct.fields[k] = wktValueToReflect(v);
}
}
return struct;
}
function wktStructToLocal(val) {
const json = {};
for (const [k, v] of Object.entries(val.fields)) {
json[k] = wktValueToLocal(v);
}
return json;
}
function wktValueToLocal(val) {
switch (val.kind.case) {
case "structValue":
return wktStructToLocal(val.kind.value);
case "listValue":
return val.kind.value.values.map(wktValueToLocal);
case "nullValue":
case undefined:
return null;
default:
return val.kind.value;
}
}
function wktValueToReflect(json) {
const value = {
$typeName: "google.protobuf.Value",
kind: { case: undefined },
};
switch (typeof json) {
case "number":
value.kind = { case: "numberValue", value: json };
break;
case "string":
value.kind = { case: "stringValue", value: json };
break;
case "boolean":
value.kind = { case: "boolValue", value: json };
break;
case "object":
if (json === null) {
const nullValue = 0;
value.kind = { case: "nullValue", value: nullValue };
}
else if (Array.isArray(json)) {
const listValue = {
$typeName: "google.protobuf.ListValue",
values: [],
};
if (Array.isArray(json)) {
for (const e of json) {
listValue.values.push(wktValueToReflect(e));
}
}
value.kind = {
case: "listValue",
value: listValue,
};
}
else {
value.kind = {
case: "structValue",
value: wktStructToReflect(json),
};
}
break;
}
return value;
}
import { ScalarType } from "../descriptors.js";
/**
* ScalarValue maps from a scalar field type to a TypeScript value type.
*/
export type ScalarValue<T = ScalarType, LongAsString extends boolean = false> = T extends ScalarType.STRING ? string : T extends ScalarType.INT32 ? number : T extends ScalarType.UINT32 ? number : T extends ScalarType.SINT32 ? number : T extends ScalarType.FIXED32 ? number : T extends ScalarType.SFIXED32 ? number : T extends ScalarType.FLOAT ? number : T extends ScalarType.DOUBLE ? number : T extends ScalarType.INT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.SINT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.SFIXED64 ? LongAsString extends true ? string : bigint : T extends ScalarType.UINT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.FIXED64 ? LongAsString extends true ? string : bigint : T extends ScalarType.BOOL ? boolean : T extends ScalarType.BYTES ? Uint8Array : never;
/**
* Returns true if both scalar values are equal.
*
* For float and double, values are compared following IEEE semantics: -0
* equals 0, and NaN does not equal NaN. This is value equality, not identity.
*
* It deliberately differs from isScalarZeroValue, which treats -0 as distinct
* from 0. A value can equal the zero value without being a zero value
* (scalarEquals(DOUBLE, -0, 0) is true while isScalarZeroValue(DOUBLE, -0) is
* false) so this function must not be used to derive implicit presence.
*/
export declare function scalarEquals(type: ScalarType, a: ScalarValue | undefined, b: ScalarValue | undefined): boolean;
/**
* Returns the zero value for the given scalar type, the value a field of this
* type has when unset: 0 for numeric types, "" for strings, false for
* booleans, and an empty Uint8Array for bytes. For 64-bit integer types, the
* result is "0" when longAsString is true, otherwise 0n.
*
* This is the type's zero value, not a proto2 custom field default. For float
* and double it is +0; isScalarZeroValue treats only +0, not -0, as this value.
*/
export declare function scalarZeroValue<T extends ScalarType, LongAsString extends boolean>(type: T, longAsString: LongAsString): ScalarValue<T, LongAsString>;
/**
* Returns true if the value is the zero value for the given scalar type: `0`
* for numeric types, `false` for booleans, `""` for strings, and an empty
* Uint8Array for bytes.
*
* This is the implicit-presence default check. A singular field with implicit
* presence is treated as unset, and omitted from the wire, when its value is
* the zero value. With explicit presence, or in repeated and map fields,
* presence is structural and this function does not apply.
*
* Note that -0 is NOT a zero value for float and double: under implicit
* presence, +0 is omitted from the wire but -0 is written, following the
* proto3 specification. As a result this can disagree with scalarEquals, which
* compares by value and treats -0 as equal to 0.
*/
export declare function isScalarZeroValue(type: ScalarType, value: unknown): boolean;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.scalarEquals = scalarEquals;
exports.scalarZeroValue = scalarZeroValue;
exports.isScalarZeroValue = isScalarZeroValue;
const proto_int64_js_1 = require("../proto-int64.js");
const descriptors_js_1 = require("../descriptors.js");
/**
* Returns true if both scalar values are equal.
*
* For float and double, values are compared following IEEE semantics: -0
* equals 0, and NaN does not equal NaN. This is value equality, not identity.
*
* It deliberately differs from isScalarZeroValue, which treats -0 as distinct
* from 0. A value can equal the zero value without being a zero value
* (scalarEquals(DOUBLE, -0, 0) is true while isScalarZeroValue(DOUBLE, -0) is
* false) so this function must not be used to derive implicit presence.
*/
function scalarEquals(type, a, b) {
if (a === b) {
// This correctly matches equal values except BYTES and (possibly) 64-bit integers.
return true;
}
// Special case BYTES - we need to compare each byte individually
if (type == descriptors_js_1.ScalarType.BYTES) {
if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array)) {
return false;
}
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
// Special case 64-bit integers - we support number, string and bigint representation.
switch (type) {
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
// Loose comparison will match between 0n, 0 and "0".
return a == b;
}
// Anything that hasn't been caught by strict comparison or special cased
// BYTES and 64-bit integers is not equal.
return false;
}
/**
* Returns the zero value for the given scalar type, the value a field of this
* type has when unset: 0 for numeric types, "" for strings, false for
* booleans, and an empty Uint8Array for bytes. For 64-bit integer types, the
* result is "0" when longAsString is true, otherwise 0n.
*
* This is the type's zero value, not a proto2 custom field default. For float
* and double it is +0; isScalarZeroValue treats only +0, not -0, as this value.
*/
function scalarZeroValue(type, longAsString) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return "";
case descriptors_js_1.ScalarType.BOOL:
return false;
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
return 0.0;
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
return (longAsString ? "0" : proto_int64_js_1.protoInt64.zero);
case descriptors_js_1.ScalarType.BYTES:
return new Uint8Array(0);
default:
// Handles INT32, UINT32, SINT32, FIXED32, SFIXED32.
// We do not use individual cases to save a few bytes code size.
return 0;
}
}
/**
* Returns true if the value is the zero value for the given scalar type: `0`
* for numeric types, `false` for booleans, `""` for strings, and an empty
* Uint8Array for bytes.
*
* This is the implicit-presence default check. A singular field with implicit
* presence is treated as unset, and omitted from the wire, when its value is
* the zero value. With explicit presence, or in repeated and map fields,
* presence is structural and this function does not apply.
*
* Note that -0 is NOT a zero value for float and double: under implicit
* presence, +0 is omitted from the wire but -0 is written, following the
* proto3 specification. As a result this can disagree with scalarEquals, which
* compares by value and treats -0 as equal to 0.
*/
function isScalarZeroValue(type, value) {
switch (type) {
case descriptors_js_1.ScalarType.BOOL:
return value === false;
case descriptors_js_1.ScalarType.STRING:
return value === "";
case descriptors_js_1.ScalarType.BYTES:
return value instanceof Uint8Array && !value.byteLength;
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
// Object.is distinguishes -0 from 0.
return Object.is(value, 0);
default:
// Loose comparison matches 0n, 0 and "0".
return value == 0;
}
}
import type { DescField, DescOneof } from "../descriptors.js";
export declare const unsafeLocal: unique symbol;
/**
* Return the selected field of a oneof group.
*
* @private
*/
export declare function unsafeOneofCase(target: Record<string, any>, oneof: DescOneof): DescField | undefined;
/**
* Returns true if the field is set.
*
* @private
*/
export declare function unsafeIsSet(target: Record<string, any>, field: DescField): boolean;
/**
* Returns true if the field is set, but only for singular fields with explicit
* presence (proto2).
*
* @private
*/
export declare function unsafeIsSetExplicit(target: object, localName: string): boolean;
/**
* Return a field value, respecting oneof groups.
*
* @private
*/
export declare function unsafeGet(target: Record<string, unknown>, field: DescField): unknown;
/**
* Set a field value, respecting oneof groups.
*
* @private
*/
export declare function unsafeSet(target: Record<string, unknown>, field: DescField, value: unknown): void;
/**
* Resets the field, so that unsafeIsSet() will return false.
*
* @private
*/
export declare function unsafeClear(target: Record<string, any>, field: DescField): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsafeLocal = void 0;
exports.unsafeOneofCase = unsafeOneofCase;
exports.unsafeIsSet = unsafeIsSet;
exports.unsafeIsSetExplicit = unsafeIsSetExplicit;
exports.unsafeGet = unsafeGet;
exports.unsafeSet = unsafeSet;
exports.unsafeClear = unsafeClear;
const scalar_js_1 = require("./scalar.js");
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
exports.unsafeLocal = Symbol.for("reflect unsafe local");
/**
* Return the selected field of a oneof group.
*
* @private
*/
function unsafeOneofCase(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, oneof) {
const c = target[oneof.localName].case;
if (c === undefined) {
return c;
}
return oneof.fields.find((f) => f.localName === c);
}
/**
* Returns true if the field is set.
*
* @private
*/
function unsafeIsSet(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, field) {
const name = field.localName;
if (field.oneof) {
return target[field.oneof.localName].case === name;
}
if (field.presence != IMPLICIT) {
// Fields with explicit presence have properties on the prototype chain
// for default / zero values (except for proto3).
return (target[name] !== undefined &&
Object.prototype.hasOwnProperty.call(target, name));
}
switch (field.fieldKind) {
case "list":
return target[name].length > 0;
case "map":
return Object.keys(target[name]).length > 0;
case "scalar":
return !(0, scalar_js_1.isScalarZeroValue)(field.scalar, target[name]);
case "enum":
return target[name] !== field.enum.values[0].number;
}
throw new Error("message field with implicit presence");
}
/**
* Returns true if the field is set, but only for singular fields with explicit
* presence (proto2).
*
* @private
*/
function unsafeIsSetExplicit(target, localName) {
return (Object.prototype.hasOwnProperty.call(target, localName) &&
target[localName] !== undefined);
}
/**
* Return a field value, respecting oneof groups.
*
* @private
*/
function unsafeGet(target, field) {
if (field.oneof) {
const oneof = target[field.oneof.localName];
if (oneof.case === field.localName) {
return oneof.value;
}
return undefined;
}
return target[field.localName];
}
/**
* Set a field value, respecting oneof groups.
*
* @private
*/
function unsafeSet(target, field, value) {
if (field.oneof) {
target[field.oneof.localName] = {
case: field.localName,
value: value,
};
}
else {
target[field.localName] = value;
}
}
/**
* Resets the field, so that unsafeIsSet() will return false.
*
* @private
*/
function unsafeClear(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, field) {
const name = field.localName;
if (field.oneof) {
const oneofLocalName = field.oneof.localName;
if (target[oneofLocalName].case === name) {
target[oneofLocalName] = { case: undefined };
}
}
else if (field.presence != IMPLICIT) {
// Fields with explicit presence have properties on the prototype chain
// for default / zero values (except for proto3). By deleting their own
// property, the field is reset.
delete target[name];
}
else {
switch (field.fieldKind) {
case "map":
target[name] = {};
break;
case "list":
target[name] = [];
break;
case "enum":
target[name] = field.enum.values[0].number;
break;
case "scalar":
target[name] = (0, scalar_js_1.scalarZeroValue)(field.scalar, field.longAsString);
break;
}
}
}
import type { FileDescriptorProto, FileDescriptorSet } from "./wkt/gen/google/protobuf/descriptor_pb.js";
import { type DescEnum, type DescExtension, type DescFile, type DescMessage, type DescService, type SupportedEdition } from "./descriptors.js";
/**
* A set of descriptors for messages, enumerations, extensions,
* and services.
*/
export interface Registry {
readonly kind: "registry";
/**
* All types (message, enumeration, extension, or service) contained
* in this registry.
*/
[Symbol.iterator](): IterableIterator<DescMessage | DescEnum | DescExtension | DescService>;
/**
* Look up a type (message, enumeration, extension, or service) by
* its fully qualified name.
*/
get(typeName: string): DescMessage | DescEnum | DescExtension | DescService | undefined;
/**
* Look up a message descriptor by its fully qualified name.
*/
getMessage(typeName: string): DescMessage | undefined;
/**
* Look up an enumeration descriptor by its fully qualified name.
*/
getEnum(typeName: string): DescEnum | undefined;
/**
* Look up an extension descriptor by its fully qualified name.
*/
getExtension(typeName: string): DescExtension | undefined;
/**
* Look up an extension by the extendee - the message it extends - and
* the extension number.
*/
getExtensionFor(extendee: DescMessage, no: number): DescExtension | undefined;
/**
* Look up a service descriptor by its fully qualified name.
*/
getService(typeName: string): DescService | undefined;
}
/**
* A registry that allows adding and removing descriptors.
*/
export interface MutableRegistry extends Registry {
/**
* Adds the given descriptor - but not types nested within - to the registry.
*/
add(desc: DescMessage | DescEnum | DescExtension | DescService): void;
/**
* Remove the given descriptor - but not types nested within - from the registry.
*/
remove(desc: DescMessage | DescEnum | DescExtension | DescService): void;
}
/**
* A registry that includes files.
*/
export interface FileRegistry extends Registry {
/**
* All files in this registry.
*/
readonly files: Iterable<DescFile>;
/**
* Look up a file descriptor by file name.
*/
getFile(fileName: string): DescFile | undefined;
}
/**
* Create a registry from the given inputs.
*
* An input can be:
* - Any message, enum, service, or extension descriptor, which adds just the
* descriptor for this type.
* - A file descriptor, which adds all typed defined in this file.
* - A registry, which adds all types from the registry.
*
* For duplicate descriptors (same type name), the one given last wins.
*/
export declare function createRegistry(...input: (Registry | DescFile | DescMessage | DescEnum | DescExtension | DescService)[]): Registry;
/**
* Create a registry that allows adding and removing descriptors.
*/
export declare function createMutableRegistry(...input: (Registry | DescFile | DescMessage | DescEnum | DescExtension | DescService)[]): MutableRegistry;
/**
* Create a registry (including file descriptors) from a google.protobuf.FileDescriptorSet
* message.
*/
export declare function createFileRegistry(fileDescriptorSet: FileDescriptorSet): FileRegistry;
/**
* Create a registry (including file descriptors) from a google.protobuf.FileDescriptorProto
* message. For every import, the given resolver function is called.
*/
export declare function createFileRegistry(fileDescriptorProto: FileDescriptorProto, resolve: (protoFileName: string) => FileDescriptorProto | DescFile | undefined): FileRegistry;
/**
* Create a registry (including file descriptors) from one or more registries,
* merging them.
*/
export declare function createFileRegistry(...registries: FileRegistry[]): FileRegistry;
export declare const minimumEdition: SupportedEdition, maximumEdition: SupportedEdition;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.maximumEdition = exports.minimumEdition = void 0;
exports.createRegistry = createRegistry;
exports.createMutableRegistry = createMutableRegistry;
exports.createFileRegistry = createFileRegistry;
const descriptors_js_1 = require("./descriptors.js");
const text_format_js_1 = require("./wire/text-format.js");
const nested_types_js_1 = require("./reflect/nested-types.js");
const unsafe_js_1 = require("./reflect/unsafe.js");
const names_js_1 = require("./reflect/names.js");
/**
* Create a registry from the given inputs.
*
* An input can be:
* - Any message, enum, service, or extension descriptor, which adds just the
* descriptor for this type.
* - A file descriptor, which adds all typed defined in this file.
* - A registry, which adds all types from the registry.
*
* For duplicate descriptors (same type name), the one given last wins.
*/
function createRegistry(...input) {
return initBaseRegistry(input);
}
/**
* Create a registry that allows adding and removing descriptors.
*/
function createMutableRegistry(...input) {
const reg = initBaseRegistry(input);
return Object.assign(Object.assign({}, reg), { remove(desc) {
var _a;
if (desc.kind == "extension") {
(_a = reg.extendees.get(desc.extendee.typeName)) === null || _a === void 0 ? void 0 : _a.delete(desc.number);
}
reg.types.delete(desc.typeName);
} });
}
function createFileRegistry(...args) {
const registry = createBaseRegistry();
if (!args.length) {
return registry;
}
if ("$typeName" in args[0] &&
args[0].$typeName == "google.protobuf.FileDescriptorSet") {
for (const file of args[0].file) {
addFile(file, registry);
}
return registry;
}
if ("$typeName" in args[0]) {
const input = args[0];
const resolve = args[1];
const seen = new Set();
function recurseDeps(file) {
const deps = [];
for (const protoFileName of file.dependency) {
if (registry.getFile(protoFileName) != undefined) {
continue;
}
if (seen.has(protoFileName)) {
continue;
}
const dep = resolve(protoFileName);
if (!dep) {
throw new Error(`Unable to resolve ${protoFileName}, imported by ${file.name}`);
}
if ("kind" in dep) {
registry.addFile(dep, false, true);
}
else {
seen.add(dep.name);
deps.push(dep);
}
}
return deps.concat(...deps.map(recurseDeps));
}
for (const file of [input, ...recurseDeps(input)].reverse()) {
addFile(file, registry);
}
}
else {
for (const fileReg of args) {
for (const file of fileReg.files) {
registry.addFile(file);
}
}
}
return registry;
}
/**
* @private
*/
function createBaseRegistry() {
const types = new Map();
const extendees = new Map();
const files = new Map();
return {
kind: "registry",
types,
extendees,
[Symbol.iterator]() {
return types.values();
},
get files() {
return files.values();
},
addFile(file, skipTypes, withDeps) {
files.set(file.proto.name, file);
if (!skipTypes) {
for (const type of (0, nested_types_js_1.nestedTypes)(file)) {
this.add(type);
}
}
if (withDeps) {
for (const f of file.dependencies) {
this.addFile(f, skipTypes, withDeps);
}
}
},
add(desc) {
if (desc.kind == "extension") {
let numberToExt = extendees.get(desc.extendee.typeName);
if (!numberToExt) {
extendees.set(desc.extendee.typeName,
// biome-ignore lint/suspicious/noAssignInExpressions: no
(numberToExt = new Map()));
}
numberToExt.set(desc.number, desc);
}
types.set(desc.typeName, desc);
},
get(typeName) {
return types.get(typeName);
},
getFile(fileName) {
return files.get(fileName);
},
getMessage(typeName) {
const t = types.get(typeName);
return (t === null || t === void 0 ? void 0 : t.kind) == "message" ? t : undefined;
},
getEnum(typeName) {
const t = types.get(typeName);
return (t === null || t === void 0 ? void 0 : t.kind) == "enum" ? t : undefined;
},
getExtension(typeName) {
const t = types.get(typeName);
return (t === null || t === void 0 ? void 0 : t.kind) == "extension" ? t : undefined;
},
getExtensionFor(extendee, no) {
var _a;
return (_a = extendees.get(extendee.typeName)) === null || _a === void 0 ? void 0 : _a.get(no);
},
getService(typeName) {
const t = types.get(typeName);
return (t === null || t === void 0 ? void 0 : t.kind) == "service" ? t : undefined;
},
};
}
/**
* @private
*/
function initBaseRegistry(inputs) {
const registry = createBaseRegistry();
for (const input of inputs) {
switch (input.kind) {
case "registry":
for (const n of input) {
registry.add(n);
}
break;
case "file":
registry.addFile(input);
break;
default:
registry.add(input);
break;
}
}
return registry;
}
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name: Edition.$localName = $number;
const EDITION_PROTO2 = 998;
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name: Edition.$localName = $number;
const EDITION_PROTO3 = 999;
// bootstrap-inject google.protobuf.Edition.EDITION_UNSTABLE: const $name: Edition.$localName = $number;
const EDITION_UNSTABLE = 9999;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_STRING: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_STRING = 9;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_GROUP: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_GROUP = 10;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_MESSAGE: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_MESSAGE = 11;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_BYTES: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_BYTES = 12;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_ENUM: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_ENUM = 14;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED: const $name: FieldDescriptorProto_Label.$localName = $number;
const LABEL_REPEATED = 3;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Label.LABEL_REQUIRED: const $name: FieldDescriptorProto_Label.$localName = $number;
const LABEL_REQUIRED = 2;
// bootstrap-inject google.protobuf.FieldOptions.JSType.JS_STRING: const $name: FieldOptions_JSType.$localName = $number;
const JS_STRING = 1;
// bootstrap-inject google.protobuf.MethodOptions.IdempotencyLevel.IDEMPOTENCY_UNKNOWN: const $name: MethodOptions_IdempotencyLevel.$localName = $number;
const IDEMPOTENCY_UNKNOWN = 0;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.EXPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const EXPLICIT = 1;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;
const LEGACY_REQUIRED = 3;
// bootstrap-inject google.protobuf.FeatureSet.RepeatedFieldEncoding.PACKED: const $name: FeatureSet_RepeatedFieldEncoding.$localName = $number;
const PACKED = 1;
// bootstrap-inject google.protobuf.FeatureSet.MessageEncoding.DELIMITED: const $name: FeatureSet_MessageEncoding.$localName = $number;
const DELIMITED = 2;
// bootstrap-inject google.protobuf.FeatureSet.EnumType.OPEN: const $name: FeatureSet_EnumType.$localName = $number;
const OPEN = 1;
// bootstrap-inject google.protobuf.FeatureSet.Utf8Validation.VERIFY: const $name: FeatureSet_Utf8Validation.$localName = $number;
const VERIFY = 2;
// biome-ignore format: want this to read well
// bootstrap-inject defaults: EDITION_PROTO2 to EDITION_2024: export const minimumEdition: SupportedEdition = $minimumEdition, maximumEdition: SupportedEdition = $maximumEdition;
// generated from protoc v34.1
exports.minimumEdition = 998, exports.maximumEdition = 1001;
const featureDefaults = {
// EDITION_PROTO2
998: {
fieldPresence: 1, // EXPLICIT,
enumType: 2, // CLOSED,
repeatedFieldEncoding: 2, // EXPANDED,
utf8Validation: 3, // NONE,
messageEncoding: 1, // LENGTH_PREFIXED,
jsonFormat: 2, // LEGACY_BEST_EFFORT,
enforceNamingStyle: 2, // STYLE_LEGACY,
defaultSymbolVisibility: 1, // EXPORT_ALL,
},
// EDITION_PROTO3
999: {
fieldPresence: 2, // IMPLICIT,
enumType: 1, // OPEN,
repeatedFieldEncoding: 1, // PACKED,
utf8Validation: 2, // VERIFY,
messageEncoding: 1, // LENGTH_PREFIXED,
jsonFormat: 1, // ALLOW,
enforceNamingStyle: 2, // STYLE_LEGACY,
defaultSymbolVisibility: 1, // EXPORT_ALL,
},
// EDITION_2023
1000: {
fieldPresence: 1, // EXPLICIT,
enumType: 1, // OPEN,
repeatedFieldEncoding: 1, // PACKED,
utf8Validation: 2, // VERIFY,
messageEncoding: 1, // LENGTH_PREFIXED,
jsonFormat: 1, // ALLOW,
enforceNamingStyle: 2, // STYLE_LEGACY,
defaultSymbolVisibility: 1, // EXPORT_ALL,
},
// EDITION_2024
1001: {
fieldPresence: 1, // EXPLICIT,
enumType: 1, // OPEN,
repeatedFieldEncoding: 1, // PACKED,
utf8Validation: 2, // VERIFY,
messageEncoding: 1, // LENGTH_PREFIXED,
jsonFormat: 1, // ALLOW,
enforceNamingStyle: 1, // STYLE2024,
defaultSymbolVisibility: 2, // EXPORT_TOP_LEVEL,
},
};
/**
* Create a descriptor for a file, add it to the registry.
*/
function addFile(proto, reg) {
var _a, _b;
const file = {
kind: "file",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
edition: getFileEdition(proto),
name: proto.name.replace(/\.proto$/, ""),
dependencies: findFileDependencies(proto, reg),
enums: [],
messages: [],
extensions: [],
services: [],
toString() {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- we asserted above
return `file ${proto.name}`;
},
};
const mapEntriesStore = new Map();
const mapEntries = {
get(typeName) {
return mapEntriesStore.get(typeName);
},
add(desc) {
var _a;
assert(((_a = desc.proto.options) === null || _a === void 0 ? void 0 : _a.mapEntry) === true);
mapEntriesStore.set(desc.typeName, desc);
},
};
for (const enumProto of proto.enumType) {
addEnum(enumProto, file, undefined, reg);
}
for (const messageProto of proto.messageType) {
addMessage(messageProto, file, undefined, reg, mapEntries);
}
for (const serviceProto of proto.service) {
addService(serviceProto, file, reg);
}
addExtensions(file, reg);
for (const mapEntry of mapEntriesStore.values()) {
// to create a map field, we need access to the map entry's fields
addFields(mapEntry, reg, mapEntries);
}
for (const message of file.messages) {
addFields(message, reg, mapEntries);
addExtensions(message, reg);
}
reg.addFile(file, true);
}
/**
* Create descriptors for extensions, and add them to the message / file,
* and to our cart.
* Recurses into nested types.
*/
function addExtensions(desc, reg) {
switch (desc.kind) {
case "file":
for (const proto of desc.proto.extension) {
const ext = newField(proto, desc, reg);
desc.extensions.push(ext);
reg.add(ext);
}
break;
case "message":
for (const proto of desc.proto.extension) {
const ext = newField(proto, desc, reg);
desc.nestedExtensions.push(ext);
reg.add(ext);
}
for (const message of desc.nestedMessages) {
addExtensions(message, reg);
}
break;
}
}
/**
* Create descriptors for fields and oneof groups, and add them to the message.
* Recurses into nested types.
*/
function addFields(message, reg, mapEntries) {
const allOneofs = message.proto.oneofDecl.map((proto) => newOneof(proto, message));
const oneofsSeen = new Set();
for (const proto of message.proto.field) {
const oneof = findOneof(proto, allOneofs);
const field = newField(proto, message, reg, oneof, mapEntries);
message.fields.push(field);
message.field[field.localName] = field;
if (oneof === undefined) {
message.members.push(field);
}
else {
oneof.fields.push(field);
if (!oneofsSeen.has(oneof)) {
oneofsSeen.add(oneof);
message.members.push(oneof);
}
}
}
for (const oneof of allOneofs.filter((o) => oneofsSeen.has(o))) {
message.oneofs.push(oneof);
}
for (const child of message.nestedMessages) {
addFields(child, reg, mapEntries);
}
}
/**
* Create a descriptor for an enumeration, and add it our cart and to the
* parent type, if any.
*/
function addEnum(proto, file, parent, reg) {
var _a, _b, _c, _d, _e;
const sharedPrefix = findEnumSharedPrefix(proto.name, proto.value);
const desc = {
kind: "enum",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
parent,
open: true,
name: proto.name,
typeName: makeTypeName(proto, parent, file),
value: {},
values: [],
sharedPrefix,
toString() {
return `enum ${this.typeName}`;
},
};
desc.open = isEnumOpen(desc);
reg.add(desc);
for (const p of proto.value) {
const name = p.name;
desc.values.push(
// biome-ignore lint/suspicious/noAssignInExpressions: no
(desc.value[p.number] = {
kind: "enum_value",
proto: p,
deprecated: (_d = (_c = p.options) === null || _c === void 0 ? void 0 : _c.deprecated) !== null && _d !== void 0 ? _d : false,
parent: desc,
name,
localName: (0, names_js_1.safeObjectProperty)(sharedPrefix == undefined
? name
: name.substring(sharedPrefix.length)),
number: p.number,
toString() {
return `enum value ${desc.typeName}.${name}`;
},
}));
}
((_e = parent === null || parent === void 0 ? void 0 : parent.nestedEnums) !== null && _e !== void 0 ? _e : file.enums).push(desc);
}
/**
* Create a descriptor for a message, including nested types, and add it to our
* cart. Note that this does not create descriptors fields.
*/
function addMessage(proto, file, parent, reg, mapEntries) {
var _a, _b, _c, _d;
const desc = {
kind: "message",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
parent,
name: proto.name,
typeName: makeTypeName(proto, parent, file),
fields: [],
field: {},
oneofs: [],
members: [],
nestedEnums: [],
nestedMessages: [],
nestedExtensions: [],
toString() {
return `message ${this.typeName}`;
},
};
if (((_c = proto.options) === null || _c === void 0 ? void 0 : _c.mapEntry) === true) {
mapEntries.add(desc);
}
else {
((_d = parent === null || parent === void 0 ? void 0 : parent.nestedMessages) !== null && _d !== void 0 ? _d : file.messages).push(desc);
reg.add(desc);
}
for (const enumProto of proto.enumType) {
addEnum(enumProto, file, desc, reg);
}
for (const messageProto of proto.nestedType) {
addMessage(messageProto, file, desc, reg, mapEntries);
}
}
/**
* Create a descriptor for a service, including methods, and add it to our
* cart.
*/
function addService(proto, file, reg) {
var _a, _b;
const desc = {
kind: "service",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
name: proto.name,
typeName: makeTypeName(proto, undefined, file),
methods: [],
method: {},
toString() {
return `service ${this.typeName}`;
},
};
file.services.push(desc);
reg.add(desc);
for (const methodProto of proto.method) {
const method = newMethod(methodProto, desc, reg);
desc.methods.push(method);
desc.method[method.localName] = method;
}
}
/**
* Create a descriptor for a method.
*/
function newMethod(proto, parent, reg) {
var _a, _b, _c, _d;
let methodKind;
if (proto.clientStreaming && proto.serverStreaming) {
methodKind = "bidi_streaming";
}
else if (proto.clientStreaming) {
methodKind = "client_streaming";
}
else if (proto.serverStreaming) {
methodKind = "server_streaming";
}
else {
methodKind = "unary";
}
const input = reg.getMessage(trimLeadingDot(proto.inputType));
const output = reg.getMessage(trimLeadingDot(proto.outputType));
assert(input, `invalid MethodDescriptorProto: input_type ${proto.inputType} not found`);
assert(output, `invalid MethodDescriptorProto: output_type ${proto.inputType} not found`);
const name = proto.name;
return {
kind: "rpc",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
parent,
name,
localName: (0, names_js_1.safeObjectProperty)(name.length
? (0, names_js_1.safeObjectProperty)(name[0].toLowerCase() + name.substring(1))
: name),
methodKind,
input,
output,
idempotency: (_d = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.idempotencyLevel) !== null && _d !== void 0 ? _d : IDEMPOTENCY_UNKNOWN,
toString() {
return `rpc ${parent.typeName}.${name}`;
},
};
}
/**
* Create a descriptor for a oneof group.
*/
function newOneof(proto, parent) {
return {
kind: "oneof",
proto,
deprecated: false,
parent,
fields: [],
name: proto.name,
localName: (0, names_js_1.safeObjectProperty)((0, names_js_1.protoCamelCase)(proto.name)),
toString() {
return `oneof ${parent.typeName}.${this.name}`;
},
};
}
function newField(proto, parentOrFile, reg, oneof, mapEntries) {
var _a, _b, _c;
const isExtension = mapEntries === undefined;
const field = {
kind: "field",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
name: proto.name,
number: proto.number,
scalar: undefined,
message: undefined,
enum: undefined,
presence: getFieldPresence(proto, oneof, isExtension, parentOrFile),
utf8Validation: isUtf8Validated(proto, parentOrFile),
listKind: undefined,
mapKind: undefined,
mapKey: undefined,
delimitedEncoding: undefined,
packed: undefined,
longAsString: false,
getDefaultValue: undefined,
};
if (isExtension) {
// extension field
const file = parentOrFile.kind == "file" ? parentOrFile : parentOrFile.file;
const parent = parentOrFile.kind == "file" ? undefined : parentOrFile;
const typeName = makeTypeName(proto, parent, file);
field.kind = "extension";
field.file = file;
field.parent = parent;
field.oneof = undefined;
field.typeName = typeName;
field.jsonName = `[${typeName}]`; // option json_name is not allowed on extension fields
field.toString = () => `extension ${typeName}`;
const extendee = reg.getMessage(trimLeadingDot(proto.extendee));
assert(extendee, `invalid FieldDescriptorProto: extendee ${proto.extendee} not found`);
field.extendee = extendee;
}
else {
// regular field
const parent = parentOrFile;
assert(parent.kind == "message");
field.parent = parent;
field.oneof = oneof;
field.localName = oneof
? (0, names_js_1.protoCamelCase)(proto.name)
: (0, names_js_1.safeObjectProperty)((0, names_js_1.protoCamelCase)(proto.name));
field.jsonName = proto.jsonName;
field.toString = () => `field ${parent.typeName}.${proto.name}`;
}
const label = proto.label;
const type = proto.type;
const jstype = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.jstype;
if (label === LABEL_REPEATED) {
// list or map field
const mapEntry = type == TYPE_MESSAGE
? mapEntries === null || mapEntries === void 0 ? void 0 : mapEntries.get(trimLeadingDot(proto.typeName))
: undefined;
if (mapEntry) {
// map field
field.fieldKind = "map";
const { key, value } = findMapEntryFields(mapEntry);
field.mapKey = key.scalar;
field.mapKind = value.fieldKind;
field.message = value.message;
field.delimitedEncoding = false; // map fields are always LENGTH_PREFIXED
field.enum = value.enum;
field.scalar = value.scalar;
return field;
}
// list field
field.fieldKind = "list";
switch (type) {
case TYPE_MESSAGE:
case TYPE_GROUP:
field.listKind = "message";
field.message = reg.getMessage(trimLeadingDot(proto.typeName));
assert(field.message);
field.delimitedEncoding = isDelimitedEncoding(proto, parentOrFile);
break;
case TYPE_ENUM:
field.listKind = "enum";
field.enum = reg.getEnum(trimLeadingDot(proto.typeName));
assert(field.enum);
break;
default:
field.listKind = "scalar";
field.scalar = type;
field.longAsString = jstype == JS_STRING;
break;
}
field.packed = isPackedField(proto, parentOrFile);
return field;
}
// singular
switch (type) {
case TYPE_MESSAGE:
case TYPE_GROUP:
field.fieldKind = "message";
field.message = reg.getMessage(trimLeadingDot(proto.typeName));
assert(field.message, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
field.delimitedEncoding = isDelimitedEncoding(proto, parentOrFile);
field.getDefaultValue = () => undefined;
break;
case TYPE_ENUM: {
const enumeration = reg.getEnum(trimLeadingDot(proto.typeName));
assert(enumeration !== undefined, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
field.fieldKind = "enum";
field.enum = reg.getEnum(trimLeadingDot(proto.typeName));
field.getDefaultValue = () => {
return (0, unsafe_js_1.unsafeIsSetExplicit)(proto, "defaultValue")
? (0, text_format_js_1.parseTextFormatEnumValue)(enumeration, proto.defaultValue)
: undefined;
};
break;
}
default: {
field.fieldKind = "scalar";
field.scalar = type;
field.longAsString = jstype == JS_STRING;
field.getDefaultValue = () => {
return (0, unsafe_js_1.unsafeIsSetExplicit)(proto, "defaultValue")
? (0, text_format_js_1.parseTextFormatScalarValue)(type, proto.defaultValue)
: undefined;
};
break;
}
}
return field;
}
/**
* Parse the "syntax" and "edition" fields, returning one of the supported
* editions.
*/
function getFileEdition(proto) {
switch (proto.syntax) {
case "":
case "proto2":
return EDITION_PROTO2;
case "proto3":
return EDITION_PROTO3;
case "editions":
// EDITION_UNSTABLE is a sandbox for in-development features. Collapse
// it to maximumEdition so SupportedEdition and feature resolution do
// not leak the test-only edition to users.
if (proto.edition === EDITION_UNSTABLE) {
return exports.maximumEdition;
}
if (proto.edition in featureDefaults) {
return proto.edition;
}
throw new Error(`${proto.name}: unsupported edition`);
default:
throw new Error(`${proto.name}: unsupported syntax "${proto.syntax}"`);
}
}
/**
* Resolve dependencies of FileDescriptorProto to DescFile.
*/
function findFileDependencies(proto, reg) {
return proto.dependency.map((wantName) => {
const dep = reg.getFile(wantName);
if (!dep) {
throw new Error(`Cannot find ${wantName}, imported by ${proto.name}`);
}
return dep;
});
}
/**
* Finds a prefix shared by enum values, for example `my_enum_` for
* `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`.
*/
function findEnumSharedPrefix(enumName, values) {
const prefix = camelToSnakeCase(enumName) + "_";
for (const value of values) {
if (!value.name.toLowerCase().startsWith(prefix)) {
return undefined;
}
const shortName = value.name.substring(prefix.length);
if (shortName.length == 0) {
return undefined;
}
if (/^\d/.test(shortName)) {
// identifiers must not start with numbers
return undefined;
}
}
return prefix;
}
/**
* Converts lowerCamelCase or UpperCamelCase into lower_snake_case.
* This is used to find shared prefixes in an enum.
*/
function camelToSnakeCase(camel) {
return (camel.substring(0, 1) + camel.substring(1).replace(/[A-Z]/g, (c) => "_" + c)).toLowerCase();
}
/**
* Create a fully qualified name for a protobuf type or extension field.
*
* The fully qualified name for messages, enumerations, and services is
* constructed by concatenating the package name (if present), parent
* message names (for nested types), and the type name. We omit the leading
* dot added by protobuf compilers. Examples:
* - mypackage.MyMessage
* - mypackage.MyMessage.NestedMessage
*
* The fully qualified name for extension fields is constructed by
* concatenating the package name (if present), parent message names (for
* extensions declared within a message), and the field name. Examples:
* - mypackage.extfield
* - mypackage.MyMessage.extfield
*/
function makeTypeName(proto, parent, file) {
let typeName;
if (parent) {
typeName = `${parent.typeName}.${proto.name}`;
}
else if (file.proto.package.length > 0) {
typeName = `${file.proto.package}.${proto.name}`;
}
else {
typeName = `${proto.name}`;
}
return typeName;
}
/**
* Remove the leading dot from a fully qualified type name.
*/
function trimLeadingDot(typeName) {
return typeName.startsWith(".") ? typeName.substring(1) : typeName;
}
/**
* Did the user put the field in a oneof group?
* Synthetic oneofs for proto3 optionals are ignored.
*/
function findOneof(proto, allOneofs) {
if (!(0, unsafe_js_1.unsafeIsSetExplicit)(proto, "oneofIndex")) {
return undefined;
}
if (proto.proto3Optional) {
return undefined;
}
const oneof = allOneofs[proto.oneofIndex];
assert(oneof, `invalid FieldDescriptorProto: oneof #${proto.oneofIndex} for field #${proto.number} not found`);
return oneof;
}
/**
* Presence of the field.
* See https://protobuf.dev/programming-guides/field_presence/
*/
function getFieldPresence(proto, oneof, isExtension, parent) {
if (proto.label == LABEL_REQUIRED) {
// proto2 required is LEGACY_REQUIRED
return LEGACY_REQUIRED;
}
if (proto.label == LABEL_REPEATED) {
// repeated fields (including maps) do not track presence
return IMPLICIT;
}
if (!!oneof || proto.proto3Optional) {
// oneof is always explicit
return EXPLICIT;
}
if (isExtension) {
// extensions always track presence
return EXPLICIT;
}
const resolved = resolveFeature("fieldPresence", { proto, parent });
if (resolved == IMPLICIT &&
(proto.type == TYPE_MESSAGE || proto.type == TYPE_GROUP)) {
// singular message field cannot be implicit
return EXPLICIT;
}
return resolved;
}
/**
* Pack this repeated field?
*/
function isPackedField(proto, parent) {
if (proto.label != LABEL_REPEATED) {
return false;
}
switch (proto.type) {
case TYPE_STRING:
case TYPE_BYTES:
case TYPE_GROUP:
case TYPE_MESSAGE:
// length-delimited types cannot be packed
return false;
}
const o = proto.options;
if (o && (0, unsafe_js_1.unsafeIsSetExplicit)(o, "packed")) {
// prefer the field option over edition features
return o.packed;
}
return (PACKED ==
resolveFeature("repeatedFieldEncoding", {
proto,
parent,
}));
}
/**
* Find the key and value fields of a synthetic map entry message.
*/
function findMapEntryFields(mapEntry) {
const key = mapEntry.fields.find((f) => f.number === 1);
const value = mapEntry.fields.find((f) => f.number === 2);
assert(key &&
key.fieldKind == "scalar" &&
key.scalar != descriptors_js_1.ScalarType.BYTES &&
key.scalar != descriptors_js_1.ScalarType.FLOAT &&
key.scalar != descriptors_js_1.ScalarType.DOUBLE &&
value &&
value.fieldKind != "list" &&
value.fieldKind != "map");
return { key, value };
}
/**
* Enumerations can be open or closed.
* See https://protobuf.dev/programming-guides/enum/
*/
function isEnumOpen(desc) {
var _a;
return (OPEN ==
resolveFeature("enumType", {
proto: desc.proto,
parent: (_a = desc.parent) !== null && _a !== void 0 ? _a : desc.file,
}));
}
/**
* Encode the message delimited (a.k.a. proto2 group encoding), or
* length-prefixed?
*/
function isDelimitedEncoding(proto, parent) {
if (proto.type == TYPE_GROUP) {
return true;
}
return (DELIMITED ==
resolveFeature("messageEncoding", {
proto,
parent,
}));
}
/**
* Reject invalid UTF-8 when reading string fields from the binary wire format?
* Driven by the resolved `utf8_validation` feature: VERIFY (proto3 / editions
* 2023+ default) enforces; NONE (proto2 default) does not.
*/
function isUtf8Validated(proto, parent) {
return (VERIFY ==
resolveFeature("utf8Validation", {
proto,
parent,
}));
}
function resolveFeature(name, ref) {
var _a, _b;
const featureSet = (_a = ref.proto.options) === null || _a === void 0 ? void 0 : _a.features;
if (featureSet) {
const val = featureSet[name];
if (val != 0) {
return val;
}
}
if ("kind" in ref) {
if (ref.kind == "message") {
return resolveFeature(name, (_b = ref.parent) !== null && _b !== void 0 ? _b : ref.file);
}
const editionDefaults = featureDefaults[ref.edition];
if (!editionDefaults) {
throw new Error(`feature default for edition ${ref.edition} not found`);
}
return editionDefaults[name];
}
return resolveFeature(name, ref.parent);
}
/**
* Assert that condition is truthy or throw error (with message)
*/
function assert(condition, msg) {
if (!condition) {
throw new Error(msg);
}
}
import type { MessageShape } from "./types.js";
import { BinaryWriter } from "./wire/binary-encoding.js";
import { type DescField, type DescMessage } from "./descriptors.js";
import type { ReflectMessage } from "./reflect/index.js";
/**
* Options for serializing to binary data.
*
* V1 also had the option `readerFactory` for using a custom implementation to
* encode to binary.
*/
export interface BinaryWriteOptions {
/**
* Include unknown fields in the serialized output? The default behavior
* is to retain unknown fields and include them in the serialized output.
*
* For more details see https://developers.google.com/protocol-buffers/docs/proto3#unknowns
*/
writeUnknownFields: boolean;
}
export declare function toBinary<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>, options?: Partial<BinaryWriteOptions>): Uint8Array<ArrayBuffer>;
/**
* @private
*/
export declare function writeField(writer: BinaryWriter, opts: BinaryWriteOptions, msg: ReflectMessage, field: DescField): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBinary = toBinary;
exports.writeField = writeField;
const reflect_js_1 = require("./reflect/reflect.js");
const binary_encoding_js_1 = require("./wire/binary-encoding.js");
const descriptors_js_1 = require("./descriptors.js");
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;
const LEGACY_REQUIRED = 3;
// Default options for serializing binary data.
const writeDefaults = {
writeUnknownFields: true,
};
function makeWriteOptions(options) {
return options ? Object.assign(Object.assign({}, writeDefaults), options) : writeDefaults;
}
function toBinary(schema, message, options) {
return writeFields(new binary_encoding_js_1.BinaryWriter(), makeWriteOptions(options), (0, reflect_js_1.reflect)(schema, message)).finish();
}
function writeFields(writer, opts, msg) {
var _a;
for (const f of msg.sortedFields) {
if (!msg.isSet(f)) {
if (f.presence == LEGACY_REQUIRED) {
throw new Error(`cannot encode ${f} to binary: required field not set`);
}
continue;
}
writeField(writer, opts, msg, f);
}
if (opts.writeUnknownFields) {
for (const { no, wireType, data } of (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : []) {
writer.tag(no, wireType).raw(data);
}
}
return writer;
}
/**
* @private
*/
function writeField(writer, opts, msg, field) {
var _a;
switch (field.fieldKind) {
case "scalar":
case "enum":
writeScalar(writer, msg.desc.typeName, field.name, (_a = field.scalar) !== null && _a !== void 0 ? _a : descriptors_js_1.ScalarType.INT32, field.number, msg.get(field));
break;
case "list":
writeListField(writer, opts, field, msg.get(field));
break;
case "message":
writeMessageField(writer, opts, field, msg.get(field));
break;
case "map":
for (const [key, val] of msg.get(field)) {
writeMapEntry(writer, opts, field, key, val);
}
break;
}
}
function writeScalar(writer, msgName, fieldName, scalarType, fieldNo, value) {
writeScalarValue(writer.tag(fieldNo, writeTypeOfScalar(scalarType)), msgName, fieldName, scalarType, value);
}
function writeMessageField(writer, opts, field, message) {
if (field.delimitedEncoding) {
writeFields(writer.tag(field.number, binary_encoding_js_1.WireType.StartGroup), opts, message).tag(field.number, binary_encoding_js_1.WireType.EndGroup);
}
else {
writeFields(writer.tag(field.number, binary_encoding_js_1.WireType.LengthDelimited).fork(), opts, message).join();
}
}
function writeListField(writer, opts, field, list) {
var _a;
if (field.listKind == "message") {
for (const item of list) {
writeMessageField(writer, opts, field, item);
}
return;
}
const scalarType = (_a = field.scalar) !== null && _a !== void 0 ? _a : descriptors_js_1.ScalarType.INT32;
if (field.packed) {
if (!list.size) {
return;
}
writer.tag(field.number, binary_encoding_js_1.WireType.LengthDelimited).fork();
for (const item of list) {
writeScalarValue(writer, field.parent.typeName, field.name, scalarType, item);
}
writer.join();
return;
}
for (const item of list) {
writeScalar(writer, field.parent.typeName, field.name, scalarType, field.number, item);
}
}
function writeMapEntry(writer, opts, field, key, value) {
var _a;
writer.tag(field.number, binary_encoding_js_1.WireType.LengthDelimited).fork();
// write key, expecting key field number = 1
writeScalar(writer, field.parent.typeName, field.name, field.mapKey, 1, key);
// write value, expecting value field number = 2
switch (field.mapKind) {
case "scalar":
case "enum":
writeScalar(writer, field.parent.typeName, field.name, (_a = field.scalar) !== null && _a !== void 0 ? _a : descriptors_js_1.ScalarType.INT32, 2, value);
break;
case "message":
writeFields(writer.tag(2, binary_encoding_js_1.WireType.LengthDelimited).fork(), opts, value).join();
break;
}
writer.join();
}
function writeScalarValue(writer, msgName, fieldName, type, value) {
try {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
writer.string(value);
break;
case descriptors_js_1.ScalarType.BOOL:
writer.bool(value);
break;
case descriptors_js_1.ScalarType.DOUBLE:
writer.double(value);
break;
case descriptors_js_1.ScalarType.FLOAT:
writer.float(value);
break;
case descriptors_js_1.ScalarType.INT32:
writer.int32(value);
break;
case descriptors_js_1.ScalarType.INT64:
writer.int64(value);
break;
case descriptors_js_1.ScalarType.UINT64:
writer.uint64(value);
break;
case descriptors_js_1.ScalarType.FIXED64:
writer.fixed64(value);
break;
case descriptors_js_1.ScalarType.BYTES:
writer.bytes(value);
break;
case descriptors_js_1.ScalarType.FIXED32:
writer.fixed32(value);
break;
case descriptors_js_1.ScalarType.SFIXED32:
writer.sfixed32(value);
break;
case descriptors_js_1.ScalarType.SFIXED64:
writer.sfixed64(value);
break;
case descriptors_js_1.ScalarType.SINT64:
writer.sint64(value);
break;
case descriptors_js_1.ScalarType.UINT32:
writer.uint32(value);
break;
case descriptors_js_1.ScalarType.SINT32:
writer.sint32(value);
break;
}
}
catch (e) {
if (e instanceof Error) {
throw new Error(`cannot encode field ${msgName}.${fieldName} to binary: ${e.message}`);
}
throw e;
}
}
function writeTypeOfScalar(type) {
switch (type) {
case descriptors_js_1.ScalarType.BYTES:
case descriptors_js_1.ScalarType.STRING:
return binary_encoding_js_1.WireType.LengthDelimited;
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SFIXED64:
return binary_encoding_js_1.WireType.Bit64;
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.FLOAT:
return binary_encoding_js_1.WireType.Bit32;
default:
return binary_encoding_js_1.WireType.Varint;
}
}
import { type DescEnum, type DescMessage } from "./descriptors.js";
import type { JsonValue } from "./json-value.js";
import type { Registry } from "./registry.js";
import type { EnumJsonType, EnumShape, MessageJsonType, MessageShape } from "./types.js";
/**
* Options for serializing to JSON.
*/
export interface JsonWriteOptions {
/**
* By default, fields with implicit presence are not serialized if they are
* unset. For example, an empty list field or a proto3 int32 field with 0 is
* not serialized. With this option enabled, such fields are included in the
* output.
*/
alwaysEmitImplicit: boolean;
/**
* Emit enum values as integers instead of strings: The name of an enum
* value is used by default in JSON output. An option may be provided to
* use the numeric value of the enum value instead.
*/
enumAsInteger: boolean;
/**
* Use proto field name instead of lowerCamelCase name: By default proto3
* JSON printer should convert the field name to lowerCamelCase and use
* that as the JSON name. An implementation may provide an option to use
* proto field name as the JSON name instead. Proto3 JSON parsers are
* required to accept both the converted lowerCamelCase name and the proto
* field name.
*/
useProtoFieldName: boolean;
/**
* This option is required to write `google.protobuf.Any` and extensions
* to JSON format.
*/
registry?: Registry | undefined;
}
/**
* Options for serializing to JSON.
*/
export interface JsonWriteStringOptions extends JsonWriteOptions {
/**
* Format JSON with indentation. Indicates the number of space characters to
* be used as indentation.
*
* This option is passed to JSON.stringify as `space`.
*/
prettySpaces: number;
}
/**
* Serialize the message to a JSON value, a JavaScript value that can be
* passed to JSON.stringify().
*/
export declare function toJson<Desc extends DescMessage, Opts extends Partial<JsonWriteOptions> | undefined = undefined>(schema: Desc, message: MessageShape<Desc>, options?: Opts): ToJson<Desc, Opts>;
type ToJson<Desc extends DescMessage, Opts extends undefined | Partial<JsonWriteOptions>> = Opts extends undefined | {
alwaysEmitImplicit?: false;
enumAsInteger?: false;
useProtoFieldName?: false;
} ? MessageJsonType<Desc> : JsonValue;
/**
* Serialize the message to a JSON string.
*/
export declare function toJsonString<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>, options?: Partial<JsonWriteStringOptions>): string;
/**
* Serialize a single enum value to JSON.
*/
export declare function enumToJson<Desc extends DescEnum>(descEnum: Desc, value: EnumShape<Desc>): EnumJsonType<Desc>;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.toJson = toJson;
exports.toJsonString = toJsonString;
exports.enumToJson = enumToJson;
const descriptors_js_1 = require("./descriptors.js");
const names_js_1 = require("./reflect/names.js");
const reflect_js_1 = require("./reflect/reflect.js");
const index_js_1 = require("./wkt/index.js");
const wrappers_js_1 = require("./wkt/wrappers.js");
const index_js_2 = require("./wire/index.js");
const extensions_js_1 = require("./extensions.js");
const reflect_check_js_1 = require("./reflect/reflect-check.js");
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;
const LEGACY_REQUIRED = 3;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
// Default options for serializing to JSON.
const jsonWriteDefaults = {
alwaysEmitImplicit: false,
enumAsInteger: false,
useProtoFieldName: false,
};
function makeWriteOptions(options) {
return options ? Object.assign(Object.assign({}, jsonWriteDefaults), options) : jsonWriteDefaults;
}
/**
* Serialize the message to a JSON value, a JavaScript value that can be
* passed to JSON.stringify().
*/
function toJson(schema, message, options) {
return reflectToJson((0, reflect_js_1.reflect)(schema, message), makeWriteOptions(options));
}
/**
* Serialize the message to a JSON string.
*/
function toJsonString(schema, message, options) {
var _a;
const jsonValue = toJson(schema, message, options);
return JSON.stringify(jsonValue, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
}
/**
* Serialize a single enum value to JSON.
*/
function enumToJson(descEnum, value) {
var _a;
if (descEnum.typeName == "google.protobuf.NullValue") {
return null;
}
const name = (_a = descEnum.value[value]) === null || _a === void 0 ? void 0 : _a.name;
if (name === undefined) {
throw new Error(`${value} is not a value in ${descEnum}`);
}
return name;
}
function reflectToJson(msg, opts) {
var _a;
const wktJson = tryWktToJson(msg, opts);
if (wktJson !== undefined)
return wktJson;
const json = {};
for (const f of msg.sortedFields) {
if (!msg.isSet(f)) {
if (f.presence == LEGACY_REQUIRED) {
throw new Error(`cannot encode ${f} to JSON: required field not set`);
}
if (!opts.alwaysEmitImplicit || f.presence !== IMPLICIT) {
// Fields with implicit presence omit zero values (e.g. empty string) by default
continue;
}
}
const jsonValue = fieldToJson(f, msg.get(f), opts);
if (jsonValue !== undefined) {
json[jsonName(f, opts)] = jsonValue;
}
}
if (opts.registry) {
const tagSeen = new Set();
for (const { no } of (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : []) {
// Same tag can appear multiple times, so we
// keep track and skip identical ones.
if (!tagSeen.has(no)) {
tagSeen.add(no);
const extension = opts.registry.getExtensionFor(msg.desc, no);
if (!extension) {
continue;
}
const value = (0, extensions_js_1.getExtension)(msg.message, extension);
const [container, field] = (0, extensions_js_1.createExtensionContainer)(extension, value);
const jsonValue = fieldToJson(field, container.get(field), opts);
if (jsonValue !== undefined) {
json[extension.jsonName] = jsonValue;
}
}
}
}
return json;
}
function fieldToJson(f, val, opts) {
switch (f.fieldKind) {
case "scalar":
return scalarToJson(f, val);
case "message":
return reflectToJson(val, opts);
case "enum":
return enumToJsonInternal(f.enum, val, opts.enumAsInteger);
case "list":
return listToJson(val, opts);
case "map":
return mapToJson(val, opts);
}
}
function mapToJson(map, opts) {
const f = map.field();
const jsonObj = {};
switch (f.mapKind) {
case "scalar":
for (const [entryKey, entryValue] of map) {
jsonObj[entryKey] = scalarToJson(f, entryValue);
}
break;
case "message":
for (const [entryKey, entryValue] of map) {
jsonObj[entryKey] = reflectToJson(entryValue, opts);
}
break;
case "enum":
for (const [entryKey, entryValue] of map) {
jsonObj[entryKey] = enumToJsonInternal(f.enum, entryValue, opts.enumAsInteger);
}
break;
}
return opts.alwaysEmitImplicit || map.size > 0 ? jsonObj : undefined;
}
function listToJson(list, opts) {
const f = list.field();
const jsonArr = [];
switch (f.listKind) {
case "scalar":
for (const item of list) {
jsonArr.push(scalarToJson(f, item));
}
break;
case "enum":
for (const item of list) {
jsonArr.push(enumToJsonInternal(f.enum, item, opts.enumAsInteger));
}
break;
case "message":
for (const item of list) {
jsonArr.push(reflectToJson(item, opts));
}
break;
}
return opts.alwaysEmitImplicit || jsonArr.length > 0 ? jsonArr : undefined;
}
function enumToJsonInternal(desc, value, enumAsInteger) {
var _a;
if (typeof value != "number") {
throw new Error(`cannot encode ${desc} to JSON: expected number, got ${(0, reflect_check_js_1.formatVal)(value)}`);
}
if (desc.typeName == "google.protobuf.NullValue") {
return null;
}
if (enumAsInteger) {
return value;
}
const val = desc.value[value];
return (_a = val === null || val === void 0 ? void 0 : val.name) !== null && _a !== void 0 ? _a : value; // if we don't know the enum value, just return the number
}
function scalarToJson(field, value) {
var _a, _b, _c, _d, _e, _f;
switch (field.scalar) {
// int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
if (typeof value != "number") {
throw new Error(`cannot encode ${field} to JSON: ${(_a = (0, reflect_check_js_1.checkField)(field, value)) === null || _a === void 0 ? void 0 : _a.message}`);
}
return value;
// float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
// Either numbers or strings are accepted. Exponent notation is also accepted.
case descriptors_js_1.ScalarType.FLOAT:
case descriptors_js_1.ScalarType.DOUBLE: // eslint-disable-line no-fallthrough
if (typeof value != "number") {
throw new Error(`cannot encode ${field} to JSON: ${(_b = (0, reflect_check_js_1.checkField)(field, value)) === null || _b === void 0 ? void 0 : _b.message}`);
}
if (Number.isNaN(value))
return "NaN";
if (value === Number.POSITIVE_INFINITY)
return "Infinity";
if (value === Number.NEGATIVE_INFINITY)
return "-Infinity";
return value;
// string:
case descriptors_js_1.ScalarType.STRING:
if (typeof value != "string") {
throw new Error(`cannot encode ${field} to JSON: ${(_c = (0, reflect_check_js_1.checkField)(field, value)) === null || _c === void 0 ? void 0 : _c.message}`);
}
return value;
// bool:
case descriptors_js_1.ScalarType.BOOL:
if (typeof value != "boolean") {
throw new Error(`cannot encode ${field} to JSON: ${(_d = (0, reflect_check_js_1.checkField)(field, value)) === null || _d === void 0 ? void 0 : _d.message}`);
}
return value;
// JSON value will be a decimal string. Either numbers or strings are accepted.
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
if (typeof value == "bigint" ||
typeof value == "string" ||
(typeof value == "number" && Number.isInteger(value))) {
return value.toString();
}
throw new Error(`cannot encode ${field} to JSON: ${(_e = (0, reflect_check_js_1.checkField)(field, value)) === null || _e === void 0 ? void 0 : _e.message}`);
// bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
// Either standard or URL-safe base64 encoding with/without paddings are accepted.
case descriptors_js_1.ScalarType.BYTES:
if (value instanceof Uint8Array) {
return (0, index_js_2.base64Encode)(value);
}
throw new Error(`cannot encode ${field} to JSON: ${(_f = (0, reflect_check_js_1.checkField)(field, value)) === null || _f === void 0 ? void 0 : _f.message}`);
}
}
function jsonName(f, opts) {
return opts.useProtoFieldName ? f.name : f.jsonName;
}
// returns a json value if wkt, otherwise returns undefined.
function tryWktToJson(msg, opts) {
if (!msg.desc.typeName.startsWith("google.protobuf.")) {
return undefined;
}
switch (msg.desc.typeName) {
case "google.protobuf.Any":
return anyToJson(msg.message, opts);
case "google.protobuf.Timestamp":
return timestampToJson(msg.message);
case "google.protobuf.Duration":
return durationToJson(msg.message);
case "google.protobuf.FieldMask":
return fieldMaskToJson(msg.message);
case "google.protobuf.Struct":
return structToJson(msg.message);
case "google.protobuf.Value":
return valueToJson(msg.message);
case "google.protobuf.ListValue":
return listValueToJson(msg.message);
default:
if ((0, wrappers_js_1.isWrapperDesc)(msg.desc)) {
const valueField = msg.desc.fields[0];
return scalarToJson(valueField, msg.get(valueField));
}
return undefined;
}
}
function anyToJson(val, opts) {
if (val.typeUrl === "") {
return {};
}
const { registry } = opts;
let message;
let desc;
if (registry) {
message = (0, index_js_1.anyUnpack)(val, registry);
if (message) {
desc = registry.getMessage(message.$typeName);
}
}
if (!desc || !message) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: "${val.typeUrl}" is not in the type registry`);
}
const reflected = (0, reflect_js_1.reflect)(desc, message);
const json = (0, wrappers_js_1.hasCustomJsonRepresentation)(desc)
? { value: tryWktToJson(reflected, opts) }
: reflectToJson(reflected, opts);
json["@type"] = val.typeUrl;
return json;
}
function durationToJson(val) {
const seconds = Number(val.seconds);
const nanos = val.nanos;
if (seconds > 315576000000 || seconds < -315576000000) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: value out of range`);
}
if ((seconds > 0 && nanos < 0) || (seconds < 0 && nanos > 0)) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos sign must match seconds sign`);
}
let text = val.seconds.toString();
if (nanos !== 0) {
let nanosStr = Math.abs(nanos).toString();
nanosStr = "0".repeat(9 - nanosStr.length) + nanosStr;
if (nanosStr.substring(3) === "000000") {
nanosStr = nanosStr.substring(0, 3);
}
else if (nanosStr.substring(6) === "000") {
nanosStr = nanosStr.substring(0, 6);
}
text += "." + nanosStr;
if (nanos < 0 && seconds == 0) {
text = "-" + text;
}
}
return text + "s";
}
function fieldMaskToJson(val) {
return val.paths
.map((p) => {
if ((0, names_js_1.protoSnakeCase)((0, names_js_1.protoCamelCase)(p)) !== p) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: lowerCamelCase of path name "${p}" is irreversible`);
}
return (0, names_js_1.protoCamelCase)(p);
})
.join(",");
}
function structToJson(val) {
const json = {};
for (const [k, v] of Object.entries(val.fields)) {
json[k] = valueToJson(v);
}
return json;
}
function valueToJson(val) {
switch (val.kind.case) {
case "nullValue":
return null;
case "numberValue":
if (!Number.isFinite(val.kind.value)) {
throw new Error(`${val.$typeName} cannot be NaN or Infinity`);
}
return val.kind.value;
case "boolValue":
return val.kind.value;
case "stringValue":
return val.kind.value;
case "structValue":
return structToJson(val.kind.value);
case "listValue":
return listValueToJson(val.kind.value);
default:
throw new Error(`${val.$typeName} must have a value`);
}
}
function listValueToJson(val) {
return val.values.map(valueToJson);
}
function timestampToJson(val) {
const ms = Number(val.seconds) * 1000;
if (ms < Date.parse("0001-01-01T00:00:00Z") ||
ms > Date.parse("9999-12-31T23:59:59Z")) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
}
if (val.nanos < 0) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be negative`);
}
if (val.nanos > 999999999) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be greater than 99999999`);
}
let z = "Z";
if (val.nanos > 0) {
const nanosStr = (val.nanos + 1000000000).toString().substring(1);
if (nanosStr.substring(3) === "000000") {
z = "." + nanosStr.substring(0, 3) + "Z";
}
else if (nanosStr.substring(6) === "000") {
z = "." + nanosStr.substring(0, 6) + "Z";
}
else {
z = "." + nanosStr + "Z";
}
}
return new Date(ms).toISOString().replace(".000Z", z);
}
import type { GenEnum as GenEnumV1, GenExtension as GenExtensionV1, GenMessage as GenMessageV1 } from "./codegenv1/types.js";
import type { GenEnum as GenEnumV2, GenExtension as GenExtensionV2, GenMessage as GenMessageV2 } from "./codegenv2/types.js";
import type { DescEnum, DescExtension, DescMessage, DescMethod } from "./descriptors.js";
import type { OneofADT } from "./reflect/guard.js";
import type { WireType } from "./wire/index.js";
import type { JsonValue } from "./json-value.js";
/**
* The type `Message` contains the properties shared by all messages.
*/
export type Message<TypeName extends string = string> = {
/**
* The fully qualified Protobuf type-name of the message.
*/
readonly $typeName: TypeName;
/**
* Unknown fields and extensions stored on the message.
*/
$unknown?: UnknownField[] | undefined;
};
/**
* Extract the message type from a message descriptor.
*/
export type MessageShape<Desc extends DescMessage> = Desc extends GenMessageV1<infer RuntimeShapeV1> ? RuntimeShapeV1 : Desc extends GenMessageV2<infer RuntimeShape> ? RuntimeShape : Message;
/**
* Extract the message JSON type from a message descriptor.
*
* JSON types are only available for code generated with the plugin option
* `json_types=true`. If JSON types are unavailable, this type falls back to the
* `JsonValue` type.
*/
export type MessageJsonType<Desc extends DescMessage> = Desc extends GenMessageV1<Message, infer JsonTypeV1 extends JsonValue> ? JsonTypeV1 : Desc extends GenMessageV2<Message, {
jsonType: infer JsonType extends JsonValue;
}> ? JsonType : JsonValue;
/**
* Extract the message Valid type from a message descriptor.
*
* Valid types are only available for code generated with the plugin option
* `valid_types`. If Valid types are unavailable, this type falls back to the
* regular message shape.
*/
export type MessageValidType<Desc extends DescMessage> = Desc extends GenMessageV1<infer RuntimeShapeV1> ? RuntimeShapeV1 : Desc extends GenMessageV2<Message, {
validType: infer ValidType extends Message;
}> ? ValidType : Desc extends GenMessageV2<infer RuntimeShape> ? RuntimeShape : Message;
/**
* Extract the init type from a message descriptor.
* The init type is accepted by the function create().
*/
export type MessageInitShape<Desc extends DescMessage> = Desc extends GenMessageV1<infer RuntimeShape> ? MessageInit<RuntimeShape> : Desc extends GenMessageV2<infer RuntimeShape> ? MessageInit<RuntimeShape> : Record<string, unknown>;
/**
* Extract the enum type of from an enum descriptor.
*/
export type EnumShape<Desc extends DescEnum> = Desc extends GenEnumV1<infer RuntimeShape> ? RuntimeShape : Desc extends GenEnumV2<infer RuntimeShape> ? RuntimeShape : number;
/**
* Extract the enum JSON type from a enum descriptor.
*/
export type EnumJsonType<Desc extends DescEnum> = Desc extends GenEnumV1<number, infer JsonType> ? JsonType : Desc extends GenEnumV2<number, infer JsonType> ? JsonType : string | null;
/**
* Extract the value type from an extension descriptor.
*/
export type ExtensionValueShape<Desc extends DescExtension> = Desc extends GenExtensionV1<Message, infer RuntimeShape> ? RuntimeShape : Desc extends GenExtensionV2<Message, infer RuntimeShape> ? RuntimeShape : unknown;
/**
* Extract the type of the extended message from an extension descriptor.
*/
export type Extendee<Desc extends DescExtension> = Desc extends GenExtensionV1<infer Extendee> ? Extendee : Desc extends GenExtensionV2<infer Extendee> ? Extendee : Message;
/**
* Unknown fields are fields that were not recognized during parsing, or
* extension.
*/
export type UnknownField = {
readonly no: number;
readonly wireType: WireType;
readonly data: Uint8Array;
};
/**
* Describes a streaming RPC declaration.
*/
export type DescMethodStreaming<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodClientStreaming<I, O> | DescMethodServerStreaming<I, O> | DescMethodBiDiStreaming<I, O>;
/**
* Describes a unary RPC declaration.
*/
export type DescMethodUnary<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodTyped<"unary", I, O>;
/**
* Describes a server streaming RPC declaration.
*/
export type DescMethodServerStreaming<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodTyped<"server_streaming", I, O>;
/**
* Describes a client streaming RPC declaration.
*/
export type DescMethodClientStreaming<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodTyped<"client_streaming", I, O>;
/**
* Describes a bidi streaming RPC declaration.
*/
export type DescMethodBiDiStreaming<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodTyped<"bidi_streaming", I, O>;
/**
* The init type for a message, which makes all fields optional.
* The init type is accepted by the function create().
*/
type MessageInit<T extends Message> = T | {
[P in keyof T as P extends "$unknown" ? never : P]?: P extends "$typeName" ? never : FieldInit<T[P]>;
};
type FieldInit<F> = F extends (Date | Uint8Array | bigint | boolean | string | number) ? F : F extends Array<infer U> ? Array<FieldInit<U>> : F extends ReadonlyArray<infer U> ? ReadonlyArray<FieldInit<U>> : F extends Message ? MessageInit<F> : F extends OneofSelectedMessage<infer C, infer V> ? {
case: C;
value: MessageInit<V>;
} : F extends OneofADT ? F : F extends MapWithMessage<infer V> ? {
[key: string | number]: MessageInit<V>;
} : F;
type MapWithMessage<V extends Message> = {
[key: string | number]: V;
};
type OneofSelectedMessage<K extends string, M extends Message> = {
case: K;
value: M;
};
type DescMethodTyped<K extends DescMethod["methodKind"], I extends DescMessage, O extends DescMessage> = Omit<DescMethod, "methodKind" | "input" | "output"> & {
/**
* One of the four available method types.
*/
readonly methodKind: K;
/**
* The message type for requests.
*/
readonly input: I;
/**
* The message type for responses.
*/
readonly output: O;
};
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Decodes a base64 string to a byte array.
*
* - ignores white-space, including line breaks and tabs
* - allows inner padding (can decode concatenated base64 strings)
* - does not require padding
* - understands base64url encoding:
* "-" instead of "+",
* "_" instead of "/",
* no padding
*/
export declare function base64Decode(base64Str: string): Uint8Array<ArrayBuffer>;
/**
* Encode a byte array to a base64 string.
*
* By default, this function uses the standard base64 encoding with padding.
*
* To encode without padding, use encoding = "std_raw".
*
* To encode with the URL encoding, use encoding = "url", which replaces the
* characters +/ by their URL-safe counterparts -_, and omits padding.
*/
export declare function base64Encode(bytes: Uint8Array, encoding?: "std" | "std_raw" | "url"): string;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.base64Decode = base64Decode;
exports.base64Encode = base64Encode;
/**
* Decodes a base64 string to a byte array.
*
* - ignores white-space, including line breaks and tabs
* - allows inner padding (can decode concatenated base64 strings)
* - does not require padding
* - understands base64url encoding:
* "-" instead of "+",
* "_" instead of "/",
* no padding
*/
function base64Decode(base64Str) {
const table = getDecodeTable();
// estimate byte size, not accounting for inner padding and whitespace
let es = (base64Str.length * 3) / 4;
if (base64Str[base64Str.length - 2] == "=")
es -= 2;
else if (base64Str[base64Str.length - 1] == "=")
es -= 1;
let bytes = new Uint8Array(es), bytePos = 0, // position in byte array
groupPos = 0, // position in base64 group
b, // current byte
p = 0; // previous byte
for (let i = 0; i < base64Str.length; i++) {
b = table[base64Str.charCodeAt(i)];
if (b === undefined) {
switch (base64Str[i]) {
// @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true
case "=":
groupPos = 0; // reset state when padding found
case "\n":
case "\r":
case "\t":
case " ":
continue; // skip white-space, and padding
default:
throw Error("invalid base64 string");
}
}
switch (groupPos) {
case 0:
p = b;
groupPos = 1;
break;
case 1:
bytes[bytePos++] = (p << 2) | ((b & 48) >> 4);
p = b;
groupPos = 2;
break;
case 2:
bytes[bytePos++] = ((p & 15) << 4) | ((b & 60) >> 2);
p = b;
groupPos = 3;
break;
case 3:
bytes[bytePos++] = ((p & 3) << 6) | b;
groupPos = 0;
break;
}
}
if (groupPos == 1)
throw Error("invalid base64 string");
return bytes.subarray(0, bytePos);
}
/**
* Encode a byte array to a base64 string.
*
* By default, this function uses the standard base64 encoding with padding.
*
* To encode without padding, use encoding = "std_raw".
*
* To encode with the URL encoding, use encoding = "url", which replaces the
* characters +/ by their URL-safe counterparts -_, and omits padding.
*/
function base64Encode(bytes, encoding = "std") {
const table = getEncodeTable(encoding);
const pad = encoding == "std";
let base64 = "", groupPos = 0, // position in base64 group
b, // current byte
p = 0; // carry over from previous byte
for (let i = 0; i < bytes.length; i++) {
b = bytes[i];
switch (groupPos) {
case 0:
base64 += table[b >> 2];
p = (b & 3) << 4;
groupPos = 1;
break;
case 1:
base64 += table[p | (b >> 4)];
p = (b & 15) << 2;
groupPos = 2;
break;
case 2:
base64 += table[p | (b >> 6)];
base64 += table[b & 63];
groupPos = 0;
break;
}
}
// add output padding
if (groupPos) {
base64 += table[p];
if (pad) {
base64 += "=";
if (groupPos == 1)
base64 += "=";
}
}
return base64;
}
// lookup table from base64 character to byte
let encodeTableStd;
let encodeTableUrl;
// lookup table from base64 character *code* to byte because lookup by number is fast
let decodeTable;
function getEncodeTable(encoding) {
if (!encodeTableStd) {
encodeTableStd =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
encodeTableUrl = encodeTableStd.slice(0, -2).concat("-", "_");
}
return encoding == "url"
? // biome-ignore lint/style/noNonNullAssertion: TS fails to narrow down
encodeTableUrl
: encodeTableStd;
}
function getDecodeTable() {
if (!decodeTable) {
decodeTable = [];
const encodeTable = getEncodeTable("std");
for (let i = 0; i < encodeTable.length; i++)
decodeTable[encodeTable[i].charCodeAt(0)] = i;
// support base64url variants
decodeTable["-".charCodeAt(0)] = encodeTable.indexOf("+");
decodeTable["_".charCodeAt(0)] = encodeTable.indexOf("/");
}
return decodeTable;
}
/**
* Protobuf binary format wire types.
*
* A wire type provides just enough information to find the length of the
* following value.
*
* See https://developers.google.com/protocol-buffers/docs/encoding#structure
*/
export declare enum WireType {
/**
* Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
*/
Varint = 0,
/**
* Used for fixed64, sfixed64, double.
* Always 8 bytes with little-endian byte order.
*/
Bit64 = 1,
/**
* Used for string, bytes, embedded messages, packed repeated fields
*
* Only repeated numeric types (types which use the varint, 32-bit,
* or 64-bit wire types) can be packed. In proto3, such fields are
* packed by default.
*/
LengthDelimited = 2,
/**
* Start of a tag-delimited aggregate, such as a proto2 group, or a message
* in editions with message_encoding = DELIMITED.
*/
StartGroup = 3,
/**
* End of a tag-delimited aggregate.
*/
EndGroup = 4,
/**
* Used for fixed32, sfixed32, float.
* Always 4 bytes with little-endian byte order.
*/
Bit32 = 5
}
/**
* Maximum value for a 32-bit floating point value (Protobuf FLOAT).
*/
export declare const FLOAT32_MAX = 3.4028234663852886e+38;
/**
* Minimum value for a 32-bit floating point value (Protobuf FLOAT).
*/
export declare const FLOAT32_MIN = -3.4028234663852886e+38;
/**
* Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).
*/
export declare const UINT32_MAX = 4294967295;
/**
* Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
export declare const INT32_MAX = 2147483647;
/**
* Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
export declare const INT32_MIN = -2147483648;
export declare class BinaryWriter {
private readonly encodeUtf8;
/**
* We cannot allocate a buffer for the entire output
* because we don't know its size.
*
* So we collect smaller chunks of known size and
* concat them later.
*
* Use `raw()` to push data to this array. It will flush
* `buf` first.
*/
private chunks;
/**
* A growing buffer for byte values. If you don't know
* the size of the data you are writing, push to this
* array.
*/
protected buf: number[];
/**
* Previous fork states.
*/
private stack;
constructor(encodeUtf8?: (text: string) => Uint8Array);
/**
* Return all bytes written and reset this writer.
*/
finish(): Uint8Array<ArrayBuffer>;
/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
*/
fork(): this;
/**
* Join the last fork. Write its length and bytes, then
* return to the previous state.
*/
join(): this;
/**
* Writes a tag (field number and wire type).
*
* Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
*
* Generated code should compute the tag ahead of time and call `uint32()`.
*/
tag(fieldNo: number, type: WireType): this;
/**
* Write a chunk of raw bytes.
*/
raw(chunk: Uint8Array): this;
/**
* Write a `uint32` value, an unsigned 32 bit varint.
*/
uint32(value: number): this;
/**
* Write a `int32` value, a signed 32 bit varint.
*/
int32(value: number): this;
/**
* Write a `bool` value, a varint.
*/
bool(value: boolean): this;
/**
* Write a `bytes` value, length-delimited arbitrary data.
*/
bytes(value: Uint8Array): this;
/**
* Write a `string` value, length-delimited data converted to UTF-8 text.
*/
string(value: string): this;
/**
* Write a `float` value, 32-bit floating point number.
*/
float(value: number): this;
/**
* Write a `double` value, a 64-bit floating point number.
*/
double(value: number): this;
/**
* Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
*/
fixed32(value: number): this;
/**
* Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
*/
sfixed32(value: number): this;
/**
* Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
*/
sint32(value: number): this;
/**
* Write a `sfixed64` value, a signed, fixed-length 64-bit integer.
*/
sfixed64(value: string | number | bigint): this;
/**
* Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
*/
fixed64(value: string | number | bigint): this;
/**
* Write a `int64` value, a signed 64-bit varint.
*/
int64(value: string | number | bigint): this;
/**
* Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(value: string | number | bigint): this;
/**
* Write a `uint64` value, an unsigned 64-bit varint.
*/
uint64(value: string | number | bigint): this;
}
export declare class BinaryReader {
private readonly decodeUtf8;
/**
* Current position.
*/
pos: number;
/**
* Number of bytes available in this reader.
*/
readonly len: number;
protected readonly buf: Uint8Array;
private readonly view;
constructor(buf: Uint8Array, decodeUtf8?: (bytes: Uint8Array, strict?: boolean) => string);
/**
* Reads a tag - field number and wire type. Tags are uint32 varints; values
* that do not fit in uint32 are rejected.
*/
tag(): [number, WireType];
/**
* Skip one element and return the skipped data.
*
* When skipping StartGroup, provide the tags field number to check for
* matching field number in the EndGroup tag. Recursion into nested groups
* is guarded by the `recursionLimit` argument: When the limit is reached,
* this method throws.
*/
skip(wireType: WireType, fieldNo?: number, recursionLimit?: number): Uint8Array;
protected varint64: () => [number, number];
/**
* Throws error if position in byte array is out of range.
*/
protected assertBounds(): void;
/**
* Read a `uint32` field, an unsigned 32 bit varint.
*/
uint32: () => number;
/**
* Read a `int32` field, a signed 32 bit varint.
*/
int32(): number;
/**
* Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
*/
sint32(): number;
/**
* Read a `int64` field, a signed 64-bit varint.
*/
int64(): bigint | string;
/**
* Read a `uint64` field, an unsigned 64-bit varint.
*/
uint64(): bigint | string;
/**
* Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(): bigint | string;
/**
* Read a `bool` field, a variant.
*/
bool(): boolean;
/**
* Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
*/
fixed32(): number;
/**
* Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
*/
sfixed32(): number;
/**
* Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
*/
fixed64(): bigint | string;
/**
* Read a `fixed64` field, a signed, fixed-length 64-bit integer.
*/
sfixed64(): bigint | string;
/**
* Read a `float` field, 32-bit floating point number.
*/
float(): number;
/**
* Read a `double` field, a 64-bit floating point number.
*/
double(): number;
/**
* Read a `bytes` field, length-delimited arbitrary data.
*/
bytes(): Uint8Array;
/**
* Read a `string` field, length-delimited data converted to UTF-8 text. If
* `strict` is true, throw on invalid UTF-8 instead of substituting U+FFFD.
*/
string(strict?: boolean): string;
}
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinaryReader = exports.BinaryWriter = exports.INT32_MIN = exports.INT32_MAX = exports.UINT32_MAX = exports.FLOAT32_MIN = exports.FLOAT32_MAX = exports.WireType = void 0;
const varint_js_1 = require("./varint.js");
const proto_int64_js_1 = require("../proto-int64.js");
const text_encoding_js_1 = require("./text-encoding.js");
/**
* Protobuf binary format wire types.
*
* A wire type provides just enough information to find the length of the
* following value.
*
* See https://developers.google.com/protocol-buffers/docs/encoding#structure
*/
var WireType;
(function (WireType) {
/**
* Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
*/
WireType[WireType["Varint"] = 0] = "Varint";
/**
* Used for fixed64, sfixed64, double.
* Always 8 bytes with little-endian byte order.
*/
WireType[WireType["Bit64"] = 1] = "Bit64";
/**
* Used for string, bytes, embedded messages, packed repeated fields
*
* Only repeated numeric types (types which use the varint, 32-bit,
* or 64-bit wire types) can be packed. In proto3, such fields are
* packed by default.
*/
WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited";
/**
* Start of a tag-delimited aggregate, such as a proto2 group, or a message
* in editions with message_encoding = DELIMITED.
*/
WireType[WireType["StartGroup"] = 3] = "StartGroup";
/**
* End of a tag-delimited aggregate.
*/
WireType[WireType["EndGroup"] = 4] = "EndGroup";
/**
* Used for fixed32, sfixed32, float.
* Always 4 bytes with little-endian byte order.
*/
WireType[WireType["Bit32"] = 5] = "Bit32";
})(WireType || (exports.WireType = WireType = {}));
/**
* Maximum value for a 32-bit floating point value (Protobuf FLOAT).
*/
exports.FLOAT32_MAX = 3.4028234663852886e38;
/**
* Minimum value for a 32-bit floating point value (Protobuf FLOAT).
*/
exports.FLOAT32_MIN = -3.4028234663852886e38;
/**
* Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).
*/
exports.UINT32_MAX = 0xffffffff;
/**
* Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
exports.INT32_MAX = 0x7fffffff;
/**
* Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
exports.INT32_MIN = -0x80000000;
class BinaryWriter {
constructor(encodeUtf8 = (0, text_encoding_js_1.getTextEncoding)().encodeUtf8) {
this.encodeUtf8 = encodeUtf8;
/**
* Previous fork states.
*/
this.stack = [];
this.chunks = [];
this.buf = [];
}
/**
* Return all bytes written and reset this writer.
*/
finish() {
if (this.buf.length) {
this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
this.buf = [];
}
let len = 0;
for (let i = 0; i < this.chunks.length; i++)
len += this.chunks[i].length;
let bytes = new Uint8Array(len);
let offset = 0;
for (let i = 0; i < this.chunks.length; i++) {
bytes.set(this.chunks[i], offset);
offset += this.chunks[i].length;
}
this.chunks = [];
return bytes;
}
/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
*/
fork() {
this.stack.push({ chunks: this.chunks, buf: this.buf });
this.chunks = [];
this.buf = [];
return this;
}
/**
* Join the last fork. Write its length and bytes, then
* return to the previous state.
*/
join() {
// get chunk of fork
let chunk = this.finish();
// restore previous state
let prev = this.stack.pop();
if (!prev)
throw new Error("invalid state, fork stack empty");
this.chunks = prev.chunks;
this.buf = prev.buf;
// write length of chunk as varint
this.uint32(chunk.byteLength);
return this.raw(chunk);
}
/**
* Writes a tag (field number and wire type).
*
* Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
*
* Generated code should compute the tag ahead of time and call `uint32()`.
*/
tag(fieldNo, type) {
return this.uint32(((fieldNo << 3) | type) >>> 0);
}
/**
* Write a chunk of raw bytes.
*/
raw(chunk) {
if (this.buf.length) {
this.chunks.push(new Uint8Array(this.buf));
this.buf = [];
}
this.chunks.push(chunk);
return this;
}
/**
* Write a `uint32` value, an unsigned 32 bit varint.
*/
uint32(value) {
assertUInt32(value);
// write value as varint 32, inlined for speed
while (value > 0x7f) {
this.buf.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
this.buf.push(value);
return this;
}
/**
* Write a `int32` value, a signed 32 bit varint.
*/
int32(value) {
assertInt32(value);
(0, varint_js_1.varint32write)(value, this.buf);
return this;
}
/**
* Write a `bool` value, a varint.
*/
bool(value) {
this.buf.push(value ? 1 : 0);
return this;
}
/**
* Write a `bytes` value, length-delimited arbitrary data.
*/
bytes(value) {
this.uint32(value.byteLength); // write length of chunk as varint
return this.raw(value);
}
/**
* Write a `string` value, length-delimited data converted to UTF-8 text.
*/
string(value) {
let chunk = this.encodeUtf8(value);
this.uint32(chunk.byteLength); // write length of chunk as varint
return this.raw(chunk);
}
/**
* Write a `float` value, 32-bit floating point number.
*/
float(value) {
assertFloat32(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setFloat32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `double` value, a 64-bit floating point number.
*/
double(value) {
let chunk = new Uint8Array(8);
new DataView(chunk.buffer).setFloat64(0, value, true);
return this.raw(chunk);
}
/**
* Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
*/
fixed32(value) {
assertUInt32(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setUint32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
*/
sfixed32(value) {
assertInt32(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setInt32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
*/
sint32(value) {
assertInt32(value);
// zigzag encode
value = ((value << 1) ^ (value >> 31)) >>> 0;
(0, varint_js_1.varint32write)(value, this.buf);
return this;
}
/**
* Write a `sfixed64` value, a signed, fixed-length 64-bit integer.
*/
sfixed64(value) {
let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = proto_int64_js_1.protoInt64.enc(value);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
return this.raw(chunk);
}
/**
* Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
*/
fixed64(value) {
let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = proto_int64_js_1.protoInt64.uEnc(value);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
return this.raw(chunk);
}
/**
* Write a `int64` value, a signed 64-bit varint.
*/
int64(value) {
let tc = proto_int64_js_1.protoInt64.enc(value);
(0, varint_js_1.varint64write)(tc.lo, tc.hi, this.buf);
return this;
}
/**
* Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(value) {
const tc = proto_int64_js_1.protoInt64.enc(value),
// zigzag encode
sign = tc.hi >> 31, lo = (tc.lo << 1) ^ sign, hi = ((tc.hi << 1) | (tc.lo >>> 31)) ^ sign;
(0, varint_js_1.varint64write)(lo, hi, this.buf);
return this;
}
/**
* Write a `uint64` value, an unsigned 64-bit varint.
*/
uint64(value) {
const tc = proto_int64_js_1.protoInt64.uEnc(value);
(0, varint_js_1.varint64write)(tc.lo, tc.hi, this.buf);
return this;
}
}
exports.BinaryWriter = BinaryWriter;
class BinaryReader {
constructor(buf, decodeUtf8 = (0, text_encoding_js_1.getTextEncoding)().decodeUtf8) {
this.decodeUtf8 = decodeUtf8;
this.varint64 = varint_js_1.varint64read; // dirty cast for `this`
/**
* Read a `uint32` field, an unsigned 32 bit varint.
*/
this.uint32 = varint_js_1.varint32read;
this.buf = buf;
this.len = buf.length;
this.pos = 0;
this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
}
/**
* Reads a tag - field number and wire type. Tags are uint32 varints; values
* that do not fit in uint32 are rejected.
*/
tag() {
const start = this.pos;
const tag = this.uint32();
const bytesRead = this.pos - start;
if (bytesRead > 5 || (bytesRead == 5 && this.buf[this.pos - 1] > 0x0f)) {
throw new Error("illegal tag: varint overflows uint32");
}
const fieldNo = tag >>> 3;
const wireType = tag & 7;
if (fieldNo <= 0 || wireType > 5) {
throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
}
return [fieldNo, wireType];
}
/**
* Skip one element and return the skipped data.
*
* When skipping StartGroup, provide the tags field number to check for
* matching field number in the EndGroup tag. Recursion into nested groups
* is guarded by the `recursionLimit` argument: When the limit is reached,
* this method throws.
*/
skip(wireType, fieldNo, recursionLimit = 100) {
let start = this.pos;
switch (wireType) {
case WireType.Varint:
while (this.buf[this.pos++] & 0x80) {
// ignore
}
break;
// @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true
case WireType.Bit64:
this.pos += 4;
case WireType.Bit32:
this.pos += 4;
break;
case WireType.LengthDelimited:
let len = this.uint32();
this.pos += len;
break;
case WireType.StartGroup:
if (recursionLimit <= 0) {
throw new Error("maximum recursion depth reached");
}
for (;;) {
const [fn, wt] = this.tag();
if (wt === WireType.EndGroup) {
if (fieldNo !== undefined && fn !== fieldNo) {
throw new Error("invalid end group tag");
}
break;
}
this.skip(wt, fn, recursionLimit - 1);
}
break;
default:
throw new Error("cant skip wire type " + wireType);
}
this.assertBounds();
return this.buf.subarray(start, this.pos);
}
/**
* Throws error if position in byte array is out of range.
*/
assertBounds() {
if (this.pos > this.len)
throw new RangeError("premature EOF");
}
/**
* Read a `int32` field, a signed 32 bit varint.
*/
int32() {
return this.uint32() | 0;
}
/**
* Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
*/
sint32() {
let zze = this.uint32();
// decode zigzag
return (zze >>> 1) ^ -(zze & 1);
}
/**
* Read a `int64` field, a signed 64-bit varint.
*/
int64() {
return proto_int64_js_1.protoInt64.dec(...this.varint64());
}
/**
* Read a `uint64` field, an unsigned 64-bit varint.
*/
uint64() {
return proto_int64_js_1.protoInt64.uDec(...this.varint64());
}
/**
* Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
*/
sint64() {
let [lo, hi] = this.varint64();
// decode zig zag
let s = -(lo & 1);
lo = ((lo >>> 1) | ((hi & 1) << 31)) ^ s;
hi = (hi >>> 1) ^ s;
return proto_int64_js_1.protoInt64.dec(lo, hi);
}
/**
* Read a `bool` field, a variant.
*/
bool() {
let [lo, hi] = this.varint64();
return lo !== 0 || hi !== 0;
}
/**
* Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
*/
fixed32() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getUint32((this.pos += 4) - 4, true);
}
/**
* Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
*/
sfixed32() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getInt32((this.pos += 4) - 4, true);
}
/**
* Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
*/
fixed64() {
return proto_int64_js_1.protoInt64.uDec(this.sfixed32(), this.sfixed32());
}
/**
* Read a `fixed64` field, a signed, fixed-length 64-bit integer.
*/
sfixed64() {
return proto_int64_js_1.protoInt64.dec(this.sfixed32(), this.sfixed32());
}
/**
* Read a `float` field, 32-bit floating point number.
*/
float() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getFloat32((this.pos += 4) - 4, true);
}
/**
* Read a `double` field, a 64-bit floating point number.
*/
double() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getFloat64((this.pos += 8) - 8, true);
}
/**
* Read a `bytes` field, length-delimited arbitrary data.
*/
bytes() {
let len = this.uint32(), start = this.pos;
this.pos += len;
this.assertBounds();
return this.buf.subarray(start, start + len);
}
/**
* Read a `string` field, length-delimited data converted to UTF-8 text. If
* `strict` is true, throw on invalid UTF-8 instead of substituting U+FFFD.
*/
string(strict) {
return this.decodeUtf8(this.bytes(), strict);
}
}
exports.BinaryReader = BinaryReader;
/**
* Assert a valid signed protobuf 32-bit integer as a number or string.
*/
function assertInt32(arg) {
if (typeof arg == "string") {
arg = Number(arg);
}
else if (typeof arg != "number") {
throw new Error("invalid int32: " + typeof arg);
}
if (!Number.isInteger(arg) ||
arg > exports.INT32_MAX ||
arg < exports.INT32_MIN)
throw new Error("invalid int32: " + arg);
}
/**
* Assert a valid unsigned protobuf 32-bit integer as a number or string.
*/
function assertUInt32(arg) {
if (typeof arg == "string") {
arg = Number(arg);
}
else if (typeof arg != "number") {
throw new Error("invalid uint32: " + typeof arg);
}
if (!Number.isInteger(arg) ||
arg > exports.UINT32_MAX ||
arg < 0)
throw new Error("invalid uint32: " + arg);
}
/**
* Assert a valid protobuf float value as a number or string.
*/
function assertFloat32(arg) {
if (typeof arg == "string") {
const o = arg;
arg = Number(arg);
if (Number.isNaN(arg) && o !== "NaN") {
throw new Error("invalid float32: " + o);
}
}
else if (typeof arg != "number") {
throw new Error("invalid float32: " + typeof arg);
}
if (Number.isFinite(arg) &&
(arg > exports.FLOAT32_MAX || arg < exports.FLOAT32_MIN))
throw new Error("invalid float32: " + arg);
}
export * from "./binary-encoding.js";
export * from "./base64-encoding.js";
export * from "./text-encoding.js";
export * from "./text-format.js";
export * from "./size-delimited.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./binary-encoding.js"), exports);
__exportStar(require("./base64-encoding.js"), exports);
__exportStar(require("./text-encoding.js"), exports);
__exportStar(require("./text-format.js"), exports);
__exportStar(require("./size-delimited.js"), exports);
import type { DescMessage } from "../descriptors.js";
import type { BinaryWriteOptions } from "../to-binary.js";
import type { MessageShape } from "../types.js";
import type { BinaryReadOptions } from "../from-binary.js";
/**
* Serialize a message, prefixing it with its size.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
export declare function sizeDelimitedEncode<Desc extends DescMessage>(messageDesc: Desc, message: MessageShape<Desc>, options?: BinaryWriteOptions): Uint8Array;
/**
* Parse a stream of size-delimited messages.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
export declare function sizeDelimitedDecodeStream<Desc extends DescMessage>(messageDesc: Desc, iterable: AsyncIterable<Uint8Array>, options?: Partial<BinaryReadOptions>): AsyncIterableIterator<MessageShape<Desc>>;
/**
* Decodes the size from the given size-delimited message, which may be
* incomplete.
*
* Returns an object with the following properties:
* - size: The size of the delimited message in bytes
* - offset: The offset in the given byte array where the message starts
* - eof: true
*
* If the size-delimited data does not include all bytes of the varint size,
* the following object is returned:
* - size: null
* - offset: null
* - eof: false
*
* This function can be used to implement parsing of size-delimited messages
* from a stream.
*/
export declare function sizeDelimitedPeek(data: Uint8Array): {
readonly eof: false;
readonly size: number;
readonly offset: number;
} | {
readonly eof: true;
readonly size: null;
readonly offset: null;
};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sizeDelimitedEncode = sizeDelimitedEncode;
exports.sizeDelimitedDecodeStream = sizeDelimitedDecodeStream;
exports.sizeDelimitedPeek = sizeDelimitedPeek;
const to_binary_js_1 = require("../to-binary.js");
const binary_encoding_js_1 = require("./binary-encoding.js");
const from_binary_js_1 = require("../from-binary.js");
/**
* Serialize a message, prefixing it with its size.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
function sizeDelimitedEncode(messageDesc, message, options) {
const writer = new binary_encoding_js_1.BinaryWriter();
writer.bytes((0, to_binary_js_1.toBinary)(messageDesc, message, options));
return writer.finish();
}
/**
* Parse a stream of size-delimited messages.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
function sizeDelimitedDecodeStream(messageDesc, iterable, options) {
return __asyncGenerator(this, arguments, function* sizeDelimitedDecodeStream_1() {
var _a, e_1, _b, _c;
// append chunk to buffer, returning updated buffer
function append(buffer, chunk) {
const n = new Uint8Array(buffer.byteLength + chunk.byteLength);
n.set(buffer);
n.set(chunk, buffer.length);
return n;
}
let buffer = new Uint8Array(0);
try {
for (var _d = true, iterable_1 = __asyncValues(iterable), iterable_1_1; iterable_1_1 = yield __await(iterable_1.next()), _a = iterable_1_1.done, !_a; _d = true) {
_c = iterable_1_1.value;
_d = false;
const chunk = _c;
buffer = append(buffer, chunk);
for (;;) {
const size = sizeDelimitedPeek(buffer);
if (size.eof) {
// size is incomplete, buffer more data
break;
}
if (size.offset + size.size > buffer.byteLength) {
// message is incomplete, buffer more data
break;
}
yield yield __await((0, from_binary_js_1.fromBinary)(messageDesc, buffer.subarray(size.offset, size.offset + size.size), options));
buffer = buffer.subarray(size.offset + size.size);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = iterable_1.return)) yield __await(_b.call(iterable_1));
}
finally { if (e_1) throw e_1.error; }
}
if (buffer.byteLength > 0) {
throw new Error("incomplete data");
}
});
}
/**
* Decodes the size from the given size-delimited message, which may be
* incomplete.
*
* Returns an object with the following properties:
* - size: The size of the delimited message in bytes
* - offset: The offset in the given byte array where the message starts
* - eof: true
*
* If the size-delimited data does not include all bytes of the varint size,
* the following object is returned:
* - size: null
* - offset: null
* - eof: false
*
* This function can be used to implement parsing of size-delimited messages
* from a stream.
*/
function sizeDelimitedPeek(data) {
const sizeEof = { eof: true, size: null, offset: null };
for (let i = 0; i < 10; i++) {
if (i > data.byteLength) {
return sizeEof;
}
if ((data[i] & 0x80) == 0) {
const reader = new binary_encoding_js_1.BinaryReader(data);
let size;
try {
size = reader.uint32();
}
catch (e) {
if (e instanceof RangeError) {
return sizeEof;
}
throw e;
}
return {
eof: false,
size,
offset: reader.pos,
};
}
}
throw new Error("invalid varint");
}
interface TextEncoding {
/**
* Verify that the given text is valid UTF-8.
*/
checkUtf8: (text: string) => boolean;
/**
* Encode UTF-8 text to binary.
*/
encodeUtf8: (text: string) => Uint8Array<ArrayBuffer>;
/**
* Decode UTF-8 text from binary. If `strict` is true, throw on invalid byte
* sequences instead of silently substituting U+FFFD. Implementations that
* do not support strict decoding may ignore the flag.
*/
decodeUtf8: (bytes: Uint8Array, strict?: boolean) => string;
}
/**
* Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to
* binary. This WHATWG API is widely available, but it is not part of the
* ECMAScript standard. On runtimes where it is not available, use this
* function to provide your own implementation.
*
* Note that the Text Encoding API does not provide a way to validate UTF-8.
* Our implementation falls back to use encodeURIComponent().
*/
export declare function configureTextEncoding(textEncoding: TextEncoding): void;
export declare function getTextEncoding(): TextEncoding;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.configureTextEncoding = configureTextEncoding;
exports.getTextEncoding = getTextEncoding;
const symbol = Symbol.for("@bufbuild/protobuf/text-encoding");
/**
* Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to
* binary. This WHATWG API is widely available, but it is not part of the
* ECMAScript standard. On runtimes where it is not available, use this
* function to provide your own implementation.
*
* Note that the Text Encoding API does not provide a way to validate UTF-8.
* Our implementation falls back to use encodeURIComponent().
*/
function configureTextEncoding(textEncoding) {
globalThis[symbol] = textEncoding;
}
function getTextEncoding() {
if (globalThis[symbol] == undefined) {
const te = new globalThis.TextEncoder();
const td = new globalThis.TextDecoder();
let tdStrict;
globalThis[symbol] = {
encodeUtf8(text) {
return te.encode(text);
},
decodeUtf8(bytes, strict) {
if (strict) {
if (tdStrict === undefined) {
tdStrict = new globalThis.TextDecoder("utf-8", { fatal: true });
}
return tdStrict.decode(bytes);
}
return td.decode(bytes);
},
checkUtf8(text) {
try {
encodeURIComponent(text);
return true;
}
catch (_) {
return false;
}
},
};
}
return globalThis[symbol];
}
import { type DescEnum, ScalarType } from "../descriptors.js";
/**
* Parse an enum value from the Protobuf text format.
*
* @private
*/
export declare function parseTextFormatEnumValue(descEnum: DescEnum, value: string): number;
/**
* Parse a scalar value from the Protobuf text format.
*
* @private
*/
export declare function parseTextFormatScalarValue(type: ScalarType, value: string): number | boolean | string | bigint | Uint8Array;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseTextFormatEnumValue = parseTextFormatEnumValue;
exports.parseTextFormatScalarValue = parseTextFormatScalarValue;
const descriptors_js_1 = require("../descriptors.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Parse an enum value from the Protobuf text format.
*
* @private
*/
function parseTextFormatEnumValue(descEnum, value) {
const enumValue = descEnum.values.find((v) => v.name === value);
if (!enumValue) {
throw new Error(`cannot parse ${descEnum} default value: ${value}`);
}
return enumValue.number;
}
/**
* Parse a scalar value from the Protobuf text format.
*
* @private
*/
function parseTextFormatScalarValue(type, value) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return value;
case descriptors_js_1.ScalarType.BYTES: {
const u = unescapeBytesDefaultValue(value);
if (u === false) {
throw new Error(`cannot parse ${descriptors_js_1.ScalarType[type]} default value: ${value}`);
}
return u;
}
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
return proto_int64_js_1.protoInt64.parse(value);
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
return proto_int64_js_1.protoInt64.uParse(value);
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
switch (value) {
case "inf":
return Number.POSITIVE_INFINITY;
case "-inf":
return Number.NEGATIVE_INFINITY;
case "nan":
return Number.NaN;
default:
return parseFloat(value);
}
case descriptors_js_1.ScalarType.BOOL:
return value === "true";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.SFIXED32:
return parseInt(value, 10);
}
}
/**
* Parses a text-encoded default value (proto2) of a BYTES field.
*/
function unescapeBytesDefaultValue(str) {
const b = [];
const input = {
tail: str,
c: "",
next() {
if (this.tail.length == 0) {
return false;
}
this.c = this.tail[0];
this.tail = this.tail.substring(1);
return true;
},
take(n) {
if (this.tail.length >= n) {
const r = this.tail.substring(0, n);
this.tail = this.tail.substring(n);
return r;
}
return false;
},
};
while (input.next()) {
switch (input.c) {
case "\\":
if (input.next()) {
switch (input.c) {
case "\\":
b.push(input.c.charCodeAt(0));
break;
case "b":
b.push(0x08);
break;
case "f":
b.push(0x0c);
break;
case "n":
b.push(0x0a);
break;
case "r":
b.push(0x0d);
break;
case "t":
b.push(0x09);
break;
case "v":
b.push(0x0b);
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7": {
const s = input.c;
const t = input.take(2);
if (t === false) {
return false;
}
const n = parseInt(s + t, 8);
if (Number.isNaN(n)) {
return false;
}
b.push(n);
break;
}
case "x": {
const s = input.c;
const t = input.take(2);
if (t === false) {
return false;
}
const n = parseInt(s + t, 16);
if (Number.isNaN(n)) {
return false;
}
b.push(n);
break;
}
case "u": {
const s = input.c;
const t = input.take(4);
if (t === false) {
return false;
}
const n = parseInt(s + t, 16);
if (Number.isNaN(n)) {
return false;
}
const chunk = new Uint8Array(4);
const view = new DataView(chunk.buffer);
view.setInt32(0, n, true);
b.push(chunk[0], chunk[1], chunk[2], chunk[3]);
break;
}
case "U": {
const s = input.c;
const t = input.take(8);
if (t === false) {
return false;
}
const tc = proto_int64_js_1.protoInt64.uEnc(s + t);
const chunk = new Uint8Array(8);
const view = new DataView(chunk.buffer);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
b.push(chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7]);
break;
}
}
}
break;
default:
b.push(input.c.charCodeAt(0));
}
}
return new Uint8Array(b);
}
/**
* Read a 64 bit varint as two JS numbers.
*
* Returns tuple:
* [0]: low bits
* [1]: high bits
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
*/
export declare function varint64read<T extends ReaderLike>(this: T): [number, number];
/**
* Write a 64 bit varint, given as two JS numbers, to the given bytes array.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
*/
export declare function varint64write(lo: number, hi: number, bytes: number[]): void;
/**
* Parse decimal string of 64 bit integer value as two JS numbers.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function int64FromString(dec: string): {
lo: number;
hi: number;
};
/**
* Losslessly converts a 64-bit signed integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function int64ToString(lo: number, hi: number): string;
/**
* Losslessly converts a 64-bit unsigned integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function uInt64ToString(lo: number, hi: number): string;
/**
* Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
*/
export declare function varint32write(value: number, bytes: number[]): void;
/**
* Read an unsigned 32 bit varint.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
*/
export declare function varint32read<T extends ReaderLike>(this: T): number;
type ReaderLike = {
buf: Uint8Array;
pos: number;
len: number;
assertBounds(): void;
};
export {};
"use strict";
// Copyright 2008 Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Code generated by the Protocol Buffer compiler is owned by the owner
// of the input file used when generating it. This code is not
// standalone and requires a support library to be linked with it. This
// support library is itself covered by the above license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.varint64read = varint64read;
exports.varint64write = varint64write;
exports.int64FromString = int64FromString;
exports.int64ToString = int64ToString;
exports.uInt64ToString = uInt64ToString;
exports.varint32write = varint32write;
exports.varint32read = varint32read;
/**
* Read a 64 bit varint as two JS numbers.
*
* Returns tuple:
* [0]: low bits
* [1]: high bits
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
*/
function varint64read() {
let lowBits = 0;
let highBits = 0;
for (let shift = 0; shift < 28; shift += 7) {
let b = this.buf[this.pos++];
lowBits |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
}
let middleByte = this.buf[this.pos++];
// last four bits of the first 32 bit number
lowBits |= (middleByte & 0x0f) << 28;
// 3 upper bits are part of the next 32 bit number
highBits = (middleByte & 0x70) >> 4;
if ((middleByte & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
for (let shift = 3; shift <= 31; shift += 7) {
let b = this.buf[this.pos++];
highBits |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
}
throw new Error("invalid varint");
}
/**
* Write a 64 bit varint, given as two JS numbers, to the given bytes array.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
*/
function varint64write(lo, hi, bytes) {
for (let i = 0; i < 28; i = i + 7) {
const shift = lo >>> i;
const hasNext = !(shift >>> 7 == 0 && hi == 0);
const byte = (hasNext ? shift | 0x80 : shift) & 0xff;
bytes.push(byte);
if (!hasNext) {
return;
}
}
const splitBits = ((lo >>> 28) & 0x0f) | ((hi & 0x07) << 4);
const hasMoreBits = !(hi >> 3 == 0);
bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xff);
if (!hasMoreBits) {
return;
}
for (let i = 3; i < 31; i = i + 7) {
const shift = hi >>> i;
const hasNext = !(shift >>> 7 == 0);
const byte = (hasNext ? shift | 0x80 : shift) & 0xff;
bytes.push(byte);
if (!hasNext) {
return;
}
}
bytes.push((hi >>> 31) & 0x01);
}
// constants for binary math
const TWO_PWR_32_DBL = 0x100000000;
/**
* Parse decimal string of 64 bit integer value as two JS numbers.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function int64FromString(dec) {
// Check for minus sign.
const minus = dec[0] === "-";
if (minus) {
dec = dec.slice(1);
}
// Work 6 decimal digits at a time, acting like we're converting base 1e6
// digits to binary. This is safe to do with floating point math because
// Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
const base = 1e6;
let lowBits = 0;
let highBits = 0;
function add1e6digit(begin, end) {
// Note: Number('') is 0.
const digit1e6 = Number(dec.slice(begin, end));
highBits *= base;
lowBits = lowBits * base + digit1e6;
// Carry bits from lowBits to
if (lowBits >= TWO_PWR_32_DBL) {
highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);
lowBits = lowBits % TWO_PWR_32_DBL;
}
}
add1e6digit(-24, -18);
add1e6digit(-18, -12);
add1e6digit(-12, -6);
add1e6digit(-6);
return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits);
}
/**
* Losslessly converts a 64-bit signed integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function int64ToString(lo, hi) {
let bits = newBits(lo, hi);
// If we're treating the input as a signed value and the high bit is set, do
// a manual two's complement conversion before the decimal conversion.
const negative = bits.hi & 0x80000000;
if (negative) {
bits = negate(bits.lo, bits.hi);
}
const result = uInt64ToString(bits.lo, bits.hi);
return negative ? "-" + result : result;
}
/**
* Losslessly converts a 64-bit unsigned integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function uInt64ToString(lo, hi) {
({ lo, hi } = toUnsigned(lo, hi));
// Skip the expensive conversion if the number is small enough to use the
// built-in conversions.
// Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with
// highBits <= 0x1FFFFF can be safely expressed with a double and retain
// integer precision.
// Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true.
if (hi <= 0x1fffff) {
return String(TWO_PWR_32_DBL * hi + lo);
}
// What this code is doing is essentially converting the input number from
// base-2 to base-1e7, which allows us to represent the 64-bit range with
// only 3 (very large) digits. Those digits are then trivial to convert to
// a base-10 string.
// The magic numbers used here are -
// 2^24 = 16777216 = (1,6777216) in base-1e7.
// 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
// Split 32:32 representation into 16:24:24 representation so our
// intermediate digits don't overflow.
const low = lo & 0xffffff;
const mid = ((lo >>> 24) | (hi << 8)) & 0xffffff;
const high = (hi >> 16) & 0xffff;
// Assemble our three base-1e7 digits, ignoring carries. The maximum
// value in a digit at this step is representable as a 48-bit integer, which
// can be stored in a 64-bit floating point number.
let digitA = low + mid * 6777216 + high * 6710656;
let digitB = mid + high * 8147497;
let digitC = high * 2;
// Apply carries from A to B and from B to C.
const base = 10000000;
if (digitA >= base) {
digitB += Math.floor(digitA / base);
digitA %= base;
}
if (digitB >= base) {
digitC += Math.floor(digitB / base);
digitB %= base;
}
// If digitC is 0, then we should have returned in the trivial code path
// at the top for non-safe integers. Given this, we can assume both digitB
// and digitA need leading zeros.
return (digitC.toString() +
decimalFrom1e7WithLeadingZeros(digitB) +
decimalFrom1e7WithLeadingZeros(digitA));
}
function toUnsigned(lo, hi) {
return { lo: lo >>> 0, hi: hi >>> 0 };
}
function newBits(lo, hi) {
return { lo: lo | 0, hi: hi | 0 };
}
/**
* Returns two's compliment negation of input.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers
*/
function negate(lowBits, highBits) {
highBits = ~highBits;
if (lowBits) {
lowBits = ~lowBits + 1;
}
else {
// If lowBits is 0, then bitwise-not is 0xFFFFFFFF,
// adding 1 to that, results in 0x100000000, which leaves
// the low bits 0x0 and simply adds one to the high bits.
highBits += 1;
}
return newBits(lowBits, highBits);
}
/**
* Returns decimal representation of digit1e7 with leading zeros.
*/
const decimalFrom1e7WithLeadingZeros = (digit1e7) => {
const partial = String(digit1e7);
return "0000000".slice(partial.length) + partial;
};
/**
* Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
*/
function varint32write(value, bytes) {
if (value >= 0) {
// write value as varint 32
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
bytes.push(value);
}
else {
for (let i = 0; i < 9; i++) {
bytes.push((value & 127) | 128);
value = value >> 7;
}
bytes.push(1);
}
}
/**
* Read an unsigned 32 bit varint.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
*/
function varint32read() {
let b = this.buf[this.pos++];
let result = b & 0x7f;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 7;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 14;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 21;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
// Extract only last 4 bits
b = this.buf[this.pos++];
result |= (b & 0x0f) << 28;
for (let readBytes = 5; (b & 0x80) !== 0 && readBytes < 10; readBytes++)
b = this.buf[this.pos++];
if ((b & 0x80) != 0)
throw new Error("invalid varint");
this.assertBounds();
// Result can have 32 bits, convert it to unsigned
return result >>> 0;
}
import type { Message, MessageShape } from "../types.js";
import type { Any } from "./gen/google/protobuf/any_pb.js";
import type { DescMessage } from "../descriptors.js";
import type { Registry } from "../registry.js";
/**
* Creates a `google.protobuf.Any` from a message.
*/
export declare function anyPack<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>): Any;
/**
* Packs the message into the given any.
*/
export declare function anyPack<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>, into: Any): void;
/**
* Returns true if the Any contains the type given by schema.
*/
export declare function anyIs(any: Any, schema: DescMessage): boolean;
/**
* Returns true if the Any contains a message with the given typeName.
*/
export declare function anyIs(any: Any, typeName: string): boolean;
/**
* Unpacks the message the Any represents.
*
* Returns undefined if the Any is empty, or if packed type is not included
* in the given registry.
*/
export declare function anyUnpack(any: Any, registry: Registry): Message | undefined;
/**
* Unpacks the message the Any represents.
*
* Returns undefined if the Any is empty, or if it does not contain the type
* given by schema.
*/
export declare function anyUnpack<Desc extends DescMessage>(any: Any, schema: Desc): MessageShape<Desc> | undefined;
/**
* Same as anyUnpack but unpacks into the target message.
*/
export declare function anyUnpackTo<Desc extends DescMessage>(any: Any, schema: Desc, message: MessageShape<Desc>): MessageShape<Desc> | undefined;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.anyPack = anyPack;
exports.anyIs = anyIs;
exports.anyUnpack = anyUnpack;
exports.anyUnpackTo = anyUnpackTo;
const any_pb_js_1 = require("./gen/google/protobuf/any_pb.js");
const create_js_1 = require("../create.js");
const to_binary_js_1 = require("../to-binary.js");
const from_binary_js_1 = require("../from-binary.js");
function anyPack(schema, message, into) {
let ret = false;
if (!into) {
into = (0, create_js_1.create)(any_pb_js_1.AnySchema);
ret = true;
}
into.value = (0, to_binary_js_1.toBinary)(schema, message);
into.typeUrl = typeNameToUrl(message.$typeName);
return ret ? into : undefined;
}
function anyIs(any, descOrTypeName) {
if (any.typeUrl === "") {
return false;
}
const want = typeof descOrTypeName == "string"
? descOrTypeName
: descOrTypeName.typeName;
const got = typeUrlToName(any.typeUrl);
return want === got;
}
function anyUnpack(any, registryOrMessageDesc) {
if (any.typeUrl === "") {
return undefined;
}
const desc = registryOrMessageDesc.kind == "message"
? registryOrMessageDesc
: registryOrMessageDesc.getMessage(typeUrlToName(any.typeUrl));
if (!desc || !anyIs(any, desc)) {
return undefined;
}
return (0, from_binary_js_1.fromBinary)(desc, any.value);
}
/**
* Same as anyUnpack but unpacks into the target message.
*/
function anyUnpackTo(any, schema, message) {
if (!anyIs(any, schema)) {
return undefined;
}
return (0, from_binary_js_1.mergeFromBinary)(schema, message, any.value);
}
function typeNameToUrl(name) {
return `type.googleapis.com/${name}`;
}
function typeUrlToName(url) {
const slash = url.lastIndexOf("/");
const name = slash >= 0 ? url.substring(slash + 1) : url;
if (!name.length) {
throw new Error(`invalid type url: ${url}`);
}
return name;
}
import type { Duration } from "./gen/google/protobuf/duration_pb.js";
/**
* Create a google.protobuf.Duration message from a Unix timestamp in milliseconds.
*/
export declare function durationFromMs(durationMs: number): Duration;
/**
* Convert a google.protobuf.Duration to a Unix timestamp in milliseconds.
*/
export declare function durationMs(duration: Duration): number;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.durationFromMs = durationFromMs;
exports.durationMs = durationMs;
const duration_pb_js_1 = require("./gen/google/protobuf/duration_pb.js");
const create_js_1 = require("../create.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Create a google.protobuf.Duration message from a Unix timestamp in milliseconds.
*/
function durationFromMs(durationMs) {
const sign = durationMs < 0 ? -1 : 1;
const absDurationMs = Math.abs(durationMs);
const absSeconds = Math.floor(absDurationMs / 1000);
const absNanos = (absDurationMs - absSeconds * 1000) * 1000000;
return (0, create_js_1.create)(duration_pb_js_1.DurationSchema, {
seconds: proto_int64_js_1.protoInt64.parse(absSeconds * sign),
nanos: absNanos === 0 ? 0 : absNanos * sign, // deliberately avoid signed 0 - it does not serialize
});
}
/**
* Convert a google.protobuf.Duration to a Unix timestamp in milliseconds.
*/
function durationMs(duration) {
return Number(duration.seconds) * 1000 + Math.round(duration.nanos / 1000000);
}
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/any.proto.
*/
export declare const file_google_protobuf_any: GenFile;
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
* // or ...
* if (any.isSameTypeAs(Foo.getDefaultInstance())) {
* foo = any.unpack(Foo.getDefaultInstance());
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*
*
* @generated from message google.protobuf.Any
*/
export type Any = Message<"google.protobuf.Any"> & {
/**
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com. As of May 2023, there are no widely used type server
* implementations and no plans to implement one.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
*
* @generated from field: string type_url = 1;
*/
typeUrl: string;
/**
* Must be a valid serialized protocol buffer of the above specified type.
*
* @generated from field: bytes value = 2;
*/
value: Uint8Array;
};
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
* // or ...
* if (any.isSameTypeAs(Foo.getDefaultInstance())) {
* foo = any.unpack(Foo.getDefaultInstance());
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*
*
* @generated from message google.protobuf.Any
*/
export type AnyJson = {
"@type"?: string;
};
/**
* Describes the message google.protobuf.Any.
* Use `create(AnySchema)` to create a new message.
*/
export declare const AnySchema: GenMessage<Any, {
jsonType: AnyJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnySchema = exports.file_google_protobuf_any = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/any.proto.
*/
exports.file_google_protobuf_any = (0, file_js_1.fileDesc)("Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYiJgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2NvbS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
/**
* Describes the message google.protobuf.Any.
* Use `create(AnySchema)` to create a new message.
*/
exports.AnySchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_any, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { SourceContext, SourceContextJson } from "./source_context_pb.js";
import type { Option, OptionJson, Syntax, SyntaxJson } from "./type_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/api.proto.
*/
export declare const file_google_protobuf_api: GenFile;
/**
* Api is a light-weight descriptor for an API Interface.
*
* Interfaces are also described as "protocol buffer services" in some contexts,
* such as by the "service" keyword in a .proto file, but they are different
* from API Services, which represent a concrete implementation of an interface
* as opposed to simply a description of methods and bindings. They are also
* sometimes simply referred to as "APIs" in other contexts, such as the name of
* this message itself. See https://cloud.google.com/apis/design/glossary for
* detailed terminology.
*
* New usages of this message as an alternative to ServiceDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Api
*/
export type Api = Message<"google.protobuf.Api"> & {
/**
* The fully qualified name of this interface, including package name
* followed by the interface's simple name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The methods of this interface, in unspecified order.
*
* @generated from field: repeated google.protobuf.Method methods = 2;
*/
methods: Method[];
/**
* Any metadata attached to the interface.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
/**
* A version string for this interface. If specified, must have the form
* `major-version.minor-version`, as in `1.10`. If the minor version is
* omitted, it defaults to zero. If the entire version field is empty, the
* major version is derived from the package name, as outlined below. If the
* field is not empty, the version in the package name will be verified to be
* consistent with what is provided here.
*
* The versioning schema uses [semantic
* versioning](http://semver.org) where the major version number
* indicates a breaking change and the minor version an additive,
* non-breaking change. Both version numbers are signals to users
* what to expect from different versions, and should be carefully
* chosen based on the product plan.
*
* The major version is also reflected in the package name of the
* interface, which must end in `v<major-version>`, as in
* `google.feature.v1`. For major versions 0 and 1, the suffix can
* be omitted. Zero major versions must only be used for
* experimental, non-GA interfaces.
*
*
* @generated from field: string version = 4;
*/
version: string;
/**
* Source context for the protocol buffer service represented by this
* message.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContext | undefined;
/**
* Included interfaces. See [Mixin][].
*
* @generated from field: repeated google.protobuf.Mixin mixins = 6;
*/
mixins: Mixin[];
/**
* The source syntax of the service.
*
* @generated from field: google.protobuf.Syntax syntax = 7;
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 8;
*/
edition: string;
};
/**
* Api is a light-weight descriptor for an API Interface.
*
* Interfaces are also described as "protocol buffer services" in some contexts,
* such as by the "service" keyword in a .proto file, but they are different
* from API Services, which represent a concrete implementation of an interface
* as opposed to simply a description of methods and bindings. They are also
* sometimes simply referred to as "APIs" in other contexts, such as the name of
* this message itself. See https://cloud.google.com/apis/design/glossary for
* detailed terminology.
*
* New usages of this message as an alternative to ServiceDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Api
*/
export type ApiJson = {
/**
* The fully qualified name of this interface, including package name
* followed by the interface's simple name.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* The methods of this interface, in unspecified order.
*
* @generated from field: repeated google.protobuf.Method methods = 2;
*/
methods?: MethodJson[];
/**
* Any metadata attached to the interface.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options?: OptionJson[];
/**
* A version string for this interface. If specified, must have the form
* `major-version.minor-version`, as in `1.10`. If the minor version is
* omitted, it defaults to zero. If the entire version field is empty, the
* major version is derived from the package name, as outlined below. If the
* field is not empty, the version in the package name will be verified to be
* consistent with what is provided here.
*
* The versioning schema uses [semantic
* versioning](http://semver.org) where the major version number
* indicates a breaking change and the minor version an additive,
* non-breaking change. Both version numbers are signals to users
* what to expect from different versions, and should be carefully
* chosen based on the product plan.
*
* The major version is also reflected in the package name of the
* interface, which must end in `v<major-version>`, as in
* `google.feature.v1`. For major versions 0 and 1, the suffix can
* be omitted. Zero major versions must only be used for
* experimental, non-GA interfaces.
*
*
* @generated from field: string version = 4;
*/
version?: string;
/**
* Source context for the protocol buffer service represented by this
* message.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContextJson;
/**
* Included interfaces. See [Mixin][].
*
* @generated from field: repeated google.protobuf.Mixin mixins = 6;
*/
mixins?: MixinJson[];
/**
* The source syntax of the service.
*
* @generated from field: google.protobuf.Syntax syntax = 7;
*/
syntax?: SyntaxJson;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 8;
*/
edition?: string;
};
/**
* Describes the message google.protobuf.Api.
* Use `create(ApiSchema)` to create a new message.
*/
export declare const ApiSchema: GenMessage<Api, {
jsonType: ApiJson;
}>;
/**
* Method represents a method of an API interface.
*
* New usages of this message as an alternative to MethodDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Method
*/
export type Method = Message<"google.protobuf.Method"> & {
/**
* The simple name of this method.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* A URL of the input message type.
*
* @generated from field: string request_type_url = 2;
*/
requestTypeUrl: string;
/**
* If true, the request is streamed.
*
* @generated from field: bool request_streaming = 3;
*/
requestStreaming: boolean;
/**
* The URL of the output message type.
*
* @generated from field: string response_type_url = 4;
*/
responseTypeUrl: string;
/**
* If true, the response is streamed.
*
* @generated from field: bool response_streaming = 5;
*/
responseStreaming: boolean;
/**
* Any metadata attached to the method.
*
* @generated from field: repeated google.protobuf.Option options = 6;
*/
options: Option[];
/**
* The source syntax of this method.
*
* This field should be ignored, instead the syntax should be inherited from
* Api. This is similar to Field and EnumValue.
*
* @generated from field: google.protobuf.Syntax syntax = 7 [deprecated = true];
* @deprecated
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* This field should be ignored, instead the edition should be inherited from
* Api. This is similar to Field and EnumValue.
*
* @generated from field: string edition = 8 [deprecated = true];
* @deprecated
*/
edition: string;
};
/**
* Method represents a method of an API interface.
*
* New usages of this message as an alternative to MethodDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Method
*/
export type MethodJson = {
/**
* The simple name of this method.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* A URL of the input message type.
*
* @generated from field: string request_type_url = 2;
*/
requestTypeUrl?: string;
/**
* If true, the request is streamed.
*
* @generated from field: bool request_streaming = 3;
*/
requestStreaming?: boolean;
/**
* The URL of the output message type.
*
* @generated from field: string response_type_url = 4;
*/
responseTypeUrl?: string;
/**
* If true, the response is streamed.
*
* @generated from field: bool response_streaming = 5;
*/
responseStreaming?: boolean;
/**
* Any metadata attached to the method.
*
* @generated from field: repeated google.protobuf.Option options = 6;
*/
options?: OptionJson[];
/**
* The source syntax of this method.
*
* This field should be ignored, instead the syntax should be inherited from
* Api. This is similar to Field and EnumValue.
*
* @generated from field: google.protobuf.Syntax syntax = 7 [deprecated = true];
* @deprecated
*/
syntax?: SyntaxJson;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* This field should be ignored, instead the edition should be inherited from
* Api. This is similar to Field and EnumValue.
*
* @generated from field: string edition = 8 [deprecated = true];
* @deprecated
*/
edition?: string;
};
/**
* Describes the message google.protobuf.Method.
* Use `create(MethodSchema)` to create a new message.
*/
export declare const MethodSchema: GenMessage<Method, {
jsonType: MethodJson;
}>;
/**
* Declares an API Interface to be included in this interface. The including
* interface must redeclare all the methods from the included interface, but
* documentation and options are inherited as follows:
*
* - If after comment and whitespace stripping, the documentation
* string of the redeclared method is empty, it will be inherited
* from the original method.
*
* - Each annotation belonging to the service config (http,
* visibility) which is not set in the redeclared method will be
* inherited.
*
* - If an http annotation is inherited, the path pattern will be
* modified as follows. Any version prefix will be replaced by the
* version of the including interface plus the [root][] path if
* specified.
*
* Example of a simple mixin:
*
* package google.acl.v1;
* service AccessControl {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v1/{resource=**}:getAcl";
* }
* }
*
* package google.storage.v2;
* service Storage {
* rpc GetAcl(GetAclRequest) returns (Acl);
*
* // Get a data record.
* rpc GetData(GetDataRequest) returns (Data) {
* option (google.api.http).get = "/v2/{resource=**}";
* }
* }
*
* Example of a mixin configuration:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
*
* The mixin construct implies that all methods in `AccessControl` are
* also declared with same name and request/response types in
* `Storage`. A documentation generator or annotation processor will
* see the effective `Storage.GetAcl` method after inheriting
* documentation and annotations as follows:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/{resource=**}:getAcl";
* }
* ...
* }
*
* Note how the version in the path pattern changed from `v1` to `v2`.
*
* If the `root` field in the mixin is specified, it should be a
* relative path under which inherited HTTP paths are placed. Example:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
* root: acls
*
* This implies the following inherited HTTP annotation:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
* }
* ...
* }
*
* @generated from message google.protobuf.Mixin
*/
export type Mixin = Message<"google.protobuf.Mixin"> & {
/**
* The fully qualified name of the interface which is included.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* If non-empty specifies a path under which inherited HTTP paths
* are rooted.
*
* @generated from field: string root = 2;
*/
root: string;
};
/**
* Declares an API Interface to be included in this interface. The including
* interface must redeclare all the methods from the included interface, but
* documentation and options are inherited as follows:
*
* - If after comment and whitespace stripping, the documentation
* string of the redeclared method is empty, it will be inherited
* from the original method.
*
* - Each annotation belonging to the service config (http,
* visibility) which is not set in the redeclared method will be
* inherited.
*
* - If an http annotation is inherited, the path pattern will be
* modified as follows. Any version prefix will be replaced by the
* version of the including interface plus the [root][] path if
* specified.
*
* Example of a simple mixin:
*
* package google.acl.v1;
* service AccessControl {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v1/{resource=**}:getAcl";
* }
* }
*
* package google.storage.v2;
* service Storage {
* rpc GetAcl(GetAclRequest) returns (Acl);
*
* // Get a data record.
* rpc GetData(GetDataRequest) returns (Data) {
* option (google.api.http).get = "/v2/{resource=**}";
* }
* }
*
* Example of a mixin configuration:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
*
* The mixin construct implies that all methods in `AccessControl` are
* also declared with same name and request/response types in
* `Storage`. A documentation generator or annotation processor will
* see the effective `Storage.GetAcl` method after inheriting
* documentation and annotations as follows:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/{resource=**}:getAcl";
* }
* ...
* }
*
* Note how the version in the path pattern changed from `v1` to `v2`.
*
* If the `root` field in the mixin is specified, it should be a
* relative path under which inherited HTTP paths are placed. Example:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
* root: acls
*
* This implies the following inherited HTTP annotation:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
* }
* ...
* }
*
* @generated from message google.protobuf.Mixin
*/
export type MixinJson = {
/**
* The fully qualified name of the interface which is included.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* If non-empty specifies a path under which inherited HTTP paths
* are rooted.
*
* @generated from field: string root = 2;
*/
root?: string;
};
/**
* Describes the message google.protobuf.Mixin.
* Use `create(MixinSchema)` to create a new message.
*/
export declare const MixinSchema: GenMessage<Mixin, {
jsonType: MixinJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.MixinSchema = exports.MethodSchema = exports.ApiSchema = exports.file_google_protobuf_api = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const source_context_pb_js_1 = require("./source_context_pb.js");
const type_pb_js_1 = require("./type_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/api.proto.
*/
exports.file_google_protobuf_api = (0, file_js_1.fileDesc)("Chlnb29nbGUvcHJvdG9idWYvYXBpLnByb3RvEg9nb29nbGUucHJvdG9idWYikgIKA0FwaRIMCgRuYW1lGAEgASgJEigKB21ldGhvZHMYAiADKAsyFy5nb29nbGUucHJvdG9idWYuTWV0aG9kEigKB29wdGlvbnMYAyADKAsyFy5nb29nbGUucHJvdG9idWYuT3B0aW9uEg8KB3ZlcnNpb24YBCABKAkSNgoOc291cmNlX2NvbnRleHQYBSABKAsyHi5nb29nbGUucHJvdG9idWYuU291cmNlQ29udGV4dBImCgZtaXhpbnMYBiADKAsyFi5nb29nbGUucHJvdG9idWYuTWl4aW4SJwoGc3ludGF4GAcgASgOMhcuZ29vZ2xlLnByb3RvYnVmLlN5bnRheBIPCgdlZGl0aW9uGAggASgJIu4BCgZNZXRob2QSDAoEbmFtZRgBIAEoCRIYChByZXF1ZXN0X3R5cGVfdXJsGAIgASgJEhkKEXJlcXVlc3Rfc3RyZWFtaW5nGAMgASgIEhkKEXJlc3BvbnNlX3R5cGVfdXJsGAQgASgJEhoKEnJlc3BvbnNlX3N0cmVhbWluZxgFIAEoCBIoCgdvcHRpb25zGAYgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhIrCgZzeW50YXgYByABKA4yFy5nb29nbGUucHJvdG9idWYuU3ludGF4QgIYARITCgdlZGl0aW9uGAggASgJQgIYASIjCgVNaXhpbhIMCgRuYW1lGAEgASgJEgwKBHJvb3QYAiABKAlCdgoTY29tLmdvb2dsZS5wcm90b2J1ZkIIQXBpUHJvdG9QAVosZ29vZ2xlLmdvbGFuZy5vcmcvcHJvdG9idWYvdHlwZXMva25vd24vYXBpcGKiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw", [source_context_pb_js_1.file_google_protobuf_source_context, type_pb_js_1.file_google_protobuf_type]);
/**
* Describes the message google.protobuf.Api.
* Use `create(ApiSchema)` to create a new message.
*/
exports.ApiSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_api, 0);
/**
* Describes the message google.protobuf.Method.
* Use `create(MethodSchema)` to create a new message.
*/
exports.MethodSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_api, 1);
/**
* Describes the message google.protobuf.Mixin.
* Use `create(MixinSchema)` to create a new message.
*/
exports.MixinSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_api, 2);
import type { GenEnum, GenFile, GenMessage } from "../../../../../codegenv2/types.js";
import type { FileDescriptorProto, FileDescriptorProtoJson, GeneratedCodeInfo, GeneratedCodeInfoJson } from "../descriptor_pb.js";
import type { Message } from "../../../../../types.js";
/**
* Describes the file google/protobuf/compiler/plugin.proto.
*/
export declare const file_google_protobuf_compiler_plugin: GenFile;
/**
* The version number of protocol compiler.
*
* @generated from message google.protobuf.compiler.Version
*/
export type Version = Message<"google.protobuf.compiler.Version"> & {
/**
* @generated from field: optional int32 major = 1;
*/
major: number;
/**
* @generated from field: optional int32 minor = 2;
*/
minor: number;
/**
* @generated from field: optional int32 patch = 3;
*/
patch: number;
/**
* A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
* be empty for mainline stable releases.
*
* @generated from field: optional string suffix = 4;
*/
suffix: string;
};
/**
* The version number of protocol compiler.
*
* @generated from message google.protobuf.compiler.Version
*/
export type VersionJson = {
/**
* @generated from field: optional int32 major = 1;
*/
major?: number;
/**
* @generated from field: optional int32 minor = 2;
*/
minor?: number;
/**
* @generated from field: optional int32 patch = 3;
*/
patch?: number;
/**
* A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
* be empty for mainline stable releases.
*
* @generated from field: optional string suffix = 4;
*/
suffix?: string;
};
/**
* Describes the message google.protobuf.compiler.Version.
* Use `create(VersionSchema)` to create a new message.
*/
export declare const VersionSchema: GenMessage<Version, {
jsonType: VersionJson;
}>;
/**
* An encoded CodeGeneratorRequest is written to the plugin's stdin.
*
* @generated from message google.protobuf.compiler.CodeGeneratorRequest
*/
export type CodeGeneratorRequest = Message<"google.protobuf.compiler.CodeGeneratorRequest"> & {
/**
* The .proto files that were explicitly listed on the command-line. The
* code generator should generate code only for these files. Each file's
* descriptor will be included in proto_file, below.
*
* @generated from field: repeated string file_to_generate = 1;
*/
fileToGenerate: string[];
/**
* The generator parameter passed on the command-line.
*
* @generated from field: optional string parameter = 2;
*/
parameter: string;
/**
* FileDescriptorProtos for all files in files_to_generate and everything
* they import. The files will appear in topological order, so each file
* appears before any file that imports it.
*
* Note: the files listed in files_to_generate will include runtime-retention
* options only, but all other files will include source-retention options.
* The source_file_descriptors field below is available in case you need
* source-retention options for files_to_generate.
*
* protoc guarantees that all proto_files will be written after
* the fields above, even though this is not technically guaranteed by the
* protobuf wire format. This theoretically could allow a plugin to stream
* in the FileDescriptorProtos and handle them one by one rather than read
* the entire set into memory at once. However, as of this writing, this
* is not similarly optimized on protoc's end -- it will store all fields in
* memory at once before sending them to the plugin.
*
* Type names of fields and extensions in the FileDescriptorProto are always
* fully qualified.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto proto_file = 15;
*/
protoFile: FileDescriptorProto[];
/**
* File descriptors with all options, including source-retention options.
* These descriptors are only provided for the files listed in
* files_to_generate.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto source_file_descriptors = 17;
*/
sourceFileDescriptors: FileDescriptorProto[];
/**
* The version number of protocol compiler.
*
* @generated from field: optional google.protobuf.compiler.Version compiler_version = 3;
*/
compilerVersion?: Version | undefined;
};
/**
* An encoded CodeGeneratorRequest is written to the plugin's stdin.
*
* @generated from message google.protobuf.compiler.CodeGeneratorRequest
*/
export type CodeGeneratorRequestJson = {
/**
* The .proto files that were explicitly listed on the command-line. The
* code generator should generate code only for these files. Each file's
* descriptor will be included in proto_file, below.
*
* @generated from field: repeated string file_to_generate = 1;
*/
fileToGenerate?: string[];
/**
* The generator parameter passed on the command-line.
*
* @generated from field: optional string parameter = 2;
*/
parameter?: string;
/**
* FileDescriptorProtos for all files in files_to_generate and everything
* they import. The files will appear in topological order, so each file
* appears before any file that imports it.
*
* Note: the files listed in files_to_generate will include runtime-retention
* options only, but all other files will include source-retention options.
* The source_file_descriptors field below is available in case you need
* source-retention options for files_to_generate.
*
* protoc guarantees that all proto_files will be written after
* the fields above, even though this is not technically guaranteed by the
* protobuf wire format. This theoretically could allow a plugin to stream
* in the FileDescriptorProtos and handle them one by one rather than read
* the entire set into memory at once. However, as of this writing, this
* is not similarly optimized on protoc's end -- it will store all fields in
* memory at once before sending them to the plugin.
*
* Type names of fields and extensions in the FileDescriptorProto are always
* fully qualified.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto proto_file = 15;
*/
protoFile?: FileDescriptorProtoJson[];
/**
* File descriptors with all options, including source-retention options.
* These descriptors are only provided for the files listed in
* files_to_generate.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto source_file_descriptors = 17;
*/
sourceFileDescriptors?: FileDescriptorProtoJson[];
/**
* The version number of protocol compiler.
*
* @generated from field: optional google.protobuf.compiler.Version compiler_version = 3;
*/
compilerVersion?: VersionJson;
};
/**
* Describes the message google.protobuf.compiler.CodeGeneratorRequest.
* Use `create(CodeGeneratorRequestSchema)` to create a new message.
*/
export declare const CodeGeneratorRequestSchema: GenMessage<CodeGeneratorRequest, {
jsonType: CodeGeneratorRequestJson;
}>;
/**
* The plugin writes an encoded CodeGeneratorResponse to stdout.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse
*/
export type CodeGeneratorResponse = Message<"google.protobuf.compiler.CodeGeneratorResponse"> & {
/**
* Error message. If non-empty, code generation failed. The plugin process
* should exit with status code zero even if it reports an error in this way.
*
* This should be used to indicate errors in .proto files which prevent the
* code generator from generating correct code. Errors which indicate a
* problem in protoc itself -- such as the input CodeGeneratorRequest being
* unparseable -- should be reported by writing a message to stderr and
* exiting with a non-zero status code.
*
* @generated from field: optional string error = 1;
*/
error: string;
/**
* A bitmask of supported features that the code generator supports.
* This is a bitwise "or" of values from the Feature enum.
*
* @generated from field: optional uint64 supported_features = 2;
*/
supportedFeatures: bigint;
/**
* The minimum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 minimum_edition = 3;
*/
minimumEdition: number;
/**
* The maximum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 maximum_edition = 4;
*/
maximumEdition: number;
/**
* @generated from field: repeated google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
*/
file: CodeGeneratorResponse_File[];
};
/**
* The plugin writes an encoded CodeGeneratorResponse to stdout.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse
*/
export type CodeGeneratorResponseJson = {
/**
* Error message. If non-empty, code generation failed. The plugin process
* should exit with status code zero even if it reports an error in this way.
*
* This should be used to indicate errors in .proto files which prevent the
* code generator from generating correct code. Errors which indicate a
* problem in protoc itself -- such as the input CodeGeneratorRequest being
* unparseable -- should be reported by writing a message to stderr and
* exiting with a non-zero status code.
*
* @generated from field: optional string error = 1;
*/
error?: string;
/**
* A bitmask of supported features that the code generator supports.
* This is a bitwise "or" of values from the Feature enum.
*
* @generated from field: optional uint64 supported_features = 2;
*/
supportedFeatures?: string;
/**
* The minimum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 minimum_edition = 3;
*/
minimumEdition?: number;
/**
* The maximum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 maximum_edition = 4;
*/
maximumEdition?: number;
/**
* @generated from field: repeated google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
*/
file?: CodeGeneratorResponse_FileJson[];
};
/**
* Describes the message google.protobuf.compiler.CodeGeneratorResponse.
* Use `create(CodeGeneratorResponseSchema)` to create a new message.
*/
export declare const CodeGeneratorResponseSchema: GenMessage<CodeGeneratorResponse, {
jsonType: CodeGeneratorResponseJson;
}>;
/**
* Represents a single generated file.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse.File
*/
export type CodeGeneratorResponse_File = Message<"google.protobuf.compiler.CodeGeneratorResponse.File"> & {
/**
* The file name, relative to the output directory. The name must not
* contain "." or ".." components and must be relative, not be absolute (so,
* the file cannot lie outside the output directory). "/" must be used as
* the path separator, not "\".
*
* If the name is omitted, the content will be appended to the previous
* file. This allows the generator to break large files into small chunks,
* and allows the generated text to be streamed back to protoc so that large
* files need not reside completely in memory at one time. Note that as of
* this writing protoc does not optimize for this -- it will read the entire
* CodeGeneratorResponse before writing files to disk.
*
* @generated from field: optional string name = 1;
*/
name: string;
/**
* If non-empty, indicates that the named file should already exist, and the
* content here is to be inserted into that file at a defined insertion
* point. This feature allows a code generator to extend the output
* produced by another code generator. The original generator may provide
* insertion points by placing special annotations in the file that look
* like:
* @@protoc_insertion_point(NAME)
* The annotation can have arbitrary text before and after it on the line,
* which allows it to be placed in a comment. NAME should be replaced with
* an identifier naming the point -- this is what other generators will use
* as the insertion_point. Code inserted at this point will be placed
* immediately above the line containing the insertion point (thus multiple
* insertions to the same point will come out in the order they were added).
* The double-@ is intended to make it unlikely that the generated code
* could contain things that look like insertion points by accident.
*
* For example, the C++ code generator places the following line in the
* .pb.h files that it generates:
* // @@protoc_insertion_point(namespace_scope)
* This line appears within the scope of the file's package namespace, but
* outside of any particular class. Another plugin can then specify the
* insertion_point "namespace_scope" to generate additional classes or
* other declarations that should be placed in this scope.
*
* Note that if the line containing the insertion point begins with
* whitespace, the same whitespace will be added to every line of the
* inserted text. This is useful for languages like Python, where
* indentation matters. In these languages, the insertion point comment
* should be indented the same amount as any inserted code will need to be
* in order to work correctly in that context.
*
* The code generator that generates the initial file and the one which
* inserts into it must both run as part of a single invocation of protoc.
* Code generators are executed in the order in which they appear on the
* command line.
*
* If |insertion_point| is present, |name| must also be present.
*
* @generated from field: optional string insertion_point = 2;
*/
insertionPoint: string;
/**
* The file contents.
*
* @generated from field: optional string content = 15;
*/
content: string;
/**
* Information describing the file content being inserted. If an insertion
* point is used, this information will be appropriately offset and inserted
* into the code generation metadata for the generated files.
*
* @generated from field: optional google.protobuf.GeneratedCodeInfo generated_code_info = 16;
*/
generatedCodeInfo?: GeneratedCodeInfo | undefined;
};
/**
* Represents a single generated file.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse.File
*/
export type CodeGeneratorResponse_FileJson = {
/**
* The file name, relative to the output directory. The name must not
* contain "." or ".." components and must be relative, not be absolute (so,
* the file cannot lie outside the output directory). "/" must be used as
* the path separator, not "\".
*
* If the name is omitted, the content will be appended to the previous
* file. This allows the generator to break large files into small chunks,
* and allows the generated text to be streamed back to protoc so that large
* files need not reside completely in memory at one time. Note that as of
* this writing protoc does not optimize for this -- it will read the entire
* CodeGeneratorResponse before writing files to disk.
*
* @generated from field: optional string name = 1;
*/
name?: string;
/**
* If non-empty, indicates that the named file should already exist, and the
* content here is to be inserted into that file at a defined insertion
* point. This feature allows a code generator to extend the output
* produced by another code generator. The original generator may provide
* insertion points by placing special annotations in the file that look
* like:
* @@protoc_insertion_point(NAME)
* The annotation can have arbitrary text before and after it on the line,
* which allows it to be placed in a comment. NAME should be replaced with
* an identifier naming the point -- this is what other generators will use
* as the insertion_point. Code inserted at this point will be placed
* immediately above the line containing the insertion point (thus multiple
* insertions to the same point will come out in the order they were added).
* The double-@ is intended to make it unlikely that the generated code
* could contain things that look like insertion points by accident.
*
* For example, the C++ code generator places the following line in the
* .pb.h files that it generates:
* // @@protoc_insertion_point(namespace_scope)
* This line appears within the scope of the file's package namespace, but
* outside of any particular class. Another plugin can then specify the
* insertion_point "namespace_scope" to generate additional classes or
* other declarations that should be placed in this scope.
*
* Note that if the line containing the insertion point begins with
* whitespace, the same whitespace will be added to every line of the
* inserted text. This is useful for languages like Python, where
* indentation matters. In these languages, the insertion point comment
* should be indented the same amount as any inserted code will need to be
* in order to work correctly in that context.
*
* The code generator that generates the initial file and the one which
* inserts into it must both run as part of a single invocation of protoc.
* Code generators are executed in the order in which they appear on the
* command line.
*
* If |insertion_point| is present, |name| must also be present.
*
* @generated from field: optional string insertion_point = 2;
*/
insertionPoint?: string;
/**
* The file contents.
*
* @generated from field: optional string content = 15;
*/
content?: string;
/**
* Information describing the file content being inserted. If an insertion
* point is used, this information will be appropriately offset and inserted
* into the code generation metadata for the generated files.
*
* @generated from field: optional google.protobuf.GeneratedCodeInfo generated_code_info = 16;
*/
generatedCodeInfo?: GeneratedCodeInfoJson;
};
/**
* Describes the message google.protobuf.compiler.CodeGeneratorResponse.File.
* Use `create(CodeGeneratorResponse_FileSchema)` to create a new message.
*/
export declare const CodeGeneratorResponse_FileSchema: GenMessage<CodeGeneratorResponse_File, {
jsonType: CodeGeneratorResponse_FileJson;
}>;
/**
* Sync with code_generator.h.
*
* @generated from enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
export declare enum CodeGeneratorResponse_Feature {
/**
* @generated from enum value: FEATURE_NONE = 0;
*/
NONE = 0,
/**
* @generated from enum value: FEATURE_PROTO3_OPTIONAL = 1;
*/
PROTO3_OPTIONAL = 1,
/**
* @generated from enum value: FEATURE_SUPPORTS_EDITIONS = 2;
*/
SUPPORTS_EDITIONS = 2
}
/**
* Sync with code_generator.h.
*
* @generated from enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
export type CodeGeneratorResponse_FeatureJson = "FEATURE_NONE" | "FEATURE_PROTO3_OPTIONAL" | "FEATURE_SUPPORTS_EDITIONS";
/**
* Describes the enum google.protobuf.compiler.CodeGeneratorResponse.Feature.
*/
export declare const CodeGeneratorResponse_FeatureSchema: GenEnum<CodeGeneratorResponse_Feature, CodeGeneratorResponse_FeatureJson>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGeneratorResponse_FeatureSchema = exports.CodeGeneratorResponse_Feature = exports.CodeGeneratorResponse_FileSchema = exports.CodeGeneratorResponseSchema = exports.CodeGeneratorRequestSchema = exports.VersionSchema = exports.file_google_protobuf_compiler_plugin = void 0;
const file_js_1 = require("../../../../../codegenv2/file.js");
const descriptor_pb_js_1 = require("../descriptor_pb.js");
const message_js_1 = require("../../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../../codegenv2/enum.js");
/**
* Describes the file google/protobuf/compiler/plugin.proto.
*/
exports.file_google_protobuf_compiler_plugin = (0, file_js_1.fileDesc)("CiVnb29nbGUvcHJvdG9idWYvY29tcGlsZXIvcGx1Z2luLnByb3RvEhhnb29nbGUucHJvdG9idWYuY29tcGlsZXIiRgoHVmVyc2lvbhINCgVtYWpvchgBIAEoBRINCgVtaW5vchgCIAEoBRINCgVwYXRjaBgDIAEoBRIOCgZzdWZmaXgYBCABKAkigQIKFENvZGVHZW5lcmF0b3JSZXF1ZXN0EhgKEGZpbGVfdG9fZ2VuZXJhdGUYASADKAkSEQoJcGFyYW1ldGVyGAIgASgJEjgKCnByb3RvX2ZpbGUYDyADKAsyJC5nb29nbGUucHJvdG9idWYuRmlsZURlc2NyaXB0b3JQcm90bxJFChdzb3VyY2VfZmlsZV9kZXNjcmlwdG9ycxgRIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5GaWxlRGVzY3JpcHRvclByb3RvEjsKEGNvbXBpbGVyX3ZlcnNpb24YAyABKAsyIS5nb29nbGUucHJvdG9idWYuY29tcGlsZXIuVmVyc2lvbiKSAwoVQ29kZUdlbmVyYXRvclJlc3BvbnNlEg0KBWVycm9yGAEgASgJEhoKEnN1cHBvcnRlZF9mZWF0dXJlcxgCIAEoBBIXCg9taW5pbXVtX2VkaXRpb24YAyABKAUSFwoPbWF4aW11bV9lZGl0aW9uGAQgASgFEkIKBGZpbGUYDyADKAsyNC5nb29nbGUucHJvdG9idWYuY29tcGlsZXIuQ29kZUdlbmVyYXRvclJlc3BvbnNlLkZpbGUafwoERmlsZRIMCgRuYW1lGAEgASgJEhcKD2luc2VydGlvbl9wb2ludBgCIAEoCRIPCgdjb250ZW50GA8gASgJEj8KE2dlbmVyYXRlZF9jb2RlX2luZm8YECABKAsyIi5nb29nbGUucHJvdG9idWYuR2VuZXJhdGVkQ29kZUluZm8iVwoHRmVhdHVyZRIQCgxGRUFUVVJFX05PTkUQABIbChdGRUFUVVJFX1BST1RPM19PUFRJT05BTBABEh0KGUZFQVRVUkVfU1VQUE9SVFNfRURJVElPTlMQAkJyChxjb20uZ29vZ2xlLnByb3RvYnVmLmNvbXBpbGVyQgxQbHVnaW5Qcm90b3NaKWdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL3BsdWdpbnBiqgIYR29vZ2xlLlByb3RvYnVmLkNvbXBpbGVy", [descriptor_pb_js_1.file_google_protobuf_descriptor]);
/**
* Describes the message google.protobuf.compiler.Version.
* Use `create(VersionSchema)` to create a new message.
*/
exports.VersionSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_compiler_plugin, 0);
/**
* Describes the message google.protobuf.compiler.CodeGeneratorRequest.
* Use `create(CodeGeneratorRequestSchema)` to create a new message.
*/
exports.CodeGeneratorRequestSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_compiler_plugin, 1);
/**
* Describes the message google.protobuf.compiler.CodeGeneratorResponse.
* Use `create(CodeGeneratorResponseSchema)` to create a new message.
*/
exports.CodeGeneratorResponseSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_compiler_plugin, 2);
/**
* Describes the message google.protobuf.compiler.CodeGeneratorResponse.File.
* Use `create(CodeGeneratorResponse_FileSchema)` to create a new message.
*/
exports.CodeGeneratorResponse_FileSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_compiler_plugin, 2, 0);
/**
* Sync with code_generator.h.
*
* @generated from enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
var CodeGeneratorResponse_Feature;
(function (CodeGeneratorResponse_Feature) {
/**
* @generated from enum value: FEATURE_NONE = 0;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["NONE"] = 0] = "NONE";
/**
* @generated from enum value: FEATURE_PROTO3_OPTIONAL = 1;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["PROTO3_OPTIONAL"] = 1] = "PROTO3_OPTIONAL";
/**
* @generated from enum value: FEATURE_SUPPORTS_EDITIONS = 2;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["SUPPORTS_EDITIONS"] = 2] = "SUPPORTS_EDITIONS";
})(CodeGeneratorResponse_Feature || (exports.CodeGeneratorResponse_Feature = CodeGeneratorResponse_Feature = {}));
/**
* Describes the enum google.protobuf.compiler.CodeGeneratorResponse.Feature.
*/
exports.CodeGeneratorResponse_FeatureSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_compiler_plugin, 2, 0);
import type { GenEnum, GenExtension, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { FeatureSet } from "./descriptor_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/cpp_features.proto.
*/
export declare const file_google_protobuf_cpp_features: GenFile;
/**
* @generated from message pb.CppFeatures
*/
export type CppFeatures = Message<"pb.CppFeatures"> & {
/**
* Whether or not to treat an enum field as closed. This option is only
* applicable to enum fields, and will be removed in the future. It is
* consistent with the legacy behavior of using proto3 enum types for proto2
* fields.
*
* @generated from field: optional bool legacy_closed_enum = 1;
*/
legacyClosedEnum: boolean;
/**
* @generated from field: optional pb.CppFeatures.StringType string_type = 2;
*/
stringType: CppFeatures_StringType;
/**
* @generated from field: optional bool enum_name_uses_string_view = 3;
*/
enumNameUsesStringView: boolean;
};
/**
* @generated from message pb.CppFeatures
*/
export type CppFeaturesJson = {
/**
* Whether or not to treat an enum field as closed. This option is only
* applicable to enum fields, and will be removed in the future. It is
* consistent with the legacy behavior of using proto3 enum types for proto2
* fields.
*
* @generated from field: optional bool legacy_closed_enum = 1;
*/
legacyClosedEnum?: boolean;
/**
* @generated from field: optional pb.CppFeatures.StringType string_type = 2;
*/
stringType?: CppFeatures_StringTypeJson;
/**
* @generated from field: optional bool enum_name_uses_string_view = 3;
*/
enumNameUsesStringView?: boolean;
};
/**
* Describes the message pb.CppFeatures.
* Use `create(CppFeaturesSchema)` to create a new message.
*/
export declare const CppFeaturesSchema: GenMessage<CppFeatures, {
jsonType: CppFeaturesJson;
}>;
/**
* @generated from enum pb.CppFeatures.StringType
*/
export declare enum CppFeatures_StringType {
/**
* @generated from enum value: STRING_TYPE_UNKNOWN = 0;
*/
STRING_TYPE_UNKNOWN = 0,
/**
* @generated from enum value: VIEW = 1;
*/
VIEW = 1,
/**
* @generated from enum value: CORD = 2;
*/
CORD = 2,
/**
* @generated from enum value: STRING = 3;
*/
STRING = 3
}
/**
* @generated from enum pb.CppFeatures.StringType
*/
export type CppFeatures_StringTypeJson = "STRING_TYPE_UNKNOWN" | "VIEW" | "CORD" | "STRING";
/**
* Describes the enum pb.CppFeatures.StringType.
*/
export declare const CppFeatures_StringTypeSchema: GenEnum<CppFeatures_StringType, CppFeatures_StringTypeJson>;
/**
* @generated from extension: optional pb.CppFeatures cpp = 1000;
*/
export declare const cpp: GenExtension<FeatureSet, CppFeatures>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.cpp = exports.CppFeatures_StringTypeSchema = exports.CppFeatures_StringType = exports.CppFeaturesSchema = exports.file_google_protobuf_cpp_features = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const descriptor_pb_js_1 = require("./descriptor_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
const extension_js_1 = require("../../../../codegenv2/extension.js");
/**
* Describes the file google/protobuf/cpp_features.proto.
*/
exports.file_google_protobuf_cpp_features = (0, file_js_1.fileDesc)("CiJnb29nbGUvcHJvdG9idWYvY3BwX2ZlYXR1cmVzLnByb3RvEgJwYiL8AwoLQ3BwRmVhdHVyZXMS+wEKEmxlZ2FjeV9jbG9zZWRfZW51bRgBIAEoCELeAYgBAZgBBJgBAaIBCRIEdHJ1ZRiEB6IBChIFZmFsc2UY5weyAbgBCOgHEOgHGq8BVGhlIGxlZ2FjeSBjbG9zZWQgZW51bSBiZWhhdmlvciBpbiBDKysgaXMgZGVwcmVjYXRlZCBhbmQgaXMgc2NoZWR1bGVkIHRvIGJlIHJlbW92ZWQgaW4gZWRpdGlvbiAyMDI1LiAgU2VlIGh0dHA6Ly9wcm90b2J1Zi5kZXYvcHJvZ3JhbW1pbmctZ3VpZGVzL2VudW0vI2NwcCBmb3IgbW9yZSBpbmZvcm1hdGlvbhJaCgtzdHJpbmdfdHlwZRgCIAEoDjIaLnBiLkNwcEZlYXR1cmVzLlN0cmluZ1R5cGVCKYgBAZgBBJgBAaIBCxIGU1RSSU5HGIQHogEJEgRWSUVXGOkHsgEDCOgHEkwKGmVudW1fbmFtZV91c2VzX3N0cmluZ192aWV3GAMgASgIQiiIAQGYAQaYAQGiAQoSBWZhbHNlGIQHogEJEgR0cnVlGOkHsgEDCOkHIkUKClN0cmluZ1R5cGUSFwoTU1RSSU5HX1RZUEVfVU5LTk9XThAAEggKBFZJRVcQARIICgRDT1JEEAISCgoGU1RSSU5HEAM6PwoDY3BwEhsuZ29vZ2xlLnByb3RvYnVmLkZlYXR1cmVTZXQY6AcgASgLMg8ucGIuQ3BwRmVhdHVyZXNSA2NwcA", [descriptor_pb_js_1.file_google_protobuf_descriptor]);
/**
* Describes the message pb.CppFeatures.
* Use `create(CppFeaturesSchema)` to create a new message.
*/
exports.CppFeaturesSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_cpp_features, 0);
/**
* @generated from enum pb.CppFeatures.StringType
*/
var CppFeatures_StringType;
(function (CppFeatures_StringType) {
/**
* @generated from enum value: STRING_TYPE_UNKNOWN = 0;
*/
CppFeatures_StringType[CppFeatures_StringType["STRING_TYPE_UNKNOWN"] = 0] = "STRING_TYPE_UNKNOWN";
/**
* @generated from enum value: VIEW = 1;
*/
CppFeatures_StringType[CppFeatures_StringType["VIEW"] = 1] = "VIEW";
/**
* @generated from enum value: CORD = 2;
*/
CppFeatures_StringType[CppFeatures_StringType["CORD"] = 2] = "CORD";
/**
* @generated from enum value: STRING = 3;
*/
CppFeatures_StringType[CppFeatures_StringType["STRING"] = 3] = "STRING";
})(CppFeatures_StringType || (exports.CppFeatures_StringType = CppFeatures_StringType = {}));
/**
* Describes the enum pb.CppFeatures.StringType.
*/
exports.CppFeatures_StringTypeSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_cpp_features, 0, 0);
/**
* @generated from extension: optional pb.CppFeatures cpp = 1000;
*/
exports.cpp = (0, extension_js_1.extDesc)(exports.file_google_protobuf_cpp_features, 0);

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/duration.proto.
*/
export declare const file_google_protobuf_duration: GenFile;
/**
* A Duration represents a signed, fixed-length span of time represented
* as a count of seconds and fractions of seconds at nanosecond
* resolution. It is independent of any calendar and concepts like "day"
* or "month". It is related to Timestamp in that the difference between
* two Timestamp values is a Duration and it can be added or subtracted
* from a Timestamp. Range is approximately +-10,000 years.
*
* # Examples
*
* Example 1: Compute Duration from two Timestamps in pseudo code.
*
* Timestamp start = ...;
* Timestamp end = ...;
* Duration duration = ...;
*
* duration.seconds = end.seconds - start.seconds;
* duration.nanos = end.nanos - start.nanos;
*
* if (duration.seconds < 0 && duration.nanos > 0) {
* duration.seconds += 1;
* duration.nanos -= 1000000000;
* } else if (duration.seconds > 0 && duration.nanos < 0) {
* duration.seconds -= 1;
* duration.nanos += 1000000000;
* }
*
* Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
*
* Timestamp start = ...;
* Duration duration = ...;
* Timestamp end = ...;
*
* end.seconds = start.seconds + duration.seconds;
* end.nanos = start.nanos + duration.nanos;
*
* if (end.nanos < 0) {
* end.seconds -= 1;
* end.nanos += 1000000000;
* } else if (end.nanos >= 1000000000) {
* end.seconds += 1;
* end.nanos -= 1000000000;
* }
*
* Example 3: Compute Duration from datetime.timedelta in Python.
*
* td = datetime.timedelta(days=3, minutes=10)
* duration = Duration()
* duration.FromTimedelta(td)
*
* # JSON Mapping
*
* In JSON format, the Duration type is encoded as a string rather than an
* object, where the string ends in the suffix "s" (indicating seconds) and
* is preceded by the number of seconds, with nanoseconds expressed as
* fractional seconds. For example, 3 seconds with 0 nanoseconds should be
* encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
* be expressed in JSON format as "3.000000001s", and 3 seconds and 1
* microsecond should be expressed in JSON format as "3.000001s".
*
*
* @generated from message google.protobuf.Duration
*/
export type Duration = Message<"google.protobuf.Duration"> & {
/**
* Signed seconds of the span of time. Must be from -315,576,000,000
* to +315,576,000,000 inclusive. Note: these bounds are computed from:
* 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
*
* @generated from field: int64 seconds = 1;
*/
seconds: bigint;
/**
* Signed fractions of a second at nanosecond resolution of the span
* of time. Durations less than one second are represented with a 0
* `seconds` field and a positive or negative `nanos` field. For durations
* of one second or more, a non-zero value for the `nanos` field must be
* of the same sign as the `seconds` field. Must be from -999,999,999
* to +999,999,999 inclusive.
*
* @generated from field: int32 nanos = 2;
*/
nanos: number;
};
/**
* A Duration represents a signed, fixed-length span of time represented
* as a count of seconds and fractions of seconds at nanosecond
* resolution. It is independent of any calendar and concepts like "day"
* or "month". It is related to Timestamp in that the difference between
* two Timestamp values is a Duration and it can be added or subtracted
* from a Timestamp. Range is approximately +-10,000 years.
*
* # Examples
*
* Example 1: Compute Duration from two Timestamps in pseudo code.
*
* Timestamp start = ...;
* Timestamp end = ...;
* Duration duration = ...;
*
* duration.seconds = end.seconds - start.seconds;
* duration.nanos = end.nanos - start.nanos;
*
* if (duration.seconds < 0 && duration.nanos > 0) {
* duration.seconds += 1;
* duration.nanos -= 1000000000;
* } else if (duration.seconds > 0 && duration.nanos < 0) {
* duration.seconds -= 1;
* duration.nanos += 1000000000;
* }
*
* Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
*
* Timestamp start = ...;
* Duration duration = ...;
* Timestamp end = ...;
*
* end.seconds = start.seconds + duration.seconds;
* end.nanos = start.nanos + duration.nanos;
*
* if (end.nanos < 0) {
* end.seconds -= 1;
* end.nanos += 1000000000;
* } else if (end.nanos >= 1000000000) {
* end.seconds += 1;
* end.nanos -= 1000000000;
* }
*
* Example 3: Compute Duration from datetime.timedelta in Python.
*
* td = datetime.timedelta(days=3, minutes=10)
* duration = Duration()
* duration.FromTimedelta(td)
*
* # JSON Mapping
*
* In JSON format, the Duration type is encoded as a string rather than an
* object, where the string ends in the suffix "s" (indicating seconds) and
* is preceded by the number of seconds, with nanoseconds expressed as
* fractional seconds. For example, 3 seconds with 0 nanoseconds should be
* encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
* be expressed in JSON format as "3.000000001s", and 3 seconds and 1
* microsecond should be expressed in JSON format as "3.000001s".
*
*
* @generated from message google.protobuf.Duration
*/
export type DurationJson = string;
/**
* Describes the message google.protobuf.Duration.
* Use `create(DurationSchema)` to create a new message.
*/
export declare const DurationSchema: GenMessage<Duration, {
jsonType: DurationJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DurationSchema = exports.file_google_protobuf_duration = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/duration.proto.
*/
exports.file_google_protobuf_duration = (0, file_js_1.fileDesc)("Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIgASgFQoMBChNjb20uZ29vZ2xlLnByb3RvYnVmQg1EdXJhdGlvblByb3RvUAFaMWdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2R1cmF0aW9ucGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw");
/**
* Describes the message google.protobuf.Duration.
* Use `create(DurationSchema)` to create a new message.
*/
exports.DurationSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_duration, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/empty.proto.
*/
export declare const file_google_protobuf_empty: GenFile;
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
*
* @generated from message google.protobuf.Empty
*/
export type Empty = Message<"google.protobuf.Empty"> & {};
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
*
* @generated from message google.protobuf.Empty
*/
export type EmptyJson = Record<string, never>;
/**
* Describes the message google.protobuf.Empty.
* Use `create(EmptySchema)` to create a new message.
*/
export declare const EmptySchema: GenMessage<Empty, {
jsonType: EmptyJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmptySchema = exports.file_google_protobuf_empty = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/empty.proto.
*/
exports.file_google_protobuf_empty = (0, file_js_1.fileDesc)("Chtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIHCgVFbXB0eUJ9ChNjb20uZ29vZ2xlLnByb3RvYnVmQgpFbXB0eVByb3RvUAFaLmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2VtcHR5cGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw");
/**
* Describes the message google.protobuf.Empty.
* Use `create(EmptySchema)` to create a new message.
*/
exports.EmptySchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_empty, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/field_mask.proto.
*/
export declare const file_google_protobuf_field_mask: GenFile;
/**
* `FieldMask` represents a set of symbolic field paths, for example:
*
* paths: "f.a"
* paths: "f.b.d"
*
* Here `f` represents a field in some root message, `a` and `b`
* fields in the message found in `f`, and `d` a field found in the
* message in `f.b`.
*
* Field masks are used to specify a subset of fields that should be
* returned by a get operation or modified by an update operation.
* Field masks also have a custom JSON encoding (see below).
*
* # Field Masks in Projections
*
* When used in the context of a projection, a response message or
* sub-message is filtered by the API to only contain those fields as
* specified in the mask. For example, if the mask in the previous
* example is applied to a response message as follows:
*
* f {
* a : 22
* b {
* d : 1
* x : 2
* }
* y : 13
* }
* z: 8
*
* The result will not contain specific values for fields x,y and z
* (their value will be set to the default, and omitted in proto text
* output):
*
*
* f {
* a : 22
* b {
* d : 1
* }
* }
*
* A repeated field is not allowed except at the last position of a
* paths string.
*
* If a FieldMask object is not present in a get operation, the
* operation applies to all fields (as if a FieldMask of all fields
* had been specified).
*
* Note that a field mask does not necessarily apply to the
* top-level response message. In case of a REST get operation, the
* field mask applies directly to the response, but in case of a REST
* list operation, the mask instead applies to each individual message
* in the returned resource list. In case of a REST custom method,
* other definitions may be used. Where the mask applies will be
* clearly documented together with its declaration in the API. In
* any case, the effect on the returned resource/resources is required
* behavior for APIs.
*
* # Field Masks in Update Operations
*
* A field mask in update operations specifies which fields of the
* targeted resource are going to be updated. The API is required
* to only change the values of the fields as specified in the mask
* and leave the others untouched. If a resource is passed in to
* describe the updated values, the API ignores the values of all
* fields not covered by the mask.
*
* If a repeated field is specified for an update operation, new values will
* be appended to the existing repeated field in the target resource. Note that
* a repeated field is only allowed in the last position of a `paths` string.
*
* If a sub-message is specified in the last position of the field mask for an
* update operation, then new value will be merged into the existing sub-message
* in the target resource.
*
* For example, given the target message:
*
* f {
* b {
* d: 1
* x: 2
* }
* c: [1]
* }
*
* And an update message:
*
* f {
* b {
* d: 10
* }
* c: [2]
* }
*
* then if the field mask is:
*
* paths: ["f.b", "f.c"]
*
* then the result will be:
*
* f {
* b {
* d: 10
* x: 2
* }
* c: [1, 2]
* }
*
* An implementation may provide options to override this default behavior for
* repeated and message fields.
*
* Note that libraries which implement FieldMask resolution have various
* different behaviors in the face of empty masks or the special "*" mask.
* When implementing a service you should confirm these cases have the
* appropriate behavior in the underlying FieldMask library that you desire,
* and you may need to special case those cases in your application code if
* the underlying field mask library behavior differs from your intended
* service semantics.
*
* Update methods implementing https://google.aip.dev/134
* - MUST support the special value * meaning "full replace"
* - MUST treat an omitted field mask as "replace fields which are present".
*
* Other methods implementing https://google.aip.dev/157
* - SHOULD support the special value "*" to mean "get all".
* - MUST treat an omitted field mask to mean "get all", unless otherwise
* documented.
*
* ## Considerations for HTTP REST
*
* The HTTP kind of an update operation which uses a field mask must
* be set to PATCH instead of PUT in order to satisfy HTTP semantics
* (PUT must only be used for full updates).
*
* # JSON Encoding of Field Masks
*
* In JSON, a field mask is encoded as a single string where paths are
* separated by a comma. Fields name in each path are converted
* to/from lower-camel naming conventions.
*
* As an example, consider the following message declarations:
*
* message Profile {
* User user = 1;
* Photo photo = 2;
* }
* message User {
* string display_name = 1;
* string address = 2;
* }
*
* In proto a field mask for `Profile` may look as such:
*
* mask {
* paths: "user.display_name"
* paths: "photo"
* }
*
* In JSON, the same mask is represented as below:
*
* {
* mask: "user.displayName,photo"
* }
*
* # Field Masks and Oneof Fields
*
* Field masks treat fields in oneofs just as regular fields. Consider the
* following message:
*
* message SampleMessage {
* oneof test_oneof {
* string name = 4;
* SubMessage sub_message = 9;
* }
* }
*
* The field mask can be:
*
* mask {
* paths: "name"
* }
*
* Or:
*
* mask {
* paths: "sub_message"
* }
*
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
*
* ## Field Mask Verification
*
* The implementation of any API method which has a FieldMask type field in the
* request should verify the included field paths, and return an
* `INVALID_ARGUMENT` error if any path is unmappable.
*
* @generated from message google.protobuf.FieldMask
*/
export type FieldMask = Message<"google.protobuf.FieldMask"> & {
/**
* The set of field mask paths.
*
* @generated from field: repeated string paths = 1;
*/
paths: string[];
};
/**
* `FieldMask` represents a set of symbolic field paths, for example:
*
* paths: "f.a"
* paths: "f.b.d"
*
* Here `f` represents a field in some root message, `a` and `b`
* fields in the message found in `f`, and `d` a field found in the
* message in `f.b`.
*
* Field masks are used to specify a subset of fields that should be
* returned by a get operation or modified by an update operation.
* Field masks also have a custom JSON encoding (see below).
*
* # Field Masks in Projections
*
* When used in the context of a projection, a response message or
* sub-message is filtered by the API to only contain those fields as
* specified in the mask. For example, if the mask in the previous
* example is applied to a response message as follows:
*
* f {
* a : 22
* b {
* d : 1
* x : 2
* }
* y : 13
* }
* z: 8
*
* The result will not contain specific values for fields x,y and z
* (their value will be set to the default, and omitted in proto text
* output):
*
*
* f {
* a : 22
* b {
* d : 1
* }
* }
*
* A repeated field is not allowed except at the last position of a
* paths string.
*
* If a FieldMask object is not present in a get operation, the
* operation applies to all fields (as if a FieldMask of all fields
* had been specified).
*
* Note that a field mask does not necessarily apply to the
* top-level response message. In case of a REST get operation, the
* field mask applies directly to the response, but in case of a REST
* list operation, the mask instead applies to each individual message
* in the returned resource list. In case of a REST custom method,
* other definitions may be used. Where the mask applies will be
* clearly documented together with its declaration in the API. In
* any case, the effect on the returned resource/resources is required
* behavior for APIs.
*
* # Field Masks in Update Operations
*
* A field mask in update operations specifies which fields of the
* targeted resource are going to be updated. The API is required
* to only change the values of the fields as specified in the mask
* and leave the others untouched. If a resource is passed in to
* describe the updated values, the API ignores the values of all
* fields not covered by the mask.
*
* If a repeated field is specified for an update operation, new values will
* be appended to the existing repeated field in the target resource. Note that
* a repeated field is only allowed in the last position of a `paths` string.
*
* If a sub-message is specified in the last position of the field mask for an
* update operation, then new value will be merged into the existing sub-message
* in the target resource.
*
* For example, given the target message:
*
* f {
* b {
* d: 1
* x: 2
* }
* c: [1]
* }
*
* And an update message:
*
* f {
* b {
* d: 10
* }
* c: [2]
* }
*
* then if the field mask is:
*
* paths: ["f.b", "f.c"]
*
* then the result will be:
*
* f {
* b {
* d: 10
* x: 2
* }
* c: [1, 2]
* }
*
* An implementation may provide options to override this default behavior for
* repeated and message fields.
*
* Note that libraries which implement FieldMask resolution have various
* different behaviors in the face of empty masks or the special "*" mask.
* When implementing a service you should confirm these cases have the
* appropriate behavior in the underlying FieldMask library that you desire,
* and you may need to special case those cases in your application code if
* the underlying field mask library behavior differs from your intended
* service semantics.
*
* Update methods implementing https://google.aip.dev/134
* - MUST support the special value * meaning "full replace"
* - MUST treat an omitted field mask as "replace fields which are present".
*
* Other methods implementing https://google.aip.dev/157
* - SHOULD support the special value "*" to mean "get all".
* - MUST treat an omitted field mask to mean "get all", unless otherwise
* documented.
*
* ## Considerations for HTTP REST
*
* The HTTP kind of an update operation which uses a field mask must
* be set to PATCH instead of PUT in order to satisfy HTTP semantics
* (PUT must only be used for full updates).
*
* # JSON Encoding of Field Masks
*
* In JSON, a field mask is encoded as a single string where paths are
* separated by a comma. Fields name in each path are converted
* to/from lower-camel naming conventions.
*
* As an example, consider the following message declarations:
*
* message Profile {
* User user = 1;
* Photo photo = 2;
* }
* message User {
* string display_name = 1;
* string address = 2;
* }
*
* In proto a field mask for `Profile` may look as such:
*
* mask {
* paths: "user.display_name"
* paths: "photo"
* }
*
* In JSON, the same mask is represented as below:
*
* {
* mask: "user.displayName,photo"
* }
*
* # Field Masks and Oneof Fields
*
* Field masks treat fields in oneofs just as regular fields. Consider the
* following message:
*
* message SampleMessage {
* oneof test_oneof {
* string name = 4;
* SubMessage sub_message = 9;
* }
* }
*
* The field mask can be:
*
* mask {
* paths: "name"
* }
*
* Or:
*
* mask {
* paths: "sub_message"
* }
*
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
*
* ## Field Mask Verification
*
* The implementation of any API method which has a FieldMask type field in the
* request should verify the included field paths, and return an
* `INVALID_ARGUMENT` error if any path is unmappable.
*
* @generated from message google.protobuf.FieldMask
*/
export type FieldMaskJson = string;
/**
* Describes the message google.protobuf.FieldMask.
* Use `create(FieldMaskSchema)` to create a new message.
*/
export declare const FieldMaskSchema: GenMessage<FieldMask, {
jsonType: FieldMaskJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldMaskSchema = exports.file_google_protobuf_field_mask = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/field_mask.proto.
*/
exports.file_google_protobuf_field_mask = (0, file_js_1.fileDesc)("CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnByb3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUKFAQoTY29tLmdvb2dsZS5wcm90b2J1ZkIORmllbGRNYXNrUHJvdG9QAVoyZ29vZ2xlLmdvbGFuZy5vcmcvcHJvdG9idWYvdHlwZXMva25vd24vZmllbGRtYXNrcGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw");
/**
* Describes the message google.protobuf.FieldMask.
* Use `create(FieldMaskSchema)` to create a new message.
*/
exports.FieldMaskSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_field_mask, 0);
import type { GenEnum, GenExtension, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { FeatureSet } from "./descriptor_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/go_features.proto.
*/
export declare const file_google_protobuf_go_features: GenFile;
/**
* @generated from message pb.GoFeatures
*/
export type GoFeatures = Message<"pb.GoFeatures"> & {
/**
* Whether or not to generate the deprecated UnmarshalJSON method for enums.
* Can only be true for proto using the Open Struct api.
*
* @generated from field: optional bool legacy_unmarshal_json_enum = 1;
*/
legacyUnmarshalJsonEnum: boolean;
/**
* One of OPEN, HYBRID or OPAQUE.
*
* @generated from field: optional pb.GoFeatures.APILevel api_level = 2;
*/
apiLevel: GoFeatures_APILevel;
/**
* @generated from field: optional pb.GoFeatures.StripEnumPrefix strip_enum_prefix = 3;
*/
stripEnumPrefix: GoFeatures_StripEnumPrefix;
/**
* @generated from field: optional pb.GoFeatures.OptimizeModeFeature.OptimizeMode optimize_mode = 4;
*/
optimizeMode: GoFeatures_OptimizeModeFeature_OptimizeMode;
};
/**
* @generated from message pb.GoFeatures
*/
export type GoFeaturesJson = {
/**
* Whether or not to generate the deprecated UnmarshalJSON method for enums.
* Can only be true for proto using the Open Struct api.
*
* @generated from field: optional bool legacy_unmarshal_json_enum = 1;
*/
legacyUnmarshalJsonEnum?: boolean;
/**
* One of OPEN, HYBRID or OPAQUE.
*
* @generated from field: optional pb.GoFeatures.APILevel api_level = 2;
*/
apiLevel?: GoFeatures_APILevelJson;
/**
* @generated from field: optional pb.GoFeatures.StripEnumPrefix strip_enum_prefix = 3;
*/
stripEnumPrefix?: GoFeatures_StripEnumPrefixJson;
/**
* @generated from field: optional pb.GoFeatures.OptimizeModeFeature.OptimizeMode optimize_mode = 4;
*/
optimizeMode?: GoFeatures_OptimizeModeFeature_OptimizeModeJson;
};
/**
* Describes the message pb.GoFeatures.
* Use `create(GoFeaturesSchema)` to create a new message.
*/
export declare const GoFeaturesSchema: GenMessage<GoFeatures, {
jsonType: GoFeaturesJson;
}>;
/**
* Wrap the OptimizeMode enum in a message for scoping:
* This way, users can type shorter names (SPEED, CODE_SIZE).
*
* @generated from message pb.GoFeatures.OptimizeModeFeature
*/
export type GoFeatures_OptimizeModeFeature = Message<"pb.GoFeatures.OptimizeModeFeature"> & {};
/**
* Wrap the OptimizeMode enum in a message for scoping:
* This way, users can type shorter names (SPEED, CODE_SIZE).
*
* @generated from message pb.GoFeatures.OptimizeModeFeature
*/
export type GoFeatures_OptimizeModeFeatureJson = {};
/**
* Describes the message pb.GoFeatures.OptimizeModeFeature.
* Use `create(GoFeatures_OptimizeModeFeatureSchema)` to create a new message.
*/
export declare const GoFeatures_OptimizeModeFeatureSchema: GenMessage<GoFeatures_OptimizeModeFeature, {
jsonType: GoFeatures_OptimizeModeFeatureJson;
}>;
/**
* The name of this enum matches OptimizeMode in descriptor.proto.
*
* @generated from enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode
*/
export declare enum GoFeatures_OptimizeModeFeature_OptimizeMode {
/**
* OPTIMIZE_MODE_UNSPECIFIED results in falling back to the default
* (optimize for code size), but needs to be a separate value to distinguish
* between an explicitly set optimize mode or a missing optimize mode.
*
* @generated from enum value: OPTIMIZE_MODE_UNSPECIFIED = 0;
*/
OPTIMIZE_MODE_UNSPECIFIED = 0,
/**
* @generated from enum value: SPEED = 1;
*/
SPEED = 1,
/**
* There is no enum entry for LITE_RUNTIME (descriptor.proto),
* because Go Protobuf does not have the concept of a lite runtime.
*
* @generated from enum value: CODE_SIZE = 2;
*/
CODE_SIZE = 2
}
/**
* The name of this enum matches OptimizeMode in descriptor.proto.
*
* @generated from enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode
*/
export type GoFeatures_OptimizeModeFeature_OptimizeModeJson = "OPTIMIZE_MODE_UNSPECIFIED" | "SPEED" | "CODE_SIZE";
/**
* Describes the enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode.
*/
export declare const GoFeatures_OptimizeModeFeature_OptimizeModeSchema: GenEnum<GoFeatures_OptimizeModeFeature_OptimizeMode, GoFeatures_OptimizeModeFeature_OptimizeModeJson>;
/**
* @generated from enum pb.GoFeatures.APILevel
*/
export declare enum GoFeatures_APILevel {
/**
* API_LEVEL_UNSPECIFIED results in selecting the OPEN API,
* but needs to be a separate value to distinguish between
* an explicitly set api level or a missing api level.
*
* @generated from enum value: API_LEVEL_UNSPECIFIED = 0;
*/
API_LEVEL_UNSPECIFIED = 0,
/**
* @generated from enum value: API_OPEN = 1;
*/
API_OPEN = 1,
/**
* @generated from enum value: API_HYBRID = 2;
*/
API_HYBRID = 2,
/**
* @generated from enum value: API_OPAQUE = 3;
*/
API_OPAQUE = 3
}
/**
* @generated from enum pb.GoFeatures.APILevel
*/
export type GoFeatures_APILevelJson = "API_LEVEL_UNSPECIFIED" | "API_OPEN" | "API_HYBRID" | "API_OPAQUE";
/**
* Describes the enum pb.GoFeatures.APILevel.
*/
export declare const GoFeatures_APILevelSchema: GenEnum<GoFeatures_APILevel, GoFeatures_APILevelJson>;
/**
* @generated from enum pb.GoFeatures.StripEnumPrefix
*/
export declare enum GoFeatures_StripEnumPrefix {
/**
* @generated from enum value: STRIP_ENUM_PREFIX_UNSPECIFIED = 0;
*/
UNSPECIFIED = 0,
/**
* @generated from enum value: STRIP_ENUM_PREFIX_KEEP = 1;
*/
KEEP = 1,
/**
* @generated from enum value: STRIP_ENUM_PREFIX_GENERATE_BOTH = 2;
*/
GENERATE_BOTH = 2,
/**
* @generated from enum value: STRIP_ENUM_PREFIX_STRIP = 3;
*/
STRIP = 3
}
/**
* @generated from enum pb.GoFeatures.StripEnumPrefix
*/
export type GoFeatures_StripEnumPrefixJson = "STRIP_ENUM_PREFIX_UNSPECIFIED" | "STRIP_ENUM_PREFIX_KEEP" | "STRIP_ENUM_PREFIX_GENERATE_BOTH" | "STRIP_ENUM_PREFIX_STRIP";
/**
* Describes the enum pb.GoFeatures.StripEnumPrefix.
*/
export declare const GoFeatures_StripEnumPrefixSchema: GenEnum<GoFeatures_StripEnumPrefix, GoFeatures_StripEnumPrefixJson>;
/**
* @generated from extension: optional pb.GoFeatures go = 1002;
*/
export declare const go: GenExtension<FeatureSet, GoFeatures>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.go = exports.GoFeatures_StripEnumPrefixSchema = exports.GoFeatures_StripEnumPrefix = exports.GoFeatures_APILevelSchema = exports.GoFeatures_APILevel = exports.GoFeatures_OptimizeModeFeature_OptimizeModeSchema = exports.GoFeatures_OptimizeModeFeature_OptimizeMode = exports.GoFeatures_OptimizeModeFeatureSchema = exports.GoFeaturesSchema = exports.file_google_protobuf_go_features = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const descriptor_pb_js_1 = require("./descriptor_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
const extension_js_1 = require("../../../../codegenv2/extension.js");
/**
* Describes the file google/protobuf/go_features.proto.
*/
exports.file_google_protobuf_go_features = (0, file_js_1.fileDesc)("CiFnb29nbGUvcHJvdG9idWYvZ29fZmVhdHVyZXMucHJvdG8SAnBiItEGCgpHb0ZlYXR1cmVzEqUBChpsZWdhY3lfdW5tYXJzaGFsX2pzb25fZW51bRgBIAEoCEKAAYgBAZgBBpgBAaIBCRIEdHJ1ZRiEB6IBChIFZmFsc2UY5weyAVsI6AcQ6AcaU1RoZSBsZWdhY3kgVW5tYXJzaGFsSlNPTiBBUEkgaXMgZGVwcmVjYXRlZCBhbmQgd2lsbCBiZSByZW1vdmVkIGluIGEgZnV0dXJlIGVkaXRpb24uEmoKCWFwaV9sZXZlbBgCIAEoDjIXLnBiLkdvRmVhdHVyZXMuQVBJTGV2ZWxCPogBAZgBA5gBAaIBGhIVQVBJX0xFVkVMX1VOU1BFQ0lGSUVEGIQHogEPEgpBUElfT1BBUVVFGOkHsgEDCOgHEmsKEXN0cmlwX2VudW1fcHJlZml4GAMgASgOMh4ucGIuR29GZWF0dXJlcy5TdHJpcEVudW1QcmVmaXhCMIgBAZgBBpgBB5gBAaIBGxIWU1RSSVBfRU5VTV9QUkVGSVhfS0VFUBiEB7IBAwjpBxJ4Cg1vcHRpbWl6ZV9tb2RlGAQgASgOMi8ucGIuR29GZWF0dXJlcy5PcHRpbWl6ZU1vZGVGZWF0dXJlLk9wdGltaXplTW9kZUIwiAEBmAEDmAEBogEeEhlPUFRJTUlaRV9NT0RFX1VOU1BFQ0lGSUVEGIQHsgEDCOkHGl4KE09wdGltaXplTW9kZUZlYXR1cmUiRwoMT3B0aW1pemVNb2RlEh0KGU9QVElNSVpFX01PREVfVU5TUEVDSUZJRUQQABIJCgVTUEVFRBABEg0KCUNPREVfU0laRRACIlMKCEFQSUxldmVsEhkKFUFQSV9MRVZFTF9VTlNQRUNJRklFRBAAEgwKCEFQSV9PUEVOEAESDgoKQVBJX0hZQlJJRBACEg4KCkFQSV9PUEFRVUUQAyKSAQoPU3RyaXBFbnVtUHJlZml4EiEKHVNUUklQX0VOVU1fUFJFRklYX1VOU1BFQ0lGSUVEEAASGgoWU1RSSVBfRU5VTV9QUkVGSVhfS0VFUBABEiMKH1NUUklQX0VOVU1fUFJFRklYX0dFTkVSQVRFX0JPVEgQAhIbChdTVFJJUF9FTlVNX1BSRUZJWF9TVFJJUBADOjwKAmdvEhsuZ29vZ2xlLnByb3RvYnVmLkZlYXR1cmVTZXQY6gcgASgLMg4ucGIuR29GZWF0dXJlc1ICZ29CL1otZ29vZ2xlLmdvbGFuZy5vcmcvcHJvdG9idWYvdHlwZXMvZ29mZWF0dXJlc3Bi", [descriptor_pb_js_1.file_google_protobuf_descriptor]);
/**
* Describes the message pb.GoFeatures.
* Use `create(GoFeaturesSchema)` to create a new message.
*/
exports.GoFeaturesSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_go_features, 0);
/**
* Describes the message pb.GoFeatures.OptimizeModeFeature.
* Use `create(GoFeatures_OptimizeModeFeatureSchema)` to create a new message.
*/
exports.GoFeatures_OptimizeModeFeatureSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_go_features, 0, 0);
/**
* The name of this enum matches OptimizeMode in descriptor.proto.
*
* @generated from enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode
*/
var GoFeatures_OptimizeModeFeature_OptimizeMode;
(function (GoFeatures_OptimizeModeFeature_OptimizeMode) {
/**
* OPTIMIZE_MODE_UNSPECIFIED results in falling back to the default
* (optimize for code size), but needs to be a separate value to distinguish
* between an explicitly set optimize mode or a missing optimize mode.
*
* @generated from enum value: OPTIMIZE_MODE_UNSPECIFIED = 0;
*/
GoFeatures_OptimizeModeFeature_OptimizeMode[GoFeatures_OptimizeModeFeature_OptimizeMode["OPTIMIZE_MODE_UNSPECIFIED"] = 0] = "OPTIMIZE_MODE_UNSPECIFIED";
/**
* @generated from enum value: SPEED = 1;
*/
GoFeatures_OptimizeModeFeature_OptimizeMode[GoFeatures_OptimizeModeFeature_OptimizeMode["SPEED"] = 1] = "SPEED";
/**
* There is no enum entry for LITE_RUNTIME (descriptor.proto),
* because Go Protobuf does not have the concept of a lite runtime.
*
* @generated from enum value: CODE_SIZE = 2;
*/
GoFeatures_OptimizeModeFeature_OptimizeMode[GoFeatures_OptimizeModeFeature_OptimizeMode["CODE_SIZE"] = 2] = "CODE_SIZE";
})(GoFeatures_OptimizeModeFeature_OptimizeMode || (exports.GoFeatures_OptimizeModeFeature_OptimizeMode = GoFeatures_OptimizeModeFeature_OptimizeMode = {}));
/**
* Describes the enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode.
*/
exports.GoFeatures_OptimizeModeFeature_OptimizeModeSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_go_features, 0, 0, 0);
/**
* @generated from enum pb.GoFeatures.APILevel
*/
var GoFeatures_APILevel;
(function (GoFeatures_APILevel) {
/**
* API_LEVEL_UNSPECIFIED results in selecting the OPEN API,
* but needs to be a separate value to distinguish between
* an explicitly set api level or a missing api level.
*
* @generated from enum value: API_LEVEL_UNSPECIFIED = 0;
*/
GoFeatures_APILevel[GoFeatures_APILevel["API_LEVEL_UNSPECIFIED"] = 0] = "API_LEVEL_UNSPECIFIED";
/**
* @generated from enum value: API_OPEN = 1;
*/
GoFeatures_APILevel[GoFeatures_APILevel["API_OPEN"] = 1] = "API_OPEN";
/**
* @generated from enum value: API_HYBRID = 2;
*/
GoFeatures_APILevel[GoFeatures_APILevel["API_HYBRID"] = 2] = "API_HYBRID";
/**
* @generated from enum value: API_OPAQUE = 3;
*/
GoFeatures_APILevel[GoFeatures_APILevel["API_OPAQUE"] = 3] = "API_OPAQUE";
})(GoFeatures_APILevel || (exports.GoFeatures_APILevel = GoFeatures_APILevel = {}));
/**
* Describes the enum pb.GoFeatures.APILevel.
*/
exports.GoFeatures_APILevelSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_go_features, 0, 0);
/**
* @generated from enum pb.GoFeatures.StripEnumPrefix
*/
var GoFeatures_StripEnumPrefix;
(function (GoFeatures_StripEnumPrefix) {
/**
* @generated from enum value: STRIP_ENUM_PREFIX_UNSPECIFIED = 0;
*/
GoFeatures_StripEnumPrefix[GoFeatures_StripEnumPrefix["UNSPECIFIED"] = 0] = "UNSPECIFIED";
/**
* @generated from enum value: STRIP_ENUM_PREFIX_KEEP = 1;
*/
GoFeatures_StripEnumPrefix[GoFeatures_StripEnumPrefix["KEEP"] = 1] = "KEEP";
/**
* @generated from enum value: STRIP_ENUM_PREFIX_GENERATE_BOTH = 2;
*/
GoFeatures_StripEnumPrefix[GoFeatures_StripEnumPrefix["GENERATE_BOTH"] = 2] = "GENERATE_BOTH";
/**
* @generated from enum value: STRIP_ENUM_PREFIX_STRIP = 3;
*/
GoFeatures_StripEnumPrefix[GoFeatures_StripEnumPrefix["STRIP"] = 3] = "STRIP";
})(GoFeatures_StripEnumPrefix || (exports.GoFeatures_StripEnumPrefix = GoFeatures_StripEnumPrefix = {}));
/**
* Describes the enum pb.GoFeatures.StripEnumPrefix.
*/
exports.GoFeatures_StripEnumPrefixSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_go_features, 0, 1);
/**
* @generated from extension: optional pb.GoFeatures go = 1002;
*/
exports.go = (0, extension_js_1.extDesc)(exports.file_google_protobuf_go_features, 0);
import type { GenEnum, GenExtension, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { FeatureSet } from "./descriptor_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/java_features.proto.
*/
export declare const file_google_protobuf_java_features: GenFile;
/**
* @generated from message pb.JavaFeatures
*/
export type JavaFeatures = Message<"pb.JavaFeatures"> & {
/**
* Whether or not to treat an enum field as closed. This option is only
* applicable to enum fields, and will be removed in the future. It is
* consistent with the legacy behavior of using proto3 enum types for proto2
* fields.
*
* @generated from field: optional bool legacy_closed_enum = 1;
*/
legacyClosedEnum: boolean;
/**
* @generated from field: optional pb.JavaFeatures.Utf8Validation utf8_validation = 2;
*/
utf8Validation: JavaFeatures_Utf8Validation;
/**
* Allows creation of large Java enums, extending beyond the standard
* constant limits imposed by the Java language.
*
* @generated from field: optional bool large_enum = 3;
*/
largeEnum: boolean;
/**
* Whether to use the old default outer class name scheme, or the new feature
* which adds a "Proto" suffix to the outer class name.
*
* Users will not be able to set this option, because we removed it in the
* same edition that it was introduced. But we use it to determine which
* naming scheme to use for outer class name defaults.
*
* @generated from field: optional bool use_old_outer_classname_default = 4;
*/
useOldOuterClassnameDefault: boolean;
/**
* Whether to nest the generated class in the generated file class. This is
* only applicable to *top-level* messages, enums, and services.
*
* @generated from field: optional pb.JavaFeatures.NestInFileClassFeature.NestInFileClass nest_in_file_class = 5;
*/
nestInFileClass: JavaFeatures_NestInFileClassFeature_NestInFileClass;
};
/**
* @generated from message pb.JavaFeatures
*/
export type JavaFeaturesJson = {
/**
* Whether or not to treat an enum field as closed. This option is only
* applicable to enum fields, and will be removed in the future. It is
* consistent with the legacy behavior of using proto3 enum types for proto2
* fields.
*
* @generated from field: optional bool legacy_closed_enum = 1;
*/
legacyClosedEnum?: boolean;
/**
* @generated from field: optional pb.JavaFeatures.Utf8Validation utf8_validation = 2;
*/
utf8Validation?: JavaFeatures_Utf8ValidationJson;
/**
* Allows creation of large Java enums, extending beyond the standard
* constant limits imposed by the Java language.
*
* @generated from field: optional bool large_enum = 3;
*/
largeEnum?: boolean;
/**
* Whether to use the old default outer class name scheme, or the new feature
* which adds a "Proto" suffix to the outer class name.
*
* Users will not be able to set this option, because we removed it in the
* same edition that it was introduced. But we use it to determine which
* naming scheme to use for outer class name defaults.
*
* @generated from field: optional bool use_old_outer_classname_default = 4;
*/
useOldOuterClassnameDefault?: boolean;
/**
* Whether to nest the generated class in the generated file class. This is
* only applicable to *top-level* messages, enums, and services.
*
* @generated from field: optional pb.JavaFeatures.NestInFileClassFeature.NestInFileClass nest_in_file_class = 5;
*/
nestInFileClass?: JavaFeatures_NestInFileClassFeature_NestInFileClassJson;
};
/**
* Describes the message pb.JavaFeatures.
* Use `create(JavaFeaturesSchema)` to create a new message.
*/
export declare const JavaFeaturesSchema: GenMessage<JavaFeatures, {
jsonType: JavaFeaturesJson;
}>;
/**
* @generated from message pb.JavaFeatures.NestInFileClassFeature
*/
export type JavaFeatures_NestInFileClassFeature = Message<"pb.JavaFeatures.NestInFileClassFeature"> & {};
/**
* @generated from message pb.JavaFeatures.NestInFileClassFeature
*/
export type JavaFeatures_NestInFileClassFeatureJson = {};
/**
* Describes the message pb.JavaFeatures.NestInFileClassFeature.
* Use `create(JavaFeatures_NestInFileClassFeatureSchema)` to create a new message.
*/
export declare const JavaFeatures_NestInFileClassFeatureSchema: GenMessage<JavaFeatures_NestInFileClassFeature, {
jsonType: JavaFeatures_NestInFileClassFeatureJson;
}>;
/**
* @generated from enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass
*/
export declare enum JavaFeatures_NestInFileClassFeature_NestInFileClass {
/**
* Invalid default, which should never be used.
*
* @generated from enum value: NEST_IN_FILE_CLASS_UNKNOWN = 0;
*/
NEST_IN_FILE_CLASS_UNKNOWN = 0,
/**
* Do not nest the generated class in the file class.
*
* @generated from enum value: NO = 1;
*/
NO = 1,
/**
* Nest the generated class in the file class.
*
* @generated from enum value: YES = 2;
*/
YES = 2,
/**
* Fall back to the `java_multiple_files` option. Users won't be able to
* set this option.
*
* @generated from enum value: LEGACY = 3;
*/
LEGACY = 3
}
/**
* @generated from enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass
*/
export type JavaFeatures_NestInFileClassFeature_NestInFileClassJson = "NEST_IN_FILE_CLASS_UNKNOWN" | "NO" | "YES" | "LEGACY";
/**
* Describes the enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass.
*/
export declare const JavaFeatures_NestInFileClassFeature_NestInFileClassSchema: GenEnum<JavaFeatures_NestInFileClassFeature_NestInFileClass, JavaFeatures_NestInFileClassFeature_NestInFileClassJson>;
/**
* The UTF8 validation strategy to use.
*
* @generated from enum pb.JavaFeatures.Utf8Validation
*/
export declare enum JavaFeatures_Utf8Validation {
/**
* Invalid default, which should never be used.
*
* @generated from enum value: UTF8_VALIDATION_UNKNOWN = 0;
*/
UTF8_VALIDATION_UNKNOWN = 0,
/**
* Respect the UTF8 validation behavior specified by the global
* utf8_validation feature.
*
* @generated from enum value: DEFAULT = 1;
*/
DEFAULT = 1,
/**
* Verifies UTF8 validity overriding the global utf8_validation
* feature. This represents the legacy java_string_check_utf8 option.
*
* @generated from enum value: VERIFY = 2;
*/
VERIFY = 2
}
/**
* The UTF8 validation strategy to use.
*
* @generated from enum pb.JavaFeatures.Utf8Validation
*/
export type JavaFeatures_Utf8ValidationJson = "UTF8_VALIDATION_UNKNOWN" | "DEFAULT" | "VERIFY";
/**
* Describes the enum pb.JavaFeatures.Utf8Validation.
*/
export declare const JavaFeatures_Utf8ValidationSchema: GenEnum<JavaFeatures_Utf8Validation, JavaFeatures_Utf8ValidationJson>;
/**
* @generated from extension: optional pb.JavaFeatures java = 1001;
*/
export declare const java: GenExtension<FeatureSet, JavaFeatures>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.java = exports.JavaFeatures_Utf8ValidationSchema = exports.JavaFeatures_Utf8Validation = exports.JavaFeatures_NestInFileClassFeature_NestInFileClassSchema = exports.JavaFeatures_NestInFileClassFeature_NestInFileClass = exports.JavaFeatures_NestInFileClassFeatureSchema = exports.JavaFeaturesSchema = exports.file_google_protobuf_java_features = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const descriptor_pb_js_1 = require("./descriptor_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
const extension_js_1 = require("../../../../codegenv2/extension.js");
/**
* Describes the file google/protobuf/java_features.proto.
*/
exports.file_google_protobuf_java_features = (0, file_js_1.fileDesc)("CiNnb29nbGUvcHJvdG9idWYvamF2YV9mZWF0dXJlcy5wcm90bxICcGIigwgKDEphdmFGZWF0dXJlcxL+AQoSbGVnYWN5X2Nsb3NlZF9lbnVtGAEgASgIQuEBiAEBmAEEmAEBogEJEgR0cnVlGIQHogEKEgVmYWxzZRjnB7IBuwEI6AcQ6AcasgFUaGUgbGVnYWN5IGNsb3NlZCBlbnVtIGJlaGF2aW9yIGluIEphdmEgaXMgZGVwcmVjYXRlZCBhbmQgaXMgc2NoZWR1bGVkIHRvIGJlIHJlbW92ZWQgaW4gZWRpdGlvbiAyMDI1LiAgU2VlIGh0dHA6Ly9wcm90b2J1Zi5kZXYvcHJvZ3JhbW1pbmctZ3VpZGVzL2VudW0vI2phdmEgZm9yIG1vcmUgaW5mb3JtYXRpb24uEp8CCg91dGY4X3ZhbGlkYXRpb24YAiABKA4yHy5wYi5KYXZhRmVhdHVyZXMuVXRmOFZhbGlkYXRpb25C5AGIAQGYAQSYAQGiAQwSB0RFRkFVTFQYhAeyAcgBCOgHEOkHGr8BVGhlIEphdmEtc3BlY2lmaWMgdXRmOCB2YWxpZGF0aW9uIGZlYXR1cmUgaXMgZGVwcmVjYXRlZCBhbmQgaXMgc2NoZWR1bGVkIHRvIGJlIHJlbW92ZWQgaW4gZWRpdGlvbiAyMDI1LiAgVXRmOCB2YWxpZGF0aW9uIGJlaGF2aW9yIHNob3VsZCB1c2UgdGhlIGdsb2JhbCBjcm9zcy1sYW5ndWFnZSB1dGY4X3ZhbGlkYXRpb24gZmVhdHVyZS4SMAoKbGFyZ2VfZW51bRgDIAEoCEIciAEBmAEGmAEBogEKEgVmYWxzZRiEB7IBAwjpBxJRCh91c2Vfb2xkX291dGVyX2NsYXNzbmFtZV9kZWZhdWx0GAQgASgIQiiIAQGYAQGiAQkSBHRydWUYhAeiAQoSBWZhbHNlGOkHsgEGCOkHIOkHEn8KEm5lc3RfaW5fZmlsZV9jbGFzcxgFIAEoDjI3LnBiLkphdmFGZWF0dXJlcy5OZXN0SW5GaWxlQ2xhc3NGZWF0dXJlLk5lc3RJbkZpbGVDbGFzc0IqiAEBmAEDmAEGmAEIogELEgZMRUdBQ1kYhAeiAQcSAk5PGOkHsgEDCOkHGnwKFk5lc3RJbkZpbGVDbGFzc0ZlYXR1cmUiWAoPTmVzdEluRmlsZUNsYXNzEh4KGk5FU1RfSU5fRklMRV9DTEFTU19VTktOT1dOEAASBgoCTk8QARIHCgNZRVMQAhIUCgZMRUdBQ1kQAxoIIgYI6Qcg6QdKCAgBEICAgIACIkYKDlV0ZjhWYWxpZGF0aW9uEhsKF1VURjhfVkFMSURBVElPTl9VTktOT1dOEAASCwoHREVGQVVMVBABEgoKBlZFUklGWRACSgQIBhAHOkIKBGphdmESGy5nb29nbGUucHJvdG9idWYuRmVhdHVyZVNldBjpByABKAsyEC5wYi5KYXZhRmVhdHVyZXNSBGphdmFCKAoTY29tLmdvb2dsZS5wcm90b2J1ZkIRSmF2YUZlYXR1cmVzUHJvdG8", [descriptor_pb_js_1.file_google_protobuf_descriptor]);
/**
* Describes the message pb.JavaFeatures.
* Use `create(JavaFeaturesSchema)` to create a new message.
*/
exports.JavaFeaturesSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_java_features, 0);
/**
* Describes the message pb.JavaFeatures.NestInFileClassFeature.
* Use `create(JavaFeatures_NestInFileClassFeatureSchema)` to create a new message.
*/
exports.JavaFeatures_NestInFileClassFeatureSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_java_features, 0, 0);
/**
* @generated from enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass
*/
var JavaFeatures_NestInFileClassFeature_NestInFileClass;
(function (JavaFeatures_NestInFileClassFeature_NestInFileClass) {
/**
* Invalid default, which should never be used.
*
* @generated from enum value: NEST_IN_FILE_CLASS_UNKNOWN = 0;
*/
JavaFeatures_NestInFileClassFeature_NestInFileClass[JavaFeatures_NestInFileClassFeature_NestInFileClass["NEST_IN_FILE_CLASS_UNKNOWN"] = 0] = "NEST_IN_FILE_CLASS_UNKNOWN";
/**
* Do not nest the generated class in the file class.
*
* @generated from enum value: NO = 1;
*/
JavaFeatures_NestInFileClassFeature_NestInFileClass[JavaFeatures_NestInFileClassFeature_NestInFileClass["NO"] = 1] = "NO";
/**
* Nest the generated class in the file class.
*
* @generated from enum value: YES = 2;
*/
JavaFeatures_NestInFileClassFeature_NestInFileClass[JavaFeatures_NestInFileClassFeature_NestInFileClass["YES"] = 2] = "YES";
/**
* Fall back to the `java_multiple_files` option. Users won't be able to
* set this option.
*
* @generated from enum value: LEGACY = 3;
*/
JavaFeatures_NestInFileClassFeature_NestInFileClass[JavaFeatures_NestInFileClassFeature_NestInFileClass["LEGACY"] = 3] = "LEGACY";
})(JavaFeatures_NestInFileClassFeature_NestInFileClass || (exports.JavaFeatures_NestInFileClassFeature_NestInFileClass = JavaFeatures_NestInFileClassFeature_NestInFileClass = {}));
/**
* Describes the enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass.
*/
exports.JavaFeatures_NestInFileClassFeature_NestInFileClassSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_java_features, 0, 0, 0);
/**
* The UTF8 validation strategy to use.
*
* @generated from enum pb.JavaFeatures.Utf8Validation
*/
var JavaFeatures_Utf8Validation;
(function (JavaFeatures_Utf8Validation) {
/**
* Invalid default, which should never be used.
*
* @generated from enum value: UTF8_VALIDATION_UNKNOWN = 0;
*/
JavaFeatures_Utf8Validation[JavaFeatures_Utf8Validation["UTF8_VALIDATION_UNKNOWN"] = 0] = "UTF8_VALIDATION_UNKNOWN";
/**
* Respect the UTF8 validation behavior specified by the global
* utf8_validation feature.
*
* @generated from enum value: DEFAULT = 1;
*/
JavaFeatures_Utf8Validation[JavaFeatures_Utf8Validation["DEFAULT"] = 1] = "DEFAULT";
/**
* Verifies UTF8 validity overriding the global utf8_validation
* feature. This represents the legacy java_string_check_utf8 option.
*
* @generated from enum value: VERIFY = 2;
*/
JavaFeatures_Utf8Validation[JavaFeatures_Utf8Validation["VERIFY"] = 2] = "VERIFY";
})(JavaFeatures_Utf8Validation || (exports.JavaFeatures_Utf8Validation = JavaFeatures_Utf8Validation = {}));
/**
* Describes the enum pb.JavaFeatures.Utf8Validation.
*/
exports.JavaFeatures_Utf8ValidationSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_java_features, 0, 0);
/**
* @generated from extension: optional pb.JavaFeatures java = 1001;
*/
exports.java = (0, extension_js_1.extDesc)(exports.file_google_protobuf_java_features, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/source_context.proto.
*/
export declare const file_google_protobuf_source_context: GenFile;
/**
* `SourceContext` represents information about the source of a
* protobuf element, like the file in which it is defined.
*
* @generated from message google.protobuf.SourceContext
*/
export type SourceContext = Message<"google.protobuf.SourceContext"> & {
/**
* The path-qualified name of the .proto file that contained the associated
* protobuf element. For example: `"google/protobuf/source_context.proto"`.
*
* @generated from field: string file_name = 1;
*/
fileName: string;
};
/**
* `SourceContext` represents information about the source of a
* protobuf element, like the file in which it is defined.
*
* @generated from message google.protobuf.SourceContext
*/
export type SourceContextJson = {
/**
* The path-qualified name of the .proto file that contained the associated
* protobuf element. For example: `"google/protobuf/source_context.proto"`.
*
* @generated from field: string file_name = 1;
*/
fileName?: string;
};
/**
* Describes the message google.protobuf.SourceContext.
* Use `create(SourceContextSchema)` to create a new message.
*/
export declare const SourceContextSchema: GenMessage<SourceContext, {
jsonType: SourceContextJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceContextSchema = exports.file_google_protobuf_source_context = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/source_context.proto.
*/
exports.file_google_protobuf_source_context = (0, file_js_1.fileDesc)("CiRnb29nbGUvcHJvdG9idWYvc291cmNlX2NvbnRleHQucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIiCg1Tb3VyY2VDb250ZXh0EhEKCWZpbGVfbmFtZRgBIAEoCUKKAQoTY29tLmdvb2dsZS5wcm90b2J1ZkISU291cmNlQ29udGV4dFByb3RvUAFaNmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3NvdXJjZWNvbnRleHRwYqICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z");
/**
* Describes the message google.protobuf.SourceContext.
* Use `create(SourceContextSchema)` to create a new message.
*/
exports.SourceContextSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_source_context, 0);
import type { GenEnum, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
import type { JsonObject, JsonValue } from "../../../../json-value.js";
/**
* Describes the file google/protobuf/struct.proto.
*/
export declare const file_google_protobuf_struct: GenFile;
/**
* `Struct` represents a structured data value, consisting of fields
* which map to dynamically typed values. In some languages, `Struct`
* might be supported by a native representation. For example, in
* scripting languages like JS a struct is represented as an
* object. The details of that representation are described together
* with the proto support for the language.
*
* The JSON representation for `Struct` is JSON object.
*
* @generated from message google.protobuf.Struct
*/
export type Struct = Message<"google.protobuf.Struct"> & {
/**
* Unordered map of dynamically typed values.
*
* @generated from field: map<string, google.protobuf.Value> fields = 1;
*/
fields: {
[key: string]: Value;
};
};
/**
* `Struct` represents a structured data value, consisting of fields
* which map to dynamically typed values. In some languages, `Struct`
* might be supported by a native representation. For example, in
* scripting languages like JS a struct is represented as an
* object. The details of that representation are described together
* with the proto support for the language.
*
* The JSON representation for `Struct` is JSON object.
*
* @generated from message google.protobuf.Struct
*/
export type StructJson = JsonObject;
/**
* Describes the message google.protobuf.Struct.
* Use `create(StructSchema)` to create a new message.
*/
export declare const StructSchema: GenMessage<Struct, {
jsonType: StructJson;
}>;
/**
* `Value` represents a dynamically typed value which can be either
* null, a number, a string, a boolean, a recursive struct value, or a
* list of values. A producer of value is expected to set one of these
* variants. Absence of any variant indicates an error.
*
* The JSON representation for `Value` is JSON value.
*
* @generated from message google.protobuf.Value
*/
export type Value = Message<"google.protobuf.Value"> & {
/**
* The kind of value.
*
* @generated from oneof google.protobuf.Value.kind
*/
kind: {
/**
* Represents a null value.
*
* @generated from field: google.protobuf.NullValue null_value = 1;
*/
value: NullValue;
case: "nullValue";
} | {
/**
* Represents a double value.
*
* @generated from field: double number_value = 2;
*/
value: number;
case: "numberValue";
} | {
/**
* Represents a string value.
*
* @generated from field: string string_value = 3;
*/
value: string;
case: "stringValue";
} | {
/**
* Represents a boolean value.
*
* @generated from field: bool bool_value = 4;
*/
value: boolean;
case: "boolValue";
} | {
/**
* Represents a structured value.
*
* @generated from field: google.protobuf.Struct struct_value = 5;
*/
value: Struct;
case: "structValue";
} | {
/**
* Represents a repeated `Value`.
*
* @generated from field: google.protobuf.ListValue list_value = 6;
*/
value: ListValue;
case: "listValue";
} | {
case: undefined;
value?: undefined;
};
};
/**
* `Value` represents a dynamically typed value which can be either
* null, a number, a string, a boolean, a recursive struct value, or a
* list of values. A producer of value is expected to set one of these
* variants. Absence of any variant indicates an error.
*
* The JSON representation for `Value` is JSON value.
*
* @generated from message google.protobuf.Value
*/
export type ValueJson = JsonValue;
/**
* Describes the message google.protobuf.Value.
* Use `create(ValueSchema)` to create a new message.
*/
export declare const ValueSchema: GenMessage<Value, {
jsonType: ValueJson;
}>;
/**
* `ListValue` is a wrapper around a repeated field of values.
*
* The JSON representation for `ListValue` is JSON array.
*
* @generated from message google.protobuf.ListValue
*/
export type ListValue = Message<"google.protobuf.ListValue"> & {
/**
* Repeated field of dynamically typed values.
*
* @generated from field: repeated google.protobuf.Value values = 1;
*/
values: Value[];
};
/**
* `ListValue` is a wrapper around a repeated field of values.
*
* The JSON representation for `ListValue` is JSON array.
*
* @generated from message google.protobuf.ListValue
*/
export type ListValueJson = JsonValue[];
/**
* Describes the message google.protobuf.ListValue.
* Use `create(ListValueSchema)` to create a new message.
*/
export declare const ListValueSchema: GenMessage<ListValue, {
jsonType: ListValueJson;
}>;
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* @generated from enum google.protobuf.NullValue
*/
export declare enum NullValue {
/**
* Null value.
*
* @generated from enum value: NULL_VALUE = 0;
*/
NULL_VALUE = 0
}
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* @generated from enum google.protobuf.NullValue
*/
export type NullValueJson = null;
/**
* Describes the enum google.protobuf.NullValue.
*/
export declare const NullValueSchema: GenEnum<NullValue, NullValueJson>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.NullValueSchema = exports.NullValue = exports.ListValueSchema = exports.ValueSchema = exports.StructSchema = exports.file_google_protobuf_struct = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
/**
* Describes the file google/protobuf/struct.proto.
*/
exports.file_google_protobuf_struct = (0, file_js_1.fileDesc)("Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9idWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9idWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToCOAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJvdG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoMc3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8KDHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RWYWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAAQn8KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAFaL2dvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3N0cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
/**
* Describes the message google.protobuf.Struct.
* Use `create(StructSchema)` to create a new message.
*/
exports.StructSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_struct, 0);
/**
* Describes the message google.protobuf.Value.
* Use `create(ValueSchema)` to create a new message.
*/
exports.ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_struct, 1);
/**
* Describes the message google.protobuf.ListValue.
* Use `create(ListValueSchema)` to create a new message.
*/
exports.ListValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_struct, 2);
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* @generated from enum google.protobuf.NullValue
*/
var NullValue;
(function (NullValue) {
/**
* Null value.
*
* @generated from enum value: NULL_VALUE = 0;
*/
NullValue[NullValue["NULL_VALUE"] = 0] = "NULL_VALUE";
})(NullValue || (exports.NullValue = NullValue = {}));
/**
* Describes the enum google.protobuf.NullValue.
*/
exports.NullValueSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_struct, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/timestamp.proto.
*/
export declare const file_google_protobuf_timestamp: GenFile;
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A ProtoJSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a ProtoJSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
* ) to obtain a formatter capable of generating timestamps in this format.
*
*
* @generated from message google.protobuf.Timestamp
*/
export type Timestamp = Message<"google.protobuf.Timestamp"> & {
/**
* Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must
* be between -62135596800 and 253402300799 inclusive (which corresponds to
* 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z).
*
* @generated from field: int64 seconds = 1;
*/
seconds: bigint;
/**
* Non-negative fractions of a second at nanosecond resolution. This field is
* the nanosecond portion of the duration, not an alternative to seconds.
* Negative second values with fractions must still have non-negative nanos
* values that count forward in time. Must be between 0 and 999,999,999
* inclusive.
*
* @generated from field: int32 nanos = 2;
*/
nanos: number;
};
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A ProtoJSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a ProtoJSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
* ) to obtain a formatter capable of generating timestamps in this format.
*
*
* @generated from message google.protobuf.Timestamp
*/
export type TimestampJson = string;
/**
* Describes the message google.protobuf.Timestamp.
* Use `create(TimestampSchema)` to create a new message.
*/
export declare const TimestampSchema: GenMessage<Timestamp, {
jsonType: TimestampJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimestampSchema = exports.file_google_protobuf_timestamp = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/timestamp.proto.
*/
exports.file_google_protobuf_timestamp = (0, file_js_1.fileDesc)("Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJvdG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MYAiABKAVChQEKE2NvbS5nb29nbGUucHJvdG9idWZCDlRpbWVzdGFtcFByb3RvUAFaMmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3RpbWVzdGFtcHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
/**
* Describes the message google.protobuf.Timestamp.
* Use `create(TimestampSchema)` to create a new message.
*/
exports.TimestampSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_timestamp, 0);
import type { GenEnum, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Any, AnyJson } from "./any_pb.js";
import type { SourceContext, SourceContextJson } from "./source_context_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/type.proto.
*/
export declare const file_google_protobuf_type: GenFile;
/**
* A protocol buffer message type.
*
* New usages of this message as an alternative to DescriptorProto are strongly
* discouraged. This message does not reliability preserve all information
* necessary to model the schema and preserve semantics. Instead make use of
* FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Type
*/
export type Type = Message<"google.protobuf.Type"> & {
/**
* The fully qualified message name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The list of fields.
*
* @generated from field: repeated google.protobuf.Field fields = 2;
*/
fields: Field[];
/**
* The list of types appearing in `oneof` definitions in this type.
*
* @generated from field: repeated string oneofs = 3;
*/
oneofs: string[];
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 4;
*/
options: Option[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContext | undefined;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 6;
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 7;
*/
edition: string;
};
/**
* A protocol buffer message type.
*
* New usages of this message as an alternative to DescriptorProto are strongly
* discouraged. This message does not reliability preserve all information
* necessary to model the schema and preserve semantics. Instead make use of
* FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Type
*/
export type TypeJson = {
/**
* The fully qualified message name.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* The list of fields.
*
* @generated from field: repeated google.protobuf.Field fields = 2;
*/
fields?: FieldJson[];
/**
* The list of types appearing in `oneof` definitions in this type.
*
* @generated from field: repeated string oneofs = 3;
*/
oneofs?: string[];
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 4;
*/
options?: OptionJson[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContextJson;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 6;
*/
syntax?: SyntaxJson;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 7;
*/
edition?: string;
};
/**
* Describes the message google.protobuf.Type.
* Use `create(TypeSchema)` to create a new message.
*/
export declare const TypeSchema: GenMessage<Type, {
jsonType: TypeJson;
}>;
/**
* A single field of a message type.
*
* New usages of this message as an alternative to FieldDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Field
*/
export type Field = Message<"google.protobuf.Field"> & {
/**
* The field type.
*
* @generated from field: google.protobuf.Field.Kind kind = 1;
*/
kind: Field_Kind;
/**
* The field cardinality.
*
* @generated from field: google.protobuf.Field.Cardinality cardinality = 2;
*/
cardinality: Field_Cardinality;
/**
* The field number.
*
* @generated from field: int32 number = 3;
*/
number: number;
/**
* The field name.
*
* @generated from field: string name = 4;
*/
name: string;
/**
* The field type URL, without the scheme, for message or enumeration
* types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
*
* @generated from field: string type_url = 6;
*/
typeUrl: string;
/**
* The index of the field type in `Type.oneofs`, for message or enumeration
* types. The first type has index 1; zero means the type is not in the list.
*
* @generated from field: int32 oneof_index = 7;
*/
oneofIndex: number;
/**
* Whether to use alternative packed wire representation.
*
* @generated from field: bool packed = 8;
*/
packed: boolean;
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 9;
*/
options: Option[];
/**
* The field JSON name.
*
* @generated from field: string json_name = 10;
*/
jsonName: string;
/**
* The string value of the default value of this field. Proto2 syntax only.
*
* @generated from field: string default_value = 11;
*/
defaultValue: string;
};
/**
* A single field of a message type.
*
* New usages of this message as an alternative to FieldDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Field
*/
export type FieldJson = {
/**
* The field type.
*
* @generated from field: google.protobuf.Field.Kind kind = 1;
*/
kind?: Field_KindJson;
/**
* The field cardinality.
*
* @generated from field: google.protobuf.Field.Cardinality cardinality = 2;
*/
cardinality?: Field_CardinalityJson;
/**
* The field number.
*
* @generated from field: int32 number = 3;
*/
number?: number;
/**
* The field name.
*
* @generated from field: string name = 4;
*/
name?: string;
/**
* The field type URL, without the scheme, for message or enumeration
* types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
*
* @generated from field: string type_url = 6;
*/
typeUrl?: string;
/**
* The index of the field type in `Type.oneofs`, for message or enumeration
* types. The first type has index 1; zero means the type is not in the list.
*
* @generated from field: int32 oneof_index = 7;
*/
oneofIndex?: number;
/**
* Whether to use alternative packed wire representation.
*
* @generated from field: bool packed = 8;
*/
packed?: boolean;
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 9;
*/
options?: OptionJson[];
/**
* The field JSON name.
*
* @generated from field: string json_name = 10;
*/
jsonName?: string;
/**
* The string value of the default value of this field. Proto2 syntax only.
*
* @generated from field: string default_value = 11;
*/
defaultValue?: string;
};
/**
* Describes the message google.protobuf.Field.
* Use `create(FieldSchema)` to create a new message.
*/
export declare const FieldSchema: GenMessage<Field, {
jsonType: FieldJson;
}>;
/**
* Basic field types.
*
* @generated from enum google.protobuf.Field.Kind
*/
export declare enum Field_Kind {
/**
* Field type unknown.
*
* @generated from enum value: TYPE_UNKNOWN = 0;
*/
TYPE_UNKNOWN = 0,
/**
* Field type double.
*
* @generated from enum value: TYPE_DOUBLE = 1;
*/
TYPE_DOUBLE = 1,
/**
* Field type float.
*
* @generated from enum value: TYPE_FLOAT = 2;
*/
TYPE_FLOAT = 2,
/**
* Field type int64.
*
* @generated from enum value: TYPE_INT64 = 3;
*/
TYPE_INT64 = 3,
/**
* Field type uint64.
*
* @generated from enum value: TYPE_UINT64 = 4;
*/
TYPE_UINT64 = 4,
/**
* Field type int32.
*
* @generated from enum value: TYPE_INT32 = 5;
*/
TYPE_INT32 = 5,
/**
* Field type fixed64.
*
* @generated from enum value: TYPE_FIXED64 = 6;
*/
TYPE_FIXED64 = 6,
/**
* Field type fixed32.
*
* @generated from enum value: TYPE_FIXED32 = 7;
*/
TYPE_FIXED32 = 7,
/**
* Field type bool.
*
* @generated from enum value: TYPE_BOOL = 8;
*/
TYPE_BOOL = 8,
/**
* Field type string.
*
* @generated from enum value: TYPE_STRING = 9;
*/
TYPE_STRING = 9,
/**
* Field type group. Proto2 syntax only, and deprecated.
*
* @generated from enum value: TYPE_GROUP = 10;
*/
TYPE_GROUP = 10,
/**
* Field type message.
*
* @generated from enum value: TYPE_MESSAGE = 11;
*/
TYPE_MESSAGE = 11,
/**
* Field type bytes.
*
* @generated from enum value: TYPE_BYTES = 12;
*/
TYPE_BYTES = 12,
/**
* Field type uint32.
*
* @generated from enum value: TYPE_UINT32 = 13;
*/
TYPE_UINT32 = 13,
/**
* Field type enum.
*
* @generated from enum value: TYPE_ENUM = 14;
*/
TYPE_ENUM = 14,
/**
* Field type sfixed32.
*
* @generated from enum value: TYPE_SFIXED32 = 15;
*/
TYPE_SFIXED32 = 15,
/**
* Field type sfixed64.
*
* @generated from enum value: TYPE_SFIXED64 = 16;
*/
TYPE_SFIXED64 = 16,
/**
* Field type sint32.
*
* @generated from enum value: TYPE_SINT32 = 17;
*/
TYPE_SINT32 = 17,
/**
* Field type sint64.
*
* @generated from enum value: TYPE_SINT64 = 18;
*/
TYPE_SINT64 = 18
}
/**
* Basic field types.
*
* @generated from enum google.protobuf.Field.Kind
*/
export type Field_KindJson = "TYPE_UNKNOWN" | "TYPE_DOUBLE" | "TYPE_FLOAT" | "TYPE_INT64" | "TYPE_UINT64" | "TYPE_INT32" | "TYPE_FIXED64" | "TYPE_FIXED32" | "TYPE_BOOL" | "TYPE_STRING" | "TYPE_GROUP" | "TYPE_MESSAGE" | "TYPE_BYTES" | "TYPE_UINT32" | "TYPE_ENUM" | "TYPE_SFIXED32" | "TYPE_SFIXED64" | "TYPE_SINT32" | "TYPE_SINT64";
/**
* Describes the enum google.protobuf.Field.Kind.
*/
export declare const Field_KindSchema: GenEnum<Field_Kind, Field_KindJson>;
/**
* Whether a field is optional, required, or repeated.
*
* @generated from enum google.protobuf.Field.Cardinality
*/
export declare enum Field_Cardinality {
/**
* For fields with unknown cardinality.
*
* @generated from enum value: CARDINALITY_UNKNOWN = 0;
*/
UNKNOWN = 0,
/**
* For optional fields.
*
* @generated from enum value: CARDINALITY_OPTIONAL = 1;
*/
OPTIONAL = 1,
/**
* For required fields. Proto2 syntax only.
*
* @generated from enum value: CARDINALITY_REQUIRED = 2;
*/
REQUIRED = 2,
/**
* For repeated fields.
*
* @generated from enum value: CARDINALITY_REPEATED = 3;
*/
REPEATED = 3
}
/**
* Whether a field is optional, required, or repeated.
*
* @generated from enum google.protobuf.Field.Cardinality
*/
export type Field_CardinalityJson = "CARDINALITY_UNKNOWN" | "CARDINALITY_OPTIONAL" | "CARDINALITY_REQUIRED" | "CARDINALITY_REPEATED";
/**
* Describes the enum google.protobuf.Field.Cardinality.
*/
export declare const Field_CardinalitySchema: GenEnum<Field_Cardinality, Field_CardinalityJson>;
/**
* Enum type definition.
*
* New usages of this message as an alternative to EnumDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Enum
*/
export type Enum = Message<"google.protobuf.Enum"> & {
/**
* Enum type name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* Enum value definitions.
*
* @generated from field: repeated google.protobuf.EnumValue enumvalue = 2;
*/
enumvalue: EnumValue[];
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 4;
*/
sourceContext?: SourceContext | undefined;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 5;
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 6;
*/
edition: string;
};
/**
* Enum type definition.
*
* New usages of this message as an alternative to EnumDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Enum
*/
export type EnumJson = {
/**
* Enum type name.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* Enum value definitions.
*
* @generated from field: repeated google.protobuf.EnumValue enumvalue = 2;
*/
enumvalue?: EnumValueJson[];
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options?: OptionJson[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 4;
*/
sourceContext?: SourceContextJson;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 5;
*/
syntax?: SyntaxJson;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 6;
*/
edition?: string;
};
/**
* Describes the message google.protobuf.Enum.
* Use `create(EnumSchema)` to create a new message.
*/
export declare const EnumSchema: GenMessage<Enum, {
jsonType: EnumJson;
}>;
/**
* Enum value definition.
*
* New usages of this message as an alternative to EnumValueDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.EnumValue
*/
export type EnumValue = Message<"google.protobuf.EnumValue"> & {
/**
* Enum value name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* Enum value number.
*
* @generated from field: int32 number = 2;
*/
number: number;
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
};
/**
* Enum value definition.
*
* New usages of this message as an alternative to EnumValueDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.EnumValue
*/
export type EnumValueJson = {
/**
* Enum value name.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* Enum value number.
*
* @generated from field: int32 number = 2;
*/
number?: number;
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options?: OptionJson[];
};
/**
* Describes the message google.protobuf.EnumValue.
* Use `create(EnumValueSchema)` to create a new message.
*/
export declare const EnumValueSchema: GenMessage<EnumValue, {
jsonType: EnumValueJson;
}>;
/**
* A protocol buffer option, which can be attached to a message, field,
* enumeration, etc.
*
* New usages of this message as an alternative to FileOptions, MessageOptions,
* FieldOptions, EnumOptions, EnumValueOptions, ServiceOptions, or MethodOptions
* are strongly discouraged.
*
* @generated from message google.protobuf.Option
*/
export type Option = Message<"google.protobuf.Option"> & {
/**
* The option's name. For protobuf built-in options (options defined in
* descriptor.proto), this is the short name. For example, `"map_entry"`.
* For custom options, it should be the fully-qualified name. For example,
* `"google.api.http"`.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The option's value packed in an Any message. If the value is a primitive,
* the corresponding wrapper type defined in google/protobuf/wrappers.proto
* should be used. If the value is an enum, it should be stored as an int32
* value using the google.protobuf.Int32Value type.
*
* @generated from field: google.protobuf.Any value = 2;
*/
value?: Any | undefined;
};
/**
* A protocol buffer option, which can be attached to a message, field,
* enumeration, etc.
*
* New usages of this message as an alternative to FileOptions, MessageOptions,
* FieldOptions, EnumOptions, EnumValueOptions, ServiceOptions, or MethodOptions
* are strongly discouraged.
*
* @generated from message google.protobuf.Option
*/
export type OptionJson = {
/**
* The option's name. For protobuf built-in options (options defined in
* descriptor.proto), this is the short name. For example, `"map_entry"`.
* For custom options, it should be the fully-qualified name. For example,
* `"google.api.http"`.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* The option's value packed in an Any message. If the value is a primitive,
* the corresponding wrapper type defined in google/protobuf/wrappers.proto
* should be used. If the value is an enum, it should be stored as an int32
* value using the google.protobuf.Int32Value type.
*
* @generated from field: google.protobuf.Any value = 2;
*/
value?: AnyJson;
};
/**
* Describes the message google.protobuf.Option.
* Use `create(OptionSchema)` to create a new message.
*/
export declare const OptionSchema: GenMessage<Option, {
jsonType: OptionJson;
}>;
/**
* The syntax in which a protocol buffer element is defined.
*
* @generated from enum google.protobuf.Syntax
*/
export declare enum Syntax {
/**
* Syntax `proto2`.
*
* @generated from enum value: SYNTAX_PROTO2 = 0;
*/
PROTO2 = 0,
/**
* Syntax `proto3`.
*
* @generated from enum value: SYNTAX_PROTO3 = 1;
*/
PROTO3 = 1,
/**
* Syntax `editions`.
*
* @generated from enum value: SYNTAX_EDITIONS = 2;
*/
EDITIONS = 2
}
/**
* The syntax in which a protocol buffer element is defined.
*
* @generated from enum google.protobuf.Syntax
*/
export type SyntaxJson = "SYNTAX_PROTO2" | "SYNTAX_PROTO3" | "SYNTAX_EDITIONS";
/**
* Describes the enum google.protobuf.Syntax.
*/
export declare const SyntaxSchema: GenEnum<Syntax, SyntaxJson>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SyntaxSchema = exports.Syntax = exports.OptionSchema = exports.EnumValueSchema = exports.EnumSchema = exports.Field_CardinalitySchema = exports.Field_Cardinality = exports.Field_KindSchema = exports.Field_Kind = exports.FieldSchema = exports.TypeSchema = exports.file_google_protobuf_type = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const any_pb_js_1 = require("./any_pb.js");
const source_context_pb_js_1 = require("./source_context_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
/**
* Describes the file google/protobuf/type.proto.
*/
exports.file_google_protobuf_type = (0, file_js_1.fileDesc)("Chpnb29nbGUvcHJvdG9idWYvdHlwZS5wcm90bxIPZ29vZ2xlLnByb3RvYnVmIugBCgRUeXBlEgwKBG5hbWUYASABKAkSJgoGZmllbGRzGAIgAygLMhYuZ29vZ2xlLnByb3RvYnVmLkZpZWxkEg4KBm9uZW9mcxgDIAMoCRIoCgdvcHRpb25zGAQgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhI2Cg5zb3VyY2VfY29udGV4dBgFIAEoCzIeLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb250ZXh0EicKBnN5bnRheBgGIAEoDjIXLmdvb2dsZS5wcm90b2J1Zi5TeW50YXgSDwoHZWRpdGlvbhgHIAEoCSLVBQoFRmllbGQSKQoEa2luZBgBIAEoDjIbLmdvb2dsZS5wcm90b2J1Zi5GaWVsZC5LaW5kEjcKC2NhcmRpbmFsaXR5GAIgASgOMiIuZ29vZ2xlLnByb3RvYnVmLkZpZWxkLkNhcmRpbmFsaXR5Eg4KBm51bWJlchgDIAEoBRIMCgRuYW1lGAQgASgJEhAKCHR5cGVfdXJsGAYgASgJEhMKC29uZW9mX2luZGV4GAcgASgFEg4KBnBhY2tlZBgIIAEoCBIoCgdvcHRpb25zGAkgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhIRCglqc29uX25hbWUYCiABKAkSFQoNZGVmYXVsdF92YWx1ZRgLIAEoCSLIAgoES2luZBIQCgxUWVBFX1VOS05PV04QABIPCgtUWVBFX0RPVUJMRRABEg4KClRZUEVfRkxPQVQQAhIOCgpUWVBFX0lOVDY0EAMSDwoLVFlQRV9VSU5UNjQQBBIOCgpUWVBFX0lOVDMyEAUSEAoMVFlQRV9GSVhFRDY0EAYSEAoMVFlQRV9GSVhFRDMyEAcSDQoJVFlQRV9CT09MEAgSDwoLVFlQRV9TVFJJTkcQCRIOCgpUWVBFX0dST1VQEAoSEAoMVFlQRV9NRVNTQUdFEAsSDgoKVFlQRV9CWVRFUxAMEg8KC1RZUEVfVUlOVDMyEA0SDQoJVFlQRV9FTlVNEA4SEQoNVFlQRV9TRklYRUQzMhAPEhEKDVRZUEVfU0ZJWEVENjQQEBIPCgtUWVBFX1NJTlQzMhAREg8KC1RZUEVfU0lOVDY0EBIidAoLQ2FyZGluYWxpdHkSFwoTQ0FSRElOQUxJVFlfVU5LTk9XThAAEhgKFENBUkRJTkFMSVRZX09QVElPTkFMEAESGAoUQ0FSRElOQUxJVFlfUkVRVUlSRUQQAhIYChRDQVJESU5BTElUWV9SRVBFQVRFRBADIt8BCgRFbnVtEgwKBG5hbWUYASABKAkSLQoJZW51bXZhbHVlGAIgAygLMhouZ29vZ2xlLnByb3RvYnVmLkVudW1WYWx1ZRIoCgdvcHRpb25zGAMgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhI2Cg5zb3VyY2VfY29udGV4dBgEIAEoCzIeLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb250ZXh0EicKBnN5bnRheBgFIAEoDjIXLmdvb2dsZS5wcm90b2J1Zi5TeW50YXgSDwoHZWRpdGlvbhgGIAEoCSJTCglFbnVtVmFsdWUSDAoEbmFtZRgBIAEoCRIOCgZudW1iZXIYAiABKAUSKAoHb3B0aW9ucxgDIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5PcHRpb24iOwoGT3B0aW9uEgwKBG5hbWUYASABKAkSIwoFdmFsdWUYAiABKAsyFC5nb29nbGUucHJvdG9idWYuQW55KkMKBlN5bnRheBIRCg1TWU5UQVhfUFJPVE8yEAASEQoNU1lOVEFYX1BST1RPMxABEhMKD1NZTlRBWF9FRElUSU9OUxACQnsKE2NvbS5nb29nbGUucHJvdG9idWZCCVR5cGVQcm90b1ABWi1nb29nbGUuZ29sYW5nLm9yZy9wcm90b2J1Zi90eXBlcy9rbm93bi90eXBlcGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw", [any_pb_js_1.file_google_protobuf_any, source_context_pb_js_1.file_google_protobuf_source_context]);
/**
* Describes the message google.protobuf.Type.
* Use `create(TypeSchema)` to create a new message.
*/
exports.TypeSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 0);
/**
* Describes the message google.protobuf.Field.
* Use `create(FieldSchema)` to create a new message.
*/
exports.FieldSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 1);
/**
* Basic field types.
*
* @generated from enum google.protobuf.Field.Kind
*/
var Field_Kind;
(function (Field_Kind) {
/**
* Field type unknown.
*
* @generated from enum value: TYPE_UNKNOWN = 0;
*/
Field_Kind[Field_Kind["TYPE_UNKNOWN"] = 0] = "TYPE_UNKNOWN";
/**
* Field type double.
*
* @generated from enum value: TYPE_DOUBLE = 1;
*/
Field_Kind[Field_Kind["TYPE_DOUBLE"] = 1] = "TYPE_DOUBLE";
/**
* Field type float.
*
* @generated from enum value: TYPE_FLOAT = 2;
*/
Field_Kind[Field_Kind["TYPE_FLOAT"] = 2] = "TYPE_FLOAT";
/**
* Field type int64.
*
* @generated from enum value: TYPE_INT64 = 3;
*/
Field_Kind[Field_Kind["TYPE_INT64"] = 3] = "TYPE_INT64";
/**
* Field type uint64.
*
* @generated from enum value: TYPE_UINT64 = 4;
*/
Field_Kind[Field_Kind["TYPE_UINT64"] = 4] = "TYPE_UINT64";
/**
* Field type int32.
*
* @generated from enum value: TYPE_INT32 = 5;
*/
Field_Kind[Field_Kind["TYPE_INT32"] = 5] = "TYPE_INT32";
/**
* Field type fixed64.
*
* @generated from enum value: TYPE_FIXED64 = 6;
*/
Field_Kind[Field_Kind["TYPE_FIXED64"] = 6] = "TYPE_FIXED64";
/**
* Field type fixed32.
*
* @generated from enum value: TYPE_FIXED32 = 7;
*/
Field_Kind[Field_Kind["TYPE_FIXED32"] = 7] = "TYPE_FIXED32";
/**
* Field type bool.
*
* @generated from enum value: TYPE_BOOL = 8;
*/
Field_Kind[Field_Kind["TYPE_BOOL"] = 8] = "TYPE_BOOL";
/**
* Field type string.
*
* @generated from enum value: TYPE_STRING = 9;
*/
Field_Kind[Field_Kind["TYPE_STRING"] = 9] = "TYPE_STRING";
/**
* Field type group. Proto2 syntax only, and deprecated.
*
* @generated from enum value: TYPE_GROUP = 10;
*/
Field_Kind[Field_Kind["TYPE_GROUP"] = 10] = "TYPE_GROUP";
/**
* Field type message.
*
* @generated from enum value: TYPE_MESSAGE = 11;
*/
Field_Kind[Field_Kind["TYPE_MESSAGE"] = 11] = "TYPE_MESSAGE";
/**
* Field type bytes.
*
* @generated from enum value: TYPE_BYTES = 12;
*/
Field_Kind[Field_Kind["TYPE_BYTES"] = 12] = "TYPE_BYTES";
/**
* Field type uint32.
*
* @generated from enum value: TYPE_UINT32 = 13;
*/
Field_Kind[Field_Kind["TYPE_UINT32"] = 13] = "TYPE_UINT32";
/**
* Field type enum.
*
* @generated from enum value: TYPE_ENUM = 14;
*/
Field_Kind[Field_Kind["TYPE_ENUM"] = 14] = "TYPE_ENUM";
/**
* Field type sfixed32.
*
* @generated from enum value: TYPE_SFIXED32 = 15;
*/
Field_Kind[Field_Kind["TYPE_SFIXED32"] = 15] = "TYPE_SFIXED32";
/**
* Field type sfixed64.
*
* @generated from enum value: TYPE_SFIXED64 = 16;
*/
Field_Kind[Field_Kind["TYPE_SFIXED64"] = 16] = "TYPE_SFIXED64";
/**
* Field type sint32.
*
* @generated from enum value: TYPE_SINT32 = 17;
*/
Field_Kind[Field_Kind["TYPE_SINT32"] = 17] = "TYPE_SINT32";
/**
* Field type sint64.
*
* @generated from enum value: TYPE_SINT64 = 18;
*/
Field_Kind[Field_Kind["TYPE_SINT64"] = 18] = "TYPE_SINT64";
})(Field_Kind || (exports.Field_Kind = Field_Kind = {}));
/**
* Describes the enum google.protobuf.Field.Kind.
*/
exports.Field_KindSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_type, 1, 0);
/**
* Whether a field is optional, required, or repeated.
*
* @generated from enum google.protobuf.Field.Cardinality
*/
var Field_Cardinality;
(function (Field_Cardinality) {
/**
* For fields with unknown cardinality.
*
* @generated from enum value: CARDINALITY_UNKNOWN = 0;
*/
Field_Cardinality[Field_Cardinality["UNKNOWN"] = 0] = "UNKNOWN";
/**
* For optional fields.
*
* @generated from enum value: CARDINALITY_OPTIONAL = 1;
*/
Field_Cardinality[Field_Cardinality["OPTIONAL"] = 1] = "OPTIONAL";
/**
* For required fields. Proto2 syntax only.
*
* @generated from enum value: CARDINALITY_REQUIRED = 2;
*/
Field_Cardinality[Field_Cardinality["REQUIRED"] = 2] = "REQUIRED";
/**
* For repeated fields.
*
* @generated from enum value: CARDINALITY_REPEATED = 3;
*/
Field_Cardinality[Field_Cardinality["REPEATED"] = 3] = "REPEATED";
})(Field_Cardinality || (exports.Field_Cardinality = Field_Cardinality = {}));
/**
* Describes the enum google.protobuf.Field.Cardinality.
*/
exports.Field_CardinalitySchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_type, 1, 1);
/**
* Describes the message google.protobuf.Enum.
* Use `create(EnumSchema)` to create a new message.
*/
exports.EnumSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 2);
/**
* Describes the message google.protobuf.EnumValue.
* Use `create(EnumValueSchema)` to create a new message.
*/
exports.EnumValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 3);
/**
* Describes the message google.protobuf.Option.
* Use `create(OptionSchema)` to create a new message.
*/
exports.OptionSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 4);
/**
* The syntax in which a protocol buffer element is defined.
*
* @generated from enum google.protobuf.Syntax
*/
var Syntax;
(function (Syntax) {
/**
* Syntax `proto2`.
*
* @generated from enum value: SYNTAX_PROTO2 = 0;
*/
Syntax[Syntax["PROTO2"] = 0] = "PROTO2";
/**
* Syntax `proto3`.
*
* @generated from enum value: SYNTAX_PROTO3 = 1;
*/
Syntax[Syntax["PROTO3"] = 1] = "PROTO3";
/**
* Syntax `editions`.
*
* @generated from enum value: SYNTAX_EDITIONS = 2;
*/
Syntax[Syntax["EDITIONS"] = 2] = "EDITIONS";
})(Syntax || (exports.Syntax = Syntax = {}));
/**
* Describes the enum google.protobuf.Syntax.
*/
exports.SyntaxSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_type, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/wrappers.proto.
*/
export declare const file_google_protobuf_wrappers: GenFile;
/**
* Wrapper message for `double`.
*
* The JSON representation for `DoubleValue` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.DoubleValue
*/
export type DoubleValue = Message<"google.protobuf.DoubleValue"> & {
/**
* The double value.
*
* @generated from field: double value = 1;
*/
value: number;
};
/**
* Wrapper message for `double`.
*
* The JSON representation for `DoubleValue` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.DoubleValue
*/
export type DoubleValueJson = number | "NaN" | "Infinity" | "-Infinity";
/**
* Describes the message google.protobuf.DoubleValue.
* Use `create(DoubleValueSchema)` to create a new message.
*/
export declare const DoubleValueSchema: GenMessage<DoubleValue, {
jsonType: DoubleValueJson;
}>;
/**
* Wrapper message for `float`.
*
* The JSON representation for `FloatValue` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.FloatValue
*/
export type FloatValue = Message<"google.protobuf.FloatValue"> & {
/**
* The float value.
*
* @generated from field: float value = 1;
*/
value: number;
};
/**
* Wrapper message for `float`.
*
* The JSON representation for `FloatValue` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.FloatValue
*/
export type FloatValueJson = number | "NaN" | "Infinity" | "-Infinity";
/**
* Describes the message google.protobuf.FloatValue.
* Use `create(FloatValueSchema)` to create a new message.
*/
export declare const FloatValueSchema: GenMessage<FloatValue, {
jsonType: FloatValueJson;
}>;
/**
* Wrapper message for `int64`.
*
* The JSON representation for `Int64Value` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.Int64Value
*/
export type Int64Value = Message<"google.protobuf.Int64Value"> & {
/**
* The int64 value.
*
* @generated from field: int64 value = 1;
*/
value: bigint;
};
/**
* Wrapper message for `int64`.
*
* The JSON representation for `Int64Value` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.Int64Value
*/
export type Int64ValueJson = string;
/**
* Describes the message google.protobuf.Int64Value.
* Use `create(Int64ValueSchema)` to create a new message.
*/
export declare const Int64ValueSchema: GenMessage<Int64Value, {
jsonType: Int64ValueJson;
}>;
/**
* Wrapper message for `uint64`.
*
* The JSON representation for `UInt64Value` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.UInt64Value
*/
export type UInt64Value = Message<"google.protobuf.UInt64Value"> & {
/**
* The uint64 value.
*
* @generated from field: uint64 value = 1;
*/
value: bigint;
};
/**
* Wrapper message for `uint64`.
*
* The JSON representation for `UInt64Value` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.UInt64Value
*/
export type UInt64ValueJson = string;
/**
* Describes the message google.protobuf.UInt64Value.
* Use `create(UInt64ValueSchema)` to create a new message.
*/
export declare const UInt64ValueSchema: GenMessage<UInt64Value, {
jsonType: UInt64ValueJson;
}>;
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.Int32Value
*/
export type Int32Value = Message<"google.protobuf.Int32Value"> & {
/**
* The int32 value.
*
* @generated from field: int32 value = 1;
*/
value: number;
};
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.Int32Value
*/
export type Int32ValueJson = number;
/**
* Describes the message google.protobuf.Int32Value.
* Use `create(Int32ValueSchema)` to create a new message.
*/
export declare const Int32ValueSchema: GenMessage<Int32Value, {
jsonType: Int32ValueJson;
}>;
/**
* Wrapper message for `uint32`.
*
* The JSON representation for `UInt32Value` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.UInt32Value
*/
export type UInt32Value = Message<"google.protobuf.UInt32Value"> & {
/**
* The uint32 value.
*
* @generated from field: uint32 value = 1;
*/
value: number;
};
/**
* Wrapper message for `uint32`.
*
* The JSON representation for `UInt32Value` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.UInt32Value
*/
export type UInt32ValueJson = number;
/**
* Describes the message google.protobuf.UInt32Value.
* Use `create(UInt32ValueSchema)` to create a new message.
*/
export declare const UInt32ValueSchema: GenMessage<UInt32Value, {
jsonType: UInt32ValueJson;
}>;
/**
* Wrapper message for `bool`.
*
* The JSON representation for `BoolValue` is JSON `true` and `false`.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.BoolValue
*/
export type BoolValue = Message<"google.protobuf.BoolValue"> & {
/**
* The bool value.
*
* @generated from field: bool value = 1;
*/
value: boolean;
};
/**
* Wrapper message for `bool`.
*
* The JSON representation for `BoolValue` is JSON `true` and `false`.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.BoolValue
*/
export type BoolValueJson = boolean;
/**
* Describes the message google.protobuf.BoolValue.
* Use `create(BoolValueSchema)` to create a new message.
*/
export declare const BoolValueSchema: GenMessage<BoolValue, {
jsonType: BoolValueJson;
}>;
/**
* Wrapper message for `string`.
*
* The JSON representation for `StringValue` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.StringValue
*/
export type StringValue = Message<"google.protobuf.StringValue"> & {
/**
* The string value.
*
* @generated from field: string value = 1;
*/
value: string;
};
/**
* Wrapper message for `string`.
*
* The JSON representation for `StringValue` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.StringValue
*/
export type StringValueJson = string;
/**
* Describes the message google.protobuf.StringValue.
* Use `create(StringValueSchema)` to create a new message.
*/
export declare const StringValueSchema: GenMessage<StringValue, {
jsonType: StringValueJson;
}>;
/**
* Wrapper message for `bytes`.
*
* The JSON representation for `BytesValue` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.BytesValue
*/
export type BytesValue = Message<"google.protobuf.BytesValue"> & {
/**
* The bytes value.
*
* @generated from field: bytes value = 1;
*/
value: Uint8Array;
};
/**
* Wrapper message for `bytes`.
*
* The JSON representation for `BytesValue` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.BytesValue
*/
export type BytesValueJson = string;
/**
* Describes the message google.protobuf.BytesValue.
* Use `create(BytesValueSchema)` to create a new message.
*/
export declare const BytesValueSchema: GenMessage<BytesValue, {
jsonType: BytesValueJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BytesValueSchema = exports.StringValueSchema = exports.BoolValueSchema = exports.UInt32ValueSchema = exports.Int32ValueSchema = exports.UInt64ValueSchema = exports.Int64ValueSchema = exports.FloatValueSchema = exports.DoubleValueSchema = exports.file_google_protobuf_wrappers = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/wrappers.proto.
*/
exports.file_google_protobuf_wrappers = (0, file_js_1.fileDesc)("Ch5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIcCgtEb3VibGVWYWx1ZRINCgV2YWx1ZRgBIAEoASIbCgpGbG9hdFZhbHVlEg0KBXZhbHVlGAEgASgCIhsKCkludDY0VmFsdWUSDQoFdmFsdWUYASABKAMiHAoLVUludDY0VmFsdWUSDQoFdmFsdWUYASABKAQiGwoKSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEoBSIcCgtVSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEoDSIaCglCb29sVmFsdWUSDQoFdmFsdWUYASABKAgiHAoLU3RyaW5nVmFsdWUSDQoFdmFsdWUYASABKAkiGwoKQnl0ZXNWYWx1ZRINCgV2YWx1ZRgBIAEoDEKDAQoTY29tLmdvb2dsZS5wcm90b2J1ZkINV3JhcHBlcnNQcm90b1ABWjFnb29nbGUuZ29sYW5nLm9yZy9wcm90b2J1Zi90eXBlcy9rbm93bi93cmFwcGVyc3Bi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
/**
* Describes the message google.protobuf.DoubleValue.
* Use `create(DoubleValueSchema)` to create a new message.
*/
exports.DoubleValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 0);
/**
* Describes the message google.protobuf.FloatValue.
* Use `create(FloatValueSchema)` to create a new message.
*/
exports.FloatValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 1);
/**
* Describes the message google.protobuf.Int64Value.
* Use `create(Int64ValueSchema)` to create a new message.
*/
exports.Int64ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 2);
/**
* Describes the message google.protobuf.UInt64Value.
* Use `create(UInt64ValueSchema)` to create a new message.
*/
exports.UInt64ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 3);
/**
* Describes the message google.protobuf.Int32Value.
* Use `create(Int32ValueSchema)` to create a new message.
*/
exports.Int32ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 4);
/**
* Describes the message google.protobuf.UInt32Value.
* Use `create(UInt32ValueSchema)` to create a new message.
*/
exports.UInt32ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 5);
/**
* Describes the message google.protobuf.BoolValue.
* Use `create(BoolValueSchema)` to create a new message.
*/
exports.BoolValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 6);
/**
* Describes the message google.protobuf.StringValue.
* Use `create(StringValueSchema)` to create a new message.
*/
exports.StringValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 7);
/**
* Describes the message google.protobuf.BytesValue.
* Use `create(BytesValueSchema)` to create a new message.
*/
exports.BytesValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 8);
export * from "./timestamp.js";
export * from "./duration.js";
export * from "./any.js";
export * from "./wrappers.js";
export * from "./gen/google/protobuf/any_pb.js";
export * from "./gen/google/protobuf/api_pb.js";
export * from "./gen/google/protobuf/cpp_features_pb.js";
export * from "./gen/google/protobuf/descriptor_pb.js";
export * from "./gen/google/protobuf/duration_pb.js";
export * from "./gen/google/protobuf/empty_pb.js";
export * from "./gen/google/protobuf/field_mask_pb.js";
export * from "./gen/google/protobuf/go_features_pb.js";
export * from "./gen/google/protobuf/java_features_pb.js";
export * from "./gen/google/protobuf/source_context_pb.js";
export * from "./gen/google/protobuf/struct_pb.js";
export * from "./gen/google/protobuf/timestamp_pb.js";
export * from "./gen/google/protobuf/type_pb.js";
export * from "./gen/google/protobuf/wrappers_pb.js";
export * from "./gen/google/protobuf/compiler/plugin_pb.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./timestamp.js"), exports);
__exportStar(require("./duration.js"), exports);
__exportStar(require("./any.js"), exports);
__exportStar(require("./wrappers.js"), exports);
__exportStar(require("./gen/google/protobuf/any_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/api_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/cpp_features_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/descriptor_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/duration_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/empty_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/field_mask_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/go_features_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/java_features_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/source_context_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/struct_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/timestamp_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/type_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/wrappers_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/compiler/plugin_pb.js"), exports);
import type { Timestamp } from "./gen/google/protobuf/timestamp_pb.js";
/**
* Create a google.protobuf.Timestamp for the current time.
*/
export declare function timestampNow(): Timestamp;
/**
* Create a google.protobuf.Timestamp message from an ECMAScript Date.
*/
export declare function timestampFromDate(date: Date): Timestamp;
/**
* Convert a google.protobuf.Timestamp message to an ECMAScript Date.
*/
export declare function timestampDate(timestamp: Timestamp): Date;
/**
* Create a google.protobuf.Timestamp message from a Unix timestamp in milliseconds.
*/
export declare function timestampFromMs(timestampMs: number): Timestamp;
/**
* Convert a google.protobuf.Timestamp to a Unix timestamp in milliseconds.
*/
export declare function timestampMs(timestamp: Timestamp): number;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.timestampNow = timestampNow;
exports.timestampFromDate = timestampFromDate;
exports.timestampDate = timestampDate;
exports.timestampFromMs = timestampFromMs;
exports.timestampMs = timestampMs;
const timestamp_pb_js_1 = require("./gen/google/protobuf/timestamp_pb.js");
const create_js_1 = require("../create.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Create a google.protobuf.Timestamp for the current time.
*/
function timestampNow() {
return timestampFromDate(new Date());
}
/**
* Create a google.protobuf.Timestamp message from an ECMAScript Date.
*/
function timestampFromDate(date) {
return timestampFromMs(date.getTime());
}
/**
* Convert a google.protobuf.Timestamp message to an ECMAScript Date.
*/
function timestampDate(timestamp) {
return new Date(timestampMs(timestamp));
}
/**
* Create a google.protobuf.Timestamp message from a Unix timestamp in milliseconds.
*/
function timestampFromMs(timestampMs) {
const seconds = Math.floor(timestampMs / 1000);
return (0, create_js_1.create)(timestamp_pb_js_1.TimestampSchema, {
seconds: proto_int64_js_1.protoInt64.parse(seconds),
nanos: (timestampMs - seconds * 1000) * 1000000,
});
}
/**
* Convert a google.protobuf.Timestamp to a Unix timestamp in milliseconds.
*/
function timestampMs(timestamp) {
return (Number(timestamp.seconds) * 1000 + Math.round(timestamp.nanos / 1000000));
}
import type { Message } from "../types.js";
import type { BoolValue, BytesValue, DoubleValue, FloatValue, Int32Value, Int64Value, StringValue, UInt32Value, UInt64Value } from "./gen/google/protobuf/wrappers_pb.js";
import type { DescField, DescMessage } from "../descriptors.js";
export declare function isWrapper(arg: Message): arg is DoubleValue | FloatValue | Int64Value | UInt64Value | Int32Value | UInt32Value | BoolValue | StringValue | BytesValue;
export type WktWrapperDesc = DescMessage & {
fields: [
DescField & {
fieldKind: "scalar";
number: 1;
name: "value";
oneof: undefined;
}
];
};
export declare function isWrapperDesc(messageDesc: DescMessage): messageDesc is WktWrapperDesc;
/**
* Returns true if the descriptor is a well-known type with a custom JSON
* representation per the protobuf JSON spec. Examples: Timestamp as an
* RFC 3339 string, Duration as "5s", wrappers as the unwrapped scalar.
*
* When packed inside `google.protobuf.Any`, these messages are serialized
* as `{"@type": ..., "value": <custom form>}`; all other messages embed
* their fields directly.
*/
export declare function hasCustomJsonRepresentation(desc: DescMessage): boolean;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isWrapper = isWrapper;
exports.isWrapperDesc = isWrapperDesc;
exports.hasCustomJsonRepresentation = hasCustomJsonRepresentation;
function isWrapper(arg) {
return isWrapperTypeName(arg.$typeName);
}
function isWrapperDesc(messageDesc) {
const f = messageDesc.fields[0];
return (isWrapperTypeName(messageDesc.typeName) &&
f !== undefined &&
f.fieldKind == "scalar" &&
f.name == "value" &&
f.number == 1);
}
/**
* Returns true if the descriptor is a well-known type with a custom JSON
* representation per the protobuf JSON spec. Examples: Timestamp as an
* RFC 3339 string, Duration as "5s", wrappers as the unwrapped scalar.
*
* When packed inside `google.protobuf.Any`, these messages are serialized
* as `{"@type": ..., "value": <custom form>}`; all other messages embed
* their fields directly.
*/
function hasCustomJsonRepresentation(desc) {
switch (desc.typeName) {
case "google.protobuf.Any":
case "google.protobuf.Timestamp":
case "google.protobuf.Duration":
case "google.protobuf.FieldMask":
case "google.protobuf.Struct":
case "google.protobuf.Value":
case "google.protobuf.ListValue":
return true;
default:
return isWrapperDesc(desc);
}
}
function isWrapperTypeName(name) {
return (name.startsWith("google.protobuf.") &&
[
"DoubleValue",
"FloatValue",
"Int64Value",
"UInt64Value",
"Int32Value",
"UInt32Value",
"BoolValue",
"StringValue",
"BytesValue",
].includes(name.substring(16)));
}
export { boot } from "../codegenv2/boot.js";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export { boot } from "../codegenv2/boot.js";
{
"type": "module",
"sideEffects": false
}
+9
-5

@@ -59,7 +59,11 @@ import type { Message } from "../types.js";

export type GenServiceMethods = Record<string, Pick<DescMethod, "input" | "output" | "methodKind">>;
declare class brandv1<A, B = unknown> {
protected v: "codegenv1";
protected a: A | boolean;
protected b: B | boolean;
}
type brandv1<A, B = unknown> = {
/**
* @internal
*/
readonly $codegenv1: {
a: A;
b: B;
};
};
/**

@@ -66,0 +70,0 @@ * Union of the property names of all fields, including oneof members.

@@ -14,9 +14,2 @@ // Copyright 2021-2026 Buf Technologies, Inc.

// limitations under the License.
class brandv1 {
constructor() {
this.v = "codegenv1";
this.a = false;
this.b = false;
}
}
export {};

@@ -65,7 +65,11 @@ import type { Message } from "../types.js";

export type GenServiceMethods = Record<string, Pick<DescMethod, "input" | "output" | "methodKind">>;
declare class brandv2<A, B = unknown> {
protected v: "codegenv2";
protected a: A | boolean;
protected b: B | boolean;
}
type brandv2<A, B = unknown> = {
/**
* @internal
*/
readonly $codegenv2: {
a: A;
b: B;
};
};
/**

@@ -72,0 +76,0 @@ * Union of the property names of all fields, including oneof members.

@@ -14,9 +14,2 @@ // Copyright 2021-2026 Buf Technologies, Inc.

// limitations under the License.
class brandv2 {
constructor() {
this.v = "codegenv2";
this.a = false;
this.b = false;
}
}
export {};

@@ -35,8 +35,13 @@ import type { MessageShape } from "./types.js";

/**
* Compare two messages of the same type.
* Compare two messages of the same type for equality.
*
* Note that this function disregards extensions and unknown fields, and that
* NaN is not equal NaN, following the IEEE standard.
* Fields are compared one by one, but only when set: a field set in one message
* but not the other makes them unequal, while fields set in both are compared
* by value. Extensions and unknown fields are disregarded by default.
*
* Float and double values are compared with IEEE semantics: NaN does not equal
* NaN, and -0 equals 0 (with the exception for singular fields with implicit
* presence: -0 is set, +0 is unset).
*/
export declare function equals<Desc extends DescMessage>(schema: Desc, a: MessageShape<Desc>, b: MessageShape<Desc>, options?: EqualsOptions): boolean;
export {};

@@ -20,6 +20,11 @@ // Copyright 2021-2026 Buf Technologies, Inc.

/**
* Compare two messages of the same type.
* Compare two messages of the same type for equality.
*
* Note that this function disregards extensions and unknown fields, and that
* NaN is not equal NaN, following the IEEE standard.
* Fields are compared one by one, but only when set: a field set in one message
* but not the other makes them unequal, while fields set in both are compared
* by value. Extensions and unknown fields are disregarded by default.
*
* Float and double values are compared with IEEE semantics: NaN does not equal
* NaN, and -0 equals 0 (with the exception for singular fields with implicit
* presence: -0 is set, +0 is unset).
*/

@@ -26,0 +31,0 @@ export function equals(schema, a, b, options) {

import type { AnyDesc, DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescOneof, DescService } from "./descriptors.js";
import type { BinaryReadOptions } from "./from-binary.js";
import type { ReflectMessage } from "./reflect/reflect-types.js";

@@ -19,3 +20,3 @@ import type { Extendee, ExtensionValueShape } from "./types.js";

*/
export declare function getExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc): ExtensionValueShape<Desc>;
export declare function getExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc, options?: Partial<BinaryReadOptions>): ExtensionValueShape<Desc>;
/**

@@ -22,0 +23,0 @@ * Set an extension value on a message. If the message already has a value for

@@ -15,3 +15,3 @@ // Copyright 2021-2026 Buf Technologies, Inc.

import { create } from "./create.js";
import { readField } from "./from-binary.js";
import { makeReadContext, readField } from "./from-binary.js";
import { reflect } from "./reflect/reflect.js";

@@ -36,10 +36,9 @@ import { scalarZeroValue } from "./reflect/scalar.js";

*/
export function getExtension(message, extension) {
export function getExtension(message, extension, options) {
assertExtendee(extension, message);
const ufs = filterUnknownFields(message.$unknown, extension);
const [container, field, get] = createExtensionContainer(extension);
const ctx = makeReadContext(options);
for (const uf of ufs) {
readField(container, new BinaryReader(uf.data), field, uf.wireType, {
readUnknownFields: true,
});
readField(container, new BinaryReader(uf.data), field, uf.wireType, ctx);
}

@@ -46,0 +45,0 @@ return get();

@@ -16,4 +16,17 @@ import { type DescField, type DescMessage } from "./descriptors.js";

readUnknownFields: boolean;
/**
* The maximum depth of nested messages to parse. If a message nests deeper
* than this limit, parsing fails with an error instead of exhausting the
* call stack. Defaults to 100.
*/
recursionLimit: number;
}
interface BinaryReadContext extends BinaryReadOptions {
depth: number;
}
/**
* @private Only exported for getExtension()
*/
export declare function makeReadContext(options?: Partial<BinaryReadOptions>): BinaryReadContext;
/**
* Parse serialized binary data.

@@ -33,4 +46,5 @@ */

/**
* @private
* @private Only exported for getExtension()
*/
export declare function readField(message: ReflectMessage, reader: BinaryReader, field: DescField, wireType: WireType, options: BinaryReadOptions): void;
export declare function readField(message: ReflectMessage, reader: BinaryReader, field: DescField, wireType: WireType, ctx: BinaryReadContext): void;
export {};

@@ -19,8 +19,7 @@ // Copyright 2021-2026 Buf Technologies, Inc.

import { varint32write } from "./wire/varint.js";
// Default options for parsing binary data.
const readDefaults = {
readUnknownFields: true,
};
function makeReadOptions(options) {
return options ? Object.assign(Object.assign({}, readDefaults), options) : readDefaults;
/**
* @private Only exported for getExtension()
*/
export function makeReadContext(options) {
return Object.assign(Object.assign({ readUnknownFields: true, recursionLimit: 100 }, options), { depth: 0 });
}

@@ -32,3 +31,3 @@ /**

const msg = reflect(schema, undefined, false);
readMessage(msg, new BinaryReader(bytes), makeReadOptions(options), false, bytes.byteLength);
readMessage(msg, new BinaryReader(bytes), makeReadContext(options), false, bytes.byteLength);
return msg.message;

@@ -46,3 +45,3 @@ }

export function mergeFromBinary(schema, target, bytes, options) {
readMessage(reflect(schema, target, false), new BinaryReader(bytes), makeReadOptions(options), false, bytes.byteLength);
readMessage(reflect(schema, target, false), new BinaryReader(bytes), makeReadContext(options), false, bytes.byteLength);
return target;

@@ -58,4 +57,7 @@ }

*/
function readMessage(message, reader, options, delimited, lengthOrDelimitedFieldNo) {
function readMessage(message, reader, ctx, delimited, lengthOrDelimitedFieldNo) {
var _a;
if (++ctx.depth > ctx.recursionLimit) {
throw new Error(`cannot decode ${message.desc} from binary: maximum recursion depth of ${ctx.recursionLimit} reached`);
}
const end = delimited ? reader.len : reader.pos + lengthOrDelimitedFieldNo;

@@ -72,4 +74,6 @@ let fieldNo;

if (!field) {
const data = reader.skip(wireType, fieldNo);
if (options.readUnknownFields) {
// Use remaining recursion budget for skipping nested groups
const recursionLimit = ctx.recursionLimit - ctx.depth;
const data = reader.skip(wireType, fieldNo, recursionLimit);
if (ctx.readUnknownFields) {
unknownFields.push({ no: fieldNo, wireType, data });

@@ -79,3 +83,3 @@ }

}
readField(message, reader, field, wireType, options);
readField(message, reader, field, wireType, ctx);
}

@@ -90,7 +94,8 @@ if (delimited) {

}
ctx.depth--;
}
/**
* @private
* @private Only exported for getExtension()
*/
export function readField(message, reader, field, wireType, options) {
export function readField(message, reader, field, wireType, ctx) {
var _a;

@@ -111,3 +116,3 @@ switch (field.fieldKind) {

}
else if (options.readUnknownFields) {
else if (ctx.readUnknownFields) {
const bytes = [];

@@ -126,9 +131,9 @@ varint32write(val, bytes);

case "message":
message.set(field, readMessageField(reader, options, field, message.get(field)));
message.set(field, readMessageField(reader, ctx, field, message.get(field)));
break;
case "list":
readListField(reader, wireType, message.get(field), options);
readListField(reader, wireType, message.get(field), ctx);
break;
case "map":
readMapEntry(reader, message.get(field), options);
readMapEntry(reader, message.get(field), ctx);
break;

@@ -138,3 +143,3 @@ }

// Read a map field, expecting key field = 1, value field = 2
function readMapEntry(reader, map, options) {
function readMapEntry(reader, map, ctx) {
const field = map.field();

@@ -163,3 +168,3 @@ let key;

case "message":
val = readMessageField(reader, options, field);
val = readMessageField(reader, ctx, field);
break;

@@ -188,7 +193,7 @@ }

}
function readListField(reader, wireType, list, options) {
function readListField(reader, wireType, list, ctx) {
var _a;
const field = list.field();
if (field.listKind === "message") {
list.add(readMessageField(reader, options, field));
list.add(readMessageField(reader, ctx, field));
return;

@@ -209,6 +214,6 @@ }

}
function readMessageField(reader, options, field, mergeMessage) {
function readMessageField(reader, ctx, field, mergeMessage) {
const delimited = field.delimitedEncoding;
const message = mergeMessage !== null && mergeMessage !== void 0 ? mergeMessage : reflect(field.message, undefined, false);
readMessage(message, reader, options, delimited, delimited ? field.number : reader.uint32());
readMessage(message, reader, ctx, delimited, delimited ? field.number : reader.uint32());
return message;

@@ -215,0 +220,0 @@ }

@@ -20,9 +20,17 @@ import { type DescEnum, type DescMessage } from "./descriptors.js";

registry?: Registry | undefined;
/**
* The maximum depth of nested messages to parse. If a message nests deeper
* than this limit, parsing fails with an error instead of exhausting the
* call stack. Defaults to 100.
*/
recursionLimit: number;
}
/**
* Parse a message from a JSON string.
*
* Duplicate keys are rejected.
*/
export declare function fromJsonString<Desc extends DescMessage>(schema: Desc, json: string, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON string, merging fields.
* Parse a message from a JSON string, merging fields into the target.
*

@@ -34,2 +42,4 @@ * Repeated fields are appended. Map entries are added, overwriting

* new data.
*
* Duplicate keys in the JSON are rejected, as in `fromJsonString`.
*/

@@ -39,6 +49,10 @@ export declare function mergeFromJsonString<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, json: string, options?: Partial<JsonReadOptions>): MessageShape<Desc>;

* Parse a message from a JSON value.
*
* Duplicate keys are rejected, but a value parsed by JSON.parse has already
* dropped duplicates (the last one wins). Use `fromJsonString` for strict
* duplicate-key checking.
*/
export declare function fromJson<Desc extends DescMessage>(schema: Desc, json: JsonValue, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON value, merging fields.
* Parse a message from a JSON value, merging fields into the target.
*

@@ -50,2 +64,5 @@ * Repeated fields are appended. Map entries are added, overwriting

* new data.
*
* Duplicate keys are rejected as in `fromJson`; use `mergeFromJsonString`
* for strict checking.
*/

@@ -52,0 +69,0 @@ export declare function mergeFromJson<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, json: JsonValue, options?: Partial<JsonReadOptions>): MessageShape<Desc>;

@@ -24,11 +24,9 @@ // Copyright 2021-2026 Buf Technologies, Inc.

import { createExtensionContainer, setExtension } from "./extensions.js";
// Default options for parsing JSON.
const jsonReadDefaults = {
ignoreUnknownFields: false,
};
function makeReadOptions(options) {
return options ? Object.assign(Object.assign({}, jsonReadDefaults), options) : jsonReadDefaults;
function makeReadContext(options) {
return Object.assign(Object.assign({ ignoreUnknownFields: false, recursionLimit: 100 }, options), { depth: 0 });
}
/**
* Parse a message from a JSON string.
*
* Duplicate keys are rejected.
*/

@@ -39,3 +37,3 @@ export function fromJsonString(schema, json, options) {

/**
* Parse a message from a JSON string, merging fields.
* Parse a message from a JSON string, merging fields into the target.
*

@@ -47,2 +45,4 @@ * Repeated fields are appended. Map entries are added, overwriting

* new data.
*
* Duplicate keys in the JSON are rejected, as in `fromJsonString`.
*/

@@ -54,2 +54,6 @@ export function mergeFromJsonString(schema, target, json, options) {

* Parse a message from a JSON value.
*
* Duplicate keys are rejected, but a value parsed by JSON.parse has already
* dropped duplicates (the last one wins). Use `fromJsonString` for strict
* duplicate-key checking.
*/

@@ -59,3 +63,3 @@ export function fromJson(schema, json, options) {

try {
readMessage(msg, json, makeReadOptions(options));
readMessage(msg, json, makeReadContext(options));
}

@@ -74,3 +78,3 @@ catch (e) {

/**
* Parse a message from a JSON value, merging fields.
* Parse a message from a JSON value, merging fields into the target.
*

@@ -82,6 +86,9 @@ * Repeated fields are appended. Map entries are added, overwriting

* new data.
*
* Duplicate keys are rejected as in `fromJson`; use `mergeFromJsonString`
* for strict checking.
*/
export function mergeFromJson(schema, target, json, options) {
try {
readMessage(reflect(schema, target), json, makeReadOptions(options));
readMessage(reflect(schema, target), json, makeReadContext(options));
}

@@ -123,5 +130,9 @@ catch (e) {

}
function readMessage(msg, json, opts) {
function readMessage(msg, json, ctx) {
var _a;
if (tryWktFromJson(msg, json, opts)) {
if (++ctx.depth > ctx.recursionLimit) {
throw new Error(`cannot decode ${msg.desc} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
}
if (tryWktFromJson(msg, json, ctx)) {
ctx.depth--;
return;

@@ -133,10 +144,18 @@ }

const oneofSeen = new Map();
const fieldSeen = new Set();
for (const [jsonKey, jsonValue] of Object.entries(json)) {
const field = getJsonField(msg.desc, jsonKey);
if (field) {
if (fieldSeen.has(field)) {
// The same field may be set by its proto name and its JSON name, or by
// a duplicate or unicode-escaped key that JSON.parse already collapsed.
// Checked before the null-skip below so that a null entry still counts.
throw new FieldError(field, "set multiple times");
}
fieldSeen.add(field);
if (field.oneof && jsonValue === null && field.fieldKind == "scalar") {
// see conformance test Required.Proto3.JsonInput.OneofFieldNull{First,Second}
continue;
}
if (field.oneof) {
if (jsonValue === null && field.fieldKind == "scalar") {
// see conformance test Required.Proto3.JsonInput.OneofFieldNull{First,Second}
continue;
}
const seen = oneofSeen.get(field.oneof);

@@ -148,3 +167,3 @@ if (seen !== undefined) {

}
readField(msg, field, jsonValue, opts);
readField(msg, field, jsonValue, ctx);
}

@@ -156,9 +175,9 @@ else {

// biome-ignore lint/suspicious/noAssignInExpressions: no
(extension = (_a = opts.registry) === null || _a === void 0 ? void 0 : _a.getExtension(jsonKey.substring(1, jsonKey.length - 1))) &&
(extension = (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getExtension(jsonKey.substring(1, jsonKey.length - 1))) &&
extension.extendee.typeName === msg.desc.typeName) {
const [container, field, get] = createExtensionContainer(extension);
readField(container, field, jsonValue, opts);
readField(container, field, jsonValue, ctx);
setExtension(msg.message, extension, get());
}
if (!extension && !opts.ignoreUnknownFields) {
if (!extension && !ctx.ignoreUnknownFields) {
throw new Error(`cannot decode ${msg.desc} from JSON: key "${jsonKey}" is unknown`);

@@ -168,4 +187,5 @@ }

}
ctx.depth--;
}
function readField(msg, field, json, opts) {
function readField(msg, field, json, ctx) {
switch (field.fieldKind) {

@@ -176,16 +196,16 @@ case "scalar":

case "enum":
readEnumField(msg, field, json, opts);
readEnumField(msg, field, json, ctx);
break;
case "message":
readMessageField(msg, field, json, opts);
readMessageField(msg, field, json, ctx);
break;
case "list":
readListField(msg.get(field), json, opts);
readListField(msg.get(field), json, ctx);
break;
case "map":
readMapField(msg.get(field), json, opts);
readMapField(msg.get(field), json, ctx);
break;
}
}
function readListOrMapItem(field, json, opts) {
function readListOrMapItem(field, json, ctx) {
if (field.scalar && json !== null) {

@@ -196,11 +216,11 @@ return scalarFromJson(field, json);

const msgValue = reflect(field.message);
readMessage(msgValue, json, opts);
readMessage(msgValue, json, ctx);
return msgValue;
}
if (field.enum && !isResetSentinelNullValue(field, json)) {
return readEnum(field.enum, json, opts.ignoreUnknownFields);
return readEnum(field.enum, json, ctx.ignoreUnknownFields);
}
throw new FieldError(field, `${field.fieldKind === "list" ? "list item" : "map value"} must not be null`);
}
function readMapField(map, json, opts) {
function readMapField(map, json, ctx) {
if (json === null) {

@@ -213,5 +233,10 @@ return;

}
const seen = new Set();
for (const [jsonMapKey, jsonMapValue] of Object.entries(json)) {
const key = mapKeyFromJson(field.mapKey, jsonMapKey);
const value = readListOrMapItem(field, jsonMapValue, opts);
if (seen.has(key)) {
throw new FieldError(field, `duplicate map key "${jsonMapKey}"`);
}
seen.add(key);
const value = readListOrMapItem(field, jsonMapValue, ctx);
if (value !== tokenIgnoredUnknownEnum) {

@@ -222,3 +247,3 @@ map.set(key, value);

}
function readListField(list, json, opts) {
function readListField(list, json, ctx) {
if (json === null) {

@@ -232,3 +257,3 @@ return;

for (const jsonItem of json) {
const value = readListOrMapItem(field, jsonItem, opts);
const value = readListOrMapItem(field, jsonItem, ctx);
if (value !== tokenIgnoredUnknownEnum) {

@@ -239,3 +264,3 @@ list.add(value);

}
function readMessageField(msg, field, json, opts) {
function readMessageField(msg, field, json, ctx) {
if (isResetSentinelNullValue(field, json)) {

@@ -246,6 +271,6 @@ msg.clear(field);

const msgValue = msg.isSet(field) ? msg.get(field) : reflect(field.message);
readMessage(msgValue, json, opts);
readMessage(msgValue, json, ctx);
msg.set(field, msgValue);
}
function readEnumField(msg, field, json, opts) {
function readEnumField(msg, field, json, ctx) {
if (isResetSentinelNullValue(field, json)) {

@@ -255,3 +280,3 @@ msg.clear(field);

}
const enumValue = readEnum(field.enum, json, opts.ignoreUnknownFields);
const enumValue = readEnum(field.enum, json, ctx.ignoreUnknownFields);
if (enumValue !== tokenIgnoredUnknownEnum) {

@@ -385,3 +410,4 @@ msg.set(field, enumValue);

* Try to parse a JSON value to a map key for the reflect API.
*
* Canonicalizes 64-bit integers given as string, so that "01 and "1" are one
* key, and duplicates can raise an error.
* Returns the input if the JSON value cannot be converted.

@@ -405,2 +431,10 @@ */

return int32FromJson(jsonString);
case ScalarType.INT64:
case ScalarType.SINT64:
case ScalarType.SFIXED64:
case ScalarType.UINT64:
case ScalarType.FIXED64:
return /^-?0+$/.test(jsonString)
? "0"
: jsonString.replace(/^(-?)0+(?=\d)/, "$1");
default:

@@ -434,5 +468,10 @@ return jsonString;

}
/**
* Parse a JSON string, rejecting duplicate object keys (which JSON.parse would
* otherwise silently merge).
*/
function parseJsonString(jsonString, typeName) {
let json;
try {
return JSON.parse(jsonString);
json = JSON.parse(jsonString);
}

@@ -445,4 +484,81 @@ catch (e) {

}
checkDuplicateKeys(jsonString, typeName);
return json;
}
function tryWktFromJson(msg, jsonValue, opts) {
/**
* Scan a JSON string for duplicate object member names at any depth, throwing
* if any are found. JSON.parse() silently keeps the last of duplicate keys, so
* this raw-string scan is the only way to reject them. It must only be called
* with a string that JSON.parse() has already accepted, so it can assume the
* input is well-formed.
*/
function checkDuplicateKeys(jsonString, typeName) {
// One Set of seen member names for each open object; arrays push null.
const stack = [];
// Whether the next string token is an object member name.
let expectKey = false;
let i = 0;
while (i < jsonString.length) {
switch (jsonString[i]) {
case "{":
stack.push(new Set());
expectKey = true;
i++;
break;
case "[":
stack.push(null);
expectKey = false;
i++;
break;
case "}":
case "]":
stack.pop();
expectKey = false;
i++;
break;
case ",":
expectKey = stack[stack.length - 1] != null;
i++;
break;
case ":":
expectKey = false;
i++;
break;
case '"': {
const open = i++;
let escaped = false;
while (i < jsonString.length) {
if (jsonString[i] == "\\") {
escaped = true;
i += 2; // skip the backslash and the character it escapes
continue;
}
if (jsonString[i] == '"') {
break;
}
i++;
}
const close = i++;
const seen = stack[stack.length - 1];
if (expectKey && seen) {
// Decode escapes (rare) so that, for example, a key written with a
// unicode escape collides with the same key written literally.
const name = escaped
? JSON.parse(jsonString.substring(open, close + 1))
: jsonString.substring(open + 1, close);
if (seen.has(name)) {
throw new Error(`cannot decode message ${typeName} from JSON: duplicate object key "${name}"`);
}
seen.add(name);
}
expectKey = false;
break;
}
default:
i++;
break;
}
}
}
function tryWktFromJson(msg, jsonValue, ctx) {
if (!msg.desc.typeName.startsWith("google.protobuf.")) {

@@ -453,3 +569,3 @@ return false;

case "google.protobuf.Any":
anyFromJson(msg.message, jsonValue, opts);
anyFromJson(msg.message, jsonValue, ctx);
return true;

@@ -466,9 +582,9 @@ case "google.protobuf.Timestamp":

case "google.protobuf.Struct":
structFromJson(msg.message, jsonValue);
structFromJson(msg.message, jsonValue, ctx);
return true;
case "google.protobuf.Value":
valueFromJson(msg.message, jsonValue);
valueFromJson(msg.message, jsonValue, ctx);
return true;
case "google.protobuf.ListValue":
listValueFromJson(msg.message, jsonValue);
listValueFromJson(msg.message, jsonValue, ctx);
return true;

@@ -489,3 +605,3 @@ default:

}
function anyFromJson(any, json, opts) {
function anyFromJson(any, json, ctx) {
var _a;

@@ -508,3 +624,3 @@ if (json === null || Array.isArray(json) || typeof json != "object") {

}
const desc = (_a = opts.registry) === null || _a === void 0 ? void 0 : _a.getMessage(typeName);
const desc = (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getMessage(typeName);
if (!desc) {

@@ -517,3 +633,3 @@ throw new Error(`cannot decode message ${any.$typeName} from JSON: ${typeUrl} is not in the type registry`);

const value = json.value;
readMessage(msg, value, opts);
readMessage(msg, value, ctx);
}

@@ -524,3 +640,3 @@ else {

delete copy["@type"];
readMessage(msg, copy, opts);
readMessage(msg, copy, ctx);
}

@@ -591,3 +707,3 @@ anyPack(msg.desc, msg.message, any);

}
function structFromJson(struct, json) {
function structFromJson(struct, json, ctx) {
if (typeof json != "object" || json == null || Array.isArray(json)) {

@@ -598,7 +714,10 @@ throw new Error(`cannot decode message ${struct.$typeName} from JSON ${formatVal(json)}`);

const parsedV = create(ValueSchema);
valueFromJson(parsedV, v);
valueFromJson(parsedV, v, ctx);
struct.fields[k] = parsedV;
}
}
function valueFromJson(value, json) {
function valueFromJson(value, json, ctx) {
if (++ctx.depth > ctx.recursionLimit) {
throw new Error(`cannot decode ${value.$typeName} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
}
switch (typeof json) {

@@ -620,3 +739,3 @@ case "number":

const listValue = create(ListValueSchema);
listValueFromJson(listValue, json);
listValueFromJson(listValue, json, ctx);
value.kind = { case: "listValue", value: listValue };

@@ -626,3 +745,3 @@ }

const struct = create(StructSchema);
structFromJson(struct, json);
structFromJson(struct, json, ctx);
value.kind = { case: "structValue", value: struct };

@@ -634,5 +753,6 @@ }

}
ctx.depth--;
return value;
}
function listValueFromJson(listValue, json) {
function listValueFromJson(listValue, json, ctx) {
if (!Array.isArray(json)) {

@@ -643,5 +763,5 @@ throw new Error(`cannot decode message ${listValue.$typeName} from JSON ${formatVal(json)}`);

const value = create(ValueSchema);
valueFromJson(value, e);
valueFromJson(value, e, ctx);
listValue.values.push(value);
}
}

@@ -28,2 +28,3 @@ // Copyright 2021-2026 Buf Technologies, Inc.

(!!globalThis.Deno ||
!!globalThis.Bun ||
typeof process != "object" ||

@@ -30,0 +31,0 @@ typeof process.env != "object" ||

@@ -77,3 +77,5 @@ // Copyright 2021-2026 Buf Technologies, Inc.

if (field.enum.open) {
return Number.isInteger(value);
// Open enums accept unrecognized values, but enum values are always
// int32 (see https://protobuf.dev/programming-guides/proto3/#enum).
return checkScalarValue(value, ScalarType.INT32);
}

@@ -80,0 +82,0 @@ return field.enum.values.some((v) => v.number === value);

@@ -8,15 +8,37 @@ import { ScalarType } from "../descriptors.js";

* Returns true if both scalar values are equal.
*
* For float and double, values are compared following IEEE semantics: -0
* equals 0, and NaN does not equal NaN. This is value equality, not identity.
*
* It deliberately differs from isScalarZeroValue, which treats -0 as distinct
* from 0. A value can equal the zero value without being a zero value
* (scalarEquals(DOUBLE, -0, 0) is true while isScalarZeroValue(DOUBLE, -0) is
* false) so this function must not be used to derive implicit presence.
*/
export declare function scalarEquals(type: ScalarType, a: ScalarValue | undefined, b: ScalarValue | undefined): boolean;
/**
* Returns the zero value for the given scalar type.
* Returns the zero value for the given scalar type, the value a field of this
* type has when unset: 0 for numeric types, "" for strings, false for
* booleans, and an empty Uint8Array for bytes. For 64-bit integer types, the
* result is "0" when longAsString is true, otherwise 0n.
*
* This is the type's zero value, not a proto2 custom field default. For float
* and double it is +0; isScalarZeroValue treats only +0, not -0, as this value.
*/
export declare function scalarZeroValue<T extends ScalarType, LongAsString extends boolean>(type: T, longAsString: LongAsString): ScalarValue<T, LongAsString>;
/**
* Returns true for a zero-value. For example, an integer has the zero-value `0`,
* a boolean is `false`, a string is `""`, and bytes is an empty Uint8Array.
* Returns true if the value is the zero value for the given scalar type: `0`
* for numeric types, `false` for booleans, `""` for strings, and an empty
* Uint8Array for bytes.
*
* In proto3, zero-values are not written to the wire, unless the field is
* optional or repeated.
* This is the implicit-presence default check. A singular field with implicit
* presence is treated as unset, and omitted from the wire, when its value is
* the zero value. With explicit presence, or in repeated and map fields,
* presence is structural and this function does not apply.
*
* Note that -0 is NOT a zero value for float and double: under implicit
* presence, +0 is omitted from the wire but -0 is written, following the
* proto3 specification. As a result this can disagree with scalarEquals, which
* compares by value and treats -0 as equal to 0.
*/
export declare function isScalarZeroValue(type: ScalarType, value: unknown): boolean;

@@ -18,2 +18,10 @@ // Copyright 2021-2026 Buf Technologies, Inc.

* Returns true if both scalar values are equal.
*
* For float and double, values are compared following IEEE semantics: -0
* equals 0, and NaN does not equal NaN. This is value equality, not identity.
*
* It deliberately differs from isScalarZeroValue, which treats -0 as distinct
* from 0. A value can equal the zero value without being a zero value
* (scalarEquals(DOUBLE, -0, 0) is true while isScalarZeroValue(DOUBLE, -0) is
* false) so this function must not be used to derive implicit presence.
*/

@@ -55,3 +63,9 @@ export function scalarEquals(type, a, b) {

/**
* Returns the zero value for the given scalar type.
* Returns the zero value for the given scalar type, the value a field of this
* type has when unset: 0 for numeric types, "" for strings, false for
* booleans, and an empty Uint8Array for bytes. For 64-bit integer types, the
* result is "0" when longAsString is true, otherwise 0n.
*
* This is the type's zero value, not a proto2 custom field default. For float
* and double it is +0; isScalarZeroValue treats only +0, not -0, as this value.
*/

@@ -82,7 +96,15 @@ export function scalarZeroValue(type, longAsString) {

/**
* Returns true for a zero-value. For example, an integer has the zero-value `0`,
* a boolean is `false`, a string is `""`, and bytes is an empty Uint8Array.
* Returns true if the value is the zero value for the given scalar type: `0`
* for numeric types, `false` for booleans, `""` for strings, and an empty
* Uint8Array for bytes.
*
* In proto3, zero-values are not written to the wire, unless the field is
* optional or repeated.
* This is the implicit-presence default check. A singular field with implicit
* presence is treated as unset, and omitted from the wire, when its value is
* the zero value. With explicit presence, or in repeated and map fields,
* presence is structural and this function does not apply.
*
* Note that -0 is NOT a zero value for float and double: under implicit
* presence, +0 is omitted from the wire but -0 is written, following the
* proto3 specification. As a result this can disagree with scalarEquals, which
* compares by value and treats -0 as equal to 0.
*/

@@ -97,5 +119,10 @@ export function isScalarZeroValue(type, value) {

return value instanceof Uint8Array && !value.byteLength;
case ScalarType.DOUBLE:
case ScalarType.FLOAT:
// Object.is distinguishes -0 from 0.
return Object.is(value, 0);
default:
return value == 0; // Loose comparison matches 0n, 0 and "0"
// Loose comparison matches 0n, 0 and "0".
return value == 0;
}
}

@@ -230,3 +230,3 @@ // Copyright 2021-2026 Buf Technologies, Inc.

// bootstrap-inject defaults: EDITION_PROTO2 to EDITION_2024: export const minimumEdition: SupportedEdition = $minimumEdition, maximumEdition: SupportedEdition = $maximumEdition;
// generated from protoc v34.0
// generated from protoc v34.1
export const minimumEdition = 998, maximumEdition = 1001;

@@ -233,0 +233,0 @@ const featureDefaults = {

@@ -197,5 +197,7 @@ /**

* When skipping StartGroup, provide the tags field number to check for
* matching field number in the EndGroup tag.
* matching field number in the EndGroup tag. Recursion into nested groups
* is guarded by the `recursionLimit` argument: When the limit is reached,
* this method throws.
*/
skip(wireType: WireType, fieldNo?: number): Uint8Array;
skip(wireType: WireType, fieldNo?: number, recursionLimit?: number): Uint8Array;
protected varint64: () => [number, number];

@@ -202,0 +204,0 @@ /**

@@ -327,5 +327,7 @@ // Copyright 2021-2026 Buf Technologies, Inc.

* When skipping StartGroup, provide the tags field number to check for
* matching field number in the EndGroup tag.
* matching field number in the EndGroup tag. Recursion into nested groups
* is guarded by the `recursionLimit` argument: When the limit is reached,
* this method throws.
*/
skip(wireType, fieldNo) {
skip(wireType, fieldNo, recursionLimit = 100) {
let start = this.pos;

@@ -349,2 +351,5 @@ switch (wireType) {

case WireType.StartGroup:
if (recursionLimit <= 0) {
throw new Error("maximum recursion depth reached");
}
for (;;) {

@@ -358,3 +363,3 @@ const [fn, wt] = this.tag();

}
this.skip(wt, fn);
this.skip(wt, fn, recursionLimit - 1);
}

@@ -361,0 +366,0 @@ break;

@@ -24,3 +24,3 @@ import type { DescMessage } from "../descriptors.js";

*/
export declare function sizeDelimitedDecodeStream<Desc extends DescMessage>(messageDesc: Desc, iterable: AsyncIterable<Uint8Array>, options?: BinaryReadOptions): AsyncIterableIterator<MessageShape<Desc>>;
export declare function sizeDelimitedDecodeStream<Desc extends DescMessage>(messageDesc: Desc, iterable: AsyncIterable<Uint8Array>, options?: Partial<BinaryReadOptions>): AsyncIterableIterator<MessageShape<Desc>>;
/**

@@ -27,0 +27,0 @@ * Decodes the size from the given size-delimited message, which may be

{
"name": "@bufbuild/protobuf",
"version": "2.12.0",
"version": "2.12.1",
"license": "(Apache-2.0 AND BSD-3-Clause)",
"description": "A complete implementation of Protocol Buffers in TypeScript, suitable for web browsers and Node.js.",
"keywords": ["protobuf", "schema", "typescript", "ecmascript"],
"description": "Protocol Buffers for ECMAScript. The only JavaScript Protobuf library that is fully-compliant with Protobuf conformance tests.",
"keywords": [
"protobuf",
"schema",
"typescript",
"ecmascript"
],
"homepage": "https://protobufes.com/",
"repository": {

@@ -13,6 +19,3 @@ "type": "git",

"scripts": {
"prebuild": "rm -rf ./dist/*",
"build": "npm run build:cjs && npm run build:esm",
"build:cjs": "../../node_modules/typescript/bin/tsc --project tsconfig.json --module commonjs --verbatimModuleSyntax false --moduleResolution node10 --outDir ./dist/cjs && echo >./dist/cjs/package.json '{\"type\":\"commonjs\"}'",
"build:esm": "../../node_modules/typescript/bin/tsc --project tsconfig.json --outDir ./dist/esm",
"build": "tshy",
"bootstrap": "npm run bootstrap:inject && npm run bootstrap:wkt",

@@ -29,42 +32,105 @@ "bootstrap:inject": "node scripts/bootstrap-inject.mjs src",

"sideEffects": false,
"main": "./dist/cjs/index.js",
"tshy": {
"exports": {
".": "./src/index.ts",
"./codegenv1": "./src/codegenv1/index.ts",
"./codegenv2": "./src/codegenv2/index.ts",
"./reflect": "./src/reflect/index.ts",
"./wkt": "./src/wkt/index.ts",
"./wire": "./src/wire/index.ts",
"./package.json": "./package.json"
}
},
"devDependencies": {
"tshy": "^4.1.3",
"upstream-protobuf": "*"
},
"files": [
"dist/**"
],
"exports": {
".": {
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js"
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
},
"./codegenv1": {
"import": "./dist/esm/codegenv1/index.js",
"require": "./dist/cjs/codegenv1/index.js"
"import": {
"types": "./dist/esm/codegenv1/index.d.ts",
"default": "./dist/esm/codegenv1/index.js"
},
"require": {
"types": "./dist/commonjs/codegenv1/index.d.ts",
"default": "./dist/commonjs/codegenv1/index.js"
}
},
"./codegenv2": {
"import": "./dist/esm/codegenv2/index.js",
"require": "./dist/cjs/codegenv2/index.js"
"import": {
"types": "./dist/esm/codegenv2/index.d.ts",
"default": "./dist/esm/codegenv2/index.js"
},
"require": {
"types": "./dist/commonjs/codegenv2/index.d.ts",
"default": "./dist/commonjs/codegenv2/index.js"
}
},
"./reflect": {
"import": "./dist/esm/reflect/index.js",
"require": "./dist/cjs/reflect/index.js"
"import": {
"types": "./dist/esm/reflect/index.d.ts",
"default": "./dist/esm/reflect/index.js"
},
"require": {
"types": "./dist/commonjs/reflect/index.d.ts",
"default": "./dist/commonjs/reflect/index.js"
}
},
"./wkt": {
"import": "./dist/esm/wkt/index.js",
"require": "./dist/cjs/wkt/index.js"
"import": {
"types": "./dist/esm/wkt/index.d.ts",
"default": "./dist/esm/wkt/index.js"
},
"require": {
"types": "./dist/commonjs/wkt/index.d.ts",
"default": "./dist/commonjs/wkt/index.js"
}
},
"./wire": {
"import": "./dist/esm/wire/index.js",
"require": "./dist/cjs/wire/index.js"
}
"import": {
"types": "./dist/esm/wire/index.d.ts",
"default": "./dist/esm/wire/index.js"
},
"require": {
"types": "./dist/commonjs/wire/index.d.ts",
"default": "./dist/commonjs/wire/index.js"
}
},
"./package.json": "./package.json"
},
"main": "./dist/commonjs/index.js",
"types": "./dist/commonjs/index.d.ts",
"module": "./dist/esm/index.js",
"typesVersions": {
"*": {
"codegenv1": ["./dist/cjs/codegenv1/index.d.ts"],
"codegenv2": ["./dist/cjs/codegenv2/index.d.ts"],
"reflect": ["./dist/cjs/reflect/index.d.ts"],
"wkt": ["./dist/cjs/wkt/index.d.ts"],
"wire": ["./dist/cjs/wire/index.d.ts"]
"codegenv1": [
"./dist/commonjs/codegenv1/index.d.ts"
],
"codegenv2": [
"./dist/commonjs/codegenv2/index.d.ts"
],
"reflect": [
"./dist/commonjs/reflect/index.d.ts"
],
"wkt": [
"./dist/commonjs/wkt/index.d.ts"
],
"wire": [
"./dist/commonjs/wire/index.d.ts"
]
}
},
"devDependencies": {
"upstream-protobuf": "*"
},
"files": ["dist/**"]
}
}

@@ -35,6 +35,6 @@ # @bufbuild/protobuf

To learn how to work with `@bufbuild/protobuf`, check out the docs for the [Runtime API](https://github.com/bufbuild/protobuf-es/tree/main/MANUAL.md#working-with-messages)
and the [generated code](https://github.com/bufbuild/protobuf-es/tree/main/MANUAL.md#generated-code).
To learn how to work with `@bufbuild/protobuf`, check out the docs for the [Runtime API](https://protobufes.com/guides/messages/)
and the [generated code](https://protobufes.com/reference/generated-code/).
Official documentation for the Protobuf-ES project can be found at [github.com/bufbuild/protobuf-es](https://github.com/bufbuild/protobuf-es).
Official documentation for the Protobuf-ES project can be found at [protobufes.com](https://protobufes.com/).

@@ -41,0 +41,0 @@ For more information on Buf, check out the official [Buf documentation](https://buf.build/docs/).

import type { MessageShape } from "./types.js";
import { type DescMessage } from "./descriptors.js";
/**
* Create a deep copy of a message, including extensions and unknown fields.
*/
export declare function clone<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>): MessageShape<Desc>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.clone = clone;
const descriptors_js_1 = require("./descriptors.js");
const reflect_js_1 = require("./reflect/reflect.js");
const guard_js_1 = require("./reflect/guard.js");
/**
* Create a deep copy of a message, including extensions and unknown fields.
*/
function clone(schema, message) {
return cloneReflect((0, reflect_js_1.reflect)(schema, message)).message;
}
function cloneReflect(i) {
const o = (0, reflect_js_1.reflect)(i.desc);
for (const f of i.fields) {
if (!i.isSet(f)) {
continue;
}
switch (f.fieldKind) {
case "list":
const list = o.get(f);
for (const item of i.get(f)) {
list.add(cloneSingular(f, item));
}
break;
case "map":
const map = o.get(f);
for (const entry of i.get(f).entries()) {
map.set(entry[0], cloneSingular(f, entry[1]));
}
break;
default: {
o.set(f, cloneSingular(f, i.get(f)));
break;
}
}
}
const unknown = i.getUnknown();
if (unknown && unknown.length > 0) {
o.setUnknown([...unknown]);
}
return o;
}
function cloneSingular(field, value) {
if (field.message !== undefined && (0, guard_js_1.isReflectMessage)(value)) {
return cloneReflect(value);
}
if (field.scalar == descriptors_js_1.ScalarType.BYTES && value instanceof Uint8Array) {
// @ts-expect-error T cannot extend Uint8Array in practice
return value.slice();
}
return value;
}
import type { DescFile } from "../descriptors.js";
import type { GenEnum } from "./types.js";
import type { JsonValue } from "../json-value.js";
export { tsEnum } from "../codegenv2/enum.js";
/**
* Hydrate an enum descriptor.
*
* @private
*/
export declare function enumDesc<Shape extends number, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenEnum<Shape, JsonType>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.tsEnum = void 0;
exports.enumDesc = enumDesc;
var enum_js_1 = require("../codegenv2/enum.js");
Object.defineProperty(exports, "tsEnum", { enumerable: true, get: function () { return enum_js_1.tsEnum; } });
/**
* Hydrate an enum descriptor.
*
* @private
*/
function enumDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.enums[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedEnums[e];
}
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenExtension } from "./types.js";
/**
* Hydrate an extension descriptor.
*
* @private
*/
export declare function extDesc<Extendee extends Message, Value>(file: DescFile, path: number, ...paths: number[]): GenExtension<Extendee, Value>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.extDesc = extDesc;
/**
* Hydrate an extension descriptor.
*
* @private
*/
function extDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.extensions[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedExtensions[e];
}
export { fileDesc } from "../codegenv2/file.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileDesc = void 0;
var file_js_1 = require("../codegenv2/file.js");
Object.defineProperty(exports, "fileDesc", { enumerable: true, get: function () { return file_js_1.fileDesc; } });
export * from "../codegenv2/boot.js";
export * from "../codegenv2/embed.js";
export * from "./enum.js";
export * from "./extension.js";
export * from "./file.js";
export * from "./message.js";
export * from "./service.js";
export * from "./symbols.js";
export * from "../codegenv2/scalar.js";
export * from "./types.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("../codegenv2/boot.js"), exports);
__exportStar(require("../codegenv2/embed.js"), exports);
__exportStar(require("./enum.js"), exports);
__exportStar(require("./extension.js"), exports);
__exportStar(require("./file.js"), exports);
__exportStar(require("./message.js"), exports);
__exportStar(require("./service.js"), exports);
__exportStar(require("./symbols.js"), exports);
__exportStar(require("../codegenv2/scalar.js"), exports);
__exportStar(require("./types.js"), exports);
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenMessage } from "./types.js";
import type { JsonValue } from "../json-value.js";
/**
* Hydrate a message descriptor.
*
* @private
*/
export declare function messageDesc<Shape extends Message, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenMessage<Shape, JsonType>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.messageDesc = messageDesc;
/**
* Hydrate a message descriptor.
*
* @private
*/
function messageDesc(file, path, ...paths) {
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]);
}
import type { GenService, GenServiceMethods } from "./types.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a service descriptor.
*
* @private
*/
export declare function serviceDesc<T extends GenServiceMethods>(file: DescFile, path: number, ...paths: number[]): GenService<T>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceDesc = serviceDesc;
/**
* Hydrate a service descriptor.
*
* @private
*/
function serviceDesc(file, path, ...paths) {
if (paths.length > 0) {
throw new Error();
}
return file.services[path];
}
/**
* @private
*/
export declare const packageName = "@bufbuild/protobuf";
/**
* @private
*/
export declare const wktPublicImportPaths: Readonly<Record<string, string>>;
/**
* @private
*/
export declare const symbols: {
readonly codegen: {
readonly boot: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/boot.js";
readonly from: string;
};
readonly fileDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/file.js";
readonly from: string;
};
readonly enumDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/enum.js";
readonly from: string;
};
readonly extDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/extension.js";
readonly from: string;
};
readonly messageDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/message.js";
readonly from: string;
};
readonly serviceDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/service.js";
readonly from: string;
};
readonly tsEnum: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/enum.js";
readonly from: string;
};
readonly GenFile: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenEnum: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenExtension: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenMessage: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenService: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
};
readonly isMessage: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../is-message.js";
readonly from: "@bufbuild/protobuf";
};
readonly Message: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../types.js";
readonly from: "@bufbuild/protobuf";
};
readonly create: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../create.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly protoInt64: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../proto-int64.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonValue: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonObject: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../json-value.js";
readonly from: "@bufbuild/protobuf";
};
};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.symbols = exports.wktPublicImportPaths = exports.packageName = void 0;
const symbols_js_1 = require("../codegenv2/symbols.js");
/**
* @private
*/
exports.packageName = symbols_js_1.packageName;
/**
* @private
*/
exports.wktPublicImportPaths = symbols_js_1.wktPublicImportPaths;
/**
* @private
*/
// biome-ignore format: want this to read well
exports.symbols = Object.assign(Object.assign({}, symbols_js_1.symbols), { codegen: {
boot: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/boot.js", from: exports.packageName + "/codegenv1" },
fileDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/file.js", from: exports.packageName + "/codegenv1" },
enumDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/enum.js", from: exports.packageName + "/codegenv1" },
extDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/extension.js", from: exports.packageName + "/codegenv1" },
messageDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/message.js", from: exports.packageName + "/codegenv1" },
serviceDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/service.js", from: exports.packageName + "/codegenv1" },
tsEnum: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/enum.js", from: exports.packageName + "/codegenv1" },
GenFile: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenEnum: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenExtension: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenMessage: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenService: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
} });
import type { Message } from "../types.js";
import type { DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescService } from "../descriptors.js";
import type { JsonValue } from "../json-value.js";
/**
* Describes a protobuf source file.
*
* @private
*/
export type GenFile = DescFile;
/**
* Describes a message declaration in a protobuf source file.
*
* This type is identical to DescMessage, but carries additional type
* information.
*
* @private
*/
export type GenMessage<RuntimeShape extends Message, JsonType = JsonValue> = Omit<DescMessage, "field" | "typeName"> & {
field: Record<MessageFieldNames<RuntimeShape>, DescField>;
typeName: RuntimeShape["$typeName"];
} & brandv1<RuntimeShape, JsonType>;
/**
* Describes an enumeration in a protobuf source file.
*
* This type is identical to DescEnum, but carries additional type
* information.
*
* @private
*/
export type GenEnum<RuntimeShape extends number, JsonType extends JsonValue = JsonValue> = Omit<DescEnum, "value"> & {
value: Record<RuntimeShape, DescEnumValue>;
} & brandv1<RuntimeShape, JsonType>;
/**
* Describes an extension in a protobuf source file.
*
* This type is identical to DescExtension, but carries additional type
* information.
*
* @private
*/
export type GenExtension<Extendee extends Message = Message, RuntimeShape = unknown> = DescExtension & brandv1<Extendee, RuntimeShape>;
/**
* Describes a service declaration in a protobuf source file.
*
* This type is identical to DescService, but carries additional type
* information.
*
* @private
*/
export type GenService<RuntimeShape extends GenServiceMethods> = Omit<DescService, "method"> & {
method: {
[K in keyof RuntimeShape]: RuntimeShape[K] & DescMethod;
};
};
/**
* @private
*/
export type GenServiceMethods = Record<string, Pick<DescMethod, "input" | "output" | "methodKind">>;
declare class brandv1<A, B = unknown> {
protected v: "codegenv1";
protected a: A | boolean;
protected b: B | boolean;
}
/**
* Union of the property names of all fields, including oneof members.
* For an anonymous message (no generated message shape), it's simply a string.
*/
type MessageFieldNames<T extends Message> = Message extends T ? string : Exclude<keyof {
[P in keyof T as P extends ("$typeName" | "$unknown") ? never : T[P] extends Oneof<infer K> ? K : P]-?: true;
}, number | symbol>;
type Oneof<K extends string> = {
case: K | undefined;
value?: unknown;
};
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
class brandv1 {
constructor() {
this.v = "codegenv1";
this.a = false;
this.b = false;
}
}
import type { DescriptorProto_ExtensionRange, FieldDescriptorProto_Label, FieldDescriptorProto_Type, FieldOptions_OptionRetention, FieldOptions_OptionTargetType, FieldOptions_EditionDefault, EnumValueDescriptorProto, FileDescriptorProto } from "../wkt/gen/google/protobuf/descriptor_pb.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a file descriptor for google/protobuf/descriptor.proto from a plain
* object.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export declare function boot(boot: FileDescriptorProtoBoot): DescFile;
/**
* An object literal for initializing the message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export type FileDescriptorProtoBoot = {
name: "google/protobuf/descriptor.proto";
package: "google.protobuf";
messageType: DescriptorProtoBoot[];
enumType: EnumDescriptorProtoBoot[];
};
export type DescriptorProtoBoot = {
name: string;
field?: FieldDescriptorProtoBoot[];
nestedType?: DescriptorProtoBoot[];
enumType?: EnumDescriptorProtoBoot[];
extensionRange?: Pick<DescriptorProto_ExtensionRange, "start" | "end">[];
};
export type FieldDescriptorProtoBoot = {
name: string;
number: number;
label?: FieldDescriptorProto_Label;
type: FieldDescriptorProto_Type;
typeName?: string;
extendee?: string;
defaultValue?: string;
options?: FieldOptionsBoot;
};
export type FieldOptionsBoot = {
packed?: boolean;
deprecated?: boolean;
retention?: FieldOptions_OptionRetention;
targets?: FieldOptions_OptionTargetType[];
editionDefaults?: FieldOptions_EditionDefaultBoot[];
};
export type FieldOptions_EditionDefaultBoot = Pick<FieldOptions_EditionDefault, "edition" | "value">;
export type EnumDescriptorProtoBoot = {
name: string;
value: EnumValueDescriptorProtoBoot[];
};
export type EnumValueDescriptorProtoBoot = Pick<EnumValueDescriptorProto, "name" | "number">;
/**
* Creates the message google.protobuf.FileDescriptorProto from an object literal.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export declare function bootFileDescriptorProto(init: FileDescriptorProtoBoot): FileDescriptorProto;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.boot = boot;
exports.bootFileDescriptorProto = bootFileDescriptorProto;
const restore_json_names_js_1 = require("./restore-json-names.js");
const registry_js_1 = require("../registry.js");
/**
* Hydrate a file descriptor for google/protobuf/descriptor.proto from a plain
* object.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
function boot(boot) {
const root = bootFileDescriptorProto(boot);
root.messageType.forEach(restore_json_names_js_1.restoreJsonNames);
const reg = (0, registry_js_1.createFileRegistry)(root, () => undefined);
// biome-ignore lint/style/noNonNullAssertion: non-null assertion because we just created the registry from the file we look up
return reg.getFile(root.name);
}
/**
* Creates the message google.protobuf.FileDescriptorProto from an object literal.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
function bootFileDescriptorProto(init) {
const proto = Object.create({
syntax: "",
edition: 0,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FileDescriptorProto", dependency: [], publicDependency: [], weakDependency: [], optionDependency: [], service: [], extension: [] }, init), { messageType: init.messageType.map(bootDescriptorProto), enumType: init.enumType.map(bootEnumDescriptorProto) }));
}
function bootDescriptorProto(init) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const proto = Object.create({
visibility: 0,
});
return Object.assign(proto, {
$typeName: "google.protobuf.DescriptorProto",
name: init.name,
field: (_b = (_a = init.field) === null || _a === void 0 ? void 0 : _a.map(bootFieldDescriptorProto)) !== null && _b !== void 0 ? _b : [],
extension: [],
nestedType: (_d = (_c = init.nestedType) === null || _c === void 0 ? void 0 : _c.map(bootDescriptorProto)) !== null && _d !== void 0 ? _d : [],
enumType: (_f = (_e = init.enumType) === null || _e === void 0 ? void 0 : _e.map(bootEnumDescriptorProto)) !== null && _f !== void 0 ? _f : [],
extensionRange: (_h = (_g = init.extensionRange) === null || _g === void 0 ? void 0 : _g.map((e) => (Object.assign({ $typeName: "google.protobuf.DescriptorProto.ExtensionRange" }, e)))) !== null && _h !== void 0 ? _h : [],
oneofDecl: [],
reservedRange: [],
reservedName: [],
});
}
function bootFieldDescriptorProto(init) {
const proto = Object.create({
label: 1,
typeName: "",
extendee: "",
defaultValue: "",
oneofIndex: 0,
jsonName: "",
proto3Optional: false,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FieldDescriptorProto" }, init), { options: init.options ? bootFieldOptions(init.options) : undefined }));
}
function bootFieldOptions(init) {
var _a, _b, _c;
const proto = Object.create({
ctype: 0,
packed: false,
jstype: 0,
lazy: false,
unverifiedLazy: false,
deprecated: false,
weak: false,
debugRedact: false,
retention: 0,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FieldOptions" }, init), { targets: (_a = init.targets) !== null && _a !== void 0 ? _a : [], editionDefaults: (_c = (_b = init.editionDefaults) === null || _b === void 0 ? void 0 : _b.map((e) => (Object.assign({ $typeName: "google.protobuf.FieldOptions.EditionDefault" }, e)))) !== null && _c !== void 0 ? _c : [], uninterpretedOption: [] }));
}
function bootEnumDescriptorProto(init) {
const proto = Object.create({
visibility: 0,
});
return Object.assign(proto, {
$typeName: "google.protobuf.EnumDescriptorProto",
name: init.name,
reservedName: [],
reservedRange: [],
value: init.value.map((e) => (Object.assign({ $typeName: "google.protobuf.EnumValueDescriptorProto" }, e))),
});
}
import type { DescEnum, DescExtension, DescMessage, DescService } from "../descriptors.js";
import { type FileDescriptorProto } from "../wkt/gen/google/protobuf/descriptor_pb.js";
import type { FileDescriptorProtoBoot } from "./boot.js";
type EmbedUnknown = {
bootable: false;
proto(): FileDescriptorProto;
base64(): string;
};
type EmbedDescriptorProto = Omit<EmbedUnknown, "bootable"> & {
bootable: true;
boot(): FileDescriptorProtoBoot;
};
/**
* Create necessary information to embed a file descriptor in
* generated code.
*
* @private
*/
export declare function embedFileDesc(file: FileDescriptorProto): EmbedUnknown | EmbedDescriptorProto;
/**
* Compute the path to a message, enumeration, extension, or service in a
* file descriptor.
*
* @private
*/
export declare function pathInFileDesc(desc: DescMessage | DescEnum | DescExtension | DescService): number[];
/**
* The file descriptor for google/protobuf/descriptor.proto cannot be embedded
* in serialized form, since it is required to parse itself.
*
* This function takes an instance of the message, and returns a plain object
* that can be hydrated to the message again via bootFileDescriptorProto().
*
* This function only works with a message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto, and only supports features that are
* relevant for the specific use case. For example, it discards file options,
* reserved ranges and reserved names, and field options that are unused in
* descriptor.proto.
*
* @private
*/
export declare function createFileDescriptorProtoBoot(proto: FileDescriptorProto): FileDescriptorProtoBoot;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.embedFileDesc = embedFileDesc;
exports.pathInFileDesc = pathInFileDesc;
exports.createFileDescriptorProtoBoot = createFileDescriptorProtoBoot;
const names_js_1 = require("../reflect/names.js");
const fields_js_1 = require("../fields.js");
const base64_encoding_js_1 = require("../wire/base64-encoding.js");
const to_binary_js_1 = require("../to-binary.js");
const clone_js_1 = require("../clone.js");
const descriptor_pb_js_1 = require("../wkt/gen/google/protobuf/descriptor_pb.js");
/**
* Create necessary information to embed a file descriptor in
* generated code.
*
* @private
*/
function embedFileDesc(file) {
const embed = {
bootable: false,
proto() {
const stripped = (0, clone_js_1.clone)(descriptor_pb_js_1.FileDescriptorProtoSchema, file);
(0, fields_js_1.clearField)(stripped, descriptor_pb_js_1.FileDescriptorProtoSchema.field.dependency);
(0, fields_js_1.clearField)(stripped, descriptor_pb_js_1.FileDescriptorProtoSchema.field.sourceCodeInfo);
stripped.messageType.map(stripJsonNames);
return stripped;
},
base64() {
const bytes = (0, to_binary_js_1.toBinary)(descriptor_pb_js_1.FileDescriptorProtoSchema, this.proto());
return (0, base64_encoding_js_1.base64Encode)(bytes, "std_raw");
},
};
return file.name == "google/protobuf/descriptor.proto"
? Object.assign(Object.assign({}, embed), { bootable: true, boot() {
return createFileDescriptorProtoBoot(this.proto());
} }) : embed;
}
function stripJsonNames(d) {
for (const f of d.field) {
if (f.jsonName === (0, names_js_1.protoCamelCase)(f.name)) {
(0, fields_js_1.clearField)(f, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.jsonName);
}
}
for (const n of d.nestedType) {
stripJsonNames(n);
}
}
/**
* Compute the path to a message, enumeration, extension, or service in a
* file descriptor.
*
* @private
*/
function pathInFileDesc(desc) {
if (desc.kind == "service") {
return [desc.file.services.indexOf(desc)];
}
const parent = desc.parent;
if (parent == undefined) {
switch (desc.kind) {
case "enum":
return [desc.file.enums.indexOf(desc)];
case "message":
return [desc.file.messages.indexOf(desc)];
case "extension":
return [desc.file.extensions.indexOf(desc)];
}
}
function findPath(cur) {
const nested = [];
for (let parent = cur.parent; parent;) {
const idx = parent.nestedMessages.indexOf(cur);
nested.unshift(idx);
cur = parent;
parent = cur.parent;
}
nested.unshift(cur.file.messages.indexOf(cur));
return nested;
}
const path = findPath(parent);
switch (desc.kind) {
case "extension":
return [...path, parent.nestedExtensions.indexOf(desc)];
case "message":
return [...path, parent.nestedMessages.indexOf(desc)];
case "enum":
return [...path, parent.nestedEnums.indexOf(desc)];
}
}
/**
* The file descriptor for google/protobuf/descriptor.proto cannot be embedded
* in serialized form, since it is required to parse itself.
*
* This function takes an instance of the message, and returns a plain object
* that can be hydrated to the message again via bootFileDescriptorProto().
*
* This function only works with a message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto, and only supports features that are
* relevant for the specific use case. For example, it discards file options,
* reserved ranges and reserved names, and field options that are unused in
* descriptor.proto.
*
* @private
*/
function createFileDescriptorProtoBoot(proto) {
var _a;
assert(proto.name == "google/protobuf/descriptor.proto");
assert(proto.package == "google.protobuf");
assert(!proto.dependency.length);
assert(!proto.publicDependency.length);
assert(!proto.weakDependency.length);
assert(!proto.optionDependency.length);
assert(!proto.service.length);
assert(!proto.extension.length);
assert(proto.sourceCodeInfo === undefined);
assert(proto.syntax == "" || proto.syntax == "proto2");
assert(!((_a = proto.options) === null || _a === void 0 ? void 0 : _a.features)); // we're dropping file options
assert(proto.edition === descriptor_pb_js_1.Edition.EDITION_UNKNOWN);
return {
name: proto.name,
package: proto.package,
messageType: proto.messageType.map(createDescriptorBoot),
enumType: proto.enumType.map(createEnumDescriptorBoot),
};
}
function createDescriptorBoot(proto) {
assert(proto.extension.length == 0);
assert(!proto.oneofDecl.length);
assert(!proto.options);
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.DescriptorProtoSchema.field.visibility));
const b = {
name: proto.name,
};
if (proto.field.length) {
b.field = proto.field.map(createFieldDescriptorBoot);
}
if (proto.nestedType.length) {
b.nestedType = proto.nestedType.map(createDescriptorBoot);
}
if (proto.enumType.length) {
b.enumType = proto.enumType.map(createEnumDescriptorBoot);
}
if (proto.extensionRange.length) {
b.extensionRange = proto.extensionRange.map((r) => {
assert(!r.options);
return { start: r.start, end: r.end };
});
}
return b;
}
function createFieldDescriptorBoot(proto) {
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.name));
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.number));
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.type));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.oneofIndex));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.jsonName) ||
proto.jsonName === (0, names_js_1.protoCamelCase)(proto.name));
const b = {
name: proto.name,
number: proto.number,
type: proto.type,
};
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.label)) {
b.label = proto.label;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.typeName)) {
b.typeName = proto.typeName;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.extendee)) {
b.extendee = proto.extendee;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.defaultValue)) {
b.defaultValue = proto.defaultValue;
}
if (proto.options) {
b.options = createFieldOptionsBoot(proto.options);
}
return b;
}
function createFieldOptionsBoot(proto) {
const b = {};
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.ctype));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.packed)) {
b.packed = proto.packed;
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.jstype));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.lazy));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.unverifiedLazy));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.deprecated)) {
b.deprecated = proto.deprecated;
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.weak));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.debugRedact));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.retention)) {
b.retention = proto.retention;
}
if (proto.targets.length) {
b.targets = proto.targets;
}
if (proto.editionDefaults.length) {
b.editionDefaults = proto.editionDefaults.map((d) => ({
value: d.value,
edition: d.edition,
}));
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.features));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.uninterpretedOption));
return b;
}
function createEnumDescriptorBoot(proto) {
assert(!proto.options);
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.EnumDescriptorProtoSchema.field.visibility));
return {
name: proto.name,
value: proto.value.map((v) => {
assert(!v.options);
return {
name: v.name,
number: v.number,
};
}),
};
}
/**
* Assert that condition is truthy or throw error.
*/
function assert(condition) {
if (!condition) {
throw new Error();
}
}
import type { DescEnum, DescFile } from "../descriptors.js";
import type { GenEnum } from "./types.js";
import type { JsonValue } from "../json-value.js";
/**
* Hydrate an enum descriptor.
*
* @private
*/
export declare function enumDesc<Shape extends number, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenEnum<Shape, JsonType>;
/**
* Construct a TypeScript enum object at runtime from a descriptor.
*/
export declare function tsEnum(desc: DescEnum): enumObject;
type enumObject = {
[key: number]: string;
[k: string]: number | string;
};
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.enumDesc = enumDesc;
exports.tsEnum = tsEnum;
/**
* Hydrate an enum descriptor.
*
* @private
*/
function enumDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.enums[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedEnums[e];
}
/**
* Construct a TypeScript enum object at runtime from a descriptor.
*/
function tsEnum(desc) {
const enumObject = {};
for (const value of desc.values) {
enumObject[value.localName] = value.number;
enumObject[value.number] = value.localName;
}
return enumObject;
}
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenExtension } from "./types.js";
/**
* Hydrate an extension descriptor.
*
* @private
*/
export declare function extDesc<Extendee extends Message, Value>(file: DescFile, path: number, ...paths: number[]): GenExtension<Extendee, Value>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.extDesc = extDesc;
/**
* Hydrate an extension descriptor.
*
* @private
*/
function extDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.extensions[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedExtensions[e];
}
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a file descriptor.
*
* @private
*/
export declare function fileDesc(b64: string, imports?: DescFile[]): DescFile;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileDesc = fileDesc;
const base64_encoding_js_1 = require("../wire/base64-encoding.js");
const descriptor_pb_js_1 = require("../wkt/gen/google/protobuf/descriptor_pb.js");
const registry_js_1 = require("../registry.js");
const restore_json_names_js_1 = require("./restore-json-names.js");
const from_binary_js_1 = require("../from-binary.js");
/**
* Hydrate a file descriptor.
*
* @private
*/
function fileDesc(b64, imports) {
var _a;
const root = (0, from_binary_js_1.fromBinary)(descriptor_pb_js_1.FileDescriptorProtoSchema, (0, base64_encoding_js_1.base64Decode)(b64));
root.messageType.forEach(restore_json_names_js_1.restoreJsonNames);
root.dependency = (_a = imports === null || imports === void 0 ? void 0 : imports.map((f) => f.proto.name)) !== null && _a !== void 0 ? _a : [];
const reg = (0, registry_js_1.createFileRegistry)(root, (protoFileName) => imports === null || imports === void 0 ? void 0 : imports.find((f) => f.proto.name === protoFileName));
// biome-ignore lint/style/noNonNullAssertion: non-null assertion because we just created the registry from the file we look up
return reg.getFile(root.name);
}
export * from "./boot.js";
export * from "./embed.js";
export * from "./enum.js";
export * from "./extension.js";
export * from "./file.js";
export * from "./message.js";
export * from "./service.js";
export * from "./symbols.js";
export * from "./scalar.js";
export * from "./types.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./boot.js"), exports);
__exportStar(require("./embed.js"), exports);
__exportStar(require("./enum.js"), exports);
__exportStar(require("./extension.js"), exports);
__exportStar(require("./file.js"), exports);
__exportStar(require("./message.js"), exports);
__exportStar(require("./service.js"), exports);
__exportStar(require("./symbols.js"), exports);
__exportStar(require("./scalar.js"), exports);
__exportStar(require("./types.js"), exports);
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenMessage } from "./types.js";
/**
* Hydrate a message descriptor.
*
* @private
*/
export declare function messageDesc<Shape extends Message, Opt extends {
jsonType?: unknown;
validType?: unknown;
} = {
jsonType: undefined;
validType: undefined;
}>(file: DescFile, path: number, ...paths: number[]): GenMessage<Shape, Opt>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.messageDesc = messageDesc;
/**
* Hydrate a message descriptor.
*
* @private
*/
function messageDesc(file, path, ...paths) {
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]);
}
import type { DescriptorProto } from "../wkt/gen/google/protobuf/descriptor_pb.js";
/**
* @private
*/
export declare function restoreJsonNames(message: DescriptorProto): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.restoreJsonNames = restoreJsonNames;
const names_js_1 = require("../reflect/names.js");
const unsafe_js_1 = require("../reflect/unsafe.js");
/**
* @private
*/
function restoreJsonNames(message) {
for (const f of message.field) {
if (!(0, unsafe_js_1.unsafeIsSetExplicit)(f, "jsonName")) {
f.jsonName = (0, names_js_1.protoCamelCase)(f.name);
}
}
message.nestedType.forEach(restoreJsonNames);
}
import { ScalarType } from "../descriptors.js";
/**
* Return the TypeScript type (as a string) for the given scalar type.
*/
export declare function scalarTypeScriptType(scalar: ScalarType, longAsString: boolean): "string" | "boolean" | "bigint" | "bigint | string" | "Uint8Array" | "number";
/**
* Return the JSON type (as a string) for the given scalar type.
*/
export declare function scalarJsonType(scalar: ScalarType): "string" | "boolean" | "number" | `number | "NaN" | "Infinity" | "-Infinity"`;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.scalarTypeScriptType = scalarTypeScriptType;
exports.scalarJsonType = scalarJsonType;
const descriptors_js_1 = require("../descriptors.js");
/**
* Return the TypeScript type (as a string) for the given scalar type.
*/
function scalarTypeScriptType(scalar, longAsString) {
switch (scalar) {
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.INT64:
return longAsString ? "string" : "bigint";
case descriptors_js_1.ScalarType.BYTES:
return "Uint8Array";
default:
return "number";
}
}
/**
* Return the JSON type (as a string) for the given scalar type.
*/
function scalarJsonType(scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
return `number | "NaN" | "Infinity" | "-Infinity"`;
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.INT64:
return "string";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
return "number";
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.BYTES:
return "string";
}
}
import type { GenService, GenServiceMethods } from "./types.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a service descriptor.
*
* @private
*/
export declare function serviceDesc<T extends GenServiceMethods>(file: DescFile, path: number, ...paths: number[]): GenService<T>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceDesc = serviceDesc;
/**
* Hydrate a service descriptor.
*
* @private
*/
function serviceDesc(file, path, ...paths) {
if (paths.length > 0) {
throw new Error();
}
return file.services[path];
}
/**
* @private
*/
export declare const packageName = "@bufbuild/protobuf";
/**
* @private
*/
export declare const wktPublicImportPaths: Readonly<Record<string, string>>;
/**
* @private
*/
export declare const symbols: {
readonly isMessage: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../is-message.js";
readonly from: "@bufbuild/protobuf";
};
readonly Message: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../types.js";
readonly from: "@bufbuild/protobuf";
};
readonly create: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../create.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../from-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly protoInt64: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../proto-int64.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonValue: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonObject: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly codegen: {
readonly boot: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/boot.js";
readonly from: string;
};
readonly fileDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/file.js";
readonly from: string;
};
readonly enumDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/enum.js";
readonly from: string;
};
readonly extDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/extension.js";
readonly from: string;
};
readonly messageDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/message.js";
readonly from: string;
};
readonly serviceDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/service.js";
readonly from: string;
};
readonly tsEnum: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv2/enum.js";
readonly from: string;
};
readonly GenFile: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
readonly GenEnum: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
readonly GenExtension: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
readonly GenMessage: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
readonly GenService: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv2/types.js";
readonly from: string;
};
};
};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.symbols = exports.wktPublicImportPaths = exports.packageName = void 0;
/**
* @private
*/
exports.packageName = "@bufbuild/protobuf";
/**
* @private
*/
exports.wktPublicImportPaths = {
"google/protobuf/compiler/plugin.proto": exports.packageName + "/wkt",
"google/protobuf/any.proto": exports.packageName + "/wkt",
"google/protobuf/api.proto": exports.packageName + "/wkt",
"google/protobuf/cpp_features.proto": exports.packageName + "/wkt",
"google/protobuf/descriptor.proto": exports.packageName + "/wkt",
"google/protobuf/duration.proto": exports.packageName + "/wkt",
"google/protobuf/empty.proto": exports.packageName + "/wkt",
"google/protobuf/field_mask.proto": exports.packageName + "/wkt",
"google/protobuf/go_features.proto": exports.packageName + "/wkt",
"google/protobuf/java_features.proto": exports.packageName + "/wkt",
"google/protobuf/source_context.proto": exports.packageName + "/wkt",
"google/protobuf/struct.proto": exports.packageName + "/wkt",
"google/protobuf/timestamp.proto": exports.packageName + "/wkt",
"google/protobuf/type.proto": exports.packageName + "/wkt",
"google/protobuf/wrappers.proto": exports.packageName + "/wkt",
};
/**
* @private
*/
// biome-ignore format: want this to read well
exports.symbols = {
isMessage: { typeOnly: false, bootstrapWktFrom: "../../is-message.js", from: exports.packageName },
Message: { typeOnly: true, bootstrapWktFrom: "../../types.js", from: exports.packageName },
create: { typeOnly: false, bootstrapWktFrom: "../../create.js", from: exports.packageName },
fromJson: { typeOnly: false, bootstrapWktFrom: "../../from-json.js", from: exports.packageName },
fromJsonString: { typeOnly: false, bootstrapWktFrom: "../../from-json.js", from: exports.packageName },
fromBinary: { typeOnly: false, bootstrapWktFrom: "../../from-binary.js", from: exports.packageName },
toBinary: { typeOnly: false, bootstrapWktFrom: "../../to-binary.js", from: exports.packageName },
toJson: { typeOnly: false, bootstrapWktFrom: "../../to-json.js", from: exports.packageName },
toJsonString: { typeOnly: false, bootstrapWktFrom: "../../to-json.js", from: exports.packageName },
protoInt64: { typeOnly: false, bootstrapWktFrom: "../../proto-int64.js", from: exports.packageName },
JsonValue: { typeOnly: true, bootstrapWktFrom: "../../json-value.js", from: exports.packageName },
JsonObject: { typeOnly: true, bootstrapWktFrom: "../../json-value.js", from: exports.packageName },
codegen: {
boot: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/boot.js", from: exports.packageName + "/codegenv2" },
fileDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/file.js", from: exports.packageName + "/codegenv2" },
enumDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/enum.js", from: exports.packageName + "/codegenv2" },
extDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/extension.js", from: exports.packageName + "/codegenv2" },
messageDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/message.js", from: exports.packageName + "/codegenv2" },
serviceDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/service.js", from: exports.packageName + "/codegenv2" },
tsEnum: { typeOnly: false, bootstrapWktFrom: "../../codegenv2/enum.js", from: exports.packageName + "/codegenv2" },
GenFile: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenEnum: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenExtension: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenMessage: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenService: { typeOnly: true, bootstrapWktFrom: "../../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
},
};
import type { Message } from "../types.js";
import type { DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescService } from "../descriptors.js";
import type { JsonValue } from "../json-value.js";
/**
* Describes a protobuf source file.
*
* @private
*/
export type GenFile = DescFile;
/**
* Describes a message declaration in a protobuf source file.
*
* This type is identical to DescMessage, but carries additional type
* information.
*
* @private
*/
export type GenMessage<RuntimeShape extends Message, Opt extends {
jsonType?: unknown;
validType?: unknown;
} = {
jsonType?: unknown;
validType?: unknown;
}> = Omit<DescMessage, "field" | "typeName"> & {
field: Record<MessageFieldNames<RuntimeShape>, DescField>;
typeName: RuntimeShape["$typeName"];
} & brandv2<RuntimeShape, Opt>;
/**
* Describes an enumeration in a protobuf source file.
*
* This type is identical to DescEnum, but carries additional type
* information.
*
* @private
*/
export type GenEnum<RuntimeShape extends number, JsonType extends JsonValue = JsonValue> = Omit<DescEnum, "value"> & {
value: Record<RuntimeShape, DescEnumValue>;
} & brandv2<RuntimeShape, JsonType>;
/**
* Describes an extension in a protobuf source file.
*
* This type is identical to DescExtension, but carries additional type
* information.
*
* @private
*/
export type GenExtension<Extendee extends Message = Message, RuntimeShape = unknown> = DescExtension & brandv2<Extendee, RuntimeShape>;
/**
* Describes a service declaration in a protobuf source file.
*
* This type is identical to DescService, but carries additional type
* information.
*
* @private
*/
export type GenService<RuntimeShape extends GenServiceMethods> = Omit<DescService, "method"> & {
method: {
[K in keyof RuntimeShape]: RuntimeShape[K] & DescMethod;
};
};
/**
* @private
*/
export type GenServiceMethods = Record<string, Pick<DescMethod, "input" | "output" | "methodKind">>;
declare class brandv2<A, B = unknown> {
protected v: "codegenv2";
protected a: A | boolean;
protected b: B | boolean;
}
/**
* Union of the property names of all fields, including oneof members.
* For an anonymous message (no generated message shape), it's simply a string.
*/
type MessageFieldNames<T extends Message> = Message extends T ? string : Exclude<keyof {
[P in keyof T as P extends ("$typeName" | "$unknown") ? never : T[P] extends Oneof<infer K> ? K : P]-?: true;
}, number | symbol>;
type Oneof<K extends string> = {
case: K | undefined;
value?: unknown;
};
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
class brandv2 {
constructor() {
this.v = "codegenv2";
this.a = false;
this.b = false;
}
}
import { type DescMessage } from "./descriptors.js";
import type { MessageInitShape, MessageShape } from "./types.js";
/**
* Create a new message instance.
*
* The second argument is an optional initializer object, where all fields are
* optional.
*/
export declare function create<Desc extends DescMessage>(schema: Desc, init?: MessageInitShape<Desc>): MessageShape<Desc>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = create;
const is_message_js_1 = require("./is-message.js");
const descriptors_js_1 = require("./descriptors.js");
const scalar_js_1 = require("./reflect/scalar.js");
const guard_js_1 = require("./reflect/guard.js");
const unsafe_js_1 = require("./reflect/unsafe.js");
const wrappers_js_1 = require("./wkt/wrappers.js");
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name: Edition.$localName = $number;
const EDITION_PROTO3 = 999;
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name: Edition.$localName = $number;
const EDITION_PROTO2 = 998;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
/**
* Create a new message instance.
*
* The second argument is an optional initializer object, where all fields are
* optional.
*/
function create(schema, init) {
if ((0, is_message_js_1.isMessage)(init, schema)) {
return init;
}
const message = createZeroMessage(schema);
if (init !== undefined) {
initMessage(schema, message, init);
}
return message;
}
/**
* Sets field values from a MessageInitShape on a zero message.
*/
function initMessage(messageDesc, message, init) {
for (const member of messageDesc.members) {
let value = init[member.localName];
if (value == null) {
// intentionally ignore undefined and null
continue;
}
let field;
if (member.kind == "oneof") {
const oneofField = (0, unsafe_js_1.unsafeOneofCase)(init, member);
if (!oneofField) {
continue;
}
field = oneofField;
value = (0, unsafe_js_1.unsafeGet)(init, oneofField);
}
else {
field = member;
}
switch (field.fieldKind) {
case "message":
value = toMessage(field, value);
break;
case "scalar":
value = initScalar(field, value);
break;
case "list":
value = initList(field, value);
break;
case "map":
value = initMap(field, value);
break;
}
(0, unsafe_js_1.unsafeSet)(message, field, value);
}
return message;
}
function initScalar(field, value) {
if (field.scalar == descriptors_js_1.ScalarType.BYTES) {
return toU8Arr(value);
}
return value;
}
function initMap(field, value) {
if ((0, guard_js_1.isObject)(value)) {
if (field.scalar == descriptors_js_1.ScalarType.BYTES) {
return convertObjectValues(value, toU8Arr);
}
if (field.mapKind == "message") {
return convertObjectValues(value, (val) => toMessage(field, val));
}
}
return value;
}
function initList(field, value) {
if (Array.isArray(value)) {
if (field.scalar == descriptors_js_1.ScalarType.BYTES) {
return value.map(toU8Arr);
}
if (field.listKind == "message") {
return value.map((item) => toMessage(field, item));
}
}
return value;
}
function toMessage(field, value) {
if (field.fieldKind == "message" &&
!field.oneof &&
(0, wrappers_js_1.isWrapperDesc)(field.message)) {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
return initScalar(field.message.fields[0], value);
}
if ((0, guard_js_1.isObject)(value)) {
if (field.message.typeName == "google.protobuf.Struct" &&
field.parent.typeName !== "google.protobuf.Value") {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
return value;
}
if (!(0, is_message_js_1.isMessage)(value, field.message)) {
return create(field.message, value);
}
}
return value;
}
// converts any ArrayLike<number> to Uint8Array if necessary.
function toU8Arr(value) {
return Array.isArray(value) ? new Uint8Array(value) : value;
}
function convertObjectValues(obj, fn) {
const ret = {};
for (const entry of Object.entries(obj)) {
ret[entry[0]] = fn(entry[1]);
}
return ret;
}
const tokenZeroMessageField = Symbol();
const messagePrototypes = new WeakMap();
/**
* Create a zero message.
*/
function createZeroMessage(desc) {
let msg;
if (!needsPrototypeChain(desc)) {
msg = {
$typeName: desc.typeName,
};
for (const member of desc.members) {
if (member.kind == "oneof" || member.presence == IMPLICIT) {
msg[member.localName] = createZeroField(member);
}
}
}
else {
// Support default values and track presence via the prototype chain
const cached = messagePrototypes.get(desc);
let prototype;
let members;
if (cached) {
({ prototype, members } = cached);
}
else {
prototype = {};
members = new Set();
for (const member of desc.members) {
if (member.kind == "oneof") {
// we can only put immutable values on the prototype,
// oneof ADTs are mutable
continue;
}
if (member.fieldKind != "scalar" && member.fieldKind != "enum") {
// only scalar and enum values are immutable, map, list, and message
// are not
continue;
}
if (member.presence == IMPLICIT) {
// implicit presence tracks field presence by zero values - e.g. 0, false, "", are unset, 1, true, "x" are set.
// message, map, list fields are mutable, and also have IMPLICIT presence.
continue;
}
members.add(member);
prototype[member.localName] = createZeroField(member);
}
messagePrototypes.set(desc, { prototype, members });
}
msg = Object.create(prototype);
msg.$typeName = desc.typeName;
for (const member of desc.members) {
if (members.has(member)) {
continue;
}
if (member.kind == "field") {
if (member.fieldKind == "message") {
continue;
}
if (member.fieldKind == "scalar" || member.fieldKind == "enum") {
if (member.presence != IMPLICIT) {
continue;
}
}
}
msg[member.localName] = createZeroField(member);
}
}
return msg;
}
/**
* Do we need the prototype chain to track field presence?
*/
function needsPrototypeChain(desc) {
switch (desc.file.edition) {
case EDITION_PROTO3:
// proto3 always uses implicit presence, we never need the prototype chain.
return false;
case EDITION_PROTO2:
// proto2 never uses implicit presence, we always need the prototype chain.
return true;
default:
// If a message uses scalar or enum fields with explicit presence, we need
// the prototype chain to track presence. This rule does not apply to fields
// in a oneof group - they use a different mechanism to track presence.
return desc.fields.some((f) => f.presence != IMPLICIT && f.fieldKind != "message" && !f.oneof);
}
}
/**
* Returns a zero value for oneof groups, and for every field kind except
* messages. Scalar and enum fields can have default values.
*/
function createZeroField(field) {
if (field.kind == "oneof") {
return { case: undefined };
}
if (field.fieldKind == "list") {
return [];
}
if (field.fieldKind == "map") {
return {}; // Object.create(null) would be desirable here, but is unsupported by react https://react.dev/reference/react/use-server#serializable-parameters-and-return-values
}
if (field.fieldKind == "message") {
return tokenZeroMessageField;
}
const defaultValue = field.getDefaultValue();
if (defaultValue !== undefined) {
return field.fieldKind == "scalar" && field.longAsString
? defaultValue.toString()
: defaultValue;
}
return field.fieldKind == "scalar"
? (0, scalar_js_1.scalarZeroValue)(field.scalar, field.longAsString)
: field.enum.values[0].number;
}
import type { DescriptorProto, Edition, EnumDescriptorProto, EnumValueDescriptorProto, FeatureSet_FieldPresence, FieldDescriptorProto, FileDescriptorProto, MethodDescriptorProto, MethodOptions_IdempotencyLevel, OneofDescriptorProto, ServiceDescriptorProto } from "./wkt/gen/google/protobuf/descriptor_pb.js";
import type { ScalarValue } from "./reflect/scalar.js";
export type SupportedEdition = Extract<Edition, Edition.EDITION_PROTO2 | Edition.EDITION_PROTO3 | Edition.EDITION_2023 | Edition.EDITION_2024>;
type SupportedFieldPresence = Extract<FeatureSet_FieldPresence, FeatureSet_FieldPresence.EXPLICIT | FeatureSet_FieldPresence.IMPLICIT | FeatureSet_FieldPresence.LEGACY_REQUIRED>;
/**
* Scalar value types. This is a subset of field types declared by protobuf
* enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
* are omitted, but the numerical values are identical.
*/
export declare enum ScalarType {
DOUBLE = 1,
FLOAT = 2,
INT64 = 3,
UINT64 = 4,
INT32 = 5,
FIXED64 = 6,
FIXED32 = 7,
BOOL = 8,
STRING = 9,
BYTES = 12,
UINT32 = 13,
SFIXED32 = 15,
SFIXED64 = 16,
SINT32 = 17,// Uses ZigZag encoding.
SINT64 = 18
}
/**
* A union of all descriptors, discriminated by a `kind` property.
*/
export type AnyDesc = DescFile | DescEnum | DescEnumValue | DescMessage | DescField | DescExtension | DescOneof | DescService | DescMethod;
/**
* Describes a protobuf source file.
*/
export interface DescFile {
readonly kind: "file";
/**
* The edition of the protobuf file. Will be EDITION_PROTO2 for syntax="proto2",
* EDITION_PROTO3 for syntax="proto3";
*/
readonly edition: SupportedEdition;
/**
* The name of the file, excluding the .proto suffix.
* For a protobuf file `foo/bar.proto`, this is `foo/bar`.
*/
readonly name: string;
/**
* Files imported by this file.
*/
readonly dependencies: DescFile[];
/**
* Top-level enumerations declared in this file.
* Note that more enumerations might be declared within message declarations.
*/
readonly enums: DescEnum[];
/**
* Top-level messages declared in this file.
* Note that more messages might be declared within message declarations.
*/
readonly messages: DescMessage[];
/**
* Top-level extensions declared in this file.
* Note that more extensions might be declared within message declarations.
*/
readonly extensions: DescExtension[];
/**
* Services declared in this file.
*/
readonly services: DescService[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: FileDescriptorProto;
toString(): string;
}
/**
* Describes an enumeration in a protobuf source file.
*/
export interface DescEnum {
readonly kind: "enum";
/**
* The fully qualified name of the enumeration. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the enumeration, as declared in the protobuf source.
*/
readonly name: string;
/**
* The file this enumeration was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this enumeration was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* Enumerations can be open or closed.
* See https://protobuf.dev/programming-guides/enum/
*/
readonly open: boolean;
/**
* Values declared for this enumeration.
*/
readonly values: DescEnumValue[];
/**
* All values of this enum by their number.
*/
readonly value: Record<number, DescEnumValue>;
/**
* A prefix shared by all enum values.
* For example, `my_enum_` for `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`
*/
readonly sharedPrefix?: string | undefined;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: EnumDescriptorProto;
toString(): string;
}
/**
* Describes an individual value of an enumeration in a protobuf source file.
*/
export interface DescEnumValue {
readonly kind: "enum_value";
/**
* The name of the enumeration value, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the value in a TypeScript enum.
*/
readonly localName: string;
/**
* The enumeration this value belongs to.
*/
readonly parent: DescEnum;
/**
* The numeric enumeration value, as specified in the protobuf source.
*/
readonly number: number;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: EnumValueDescriptorProto;
toString(): string;
}
/**
* Describes a message declaration in a protobuf source file.
*/
export interface DescMessage {
readonly kind: "message";
/**
* The fully qualified name of the message. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the message, as specified in the protobuf source.
*/
readonly name: string;
/**
* The file this message was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this message was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* Fields declared for this message, including fields declared in a oneof
* group.
*/
readonly fields: DescField[];
/**
* All fields of this message by their "localName".
*/
readonly field: Record<string, DescField>;
/**
* Oneof groups declared for this message.
* This does not include synthetic oneofs for proto3 optionals.
*/
readonly oneofs: DescOneof[];
/**
* Standalone fields and oneof groups for this message, ordered by
* their appearance in the protobuf source.
*/
readonly members: (DescField | DescOneof)[];
/**
* Enumerations declared within the message, if any.
*/
readonly nestedEnums: DescEnum[];
/**
* Messages declared within the message, if any.
* This does not include synthetic messages like map entries.
*/
readonly nestedMessages: DescMessage[];
/**
* Extensions declared within the message, if any.
*/
readonly nestedExtensions: DescExtension[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: DescriptorProto;
toString(): string;
}
/**
* Describes a field declaration in a protobuf source file.
*/
export type DescField = (descFieldScalar & descFieldCommon) | (descFieldList & descFieldCommon) | (descFieldMessage & descFieldCommon) | (descFieldEnum & descFieldCommon) | (descFieldMap & descFieldCommon);
type descFieldCommon = descFieldAndExtensionShared & {
readonly kind: "field";
/**
* The message this field is declared on.
*/
readonly parent: DescMessage;
/**
* A safe and idiomatic name for the field as a property in ECMAScript.
*/
readonly localName: string;
};
/**
* Describes an extension in a protobuf source file.
*/
export type DescExtension = (Omit<descFieldScalar, "oneof"> & descExtensionCommon) | (Omit<descFieldEnum, "oneof"> & descExtensionCommon) | (Omit<descFieldMessage, "oneof"> & descExtensionCommon) | (descFieldList & descExtensionCommon);
type descExtensionCommon = descFieldAndExtensionShared & {
readonly kind: "extension";
/**
* The fully qualified name of the extension.
*/
readonly typeName: string;
/**
* The file this extension was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this extension was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* The message that this extension extends.
*/
readonly extendee: DescMessage;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
};
interface descFieldAndExtensionShared {
/**
* The field name, as specified in the protobuf source
*/
readonly name: string;
/**
* The field number, as specified in the protobuf source.
*/
readonly number: number;
/**
* The field name in JSON.
*/
readonly jsonName: string;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* Presence of the field.
* See https://protobuf.dev/programming-guides/field_presence/
*/
readonly presence: SupportedFieldPresence;
/**
* Whether to reject invalid UTF-8 when reading this field from the binary
* wire format. Reflects the resolved `utf8_validation` feature: true for
* VERIFY (proto3 and editions 2023+ default), false for NONE (proto2
* default).
*/
readonly utf8Validation: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: FieldDescriptorProto;
/**
* Get the edition features for this protobuf element.
*/
toString(): string;
}
type descFieldSingularCommon = {
/**
* The `oneof` group this field belongs to, if any.
*
* This does not include synthetic oneofs for proto3 optionals.
*/
readonly oneof: DescOneof | undefined;
};
type descFieldScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly fieldKind: "scalar";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: T;
/**
* By default, 64-bit integral types (int64, uint64, sint64, fixed64,
* sfixed64) are represented with BigInt.
*
* If the field option `jstype = JS_STRING` is set, this property
* is true, and 64-bit integral types are represented with String.
*/
readonly longAsString: boolean;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): ScalarValue<T> | undefined;
} & descFieldSingularCommon : never;
type descFieldMessage = {
readonly fieldKind: "message";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: DescMessage;
/**
* Encode the message delimited (a.k.a. proto2 group encoding), or
* length-prefixed?
*/
readonly delimitedEncoding: boolean;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): undefined;
} & descFieldSingularCommon;
type descFieldEnum = {
readonly fieldKind: "enum";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: DescEnum;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): number | undefined;
} & descFieldSingularCommon;
type descFieldList = (descFieldListScalar & descFieldListCommon) | (descFieldListEnum & descFieldListCommon) | (descFieldListMessage & descFieldListCommon);
type descFieldListCommon = {
readonly fieldKind: "list";
/**
* Pack this repeated field? Only valid for repeated enum fields, and
* for repeated scalar fields except BYTES and STRING.
*/
readonly packed: boolean;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
};
type descFieldListScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly listKind: "scalar";
/**
* The enum list element type.
*/
readonly enum: undefined;
/**
* The message list element type.
*/
readonly message: undefined;
/**
* Scalar list element type.
*/
readonly scalar: T;
/**
* By default, 64-bit integral types (int64, uint64, sint64, fixed64,
* sfixed64) are represented with BigInt.
*
* If the field option `jstype = JS_STRING` is set, this property
* is true, and 64-bit integral types are represented with String.
*/
readonly longAsString: boolean;
} : never;
type descFieldListEnum = {
readonly listKind: "enum";
/**
* The enum list element type.
*/
readonly enum: DescEnum;
/**
* The message list element type.
*/
readonly message: undefined;
/**
* Scalar list element type.
*/
readonly scalar: undefined;
};
type descFieldListMessage = {
readonly listKind: "message";
/**
* The enum list element type.
*/
readonly enum: undefined;
/**
* The message list element type.
*/
readonly message: DescMessage;
/**
* Scalar list element type.
*/
readonly scalar: undefined;
/**
* Encode the message delimited (a.k.a. proto2 group encoding), or
* length-prefixed?
*/
readonly delimitedEncoding: boolean;
};
type descFieldMap = (descFieldMapScalar & descFieldMapCommon) | (descFieldMapEnum & descFieldMapCommon) | (descFieldMapMessage & descFieldMapCommon);
type descFieldMapCommon<T extends ScalarType = ScalarType> = T extends Exclude<ScalarType, ScalarType.FLOAT | ScalarType.DOUBLE | ScalarType.BYTES> ? {
readonly fieldKind: "map";
/**
* The scalar map key type.
*/
readonly mapKey: T;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
/**
* Encode the map entry message delimited (a.k.a. proto2 group encoding),
* or length-prefixed? As of Edition 2023, this is always false for map fields,
* and also applies to map values, if they are messages.
*/
readonly delimitedEncoding: false;
} : never;
type descFieldMapScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly mapKind: "scalar";
/**
* The enum map value type.
*/
readonly enum: undefined;
/**
* The message map value type.
*/
readonly message: undefined;
/**
* Scalar map value type.
*/
readonly scalar: T;
} : never;
type descFieldMapEnum = {
readonly mapKind: "enum";
/**
* The enum map value type.
*/
readonly enum: DescEnum;
/**
* The message map value type.
*/
readonly message: undefined;
/**
* Scalar map value type.
*/
readonly scalar: undefined;
};
type descFieldMapMessage = {
readonly mapKind: "message";
/**
* The enum map value type.
*/
readonly enum: undefined;
/**
* The message map value type.
*/
readonly message: DescMessage;
/**
* Scalar map value type.
*/
readonly scalar: undefined;
};
/**
* Describes a oneof group in a protobuf source file.
*/
export interface DescOneof {
readonly kind: "oneof";
/**
* The name of the oneof group, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the oneof group as a property in ECMAScript.
*/
readonly localName: string;
/**
* The message this oneof group was declared in.
*/
readonly parent: DescMessage;
/**
* The fields declared in this oneof group.
*/
readonly fields: DescField[];
/**
* Marked as deprecated in the protobuf source.
* Note that oneof groups cannot be marked as deprecated, this property
* only exists for consistency and will always be false.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: OneofDescriptorProto;
toString(): string;
}
/**
* Describes a service declaration in a protobuf source file.
*/
export interface DescService {
readonly kind: "service";
/**
* The fully qualified name of the service. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the service, as specified in the protobuf source.
*/
readonly name: string;
/**
* The file this service was declared in.
*/
readonly file: DescFile;
/**
* The RPCs this service declares.
*/
readonly methods: DescMethod[];
/**
* All methods of this service by their "localName".
*/
readonly method: Record<string, DescMethod>;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: ServiceDescriptorProto;
toString(): string;
}
/**
* Describes an RPC declaration in a protobuf source file.
*/
export interface DescMethod {
readonly kind: "rpc";
/**
* The name of the RPC, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the RPC as a method in ECMAScript.
*/
readonly localName: string;
/**
* The parent service.
*/
readonly parent: DescService;
/**
* One of the four available method types.
*/
readonly methodKind: "unary" | "server_streaming" | "client_streaming" | "bidi_streaming";
/**
* The message type for requests.
*/
readonly input: DescMessage;
/**
* The message type for responses.
*/
readonly output: DescMessage;
/**
* The idempotency level declared in the protobuf source, if any.
*/
readonly idempotency: MethodOptions_IdempotencyLevel;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: MethodDescriptorProto;
toString(): string;
}
/**
* Comments on an element in a protobuf source file.
*/
export interface DescComments {
readonly leadingDetached: readonly string[];
readonly leading?: string | undefined;
readonly trailing?: string | undefined;
readonly sourcePath: readonly number[];
}
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScalarType = void 0;
/**
* Scalar value types. This is a subset of field types declared by protobuf
* enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
* are omitted, but the numerical values are identical.
*/
var ScalarType;
(function (ScalarType) {
// 0 is reserved for errors.
// Order is weird for historical reasons.
ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE";
ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT";
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
// negative values are likely.
ScalarType[ScalarType["INT64"] = 3] = "INT64";
ScalarType[ScalarType["UINT64"] = 4] = "UINT64";
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
// negative values are likely.
ScalarType[ScalarType["INT32"] = 5] = "INT32";
ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64";
ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32";
ScalarType[ScalarType["BOOL"] = 8] = "BOOL";
ScalarType[ScalarType["STRING"] = 9] = "STRING";
// Tag-delimited aggregate.
// Group type is deprecated and not supported in proto3. However, Proto3
// implementations should still be able to parse the group wire format and
// treat group fields as unknown fields.
// TYPE_GROUP = 10,
// TYPE_MESSAGE = 11, // Length-delimited aggregate.
// New in version 2.
ScalarType[ScalarType["BYTES"] = 12] = "BYTES";
ScalarType[ScalarType["UINT32"] = 13] = "UINT32";
// TYPE_ENUM = 14,
ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32";
ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64";
ScalarType[ScalarType["SINT32"] = 17] = "SINT32";
ScalarType[ScalarType["SINT64"] = 18] = "SINT64";
})(ScalarType || (exports.ScalarType = ScalarType = {}));
import type { MessageShape } from "./types.js";
import { type DescMessage } from "./descriptors.js";
import type { Registry } from "./registry.js";
interface EqualsOptions {
/**
* A registry to look up extensions, and messages packed in Any.
*
* @private Experimental API, does not follow semantic versioning.
*/
registry: Registry;
/**
* Unpack google.protobuf.Any before comparing.
* If a type is not in the registry, comparison falls back to comparing the
* fields of Any.
*
* @private Experimental API, does not follow semantic versioning.
*/
unpackAny?: boolean;
/**
* Consider extensions when comparing.
*
* @private Experimental API, does not follow semantic versioning.
*/
extensions?: boolean;
/**
* Consider unknown fields when comparing.
* The registry is used to distinguish between extensions, and unknown fields
* caused by schema changes.
*
* @private Experimental API, does not follow semantic versioning.
*/
unknown?: boolean;
}
/**
* Compare two messages of the same type.
*
* Note that this function disregards extensions and unknown fields, and that
* NaN is not equal NaN, following the IEEE standard.
*/
export declare function equals<Desc extends DescMessage>(schema: Desc, a: MessageShape<Desc>, b: MessageShape<Desc>, options?: EqualsOptions): boolean;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.equals = equals;
const scalar_js_1 = require("./reflect/scalar.js");
const reflect_js_1 = require("./reflect/reflect.js");
const descriptors_js_1 = require("./descriptors.js");
const index_js_1 = require("./wkt/index.js");
const extensions_js_1 = require("./extensions.js");
/**
* Compare two messages of the same type.
*
* Note that this function disregards extensions and unknown fields, and that
* NaN is not equal NaN, following the IEEE standard.
*/
function equals(schema, a, b, options) {
if (a.$typeName != schema.typeName || b.$typeName != schema.typeName) {
return false;
}
if (a === b) {
return true;
}
return reflectEquals((0, reflect_js_1.reflect)(schema, a), (0, reflect_js_1.reflect)(schema, b), options);
}
function reflectEquals(a, b, opts) {
if (a.desc.typeName === "google.protobuf.Any" && (opts === null || opts === void 0 ? void 0 : opts.unpackAny) == true) {
return anyUnpackedEquals(a.message, b.message, opts);
}
for (const f of a.fields) {
if (!fieldEquals(f, a, b, opts)) {
return false;
}
}
if ((opts === null || opts === void 0 ? void 0 : opts.unknown) == true && !unknownEquals(a, b, opts.registry)) {
return false;
}
if ((opts === null || opts === void 0 ? void 0 : opts.extensions) == true && !extensionsEquals(a, b, opts)) {
return false;
}
return true;
}
// TODO(tstamm) add an option to consider NaN equal to NaN?
function fieldEquals(f, a, b, opts) {
if (!a.isSet(f) && !b.isSet(f)) {
return true;
}
if (!a.isSet(f) || !b.isSet(f)) {
return false;
}
switch (f.fieldKind) {
case "scalar":
return (0, scalar_js_1.scalarEquals)(f.scalar, a.get(f), b.get(f));
case "enum":
return a.get(f) === b.get(f);
case "message":
return reflectEquals(a.get(f), b.get(f), opts);
case "map": {
// TODO(tstamm) can't we compare sizes first?
const mapA = a.get(f);
const mapB = b.get(f);
const keys = [];
for (const k of mapA.keys()) {
if (!mapB.has(k)) {
return false;
}
keys.push(k);
}
for (const k of mapB.keys()) {
if (!mapA.has(k)) {
return false;
}
}
for (const key of keys) {
const va = mapA.get(key);
const vb = mapB.get(key);
if (va === vb) {
continue;
}
switch (f.mapKind) {
case "enum":
return false;
case "message":
if (!reflectEquals(va, vb, opts)) {
return false;
}
break;
case "scalar":
if (!(0, scalar_js_1.scalarEquals)(f.scalar, va, vb)) {
return false;
}
break;
}
}
break;
}
case "list": {
const listA = a.get(f);
const listB = b.get(f);
if (listA.size != listB.size) {
return false;
}
for (let i = 0; i < listA.size; i++) {
const va = listA.get(i);
const vb = listB.get(i);
if (va === vb) {
continue;
}
switch (f.listKind) {
case "enum":
return false;
case "message":
if (!reflectEquals(va, vb, opts)) {
return false;
}
break;
case "scalar":
if (!(0, scalar_js_1.scalarEquals)(f.scalar, va, vb)) {
return false;
}
break;
}
}
break;
}
}
return true;
}
function anyUnpackedEquals(a, b, opts) {
if (a.typeUrl !== b.typeUrl) {
return false;
}
const unpackedA = (0, index_js_1.anyUnpack)(a, opts.registry);
const unpackedB = (0, index_js_1.anyUnpack)(b, opts.registry);
if (unpackedA && unpackedB) {
const schema = opts.registry.getMessage(unpackedA.$typeName);
if (schema) {
return equals(schema, unpackedA, unpackedB, opts);
}
}
return (0, scalar_js_1.scalarEquals)(descriptors_js_1.ScalarType.BYTES, a.value, b.value);
}
function unknownEquals(a, b, registry) {
function getTrulyUnknown(msg, registry) {
var _a;
const u = (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : [];
return registry
? u.filter((uf) => !registry.getExtensionFor(msg.desc, uf.no))
: u;
}
const unknownA = getTrulyUnknown(a, registry);
const unknownB = getTrulyUnknown(b, registry);
if (unknownA.length != unknownB.length) {
return false;
}
for (let i = 0; i < unknownA.length; i++) {
const a = unknownA[i];
const b = unknownB[i];
if (a.no != b.no) {
return false;
}
if (a.wireType != b.wireType) {
return false;
}
if (!(0, scalar_js_1.scalarEquals)(descriptors_js_1.ScalarType.BYTES, a.data, b.data)) {
return false;
}
}
return true;
}
function extensionsEquals(a, b, opts) {
function getSetExtensions(msg, registry) {
var _a;
return ((_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : [])
.map((uf) => registry.getExtensionFor(msg.desc, uf.no))
.filter((e) => e != undefined)
.filter((e, index, arr) => arr.indexOf(e) === index);
}
const extensionsA = getSetExtensions(a, opts.registry);
const extensionsB = getSetExtensions(b, opts.registry);
if (extensionsA.length != extensionsB.length ||
extensionsA.some((e) => !extensionsB.includes(e))) {
return false;
}
for (const extension of extensionsA) {
const [containerA, field] = (0, extensions_js_1.createExtensionContainer)(extension, (0, extensions_js_1.getExtension)(a.message, extension));
const [containerB] = (0, extensions_js_1.createExtensionContainer)(extension, (0, extensions_js_1.getExtension)(b.message, extension));
if (!fieldEquals(field, containerA, containerB, opts)) {
return false;
}
}
return true;
}
import type { AnyDesc, DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescOneof, DescService } from "./descriptors.js";
import type { ReflectMessage } from "./reflect/reflect-types.js";
import type { Extendee, ExtensionValueShape } from "./types.js";
import type { EnumOptions, EnumValueOptions, FieldOptions, FileOptions, MessageOptions, MethodOptions, OneofOptions, ServiceOptions } from "./wkt/gen/google/protobuf/descriptor_pb.js";
/**
* Retrieve an extension value from a message.
*
* The function never returns undefined. Use hasExtension() to check whether an
* extension is set. If the extension is not set, this function returns the
* default value (if one was specified in the protobuf source), or the zero value
* (for example `0` for numeric types, `[]` for repeated extension fields, and
* an empty message instance for message fields).
*
* Extensions are stored as unknown fields on a message. To mutate an extension
* value, make sure to store the new value with setExtension() after mutating.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function getExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc): ExtensionValueShape<Desc>;
/**
* Set an extension value on a message. If the message already has a value for
* this extension, the value is replaced.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function setExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc, value: ExtensionValueShape<Desc>): void;
/**
* Remove an extension value from a message.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function clearExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc): void;
/**
* Check whether an extension is set on a message.
*/
export declare function hasExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc): boolean;
/**
* Check whether an option is set on a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls hasExtension().
*/
export declare function hasOption<Ext extends DescExtension, Desc extends DescForOptionExtension<Ext>>(element: Desc, option: Ext): boolean;
/**
* Retrieve an option value from a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls getExtension(). Same as getExtension(), this
* function never returns undefined.
*/
export declare function getOption<Ext extends DescExtension, Desc extends DescForOptionExtension<Ext>>(element: Desc, option: Ext): ExtensionValueShape<Ext>;
type DescForOptionExtension<Ext extends DescExtension> = Extendee<Ext> extends FileOptions ? DescFile : Extendee<Ext> extends EnumOptions ? DescEnum : Extendee<Ext> extends EnumValueOptions ? DescEnumValue : Extendee<Ext> extends MessageOptions ? DescMessage : Extendee<Ext> extends MessageOptions ? DescEnum : Extendee<Ext> extends FieldOptions ? DescField | DescExtension : Extendee<Ext> extends OneofOptions ? DescOneof : Extendee<Ext> extends ServiceOptions ? DescService : Extendee<Ext> extends EnumOptions ? DescEnum : Extendee<Ext> extends MethodOptions ? DescMethod : AnyDesc;
/**
* @private
*/
export declare function createExtensionContainer<Desc extends DescExtension>(extension: Desc, value?: ExtensionValueShape<Desc>): [ReflectMessage, DescField, () => ExtensionValueShape<Desc>];
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.getExtension = getExtension;
exports.setExtension = setExtension;
exports.clearExtension = clearExtension;
exports.hasExtension = hasExtension;
exports.hasOption = hasOption;
exports.getOption = getOption;
exports.createExtensionContainer = createExtensionContainer;
const create_js_1 = require("./create.js");
const from_binary_js_1 = require("./from-binary.js");
const reflect_js_1 = require("./reflect/reflect.js");
const scalar_js_1 = require("./reflect/scalar.js");
const to_binary_js_1 = require("./to-binary.js");
const binary_encoding_js_1 = require("./wire/binary-encoding.js");
const wrappers_js_1 = require("./wkt/wrappers.js");
/**
* Retrieve an extension value from a message.
*
* The function never returns undefined. Use hasExtension() to check whether an
* extension is set. If the extension is not set, this function returns the
* default value (if one was specified in the protobuf source), or the zero value
* (for example `0` for numeric types, `[]` for repeated extension fields, and
* an empty message instance for message fields).
*
* Extensions are stored as unknown fields on a message. To mutate an extension
* value, make sure to store the new value with setExtension() after mutating.
*
* If the extension does not extend the given message, an error is raised.
*/
function getExtension(message, extension) {
assertExtendee(extension, message);
const ufs = filterUnknownFields(message.$unknown, extension);
const [container, field, get] = createExtensionContainer(extension);
for (const uf of ufs) {
(0, from_binary_js_1.readField)(container, new binary_encoding_js_1.BinaryReader(uf.data), field, uf.wireType, {
readUnknownFields: true,
});
}
return get();
}
/**
* Set an extension value on a message. If the message already has a value for
* this extension, the value is replaced.
*
* If the extension does not extend the given message, an error is raised.
*/
function setExtension(message, extension, value) {
var _a;
assertExtendee(extension, message);
const ufs = ((_a = message.$unknown) !== null && _a !== void 0 ? _a : []).filter((uf) => uf.no !== extension.number);
const [container, field] = createExtensionContainer(extension, value);
const writer = new binary_encoding_js_1.BinaryWriter();
(0, to_binary_js_1.writeField)(writer, { writeUnknownFields: true }, container, field);
const reader = new binary_encoding_js_1.BinaryReader(writer.finish());
while (reader.pos < reader.len) {
const [no, wireType] = reader.tag();
const data = reader.skip(wireType, no);
ufs.push({ no, wireType, data });
}
message.$unknown = ufs;
}
/**
* Remove an extension value from a message.
*
* If the extension does not extend the given message, an error is raised.
*/
function clearExtension(message, extension) {
assertExtendee(extension, message);
if (message.$unknown === undefined) {
return;
}
message.$unknown = message.$unknown.filter((uf) => uf.no !== extension.number);
}
/**
* Check whether an extension is set on a message.
*/
function hasExtension(message, extension) {
var _a;
return (extension.extendee.typeName === message.$typeName &&
!!((_a = message.$unknown) === null || _a === void 0 ? void 0 : _a.find((uf) => uf.no === extension.number)));
}
/**
* Check whether an option is set on a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls hasExtension().
*/
function hasOption(element, option) {
const message = element.proto.options;
if (!message) {
return false;
}
return hasExtension(message, option);
}
/**
* Retrieve an option value from a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls getExtension(). Same as getExtension(), this
* function never returns undefined.
*/
function getOption(element, option) {
const message = element.proto.options;
if (!message) {
const [, , get] = createExtensionContainer(option);
return get();
}
return getExtension(message, option);
}
function filterUnknownFields(unknownFields, extension) {
if (unknownFields === undefined)
return [];
if (extension.fieldKind === "enum" || extension.fieldKind === "scalar") {
// singular scalar fields do not merge, we pick the last
for (let i = unknownFields.length - 1; i >= 0; --i) {
if (unknownFields[i].no == extension.number) {
return [unknownFields[i]];
}
}
return [];
}
return unknownFields.filter((uf) => uf.no === extension.number);
}
/**
* @private
*/
function createExtensionContainer(extension, value) {
const localName = extension.typeName;
const field = Object.assign(Object.assign({}, extension), { kind: "field", parent: extension.extendee, localName });
const desc = Object.assign(Object.assign({}, extension.extendee), { fields: [field], members: [field], oneofs: [] });
const container = (0, create_js_1.create)(desc, value !== undefined ? { [localName]: value } : undefined);
return [
(0, reflect_js_1.reflect)(desc, container),
field,
() => {
const value = container[localName];
if (value === undefined) {
// biome-ignore lint/style/noNonNullAssertion: Only message fields are undefined, rest will have a zero value.
const desc = extension.message;
if ((0, wrappers_js_1.isWrapperDesc)(desc)) {
return (0, scalar_js_1.scalarZeroValue)(desc.fields[0].scalar, desc.fields[0].longAsString);
}
return (0, create_js_1.create)(desc);
}
return value;
},
];
}
function assertExtendee(extension, message) {
if (extension.extendee.typeName != message.$typeName) {
throw new Error(`extension ${extension.typeName} can only be applied to message ${extension.extendee.typeName}`);
}
}
import type { MessageShape } from "./types.js";
import type { DescField, DescMessage } from "./descriptors.js";
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
export declare function isFieldSet<Desc extends DescMessage>(message: MessageShape<Desc>, field: DescField): boolean;
/**
* Resets the field, so that isFieldSet() will return false.
*/
export declare function clearField<Desc extends DescMessage>(message: MessageShape<Desc>, field: DescField): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFieldSet = isFieldSet;
exports.clearField = clearField;
const unsafe_js_1 = require("./reflect/unsafe.js");
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
function isFieldSet(message, field) {
return (field.parent.typeName == message.$typeName && (0, unsafe_js_1.unsafeIsSet)(message, field));
}
/**
* Resets the field, so that isFieldSet() will return false.
*/
function clearField(message, field) {
if (field.parent.typeName == message.$typeName) {
(0, unsafe_js_1.unsafeClear)(message, field);
}
}
import { type DescField, type DescMessage } from "./descriptors.js";
import type { MessageShape } from "./types.js";
import type { ReflectMessage } from "./reflect/index.js";
import { BinaryReader, WireType } from "./wire/binary-encoding.js";
/**
* Options for parsing binary data.
*/
export interface BinaryReadOptions {
/**
* Retain unknown fields during parsing? The default behavior is to retain
* unknown fields and include them in the serialized output.
*
* For more details see https://developers.google.com/protocol-buffers/docs/proto3#unknowns
*/
readUnknownFields: boolean;
}
/**
* Parse serialized binary data.
*/
export declare function fromBinary<Desc extends DescMessage>(schema: Desc, bytes: Uint8Array, options?: Partial<BinaryReadOptions>): MessageShape<Desc>;
/**
* Parse from binary data, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
export declare function mergeFromBinary<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, bytes: Uint8Array, options?: Partial<BinaryReadOptions>): MessageShape<Desc>;
/**
* @private
*/
export declare function readField(message: ReflectMessage, reader: BinaryReader, field: DescField, wireType: WireType, options: BinaryReadOptions): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromBinary = fromBinary;
exports.mergeFromBinary = mergeFromBinary;
exports.readField = readField;
const descriptors_js_1 = require("./descriptors.js");
const scalar_js_1 = require("./reflect/scalar.js");
const reflect_js_1 = require("./reflect/reflect.js");
const binary_encoding_js_1 = require("./wire/binary-encoding.js");
const varint_js_1 = require("./wire/varint.js");
// Default options for parsing binary data.
const readDefaults = {
readUnknownFields: true,
};
function makeReadOptions(options) {
return options ? Object.assign(Object.assign({}, readDefaults), options) : readDefaults;
}
/**
* Parse serialized binary data.
*/
function fromBinary(schema, bytes, options) {
const msg = (0, reflect_js_1.reflect)(schema, undefined, false);
readMessage(msg, new binary_encoding_js_1.BinaryReader(bytes), makeReadOptions(options), false, bytes.byteLength);
return msg.message;
}
/**
* Parse from binary data, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
function mergeFromBinary(schema, target, bytes, options) {
readMessage((0, reflect_js_1.reflect)(schema, target, false), new binary_encoding_js_1.BinaryReader(bytes), makeReadOptions(options), false, bytes.byteLength);
return target;
}
/**
* If `delimited` is false, read the length given in `lengthOrDelimitedFieldNo`.
*
* If `delimited` is true, read until an EndGroup tag. `lengthOrDelimitedFieldNo`
* is the expected field number.
*
* @private
*/
function readMessage(message, reader, options, delimited, lengthOrDelimitedFieldNo) {
var _a;
const end = delimited ? reader.len : reader.pos + lengthOrDelimitedFieldNo;
let fieldNo;
let wireType;
const unknownFields = (_a = message.getUnknown()) !== null && _a !== void 0 ? _a : [];
while (reader.pos < end) {
[fieldNo, wireType] = reader.tag();
if (delimited && wireType == binary_encoding_js_1.WireType.EndGroup) {
break;
}
const field = message.findNumber(fieldNo);
if (!field) {
const data = reader.skip(wireType, fieldNo);
if (options.readUnknownFields) {
unknownFields.push({ no: fieldNo, wireType, data });
}
continue;
}
readField(message, reader, field, wireType, options);
}
if (delimited) {
if (wireType != binary_encoding_js_1.WireType.EndGroup || fieldNo !== lengthOrDelimitedFieldNo) {
throw new Error("invalid end group tag");
}
}
if (unknownFields.length > 0) {
message.setUnknown(unknownFields);
}
}
/**
* @private
*/
function readField(message, reader, field, wireType, options) {
var _a;
switch (field.fieldKind) {
case "scalar":
message.set(field, readScalar(reader, field.scalar, field.utf8Validation));
break;
case "enum":
const val = readScalar(reader, descriptors_js_1.ScalarType.INT32);
if (field.enum.open) {
message.set(field, val);
}
else {
const ok = field.enum.values.some((v) => v.number === val);
if (ok) {
message.set(field, val);
}
else if (options.readUnknownFields) {
const bytes = [];
(0, varint_js_1.varint32write)(val, bytes);
const unknownFields = (_a = message.getUnknown()) !== null && _a !== void 0 ? _a : [];
unknownFields.push({
no: field.number,
wireType,
data: new Uint8Array(bytes),
});
message.setUnknown(unknownFields);
}
}
break;
case "message":
message.set(field, readMessageField(reader, options, field, message.get(field)));
break;
case "list":
readListField(reader, wireType, message.get(field), options);
break;
case "map":
readMapEntry(reader, message.get(field), options);
break;
}
}
// Read a map field, expecting key field = 1, value field = 2
function readMapEntry(reader, map, options) {
const field = map.field();
let key;
let val;
// Read the length of the map entry, which is a varint.
const len = reader.uint32();
// WARNING: Calculate end AFTER advancing reader.pos (above), so that
// reader.pos is at the start of the map entry.
const end = reader.pos + len;
while (reader.pos < end) {
const [fieldNo] = reader.tag();
switch (fieldNo) {
case 1:
key = readScalar(reader, field.mapKey, field.utf8Validation);
break;
case 2:
switch (field.mapKind) {
case "scalar":
val = readScalar(reader, field.scalar, field.utf8Validation);
break;
case "enum":
val = reader.int32();
break;
case "message":
val = readMessageField(reader, options, field);
break;
}
break;
}
}
if (key === undefined) {
key = (0, scalar_js_1.scalarZeroValue)(field.mapKey, false);
}
if (val === undefined) {
switch (field.mapKind) {
case "scalar":
val = (0, scalar_js_1.scalarZeroValue)(field.scalar, false);
break;
case "enum":
val = field.enum.values[0].number;
break;
case "message":
val = (0, reflect_js_1.reflect)(field.message, undefined, false);
break;
}
}
map.set(key, val);
}
function readListField(reader, wireType, list, options) {
var _a;
const field = list.field();
if (field.listKind === "message") {
list.add(readMessageField(reader, options, field));
return;
}
const scalarType = (_a = field.scalar) !== null && _a !== void 0 ? _a : descriptors_js_1.ScalarType.INT32;
const packed = wireType == binary_encoding_js_1.WireType.LengthDelimited &&
scalarType != descriptors_js_1.ScalarType.STRING &&
scalarType != descriptors_js_1.ScalarType.BYTES;
if (!packed) {
list.add(readScalar(reader, scalarType, field.utf8Validation));
return;
}
const e = reader.uint32() + reader.pos;
while (reader.pos < e) {
list.add(readScalar(reader, scalarType, field.utf8Validation));
}
}
function readMessageField(reader, options, field, mergeMessage) {
const delimited = field.delimitedEncoding;
const message = mergeMessage !== null && mergeMessage !== void 0 ? mergeMessage : (0, reflect_js_1.reflect)(field.message, undefined, false);
readMessage(message, reader, options, delimited, delimited ? field.number : reader.uint32());
return message;
}
function readScalar(reader, type, validateUtf8 = false) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return reader.string(validateUtf8);
case descriptors_js_1.ScalarType.BOOL:
return reader.bool();
case descriptors_js_1.ScalarType.DOUBLE:
return reader.double();
case descriptors_js_1.ScalarType.FLOAT:
return reader.float();
case descriptors_js_1.ScalarType.INT32:
return reader.int32();
case descriptors_js_1.ScalarType.INT64:
return reader.int64();
case descriptors_js_1.ScalarType.UINT64:
return reader.uint64();
case descriptors_js_1.ScalarType.FIXED64:
return reader.fixed64();
case descriptors_js_1.ScalarType.BYTES:
return reader.bytes();
case descriptors_js_1.ScalarType.FIXED32:
return reader.fixed32();
case descriptors_js_1.ScalarType.SFIXED32:
return reader.sfixed32();
case descriptors_js_1.ScalarType.SFIXED64:
return reader.sfixed64();
case descriptors_js_1.ScalarType.SINT64:
return reader.sint64();
case descriptors_js_1.ScalarType.UINT32:
return reader.uint32();
case descriptors_js_1.ScalarType.SINT32:
return reader.sint32();
}
}
import { type DescEnum, type DescMessage } from "./descriptors.js";
import type { JsonValue } from "./json-value.js";
import type { Registry } from "./registry.js";
import type { EnumJsonType, EnumShape, MessageShape } from "./types.js";
/**
* Options for parsing JSON data.
*/
export interface JsonReadOptions {
/**
* Ignore unknown fields: Proto3 JSON parser should reject unknown fields
* by default. This option ignores unknown fields in parsing, as well as
* unrecognized enum string representations.
*/
ignoreUnknownFields: boolean;
/**
* This option is required to read `google.protobuf.Any` and extensions
* from JSON format.
*/
registry?: Registry | undefined;
}
/**
* Parse a message from a JSON string.
*/
export declare function fromJsonString<Desc extends DescMessage>(schema: Desc, json: string, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON string, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
export declare function mergeFromJsonString<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, json: string, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON value.
*/
export declare function fromJson<Desc extends DescMessage>(schema: Desc, json: JsonValue, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON value, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
export declare function mergeFromJson<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, json: JsonValue, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parses an enum value from JSON.
*/
export declare function enumFromJson<Desc extends DescEnum>(descEnum: Desc, json: EnumJsonType<Desc>): EnumShape<Desc>;
/**
* Is the given value a JSON enum value?
*/
export declare function isEnumJson<Desc extends DescEnum>(descEnum: Desc, value: unknown): value is EnumJsonType<Desc>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJsonString = fromJsonString;
exports.mergeFromJsonString = mergeFromJsonString;
exports.fromJson = fromJson;
exports.mergeFromJson = mergeFromJson;
exports.enumFromJson = enumFromJson;
exports.isEnumJson = isEnumJson;
const descriptors_js_1 = require("./descriptors.js");
const proto_int64_js_1 = require("./proto-int64.js");
const create_js_1 = require("./create.js");
const reflect_js_1 = require("./reflect/reflect.js");
const error_js_1 = require("./reflect/error.js");
const reflect_check_js_1 = require("./reflect/reflect-check.js");
const names_js_1 = require("./reflect/names.js");
const base64_encoding_js_1 = require("./wire/base64-encoding.js");
const index_js_1 = require("./wkt/index.js");
const extensions_js_1 = require("./extensions.js");
// Default options for parsing JSON.
const jsonReadDefaults = {
ignoreUnknownFields: false,
};
function makeReadOptions(options) {
return options ? Object.assign(Object.assign({}, jsonReadDefaults), options) : jsonReadDefaults;
}
/**
* Parse a message from a JSON string.
*/
function fromJsonString(schema, json, options) {
return fromJson(schema, parseJsonString(json, schema.typeName), options);
}
/**
* Parse a message from a JSON string, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
function mergeFromJsonString(schema, target, json, options) {
return mergeFromJson(schema, target, parseJsonString(json, schema.typeName), options);
}
/**
* Parse a message from a JSON value.
*/
function fromJson(schema, json, options) {
const msg = (0, reflect_js_1.reflect)(schema);
try {
readMessage(msg, json, makeReadOptions(options));
}
catch (e) {
if ((0, error_js_1.isFieldError)(e)) {
// @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
throw new Error(`cannot decode ${e.field()} from JSON: ${e.message}`, {
cause: e,
});
}
throw e;
}
return msg.message;
}
/**
* Parse a message from a JSON value, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
function mergeFromJson(schema, target, json, options) {
try {
readMessage((0, reflect_js_1.reflect)(schema, target), json, makeReadOptions(options));
}
catch (e) {
if ((0, error_js_1.isFieldError)(e)) {
// @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
throw new Error(`cannot decode ${e.field()} from JSON: ${e.message}`, {
cause: e,
});
}
throw e;
}
return target;
}
/**
* Parses an enum value from JSON.
*/
function enumFromJson(descEnum, json) {
return readEnum(descEnum, json, false);
}
/**
* Is the given value a JSON enum value?
*/
function isEnumJson(descEnum, value) {
return undefined !== descEnum.values.find((v) => v.name === value);
}
const messageJsonFields = new WeakMap();
function getJsonField(desc, jsonKey) {
var _a;
if (!messageJsonFields.has(desc)) {
const jsonNames = new Map();
for (const field of desc.fields) {
jsonNames.set(field.name, field).set(field.jsonName, field);
}
messageJsonFields.set(desc, jsonNames);
}
return (_a = messageJsonFields.get(desc)) === null || _a === void 0 ? void 0 : _a.get(jsonKey);
}
function readMessage(msg, json, opts) {
var _a;
if (tryWktFromJson(msg, json, opts)) {
return;
}
if (json == null || Array.isArray(json) || typeof json != "object") {
throw new Error(`cannot decode ${msg.desc} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
const oneofSeen = new Map();
for (const [jsonKey, jsonValue] of Object.entries(json)) {
const field = getJsonField(msg.desc, jsonKey);
if (field) {
if (field.oneof) {
if (jsonValue === null && field.fieldKind == "scalar") {
// see conformance test Required.Proto3.JsonInput.OneofFieldNull{First,Second}
continue;
}
const seen = oneofSeen.get(field.oneof);
if (seen !== undefined) {
throw new error_js_1.FieldError(field.oneof, `oneof set multiple times by ${seen.name} and ${field.name}`);
}
oneofSeen.set(field.oneof, field);
}
readField(msg, field, jsonValue, opts);
}
else {
let extension = undefined;
if (jsonKey.startsWith("[") &&
jsonKey.endsWith("]") &&
// biome-ignore lint/suspicious/noAssignInExpressions: no
(extension = (_a = opts.registry) === null || _a === void 0 ? void 0 : _a.getExtension(jsonKey.substring(1, jsonKey.length - 1))) &&
extension.extendee.typeName === msg.desc.typeName) {
const [container, field, get] = (0, extensions_js_1.createExtensionContainer)(extension);
readField(container, field, jsonValue, opts);
(0, extensions_js_1.setExtension)(msg.message, extension, get());
}
if (!extension && !opts.ignoreUnknownFields) {
throw new Error(`cannot decode ${msg.desc} from JSON: key "${jsonKey}" is unknown`);
}
}
}
}
function readField(msg, field, json, opts) {
switch (field.fieldKind) {
case "scalar":
readScalarField(msg, field, json);
break;
case "enum":
readEnumField(msg, field, json, opts);
break;
case "message":
readMessageField(msg, field, json, opts);
break;
case "list":
readListField(msg.get(field), json, opts);
break;
case "map":
readMapField(msg.get(field), json, opts);
break;
}
}
function readListOrMapItem(field, json, opts) {
if (field.scalar && json !== null) {
return scalarFromJson(field, json);
}
if (field.message && !isResetSentinelNullValue(field, json)) {
const msgValue = (0, reflect_js_1.reflect)(field.message);
readMessage(msgValue, json, opts);
return msgValue;
}
if (field.enum && !isResetSentinelNullValue(field, json)) {
return readEnum(field.enum, json, opts.ignoreUnknownFields);
}
throw new error_js_1.FieldError(field, `${field.fieldKind === "list" ? "list item" : "map value"} must not be null`);
}
function readMapField(map, json, opts) {
if (json === null) {
return;
}
const field = map.field();
if (typeof json != "object" || Array.isArray(json)) {
throw new error_js_1.FieldError(field, "expected object, got " + (0, reflect_check_js_1.formatVal)(json));
}
for (const [jsonMapKey, jsonMapValue] of Object.entries(json)) {
const key = mapKeyFromJson(field.mapKey, jsonMapKey);
const value = readListOrMapItem(field, jsonMapValue, opts);
if (value !== tokenIgnoredUnknownEnum) {
map.set(key, value);
}
}
}
function readListField(list, json, opts) {
if (json === null) {
return;
}
const field = list.field();
if (!Array.isArray(json)) {
throw new error_js_1.FieldError(field, "expected Array, got " + (0, reflect_check_js_1.formatVal)(json));
}
for (const jsonItem of json) {
const value = readListOrMapItem(field, jsonItem, opts);
if (value !== tokenIgnoredUnknownEnum) {
list.add(value);
}
}
}
function readMessageField(msg, field, json, opts) {
if (isResetSentinelNullValue(field, json)) {
msg.clear(field);
return;
}
const msgValue = msg.isSet(field) ? msg.get(field) : (0, reflect_js_1.reflect)(field.message);
readMessage(msgValue, json, opts);
msg.set(field, msgValue);
}
function readEnumField(msg, field, json, opts) {
if (isResetSentinelNullValue(field, json)) {
msg.clear(field);
return;
}
const enumValue = readEnum(field.enum, json, opts.ignoreUnknownFields);
if (enumValue !== tokenIgnoredUnknownEnum) {
msg.set(field, enumValue);
}
}
function readScalarField(msg, field, json) {
if (json === null) {
msg.clear(field);
}
else {
msg.set(field, scalarFromJson(field, json));
}
}
/**
* Indicates whether a value is a sentinel for reseting a field.
*
* For this to be true, the value must be a JSON null and the field must not
* permit a present, Protobuf-serializable null.
*
* Only message google.protobuf.Value and enum google.protobuf.NullValue fields
* permit Protobuf-serializable nulls.
*
* Note that field-resetting sentinel nulls are not permitted in lists and maps.
*/
function isResetSentinelNullValue(field, json) {
var _a, _b;
return (json === null &&
((_a = field.message) === null || _a === void 0 ? void 0 : _a.typeName) != "google.protobuf.Value" &&
((_b = field.enum) === null || _b === void 0 ? void 0 : _b.typeName) != "google.protobuf.NullValue");
}
const tokenIgnoredUnknownEnum = Symbol();
function readEnum(desc, json, ignoreUnknownFields) {
if (json === null) {
return desc.values[0].number;
}
switch (typeof json) {
case "number":
if (Number.isInteger(json)) {
return json;
}
break;
case "string":
const value = desc.values.find((ev) => ev.name === json);
if (value !== undefined) {
return value.number;
}
if (ignoreUnknownFields) {
return tokenIgnoredUnknownEnum;
}
break;
}
throw new Error(`cannot decode ${desc} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
/**
* Try to parse a JSON value to a scalar value for the reflect API.
*
* Returns the input if the JSON value cannot be converted. Raises a FieldError
* if conversion would be ambiguous.
*/
function scalarFromJson(field, json) {
// int64, sfixed64, sint64, fixed64, uint64: Reflect supports string and number.
// string, bool: Supported by reflect.
switch (field.scalar) {
// float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
// Either numbers or strings are accepted. Exponent notation is also accepted.
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
if (json === "NaN")
return NaN;
if (json === "Infinity")
return Number.POSITIVE_INFINITY;
if (json === "-Infinity")
return Number.NEGATIVE_INFINITY;
if (typeof json == "number") {
if (Number.isNaN(json)) {
// NaN must be encoded with string constants
throw new error_js_1.FieldError(field, "unexpected NaN number");
}
if (!Number.isFinite(json)) {
// Infinity must be encoded with string constants
throw new error_js_1.FieldError(field, "unexpected infinite number");
}
break;
}
if (typeof json == "string") {
if (json === "") {
// empty string is not a number
break;
}
if (json.trim().length !== json.length) {
// extra whitespace
break;
}
const float = Number(json);
if (!Number.isFinite(float)) {
// Infinity and NaN must be encoded with string constants
break;
}
return float;
}
break;
// int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.UINT32:
return int32FromJson(json);
// bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
// Either standard or URL-safe base64 encoding with/without paddings are accepted.
case descriptors_js_1.ScalarType.BYTES:
if (typeof json == "string") {
if (json === "") {
return new Uint8Array(0);
}
try {
return (0, base64_encoding_js_1.base64Decode)(json);
}
catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new error_js_1.FieldError(field, message);
}
}
break;
}
return json;
}
/**
* Try to parse a JSON value to a map key for the reflect API.
*
* Returns the input if the JSON value cannot be converted.
*/
function mapKeyFromJson(type, jsonString) {
switch (type) {
case descriptors_js_1.ScalarType.BOOL:
switch (jsonString) {
case "true":
return true;
case "false":
return false;
}
return jsonString;
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
return int32FromJson(jsonString);
default:
return jsonString;
}
}
/**
* Try to parse a JSON value to a 32-bit integer for the reflect API.
*
* Returns the input if the JSON value cannot be converted.
*/
function int32FromJson(json) {
if (typeof json == "string") {
if (json === "") {
// empty string is not a number
return json;
}
if (json.trim().length !== json.length) {
// extra whitespace
return json;
}
const num = Number(json);
if (Number.isNaN(num)) {
// not a number
return json;
}
return num;
}
return json;
}
function parseJsonString(jsonString, typeName) {
try {
return JSON.parse(jsonString);
}
catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(`cannot decode message ${typeName} from JSON: ${message}`,
// @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
{ cause: e });
}
}
function tryWktFromJson(msg, jsonValue, opts) {
if (!msg.desc.typeName.startsWith("google.protobuf.")) {
return false;
}
switch (msg.desc.typeName) {
case "google.protobuf.Any":
anyFromJson(msg.message, jsonValue, opts);
return true;
case "google.protobuf.Timestamp":
timestampFromJson(msg.message, jsonValue);
return true;
case "google.protobuf.Duration":
durationFromJson(msg.message, jsonValue);
return true;
case "google.protobuf.FieldMask":
fieldMaskFromJson(msg.message, jsonValue);
return true;
case "google.protobuf.Struct":
structFromJson(msg.message, jsonValue);
return true;
case "google.protobuf.Value":
valueFromJson(msg.message, jsonValue);
return true;
case "google.protobuf.ListValue":
listValueFromJson(msg.message, jsonValue);
return true;
default:
if ((0, index_js_1.isWrapperDesc)(msg.desc)) {
const valueField = msg.desc.fields[0];
if (jsonValue === null) {
msg.clear(valueField);
}
else {
msg.set(valueField, scalarFromJson(valueField, jsonValue));
}
return true;
}
return false;
}
}
function anyFromJson(any, json, opts) {
var _a;
if (json === null || Array.isArray(json) || typeof json != "object") {
throw new Error(`cannot decode message ${any.$typeName} from JSON: expected object but got ${(0, reflect_check_js_1.formatVal)(json)}`);
}
if (Object.keys(json).length == 0) {
return;
}
const typeUrl = json["@type"];
if (typeof typeUrl != "string" || typeUrl == "") {
throw new Error(`cannot decode message ${any.$typeName} from JSON: "@type" is empty`);
}
const typeName = typeUrl.includes("/")
? typeUrl.substring(typeUrl.lastIndexOf("/") + 1)
: typeUrl;
if (!typeName.length) {
throw new Error(`cannot decode message ${any.$typeName} from JSON: "@type" is invalid`);
}
const desc = (_a = opts.registry) === null || _a === void 0 ? void 0 : _a.getMessage(typeName);
if (!desc) {
throw new Error(`cannot decode message ${any.$typeName} from JSON: ${typeUrl} is not in the type registry`);
}
const msg = (0, reflect_js_1.reflect)(desc);
if ((0, index_js_1.hasCustomJsonRepresentation)(desc) &&
Object.prototype.hasOwnProperty.call(json, "value")) {
const value = json.value;
readMessage(msg, value, opts);
}
else {
const copy = Object.assign({}, json);
// biome-ignore lint/performance/noDelete: <explanation>
delete copy["@type"];
readMessage(msg, copy, opts);
}
(0, index_js_1.anyPack)(msg.desc, msg.message, any);
}
function timestampFromJson(timestamp, json) {
if (typeof json !== "string") {
throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
const matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);
if (!matches) {
throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);
}
const ms = Date.parse(
// biome-ignore format: want this to read well
matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z"));
if (Number.isNaN(ms)) {
throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);
}
if (ms < Date.parse("0001-01-01T00:00:00Z") ||
ms > Date.parse("9999-12-31T23:59:59Z")) {
throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
}
timestamp.seconds = proto_int64_js_1.protoInt64.parse(ms / 1000);
timestamp.nanos = 0;
if (matches[7]) {
timestamp.nanos =
parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) -
1000000000;
}
}
function durationFromJson(duration, json) {
if (typeof json !== "string") {
throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
const match = json.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);
if (match === null) {
throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
const longSeconds = Number(match[1]);
if (longSeconds > 315576000000 || longSeconds < -315576000000) {
throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
duration.seconds = proto_int64_js_1.protoInt64.parse(longSeconds);
if (typeof match[2] !== "string") {
return;
}
const nanosStr = match[2] + "0".repeat(9 - match[2].length);
duration.nanos = parseInt(nanosStr);
if (longSeconds < 0 || Object.is(longSeconds, -0)) {
duration.nanos = -duration.nanos;
}
}
function fieldMaskFromJson(fieldMask, json) {
if (typeof json !== "string") {
throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
}
if (json === "") {
return;
}
fieldMask.paths = json.split(",").map((path) => {
if (path.includes("_")) {
throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: path names must be lowerCamelCase`);
}
return (0, names_js_1.protoSnakeCase)(path);
});
}
function structFromJson(struct, json) {
if (typeof json != "object" || json == null || Array.isArray(json)) {
throw new Error(`cannot decode message ${struct.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
}
for (const [k, v] of Object.entries(json)) {
const parsedV = (0, create_js_1.create)(index_js_1.ValueSchema);
valueFromJson(parsedV, v);
struct.fields[k] = parsedV;
}
}
function valueFromJson(value, json) {
switch (typeof json) {
case "number":
value.kind = { case: "numberValue", value: json };
break;
case "string":
value.kind = { case: "stringValue", value: json };
break;
case "boolean":
value.kind = { case: "boolValue", value: json };
break;
case "object":
if (json === null) {
value.kind = { case: "nullValue", value: index_js_1.NullValue.NULL_VALUE };
}
else if (Array.isArray(json)) {
const listValue = (0, create_js_1.create)(index_js_1.ListValueSchema);
listValueFromJson(listValue, json);
value.kind = { case: "listValue", value: listValue };
}
else {
const struct = (0, create_js_1.create)(index_js_1.StructSchema);
structFromJson(struct, json);
value.kind = { case: "structValue", value: struct };
}
break;
default:
throw new Error(`cannot decode message ${value.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
}
return value;
}
function listValueFromJson(listValue, json) {
if (!Array.isArray(json)) {
throw new Error(`cannot decode message ${listValue.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
}
for (const e of json) {
const value = (0, create_js_1.create)(index_js_1.ValueSchema);
valueFromJson(value, e);
listValue.values.push(value);
}
}
export * from "./types.js";
export * from "./is-message.js";
export * from "./create.js";
export * from "./clone.js";
export * from "./descriptors.js";
export * from "./equals.js";
export * from "./fields.js";
export * from "./registry.js";
export type { JsonValue, JsonObject } from "./json-value.js";
export { toBinary } from "./to-binary.js";
export type { BinaryWriteOptions } from "./to-binary.js";
export { fromBinary, mergeFromBinary } from "./from-binary.js";
export type { BinaryReadOptions } from "./from-binary.js";
export * from "./to-json.js";
export * from "./from-json.js";
export * from "./merge.js";
export { hasExtension, getExtension, setExtension, clearExtension, hasOption, getOption, } from "./extensions.js";
export * from "./proto-int64.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOption = exports.hasOption = exports.clearExtension = exports.setExtension = exports.getExtension = exports.hasExtension = exports.mergeFromBinary = exports.fromBinary = exports.toBinary = void 0;
__exportStar(require("./types.js"), exports);
__exportStar(require("./is-message.js"), exports);
__exportStar(require("./create.js"), exports);
__exportStar(require("./clone.js"), exports);
__exportStar(require("./descriptors.js"), exports);
__exportStar(require("./equals.js"), exports);
__exportStar(require("./fields.js"), exports);
__exportStar(require("./registry.js"), exports);
var to_binary_js_1 = require("./to-binary.js");
Object.defineProperty(exports, "toBinary", { enumerable: true, get: function () { return to_binary_js_1.toBinary; } });
var from_binary_js_1 = require("./from-binary.js");
Object.defineProperty(exports, "fromBinary", { enumerable: true, get: function () { return from_binary_js_1.fromBinary; } });
Object.defineProperty(exports, "mergeFromBinary", { enumerable: true, get: function () { return from_binary_js_1.mergeFromBinary; } });
__exportStar(require("./to-json.js"), exports);
__exportStar(require("./from-json.js"), exports);
__exportStar(require("./merge.js"), exports);
var extensions_js_1 = require("./extensions.js");
Object.defineProperty(exports, "hasExtension", { enumerable: true, get: function () { return extensions_js_1.hasExtension; } });
Object.defineProperty(exports, "getExtension", { enumerable: true, get: function () { return extensions_js_1.getExtension; } });
Object.defineProperty(exports, "setExtension", { enumerable: true, get: function () { return extensions_js_1.setExtension; } });
Object.defineProperty(exports, "clearExtension", { enumerable: true, get: function () { return extensions_js_1.clearExtension; } });
Object.defineProperty(exports, "hasOption", { enumerable: true, get: function () { return extensions_js_1.hasOption; } });
Object.defineProperty(exports, "getOption", { enumerable: true, get: function () { return extensions_js_1.getOption; } });
__exportStar(require("./proto-int64.js"), exports);
import type { MessageShape } from "./types.js";
import type { DescMessage } from "./descriptors.js";
/**
* Determine whether the given `arg` is a message.
* If `desc` is set, determine whether `arg` is this specific message.
*/
export declare function isMessage<Desc extends DescMessage>(arg: unknown, schema?: Desc): arg is MessageShape<Desc>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isMessage = isMessage;
/**
* Determine whether the given `arg` is a message.
* If `desc` is set, determine whether `arg` is this specific message.
*/
function isMessage(arg, schema) {
const isMessage = arg !== null &&
typeof arg == "object" &&
"$typeName" in arg &&
typeof arg.$typeName == "string";
if (!isMessage) {
return false;
}
if (schema === undefined) {
return true;
}
return schema.typeName === arg.$typeName;
}
/**
* Represents any possible JSON value:
* - number
* - string
* - boolean
* - null
* - object (with any JSON value as property)
* - array (with any JSON value as element)
*/
export type JsonValue = number | string | boolean | null | JsonObject | JsonValue[];
/**
* Represents a JSON object.
*/
export type JsonObject = {
[k: string]: JsonValue;
};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
import type { MessageShape } from "./types.js";
import type { DescMessage } from "./descriptors.js";
/**
* Merge message `source` into message `target`, following Protobuf semantics.
*
* This is the same as serializing the source message, then deserializing it
* into the target message via `mergeFromBinary()`, with one difference:
* While serialization will create a copy of all values, `merge()` will copy
* the reference for `bytes` and messages.
*
* Also see https://protobuf.com/docs/language-spec#merging-protobuf-messages
*/
export declare function merge<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, source: MessageShape<Desc>): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.merge = merge;
const reflect_js_1 = require("./reflect/reflect.js");
/**
* Merge message `source` into message `target`, following Protobuf semantics.
*
* This is the same as serializing the source message, then deserializing it
* into the target message via `mergeFromBinary()`, with one difference:
* While serialization will create a copy of all values, `merge()` will copy
* the reference for `bytes` and messages.
*
* Also see https://protobuf.com/docs/language-spec#merging-protobuf-messages
*/
function merge(schema, target, source) {
reflectMerge((0, reflect_js_1.reflect)(schema, target), (0, reflect_js_1.reflect)(schema, source));
}
function reflectMerge(target, source) {
var _a;
var _b;
const sourceUnknown = source.message.$unknown;
if (sourceUnknown !== undefined && sourceUnknown.length > 0) {
(_a = (_b = target.message).$unknown) !== null && _a !== void 0 ? _a : (_b.$unknown = []);
target.message.$unknown.push(...sourceUnknown);
}
for (const f of target.fields) {
if (!source.isSet(f)) {
continue;
}
switch (f.fieldKind) {
case "scalar":
case "enum":
target.set(f, source.get(f));
break;
case "message":
if (target.isSet(f)) {
reflectMerge(target.get(f), source.get(f));
}
else {
target.set(f, source.get(f));
}
break;
case "list":
const list = target.get(f);
for (const e of source.get(f)) {
list.add(e);
}
break;
case "map":
const map = target.get(f);
for (const [k, v] of source.get(f)) {
map.set(k, v);
}
break;
}
}
}
{"type":"commonjs"}
/**
* Int64Support for the current environment.
*/
export declare const protoInt64: Int64Support;
/**
* We use the `bigint` primitive to represent 64-bit integral types. If bigint
* is unavailable, we fall back to a string representation, which means that
* all values typed as `bigint` will actually be strings.
*
* If your code is intended to run in an environment where bigint may be
* unavailable, it must handle both the bigint and the string representation.
* For presenting values, this is straight-forward with implicit or explicit
* conversion to string:
*
* ```ts
* let el = document.createElement("span");
* el.innerText = message.int64Field; // assuming a protobuf int64 field
*
* console.log(`int64: ${message.int64Field}`);
*
* let str: string = message.int64Field.toString();
* ```
*
* If you need to manipulate 64-bit integral values and are sure the values
* can be safely represented as an IEEE-754 double precision number, you can
* convert to a JavaScript Number:
*
* ```ts
* console.log(message.int64Field.toString())
* let num = Number(message.int64Field);
* num = num + 1;
* message.int64Field = protoInt64.parse(num);
* ```
*
* If you need to manipulate 64-bit integral values that are outside the
* range of safe representation as a JavaScript Number, we recommend you
* use a third party library, for example the npm package "long":
*
* ```ts
* // convert the field value to a Long
* const bits = protoInt64.enc(message.int64Field);
* const longValue = Long.fromBits(bits.lo, bits.hi);
*
* // perform arithmetic
* const longResult = longValue.subtract(1);
*
* // set the result in the field
* message.int64Field = protoInt64.dec(longResult.low, longResult.high);
*
* // Assuming int64Field contains 9223372036854775807:
* console.log(message.int64Field); // 9223372036854775806
* ```
*/
interface Int64Support {
/**
* 0n if bigint is available, "0" if unavailable.
*/
readonly zero: bigint;
/**
* Is bigint available?
*/
readonly supported: boolean;
/**
* Parse a signed 64-bit integer.
* Returns a bigint if available, a string otherwise.
*/
parse(value: string | number | bigint): bigint;
/**
* Parse an unsigned 64-bit integer.
* Returns a bigint if available, a string otherwise.
*/
uParse(value: string | number | bigint): bigint;
/**
* Convert a signed 64-bit integral value to a two's complement.
*/
enc(value: string | number | bigint): {
lo: number;
hi: number;
};
/**
* Convert an unsigned 64-bit integral value to a two's complement.
*/
uEnc(value: string | number | bigint): {
lo: number;
hi: number;
};
/**
* Convert a two's complement to a signed 64-bit integral value.
* Returns a bigint if available, a string otherwise.
*/
dec(lo: number, hi: number): bigint;
/**
* Convert a two's complement to an unsigned 64-bit integral value.
* Returns a bigint if available, a string otherwise.
*/
uDec(lo: number, hi: number): bigint;
}
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.protoInt64 = void 0;
const varint_js_1 = require("./wire/varint.js");
/**
* Int64Support for the current environment.
*/
exports.protoInt64 = makeInt64Support();
function makeInt64Support() {
const dv = new DataView(new ArrayBuffer(8));
// note that Safari 14 implements BigInt, but not the DataView methods
const ok = typeof BigInt === "function" &&
typeof dv.getBigInt64 === "function" &&
typeof dv.getBigUint64 === "function" &&
typeof dv.setBigInt64 === "function" &&
typeof dv.setBigUint64 === "function" &&
(!!globalThis.Deno ||
typeof process != "object" ||
typeof process.env != "object" ||
process.env.BUF_BIGINT_DISABLE !== "1");
if (ok) {
const MIN = BigInt("-9223372036854775808");
const MAX = BigInt("9223372036854775807");
const UMIN = BigInt("0");
const UMAX = BigInt("18446744073709551615");
return {
zero: BigInt(0),
supported: true,
parse(value) {
const bi = typeof value == "bigint" ? value : BigInt(value);
if (bi > MAX || bi < MIN) {
throw new Error(`invalid int64: ${value}`);
}
return bi;
},
uParse(value) {
const bi = typeof value == "bigint" ? value : BigInt(value);
if (bi > UMAX || bi < UMIN) {
throw new Error(`invalid uint64: ${value}`);
}
return bi;
},
enc(value) {
dv.setBigInt64(0, this.parse(value), true);
return {
lo: dv.getInt32(0, true),
hi: dv.getInt32(4, true),
};
},
uEnc(value) {
dv.setBigInt64(0, this.uParse(value), true);
return {
lo: dv.getInt32(0, true),
hi: dv.getInt32(4, true),
};
},
dec(lo, hi) {
dv.setInt32(0, lo, true);
dv.setInt32(4, hi, true);
return dv.getBigInt64(0, true);
},
uDec(lo, hi) {
dv.setInt32(0, lo, true);
dv.setInt32(4, hi, true);
return dv.getBigUint64(0, true);
},
};
}
return {
zero: "0",
supported: false,
parse(value) {
if (typeof value != "string") {
value = value.toString();
}
assertInt64String(value);
return value;
},
uParse(value) {
if (typeof value != "string") {
value = value.toString();
}
assertUInt64String(value);
return value;
},
enc(value) {
if (typeof value != "string") {
value = value.toString();
}
assertInt64String(value);
return (0, varint_js_1.int64FromString)(value);
},
uEnc(value) {
if (typeof value != "string") {
value = value.toString();
}
assertUInt64String(value);
return (0, varint_js_1.int64FromString)(value);
},
dec(lo, hi) {
return (0, varint_js_1.int64ToString)(lo, hi);
},
uDec(lo, hi) {
return (0, varint_js_1.uInt64ToString)(lo, hi);
},
};
}
function assertInt64String(value) {
if (!/^-?[0-9]+$/.test(value)) {
throw new Error("invalid int64: " + value);
}
}
function assertUInt64String(value) {
if (!/^[0-9]+$/.test(value)) {
throw new Error("invalid uint64: " + value);
}
}
import type { DescField, DescOneof } from "../descriptors.js";
declare const errorNames: string[];
export declare class FieldError extends Error {
readonly name: (typeof errorNames)[number];
constructor(fieldOrOneof: DescField | DescOneof, message: string, name?: (typeof errorNames)[number]);
readonly field: () => DescField | DescOneof;
}
export declare function isFieldError(arg: unknown): arg is FieldError;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldError = void 0;
exports.isFieldError = isFieldError;
const errorNames = [
"FieldValueInvalidError",
"FieldListRangeError",
"ForeignFieldError",
];
class FieldError extends Error {
constructor(fieldOrOneof, message, name = "FieldValueInvalidError") {
super(message);
this.name = name;
this.field = () => fieldOrOneof;
}
}
exports.FieldError = FieldError;
function isFieldError(arg) {
return (arg instanceof Error &&
errorNames.includes(arg.name) &&
"field" in arg &&
typeof arg.field == "function");
}
import type { Message } from "../types.js";
import type { ScalarValue } from "./scalar.js";
import type { ReflectList, ReflectMap, ReflectMessage } from "./reflect-types.js";
import type { DescField, DescMessage } from "../descriptors.js";
export declare function isObject(arg: unknown): arg is Record<string, unknown>;
export declare function isOneofADT(arg: unknown): arg is OneofADT;
export type OneofADT = {
case: undefined;
value?: undefined;
} | {
case: string;
value: Message | ScalarValue;
};
export declare function isReflectList(arg: unknown, field?: DescField & {
fieldKind: "list";
}): arg is ReflectList;
export declare function isReflectMap(arg: unknown, field?: DescField & {
fieldKind: "map";
}): arg is ReflectMap;
export declare function isReflectMessage(arg: unknown, messageDesc?: DescMessage): arg is ReflectMessage;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isObject = isObject;
exports.isOneofADT = isOneofADT;
exports.isReflectList = isReflectList;
exports.isReflectMap = isReflectMap;
exports.isReflectMessage = isReflectMessage;
const unsafe_js_1 = require("./unsafe.js");
function isObject(arg) {
return arg !== null && typeof arg == "object" && !Array.isArray(arg);
}
function isOneofADT(arg) {
return (arg !== null &&
typeof arg == "object" &&
"case" in arg &&
((typeof arg.case == "string" && "value" in arg && arg.value != null) ||
(arg.case === undefined &&
(!("value" in arg) || arg.value === undefined))));
}
function isReflectList(arg, field) {
var _a, _b, _c, _d;
if (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"add" in arg &&
"field" in arg &&
typeof arg.field == "function") {
if (field !== undefined) {
const a = field;
const b = arg.field();
return (a.listKind == b.listKind &&
a.scalar === b.scalar &&
((_a = a.message) === null || _a === void 0 ? void 0 : _a.typeName) === ((_b = b.message) === null || _b === void 0 ? void 0 : _b.typeName) &&
((_c = a.enum) === null || _c === void 0 ? void 0 : _c.typeName) === ((_d = b.enum) === null || _d === void 0 ? void 0 : _d.typeName));
}
return true;
}
return false;
}
function isReflectMap(arg, field) {
var _a, _b, _c, _d;
if (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"has" in arg &&
"field" in arg &&
typeof arg.field == "function") {
if (field !== undefined) {
const a = field, b = arg.field();
return (a.mapKey === b.mapKey &&
a.mapKind == b.mapKind &&
a.scalar === b.scalar &&
((_a = a.message) === null || _a === void 0 ? void 0 : _a.typeName) === ((_b = b.message) === null || _b === void 0 ? void 0 : _b.typeName) &&
((_c = a.enum) === null || _c === void 0 ? void 0 : _c.typeName) === ((_d = b.enum) === null || _d === void 0 ? void 0 : _d.typeName));
}
return true;
}
return false;
}
function isReflectMessage(arg, messageDesc) {
return (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"desc" in arg &&
isObject(arg.desc) &&
arg.desc.kind === "message" &&
(messageDesc === undefined || arg.desc.typeName == messageDesc.typeName));
}
export * from "./error.js";
export * from "./names.js";
export * from "./nested-types.js";
export * from "./reflect.js";
export * from "./reflect-types.js";
export * from "./scalar.js";
export * from "./path.js";
export { isReflectList, isReflectMap, isReflectMessage } from "./guard.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isReflectMessage = exports.isReflectMap = exports.isReflectList = void 0;
__exportStar(require("./error.js"), exports);
__exportStar(require("./names.js"), exports);
__exportStar(require("./nested-types.js"), exports);
__exportStar(require("./reflect.js"), exports);
__exportStar(require("./reflect-types.js"), exports);
__exportStar(require("./scalar.js"), exports);
__exportStar(require("./path.js"), exports);
var guard_js_1 = require("./guard.js");
Object.defineProperty(exports, "isReflectList", { enumerable: true, get: function () { return guard_js_1.isReflectList; } });
Object.defineProperty(exports, "isReflectMap", { enumerable: true, get: function () { return guard_js_1.isReflectMap; } });
Object.defineProperty(exports, "isReflectMessage", { enumerable: true, get: function () { return guard_js_1.isReflectMessage; } });
import type { AnyDesc } from "../descriptors.js";
/**
* Return a fully-qualified name for a Protobuf descriptor.
* For a file descriptor, return the original file path.
*
* See https://protobuf.com/docs/language-spec#fully-qualified-names
*/
export declare function qualifiedName(desc: AnyDesc): string;
/**
* Converts snake_case to protoCamelCase according to the convention
* used by protoc to convert a field name to a JSON name.
*
* See https://protobuf.com/docs/language-spec#default-json-names
*
* The function protoSnakeCase provides the reverse.
*/
export declare function protoCamelCase(snakeCase: string): string;
/**
* Converts protoCamelCase to snake_case.
*
* This function is the reverse of function protoCamelCase. Note that some names
* are not reversible - for example, "foo__bar" -> "fooBar" -> "foo_bar".
*/
export declare function protoSnakeCase(lowerCamelCase: string): string;
/**
* Escapes names that are reserved for ECMAScript built-in object properties.
*
* Also see safeIdentifier() from @bufbuild/protoplugin.
*/
export declare function safeObjectProperty(name: string): string;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.qualifiedName = qualifiedName;
exports.protoCamelCase = protoCamelCase;
exports.protoSnakeCase = protoSnakeCase;
exports.safeObjectProperty = safeObjectProperty;
/**
* Return a fully-qualified name for a Protobuf descriptor.
* For a file descriptor, return the original file path.
*
* See https://protobuf.com/docs/language-spec#fully-qualified-names
*/
function qualifiedName(desc) {
switch (desc.kind) {
case "field":
case "oneof":
case "rpc":
return desc.parent.typeName + "." + desc.name;
case "enum_value": {
const p = desc.parent.parent
? desc.parent.parent.typeName
: desc.parent.file.proto.package;
return p + (p.length > 0 ? "." : "") + desc.name;
}
case "service":
case "message":
case "enum":
case "extension":
return desc.typeName;
case "file":
return desc.proto.name;
}
}
/**
* Converts snake_case to protoCamelCase according to the convention
* used by protoc to convert a field name to a JSON name.
*
* See https://protobuf.com/docs/language-spec#default-json-names
*
* The function protoSnakeCase provides the reverse.
*/
function protoCamelCase(snakeCase) {
let capNext = false;
const b = [];
for (let i = 0; i < snakeCase.length; i++) {
let c = snakeCase.charAt(i);
switch (c) {
case "_":
capNext = true;
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
b.push(c);
capNext = false;
break;
default:
if (capNext) {
capNext = false;
c = c.toUpperCase();
}
b.push(c);
break;
}
}
return b.join("");
}
/**
* Converts protoCamelCase to snake_case.
*
* This function is the reverse of function protoCamelCase. Note that some names
* are not reversible - for example, "foo__bar" -> "fooBar" -> "foo_bar".
*/
function protoSnakeCase(lowerCamelCase) {
return lowerCamelCase.replace(/[A-Z]/g, (letter) => "_" + letter.toLowerCase());
}
/**
* Names that cannot be used for object properties because they are reserved
* by built-in JavaScript properties.
*/
const reservedObjectProperties = new Set([
// names reserved by JavaScript
"constructor",
"toString",
"toJSON",
"valueOf",
]);
/**
* Escapes names that are reserved for ECMAScript built-in object properties.
*
* Also see safeIdentifier() from @bufbuild/protoplugin.
*/
function safeObjectProperty(name) {
return reservedObjectProperties.has(name) ? name + "$" : name;
}
import type { AnyDesc, DescEnum, DescExtension, DescFile, DescMessage, DescService } from "../descriptors.js";
/**
* Iterate over all types - enumerations, extensions, services, messages -
* and enumerations, extensions and messages nested in messages.
*/
export declare function nestedTypes(desc: DescFile | DescMessage): Iterable<DescMessage | DescEnum | DescExtension | DescService>;
/**
* Iterate over types referenced by fields of the given message.
*
* For example:
*
* ```proto
* syntax="proto3";
*
* message Example {
* Msg singular = 1;
* repeated Level list = 2;
* }
*
* message Msg {}
*
* enum Level {
* LEVEL_UNSPECIFIED = 0;
* }
* ```
*
* The message Example references the message Msg, and the enum Level.
*/
export declare function usedTypes(descMessage: DescMessage): Iterable<DescMessage | DescEnum>;
/**
* Returns the ancestors of a given Protobuf element, up to the file.
*/
export declare function parentTypes(desc: AnyDesc): Parent[];
type Parent = DescFile | DescEnum | DescMessage | DescService;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.nestedTypes = nestedTypes;
exports.usedTypes = usedTypes;
exports.parentTypes = parentTypes;
/**
* Iterate over all types - enumerations, extensions, services, messages -
* and enumerations, extensions and messages nested in messages.
*/
function* nestedTypes(desc) {
switch (desc.kind) {
case "file":
for (const message of desc.messages) {
yield message;
yield* nestedTypes(message);
}
yield* desc.enums;
yield* desc.services;
yield* desc.extensions;
break;
case "message":
for (const message of desc.nestedMessages) {
yield message;
yield* nestedTypes(message);
}
yield* desc.nestedEnums;
yield* desc.nestedExtensions;
break;
}
}
/**
* Iterate over types referenced by fields of the given message.
*
* For example:
*
* ```proto
* syntax="proto3";
*
* message Example {
* Msg singular = 1;
* repeated Level list = 2;
* }
*
* message Msg {}
*
* enum Level {
* LEVEL_UNSPECIFIED = 0;
* }
* ```
*
* The message Example references the message Msg, and the enum Level.
*/
function usedTypes(descMessage) {
return usedTypesInternal(descMessage, new Set());
}
function* usedTypesInternal(descMessage, seen) {
var _a, _b;
for (const field of descMessage.fields) {
const ref = (_b = (_a = field.enum) !== null && _a !== void 0 ? _a : field.message) !== null && _b !== void 0 ? _b : undefined;
if (!ref || seen.has(ref.typeName)) {
continue;
}
seen.add(ref.typeName);
yield ref;
if (ref.kind == "message") {
yield* usedTypesInternal(ref, seen);
}
}
}
/**
* Returns the ancestors of a given Protobuf element, up to the file.
*/
function parentTypes(desc) {
const parents = [];
while (desc.kind !== "file") {
const p = parent(desc);
desc = p;
parents.push(p);
}
return parents;
}
function parent(desc) {
var _a;
switch (desc.kind) {
case "enum_value":
case "field":
case "oneof":
case "rpc":
return desc.parent;
case "service":
return desc.file;
case "extension":
case "enum":
case "message":
return (_a = desc.parent) !== null && _a !== void 0 ? _a : desc.file;
}
}
import { type DescExtension, type DescField, type DescMessage, type DescOneof } from "../descriptors.js";
import type { Registry } from "../registry.js";
/**
* A path to a (nested) member of a Protobuf message, such as a field, oneof,
* extension, list element, or map entry.
*
* Note that we may add additional types to this union in the future to support
* more use cases.
*/
export type Path = (DescField | DescExtension | DescOneof | {
kind: "list_sub";
index: number;
} | {
kind: "map_sub";
key: string | number | bigint | boolean;
})[];
/**
* Builds a Path.
*/
export type PathBuilder = {
/**
* The root message of the path.
*/
readonly schema: DescMessage;
/**
* Add field access.
*
* Throws an InvalidPathError if the field cannot be added to the path.
*/
field(field: DescField): PathBuilder;
/**
* Access a oneof.
*
* Throws an InvalidPathError if the oneof cannot be added to the path.
*
*/
oneof(oneof: DescOneof): PathBuilder;
/**
* Access an extension.
*
* Throws an InvalidPathError if the extension cannot be added to the path.
*/
extension(extension: DescExtension): PathBuilder;
/**
* Access a list field by index.
*
* Throws an InvalidPathError if the list access cannot be added to the path.
*/
list(index: number): PathBuilder;
/**
* Access a map field by key.
*
* Throws an InvalidPathError if the map access cannot be added to the path.
*/
map(key: string | number | bigint | boolean): PathBuilder;
/**
* Append a path.
*
* Throws an InvalidPathError if the path cannot be added.
*/
add(path: Path | PathBuilder): PathBuilder;
/**
* Return the path.
*/
toPath(): Path;
/**
* Create a copy of this builder.
*/
clone(): PathBuilder;
/**
* Get the current container - a list, map, or message.
*/
getLeft(): DescMessage | (DescField & {
fieldKind: "list";
}) | (DescField & {
fieldKind: "map";
}) | undefined;
};
/**
* Create a PathBuilder.
*/
export declare function buildPath(schema: DescMessage): PathBuilder;
/**
* Parse a Path from a string.
*
* Throws an InvalidPathError if the path is invalid.
*
* Note that a Registry must be provided via the options argument to parse
* paths that refer to an extension.
*/
export declare function parsePath(schema: DescMessage, path: string, options?: {
registry?: Registry | undefined;
}): Path;
/**
* Stringify a path.
*/
export declare function pathToString(path: Path): string;
/**
* InvalidPathError is thrown for invalid Paths, for example during parsing from
* a string, or when a new Path is built.
*/
export declare class InvalidPathError extends Error {
name: string;
readonly schema: DescMessage;
readonly path: Path | string;
constructor(schema: DescMessage, message: string, path: string | Path);
}
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidPathError = void 0;
exports.buildPath = buildPath;
exports.parsePath = parsePath;
exports.pathToString = pathToString;
const descriptors_js_1 = require("../descriptors.js");
/**
* Create a PathBuilder.
*/
function buildPath(schema) {
return new PathBuilderImpl(schema, schema, []);
}
/**
* Parse a Path from a string.
*
* Throws an InvalidPathError if the path is invalid.
*
* Note that a Registry must be provided via the options argument to parse
* paths that refer to an extension.
*/
function parsePath(schema, path, options) {
var _a, _b;
const builder = new PathBuilderImpl(schema, schema, []);
const err = (message, i) => new InvalidPathError(schema, message + " at column " + (i + 1), path);
for (let i = 0; i < path.length;) {
const token = nextToken(i, path);
const left = builder.getLeft();
let right = undefined;
if ("field" in token) {
right =
(left === null || left === void 0 ? void 0 : left.kind) != "message"
? undefined
: ((_a = left.fields.find((field) => field.name === token.field)) !== null && _a !== void 0 ? _a : left.oneofs.find((oneof) => oneof.name === token.field));
if (!right) {
throw err(`Unknown field "${token.field}"`, i);
}
}
else if ("ext" in token) {
right = (_b = options === null || options === void 0 ? void 0 : options.registry) === null || _b === void 0 ? void 0 : _b.getExtension(token.ext);
if (!right) {
throw err(`Unknown extension "${token.ext}"`, i);
}
}
else if ("val" in token) {
// list or map
right =
(left === null || left === void 0 ? void 0 : left.kind) == "field" &&
left.fieldKind == "list" &&
typeof token.val == "bigint"
? { kind: "list_sub", index: Number(token.val) }
: { kind: "map_sub", key: token.val };
}
else if ("err" in token) {
throw err(token.err, token.i);
}
if (right) {
try {
builder.add([right]);
}
catch (e) {
throw err(e instanceof InvalidPathError ? e.message : String(e), i);
}
}
i = token.i;
}
return builder.toPath();
}
/**
* Stringify a path.
*/
function pathToString(path) {
const str = [];
for (const ele of path) {
switch (ele.kind) {
case "field":
case "oneof":
if (str.length > 0) {
str.push(".");
}
str.push(ele.name);
break;
case "extension":
str.push("[", ele.typeName, "]");
break;
case "list_sub":
str.push("[", ele.index, "]");
break;
case "map_sub":
if (typeof ele.key == "string") {
str.push('["', ele.key
.split("\\")
.join("\\\\")
.split('"')
.join('\\"')
.split("\r")
.join("\\r")
.split("\n")
.join("\\n"), '"]');
}
else {
str.push("[", ele.key, "]");
}
break;
}
}
return str.join("");
}
/**
* InvalidPathError is thrown for invalid Paths, for example during parsing from
* a string, or when a new Path is built.
*/
class InvalidPathError extends Error {
constructor(schema, message, path) {
super(message);
this.name = "InvalidPathError";
this.schema = schema;
this.path = path;
// see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example
Object.setPrototypeOf(this, new.target.prototype);
}
}
exports.InvalidPathError = InvalidPathError;
class PathBuilderImpl {
constructor(schema, left, path) {
this.schema = schema;
this.left = left;
this.path = path;
}
getLeft() {
return this.left;
}
field(field) {
return this.push(field);
}
oneof(oneof) {
return this.push(oneof);
}
extension(extension) {
return this.push(extension);
}
list(index) {
return this.push({ kind: "list_sub", index });
}
map(key) {
return this.push({ kind: "map_sub", key });
}
add(pathOrBuilder) {
const path = Array.isArray(pathOrBuilder)
? pathOrBuilder
: pathOrBuilder.toPath();
const l = this.path.length;
try {
for (const ele of path) {
this.push(ele);
}
}
catch (e) {
// undo pushes
this.path.splice(l);
throw e;
}
return this;
}
toPath() {
return this.path.concat();
}
clone() {
return new PathBuilderImpl(this.schema, this.left, this.path.concat());
}
push(ele) {
switch (ele.kind) {
case "field":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.parent.typeName) {
throw this.err("field access");
}
this.path.push(ele);
this.left =
ele.fieldKind == "message"
? ele.message
: ele.fieldKind == "list" || ele.fieldKind == "map"
? ele
: undefined;
return this;
case "oneof":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.parent.typeName) {
throw this.err("oneof access");
}
this.path.push(ele);
this.left = undefined;
return this;
case "extension":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.extendee.typeName) {
throw this.err("extension access");
}
this.path.push(ele);
this.left = ele.fieldKind == "message" ? ele.message : undefined;
return this;
case "list_sub":
if (!this.left ||
this.left.kind != "field" ||
this.left.fieldKind != "list") {
throw this.err("list access");
}
if (ele.index < 0 || !Number.isInteger(ele.index)) {
throw this.err("list index");
}
this.path.push(ele);
this.left =
this.left.listKind == "message" ? this.left.message : undefined;
return this;
case "map_sub":
if (!this.left ||
this.left.kind != "field" ||
this.left.fieldKind != "map") {
throw this.err("map access");
}
if (!checkKeyType(ele.key, this.left.mapKey)) {
throw this.err("map key");
}
this.path.push(ele);
this.left =
this.left.mapKind == "message" ? this.left.message : undefined;
return this;
}
}
err(what) {
return new InvalidPathError(this.schema, "Invalid " + what, this.path);
}
}
function checkKeyType(key, type) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return typeof key == "string";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.FIXED32:
return typeof key == "number";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
return typeof key == "bigint";
case descriptors_js_1.ScalarType.BOOL:
return typeof key == "boolean";
}
}
function nextToken(i, path) {
const re_extension = /^[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*$/;
const re_field = /^[A-Za-z_][A-Za-z_0-9]*$/;
if (path[i] == "[") {
i++;
while (path[i] == " ") {
// skip leading whitespace
i++;
}
if (i >= path.length) {
return { err: "Premature end", i: path.length - 1 };
}
let token;
if (path[i] == `"`) {
// string literal
i++;
let val = "";
for (;;) {
if (path[i] == `"`) {
// end of string literal
i++;
break;
}
if (path[i] == "\\") {
switch (path[i + 1]) {
case `"`:
case "\\":
val += path[i + 1];
break;
case "r":
val += "\r";
break;
case "n":
val += "\n";
break;
default:
return { err: "Invalid escape sequence", i };
}
i++;
}
else {
val += path[i];
}
if (i >= path.length) {
return { err: "Premature end of string", i: path.length - 1 };
}
i++;
}
token = { val };
}
else if (path[i].match(/\d/)) {
// integer literal
const start = i;
while (i < path.length && /\d/.test(path[i])) {
i++;
}
token = { val: BigInt(path.substring(start, i)) };
}
else if (path[i] == "]") {
return { err: "Premature ]", i };
}
else {
// extension identifier or bool literal
const start = i;
while (i < path.length && path[i] != " " && path[i] != "]") {
i++;
}
const name = path.substring(start, i);
if (name === "true") {
token = { val: true };
}
else if (name === "false") {
token = { val: false };
}
else if (re_extension.test(name)) {
token = { ext: name };
}
else {
return { err: "Invalid ident", i: start };
}
}
while (path[i] == " ") {
// skip trailing whitespace
i++;
}
if (path[i] != "]") {
return { err: "Missing ]", i };
}
i++;
return Object.assign(Object.assign({}, token), { i });
}
// field identifier
if (i > 0) {
if (path[i] != ".") {
return { err: `Expected "."`, i };
}
i++;
}
const start = i;
while (i < path.length && path[i] != "." && path[i] != "[") {
i++;
}
const field = path.substring(start, i);
return re_field.test(field)
? { field, i }
: { err: "Invalid ident", i: start };
}
import { type DescField } from "../descriptors.js";
import { FieldError } from "./error.js";
/**
* Check whether the given field value is valid for the reflect API.
*/
export declare function checkField(field: DescField, value: unknown): FieldError | undefined;
/**
* Check whether the given list item is valid for the reflect API.
*/
export declare function checkListItem(field: DescField & {
fieldKind: "list";
}, index: number, value: unknown): FieldError | undefined;
/**
* Check whether the given map key and value are valid for the reflect API.
*/
export declare function checkMapEntry(field: DescField & {
fieldKind: "map";
}, key: unknown, value: unknown): FieldError | undefined;
export declare function formatVal(val: unknown): string;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkField = checkField;
exports.checkListItem = checkListItem;
exports.checkMapEntry = checkMapEntry;
exports.formatVal = formatVal;
const descriptors_js_1 = require("../descriptors.js");
const is_message_js_1 = require("../is-message.js");
const error_js_1 = require("./error.js");
const guard_js_1 = require("./guard.js");
const binary_encoding_js_1 = require("../wire/binary-encoding.js");
const text_encoding_js_1 = require("../wire/text-encoding.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Check whether the given field value is valid for the reflect API.
*/
function checkField(field, value) {
const check = field.fieldKind == "list"
? (0, guard_js_1.isReflectList)(value, field)
: field.fieldKind == "map"
? (0, guard_js_1.isReflectMap)(value, field)
: checkSingular(field, value);
if (check === true) {
return undefined;
}
let reason;
switch (field.fieldKind) {
case "list":
reason = `expected ${formatReflectList(field)}, got ${formatVal(value)}`;
break;
case "map":
reason = `expected ${formatReflectMap(field)}, got ${formatVal(value)}`;
break;
default: {
reason = reasonSingular(field, value, check);
}
}
return new error_js_1.FieldError(field, reason);
}
/**
* Check whether the given list item is valid for the reflect API.
*/
function checkListItem(field, index, value) {
const check = checkSingular(field, value);
if (check !== true) {
return new error_js_1.FieldError(field, `list item #${index + 1}: ${reasonSingular(field, value, check)}`);
}
return undefined;
}
/**
* Check whether the given map key and value are valid for the reflect API.
*/
function checkMapEntry(field, key, value) {
const checkKey = checkScalarValue(key, field.mapKey);
if (checkKey !== true) {
return new error_js_1.FieldError(field, `invalid map key: ${reasonSingular({ scalar: field.mapKey }, key, checkKey)}`);
}
const checkVal = checkSingular(field, value);
if (checkVal !== true) {
return new error_js_1.FieldError(field, `map entry ${formatVal(key)}: ${reasonSingular(field, value, checkVal)}`);
}
return undefined;
}
function checkSingular(field, value) {
if (field.scalar !== undefined) {
return checkScalarValue(value, field.scalar);
}
if (field.enum !== undefined) {
if (field.enum.open) {
return Number.isInteger(value);
}
return field.enum.values.some((v) => v.number === value);
}
return (0, guard_js_1.isReflectMessage)(value, field.message);
}
function checkScalarValue(value, scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.DOUBLE:
return typeof value == "number";
case descriptors_js_1.ScalarType.FLOAT:
if (typeof value != "number") {
return false;
}
if (Number.isNaN(value) || !Number.isFinite(value)) {
return true;
}
if (value > binary_encoding_js_1.FLOAT32_MAX || value < binary_encoding_js_1.FLOAT32_MIN) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
// signed
if (typeof value !== "number" || !Number.isInteger(value)) {
return false;
}
if (value > binary_encoding_js_1.INT32_MAX || value < binary_encoding_js_1.INT32_MIN) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
// unsigned
if (typeof value !== "number" || !Number.isInteger(value)) {
return false;
}
if (value > binary_encoding_js_1.UINT32_MAX || value < 0) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.BOOL:
return typeof value == "boolean";
case descriptors_js_1.ScalarType.STRING:
if (typeof value != "string") {
return false;
}
return (0, text_encoding_js_1.getTextEncoding)().checkUtf8(value) || "invalid UTF8";
case descriptors_js_1.ScalarType.BYTES:
return value instanceof Uint8Array;
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
// signed
if (typeof value == "bigint" ||
typeof value == "number" ||
(typeof value == "string" && value.length > 0)) {
try {
proto_int64_js_1.protoInt64.parse(value);
return true;
}
catch (_) {
return `${value} out of range`;
}
}
return false;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
// unsigned
if (typeof value == "bigint" ||
typeof value == "number" ||
(typeof value == "string" && value.length > 0)) {
try {
proto_int64_js_1.protoInt64.uParse(value);
return true;
}
catch (_) {
return `${value} out of range`;
}
}
return false;
}
}
function reasonSingular(field, val, details) {
details =
typeof details == "string" ? `: ${details}` : `, got ${formatVal(val)}`;
if (field.scalar !== undefined) {
return `expected ${scalarTypeDescription(field.scalar)}` + details;
}
if (field.enum !== undefined) {
return `expected ${field.enum.toString()}` + details;
}
return `expected ${formatReflectMessage(field.message)}` + details;
}
function formatVal(val) {
switch (typeof val) {
case "object":
if (val === null) {
return "null";
}
if (val instanceof Uint8Array) {
return `Uint8Array(${val.length})`;
}
if (Array.isArray(val)) {
return `Array(${val.length})`;
}
if ((0, guard_js_1.isReflectList)(val)) {
return formatReflectList(val.field());
}
if ((0, guard_js_1.isReflectMap)(val)) {
return formatReflectMap(val.field());
}
if ((0, guard_js_1.isReflectMessage)(val)) {
return formatReflectMessage(val.desc);
}
if ((0, is_message_js_1.isMessage)(val)) {
return `message ${val.$typeName}`;
}
return "object";
case "string":
return val.length > 30 ? "string" : `"${val.split('"').join('\\"')}"`;
case "boolean":
return String(val);
case "number":
return String(val);
case "bigint":
return String(val) + "n";
default:
// "symbol" | "undefined" | "object" | "function"
return typeof val;
}
}
function formatReflectMessage(desc) {
return `ReflectMessage (${desc.typeName})`;
}
function formatReflectList(field) {
switch (field.listKind) {
case "message":
return `ReflectList (${field.message.toString()})`;
case "enum":
return `ReflectList (${field.enum.toString()})`;
case "scalar":
return `ReflectList (${descriptors_js_1.ScalarType[field.scalar]})`;
}
}
function formatReflectMap(field) {
switch (field.mapKind) {
case "message":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${field.message.toString()})`;
case "enum":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${field.enum.toString()})`;
case "scalar":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${descriptors_js_1.ScalarType[field.scalar]})`;
}
}
function scalarTypeDescription(scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.SFIXED64:
return "bigint (int64)";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
return "bigint (uint64)";
case descriptors_js_1.ScalarType.BYTES:
return "Uint8Array";
case descriptors_js_1.ScalarType.DOUBLE:
return "number (float64)";
case descriptors_js_1.ScalarType.FLOAT:
return "number (float32)";
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
return "number (uint32)";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
return "number (int32)";
}
}
import type { DescField, DescMessage, DescOneof } from "../descriptors.js";
import { unsafeLocal } from "./unsafe.js";
import type { Message, UnknownField } from "../types.js";
import type { ScalarValue } from "./scalar.js";
/**
* ReflectMessage provides dynamic access and manipulation of a message.
*/
export interface ReflectMessage {
/**
* The underlying message instance.
*/
readonly message: Message;
/**
* The descriptor for the message.
*/
readonly desc: DescMessage;
/**
* The fields of the message. This is a shortcut to message.fields.
*/
readonly fields: readonly DescField[];
/**
* The fields of the message, sorted by field number ascending.
*/
readonly sortedFields: readonly DescField[];
/**
* Oneof groups of the message. This is a shortcut to message.oneofs.
*/
readonly oneofs: readonly DescOneof[];
/**
* Fields and oneof groups for this message. This is a shortcut to message.members.
*/
readonly members: readonly (DescField | DescOneof)[];
/**
* Find a field by number.
*/
findNumber(number: number): DescField | undefined;
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
isSet(field: DescField): boolean;
/**
* Resets the field, so that isSet() will return false.
*/
clear(field: DescField): void;
/**
* Return the selected field of a oneof group.
*/
oneofCase(oneof: DescOneof): DescField | undefined;
/**
* Returns the field value. Values are converted or wrapped to make it easier
* to manipulate messages.
*
* - Scalar fields:
* Returns the value, but converts 64-bit integer fields with the option
* `jstype=JS_STRING` to a bigint value.
* If the field is not set, the default value is returned. If no default
* value is set, the zero value is returned.
*
* - Enum fields:
* Returns the numeric value. If the field is not set, the default value is
* returned. If no default value is set, the zero value is returned.
*
* - Message fields:
* Returns a ReflectMessage. If the field is not set, a new message is
* returned, but not set on the field.
*
* - List fields:
* Returns a ReflectList object.
*
* - Map fields:
* Returns a ReflectMap object.
*
* Note that get() never returns `undefined`. To determine whether a field is
* set, use isSet().
*/
get<Field extends DescField>(field: Field): ReflectMessageGet<Field>;
/**
* Set a field value.
*
* Expects values in the same form that get() returns:
*
* - Scalar fields:
* 64-bit integer fields with the option `jstype=JS_STRING` as a bigint value.
*
* - Message fields:
* ReflectMessage.
*
* - List fields:
* ReflectList.
*
* - Map fields:
* ReflectMap.
*
* Throws an error if the value is invalid for the field. `undefined` is not
* a valid value. To reset a field, use clear().
*/
set<Field extends DescField>(field: Field, value: unknown): void;
/**
* Returns the unknown fields of the message.
*/
getUnknown(): UnknownField[] | undefined;
/**
* Sets the unknown fields of the message, overwriting any previous values.
*/
setUnknown(value: UnknownField[]): void;
[unsafeLocal]: Message;
}
/**
* ReflectList provides dynamic access and manipulation of a list field on a
* message.
*
* ReflectList is iterable - you can loop through all items with a for...of loop.
*
* Values are converted or wrapped to make it easier to manipulate them:
* - Scalar 64-bit integer fields with the option `jstype=JS_STRING` are
* converted to bigint.
* - Messages are wrapped in a ReflectMessage.
*/
export interface ReflectList<V = unknown> extends Iterable<V> {
/**
* Returns the list field.
*/
field(): DescField & {
fieldKind: "list";
};
/**
* The size of the list.
*/
readonly size: number;
/**
* Retrieves the item at the specified index, or undefined if the index
* is out of range.
*/
get(index: number): V | undefined;
/**
* Adds an item at the end of the list.
* Throws an error if an item is invalid for this list.
*/
add(item: V): void;
/**
* Replaces the item at the specified index with the specified item.
* Throws an error if the index is out of range (index < 0 || index >= size).
* Throws an error if the item is invalid for this list.
*/
set(index: number, item: V): void;
/**
* Removes all items from the list.
*/
clear(): void;
[Symbol.iterator](): IterableIterator<V>;
entries(): IterableIterator<[number, V]>;
keys(): IterableIterator<number>;
values(): IterableIterator<V>;
[unsafeLocal]: unknown[];
}
/**
* ReflectMap provides dynamic access and manipulation of a map field on a
* message.
*
* ReflectMap is iterable - you can loop through all entries with a for...of loop.
*
* Keys and values are converted or wrapped to make it easier to manipulate them:
* - A map field is a record object on a message, where keys are always strings.
* ReflectMap converts keys to their closest possible type in TypeScript.
* - Messages are wrapped in a ReflectMessage.
*/
export interface ReflectMap<K = unknown, V = unknown> extends ReadonlyMap<K, V> {
/**
* Returns the map field.
*/
field(): DescField & {
fieldKind: "map";
};
/**
* Removes the entry for the specified key.
* Returns false if the key is unknown.
*/
delete(key: K): boolean;
/**
* Sets or replaces the item at the specified key with the specified value.
* Throws an error if the key or value is invalid for this map.
*/
set(key: K, value: V): this;
/**
* Removes all entries from the map.
*/
clear(): void;
[unsafeLocal]: Record<string, unknown>;
}
/**
* The return type of ReflectMessage.get()
*/
export type ReflectMessageGet<Field extends DescField = DescField> = (Field extends {
fieldKind: "map";
} ? ReflectMap : Field extends {
fieldKind: "list";
} ? ReflectList : Field extends {
fieldKind: "enum";
} ? number : Field extends {
fieldKind: "message";
} ? ReflectMessage : Field extends {
fieldKind: "scalar";
scalar: infer T;
} ? ScalarValue<T> : never);
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
const unsafe_js_1 = require("./unsafe.js");
import { type DescField, type DescMessage } from "../descriptors.js";
import type { MessageShape } from "../types.js";
import type { ReflectList, ReflectMap, ReflectMessage } from "./reflect-types.js";
/**
* Create a ReflectMessage.
*/
export declare function reflect<Desc extends DescMessage>(messageDesc: Desc, message?: MessageShape<Desc>,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectMessage;
/**
* Create a ReflectList.
*/
export declare function reflectList<V>(field: DescField & {
fieldKind: "list";
}, unsafeInput?: unknown[],
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectList<V>;
/**
* Create a ReflectMap.
*/
export declare function reflectMap<K = unknown, V = unknown>(field: DescField & {
fieldKind: "map";
}, unsafeInput?: Record<string, unknown>,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectMap<K, V>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.reflect = reflect;
exports.reflectList = reflectList;
exports.reflectMap = reflectMap;
const descriptors_js_1 = require("../descriptors.js");
const reflect_check_js_1 = require("./reflect-check.js");
const error_js_1 = require("./error.js");
const unsafe_js_1 = require("./unsafe.js");
const create_js_1 = require("../create.js");
const wrappers_js_1 = require("../wkt/wrappers.js");
const scalar_js_1 = require("./scalar.js");
const proto_int64_js_1 = require("../proto-int64.js");
const guard_js_1 = require("./guard.js");
/**
* Create a ReflectMessage.
*/
function reflect(messageDesc, message,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectMessageImpl(messageDesc, message, check);
}
const messageSortedFields = new WeakMap();
class ReflectMessageImpl {
get sortedFields() {
const cached = messageSortedFields.get(this.desc);
if (cached) {
return cached;
}
const sortedFields = this.desc.fields
.concat()
.sort((a, b) => a.number - b.number);
messageSortedFields.set(this.desc, sortedFields);
return sortedFields;
}
constructor(messageDesc, message, check = true) {
this.lists = new Map();
this.maps = new Map();
this.check = check;
this.desc = messageDesc;
this.message = this[unsafe_js_1.unsafeLocal] = message !== null && message !== void 0 ? message : (0, create_js_1.create)(messageDesc);
this.fields = messageDesc.fields;
this.oneofs = messageDesc.oneofs;
this.members = messageDesc.members;
}
findNumber(number) {
if (!this._fieldsByNumber) {
this._fieldsByNumber = new Map(this.desc.fields.map((f) => [f.number, f]));
}
return this._fieldsByNumber.get(number);
}
oneofCase(oneof) {
assertOwn(this.message, oneof);
return (0, unsafe_js_1.unsafeOneofCase)(this.message, oneof);
}
isSet(field) {
assertOwn(this.message, field);
return (0, unsafe_js_1.unsafeIsSet)(this.message, field);
}
clear(field) {
assertOwn(this.message, field);
(0, unsafe_js_1.unsafeClear)(this.message, field);
}
get(field) {
assertOwn(this.message, field);
const value = (0, unsafe_js_1.unsafeGet)(this.message, field);
switch (field.fieldKind) {
case "list":
// eslint-disable-next-line no-case-declarations
let list = this.lists.get(field);
if (!list || list[unsafe_js_1.unsafeLocal] !== value) {
this.lists.set(field,
// biome-ignore lint/suspicious/noAssignInExpressions: no
(list = new ReflectListImpl(field, value, this.check)));
}
return list;
case "map":
let map = this.maps.get(field);
if (!map || map[unsafe_js_1.unsafeLocal] !== value) {
this.maps.set(field,
// biome-ignore lint/suspicious/noAssignInExpressions: no
(map = new ReflectMapImpl(field, value, this.check)));
}
return map;
case "message":
return messageToReflect(field, value, this.check);
case "scalar":
return (value === undefined
? (0, scalar_js_1.scalarZeroValue)(field.scalar, false)
: longToReflect(field, value));
case "enum":
return (value !== null && value !== void 0 ? value : field.enum.values[0].number);
}
}
set(field, value) {
assertOwn(this.message, field);
if (this.check) {
const err = (0, reflect_check_js_1.checkField)(field, value);
if (err) {
throw err;
}
}
let local;
if (field.fieldKind == "message") {
local = messageToLocal(field, value);
}
else if ((0, guard_js_1.isReflectMap)(value) || (0, guard_js_1.isReflectList)(value)) {
local = value[unsafe_js_1.unsafeLocal];
}
else {
local = longToLocal(field, value);
}
(0, unsafe_js_1.unsafeSet)(this.message, field, local);
}
getUnknown() {
return this.message.$unknown;
}
setUnknown(value) {
this.message.$unknown = value;
}
}
function assertOwn(owner, member) {
if (member.parent.typeName !== owner.$typeName) {
throw new error_js_1.FieldError(member, `cannot use ${member.toString()} with message ${owner.$typeName}`, "ForeignFieldError");
}
}
/**
* Create a ReflectList.
*/
function reflectList(field, unsafeInput,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectListImpl(field, unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : [], check);
}
class ReflectListImpl {
field() {
return this._field;
}
get size() {
return this._arr.length;
}
constructor(field, unsafeInput, check) {
this._field = field;
this._arr = this[unsafe_js_1.unsafeLocal] = unsafeInput;
this.check = check;
}
get(index) {
const item = this._arr[index];
return item === undefined
? undefined
: listItemToReflect(this._field, item, this.check);
}
set(index, item) {
if (index < 0 || index >= this._arr.length) {
throw new error_js_1.FieldError(this._field, `list item #${index + 1}: out of range`);
}
if (this.check) {
const err = (0, reflect_check_js_1.checkListItem)(this._field, index, item);
if (err) {
throw err;
}
}
this._arr[index] = listItemToLocal(this._field, item);
}
add(item) {
if (this.check) {
const err = (0, reflect_check_js_1.checkListItem)(this._field, this._arr.length, item);
if (err) {
throw err;
}
}
this._arr.push(listItemToLocal(this._field, item));
return undefined;
}
clear() {
this._arr.splice(0, this._arr.length);
}
[Symbol.iterator]() {
return this.values();
}
keys() {
return this._arr.keys();
}
*values() {
for (const item of this._arr) {
yield listItemToReflect(this._field, item, this.check);
}
}
*entries() {
for (let i = 0; i < this._arr.length; i++) {
yield [i, listItemToReflect(this._field, this._arr[i], this.check)];
}
}
}
/**
* Create a ReflectMap.
*/
function reflectMap(field, unsafeInput,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectMapImpl(field, unsafeInput, check);
}
class ReflectMapImpl {
constructor(field, unsafeInput, check = true) {
this.obj = this[unsafe_js_1.unsafeLocal] = unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : {};
this.check = check;
this._field = field;
}
field() {
return this._field;
}
set(key, value) {
if (this.check) {
const err = (0, reflect_check_js_1.checkMapEntry)(this._field, key, value);
if (err) {
throw err;
}
}
this.obj[mapKeyToLocal(key)] = mapValueToLocal(this._field, value);
return this;
}
delete(key) {
const k = mapKeyToLocal(key);
const has = Object.prototype.hasOwnProperty.call(this.obj, k);
if (has) {
delete this.obj[k];
}
return has;
}
clear() {
for (const key of Object.keys(this.obj)) {
delete this.obj[key];
}
}
get(key) {
let val = this.obj[mapKeyToLocal(key)];
if (val !== undefined) {
val = mapValueToReflect(this._field, val, this.check);
}
return val;
}
has(key) {
return Object.prototype.hasOwnProperty.call(this.obj, mapKeyToLocal(key));
}
*keys() {
for (const objKey of Object.keys(this.obj)) {
yield mapKeyToReflect(objKey, this._field.mapKey);
}
}
*entries() {
for (const objEntry of Object.entries(this.obj)) {
yield [
mapKeyToReflect(objEntry[0], this._field.mapKey),
mapValueToReflect(this._field, objEntry[1], this.check),
];
}
}
[Symbol.iterator]() {
return this.entries();
}
get size() {
return Object.keys(this.obj).length;
}
*values() {
for (const val of Object.values(this.obj)) {
yield mapValueToReflect(this._field, val, this.check);
}
}
forEach(callbackfn, thisArg) {
for (const mapEntry of this.entries()) {
callbackfn.call(thisArg, mapEntry[1], mapEntry[0], this);
}
}
}
function messageToLocal(field, value) {
if (!(0, guard_js_1.isReflectMessage)(value)) {
return value;
}
if ((0, wrappers_js_1.isWrapper)(value.message) &&
!field.oneof &&
field.fieldKind == "message") {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
return value.message.value;
}
if (value.desc.typeName == "google.protobuf.Struct" &&
field.parent.typeName != "google.protobuf.Value") {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
return wktStructToLocal(value.message);
}
return value.message;
}
function messageToReflect(field, value, check) {
if (value !== undefined) {
if ((0, wrappers_js_1.isWrapperDesc)(field.message) &&
!field.oneof &&
field.fieldKind == "message") {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
value = {
$typeName: field.message.typeName,
value: longToReflect(field.message.fields[0], value),
};
}
else if (field.message.typeName == "google.protobuf.Struct" &&
field.parent.typeName != "google.protobuf.Value" &&
(0, guard_js_1.isObject)(value)) {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
value = wktStructToReflect(value);
}
}
return new ReflectMessageImpl(field.message, value, check);
}
function listItemToLocal(field, value) {
if (field.listKind == "message") {
return messageToLocal(field, value);
}
return longToLocal(field, value);
}
function listItemToReflect(field, value, check) {
if (field.listKind == "message") {
return messageToReflect(field, value, check);
}
return longToReflect(field, value);
}
function mapValueToLocal(field, value) {
if (field.mapKind == "message") {
return messageToLocal(field, value);
}
return longToLocal(field, value);
}
function mapValueToReflect(field, value, check) {
if (field.mapKind == "message") {
return messageToReflect(field, value, check);
}
return value;
}
function mapKeyToLocal(key) {
return typeof key == "string" || typeof key == "number" ? key : String(key);
}
/**
* Converts a map key (any scalar value except float, double, or bytes) from its
* representation in a message (string or number, the only possible object key
* types) to the closest possible type in ECMAScript.
*/
function mapKeyToReflect(key, type) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return key;
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32: {
const n = Number.parseInt(key);
if (Number.isFinite(n)) {
return n;
}
break;
}
case descriptors_js_1.ScalarType.BOOL:
switch (key) {
case "true":
return true;
case "false":
return false;
}
break;
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
try {
return proto_int64_js_1.protoInt64.uParse(key);
}
catch (_a) {
//
}
break;
default:
// INT64, SFIXED64, SINT64
try {
return proto_int64_js_1.protoInt64.parse(key);
}
catch (_b) {
//
}
break;
}
return key;
}
function longToReflect(field, value) {
switch (field.scalar) {
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
if ("longAsString" in field &&
field.longAsString &&
typeof value == "string") {
value = proto_int64_js_1.protoInt64.parse(value);
}
break;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
if ("longAsString" in field &&
field.longAsString &&
typeof value == "string") {
value = proto_int64_js_1.protoInt64.uParse(value);
}
break;
}
return value;
}
function longToLocal(field, value) {
switch (field.scalar) {
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
if ("longAsString" in field && field.longAsString) {
value = String(value);
}
else if (typeof value == "string" || typeof value == "number") {
value = proto_int64_js_1.protoInt64.parse(value);
}
break;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
if ("longAsString" in field && field.longAsString) {
value = String(value);
}
else if (typeof value == "string" || typeof value == "number") {
value = proto_int64_js_1.protoInt64.uParse(value);
}
break;
}
return value;
}
function wktStructToReflect(json) {
const struct = {
$typeName: "google.protobuf.Struct",
fields: {},
};
if ((0, guard_js_1.isObject)(json)) {
for (const [k, v] of Object.entries(json)) {
struct.fields[k] = wktValueToReflect(v);
}
}
return struct;
}
function wktStructToLocal(val) {
const json = {};
for (const [k, v] of Object.entries(val.fields)) {
json[k] = wktValueToLocal(v);
}
return json;
}
function wktValueToLocal(val) {
switch (val.kind.case) {
case "structValue":
return wktStructToLocal(val.kind.value);
case "listValue":
return val.kind.value.values.map(wktValueToLocal);
case "nullValue":
case undefined:
return null;
default:
return val.kind.value;
}
}
function wktValueToReflect(json) {
const value = {
$typeName: "google.protobuf.Value",
kind: { case: undefined },
};
switch (typeof json) {
case "number":
value.kind = { case: "numberValue", value: json };
break;
case "string":
value.kind = { case: "stringValue", value: json };
break;
case "boolean":
value.kind = { case: "boolValue", value: json };
break;
case "object":
if (json === null) {
const nullValue = 0;
value.kind = { case: "nullValue", value: nullValue };
}
else if (Array.isArray(json)) {
const listValue = {
$typeName: "google.protobuf.ListValue",
values: [],
};
if (Array.isArray(json)) {
for (const e of json) {
listValue.values.push(wktValueToReflect(e));
}
}
value.kind = {
case: "listValue",
value: listValue,
};
}
else {
value.kind = {
case: "structValue",
value: wktStructToReflect(json),
};
}
break;
}
return value;
}
import { ScalarType } from "../descriptors.js";
/**
* ScalarValue maps from a scalar field type to a TypeScript value type.
*/
export type ScalarValue<T = ScalarType, LongAsString extends boolean = false> = T extends ScalarType.STRING ? string : T extends ScalarType.INT32 ? number : T extends ScalarType.UINT32 ? number : T extends ScalarType.SINT32 ? number : T extends ScalarType.FIXED32 ? number : T extends ScalarType.SFIXED32 ? number : T extends ScalarType.FLOAT ? number : T extends ScalarType.DOUBLE ? number : T extends ScalarType.INT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.SINT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.SFIXED64 ? LongAsString extends true ? string : bigint : T extends ScalarType.UINT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.FIXED64 ? LongAsString extends true ? string : bigint : T extends ScalarType.BOOL ? boolean : T extends ScalarType.BYTES ? Uint8Array : never;
/**
* Returns true if both scalar values are equal.
*/
export declare function scalarEquals(type: ScalarType, a: ScalarValue | undefined, b: ScalarValue | undefined): boolean;
/**
* Returns the zero value for the given scalar type.
*/
export declare function scalarZeroValue<T extends ScalarType, LongAsString extends boolean>(type: T, longAsString: LongAsString): ScalarValue<T, LongAsString>;
/**
* Returns true for a zero-value. For example, an integer has the zero-value `0`,
* a boolean is `false`, a string is `""`, and bytes is an empty Uint8Array.
*
* In proto3, zero-values are not written to the wire, unless the field is
* optional or repeated.
*/
export declare function isScalarZeroValue(type: ScalarType, value: unknown): boolean;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.scalarEquals = scalarEquals;
exports.scalarZeroValue = scalarZeroValue;
exports.isScalarZeroValue = isScalarZeroValue;
const proto_int64_js_1 = require("../proto-int64.js");
const descriptors_js_1 = require("../descriptors.js");
/**
* Returns true if both scalar values are equal.
*/
function scalarEquals(type, a, b) {
if (a === b) {
// This correctly matches equal values except BYTES and (possibly) 64-bit integers.
return true;
}
// Special case BYTES - we need to compare each byte individually
if (type == descriptors_js_1.ScalarType.BYTES) {
if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array)) {
return false;
}
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
// Special case 64-bit integers - we support number, string and bigint representation.
switch (type) {
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
// Loose comparison will match between 0n, 0 and "0".
return a == b;
}
// Anything that hasn't been caught by strict comparison or special cased
// BYTES and 64-bit integers is not equal.
return false;
}
/**
* Returns the zero value for the given scalar type.
*/
function scalarZeroValue(type, longAsString) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return "";
case descriptors_js_1.ScalarType.BOOL:
return false;
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
return 0.0;
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
return (longAsString ? "0" : proto_int64_js_1.protoInt64.zero);
case descriptors_js_1.ScalarType.BYTES:
return new Uint8Array(0);
default:
// Handles INT32, UINT32, SINT32, FIXED32, SFIXED32.
// We do not use individual cases to save a few bytes code size.
return 0;
}
}
/**
* Returns true for a zero-value. For example, an integer has the zero-value `0`,
* a boolean is `false`, a string is `""`, and bytes is an empty Uint8Array.
*
* In proto3, zero-values are not written to the wire, unless the field is
* optional or repeated.
*/
function isScalarZeroValue(type, value) {
switch (type) {
case descriptors_js_1.ScalarType.BOOL:
return value === false;
case descriptors_js_1.ScalarType.STRING:
return value === "";
case descriptors_js_1.ScalarType.BYTES:
return value instanceof Uint8Array && !value.byteLength;
default:
return value == 0; // Loose comparison matches 0n, 0 and "0"
}
}
import type { DescField, DescOneof } from "../descriptors.js";
export declare const unsafeLocal: unique symbol;
/**
* Return the selected field of a oneof group.
*
* @private
*/
export declare function unsafeOneofCase(target: Record<string, any>, oneof: DescOneof): DescField | undefined;
/**
* Returns true if the field is set.
*
* @private
*/
export declare function unsafeIsSet(target: Record<string, any>, field: DescField): boolean;
/**
* Returns true if the field is set, but only for singular fields with explicit
* presence (proto2).
*
* @private
*/
export declare function unsafeIsSetExplicit(target: object, localName: string): boolean;
/**
* Return a field value, respecting oneof groups.
*
* @private
*/
export declare function unsafeGet(target: Record<string, unknown>, field: DescField): unknown;
/**
* Set a field value, respecting oneof groups.
*
* @private
*/
export declare function unsafeSet(target: Record<string, unknown>, field: DescField, value: unknown): void;
/**
* Resets the field, so that unsafeIsSet() will return false.
*
* @private
*/
export declare function unsafeClear(target: Record<string, any>, field: DescField): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsafeLocal = void 0;
exports.unsafeOneofCase = unsafeOneofCase;
exports.unsafeIsSet = unsafeIsSet;
exports.unsafeIsSetExplicit = unsafeIsSetExplicit;
exports.unsafeGet = unsafeGet;
exports.unsafeSet = unsafeSet;
exports.unsafeClear = unsafeClear;
const scalar_js_1 = require("./scalar.js");
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
exports.unsafeLocal = Symbol.for("reflect unsafe local");
/**
* Return the selected field of a oneof group.
*
* @private
*/
function unsafeOneofCase(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, oneof) {
const c = target[oneof.localName].case;
if (c === undefined) {
return c;
}
return oneof.fields.find((f) => f.localName === c);
}
/**
* Returns true if the field is set.
*
* @private
*/
function unsafeIsSet(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, field) {
const name = field.localName;
if (field.oneof) {
return target[field.oneof.localName].case === name;
}
if (field.presence != IMPLICIT) {
// Fields with explicit presence have properties on the prototype chain
// for default / zero values (except for proto3).
return (target[name] !== undefined &&
Object.prototype.hasOwnProperty.call(target, name));
}
switch (field.fieldKind) {
case "list":
return target[name].length > 0;
case "map":
return Object.keys(target[name]).length > 0;
case "scalar":
return !(0, scalar_js_1.isScalarZeroValue)(field.scalar, target[name]);
case "enum":
return target[name] !== field.enum.values[0].number;
}
throw new Error("message field with implicit presence");
}
/**
* Returns true if the field is set, but only for singular fields with explicit
* presence (proto2).
*
* @private
*/
function unsafeIsSetExplicit(target, localName) {
return (Object.prototype.hasOwnProperty.call(target, localName) &&
target[localName] !== undefined);
}
/**
* Return a field value, respecting oneof groups.
*
* @private
*/
function unsafeGet(target, field) {
if (field.oneof) {
const oneof = target[field.oneof.localName];
if (oneof.case === field.localName) {
return oneof.value;
}
return undefined;
}
return target[field.localName];
}
/**
* Set a field value, respecting oneof groups.
*
* @private
*/
function unsafeSet(target, field, value) {
if (field.oneof) {
target[field.oneof.localName] = {
case: field.localName,
value: value,
};
}
else {
target[field.localName] = value;
}
}
/**
* Resets the field, so that unsafeIsSet() will return false.
*
* @private
*/
function unsafeClear(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, field) {
const name = field.localName;
if (field.oneof) {
const oneofLocalName = field.oneof.localName;
if (target[oneofLocalName].case === name) {
target[oneofLocalName] = { case: undefined };
}
}
else if (field.presence != IMPLICIT) {
// Fields with explicit presence have properties on the prototype chain
// for default / zero values (except for proto3). By deleting their own
// property, the field is reset.
delete target[name];
}
else {
switch (field.fieldKind) {
case "map":
target[name] = {};
break;
case "list":
target[name] = [];
break;
case "enum":
target[name] = field.enum.values[0].number;
break;
case "scalar":
target[name] = (0, scalar_js_1.scalarZeroValue)(field.scalar, field.longAsString);
break;
}
}
}
import type { FileDescriptorProto, FileDescriptorSet } from "./wkt/gen/google/protobuf/descriptor_pb.js";
import { type DescEnum, type DescExtension, type DescFile, type DescMessage, type DescService, type SupportedEdition } from "./descriptors.js";
/**
* A set of descriptors for messages, enumerations, extensions,
* and services.
*/
export interface Registry {
readonly kind: "registry";
/**
* All types (message, enumeration, extension, or service) contained
* in this registry.
*/
[Symbol.iterator](): IterableIterator<DescMessage | DescEnum | DescExtension | DescService>;
/**
* Look up a type (message, enumeration, extension, or service) by
* its fully qualified name.
*/
get(typeName: string): DescMessage | DescEnum | DescExtension | DescService | undefined;
/**
* Look up a message descriptor by its fully qualified name.
*/
getMessage(typeName: string): DescMessage | undefined;
/**
* Look up an enumeration descriptor by its fully qualified name.
*/
getEnum(typeName: string): DescEnum | undefined;
/**
* Look up an extension descriptor by its fully qualified name.
*/
getExtension(typeName: string): DescExtension | undefined;
/**
* Look up an extension by the extendee - the message it extends - and
* the extension number.
*/
getExtensionFor(extendee: DescMessage, no: number): DescExtension | undefined;
/**
* Look up a service descriptor by its fully qualified name.
*/
getService(typeName: string): DescService | undefined;
}
/**
* A registry that allows adding and removing descriptors.
*/
export interface MutableRegistry extends Registry {
/**
* Adds the given descriptor - but not types nested within - to the registry.
*/
add(desc: DescMessage | DescEnum | DescExtension | DescService): void;
/**
* Remove the given descriptor - but not types nested within - from the registry.
*/
remove(desc: DescMessage | DescEnum | DescExtension | DescService): void;
}
/**
* A registry that includes files.
*/
export interface FileRegistry extends Registry {
/**
* All files in this registry.
*/
readonly files: Iterable<DescFile>;
/**
* Look up a file descriptor by file name.
*/
getFile(fileName: string): DescFile | undefined;
}
/**
* Create a registry from the given inputs.
*
* An input can be:
* - Any message, enum, service, or extension descriptor, which adds just the
* descriptor for this type.
* - A file descriptor, which adds all typed defined in this file.
* - A registry, which adds all types from the registry.
*
* For duplicate descriptors (same type name), the one given last wins.
*/
export declare function createRegistry(...input: (Registry | DescFile | DescMessage | DescEnum | DescExtension | DescService)[]): Registry;
/**
* Create a registry that allows adding and removing descriptors.
*/
export declare function createMutableRegistry(...input: (Registry | DescFile | DescMessage | DescEnum | DescExtension | DescService)[]): MutableRegistry;
/**
* Create a registry (including file descriptors) from a google.protobuf.FileDescriptorSet
* message.
*/
export declare function createFileRegistry(fileDescriptorSet: FileDescriptorSet): FileRegistry;
/**
* Create a registry (including file descriptors) from a google.protobuf.FileDescriptorProto
* message. For every import, the given resolver function is called.
*/
export declare function createFileRegistry(fileDescriptorProto: FileDescriptorProto, resolve: (protoFileName: string) => FileDescriptorProto | DescFile | undefined): FileRegistry;
/**
* Create a registry (including file descriptors) from one or more registries,
* merging them.
*/
export declare function createFileRegistry(...registries: FileRegistry[]): FileRegistry;
export declare const minimumEdition: SupportedEdition, maximumEdition: SupportedEdition;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.maximumEdition = exports.minimumEdition = void 0;
exports.createRegistry = createRegistry;
exports.createMutableRegistry = createMutableRegistry;
exports.createFileRegistry = createFileRegistry;
const descriptors_js_1 = require("./descriptors.js");
const text_format_js_1 = require("./wire/text-format.js");
const nested_types_js_1 = require("./reflect/nested-types.js");
const unsafe_js_1 = require("./reflect/unsafe.js");
const names_js_1 = require("./reflect/names.js");
/**
* Create a registry from the given inputs.
*
* An input can be:
* - Any message, enum, service, or extension descriptor, which adds just the
* descriptor for this type.
* - A file descriptor, which adds all typed defined in this file.
* - A registry, which adds all types from the registry.
*
* For duplicate descriptors (same type name), the one given last wins.
*/
function createRegistry(...input) {
return initBaseRegistry(input);
}
/**
* Create a registry that allows adding and removing descriptors.
*/
function createMutableRegistry(...input) {
const reg = initBaseRegistry(input);
return Object.assign(Object.assign({}, reg), { remove(desc) {
var _a;
if (desc.kind == "extension") {
(_a = reg.extendees.get(desc.extendee.typeName)) === null || _a === void 0 ? void 0 : _a.delete(desc.number);
}
reg.types.delete(desc.typeName);
} });
}
function createFileRegistry(...args) {
const registry = createBaseRegistry();
if (!args.length) {
return registry;
}
if ("$typeName" in args[0] &&
args[0].$typeName == "google.protobuf.FileDescriptorSet") {
for (const file of args[0].file) {
addFile(file, registry);
}
return registry;
}
if ("$typeName" in args[0]) {
const input = args[0];
const resolve = args[1];
const seen = new Set();
function recurseDeps(file) {
const deps = [];
for (const protoFileName of file.dependency) {
if (registry.getFile(protoFileName) != undefined) {
continue;
}
if (seen.has(protoFileName)) {
continue;
}
const dep = resolve(protoFileName);
if (!dep) {
throw new Error(`Unable to resolve ${protoFileName}, imported by ${file.name}`);
}
if ("kind" in dep) {
registry.addFile(dep, false, true);
}
else {
seen.add(dep.name);
deps.push(dep);
}
}
return deps.concat(...deps.map(recurseDeps));
}
for (const file of [input, ...recurseDeps(input)].reverse()) {
addFile(file, registry);
}
}
else {
for (const fileReg of args) {
for (const file of fileReg.files) {
registry.addFile(file);
}
}
}
return registry;
}
/**
* @private
*/
function createBaseRegistry() {
const types = new Map();
const extendees = new Map();
const files = new Map();
return {
kind: "registry",
types,
extendees,
[Symbol.iterator]() {
return types.values();
},
get files() {
return files.values();
},
addFile(file, skipTypes, withDeps) {
files.set(file.proto.name, file);
if (!skipTypes) {
for (const type of (0, nested_types_js_1.nestedTypes)(file)) {
this.add(type);
}
}
if (withDeps) {
for (const f of file.dependencies) {
this.addFile(f, skipTypes, withDeps);
}
}
},
add(desc) {
if (desc.kind == "extension") {
let numberToExt = extendees.get(desc.extendee.typeName);
if (!numberToExt) {
extendees.set(desc.extendee.typeName,
// biome-ignore lint/suspicious/noAssignInExpressions: no
(numberToExt = new Map()));
}
numberToExt.set(desc.number, desc);
}
types.set(desc.typeName, desc);
},
get(typeName) {
return types.get(typeName);
},
getFile(fileName) {
return files.get(fileName);
},
getMessage(typeName) {
const t = types.get(typeName);
return (t === null || t === void 0 ? void 0 : t.kind) == "message" ? t : undefined;
},
getEnum(typeName) {
const t = types.get(typeName);
return (t === null || t === void 0 ? void 0 : t.kind) == "enum" ? t : undefined;
},
getExtension(typeName) {
const t = types.get(typeName);
return (t === null || t === void 0 ? void 0 : t.kind) == "extension" ? t : undefined;
},
getExtensionFor(extendee, no) {
var _a;
return (_a = extendees.get(extendee.typeName)) === null || _a === void 0 ? void 0 : _a.get(no);
},
getService(typeName) {
const t = types.get(typeName);
return (t === null || t === void 0 ? void 0 : t.kind) == "service" ? t : undefined;
},
};
}
/**
* @private
*/
function initBaseRegistry(inputs) {
const registry = createBaseRegistry();
for (const input of inputs) {
switch (input.kind) {
case "registry":
for (const n of input) {
registry.add(n);
}
break;
case "file":
registry.addFile(input);
break;
default:
registry.add(input);
break;
}
}
return registry;
}
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name: Edition.$localName = $number;
const EDITION_PROTO2 = 998;
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name: Edition.$localName = $number;
const EDITION_PROTO3 = 999;
// bootstrap-inject google.protobuf.Edition.EDITION_UNSTABLE: const $name: Edition.$localName = $number;
const EDITION_UNSTABLE = 9999;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_STRING: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_STRING = 9;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_GROUP: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_GROUP = 10;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_MESSAGE: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_MESSAGE = 11;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_BYTES: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_BYTES = 12;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_ENUM: const $name: FieldDescriptorProto_Type.$localName = $number;
const TYPE_ENUM = 14;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED: const $name: FieldDescriptorProto_Label.$localName = $number;
const LABEL_REPEATED = 3;
// bootstrap-inject google.protobuf.FieldDescriptorProto.Label.LABEL_REQUIRED: const $name: FieldDescriptorProto_Label.$localName = $number;
const LABEL_REQUIRED = 2;
// bootstrap-inject google.protobuf.FieldOptions.JSType.JS_STRING: const $name: FieldOptions_JSType.$localName = $number;
const JS_STRING = 1;
// bootstrap-inject google.protobuf.MethodOptions.IdempotencyLevel.IDEMPOTENCY_UNKNOWN: const $name: MethodOptions_IdempotencyLevel.$localName = $number;
const IDEMPOTENCY_UNKNOWN = 0;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.EXPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const EXPLICIT = 1;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;
const LEGACY_REQUIRED = 3;
// bootstrap-inject google.protobuf.FeatureSet.RepeatedFieldEncoding.PACKED: const $name: FeatureSet_RepeatedFieldEncoding.$localName = $number;
const PACKED = 1;
// bootstrap-inject google.protobuf.FeatureSet.MessageEncoding.DELIMITED: const $name: FeatureSet_MessageEncoding.$localName = $number;
const DELIMITED = 2;
// bootstrap-inject google.protobuf.FeatureSet.EnumType.OPEN: const $name: FeatureSet_EnumType.$localName = $number;
const OPEN = 1;
// bootstrap-inject google.protobuf.FeatureSet.Utf8Validation.VERIFY: const $name: FeatureSet_Utf8Validation.$localName = $number;
const VERIFY = 2;
// biome-ignore format: want this to read well
// bootstrap-inject defaults: EDITION_PROTO2 to EDITION_2024: export const minimumEdition: SupportedEdition = $minimumEdition, maximumEdition: SupportedEdition = $maximumEdition;
// generated from protoc v34.0
exports.minimumEdition = 998, exports.maximumEdition = 1001;
const featureDefaults = {
// EDITION_PROTO2
998: {
fieldPresence: 1, // EXPLICIT,
enumType: 2, // CLOSED,
repeatedFieldEncoding: 2, // EXPANDED,
utf8Validation: 3, // NONE,
messageEncoding: 1, // LENGTH_PREFIXED,
jsonFormat: 2, // LEGACY_BEST_EFFORT,
enforceNamingStyle: 2, // STYLE_LEGACY,
defaultSymbolVisibility: 1, // EXPORT_ALL,
},
// EDITION_PROTO3
999: {
fieldPresence: 2, // IMPLICIT,
enumType: 1, // OPEN,
repeatedFieldEncoding: 1, // PACKED,
utf8Validation: 2, // VERIFY,
messageEncoding: 1, // LENGTH_PREFIXED,
jsonFormat: 1, // ALLOW,
enforceNamingStyle: 2, // STYLE_LEGACY,
defaultSymbolVisibility: 1, // EXPORT_ALL,
},
// EDITION_2023
1000: {
fieldPresence: 1, // EXPLICIT,
enumType: 1, // OPEN,
repeatedFieldEncoding: 1, // PACKED,
utf8Validation: 2, // VERIFY,
messageEncoding: 1, // LENGTH_PREFIXED,
jsonFormat: 1, // ALLOW,
enforceNamingStyle: 2, // STYLE_LEGACY,
defaultSymbolVisibility: 1, // EXPORT_ALL,
},
// EDITION_2024
1001: {
fieldPresence: 1, // EXPLICIT,
enumType: 1, // OPEN,
repeatedFieldEncoding: 1, // PACKED,
utf8Validation: 2, // VERIFY,
messageEncoding: 1, // LENGTH_PREFIXED,
jsonFormat: 1, // ALLOW,
enforceNamingStyle: 1, // STYLE2024,
defaultSymbolVisibility: 2, // EXPORT_TOP_LEVEL,
},
};
/**
* Create a descriptor for a file, add it to the registry.
*/
function addFile(proto, reg) {
var _a, _b;
const file = {
kind: "file",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
edition: getFileEdition(proto),
name: proto.name.replace(/\.proto$/, ""),
dependencies: findFileDependencies(proto, reg),
enums: [],
messages: [],
extensions: [],
services: [],
toString() {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- we asserted above
return `file ${proto.name}`;
},
};
const mapEntriesStore = new Map();
const mapEntries = {
get(typeName) {
return mapEntriesStore.get(typeName);
},
add(desc) {
var _a;
assert(((_a = desc.proto.options) === null || _a === void 0 ? void 0 : _a.mapEntry) === true);
mapEntriesStore.set(desc.typeName, desc);
},
};
for (const enumProto of proto.enumType) {
addEnum(enumProto, file, undefined, reg);
}
for (const messageProto of proto.messageType) {
addMessage(messageProto, file, undefined, reg, mapEntries);
}
for (const serviceProto of proto.service) {
addService(serviceProto, file, reg);
}
addExtensions(file, reg);
for (const mapEntry of mapEntriesStore.values()) {
// to create a map field, we need access to the map entry's fields
addFields(mapEntry, reg, mapEntries);
}
for (const message of file.messages) {
addFields(message, reg, mapEntries);
addExtensions(message, reg);
}
reg.addFile(file, true);
}
/**
* Create descriptors for extensions, and add them to the message / file,
* and to our cart.
* Recurses into nested types.
*/
function addExtensions(desc, reg) {
switch (desc.kind) {
case "file":
for (const proto of desc.proto.extension) {
const ext = newField(proto, desc, reg);
desc.extensions.push(ext);
reg.add(ext);
}
break;
case "message":
for (const proto of desc.proto.extension) {
const ext = newField(proto, desc, reg);
desc.nestedExtensions.push(ext);
reg.add(ext);
}
for (const message of desc.nestedMessages) {
addExtensions(message, reg);
}
break;
}
}
/**
* Create descriptors for fields and oneof groups, and add them to the message.
* Recurses into nested types.
*/
function addFields(message, reg, mapEntries) {
const allOneofs = message.proto.oneofDecl.map((proto) => newOneof(proto, message));
const oneofsSeen = new Set();
for (const proto of message.proto.field) {
const oneof = findOneof(proto, allOneofs);
const field = newField(proto, message, reg, oneof, mapEntries);
message.fields.push(field);
message.field[field.localName] = field;
if (oneof === undefined) {
message.members.push(field);
}
else {
oneof.fields.push(field);
if (!oneofsSeen.has(oneof)) {
oneofsSeen.add(oneof);
message.members.push(oneof);
}
}
}
for (const oneof of allOneofs.filter((o) => oneofsSeen.has(o))) {
message.oneofs.push(oneof);
}
for (const child of message.nestedMessages) {
addFields(child, reg, mapEntries);
}
}
/**
* Create a descriptor for an enumeration, and add it our cart and to the
* parent type, if any.
*/
function addEnum(proto, file, parent, reg) {
var _a, _b, _c, _d, _e;
const sharedPrefix = findEnumSharedPrefix(proto.name, proto.value);
const desc = {
kind: "enum",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
parent,
open: true,
name: proto.name,
typeName: makeTypeName(proto, parent, file),
value: {},
values: [],
sharedPrefix,
toString() {
return `enum ${this.typeName}`;
},
};
desc.open = isEnumOpen(desc);
reg.add(desc);
for (const p of proto.value) {
const name = p.name;
desc.values.push(
// biome-ignore lint/suspicious/noAssignInExpressions: no
(desc.value[p.number] = {
kind: "enum_value",
proto: p,
deprecated: (_d = (_c = p.options) === null || _c === void 0 ? void 0 : _c.deprecated) !== null && _d !== void 0 ? _d : false,
parent: desc,
name,
localName: (0, names_js_1.safeObjectProperty)(sharedPrefix == undefined
? name
: name.substring(sharedPrefix.length)),
number: p.number,
toString() {
return `enum value ${desc.typeName}.${name}`;
},
}));
}
((_e = parent === null || parent === void 0 ? void 0 : parent.nestedEnums) !== null && _e !== void 0 ? _e : file.enums).push(desc);
}
/**
* Create a descriptor for a message, including nested types, and add it to our
* cart. Note that this does not create descriptors fields.
*/
function addMessage(proto, file, parent, reg, mapEntries) {
var _a, _b, _c, _d;
const desc = {
kind: "message",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
parent,
name: proto.name,
typeName: makeTypeName(proto, parent, file),
fields: [],
field: {},
oneofs: [],
members: [],
nestedEnums: [],
nestedMessages: [],
nestedExtensions: [],
toString() {
return `message ${this.typeName}`;
},
};
if (((_c = proto.options) === null || _c === void 0 ? void 0 : _c.mapEntry) === true) {
mapEntries.add(desc);
}
else {
((_d = parent === null || parent === void 0 ? void 0 : parent.nestedMessages) !== null && _d !== void 0 ? _d : file.messages).push(desc);
reg.add(desc);
}
for (const enumProto of proto.enumType) {
addEnum(enumProto, file, desc, reg);
}
for (const messageProto of proto.nestedType) {
addMessage(messageProto, file, desc, reg, mapEntries);
}
}
/**
* Create a descriptor for a service, including methods, and add it to our
* cart.
*/
function addService(proto, file, reg) {
var _a, _b;
const desc = {
kind: "service",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
name: proto.name,
typeName: makeTypeName(proto, undefined, file),
methods: [],
method: {},
toString() {
return `service ${this.typeName}`;
},
};
file.services.push(desc);
reg.add(desc);
for (const methodProto of proto.method) {
const method = newMethod(methodProto, desc, reg);
desc.methods.push(method);
desc.method[method.localName] = method;
}
}
/**
* Create a descriptor for a method.
*/
function newMethod(proto, parent, reg) {
var _a, _b, _c, _d;
let methodKind;
if (proto.clientStreaming && proto.serverStreaming) {
methodKind = "bidi_streaming";
}
else if (proto.clientStreaming) {
methodKind = "client_streaming";
}
else if (proto.serverStreaming) {
methodKind = "server_streaming";
}
else {
methodKind = "unary";
}
const input = reg.getMessage(trimLeadingDot(proto.inputType));
const output = reg.getMessage(trimLeadingDot(proto.outputType));
assert(input, `invalid MethodDescriptorProto: input_type ${proto.inputType} not found`);
assert(output, `invalid MethodDescriptorProto: output_type ${proto.inputType} not found`);
const name = proto.name;
return {
kind: "rpc",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
parent,
name,
localName: (0, names_js_1.safeObjectProperty)(name.length
? (0, names_js_1.safeObjectProperty)(name[0].toLowerCase() + name.substring(1))
: name),
methodKind,
input,
output,
idempotency: (_d = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.idempotencyLevel) !== null && _d !== void 0 ? _d : IDEMPOTENCY_UNKNOWN,
toString() {
return `rpc ${parent.typeName}.${name}`;
},
};
}
/**
* Create a descriptor for a oneof group.
*/
function newOneof(proto, parent) {
return {
kind: "oneof",
proto,
deprecated: false,
parent,
fields: [],
name: proto.name,
localName: (0, names_js_1.safeObjectProperty)((0, names_js_1.protoCamelCase)(proto.name)),
toString() {
return `oneof ${parent.typeName}.${this.name}`;
},
};
}
function newField(proto, parentOrFile, reg, oneof, mapEntries) {
var _a, _b, _c;
const isExtension = mapEntries === undefined;
const field = {
kind: "field",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
name: proto.name,
number: proto.number,
scalar: undefined,
message: undefined,
enum: undefined,
presence: getFieldPresence(proto, oneof, isExtension, parentOrFile),
utf8Validation: isUtf8Validated(proto, parentOrFile),
listKind: undefined,
mapKind: undefined,
mapKey: undefined,
delimitedEncoding: undefined,
packed: undefined,
longAsString: false,
getDefaultValue: undefined,
};
if (isExtension) {
// extension field
const file = parentOrFile.kind == "file" ? parentOrFile : parentOrFile.file;
const parent = parentOrFile.kind == "file" ? undefined : parentOrFile;
const typeName = makeTypeName(proto, parent, file);
field.kind = "extension";
field.file = file;
field.parent = parent;
field.oneof = undefined;
field.typeName = typeName;
field.jsonName = `[${typeName}]`; // option json_name is not allowed on extension fields
field.toString = () => `extension ${typeName}`;
const extendee = reg.getMessage(trimLeadingDot(proto.extendee));
assert(extendee, `invalid FieldDescriptorProto: extendee ${proto.extendee} not found`);
field.extendee = extendee;
}
else {
// regular field
const parent = parentOrFile;
assert(parent.kind == "message");
field.parent = parent;
field.oneof = oneof;
field.localName = oneof
? (0, names_js_1.protoCamelCase)(proto.name)
: (0, names_js_1.safeObjectProperty)((0, names_js_1.protoCamelCase)(proto.name));
field.jsonName = proto.jsonName;
field.toString = () => `field ${parent.typeName}.${proto.name}`;
}
const label = proto.label;
const type = proto.type;
const jstype = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.jstype;
if (label === LABEL_REPEATED) {
// list or map field
const mapEntry = type == TYPE_MESSAGE
? mapEntries === null || mapEntries === void 0 ? void 0 : mapEntries.get(trimLeadingDot(proto.typeName))
: undefined;
if (mapEntry) {
// map field
field.fieldKind = "map";
const { key, value } = findMapEntryFields(mapEntry);
field.mapKey = key.scalar;
field.mapKind = value.fieldKind;
field.message = value.message;
field.delimitedEncoding = false; // map fields are always LENGTH_PREFIXED
field.enum = value.enum;
field.scalar = value.scalar;
return field;
}
// list field
field.fieldKind = "list";
switch (type) {
case TYPE_MESSAGE:
case TYPE_GROUP:
field.listKind = "message";
field.message = reg.getMessage(trimLeadingDot(proto.typeName));
assert(field.message);
field.delimitedEncoding = isDelimitedEncoding(proto, parentOrFile);
break;
case TYPE_ENUM:
field.listKind = "enum";
field.enum = reg.getEnum(trimLeadingDot(proto.typeName));
assert(field.enum);
break;
default:
field.listKind = "scalar";
field.scalar = type;
field.longAsString = jstype == JS_STRING;
break;
}
field.packed = isPackedField(proto, parentOrFile);
return field;
}
// singular
switch (type) {
case TYPE_MESSAGE:
case TYPE_GROUP:
field.fieldKind = "message";
field.message = reg.getMessage(trimLeadingDot(proto.typeName));
assert(field.message, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
field.delimitedEncoding = isDelimitedEncoding(proto, parentOrFile);
field.getDefaultValue = () => undefined;
break;
case TYPE_ENUM: {
const enumeration = reg.getEnum(trimLeadingDot(proto.typeName));
assert(enumeration !== undefined, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
field.fieldKind = "enum";
field.enum = reg.getEnum(trimLeadingDot(proto.typeName));
field.getDefaultValue = () => {
return (0, unsafe_js_1.unsafeIsSetExplicit)(proto, "defaultValue")
? (0, text_format_js_1.parseTextFormatEnumValue)(enumeration, proto.defaultValue)
: undefined;
};
break;
}
default: {
field.fieldKind = "scalar";
field.scalar = type;
field.longAsString = jstype == JS_STRING;
field.getDefaultValue = () => {
return (0, unsafe_js_1.unsafeIsSetExplicit)(proto, "defaultValue")
? (0, text_format_js_1.parseTextFormatScalarValue)(type, proto.defaultValue)
: undefined;
};
break;
}
}
return field;
}
/**
* Parse the "syntax" and "edition" fields, returning one of the supported
* editions.
*/
function getFileEdition(proto) {
switch (proto.syntax) {
case "":
case "proto2":
return EDITION_PROTO2;
case "proto3":
return EDITION_PROTO3;
case "editions":
// EDITION_UNSTABLE is a sandbox for in-development features. Collapse
// it to maximumEdition so SupportedEdition and feature resolution do
// not leak the test-only edition to users.
if (proto.edition === EDITION_UNSTABLE) {
return exports.maximumEdition;
}
if (proto.edition in featureDefaults) {
return proto.edition;
}
throw new Error(`${proto.name}: unsupported edition`);
default:
throw new Error(`${proto.name}: unsupported syntax "${proto.syntax}"`);
}
}
/**
* Resolve dependencies of FileDescriptorProto to DescFile.
*/
function findFileDependencies(proto, reg) {
return proto.dependency.map((wantName) => {
const dep = reg.getFile(wantName);
if (!dep) {
throw new Error(`Cannot find ${wantName}, imported by ${proto.name}`);
}
return dep;
});
}
/**
* Finds a prefix shared by enum values, for example `my_enum_` for
* `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`.
*/
function findEnumSharedPrefix(enumName, values) {
const prefix = camelToSnakeCase(enumName) + "_";
for (const value of values) {
if (!value.name.toLowerCase().startsWith(prefix)) {
return undefined;
}
const shortName = value.name.substring(prefix.length);
if (shortName.length == 0) {
return undefined;
}
if (/^\d/.test(shortName)) {
// identifiers must not start with numbers
return undefined;
}
}
return prefix;
}
/**
* Converts lowerCamelCase or UpperCamelCase into lower_snake_case.
* This is used to find shared prefixes in an enum.
*/
function camelToSnakeCase(camel) {
return (camel.substring(0, 1) + camel.substring(1).replace(/[A-Z]/g, (c) => "_" + c)).toLowerCase();
}
/**
* Create a fully qualified name for a protobuf type or extension field.
*
* The fully qualified name for messages, enumerations, and services is
* constructed by concatenating the package name (if present), parent
* message names (for nested types), and the type name. We omit the leading
* dot added by protobuf compilers. Examples:
* - mypackage.MyMessage
* - mypackage.MyMessage.NestedMessage
*
* The fully qualified name for extension fields is constructed by
* concatenating the package name (if present), parent message names (for
* extensions declared within a message), and the field name. Examples:
* - mypackage.extfield
* - mypackage.MyMessage.extfield
*/
function makeTypeName(proto, parent, file) {
let typeName;
if (parent) {
typeName = `${parent.typeName}.${proto.name}`;
}
else if (file.proto.package.length > 0) {
typeName = `${file.proto.package}.${proto.name}`;
}
else {
typeName = `${proto.name}`;
}
return typeName;
}
/**
* Remove the leading dot from a fully qualified type name.
*/
function trimLeadingDot(typeName) {
return typeName.startsWith(".") ? typeName.substring(1) : typeName;
}
/**
* Did the user put the field in a oneof group?
* Synthetic oneofs for proto3 optionals are ignored.
*/
function findOneof(proto, allOneofs) {
if (!(0, unsafe_js_1.unsafeIsSetExplicit)(proto, "oneofIndex")) {
return undefined;
}
if (proto.proto3Optional) {
return undefined;
}
const oneof = allOneofs[proto.oneofIndex];
assert(oneof, `invalid FieldDescriptorProto: oneof #${proto.oneofIndex} for field #${proto.number} not found`);
return oneof;
}
/**
* Presence of the field.
* See https://protobuf.dev/programming-guides/field_presence/
*/
function getFieldPresence(proto, oneof, isExtension, parent) {
if (proto.label == LABEL_REQUIRED) {
// proto2 required is LEGACY_REQUIRED
return LEGACY_REQUIRED;
}
if (proto.label == LABEL_REPEATED) {
// repeated fields (including maps) do not track presence
return IMPLICIT;
}
if (!!oneof || proto.proto3Optional) {
// oneof is always explicit
return EXPLICIT;
}
if (isExtension) {
// extensions always track presence
return EXPLICIT;
}
const resolved = resolveFeature("fieldPresence", { proto, parent });
if (resolved == IMPLICIT &&
(proto.type == TYPE_MESSAGE || proto.type == TYPE_GROUP)) {
// singular message field cannot be implicit
return EXPLICIT;
}
return resolved;
}
/**
* Pack this repeated field?
*/
function isPackedField(proto, parent) {
if (proto.label != LABEL_REPEATED) {
return false;
}
switch (proto.type) {
case TYPE_STRING:
case TYPE_BYTES:
case TYPE_GROUP:
case TYPE_MESSAGE:
// length-delimited types cannot be packed
return false;
}
const o = proto.options;
if (o && (0, unsafe_js_1.unsafeIsSetExplicit)(o, "packed")) {
// prefer the field option over edition features
return o.packed;
}
return (PACKED ==
resolveFeature("repeatedFieldEncoding", {
proto,
parent,
}));
}
/**
* Find the key and value fields of a synthetic map entry message.
*/
function findMapEntryFields(mapEntry) {
const key = mapEntry.fields.find((f) => f.number === 1);
const value = mapEntry.fields.find((f) => f.number === 2);
assert(key &&
key.fieldKind == "scalar" &&
key.scalar != descriptors_js_1.ScalarType.BYTES &&
key.scalar != descriptors_js_1.ScalarType.FLOAT &&
key.scalar != descriptors_js_1.ScalarType.DOUBLE &&
value &&
value.fieldKind != "list" &&
value.fieldKind != "map");
return { key, value };
}
/**
* Enumerations can be open or closed.
* See https://protobuf.dev/programming-guides/enum/
*/
function isEnumOpen(desc) {
var _a;
return (OPEN ==
resolveFeature("enumType", {
proto: desc.proto,
parent: (_a = desc.parent) !== null && _a !== void 0 ? _a : desc.file,
}));
}
/**
* Encode the message delimited (a.k.a. proto2 group encoding), or
* length-prefixed?
*/
function isDelimitedEncoding(proto, parent) {
if (proto.type == TYPE_GROUP) {
return true;
}
return (DELIMITED ==
resolveFeature("messageEncoding", {
proto,
parent,
}));
}
/**
* Reject invalid UTF-8 when reading string fields from the binary wire format?
* Driven by the resolved `utf8_validation` feature: VERIFY (proto3 / editions
* 2023+ default) enforces; NONE (proto2 default) does not.
*/
function isUtf8Validated(proto, parent) {
return (VERIFY ==
resolveFeature("utf8Validation", {
proto,
parent,
}));
}
function resolveFeature(name, ref) {
var _a, _b;
const featureSet = (_a = ref.proto.options) === null || _a === void 0 ? void 0 : _a.features;
if (featureSet) {
const val = featureSet[name];
if (val != 0) {
return val;
}
}
if ("kind" in ref) {
if (ref.kind == "message") {
return resolveFeature(name, (_b = ref.parent) !== null && _b !== void 0 ? _b : ref.file);
}
const editionDefaults = featureDefaults[ref.edition];
if (!editionDefaults) {
throw new Error(`feature default for edition ${ref.edition} not found`);
}
return editionDefaults[name];
}
return resolveFeature(name, ref.parent);
}
/**
* Assert that condition is truthy or throw error (with message)
*/
function assert(condition, msg) {
if (!condition) {
throw new Error(msg);
}
}
import type { MessageShape } from "./types.js";
import { BinaryWriter } from "./wire/binary-encoding.js";
import { type DescField, type DescMessage } from "./descriptors.js";
import type { ReflectMessage } from "./reflect/index.js";
/**
* Options for serializing to binary data.
*
* V1 also had the option `readerFactory` for using a custom implementation to
* encode to binary.
*/
export interface BinaryWriteOptions {
/**
* Include unknown fields in the serialized output? The default behavior
* is to retain unknown fields and include them in the serialized output.
*
* For more details see https://developers.google.com/protocol-buffers/docs/proto3#unknowns
*/
writeUnknownFields: boolean;
}
export declare function toBinary<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>, options?: Partial<BinaryWriteOptions>): Uint8Array<ArrayBuffer>;
/**
* @private
*/
export declare function writeField(writer: BinaryWriter, opts: BinaryWriteOptions, msg: ReflectMessage, field: DescField): void;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBinary = toBinary;
exports.writeField = writeField;
const reflect_js_1 = require("./reflect/reflect.js");
const binary_encoding_js_1 = require("./wire/binary-encoding.js");
const descriptors_js_1 = require("./descriptors.js");
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;
const LEGACY_REQUIRED = 3;
// Default options for serializing binary data.
const writeDefaults = {
writeUnknownFields: true,
};
function makeWriteOptions(options) {
return options ? Object.assign(Object.assign({}, writeDefaults), options) : writeDefaults;
}
function toBinary(schema, message, options) {
return writeFields(new binary_encoding_js_1.BinaryWriter(), makeWriteOptions(options), (0, reflect_js_1.reflect)(schema, message)).finish();
}
function writeFields(writer, opts, msg) {
var _a;
for (const f of msg.sortedFields) {
if (!msg.isSet(f)) {
if (f.presence == LEGACY_REQUIRED) {
throw new Error(`cannot encode ${f} to binary: required field not set`);
}
continue;
}
writeField(writer, opts, msg, f);
}
if (opts.writeUnknownFields) {
for (const { no, wireType, data } of (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : []) {
writer.tag(no, wireType).raw(data);
}
}
return writer;
}
/**
* @private
*/
function writeField(writer, opts, msg, field) {
var _a;
switch (field.fieldKind) {
case "scalar":
case "enum":
writeScalar(writer, msg.desc.typeName, field.name, (_a = field.scalar) !== null && _a !== void 0 ? _a : descriptors_js_1.ScalarType.INT32, field.number, msg.get(field));
break;
case "list":
writeListField(writer, opts, field, msg.get(field));
break;
case "message":
writeMessageField(writer, opts, field, msg.get(field));
break;
case "map":
for (const [key, val] of msg.get(field)) {
writeMapEntry(writer, opts, field, key, val);
}
break;
}
}
function writeScalar(writer, msgName, fieldName, scalarType, fieldNo, value) {
writeScalarValue(writer.tag(fieldNo, writeTypeOfScalar(scalarType)), msgName, fieldName, scalarType, value);
}
function writeMessageField(writer, opts, field, message) {
if (field.delimitedEncoding) {
writeFields(writer.tag(field.number, binary_encoding_js_1.WireType.StartGroup), opts, message).tag(field.number, binary_encoding_js_1.WireType.EndGroup);
}
else {
writeFields(writer.tag(field.number, binary_encoding_js_1.WireType.LengthDelimited).fork(), opts, message).join();
}
}
function writeListField(writer, opts, field, list) {
var _a;
if (field.listKind == "message") {
for (const item of list) {
writeMessageField(writer, opts, field, item);
}
return;
}
const scalarType = (_a = field.scalar) !== null && _a !== void 0 ? _a : descriptors_js_1.ScalarType.INT32;
if (field.packed) {
if (!list.size) {
return;
}
writer.tag(field.number, binary_encoding_js_1.WireType.LengthDelimited).fork();
for (const item of list) {
writeScalarValue(writer, field.parent.typeName, field.name, scalarType, item);
}
writer.join();
return;
}
for (const item of list) {
writeScalar(writer, field.parent.typeName, field.name, scalarType, field.number, item);
}
}
function writeMapEntry(writer, opts, field, key, value) {
var _a;
writer.tag(field.number, binary_encoding_js_1.WireType.LengthDelimited).fork();
// write key, expecting key field number = 1
writeScalar(writer, field.parent.typeName, field.name, field.mapKey, 1, key);
// write value, expecting value field number = 2
switch (field.mapKind) {
case "scalar":
case "enum":
writeScalar(writer, field.parent.typeName, field.name, (_a = field.scalar) !== null && _a !== void 0 ? _a : descriptors_js_1.ScalarType.INT32, 2, value);
break;
case "message":
writeFields(writer.tag(2, binary_encoding_js_1.WireType.LengthDelimited).fork(), opts, value).join();
break;
}
writer.join();
}
function writeScalarValue(writer, msgName, fieldName, type, value) {
try {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
writer.string(value);
break;
case descriptors_js_1.ScalarType.BOOL:
writer.bool(value);
break;
case descriptors_js_1.ScalarType.DOUBLE:
writer.double(value);
break;
case descriptors_js_1.ScalarType.FLOAT:
writer.float(value);
break;
case descriptors_js_1.ScalarType.INT32:
writer.int32(value);
break;
case descriptors_js_1.ScalarType.INT64:
writer.int64(value);
break;
case descriptors_js_1.ScalarType.UINT64:
writer.uint64(value);
break;
case descriptors_js_1.ScalarType.FIXED64:
writer.fixed64(value);
break;
case descriptors_js_1.ScalarType.BYTES:
writer.bytes(value);
break;
case descriptors_js_1.ScalarType.FIXED32:
writer.fixed32(value);
break;
case descriptors_js_1.ScalarType.SFIXED32:
writer.sfixed32(value);
break;
case descriptors_js_1.ScalarType.SFIXED64:
writer.sfixed64(value);
break;
case descriptors_js_1.ScalarType.SINT64:
writer.sint64(value);
break;
case descriptors_js_1.ScalarType.UINT32:
writer.uint32(value);
break;
case descriptors_js_1.ScalarType.SINT32:
writer.sint32(value);
break;
}
}
catch (e) {
if (e instanceof Error) {
throw new Error(`cannot encode field ${msgName}.${fieldName} to binary: ${e.message}`);
}
throw e;
}
}
function writeTypeOfScalar(type) {
switch (type) {
case descriptors_js_1.ScalarType.BYTES:
case descriptors_js_1.ScalarType.STRING:
return binary_encoding_js_1.WireType.LengthDelimited;
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SFIXED64:
return binary_encoding_js_1.WireType.Bit64;
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.FLOAT:
return binary_encoding_js_1.WireType.Bit32;
default:
return binary_encoding_js_1.WireType.Varint;
}
}
import { type DescEnum, type DescMessage } from "./descriptors.js";
import type { JsonValue } from "./json-value.js";
import type { Registry } from "./registry.js";
import type { EnumJsonType, EnumShape, MessageJsonType, MessageShape } from "./types.js";
/**
* Options for serializing to JSON.
*/
export interface JsonWriteOptions {
/**
* By default, fields with implicit presence are not serialized if they are
* unset. For example, an empty list field or a proto3 int32 field with 0 is
* not serialized. With this option enabled, such fields are included in the
* output.
*/
alwaysEmitImplicit: boolean;
/**
* Emit enum values as integers instead of strings: The name of an enum
* value is used by default in JSON output. An option may be provided to
* use the numeric value of the enum value instead.
*/
enumAsInteger: boolean;
/**
* Use proto field name instead of lowerCamelCase name: By default proto3
* JSON printer should convert the field name to lowerCamelCase and use
* that as the JSON name. An implementation may provide an option to use
* proto field name as the JSON name instead. Proto3 JSON parsers are
* required to accept both the converted lowerCamelCase name and the proto
* field name.
*/
useProtoFieldName: boolean;
/**
* This option is required to write `google.protobuf.Any` and extensions
* to JSON format.
*/
registry?: Registry | undefined;
}
/**
* Options for serializing to JSON.
*/
export interface JsonWriteStringOptions extends JsonWriteOptions {
/**
* Format JSON with indentation. Indicates the number of space characters to
* be used as indentation.
*
* This option is passed to JSON.stringify as `space`.
*/
prettySpaces: number;
}
/**
* Serialize the message to a JSON value, a JavaScript value that can be
* passed to JSON.stringify().
*/
export declare function toJson<Desc extends DescMessage, Opts extends Partial<JsonWriteOptions> | undefined = undefined>(schema: Desc, message: MessageShape<Desc>, options?: Opts): ToJson<Desc, Opts>;
type ToJson<Desc extends DescMessage, Opts extends undefined | Partial<JsonWriteOptions>> = Opts extends undefined | {
alwaysEmitImplicit?: false;
enumAsInteger?: false;
useProtoFieldName?: false;
} ? MessageJsonType<Desc> : JsonValue;
/**
* Serialize the message to a JSON string.
*/
export declare function toJsonString<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>, options?: Partial<JsonWriteStringOptions>): string;
/**
* Serialize a single enum value to JSON.
*/
export declare function enumToJson<Desc extends DescEnum>(descEnum: Desc, value: EnumShape<Desc>): EnumJsonType<Desc>;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.toJson = toJson;
exports.toJsonString = toJsonString;
exports.enumToJson = enumToJson;
const descriptors_js_1 = require("./descriptors.js");
const names_js_1 = require("./reflect/names.js");
const reflect_js_1 = require("./reflect/reflect.js");
const index_js_1 = require("./wkt/index.js");
const wrappers_js_1 = require("./wkt/wrappers.js");
const index_js_2 = require("./wire/index.js");
const extensions_js_1 = require("./extensions.js");
const reflect_check_js_1 = require("./reflect/reflect-check.js");
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;
const LEGACY_REQUIRED = 3;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
// Default options for serializing to JSON.
const jsonWriteDefaults = {
alwaysEmitImplicit: false,
enumAsInteger: false,
useProtoFieldName: false,
};
function makeWriteOptions(options) {
return options ? Object.assign(Object.assign({}, jsonWriteDefaults), options) : jsonWriteDefaults;
}
/**
* Serialize the message to a JSON value, a JavaScript value that can be
* passed to JSON.stringify().
*/
function toJson(schema, message, options) {
return reflectToJson((0, reflect_js_1.reflect)(schema, message), makeWriteOptions(options));
}
/**
* Serialize the message to a JSON string.
*/
function toJsonString(schema, message, options) {
var _a;
const jsonValue = toJson(schema, message, options);
return JSON.stringify(jsonValue, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
}
/**
* Serialize a single enum value to JSON.
*/
function enumToJson(descEnum, value) {
var _a;
if (descEnum.typeName == "google.protobuf.NullValue") {
return null;
}
const name = (_a = descEnum.value[value]) === null || _a === void 0 ? void 0 : _a.name;
if (name === undefined) {
throw new Error(`${value} is not a value in ${descEnum}`);
}
return name;
}
function reflectToJson(msg, opts) {
var _a;
const wktJson = tryWktToJson(msg, opts);
if (wktJson !== undefined)
return wktJson;
const json = {};
for (const f of msg.sortedFields) {
if (!msg.isSet(f)) {
if (f.presence == LEGACY_REQUIRED) {
throw new Error(`cannot encode ${f} to JSON: required field not set`);
}
if (!opts.alwaysEmitImplicit || f.presence !== IMPLICIT) {
// Fields with implicit presence omit zero values (e.g. empty string) by default
continue;
}
}
const jsonValue = fieldToJson(f, msg.get(f), opts);
if (jsonValue !== undefined) {
json[jsonName(f, opts)] = jsonValue;
}
}
if (opts.registry) {
const tagSeen = new Set();
for (const { no } of (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : []) {
// Same tag can appear multiple times, so we
// keep track and skip identical ones.
if (!tagSeen.has(no)) {
tagSeen.add(no);
const extension = opts.registry.getExtensionFor(msg.desc, no);
if (!extension) {
continue;
}
const value = (0, extensions_js_1.getExtension)(msg.message, extension);
const [container, field] = (0, extensions_js_1.createExtensionContainer)(extension, value);
const jsonValue = fieldToJson(field, container.get(field), opts);
if (jsonValue !== undefined) {
json[extension.jsonName] = jsonValue;
}
}
}
}
return json;
}
function fieldToJson(f, val, opts) {
switch (f.fieldKind) {
case "scalar":
return scalarToJson(f, val);
case "message":
return reflectToJson(val, opts);
case "enum":
return enumToJsonInternal(f.enum, val, opts.enumAsInteger);
case "list":
return listToJson(val, opts);
case "map":
return mapToJson(val, opts);
}
}
function mapToJson(map, opts) {
const f = map.field();
const jsonObj = {};
switch (f.mapKind) {
case "scalar":
for (const [entryKey, entryValue] of map) {
jsonObj[entryKey] = scalarToJson(f, entryValue);
}
break;
case "message":
for (const [entryKey, entryValue] of map) {
jsonObj[entryKey] = reflectToJson(entryValue, opts);
}
break;
case "enum":
for (const [entryKey, entryValue] of map) {
jsonObj[entryKey] = enumToJsonInternal(f.enum, entryValue, opts.enumAsInteger);
}
break;
}
return opts.alwaysEmitImplicit || map.size > 0 ? jsonObj : undefined;
}
function listToJson(list, opts) {
const f = list.field();
const jsonArr = [];
switch (f.listKind) {
case "scalar":
for (const item of list) {
jsonArr.push(scalarToJson(f, item));
}
break;
case "enum":
for (const item of list) {
jsonArr.push(enumToJsonInternal(f.enum, item, opts.enumAsInteger));
}
break;
case "message":
for (const item of list) {
jsonArr.push(reflectToJson(item, opts));
}
break;
}
return opts.alwaysEmitImplicit || jsonArr.length > 0 ? jsonArr : undefined;
}
function enumToJsonInternal(desc, value, enumAsInteger) {
var _a;
if (typeof value != "number") {
throw new Error(`cannot encode ${desc} to JSON: expected number, got ${(0, reflect_check_js_1.formatVal)(value)}`);
}
if (desc.typeName == "google.protobuf.NullValue") {
return null;
}
if (enumAsInteger) {
return value;
}
const val = desc.value[value];
return (_a = val === null || val === void 0 ? void 0 : val.name) !== null && _a !== void 0 ? _a : value; // if we don't know the enum value, just return the number
}
function scalarToJson(field, value) {
var _a, _b, _c, _d, _e, _f;
switch (field.scalar) {
// int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
if (typeof value != "number") {
throw new Error(`cannot encode ${field} to JSON: ${(_a = (0, reflect_check_js_1.checkField)(field, value)) === null || _a === void 0 ? void 0 : _a.message}`);
}
return value;
// float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
// Either numbers or strings are accepted. Exponent notation is also accepted.
case descriptors_js_1.ScalarType.FLOAT:
case descriptors_js_1.ScalarType.DOUBLE: // eslint-disable-line no-fallthrough
if (typeof value != "number") {
throw new Error(`cannot encode ${field} to JSON: ${(_b = (0, reflect_check_js_1.checkField)(field, value)) === null || _b === void 0 ? void 0 : _b.message}`);
}
if (Number.isNaN(value))
return "NaN";
if (value === Number.POSITIVE_INFINITY)
return "Infinity";
if (value === Number.NEGATIVE_INFINITY)
return "-Infinity";
return value;
// string:
case descriptors_js_1.ScalarType.STRING:
if (typeof value != "string") {
throw new Error(`cannot encode ${field} to JSON: ${(_c = (0, reflect_check_js_1.checkField)(field, value)) === null || _c === void 0 ? void 0 : _c.message}`);
}
return value;
// bool:
case descriptors_js_1.ScalarType.BOOL:
if (typeof value != "boolean") {
throw new Error(`cannot encode ${field} to JSON: ${(_d = (0, reflect_check_js_1.checkField)(field, value)) === null || _d === void 0 ? void 0 : _d.message}`);
}
return value;
// JSON value will be a decimal string. Either numbers or strings are accepted.
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
if (typeof value == "bigint" ||
typeof value == "string" ||
(typeof value == "number" && Number.isInteger(value))) {
return value.toString();
}
throw new Error(`cannot encode ${field} to JSON: ${(_e = (0, reflect_check_js_1.checkField)(field, value)) === null || _e === void 0 ? void 0 : _e.message}`);
// bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
// Either standard or URL-safe base64 encoding with/without paddings are accepted.
case descriptors_js_1.ScalarType.BYTES:
if (value instanceof Uint8Array) {
return (0, index_js_2.base64Encode)(value);
}
throw new Error(`cannot encode ${field} to JSON: ${(_f = (0, reflect_check_js_1.checkField)(field, value)) === null || _f === void 0 ? void 0 : _f.message}`);
}
}
function jsonName(f, opts) {
return opts.useProtoFieldName ? f.name : f.jsonName;
}
// returns a json value if wkt, otherwise returns undefined.
function tryWktToJson(msg, opts) {
if (!msg.desc.typeName.startsWith("google.protobuf.")) {
return undefined;
}
switch (msg.desc.typeName) {
case "google.protobuf.Any":
return anyToJson(msg.message, opts);
case "google.protobuf.Timestamp":
return timestampToJson(msg.message);
case "google.protobuf.Duration":
return durationToJson(msg.message);
case "google.protobuf.FieldMask":
return fieldMaskToJson(msg.message);
case "google.protobuf.Struct":
return structToJson(msg.message);
case "google.protobuf.Value":
return valueToJson(msg.message);
case "google.protobuf.ListValue":
return listValueToJson(msg.message);
default:
if ((0, wrappers_js_1.isWrapperDesc)(msg.desc)) {
const valueField = msg.desc.fields[0];
return scalarToJson(valueField, msg.get(valueField));
}
return undefined;
}
}
function anyToJson(val, opts) {
if (val.typeUrl === "") {
return {};
}
const { registry } = opts;
let message;
let desc;
if (registry) {
message = (0, index_js_1.anyUnpack)(val, registry);
if (message) {
desc = registry.getMessage(message.$typeName);
}
}
if (!desc || !message) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: "${val.typeUrl}" is not in the type registry`);
}
const reflected = (0, reflect_js_1.reflect)(desc, message);
const json = (0, wrappers_js_1.hasCustomJsonRepresentation)(desc)
? { value: tryWktToJson(reflected, opts) }
: reflectToJson(reflected, opts);
json["@type"] = val.typeUrl;
return json;
}
function durationToJson(val) {
const seconds = Number(val.seconds);
const nanos = val.nanos;
if (seconds > 315576000000 || seconds < -315576000000) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: value out of range`);
}
if ((seconds > 0 && nanos < 0) || (seconds < 0 && nanos > 0)) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos sign must match seconds sign`);
}
let text = val.seconds.toString();
if (nanos !== 0) {
let nanosStr = Math.abs(nanos).toString();
nanosStr = "0".repeat(9 - nanosStr.length) + nanosStr;
if (nanosStr.substring(3) === "000000") {
nanosStr = nanosStr.substring(0, 3);
}
else if (nanosStr.substring(6) === "000") {
nanosStr = nanosStr.substring(0, 6);
}
text += "." + nanosStr;
if (nanos < 0 && seconds == 0) {
text = "-" + text;
}
}
return text + "s";
}
function fieldMaskToJson(val) {
return val.paths
.map((p) => {
if ((0, names_js_1.protoSnakeCase)((0, names_js_1.protoCamelCase)(p)) !== p) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: lowerCamelCase of path name "${p}" is irreversible`);
}
return (0, names_js_1.protoCamelCase)(p);
})
.join(",");
}
function structToJson(val) {
const json = {};
for (const [k, v] of Object.entries(val.fields)) {
json[k] = valueToJson(v);
}
return json;
}
function valueToJson(val) {
switch (val.kind.case) {
case "nullValue":
return null;
case "numberValue":
if (!Number.isFinite(val.kind.value)) {
throw new Error(`${val.$typeName} cannot be NaN or Infinity`);
}
return val.kind.value;
case "boolValue":
return val.kind.value;
case "stringValue":
return val.kind.value;
case "structValue":
return structToJson(val.kind.value);
case "listValue":
return listValueToJson(val.kind.value);
default:
throw new Error(`${val.$typeName} must have a value`);
}
}
function listValueToJson(val) {
return val.values.map(valueToJson);
}
function timestampToJson(val) {
const ms = Number(val.seconds) * 1000;
if (ms < Date.parse("0001-01-01T00:00:00Z") ||
ms > Date.parse("9999-12-31T23:59:59Z")) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
}
if (val.nanos < 0) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be negative`);
}
if (val.nanos > 999999999) {
throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be greater than 99999999`);
}
let z = "Z";
if (val.nanos > 0) {
const nanosStr = (val.nanos + 1000000000).toString().substring(1);
if (nanosStr.substring(3) === "000000") {
z = "." + nanosStr.substring(0, 3) + "Z";
}
else if (nanosStr.substring(6) === "000") {
z = "." + nanosStr.substring(0, 6) + "Z";
}
else {
z = "." + nanosStr + "Z";
}
}
return new Date(ms).toISOString().replace(".000Z", z);
}
import type { GenEnum as GenEnumV1, GenExtension as GenExtensionV1, GenMessage as GenMessageV1 } from "./codegenv1/types.js";
import type { GenEnum as GenEnumV2, GenExtension as GenExtensionV2, GenMessage as GenMessageV2 } from "./codegenv2/types.js";
import type { DescEnum, DescExtension, DescMessage, DescMethod } from "./descriptors.js";
import type { OneofADT } from "./reflect/guard.js";
import type { WireType } from "./wire/index.js";
import type { JsonValue } from "./json-value.js";
/**
* The type `Message` contains the properties shared by all messages.
*/
export type Message<TypeName extends string = string> = {
/**
* The fully qualified Protobuf type-name of the message.
*/
readonly $typeName: TypeName;
/**
* Unknown fields and extensions stored on the message.
*/
$unknown?: UnknownField[] | undefined;
};
/**
* Extract the message type from a message descriptor.
*/
export type MessageShape<Desc extends DescMessage> = Desc extends GenMessageV1<infer RuntimeShapeV1> ? RuntimeShapeV1 : Desc extends GenMessageV2<infer RuntimeShape> ? RuntimeShape : Message;
/**
* Extract the message JSON type from a message descriptor.
*
* JSON types are only available for code generated with the plugin option
* `json_types=true`. If JSON types are unavailable, this type falls back to the
* `JsonValue` type.
*/
export type MessageJsonType<Desc extends DescMessage> = Desc extends GenMessageV1<Message, infer JsonTypeV1 extends JsonValue> ? JsonTypeV1 : Desc extends GenMessageV2<Message, {
jsonType: infer JsonType extends JsonValue;
}> ? JsonType : JsonValue;
/**
* Extract the message Valid type from a message descriptor.
*
* Valid types are only available for code generated with the plugin option
* `valid_types`. If Valid types are unavailable, this type falls back to the
* regular message shape.
*/
export type MessageValidType<Desc extends DescMessage> = Desc extends GenMessageV1<infer RuntimeShapeV1> ? RuntimeShapeV1 : Desc extends GenMessageV2<Message, {
validType: infer ValidType extends Message;
}> ? ValidType : Desc extends GenMessageV2<infer RuntimeShape> ? RuntimeShape : Message;
/**
* Extract the init type from a message descriptor.
* The init type is accepted by the function create().
*/
export type MessageInitShape<Desc extends DescMessage> = Desc extends GenMessageV1<infer RuntimeShape> ? MessageInit<RuntimeShape> : Desc extends GenMessageV2<infer RuntimeShape> ? MessageInit<RuntimeShape> : Record<string, unknown>;
/**
* Extract the enum type of from an enum descriptor.
*/
export type EnumShape<Desc extends DescEnum> = Desc extends GenEnumV1<infer RuntimeShape> ? RuntimeShape : Desc extends GenEnumV2<infer RuntimeShape> ? RuntimeShape : number;
/**
* Extract the enum JSON type from a enum descriptor.
*/
export type EnumJsonType<Desc extends DescEnum> = Desc extends GenEnumV1<number, infer JsonType> ? JsonType : Desc extends GenEnumV2<number, infer JsonType> ? JsonType : string | null;
/**
* Extract the value type from an extension descriptor.
*/
export type ExtensionValueShape<Desc extends DescExtension> = Desc extends GenExtensionV1<Message, infer RuntimeShape> ? RuntimeShape : Desc extends GenExtensionV2<Message, infer RuntimeShape> ? RuntimeShape : unknown;
/**
* Extract the type of the extended message from an extension descriptor.
*/
export type Extendee<Desc extends DescExtension> = Desc extends GenExtensionV1<infer Extendee> ? Extendee : Desc extends GenExtensionV2<infer Extendee> ? Extendee : Message;
/**
* Unknown fields are fields that were not recognized during parsing, or
* extension.
*/
export type UnknownField = {
readonly no: number;
readonly wireType: WireType;
readonly data: Uint8Array;
};
/**
* Describes a streaming RPC declaration.
*/
export type DescMethodStreaming<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodClientStreaming<I, O> | DescMethodServerStreaming<I, O> | DescMethodBiDiStreaming<I, O>;
/**
* Describes a unary RPC declaration.
*/
export type DescMethodUnary<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodTyped<"unary", I, O>;
/**
* Describes a server streaming RPC declaration.
*/
export type DescMethodServerStreaming<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodTyped<"server_streaming", I, O>;
/**
* Describes a client streaming RPC declaration.
*/
export type DescMethodClientStreaming<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodTyped<"client_streaming", I, O>;
/**
* Describes a bidi streaming RPC declaration.
*/
export type DescMethodBiDiStreaming<I extends DescMessage = DescMessage, O extends DescMessage = DescMessage> = DescMethodTyped<"bidi_streaming", I, O>;
/**
* The init type for a message, which makes all fields optional.
* The init type is accepted by the function create().
*/
type MessageInit<T extends Message> = T | {
[P in keyof T as P extends "$unknown" ? never : P]?: P extends "$typeName" ? never : FieldInit<T[P]>;
};
type FieldInit<F> = F extends (Date | Uint8Array | bigint | boolean | string | number) ? F : F extends Array<infer U> ? Array<FieldInit<U>> : F extends ReadonlyArray<infer U> ? ReadonlyArray<FieldInit<U>> : F extends Message ? MessageInit<F> : F extends OneofSelectedMessage<infer C, infer V> ? {
case: C;
value: MessageInit<V>;
} : F extends OneofADT ? F : F extends MapWithMessage<infer V> ? {
[key: string | number]: MessageInit<V>;
} : F;
type MapWithMessage<V extends Message> = {
[key: string | number]: V;
};
type OneofSelectedMessage<K extends string, M extends Message> = {
case: K;
value: M;
};
type DescMethodTyped<K extends DescMethod["methodKind"], I extends DescMessage, O extends DescMessage> = Omit<DescMethod, "methodKind" | "input" | "output"> & {
/**
* One of the four available method types.
*/
readonly methodKind: K;
/**
* The message type for requests.
*/
readonly input: I;
/**
* The message type for responses.
*/
readonly output: O;
};
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Decodes a base64 string to a byte array.
*
* - ignores white-space, including line breaks and tabs
* - allows inner padding (can decode concatenated base64 strings)
* - does not require padding
* - understands base64url encoding:
* "-" instead of "+",
* "_" instead of "/",
* no padding
*/
export declare function base64Decode(base64Str: string): Uint8Array<ArrayBuffer>;
/**
* Encode a byte array to a base64 string.
*
* By default, this function uses the standard base64 encoding with padding.
*
* To encode without padding, use encoding = "std_raw".
*
* To encode with the URL encoding, use encoding = "url", which replaces the
* characters +/ by their URL-safe counterparts -_, and omits padding.
*/
export declare function base64Encode(bytes: Uint8Array, encoding?: "std" | "std_raw" | "url"): string;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.base64Decode = base64Decode;
exports.base64Encode = base64Encode;
/**
* Decodes a base64 string to a byte array.
*
* - ignores white-space, including line breaks and tabs
* - allows inner padding (can decode concatenated base64 strings)
* - does not require padding
* - understands base64url encoding:
* "-" instead of "+",
* "_" instead of "/",
* no padding
*/
function base64Decode(base64Str) {
const table = getDecodeTable();
// estimate byte size, not accounting for inner padding and whitespace
let es = (base64Str.length * 3) / 4;
if (base64Str[base64Str.length - 2] == "=")
es -= 2;
else if (base64Str[base64Str.length - 1] == "=")
es -= 1;
let bytes = new Uint8Array(es), bytePos = 0, // position in byte array
groupPos = 0, // position in base64 group
b, // current byte
p = 0; // previous byte
for (let i = 0; i < base64Str.length; i++) {
b = table[base64Str.charCodeAt(i)];
if (b === undefined) {
switch (base64Str[i]) {
// @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true
case "=":
groupPos = 0; // reset state when padding found
case "\n":
case "\r":
case "\t":
case " ":
continue; // skip white-space, and padding
default:
throw Error("invalid base64 string");
}
}
switch (groupPos) {
case 0:
p = b;
groupPos = 1;
break;
case 1:
bytes[bytePos++] = (p << 2) | ((b & 48) >> 4);
p = b;
groupPos = 2;
break;
case 2:
bytes[bytePos++] = ((p & 15) << 4) | ((b & 60) >> 2);
p = b;
groupPos = 3;
break;
case 3:
bytes[bytePos++] = ((p & 3) << 6) | b;
groupPos = 0;
break;
}
}
if (groupPos == 1)
throw Error("invalid base64 string");
return bytes.subarray(0, bytePos);
}
/**
* Encode a byte array to a base64 string.
*
* By default, this function uses the standard base64 encoding with padding.
*
* To encode without padding, use encoding = "std_raw".
*
* To encode with the URL encoding, use encoding = "url", which replaces the
* characters +/ by their URL-safe counterparts -_, and omits padding.
*/
function base64Encode(bytes, encoding = "std") {
const table = getEncodeTable(encoding);
const pad = encoding == "std";
let base64 = "", groupPos = 0, // position in base64 group
b, // current byte
p = 0; // carry over from previous byte
for (let i = 0; i < bytes.length; i++) {
b = bytes[i];
switch (groupPos) {
case 0:
base64 += table[b >> 2];
p = (b & 3) << 4;
groupPos = 1;
break;
case 1:
base64 += table[p | (b >> 4)];
p = (b & 15) << 2;
groupPos = 2;
break;
case 2:
base64 += table[p | (b >> 6)];
base64 += table[b & 63];
groupPos = 0;
break;
}
}
// add output padding
if (groupPos) {
base64 += table[p];
if (pad) {
base64 += "=";
if (groupPos == 1)
base64 += "=";
}
}
return base64;
}
// lookup table from base64 character to byte
let encodeTableStd;
let encodeTableUrl;
// lookup table from base64 character *code* to byte because lookup by number is fast
let decodeTable;
function getEncodeTable(encoding) {
if (!encodeTableStd) {
encodeTableStd =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
encodeTableUrl = encodeTableStd.slice(0, -2).concat("-", "_");
}
return encoding == "url"
? // biome-ignore lint/style/noNonNullAssertion: TS fails to narrow down
encodeTableUrl
: encodeTableStd;
}
function getDecodeTable() {
if (!decodeTable) {
decodeTable = [];
const encodeTable = getEncodeTable("std");
for (let i = 0; i < encodeTable.length; i++)
decodeTable[encodeTable[i].charCodeAt(0)] = i;
// support base64url variants
decodeTable["-".charCodeAt(0)] = encodeTable.indexOf("+");
decodeTable["_".charCodeAt(0)] = encodeTable.indexOf("/");
}
return decodeTable;
}
/**
* Protobuf binary format wire types.
*
* A wire type provides just enough information to find the length of the
* following value.
*
* See https://developers.google.com/protocol-buffers/docs/encoding#structure
*/
export declare enum WireType {
/**
* Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
*/
Varint = 0,
/**
* Used for fixed64, sfixed64, double.
* Always 8 bytes with little-endian byte order.
*/
Bit64 = 1,
/**
* Used for string, bytes, embedded messages, packed repeated fields
*
* Only repeated numeric types (types which use the varint, 32-bit,
* or 64-bit wire types) can be packed. In proto3, such fields are
* packed by default.
*/
LengthDelimited = 2,
/**
* Start of a tag-delimited aggregate, such as a proto2 group, or a message
* in editions with message_encoding = DELIMITED.
*/
StartGroup = 3,
/**
* End of a tag-delimited aggregate.
*/
EndGroup = 4,
/**
* Used for fixed32, sfixed32, float.
* Always 4 bytes with little-endian byte order.
*/
Bit32 = 5
}
/**
* Maximum value for a 32-bit floating point value (Protobuf FLOAT).
*/
export declare const FLOAT32_MAX = 3.4028234663852886e+38;
/**
* Minimum value for a 32-bit floating point value (Protobuf FLOAT).
*/
export declare const FLOAT32_MIN = -3.4028234663852886e+38;
/**
* Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).
*/
export declare const UINT32_MAX = 4294967295;
/**
* Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
export declare const INT32_MAX = 2147483647;
/**
* Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
export declare const INT32_MIN = -2147483648;
export declare class BinaryWriter {
private readonly encodeUtf8;
/**
* We cannot allocate a buffer for the entire output
* because we don't know its size.
*
* So we collect smaller chunks of known size and
* concat them later.
*
* Use `raw()` to push data to this array. It will flush
* `buf` first.
*/
private chunks;
/**
* A growing buffer for byte values. If you don't know
* the size of the data you are writing, push to this
* array.
*/
protected buf: number[];
/**
* Previous fork states.
*/
private stack;
constructor(encodeUtf8?: (text: string) => Uint8Array);
/**
* Return all bytes written and reset this writer.
*/
finish(): Uint8Array<ArrayBuffer>;
/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
*/
fork(): this;
/**
* Join the last fork. Write its length and bytes, then
* return to the previous state.
*/
join(): this;
/**
* Writes a tag (field number and wire type).
*
* Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
*
* Generated code should compute the tag ahead of time and call `uint32()`.
*/
tag(fieldNo: number, type: WireType): this;
/**
* Write a chunk of raw bytes.
*/
raw(chunk: Uint8Array): this;
/**
* Write a `uint32` value, an unsigned 32 bit varint.
*/
uint32(value: number): this;
/**
* Write a `int32` value, a signed 32 bit varint.
*/
int32(value: number): this;
/**
* Write a `bool` value, a varint.
*/
bool(value: boolean): this;
/**
* Write a `bytes` value, length-delimited arbitrary data.
*/
bytes(value: Uint8Array): this;
/**
* Write a `string` value, length-delimited data converted to UTF-8 text.
*/
string(value: string): this;
/**
* Write a `float` value, 32-bit floating point number.
*/
float(value: number): this;
/**
* Write a `double` value, a 64-bit floating point number.
*/
double(value: number): this;
/**
* Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
*/
fixed32(value: number): this;
/**
* Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
*/
sfixed32(value: number): this;
/**
* Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
*/
sint32(value: number): this;
/**
* Write a `sfixed64` value, a signed, fixed-length 64-bit integer.
*/
sfixed64(value: string | number | bigint): this;
/**
* Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
*/
fixed64(value: string | number | bigint): this;
/**
* Write a `int64` value, a signed 64-bit varint.
*/
int64(value: string | number | bigint): this;
/**
* Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(value: string | number | bigint): this;
/**
* Write a `uint64` value, an unsigned 64-bit varint.
*/
uint64(value: string | number | bigint): this;
}
export declare class BinaryReader {
private readonly decodeUtf8;
/**
* Current position.
*/
pos: number;
/**
* Number of bytes available in this reader.
*/
readonly len: number;
protected readonly buf: Uint8Array;
private readonly view;
constructor(buf: Uint8Array, decodeUtf8?: (bytes: Uint8Array, strict?: boolean) => string);
/**
* Reads a tag - field number and wire type. Tags are uint32 varints; values
* that do not fit in uint32 are rejected.
*/
tag(): [number, WireType];
/**
* Skip one element and return the skipped data.
*
* When skipping StartGroup, provide the tags field number to check for
* matching field number in the EndGroup tag.
*/
skip(wireType: WireType, fieldNo?: number): Uint8Array;
protected varint64: () => [number, number];
/**
* Throws error if position in byte array is out of range.
*/
protected assertBounds(): void;
/**
* Read a `uint32` field, an unsigned 32 bit varint.
*/
uint32: () => number;
/**
* Read a `int32` field, a signed 32 bit varint.
*/
int32(): number;
/**
* Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
*/
sint32(): number;
/**
* Read a `int64` field, a signed 64-bit varint.
*/
int64(): bigint | string;
/**
* Read a `uint64` field, an unsigned 64-bit varint.
*/
uint64(): bigint | string;
/**
* Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(): bigint | string;
/**
* Read a `bool` field, a variant.
*/
bool(): boolean;
/**
* Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
*/
fixed32(): number;
/**
* Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
*/
sfixed32(): number;
/**
* Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
*/
fixed64(): bigint | string;
/**
* Read a `fixed64` field, a signed, fixed-length 64-bit integer.
*/
sfixed64(): bigint | string;
/**
* Read a `float` field, 32-bit floating point number.
*/
float(): number;
/**
* Read a `double` field, a 64-bit floating point number.
*/
double(): number;
/**
* Read a `bytes` field, length-delimited arbitrary data.
*/
bytes(): Uint8Array;
/**
* Read a `string` field, length-delimited data converted to UTF-8 text. If
* `strict` is true, throw on invalid UTF-8 instead of substituting U+FFFD.
*/
string(strict?: boolean): string;
}
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinaryReader = exports.BinaryWriter = exports.INT32_MIN = exports.INT32_MAX = exports.UINT32_MAX = exports.FLOAT32_MIN = exports.FLOAT32_MAX = exports.WireType = void 0;
const varint_js_1 = require("./varint.js");
const proto_int64_js_1 = require("../proto-int64.js");
const text_encoding_js_1 = require("./text-encoding.js");
/**
* Protobuf binary format wire types.
*
* A wire type provides just enough information to find the length of the
* following value.
*
* See https://developers.google.com/protocol-buffers/docs/encoding#structure
*/
var WireType;
(function (WireType) {
/**
* Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
*/
WireType[WireType["Varint"] = 0] = "Varint";
/**
* Used for fixed64, sfixed64, double.
* Always 8 bytes with little-endian byte order.
*/
WireType[WireType["Bit64"] = 1] = "Bit64";
/**
* Used for string, bytes, embedded messages, packed repeated fields
*
* Only repeated numeric types (types which use the varint, 32-bit,
* or 64-bit wire types) can be packed. In proto3, such fields are
* packed by default.
*/
WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited";
/**
* Start of a tag-delimited aggregate, such as a proto2 group, or a message
* in editions with message_encoding = DELIMITED.
*/
WireType[WireType["StartGroup"] = 3] = "StartGroup";
/**
* End of a tag-delimited aggregate.
*/
WireType[WireType["EndGroup"] = 4] = "EndGroup";
/**
* Used for fixed32, sfixed32, float.
* Always 4 bytes with little-endian byte order.
*/
WireType[WireType["Bit32"] = 5] = "Bit32";
})(WireType || (exports.WireType = WireType = {}));
/**
* Maximum value for a 32-bit floating point value (Protobuf FLOAT).
*/
exports.FLOAT32_MAX = 3.4028234663852886e38;
/**
* Minimum value for a 32-bit floating point value (Protobuf FLOAT).
*/
exports.FLOAT32_MIN = -3.4028234663852886e38;
/**
* Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).
*/
exports.UINT32_MAX = 0xffffffff;
/**
* Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
exports.INT32_MAX = 0x7fffffff;
/**
* Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
exports.INT32_MIN = -0x80000000;
class BinaryWriter {
constructor(encodeUtf8 = (0, text_encoding_js_1.getTextEncoding)().encodeUtf8) {
this.encodeUtf8 = encodeUtf8;
/**
* Previous fork states.
*/
this.stack = [];
this.chunks = [];
this.buf = [];
}
/**
* Return all bytes written and reset this writer.
*/
finish() {
if (this.buf.length) {
this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
this.buf = [];
}
let len = 0;
for (let i = 0; i < this.chunks.length; i++)
len += this.chunks[i].length;
let bytes = new Uint8Array(len);
let offset = 0;
for (let i = 0; i < this.chunks.length; i++) {
bytes.set(this.chunks[i], offset);
offset += this.chunks[i].length;
}
this.chunks = [];
return bytes;
}
/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
*/
fork() {
this.stack.push({ chunks: this.chunks, buf: this.buf });
this.chunks = [];
this.buf = [];
return this;
}
/**
* Join the last fork. Write its length and bytes, then
* return to the previous state.
*/
join() {
// get chunk of fork
let chunk = this.finish();
// restore previous state
let prev = this.stack.pop();
if (!prev)
throw new Error("invalid state, fork stack empty");
this.chunks = prev.chunks;
this.buf = prev.buf;
// write length of chunk as varint
this.uint32(chunk.byteLength);
return this.raw(chunk);
}
/**
* Writes a tag (field number and wire type).
*
* Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
*
* Generated code should compute the tag ahead of time and call `uint32()`.
*/
tag(fieldNo, type) {
return this.uint32(((fieldNo << 3) | type) >>> 0);
}
/**
* Write a chunk of raw bytes.
*/
raw(chunk) {
if (this.buf.length) {
this.chunks.push(new Uint8Array(this.buf));
this.buf = [];
}
this.chunks.push(chunk);
return this;
}
/**
* Write a `uint32` value, an unsigned 32 bit varint.
*/
uint32(value) {
assertUInt32(value);
// write value as varint 32, inlined for speed
while (value > 0x7f) {
this.buf.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
this.buf.push(value);
return this;
}
/**
* Write a `int32` value, a signed 32 bit varint.
*/
int32(value) {
assertInt32(value);
(0, varint_js_1.varint32write)(value, this.buf);
return this;
}
/**
* Write a `bool` value, a varint.
*/
bool(value) {
this.buf.push(value ? 1 : 0);
return this;
}
/**
* Write a `bytes` value, length-delimited arbitrary data.
*/
bytes(value) {
this.uint32(value.byteLength); // write length of chunk as varint
return this.raw(value);
}
/**
* Write a `string` value, length-delimited data converted to UTF-8 text.
*/
string(value) {
let chunk = this.encodeUtf8(value);
this.uint32(chunk.byteLength); // write length of chunk as varint
return this.raw(chunk);
}
/**
* Write a `float` value, 32-bit floating point number.
*/
float(value) {
assertFloat32(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setFloat32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `double` value, a 64-bit floating point number.
*/
double(value) {
let chunk = new Uint8Array(8);
new DataView(chunk.buffer).setFloat64(0, value, true);
return this.raw(chunk);
}
/**
* Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
*/
fixed32(value) {
assertUInt32(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setUint32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
*/
sfixed32(value) {
assertInt32(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setInt32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
*/
sint32(value) {
assertInt32(value);
// zigzag encode
value = ((value << 1) ^ (value >> 31)) >>> 0;
(0, varint_js_1.varint32write)(value, this.buf);
return this;
}
/**
* Write a `sfixed64` value, a signed, fixed-length 64-bit integer.
*/
sfixed64(value) {
let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = proto_int64_js_1.protoInt64.enc(value);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
return this.raw(chunk);
}
/**
* Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
*/
fixed64(value) {
let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = proto_int64_js_1.protoInt64.uEnc(value);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
return this.raw(chunk);
}
/**
* Write a `int64` value, a signed 64-bit varint.
*/
int64(value) {
let tc = proto_int64_js_1.protoInt64.enc(value);
(0, varint_js_1.varint64write)(tc.lo, tc.hi, this.buf);
return this;
}
/**
* Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(value) {
const tc = proto_int64_js_1.protoInt64.enc(value),
// zigzag encode
sign = tc.hi >> 31, lo = (tc.lo << 1) ^ sign, hi = ((tc.hi << 1) | (tc.lo >>> 31)) ^ sign;
(0, varint_js_1.varint64write)(lo, hi, this.buf);
return this;
}
/**
* Write a `uint64` value, an unsigned 64-bit varint.
*/
uint64(value) {
const tc = proto_int64_js_1.protoInt64.uEnc(value);
(0, varint_js_1.varint64write)(tc.lo, tc.hi, this.buf);
return this;
}
}
exports.BinaryWriter = BinaryWriter;
class BinaryReader {
constructor(buf, decodeUtf8 = (0, text_encoding_js_1.getTextEncoding)().decodeUtf8) {
this.decodeUtf8 = decodeUtf8;
this.varint64 = varint_js_1.varint64read; // dirty cast for `this`
/**
* Read a `uint32` field, an unsigned 32 bit varint.
*/
this.uint32 = varint_js_1.varint32read;
this.buf = buf;
this.len = buf.length;
this.pos = 0;
this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
}
/**
* Reads a tag - field number and wire type. Tags are uint32 varints; values
* that do not fit in uint32 are rejected.
*/
tag() {
const start = this.pos;
const tag = this.uint32();
const bytesRead = this.pos - start;
if (bytesRead > 5 || (bytesRead == 5 && this.buf[this.pos - 1] > 0x0f)) {
throw new Error("illegal tag: varint overflows uint32");
}
const fieldNo = tag >>> 3;
const wireType = tag & 7;
if (fieldNo <= 0 || wireType > 5) {
throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
}
return [fieldNo, wireType];
}
/**
* Skip one element and return the skipped data.
*
* When skipping StartGroup, provide the tags field number to check for
* matching field number in the EndGroup tag.
*/
skip(wireType, fieldNo) {
let start = this.pos;
switch (wireType) {
case WireType.Varint:
while (this.buf[this.pos++] & 0x80) {
// ignore
}
break;
// @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true
case WireType.Bit64:
this.pos += 4;
case WireType.Bit32:
this.pos += 4;
break;
case WireType.LengthDelimited:
let len = this.uint32();
this.pos += len;
break;
case WireType.StartGroup:
for (;;) {
const [fn, wt] = this.tag();
if (wt === WireType.EndGroup) {
if (fieldNo !== undefined && fn !== fieldNo) {
throw new Error("invalid end group tag");
}
break;
}
this.skip(wt, fn);
}
break;
default:
throw new Error("cant skip wire type " + wireType);
}
this.assertBounds();
return this.buf.subarray(start, this.pos);
}
/**
* Throws error if position in byte array is out of range.
*/
assertBounds() {
if (this.pos > this.len)
throw new RangeError("premature EOF");
}
/**
* Read a `int32` field, a signed 32 bit varint.
*/
int32() {
return this.uint32() | 0;
}
/**
* Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
*/
sint32() {
let zze = this.uint32();
// decode zigzag
return (zze >>> 1) ^ -(zze & 1);
}
/**
* Read a `int64` field, a signed 64-bit varint.
*/
int64() {
return proto_int64_js_1.protoInt64.dec(...this.varint64());
}
/**
* Read a `uint64` field, an unsigned 64-bit varint.
*/
uint64() {
return proto_int64_js_1.protoInt64.uDec(...this.varint64());
}
/**
* Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
*/
sint64() {
let [lo, hi] = this.varint64();
// decode zig zag
let s = -(lo & 1);
lo = ((lo >>> 1) | ((hi & 1) << 31)) ^ s;
hi = (hi >>> 1) ^ s;
return proto_int64_js_1.protoInt64.dec(lo, hi);
}
/**
* Read a `bool` field, a variant.
*/
bool() {
let [lo, hi] = this.varint64();
return lo !== 0 || hi !== 0;
}
/**
* Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
*/
fixed32() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getUint32((this.pos += 4) - 4, true);
}
/**
* Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
*/
sfixed32() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getInt32((this.pos += 4) - 4, true);
}
/**
* Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
*/
fixed64() {
return proto_int64_js_1.protoInt64.uDec(this.sfixed32(), this.sfixed32());
}
/**
* Read a `fixed64` field, a signed, fixed-length 64-bit integer.
*/
sfixed64() {
return proto_int64_js_1.protoInt64.dec(this.sfixed32(), this.sfixed32());
}
/**
* Read a `float` field, 32-bit floating point number.
*/
float() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getFloat32((this.pos += 4) - 4, true);
}
/**
* Read a `double` field, a 64-bit floating point number.
*/
double() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getFloat64((this.pos += 8) - 8, true);
}
/**
* Read a `bytes` field, length-delimited arbitrary data.
*/
bytes() {
let len = this.uint32(), start = this.pos;
this.pos += len;
this.assertBounds();
return this.buf.subarray(start, start + len);
}
/**
* Read a `string` field, length-delimited data converted to UTF-8 text. If
* `strict` is true, throw on invalid UTF-8 instead of substituting U+FFFD.
*/
string(strict) {
return this.decodeUtf8(this.bytes(), strict);
}
}
exports.BinaryReader = BinaryReader;
/**
* Assert a valid signed protobuf 32-bit integer as a number or string.
*/
function assertInt32(arg) {
if (typeof arg == "string") {
arg = Number(arg);
}
else if (typeof arg != "number") {
throw new Error("invalid int32: " + typeof arg);
}
if (!Number.isInteger(arg) ||
arg > exports.INT32_MAX ||
arg < exports.INT32_MIN)
throw new Error("invalid int32: " + arg);
}
/**
* Assert a valid unsigned protobuf 32-bit integer as a number or string.
*/
function assertUInt32(arg) {
if (typeof arg == "string") {
arg = Number(arg);
}
else if (typeof arg != "number") {
throw new Error("invalid uint32: " + typeof arg);
}
if (!Number.isInteger(arg) ||
arg > exports.UINT32_MAX ||
arg < 0)
throw new Error("invalid uint32: " + arg);
}
/**
* Assert a valid protobuf float value as a number or string.
*/
function assertFloat32(arg) {
if (typeof arg == "string") {
const o = arg;
arg = Number(arg);
if (Number.isNaN(arg) && o !== "NaN") {
throw new Error("invalid float32: " + o);
}
}
else if (typeof arg != "number") {
throw new Error("invalid float32: " + typeof arg);
}
if (Number.isFinite(arg) &&
(arg > exports.FLOAT32_MAX || arg < exports.FLOAT32_MIN))
throw new Error("invalid float32: " + arg);
}
export * from "./binary-encoding.js";
export * from "./base64-encoding.js";
export * from "./text-encoding.js";
export * from "./text-format.js";
export * from "./size-delimited.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./binary-encoding.js"), exports);
__exportStar(require("./base64-encoding.js"), exports);
__exportStar(require("./text-encoding.js"), exports);
__exportStar(require("./text-format.js"), exports);
__exportStar(require("./size-delimited.js"), exports);
import type { DescMessage } from "../descriptors.js";
import type { BinaryWriteOptions } from "../to-binary.js";
import type { MessageShape } from "../types.js";
import type { BinaryReadOptions } from "../from-binary.js";
/**
* Serialize a message, prefixing it with its size.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
export declare function sizeDelimitedEncode<Desc extends DescMessage>(messageDesc: Desc, message: MessageShape<Desc>, options?: BinaryWriteOptions): Uint8Array;
/**
* Parse a stream of size-delimited messages.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
export declare function sizeDelimitedDecodeStream<Desc extends DescMessage>(messageDesc: Desc, iterable: AsyncIterable<Uint8Array>, options?: BinaryReadOptions): AsyncIterableIterator<MessageShape<Desc>>;
/**
* Decodes the size from the given size-delimited message, which may be
* incomplete.
*
* Returns an object with the following properties:
* - size: The size of the delimited message in bytes
* - offset: The offset in the given byte array where the message starts
* - eof: true
*
* If the size-delimited data does not include all bytes of the varint size,
* the following object is returned:
* - size: null
* - offset: null
* - eof: false
*
* This function can be used to implement parsing of size-delimited messages
* from a stream.
*/
export declare function sizeDelimitedPeek(data: Uint8Array): {
readonly eof: false;
readonly size: number;
readonly offset: number;
} | {
readonly eof: true;
readonly size: null;
readonly offset: null;
};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sizeDelimitedEncode = sizeDelimitedEncode;
exports.sizeDelimitedDecodeStream = sizeDelimitedDecodeStream;
exports.sizeDelimitedPeek = sizeDelimitedPeek;
const to_binary_js_1 = require("../to-binary.js");
const binary_encoding_js_1 = require("./binary-encoding.js");
const from_binary_js_1 = require("../from-binary.js");
/**
* Serialize a message, prefixing it with its size.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
function sizeDelimitedEncode(messageDesc, message, options) {
const writer = new binary_encoding_js_1.BinaryWriter();
writer.bytes((0, to_binary_js_1.toBinary)(messageDesc, message, options));
return writer.finish();
}
/**
* Parse a stream of size-delimited messages.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
function sizeDelimitedDecodeStream(messageDesc, iterable, options) {
return __asyncGenerator(this, arguments, function* sizeDelimitedDecodeStream_1() {
var _a, e_1, _b, _c;
// append chunk to buffer, returning updated buffer
function append(buffer, chunk) {
const n = new Uint8Array(buffer.byteLength + chunk.byteLength);
n.set(buffer);
n.set(chunk, buffer.length);
return n;
}
let buffer = new Uint8Array(0);
try {
for (var _d = true, iterable_1 = __asyncValues(iterable), iterable_1_1; iterable_1_1 = yield __await(iterable_1.next()), _a = iterable_1_1.done, !_a; _d = true) {
_c = iterable_1_1.value;
_d = false;
const chunk = _c;
buffer = append(buffer, chunk);
for (;;) {
const size = sizeDelimitedPeek(buffer);
if (size.eof) {
// size is incomplete, buffer more data
break;
}
if (size.offset + size.size > buffer.byteLength) {
// message is incomplete, buffer more data
break;
}
yield yield __await((0, from_binary_js_1.fromBinary)(messageDesc, buffer.subarray(size.offset, size.offset + size.size), options));
buffer = buffer.subarray(size.offset + size.size);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = iterable_1.return)) yield __await(_b.call(iterable_1));
}
finally { if (e_1) throw e_1.error; }
}
if (buffer.byteLength > 0) {
throw new Error("incomplete data");
}
});
}
/**
* Decodes the size from the given size-delimited message, which may be
* incomplete.
*
* Returns an object with the following properties:
* - size: The size of the delimited message in bytes
* - offset: The offset in the given byte array where the message starts
* - eof: true
*
* If the size-delimited data does not include all bytes of the varint size,
* the following object is returned:
* - size: null
* - offset: null
* - eof: false
*
* This function can be used to implement parsing of size-delimited messages
* from a stream.
*/
function sizeDelimitedPeek(data) {
const sizeEof = { eof: true, size: null, offset: null };
for (let i = 0; i < 10; i++) {
if (i > data.byteLength) {
return sizeEof;
}
if ((data[i] & 0x80) == 0) {
const reader = new binary_encoding_js_1.BinaryReader(data);
let size;
try {
size = reader.uint32();
}
catch (e) {
if (e instanceof RangeError) {
return sizeEof;
}
throw e;
}
return {
eof: false,
size,
offset: reader.pos,
};
}
}
throw new Error("invalid varint");
}
interface TextEncoding {
/**
* Verify that the given text is valid UTF-8.
*/
checkUtf8: (text: string) => boolean;
/**
* Encode UTF-8 text to binary.
*/
encodeUtf8: (text: string) => Uint8Array<ArrayBuffer>;
/**
* Decode UTF-8 text from binary. If `strict` is true, throw on invalid byte
* sequences instead of silently substituting U+FFFD. Implementations that
* do not support strict decoding may ignore the flag.
*/
decodeUtf8: (bytes: Uint8Array, strict?: boolean) => string;
}
/**
* Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to
* binary. This WHATWG API is widely available, but it is not part of the
* ECMAScript standard. On runtimes where it is not available, use this
* function to provide your own implementation.
*
* Note that the Text Encoding API does not provide a way to validate UTF-8.
* Our implementation falls back to use encodeURIComponent().
*/
export declare function configureTextEncoding(textEncoding: TextEncoding): void;
export declare function getTextEncoding(): TextEncoding;
export {};
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.configureTextEncoding = configureTextEncoding;
exports.getTextEncoding = getTextEncoding;
const symbol = Symbol.for("@bufbuild/protobuf/text-encoding");
/**
* Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to
* binary. This WHATWG API is widely available, but it is not part of the
* ECMAScript standard. On runtimes where it is not available, use this
* function to provide your own implementation.
*
* Note that the Text Encoding API does not provide a way to validate UTF-8.
* Our implementation falls back to use encodeURIComponent().
*/
function configureTextEncoding(textEncoding) {
globalThis[symbol] = textEncoding;
}
function getTextEncoding() {
if (globalThis[symbol] == undefined) {
const te = new globalThis.TextEncoder();
const td = new globalThis.TextDecoder();
let tdStrict;
globalThis[symbol] = {
encodeUtf8(text) {
return te.encode(text);
},
decodeUtf8(bytes, strict) {
if (strict) {
if (tdStrict === undefined) {
tdStrict = new globalThis.TextDecoder("utf-8", { fatal: true });
}
return tdStrict.decode(bytes);
}
return td.decode(bytes);
},
checkUtf8(text) {
try {
encodeURIComponent(text);
return true;
}
catch (_) {
return false;
}
},
};
}
return globalThis[symbol];
}
import { type DescEnum, ScalarType } from "../descriptors.js";
/**
* Parse an enum value from the Protobuf text format.
*
* @private
*/
export declare function parseTextFormatEnumValue(descEnum: DescEnum, value: string): number;
/**
* Parse a scalar value from the Protobuf text format.
*
* @private
*/
export declare function parseTextFormatScalarValue(type: ScalarType, value: string): number | boolean | string | bigint | Uint8Array;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseTextFormatEnumValue = parseTextFormatEnumValue;
exports.parseTextFormatScalarValue = parseTextFormatScalarValue;
const descriptors_js_1 = require("../descriptors.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Parse an enum value from the Protobuf text format.
*
* @private
*/
function parseTextFormatEnumValue(descEnum, value) {
const enumValue = descEnum.values.find((v) => v.name === value);
if (!enumValue) {
throw new Error(`cannot parse ${descEnum} default value: ${value}`);
}
return enumValue.number;
}
/**
* Parse a scalar value from the Protobuf text format.
*
* @private
*/
function parseTextFormatScalarValue(type, value) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return value;
case descriptors_js_1.ScalarType.BYTES: {
const u = unescapeBytesDefaultValue(value);
if (u === false) {
throw new Error(`cannot parse ${descriptors_js_1.ScalarType[type]} default value: ${value}`);
}
return u;
}
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
return proto_int64_js_1.protoInt64.parse(value);
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
return proto_int64_js_1.protoInt64.uParse(value);
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
switch (value) {
case "inf":
return Number.POSITIVE_INFINITY;
case "-inf":
return Number.NEGATIVE_INFINITY;
case "nan":
return Number.NaN;
default:
return parseFloat(value);
}
case descriptors_js_1.ScalarType.BOOL:
return value === "true";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.SFIXED32:
return parseInt(value, 10);
}
}
/**
* Parses a text-encoded default value (proto2) of a BYTES field.
*/
function unescapeBytesDefaultValue(str) {
const b = [];
const input = {
tail: str,
c: "",
next() {
if (this.tail.length == 0) {
return false;
}
this.c = this.tail[0];
this.tail = this.tail.substring(1);
return true;
},
take(n) {
if (this.tail.length >= n) {
const r = this.tail.substring(0, n);
this.tail = this.tail.substring(n);
return r;
}
return false;
},
};
while (input.next()) {
switch (input.c) {
case "\\":
if (input.next()) {
switch (input.c) {
case "\\":
b.push(input.c.charCodeAt(0));
break;
case "b":
b.push(0x08);
break;
case "f":
b.push(0x0c);
break;
case "n":
b.push(0x0a);
break;
case "r":
b.push(0x0d);
break;
case "t":
b.push(0x09);
break;
case "v":
b.push(0x0b);
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7": {
const s = input.c;
const t = input.take(2);
if (t === false) {
return false;
}
const n = parseInt(s + t, 8);
if (Number.isNaN(n)) {
return false;
}
b.push(n);
break;
}
case "x": {
const s = input.c;
const t = input.take(2);
if (t === false) {
return false;
}
const n = parseInt(s + t, 16);
if (Number.isNaN(n)) {
return false;
}
b.push(n);
break;
}
case "u": {
const s = input.c;
const t = input.take(4);
if (t === false) {
return false;
}
const n = parseInt(s + t, 16);
if (Number.isNaN(n)) {
return false;
}
const chunk = new Uint8Array(4);
const view = new DataView(chunk.buffer);
view.setInt32(0, n, true);
b.push(chunk[0], chunk[1], chunk[2], chunk[3]);
break;
}
case "U": {
const s = input.c;
const t = input.take(8);
if (t === false) {
return false;
}
const tc = proto_int64_js_1.protoInt64.uEnc(s + t);
const chunk = new Uint8Array(8);
const view = new DataView(chunk.buffer);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
b.push(chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7]);
break;
}
}
}
break;
default:
b.push(input.c.charCodeAt(0));
}
}
return new Uint8Array(b);
}
/**
* Read a 64 bit varint as two JS numbers.
*
* Returns tuple:
* [0]: low bits
* [1]: high bits
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
*/
export declare function varint64read<T extends ReaderLike>(this: T): [number, number];
/**
* Write a 64 bit varint, given as two JS numbers, to the given bytes array.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
*/
export declare function varint64write(lo: number, hi: number, bytes: number[]): void;
/**
* Parse decimal string of 64 bit integer value as two JS numbers.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function int64FromString(dec: string): {
lo: number;
hi: number;
};
/**
* Losslessly converts a 64-bit signed integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function int64ToString(lo: number, hi: number): string;
/**
* Losslessly converts a 64-bit unsigned integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function uInt64ToString(lo: number, hi: number): string;
/**
* Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
*/
export declare function varint32write(value: number, bytes: number[]): void;
/**
* Read an unsigned 32 bit varint.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
*/
export declare function varint32read<T extends ReaderLike>(this: T): number;
type ReaderLike = {
buf: Uint8Array;
pos: number;
len: number;
assertBounds(): void;
};
export {};
"use strict";
// Copyright 2008 Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Code generated by the Protocol Buffer compiler is owned by the owner
// of the input file used when generating it. This code is not
// standalone and requires a support library to be linked with it. This
// support library is itself covered by the above license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.varint64read = varint64read;
exports.varint64write = varint64write;
exports.int64FromString = int64FromString;
exports.int64ToString = int64ToString;
exports.uInt64ToString = uInt64ToString;
exports.varint32write = varint32write;
exports.varint32read = varint32read;
/**
* Read a 64 bit varint as two JS numbers.
*
* Returns tuple:
* [0]: low bits
* [1]: high bits
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
*/
function varint64read() {
let lowBits = 0;
let highBits = 0;
for (let shift = 0; shift < 28; shift += 7) {
let b = this.buf[this.pos++];
lowBits |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
}
let middleByte = this.buf[this.pos++];
// last four bits of the first 32 bit number
lowBits |= (middleByte & 0x0f) << 28;
// 3 upper bits are part of the next 32 bit number
highBits = (middleByte & 0x70) >> 4;
if ((middleByte & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
for (let shift = 3; shift <= 31; shift += 7) {
let b = this.buf[this.pos++];
highBits |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
}
throw new Error("invalid varint");
}
/**
* Write a 64 bit varint, given as two JS numbers, to the given bytes array.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
*/
function varint64write(lo, hi, bytes) {
for (let i = 0; i < 28; i = i + 7) {
const shift = lo >>> i;
const hasNext = !(shift >>> 7 == 0 && hi == 0);
const byte = (hasNext ? shift | 0x80 : shift) & 0xff;
bytes.push(byte);
if (!hasNext) {
return;
}
}
const splitBits = ((lo >>> 28) & 0x0f) | ((hi & 0x07) << 4);
const hasMoreBits = !(hi >> 3 == 0);
bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xff);
if (!hasMoreBits) {
return;
}
for (let i = 3; i < 31; i = i + 7) {
const shift = hi >>> i;
const hasNext = !(shift >>> 7 == 0);
const byte = (hasNext ? shift | 0x80 : shift) & 0xff;
bytes.push(byte);
if (!hasNext) {
return;
}
}
bytes.push((hi >>> 31) & 0x01);
}
// constants for binary math
const TWO_PWR_32_DBL = 0x100000000;
/**
* Parse decimal string of 64 bit integer value as two JS numbers.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function int64FromString(dec) {
// Check for minus sign.
const minus = dec[0] === "-";
if (minus) {
dec = dec.slice(1);
}
// Work 6 decimal digits at a time, acting like we're converting base 1e6
// digits to binary. This is safe to do with floating point math because
// Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
const base = 1e6;
let lowBits = 0;
let highBits = 0;
function add1e6digit(begin, end) {
// Note: Number('') is 0.
const digit1e6 = Number(dec.slice(begin, end));
highBits *= base;
lowBits = lowBits * base + digit1e6;
// Carry bits from lowBits to
if (lowBits >= TWO_PWR_32_DBL) {
highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);
lowBits = lowBits % TWO_PWR_32_DBL;
}
}
add1e6digit(-24, -18);
add1e6digit(-18, -12);
add1e6digit(-12, -6);
add1e6digit(-6);
return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits);
}
/**
* Losslessly converts a 64-bit signed integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function int64ToString(lo, hi) {
let bits = newBits(lo, hi);
// If we're treating the input as a signed value and the high bit is set, do
// a manual two's complement conversion before the decimal conversion.
const negative = bits.hi & 0x80000000;
if (negative) {
bits = negate(bits.lo, bits.hi);
}
const result = uInt64ToString(bits.lo, bits.hi);
return negative ? "-" + result : result;
}
/**
* Losslessly converts a 64-bit unsigned integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function uInt64ToString(lo, hi) {
({ lo, hi } = toUnsigned(lo, hi));
// Skip the expensive conversion if the number is small enough to use the
// built-in conversions.
// Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with
// highBits <= 0x1FFFFF can be safely expressed with a double and retain
// integer precision.
// Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true.
if (hi <= 0x1fffff) {
return String(TWO_PWR_32_DBL * hi + lo);
}
// What this code is doing is essentially converting the input number from
// base-2 to base-1e7, which allows us to represent the 64-bit range with
// only 3 (very large) digits. Those digits are then trivial to convert to
// a base-10 string.
// The magic numbers used here are -
// 2^24 = 16777216 = (1,6777216) in base-1e7.
// 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
// Split 32:32 representation into 16:24:24 representation so our
// intermediate digits don't overflow.
const low = lo & 0xffffff;
const mid = ((lo >>> 24) | (hi << 8)) & 0xffffff;
const high = (hi >> 16) & 0xffff;
// Assemble our three base-1e7 digits, ignoring carries. The maximum
// value in a digit at this step is representable as a 48-bit integer, which
// can be stored in a 64-bit floating point number.
let digitA = low + mid * 6777216 + high * 6710656;
let digitB = mid + high * 8147497;
let digitC = high * 2;
// Apply carries from A to B and from B to C.
const base = 10000000;
if (digitA >= base) {
digitB += Math.floor(digitA / base);
digitA %= base;
}
if (digitB >= base) {
digitC += Math.floor(digitB / base);
digitB %= base;
}
// If digitC is 0, then we should have returned in the trivial code path
// at the top for non-safe integers. Given this, we can assume both digitB
// and digitA need leading zeros.
return (digitC.toString() +
decimalFrom1e7WithLeadingZeros(digitB) +
decimalFrom1e7WithLeadingZeros(digitA));
}
function toUnsigned(lo, hi) {
return { lo: lo >>> 0, hi: hi >>> 0 };
}
function newBits(lo, hi) {
return { lo: lo | 0, hi: hi | 0 };
}
/**
* Returns two's compliment negation of input.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers
*/
function negate(lowBits, highBits) {
highBits = ~highBits;
if (lowBits) {
lowBits = ~lowBits + 1;
}
else {
// If lowBits is 0, then bitwise-not is 0xFFFFFFFF,
// adding 1 to that, results in 0x100000000, which leaves
// the low bits 0x0 and simply adds one to the high bits.
highBits += 1;
}
return newBits(lowBits, highBits);
}
/**
* Returns decimal representation of digit1e7 with leading zeros.
*/
const decimalFrom1e7WithLeadingZeros = (digit1e7) => {
const partial = String(digit1e7);
return "0000000".slice(partial.length) + partial;
};
/**
* Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
*/
function varint32write(value, bytes) {
if (value >= 0) {
// write value as varint 32
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
bytes.push(value);
}
else {
for (let i = 0; i < 9; i++) {
bytes.push((value & 127) | 128);
value = value >> 7;
}
bytes.push(1);
}
}
/**
* Read an unsigned 32 bit varint.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
*/
function varint32read() {
let b = this.buf[this.pos++];
let result = b & 0x7f;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 7;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 14;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 21;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
// Extract only last 4 bits
b = this.buf[this.pos++];
result |= (b & 0x0f) << 28;
for (let readBytes = 5; (b & 0x80) !== 0 && readBytes < 10; readBytes++)
b = this.buf[this.pos++];
if ((b & 0x80) != 0)
throw new Error("invalid varint");
this.assertBounds();
// Result can have 32 bits, convert it to unsigned
return result >>> 0;
}
import type { Message, MessageShape } from "../types.js";
import type { Any } from "./gen/google/protobuf/any_pb.js";
import type { DescMessage } from "../descriptors.js";
import type { Registry } from "../registry.js";
/**
* Creates a `google.protobuf.Any` from a message.
*/
export declare function anyPack<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>): Any;
/**
* Packs the message into the given any.
*/
export declare function anyPack<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>, into: Any): void;
/**
* Returns true if the Any contains the type given by schema.
*/
export declare function anyIs(any: Any, schema: DescMessage): boolean;
/**
* Returns true if the Any contains a message with the given typeName.
*/
export declare function anyIs(any: Any, typeName: string): boolean;
/**
* Unpacks the message the Any represents.
*
* Returns undefined if the Any is empty, or if packed type is not included
* in the given registry.
*/
export declare function anyUnpack(any: Any, registry: Registry): Message | undefined;
/**
* Unpacks the message the Any represents.
*
* Returns undefined if the Any is empty, or if it does not contain the type
* given by schema.
*/
export declare function anyUnpack<Desc extends DescMessage>(any: Any, schema: Desc): MessageShape<Desc> | undefined;
/**
* Same as anyUnpack but unpacks into the target message.
*/
export declare function anyUnpackTo<Desc extends DescMessage>(any: Any, schema: Desc, message: MessageShape<Desc>): MessageShape<Desc> | undefined;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.anyPack = anyPack;
exports.anyIs = anyIs;
exports.anyUnpack = anyUnpack;
exports.anyUnpackTo = anyUnpackTo;
const any_pb_js_1 = require("./gen/google/protobuf/any_pb.js");
const create_js_1 = require("../create.js");
const to_binary_js_1 = require("../to-binary.js");
const from_binary_js_1 = require("../from-binary.js");
function anyPack(schema, message, into) {
let ret = false;
if (!into) {
into = (0, create_js_1.create)(any_pb_js_1.AnySchema);
ret = true;
}
into.value = (0, to_binary_js_1.toBinary)(schema, message);
into.typeUrl = typeNameToUrl(message.$typeName);
return ret ? into : undefined;
}
function anyIs(any, descOrTypeName) {
if (any.typeUrl === "") {
return false;
}
const want = typeof descOrTypeName == "string"
? descOrTypeName
: descOrTypeName.typeName;
const got = typeUrlToName(any.typeUrl);
return want === got;
}
function anyUnpack(any, registryOrMessageDesc) {
if (any.typeUrl === "") {
return undefined;
}
const desc = registryOrMessageDesc.kind == "message"
? registryOrMessageDesc
: registryOrMessageDesc.getMessage(typeUrlToName(any.typeUrl));
if (!desc || !anyIs(any, desc)) {
return undefined;
}
return (0, from_binary_js_1.fromBinary)(desc, any.value);
}
/**
* Same as anyUnpack but unpacks into the target message.
*/
function anyUnpackTo(any, schema, message) {
if (!anyIs(any, schema)) {
return undefined;
}
return (0, from_binary_js_1.mergeFromBinary)(schema, message, any.value);
}
function typeNameToUrl(name) {
return `type.googleapis.com/${name}`;
}
function typeUrlToName(url) {
const slash = url.lastIndexOf("/");
const name = slash >= 0 ? url.substring(slash + 1) : url;
if (!name.length) {
throw new Error(`invalid type url: ${url}`);
}
return name;
}
import type { Duration } from "./gen/google/protobuf/duration_pb.js";
/**
* Create a google.protobuf.Duration message from a Unix timestamp in milliseconds.
*/
export declare function durationFromMs(durationMs: number): Duration;
/**
* Convert a google.protobuf.Duration to a Unix timestamp in milliseconds.
*/
export declare function durationMs(duration: Duration): number;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.durationFromMs = durationFromMs;
exports.durationMs = durationMs;
const duration_pb_js_1 = require("./gen/google/protobuf/duration_pb.js");
const create_js_1 = require("../create.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Create a google.protobuf.Duration message from a Unix timestamp in milliseconds.
*/
function durationFromMs(durationMs) {
const sign = durationMs < 0 ? -1 : 1;
const absDurationMs = Math.abs(durationMs);
const absSeconds = Math.floor(absDurationMs / 1000);
const absNanos = (absDurationMs - absSeconds * 1000) * 1000000;
return (0, create_js_1.create)(duration_pb_js_1.DurationSchema, {
seconds: proto_int64_js_1.protoInt64.parse(absSeconds * sign),
nanos: absNanos === 0 ? 0 : absNanos * sign, // deliberately avoid signed 0 - it does not serialize
});
}
/**
* Convert a google.protobuf.Duration to a Unix timestamp in milliseconds.
*/
function durationMs(duration) {
return Number(duration.seconds) * 1000 + Math.round(duration.nanos / 1000000);
}
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/any.proto.
*/
export declare const file_google_protobuf_any: GenFile;
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
* // or ...
* if (any.isSameTypeAs(Foo.getDefaultInstance())) {
* foo = any.unpack(Foo.getDefaultInstance());
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*
*
* @generated from message google.protobuf.Any
*/
export type Any = Message<"google.protobuf.Any"> & {
/**
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com. As of May 2023, there are no widely used type server
* implementations and no plans to implement one.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
*
* @generated from field: string type_url = 1;
*/
typeUrl: string;
/**
* Must be a valid serialized protocol buffer of the above specified type.
*
* @generated from field: bytes value = 2;
*/
value: Uint8Array;
};
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
* // or ...
* if (any.isSameTypeAs(Foo.getDefaultInstance())) {
* foo = any.unpack(Foo.getDefaultInstance());
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*
*
* @generated from message google.protobuf.Any
*/
export type AnyJson = {
"@type"?: string;
};
/**
* Describes the message google.protobuf.Any.
* Use `create(AnySchema)` to create a new message.
*/
export declare const AnySchema: GenMessage<Any, {
jsonType: AnyJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnySchema = exports.file_google_protobuf_any = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/any.proto.
*/
exports.file_google_protobuf_any = (0, file_js_1.fileDesc)("Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYiJgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2NvbS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
/**
* Describes the message google.protobuf.Any.
* Use `create(AnySchema)` to create a new message.
*/
exports.AnySchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_any, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { SourceContext, SourceContextJson } from "./source_context_pb.js";
import type { Option, OptionJson, Syntax, SyntaxJson } from "./type_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/api.proto.
*/
export declare const file_google_protobuf_api: GenFile;
/**
* Api is a light-weight descriptor for an API Interface.
*
* Interfaces are also described as "protocol buffer services" in some contexts,
* such as by the "service" keyword in a .proto file, but they are different
* from API Services, which represent a concrete implementation of an interface
* as opposed to simply a description of methods and bindings. They are also
* sometimes simply referred to as "APIs" in other contexts, such as the name of
* this message itself. See https://cloud.google.com/apis/design/glossary for
* detailed terminology.
*
* New usages of this message as an alternative to ServiceDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Api
*/
export type Api = Message<"google.protobuf.Api"> & {
/**
* The fully qualified name of this interface, including package name
* followed by the interface's simple name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The methods of this interface, in unspecified order.
*
* @generated from field: repeated google.protobuf.Method methods = 2;
*/
methods: Method[];
/**
* Any metadata attached to the interface.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
/**
* A version string for this interface. If specified, must have the form
* `major-version.minor-version`, as in `1.10`. If the minor version is
* omitted, it defaults to zero. If the entire version field is empty, the
* major version is derived from the package name, as outlined below. If the
* field is not empty, the version in the package name will be verified to be
* consistent with what is provided here.
*
* The versioning schema uses [semantic
* versioning](http://semver.org) where the major version number
* indicates a breaking change and the minor version an additive,
* non-breaking change. Both version numbers are signals to users
* what to expect from different versions, and should be carefully
* chosen based on the product plan.
*
* The major version is also reflected in the package name of the
* interface, which must end in `v<major-version>`, as in
* `google.feature.v1`. For major versions 0 and 1, the suffix can
* be omitted. Zero major versions must only be used for
* experimental, non-GA interfaces.
*
*
* @generated from field: string version = 4;
*/
version: string;
/**
* Source context for the protocol buffer service represented by this
* message.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContext | undefined;
/**
* Included interfaces. See [Mixin][].
*
* @generated from field: repeated google.protobuf.Mixin mixins = 6;
*/
mixins: Mixin[];
/**
* The source syntax of the service.
*
* @generated from field: google.protobuf.Syntax syntax = 7;
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 8;
*/
edition: string;
};
/**
* Api is a light-weight descriptor for an API Interface.
*
* Interfaces are also described as "protocol buffer services" in some contexts,
* such as by the "service" keyword in a .proto file, but they are different
* from API Services, which represent a concrete implementation of an interface
* as opposed to simply a description of methods and bindings. They are also
* sometimes simply referred to as "APIs" in other contexts, such as the name of
* this message itself. See https://cloud.google.com/apis/design/glossary for
* detailed terminology.
*
* New usages of this message as an alternative to ServiceDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Api
*/
export type ApiJson = {
/**
* The fully qualified name of this interface, including package name
* followed by the interface's simple name.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* The methods of this interface, in unspecified order.
*
* @generated from field: repeated google.protobuf.Method methods = 2;
*/
methods?: MethodJson[];
/**
* Any metadata attached to the interface.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options?: OptionJson[];
/**
* A version string for this interface. If specified, must have the form
* `major-version.minor-version`, as in `1.10`. If the minor version is
* omitted, it defaults to zero. If the entire version field is empty, the
* major version is derived from the package name, as outlined below. If the
* field is not empty, the version in the package name will be verified to be
* consistent with what is provided here.
*
* The versioning schema uses [semantic
* versioning](http://semver.org) where the major version number
* indicates a breaking change and the minor version an additive,
* non-breaking change. Both version numbers are signals to users
* what to expect from different versions, and should be carefully
* chosen based on the product plan.
*
* The major version is also reflected in the package name of the
* interface, which must end in `v<major-version>`, as in
* `google.feature.v1`. For major versions 0 and 1, the suffix can
* be omitted. Zero major versions must only be used for
* experimental, non-GA interfaces.
*
*
* @generated from field: string version = 4;
*/
version?: string;
/**
* Source context for the protocol buffer service represented by this
* message.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContextJson;
/**
* Included interfaces. See [Mixin][].
*
* @generated from field: repeated google.protobuf.Mixin mixins = 6;
*/
mixins?: MixinJson[];
/**
* The source syntax of the service.
*
* @generated from field: google.protobuf.Syntax syntax = 7;
*/
syntax?: SyntaxJson;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 8;
*/
edition?: string;
};
/**
* Describes the message google.protobuf.Api.
* Use `create(ApiSchema)` to create a new message.
*/
export declare const ApiSchema: GenMessage<Api, {
jsonType: ApiJson;
}>;
/**
* Method represents a method of an API interface.
*
* New usages of this message as an alternative to MethodDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Method
*/
export type Method = Message<"google.protobuf.Method"> & {
/**
* The simple name of this method.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* A URL of the input message type.
*
* @generated from field: string request_type_url = 2;
*/
requestTypeUrl: string;
/**
* If true, the request is streamed.
*
* @generated from field: bool request_streaming = 3;
*/
requestStreaming: boolean;
/**
* The URL of the output message type.
*
* @generated from field: string response_type_url = 4;
*/
responseTypeUrl: string;
/**
* If true, the response is streamed.
*
* @generated from field: bool response_streaming = 5;
*/
responseStreaming: boolean;
/**
* Any metadata attached to the method.
*
* @generated from field: repeated google.protobuf.Option options = 6;
*/
options: Option[];
/**
* The source syntax of this method.
*
* This field should be ignored, instead the syntax should be inherited from
* Api. This is similar to Field and EnumValue.
*
* @generated from field: google.protobuf.Syntax syntax = 7 [deprecated = true];
* @deprecated
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* This field should be ignored, instead the edition should be inherited from
* Api. This is similar to Field and EnumValue.
*
* @generated from field: string edition = 8 [deprecated = true];
* @deprecated
*/
edition: string;
};
/**
* Method represents a method of an API interface.
*
* New usages of this message as an alternative to MethodDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Method
*/
export type MethodJson = {
/**
* The simple name of this method.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* A URL of the input message type.
*
* @generated from field: string request_type_url = 2;
*/
requestTypeUrl?: string;
/**
* If true, the request is streamed.
*
* @generated from field: bool request_streaming = 3;
*/
requestStreaming?: boolean;
/**
* The URL of the output message type.
*
* @generated from field: string response_type_url = 4;
*/
responseTypeUrl?: string;
/**
* If true, the response is streamed.
*
* @generated from field: bool response_streaming = 5;
*/
responseStreaming?: boolean;
/**
* Any metadata attached to the method.
*
* @generated from field: repeated google.protobuf.Option options = 6;
*/
options?: OptionJson[];
/**
* The source syntax of this method.
*
* This field should be ignored, instead the syntax should be inherited from
* Api. This is similar to Field and EnumValue.
*
* @generated from field: google.protobuf.Syntax syntax = 7 [deprecated = true];
* @deprecated
*/
syntax?: SyntaxJson;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* This field should be ignored, instead the edition should be inherited from
* Api. This is similar to Field and EnumValue.
*
* @generated from field: string edition = 8 [deprecated = true];
* @deprecated
*/
edition?: string;
};
/**
* Describes the message google.protobuf.Method.
* Use `create(MethodSchema)` to create a new message.
*/
export declare const MethodSchema: GenMessage<Method, {
jsonType: MethodJson;
}>;
/**
* Declares an API Interface to be included in this interface. The including
* interface must redeclare all the methods from the included interface, but
* documentation and options are inherited as follows:
*
* - If after comment and whitespace stripping, the documentation
* string of the redeclared method is empty, it will be inherited
* from the original method.
*
* - Each annotation belonging to the service config (http,
* visibility) which is not set in the redeclared method will be
* inherited.
*
* - If an http annotation is inherited, the path pattern will be
* modified as follows. Any version prefix will be replaced by the
* version of the including interface plus the [root][] path if
* specified.
*
* Example of a simple mixin:
*
* package google.acl.v1;
* service AccessControl {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v1/{resource=**}:getAcl";
* }
* }
*
* package google.storage.v2;
* service Storage {
* rpc GetAcl(GetAclRequest) returns (Acl);
*
* // Get a data record.
* rpc GetData(GetDataRequest) returns (Data) {
* option (google.api.http).get = "/v2/{resource=**}";
* }
* }
*
* Example of a mixin configuration:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
*
* The mixin construct implies that all methods in `AccessControl` are
* also declared with same name and request/response types in
* `Storage`. A documentation generator or annotation processor will
* see the effective `Storage.GetAcl` method after inheriting
* documentation and annotations as follows:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/{resource=**}:getAcl";
* }
* ...
* }
*
* Note how the version in the path pattern changed from `v1` to `v2`.
*
* If the `root` field in the mixin is specified, it should be a
* relative path under which inherited HTTP paths are placed. Example:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
* root: acls
*
* This implies the following inherited HTTP annotation:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
* }
* ...
* }
*
* @generated from message google.protobuf.Mixin
*/
export type Mixin = Message<"google.protobuf.Mixin"> & {
/**
* The fully qualified name of the interface which is included.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* If non-empty specifies a path under which inherited HTTP paths
* are rooted.
*
* @generated from field: string root = 2;
*/
root: string;
};
/**
* Declares an API Interface to be included in this interface. The including
* interface must redeclare all the methods from the included interface, but
* documentation and options are inherited as follows:
*
* - If after comment and whitespace stripping, the documentation
* string of the redeclared method is empty, it will be inherited
* from the original method.
*
* - Each annotation belonging to the service config (http,
* visibility) which is not set in the redeclared method will be
* inherited.
*
* - If an http annotation is inherited, the path pattern will be
* modified as follows. Any version prefix will be replaced by the
* version of the including interface plus the [root][] path if
* specified.
*
* Example of a simple mixin:
*
* package google.acl.v1;
* service AccessControl {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v1/{resource=**}:getAcl";
* }
* }
*
* package google.storage.v2;
* service Storage {
* rpc GetAcl(GetAclRequest) returns (Acl);
*
* // Get a data record.
* rpc GetData(GetDataRequest) returns (Data) {
* option (google.api.http).get = "/v2/{resource=**}";
* }
* }
*
* Example of a mixin configuration:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
*
* The mixin construct implies that all methods in `AccessControl` are
* also declared with same name and request/response types in
* `Storage`. A documentation generator or annotation processor will
* see the effective `Storage.GetAcl` method after inheriting
* documentation and annotations as follows:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/{resource=**}:getAcl";
* }
* ...
* }
*
* Note how the version in the path pattern changed from `v1` to `v2`.
*
* If the `root` field in the mixin is specified, it should be a
* relative path under which inherited HTTP paths are placed. Example:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
* root: acls
*
* This implies the following inherited HTTP annotation:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
* }
* ...
* }
*
* @generated from message google.protobuf.Mixin
*/
export type MixinJson = {
/**
* The fully qualified name of the interface which is included.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* If non-empty specifies a path under which inherited HTTP paths
* are rooted.
*
* @generated from field: string root = 2;
*/
root?: string;
};
/**
* Describes the message google.protobuf.Mixin.
* Use `create(MixinSchema)` to create a new message.
*/
export declare const MixinSchema: GenMessage<Mixin, {
jsonType: MixinJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.MixinSchema = exports.MethodSchema = exports.ApiSchema = exports.file_google_protobuf_api = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const source_context_pb_js_1 = require("./source_context_pb.js");
const type_pb_js_1 = require("./type_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/api.proto.
*/
exports.file_google_protobuf_api = (0, file_js_1.fileDesc)("Chlnb29nbGUvcHJvdG9idWYvYXBpLnByb3RvEg9nb29nbGUucHJvdG9idWYikgIKA0FwaRIMCgRuYW1lGAEgASgJEigKB21ldGhvZHMYAiADKAsyFy5nb29nbGUucHJvdG9idWYuTWV0aG9kEigKB29wdGlvbnMYAyADKAsyFy5nb29nbGUucHJvdG9idWYuT3B0aW9uEg8KB3ZlcnNpb24YBCABKAkSNgoOc291cmNlX2NvbnRleHQYBSABKAsyHi5nb29nbGUucHJvdG9idWYuU291cmNlQ29udGV4dBImCgZtaXhpbnMYBiADKAsyFi5nb29nbGUucHJvdG9idWYuTWl4aW4SJwoGc3ludGF4GAcgASgOMhcuZ29vZ2xlLnByb3RvYnVmLlN5bnRheBIPCgdlZGl0aW9uGAggASgJIu4BCgZNZXRob2QSDAoEbmFtZRgBIAEoCRIYChByZXF1ZXN0X3R5cGVfdXJsGAIgASgJEhkKEXJlcXVlc3Rfc3RyZWFtaW5nGAMgASgIEhkKEXJlc3BvbnNlX3R5cGVfdXJsGAQgASgJEhoKEnJlc3BvbnNlX3N0cmVhbWluZxgFIAEoCBIoCgdvcHRpb25zGAYgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhIrCgZzeW50YXgYByABKA4yFy5nb29nbGUucHJvdG9idWYuU3ludGF4QgIYARITCgdlZGl0aW9uGAggASgJQgIYASIjCgVNaXhpbhIMCgRuYW1lGAEgASgJEgwKBHJvb3QYAiABKAlCdgoTY29tLmdvb2dsZS5wcm90b2J1ZkIIQXBpUHJvdG9QAVosZ29vZ2xlLmdvbGFuZy5vcmcvcHJvdG9idWYvdHlwZXMva25vd24vYXBpcGKiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw", [source_context_pb_js_1.file_google_protobuf_source_context, type_pb_js_1.file_google_protobuf_type]);
/**
* Describes the message google.protobuf.Api.
* Use `create(ApiSchema)` to create a new message.
*/
exports.ApiSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_api, 0);
/**
* Describes the message google.protobuf.Method.
* Use `create(MethodSchema)` to create a new message.
*/
exports.MethodSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_api, 1);
/**
* Describes the message google.protobuf.Mixin.
* Use `create(MixinSchema)` to create a new message.
*/
exports.MixinSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_api, 2);
import type { GenEnum, GenFile, GenMessage } from "../../../../../codegenv2/types.js";
import type { FileDescriptorProto, FileDescriptorProtoJson, GeneratedCodeInfo, GeneratedCodeInfoJson } from "../descriptor_pb.js";
import type { Message } from "../../../../../types.js";
/**
* Describes the file google/protobuf/compiler/plugin.proto.
*/
export declare const file_google_protobuf_compiler_plugin: GenFile;
/**
* The version number of protocol compiler.
*
* @generated from message google.protobuf.compiler.Version
*/
export type Version = Message<"google.protobuf.compiler.Version"> & {
/**
* @generated from field: optional int32 major = 1;
*/
major: number;
/**
* @generated from field: optional int32 minor = 2;
*/
minor: number;
/**
* @generated from field: optional int32 patch = 3;
*/
patch: number;
/**
* A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
* be empty for mainline stable releases.
*
* @generated from field: optional string suffix = 4;
*/
suffix: string;
};
/**
* The version number of protocol compiler.
*
* @generated from message google.protobuf.compiler.Version
*/
export type VersionJson = {
/**
* @generated from field: optional int32 major = 1;
*/
major?: number;
/**
* @generated from field: optional int32 minor = 2;
*/
minor?: number;
/**
* @generated from field: optional int32 patch = 3;
*/
patch?: number;
/**
* A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
* be empty for mainline stable releases.
*
* @generated from field: optional string suffix = 4;
*/
suffix?: string;
};
/**
* Describes the message google.protobuf.compiler.Version.
* Use `create(VersionSchema)` to create a new message.
*/
export declare const VersionSchema: GenMessage<Version, {
jsonType: VersionJson;
}>;
/**
* An encoded CodeGeneratorRequest is written to the plugin's stdin.
*
* @generated from message google.protobuf.compiler.CodeGeneratorRequest
*/
export type CodeGeneratorRequest = Message<"google.protobuf.compiler.CodeGeneratorRequest"> & {
/**
* The .proto files that were explicitly listed on the command-line. The
* code generator should generate code only for these files. Each file's
* descriptor will be included in proto_file, below.
*
* @generated from field: repeated string file_to_generate = 1;
*/
fileToGenerate: string[];
/**
* The generator parameter passed on the command-line.
*
* @generated from field: optional string parameter = 2;
*/
parameter: string;
/**
* FileDescriptorProtos for all files in files_to_generate and everything
* they import. The files will appear in topological order, so each file
* appears before any file that imports it.
*
* Note: the files listed in files_to_generate will include runtime-retention
* options only, but all other files will include source-retention options.
* The source_file_descriptors field below is available in case you need
* source-retention options for files_to_generate.
*
* protoc guarantees that all proto_files will be written after
* the fields above, even though this is not technically guaranteed by the
* protobuf wire format. This theoretically could allow a plugin to stream
* in the FileDescriptorProtos and handle them one by one rather than read
* the entire set into memory at once. However, as of this writing, this
* is not similarly optimized on protoc's end -- it will store all fields in
* memory at once before sending them to the plugin.
*
* Type names of fields and extensions in the FileDescriptorProto are always
* fully qualified.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto proto_file = 15;
*/
protoFile: FileDescriptorProto[];
/**
* File descriptors with all options, including source-retention options.
* These descriptors are only provided for the files listed in
* files_to_generate.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto source_file_descriptors = 17;
*/
sourceFileDescriptors: FileDescriptorProto[];
/**
* The version number of protocol compiler.
*
* @generated from field: optional google.protobuf.compiler.Version compiler_version = 3;
*/
compilerVersion?: Version | undefined;
};
/**
* An encoded CodeGeneratorRequest is written to the plugin's stdin.
*
* @generated from message google.protobuf.compiler.CodeGeneratorRequest
*/
export type CodeGeneratorRequestJson = {
/**
* The .proto files that were explicitly listed on the command-line. The
* code generator should generate code only for these files. Each file's
* descriptor will be included in proto_file, below.
*
* @generated from field: repeated string file_to_generate = 1;
*/
fileToGenerate?: string[];
/**
* The generator parameter passed on the command-line.
*
* @generated from field: optional string parameter = 2;
*/
parameter?: string;
/**
* FileDescriptorProtos for all files in files_to_generate and everything
* they import. The files will appear in topological order, so each file
* appears before any file that imports it.
*
* Note: the files listed in files_to_generate will include runtime-retention
* options only, but all other files will include source-retention options.
* The source_file_descriptors field below is available in case you need
* source-retention options for files_to_generate.
*
* protoc guarantees that all proto_files will be written after
* the fields above, even though this is not technically guaranteed by the
* protobuf wire format. This theoretically could allow a plugin to stream
* in the FileDescriptorProtos and handle them one by one rather than read
* the entire set into memory at once. However, as of this writing, this
* is not similarly optimized on protoc's end -- it will store all fields in
* memory at once before sending them to the plugin.
*
* Type names of fields and extensions in the FileDescriptorProto are always
* fully qualified.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto proto_file = 15;
*/
protoFile?: FileDescriptorProtoJson[];
/**
* File descriptors with all options, including source-retention options.
* These descriptors are only provided for the files listed in
* files_to_generate.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto source_file_descriptors = 17;
*/
sourceFileDescriptors?: FileDescriptorProtoJson[];
/**
* The version number of protocol compiler.
*
* @generated from field: optional google.protobuf.compiler.Version compiler_version = 3;
*/
compilerVersion?: VersionJson;
};
/**
* Describes the message google.protobuf.compiler.CodeGeneratorRequest.
* Use `create(CodeGeneratorRequestSchema)` to create a new message.
*/
export declare const CodeGeneratorRequestSchema: GenMessage<CodeGeneratorRequest, {
jsonType: CodeGeneratorRequestJson;
}>;
/**
* The plugin writes an encoded CodeGeneratorResponse to stdout.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse
*/
export type CodeGeneratorResponse = Message<"google.protobuf.compiler.CodeGeneratorResponse"> & {
/**
* Error message. If non-empty, code generation failed. The plugin process
* should exit with status code zero even if it reports an error in this way.
*
* This should be used to indicate errors in .proto files which prevent the
* code generator from generating correct code. Errors which indicate a
* problem in protoc itself -- such as the input CodeGeneratorRequest being
* unparseable -- should be reported by writing a message to stderr and
* exiting with a non-zero status code.
*
* @generated from field: optional string error = 1;
*/
error: string;
/**
* A bitmask of supported features that the code generator supports.
* This is a bitwise "or" of values from the Feature enum.
*
* @generated from field: optional uint64 supported_features = 2;
*/
supportedFeatures: bigint;
/**
* The minimum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 minimum_edition = 3;
*/
minimumEdition: number;
/**
* The maximum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 maximum_edition = 4;
*/
maximumEdition: number;
/**
* @generated from field: repeated google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
*/
file: CodeGeneratorResponse_File[];
};
/**
* The plugin writes an encoded CodeGeneratorResponse to stdout.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse
*/
export type CodeGeneratorResponseJson = {
/**
* Error message. If non-empty, code generation failed. The plugin process
* should exit with status code zero even if it reports an error in this way.
*
* This should be used to indicate errors in .proto files which prevent the
* code generator from generating correct code. Errors which indicate a
* problem in protoc itself -- such as the input CodeGeneratorRequest being
* unparseable -- should be reported by writing a message to stderr and
* exiting with a non-zero status code.
*
* @generated from field: optional string error = 1;
*/
error?: string;
/**
* A bitmask of supported features that the code generator supports.
* This is a bitwise "or" of values from the Feature enum.
*
* @generated from field: optional uint64 supported_features = 2;
*/
supportedFeatures?: string;
/**
* The minimum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 minimum_edition = 3;
*/
minimumEdition?: number;
/**
* The maximum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 maximum_edition = 4;
*/
maximumEdition?: number;
/**
* @generated from field: repeated google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
*/
file?: CodeGeneratorResponse_FileJson[];
};
/**
* Describes the message google.protobuf.compiler.CodeGeneratorResponse.
* Use `create(CodeGeneratorResponseSchema)` to create a new message.
*/
export declare const CodeGeneratorResponseSchema: GenMessage<CodeGeneratorResponse, {
jsonType: CodeGeneratorResponseJson;
}>;
/**
* Represents a single generated file.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse.File
*/
export type CodeGeneratorResponse_File = Message<"google.protobuf.compiler.CodeGeneratorResponse.File"> & {
/**
* The file name, relative to the output directory. The name must not
* contain "." or ".." components and must be relative, not be absolute (so,
* the file cannot lie outside the output directory). "/" must be used as
* the path separator, not "\".
*
* If the name is omitted, the content will be appended to the previous
* file. This allows the generator to break large files into small chunks,
* and allows the generated text to be streamed back to protoc so that large
* files need not reside completely in memory at one time. Note that as of
* this writing protoc does not optimize for this -- it will read the entire
* CodeGeneratorResponse before writing files to disk.
*
* @generated from field: optional string name = 1;
*/
name: string;
/**
* If non-empty, indicates that the named file should already exist, and the
* content here is to be inserted into that file at a defined insertion
* point. This feature allows a code generator to extend the output
* produced by another code generator. The original generator may provide
* insertion points by placing special annotations in the file that look
* like:
* @@protoc_insertion_point(NAME)
* The annotation can have arbitrary text before and after it on the line,
* which allows it to be placed in a comment. NAME should be replaced with
* an identifier naming the point -- this is what other generators will use
* as the insertion_point. Code inserted at this point will be placed
* immediately above the line containing the insertion point (thus multiple
* insertions to the same point will come out in the order they were added).
* The double-@ is intended to make it unlikely that the generated code
* could contain things that look like insertion points by accident.
*
* For example, the C++ code generator places the following line in the
* .pb.h files that it generates:
* // @@protoc_insertion_point(namespace_scope)
* This line appears within the scope of the file's package namespace, but
* outside of any particular class. Another plugin can then specify the
* insertion_point "namespace_scope" to generate additional classes or
* other declarations that should be placed in this scope.
*
* Note that if the line containing the insertion point begins with
* whitespace, the same whitespace will be added to every line of the
* inserted text. This is useful for languages like Python, where
* indentation matters. In these languages, the insertion point comment
* should be indented the same amount as any inserted code will need to be
* in order to work correctly in that context.
*
* The code generator that generates the initial file and the one which
* inserts into it must both run as part of a single invocation of protoc.
* Code generators are executed in the order in which they appear on the
* command line.
*
* If |insertion_point| is present, |name| must also be present.
*
* @generated from field: optional string insertion_point = 2;
*/
insertionPoint: string;
/**
* The file contents.
*
* @generated from field: optional string content = 15;
*/
content: string;
/**
* Information describing the file content being inserted. If an insertion
* point is used, this information will be appropriately offset and inserted
* into the code generation metadata for the generated files.
*
* @generated from field: optional google.protobuf.GeneratedCodeInfo generated_code_info = 16;
*/
generatedCodeInfo?: GeneratedCodeInfo | undefined;
};
/**
* Represents a single generated file.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse.File
*/
export type CodeGeneratorResponse_FileJson = {
/**
* The file name, relative to the output directory. The name must not
* contain "." or ".." components and must be relative, not be absolute (so,
* the file cannot lie outside the output directory). "/" must be used as
* the path separator, not "\".
*
* If the name is omitted, the content will be appended to the previous
* file. This allows the generator to break large files into small chunks,
* and allows the generated text to be streamed back to protoc so that large
* files need not reside completely in memory at one time. Note that as of
* this writing protoc does not optimize for this -- it will read the entire
* CodeGeneratorResponse before writing files to disk.
*
* @generated from field: optional string name = 1;
*/
name?: string;
/**
* If non-empty, indicates that the named file should already exist, and the
* content here is to be inserted into that file at a defined insertion
* point. This feature allows a code generator to extend the output
* produced by another code generator. The original generator may provide
* insertion points by placing special annotations in the file that look
* like:
* @@protoc_insertion_point(NAME)
* The annotation can have arbitrary text before and after it on the line,
* which allows it to be placed in a comment. NAME should be replaced with
* an identifier naming the point -- this is what other generators will use
* as the insertion_point. Code inserted at this point will be placed
* immediately above the line containing the insertion point (thus multiple
* insertions to the same point will come out in the order they were added).
* The double-@ is intended to make it unlikely that the generated code
* could contain things that look like insertion points by accident.
*
* For example, the C++ code generator places the following line in the
* .pb.h files that it generates:
* // @@protoc_insertion_point(namespace_scope)
* This line appears within the scope of the file's package namespace, but
* outside of any particular class. Another plugin can then specify the
* insertion_point "namespace_scope" to generate additional classes or
* other declarations that should be placed in this scope.
*
* Note that if the line containing the insertion point begins with
* whitespace, the same whitespace will be added to every line of the
* inserted text. This is useful for languages like Python, where
* indentation matters. In these languages, the insertion point comment
* should be indented the same amount as any inserted code will need to be
* in order to work correctly in that context.
*
* The code generator that generates the initial file and the one which
* inserts into it must both run as part of a single invocation of protoc.
* Code generators are executed in the order in which they appear on the
* command line.
*
* If |insertion_point| is present, |name| must also be present.
*
* @generated from field: optional string insertion_point = 2;
*/
insertionPoint?: string;
/**
* The file contents.
*
* @generated from field: optional string content = 15;
*/
content?: string;
/**
* Information describing the file content being inserted. If an insertion
* point is used, this information will be appropriately offset and inserted
* into the code generation metadata for the generated files.
*
* @generated from field: optional google.protobuf.GeneratedCodeInfo generated_code_info = 16;
*/
generatedCodeInfo?: GeneratedCodeInfoJson;
};
/**
* Describes the message google.protobuf.compiler.CodeGeneratorResponse.File.
* Use `create(CodeGeneratorResponse_FileSchema)` to create a new message.
*/
export declare const CodeGeneratorResponse_FileSchema: GenMessage<CodeGeneratorResponse_File, {
jsonType: CodeGeneratorResponse_FileJson;
}>;
/**
* Sync with code_generator.h.
*
* @generated from enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
export declare enum CodeGeneratorResponse_Feature {
/**
* @generated from enum value: FEATURE_NONE = 0;
*/
NONE = 0,
/**
* @generated from enum value: FEATURE_PROTO3_OPTIONAL = 1;
*/
PROTO3_OPTIONAL = 1,
/**
* @generated from enum value: FEATURE_SUPPORTS_EDITIONS = 2;
*/
SUPPORTS_EDITIONS = 2
}
/**
* Sync with code_generator.h.
*
* @generated from enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
export type CodeGeneratorResponse_FeatureJson = "FEATURE_NONE" | "FEATURE_PROTO3_OPTIONAL" | "FEATURE_SUPPORTS_EDITIONS";
/**
* Describes the enum google.protobuf.compiler.CodeGeneratorResponse.Feature.
*/
export declare const CodeGeneratorResponse_FeatureSchema: GenEnum<CodeGeneratorResponse_Feature, CodeGeneratorResponse_FeatureJson>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGeneratorResponse_FeatureSchema = exports.CodeGeneratorResponse_Feature = exports.CodeGeneratorResponse_FileSchema = exports.CodeGeneratorResponseSchema = exports.CodeGeneratorRequestSchema = exports.VersionSchema = exports.file_google_protobuf_compiler_plugin = void 0;
const file_js_1 = require("../../../../../codegenv2/file.js");
const descriptor_pb_js_1 = require("../descriptor_pb.js");
const message_js_1 = require("../../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../../codegenv2/enum.js");
/**
* Describes the file google/protobuf/compiler/plugin.proto.
*/
exports.file_google_protobuf_compiler_plugin = (0, file_js_1.fileDesc)("CiVnb29nbGUvcHJvdG9idWYvY29tcGlsZXIvcGx1Z2luLnByb3RvEhhnb29nbGUucHJvdG9idWYuY29tcGlsZXIiRgoHVmVyc2lvbhINCgVtYWpvchgBIAEoBRINCgVtaW5vchgCIAEoBRINCgVwYXRjaBgDIAEoBRIOCgZzdWZmaXgYBCABKAkigQIKFENvZGVHZW5lcmF0b3JSZXF1ZXN0EhgKEGZpbGVfdG9fZ2VuZXJhdGUYASADKAkSEQoJcGFyYW1ldGVyGAIgASgJEjgKCnByb3RvX2ZpbGUYDyADKAsyJC5nb29nbGUucHJvdG9idWYuRmlsZURlc2NyaXB0b3JQcm90bxJFChdzb3VyY2VfZmlsZV9kZXNjcmlwdG9ycxgRIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5GaWxlRGVzY3JpcHRvclByb3RvEjsKEGNvbXBpbGVyX3ZlcnNpb24YAyABKAsyIS5nb29nbGUucHJvdG9idWYuY29tcGlsZXIuVmVyc2lvbiKSAwoVQ29kZUdlbmVyYXRvclJlc3BvbnNlEg0KBWVycm9yGAEgASgJEhoKEnN1cHBvcnRlZF9mZWF0dXJlcxgCIAEoBBIXCg9taW5pbXVtX2VkaXRpb24YAyABKAUSFwoPbWF4aW11bV9lZGl0aW9uGAQgASgFEkIKBGZpbGUYDyADKAsyNC5nb29nbGUucHJvdG9idWYuY29tcGlsZXIuQ29kZUdlbmVyYXRvclJlc3BvbnNlLkZpbGUafwoERmlsZRIMCgRuYW1lGAEgASgJEhcKD2luc2VydGlvbl9wb2ludBgCIAEoCRIPCgdjb250ZW50GA8gASgJEj8KE2dlbmVyYXRlZF9jb2RlX2luZm8YECABKAsyIi5nb29nbGUucHJvdG9idWYuR2VuZXJhdGVkQ29kZUluZm8iVwoHRmVhdHVyZRIQCgxGRUFUVVJFX05PTkUQABIbChdGRUFUVVJFX1BST1RPM19PUFRJT05BTBABEh0KGUZFQVRVUkVfU1VQUE9SVFNfRURJVElPTlMQAkJyChxjb20uZ29vZ2xlLnByb3RvYnVmLmNvbXBpbGVyQgxQbHVnaW5Qcm90b3NaKWdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL3BsdWdpbnBiqgIYR29vZ2xlLlByb3RvYnVmLkNvbXBpbGVy", [descriptor_pb_js_1.file_google_protobuf_descriptor]);
/**
* Describes the message google.protobuf.compiler.Version.
* Use `create(VersionSchema)` to create a new message.
*/
exports.VersionSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_compiler_plugin, 0);
/**
* Describes the message google.protobuf.compiler.CodeGeneratorRequest.
* Use `create(CodeGeneratorRequestSchema)` to create a new message.
*/
exports.CodeGeneratorRequestSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_compiler_plugin, 1);
/**
* Describes the message google.protobuf.compiler.CodeGeneratorResponse.
* Use `create(CodeGeneratorResponseSchema)` to create a new message.
*/
exports.CodeGeneratorResponseSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_compiler_plugin, 2);
/**
* Describes the message google.protobuf.compiler.CodeGeneratorResponse.File.
* Use `create(CodeGeneratorResponse_FileSchema)` to create a new message.
*/
exports.CodeGeneratorResponse_FileSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_compiler_plugin, 2, 0);
/**
* Sync with code_generator.h.
*
* @generated from enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
var CodeGeneratorResponse_Feature;
(function (CodeGeneratorResponse_Feature) {
/**
* @generated from enum value: FEATURE_NONE = 0;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["NONE"] = 0] = "NONE";
/**
* @generated from enum value: FEATURE_PROTO3_OPTIONAL = 1;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["PROTO3_OPTIONAL"] = 1] = "PROTO3_OPTIONAL";
/**
* @generated from enum value: FEATURE_SUPPORTS_EDITIONS = 2;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["SUPPORTS_EDITIONS"] = 2] = "SUPPORTS_EDITIONS";
})(CodeGeneratorResponse_Feature || (exports.CodeGeneratorResponse_Feature = CodeGeneratorResponse_Feature = {}));
/**
* Describes the enum google.protobuf.compiler.CodeGeneratorResponse.Feature.
*/
exports.CodeGeneratorResponse_FeatureSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_compiler_plugin, 2, 0);
import type { GenEnum, GenExtension, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { FeatureSet } from "./descriptor_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/cpp_features.proto.
*/
export declare const file_google_protobuf_cpp_features: GenFile;
/**
* @generated from message pb.CppFeatures
*/
export type CppFeatures = Message<"pb.CppFeatures"> & {
/**
* Whether or not to treat an enum field as closed. This option is only
* applicable to enum fields, and will be removed in the future. It is
* consistent with the legacy behavior of using proto3 enum types for proto2
* fields.
*
* @generated from field: optional bool legacy_closed_enum = 1;
*/
legacyClosedEnum: boolean;
/**
* @generated from field: optional pb.CppFeatures.StringType string_type = 2;
*/
stringType: CppFeatures_StringType;
/**
* @generated from field: optional bool enum_name_uses_string_view = 3;
*/
enumNameUsesStringView: boolean;
};
/**
* @generated from message pb.CppFeatures
*/
export type CppFeaturesJson = {
/**
* Whether or not to treat an enum field as closed. This option is only
* applicable to enum fields, and will be removed in the future. It is
* consistent with the legacy behavior of using proto3 enum types for proto2
* fields.
*
* @generated from field: optional bool legacy_closed_enum = 1;
*/
legacyClosedEnum?: boolean;
/**
* @generated from field: optional pb.CppFeatures.StringType string_type = 2;
*/
stringType?: CppFeatures_StringTypeJson;
/**
* @generated from field: optional bool enum_name_uses_string_view = 3;
*/
enumNameUsesStringView?: boolean;
};
/**
* Describes the message pb.CppFeatures.
* Use `create(CppFeaturesSchema)` to create a new message.
*/
export declare const CppFeaturesSchema: GenMessage<CppFeatures, {
jsonType: CppFeaturesJson;
}>;
/**
* @generated from enum pb.CppFeatures.StringType
*/
export declare enum CppFeatures_StringType {
/**
* @generated from enum value: STRING_TYPE_UNKNOWN = 0;
*/
STRING_TYPE_UNKNOWN = 0,
/**
* @generated from enum value: VIEW = 1;
*/
VIEW = 1,
/**
* @generated from enum value: CORD = 2;
*/
CORD = 2,
/**
* @generated from enum value: STRING = 3;
*/
STRING = 3
}
/**
* @generated from enum pb.CppFeatures.StringType
*/
export type CppFeatures_StringTypeJson = "STRING_TYPE_UNKNOWN" | "VIEW" | "CORD" | "STRING";
/**
* Describes the enum pb.CppFeatures.StringType.
*/
export declare const CppFeatures_StringTypeSchema: GenEnum<CppFeatures_StringType, CppFeatures_StringTypeJson>;
/**
* @generated from extension: optional pb.CppFeatures cpp = 1000;
*/
export declare const cpp: GenExtension<FeatureSet, CppFeatures>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.cpp = exports.CppFeatures_StringTypeSchema = exports.CppFeatures_StringType = exports.CppFeaturesSchema = exports.file_google_protobuf_cpp_features = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const descriptor_pb_js_1 = require("./descriptor_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
const extension_js_1 = require("../../../../codegenv2/extension.js");
/**
* Describes the file google/protobuf/cpp_features.proto.
*/
exports.file_google_protobuf_cpp_features = (0, file_js_1.fileDesc)("CiJnb29nbGUvcHJvdG9idWYvY3BwX2ZlYXR1cmVzLnByb3RvEgJwYiL8AwoLQ3BwRmVhdHVyZXMS+wEKEmxlZ2FjeV9jbG9zZWRfZW51bRgBIAEoCELeAYgBAZgBBJgBAaIBCRIEdHJ1ZRiEB6IBChIFZmFsc2UY5weyAbgBCOgHEOgHGq8BVGhlIGxlZ2FjeSBjbG9zZWQgZW51bSBiZWhhdmlvciBpbiBDKysgaXMgZGVwcmVjYXRlZCBhbmQgaXMgc2NoZWR1bGVkIHRvIGJlIHJlbW92ZWQgaW4gZWRpdGlvbiAyMDI1LiAgU2VlIGh0dHA6Ly9wcm90b2J1Zi5kZXYvcHJvZ3JhbW1pbmctZ3VpZGVzL2VudW0vI2NwcCBmb3IgbW9yZSBpbmZvcm1hdGlvbhJaCgtzdHJpbmdfdHlwZRgCIAEoDjIaLnBiLkNwcEZlYXR1cmVzLlN0cmluZ1R5cGVCKYgBAZgBBJgBAaIBCxIGU1RSSU5HGIQHogEJEgRWSUVXGOkHsgEDCOgHEkwKGmVudW1fbmFtZV91c2VzX3N0cmluZ192aWV3GAMgASgIQiiIAQGYAQaYAQGiAQoSBWZhbHNlGIQHogEJEgR0cnVlGOkHsgEDCOkHIkUKClN0cmluZ1R5cGUSFwoTU1RSSU5HX1RZUEVfVU5LTk9XThAAEggKBFZJRVcQARIICgRDT1JEEAISCgoGU1RSSU5HEAM6PwoDY3BwEhsuZ29vZ2xlLnByb3RvYnVmLkZlYXR1cmVTZXQY6AcgASgLMg8ucGIuQ3BwRmVhdHVyZXNSA2NwcA", [descriptor_pb_js_1.file_google_protobuf_descriptor]);
/**
* Describes the message pb.CppFeatures.
* Use `create(CppFeaturesSchema)` to create a new message.
*/
exports.CppFeaturesSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_cpp_features, 0);
/**
* @generated from enum pb.CppFeatures.StringType
*/
var CppFeatures_StringType;
(function (CppFeatures_StringType) {
/**
* @generated from enum value: STRING_TYPE_UNKNOWN = 0;
*/
CppFeatures_StringType[CppFeatures_StringType["STRING_TYPE_UNKNOWN"] = 0] = "STRING_TYPE_UNKNOWN";
/**
* @generated from enum value: VIEW = 1;
*/
CppFeatures_StringType[CppFeatures_StringType["VIEW"] = 1] = "VIEW";
/**
* @generated from enum value: CORD = 2;
*/
CppFeatures_StringType[CppFeatures_StringType["CORD"] = 2] = "CORD";
/**
* @generated from enum value: STRING = 3;
*/
CppFeatures_StringType[CppFeatures_StringType["STRING"] = 3] = "STRING";
})(CppFeatures_StringType || (exports.CppFeatures_StringType = CppFeatures_StringType = {}));
/**
* Describes the enum pb.CppFeatures.StringType.
*/
exports.CppFeatures_StringTypeSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_cpp_features, 0, 0);
/**
* @generated from extension: optional pb.CppFeatures cpp = 1000;
*/
exports.cpp = (0, extension_js_1.extDesc)(exports.file_google_protobuf_cpp_features, 0);

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/duration.proto.
*/
export declare const file_google_protobuf_duration: GenFile;
/**
* A Duration represents a signed, fixed-length span of time represented
* as a count of seconds and fractions of seconds at nanosecond
* resolution. It is independent of any calendar and concepts like "day"
* or "month". It is related to Timestamp in that the difference between
* two Timestamp values is a Duration and it can be added or subtracted
* from a Timestamp. Range is approximately +-10,000 years.
*
* # Examples
*
* Example 1: Compute Duration from two Timestamps in pseudo code.
*
* Timestamp start = ...;
* Timestamp end = ...;
* Duration duration = ...;
*
* duration.seconds = end.seconds - start.seconds;
* duration.nanos = end.nanos - start.nanos;
*
* if (duration.seconds < 0 && duration.nanos > 0) {
* duration.seconds += 1;
* duration.nanos -= 1000000000;
* } else if (duration.seconds > 0 && duration.nanos < 0) {
* duration.seconds -= 1;
* duration.nanos += 1000000000;
* }
*
* Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
*
* Timestamp start = ...;
* Duration duration = ...;
* Timestamp end = ...;
*
* end.seconds = start.seconds + duration.seconds;
* end.nanos = start.nanos + duration.nanos;
*
* if (end.nanos < 0) {
* end.seconds -= 1;
* end.nanos += 1000000000;
* } else if (end.nanos >= 1000000000) {
* end.seconds += 1;
* end.nanos -= 1000000000;
* }
*
* Example 3: Compute Duration from datetime.timedelta in Python.
*
* td = datetime.timedelta(days=3, minutes=10)
* duration = Duration()
* duration.FromTimedelta(td)
*
* # JSON Mapping
*
* In JSON format, the Duration type is encoded as a string rather than an
* object, where the string ends in the suffix "s" (indicating seconds) and
* is preceded by the number of seconds, with nanoseconds expressed as
* fractional seconds. For example, 3 seconds with 0 nanoseconds should be
* encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
* be expressed in JSON format as "3.000000001s", and 3 seconds and 1
* microsecond should be expressed in JSON format as "3.000001s".
*
*
* @generated from message google.protobuf.Duration
*/
export type Duration = Message<"google.protobuf.Duration"> & {
/**
* Signed seconds of the span of time. Must be from -315,576,000,000
* to +315,576,000,000 inclusive. Note: these bounds are computed from:
* 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
*
* @generated from field: int64 seconds = 1;
*/
seconds: bigint;
/**
* Signed fractions of a second at nanosecond resolution of the span
* of time. Durations less than one second are represented with a 0
* `seconds` field and a positive or negative `nanos` field. For durations
* of one second or more, a non-zero value for the `nanos` field must be
* of the same sign as the `seconds` field. Must be from -999,999,999
* to +999,999,999 inclusive.
*
* @generated from field: int32 nanos = 2;
*/
nanos: number;
};
/**
* A Duration represents a signed, fixed-length span of time represented
* as a count of seconds and fractions of seconds at nanosecond
* resolution. It is independent of any calendar and concepts like "day"
* or "month". It is related to Timestamp in that the difference between
* two Timestamp values is a Duration and it can be added or subtracted
* from a Timestamp. Range is approximately +-10,000 years.
*
* # Examples
*
* Example 1: Compute Duration from two Timestamps in pseudo code.
*
* Timestamp start = ...;
* Timestamp end = ...;
* Duration duration = ...;
*
* duration.seconds = end.seconds - start.seconds;
* duration.nanos = end.nanos - start.nanos;
*
* if (duration.seconds < 0 && duration.nanos > 0) {
* duration.seconds += 1;
* duration.nanos -= 1000000000;
* } else if (duration.seconds > 0 && duration.nanos < 0) {
* duration.seconds -= 1;
* duration.nanos += 1000000000;
* }
*
* Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
*
* Timestamp start = ...;
* Duration duration = ...;
* Timestamp end = ...;
*
* end.seconds = start.seconds + duration.seconds;
* end.nanos = start.nanos + duration.nanos;
*
* if (end.nanos < 0) {
* end.seconds -= 1;
* end.nanos += 1000000000;
* } else if (end.nanos >= 1000000000) {
* end.seconds += 1;
* end.nanos -= 1000000000;
* }
*
* Example 3: Compute Duration from datetime.timedelta in Python.
*
* td = datetime.timedelta(days=3, minutes=10)
* duration = Duration()
* duration.FromTimedelta(td)
*
* # JSON Mapping
*
* In JSON format, the Duration type is encoded as a string rather than an
* object, where the string ends in the suffix "s" (indicating seconds) and
* is preceded by the number of seconds, with nanoseconds expressed as
* fractional seconds. For example, 3 seconds with 0 nanoseconds should be
* encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
* be expressed in JSON format as "3.000000001s", and 3 seconds and 1
* microsecond should be expressed in JSON format as "3.000001s".
*
*
* @generated from message google.protobuf.Duration
*/
export type DurationJson = string;
/**
* Describes the message google.protobuf.Duration.
* Use `create(DurationSchema)` to create a new message.
*/
export declare const DurationSchema: GenMessage<Duration, {
jsonType: DurationJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DurationSchema = exports.file_google_protobuf_duration = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/duration.proto.
*/
exports.file_google_protobuf_duration = (0, file_js_1.fileDesc)("Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIgASgFQoMBChNjb20uZ29vZ2xlLnByb3RvYnVmQg1EdXJhdGlvblByb3RvUAFaMWdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2R1cmF0aW9ucGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw");
/**
* Describes the message google.protobuf.Duration.
* Use `create(DurationSchema)` to create a new message.
*/
exports.DurationSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_duration, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/empty.proto.
*/
export declare const file_google_protobuf_empty: GenFile;
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
*
* @generated from message google.protobuf.Empty
*/
export type Empty = Message<"google.protobuf.Empty"> & {};
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
*
* @generated from message google.protobuf.Empty
*/
export type EmptyJson = Record<string, never>;
/**
* Describes the message google.protobuf.Empty.
* Use `create(EmptySchema)` to create a new message.
*/
export declare const EmptySchema: GenMessage<Empty, {
jsonType: EmptyJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmptySchema = exports.file_google_protobuf_empty = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/empty.proto.
*/
exports.file_google_protobuf_empty = (0, file_js_1.fileDesc)("Chtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIHCgVFbXB0eUJ9ChNjb20uZ29vZ2xlLnByb3RvYnVmQgpFbXB0eVByb3RvUAFaLmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2VtcHR5cGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw");
/**
* Describes the message google.protobuf.Empty.
* Use `create(EmptySchema)` to create a new message.
*/
exports.EmptySchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_empty, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/field_mask.proto.
*/
export declare const file_google_protobuf_field_mask: GenFile;
/**
* `FieldMask` represents a set of symbolic field paths, for example:
*
* paths: "f.a"
* paths: "f.b.d"
*
* Here `f` represents a field in some root message, `a` and `b`
* fields in the message found in `f`, and `d` a field found in the
* message in `f.b`.
*
* Field masks are used to specify a subset of fields that should be
* returned by a get operation or modified by an update operation.
* Field masks also have a custom JSON encoding (see below).
*
* # Field Masks in Projections
*
* When used in the context of a projection, a response message or
* sub-message is filtered by the API to only contain those fields as
* specified in the mask. For example, if the mask in the previous
* example is applied to a response message as follows:
*
* f {
* a : 22
* b {
* d : 1
* x : 2
* }
* y : 13
* }
* z: 8
*
* The result will not contain specific values for fields x,y and z
* (their value will be set to the default, and omitted in proto text
* output):
*
*
* f {
* a : 22
* b {
* d : 1
* }
* }
*
* A repeated field is not allowed except at the last position of a
* paths string.
*
* If a FieldMask object is not present in a get operation, the
* operation applies to all fields (as if a FieldMask of all fields
* had been specified).
*
* Note that a field mask does not necessarily apply to the
* top-level response message. In case of a REST get operation, the
* field mask applies directly to the response, but in case of a REST
* list operation, the mask instead applies to each individual message
* in the returned resource list. In case of a REST custom method,
* other definitions may be used. Where the mask applies will be
* clearly documented together with its declaration in the API. In
* any case, the effect on the returned resource/resources is required
* behavior for APIs.
*
* # Field Masks in Update Operations
*
* A field mask in update operations specifies which fields of the
* targeted resource are going to be updated. The API is required
* to only change the values of the fields as specified in the mask
* and leave the others untouched. If a resource is passed in to
* describe the updated values, the API ignores the values of all
* fields not covered by the mask.
*
* If a repeated field is specified for an update operation, new values will
* be appended to the existing repeated field in the target resource. Note that
* a repeated field is only allowed in the last position of a `paths` string.
*
* If a sub-message is specified in the last position of the field mask for an
* update operation, then new value will be merged into the existing sub-message
* in the target resource.
*
* For example, given the target message:
*
* f {
* b {
* d: 1
* x: 2
* }
* c: [1]
* }
*
* And an update message:
*
* f {
* b {
* d: 10
* }
* c: [2]
* }
*
* then if the field mask is:
*
* paths: ["f.b", "f.c"]
*
* then the result will be:
*
* f {
* b {
* d: 10
* x: 2
* }
* c: [1, 2]
* }
*
* An implementation may provide options to override this default behavior for
* repeated and message fields.
*
* Note that libraries which implement FieldMask resolution have various
* different behaviors in the face of empty masks or the special "*" mask.
* When implementing a service you should confirm these cases have the
* appropriate behavior in the underlying FieldMask library that you desire,
* and you may need to special case those cases in your application code if
* the underlying field mask library behavior differs from your intended
* service semantics.
*
* Update methods implementing https://google.aip.dev/134
* - MUST support the special value * meaning "full replace"
* - MUST treat an omitted field mask as "replace fields which are present".
*
* Other methods implementing https://google.aip.dev/157
* - SHOULD support the special value "*" to mean "get all".
* - MUST treat an omitted field mask to mean "get all", unless otherwise
* documented.
*
* ## Considerations for HTTP REST
*
* The HTTP kind of an update operation which uses a field mask must
* be set to PATCH instead of PUT in order to satisfy HTTP semantics
* (PUT must only be used for full updates).
*
* # JSON Encoding of Field Masks
*
* In JSON, a field mask is encoded as a single string where paths are
* separated by a comma. Fields name in each path are converted
* to/from lower-camel naming conventions.
*
* As an example, consider the following message declarations:
*
* message Profile {
* User user = 1;
* Photo photo = 2;
* }
* message User {
* string display_name = 1;
* string address = 2;
* }
*
* In proto a field mask for `Profile` may look as such:
*
* mask {
* paths: "user.display_name"
* paths: "photo"
* }
*
* In JSON, the same mask is represented as below:
*
* {
* mask: "user.displayName,photo"
* }
*
* # Field Masks and Oneof Fields
*
* Field masks treat fields in oneofs just as regular fields. Consider the
* following message:
*
* message SampleMessage {
* oneof test_oneof {
* string name = 4;
* SubMessage sub_message = 9;
* }
* }
*
* The field mask can be:
*
* mask {
* paths: "name"
* }
*
* Or:
*
* mask {
* paths: "sub_message"
* }
*
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
*
* ## Field Mask Verification
*
* The implementation of any API method which has a FieldMask type field in the
* request should verify the included field paths, and return an
* `INVALID_ARGUMENT` error if any path is unmappable.
*
* @generated from message google.protobuf.FieldMask
*/
export type FieldMask = Message<"google.protobuf.FieldMask"> & {
/**
* The set of field mask paths.
*
* @generated from field: repeated string paths = 1;
*/
paths: string[];
};
/**
* `FieldMask` represents a set of symbolic field paths, for example:
*
* paths: "f.a"
* paths: "f.b.d"
*
* Here `f` represents a field in some root message, `a` and `b`
* fields in the message found in `f`, and `d` a field found in the
* message in `f.b`.
*
* Field masks are used to specify a subset of fields that should be
* returned by a get operation or modified by an update operation.
* Field masks also have a custom JSON encoding (see below).
*
* # Field Masks in Projections
*
* When used in the context of a projection, a response message or
* sub-message is filtered by the API to only contain those fields as
* specified in the mask. For example, if the mask in the previous
* example is applied to a response message as follows:
*
* f {
* a : 22
* b {
* d : 1
* x : 2
* }
* y : 13
* }
* z: 8
*
* The result will not contain specific values for fields x,y and z
* (their value will be set to the default, and omitted in proto text
* output):
*
*
* f {
* a : 22
* b {
* d : 1
* }
* }
*
* A repeated field is not allowed except at the last position of a
* paths string.
*
* If a FieldMask object is not present in a get operation, the
* operation applies to all fields (as if a FieldMask of all fields
* had been specified).
*
* Note that a field mask does not necessarily apply to the
* top-level response message. In case of a REST get operation, the
* field mask applies directly to the response, but in case of a REST
* list operation, the mask instead applies to each individual message
* in the returned resource list. In case of a REST custom method,
* other definitions may be used. Where the mask applies will be
* clearly documented together with its declaration in the API. In
* any case, the effect on the returned resource/resources is required
* behavior for APIs.
*
* # Field Masks in Update Operations
*
* A field mask in update operations specifies which fields of the
* targeted resource are going to be updated. The API is required
* to only change the values of the fields as specified in the mask
* and leave the others untouched. If a resource is passed in to
* describe the updated values, the API ignores the values of all
* fields not covered by the mask.
*
* If a repeated field is specified for an update operation, new values will
* be appended to the existing repeated field in the target resource. Note that
* a repeated field is only allowed in the last position of a `paths` string.
*
* If a sub-message is specified in the last position of the field mask for an
* update operation, then new value will be merged into the existing sub-message
* in the target resource.
*
* For example, given the target message:
*
* f {
* b {
* d: 1
* x: 2
* }
* c: [1]
* }
*
* And an update message:
*
* f {
* b {
* d: 10
* }
* c: [2]
* }
*
* then if the field mask is:
*
* paths: ["f.b", "f.c"]
*
* then the result will be:
*
* f {
* b {
* d: 10
* x: 2
* }
* c: [1, 2]
* }
*
* An implementation may provide options to override this default behavior for
* repeated and message fields.
*
* Note that libraries which implement FieldMask resolution have various
* different behaviors in the face of empty masks or the special "*" mask.
* When implementing a service you should confirm these cases have the
* appropriate behavior in the underlying FieldMask library that you desire,
* and you may need to special case those cases in your application code if
* the underlying field mask library behavior differs from your intended
* service semantics.
*
* Update methods implementing https://google.aip.dev/134
* - MUST support the special value * meaning "full replace"
* - MUST treat an omitted field mask as "replace fields which are present".
*
* Other methods implementing https://google.aip.dev/157
* - SHOULD support the special value "*" to mean "get all".
* - MUST treat an omitted field mask to mean "get all", unless otherwise
* documented.
*
* ## Considerations for HTTP REST
*
* The HTTP kind of an update operation which uses a field mask must
* be set to PATCH instead of PUT in order to satisfy HTTP semantics
* (PUT must only be used for full updates).
*
* # JSON Encoding of Field Masks
*
* In JSON, a field mask is encoded as a single string where paths are
* separated by a comma. Fields name in each path are converted
* to/from lower-camel naming conventions.
*
* As an example, consider the following message declarations:
*
* message Profile {
* User user = 1;
* Photo photo = 2;
* }
* message User {
* string display_name = 1;
* string address = 2;
* }
*
* In proto a field mask for `Profile` may look as such:
*
* mask {
* paths: "user.display_name"
* paths: "photo"
* }
*
* In JSON, the same mask is represented as below:
*
* {
* mask: "user.displayName,photo"
* }
*
* # Field Masks and Oneof Fields
*
* Field masks treat fields in oneofs just as regular fields. Consider the
* following message:
*
* message SampleMessage {
* oneof test_oneof {
* string name = 4;
* SubMessage sub_message = 9;
* }
* }
*
* The field mask can be:
*
* mask {
* paths: "name"
* }
*
* Or:
*
* mask {
* paths: "sub_message"
* }
*
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
*
* ## Field Mask Verification
*
* The implementation of any API method which has a FieldMask type field in the
* request should verify the included field paths, and return an
* `INVALID_ARGUMENT` error if any path is unmappable.
*
* @generated from message google.protobuf.FieldMask
*/
export type FieldMaskJson = string;
/**
* Describes the message google.protobuf.FieldMask.
* Use `create(FieldMaskSchema)` to create a new message.
*/
export declare const FieldMaskSchema: GenMessage<FieldMask, {
jsonType: FieldMaskJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldMaskSchema = exports.file_google_protobuf_field_mask = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/field_mask.proto.
*/
exports.file_google_protobuf_field_mask = (0, file_js_1.fileDesc)("CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnByb3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUKFAQoTY29tLmdvb2dsZS5wcm90b2J1ZkIORmllbGRNYXNrUHJvdG9QAVoyZ29vZ2xlLmdvbGFuZy5vcmcvcHJvdG9idWYvdHlwZXMva25vd24vZmllbGRtYXNrcGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw");
/**
* Describes the message google.protobuf.FieldMask.
* Use `create(FieldMaskSchema)` to create a new message.
*/
exports.FieldMaskSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_field_mask, 0);
import type { GenEnum, GenExtension, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { FeatureSet } from "./descriptor_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/go_features.proto.
*/
export declare const file_google_protobuf_go_features: GenFile;
/**
* @generated from message pb.GoFeatures
*/
export type GoFeatures = Message<"pb.GoFeatures"> & {
/**
* Whether or not to generate the deprecated UnmarshalJSON method for enums.
* Can only be true for proto using the Open Struct api.
*
* @generated from field: optional bool legacy_unmarshal_json_enum = 1;
*/
legacyUnmarshalJsonEnum: boolean;
/**
* One of OPEN, HYBRID or OPAQUE.
*
* @generated from field: optional pb.GoFeatures.APILevel api_level = 2;
*/
apiLevel: GoFeatures_APILevel;
/**
* @generated from field: optional pb.GoFeatures.StripEnumPrefix strip_enum_prefix = 3;
*/
stripEnumPrefix: GoFeatures_StripEnumPrefix;
/**
* @generated from field: optional pb.GoFeatures.OptimizeModeFeature.OptimizeMode optimize_mode = 4;
*/
optimizeMode: GoFeatures_OptimizeModeFeature_OptimizeMode;
};
/**
* @generated from message pb.GoFeatures
*/
export type GoFeaturesJson = {
/**
* Whether or not to generate the deprecated UnmarshalJSON method for enums.
* Can only be true for proto using the Open Struct api.
*
* @generated from field: optional bool legacy_unmarshal_json_enum = 1;
*/
legacyUnmarshalJsonEnum?: boolean;
/**
* One of OPEN, HYBRID or OPAQUE.
*
* @generated from field: optional pb.GoFeatures.APILevel api_level = 2;
*/
apiLevel?: GoFeatures_APILevelJson;
/**
* @generated from field: optional pb.GoFeatures.StripEnumPrefix strip_enum_prefix = 3;
*/
stripEnumPrefix?: GoFeatures_StripEnumPrefixJson;
/**
* @generated from field: optional pb.GoFeatures.OptimizeModeFeature.OptimizeMode optimize_mode = 4;
*/
optimizeMode?: GoFeatures_OptimizeModeFeature_OptimizeModeJson;
};
/**
* Describes the message pb.GoFeatures.
* Use `create(GoFeaturesSchema)` to create a new message.
*/
export declare const GoFeaturesSchema: GenMessage<GoFeatures, {
jsonType: GoFeaturesJson;
}>;
/**
* Wrap the OptimizeMode enum in a message for scoping:
* This way, users can type shorter names (SPEED, CODE_SIZE).
*
* @generated from message pb.GoFeatures.OptimizeModeFeature
*/
export type GoFeatures_OptimizeModeFeature = Message<"pb.GoFeatures.OptimizeModeFeature"> & {};
/**
* Wrap the OptimizeMode enum in a message for scoping:
* This way, users can type shorter names (SPEED, CODE_SIZE).
*
* @generated from message pb.GoFeatures.OptimizeModeFeature
*/
export type GoFeatures_OptimizeModeFeatureJson = {};
/**
* Describes the message pb.GoFeatures.OptimizeModeFeature.
* Use `create(GoFeatures_OptimizeModeFeatureSchema)` to create a new message.
*/
export declare const GoFeatures_OptimizeModeFeatureSchema: GenMessage<GoFeatures_OptimizeModeFeature, {
jsonType: GoFeatures_OptimizeModeFeatureJson;
}>;
/**
* The name of this enum matches OptimizeMode in descriptor.proto.
*
* @generated from enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode
*/
export declare enum GoFeatures_OptimizeModeFeature_OptimizeMode {
/**
* OPTIMIZE_MODE_UNSPECIFIED results in falling back to the default
* (optimize for code size), but needs to be a separate value to distinguish
* between an explicitly set optimize mode or a missing optimize mode.
*
* @generated from enum value: OPTIMIZE_MODE_UNSPECIFIED = 0;
*/
OPTIMIZE_MODE_UNSPECIFIED = 0,
/**
* @generated from enum value: SPEED = 1;
*/
SPEED = 1,
/**
* There is no enum entry for LITE_RUNTIME (descriptor.proto),
* because Go Protobuf does not have the concept of a lite runtime.
*
* @generated from enum value: CODE_SIZE = 2;
*/
CODE_SIZE = 2
}
/**
* The name of this enum matches OptimizeMode in descriptor.proto.
*
* @generated from enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode
*/
export type GoFeatures_OptimizeModeFeature_OptimizeModeJson = "OPTIMIZE_MODE_UNSPECIFIED" | "SPEED" | "CODE_SIZE";
/**
* Describes the enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode.
*/
export declare const GoFeatures_OptimizeModeFeature_OptimizeModeSchema: GenEnum<GoFeatures_OptimizeModeFeature_OptimizeMode, GoFeatures_OptimizeModeFeature_OptimizeModeJson>;
/**
* @generated from enum pb.GoFeatures.APILevel
*/
export declare enum GoFeatures_APILevel {
/**
* API_LEVEL_UNSPECIFIED results in selecting the OPEN API,
* but needs to be a separate value to distinguish between
* an explicitly set api level or a missing api level.
*
* @generated from enum value: API_LEVEL_UNSPECIFIED = 0;
*/
API_LEVEL_UNSPECIFIED = 0,
/**
* @generated from enum value: API_OPEN = 1;
*/
API_OPEN = 1,
/**
* @generated from enum value: API_HYBRID = 2;
*/
API_HYBRID = 2,
/**
* @generated from enum value: API_OPAQUE = 3;
*/
API_OPAQUE = 3
}
/**
* @generated from enum pb.GoFeatures.APILevel
*/
export type GoFeatures_APILevelJson = "API_LEVEL_UNSPECIFIED" | "API_OPEN" | "API_HYBRID" | "API_OPAQUE";
/**
* Describes the enum pb.GoFeatures.APILevel.
*/
export declare const GoFeatures_APILevelSchema: GenEnum<GoFeatures_APILevel, GoFeatures_APILevelJson>;
/**
* @generated from enum pb.GoFeatures.StripEnumPrefix
*/
export declare enum GoFeatures_StripEnumPrefix {
/**
* @generated from enum value: STRIP_ENUM_PREFIX_UNSPECIFIED = 0;
*/
UNSPECIFIED = 0,
/**
* @generated from enum value: STRIP_ENUM_PREFIX_KEEP = 1;
*/
KEEP = 1,
/**
* @generated from enum value: STRIP_ENUM_PREFIX_GENERATE_BOTH = 2;
*/
GENERATE_BOTH = 2,
/**
* @generated from enum value: STRIP_ENUM_PREFIX_STRIP = 3;
*/
STRIP = 3
}
/**
* @generated from enum pb.GoFeatures.StripEnumPrefix
*/
export type GoFeatures_StripEnumPrefixJson = "STRIP_ENUM_PREFIX_UNSPECIFIED" | "STRIP_ENUM_PREFIX_KEEP" | "STRIP_ENUM_PREFIX_GENERATE_BOTH" | "STRIP_ENUM_PREFIX_STRIP";
/**
* Describes the enum pb.GoFeatures.StripEnumPrefix.
*/
export declare const GoFeatures_StripEnumPrefixSchema: GenEnum<GoFeatures_StripEnumPrefix, GoFeatures_StripEnumPrefixJson>;
/**
* @generated from extension: optional pb.GoFeatures go = 1002;
*/
export declare const go: GenExtension<FeatureSet, GoFeatures>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.go = exports.GoFeatures_StripEnumPrefixSchema = exports.GoFeatures_StripEnumPrefix = exports.GoFeatures_APILevelSchema = exports.GoFeatures_APILevel = exports.GoFeatures_OptimizeModeFeature_OptimizeModeSchema = exports.GoFeatures_OptimizeModeFeature_OptimizeMode = exports.GoFeatures_OptimizeModeFeatureSchema = exports.GoFeaturesSchema = exports.file_google_protobuf_go_features = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const descriptor_pb_js_1 = require("./descriptor_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
const extension_js_1 = require("../../../../codegenv2/extension.js");
/**
* Describes the file google/protobuf/go_features.proto.
*/
exports.file_google_protobuf_go_features = (0, file_js_1.fileDesc)("CiFnb29nbGUvcHJvdG9idWYvZ29fZmVhdHVyZXMucHJvdG8SAnBiItEGCgpHb0ZlYXR1cmVzEqUBChpsZWdhY3lfdW5tYXJzaGFsX2pzb25fZW51bRgBIAEoCEKAAYgBAZgBBpgBAaIBCRIEdHJ1ZRiEB6IBChIFZmFsc2UY5weyAVsI6AcQ6AcaU1RoZSBsZWdhY3kgVW5tYXJzaGFsSlNPTiBBUEkgaXMgZGVwcmVjYXRlZCBhbmQgd2lsbCBiZSByZW1vdmVkIGluIGEgZnV0dXJlIGVkaXRpb24uEmoKCWFwaV9sZXZlbBgCIAEoDjIXLnBiLkdvRmVhdHVyZXMuQVBJTGV2ZWxCPogBAZgBA5gBAaIBGhIVQVBJX0xFVkVMX1VOU1BFQ0lGSUVEGIQHogEPEgpBUElfT1BBUVVFGOkHsgEDCOgHEmsKEXN0cmlwX2VudW1fcHJlZml4GAMgASgOMh4ucGIuR29GZWF0dXJlcy5TdHJpcEVudW1QcmVmaXhCMIgBAZgBBpgBB5gBAaIBGxIWU1RSSVBfRU5VTV9QUkVGSVhfS0VFUBiEB7IBAwjpBxJ4Cg1vcHRpbWl6ZV9tb2RlGAQgASgOMi8ucGIuR29GZWF0dXJlcy5PcHRpbWl6ZU1vZGVGZWF0dXJlLk9wdGltaXplTW9kZUIwiAEBmAEDmAEBogEeEhlPUFRJTUlaRV9NT0RFX1VOU1BFQ0lGSUVEGIQHsgEDCOkHGl4KE09wdGltaXplTW9kZUZlYXR1cmUiRwoMT3B0aW1pemVNb2RlEh0KGU9QVElNSVpFX01PREVfVU5TUEVDSUZJRUQQABIJCgVTUEVFRBABEg0KCUNPREVfU0laRRACIlMKCEFQSUxldmVsEhkKFUFQSV9MRVZFTF9VTlNQRUNJRklFRBAAEgwKCEFQSV9PUEVOEAESDgoKQVBJX0hZQlJJRBACEg4KCkFQSV9PUEFRVUUQAyKSAQoPU3RyaXBFbnVtUHJlZml4EiEKHVNUUklQX0VOVU1fUFJFRklYX1VOU1BFQ0lGSUVEEAASGgoWU1RSSVBfRU5VTV9QUkVGSVhfS0VFUBABEiMKH1NUUklQX0VOVU1fUFJFRklYX0dFTkVSQVRFX0JPVEgQAhIbChdTVFJJUF9FTlVNX1BSRUZJWF9TVFJJUBADOjwKAmdvEhsuZ29vZ2xlLnByb3RvYnVmLkZlYXR1cmVTZXQY6gcgASgLMg4ucGIuR29GZWF0dXJlc1ICZ29CL1otZ29vZ2xlLmdvbGFuZy5vcmcvcHJvdG9idWYvdHlwZXMvZ29mZWF0dXJlc3Bi", [descriptor_pb_js_1.file_google_protobuf_descriptor]);
/**
* Describes the message pb.GoFeatures.
* Use `create(GoFeaturesSchema)` to create a new message.
*/
exports.GoFeaturesSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_go_features, 0);
/**
* Describes the message pb.GoFeatures.OptimizeModeFeature.
* Use `create(GoFeatures_OptimizeModeFeatureSchema)` to create a new message.
*/
exports.GoFeatures_OptimizeModeFeatureSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_go_features, 0, 0);
/**
* The name of this enum matches OptimizeMode in descriptor.proto.
*
* @generated from enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode
*/
var GoFeatures_OptimizeModeFeature_OptimizeMode;
(function (GoFeatures_OptimizeModeFeature_OptimizeMode) {
/**
* OPTIMIZE_MODE_UNSPECIFIED results in falling back to the default
* (optimize for code size), but needs to be a separate value to distinguish
* between an explicitly set optimize mode or a missing optimize mode.
*
* @generated from enum value: OPTIMIZE_MODE_UNSPECIFIED = 0;
*/
GoFeatures_OptimizeModeFeature_OptimizeMode[GoFeatures_OptimizeModeFeature_OptimizeMode["OPTIMIZE_MODE_UNSPECIFIED"] = 0] = "OPTIMIZE_MODE_UNSPECIFIED";
/**
* @generated from enum value: SPEED = 1;
*/
GoFeatures_OptimizeModeFeature_OptimizeMode[GoFeatures_OptimizeModeFeature_OptimizeMode["SPEED"] = 1] = "SPEED";
/**
* There is no enum entry for LITE_RUNTIME (descriptor.proto),
* because Go Protobuf does not have the concept of a lite runtime.
*
* @generated from enum value: CODE_SIZE = 2;
*/
GoFeatures_OptimizeModeFeature_OptimizeMode[GoFeatures_OptimizeModeFeature_OptimizeMode["CODE_SIZE"] = 2] = "CODE_SIZE";
})(GoFeatures_OptimizeModeFeature_OptimizeMode || (exports.GoFeatures_OptimizeModeFeature_OptimizeMode = GoFeatures_OptimizeModeFeature_OptimizeMode = {}));
/**
* Describes the enum pb.GoFeatures.OptimizeModeFeature.OptimizeMode.
*/
exports.GoFeatures_OptimizeModeFeature_OptimizeModeSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_go_features, 0, 0, 0);
/**
* @generated from enum pb.GoFeatures.APILevel
*/
var GoFeatures_APILevel;
(function (GoFeatures_APILevel) {
/**
* API_LEVEL_UNSPECIFIED results in selecting the OPEN API,
* but needs to be a separate value to distinguish between
* an explicitly set api level or a missing api level.
*
* @generated from enum value: API_LEVEL_UNSPECIFIED = 0;
*/
GoFeatures_APILevel[GoFeatures_APILevel["API_LEVEL_UNSPECIFIED"] = 0] = "API_LEVEL_UNSPECIFIED";
/**
* @generated from enum value: API_OPEN = 1;
*/
GoFeatures_APILevel[GoFeatures_APILevel["API_OPEN"] = 1] = "API_OPEN";
/**
* @generated from enum value: API_HYBRID = 2;
*/
GoFeatures_APILevel[GoFeatures_APILevel["API_HYBRID"] = 2] = "API_HYBRID";
/**
* @generated from enum value: API_OPAQUE = 3;
*/
GoFeatures_APILevel[GoFeatures_APILevel["API_OPAQUE"] = 3] = "API_OPAQUE";
})(GoFeatures_APILevel || (exports.GoFeatures_APILevel = GoFeatures_APILevel = {}));
/**
* Describes the enum pb.GoFeatures.APILevel.
*/
exports.GoFeatures_APILevelSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_go_features, 0, 0);
/**
* @generated from enum pb.GoFeatures.StripEnumPrefix
*/
var GoFeatures_StripEnumPrefix;
(function (GoFeatures_StripEnumPrefix) {
/**
* @generated from enum value: STRIP_ENUM_PREFIX_UNSPECIFIED = 0;
*/
GoFeatures_StripEnumPrefix[GoFeatures_StripEnumPrefix["UNSPECIFIED"] = 0] = "UNSPECIFIED";
/**
* @generated from enum value: STRIP_ENUM_PREFIX_KEEP = 1;
*/
GoFeatures_StripEnumPrefix[GoFeatures_StripEnumPrefix["KEEP"] = 1] = "KEEP";
/**
* @generated from enum value: STRIP_ENUM_PREFIX_GENERATE_BOTH = 2;
*/
GoFeatures_StripEnumPrefix[GoFeatures_StripEnumPrefix["GENERATE_BOTH"] = 2] = "GENERATE_BOTH";
/**
* @generated from enum value: STRIP_ENUM_PREFIX_STRIP = 3;
*/
GoFeatures_StripEnumPrefix[GoFeatures_StripEnumPrefix["STRIP"] = 3] = "STRIP";
})(GoFeatures_StripEnumPrefix || (exports.GoFeatures_StripEnumPrefix = GoFeatures_StripEnumPrefix = {}));
/**
* Describes the enum pb.GoFeatures.StripEnumPrefix.
*/
exports.GoFeatures_StripEnumPrefixSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_go_features, 0, 1);
/**
* @generated from extension: optional pb.GoFeatures go = 1002;
*/
exports.go = (0, extension_js_1.extDesc)(exports.file_google_protobuf_go_features, 0);
import type { GenEnum, GenExtension, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { FeatureSet } from "./descriptor_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/java_features.proto.
*/
export declare const file_google_protobuf_java_features: GenFile;
/**
* @generated from message pb.JavaFeatures
*/
export type JavaFeatures = Message<"pb.JavaFeatures"> & {
/**
* Whether or not to treat an enum field as closed. This option is only
* applicable to enum fields, and will be removed in the future. It is
* consistent with the legacy behavior of using proto3 enum types for proto2
* fields.
*
* @generated from field: optional bool legacy_closed_enum = 1;
*/
legacyClosedEnum: boolean;
/**
* @generated from field: optional pb.JavaFeatures.Utf8Validation utf8_validation = 2;
*/
utf8Validation: JavaFeatures_Utf8Validation;
/**
* Allows creation of large Java enums, extending beyond the standard
* constant limits imposed by the Java language.
*
* @generated from field: optional bool large_enum = 3;
*/
largeEnum: boolean;
/**
* Whether to use the old default outer class name scheme, or the new feature
* which adds a "Proto" suffix to the outer class name.
*
* Users will not be able to set this option, because we removed it in the
* same edition that it was introduced. But we use it to determine which
* naming scheme to use for outer class name defaults.
*
* @generated from field: optional bool use_old_outer_classname_default = 4;
*/
useOldOuterClassnameDefault: boolean;
/**
* Whether to nest the generated class in the generated file class. This is
* only applicable to *top-level* messages, enums, and services.
*
* @generated from field: optional pb.JavaFeatures.NestInFileClassFeature.NestInFileClass nest_in_file_class = 5;
*/
nestInFileClass: JavaFeatures_NestInFileClassFeature_NestInFileClass;
};
/**
* @generated from message pb.JavaFeatures
*/
export type JavaFeaturesJson = {
/**
* Whether or not to treat an enum field as closed. This option is only
* applicable to enum fields, and will be removed in the future. It is
* consistent with the legacy behavior of using proto3 enum types for proto2
* fields.
*
* @generated from field: optional bool legacy_closed_enum = 1;
*/
legacyClosedEnum?: boolean;
/**
* @generated from field: optional pb.JavaFeatures.Utf8Validation utf8_validation = 2;
*/
utf8Validation?: JavaFeatures_Utf8ValidationJson;
/**
* Allows creation of large Java enums, extending beyond the standard
* constant limits imposed by the Java language.
*
* @generated from field: optional bool large_enum = 3;
*/
largeEnum?: boolean;
/**
* Whether to use the old default outer class name scheme, or the new feature
* which adds a "Proto" suffix to the outer class name.
*
* Users will not be able to set this option, because we removed it in the
* same edition that it was introduced. But we use it to determine which
* naming scheme to use for outer class name defaults.
*
* @generated from field: optional bool use_old_outer_classname_default = 4;
*/
useOldOuterClassnameDefault?: boolean;
/**
* Whether to nest the generated class in the generated file class. This is
* only applicable to *top-level* messages, enums, and services.
*
* @generated from field: optional pb.JavaFeatures.NestInFileClassFeature.NestInFileClass nest_in_file_class = 5;
*/
nestInFileClass?: JavaFeatures_NestInFileClassFeature_NestInFileClassJson;
};
/**
* Describes the message pb.JavaFeatures.
* Use `create(JavaFeaturesSchema)` to create a new message.
*/
export declare const JavaFeaturesSchema: GenMessage<JavaFeatures, {
jsonType: JavaFeaturesJson;
}>;
/**
* @generated from message pb.JavaFeatures.NestInFileClassFeature
*/
export type JavaFeatures_NestInFileClassFeature = Message<"pb.JavaFeatures.NestInFileClassFeature"> & {};
/**
* @generated from message pb.JavaFeatures.NestInFileClassFeature
*/
export type JavaFeatures_NestInFileClassFeatureJson = {};
/**
* Describes the message pb.JavaFeatures.NestInFileClassFeature.
* Use `create(JavaFeatures_NestInFileClassFeatureSchema)` to create a new message.
*/
export declare const JavaFeatures_NestInFileClassFeatureSchema: GenMessage<JavaFeatures_NestInFileClassFeature, {
jsonType: JavaFeatures_NestInFileClassFeatureJson;
}>;
/**
* @generated from enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass
*/
export declare enum JavaFeatures_NestInFileClassFeature_NestInFileClass {
/**
* Invalid default, which should never be used.
*
* @generated from enum value: NEST_IN_FILE_CLASS_UNKNOWN = 0;
*/
NEST_IN_FILE_CLASS_UNKNOWN = 0,
/**
* Do not nest the generated class in the file class.
*
* @generated from enum value: NO = 1;
*/
NO = 1,
/**
* Nest the generated class in the file class.
*
* @generated from enum value: YES = 2;
*/
YES = 2,
/**
* Fall back to the `java_multiple_files` option. Users won't be able to
* set this option.
*
* @generated from enum value: LEGACY = 3;
*/
LEGACY = 3
}
/**
* @generated from enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass
*/
export type JavaFeatures_NestInFileClassFeature_NestInFileClassJson = "NEST_IN_FILE_CLASS_UNKNOWN" | "NO" | "YES" | "LEGACY";
/**
* Describes the enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass.
*/
export declare const JavaFeatures_NestInFileClassFeature_NestInFileClassSchema: GenEnum<JavaFeatures_NestInFileClassFeature_NestInFileClass, JavaFeatures_NestInFileClassFeature_NestInFileClassJson>;
/**
* The UTF8 validation strategy to use.
*
* @generated from enum pb.JavaFeatures.Utf8Validation
*/
export declare enum JavaFeatures_Utf8Validation {
/**
* Invalid default, which should never be used.
*
* @generated from enum value: UTF8_VALIDATION_UNKNOWN = 0;
*/
UTF8_VALIDATION_UNKNOWN = 0,
/**
* Respect the UTF8 validation behavior specified by the global
* utf8_validation feature.
*
* @generated from enum value: DEFAULT = 1;
*/
DEFAULT = 1,
/**
* Verifies UTF8 validity overriding the global utf8_validation
* feature. This represents the legacy java_string_check_utf8 option.
*
* @generated from enum value: VERIFY = 2;
*/
VERIFY = 2
}
/**
* The UTF8 validation strategy to use.
*
* @generated from enum pb.JavaFeatures.Utf8Validation
*/
export type JavaFeatures_Utf8ValidationJson = "UTF8_VALIDATION_UNKNOWN" | "DEFAULT" | "VERIFY";
/**
* Describes the enum pb.JavaFeatures.Utf8Validation.
*/
export declare const JavaFeatures_Utf8ValidationSchema: GenEnum<JavaFeatures_Utf8Validation, JavaFeatures_Utf8ValidationJson>;
/**
* @generated from extension: optional pb.JavaFeatures java = 1001;
*/
export declare const java: GenExtension<FeatureSet, JavaFeatures>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.java = exports.JavaFeatures_Utf8ValidationSchema = exports.JavaFeatures_Utf8Validation = exports.JavaFeatures_NestInFileClassFeature_NestInFileClassSchema = exports.JavaFeatures_NestInFileClassFeature_NestInFileClass = exports.JavaFeatures_NestInFileClassFeatureSchema = exports.JavaFeaturesSchema = exports.file_google_protobuf_java_features = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const descriptor_pb_js_1 = require("./descriptor_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
const extension_js_1 = require("../../../../codegenv2/extension.js");
/**
* Describes the file google/protobuf/java_features.proto.
*/
exports.file_google_protobuf_java_features = (0, file_js_1.fileDesc)("CiNnb29nbGUvcHJvdG9idWYvamF2YV9mZWF0dXJlcy5wcm90bxICcGIigwgKDEphdmFGZWF0dXJlcxL+AQoSbGVnYWN5X2Nsb3NlZF9lbnVtGAEgASgIQuEBiAEBmAEEmAEBogEJEgR0cnVlGIQHogEKEgVmYWxzZRjnB7IBuwEI6AcQ6AcasgFUaGUgbGVnYWN5IGNsb3NlZCBlbnVtIGJlaGF2aW9yIGluIEphdmEgaXMgZGVwcmVjYXRlZCBhbmQgaXMgc2NoZWR1bGVkIHRvIGJlIHJlbW92ZWQgaW4gZWRpdGlvbiAyMDI1LiAgU2VlIGh0dHA6Ly9wcm90b2J1Zi5kZXYvcHJvZ3JhbW1pbmctZ3VpZGVzL2VudW0vI2phdmEgZm9yIG1vcmUgaW5mb3JtYXRpb24uEp8CCg91dGY4X3ZhbGlkYXRpb24YAiABKA4yHy5wYi5KYXZhRmVhdHVyZXMuVXRmOFZhbGlkYXRpb25C5AGIAQGYAQSYAQGiAQwSB0RFRkFVTFQYhAeyAcgBCOgHEOkHGr8BVGhlIEphdmEtc3BlY2lmaWMgdXRmOCB2YWxpZGF0aW9uIGZlYXR1cmUgaXMgZGVwcmVjYXRlZCBhbmQgaXMgc2NoZWR1bGVkIHRvIGJlIHJlbW92ZWQgaW4gZWRpdGlvbiAyMDI1LiAgVXRmOCB2YWxpZGF0aW9uIGJlaGF2aW9yIHNob3VsZCB1c2UgdGhlIGdsb2JhbCBjcm9zcy1sYW5ndWFnZSB1dGY4X3ZhbGlkYXRpb24gZmVhdHVyZS4SMAoKbGFyZ2VfZW51bRgDIAEoCEIciAEBmAEGmAEBogEKEgVmYWxzZRiEB7IBAwjpBxJRCh91c2Vfb2xkX291dGVyX2NsYXNzbmFtZV9kZWZhdWx0GAQgASgIQiiIAQGYAQGiAQkSBHRydWUYhAeiAQoSBWZhbHNlGOkHsgEGCOkHIOkHEn8KEm5lc3RfaW5fZmlsZV9jbGFzcxgFIAEoDjI3LnBiLkphdmFGZWF0dXJlcy5OZXN0SW5GaWxlQ2xhc3NGZWF0dXJlLk5lc3RJbkZpbGVDbGFzc0IqiAEBmAEDmAEGmAEIogELEgZMRUdBQ1kYhAeiAQcSAk5PGOkHsgEDCOkHGnwKFk5lc3RJbkZpbGVDbGFzc0ZlYXR1cmUiWAoPTmVzdEluRmlsZUNsYXNzEh4KGk5FU1RfSU5fRklMRV9DTEFTU19VTktOT1dOEAASBgoCTk8QARIHCgNZRVMQAhIUCgZMRUdBQ1kQAxoIIgYI6Qcg6QdKCAgBEICAgIACIkYKDlV0ZjhWYWxpZGF0aW9uEhsKF1VURjhfVkFMSURBVElPTl9VTktOT1dOEAASCwoHREVGQVVMVBABEgoKBlZFUklGWRACSgQIBhAHOkIKBGphdmESGy5nb29nbGUucHJvdG9idWYuRmVhdHVyZVNldBjpByABKAsyEC5wYi5KYXZhRmVhdHVyZXNSBGphdmFCKAoTY29tLmdvb2dsZS5wcm90b2J1ZkIRSmF2YUZlYXR1cmVzUHJvdG8", [descriptor_pb_js_1.file_google_protobuf_descriptor]);
/**
* Describes the message pb.JavaFeatures.
* Use `create(JavaFeaturesSchema)` to create a new message.
*/
exports.JavaFeaturesSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_java_features, 0);
/**
* Describes the message pb.JavaFeatures.NestInFileClassFeature.
* Use `create(JavaFeatures_NestInFileClassFeatureSchema)` to create a new message.
*/
exports.JavaFeatures_NestInFileClassFeatureSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_java_features, 0, 0);
/**
* @generated from enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass
*/
var JavaFeatures_NestInFileClassFeature_NestInFileClass;
(function (JavaFeatures_NestInFileClassFeature_NestInFileClass) {
/**
* Invalid default, which should never be used.
*
* @generated from enum value: NEST_IN_FILE_CLASS_UNKNOWN = 0;
*/
JavaFeatures_NestInFileClassFeature_NestInFileClass[JavaFeatures_NestInFileClassFeature_NestInFileClass["NEST_IN_FILE_CLASS_UNKNOWN"] = 0] = "NEST_IN_FILE_CLASS_UNKNOWN";
/**
* Do not nest the generated class in the file class.
*
* @generated from enum value: NO = 1;
*/
JavaFeatures_NestInFileClassFeature_NestInFileClass[JavaFeatures_NestInFileClassFeature_NestInFileClass["NO"] = 1] = "NO";
/**
* Nest the generated class in the file class.
*
* @generated from enum value: YES = 2;
*/
JavaFeatures_NestInFileClassFeature_NestInFileClass[JavaFeatures_NestInFileClassFeature_NestInFileClass["YES"] = 2] = "YES";
/**
* Fall back to the `java_multiple_files` option. Users won't be able to
* set this option.
*
* @generated from enum value: LEGACY = 3;
*/
JavaFeatures_NestInFileClassFeature_NestInFileClass[JavaFeatures_NestInFileClassFeature_NestInFileClass["LEGACY"] = 3] = "LEGACY";
})(JavaFeatures_NestInFileClassFeature_NestInFileClass || (exports.JavaFeatures_NestInFileClassFeature_NestInFileClass = JavaFeatures_NestInFileClassFeature_NestInFileClass = {}));
/**
* Describes the enum pb.JavaFeatures.NestInFileClassFeature.NestInFileClass.
*/
exports.JavaFeatures_NestInFileClassFeature_NestInFileClassSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_java_features, 0, 0, 0);
/**
* The UTF8 validation strategy to use.
*
* @generated from enum pb.JavaFeatures.Utf8Validation
*/
var JavaFeatures_Utf8Validation;
(function (JavaFeatures_Utf8Validation) {
/**
* Invalid default, which should never be used.
*
* @generated from enum value: UTF8_VALIDATION_UNKNOWN = 0;
*/
JavaFeatures_Utf8Validation[JavaFeatures_Utf8Validation["UTF8_VALIDATION_UNKNOWN"] = 0] = "UTF8_VALIDATION_UNKNOWN";
/**
* Respect the UTF8 validation behavior specified by the global
* utf8_validation feature.
*
* @generated from enum value: DEFAULT = 1;
*/
JavaFeatures_Utf8Validation[JavaFeatures_Utf8Validation["DEFAULT"] = 1] = "DEFAULT";
/**
* Verifies UTF8 validity overriding the global utf8_validation
* feature. This represents the legacy java_string_check_utf8 option.
*
* @generated from enum value: VERIFY = 2;
*/
JavaFeatures_Utf8Validation[JavaFeatures_Utf8Validation["VERIFY"] = 2] = "VERIFY";
})(JavaFeatures_Utf8Validation || (exports.JavaFeatures_Utf8Validation = JavaFeatures_Utf8Validation = {}));
/**
* Describes the enum pb.JavaFeatures.Utf8Validation.
*/
exports.JavaFeatures_Utf8ValidationSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_java_features, 0, 0);
/**
* @generated from extension: optional pb.JavaFeatures java = 1001;
*/
exports.java = (0, extension_js_1.extDesc)(exports.file_google_protobuf_java_features, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/source_context.proto.
*/
export declare const file_google_protobuf_source_context: GenFile;
/**
* `SourceContext` represents information about the source of a
* protobuf element, like the file in which it is defined.
*
* @generated from message google.protobuf.SourceContext
*/
export type SourceContext = Message<"google.protobuf.SourceContext"> & {
/**
* The path-qualified name of the .proto file that contained the associated
* protobuf element. For example: `"google/protobuf/source_context.proto"`.
*
* @generated from field: string file_name = 1;
*/
fileName: string;
};
/**
* `SourceContext` represents information about the source of a
* protobuf element, like the file in which it is defined.
*
* @generated from message google.protobuf.SourceContext
*/
export type SourceContextJson = {
/**
* The path-qualified name of the .proto file that contained the associated
* protobuf element. For example: `"google/protobuf/source_context.proto"`.
*
* @generated from field: string file_name = 1;
*/
fileName?: string;
};
/**
* Describes the message google.protobuf.SourceContext.
* Use `create(SourceContextSchema)` to create a new message.
*/
export declare const SourceContextSchema: GenMessage<SourceContext, {
jsonType: SourceContextJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceContextSchema = exports.file_google_protobuf_source_context = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/source_context.proto.
*/
exports.file_google_protobuf_source_context = (0, file_js_1.fileDesc)("CiRnb29nbGUvcHJvdG9idWYvc291cmNlX2NvbnRleHQucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIiCg1Tb3VyY2VDb250ZXh0EhEKCWZpbGVfbmFtZRgBIAEoCUKKAQoTY29tLmdvb2dsZS5wcm90b2J1ZkISU291cmNlQ29udGV4dFByb3RvUAFaNmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3NvdXJjZWNvbnRleHRwYqICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z");
/**
* Describes the message google.protobuf.SourceContext.
* Use `create(SourceContextSchema)` to create a new message.
*/
exports.SourceContextSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_source_context, 0);
import type { GenEnum, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
import type { JsonObject, JsonValue } from "../../../../json-value.js";
/**
* Describes the file google/protobuf/struct.proto.
*/
export declare const file_google_protobuf_struct: GenFile;
/**
* `Struct` represents a structured data value, consisting of fields
* which map to dynamically typed values. In some languages, `Struct`
* might be supported by a native representation. For example, in
* scripting languages like JS a struct is represented as an
* object. The details of that representation are described together
* with the proto support for the language.
*
* The JSON representation for `Struct` is JSON object.
*
* @generated from message google.protobuf.Struct
*/
export type Struct = Message<"google.protobuf.Struct"> & {
/**
* Unordered map of dynamically typed values.
*
* @generated from field: map<string, google.protobuf.Value> fields = 1;
*/
fields: {
[key: string]: Value;
};
};
/**
* `Struct` represents a structured data value, consisting of fields
* which map to dynamically typed values. In some languages, `Struct`
* might be supported by a native representation. For example, in
* scripting languages like JS a struct is represented as an
* object. The details of that representation are described together
* with the proto support for the language.
*
* The JSON representation for `Struct` is JSON object.
*
* @generated from message google.protobuf.Struct
*/
export type StructJson = JsonObject;
/**
* Describes the message google.protobuf.Struct.
* Use `create(StructSchema)` to create a new message.
*/
export declare const StructSchema: GenMessage<Struct, {
jsonType: StructJson;
}>;
/**
* `Value` represents a dynamically typed value which can be either
* null, a number, a string, a boolean, a recursive struct value, or a
* list of values. A producer of value is expected to set one of these
* variants. Absence of any variant indicates an error.
*
* The JSON representation for `Value` is JSON value.
*
* @generated from message google.protobuf.Value
*/
export type Value = Message<"google.protobuf.Value"> & {
/**
* The kind of value.
*
* @generated from oneof google.protobuf.Value.kind
*/
kind: {
/**
* Represents a null value.
*
* @generated from field: google.protobuf.NullValue null_value = 1;
*/
value: NullValue;
case: "nullValue";
} | {
/**
* Represents a double value.
*
* @generated from field: double number_value = 2;
*/
value: number;
case: "numberValue";
} | {
/**
* Represents a string value.
*
* @generated from field: string string_value = 3;
*/
value: string;
case: "stringValue";
} | {
/**
* Represents a boolean value.
*
* @generated from field: bool bool_value = 4;
*/
value: boolean;
case: "boolValue";
} | {
/**
* Represents a structured value.
*
* @generated from field: google.protobuf.Struct struct_value = 5;
*/
value: Struct;
case: "structValue";
} | {
/**
* Represents a repeated `Value`.
*
* @generated from field: google.protobuf.ListValue list_value = 6;
*/
value: ListValue;
case: "listValue";
} | {
case: undefined;
value?: undefined;
};
};
/**
* `Value` represents a dynamically typed value which can be either
* null, a number, a string, a boolean, a recursive struct value, or a
* list of values. A producer of value is expected to set one of these
* variants. Absence of any variant indicates an error.
*
* The JSON representation for `Value` is JSON value.
*
* @generated from message google.protobuf.Value
*/
export type ValueJson = JsonValue;
/**
* Describes the message google.protobuf.Value.
* Use `create(ValueSchema)` to create a new message.
*/
export declare const ValueSchema: GenMessage<Value, {
jsonType: ValueJson;
}>;
/**
* `ListValue` is a wrapper around a repeated field of values.
*
* The JSON representation for `ListValue` is JSON array.
*
* @generated from message google.protobuf.ListValue
*/
export type ListValue = Message<"google.protobuf.ListValue"> & {
/**
* Repeated field of dynamically typed values.
*
* @generated from field: repeated google.protobuf.Value values = 1;
*/
values: Value[];
};
/**
* `ListValue` is a wrapper around a repeated field of values.
*
* The JSON representation for `ListValue` is JSON array.
*
* @generated from message google.protobuf.ListValue
*/
export type ListValueJson = JsonValue[];
/**
* Describes the message google.protobuf.ListValue.
* Use `create(ListValueSchema)` to create a new message.
*/
export declare const ListValueSchema: GenMessage<ListValue, {
jsonType: ListValueJson;
}>;
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* @generated from enum google.protobuf.NullValue
*/
export declare enum NullValue {
/**
* Null value.
*
* @generated from enum value: NULL_VALUE = 0;
*/
NULL_VALUE = 0
}
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* @generated from enum google.protobuf.NullValue
*/
export type NullValueJson = null;
/**
* Describes the enum google.protobuf.NullValue.
*/
export declare const NullValueSchema: GenEnum<NullValue, NullValueJson>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.NullValueSchema = exports.NullValue = exports.ListValueSchema = exports.ValueSchema = exports.StructSchema = exports.file_google_protobuf_struct = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
/**
* Describes the file google/protobuf/struct.proto.
*/
exports.file_google_protobuf_struct = (0, file_js_1.fileDesc)("Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9idWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9idWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToCOAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJvdG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoMc3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8KDHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RWYWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAAQn8KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAFaL2dvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3N0cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
/**
* Describes the message google.protobuf.Struct.
* Use `create(StructSchema)` to create a new message.
*/
exports.StructSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_struct, 0);
/**
* Describes the message google.protobuf.Value.
* Use `create(ValueSchema)` to create a new message.
*/
exports.ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_struct, 1);
/**
* Describes the message google.protobuf.ListValue.
* Use `create(ListValueSchema)` to create a new message.
*/
exports.ListValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_struct, 2);
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* @generated from enum google.protobuf.NullValue
*/
var NullValue;
(function (NullValue) {
/**
* Null value.
*
* @generated from enum value: NULL_VALUE = 0;
*/
NullValue[NullValue["NULL_VALUE"] = 0] = "NULL_VALUE";
})(NullValue || (exports.NullValue = NullValue = {}));
/**
* Describes the enum google.protobuf.NullValue.
*/
exports.NullValueSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_struct, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/timestamp.proto.
*/
export declare const file_google_protobuf_timestamp: GenFile;
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A ProtoJSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a ProtoJSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
* ) to obtain a formatter capable of generating timestamps in this format.
*
*
* @generated from message google.protobuf.Timestamp
*/
export type Timestamp = Message<"google.protobuf.Timestamp"> & {
/**
* Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must
* be between -62135596800 and 253402300799 inclusive (which corresponds to
* 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z).
*
* @generated from field: int64 seconds = 1;
*/
seconds: bigint;
/**
* Non-negative fractions of a second at nanosecond resolution. This field is
* the nanosecond portion of the duration, not an alternative to seconds.
* Negative second values with fractions must still have non-negative nanos
* values that count forward in time. Must be between 0 and 999,999,999
* inclusive.
*
* @generated from field: int32 nanos = 2;
*/
nanos: number;
};
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A ProtoJSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a ProtoJSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
* ) to obtain a formatter capable of generating timestamps in this format.
*
*
* @generated from message google.protobuf.Timestamp
*/
export type TimestampJson = string;
/**
* Describes the message google.protobuf.Timestamp.
* Use `create(TimestampSchema)` to create a new message.
*/
export declare const TimestampSchema: GenMessage<Timestamp, {
jsonType: TimestampJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimestampSchema = exports.file_google_protobuf_timestamp = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/timestamp.proto.
*/
exports.file_google_protobuf_timestamp = (0, file_js_1.fileDesc)("Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJvdG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MYAiABKAVChQEKE2NvbS5nb29nbGUucHJvdG9idWZCDlRpbWVzdGFtcFByb3RvUAFaMmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3RpbWVzdGFtcHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
/**
* Describes the message google.protobuf.Timestamp.
* Use `create(TimestampSchema)` to create a new message.
*/
exports.TimestampSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_timestamp, 0);
import type { GenEnum, GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Any, AnyJson } from "./any_pb.js";
import type { SourceContext, SourceContextJson } from "./source_context_pb.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/type.proto.
*/
export declare const file_google_protobuf_type: GenFile;
/**
* A protocol buffer message type.
*
* New usages of this message as an alternative to DescriptorProto are strongly
* discouraged. This message does not reliability preserve all information
* necessary to model the schema and preserve semantics. Instead make use of
* FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Type
*/
export type Type = Message<"google.protobuf.Type"> & {
/**
* The fully qualified message name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The list of fields.
*
* @generated from field: repeated google.protobuf.Field fields = 2;
*/
fields: Field[];
/**
* The list of types appearing in `oneof` definitions in this type.
*
* @generated from field: repeated string oneofs = 3;
*/
oneofs: string[];
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 4;
*/
options: Option[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContext | undefined;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 6;
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 7;
*/
edition: string;
};
/**
* A protocol buffer message type.
*
* New usages of this message as an alternative to DescriptorProto are strongly
* discouraged. This message does not reliability preserve all information
* necessary to model the schema and preserve semantics. Instead make use of
* FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Type
*/
export type TypeJson = {
/**
* The fully qualified message name.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* The list of fields.
*
* @generated from field: repeated google.protobuf.Field fields = 2;
*/
fields?: FieldJson[];
/**
* The list of types appearing in `oneof` definitions in this type.
*
* @generated from field: repeated string oneofs = 3;
*/
oneofs?: string[];
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 4;
*/
options?: OptionJson[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContextJson;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 6;
*/
syntax?: SyntaxJson;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 7;
*/
edition?: string;
};
/**
* Describes the message google.protobuf.Type.
* Use `create(TypeSchema)` to create a new message.
*/
export declare const TypeSchema: GenMessage<Type, {
jsonType: TypeJson;
}>;
/**
* A single field of a message type.
*
* New usages of this message as an alternative to FieldDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Field
*/
export type Field = Message<"google.protobuf.Field"> & {
/**
* The field type.
*
* @generated from field: google.protobuf.Field.Kind kind = 1;
*/
kind: Field_Kind;
/**
* The field cardinality.
*
* @generated from field: google.protobuf.Field.Cardinality cardinality = 2;
*/
cardinality: Field_Cardinality;
/**
* The field number.
*
* @generated from field: int32 number = 3;
*/
number: number;
/**
* The field name.
*
* @generated from field: string name = 4;
*/
name: string;
/**
* The field type URL, without the scheme, for message or enumeration
* types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
*
* @generated from field: string type_url = 6;
*/
typeUrl: string;
/**
* The index of the field type in `Type.oneofs`, for message or enumeration
* types. The first type has index 1; zero means the type is not in the list.
*
* @generated from field: int32 oneof_index = 7;
*/
oneofIndex: number;
/**
* Whether to use alternative packed wire representation.
*
* @generated from field: bool packed = 8;
*/
packed: boolean;
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 9;
*/
options: Option[];
/**
* The field JSON name.
*
* @generated from field: string json_name = 10;
*/
jsonName: string;
/**
* The string value of the default value of this field. Proto2 syntax only.
*
* @generated from field: string default_value = 11;
*/
defaultValue: string;
};
/**
* A single field of a message type.
*
* New usages of this message as an alternative to FieldDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Field
*/
export type FieldJson = {
/**
* The field type.
*
* @generated from field: google.protobuf.Field.Kind kind = 1;
*/
kind?: Field_KindJson;
/**
* The field cardinality.
*
* @generated from field: google.protobuf.Field.Cardinality cardinality = 2;
*/
cardinality?: Field_CardinalityJson;
/**
* The field number.
*
* @generated from field: int32 number = 3;
*/
number?: number;
/**
* The field name.
*
* @generated from field: string name = 4;
*/
name?: string;
/**
* The field type URL, without the scheme, for message or enumeration
* types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
*
* @generated from field: string type_url = 6;
*/
typeUrl?: string;
/**
* The index of the field type in `Type.oneofs`, for message or enumeration
* types. The first type has index 1; zero means the type is not in the list.
*
* @generated from field: int32 oneof_index = 7;
*/
oneofIndex?: number;
/**
* Whether to use alternative packed wire representation.
*
* @generated from field: bool packed = 8;
*/
packed?: boolean;
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 9;
*/
options?: OptionJson[];
/**
* The field JSON name.
*
* @generated from field: string json_name = 10;
*/
jsonName?: string;
/**
* The string value of the default value of this field. Proto2 syntax only.
*
* @generated from field: string default_value = 11;
*/
defaultValue?: string;
};
/**
* Describes the message google.protobuf.Field.
* Use `create(FieldSchema)` to create a new message.
*/
export declare const FieldSchema: GenMessage<Field, {
jsonType: FieldJson;
}>;
/**
* Basic field types.
*
* @generated from enum google.protobuf.Field.Kind
*/
export declare enum Field_Kind {
/**
* Field type unknown.
*
* @generated from enum value: TYPE_UNKNOWN = 0;
*/
TYPE_UNKNOWN = 0,
/**
* Field type double.
*
* @generated from enum value: TYPE_DOUBLE = 1;
*/
TYPE_DOUBLE = 1,
/**
* Field type float.
*
* @generated from enum value: TYPE_FLOAT = 2;
*/
TYPE_FLOAT = 2,
/**
* Field type int64.
*
* @generated from enum value: TYPE_INT64 = 3;
*/
TYPE_INT64 = 3,
/**
* Field type uint64.
*
* @generated from enum value: TYPE_UINT64 = 4;
*/
TYPE_UINT64 = 4,
/**
* Field type int32.
*
* @generated from enum value: TYPE_INT32 = 5;
*/
TYPE_INT32 = 5,
/**
* Field type fixed64.
*
* @generated from enum value: TYPE_FIXED64 = 6;
*/
TYPE_FIXED64 = 6,
/**
* Field type fixed32.
*
* @generated from enum value: TYPE_FIXED32 = 7;
*/
TYPE_FIXED32 = 7,
/**
* Field type bool.
*
* @generated from enum value: TYPE_BOOL = 8;
*/
TYPE_BOOL = 8,
/**
* Field type string.
*
* @generated from enum value: TYPE_STRING = 9;
*/
TYPE_STRING = 9,
/**
* Field type group. Proto2 syntax only, and deprecated.
*
* @generated from enum value: TYPE_GROUP = 10;
*/
TYPE_GROUP = 10,
/**
* Field type message.
*
* @generated from enum value: TYPE_MESSAGE = 11;
*/
TYPE_MESSAGE = 11,
/**
* Field type bytes.
*
* @generated from enum value: TYPE_BYTES = 12;
*/
TYPE_BYTES = 12,
/**
* Field type uint32.
*
* @generated from enum value: TYPE_UINT32 = 13;
*/
TYPE_UINT32 = 13,
/**
* Field type enum.
*
* @generated from enum value: TYPE_ENUM = 14;
*/
TYPE_ENUM = 14,
/**
* Field type sfixed32.
*
* @generated from enum value: TYPE_SFIXED32 = 15;
*/
TYPE_SFIXED32 = 15,
/**
* Field type sfixed64.
*
* @generated from enum value: TYPE_SFIXED64 = 16;
*/
TYPE_SFIXED64 = 16,
/**
* Field type sint32.
*
* @generated from enum value: TYPE_SINT32 = 17;
*/
TYPE_SINT32 = 17,
/**
* Field type sint64.
*
* @generated from enum value: TYPE_SINT64 = 18;
*/
TYPE_SINT64 = 18
}
/**
* Basic field types.
*
* @generated from enum google.protobuf.Field.Kind
*/
export type Field_KindJson = "TYPE_UNKNOWN" | "TYPE_DOUBLE" | "TYPE_FLOAT" | "TYPE_INT64" | "TYPE_UINT64" | "TYPE_INT32" | "TYPE_FIXED64" | "TYPE_FIXED32" | "TYPE_BOOL" | "TYPE_STRING" | "TYPE_GROUP" | "TYPE_MESSAGE" | "TYPE_BYTES" | "TYPE_UINT32" | "TYPE_ENUM" | "TYPE_SFIXED32" | "TYPE_SFIXED64" | "TYPE_SINT32" | "TYPE_SINT64";
/**
* Describes the enum google.protobuf.Field.Kind.
*/
export declare const Field_KindSchema: GenEnum<Field_Kind, Field_KindJson>;
/**
* Whether a field is optional, required, or repeated.
*
* @generated from enum google.protobuf.Field.Cardinality
*/
export declare enum Field_Cardinality {
/**
* For fields with unknown cardinality.
*
* @generated from enum value: CARDINALITY_UNKNOWN = 0;
*/
UNKNOWN = 0,
/**
* For optional fields.
*
* @generated from enum value: CARDINALITY_OPTIONAL = 1;
*/
OPTIONAL = 1,
/**
* For required fields. Proto2 syntax only.
*
* @generated from enum value: CARDINALITY_REQUIRED = 2;
*/
REQUIRED = 2,
/**
* For repeated fields.
*
* @generated from enum value: CARDINALITY_REPEATED = 3;
*/
REPEATED = 3
}
/**
* Whether a field is optional, required, or repeated.
*
* @generated from enum google.protobuf.Field.Cardinality
*/
export type Field_CardinalityJson = "CARDINALITY_UNKNOWN" | "CARDINALITY_OPTIONAL" | "CARDINALITY_REQUIRED" | "CARDINALITY_REPEATED";
/**
* Describes the enum google.protobuf.Field.Cardinality.
*/
export declare const Field_CardinalitySchema: GenEnum<Field_Cardinality, Field_CardinalityJson>;
/**
* Enum type definition.
*
* New usages of this message as an alternative to EnumDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Enum
*/
export type Enum = Message<"google.protobuf.Enum"> & {
/**
* Enum type name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* Enum value definitions.
*
* @generated from field: repeated google.protobuf.EnumValue enumvalue = 2;
*/
enumvalue: EnumValue[];
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 4;
*/
sourceContext?: SourceContext | undefined;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 5;
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 6;
*/
edition: string;
};
/**
* Enum type definition.
*
* New usages of this message as an alternative to EnumDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.Enum
*/
export type EnumJson = {
/**
* Enum type name.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* Enum value definitions.
*
* @generated from field: repeated google.protobuf.EnumValue enumvalue = 2;
*/
enumvalue?: EnumValueJson[];
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options?: OptionJson[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 4;
*/
sourceContext?: SourceContextJson;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 5;
*/
syntax?: SyntaxJson;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 6;
*/
edition?: string;
};
/**
* Describes the message google.protobuf.Enum.
* Use `create(EnumSchema)` to create a new message.
*/
export declare const EnumSchema: GenMessage<Enum, {
jsonType: EnumJson;
}>;
/**
* Enum value definition.
*
* New usages of this message as an alternative to EnumValueDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.EnumValue
*/
export type EnumValue = Message<"google.protobuf.EnumValue"> & {
/**
* Enum value name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* Enum value number.
*
* @generated from field: int32 number = 2;
*/
number: number;
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
};
/**
* Enum value definition.
*
* New usages of this message as an alternative to EnumValueDescriptorProto are
* strongly discouraged. This message does not reliability preserve all
* information necessary to model the schema and preserve semantics. Instead
* make use of FileDescriptorSet which preserves the necessary information.
*
* @generated from message google.protobuf.EnumValue
*/
export type EnumValueJson = {
/**
* Enum value name.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* Enum value number.
*
* @generated from field: int32 number = 2;
*/
number?: number;
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options?: OptionJson[];
};
/**
* Describes the message google.protobuf.EnumValue.
* Use `create(EnumValueSchema)` to create a new message.
*/
export declare const EnumValueSchema: GenMessage<EnumValue, {
jsonType: EnumValueJson;
}>;
/**
* A protocol buffer option, which can be attached to a message, field,
* enumeration, etc.
*
* New usages of this message as an alternative to FileOptions, MessageOptions,
* FieldOptions, EnumOptions, EnumValueOptions, ServiceOptions, or MethodOptions
* are strongly discouraged.
*
* @generated from message google.protobuf.Option
*/
export type Option = Message<"google.protobuf.Option"> & {
/**
* The option's name. For protobuf built-in options (options defined in
* descriptor.proto), this is the short name. For example, `"map_entry"`.
* For custom options, it should be the fully-qualified name. For example,
* `"google.api.http"`.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The option's value packed in an Any message. If the value is a primitive,
* the corresponding wrapper type defined in google/protobuf/wrappers.proto
* should be used. If the value is an enum, it should be stored as an int32
* value using the google.protobuf.Int32Value type.
*
* @generated from field: google.protobuf.Any value = 2;
*/
value?: Any | undefined;
};
/**
* A protocol buffer option, which can be attached to a message, field,
* enumeration, etc.
*
* New usages of this message as an alternative to FileOptions, MessageOptions,
* FieldOptions, EnumOptions, EnumValueOptions, ServiceOptions, or MethodOptions
* are strongly discouraged.
*
* @generated from message google.protobuf.Option
*/
export type OptionJson = {
/**
* The option's name. For protobuf built-in options (options defined in
* descriptor.proto), this is the short name. For example, `"map_entry"`.
* For custom options, it should be the fully-qualified name. For example,
* `"google.api.http"`.
*
* @generated from field: string name = 1;
*/
name?: string;
/**
* The option's value packed in an Any message. If the value is a primitive,
* the corresponding wrapper type defined in google/protobuf/wrappers.proto
* should be used. If the value is an enum, it should be stored as an int32
* value using the google.protobuf.Int32Value type.
*
* @generated from field: google.protobuf.Any value = 2;
*/
value?: AnyJson;
};
/**
* Describes the message google.protobuf.Option.
* Use `create(OptionSchema)` to create a new message.
*/
export declare const OptionSchema: GenMessage<Option, {
jsonType: OptionJson;
}>;
/**
* The syntax in which a protocol buffer element is defined.
*
* @generated from enum google.protobuf.Syntax
*/
export declare enum Syntax {
/**
* Syntax `proto2`.
*
* @generated from enum value: SYNTAX_PROTO2 = 0;
*/
PROTO2 = 0,
/**
* Syntax `proto3`.
*
* @generated from enum value: SYNTAX_PROTO3 = 1;
*/
PROTO3 = 1,
/**
* Syntax `editions`.
*
* @generated from enum value: SYNTAX_EDITIONS = 2;
*/
EDITIONS = 2
}
/**
* The syntax in which a protocol buffer element is defined.
*
* @generated from enum google.protobuf.Syntax
*/
export type SyntaxJson = "SYNTAX_PROTO2" | "SYNTAX_PROTO3" | "SYNTAX_EDITIONS";
/**
* Describes the enum google.protobuf.Syntax.
*/
export declare const SyntaxSchema: GenEnum<Syntax, SyntaxJson>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SyntaxSchema = exports.Syntax = exports.OptionSchema = exports.EnumValueSchema = exports.EnumSchema = exports.Field_CardinalitySchema = exports.Field_Cardinality = exports.Field_KindSchema = exports.Field_Kind = exports.FieldSchema = exports.TypeSchema = exports.file_google_protobuf_type = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const any_pb_js_1 = require("./any_pb.js");
const source_context_pb_js_1 = require("./source_context_pb.js");
const message_js_1 = require("../../../../codegenv2/message.js");
const enum_js_1 = require("../../../../codegenv2/enum.js");
/**
* Describes the file google/protobuf/type.proto.
*/
exports.file_google_protobuf_type = (0, file_js_1.fileDesc)("Chpnb29nbGUvcHJvdG9idWYvdHlwZS5wcm90bxIPZ29vZ2xlLnByb3RvYnVmIugBCgRUeXBlEgwKBG5hbWUYASABKAkSJgoGZmllbGRzGAIgAygLMhYuZ29vZ2xlLnByb3RvYnVmLkZpZWxkEg4KBm9uZW9mcxgDIAMoCRIoCgdvcHRpb25zGAQgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhI2Cg5zb3VyY2VfY29udGV4dBgFIAEoCzIeLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb250ZXh0EicKBnN5bnRheBgGIAEoDjIXLmdvb2dsZS5wcm90b2J1Zi5TeW50YXgSDwoHZWRpdGlvbhgHIAEoCSLVBQoFRmllbGQSKQoEa2luZBgBIAEoDjIbLmdvb2dsZS5wcm90b2J1Zi5GaWVsZC5LaW5kEjcKC2NhcmRpbmFsaXR5GAIgASgOMiIuZ29vZ2xlLnByb3RvYnVmLkZpZWxkLkNhcmRpbmFsaXR5Eg4KBm51bWJlchgDIAEoBRIMCgRuYW1lGAQgASgJEhAKCHR5cGVfdXJsGAYgASgJEhMKC29uZW9mX2luZGV4GAcgASgFEg4KBnBhY2tlZBgIIAEoCBIoCgdvcHRpb25zGAkgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhIRCglqc29uX25hbWUYCiABKAkSFQoNZGVmYXVsdF92YWx1ZRgLIAEoCSLIAgoES2luZBIQCgxUWVBFX1VOS05PV04QABIPCgtUWVBFX0RPVUJMRRABEg4KClRZUEVfRkxPQVQQAhIOCgpUWVBFX0lOVDY0EAMSDwoLVFlQRV9VSU5UNjQQBBIOCgpUWVBFX0lOVDMyEAUSEAoMVFlQRV9GSVhFRDY0EAYSEAoMVFlQRV9GSVhFRDMyEAcSDQoJVFlQRV9CT09MEAgSDwoLVFlQRV9TVFJJTkcQCRIOCgpUWVBFX0dST1VQEAoSEAoMVFlQRV9NRVNTQUdFEAsSDgoKVFlQRV9CWVRFUxAMEg8KC1RZUEVfVUlOVDMyEA0SDQoJVFlQRV9FTlVNEA4SEQoNVFlQRV9TRklYRUQzMhAPEhEKDVRZUEVfU0ZJWEVENjQQEBIPCgtUWVBFX1NJTlQzMhAREg8KC1RZUEVfU0lOVDY0EBIidAoLQ2FyZGluYWxpdHkSFwoTQ0FSRElOQUxJVFlfVU5LTk9XThAAEhgKFENBUkRJTkFMSVRZX09QVElPTkFMEAESGAoUQ0FSRElOQUxJVFlfUkVRVUlSRUQQAhIYChRDQVJESU5BTElUWV9SRVBFQVRFRBADIt8BCgRFbnVtEgwKBG5hbWUYASABKAkSLQoJZW51bXZhbHVlGAIgAygLMhouZ29vZ2xlLnByb3RvYnVmLkVudW1WYWx1ZRIoCgdvcHRpb25zGAMgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhI2Cg5zb3VyY2VfY29udGV4dBgEIAEoCzIeLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb250ZXh0EicKBnN5bnRheBgFIAEoDjIXLmdvb2dsZS5wcm90b2J1Zi5TeW50YXgSDwoHZWRpdGlvbhgGIAEoCSJTCglFbnVtVmFsdWUSDAoEbmFtZRgBIAEoCRIOCgZudW1iZXIYAiABKAUSKAoHb3B0aW9ucxgDIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5PcHRpb24iOwoGT3B0aW9uEgwKBG5hbWUYASABKAkSIwoFdmFsdWUYAiABKAsyFC5nb29nbGUucHJvdG9idWYuQW55KkMKBlN5bnRheBIRCg1TWU5UQVhfUFJPVE8yEAASEQoNU1lOVEFYX1BST1RPMxABEhMKD1NZTlRBWF9FRElUSU9OUxACQnsKE2NvbS5nb29nbGUucHJvdG9idWZCCVR5cGVQcm90b1ABWi1nb29nbGUuZ29sYW5nLm9yZy9wcm90b2J1Zi90eXBlcy9rbm93bi90eXBlcGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw", [any_pb_js_1.file_google_protobuf_any, source_context_pb_js_1.file_google_protobuf_source_context]);
/**
* Describes the message google.protobuf.Type.
* Use `create(TypeSchema)` to create a new message.
*/
exports.TypeSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 0);
/**
* Describes the message google.protobuf.Field.
* Use `create(FieldSchema)` to create a new message.
*/
exports.FieldSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 1);
/**
* Basic field types.
*
* @generated from enum google.protobuf.Field.Kind
*/
var Field_Kind;
(function (Field_Kind) {
/**
* Field type unknown.
*
* @generated from enum value: TYPE_UNKNOWN = 0;
*/
Field_Kind[Field_Kind["TYPE_UNKNOWN"] = 0] = "TYPE_UNKNOWN";
/**
* Field type double.
*
* @generated from enum value: TYPE_DOUBLE = 1;
*/
Field_Kind[Field_Kind["TYPE_DOUBLE"] = 1] = "TYPE_DOUBLE";
/**
* Field type float.
*
* @generated from enum value: TYPE_FLOAT = 2;
*/
Field_Kind[Field_Kind["TYPE_FLOAT"] = 2] = "TYPE_FLOAT";
/**
* Field type int64.
*
* @generated from enum value: TYPE_INT64 = 3;
*/
Field_Kind[Field_Kind["TYPE_INT64"] = 3] = "TYPE_INT64";
/**
* Field type uint64.
*
* @generated from enum value: TYPE_UINT64 = 4;
*/
Field_Kind[Field_Kind["TYPE_UINT64"] = 4] = "TYPE_UINT64";
/**
* Field type int32.
*
* @generated from enum value: TYPE_INT32 = 5;
*/
Field_Kind[Field_Kind["TYPE_INT32"] = 5] = "TYPE_INT32";
/**
* Field type fixed64.
*
* @generated from enum value: TYPE_FIXED64 = 6;
*/
Field_Kind[Field_Kind["TYPE_FIXED64"] = 6] = "TYPE_FIXED64";
/**
* Field type fixed32.
*
* @generated from enum value: TYPE_FIXED32 = 7;
*/
Field_Kind[Field_Kind["TYPE_FIXED32"] = 7] = "TYPE_FIXED32";
/**
* Field type bool.
*
* @generated from enum value: TYPE_BOOL = 8;
*/
Field_Kind[Field_Kind["TYPE_BOOL"] = 8] = "TYPE_BOOL";
/**
* Field type string.
*
* @generated from enum value: TYPE_STRING = 9;
*/
Field_Kind[Field_Kind["TYPE_STRING"] = 9] = "TYPE_STRING";
/**
* Field type group. Proto2 syntax only, and deprecated.
*
* @generated from enum value: TYPE_GROUP = 10;
*/
Field_Kind[Field_Kind["TYPE_GROUP"] = 10] = "TYPE_GROUP";
/**
* Field type message.
*
* @generated from enum value: TYPE_MESSAGE = 11;
*/
Field_Kind[Field_Kind["TYPE_MESSAGE"] = 11] = "TYPE_MESSAGE";
/**
* Field type bytes.
*
* @generated from enum value: TYPE_BYTES = 12;
*/
Field_Kind[Field_Kind["TYPE_BYTES"] = 12] = "TYPE_BYTES";
/**
* Field type uint32.
*
* @generated from enum value: TYPE_UINT32 = 13;
*/
Field_Kind[Field_Kind["TYPE_UINT32"] = 13] = "TYPE_UINT32";
/**
* Field type enum.
*
* @generated from enum value: TYPE_ENUM = 14;
*/
Field_Kind[Field_Kind["TYPE_ENUM"] = 14] = "TYPE_ENUM";
/**
* Field type sfixed32.
*
* @generated from enum value: TYPE_SFIXED32 = 15;
*/
Field_Kind[Field_Kind["TYPE_SFIXED32"] = 15] = "TYPE_SFIXED32";
/**
* Field type sfixed64.
*
* @generated from enum value: TYPE_SFIXED64 = 16;
*/
Field_Kind[Field_Kind["TYPE_SFIXED64"] = 16] = "TYPE_SFIXED64";
/**
* Field type sint32.
*
* @generated from enum value: TYPE_SINT32 = 17;
*/
Field_Kind[Field_Kind["TYPE_SINT32"] = 17] = "TYPE_SINT32";
/**
* Field type sint64.
*
* @generated from enum value: TYPE_SINT64 = 18;
*/
Field_Kind[Field_Kind["TYPE_SINT64"] = 18] = "TYPE_SINT64";
})(Field_Kind || (exports.Field_Kind = Field_Kind = {}));
/**
* Describes the enum google.protobuf.Field.Kind.
*/
exports.Field_KindSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_type, 1, 0);
/**
* Whether a field is optional, required, or repeated.
*
* @generated from enum google.protobuf.Field.Cardinality
*/
var Field_Cardinality;
(function (Field_Cardinality) {
/**
* For fields with unknown cardinality.
*
* @generated from enum value: CARDINALITY_UNKNOWN = 0;
*/
Field_Cardinality[Field_Cardinality["UNKNOWN"] = 0] = "UNKNOWN";
/**
* For optional fields.
*
* @generated from enum value: CARDINALITY_OPTIONAL = 1;
*/
Field_Cardinality[Field_Cardinality["OPTIONAL"] = 1] = "OPTIONAL";
/**
* For required fields. Proto2 syntax only.
*
* @generated from enum value: CARDINALITY_REQUIRED = 2;
*/
Field_Cardinality[Field_Cardinality["REQUIRED"] = 2] = "REQUIRED";
/**
* For repeated fields.
*
* @generated from enum value: CARDINALITY_REPEATED = 3;
*/
Field_Cardinality[Field_Cardinality["REPEATED"] = 3] = "REPEATED";
})(Field_Cardinality || (exports.Field_Cardinality = Field_Cardinality = {}));
/**
* Describes the enum google.protobuf.Field.Cardinality.
*/
exports.Field_CardinalitySchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_type, 1, 1);
/**
* Describes the message google.protobuf.Enum.
* Use `create(EnumSchema)` to create a new message.
*/
exports.EnumSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 2);
/**
* Describes the message google.protobuf.EnumValue.
* Use `create(EnumValueSchema)` to create a new message.
*/
exports.EnumValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 3);
/**
* Describes the message google.protobuf.Option.
* Use `create(OptionSchema)` to create a new message.
*/
exports.OptionSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_type, 4);
/**
* The syntax in which a protocol buffer element is defined.
*
* @generated from enum google.protobuf.Syntax
*/
var Syntax;
(function (Syntax) {
/**
* Syntax `proto2`.
*
* @generated from enum value: SYNTAX_PROTO2 = 0;
*/
Syntax[Syntax["PROTO2"] = 0] = "PROTO2";
/**
* Syntax `proto3`.
*
* @generated from enum value: SYNTAX_PROTO3 = 1;
*/
Syntax[Syntax["PROTO3"] = 1] = "PROTO3";
/**
* Syntax `editions`.
*
* @generated from enum value: SYNTAX_EDITIONS = 2;
*/
Syntax[Syntax["EDITIONS"] = 2] = "EDITIONS";
})(Syntax || (exports.Syntax = Syntax = {}));
/**
* Describes the enum google.protobuf.Syntax.
*/
exports.SyntaxSchema = (0, enum_js_1.enumDesc)(exports.file_google_protobuf_type, 0);
import type { GenFile, GenMessage } from "../../../../codegenv2/types.js";
import type { Message } from "../../../../types.js";
/**
* Describes the file google/protobuf/wrappers.proto.
*/
export declare const file_google_protobuf_wrappers: GenFile;
/**
* Wrapper message for `double`.
*
* The JSON representation for `DoubleValue` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.DoubleValue
*/
export type DoubleValue = Message<"google.protobuf.DoubleValue"> & {
/**
* The double value.
*
* @generated from field: double value = 1;
*/
value: number;
};
/**
* Wrapper message for `double`.
*
* The JSON representation for `DoubleValue` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.DoubleValue
*/
export type DoubleValueJson = number | "NaN" | "Infinity" | "-Infinity";
/**
* Describes the message google.protobuf.DoubleValue.
* Use `create(DoubleValueSchema)` to create a new message.
*/
export declare const DoubleValueSchema: GenMessage<DoubleValue, {
jsonType: DoubleValueJson;
}>;
/**
* Wrapper message for `float`.
*
* The JSON representation for `FloatValue` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.FloatValue
*/
export type FloatValue = Message<"google.protobuf.FloatValue"> & {
/**
* The float value.
*
* @generated from field: float value = 1;
*/
value: number;
};
/**
* Wrapper message for `float`.
*
* The JSON representation for `FloatValue` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.FloatValue
*/
export type FloatValueJson = number | "NaN" | "Infinity" | "-Infinity";
/**
* Describes the message google.protobuf.FloatValue.
* Use `create(FloatValueSchema)` to create a new message.
*/
export declare const FloatValueSchema: GenMessage<FloatValue, {
jsonType: FloatValueJson;
}>;
/**
* Wrapper message for `int64`.
*
* The JSON representation for `Int64Value` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.Int64Value
*/
export type Int64Value = Message<"google.protobuf.Int64Value"> & {
/**
* The int64 value.
*
* @generated from field: int64 value = 1;
*/
value: bigint;
};
/**
* Wrapper message for `int64`.
*
* The JSON representation for `Int64Value` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.Int64Value
*/
export type Int64ValueJson = string;
/**
* Describes the message google.protobuf.Int64Value.
* Use `create(Int64ValueSchema)` to create a new message.
*/
export declare const Int64ValueSchema: GenMessage<Int64Value, {
jsonType: Int64ValueJson;
}>;
/**
* Wrapper message for `uint64`.
*
* The JSON representation for `UInt64Value` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.UInt64Value
*/
export type UInt64Value = Message<"google.protobuf.UInt64Value"> & {
/**
* The uint64 value.
*
* @generated from field: uint64 value = 1;
*/
value: bigint;
};
/**
* Wrapper message for `uint64`.
*
* The JSON representation for `UInt64Value` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.UInt64Value
*/
export type UInt64ValueJson = string;
/**
* Describes the message google.protobuf.UInt64Value.
* Use `create(UInt64ValueSchema)` to create a new message.
*/
export declare const UInt64ValueSchema: GenMessage<UInt64Value, {
jsonType: UInt64ValueJson;
}>;
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.Int32Value
*/
export type Int32Value = Message<"google.protobuf.Int32Value"> & {
/**
* The int32 value.
*
* @generated from field: int32 value = 1;
*/
value: number;
};
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.Int32Value
*/
export type Int32ValueJson = number;
/**
* Describes the message google.protobuf.Int32Value.
* Use `create(Int32ValueSchema)` to create a new message.
*/
export declare const Int32ValueSchema: GenMessage<Int32Value, {
jsonType: Int32ValueJson;
}>;
/**
* Wrapper message for `uint32`.
*
* The JSON representation for `UInt32Value` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.UInt32Value
*/
export type UInt32Value = Message<"google.protobuf.UInt32Value"> & {
/**
* The uint32 value.
*
* @generated from field: uint32 value = 1;
*/
value: number;
};
/**
* Wrapper message for `uint32`.
*
* The JSON representation for `UInt32Value` is JSON number.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.UInt32Value
*/
export type UInt32ValueJson = number;
/**
* Describes the message google.protobuf.UInt32Value.
* Use `create(UInt32ValueSchema)` to create a new message.
*/
export declare const UInt32ValueSchema: GenMessage<UInt32Value, {
jsonType: UInt32ValueJson;
}>;
/**
* Wrapper message for `bool`.
*
* The JSON representation for `BoolValue` is JSON `true` and `false`.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.BoolValue
*/
export type BoolValue = Message<"google.protobuf.BoolValue"> & {
/**
* The bool value.
*
* @generated from field: bool value = 1;
*/
value: boolean;
};
/**
* Wrapper message for `bool`.
*
* The JSON representation for `BoolValue` is JSON `true` and `false`.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.BoolValue
*/
export type BoolValueJson = boolean;
/**
* Describes the message google.protobuf.BoolValue.
* Use `create(BoolValueSchema)` to create a new message.
*/
export declare const BoolValueSchema: GenMessage<BoolValue, {
jsonType: BoolValueJson;
}>;
/**
* Wrapper message for `string`.
*
* The JSON representation for `StringValue` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.StringValue
*/
export type StringValue = Message<"google.protobuf.StringValue"> & {
/**
* The string value.
*
* @generated from field: string value = 1;
*/
value: string;
};
/**
* Wrapper message for `string`.
*
* The JSON representation for `StringValue` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.StringValue
*/
export type StringValueJson = string;
/**
* Describes the message google.protobuf.StringValue.
* Use `create(StringValueSchema)` to create a new message.
*/
export declare const StringValueSchema: GenMessage<StringValue, {
jsonType: StringValueJson;
}>;
/**
* Wrapper message for `bytes`.
*
* The JSON representation for `BytesValue` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.BytesValue
*/
export type BytesValue = Message<"google.protobuf.BytesValue"> & {
/**
* The bytes value.
*
* @generated from field: bytes value = 1;
*/
value: Uint8Array;
};
/**
* Wrapper message for `bytes`.
*
* The JSON representation for `BytesValue` is JSON string.
*
* Not recommended for use in new APIs, but still useful for legacy APIs and
* has no plan to be removed.
*
* @generated from message google.protobuf.BytesValue
*/
export type BytesValueJson = string;
/**
* Describes the message google.protobuf.BytesValue.
* Use `create(BytesValueSchema)` to create a new message.
*/
export declare const BytesValueSchema: GenMessage<BytesValue, {
jsonType: BytesValueJson;
}>;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BytesValueSchema = exports.StringValueSchema = exports.BoolValueSchema = exports.UInt32ValueSchema = exports.Int32ValueSchema = exports.UInt64ValueSchema = exports.Int64ValueSchema = exports.FloatValueSchema = exports.DoubleValueSchema = exports.file_google_protobuf_wrappers = void 0;
const file_js_1 = require("../../../../codegenv2/file.js");
const message_js_1 = require("../../../../codegenv2/message.js");
/**
* Describes the file google/protobuf/wrappers.proto.
*/
exports.file_google_protobuf_wrappers = (0, file_js_1.fileDesc)("Ch5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIcCgtEb3VibGVWYWx1ZRINCgV2YWx1ZRgBIAEoASIbCgpGbG9hdFZhbHVlEg0KBXZhbHVlGAEgASgCIhsKCkludDY0VmFsdWUSDQoFdmFsdWUYASABKAMiHAoLVUludDY0VmFsdWUSDQoFdmFsdWUYASABKAQiGwoKSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEoBSIcCgtVSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEoDSIaCglCb29sVmFsdWUSDQoFdmFsdWUYASABKAgiHAoLU3RyaW5nVmFsdWUSDQoFdmFsdWUYASABKAkiGwoKQnl0ZXNWYWx1ZRINCgV2YWx1ZRgBIAEoDEKDAQoTY29tLmdvb2dsZS5wcm90b2J1ZkINV3JhcHBlcnNQcm90b1ABWjFnb29nbGUuZ29sYW5nLm9yZy9wcm90b2J1Zi90eXBlcy9rbm93bi93cmFwcGVyc3Bi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
/**
* Describes the message google.protobuf.DoubleValue.
* Use `create(DoubleValueSchema)` to create a new message.
*/
exports.DoubleValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 0);
/**
* Describes the message google.protobuf.FloatValue.
* Use `create(FloatValueSchema)` to create a new message.
*/
exports.FloatValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 1);
/**
* Describes the message google.protobuf.Int64Value.
* Use `create(Int64ValueSchema)` to create a new message.
*/
exports.Int64ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 2);
/**
* Describes the message google.protobuf.UInt64Value.
* Use `create(UInt64ValueSchema)` to create a new message.
*/
exports.UInt64ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 3);
/**
* Describes the message google.protobuf.Int32Value.
* Use `create(Int32ValueSchema)` to create a new message.
*/
exports.Int32ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 4);
/**
* Describes the message google.protobuf.UInt32Value.
* Use `create(UInt32ValueSchema)` to create a new message.
*/
exports.UInt32ValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 5);
/**
* Describes the message google.protobuf.BoolValue.
* Use `create(BoolValueSchema)` to create a new message.
*/
exports.BoolValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 6);
/**
* Describes the message google.protobuf.StringValue.
* Use `create(StringValueSchema)` to create a new message.
*/
exports.StringValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 7);
/**
* Describes the message google.protobuf.BytesValue.
* Use `create(BytesValueSchema)` to create a new message.
*/
exports.BytesValueSchema = (0, message_js_1.messageDesc)(exports.file_google_protobuf_wrappers, 8);
export * from "./timestamp.js";
export * from "./duration.js";
export * from "./any.js";
export * from "./wrappers.js";
export * from "./gen/google/protobuf/any_pb.js";
export * from "./gen/google/protobuf/api_pb.js";
export * from "./gen/google/protobuf/cpp_features_pb.js";
export * from "./gen/google/protobuf/descriptor_pb.js";
export * from "./gen/google/protobuf/duration_pb.js";
export * from "./gen/google/protobuf/empty_pb.js";
export * from "./gen/google/protobuf/field_mask_pb.js";
export * from "./gen/google/protobuf/go_features_pb.js";
export * from "./gen/google/protobuf/java_features_pb.js";
export * from "./gen/google/protobuf/source_context_pb.js";
export * from "./gen/google/protobuf/struct_pb.js";
export * from "./gen/google/protobuf/timestamp_pb.js";
export * from "./gen/google/protobuf/type_pb.js";
export * from "./gen/google/protobuf/wrappers_pb.js";
export * from "./gen/google/protobuf/compiler/plugin_pb.js";
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./timestamp.js"), exports);
__exportStar(require("./duration.js"), exports);
__exportStar(require("./any.js"), exports);
__exportStar(require("./wrappers.js"), exports);
__exportStar(require("./gen/google/protobuf/any_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/api_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/cpp_features_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/descriptor_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/duration_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/empty_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/field_mask_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/go_features_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/java_features_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/source_context_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/struct_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/timestamp_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/type_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/wrappers_pb.js"), exports);
__exportStar(require("./gen/google/protobuf/compiler/plugin_pb.js"), exports);
import type { Timestamp } from "./gen/google/protobuf/timestamp_pb.js";
/**
* Create a google.protobuf.Timestamp for the current time.
*/
export declare function timestampNow(): Timestamp;
/**
* Create a google.protobuf.Timestamp message from an ECMAScript Date.
*/
export declare function timestampFromDate(date: Date): Timestamp;
/**
* Convert a google.protobuf.Timestamp message to an ECMAScript Date.
*/
export declare function timestampDate(timestamp: Timestamp): Date;
/**
* Create a google.protobuf.Timestamp message from a Unix timestamp in milliseconds.
*/
export declare function timestampFromMs(timestampMs: number): Timestamp;
/**
* Convert a google.protobuf.Timestamp to a Unix timestamp in milliseconds.
*/
export declare function timestampMs(timestamp: Timestamp): number;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.timestampNow = timestampNow;
exports.timestampFromDate = timestampFromDate;
exports.timestampDate = timestampDate;
exports.timestampFromMs = timestampFromMs;
exports.timestampMs = timestampMs;
const timestamp_pb_js_1 = require("./gen/google/protobuf/timestamp_pb.js");
const create_js_1 = require("../create.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Create a google.protobuf.Timestamp for the current time.
*/
function timestampNow() {
return timestampFromDate(new Date());
}
/**
* Create a google.protobuf.Timestamp message from an ECMAScript Date.
*/
function timestampFromDate(date) {
return timestampFromMs(date.getTime());
}
/**
* Convert a google.protobuf.Timestamp message to an ECMAScript Date.
*/
function timestampDate(timestamp) {
return new Date(timestampMs(timestamp));
}
/**
* Create a google.protobuf.Timestamp message from a Unix timestamp in milliseconds.
*/
function timestampFromMs(timestampMs) {
const seconds = Math.floor(timestampMs / 1000);
return (0, create_js_1.create)(timestamp_pb_js_1.TimestampSchema, {
seconds: proto_int64_js_1.protoInt64.parse(seconds),
nanos: (timestampMs - seconds * 1000) * 1000000,
});
}
/**
* Convert a google.protobuf.Timestamp to a Unix timestamp in milliseconds.
*/
function timestampMs(timestamp) {
return (Number(timestamp.seconds) * 1000 + Math.round(timestamp.nanos / 1000000));
}
import type { Message } from "../types.js";
import type { BoolValue, BytesValue, DoubleValue, FloatValue, Int32Value, Int64Value, StringValue, UInt32Value, UInt64Value } from "./gen/google/protobuf/wrappers_pb.js";
import type { DescField, DescMessage } from "../descriptors.js";
export declare function isWrapper(arg: Message): arg is DoubleValue | FloatValue | Int64Value | UInt64Value | Int32Value | UInt32Value | BoolValue | StringValue | BytesValue;
export type WktWrapperDesc = DescMessage & {
fields: [
DescField & {
fieldKind: "scalar";
number: 1;
name: "value";
oneof: undefined;
}
];
};
export declare function isWrapperDesc(messageDesc: DescMessage): messageDesc is WktWrapperDesc;
/**
* Returns true if the descriptor is a well-known type with a custom JSON
* representation per the protobuf JSON spec. Examples: Timestamp as an
* RFC 3339 string, Duration as "5s", wrappers as the unwrapped scalar.
*
* When packed inside `google.protobuf.Any`, these messages are serialized
* as `{"@type": ..., "value": <custom form>}`; all other messages embed
* their fields directly.
*/
export declare function hasCustomJsonRepresentation(desc: DescMessage): boolean;
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isWrapper = isWrapper;
exports.isWrapperDesc = isWrapperDesc;
exports.hasCustomJsonRepresentation = hasCustomJsonRepresentation;
function isWrapper(arg) {
return isWrapperTypeName(arg.$typeName);
}
function isWrapperDesc(messageDesc) {
const f = messageDesc.fields[0];
return (isWrapperTypeName(messageDesc.typeName) &&
f !== undefined &&
f.fieldKind == "scalar" &&
f.name == "value" &&
f.number == 1);
}
/**
* Returns true if the descriptor is a well-known type with a custom JSON
* representation per the protobuf JSON spec. Examples: Timestamp as an
* RFC 3339 string, Duration as "5s", wrappers as the unwrapped scalar.
*
* When packed inside `google.protobuf.Any`, these messages are serialized
* as `{"@type": ..., "value": <custom form>}`; all other messages embed
* their fields directly.
*/
function hasCustomJsonRepresentation(desc) {
switch (desc.typeName) {
case "google.protobuf.Any":
case "google.protobuf.Timestamp":
case "google.protobuf.Duration":
case "google.protobuf.FieldMask":
case "google.protobuf.Struct":
case "google.protobuf.Value":
case "google.protobuf.ListValue":
return true;
default:
return isWrapperDesc(desc);
}
}
function isWrapperTypeName(name) {
return (name.startsWith("google.protobuf.") &&
[
"DoubleValue",
"FloatValue",
"Int64Value",
"UInt64Value",
"Int32Value",
"UInt32Value",
"BoolValue",
"StringValue",
"BytesValue",
].includes(name.substring(16)));
}