bufbuild / protobuf-es

Protocol Buffers for ECMAScript. The only JavaScript Protobuf library that is fully-compliant with Protobuf conformance tests.
Apache License 2.0
1.16k stars 69 forks source link

Add @bufbuild/protocompile to MANUAL.md #988

Closed timostamm closed 1 month ago

timostamm commented 1 month ago

Add @bufbuild/protocompile to the MANUAL.md.

When writing code using the reflection API, getting good test coverage can be challenging. It's easy enough to generate code (which includes descriptors) or build descriptors with buf build, but co-locating Protobuf source with a test gives better confidence.

With the compileMessage function, you can compile inline Protobuf source to a message descriptor:

import { compileMessage } from "@bufbuild/protocompile";
import { redact } from "./redact.js";

describe("redact", () => {
  it("should redact string field", () => {
    const schema = compileMessage(`
      syntax = "proto3";
      message Example {
        string foo = 1 [ debug_redact = true ];
      }
    `);
    const message: Message & Record<string, unknown> = create(schema, {
      foo: "abc",
    });
    redact(message);
    expect(message.foo).toBe("");
  });
});

The package also exports functions to compile Protobuf descriptors for all other types, such as enumerations and services.

Under the hood, the functions shell out to the buf build command. You need @bufbuild/buf as a peer dependency to use them.

Note that the functions return anonymous descriptors. They are functionally identical to generated descriptors, but do not have generated type information attached.