@coherent.js/runtime 1.0.0-beta.2

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.
package/README.md ADDED
@@ -0,0 +1,1119 @@
1
+ # πŸš€ Coherent.js
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@coherent.js/core/beta.svg)](https://www.npmjs.com/package/@coherent.js/core)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@coherent.js/core.svg)](https://www.npmjs.com/package/@coherent.js/core)
5
+ [![Beta Status](https://img.shields.io/badge/status-beta-orange.svg)](https://github.com/Tomdrouv1/coherent.js)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
+ [![GitHub stars](https://img.shields.io/github/stars/Tomdrouv1/coherent.js.svg)](https://github.com/Tomdrouv1/coherent.js/stargazers)
8
+
9
+ A high-performance JavaScript framework for building modern web applications with a focus on speed, simplicity, and developer experience.
10
+
11
+ > **⚠️ Beta Release**: Coherent.js is currently in beta (v1.0.0-beta.1). The API is stable, but we're collecting feedback before the v1.0.0 stable release. Install with `npm install @coherent.js/core@beta`
12
+
13
+ ## ✨ Features
14
+
15
+ ### Core Framework
16
+
17
+ - **Lightweight & Fast**: Optimized for performance with minimal overhead
18
+ - **Component-Based**: Build reusable UI components with a simple API
19
+ - **Server-Side Rendering (SSR)**: Built-in SSR for better SEO and performance
20
+ - **Progressive Enhancement**: Graceful fallback to client-side rendering when needed
21
+ - **State Management**: Built-in reactive state management
22
+ - **Routing**: Declarative client-side routing
23
+ - **Build Tooling**: Works with modern build tools like Vite and Webpack
24
+
25
+ ### 🎯 Features (v1.0.0-beta.1)
26
+
27
+ #### **Plugin System**
28
+ - Extensible plugin architecture with lifecycle hooks
29
+ - 7 built-in plugins (Performance, DevLogger, Analytics, Cache, ErrorRecovery, Validation, Hydration)
30
+ - Dependency resolution and priority-based execution
31
+ - 10+ lifecycle hooks for complete control
32
+
33
+ #### **Testing Utilities**
34
+ - Complete testing package with test renderer
35
+ - 15+ custom matchers for Coherent.js
36
+ - Event simulation and async testing utilities
37
+ - Mock functions and spies
38
+ - Snapshot testing support
39
+
40
+ #### **Error Boundaries**
41
+ - Production-ready error handling
42
+ - Custom fallback components
43
+ - Reset functionality and auto-recovery
44
+ - Async error boundaries
45
+ - Global error handler
46
+
47
+ #### **Developer Tools**
48
+ - Component inspector for structure analysis
49
+ - Performance profiler with session tracking
50
+ - Development logger with 6 log levels
51
+ - Real-time debugging and statistics
52
+
53
+ #### **Internationalization (i18n)**
54
+ - Complete translation system with interpolation
55
+ - Pluralization support (Intl.PluralRules)
56
+ - Date/Number/Currency/List formatters
57
+ - Automatic locale detection
58
+ - RTL language support
59
+
60
+ #### **Form Utilities**
61
+ - Comprehensive validation system
62
+ - 10+ built-in validators
63
+ - Form builder with auto-generation
64
+ - Field-level and form-level validation
65
+ - Touch tracking and error management
66
+
67
+ #### **SEO Optimization**
68
+ - Meta tag builder (Open Graph, Twitter Cards)
69
+ - XML sitemap generator
70
+ - JSON-LD structured data
71
+ - Automatic SEO optimization
72
+
73
+ #### **Performance Optimization**
74
+ - Code splitting with dynamic imports
75
+ - Advanced caching (LRU, LFU, FIFO)
76
+ - Lazy loading with Intersection Observer
77
+ - Memoization utilities
78
+ - Progressive image loading
79
+
80
+ ### Performance Highlights
81
+
82
+ - **Fast Hydration**: Efficient client-side hydration
83
+ - **Optimized Updates**: Smart re-rendering and DOM updates
84
+ - **Tree-shaking Support**: Only include what you use
85
+ - **Small Bundle Size**: Minimal footprint for faster loading
86
+ - **Smart Caching**: Multiple caching strategies built-in
87
+ - **Code Splitting**: Automatic route-based splitting
88
+
89
+ ## πŸ“¦ Packages
90
+
91
+ Coherent.js is distributed as a collection of packages. Click the badges to view on npm:
92
+
93
+ ### Core Packages
94
+
95
+ | Package | npm | Description |
96
+ |---------|-----|-------------|
97
+ | **@coherent.js/core** | [![npm](https://img.shields.io/npm/v/@coherent.js/core/beta.svg)](https://www.npmjs.com/package/@coherent.js/core) | Core framework with component system and state management |
98
+ | **@coherent.js/client** | [![npm](https://img.shields.io/npm/v/@coherent.js/client/beta.svg)](https://www.npmjs.com/package/@coherent.js/client) | Client-side hydration and browser utilities |
99
+ | **@coherent.js/runtime** | [![npm](https://img.shields.io/npm/v/@coherent.js/runtime/beta.svg)](https://www.npmjs.com/package/@coherent.js/runtime) | Enhanced runtimes (Node.js, Edge) |
100
+
101
+ ### Framework Integrations
102
+
103
+ | Package | npm | Description |
104
+ |---------|-----|-------------|
105
+ | **@coherent.js/express** | [![npm](https://img.shields.io/npm/v/@coherent.js/express/beta.svg)](https://www.npmjs.com/package/@coherent.js/express) | Express.js integration |
106
+ | **@coherent.js/fastify** | [![npm](https://img.shields.io/npm/v/@coherent.js/fastify/beta.svg)](https://www.npmjs.com/package/@coherent.js/fastify) | Fastify integration |
107
+ | **@coherent.js/koa** | [![npm](https://img.shields.io/npm/v/@coherent.js/koa/beta.svg)](https://www.npmjs.com/package/@coherent.js/koa) | Koa.js integration |
108
+ | **@coherent.js/nextjs** | [![npm](https://img.shields.io/npm/v/@coherent.js/nextjs/beta.svg)](https://www.npmjs.com/package/@coherent.js/nextjs) | Next.js integration |
109
+ | **@coherent.js/adapters** | [![npm](https://img.shields.io/npm/v/@coherent.js/adapters/beta.svg)](https://www.npmjs.com/package/@coherent.js/adapters) | Adapters for Astro, Remix, SvelteKit |
110
+
111
+ ### Developer Tools
112
+
113
+ | Package | npm | Description |
114
+ |---------|-----|-------------|
115
+ | **@coherent.js/devtools** | [![npm](https://img.shields.io/npm/v/@coherent.js/devtools/beta.svg)](https://www.npmjs.com/package/@coherent.js/devtools) | Developer tools (inspector, profiler, logger) |
116
+ | **@coherent.js/testing** | [![npm](https://img.shields.io/npm/v/@coherent.js/testing/beta.svg)](https://www.npmjs.com/package/@coherent.js/testing) | Complete testing utilities and matchers |
117
+ | **@coherent.js/cli** | [![npm](https://img.shields.io/npm/v/@coherent.js/cli/beta.svg)](https://www.npmjs.com/package/@coherent.js/cli) | CLI tools for scaffolding and development |
118
+
119
+ ### Feature Packages
120
+
121
+ | Package | npm | Description |
122
+ |---------|-----|-------------|
123
+ | **@coherent.js/i18n** | [![npm](https://img.shields.io/npm/v/@coherent.js/i18n/beta.svg)](https://www.npmjs.com/package/@coherent.js/i18n) | Full internationalization support |
124
+ | **@coherent.js/forms** | [![npm](https://img.shields.io/npm/v/@coherent.js/forms/beta.svg)](https://www.npmjs.com/package/@coherent.js/forms) | Form utilities and validation |
125
+ | **@coherent.js/seo** | [![npm](https://img.shields.io/npm/v/@coherent.js/seo/beta.svg)](https://www.npmjs.com/package/@coherent.js/seo) | SEO optimization tools |
126
+ | **@coherent.js/performance** | [![npm](https://img.shields.io/npm/v/@coherent.js/performance/beta.svg)](https://www.npmjs.com/package/@coherent.js/performance) | Performance optimization utilities |
127
+ | **@coherent.js/state** | [![npm](https://img.shields.io/npm/v/@coherent.js/state/beta.svg)](https://www.npmjs.com/package/@coherent.js/state) | Reactive state management |
128
+
129
+ ### Backend & Database
130
+
131
+ | Package | npm | Description |
132
+ |---------|-----|-------------|
133
+ | **@coherent.js/api** | [![npm](https://img.shields.io/npm/v/@coherent.js/api/beta.svg)](https://www.npmjs.com/package/@coherent.js/api) | API framework with validation and OpenAPI |
134
+ | **@coherent.js/database** | [![npm](https://img.shields.io/npm/v/@coherent.js/database/beta.svg)](https://www.npmjs.com/package/@coherent.js/database) | Database layer with multiple adapters |
135
+
136
+ ### Build Tools
137
+
138
+ | Package | npm | Description |
139
+ |---------|-----|-------------|
140
+ | **@coherent.js/build-tools** | [![npm](https://img.shields.io/npm/v/@coherent.js/build-tools/beta.svg)](https://www.npmjs.com/package/@coherent.js/build-tools) | Build optimization and bundling utilities |
141
+ | **@coherent.js/profiler** | [![npm](https://img.shields.io/npm/v/@coherent.js/profiler/beta.svg)](https://www.npmjs.com/package/@coherent.js/profiler) | Performance profiling and monitoring |
142
+ | **@coherent.js/web-components** | [![npm](https://img.shields.io/npm/v/@coherent.js/web-components/beta.svg)](https://www.npmjs.com/package/@coherent.js/web-components) | Web Components integration |
143
+
144
+ ## πŸš€ Getting Started
145
+
146
+ ### Installation
147
+
148
+ ```bash
149
+ # Using npm
150
+ npm install @coherent.js/core@beta
151
+
152
+ # Using yarn
153
+ yarn add @coherent.js/core@beta
154
+
155
+ # Using pnpm
156
+ pnpm add @coherent.js/core@beta
157
+ ```
158
+
159
+ > **Note**: Coherent.js is currently in beta (v1.0.0-beta.1). Use the `@beta` tag to install the latest beta version.
160
+
161
+ ### Development Installation
162
+
163
+ To contribute or test the framework locally:
164
+
165
+ ```bash
166
+ git clone https://github.com/Tomdrouv1/coherent.js.git
167
+ cd coherent.js
168
+ pnpm install
169
+ pnpm build
170
+ pnpm test
171
+ ```
172
+
173
+ ### Basic Usage
174
+
175
+ ```javascript
176
+ // App.js - Using pure JavaScript objects (no JSX needed!)
177
+ import { createComponent } from '@coherent.js/core';
178
+
179
+ export const Counter = createComponent(({ initialCount = 0 }) => {
180
+ let count = initialCount;
181
+
182
+ return {
183
+ div: {
184
+ className: 'counter',
185
+ children: [
186
+ { h2: { text: `Count: ${count}` } },
187
+ {
188
+ button: {
189
+ text: 'Increment',
190
+ onclick: () => {
191
+ count++;
192
+ // Re-render logic handled by framework
193
+ }
194
+ }
195
+ }
196
+ ]
197
+ }
198
+ };
199
+ });
200
+
201
+ // Client-side hydration
202
+ import { hydrate } from '@coherent.js/client';
203
+ import { Counter } from './App.js';
204
+
205
+ hydrate(Counter({ initialCount: 0 }), document.getElementById('app'));
206
+ ```
207
+
208
+ ### Server-Side Rendering (SSR)
209
+
210
+ ```js
211
+ // server.js
212
+ import { render } from '@coherent.js/core';
213
+ import { Counter } from './App.js';
214
+
215
+ const html = render(Counter({ initialCount: 5 }));
216
+ // Send this HTML to the client
217
+ ```
218
+
219
+ ## πŸ”Œ API Framework
220
+
221
+ Coherent.js includes a comprehensive API framework for building REST, RPC, and GraphQL APIs:
222
+
223
+ - **API Router**: Lightweight routing system with all HTTP methods
224
+ - **Validation**: Schema-based request validation with JSON Schema
225
+ - **Error Handling**: Standardized error classes and global error handling
226
+ - **Serialization**: Automatic serialization of complex data types (Date, Map, Set)
227
+ - **OpenAPI**: Automatic OpenAPI 3.0 documentation generation with Swagger UI
228
+ - **Middleware**: Extensible middleware system for authentication, logging, CORS, etc.
229
+ - **Adapters**: Pre-built adapters for REST, RPC, and GraphQL patterns
230
+
231
+ ## πŸ“¦ Installation
232
+
233
+ ```bash
234
+ # Core package (required)
235
+ npm install @coherent.js/core@beta
236
+
237
+ # Framework integrations (choose what you need)
238
+ npm install @coherent.js/express@beta # Express.js integration
239
+ npm install @coherent.js/fastify@beta # Fastify integration
240
+ npm install @coherent.js/koa@beta # Koa integration
241
+ npm install @coherent.js/nextjs@beta # Next.js integration
242
+
243
+ # Additional packages
244
+ npm install @coherent.js/api@beta # API framework utilities
245
+ npm install @coherent.js/database@beta # Database layer with multiple adapters
246
+ npm install @coherent.js/client@beta # Client-side hydration
247
+ ```
248
+
249
+ ### Available Packages
250
+
251
+ - `@coherent.js/core` - Core framework with component system and state management
252
+ - `@coherent.js/api` - API framework with validation, OpenAPI generation, and error handling
253
+ - `@coherent.js/database` - Database layer with PostgreSQL, MySQL, SQLite, MongoDB adapters
254
+ - `@coherent.js/client` - Client-side hydration and progressive enhancement
255
+ - `@coherent.js/express` - Express.js integration
256
+ - `@coherent.js/fastify` - Fastify integration
257
+ - `@coherent.js/koa` - Koa.js integration
258
+ - `@coherent.js/nextjs` - Next.js integration
259
+
260
+ ## πŸš€ Quick Start
261
+
262
+ ### 1. Create a Simple Component
263
+
264
+ ```javascript
265
+ // components/HelloWorld.js
266
+ import { createComponent } from '@coherent.js/core';
267
+
268
+ export const HelloWorld = createComponent(() => ({
269
+ div: {
270
+ className: 'hello',
271
+ children: [
272
+ { h1: { text: 'Hello, World!' } },
273
+ { p: { text: 'Welcome to Coherent.js' } }
274
+ ]
275
+ }
276
+ }));
277
+ ```
278
+
279
+ ### 2. Server-Side Rendering
280
+
281
+ ```js
282
+ // server.js
283
+ import express from 'express';
284
+ import { render } from '@coherent.js/core/ssr';
285
+ import { HelloWorld } from './components/HelloWorld';
286
+
287
+ const app = express();
288
+
289
+ app.get('/', (req, res) => {
290
+ const html = `
291
+ <!DOCTYPE html>
292
+ <html>
293
+ <head>
294
+ <title>Coherent.js App</title>
295
+ </head>
296
+ <body>
297
+ <div id="root">${render(HelloWorld())}</div>
298
+ <script src="/client.js" type="module"></script>
299
+ </body>
300
+ </html>
301
+ `;
302
+
303
+ res.send(html);
304
+ });
305
+
306
+ app.listen(3000, () => {
307
+ console.log('Server running on http://localhost:3000');
308
+ });
309
+ ```
310
+
311
+ ### 3. Client-Side Hydration
312
+
313
+ ```jsx
314
+ // client.js
315
+ import { hydrate, makeHydratable, autoHydrate } from '@coherent.js/client';
316
+ import { HelloWorld } from './components/HelloWorld';
317
+
318
+ // Method 1: Direct hydration
319
+ hydrate(HelloWorld, document.getElementById('root'));
320
+
321
+ // Method 2: Auto-hydration for multiple components
322
+ const HydratableHelloWorld = makeHydratable(HelloWorld);
323
+ autoHydrate({
324
+ HelloWorld: HydratableHelloWorld
325
+ });
326
+ ```
327
+
328
+ ## 🌊 Client-Side Hydration Guide
329
+
330
+ Coherent.js provides powerful client-side hydration capabilities to make server-rendered components interactive in the browser.
331
+
332
+ ### Basic Hydration Setup
333
+
334
+ For simple cases, directly hydrate a single component:
335
+
336
+ ```javascript
337
+ import { hydrate } from '@coherent.js/client';
338
+ import { MyComponent } from './components/MyComponent.js';
339
+
340
+ // Hydrate a component on page load
341
+ document.addEventListener('DOMContentLoaded', () => {
342
+ const rootElement = document.getElementById('app');
343
+ if (rootElement) {
344
+ hydrate(rootElement, MyComponent, { initialProps: {} });
345
+ }
346
+ });
347
+ ```
348
+
349
+ ### State Management with Hydration
350
+
351
+ For components with state management using `withState`:
352
+
353
+ ```javascript
354
+ // components/Counter.js
355
+ import { withState } from '@coherent.js/core';
356
+
357
+ const CounterComponent = withState({
358
+ count: 0
359
+ }, {
360
+ debug: true
361
+ });
362
+
363
+ const CounterView = (props) => {
364
+ const { state, stateUtils } = props;
365
+ const { setState } = stateUtils;
366
+
367
+ const increment = () => {
368
+ setState({ count: state.count + 1 });
369
+ };
370
+
371
+ return {
372
+ div: {
373
+ className: 'counter',
374
+ 'data-coherent-component': 'counter',
375
+ children: [
376
+ { h2: { text: `Count: ${state.count}` } },
377
+ {
378
+ button: {
379
+ id: 'increment-btn',
380
+ text: 'Increment',
381
+ onclick: increment
382
+ }
383
+ }
384
+ ]
385
+ }
386
+ };
387
+ };
388
+
389
+ export const Counter = CounterComponent(CounterView);
390
+ ```
391
+
392
+ ### Auto-Hydration for Multiple Components
393
+
394
+ For pages with multiple interactive components:
395
+
396
+ ```javascript
397
+ // hydration.js
398
+ import { makeHydratable, autoHydrate } from '@coherent.js/client';
399
+ import { Counter } from './components/Counter.js';
400
+ import { TodoList } from './components/TodoList.js';
401
+
402
+ // Make components hydratable
403
+ const HydratableCounter = makeHydratable(Counter);
404
+ const HydratableTodoList = makeHydratable(TodoList);
405
+
406
+ // Auto-hydrate all components on page load
407
+ document.addEventListener('DOMContentLoaded', () => {
408
+ autoHydrate({
409
+ counter: HydratableCounter,
410
+ todolist: HydratableTodoList
411
+ });
412
+ });
413
+ ```
414
+
415
+ ### Handling Event Listeners
416
+
417
+ Coherent.js automatically converts function event handlers to `data-action` attributes during SSR:
418
+
419
+ ```javascript
420
+ // Server renders this:
421
+ { button: { onclick: () => alert('Clicked!') } }
422
+ // Becomes: <button data-action="__coherent_action_123" data-event="click">
423
+
424
+ // Client-side hydration automatically reconnects these handlers
425
+ ```
426
+
427
+ ### Custom Hydration for Complex Cases
428
+
429
+ For complex interactive pages, you might need custom hydration logic:
430
+
431
+ ```javascript
432
+ // custom-hydration.js
433
+ async function setupPageHydration() {
434
+ // Wait for all scripts to load
435
+ await new Promise(resolve => {
436
+ if (document.readyState === 'complete') {
437
+ resolve();
438
+ } else {
439
+ window.addEventListener('load', resolve);
440
+ }
441
+ });
442
+
443
+ // Custom button mapping for specific pages
444
+ if (document.querySelector('[data-coherent-component="performance"]')) {
445
+ setupPerformancePageHandlers();
446
+ }
447
+
448
+ // Generic auto-hydration for other components
449
+ autoHydrate(componentRegistry);
450
+ }
451
+
452
+ function setupPerformancePageHandlers() {
453
+ const buttonMappings = [
454
+ { id: 'run-all-tests', handler: 'runPerformanceTests' },
455
+ { id: 'run-render-test', handler: 'runRenderingTest' },
456
+ { id: 'clear-results', handler: 'clearResults' }
457
+ ];
458
+
459
+ buttonMappings.forEach(mapping => {
460
+ const button = document.getElementById(mapping.id);
461
+ const handler = window[mapping.handler];
462
+
463
+ if (button && handler) {
464
+ // Remove any conflicting attributes
465
+ button.removeAttribute('data-action');
466
+ button.removeAttribute('data-event');
467
+
468
+ // Attach clean event listener
469
+ button.addEventListener('click', (e) => {
470
+ e.preventDefault();
471
+ handler();
472
+ });
473
+ }
474
+ });
475
+ }
476
+
477
+ // Initialize hydration
478
+ setupPageHydration();
479
+ ```
480
+
481
+ ### Best Practices for Hydration
482
+
483
+ 1. **Use data-coherent-component attributes** to identify components:
484
+ ```javascript
485
+ {
486
+ div: {
487
+ 'data-coherent-component': 'my-component',
488
+ className: 'my-component',
489
+ children: [...]
490
+ }
491
+ }
492
+ ```
493
+
494
+ 2. **Handle timing properly** - ensure DOM and scripts are loaded:
495
+ ```javascript
496
+ document.addEventListener('DOMContentLoaded', () => {
497
+ setTimeout(initHydration, 100); // Small delay for deferred scripts
498
+ });
499
+ ```
500
+
501
+ 3. **Clean up conflicting handlers** when needed:
502
+ ```javascript
503
+ // Remove server-rendered data-action attributes if they conflict
504
+ element.removeAttribute('data-action');
505
+ element.removeAttribute('data-event');
506
+ ```
507
+
508
+ 4. **Provide fallbacks** for when JavaScript is disabled:
509
+ ```javascript
510
+ // Server-rendered forms should work without JavaScript
511
+ {
512
+ form: {
513
+ action: '/api/submit',
514
+ method: 'POST',
515
+ onsubmit: enhancedSubmitHandler // Enhanced with JS
516
+ }
517
+ }
518
+ ```
519
+
520
+ ### Debugging Hydration Issues
521
+
522
+ Add debugging to understand what's happening:
523
+
524
+ ```javascript
525
+ console.log('🌊 Hydration starting...');
526
+ console.log('Available functions:', Object.keys(window).filter(k => typeof window[k] === 'function'));
527
+ console.log('Component elements:', document.querySelectorAll('[data-coherent-component]'));
528
+
529
+ // Enable debug mode for withState components
530
+ const ComponentWithDebug = withState({
531
+ // initial state
532
+ }, {
533
+ debug: true // Logs all state changes
534
+ });
535
+ ```
536
+
537
+ ## πŸ› οΈ API Framework
538
+
539
+ ### Basic API Endpoint
540
+
541
+ ```js
542
+ // api/users.js
543
+ import { createApiRouter, withValidation } from '@coherent.js/api';
544
+
545
+ const router = createApiRouter();
546
+
547
+ // Validation schema
548
+ const userSchema = {
549
+ type: 'object',
550
+ properties: {
551
+ name: { type: 'string', minLength: 1 },
552
+ email: { type: 'string', format: 'email' }
553
+ },
554
+ required: ['name', 'email']
555
+ };
556
+
557
+ // GET /api/users
558
+ router.get('/users', (req, res) => {
559
+ return { users: [] };
560
+ });
561
+
562
+ // POST /api/users
563
+ router.post('/users',
564
+ withValidation(userSchema),
565
+ (req, res) => {
566
+ const { name, email } = req.body;
567
+ // Create user logic here
568
+ return { user: { id: 1, name, email } };
569
+ }
570
+ );
571
+
572
+ export default router;
573
+ ```
574
+
575
+ ### API with Express.js
576
+
577
+ ```javascript
578
+ import express from 'express';
579
+ import apiRouter from './api-router.js'; // Your API router
580
+ import { createErrorHandler } from '@coherent/api';
581
+
582
+ const app = express();
583
+ app.use(express.json());
584
+
585
+ // Mount the API router
586
+ app.use('/api', apiRouter.toExpress());
587
+
588
+ // Global error handler
589
+ app.use(createErrorHandler());
590
+
591
+ app.listen(3000, () => {
592
+ console.log('API server running on http://localhost:3000');
593
+ });
594
+ ```
595
+
596
+ ## 🎯 Performance
597
+
598
+ ### Built-in Monitoring
599
+
600
+ ```javascript
601
+ import { performanceMonitor } from '@coherent.js/core';
602
+
603
+ performanceMonitor.start();
604
+
605
+ // Your rendering code here
606
+
607
+ const stats = performanceMonitor.generateReport();
608
+ console.log(stats);
609
+ ```
610
+
611
+ ### Memoization
612
+
613
+ ```javascript
614
+ import { memo } from '@coherent/core';
615
+
616
+ const ExpensiveComponent = memo(
617
+ (context) => {
618
+ // Expensive computation here
619
+ return { div: { text: computeResult(context.data) } };
620
+ },
621
+ (context) => context.data.id // Custom key function
622
+ );
623
+ ```
624
+
625
+ ### Streaming for Large Documents
626
+
627
+ ```javascript
628
+ import { renderToStream } from '@coherent/core';
629
+
630
+ const stream = renderToStream(largeComponent, context);
631
+
632
+ stream.on('data', (chunk) => {
633
+ response.write(chunk);
634
+ });
635
+
636
+ stream.on('end', () => {
637
+ response.end();
638
+ });
639
+ ```
640
+
641
+ ## πŸ“š Documentation
642
+
643
+ - [API Reference](docs/api-reference.md) - Complete documentation of all Coherent.js APIs
644
+ - [Migration Guide](docs/migration-guide.md) - Instructions for migrating from React, template engines, and string-based frameworks
645
+ - [Examples](examples) - Practical examples demonstrating various features
646
+
647
+ ### Using UI Components
648
+
649
+ Coherent.js uses a pure object syntax for defining components, making it intuitive and powerful:
650
+
651
+ ```javascript
652
+ import { createComponent, render } from '@coherent/core';
653
+
654
+ // Create a simple component
655
+ const Greeting = createComponent(({ name = 'World' }) => ({
656
+ div: {
657
+ className: 'greeting',
658
+ children: [
659
+ { h1: { text: `Hello, ${name}!` } },
660
+ { p: { text: 'Welcome to Coherent.js' } }
661
+ ]
662
+ }
663
+ }));
664
+
665
+ // Render the component
666
+ const html = render(Greeting({ name: 'Developer' }));
667
+ console.log(html);
668
+ ```
669
+
670
+ ### Using the API Framework
671
+
672
+ Coherent.js includes a powerful API framework for building REST APIs:
673
+
674
+ ```javascript
675
+ import { createApiRouter, withValidation } from '@coherent.js/api';
676
+
677
+ // Create an API router
678
+ const router = createApiRouter();
679
+
680
+ // Define a validation schema
681
+ const userSchema = {
682
+ type: 'object',
683
+ properties: {
684
+ name: { type: 'string', minLength: 1 },
685
+ email: { type: 'string', format: 'email' }
686
+ },
687
+ required: ['name', 'email']
688
+ };
689
+
690
+ // Define routes
691
+ router.get('/users', (req, res) => {
692
+ // Get all users
693
+ return { users: [] };
694
+ });
695
+
696
+ router.post('/users',
697
+ withValidation(userSchema),
698
+ (req, res) => {
699
+ // Create a new user
700
+ const { name, email } = req.body;
701
+ return { user: { id: 1, name, email } };
702
+ }
703
+ );
704
+
705
+ // Export for use with Express, Fastify, etc.
706
+ export default router;
707
+ ```
708
+
709
+ ### Integration with Express.js
710
+
711
+ ```javascript
712
+ // server.js
713
+ import express from 'express';
714
+ import apiRouter from './api.js';
715
+ import { createErrorHandler } from '@coherent.js/api';
716
+ import { setupCoherent, createCoherentHandler } from '@coherent.js/express';
717
+
718
+ const app = express();
719
+ app.use(express.json());
720
+
721
+ // Setup Coherent.js with Express
722
+ setupCoherent(app);
723
+
724
+ // Mount API routes
725
+ app.use('/api', apiRouter.toExpress());
726
+
727
+ // Error handling
728
+ app.use(createErrorHandler());
729
+
730
+ app.listen(3000, () => {
731
+ console.log('Server running on http://localhost:3000');
732
+ });
733
+ ```
734
+
735
+ ### Integration with Fastify
736
+
737
+ ```javascript
738
+ // server.js
739
+ import fastify from 'fastify';
740
+ import apiRouter from './api.js';
741
+ import { setupCoherent, createHandler } from '@coherent.js/fastify';
742
+
743
+ const app = fastify();
744
+
745
+ // Setup Coherent.js with Fastify
746
+ setupCoherent(app);
747
+
748
+ // Register API routes
749
+ app.register(apiRouter.toFastify());
750
+
751
+ app.listen({ port: 3000 }, (err, address) => {
752
+ if (err) {
753
+ console.error(err);
754
+ process.exit(1);
755
+ }
756
+ console.log(`Server running on ${address}`);
757
+ });
758
+ ```
759
+
760
+ ### Using in Another Project
761
+
762
+ To use Coherent.js in your own project:
763
+
764
+ 1. **Install the package**
765
+
766
+ ```bash
767
+ npm install @coherent.js/core
768
+ ```
769
+
770
+ 2. **Import and use components**
771
+
772
+ ```javascript
773
+ import { createComponent, render } from '@coherent.js/core';
774
+
775
+ const MyComponent = createComponent(({ message }) => ({
776
+ div: {
777
+ className: 'my-component',
778
+ children: [
779
+ { h2: { text: message } },
780
+ { p: { text: 'This is my Coherent.js component!' } }
781
+ ]
782
+ }
783
+ }));
784
+
785
+ const html = render(MyComponent({ message: 'Hello from Coherent.js!' }));
786
+ ```
787
+
788
+ 3. **API usage**
789
+
790
+ ```javascript
791
+ import { createApiRouter } from '@coherent.js/api';
792
+
793
+ // Create a new API router
794
+ const router = createApiRouter();
795
+
796
+ // Define a simple endpoint
797
+ router.get('/hello', (req, res) => {
798
+ return { message: 'Hello from Coherent.js API!' };
799
+ });
800
+
801
+ export default router;
802
+ ```
803
+
804
+ 4. **Express.js integration**
805
+
806
+ ```javascript
807
+ import express from 'express';
808
+ import { setupCoherent } from '@coherent/express';
809
+
810
+ const app = express();
811
+ setupCoherent(app);
812
+
813
+ // Now you can return Coherent.js components directly from routes
814
+ app.get('/', (req, res) => {
815
+ res.send({
816
+ html: {
817
+ children: [
818
+ { h1: { text: 'Hello from Coherent.js with Express!' } }
819
+ ]
820
+ }
821
+ });
822
+ });
823
+
824
+ app.listen(3000);
825
+ ```
826
+
827
+ 5. **Fastify integration**
828
+
829
+ ```javascript
830
+ import fastify from 'fastify';
831
+ import { setupCoherent } from '@coherent/fastify';
832
+
833
+ const app = fastify();
834
+ setupCoherent(app);
835
+
836
+ // Now you can return Coherent.js components directly from routes
837
+ app.get('/', (req, res) => {
838
+ return {
839
+ html: {
840
+ children: [
841
+ { h1: { text: 'Hello from Coherent.js with Fastify!' } }
842
+ ]
843
+ }
844
+ };
845
+ });
846
+
847
+ app.listen({ port: 3000 });
848
+ ```
849
+
850
+ ## πŸ—οΈ Object Structure
851
+
852
+ Coherent.js is built around pure JavaScript objects that represent HTML structures:
853
+
854
+ ```javascript
855
+ // Basic structure
856
+ {
857
+ tagName: {
858
+ attribute: 'value',
859
+ className: 'css-class',
860
+ text: 'Simple text content',
861
+ html: '<raw>HTML content</raw>',
862
+ children: [/* Array of child elements */]
863
+ }
864
+ }
865
+ ```
866
+
867
+ ### Special Properties
868
+
869
+ - `text` - Escaped text content
870
+ - `html` - Unescaped HTML content
871
+ - `children` - Array of child elements
872
+ - `className` - Converted to `class` attribute
873
+ - `htmlFor` - Converted to `for` attribute
874
+
875
+ ### Examples
876
+
877
+ ```javascript
878
+ // Simple element with text
879
+ { h1: { text: 'Page Title' } }
880
+ // β†’ <h1>Page Title</h1>
881
+
882
+ // Element with attributes
883
+ { input: { type: 'text', placeholder: 'Enter name', required: true } }
884
+ // β†’ <input type="text" placeholder="Enter name" required>
885
+
886
+ // Nested elements
887
+ {
888
+ div: {
889
+ className: 'container',
890
+ children: [
891
+ { h2: { text: 'Section Title' } },
892
+ { p: { text: 'Some content here' } }
893
+ ]
894
+ }
895
+ }
896
+ // β†’ <div class="container"><h2>Section Title</h2><p>Some content here</p></div>
897
+
898
+ // Raw HTML (use with caution!)
899
+ { div: { html: '<strong>Bold</strong> text' } }
900
+ // β†’ <div><strong>Bold</strong> text</div>
901
+ ```
902
+
903
+ ## πŸ› οΈ Development
904
+
905
+ ### Running the Demo
906
+
907
+ ```bash
908
+ git clone https://github.com/your-username/coherent-js.git
909
+ cd coherent-js
910
+ pnpm install
911
+ pnpm run demo
912
+ ```
913
+
914
+ ### Project Structure
915
+
916
+ ```bash
917
+ coherent-framework/
918
+ β”œβ”€β”€ src/
919
+ β”‚ β”œβ”€β”€ coherent.js # Main entry point
920
+ β”‚ β”œβ”€β”€ core/ # Core utilities and helpers
921
+ β”‚ β”‚ β”œβ”€β”€ object-utils.js
922
+ β”‚ β”‚ β”œβ”€β”€ html-utils.js
923
+ β”‚ β”‚ └── validation.js
924
+ β”‚ β”œβ”€β”€ rendering/ # Rendering engines
925
+ β”‚ β”‚ β”œβ”€β”€ html-renderer.js
926
+ β”‚ β”‚ └── streaming-renderer.js
927
+ β”‚ β”œβ”€β”€ performance/ # Performance monitoring
928
+ β”‚ β”‚ └── monitor.js
929
+ β”‚ β”œβ”€β”€ components/ # Component system
930
+ β”‚ β”‚ └── component-system.js
931
+ β”‚ β”œβ”€β”€ client/ # Client-side hydration
932
+ β”‚ β”‚ └── client.js
933
+ β”‚ β”œβ”€β”€ express/ # Express.js integration
934
+ β”‚ β”‚ └── index.js
935
+ β”‚ β”œβ”€β”€ fastify/ # Fastify integration
936
+ β”‚ β”‚ └── index.js
937
+ β”‚ └── nextjs/ # Next.js integration
938
+ β”‚ └── index.js
939
+ β”œβ”€β”€ examples/ # Example applications
940
+ β”‚ β”œβ”€β”€ basic-usage.js
941
+ β”‚ β”œβ”€β”€ advanced-features.js
942
+ β”‚ β”œβ”€β”€ express-integration.js
943
+ β”‚ β”œβ”€β”€ fastify-integration.js
944
+ β”‚ β”œβ”€β”€ nextjs-integration.js
945
+ β”‚ β”œβ”€β”€ performance-test.js
946
+ β”‚ └── streaming-test.js
947
+ β”œβ”€β”€ docs/ # Documentation
948
+ β”‚ β”œβ”€β”€ api-reference.md
949
+ β”‚ └── migration-guide.md
950
+ β”œβ”€β”€ tests/ # Test suite
951
+ β”‚ └── rendering.test.js
952
+ β”œβ”€β”€ scripts/ # Development scripts
953
+ β”‚ └── dev-server.js
954
+ β”œβ”€β”€ package.json
955
+ β”œβ”€β”€ README.md
956
+ β”œβ”€β”€ LICENSE
957
+ β”œβ”€β”€ CONTRIBUTING.md
958
+ └── CHANGELOG.md
959
+ ```
960
+
961
+ ## Why Choose Coherent.js?
962
+
963
+ ### vs JSX/React SSR
964
+
965
+ - βœ… **No build step required** - Pure JavaScript, no compilation
966
+ - βœ… **Smaller bundle size** - Minimal overhead, maximum performance
967
+ - βœ… **Server-optimized** - Built specifically for SSR from ground up
968
+ - βœ… **Better debugging** - Full object visibility and inspection
969
+
970
+ ### vs Template Engines (Handlebars, Mustache, etc.)
971
+
972
+ - βœ… **Type-safe with IDE support** - Full autocomplete and error checking
973
+ - βœ… **Component composition** - Reusable, composable components
974
+ - βœ… **Performance monitoring** - Built-in optimization tools
975
+ - βœ… **Streaming support** - Handle large documents efficiently
976
+
977
+ ### vs Virtual DOM (React, Vue, etc.)
978
+
979
+ - βœ… **Faster rendering** - No diffing overhead
980
+ - βœ… **Smaller bundle size** - Minimal overhead, maximum performance
981
+ - βœ… **Server-optimized** - Built specifically for SSR from ground up
982
+ - βœ… **Better debugging** - Full object visibility and inspection
983
+
984
+ ### vs String Concatenation/Template Literals
985
+
986
+ - βœ… **Automatic HTML escaping** - Built-in XSS protection
987
+ - βœ… **Structured, maintainable code** - Clear object hierarchy
988
+ - βœ… **Component reusability** - DRY principle enforcement
989
+ - βœ… **Performance optimization** - Smart caching and memoization
990
+
991
+ ## πŸ”’ Security
992
+
993
+ Coherent.js includes built-in security features:
994
+
995
+ - **Automatic HTML escaping** - All text content is automatically escaped to prevent XSS attacks
996
+ - **XSS protection** by default for user-generated content
997
+ - **Safe attribute handling** with proper escaping
998
+ - **Void element validation** to prevent malformed HTML
999
+
1000
+ ```javascript
1001
+ // This is automatically escaped
1002
+ { p: { text: '<script>alert("xss")</script>' } }
1003
+ // β†’ <p>&lt;script&gt;alert("xss")&lt;/script&gt;</p>
1004
+ ## πŸš€ Performance Benchmarks
1005
+
1006
+ Coherent.js is designed for speed:
1007
+
1008
+ - **~2-5ms** average render time for typical components
1009
+ - **Sub-millisecond** rendering for cached components
1010
+ - **Memory efficient** with automatic garbage collection
1011
+ - **Streaming support** for large documents without memory issues
1012
+
1013
+ ### Benchmark Results (1000 requests)
1014
+
1015
+ | Server Configuration | Requests per Second | Comparison to Fastest |
1016
+ |---------------------|-------------------:|---------------------:|
1017
+ | Coherent.js API Server (HTTP/1.1) | 9,627.87 req/s | 100.0% (baseline) |
1018
+ | Node.js HTTP Server | 8,837.48 req/s | 91.8% (slower) |
1019
+ | Coherent.js API Server (HTTP/2) | 8,745.49 req/s | 90.8% (slower) |
1020
+ | Coherent.js API Server (Pure Node.js) | 7,997.86 req/s | 83.1% (slower) |
1021
+ | Express.js Server | 7,553.39 req/s | 78.5% (slower) |
1022
+
1023
+ ```javascript
1024
+ // Example performance monitoring output
1025
+ {
1026
+ totalRenders: 1247,
1027
+ averageRenderTime: 2.3,
1028
+ cacheHitRate: 78.5,
1029
+ memoryEfficiency: 94.2,
1030
+ recommendations: [
1031
+ {
1032
+ type: 'caching_opportunity',
1033
+ component: 'UserProfile',
1034
+ potentialSavings: '15ms per render'
1035
+ }
1036
+ ]
1037
+ }
1038
+ ```
1039
+
1040
+ ## πŸ—ΊοΈ Roadmap
1041
+
1042
+ ### Current Status: Beta (v1.0.0-beta.1)
1043
+
1044
+ **What's Complete:**
1045
+ - [x] Core object-to-HTML rendering
1046
+ - [x] Performance monitoring system
1047
+ - [x] Streaming support
1048
+ - [x] Component utilities (memo, compose, etc.)
1049
+ - [x] TypeScript definitions - Full type safety
1050
+ - [x] Client-side hydration - Progressive enhancement
1051
+ - [x] Framework integrations - Express, Fastify, Next.js adapters
1052
+ - [x] Comprehensive API documentation
1053
+ - [x] Plugin system with 7 built-in plugins
1054
+ - [x] Testing utilities and matchers
1055
+ - [x] Developer tools (inspector, profiler, logger)
1056
+ - [x] Internationalization (i18n) support
1057
+ - [x] Form utilities and validation
1058
+ - [x] SEO optimization tools
1059
+
1060
+ **In Progress:**
1061
+ - [ ] Collect beta user feedback
1062
+ - [ ] Performance optimizations based on real-world usage
1063
+ - [ ] Additional examples and tutorials
1064
+
1065
+ **Planned for v1.0.0 Stable:**
1066
+ - [ ] Production-ready stability
1067
+ - [ ] Comprehensive test coverage (>95%)
1068
+ - [ ] Performance benchmarks against other frameworks
1069
+ - [ ] Migration tools from React/Vue
1070
+
1071
+ **Future (v1.1.0+):**
1072
+ - [ ] IDE plugins - Syntax highlighting and autocomplete
1073
+ - [ ] Component library ecosystem - Reusable UI components
1074
+ - [ ] Advanced optimizations - Tree shaking, code splitting
1075
+ - [ ] Visual development tools
1076
+
1077
+ ## 🀝 Contributing
1078
+
1079
+ We welcome contributions! Here's how to get started:
1080
+
1081
+ 1. **Fork the repository**
1082
+ 2. **Create a feature branch**: `git checkout -b feature-name`
1083
+ 3. **Make your changes** and add tests
1084
+ 4. **Run the demo**: `pnpm run demo` to ensure everything works
1085
+ 5. **Submit a pull request**
1086
+
1087
+ ### Development Guidelines
1088
+
1089
+ - Follow the existing code style
1090
+ - Add tests for new features
1091
+ - Update documentation for API changes
1092
+ - Performance test significant changes
1093
+
1094
+ ### Issues and Discussions
1095
+
1096
+ - πŸ› **Bug reports**: Use GitHub Issues
1097
+ - πŸ’‘ **Feature requests**: Start a GitHub Discussion
1098
+ - ❓ **Questions**: Check existing issues or start a discussion
1099
+
1100
+ ## πŸ“„ License
1101
+
1102
+ MIT License - see [LICENSE](LICENSE) file for details.
1103
+
1104
+ ## πŸ“ž Support
1105
+
1106
+ - **Documentation**: This README and code examples
1107
+ - **GitHub Issues**: Bug reports and feature requests
1108
+ - **GitHub Discussions**: Questions and community support
1109
+ - **Email**: [thomas.drouvin@gmail.com](mailto:thomas.drouvin@gmail.com) (for security issues)
1110
+
1111
+ ---
1112
+
1113
+ <!-- CENTER_START -->
1114
+
1115
+ **Coherent.js** - Pure objects, pure performance, pure simplicity. πŸš€
1116
+
1117
+ [Get Started](#-quick-start) β€’ [API Reference](docs/api-reference.md) β€’ [Examples](examples/) β€’ [Contribute](#-contributing)
1118
+
1119
+ <!-- CENTER_END -->