@fjell/core 4.4.7 → 4.4.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ # Fjell Core
2
+
3
+ Core Item and Key Framework for Fjell - The foundational library that provides essential item management, key utilities, and service coordination for the entire Fjell ecosystem.
4
+
5
+ ## Features
6
+
7
+ - **Type-safe item creation** with IFactory
8
+ - **Hierarchical key management** with KUtils
9
+ - **Abstract service layer** with AItemService
10
+ - **Query building and execution** with IQFactory and IQUtils
11
+ - **Comprehensive error handling** with custom error types
12
+ - **Testing utilities** for robust test suites
13
+ - **TypeScript-first design** for excellent developer experience
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @fjell/core
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ```typescript
24
+ import { IFactory, KUtils, AItemService } from '@fjell/core'
25
+
26
+ // Create items with the factory
27
+ const user = IFactory.create('user', {
28
+ id: 'user-123',
29
+ name: 'John Doe',
30
+ email: 'john@example.com'
31
+ })
32
+
33
+ // Generate hierarchical keys
34
+ const userKey = KUtils.generateKey(['users', user.id])
35
+
36
+ // Build services
37
+ class UserService extends AItemService {
38
+ async createUser(userData: any) {
39
+ const user = IFactory.create('user', userData)
40
+ await this.validate(user)
41
+ return this.save(user)
42
+ }
43
+ }
44
+ ```
45
+
46
+ ## Core Modules
47
+
48
+ ### IFactory
49
+ Factory for creating strongly-typed items with validation and defaults.
50
+
51
+ ```typescript
52
+ interface User {
53
+ id: string
54
+ name: string
55
+ email: string
56
+ }
57
+
58
+ const user = IFactory.create<User>('user', {
59
+ id: 'user-123',
60
+ name: 'John Doe',
61
+ email: 'john@example.com'
62
+ })
63
+ ```
64
+
65
+ ### KUtils
66
+ Utilities for hierarchical key generation and manipulation.
67
+
68
+ ```typescript
69
+ // Generate keys
70
+ const userKey = KUtils.generateKey(['users', 'user-123'])
71
+ const profileKey = KUtils.generateKey(['users', 'user-123', 'profile'])
72
+
73
+ // Parse keys
74
+ const components = KUtils.parseKey(userKey) // ['users', 'user-123']
75
+
76
+ // Validate keys
77
+ const isValid = KUtils.isValidKey(userKey) // true
78
+ ```
79
+
80
+ ### AItemService
81
+ Abstract base class for building domain services with lifecycle management.
82
+
83
+ ```typescript
84
+ class UserService extends AItemService {
85
+ async create(userData: Partial<User>): Promise<User> {
86
+ const user = IFactory.create<User>('user', userData)
87
+ await this.validate(user)
88
+ return this.save(user)
89
+ }
90
+
91
+ protected async validate(user: User): Promise<void> {
92
+ if (!user.email.includes('@')) {
93
+ throw new Error('Invalid email')
94
+ }
95
+ }
96
+ }
97
+ ```
98
+
99
+ ### Query System
100
+ Build and execute queries with IQFactory and IQUtils.
101
+
102
+ ```typescript
103
+ const query = IQFactory.create('user')
104
+ .where('status', 'active')
105
+ .where('role', 'admin')
106
+ .orderBy('createdAt', 'desc')
107
+ .limit(10)
108
+
109
+ const results = await IQUtils.execute(query)
110
+ ```
111
+
112
+ ## Architecture Philosophy
113
+
114
+ Fjell Core is designed around **progressive enhancement**:
115
+
116
+ 1. **Start Simple**: Basic operations require minimal setup
117
+ 2. **Scale Gradually**: Add complexity only when needed
118
+ 3. **Maintain Consistency**: Common patterns across all Fjell libraries
119
+ 4. **Enable Integration**: Designed to work with the entire ecosystem
120
+
121
+ ## Integration with Fjell Ecosystem
122
+
123
+ Fjell Core serves as the foundation for:
124
+
125
+ - **@fjell/registry**: Service location and dependency injection
126
+ - **@fjell/cache**: High-performance caching solutions
127
+ - **@fjell/lib**: Database abstraction layers
128
+ - **@fjell/providers**: React component state management
129
+ - **@fjell/client-api**: HTTP client utilities
130
+ - **@fjell/express-router**: Express.js routing utilities
131
+
132
+ ## Type Safety
133
+
134
+ Built with TypeScript-first design for excellent developer experience:
135
+
136
+ ```typescript
137
+ // Strongly typed factories
138
+ const user = IFactory.create<UserType>('user', userData)
139
+
140
+ // Type-safe key operations
141
+ const key = KUtils.generateKey(['users', user.id])
142
+ const [collection, id] = KUtils.parseKey(key)
143
+
144
+ // Compile-time validation
145
+ class UserService extends AItemService<User> {
146
+ // Methods are typed to work with User objects
147
+ }
148
+ ```
149
+
150
+ ## Error Handling
151
+
152
+ Comprehensive error handling with descriptive messages:
153
+
154
+ ```typescript
155
+ try {
156
+ const user = await userService.create(invalidData)
157
+ } catch (error) {
158
+ if (error instanceof CoreValidationError) {
159
+ console.log('Validation failed:', error.details)
160
+ } else if (error instanceof CoreNotFoundError) {
161
+ console.log('User not found:', error.id)
162
+ }
163
+ }
164
+ ```
165
+
166
+ ## Testing Support
167
+
168
+ Built-in testing utilities for robust test suites:
169
+
170
+ ```typescript
171
+ import { TestUtils } from '@fjell/core/testing'
172
+
173
+ // Mock factories
174
+ const mockFactory = TestUtils.createMockFactory()
175
+ const testUser = mockFactory.create('user', { id: 'test-123' })
176
+
177
+ // Assertion helpers
178
+ expect(TestUtils.isValidKey(key)).toBe(true)
179
+ expect(TestUtils.getKeyComponents(key)).toEqual(['users', '123'])
180
+ ```
181
+
182
+ ## Performance
183
+
184
+ Optimized for production use:
185
+
186
+ - **Minimal Runtime Overhead**: Core operations are highly optimized
187
+ - **Memory Efficient**: Smart object pooling and reuse strategies
188
+ - **Lazy Loading**: Components load only when needed
189
+ - **Tree Shaking**: Only bundle what you use
190
+
191
+ ## Examples
192
+
193
+ Check out the `/examples` directory for comprehensive usage examples:
194
+
195
+ - Basic item and key operations
196
+ - Service implementation patterns
197
+ - Query building and execution
198
+ - Integration with databases and APIs
199
+ - Testing strategies
200
+
201
+ ## Documentation
202
+
203
+ - **Getting Started**: Step-by-step setup guide
204
+ - **API Reference**: Complete API documentation
205
+ - **Examples**: Real-world usage patterns
206
+ - **Migration Guide**: Upgrading from previous versions
207
+
208
+ ## Contributing
209
+
210
+ We welcome contributions! Please see our contributing guidelines for details on:
211
+
212
+ - Code style and standards
213
+ - Testing requirements
214
+ - Documentation standards
215
+ - Pull request process
216
+
217
+ ## License
218
+
219
+ Licensed under the Apache License 2.0. See LICENSE file for details.
220
+
221
+ ## Support
222
+
223
+ - **GitHub Issues**: Report bugs and request features
224
+ - **Discussions**: Community support and questions
225
+ - **Documentation**: Comprehensive guides and API reference
226
+
227
+ Built with love by the Fjell team.
@@ -0,0 +1,230 @@
1
+ # Fjell Core API Reference
2
+
3
+ Complete API documentation for all Fjell Core modules and exports.
4
+
5
+ ## Overview
6
+
7
+ Fjell Core provides a comprehensive set of tools for item management, key utilities, and service coordination. All APIs are built with TypeScript-first design for maximum type safety.
8
+
9
+ ## Core Exports
10
+
11
+ ### Factory Classes
12
+
13
+ #### `IFactory<V, S, L1, L2, L3, L4, L5>`
14
+ Generic item factory for creating strongly-typed items with hierarchical key support.
15
+
16
+ **Type Parameters:**
17
+ - `V extends Item<S, L1, L2, L3, L4, L5>`: The item type being created
18
+ - `S extends string`: Primary key type
19
+ - `L1-L5 extends string`: Location key types (optional)
20
+
21
+ **Constructor:**
22
+ ```typescript
23
+ new IFactory<V, S, L1, L2, L3, L4, L5>(props?: Record<string, any>)
24
+ ```
25
+
26
+ **Methods:**
27
+
28
+ ##### `addRef(item: Item, name?: string): IFactory`
29
+ Adds a reference to another item.
30
+
31
+ **Parameters:**
32
+ - `item`: The item to reference
33
+ - `name`: Optional reference name (defaults to primary type)
34
+
35
+ **Returns:** Factory instance for chaining
36
+
37
+ ##### `static addRef<V, S, L1, L2, L3, L4, L5>(item: V, name?: string): IFactory`
38
+ Static method to create a factory with a reference.
39
+
40
+ ##### `addDefaultEvents(): IFactory`
41
+ Adds default event timestamps (created, updated).
42
+
43
+ **Returns:** Factory instance for chaining
44
+
45
+ #### `IQFactory`
46
+ Factory for building item queries with filtering, sorting, and pagination.
47
+
48
+ ### Utility Classes
49
+
50
+ #### `KUtils`
51
+ Comprehensive key management utilities for hierarchical key operations.
52
+
53
+ **Methods:**
54
+
55
+ ##### `createNormalizedHashFunction<T>(): (key: T) => string`
56
+ Creates a normalized hash function for consistent key comparison.
57
+
58
+ **Returns:** Hash function that normalizes pk/lk values to strings
59
+
60
+ ##### `normalizeKeyValue(value: string | number): string`
61
+ Normalizes key values for consistent comparison.
62
+
63
+ **Parameters:**
64
+ - `value`: The value to normalize
65
+
66
+ **Returns:** String representation of the value
67
+
68
+ ##### `primaryType(key: ComKey | PriKey): string`
69
+ Extracts the primary type from a composite or primary key.
70
+
71
+ ### Service Classes
72
+
73
+ #### `AItemService<S, L1, L2, L3, L4, L5>`
74
+ Abstract base class for building domain-specific item services.
75
+
76
+ **Type Parameters:**
77
+ - `S extends string`: Primary key type
78
+ - `L1-L5 extends string`: Location key types (hierarchical)
79
+
80
+ **Constructor:**
81
+ ```typescript
82
+ new AItemService<S, L1, L2, L3, L4, L5>(
83
+ pkType: S,
84
+ parentService?: AItemService<L1, L2, L3, L4, L5, never>
85
+ )
86
+ ```
87
+
88
+ **Parameters:**
89
+ - `pkType`: The primary key type for this service
90
+ - `parentService`: Optional parent service for hierarchical structures
91
+
92
+ **Methods:**
93
+
94
+ ##### `getPkType(): S`
95
+ Gets the primary key type for this service.
96
+
97
+ **Returns:** The primary key type string
98
+
99
+ ##### `getKeyTypes(): AllItemTypeArrays<S, L1, L2, L3, L4, L5>`
100
+ Gets all key types managed by this service, including parent service types.
101
+
102
+ **Returns:** Array of all key type strings in the hierarchy
103
+
104
+ ## Type Definitions
105
+
106
+ ### Key Types
107
+
108
+ #### `PriKey<S>`
109
+ Primary key structure for items.
110
+
111
+ #### `ComKey<S, L1, L2, L3, L4, L5>`
112
+ Composite key structure supporting hierarchical locations.
113
+
114
+ #### `LocKey`
115
+ Location key for hierarchical positioning.
116
+
117
+ #### `LocKeyArray`
118
+ Array of location keys for complex hierarchies.
119
+
120
+ ### Item Types
121
+
122
+ #### `Item<S, L1, L2, L3, L4, L5>`
123
+ Base item interface with hierarchical key support.
124
+
125
+ **Properties:**
126
+ - `key`: The item's key (PriKey or ComKey)
127
+ - `refs?`: Optional references to other items
128
+ - `events?`: Optional event timestamps
129
+
130
+ ### Query Types
131
+
132
+ #### `ItemQuery<S, L1, L2, L3, L4, L5>`
133
+ Query structure for filtering and retrieving items.
134
+
135
+ ## Utility Functions
136
+
137
+ ### Dictionary Operations
138
+ Exported from `dictionary` module for key-value operations with normalized hashing.
139
+
140
+ ### Key Operations
141
+ Exported from `keys` module for advanced key manipulation and validation.
142
+
143
+ ### Item Operations
144
+ Exported from `items` module for item creation, validation, and transformation.
145
+
146
+ ## Query Building
147
+
148
+ ### IQFactory
149
+ Factory for building complex queries:
150
+
151
+ ```typescript
152
+ const query = IQFactory.create('user')
153
+ .where('status', 'active')
154
+ .where('role', 'admin')
155
+ .limit(10)
156
+ .orderBy('createdAt', 'desc')
157
+ ```
158
+
159
+ ### IQUtils
160
+ Utilities for executing and optimizing queries.
161
+
162
+ ### IUtils
163
+ General item utilities for validation, transformation, and manipulation.
164
+
165
+ ## Best Practices
166
+
167
+ ### Type Safety
168
+ Always use generic type parameters to ensure compile-time type checking:
169
+
170
+ ```typescript
171
+ interface User {
172
+ id: string
173
+ name: string
174
+ email: string
175
+ }
176
+
177
+ const userFactory = new IFactory<User, 'user'>()
178
+ const user = userFactory.create({ id: '123', name: 'John', email: 'john@example.com' })
179
+ ```
180
+
181
+ ### Hierarchical Keys
182
+ Use the hierarchical key system for complex data relationships:
183
+
184
+ ```typescript
185
+ class UserService extends AItemService<'user', 'organization'> {
186
+ constructor(orgService: OrganizationService) {
187
+ super('user', orgService)
188
+ }
189
+ }
190
+ ```
191
+
192
+ ### Key Normalization
193
+ Use normalized hash functions for consistent key comparison:
194
+
195
+ ```typescript
196
+ const hashFn = KUtils.createNormalizedHashFunction<ComKey<'user', 'org'>>()
197
+ const hash = hashFn(userKey)
198
+ ```
199
+
200
+ ## Error Handling
201
+
202
+ All methods may throw validation errors or type mismatches. Always wrap operations in try-catch blocks for production code:
203
+
204
+ ```typescript
205
+ try {
206
+ const item = factory.create(data)
207
+ const key = KUtils.generateKey(components)
208
+ } catch (error) {
209
+ console.error('Operation failed:', error.message)
210
+ }
211
+ ```
212
+
213
+ ## Performance Considerations
214
+
215
+ - Use normalized hash functions for efficient key comparisons
216
+ - Leverage hierarchical services for organized data access
217
+ - Implement proper query optimization using IQUtils
218
+ - Consider memory usage with large item collections
219
+
220
+ ## Integration
221
+
222
+ Fjell Core is designed to integrate seamlessly with the entire Fjell ecosystem:
223
+
224
+ - **@fjell/registry**: Service location and dependency injection
225
+ - **@fjell/cache**: High-performance caching with key-based operations
226
+ - **@fjell/lib**: Database abstraction layers
227
+ - **@fjell/providers**: React state management
228
+ - **@fjell/client-api**: HTTP client utilities
229
+
230
+ Each integration maintains the same type safety and hierarchical key principles established in Fjell Core.