@bufbuild/protovalidate
Version:
Protocol Buffer Validation for ECMAScript
122 lines (121 loc) • 3.46 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 { scalarEquals, scalarZeroValue, } from "@bufbuild/protobuf/reflect";
import { ScalarType } from "@bufbuild/protobuf";
import { Ignore } from "./gen/buf/validate/validate_pb.js";
import { FeatureSet_FieldPresence } from "@bufbuild/protobuf/wkt";
const always = {
check() {
return true;
},
always: true,
never: false,
};
const never = {
check() {
return false;
},
always: false,
never: true,
};
export function ignoreListOrMapField(field, ignore) {
switch (ignore) {
case undefined:
case Ignore.UNSPECIFIED:
return always;
case Ignore.IF_ZERO_VALUE:
return new FieldIsSet(field);
case Ignore.ALWAYS:
return never;
}
}
export function ignoreMessageField(field, ignore) {
switch (ignore) {
case undefined:
case Ignore.UNSPECIFIED:
case Ignore.IF_ZERO_VALUE:
return new FieldIsSet(field);
case Ignore.ALWAYS:
return never;
}
}
export function ignoreScalarOrEnumField(field, ignore) {
if (ignore == Ignore.ALWAYS) {
return never;
}
if (field.presence == FeatureSet_FieldPresence.IMPLICIT) {
switch (ignore) {
case undefined:
case Ignore.UNSPECIFIED:
return always;
case Ignore.IF_ZERO_VALUE:
return new FieldIsSet(field);
}
}
// field presence EXPLICIT or LEGACY_REQUIRED
return new FieldIsSet(field);
}
export function ignoreEnumValue(enu, ignore) {
switch (ignore) {
case undefined:
case Ignore.UNSPECIFIED:
return always;
case Ignore.IF_ZERO_VALUE:
return new ScalarNot(ScalarType.INT32, enu.values[0].number);
case Ignore.ALWAYS:
return never;
}
}
export function ignoreScalarValue(scalar, ignore) {
switch (ignore) {
case undefined:
case Ignore.UNSPECIFIED:
return always;
case Ignore.IF_ZERO_VALUE:
return new ScalarNot(scalar, scalarZeroValue(scalar, false));
case Ignore.ALWAYS:
return never;
}
}
export function ignoreMessageValue(ignore) {
switch (ignore) {
case undefined:
case Ignore.UNSPECIFIED:
case Ignore.IF_ZERO_VALUE:
return always;
case Ignore.ALWAYS:
return never;
}
}
class ScalarNot {
constructor(scalar, not) {
this.scalar = scalar;
this.not = not;
this.always = false;
this.never = false;
}
check(val) {
return !scalarEquals(this.scalar, this.not, val);
}
}
class FieldIsSet {
constructor(field) {
this.field = field;
this.always = false;
this.never = false;
}
check(val) {
return val.isSet(this.field);
}
}