CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-protobufjs

Protocol Buffers for JavaScript with TypeScript support, providing pure JavaScript implementation for serializing and deserializing structured data using Google's Protocol Buffer format.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

reflection.mddocs/

Reflection System

Complete runtime reflection API for working with protobuf types, services, and schemas. Provides programmatic access to all protobuf constructs with full type information and manipulation capabilities.

Capabilities

Root Namespace

Root namespace containing all loaded protobuf definitions, serving as the entry point for type lookup and schema management.

class Root extends Namespace {
  /**
   * Constructs a new root namespace
   * @param options - Root options
   */
  constructor(options?: object);
  
  /**
   * Creates root from JSON descriptor
   * @param json - JSON descriptor object
   * @param root - Optional root to populate
   * @returns Root instance
   */
  static fromJSON(json: object, root?: Root): Root;
  
  /**
   * Deferred fields for cross-references
   */
  deferred: Field[];
  
  /**
   * Loads proto files into this root
   * @param filename - File path(s) to load
   * @param callback - Callback receiving error and root
   * @returns This root instance
   */
  load(filename: string | string[], callback: LoadCallback): Root;
  
  /**
   * Synchronously loads proto files into this root
   * @param filename - File path(s) to load  
   * @returns This root instance
   */
  loadSync(filename: string | string[]): Root;
}

Usage Examples:

const protobuf = require("protobufjs");

// Create new root
const root = new protobuf.Root();

// Load definitions
root.load("schema.proto", function(err, loadedRoot) {
    // Look up message types
    const UserMessage = root.lookupType("package.User");
    const UserService = root.lookupService("package.UserService");
});

// Create from JSON descriptor
const jsonDescriptor = { /* JSON schema */ };
const root = protobuf.Root.fromJSON(jsonDescriptor);

Type Reflection

Message type reflection providing complete schema information and instance operations.

class Type extends Namespace {
  /**
   * Constructs a new message type
   * @param name - Type name
   * @param options - Type options
   */
  constructor(name: string, options?: object);
  
  /**
   * Creates type from JSON descriptor
   * @param name - Type name
   * @param json - JSON descriptor
   * @returns Type instance
   */
  static fromJSON(name: string, json: object): Type;
  
  /**
   * Field definitions by field id
   */
  fields: { [id: number]: Field };
  
  /**
   * OneOf definitions by name
   */
  oneofs: { [name: string]: OneOf };
  
  /**
   * Extension field ranges
   */
  extensions: number[][];
  
  /**
   * Reserved field ids and names
   */
  reserved: Array<number[] | string[]>;
  
  /**
   * Array of all fields
   */
  fieldsArray: Field[];
  
  /**
   * Array of all oneofs
   */
  oneofsArray: OneOf[];
  
  /**
   * Message constructor function
   */
  ctor: Message;
  
  /**
   * Creates message instance from properties
   * @param properties - Property values
   * @returns Message instance
   */
  create(properties?: object): Message;
  
  /**
   * Encodes message to writer
   * @param message - Message instance or plain object
   * @param writer - Writer to encode to
   * @returns Writer instance
   */
  encode(message: Message | object, writer?: Writer): Writer;
  
  /**
   * Decodes message from reader
   * @param reader - Reader or buffer to decode from
   * @param length - Message length if known
   * @returns Decoded message instance
   */
  decode(reader: Reader | Uint8Array, length?: number): Message;
  
  /**
   * Verifies message properties
   * @param message - Message properties to verify
   * @returns Error message or null if valid
   */
  verify(message: object): string | null;
  
  /**
   * Creates message from plain object
   * @param object - Plain object with message data
   * @returns Message instance
   */
  fromObject(object: object): Message;
  
  /**
   * Converts message to plain object
   * @param message - Message instance
   * @param options - Conversion options
   * @returns Plain object representation
   */
  toObject(message: Message, options?: IConversionOptions): object;
}

Usage Examples:

// Get type from root
const MessageType = root.lookupType("package.MessageType");

// Inspect type properties
console.log("Fields:", MessageType.fieldsArray.map(f => f.name));
console.log("OneOfs:", MessageType.oneofsArray.map(o => o.name));

// Create and manipulate messages
const message = MessageType.create({ field1: "value", field2: 42 });
const encoded = MessageType.encode(message).finish();
const decoded = MessageType.decode(encoded);

Field Reflection

Field definitions within message types, including detailed type information and options.

class Field extends FieldBase {
  /**
   * Constructs a new message field
   * @param name - Field name
   * @param id - Field id
   * @param type - Field type
   * @param rule - Field rule (optional, required, repeated)
   * @param extend - Extended type if extension field
   * @param options - Field options
   */
  constructor(name: string, id: number, type: string, rule?: string, extend?: string, options?: object);
  
  /**
   * Field rule (optional, required, repeated)
   */
  rule: string;
  
  /**
   * Field type name
   */
  type: string;
  
  /**
   * Unique field id
   */
  id: number;
  
  /**
   * Whether field is a map
   */
  map: boolean;
  
  /**
   * Whether field is repeated
   */
  repeated: boolean;
  
  /**
   * Whether field is required
   */
  required: boolean;
  
  /**
   * Whether field is optional
   */
  optional: boolean;
  
  /**
   * OneOf this field belongs to
   */
  partOf: OneOf | null;
  
  /**
   * Default value for field type
   */
  typeDefault: any;
  
  /**
   * Explicit default value
   */
  defaultValue: any;
  
  /**
   * Resolved type reference
   */
  resolvedType: Type | Enum | null;
}

Usage Examples:

const MessageType = root.lookupType("package.Message");

// Inspect fields
MessageType.fieldsArray.forEach(field => {
    console.log(`Field: ${field.name} (${field.type}) id=${field.id}`);
    console.log(`  Rule: ${field.rule}`);
    console.log(`  Required: ${field.required}`);
    console.log(`  Default: ${field.defaultValue}`);
    
    if (field.resolvedType) {
        console.log(`  Resolved Type: ${field.resolvedType.name}`);
    }
});

Enum Reflection

Enumeration type reflection with value definitions and metadata.

class Enum extends ReflectionObject {
  /**
   * Constructs a new enum
   * @param name - Enum name
   * @param values - Enum values
   * @param options - Enum options
   */
  constructor(name: string, values?: object, options?: object);
  
  /**
   * Creates enum from JSON descriptor
   * @param name - Enum name
   * @param json - JSON descriptor
   * @returns Enum instance
   */
  static fromJSON(name: string, json: object): Enum;
  
  /**
   * Enum values by name
   */
  values: { [name: string]: number };
  
  /**
   * Enum values by id
   */
  valuesById: { [id: number]: string };
  
  /**
   * Value comments by name
   */
  comments: { [name: string]: string };
  
  /**
   * Adds enum value
   * @param name - Value name
   * @param id - Value id
   * @param comment - Optional comment
   * @returns This enum
   */
  add(name: string, id: number, comment?: string): Enum;
  
  /**
   * Removes enum value
   * @param name - Value name
   * @returns This enum
   */
  remove(name: string): Enum;
}

Usage Examples:

const StatusEnum = root.lookupEnum("package.Status");

// Inspect enum values
Object.keys(StatusEnum.values).forEach(name => {
    const id = StatusEnum.values[name];
    console.log(`${name} = ${id}`);
});

// Use enum values
const message = MessageType.create({
    status: StatusEnum.values.ACTIVE
});

Service Reflection

Service definition reflection for RPC services and their methods.

class Service extends Namespace {
  /**
   * Constructs a new service
   * @param name - Service name
   * @param options - Service options
   */
  constructor(name: string, options?: object);
  
  /**
   * Creates service from JSON descriptor
   * @param name - Service name
   * @param json - JSON descriptor
   * @returns Service instance
   */
  static fromJSON(name: string, json: object): Service;
  
  /**
   * Service methods by name
   */
  methods: { [name: string]: Method };
  
  /**
   * Array of all methods
   */
  methodsArray: Method[];
  
  /**
   * Creates RPC service instance
   * @param rpcImpl - RPC implementation
   * @param requestDelimited - Whether requests are delimited
   * @param responseDelimited - Whether responses are delimited
   * @returns Service instance
   */
  create(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): rpc.Service;
}

Method Reflection

RPC method definitions within services.

class Method extends ReflectionObject {
  /**
   * Constructs a new method
   * @param name - Method name
   * @param type - Method type (typically "rpc")
   * @param requestType - Request type name
   * @param responseType - Response type name
   * @param requestStream - Whether request is streaming
   * @param responseStream - Whether response is streaming
   * @param options - Method options
   */
  constructor(name: string, type: string, requestType: string, responseType: string, 
             requestStream?: boolean, responseStream?: boolean, options?: object);
  
  /**
   * Method type (typically "rpc")
   */
  type: string;
  
  /**
   * Request type name
   */
  requestType: string;
  
  /**
   * Response type name
   */
  responseType: string;
  
  /**
   * Whether request is streaming
   */
  requestStream: boolean;
  
  /**
   * Whether response is streaming
   */
  responseStream: boolean;
  
  /**
   * Resolved request type
   */
  resolvedRequestType: Type | null;
  
  /**
   * Resolved response type
   */
  resolvedResponseType: Type | null;
}

Namespace Operations

Base namespace operations for organizing and looking up protobuf definitions.

class Namespace extends NamespaceBase {
  /**
   * Nested objects array (fields, types, services, etc.)
   */
  nestedArray: ReflectionObject[];
  
  /**
   * Nested objects by name
   */
  nested: { [name: string]: ReflectionObject };
  
  /**
   * Adds nested object to namespace
   * @param object - Object to add
   * @returns This namespace
   */
  add(object: ReflectionObject): Namespace;
  
  /**
   * Removes nested object from namespace
   * @param object - Object to remove
   * @returns This namespace
   */
  remove(object: ReflectionObject): Namespace;
  
  /**
   * Gets nested object by name
   * @param name - Object name
   * @returns Found object or null
   */
  get(name: string): ReflectionObject | null;
  
  /**
   * Looks up nested object by path
   * @param path - Dot-separated path
   * @param filterTypes - Types to filter for
   * @param parentAlreadyChecked - Whether parent was already checked
   * @returns Found object or null
   */
  lookup(path: string | string[], filterTypes?: any, parentAlreadyChecked?: boolean): ReflectionObject | null;
  
  /**
   * Looks up message type by path
   * @param path - Dot-separated path
   * @returns Found type or null
   */
  lookupType(path: string | string[]): Type | null;
  
  /**
   * Looks up service by path
   * @param path - Dot-separated path
   * @returns Found service or null
   */
  lookupService(path: string | string[]): Service | null;
  
  /**
   * Looks up enum by path
   * @param path - Dot-separated path
   * @returns Found enum or null
   */
  lookupEnum(path: string | string[]): Enum | null;
  
  /**
   * Looks up type or enum by path
   * @param path - Dot-separated path
   * @returns Found type or enum or null
   */
  lookupTypeOrEnum(path: string | string[]): Type | Enum | null;
}

Usage Examples:

// Namespace traversal
const root = protobuf.Root.fromJSON(jsonDescriptor);

// Look up by absolute path
const UserType = root.lookupType("com.example.User");
const UserService = root.lookupService("com.example.UserService");
const StatusEnum = root.lookupEnum("com.example.Status");

// Iterate namespace contents
function printNamespace(ns, indent = "") {
    ns.nestedArray.forEach(obj => {
        console.log(indent + obj.name + " (" + obj.constructor.name + ")");
        if (obj instanceof protobuf.Namespace) {
            printNamespace(obj, indent + "  ");
        }
    });
}

printNamespace(root);

Types

interface LoadCallback {
  (error: Error | null, root?: Root): void;
}

interface IConversionOptions {
  longs?: typeof String | typeof Number | typeof Long;
  enums?: typeof String;
  bytes?: typeof Array | typeof String;
  defaults?: boolean;
  arrays?: boolean;
  objects?: boolean;
  oneofs?: boolean;
}

interface RPCImpl {
  (method: Method, requestData: Uint8Array, callback: RPCImplCallback): void;
}

interface RPCImplCallback {
  (error: Error | null, response?: Uint8Array): void;
}

Install with Tessl CLI

npx tessl i tessl/npm-protobufjs

docs

binary-io.md

cli-tools.md

code-generation.md

index.md

proto-loading.md

reflection.md

rpc-services.md

serialization.md

tile.json