npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bernierllc/connection-parser

v1.0.6

Published

Universal connection string parsing and configuration management for databases, APIs, and services

Readme

@bernierllc/connection-parser

Universal connection string parsing and configuration management for databases, APIs, and services.

Installation

npm install @bernierllc/connection-parser

Usage

import { parseConnection, parseDatabaseURL, redactCredentials } from '@bernierllc/connection-parser';

// Parse any connection string
const result = parseConnection('postgresql://user:pass@localhost:5432/mydb?ssl=true&pool_max=20');

console.log(result.config);
// {
//   protocol: 'postgresql',
//   host: 'localhost',
//   port: 5432,
//   database: 'mydb',
//   username: 'user',
//   password: 'pass',
//   ssl: true,
//   pooling: { max: 20 }
// }

// Parse database-specific URLs
const dbResult = parseDatabaseURL('mysql://root:secret@localhost:3306/testdb');

// Safely redact credentials for logging
const safeUrl = redactCredentials('postgresql://user:secret@localhost:5432/mydb');
console.log(safeUrl); // postgresql://****:****@localhost:5432/mydb

Features

  • Universal Parsing: Supports databases (PostgreSQL, MySQL, MongoDB, Redis), APIs (HTTP/HTTPS, WebSocket, GraphQL), and services (AMQP, Kafka, NATS, MQTT, LDAP)
  • Credential Security: Safe credential extraction and redaction for logging
  • Connection Pooling: Automatic extraction of pooling configuration from query parameters
  • Validation: Comprehensive validation of connection formats and parameters
  • Normalization: Consistent formatting and default value assignment
  • Type Safety: Full TypeScript support with strict typing
  • Performance: Optimized for high-throughput parsing (>10,000 connections/second)
  • NeverHub Integration: Optional integration with NeverHub service discovery

API Reference

Core Functions

parseConnection(connectionString, options?)

Parses any connection string and routes to the appropriate parser based on protocol.

const result = parseConnection('postgresql://localhost:5432/mydb', {
  validateFormat: true,
  extractCredentials: true,
  parsePooling: true
});

console.log(result.valid); // true
console.log(result.metadata.type); // 'database'

parseDatabaseURL(url, options?)

Specialized parser for database connection strings.

const result = parseDatabaseURL('postgresql://user:pass@localhost:5432/mydb?pool_min=5&pool_max=20');

console.log(result.config.pooling); // { min: 5, max: 20 }
console.log(result.metadata.hasPooling); // true

parseAPIEndpoint(endpoint, options?)

Specialized parser for API endpoints.

const result = parseAPIEndpoint('https://api.example.com/v1/users?timeout=30000');

console.log(result.config.path); // '/v1/users'
console.log(result.config.options.timeout); // 30000

parseServiceURL(url, options?)

Specialized parser for service URLs (message queues, directory services).

const result = parseServiceURL('amqp://guest:guest@localhost:5672/vhost?heartbeat=30');

console.log(result.config.database); // 'vhost' (virtual host)
console.log(result.config.options.heartbeat); // 30

Utility Functions

validateConnection(config)

Validates a connection configuration object.

import { validateConnection } from '@bernierllc/connection-parser';

const result = validateConnection({
  protocol: 'postgresql',
  host: 'localhost',
  port: 5432,
  database: 'mydb'
});

console.log(result.valid); // true
console.log(result.errors); // []

normalizeConnection(config)

Normalizes a connection configuration to standard format.

import { normalizeConnection } from '@bernierllc/connection-parser';

const normalized = normalizeConnection({
  protocol: 'PostgreSQL:', // Will be normalized to 'postgresql'
  host: 'MyHost.Example.Com', // Will be normalized to 'myhost.example.com'
  database: '  mydb  ' // Will be trimmed to 'mydb'
});

buildConnectionString(config)

Builds a connection string from a configuration object.

import { buildConnectionString } from '@bernierllc/connection-parser';

const connectionString = buildConnectionString({
  protocol: 'postgresql',
  username: 'user',
  password: 'pass',
  host: 'localhost',
  port: 5432,
  database: 'mydb',
  ssl: true,
  pooling: { min: 5, max: 20 }
});

// Result: postgresql://user:pass@localhost:5432/mydb?ssl=true&pool_min=5&pool_max=20

redactCredentials(connectionString)

Safely redacts credentials from connection strings for logging.

import { redactCredentials } from '@bernierllc/connection-parser';

const safe = redactCredentials('postgresql://user:secret@localhost:5432/mydb');
console.log(safe); // postgresql://****:****@localhost:5432/mydb

Parse Options

interface ParseOptions {
  validateFormat?: boolean;      // Validate connection format (default: true)
  extractCredentials?: boolean;  // Extract username/password (default: true)
  normalizePort?: boolean;      // Set default ports (default: true)
  parsePooling?: boolean;       // Extract pooling config (default: true)
  redactSecrets?: boolean;      // Redact credentials in raw field (default: false)
  allowedProtocols?: string[];  // Restrict allowed protocols
}

Connection Types

Database Connections

PostgreSQL

const result = parseDatabaseURL('postgresql://user:pass@localhost:5432/mydb?ssl=true');
const result2 = parseDatabaseURL('postgres://user:pass@localhost/mydb'); // Alternative format

MySQL

const result = parseDatabaseURL('mysql://root:password@localhost:3306/database?charset=utf8mb4');

MongoDB

const result = parseDatabaseURL('mongodb://user:pass@localhost:27017/mydb?authSource=admin');
const result2 = parseDatabaseURL('mongo://localhost/mydb'); // Alternative format

Redis

const result = parseDatabaseURL('redis://localhost:6379/0');
const result2 = parseDatabaseURL('rediss://localhost:6380/1'); // SSL Redis

API Endpoints

REST APIs

const result = parseAPIEndpoint('https://api.example.com/v1/users?timeout=30000');

GraphQL

const result = parseAPIEndpoint('https://api.example.com/graphql');

WebSockets

const result = parseAPIEndpoint('wss://ws.example.com/socket');

Service Connections

AMQP/RabbitMQ

const result = parseServiceURL('amqp://guest:guest@localhost:5672/vhost');
const result2 = parseServiceURL('amqps://user:[email protected]:5671/'); // SSL AMQP

Apache Kafka

const result = parseServiceURL('kafka://localhost:9092/mytopic?group_id=consumer1');

NATS

const result = parseServiceURL('nats://nats.example.com:4222?subject=events');

MQTT

const result = parseServiceURL('mqtt://localhost:1883?client_id=client1&qos=1');
const result2 = parseServiceURL('mqtts://mqtt.example.com:8883'); // SSL MQTT

LDAP

const result = parseServiceURL('ldap://ldap.example.com:389/dc=example,dc=com');
const result2 = parseServiceURL('ldaps://ldap.example.com:636/dc=example,dc=com'); // SSL LDAP

Environment Variables

Parse connection strings from environment variables:

import { parseConnection } from '@bernierllc/connection-parser';

const dbConfig = parseConnection(process.env.DATABASE_URL || '', {
  validateFormat: true,
  parsePooling: true
});

if (!dbConfig.valid) {
  throw new Error(`Invalid database URL: ${dbConfig.errors?.join(', ')}`);
}

// Use dbConfig.config for database connection

Connection Pooling

Extract pooling configuration from query parameters:

const result = parseConnection('postgresql://localhost/db?pool_min=5&pool_max=20&pool_timeout=30000');

console.log(result.config.pooling);
// {
//   min: 5,
//   max: 20,
//   timeout: 30000
// }

// Alternative parameter names are supported
const result2 = parseConnection('mysql://localhost/db?minConnections=2&maxConnections=10');
console.log(result2.config.pooling); // { min: 2, max: 10 }

Security Features

Credential Redaction

import { redactCredentials, parseConnection } from '@bernierllc/connection-parser';

const connectionString = 'postgresql://admin:topsecret@localhost:5432/mydb';

// Safe for logging
console.log(redactCredentials(connectionString));
// Output: postgresql://****:****@localhost:5432/mydb

// Parse without extracting credentials
const result = parseConnection(connectionString, { extractCredentials: false });
console.log(result.config.username); // undefined
console.log(result.config.password); // undefined

Protocol Validation

const result = parseConnection('postgresql://localhost/db', {
  allowedProtocols: ['postgresql', 'mysql'] // Restrict allowed protocols
});

Error Handling

import { parseConnection, ConnectionParserError } from '@bernierllc/connection-parser';

try {
  const result = parseConnection('invalid-url');
  
  if (!result.valid) {
    console.error('Parsing errors:', result.errors);
  }
} catch (error) {
  if (error instanceof ConnectionParserError) {
    console.error('Parser error:', error.message);
    console.error('Error code:', error.code);
    console.error('Protocol:', error.protocol);
  }
}

NeverHub Integration

When NeverHub is available, the package automatically integrates for service discovery and telemetry:

import { initializeNeverHubIntegration } from '@bernierllc/connection-parser';

// Initialize NeverHub integration (optional)
const isIntegrated = await initializeNeverHubIntegration();

if (isIntegrated) {
  console.log('NeverHub integration active');
  
  // Parsing events will be automatically published to NeverHub
  const result = parseConnection('postgresql://localhost/db');
  // Event 'config.connection.parsed' published to NeverHub
}

Performance

The parser is optimized for high-throughput scenarios:

  • >10,000 connections/second parsing performance
  • Minimal memory allocation during parsing
  • Efficient validation with early returns
  • Zero external dependencies (only Node.js built-ins)
// Benchmark example
const startTime = process.hrtime.bigint();

for (let i = 0; i < 10000; i++) {
  parseConnection('postgresql://user:pass@localhost:5432/mydb');
}

const endTime = process.hrtime.bigint();
const durationMs = Number(endTime - startTime) / 1_000_000;
console.log(`Parsed 10,000 connections in ${durationMs}ms`);

Type Definitions

interface ConnectionConfig {
  protocol: string;
  host: string;
  port?: number;
  database?: string;
  username?: string;
  password?: string;
  path?: string;
  query?: Record<string, string>;
  ssl?: boolean;
  pooling?: {
    min?: number;
    max?: number;
    timeout?: number;
    idle?: number;
  };
  options?: Record<string, unknown>;
}

interface ParseResult {
  config: ConnectionConfig;
  raw: string;
  valid: boolean;
  errors?: string[];
  metadata: {
    type: 'database' | 'api' | 'service' | 'generic';
    hasCredentials: boolean;
    hasPooling: boolean;
    isSecure: boolean;
  };
}

See Also

License

Copyright (c) 2025 Bernier LLC. All rights reserved.