@bufbuild/cel
Version:
A CEL evaluator for ECMAScript
71 lines (70 loc) • 2.31 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.
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.celError = celError;
exports.celErrorMerge = celErrorMerge;
exports.isCelError = isCelError;
const privateSymbol = Symbol.for("@bufbuild/cel/error");
/**
* Coerces a value to CelError using the following rules:
* - If the given value is a CelError just return that.
* - If it is an Error type, create a new CelError from that.
* - If it is a string, creates a new CelError with that as the message.
* - In all other cases create a new CelError with the given value as the cause.
*/
function celError(value, exprId) {
if (isCelError(value)) {
return value;
}
if (typeof exprId === "number") {
exprId = BigInt(exprId);
}
if (value instanceof Error) {
return new _CelError(value.message, value, exprId);
}
if (typeof value === "string") {
return new _CelError(value, undefined, exprId);
}
return new _CelError(`${value}`, value, exprId);
}
/**
* Merges CelErrors into one. Uses the message and exprId from the first error and
* add the rest as the cause.
*/
function celErrorMerge(first, ...rest) {
return new _CelError(first.message, rest, first.exprId);
}
/**
* Returns true if the given value is a CelError.
*/
function isCelError(v) {
return typeof v === "object" && v !== null && privateSymbol in v;
}
class _CelError extends Error {
constructor(message, _cause, _exprId) {
super(message);
this._cause = _cause;
this._exprId = _exprId;
this[_a] = {};
}
get exprId() {
return this._exprId;
}
get cause() {
return this._cause;
}
}
_a = privateSymbol;