@pulse-js/core 0.1.1 → 0.1.3

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 CHANGED
@@ -1,172 +1,188 @@
1
- # Pulse
2
-
3
- A semantic reactivity system for modern applications. Separate reactive data (sources) from business conditions (guards) with a declarative, composable, and observable approach.
4
-
5
- Pulse differs from traditional signals or state managers by treating "Conditions" as first-class citizens. Instead of embedding complex boolean logic inside components or selectors, you define semantic **Guards** that can be observed, composed, and debugged independently.
6
-
7
- ## Installation
8
-
9
- ```bash
10
- npm install @pulse-js/core @pulse-js/react @pulse-js/tools
11
- # or
12
- bun add @pulse-js/core @pulse-js/react @pulse-js/tools
13
- ```
14
-
15
- ## Core Concepts
16
-
17
- ### Sources (Refined Data)
18
-
19
- Sources are the primitive containers for your application state. They hold values and notify dependents when those values change.
20
-
21
- ```typescript
22
- import { source } from "@pulse-js/core";
23
-
24
- // Create a source
25
- const user = source({ name: "Alice", id: 1 });
26
- const rawCount = source(0);
27
-
28
- // Read the value (dependencies are tracked automatically if called inside a Guard)
29
- console.log(user());
30
-
31
- // Update the value
32
- user.set({ name: "Bob", id: 1 });
33
-
34
- // Update using a callback
35
- rawCount.update((n) => n + 1);
36
- ```
37
-
38
- ### Guards (Semantic Logic)
39
-
40
- Guards represent business rules or derivations. They are not just boolean flags; they track their own state including `status` (ok, fail, pending) and `reason` (why it failed).
41
-
42
- ```typescript
43
- import { guard } from "@pulse-js/core";
44
-
45
- // Synchronous Guard
46
- const isAdmin = guard("is-admin", () => {
47
- const u = user();
48
- if (u.role !== "admin") return false; // Implicitly sets status to 'fail'
49
- return true;
50
- });
51
-
52
- // Guards can be checked explicitly
53
- if (isAdmin.ok()) {
54
- // Grant access
55
- } else {
56
- console.log(isAdmin.reason()); // e.g. "is-admin failed"
57
- }
58
- ```
59
-
60
- ### Async Guards
61
-
62
- Pulse handles asynchronous logic natively. Guards can return Promises, and their status will automatically transition from `pending` to `ok` or `fail`.
63
-
64
- ```typescript
65
- const isServerOnline = guard("check-server", async () => {
66
- const response = await fetch("/health");
67
- if (!response.ok) throw new Error("Server unreachable");
68
- return true;
69
- });
70
-
71
- // Check status synchronously non-blocking
72
- if (isServerOnline.pending()) {
73
- showSpinner();
74
- }
75
- ```
76
-
77
- ### Composition
78
-
79
- Guards can be composed using logical operators. This creates a semantic tree of conditions that is easy to debug.
80
-
81
- ```typescript
82
- import { guard } from "@pulse-js/core";
83
-
84
- // .all() - Success only if ALL pass. Fails with the reason of the first failure.
85
- const canCheckout = guard.all("can-checkout", [
86
- isAuthenticated,
87
- hasItemsInCart,
88
- isServerOnline,
89
- ]);
90
-
91
- // .any() - Success if AT LEAST ONE passes.
92
- const hasAccess = guard.any("has-access", [isAdmin, isEditor]);
93
-
94
- // .not() - Inverts the logical result.
95
- const isGuest = guard.not("is-guest", isAuthenticated);
96
- ```
97
-
98
- ### Computed Values
99
-
100
- You can derive new data from sources or other guards using `guard.compute`.
101
-
102
- ```typescript
103
- const fullName = guard.compute(
104
- "full-name",
105
- [firstName, lastName],
106
- (first, last) => {
107
- return `${first} ${last}`;
108
- }
109
- );
110
- ```
111
-
112
- ## Server-Side Rendering (SSR)
113
-
114
- Pulse is designed with SSR in mind. It supports isomorphic rendering where async guards can be evaluated on the server, their state serialized, and then hydrated on the client.
115
-
116
- ### Server Side
117
-
118
- ```typescript
119
- import { evaluate } from "@pulse-js/core";
120
-
121
- // 1. Evaluate critical guards on the server
122
- const hydrationState = await evaluate([isUserAuthenticated, appSettings]);
123
-
124
- // 2. Serialize this state into your HTML
125
- const html = `
126
- <script>window.__PULSE_STATE__ = ${JSON.stringify(hydrationState)}</script>
127
- `;
128
- ```
129
-
130
- ### Client Side (Hydration)
131
-
132
- ```typescript
133
- import { hydrate } from "@pulse-js/core";
134
-
135
- // 1. Hydrate before rendering
136
- hydrate(window.__PULSE_STATE__);
137
- ```
138
-
139
- ## API Reference
140
-
141
- ### `source<T>(initialValue: T, options?: SourceOptions)`
142
-
143
- Creates a reactive source.
144
-
145
- - `options.name`: Unique string name (highly recommended for debugging).
146
- - `options.equals`: Custom equality function `(prev, next) => boolean`.
147
-
148
- Methods:
149
-
150
- - `.set(value: T)`: Updates the value.
151
- - `.update(fn: (current: T) => T)`: Updates value using a transform.
152
- - `.subscribe(fn: (value: T) => void)`: Manual subscription.
153
-
154
- ### `guard<T>(name: string, evaluator: () => T | Promise<T>)`
155
-
156
- Creates a semantic guard.
157
-
158
- Methods:
159
-
160
- - `.ok()`: Returns true if status is 'ok'.
161
- - `.fail()`: Returns true if status is 'fail'.
162
- - `.pending()`: Returns true if evaluating async.
163
- - `.reason()`: Returns the failure message.
164
- - `.state()`: Returns full `{ status, value, reason }` object.
165
- - `.subscribe(fn: (state: GuardState) => void)`: Manual subscription.
166
-
167
- ---
168
-
169
- ## Ecosystem
170
-
171
- - **@pulse-js/react**: React bindings and hooks.
172
- - **@pulse-js/tools**: Visual debugging tools.
1
+ <div align="center">
2
+
3
+ <img width="200" height="200" alt="logo" src="https://raw.githubusercontent.com/ZtaMDev/Pulse/refs/heads/main/pulse.svg" />
4
+
5
+ # Pulse
6
+
7
+ > A semantic reactivity system for modern applications. Separate reactive data (sources) from business conditions (guards) with a declarative, composable, and observable approach.
8
+
9
+ Pulse differs from traditional signals or state managers by treating `Conditions` as first-class citizens. Instead of embedding complex boolean logic inside components or selectors, you define semantic **Guards** that can be observed, composed, and debugged independently.
10
+
11
+ </div>
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @pulse-js/core @pulse-js/tools
17
+ ```
18
+
19
+ ### or
20
+
21
+ ```bash
22
+ bun add @pulse-js/core @pulse-js/tools
23
+ ```
24
+
25
+ Pulse works with React via adapters like `@pulse-js/react`.
26
+
27
+ ```bash
28
+ bun add @pulse-js/react
29
+ ```
30
+
31
+ ## Core Concepts
32
+
33
+ ### Sources (Refined Data)
34
+
35
+ Sources are the primitive containers for your application state. They hold values and notify dependents when those values change.
36
+
37
+ ```typescript
38
+ import { source } from "@pulse-js/core";
39
+
40
+ // Create a source
41
+ const user = source({ name: "Alice", id: 1 });
42
+ const rawCount = source(0);
43
+
44
+ // Read the value (dependencies are tracked automatically if called inside a Guard)
45
+ console.log(user());
46
+
47
+ // Update the value
48
+ user.set({ name: "Bob", id: 1 });
49
+
50
+ // Update using a callback
51
+ rawCount.update((n) => n + 1);
52
+ ```
53
+
54
+ ### Guards (Semantic Logic)
55
+
56
+ Guards represent business rules or derivations. They are not just boolean flags; they track their own state including `status` (ok, fail, pending) and `reason` (why it failed).
57
+
58
+ ```typescript
59
+ import { guard } from "@pulse-js/core";
60
+
61
+ // Synchronous Guard
62
+ const isAdmin = guard("is-admin", () => {
63
+ const u = user();
64
+ if (u.role !== "admin") return false; // Implicitly sets status to 'fail'
65
+ return true;
66
+ });
67
+
68
+ // Guards can be checked explicitly
69
+ if (isAdmin.ok()) {
70
+ // Grant access
71
+ } else {
72
+ console.log(isAdmin.reason()); // e.g. "is-admin failed"
73
+ }
74
+ ```
75
+
76
+ ### Async Guards
77
+
78
+ Pulse handles asynchronous logic natively. Guards can return Promises, and their status will automatically transition from `pending` to `ok` or `fail`.
79
+
80
+ ```typescript
81
+ const isServerOnline = guard("check-server", async () => {
82
+ const response = await fetch("/health");
83
+ if (!response.ok) throw new Error("Server unreachable");
84
+ return true;
85
+ });
86
+
87
+ // Check status synchronously non-blocking
88
+ if (isServerOnline.pending()) {
89
+ showSpinner();
90
+ }
91
+ ```
92
+
93
+ ### Composition
94
+
95
+ Guards can be composed using logical operators. This creates a semantic tree of conditions that is easy to debug.
96
+
97
+ ```typescript
98
+ import { guard } from "@pulse-js/core";
99
+
100
+ // .all() - Success only if ALL pass. Fails with the reason of the first failure.
101
+ const canCheckout = guard.all("can-checkout", [
102
+ isAuthenticated,
103
+ hasItemsInCart,
104
+ isServerOnline,
105
+ ]);
106
+
107
+ // .any() - Success if AT LEAST ONE passes.
108
+ const hasAccess = guard.any("has-access", [isAdmin, isEditor]);
109
+
110
+ // .not() - Inverts the logical result.
111
+ const isGuest = guard.not("is-guest", isAuthenticated);
112
+ ```
113
+
114
+ ### Computed Values
115
+
116
+ You can derive new data from sources or other guards using `guard.compute`.
117
+
118
+ ```typescript
119
+ const fullName = guard.compute(
120
+ "full-name",
121
+ [firstName, lastName],
122
+ (first, last) => {
123
+ return `${first} ${last}`;
124
+ }
125
+ );
126
+ ```
127
+
128
+ ## Server-Side Rendering (SSR)
129
+
130
+ Pulse is designed with SSR in mind. It supports isomorphic rendering where async guards can be evaluated on the server, their state serialized, and then hydrated on the client.
131
+
132
+ ### Server Side
133
+
134
+ ```typescript
135
+ import { evaluate } from "@pulse-js/core";
136
+
137
+ // 1. Evaluate critical guards on the server
138
+ const hydrationState = await evaluate([isUserAuthenticated, appSettings]);
139
+
140
+ // 2. Serialize this state into your HTML
141
+ const html = `
142
+ <script>window.__PULSE_STATE__ = ${JSON.stringify(hydrationState)}</script>
143
+ `;
144
+ ```
145
+
146
+ ### Client Side (Hydration)
147
+
148
+ ```typescript
149
+ import { hydrate } from "@pulse-js/core";
150
+
151
+ // 1. Hydrate before rendering
152
+ hydrate(window.__PULSE_STATE__);
153
+ ```
154
+
155
+ ## API Reference
156
+
157
+ ### `source<T>(initialValue: T, options?: SourceOptions)`
158
+
159
+ Creates a reactive source.
160
+
161
+ - `options.name`: Unique string name (highly recommended for debugging).
162
+ - `options.equals`: Custom equality function `(prev, next) => boolean`.
163
+
164
+ Methods:
165
+
166
+ - `.set(value: T)`: Updates the value.
167
+ - `.update(fn: (current: T) => T)`: Updates value using a transform.
168
+ - `.subscribe(fn: (value: T) => void)`: Manual subscription.
169
+
170
+ ### `guard<T>(name: string, evaluator: () => T | Promise<T>)`
171
+
172
+ Creates a semantic guard.
173
+
174
+ Methods:
175
+
176
+ - `.ok()`: Returns true if status is 'ok'.
177
+ - `.fail()`: Returns true if status is 'fail'.
178
+ - `.pending()`: Returns true if evaluating async.
179
+ - `.reason()`: Returns the failure message.
180
+ - `.state()`: Returns full `{ status, value, reason }` object.
181
+ - `.subscribe(fn: (state: GuardState) => void)`: Manual subscription.
182
+
183
+ ---
184
+
185
+ ## Ecosystem
186
+
187
+ - **@pulse-js/react**: React bindings and hooks.
188
+ - **@pulse-js/tools**: Visual debugging tools.
package/dist/index.cjs ADDED
@@ -0,0 +1,324 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ PulseRegistry: () => PulseRegistry,
24
+ evaluate: () => evaluate,
25
+ getCurrentGuard: () => getCurrentGuard,
26
+ guard: () => extendedGuard,
27
+ hydrate: () => hydrate,
28
+ registerGuardForHydration: () => registerGuardForHydration,
29
+ runInContext: () => runInContext,
30
+ source: () => source
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+
34
+ // src/tracking.ts
35
+ var activeGuard = null;
36
+ function runInContext(guard2, fn) {
37
+ const prev = activeGuard;
38
+ activeGuard = guard2;
39
+ try {
40
+ return fn();
41
+ } finally {
42
+ activeGuard = prev;
43
+ }
44
+ }
45
+ function getCurrentGuard() {
46
+ return activeGuard;
47
+ }
48
+
49
+ // src/ssr.ts
50
+ var guardRegistry = /* @__PURE__ */ new Map();
51
+ function registerGuardForHydration(name, guard2) {
52
+ guardRegistry.set(name, guard2);
53
+ }
54
+ async function evaluate(guards) {
55
+ const state = {};
56
+ await Promise.all(guards.map(async (g) => {
57
+ while (g.pending()) {
58
+ await new Promise((resolve) => setTimeout(resolve, 0));
59
+ }
60
+ }));
61
+ guards.forEach((g) => {
62
+ const name = g._name;
63
+ if (name) {
64
+ state[name] = g.state();
65
+ }
66
+ });
67
+ return state;
68
+ }
69
+ function hydrate(state) {
70
+ Object.entries(state).forEach(([name, guardState]) => {
71
+ const g = guardRegistry.get(name);
72
+ if (g && g._hydrate) {
73
+ g._hydrate(guardState);
74
+ }
75
+ });
76
+ }
77
+
78
+ // src/guard.ts
79
+ function guard(nameOrFn, fn) {
80
+ const name = typeof nameOrFn === "string" ? nameOrFn : void 0;
81
+ const evaluator = typeof nameOrFn === "function" ? nameOrFn : fn;
82
+ if (!evaluator) {
83
+ throw new Error("Guard requires an evaluator function");
84
+ }
85
+ let state = { status: "pending" };
86
+ const dependents = /* @__PURE__ */ new Set();
87
+ const subscribers = /* @__PURE__ */ new Set();
88
+ let evaluationId = 0;
89
+ const node = {
90
+ addDependency(trackable) {
91
+ },
92
+ notify() {
93
+ evaluate2();
94
+ }
95
+ };
96
+ const evaluate2 = () => {
97
+ const currentId = ++evaluationId;
98
+ const oldStatus = state.status;
99
+ const oldValue = state.value;
100
+ try {
101
+ const result = runInContext(node, () => evaluator());
102
+ if (result instanceof Promise) {
103
+ state = { status: "pending" };
104
+ result.then((resolved) => {
105
+ if (currentId === evaluationId) {
106
+ if (resolved === false) {
107
+ state = { status: "fail", reason: name ? `${name} failed` : "condition failed" };
108
+ } else {
109
+ state = { status: "ok", value: resolved };
110
+ }
111
+ notifyDependents();
112
+ }
113
+ }).catch((err) => {
114
+ if (currentId === evaluationId) {
115
+ state = { status: "fail", reason: err instanceof Error ? err.message : String(err) };
116
+ notifyDependents();
117
+ }
118
+ });
119
+ } else {
120
+ if (result === false) {
121
+ state = { status: "fail", reason: name ? `${name} failed` : "condition failed" };
122
+ } else {
123
+ state = { status: "ok", value: result };
124
+ }
125
+ if (oldStatus !== state.status || oldValue !== state.value) {
126
+ notifyDependents();
127
+ }
128
+ }
129
+ } catch (err) {
130
+ state = { status: "fail", reason: err instanceof Error ? err.message : String(err) };
131
+ notifyDependents();
132
+ }
133
+ };
134
+ const notifyDependents = () => {
135
+ const deps = Array.from(dependents);
136
+ dependents.clear();
137
+ deps.forEach((dep) => dep.notify());
138
+ subscribers.forEach((sub) => sub({ ...state }));
139
+ };
140
+ evaluate2();
141
+ const handleRead = () => {
142
+ const activeGuard2 = getCurrentGuard();
143
+ if (activeGuard2 && activeGuard2 !== node) {
144
+ dependents.add(activeGuard2);
145
+ }
146
+ };
147
+ const g = (() => {
148
+ handleRead();
149
+ return state.status === "ok" ? state.value : void 0;
150
+ });
151
+ g.ok = () => {
152
+ handleRead();
153
+ return state.status === "ok";
154
+ };
155
+ g.fail = () => {
156
+ handleRead();
157
+ return state.status === "fail";
158
+ };
159
+ g.pending = () => {
160
+ handleRead();
161
+ return state.status === "pending";
162
+ };
163
+ g.reason = () => {
164
+ handleRead();
165
+ return state.reason;
166
+ };
167
+ g.state = () => {
168
+ handleRead();
169
+ return state;
170
+ };
171
+ g.subscribe = (listener) => {
172
+ subscribers.add(listener);
173
+ return () => subscribers.delete(listener);
174
+ };
175
+ g._evaluate = () => evaluate2();
176
+ g._name = name;
177
+ g._hydrate = (newState) => {
178
+ state = newState;
179
+ evaluationId++;
180
+ notifyDependents();
181
+ };
182
+ if (name) {
183
+ registerGuardForHydration(name, g);
184
+ }
185
+ PulseRegistry.register(g);
186
+ return g;
187
+ }
188
+
189
+ // src/registry.ts
190
+ var Registry = class {
191
+ units = /* @__PURE__ */ new Map();
192
+ listeners = /* @__PURE__ */ new Set();
193
+ /**
194
+ * Registers a new unit (Source or Guard).
195
+ * Uses the unit's name as a key to prevent duplicates during HMR.
196
+ */
197
+ register(unit) {
198
+ const key = unit._name || unit;
199
+ this.units.set(key, unit);
200
+ this.listeners.forEach((l) => l(unit));
201
+ }
202
+ /**
203
+ * Retrieves all registered units.
204
+ */
205
+ getAll() {
206
+ return Array.from(this.units.values());
207
+ }
208
+ /**
209
+ * Subscribes to new unit registrations.
210
+ *
211
+ * @param listener - Callback receiving the newly registered unit.
212
+ * @returns Unsubscribe function.
213
+ */
214
+ onRegister(listener) {
215
+ this.listeners.add(listener);
216
+ return () => {
217
+ this.listeners.delete(listener);
218
+ };
219
+ }
220
+ };
221
+ var PulseRegistry = new Registry();
222
+
223
+ // src/source.ts
224
+ function source(initialValue, options = {}) {
225
+ let value = initialValue;
226
+ const subscribers = /* @__PURE__ */ new Set();
227
+ const dependents = /* @__PURE__ */ new Set();
228
+ const s = (() => {
229
+ const activeGuard2 = getCurrentGuard();
230
+ if (activeGuard2) {
231
+ dependents.add(activeGuard2);
232
+ }
233
+ return value;
234
+ });
235
+ s.set = (newValue) => {
236
+ const equals = options.equals || ((a, b) => a === b);
237
+ if (!equals(value, newValue)) {
238
+ value = newValue;
239
+ subscribers.forEach((sub) => sub(value));
240
+ const deps = Array.from(dependents);
241
+ dependents.clear();
242
+ deps.forEach((dep) => dep.notify());
243
+ }
244
+ };
245
+ s.update = (updater) => {
246
+ s.set(updater(value));
247
+ };
248
+ s.subscribe = (listener) => {
249
+ subscribers.add(listener);
250
+ return () => subscribers.delete(listener);
251
+ };
252
+ s._name = options.name;
253
+ PulseRegistry.register(s);
254
+ return s;
255
+ }
256
+
257
+ // src/composition.ts
258
+ function isGuard(target) {
259
+ return typeof target === "function" && "ok" in target;
260
+ }
261
+ function guardAll(nameOrGuards, maybeGuards) {
262
+ const name = typeof nameOrGuards === "string" ? nameOrGuards : void 0;
263
+ const guards = Array.isArray(nameOrGuards) ? nameOrGuards : maybeGuards;
264
+ return guard(name, () => {
265
+ let firstFail = null;
266
+ for (const g of guards) {
267
+ if (!g.ok()) {
268
+ if (!firstFail) firstFail = g;
269
+ }
270
+ }
271
+ if (firstFail) {
272
+ throw new Error(firstFail.reason() || "condition failed");
273
+ }
274
+ return true;
275
+ });
276
+ }
277
+ function guardAny(nameOrGuards, maybeGuards) {
278
+ const name = typeof nameOrGuards === "string" ? nameOrGuards : void 0;
279
+ const guards = Array.isArray(nameOrGuards) ? nameOrGuards : maybeGuards;
280
+ return guard(name, () => {
281
+ let allFails = [];
282
+ for (const g of guards) {
283
+ if (g.ok()) return true;
284
+ allFails.push(g.reason() || "failed");
285
+ }
286
+ throw new Error(allFails.length > 0 ? allFails.join(" and ") : "no conditions met");
287
+ });
288
+ }
289
+ function guardNot(nameOrTarget, maybeTarget) {
290
+ const name = typeof nameOrTarget === "string" ? nameOrTarget : void 0;
291
+ const target = typeof nameOrTarget === "string" ? maybeTarget : nameOrTarget;
292
+ return guard(name, () => {
293
+ if (isGuard(target)) {
294
+ return !target.ok();
295
+ }
296
+ return !target();
297
+ });
298
+ }
299
+ function guardCompute(name, dependencies, processor) {
300
+ return guard(name, () => {
301
+ const values = dependencies.map((dep) => typeof dep === "function" ? dep() : dep);
302
+ return processor(...values);
303
+ });
304
+ }
305
+ var guardExtensions = {
306
+ all: guardAll,
307
+ any: guardAny,
308
+ not: guardNot,
309
+ compute: guardCompute
310
+ };
311
+
312
+ // src/index.ts
313
+ var extendedGuard = Object.assign(guard, guardExtensions);
314
+ // Annotate the CommonJS export names for ESM import in node:
315
+ 0 && (module.exports = {
316
+ PulseRegistry,
317
+ evaluate,
318
+ getCurrentGuard,
319
+ guard,
320
+ hydrate,
321
+ registerGuardForHydration,
322
+ runInContext,
323
+ source
324
+ });