BSB Node.js Type Definitions
    Preparing search index...

    Class BSBService<ReferencedConfig, TEventSchemas>Abstract

    Base class for implementing a service plugin.

    v9 Breaking Change: PLUGIN_CLIENT is now auto-generated from Config.metadata. You must provide a static Config property pointing to your Config class.

    Lifecycle:

    • constructor(config)
    • init(trace): async initialization and event registration
    • run(trace): start processing
    • dispose(): cleanup resources
    • 
      
    • export const Config = createConfigSchema(
    • { name: 'service-demo', description: 'Demo Service' },
    • ConfigSchema
    • );
    • export class Plugin extends BSBService<typeof Config, typeof EventSchemas> {
    • static Config = Config; // Required for auto-generation
    • // PLUGIN_CLIENT is auto-generated from Config.metadata
    • }
    • 
      

    Type Parameters

    Index

    Constructors

    Properties

    Config: any

    Static reference to the Config class created with createConfigSchema(). Required for auto-generating PLUGIN_CLIENT from metadata.

    v9: This must be set on your plugin class for PLUGIN_CLIENT auto-generation to work.

    EventSchemas: BSBEventSchemas

    Static reference to EventSchemas created with createEventSchemas(). Required for schema export functionality.

    v9: Set this on your plugin class to enable schema export.

    initBeforePlugins?: string[]
    initAfterPlugins?: string[]
    runBeforePlugins?: string[]
    runAfterPlugins?: string[]

    Schema-first event API for this plugin with automatic validation

    appId: string = "tbd"

    The unique app id of the app that is running

    mode: DEBUG_MODE = "development"

    The mode the app is running in

    production (production mode - no debug)
    
    production-debug (production mode - debug)
    
    development (development mode - debug)
    
    cwd: string

    The current working directory of the app

    packageCwd: string

    The current working directory of the plugin

    pluginCwd: string

    The current working directory of the service

    pluginName: string

    The name of the plugin This is also the mapped name, or the name defined in the config rather than it's original defined name

    region?: string

    The deployment region for resource context

    config: ConfigPropertyTypeSafe<ReferencedConfig extends null ? null : any>

    The config of the plugin

    Accessors

    • get PLUGIN_CLIENT(): BSBServiceClientDefinition

      Auto-generated from Config.metadata. Do not set this manually - it will be ignored and replaced with auto-generated value.

      v9 Breaking Change: This is now a getter that derives from Config.metadata. If you have a manual PLUGIN_CLIENT property, remove it and set static Config instead.

      Returns BSBServiceClientDefinition

    Methods

    • Export event schemas to JSON format for cross-language client generation.

      v9: Call this static method to generate JSON schemas for your plugin's events. The generated JSON can be consumed by code generators in other languages to create type-safe clients.

      Returns EventSchemaExport

      EventSchemaExport object with plugin metadata and event definitions

      // In your plugin class:
      export class Plugin extends BSBService<typeof Config, typeof EventSchemas> {
      static Config = Config;
      static EventSchemas = EventSchemas;
      }

      // Export schemas (typically in build script):
      const schemas = Plugin.exportSchemas();
      fs.writeFileSync('schemas.json', JSON.stringify(schemas, null, 2));
    • Create an Observable from a DTrace with plugin's resource context

      This method wraps a DTrace object in an Observable that provides:

      • Automatic trace context for logging
      • Resource context (service name, version, region, etc.)
      • Immutable attribute propagation
      • Child span creation

      Parameters

      • trace: DTrace

        DTrace object

      • Optionalattributes: Record<string, string | number | boolean>

        Optional initial attributes

      • Optionalspan: Trace

        Optional Trace/Span object for lifecycle management (enables end() to work)

      Returns Observable

      Observable wrapping the trace

      // Create observable from DTrace
      const obs = this.createObservable(trace, { "user.id": "123" });
      obs.log.info("Processing request");

      // Create observable from Trace with span lifecycle
      const trace = this.__internalObservable.createTrace("http.request");
      const obs = this.createObservable(trace.trace, {}, trace);
      // ... do work ...
      obs.end(); // Properly ends the span
    • Create a new trace for distributed tracing

      Creates a new root trace with the given name and attributes. This is useful for creating new traces in contexts like HTTP handlers where you want to start a new trace for each request.

      Parameters

      • name: string

        Name for the trace (e.g., "http.request", "background.job")

      • Optionalattributes: Record<string, string | number | boolean>

        Optional initial attributes

      Returns Observable

      Observable with a new trace and span that can be ended

      // In an HTTP handler
      async handleRequest(request: Request) {
      const obs = this.createTrace("http.request", {
      "http.method": request.method,
      "http.url": request.url
      });

      try {
      await this.processRequest(obs, request);
      obs.end({ "http.status": 200 });
      } catch (error) {
      obs.error(error);
      obs.end({ "http.status": 500 });
      }
      }
    • Create a self-client for calling this service's own events.

      Use this when you need to call your own event handlers from within the service (e.g., HTTP handler calling the service's event-based API). This makes self-invocation explicit in the code and avoids confusion about event flow.

      Call this method in the constructor and store the result if you need self-invocation. Only create it if needed to minimize startup overhead.

      The self-client uses the runtime mapped plugin name from the instantiated plugin, avoiding dependency on compile-time metadata or config. It's registered in the _clients array and handled normally by the BSB lifecycle.

      Returns BSBSelfServiceClient<BSBService<ReferencedConfig, TEventSchemas>, TEventSchemas>

      Self-client with events property for calling own events

      export class Plugin extends BSBService<typeof Config, typeof EventSchemas> {
      private self;

      constructor(config: BSBServiceConstructor<typeof Config, typeof EventSchemas>) {
      super({ ...config, eventSchemas: EventSchemas });

      // Create self-client for HTTP handler to call own events
      this.self = this.createSelf();
      }

      async handleHttpRequest(obs: Observable, body: any) {
      // Explicitly call own event handler
      const result = await this.self.events.emitEventAndReturn('todo.create', obs, body);
      return { status: 201, data: result };
      }
      }
    • Dispose Optional function to be called when the plugin is being disposed

      Returns void

      dispose?(): void; //to not use it
      
      dispose() { your code here };
      
    • Init Optional function to be called when the plugin is being initialized Can be sync or async

      Parameters

      • obs: Observable

        Observable context with logging, metrics, and trace information

      Returns void | Promise<void>

      v9 BREAKING CHANGE: Now requires Observable instead of DTrace. Observable provides unified access to logging, metrics, and tracing with automatic context propagation.

      async init(obs: Observable) {
      obs.log.info("Initializing plugin");
      // Set attributes for all child operations
      const withVersion = obs.setAttribute("plugin.version", "1.0.0");
      }
    • Run Optional function to be called when the plugin is being run Can be sync or async

      Parameters

      • obs: Observable

        Observable context with logging, metrics, and trace information

      Returns void | Promise<void>

      v9 BREAKING CHANGE: Now requires Observable instead of DTrace. Observable provides unified access to logging, metrics, and tracing with automatic context propagation.

      async run(obs: Observable) {
      obs.log.info("Running plugin");
      // Create child span for work
      const workObs = obs.startSpan("do-work");
      // ... do work ...
      workObs.end();
      }