Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
281 changes: 213 additions & 68 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
# @haskou/value-objects

> Validated, immutable Value Objects for TypeScript and Domain-Driven Design.

Replace primitive obsession and defensive validation with domain-safe values that validate themselves.

[![CI](https://github.com/haskou/value-objects/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/haskou/value-objects/actions/workflows/ci.yml?query=branch%3Amaster)
[![codecov](https://codecov.io/gh/haskou/value-objects/branch/master/graph/badge.svg)](https://codecov.io/gh/haskou/value-objects)
[![npm version](https://img.shields.io/npm/v/@haskou/value-objects.svg)](https://www.npmjs.com/package/@haskou/value-objects)
[![Renovate](https://img.shields.io/badge/renovate-enabled-brightgreen?logo=renovatebot)](https://docs.renovatebot.com/)
[![npm downloads](https://img.shields.io/npm/dw/@haskou/value-objects.svg)](https://www.npmjs.com/package/@haskou/value-objects)
[![license](https://img.shields.io/npm/l/@haskou/value-objects.svg)](LICENSE.txt)

A TypeScript library for validated, immutable primitive wrappers and small utility value objects.

It provides ready-to-use objects for strings, numbers, identifiers, dates, coordinates, hashes, media, and collections. Validation happens when an object is created, so code receiving one of these objects can rely on its shape.

The package publishes ESM and CommonJS entry points plus TypeScript declarations. Both entry points share one runtime implementation, so class identity and NullObject configuration stay consistent when imports and requires are mixed. It does not declare a Node.js engine requirement. Identifier generation uses the installed `uuid` dependency with platform-specific Node and browser implementations.

## Documentation

Full documentation is available at **https://haskou.github.io/value-objects/**.

The documentation includes installation, quick start, examples, error handling, serialization notes, and one reference page per exported class.

## Installation

```bash
Expand All @@ -28,102 +20,255 @@ npm install @haskou/value-objects
yarn add @haskou/value-objects
```

## Quick start
## Why?

Primitive values force every consumer to defend itself.

```typescript
function sendEmail(email?: string | null) {
if (email === null || email === undefined) {
return;
}

if (email.length === 0) {
throw new Error('Email cannot be empty');
}

if (!email.includes('@')) {
throw new Error('Invalid email');
}

// finally use the email
}
```

And another part of the application will eventually perform the same checks again, because `string` says nothing about what the value represents.

A Value Object moves those rules to the value itself:

```typescript
import { Color, Email, Hour, PositiveNumber } from '@haskou/value-objects';
import { Email } from '@haskou/value-objects';

const email = new Email('user@example.com');
const price = new PositiveNumber(29.99);
const color = new Color('#FF0000');
const hour = new Hour('09:30');

console.log(email.valueOf()); // 'user@example.com'
console.log(price.valueOf()); // 29.99
console.log(color.toString()); // '#FF0000'
console.log(hour.addMinutes(45).toString()); // '10:15'
function sendEmail(email: Email) {
// already a valid Email
}
```

Invalid values throw specific errors.
A non-null `Email` has already passed format validation, so consumers do not need to repeat those checks.

```typescript
import { Email, InvalidEmailError } from '@haskou/value-objects';
new Email('not-an-email');
// throws InvalidEmailError
```

try {
new Email('not-an-email');
} catch (error) {
if (error instanceof InvalidEmailError) {
console.error('Invalid email');
The same idea applies to numbers, identifiers, dates, coordinates, hashes and your own domain concepts.

Validation happens when values enter the domain instead of being repeated everywhere they are used.

## Build your own domain Value Objects

The built-in Value Objects are also intended to be extended.

If your domain has a `Username`, it should not remain a generic `string` with validation scattered around the application.

```typescript
import {
assert,
NullObject,
StringValueObject,
} from '@haskou/value-objects';

export class Username extends StringValueObject {
constructor(value: string) {
super(value, 30);

if (NullObject.isNullObject(this)) return this;

assert(!this.isEmpty(), 'Username cannot be empty');
assert(value.length >= 3, 'Username must contain at least 3 characters');
assert(
/^[a-zA-Z0-9_]+$/.test(value),
'Username contains invalid characters',
);
}
}
```

## Nullish construction
Now the rules belong to the domain type:

```typescript
const username = new Username('haskou');

function createUser(username: Username) {
// no need to validate the username again
}
```

This is the main idea behind the library: use the provided Value Objects where they fit, and extend the base ones with your own domain invariants when they do not.

## Null without defensive programming

Automatic `NullObject` creation remains enabled by default for compatibility. Applications that prefer strict construction can disable it globally:
Missing values can be represented through the `NullObject` pattern instead of propagating `null | undefined` checks throughout the domain.

```typescript
import { StringValueObject, ValueObject } from '@haskou/value-objects';
import {
NullObject,
NumberValueObject,
} from '@haskou/value-objects';

const limit = new NumberValueObject(undefined as never);

NullObject.isNullObject(limit);
// true
```

The object can safely represent absence and pass through the domain without requiring:

```typescript
if (limit !== null && limit !== undefined) {
// ...
}
```

But a `NullObject` does not silently pretend to contain a valid value.

Calling behaviour that requires that value fails explicitly:

```typescript
const limit = new NumberValueObject(undefined as never);

limit.isGreaterThan(10);
// throws NullObjectError
```

This lets missing values travel through the same domain abstraction while still failing immediately when code tries to actually use them.

Applications that prefer strict construction can disable automatic `NullObject` creation:

```typescript
import {
NumberValueObject,
ValueObject,
} from '@haskou/value-objects';

ValueObject.disableNullObjectCreation();

new StringValueObject(undefined as never); // throws NullObjectCreationDisabledError
new NumberValueObject(undefined as never);
// throws NullObjectCreationDisabledError
```

## Assertions

ValueObject.enableNullObjectCreation();
The library exports an `assert` helper for expressing invariants without deeply nested validation branches.

Instead of:

```typescript
if (value !== undefined) {
if (value.length > 0) {
if (value.length <= 100) {
// ...
}
}
}
```

The VitePress guide documents the default and strict modes in detail.
Use:

## Available categories
```typescript
import { assert } from '@haskou/value-objects';

| Category | Examples |
| --- | --- |
| Base | `ValueObject`, `NullObject`, `Enum` |
| Strings | `StringValueObject`, `Password`, `Email`, `Color` |
| Numbers | `NumberValueObject`, `Integer`, `PositiveNumber` |
| IDs | `ShortId`, `UUID` |
| Time | `Timestamp`, `CalendarDay`, `Hour`, `Duration`, `MonthOfYear` |
| Coordinates | `Latitude`, `Longitude`, `Coordinates` |
| Hashes | `MD5Hash`, `SHA256Hash`, `SHA512Hash` |
| Media | `Media` |
| Collections | `UniqueObjectArray` |
assert(value !== undefined, 'Value is required');
assert(value.length > 0, 'Value cannot be empty');
assert(value.length <= 100, 'Value is too long');
```

See the complete API reference in the documentation: https://haskou.github.io/value-objects/reference/
Failed assertions throw the supplied error, or a `DomainError` when given a string.

## Documentation development
Successful assertions use TypeScript assertion signatures, so the condition is narrowed afterwards.

```bash
# Start local docs server
yarn docs:dev
## Quick start

# Build static documentation
yarn docs:build
```typescript
import {
Color,
Email,
Hour,
PositiveNumber,
} from '@haskou/value-objects';

# Preview the built site
yarn docs:preview
const email = new Email('user@example.com');
const price = new PositiveNumber(29.99);
const color = new Color('#FF0000');
const hour = new Hour('09:30');

email.valueOf(); // 'user@example.com'
price.valueOf(); // 29.99
color.toString(); // '#FF0000'
hour.addMinutes(45).toString(); // '10:15'
```

Validation errors use specific error types:

```typescript
import {
Email,
InvalidEmailError,
} from '@haskou/value-objects';

try {
new Email('not-an-email');
} catch (error) {
if (error instanceof InvalidEmailError) {
// Handle invalid domain input.
}
}
```

## Package development
## Available Value Objects

| Category | Examples |
| ----------- | ------------------------------------------------------------- |
| Base | `ValueObject`, `NullObject`, `Enum` |
| Strings | `StringValueObject`, `Password`, `Email`, `Color` |
| Numbers | `NumberValueObject`, `Integer`, `PositiveNumber` |
| Identifiers | `ShortId`, `UUID` |
| Date & time | `Timestamp`, `CalendarDay`, `Hour`, `Duration`, `MonthOfYear` |
| Coordinates | `Latitude`, `Longitude`, `Coordinates` |
| Hashes | `MD5Hash`, `SHA256Hash`, `SHA512Hash` |
| Media | `Media` |
| Collections | `UniqueObjectArray` |

The package is framework-agnostic and can be used in any TypeScript domain layer regardless of the framework, ORM or persistence technology around it.

## Documentation

Full documentation:

https://haskou.github.io/value-objects/

API reference:

https://haskou.github.io/value-objects/reference/

## Development

```bash
git clone https://github.com/haskou/value-objects.git
cd value-objects

yarn install
yarn test
yarn build
```

`yarn build` type-checks the production configuration, emits a CommonJS implementation and an ESM wrapper, generates declarations, and verifies both entry points share classes and configuration.

## Release branches

Publishing is handled by CI when a pull request is merged into the default branch.
## Contributing

| Branch prefix | npm bump |
| --- | --- |
| `fix/*` | Patch |
| `feat/*` | Minor |
| `break/*` | Major |
Bug reports, feature requests and pull requests are welcome.

Branches without one of these prefixes still run CI, but they do not publish to npm.
https://github.com/haskou/value-objects/issues

## License

Expand Down
Loading