Skip to content

Commit a686dba

Browse files
committed
feat: Enhance error handling with custom error classes and improve validation logic
- Added rich error handling with descriptive error classes for better semantics. - Improved validation logic in the Base class to throw specific errors for various validation failures. - Updated the README and CHANGELOG to reflect new features and improvements. - Added benchmarking capabilities to measure performance of model creation and updates. - Refactored CI workflow to streamline testing and coverage reporting.
1 parent 945f105 commit a686dba

9 files changed

Lines changed: 526 additions & 72 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,5 @@ jobs:
2525
run: npm run build
2626
- name: Run tests
2727
run: npm test
28-
29-
coverage:
30-
runs-on: ubuntu-latest
31-
steps:
32-
- uses: actions/checkout@v4
33-
- name: Use Node.js
34-
uses: actions/setup-node@v4
35-
with:
36-
node-version: 24.x
37-
- name: Install dependencies
38-
run: npm ci
39-
- name: Build
40-
run: npm run build
4128
- name: Run coverage
4229
run: npm run test:coverage

‎CHANGELOG.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@
22

33
All notable changes to this project will be documented in this file.
44

5+
## [1.1.0] - 2026-06-02
6+
7+
### Added
8+
- Rich and detailed error handling with descriptive error classes to enable programmatic error handling and clearer error semantics.
9+
10+
### Changed
11+
- Removed redundant checks
12+
- Fixed loop on error thrown during construction to properly set all properties to the error object instead of just the enumerable ones.
13+
14+
### Notes
15+
- These changes improve runtime safety and the test coverage baseline; see tests in `test/base.test.js` for usage patterns.
16+
517
## [1.0.0] - 2024-06-30
618
- Project renamed from `@bufferpunk/schema` to `@bufferpunk/modelcore` to better reflect its focus on runtime entities and validation rather than just schema definition.
719
- Improve TypeScript ergonomics: recommend `as const` schemas and provide `createFrom` factory for single-source-of-truth typed instantiation.

‎README.md‎

Lines changed: 60 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
11
# ModelCore - Runtime Entity Integrity for JavaScript and TypeScript
22

3-
A lightweight runtime schema validator for JavaScript and TypeScript models with support for immutability, field-level validation hooks, and TypeScript-friendly ergonomics.
3+
![Build Status](https://img.shields.io/github/actions/workflow/status/bufferpunk/schema/ci.yml?branch=main)
4+
![Coverage](https://img.shields.io/badge/coverage-100%25-green)
5+
![npm version](https://img.shields.io/npm/v/@bufferpunk/modelcore)
6+
![License](https://img.shields.io/npm/l/@bufferpunk/modelcore)
47

5-
`@bufferpunk/modelcore` is built around a `Base` class that validates plain objects using a static `schema` definition. It is useful when working with NoSQL data, API payloads, and nested objects that need runtime guarantees and constraints.
8+
**Pydantic-inspired • Lightweight • Backend & Frontend friendly**
9+
10+
A blazing fast, lightweight and Reactive Class-Based Object Modeling framework.
11+
12+
Build clean, safe, and delightful domain entities for TypeScript and JavaScript.
13+
14+
`@bufferpunk/modelcore` is built around a `Base` class that validates plain objects using a static `schema` definition. It is useful when working with NoSQL data, API payloads, and nested objects that need runtime and compile-time guarantees and constraints.
615

716
## What It Does
817

@@ -19,6 +28,27 @@ When a model extends `Base` and defines a static `schema`, instance creation and
1928

2029
This package now also provides a typed factory pattern (`createFrom`) and improved TypeScript mappings so editors receive useful type information and inferred instance types when schemas are declared with `as const`.
2130

31+
## Comparison to Other Libraries
32+
33+
- **Zod / Joi / Yup**: These are schema validation libraries that focus on validating plain objects. They do not provide a class-based model with runtime immutability or automatic coercion. You would need to manually validate and then assign values to a class instance.
34+
- **TypeORM / Sequelize**: These are ORM libraries that provide class-based models but are tightly coupled to databases and do not focus on runtime validation or immutability outside of the context of database operations.
35+
- **MobX / Vue Reactivity**: These libraries provide reactivity and state management but do not enforce validation rules or immutability at the runtime level. They track changes but do not govern them.
36+
37+
**ModelCore** fills the gap by providing a class-based modeling system that enforces validation and immutability rules at runtime and compile-time, making it suitable for both frontend and backend applications where data integrity is crucial.
38+
39+
**Here is a simple comparison with other libraries**
40+
41+
| Feature | ModelCore | Zod / Joi / Yup | TypeORM / Sequelize | MobX / Vue Reactivity |
42+
|-----------------------------|---------------------------|---------------------------|---------------------------|--------------------------|
43+
| Class-based models | ✅ | ❌ | ✅ | ❌ |
44+
| Runtime validation | ✅ | ✅ | Limited (database-focused) | ❌ |
45+
| Reactivity | ✅ | ❌ | ❌ | ✅ |
46+
| Immutability enforcement | ✅ | ❌ | Limited (database-focused) | ❌ |
47+
| Automatic coercion | ✅ | Limited (Zod has some coercion) | ❌ | ❌ |
48+
| Nested object validation | ✅ | ✅ | Limited (database-focused) | ❌ |
49+
| TypeScript support | ✅ | ✅ | ✅ | ✅ |
50+
| Frontend & Backend friendly | ✅ | ✅ | Backend-focused | Frontend-focused |
51+
2252
## Installation
2353

2454
```bash
@@ -162,13 +192,13 @@ class ImmutableUser extends Base {
162192

163193
## Updating Instances
164194

165-
Use the `update()` method or regular property assignment to modify instance properties.
195+
Use regular property access (recommended) to modify instance properties or the `update()` method (best if you want to update the whole object).
166196
The constructor automatically includes the `version` if defined on the class.
167197

168198
```ts
169199
const user = new User({ name: 'John', role: 'user' });
170-
user.update({ role: 'admin' });
171-
user.name = 'Jane'; // also works, with validation (eassiest for simple updates)
200+
user.name = 'Jane'; // (easiest and recommended for simple property changes)
201+
user.update({ name: 'Jane', role: 'admin' });
172202
```
173203

174204
## Factory and TypeScript ergonomics
@@ -213,6 +243,31 @@ npm test
213243

214244
The repository includes a GitHub Actions workflow to run build and test on Node LTS.
215245

246+
## Benchmarking
247+
248+
Use the included micro-benchmark to compare construction, factory creation, updates, and mutation paths:
249+
250+
```bash
251+
npm run bench
252+
```
253+
254+
You can adjust iteration count with `BENCH_ITERATIONS`:
255+
256+
```bash
257+
BENCH_ITERATIONS=100000 npm run bench
258+
```
259+
260+
Example result on this repository, run with `BENCH_ITERATIONS=100000`:
261+
262+
```text
263+
construct + validate 1512.23 ms 66128 ops/sec
264+
createFrom factory 1452.82 ms 68832 ops/sec
265+
update validated fields 2831.84 ms 35313 ops/sec
266+
array mutations 2747.17 ms 36401 ops/sec
267+
```
268+
269+
The benchmark is intentionally small and repeatable. It is useful for comparing changes between commits, not for replacing a full profiler or load test.
270+
216271
## Why Runtime Entities Matter
217272

218273
See the manifesto for the project's goals and positioning: [manifesto.md](manifesto.md)

‎base.d.ts‎

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,58 @@ export interface SchemaDefinition {
1919
export interface parserConfig {
2020
safe?: boolean;
2121
}
22+
export interface BaseConstructor {
23+
schema: SchemaDefinition;
24+
immutable?: boolean;
25+
version?: number;
26+
}
27+
export interface errorObject {
28+
message: string;
29+
source?: string | Function;
30+
path?: string;
31+
expected?: any;
32+
received?: any;
33+
code?: string;
34+
}
35+
export declare class ModelCoreError extends Error {
36+
source: string | Function | undefined;
37+
path: Array<string | number> | string | undefined;
38+
expected: any;
39+
received: any;
40+
code: string | undefined;
41+
static errorName: string;
42+
constructor(errObj: errorObject);
43+
}
44+
export declare class ImmutableObjectError extends ModelCoreError {
45+
static errorName: string;
46+
}
47+
export declare class ImmutablePropertyError extends ModelCoreError {
48+
static errorName: string;
49+
}
50+
export declare class ValidationError extends ModelCoreError {
51+
static errorName: string;
52+
}
53+
export declare class EnumValueError extends ModelCoreError {
54+
static errorName: string;
55+
}
56+
export declare class RangeError extends ModelCoreError {
57+
static errorName: string;
58+
}
59+
export declare class TypeValidationError extends ModelCoreError {
60+
static errorName: string;
61+
}
62+
export declare class MissingPropertyError extends ModelCoreError {
63+
static errorName: string;
64+
}
65+
export declare class SchemaDefinitionError extends ModelCoreError {
66+
static errorName: string;
67+
}
68+
export declare class RequiredError extends ModelCoreError {
69+
static errorName: string;
70+
}
71+
export declare class ValueError extends ModelCoreError {
72+
static errorName: string;
73+
}
2274
type UnwrapTypeConstructor<T> = T extends StringConstructor ? string : T extends NumberConstructor ? number : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends ArrayConstructor ? any[] : T extends ObjectConstructor ? Record<string, any> : T extends new (...args: any[]) => infer R ? R : unknown;
2375
type InferFieldRaw<T extends FieldConfig> = T['keys'] extends Record<string, FieldConfig> ? InferObject<T> : T['values'] extends FieldConfig ? InferArray<T> : UnwrapTypeConstructor<T['type']>;
2476
type InferField<T extends FieldConfig> = T['optional'] extends true ? InferFieldRaw<T> | undefined : InferFieldRaw<T>;
@@ -34,7 +86,7 @@ type InferObject<T extends FieldConfig> = T['keys'] extends Record<string, Field
3486
[K in OptionalKeys<T['keys']>]?: InferFieldRaw<T['keys'][K]>;
3587
} : Record<string, any>;
3688
type InferArray<T extends FieldConfig> = T['values'] extends FieldConfig ? Array<InferField<T['values']>> : any[];
37-
export type SchemaToType<S extends SchemaDefinition> = {
89+
type SchemaToType<S extends SchemaDefinition> = {
3890
[K in RequiredKeys<S>]: InferFieldRaw<S[K]>;
3991
} & {
4092
[K in OptionalKeys<S>]?: InferFieldRaw<S[K]>;
@@ -46,8 +98,7 @@ export default class Base {
4698
version?: number | undefined;
4799
[key: string]: any;
48100
constructor(obj: Record<string, any>, parseConfig?: parserConfig);
49-
static createFrom<T extends typeof Base>(this: T, obj: Partial<SchemaToType<T['schema']>>, // Partial allows missing optional keys on input
50-
parseConfig?: parserConfig): Partial<SchemaToType<T['schema']>>;
101+
static createFrom<T extends typeof Base>(this: T, obj: SchemaToType<T['schema']>, parseConfig?: parserConfig): SchemaToType<T['schema']>;
51102
update(obj: Record<string, any>, parseConfig?: parserConfig, isNew?: boolean): void;
52103
toObject(): Record<string, any>;
53104
json(): string;

0 commit comments

Comments
 (0)