UNPKG

@bufbuild/protovalidate

Version:

Protocol Buffer Validation for ECMAScript

68 lines (67 loc) 2.25 kB
// 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 { buildPath, } from "@bufbuild/protobuf/reflect"; import { ValidationError, Violation } from "./error.js"; /** * Cursor maintains a field path and tracks violations. */ export class Cursor { static create(root, failFast) { return new Cursor(root, failFast, [], buildPath(root)); } constructor(root, failFast, violations, builder) { this.root = root; this.failFast = failFast; this.violations = violations; this.builder = builder; } get violated() { return this.violations.length > 0; } violate(message, ruleId, rulePath, forMapKey = false) { this.violations.push(new Violation(message, ruleId, this.builder.toPath(), rulePath, forMapKey)); if (this.failFast) { this.throwIfViolated(); } } throwIfViolated() { if (this.violated) { throw new ValidationError(this.violations); } } getPath() { return this.builder.toPath(); } add(path) { return this.cloneWith(this.builder.clone().add(path)); } field(field) { return this.cloneWith(this.builder.clone().field(field)); } oneof(oneof) { return this.cloneWith(this.builder.clone().oneof(oneof)); } extension(ext) { return this.cloneWith(this.builder.clone().extension(ext)); } list(index) { return this.cloneWith(this.builder.clone().list(index)); } mapKey(key) { return this.cloneWith(this.builder.clone().map(key)); } cloneWith(path) { return new Cursor(this.root, this.failFast, this.violations, path); } }