UNPKG

@bufbuild/protovalidate

Version:

Protocol Buffer Validation for ECMAScript

113 lines (112 loc) 4.08 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 { createValidator } from "./validator.js"; /** * Convert a Violation to a StandardSchemaV1.Issue. */ function violationToIssue(violation) { const path = []; for (const segment of violation.field) { switch (segment.kind) { case "field": path.push(segment.name); continue; case "oneof": path.push(segment.name); continue; case "list_sub": path.push(segment.index); continue; case "map_sub": const key = segment.key; if (typeof key === "string" || typeof key === "number") { path.push(key); } else { path.push(String(key)); } continue; case "extension": // Extensions are represented as field names with brackets path.push(`[${segment.typeName}]`); continue; } } if (path.length > 0) { return { message: violation.message, path: path, }; } return { message: violation.message, }; } /** * Create a Standard Schema compliant validator for a Protobuf message type. * * @param messageDesc - The Protobuf message descriptor * @param options - Optional validator configuration * @returns A StandardSchemaV1 compliant validator */ export function createStandardSchema(messageDesc, options) { const validator = createValidator(options); return { "~standard": { version: 1, vendor: "protovalidate-es", validate: (value) => { // Type guard to ensure value is an object if (typeof value !== "object" || value === null) { return { issues: [ { message: "Expected an object", }, ], }; } const result = validator.validate(messageDesc, value); switch (result.kind) { case "valid": return { value: result.message, }; case "invalid": return { issues: result.violations.map(violationToIssue), }; case "error": // For compilation/runtime errors, we return them as issues return { issues: [ { message: result.error.message, }, ], }; } }, // Standard Schema types property for static analysis and type inference. // This property provides type information to external tools and libraries // for extracting input/output types using InferInput<T> and InferOutput<T>. // Runtime values are intentionally set to undefined to minimize overhead // while maintaining full TypeScript type information. types: { input: undefined, output: undefined, }, }, }; }