@langwatch/ksuid
v2.0.2
Published
Generate prefixed, k-sorted globally unique identifiers with TypeScript support
Readme
@langwatch/ksuid
A modern, zero-dependency TypeScript library for generating prefixed, k-sorted globally unique identifiers (KSUIDs).
Features
- ✅ Zero Dependencies - No external dependencies
- ✅ TypeScript First - Full TypeScript support with strict typing
- ✅ Cross-Platform - Works in Node.js, Browser, Bun, and Deno
- ✅ K-Sortable - IDs are naturally sortable by creation time
- ✅ Environment Aware - Support for different environments (prod, dev, staging, etc.)
- ✅ Instance Detection - Automatic detection of Docker containers, MAC addresses, and PIDs
Installation
npm install @langwatch/ksuid
# or
yarn add @langwatch/ksuid
# or
pnpm add @langwatch/ksuidQuick Start
Basic Usage
import { generate, parse } from '@langwatch/ksuid';
// Generate a KSUID
const ksuid = generate('user');
console.log(ksuid.toString());
// Output: user_00028U9MDT583X9eXPG1IU0ptdl1l
// Parse a KSUID
const parsed = parse('user_00028U9MDT583X9eXPG1IU0ptdl1l');
console.log(parsed.resource); // 'user'
console.log(parsed.environment); // 'prod'
console.log(parsed.date); // Date objectEnvironment-Specific IDs
import { generate, setEnvironment } from '@langwatch/ksuid';
// Set environment
setEnvironment('dev');
// Generate dev-specific KSUID
const devKsuid = generate('order');
console.log(devKsuid.toString());
// Output: dev_order_00028U9MDT583X9eXPG1IU0ptdl1lAdvanced Usage
import { Ksuid, Instance, InstanceScheme } from '@langwatch/ksuid';
// Create a custom instance
const customInstance = new Instance(
InstanceScheme.RANDOM,
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])
);
// Create KSUID manually
const ksuid = new Ksuid(
'prod',
'product',
Math.floor(Date.now() / 1000),
customInstance,
0
);
// Access KSUID properties
console.log(ksuid.timestamp); // Unix timestamp
console.log(ksuid.sequenceId); // Sequence number
console.log(ksuid.instance.scheme); // Instance scheme
console.log(ksuid.toJSON()); // Full JSON representationAPI Reference
Main Functions
generate(resource: string): Ksuid
Generates a new KSUID for the specified resource.
const ksuid = generate('user');parse(input: string): Ksuid
Parses a KSUID string and returns a Ksuid instance.
const ksuid = parse('user_00028U9MDT583X9eXPG1IU0ptdl1l');Environment Management
getEnvironment(): string
Returns the current environment.
setEnvironment(value: string): void
Sets the current environment.
setEnvironment('dev');
const env = getEnvironment(); // 'dev'Instance Management
getInstance(): Instance
Returns the current instance.
setInstance(value: Instance): void
Sets the current instance.
const instance = new Instance(InstanceScheme.RANDOM, new Uint8Array(8));
setInstance(instance);Classes
Ksuid
The main KSUID class.
Properties:
environment: string- The environment (prod, dev, etc.)resource: string- The resource type (user, order, etc.)timestamp: number- Unix timestampinstance: Instance- The instance identifiersequenceId: number- Sequence numberdate: Date- JavaScript Date object
Methods:
toString(): string- Returns the string representationequals(other: Ksuid): boolean- Compares two KSUIDstoJSON(): object- Returns JSON representation
Instance
Represents a machine/container instance.
Schemes:
InstanceScheme.RANDOM- Random identifierInstanceScheme.MAC_AND_PID- MAC address + PIDInstanceScheme.DOCKER_CONT- Docker container ID
Node
Advanced class for custom KSUID generation.
Error Classes
ValidationError- Thrown for validation failuresBase62Error- Thrown for base62 encoding/decoding errors
Platform Support
This library works in the following environments:
- Node.js (v18+) - Full support with automatic instance detection
- Browser - Uses Web Crypto API
- Bun - Native support
- Deno - Native support
Instance Detection
The library automatically detects the best instance identifier:
- Docker Containers - Uses container ID (if available)
- Node.js - Uses MAC address + PID (if available)
- Fallback - Uses cryptographically secure random bytes
Development
Setup
git clone https://github.com/langwatch/ksuid.git
cd ksuid
npm installScripts
pnpm build # Build the library
pnpm dev # Watch mode for development
pnpm test # Run tests
pnpm test:coverage # Run tests with coverage
pnpm lint # Run ESLint
pnpm typecheck # TypeScript type checkingTesting
The library has comprehensive test coverage:
pnpm testContributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
MIT License - see LICENSE file for details.
Acknowledgments
This library is inspired by the original KSUID specification and the @cuvva/ksuid implementation.
