@bufbuild/protovalidate
Version:
Protocol Buffer Validation for ECMAScript
83 lines (82 loc) • 3.16 kB
JavaScript
// Copyright 2024-2025 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.
import { createMutableRegistry, isMessage, } from "@bufbuild/protobuf";
import { reflect, usedTypes } from "@bufbuild/protobuf/reflect";
import { Cursor } from "./cursor.js";
import { CompilationError, RuntimeError, ValidationError, } from "./error.js";
import { Planner } from "./planner.js";
import { CelManager } from "./cel.js";
import { file_buf_validate_validate } from "./gen/buf/validate/validate_pb.js";
/**
* Create a validator.
*/
export function createValidator(opt) {
const registry = opt?.registry
? createMutableRegistry(opt.registry, file_buf_validate_validate)
: createMutableRegistry(file_buf_validate_validate);
const failFast = opt?.failFast ?? false;
const celMan = new CelManager(registry, opt?.regexMatch);
const planner = new Planner(celMan, opt?.legacyRequired ?? false);
return {
validate(schema, message) {
try {
validateUnsafe(registry, celMan, planner, schema, message, failFast);
}
catch (e) {
if (e instanceof ValidationError) {
return {
kind: "invalid",
message,
error: e,
violations: e.violations,
};
}
if (e instanceof CompilationError || e instanceof RuntimeError) {
return {
kind: "error",
message,
error: e,
};
}
return {
kind: "error",
message,
error: new RuntimeError("unexpected error: " + e, { cause: e }),
};
}
return {
kind: "valid",
message: message,
};
},
};
}
function validateUnsafe(registry, celMan, planner, schema, message, failFast) {
const messageTypeName = message.$typeName;
if (!isMessage(message, schema)) {
throw new RuntimeError(`Cannot validate message ${messageTypeName} with schema ${schema.typeName}`);
}
if (!registry.get(schema.typeName)) {
registry.add(schema);
for (const type of usedTypes(schema)) {
registry.add(type);
}
}
const plan = planner.plan(schema);
const msg = reflect(schema, message);
const cursor = Cursor.create(schema, failFast);
celMan.updateCelNow();
plan.eval(msg, cursor);
cursor.throwIfViolated();
}