### Install protobuf.js
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Install the main protobuf.js package using npm.
```sh
npm install protobufjs
```
--------------------------------
### Install Dependencies and Build Project
Source: https://github.com/protobufjs/protobuf.js/blob/master/CONTRIBUTING.md
Installs project dependencies, CLI dependencies, builds the project, and runs tests. Use this to set up your local development environment.
```sh
npm install
npm --prefix cli install
npm run build
npm test
```
--------------------------------
### Clone and Install Dependencies
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Clone the Protobuf.js repository and install its npm dependencies, including those for the CLI.
```sh
git clone https://github.com/protobufjs/protobuf.js
cd protobuf.js
npm install
npm --prefix cli install
```
--------------------------------
### pbjs Usage Example
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Illustrates the basic usage of the pbjs command, which takes proto or JSON files as input and generates code or bundles.
```sh
usage: pbjs [options] file1.proto file2.json ... (or pipe) other | pbjs [options] -
```
--------------------------------
### Encode and Decode Example
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Demonstrates how to encode a message to binary and decode it back, with optional verification and creation steps.
```APIDOC
## Encode and Decode Example
### Description
This example shows the typical workflow for encoding a message to binary format and then decoding it back into a message object. It includes optional steps for verifying the payload shape before encoding and creating a message instance.
### Code
```ts
const payload = { awesomeField: "hello" };
// Optionally verify if the payload is of uncertain shape
const err = AwesomeMessage.verify(payload);
if (err) throw Error(err);
// Optionally create a message instance from already valid data
const message = AwesomeMessage.create(payload);
const encoded = AwesomeMessage.encode(message).finish();
const decoded = AwesomeMessage.decode(encoded);
```
### Usage Notes
- `encode` expects a message instance or equivalent plain object. Use `verify` for plain objects with uncertain shapes.
- `create` can be used to instantiate a message from valid data.
- Unknown fields are preserved by default and can be managed via `message.$unknowns` or reader options.
```
--------------------------------
### Install protobufjs-cli
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Installs the protobufjs-cli package as a development dependency.
```sh
npm install --save-dev protobufjs-cli
```
--------------------------------
### Local Benchmark Execution Command
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Instructions to run the protobuf.js benchmarks locally. This involves installing dependencies and executing the benchmark script.
```sh
npm --prefix bench install
npm run bench
```
--------------------------------
### pbts Usage Example
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Illustrates the basic usage of the pbts command, which takes JavaScript files as input and generates TypeScript definitions.
```sh
usage: pbts [options] file1.js file2.js ... (or) other | pbts [options] -
```
--------------------------------
### Load Schema Example
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Load a .proto file and look up a message type using protobuf.js. Field names are converted to camelCase by default.
```ts
const protobuf = require("protobufjs");
const root = await protobuf.load("awesome.proto");
const AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage");
```
--------------------------------
### Convert Plain Objects Example
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Illustrates converting between message instances and plain JavaScript objects using `fromObject` and `toObject`, with configurable options.
```APIDOC
## Convert Plain Objects Example
### Description
This example demonstrates how to convert between Protobuf.js message instances and plain JavaScript objects using `fromObject` and `toObject`. It highlights the use of `ConversionOptions` to customize the output format.
### Code
```ts
const message = AwesomeMessage.fromObject({ awesomeField: 42 });
const object = AwesomeMessage.toObject(message, {
longs: String,
enums: String,
bytes: String
});
```
### Conversion Options
Common `ConversionOptions` include:
| Option | Effect |
|-------------|----------------------------------------------|
| `longs: BigInt` | Converts 64-bit values to bigint values |
| `longs: String` | Converts 64-bit values to decimal strings |
| `longs: Number` | Converts 64-bit values to JS numbers (may lose precision) |
| `enums: String` | Converts enum values to names |
| `bytes: String` | Converts bytes to base64 strings |
| `defaults: true` | Includes default values for unset fields |
| `arrays: true` | Includes empty arrays for repeated fields |
| `objects: true` | Includes empty objects for map fields |
| `oneofs: true` | Includes virtual oneof discriminator properties |
```
--------------------------------
### Run Tests
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Execute the test suite for Protobuf.js using npm.
```sh
npm test
```
--------------------------------
### Programmatic Usage of pbjs
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Demonstrates how to use the pbjs main function programmatically by passing command line arguments and a callback.
```js
const { pbjs, pbts } = require("protobufjs-cli");
pbjs.main(["--target", "json-module", "path/to/myproto.proto"], function(err, output) {
if (err) throw err;
// do something with output
});
```
--------------------------------
### Show pbjs Help
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Displays the help information for the pbjs command, detailing its options and usage for translating file formats and generating static code.
```sh
npx pbjs --help
```
--------------------------------
### Show pbts Help
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Displays the help information for the pbts command, detailing its options and usage for generating TypeScript definitions from JavaScript files.
```sh
npx pbts --help
```
--------------------------------
### Browser Builds
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Include protobuf.js in your HTML for browser usage. Choose the build that matches your runtime variant.
```html
```
--------------------------------
### Benchmark Results for Protobuf.js
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Performance benchmarks comparing protobuf.js (reflect and static) against JSON encode/decode, protoc-gen-js, and protoc-gen-es. Results are indicative and depend on hardware and Node.js version.
```text
benchmarking encode performance ...
protobuf.js reflect x 2,430,103 ops/sec ±0.62% (95 runs sampled)
protobuf.js static x 2,390,407 ops/sec ±0.42% (96 runs sampled)
JSON encode x 2,155,918 ops/sec ±0.63% (92 runs sampled)
protoc-gen-js x 995,429 ops/sec ±0.18% (98 runs sampled)
protoc-gen-es x 403,334 ops/sec ±0.14% (96 runs sampled)
protobuf.js reflect was fastest
protobuf.js static was 1.4% ops/sec slower (factor 1.0)
JSON encode was 11.3% ops/sec slower (factor 1.1)
protoc-gen-js was 58.9% ops/sec slower (factor 2.4)
protoc-gen-es was 83.3% ops/sec slower (factor 6.0)
benchmarking decode performance ...
protobuf.js reflect x 6,440,387 ops/sec ±0.25% (97 runs sampled)
protobuf.js static x 6,463,283 ops/sec ±0.27% (101 runs sampled)
JSON decode x 1,409,923 ops/sec ±0.11% (97 runs sampled)
protoc-gen-js x 947,647 ops/sec ±0.15% (99 runs sampled)
protoc-gen-es x 731,819 ops/sec ±0.28% (98 runs sampled)
protobuf.js static was fastest
protobuf.js reflect was 0.3% ops/sec slower (factor 1.0)
JSON decode was 78.2% ops/sec slower (factor 4.6)
protoc-gen-js was 85.3% ops/sec slower (factor 6.8)
protoc-gen-es was 88.7% ops/sec slower (factor 8.8)
benchmarking round-trip performance ...
protobuf.js reflect x 1,310,677 ops/sec ±0.21% (97 runs sampled)
protobuf.js static x 1,310,926 ops/sec ±0.26% (101 runs sampled)
JSON encode/decode x 741,714 ops/sec ±0.24% (99 runs sampled)
protoc-gen-js x 472,844 ops/sec ±0.09% (96 runs sampled)
protoc-gen-es x 254,044 ops/sec ±0.05% (101 runs sampled)
protobuf.js reflect was fastest
protobuf.js static was 0.0% ops/sec slower (factor 1.0)
JSON encode/decode was 43.4% ops/sec slower (factor 1.8)
protoc-gen-js was 63.9% ops/sec slower (factor 2.8)
protoc-gen-es was 80.6% ops/sec slower (factor 5.2)
```
--------------------------------
### Generate Reflection Bundle
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Use `pbjs` to generate a JSON bundle of schemas for runtime reflection. This is useful for bundling multiple proto files.
```sh
npx pbjs -t json -o awesome.json awesome1.proto awesome2.proto ...
```
--------------------------------
### Build Development and Production Versions
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Build the development and production versions of Protobuf.js, including source maps, in the 'dist/' directory.
```sh
npm run build
```
--------------------------------
### Convert Root to DescriptorSet and Back
Source: https://github.com/protobufjs/protobuf.js/blob/master/ext/README.md
Use the descriptor extension to convert an existing protobuf.js root to a FileDescriptorSet message and encode it into a buffer. This buffer can then be decoded back into a protobuf.js root.
```javascript
import protobuf from "protobufjs";
import descriptor from "protobufjs/ext/descriptor.js";
// Convert an existing root to a FileDescriptorSet message.
const root = protobuf.Root.fromJSON(bundle);
const set = root.toDescriptor("proto2");
// Encode descriptor buffers.
const buffer = descriptor.FileDescriptorSet.encode(set).finish();
// Convert a FileDescriptorSet message or buffer back to a root.
const decodedRoot = protobuf.Root.fromDescriptor(buffer);
```
--------------------------------
### Use Reflection Bundle
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Load a JSON bundle into a protobuf.js root object for runtime reflection. This allows looking up types dynamically.
```ts
const bundle = require("./awesome.json");
const root = protobuf.Root.fromJSON(bundle);
const AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage");
```
--------------------------------
### Generate Static Code
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Generates static JavaScript code and a matching declaration file from protobuf definitions.
```sh
npx pbjs -t static-module -w commonjs -o compiled.js --dts file1.proto file2.proto
```
--------------------------------
### Custom RPC Implementation for Service Clients
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Implement a custom RPC handler to connect protobuf.js service clients to any transport. The `myRpcImpl` function receives method details and request data, and must call back with response data or an error.
```javascript
function myRpcImpl(method, requestData, callback) {
// method.name
// method.path
// method.requestStream?
// method.responseStream?
performRequest(requestData, function(err, responseData) {
callback(err, responseData);
});
}
const myService = MyService.create(myRpcImpl/*, requestDelimited?, responseDelimited? */);
```
--------------------------------
### Generate Reflection Bundle
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Generates a reflection bundle and a matching declaration file. Note that declarations for JSON modules describe reflection-backed message types.
```sh
npx pbjs -t json-module -w commonjs -o bundle.js --dts file1.proto file2.proto
```
--------------------------------
### Encode and Decode a Protobuf Message
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Demonstrates the basic workflow for encoding a message to binary and decoding it back. Use `verify` for uncertain payloads and `create` for pre-validated data.
```typescript
const payload = { awesomeField: "hello" };
// Optionally verify if the payload is of uncertain shape
const err = AwesomeMessage.verify(payload);
if (err) throw Error(err);
// Optionally create a message instance from already valid data
const message = AwesomeMessage.create(payload);
const encoded = AwesomeMessage.encode(message).finish();
const decoded = AwesomeMessage.decode(encoded);
```
--------------------------------
### Generate Static Module
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Use `pbjs` to generate a static JavaScript module and TypeScript declarations from a proto file. This is suitable for ESM environments.
```sh
npx pbjs -t static-module -w esm -o awesome.js --dts awesome.proto
```
--------------------------------
### Convert Plain Objects to Protobuf Messages
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Shows how to convert a plain JavaScript object into a Protobuf message instance using `fromObject` and then convert it back to a configurable plain object using `toObject`.
```typescript
const message = AwesomeMessage.fromObject({ awesomeField: 42 });
const object = AwesomeMessage.toObject(message, {
longs: String,
enums: String,
bytes: String
});
```
--------------------------------
### Generate JSON Module
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Use `pbjs` to generate a JSON module, which exports the reflection root. Supports various module wrappers like ESM.
```sh
npx pbjs -t json-module -w esm -o awesome.js --dts awesome.proto
```
--------------------------------
### Use Generated Static Module
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Import and create a message instance from a statically generated JavaScript module.
```ts
import { awesomepackage } from "./awesome.js";
const message = awesomepackage.AwesomeMessage.create({ awesomeField: "hello" });
```
--------------------------------
### Use JSON Module
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Import and access message types from a JSON module. Note that message instances should be created using `.create()`.
```ts
import { awesomepackage } from "./awesome.js";
const AwesomeMessage = awesomepackage.AwesomeMessage;
```
--------------------------------
### Protoc Plugin for Protobuf.js
Source: https://github.com/protobufjs/protobuf.js/blob/master/cli/README.md
Uses the protoc-gen-pbjs plugin to generate JavaScript modules and declaration files alongside protoc compilation.
```sh
protoc \
--plugin=protoc-gen-pbjs=./node_modules/.bin/protoc-gen-pbjs \
--pbjs_out=gen \
--pbjs_opt=dts \
proto/awesome.proto
```
--------------------------------
### Programmatic Schema Construction
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Construct a protobuf.js schema programmatically using reflection. This allows defining types and fields in code.
```ts
const AwesomeMessage = new protobuf.Type("AwesomeMessage")
.add(new protobuf.Field("awesomeField", 1, "string"));
const root = new protobuf.Root()
.define("awesomepackage")
.add(AwesomeMessage);
```
--------------------------------
### Message API Methods
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Lists and describes the core methods available on Protobuf.js message types for binary I/O and object manipulation.
```APIDOC
## Message API Methods
### Description
Message types in Protobuf.js provide a set of focused methods for validation, conversion, and binary input/output operations.
### Methods
* **encode**(message: `Message | object`, writer?: `Writer`): `Writer`
Encodes a message or equivalent plain object. Call `.finish()` on the returned writer to obtain a buffer.
* **encodeDelimited**(message: `Message | object`, writer?: `Writer`): `Writer`
Encodes a length-delimited message.
* **decode**(reader: `Reader | Uint8Array`): `Message`
Decodes a message from protobuf binary data.
* **decodeDelimited**(reader: `Reader | Uint8Array`): `Message`
Decodes a length-delimited message.
* **create**(properties?: `object`): `Message`
Creates a message instance from already valid data.
* **verify**(object: `object`): `null | string`
Checks whether a plain object can be encoded as-is. Returns `null` if valid, otherwise an error message.
* **fromObject**(object: `object`): `Message`
Converts broader JavaScript input into a message instance.
* **toObject**(message: `Message`, options?: `ConversionOptions`): `object`
Converts a message instance to a configurable plain JavaScript object.
* **message#toJSON**(): `object`
Converts a message instance to JSON-compatible output using default conversion options.
### Notes
- Length-delimited methods are useful for streams and framed protocols.
- Decoding proto2 data with missing required fields throws `protobuf.util.ProtocolError`.
```
--------------------------------
### TypeScript Oneof Handling
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Demonstrates how TypeScript declarations generated by protobuf.js handle oneof fields, narrowing types for specific values.
```ts
const profile = Profile.create({
contact: "email",
email: "hello@example.com"
});
if (profile.contact === "email") {
profile.email; // string
}
```
```ts
const decoded = Profile.decode(bytes);
if (decoded.contact === "phone") {
decoded.phone; // string
}
```
--------------------------------
### Parse and Stringify Text Format Messages
Source: https://github.com/protobufjs/protobuf.js/blob/master/ext/README.md
The textformat extension allows parsing strings into protobuf.js message objects and converting message objects back into text format strings. This extension requires reflection metadata.
```javascript
import protobuf from "protobufjs";
import "protobufjs/ext/textformat.js";
const root = protobuf.Root.fromJSON(bundle);
const MyType = root.lookupType("MyType");
const message = MyType.fromText("value: 1");
const text = MyType.toText(message);
```
--------------------------------
### Regenerate Test Fixtures
Source: https://github.com/protobufjs/protobuf.js/blob/master/CONTRIBUTING.md
Regenerates test fixtures after making changes that might affect them. This command should be run when the build process indicates that fixtures need updating.
```sh
npm run build:tests
```
--------------------------------
### Custom Message Class Integration
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Assign a custom class as the constructor for a reflected type. This allows adding custom methods to message instances.
```ts
class AwesomeMessage extends protobuf.Message {
awesomeField = "";
constructor(properties?: protobuf.Properties) {
super(properties);
// ...
}
customInstanceMethod() {
return this.awesomeField.toLowerCase();
}
}
root.lookupType("awesomepackage.AwesomeMessage").ctor = AwesomeMessage;
const decoded = AwesomeMessage.decode(bytes);
decoded.customInstanceMethod(); // string
```
--------------------------------
### Conditional Node.js Tests
Source: https://github.com/protobufjs/protobuf.js/blob/master/tests/README.md
Use this pattern to include tests that rely on Node.js-specific features. This ensures these tests are only executed in a Node.js environment.
```javascript
if (protobuf.util.isNode) {
// node-specific tests
}
```
--------------------------------
### TypeScript Plain Object Shape for Oneof
Source: https://github.com/protobufjs/protobuf.js/blob/master/README.md
Shows how to use a scoped type for plain objects that conform to the oneof structure, ensuring type safety.
```ts
const object: Profile.$Shape = {
contact: "email",
email: "hello@example.com"
};
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.