UNPKG

uuid-core

Version:

A simple UUID generator library for Node.js, NestJS, and Next.js

98 lines (62 loc) 2.89 kB
# uuid-core A lightweight, secure, and user-friendly UUID generator library for Node.js. It supports UUID versions 1 (time-based), 4 (random), and 5 (namespace-based) as per [RFC9562](https://www.rfc-editor.org/rfc/rfc9562.html), leveraging Node.js's built-in `crypto` module with no external dependencies. ## Features - **Simple API**: Generate UUIDs with intuitive calls like `UUIDGenerator.v4()`. - **Secure**: Uses Node.js `crypto` for cryptographically secure random values and SHA-1 for v5. - **Standards-Compliant**: Adheres to RFC9562 for UUID formats. - **TypeScript Support**: Fully typed for a seamless developer experience. - **Framework Compatibility**: Designed to work seamlessly across all JavaScript environments that support npm packages. - **Validation**: Includes UUID validation and a nil UUID utility. ## Installation Install the library via npm: ```bash npm install uuid-core ``` **Requirements**: - Node.js >= 14.17.0 (for `crypto.randomUUID` support) - TypeScript >= 5.4.5 (if using TypeScript) ## Usage ### Importing the Library For ESM: ```javascript import { UUIDGenerator } from "uuid-core"; ``` For CommonJS: ```javascript const { UUIDGenerator } = require("uuid-core"); ``` ### Generating UUIDs ```javascript // Generate a time-based UUID (v1) console.log(UUIDGenerator.v1()); // Example output: "a1b2c3d4-1234-11ed-89ab-1234567890ab" // Generate a random UUID (v4) console.log(UUIDGenerator.v4()); // Example output: "123e4567-e89b-12d3-a456-426614174000" // Generate a namespace-based UUID (v5) const namespace = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; console.log(UUIDGenerator.v5("test", namespace)); // Example output: "b1c4a89e-4905-5e3c-b57f-dc92627d011e" // Get a nil UUID console.log(UUIDGenerator.empty()); // Output: "00000000-0000-0000-0000-000000000000" // Validate a UUID console.log(UUIDGenerator.validate("123e4567-e89b-12d3-a456-426614174000")); // Output: true ``` ## API Reference ### `UUIDGenerator.v1(): UUID` Generates a time-based UUID (version 1) using the current timestamp, clock sequence, and a random node ID. ### `UUIDGenerator.v4(): UUID` Generates a random UUID (version 4) using Node.js's `crypto.randomUUID`. ### `UUIDGenerator.v5(name: string, namespace: UUID): UUID` Generates a namespace-based UUID (version 5) using SHA-1 hashing of the provided name and namespace. ### `UUIDGenerator.validate(uuid: string): boolean` Checks if a string is a valid UUID (versions 1-5) per RFC9562. ### `UUIDGenerator.empty(): UUID` Returns a nil UUID (`00000000-0000-0000-0000-000000000000`). ### Types - `UUID`: A string in the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`. - `Namespace`: A UUID used as a namespace for v5 generation. ## License This project is licensed under the [MIT License](LICENSE).