@bernierllc/neverhub-adapter
v0.1.4
Published
Standardized adapter for integrating BernierLLC packages with NeverHub service discovery and event bus system
Downloads
1,659
Readme
@bernierllc/neverhub-adapter
Standardized adapter for integrating BernierLLC packages with NeverHub service discovery and event bus system.
Installation
npm install @bernierllc/neverhub-adapterFeatures
- Auto-Detection: Automatically detects if NeverHub is available in the environment
- Service Registration: Register package capabilities and dependencies with service discovery
- Event System: Publish/subscribe to events across packages in the ecosystem
- Service Discovery: Find and use other packages dynamically
- Health Monitoring: Report package health status and metrics
- Configuration: Load configuration and connection strings from NeverHub
- Graceful Degradation: Full functionality when NeverHub is unavailable
Quick Start
Basic Integration
import { NeverHubAdapter } from '@bernierllc/neverhub-adapter';
export class MyPackage {
private neverhub?: NeverHubAdapter;
async initialize(): Promise<void> {
// Auto-detect NeverHub
if (await NeverHubAdapter.detect()) {
this.neverhub = new NeverHubAdapter();
// Register with NeverHub
await this.neverhub.register({
type: 'my-package',
name: '@bernierllc/my-package',
version: '1.0.0',
capabilities: [
{ type: 'data', name: 'processing', version: '1.0.0' }
],
dependencies: ['logging']
});
}
await this.initializeCore();
}
}Event Publishing
// Safe event publishing - works even when NeverHub is unavailable
await this.neverhub?.publishEvent({
type: 'data.processed',
data: { recordId: '123', status: 'success' },
source: 'my-package'
});Event Subscription
// Subscribe to events with pattern matching
const unsubscribe = await this.neverhub?.subscribe('user.*', async (event) => {
console.log('User event received:', event);
});
// Clean up subscription when done
// unsubscribe?.();Service Discovery
// Find services by capability
const services = await this.neverhub?.discover({
capabilityTypes: ['logging']
});
if (services?.available.includes('structured-logging')) {
const logger = await this.neverhub.getService('structured-logging');
// Use the logger service
}Configuration Management
// Load configuration with defaults
const config = await this.neverhub?.getConfiguration('my-package', {
logging: { level: 'info' },
retries: 3
});
// Get connection strings
const dbConnection = await this.neverhub?.getConnectionString('my-package', 'database');Health Checks and Metrics
// Register health check
await this.neverhub?.registerHealthCheck('my-package', async () => {
return {
healthy: this.isOperational(),
message: 'Service is running normally',
metadata: { uptime: process.uptime() }
};
});
// Report metrics
await this.neverhub?.reportMetric('my-package', {
name: 'requests_total',
value: 100,
type: MetricType.COUNTER,
labels: { status: 'success' }
});API Reference
NeverHubAdapter Class
Static Methods
static detect(): Promise<boolean>- Detect if NeverHub is available
Instance Methods
Core Methods
initialize(): Promise<boolean>- Initialize the adapterregister(registration: PackageRegistration): Promise<void>- Register packagegetState(): AdapterState- Get current adapter stateisAvailable(): boolean- Check if NeverHub is availableisInitialized(): boolean- Check if adapter is initializedisRegistered(): boolean- Check if package is registered
Event Methods
publishEvent(event: Event): Promise<void>- Publish eventsubscribe(pattern: string, handler: EventHandler): Promise<() => void>- Subscribe to events
Discovery Methods
discover(criteria: DiscoveryCriteria): Promise<ServiceDiscoveryResult>- Discover servicesgetService(serviceName: string): Promise<any>- Get specific service
Configuration Methods
getConfiguration(packageName: string, defaults?: any): Promise<any>- Get configurationgetConnectionString(packageName: string, connectionName: string): Promise<string | null>- Get connection stringgetEnvironmentConfiguration(packageName: string, environment: string, defaults?: any): Promise<any>- Get environment-specific configuration
Health Methods
registerHealthCheck(packageName: string, checkFn: HealthCheckFunction): Promise<void>- Register health checkreportMetric(packageName: string, metric: Metric): Promise<void>- Report metric
Configuration
The adapter can be configured with environment variables:
NEVERHUB_API_URL- Custom NeverHub API URLNEVERHUB_ENDPOINT- Alternative endpoint specificationNEVERHUB_HOST- Host-only specification (protocol will be added)
Or programmatically:
const adapter = new NeverHubAdapter({
apiUrl: 'http://custom.neverhub.com:3001',
timeout: 5000,
maxRetries: 5,
debug: true
});Types
PackageRegistration
interface PackageRegistration {
type: string; // Package type identifier
name: string; // Full package name including scope
version: string; // Semantic version
dependencies: string[]; // List of dependency package names
capabilities: Capability[]; // List of capabilities provided
discoveryEnabled?: boolean; // Whether discoverable by others
discoverySubscriptions?: DiscoverySubscription[];
webhookUrl?: string; // Optional webhook URL
}Event
interface Event {
type: string; // Event type identifier
data: any; // Event payload
source?: string; // Source package identifier
timestamp?: string; // Event timestamp (ISO string)
metadata?: Record<string, any>; // Additional metadata
}Capability
interface Capability {
type: string; // Capability type (e.g., 'data', 'logging')
name: string; // Specific capability name
version: string; // Version of the capability interface
metadata?: Record<string, any>; // Additional metadata
}Environment Detection
The adapter automatically detects NeverHub availability through:
- Environment Variables: Checks for
NEVERHUB_API_URL,NEVERHUB_ENDPOINT, orNEVERHUB_HOST - Default Endpoints: Tests
http://localhost:3001andhttp://neverhub:3001 - Health Check: Validates API availability at
/api/health
Graceful Degradation
When NeverHub is not available, the adapter:
- Returns default values for configuration requests
- Silently ignores event publishing attempts
- Returns empty results for service discovery
- Logs warnings for debugging but never throws errors
- Maintains full package functionality
Error Handling
The adapter is designed with graceful degradation as a core principle:
- Never throws errors due to NeverHub unavailability
- Logs warnings for debugging when operations fail
- Returns sensible defaults when NeverHub data is unavailable
- Maintains package functionality regardless of NeverHub state
Advanced Usage
Custom Configuration
const adapter = new NeverHubAdapter({
apiUrl: 'http://my-neverhub.internal:3001',
timeout: 10000,
maxRetries: 5,
debug: process.env.NODE_ENV === 'development'
});Environment-Specific Configuration
const config = await adapter.getEnvironmentConfiguration(
'my-package',
process.env.NODE_ENV || 'development',
{ logging: { level: 'info' } }
);Event Pattern Matching
The event system supports flexible pattern matching:
*- Matches any event typeuser.*- Matches all user-related eventsservice.*.created- Matches creation events from any serviceexact.match- Matches only the exact event type
Utility Functions
For advanced use cases, utility functions are exported:
import {
detectNeverHub,
publishEvent,
discoverServices,
validatePackageRegistration
} from '@bernierllc/neverhub-adapter';See Also
This package integrates with other BernierLLC packages:
- @bernierllc/retry-policy - Used internally for retry logic
- @bernierllc/logging-core - Can be discovered via service discovery
License
Copyright (c) 2025 Bernier LLC. All rights reserved.
