@zenflux/core 0.1.17 → 0.1.19

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.
Files changed (2) hide show
  1. package/README.md +273 -0
  2. package/package.json +3 -3
package/README.md ADDED
@@ -0,0 +1,273 @@
1
+ # @zenflux/core
2
+
3
+ Core runtime layer for the ZenFlux ecosystem. It provides the building blocks for registering controllers, running commands (public, internal, RESTful), HTTP client helpers, logging, and lifecycle hooks that wire everything together.
4
+
5
+ ## Features
6
+ - Command registry with before/after hooks (data + UI) and cross-command triggers.
7
+ - Controller base that auto-registers public, internal, and RESTful commands.
8
+ - RESTful manager built on `fetch`, with pluggable error/response handlers.
9
+ - Lightweight logger class exposed via `zCore.classes.Logger`.
10
+ - Simple lifecycle helpers: `initialize`, `destroy`, `onAfterInitialize`.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ bun add @zenflux/core
16
+ ```
17
+
18
+ ## Quick start
19
+
20
+ ```ts
21
+ import Core, { initialize, managers, bases, commandBases } from "@zenflux/core";
22
+
23
+ initialize({
24
+ baseURL: "https://api.example.com",
25
+ requestInit: { credentials: "include" },
26
+ });
27
+
28
+ class UsersController extends bases.ControllerBase {
29
+ protected getRestful() {
30
+ return { GetUser };
31
+ }
32
+ }
33
+
34
+ class GetUser extends commandBases.CommandRestful {
35
+ static getName() {
36
+ return "users.get";
37
+ }
38
+ getEndpoint() {
39
+ return "/v1/users/{id}";
40
+ }
41
+ }
42
+
43
+ new UsersController();
44
+
45
+ const user = await managers.restful.get("users.get", { id: 42 });
46
+ ```
47
+
48
+ ### Lifecycle-aware hooks
49
+
50
+ ```ts
51
+ import { managers } from "@zenflux/core";
52
+
53
+ managers.commands.onAfter("users.get", (_args) => {
54
+ console.info("User fetched, refresh UI");
55
+ });
56
+
57
+ managers.commands.onAfterAffect("users.get", "analytics.track");
58
+ ```
59
+
60
+ ## REST handlers
61
+
62
+ You can intercept every REST call made through `managers.restful`:
63
+
64
+ ```ts
65
+ import { interfaces, managers } from "@zenflux/core";
66
+
67
+ const { E_RESPONSE_HANDLER_TYPE } = interfaces;
68
+
69
+ managers.restful.setHandler(E_RESPONSE_HANDLER_TYPE.ERROR_HANDLER, (error) => {
70
+ console.error("API error", error);
71
+ return false; // return true to swallow the error
72
+ });
73
+ ```
74
+
75
+ ## Configuration (initialize)
76
+ - `version` (string, required): usually pulled from `package.json`.
77
+ - `baseURL` (string, optional): prepended to every RESTful endpoint.
78
+ - `requestInit` (RequestInit, optional): defaults to `{ credentials: "include" }`; merged per request.
79
+
80
+ ## Command types at a glance
81
+ - `CommandPublic`: UI/data commands callable via `managers.commands.run()`.
82
+ - `CommandRestful`: wraps an HTTP call; use `managers.restful.get|create|update|delete()`.
83
+ - `CommandInternal`: internal orchestration; accessed through `managers.internal`.
84
+
85
+ ```ts
86
+ // Creating data via REST
87
+ await managers.restful.create("users.create", { name: "Ava" });
88
+
89
+ // Updating with PATCH
90
+ await managers.restful.update("users.update", { id: 5, name: "Ava B" });
91
+ ```
92
+
93
+ ### Public command example
94
+
95
+ ```ts
96
+ import { bases, commandBases } from "@zenflux/core";
97
+
98
+ class PostsController extends bases.ControllerBase {
99
+ protected getCommands() {
100
+ return { ListPosts };
101
+ }
102
+ }
103
+
104
+ class ListPosts extends commandBases.CommandPublic {
105
+ static getName() {
106
+ return "posts.list";
107
+ }
108
+
109
+ protected async apply() {
110
+ // use managers, services, or fetch directly
111
+ return [{ id: 1, title: "Hello" }];
112
+ }
113
+ }
114
+
115
+ new PostsController();
116
+ const posts = await managers.commands.run("posts.list");
117
+ ```
118
+
119
+ ## TypeScript & bundling
120
+ - ESM-first (`"type": "module"`); CJS builds available via `exports.default`.
121
+ - Deep imports for debugging are exposed in `exports` (e.g. `@zenflux/core/src/bases`).
122
+ - Types are shipped at `dist/zenflux-core.d.ts`.
123
+
124
+ ## Core concepts
125
+ - **Commands**: atomic units of work; can be public, internal, or RESTful.
126
+ - **Controllers**: group commands and register them with managers automatically.
127
+ - **Managers**: orchestrate command lookup, execution, hooks, and REST plumbing.
128
+ - **Logger**: structured logging with per-instance ids; available via `classes.Logger`.
129
+ - **Globals**: in dev, exported as `globalThis.zCore` for quick introspection.
130
+
131
+ ## API surface (cheat sheet)
132
+ - `managers.commands.run(name, args?, options?)` – execute public/internal commands.
133
+ - `managers.restful.get|create|update|delete(name, args?, options?)` – HTTP-backed commands.
134
+ - `managers.commands.onBefore / onAfter / onAfterOnce / onAfterAffect / onBeforeUI / onAfterUI` – hook orchestration.
135
+ - `managers.commands.getLogger()` – logger bound to the command manager.
136
+ - `bases.ControllerBase` – subclass and override `getCommands/getRestful/getInternal`.
137
+ - `classes.Logger` – lightweight logger; supports `startsWith`, `drop`, `log`, etc.
138
+
139
+ ## Command lifecycle (data + UI)
140
+ 1) `managers.*.run()` attaches the command instance and stores args.
141
+ 2) `onBefore` + `onBeforeUI` fire (UI hooks are kept separate).
142
+ 3) `apply()` inside your command executes (do your work here).
143
+ 4) `onAfter / onAfterUI` fire; `onAfterOnce` is consumed.
144
+ 5) `onAfterAffect` triggers dependent commands (fan-out).
145
+ 6) Command detaches; trace kept in `Commands.trace`.
146
+
147
+ ## REST handlers (types)
148
+ - `ERROR_HANDLER` – inspect/stop errors (return `true` to swallow).
149
+ - `RESPONSE_FILTER` – transform raw text before JSON parse.
150
+ - `RESPONSE_HANDLER` – inspect parsed data (return `true` to swallow).
151
+ Register via `managers.restful.setHandler(E_RESPONSE_HANDLER_TYPE.*, cb)`.
152
+
153
+ ### Internal command example
154
+
155
+ ```ts
156
+ import { bases, commandBases } from "@zenflux/core";
157
+
158
+ class SystemController extends bases.ControllerBase {
159
+ protected getInternal() {
160
+ return { WarmCache };
161
+ }
162
+ }
163
+
164
+ class WarmCache extends commandBases.CommandInternal {
165
+ static getName() {
166
+ return "system.warmCache";
167
+ }
168
+ protected async apply() {
169
+ // populate LRU, prime REST calls, etc.
170
+ return true;
171
+ }
172
+ }
173
+
174
+ new SystemController();
175
+ await managers.internal.run("system.warmCache");
176
+ ```
177
+
178
+ ## Controller checklist
179
+ - Define a controller per bounded context (e.g., Users, Billing).
180
+ - Implement `getCommands/getRestful/getInternal` returning plain object maps.
181
+ - Use `setupHooks` to wire UI/data hooks in one place.
182
+ - Keep RESTful commands thin—validation + endpoint, leave data shaping to callers.
183
+ - Prefer small, composable commands; fans out via `onAfterAffect`.
184
+
185
+ ## Configuration defaults
186
+ ```ts
187
+ initialize({
188
+ version: pkg.version,
189
+ baseURL: "http://localhost",
190
+ requestInit: { credentials: "include" },
191
+ });
192
+ ```
193
+
194
+ ## Performance & debugging
195
+ - Use `Commands.trace` to inspect recent command flow.
196
+ - Keep hooks side-effect free where possible; heavy work stays in commands.
197
+ - Logger spans (`startsWith`/`drop`) help spot slow sections.
198
+ - In dev, read `globalThis.zCore.managers` to poke running instances.
199
+
200
+ ## Known limitations
201
+ - No built-in retries/backoff for REST; add in your handlers.
202
+ - Hooks are synchronous; await inside callbacks if you need async chaining.
203
+ - Global `zCore` is exposed only in development builds.
204
+ - REST client assumes `fetch` is available (polyfill in Node if needed).
205
+
206
+ ## Folder map (high level)
207
+ - `src/bases` – abstract bases for objects, controllers, commands.
208
+ - `src/command-bases` – public/internal/RESTful command base classes.
209
+ - `src/managers` – command/REST/controller/internal managers + lifecycle.
210
+ - `src/clients` – HTTP client wrapper used by REST manager.
211
+ - `src/modules/logger` – logger implementation and config.
212
+ - `src/interfaces` – shared enums, types, and config contracts.
213
+
214
+ ## Error handling patterns
215
+ - REST: set `ERROR_HANDLER` to normalize API errors into domain objects; throw to bubble.
216
+ - Commands: throw your own error classes; subscribe with `onAfter` to centralize toast/UI.
217
+ - Controllers: validate args in `apply` and short-circuit with informative errors.
218
+ - `CommandNotFound` / `CommandAlreadyRegistered` guard misconfiguration early.
219
+
220
+ ## Logging tips
221
+ - Create one logger per service/command: `new classes.Logger(MyCommand)`.
222
+ - Use `startsWith` for timed spans and argument snapshots; `drop` to close them.
223
+ - In browsers, rely on `globalThis.zCore` to inspect `managers` and `Logger` output quickly.
224
+
225
+ ## Minimal setup (repo)
226
+ ```bash
227
+ # install deps
228
+ bun install
229
+ # build only core
230
+ bun run --filter @zenflux/core @z-core--build
231
+ # link locally in another package
232
+ bun link ./packages/zenflux-core
233
+ ```
234
+
235
+ ## Testing
236
+ - Unit/integration: `bun run --filter @zenflux/core @z-core--test`.
237
+ - Add new commands with small fixtures under `packages/zenflux-core/test`.
238
+ - Prefer deterministic tests; mock `fetch` for REST managers.
239
+
240
+ ## FAQ
241
+ - *Do I have to call `initialize`?* Yes—managers rely on it; call once at app boot.
242
+ - *Can I skip globals?* In production bundlers, `zCore` is not required; ignore it.
243
+ - *How do I extend logging?* Wrap `classes.Logger` or pipe its output to your collector.
244
+ - *Is CJS supported?* Yes via `exports.default`; ESM is the primary target.
245
+ - *Can I deep-import source files?* Yes for debugging via `@zenflux/core/src/*` paths.
246
+
247
+ ## Logging
248
+
249
+ ```ts
250
+ import { classes } from "@zenflux/core";
251
+
252
+ const logger = new classes.Logger(MyService);
253
+ logger.log("Ready"); // includes class name and unique instance id
254
+ ```
255
+
256
+ ## Lifecycle
257
+ - `initialize(config)` – sets up managers; config accepts `version`, optional `baseURL`, and `requestInit`.
258
+ - `destroy()` – clears managers and global state.
259
+ - `onAfterInitialize(cb)` – run a callback after core initialization.
260
+
261
+ ## Local development
262
+
263
+ Run from repo root:
264
+
265
+ ```bash
266
+ bun run --filter @zenflux/core @z-core--build # build
267
+ bun run --filter @zenflux/core @z-core--test # tests
268
+ bun run --filter @zenflux/core @z-core--dev # watch
269
+ ```
270
+
271
+ ---
272
+
273
+ While developing, `@zenflux/core` exposes itself as `globalThis.zCore` to aid debugging in environments without import tooling. Use it only for development tooling or debugging.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenflux/core",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "types": "dist/zenflux-core.d.ts",
5
5
  "type": "module",
6
6
  "files": [
@@ -32,7 +32,7 @@
32
32
  },
33
33
  "devDependencies": {
34
34
  "@jest/globals": "^29.7.0",
35
- "@zenflux/cli": "0.1.39"
35
+ "@zenflux/cli": "0.1.41"
36
36
  },
37
37
  "publishConfig": {
38
38
  "access": "public"
@@ -41,6 +41,6 @@
41
41
  "fastmcp": "^3.23.1",
42
42
  "zod": "^4.1.12",
43
43
  "picocolors": "^1.0.0",
44
- "@zenflux/utils": "0.1.21"
44
+ "@zenflux/utils": "0.1.23"
45
45
  }
46
46
  }