@xeno-js/core 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 Xeno
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,417 @@
1
+ <div align="center">
2
+ <img src="logo/logo.png" alt="Xeno Logo" width="140" />
3
+
4
+ <h1>Xeno Core</h1>
5
+
6
+ <p><em>Enterprise-grade DDD & CQRS framework for Node.js</em></p>
7
+
8
+ <p>
9
+ <a href="https://github.com/xeno-js/xeno-js">
10
+ <img src="https://img.shields.io/badge/Powered%20by-Xeno-blueviolet?style=flat-square" alt="Powered by Xeno" />
11
+ </a>
12
+ <a href="https://github.com/xeno-js/xeno-js/blob/main/LICENSE">
13
+ <img src="https://img.shields.io/npm/l/@xeno?style=flat-square" alt="License: ISC" />
14
+ </a>
15
+ <a href="https://www.npmjs.com/package/@xeno/core">
16
+ <img src="https://img.shields.io/npm/v/@xeno/core?style=flat-square" alt="NPM Version" />
17
+ </a>
18
+ <a href="https://buymeacoffee.com/xenojs">
19
+ <img src="https://img.shields.io/badge/Buy%20Me%20A%20Coffee-Support-FFdd00?style=flat-square&logo=buy-me-a-coffee&logoColor=black" alt="Buy Me A Coffee" />
20
+ </a>
21
+ </p>
22
+ </div>
23
+
24
+ ---
25
+
26
+ ## What is Xeno?
27
+
28
+ **Xeno** is an enterprise-grade, runtime-agnostic architectural framework for
29
+ Node.js built natively with TypeScript. It provides structural primitives for
30
+ implementing robust **Domain-Driven Design (DDD)** and **Command Query
31
+ Responsibility Segregation (CQRS)** patterns. By shifting operational logic away
32
+ from delivery mechanisms and transport frameworks, Xeno ensures your core
33
+ application architecture remains pristine, testable, and completely isolated
34
+ from external infrastructural churn.
35
+
36
+ ---
37
+
38
+ ## 💡 Why Choose Xeno?
39
+
40
+ Modern Node.js frameworks often tie business workflows tightly to HTTP server
41
+ abstractions or rely heavily on experimental language features. Xeno fixes this
42
+ with an emphasis on developer experience, type safety, and clean separation of
43
+ concerns.
44
+
45
+ - **Zero Decorators**: Xeno eliminates reliance on experimental or unstable TS
46
+ decorator specifications (`reflect-metadata`). The IoC container
47
+ (`ServiceContainer`) uses pure, explicit functional factories that optimize
48
+ compilation speeds and eliminate runtime black-box behaviors.
49
+ - **Complete Server Decoupling**: Xeno does not care if you use Fastify, Hono,
50
+ Express, Koa, or AWS Lambda. The presentation layer handles incoming data
51
+ using plain, primitive contracts, making migration or multi-runtime hosting
52
+ completely seamless.
53
+ - **Pay-For-What-You-Use (Opt-in Modularity)**: Core dependencies are
54
+ strategically classified as optional peer dependencies. If your architecture
55
+ doesn't use Redis, Sentry, or Supabase, you do not pull them into your node
56
+ modules.
57
+ - **Enterprise-Grade Resiliency & Cross-Cutting Pipelines**: Address complex
58
+ distributed patterns natively without code duplication. Xeno provides
59
+ out-of-the-box composite behaviors:
60
+ - **Idempotency**: Implements multi-tenant logic keyspaces matching advanced
61
+ SaaS factory patterns for logical partitioning.
62
+ - **Concurrency Control**: Mitigates thundering herd impacts via advanced
63
+ backoff retry strategies coupled with randomized jitter.
64
+ - **Resilience Policies**: Deep integration with circuit breakers, bulkheads,
65
+ and fallbacks.
66
+ - **Deterministic Type Safety**: Strong infrastructure validation strategies
67
+ using Zod schemas.
68
+
69
+ ---
70
+
71
+ ## 📖 Documentation & Getting Started
72
+
73
+ To explore the architecture, programmatic configurations, and extension
74
+ workflows of Xeno, read the full technical manuals located inside the main
75
+ documentation hub:
76
+
77
+ - **[Framework Documentation Repository](https://www.xeno-js.it/introduction)**
78
+
79
+ Inside, you will find exhaustive, step-by-step assembly guides covering core
80
+ host building (`AppBuilder`), isolated request middleware lifecycles, functional
81
+ `Result` monads, and zero-trust authorization pipeline behavior tracks.
82
+
83
+ ---
84
+
85
+ ## 🚀 Live Executable Demos
86
+
87
+ Want to see how Xeno works? Check out the functional example application
88
+ showcasing end-to-end command/query segregation, multi-tenant databases, and
89
+ resilient schema handling.
90
+
91
+ You can dive straight into the explicit source code modules of specialized
92
+ sandbox environments:
93
+
94
+ - **[`pipelines_middleware_demo/`](./demo/pipelines_middleware_demo/)**: Traces
95
+ an execution thread from the raw HTTP transport presentation layer, executing
96
+ automated header extraction and anchoring metadata variables into
97
+ `AsyncLocalStorage` thread boundaries.
98
+
99
+ ---
100
+
101
+ ## 📦 Installation
102
+
103
+ Install the core package:
104
+
105
+ ```bash
106
+ npm install @xeno-js/core
107
+
108
+ ```
109
+
110
+ Xeno uses **Optional Peer Dependencies**. You only install the external
111
+ libraries you actually need. Node.js will strictly lazy-load only the modules
112
+ you enable in the configuration.
113
+
114
+ ```bash
115
+ # Example: Install tools only if you enable them in the builder
116
+ npm install zod pino cockatiel drizzle-orm
117
+
118
+ ```
119
+
120
+ ---
121
+
122
+ ## ⚡ Bootstrapping & Middleware Example
123
+
124
+ Below is an architectural example of how to configure the Xeno
125
+ `ServiceContainer`, load core modules, and process an incoming application
126
+ payload natively inside a server middleware wrapper.
127
+
128
+ ### 1. Initialize the Container and Configure Modules
129
+
130
+ ```typescript
131
+ import { AppBuilder, LOG_LEVEL, TOKENS, XenoRegistry } from '@xeno-js/core'
132
+ import { FindUserQueryHandler } from './user/cqrs/handlers/index'
133
+ import { FindUserController } from './user/controllers/index'
134
+ import { UserMapper } from './user/mappers/user.mapper'
135
+ import { UserWriteRepository } from './user/repositories/user-write.repository'
136
+ import { UserDataSource } from './user/datasources/user.datasource'
137
+
138
+ // Map your registry token with XenoRegistry<TSchemaDb, TExtension>
139
+ type MyRegistry = XenoRegistry<{ /** Your Db Schema here **/}, {
140
+ USER_MAPPER_TOKEN: UserMapper
141
+ USER_DS_TOKEN: UserDataSource
142
+ USER_REPOSITORY_TOKEN: UserWriteRepository
143
+ FIND_USER_QUERY_HANDLER_TOKEN: FindUserQueryHandler
144
+ FIND_USER_CONTROLLER_TOKEN: FindUserController
145
+ }>
146
+
147
+ // Create the root IoC container context
148
+ export const xeno = new AppBuilder<MyRegistry>()
149
+ // Configure middleware and only PUBLIC routes
150
+ .addMiddlewares(opts => {
151
+ opts.routeRegistry = {
152
+ '/api/user/:id': ['GET', 'UPDATE', 'DELETE'],
153
+ }
154
+ })
155
+ // Configure the CQRS pipeline
156
+ // Can register Policies for your intent
157
+ .addPipeline((config) => {
158
+ config.authorization.policies = {
159
+ 'FIND_USER_QUERY_HANDLER_TOKEN': {
160
+ // Add authz by user id
161
+ userId: true
162
+ // Add authz by tenant id
163
+ tenantId: true
164
+ // Add authz by roles
165
+ roles: ['admin']
166
+ // Add authz by perissions
167
+ permissions: ['read'],
168
+ }
169
+ }
170
+ // Can add idempotency pipeline for command
171
+ config.commandBus.idempotency = { lockTtlSeconds: 30, processedTtlSeconds: 60 }
172
+ // Can add concurrency pipeline for command
173
+ config.commandBus.concurrency = { delayConfig: { baseDelayMs: 100, maxJitterMs: 500 }, maxRetries: 3 }
174
+ // Can add caching pipeline for query
175
+ config.queryBus.isEnabled = true
176
+ })
177
+ // Configure Database with drizzle
178
+ .addDb((opts, config) => {
179
+ opts.connectionString = config.getOrThrow('DATABASE_URL')
180
+ })
181
+ // Configure Authentication with supabase
182
+ .addAuth((opts, config) => {
183
+ opts.key = 'demo-key'
184
+ opts.url = config.getOrThrow('API_BASE_URL')
185
+ })
186
+ // Configure your logger (e.g. Console, Sentry, Pino or custom logger)
187
+ .addLogger((config) => {
188
+ config.level = LOG_LEVEL.INFO
189
+ config.console = true
190
+ })
191
+ // Register your services
192
+ .addServices((services) => {
193
+ // REGISTER MAPPER
194
+ services.addScoped('USER_MAPPER_TOKEN', () => new UserMapper())
195
+
196
+ // REGISTER DATASOURCES
197
+ services.addScoped('USER_DS_TOKEN', (c) => new UserDataSource(c.resolve(TOKENS.DB_CONTEXT)))
198
+
199
+ // REGISTER REPOSITORIES
200
+ services.addScoped('USER_REPOSITORY_TOKEN', (c) => new UserWriteRepository(c.resolve('USER_DS_TOKEN'), c.resolve('USER_MAPPER_TOKEN')))
201
+
202
+ // REGISTER HANDLERS
203
+ services.addScoped('FIND_USER_QUERY_HANDLER_TOKEN', (c) => {
204
+ const requestcontext = c.resolve('USER_CONTEXT_FACTORY')
205
+ const repository = c.resolve('USER_READ_REPOSITORY')
206
+ return new FindUserQueryHandler(repository, requestcontext)
207
+ })
208
+
209
+ // REGISTER CONTROLLERS
210
+ services.addTransient('FIND_USER_CONTROLLER_TOKEN', (c) => {
211
+ return new FindUserController(c.resolve(TOKENS.CONTEXT_ACCESSOR), c.resolve(TOKENS.MEDIATOR))
212
+ })
213
+ })
214
+
215
+ ```
216
+
217
+ ### 2. Wrap and Run within Server Middleware (e.g., Fastify / Hono)
218
+
219
+ ```typescript
220
+ import 'dotenv/config'
221
+ import { ContainerUtils, TOKENS } from '@xeno-js/core'
222
+ import fastify from 'fastify'
223
+ import { bootstrap } from './bootstrap'
224
+
225
+ async function runDemo() {
226
+ console.log('⚙️ Initialized Xeno Container...')
227
+ try {
228
+ // 1. Bootstrap the application and get the service container
229
+ const xenoApp = await bootstrap.build()
230
+
231
+ console.log('🚀 Starting Fastify server on http://localhost:3000...')
232
+
233
+ // 2. Resolve the middleware from the container
234
+ const middleware = xeno.resolve(TOKENS.MIDDLEWARE)
235
+ // 3. Create a Fastify instance to handle HTTP requests
236
+ const app = fastify()
237
+
238
+ // ─── ENDPOINT 2: QUERY ────────────────────────────────────────────
239
+ app.get('/api/user/:id', async (request, reply) => {
240
+ // 4. Execute the middleware to handle the request context and authentication, then call the StatusController's handle method with the request payload.
241
+ const responseDto = await middleware.execute(
242
+ {
243
+ path: '/api/user/:id',
244
+ method: 'GET',
245
+ transport: { res: reply, req: request },
246
+ },
247
+ { ...request.headers },
248
+ async () => {
249
+ const { id } = request.params as any
250
+ const controller = ContainerUtils.resolveServiceScoped(
251
+ 'FIND_USER_CONTROLLER_TOKEN',
252
+ xenoApp,
253
+ )
254
+ return await controller.handle({ id: id ?? '123' })
255
+ },
256
+ )
257
+
258
+ return reply
259
+ .status(responseDto.status)
260
+ .type('application/json')
261
+ .send(responseDto.data)
262
+ })
263
+
264
+ console.log('✅ Routes set up. Ready to accept requests.')
265
+
266
+ // ─── START SERVER ─────────────────────────────────────────────────
267
+ try {
268
+ await app.listen({ port: 3000 })
269
+ console.log('🚀 Application running on http://localhost:3000')
270
+ console.log('👉 GET /api/user/:id (GET: api/user/1)')
271
+ } catch (err) {
272
+ console.error('Error starting Fastify server:', err)
273
+ app.log.error(err)
274
+ process.exit(1)
275
+ }
276
+ } catch (error) {
277
+ console.error('Error during bootstrap or server setup:', error)
278
+ process.exit(1)
279
+ }
280
+ }
281
+
282
+ runDemo()
283
+ ```
284
+
285
+ ---
286
+
287
+ ## 🛠 Scaffold your project with CLI
288
+
289
+ Xeno includes an official CLI tool, `@xeno-js/cli`, designed to bootstrap your
290
+ new application in seconds. It offers an interactive setup to select exactly the
291
+ modules you need (Database, HTTP, Auth, Logging, etc.), ensuring you start with
292
+ a clean, pre-configured architecture tailored to your specific requirements.
293
+
294
+ If you want to learn how to use it, see the full options available, or
295
+ understand how the scaffolding engine works, check the
296
+ **[CLI Documentation](https://www.xeno-js.it/cli/overview)**.
297
+
298
+ ---
299
+
300
+ ## 🤝 For Contributors
301
+
302
+ We welcome contributions to Xeno! To maintain the highest code quality and
303
+ stability of the core framework, **direct pushes to the `main` and `develop`
304
+ branches are strictly prohibited.** Please follow this Git Flow to contribute:
305
+
306
+ 1. **Branch off from `develop`**: Create a new branch for your feature or
307
+ bugfix.
308
+
309
+ ```bash
310
+ git checkout develop
311
+ git pull origin develop
312
+ git checkout -b feat/your-awesome-feature
313
+ ```
314
+
315
+ 2. **Make your changes**: Write your code and ensure it passes all local checks
316
+ (linting, types, and tests).
317
+
318
+ ```bash
319
+ npm run check
320
+ ```
321
+
322
+ 3. **Commit your changes**: We enforce
323
+ [Conventional Commits](https://www.conventionalcommits.org/). Husky will
324
+ verify your commit message format.
325
+
326
+ 4. **Commit Format:**
327
+
328
+ ```bash
329
+ feat(scope): add new feature
330
+ fix(scope): resolve bug
331
+ chore(scope): update dependencies
332
+ ```
333
+
334
+ 5. **Submit a Pull Request (PR)**: Push your branch to GitHub and open a Pull
335
+ Request targeting the **`develop`** branch.
336
+
337
+ 6. **Review**: The repository owner will review your code, run pipeline tests,
338
+ and merge it into `develop`.
339
+
340
+ _Note: The `main` branch is strictly reserved for production releases. Code
341
+ flows from feature branches ➡️ `develop` ➡️ `main`._
342
+
343
+ ### Scripts
344
+
345
+ | Command | Description |
346
+ | ----------------------- | ---------------------------------------------- |
347
+ | `npm run build` | Builds the TypeScript source code into `dist/` |
348
+ | `npm run typecheck` | Checks types without emitting files |
349
+ | `npm run lint` | Runs ESLint |
350
+ | `npm run format` | Formats code with Prettier |
351
+ | `npm run test` | Runs the Vitest test suite |
352
+ | `npm run test:coverage` | Runs tests and generates a coverage report |
353
+
354
+ ### Code Quality (Husky & Git Hooks)
355
+
356
+ This project strictly enforces code quality rules before pushing to the
357
+ repository:
358
+
359
+ - **`pre-commit`**: Runs `lint-staged` on staged files (ESLint + Prettier).
360
+ - **`commit-msg`**: Checks commit messages with `commitlint` (we use
361
+ Conventional Commits).
362
+ - **`pre-push`**: Runs type checking, linting, and testing before code leaves
363
+ your machine.
364
+
365
+ ---
366
+
367
+ ## 🌱 Support & Appreciation
368
+
369
+ Building, benchmarking, and maintaining a progressive, enterprise-ready
370
+ open-source framework requires a massive amount of continuous dedication and
371
+ architectural engineering.
372
+
373
+ If Xeno has brought value to your development workflows, helped decouple your
374
+ core business logic, or simplified your system infrastructure layout, consider
375
+ supporting its open-source lifecycle. Your backing directly accelerates our
376
+ strategic roadmap for new out-of-the-box transport integrations (such as gRPC,
377
+ RabbitMQ, and GraphQL) and keeps the documentation pristine.
378
+
379
+ **Want to know how you can contribute or sponsor Xeno?** We rely on the
380
+ commitment of our community to keep the project independent and thriving.
381
+ Whether you are an individual developer or a business using Xeno, your support
382
+ makes a real difference.
383
+
384
+ 👉
385
+ **[Read our support guidelines and find out how to help](https://www.xeno-js.it/support-us)**
386
+
387
+ Thank you for being part of this decoupled open-source journey!
388
+
389
+ <amp-bounce>
390
+ </amp-bounce>
391
+ <a href="https://www.buymeacoffee.com/xenojs" target="_blank">
392
+ <img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" height="42" style="height: 42px !important;" />
393
+ </a>
394
+
395
+ ---
396
+
397
+ ## 🛡️ Powered by Xeno
398
+
399
+ If you are using Xeno in your project, let the world know! Add this badge to
400
+ your README:
401
+
402
+ ```html
403
+ <a
404
+ href="[https://github.com/xeno-js/xeno-js](https://github.com/xeno-js/xeno-js)"
405
+ target="_blank"
406
+ >
407
+ <img
408
+ src="[https://img.shields.io/badge/Powered%20by-Xeno-black?style=flat-square](https://img.shields.io/badge/Powered%20by-Xeno-black?style=flat-square)"
409
+ alt="Powered by Xeno"
410
+ height="20"
411
+ />
412
+ </a>
413
+ ```
414
+
415
+ ## 📄 License
416
+
417
+ Copyright (c) 2026 Xeno. Licensed under the [ISC License](LICENSE).