@stonyx/events 0.1.1-alpha.0 → 0.1.1-alpha.10

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,3 +1,7 @@
1
+ [![CI](https://github.com/abofs/stonyx-events/actions/workflows/ci.yml/badge.svg)](https://github.com/abofs/stonyx-events/actions/workflows/ci.yml)
2
+ [![npm version](https://img.shields.io/npm/v/@stonyx/events.svg)](https://www.npmjs.com/package/@stonyx/events)
3
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
4
+
1
5
  # @stonyx/events
2
6
 
3
7
  A lightweight pub/sub event system for the Stonyx framework. Provides singleton event management with error isolation, async support, and type-safe event registration.
@@ -19,36 +23,65 @@ npm install @stonyx/events
19
23
 
20
24
  ## Usage
21
25
 
22
- ```javascript
23
- import Events from '@stonyx/events';
26
+ ### Option 1: Convenience Functions (Recommended)
24
27
 
25
- const events = new Events();
28
+ The package exports convenience functions that use a singleton instance:
29
+
30
+ ```javascript
31
+ import { setup, subscribe, emit, once } from '@stonyx/events';
26
32
 
27
33
  // Register available events
28
- events.setup(['userLogin', 'userLogout', 'dataChange']);
34
+ setup(['userLogin', 'userLogout', 'dataChange']);
29
35
 
30
36
  // Subscribe to events
31
- events.subscribe('userLogin', (user) => {
37
+ subscribe('userLogin', (user) => {
32
38
  console.log(`${user.name} logged in`);
33
39
  });
34
40
 
35
41
  // Subscribe once (auto-unsubscribe after first fire)
36
- events.once('dataChange', () => {
42
+ once('dataChange', () => {
37
43
  console.log('Data changed for the first time');
38
44
  });
39
45
 
40
46
  // Emit events
41
- events.emit('userLogin', { name: 'Alice' });
47
+ emit('userLogin', { name: 'Alice' });
42
48
 
43
49
  // Unsubscribe
44
- const unsub = events.subscribe('userLogout', handler);
50
+ const unsub = subscribe('userLogout', handler);
45
51
  unsub(); // Remove subscription
46
52
  ```
47
53
 
54
+ ### Option 2: Class-based (Advanced)
55
+
56
+ You can also instantiate the Events class directly for more control:
57
+
58
+ ```javascript
59
+ import Events from '@stonyx/events';
60
+
61
+ const events = new Events();
62
+
63
+ // Register available events
64
+ events.setup(['userLogin', 'userLogout', 'dataChange']);
65
+
66
+ // Subscribe to events
67
+ events.subscribe('userLogin', (user) => {
68
+ console.log(`${user.name} logged in`);
69
+ });
70
+
71
+ // Emit events
72
+ events.emit('userLogin', { name: 'Alice' });
73
+ ```
74
+
75
+ **Note:** The Events class uses a singleton pattern, so all instances share the same event registry.
76
+
48
77
  ## API Reference
49
78
 
50
- | Method | Parameters | Description |
51
- |--------|-----------|-------------|
79
+ ### Convenience Functions (Exported)
80
+
81
+ All functions use a singleton Events instance:
82
+
83
+ | Function | Parameters | Description |
84
+ |----------|-----------|-------------|
52
85
  | `setup()` | `eventNames: string[]` | Register available event names. Events must be registered before subscribing. |
53
86
  | `subscribe()` | `event: string, callback: Function` | Subscribe to an event. Returns an unsubscribe function. |
54
87
  | `once()` | `event: string, callback: Function` | Subscribe to an event once. Auto-unsubscribes after first emit. |
@@ -57,16 +90,26 @@ unsub(); // Remove subscription
57
90
  | `clear()` | `event: string` | Remove all subscriptions for an event. |
58
91
  | `reset()` | none | Clear all subscriptions and events. Useful for testing. |
59
92
 
60
- ## How It Works
93
+ ### Events Class Methods
61
94
 
62
- The Events class provides a lightweight pub/sub system with the following features:
95
+ If using the class directly, all methods above are available as instance methods:
63
96
 
64
- - **Event Registration**: Events must be registered with `setup()` before use, ensuring type safety
65
- - **Singleton Pattern**: Single Events instance shared across your application
66
- - **Async Support**: Event handlers can be async functions
67
- - **Error Isolation**: Errors in one handler don't affect others or prevent other handlers from running
68
- - **One-time Subscriptions**: Use `once()` for handlers that should only fire once
69
- - **Unsubscribe**: All subscriptions return an unsubscribe function for cleanup
97
+ ```javascript
98
+ import Events from '@stonyx/events';
99
+ const events = new Events();
100
+
101
+ events.setup(['myEvent']);
102
+ events.subscribe('myEvent', handler);
103
+ events.emit('myEvent', data);
104
+ ```
105
+
106
+ ## How It Works
107
+
108
+ - The `Events` class uses a static `instance` property to enforce a singleton -- every `new Events()` returns the same object
109
+ - Event names are held in a `registeredEvents` Set; subscribing to an unregistered name throws immediately, catching typos early
110
+ - Subscribers are stored in a `Map<string, Set<Function>>`, so duplicate function references are automatically deduplicated
111
+ - `emit()` is async: it maps every subscriber into a `Promise`, wraps each in a try/catch for error isolation, and awaits them all with `Promise.all()`
112
+ - `once()` wraps the callback in a self-removing wrapper that calls `unsubscribe` before invoking the original handler
70
113
 
71
114
  ## License
72
115
 
package/package.json CHANGED
@@ -3,20 +3,17 @@
3
3
  "keywords": [
4
4
  "stonyx-module"
5
5
  ],
6
- "version": "0.1.1-alpha.0",
6
+ "version": "0.1.1-alpha.10",
7
7
  "description": "Lightweight pub/sub event system for the Stonyx framework",
8
8
  "main": "src/main.js",
9
9
  "type": "module",
10
10
  "files": [
11
- "*"
11
+ "src",
12
+ "README.md"
12
13
  ],
13
14
  "exports": {
14
15
  ".": "./src/main.js"
15
16
  },
16
- "scripts": {
17
- "test": "qunit",
18
- "prepublishOnly": "npm test"
19
- },
20
17
  "publishConfig": {
21
18
  "access": "public",
22
19
  "provenance": true
@@ -35,9 +32,12 @@
35
32
  },
36
33
  "homepage": "https://github.com/abofs/stonyx-events#readme",
37
34
  "devDependencies": {
38
- "@stonyx/utils": "^0.2.2",
35
+ "@stonyx/utils": "0.2.3-beta.13",
39
36
  "qunit": "^2.24.1",
40
37
  "sinon": "^21.0.0"
41
38
  },
42
- "dependencies": {}
43
- }
39
+ "dependencies": {},
40
+ "scripts": {
41
+ "test": "qunit"
42
+ }
43
+ }
package/src/main.js CHANGED
@@ -165,3 +165,15 @@ class Events {
165
165
  }
166
166
 
167
167
  export default Events;
168
+
169
+ // Create singleton instance
170
+ const events = new Events();
171
+
172
+ // Export convenience functions that use the singleton
173
+ export const setup = (...args) => events.setup(...args);
174
+ export const subscribe = (...args) => events.subscribe(...args);
175
+ export const once = (...args) => events.once(...args);
176
+ export const unsubscribe = (...args) => events.unsubscribe(...args);
177
+ export const emit = (...args) => events.emit(...args);
178
+ export const clear = (...args) => events.clear(...args);
179
+ export const reset = (...args) => events.reset(...args);
@@ -1,421 +0,0 @@
1
- # @stonyx/events - Project Structure & Architecture
2
-
3
- ## Project Overview
4
-
5
- **@stonyx/events** is a lightweight pub/sub event system for the Stonyx framework. It provides a singleton-based event management system with error isolation, async support, and type-safe event registration.
6
-
7
- ### Core Purpose
8
- - Provide application-wide event bus for decoupled communication
9
- - Support async event handlers with error isolation
10
- - Ensure type safety through event registration
11
- - Maintain singleton pattern for shared event system
12
-
13
- ### Technology Stack
14
- - **Runtime**: Node.js v24.13.0
15
- - **Module System**: ES Modules
16
- - **Testing**: QUnit 2.24.1 + Sinon 21.0.0
17
- - **License**: Apache 2.0
18
-
19
- ## Architecture Overview
20
-
21
- ### Design Patterns
22
-
23
- **Singleton Pattern**
24
- - Single Events instance shared across the application
25
- - Prevents multiple competing event systems
26
- - Ensures all parts of the application use the same event bus
27
-
28
- **Error Isolation**
29
- - Errors in one handler don't affect other handlers
30
- - All handlers run even if some fail
31
- - Errors are logged to console.error but don't propagate
32
-
33
- **Async Support**
34
- - All event handlers can be async functions
35
- - `emit()` waits for all handlers to complete
36
- - Handlers run in parallel via Promise.all()
37
-
38
- **Type Safety**
39
- - Events must be registered with `setup()` before use
40
- - Prevents typos and invalid event names
41
- - Enforces explicit event declarations
42
-
43
- ## File Structure
44
-
45
- ```
46
- stonyx-events/
47
- ├── .github/
48
- │ └── workflows/
49
- │ └── ci.yml # GitHub Actions CI pipeline
50
- ├── .claude/
51
- │ ├── settings.local.json # Claude Code permissions
52
- │ └── project-structure.md # This file
53
- ├── config/
54
- │ └── environment.js # Environment configuration
55
- ├── src/
56
- │ └── main.js # Events class implementation
57
- ├── test/
58
- │ └── unit/
59
- │ └── events-test.js # QUnit tests for Events
60
- ├── .gitignore # Git ignore patterns
61
- ├── .npmignore # NPM ignore patterns
62
- ├── .nvmrc # Node version specification
63
- ├── LICENSE.md # Apache 2.0 license
64
- ├── README.md # User-facing documentation
65
- ├── package.json # NPM package configuration
66
- └── stonyx-bootstrap.cjs # CommonJS bootstrap for testing
67
- ```
68
-
69
- ## Core Components Deep Dive
70
-
71
- ### Events Class (`src/main.js`)
72
-
73
- The Events class is the heart of the module, providing all pub/sub functionality.
74
-
75
- #### Properties
76
-
77
- **`static instance`** (Events|null)
78
- - Singleton instance reference
79
- - Ensures only one Events instance exists
80
-
81
- **`events`** (Map<string, Set<Function>>)
82
- - Map of event names to their subscriber sets
83
- - Uses Set to prevent duplicate subscriptions
84
- - Automatically created when events are registered
85
-
86
- **`registeredEvents`** (Set<string>)
87
- - Set of all registered event names
88
- - Used to validate subscriptions
89
- - Prevents subscribing to unregistered events
90
-
91
- #### Methods
92
-
93
- **`setup(eventNames: string[])`**
94
- - Register available event names
95
- - Must be called before subscribing to events
96
- - Validates that all names are strings
97
- - Creates empty subscriber sets for each event
98
-
99
- **`subscribe(event: string, callback: Function)`**
100
- - Subscribe to an event
101
- - Throws if event is not registered
102
- - Throws if callback is not a function
103
- - Returns an unsubscribe function
104
- - Callback signature: `(...args: any[]) => void | Promise<void>`
105
-
106
- **`once(event: string, callback: Function)`**
107
- - Subscribe to an event once
108
- - Auto-unsubscribes after first emit
109
- - Wraps callback in a self-removing wrapper
110
- - Returns an unsubscribe function
111
- - Supports async callbacks
112
-
113
- **`emit(event: string, ...args: any[])`**
114
- - Emit an event with arguments
115
- - Async function that waits for all handlers
116
- - Runs all handlers in parallel
117
- - Isolates errors per handler
118
- - Does nothing if event has no subscribers
119
-
120
- **`unsubscribe(event: string, callback: Function)`**
121
- - Remove a specific subscription
122
- - Safe to call multiple times
123
- - Does nothing if event or callback doesn't exist
124
-
125
- **`clear(event: string)`**
126
- - Remove all subscriptions for an event
127
- - Useful for cleanup between tests
128
- - Event remains registered
129
-
130
- **`reset()`**
131
- - Clear all subscriptions and registrations
132
- - Resets to pristine state
133
- - Essential for test isolation
134
-
135
- ## Dependencies & Integration
136
-
137
- ### Direct Dependencies
138
-
139
- **stonyx** (file:../stonyx)
140
- - Core Stonyx framework
141
- - Provides base configuration and bootstrapping
142
- - Required for module initialization
143
-
144
- ### Dev Dependencies
145
-
146
- **@stonyx/utils** (file:../stonyx-utils)
147
- - Utility functions (currently unused but available)
148
-
149
- **qunit** (^2.24.1)
150
- - Testing framework
151
- - Runs via CLI with stonyx-bootstrap.cjs
152
-
153
- **sinon** (^21.0.0)
154
- - Mocking/stubbing library
155
- - Available for advanced testing scenarios
156
-
157
- ### Modules That Depend on @stonyx/events
158
-
159
- **@stonyx/orm**
160
- - Uses Events for CRUD lifecycle hooks
161
- - Fires events: create:before, create:after, update:before, update:after, delete:before, delete:after
162
- - Provides `ormEvents` singleton instance
163
-
164
- ## Code Patterns & Conventions
165
-
166
- ### Module System
167
- - ES Modules throughout
168
- - Default export for Events class
169
- - No named exports (single-purpose module)
170
-
171
- ### Error Handling
172
- - Validation errors throw immediately
173
- - Runtime errors in handlers are caught and logged
174
- - No silent failures
175
-
176
- ### Logging
177
- - Environment variable: `EVENTS_LOG` (currently unused in implementation)
178
- - Configuration prepared in `config/environment.js`
179
- - Future: Could add debug logging for emit/subscribe events
180
-
181
- ### Naming Conventions
182
- - Event names: camelCase strings (e.g., 'userLogin', 'dataChange')
183
- - Method names: lowercase verbs (setup, subscribe, emit)
184
- - Private instance variables: None (all properties public for testing)
185
-
186
- ## Testing Guidelines
187
-
188
- ### Test Structure
189
- - All tests in `test/unit/events-test.js`
190
- - QUnit module: `[Unit] Events`
191
- - 18 test cases covering all functionality
192
- - Each test calls `events.reset()` before and after
193
-
194
- ### Test Patterns
195
-
196
- **Singleton Isolation**
197
- ```javascript
198
- const events = new Events();
199
- events.reset(); // Clear any previous state
200
- // ... test code ...
201
- events.reset(); // Clean up after test
202
- ```
203
-
204
- **Async Testing**
205
- ```javascript
206
- test('description', async function (assert) {
207
- // Use async/await for emit()
208
- await events.emit('event');
209
- assert.ok(condition);
210
- });
211
- ```
212
-
213
- **Error Suppression**
214
- ```javascript
215
- const originalConsoleError = console.error;
216
- console.error = () => {}; // Suppress expected errors
217
- // ... test code ...
218
- console.error = originalConsoleError; // Restore
219
- ```
220
-
221
- ### Coverage Areas
222
- 1. Event registration (setup)
223
- 2. Subscription management (subscribe, unsubscribe)
224
- 3. Event emission (emit)
225
- 4. One-time subscriptions (once)
226
- 5. Error isolation
227
- 6. Async support
228
- 7. Singleton behavior
229
- 8. Edge cases (unregistered events, no subscribers)
230
-
231
- ## Extension Points
232
-
233
- While the Events system is intentionally minimal, potential future enhancements include:
234
-
235
- ### Event Priorities
236
- - Add priority levels for subscribers
237
- - Execute high-priority handlers first
238
- - Use case: Logging before business logic
239
-
240
- ### Wildcard Events
241
- - Support pattern matching (e.g., 'user:*')
242
- - Subscribe to multiple events at once
243
- - Use case: Debugging, logging all events
244
-
245
- ### Event History
246
- - Optional recording of emitted events
247
- - Replay functionality for debugging
248
- - Use case: Time-travel debugging, audit logs
249
-
250
- ### Middleware
251
- - Pre/post-emit hooks
252
- - Event transformation pipeline
253
- - Use case: Validation, logging, metrics
254
-
255
- ## Configuration Reference
256
-
257
- ### Environment Variables
258
-
259
- **EVENTS_LOG**
260
- - Type: Boolean (truthy/falsy)
261
- - Default: `false`
262
- - Purpose: Enable debug logging (not yet implemented)
263
- - Usage: `EVENTS_LOG=true npm test`
264
-
265
- ### config/environment.js
266
-
267
- ```javascript
268
- {
269
- log: EVENTS_LOG ?? false, // Debug logging flag
270
- logColor: '#888', // Color for log output
271
- }
272
- ```
273
-
274
- Currently, these config values are prepared but not used in the Events implementation. They provide a foundation for future debug logging features.
275
-
276
- ## Package Exports
277
-
278
- ### Main Export
279
-
280
- ```javascript
281
- import Events from '@stonyx/events';
282
- ```
283
-
284
- The package exports a single default export: the Events class.
285
-
286
- ### Usage Pattern
287
-
288
- ```javascript
289
- // Create/get singleton instance
290
- const events = new Events();
291
-
292
- // Register events
293
- events.setup(['userLogin', 'userLogout']);
294
-
295
- // Subscribe
296
- events.subscribe('userLogin', (user) => {
297
- console.log('User logged in:', user);
298
- });
299
-
300
- // Emit (fire-and-forget, don't await)
301
- events.emit('userLogin', { id: 1, name: 'Alice' });
302
-
303
- // Or await if you need to ensure all handlers complete
304
- await events.emit('userLogin', { id: 1, name: 'Alice' });
305
- ```
306
-
307
- ## Development Workflow
308
-
309
- ### Local Development
310
-
311
- 1. **Install dependencies**
312
- ```bash
313
- cd /Users/mstonepc/Repos/abofs
314
- ./linker.sh local # Link all local Stonyx modules
315
- cd stonyx-events
316
- npm install
317
- ```
318
-
319
- 2. **Run tests**
320
- ```bash
321
- npm test
322
- ```
323
-
324
- 3. **Make changes**
325
- - Edit `src/main.js` for implementation
326
- - Edit `test/unit/events-test.js` for tests
327
- - Follow TDD: Write failing test, implement feature, verify
328
-
329
- ### Test-Driven Development
330
-
331
- The module follows TDD principles:
332
- 1. Write a failing test for new functionality
333
- 2. Implement the minimum code to pass the test
334
- 3. Refactor while keeping tests green
335
- 4. Ensure all tests pass before committing
336
-
337
- ### CI/CD Pipeline
338
-
339
- **GitHub Actions** (`.github/workflows/ci.yml`)
340
- - Triggers on PRs to `dev` and `main` branches
341
- - Uses pnpm for package management
342
- - Runs `pnpm test` to verify all tests pass
343
- - Cancels previous runs on new commits
344
-
345
- ### Publishing Workflow
346
-
347
- 1. **Version bump**
348
- ```bash
349
- npm version patch|minor|major
350
- ```
351
-
352
- 2. **Publish to NPM**
353
- ```bash
354
- npm publish
355
- ```
356
-
357
- 3. **Update dependents**
358
- - Update `@stonyx/orm` to use published version
359
- - Update other modules as needed
360
-
361
- ## Common Pitfalls & Gotchas
362
-
363
- ### Singleton Behavior
364
- - **Issue**: Creating new Events() always returns the same instance
365
- - **Solution**: Don't rely on local variables; singleton ensures shared state
366
- - **Testing**: Always call `reset()` between tests to clear state
367
-
368
- ### Async Handling
369
- - **Issue**: Forgetting to await emit() can lead to race conditions
370
- - **Solution**: Use `await events.emit()` when order matters
371
- - **Note**: For fire-and-forget, omit await (e.g., in synchronous createRecord)
372
-
373
- ### Error Isolation
374
- - **Issue**: One handler error doesn't stop other handlers, but logs to console
375
- - **Solution**: Expect console.error output in tests with failing handlers
376
- - **Testing**: Suppress console.error when testing error isolation
377
-
378
- ### Event Registration
379
- - **Issue**: Subscribing to unregistered events throws an error
380
- - **Solution**: Always call `setup()` with event names before subscribing
381
- - **Why**: Prevents typos and ensures explicit event declarations
382
-
383
- ### Set-based Subscriptions
384
- - **Issue**: Adding the same callback function twice only subscribes once
385
- - **Solution**: Use different function instances for multiple subscriptions
386
- - **Note**: This is by design to prevent accidental duplicate subscriptions
387
-
388
- ## Future Enhancement Opportunities
389
-
390
- ### Performance Optimizations
391
- - Lazy initialization of event subscriber sets
392
- - Debouncing/throttling for high-frequency events
393
- - Event batching for bulk updates
394
-
395
- ### Developer Experience
396
- - TypeScript definitions for type-safe event names and payloads
397
- - Debug mode with detailed logging
398
- - Event visualization/monitoring tools
399
-
400
- ### Advanced Features
401
- - Event namespacing (e.g., 'user:login:success')
402
- - Event bubbling/capturing (DOM-like event propagation)
403
- - Async middleware pipeline
404
- - Event replay for debugging
405
-
406
- ### Integration
407
- - Automatic event logging to @stonyx/logger (when it exists)
408
- - Metrics/telemetry integration
409
- - Event persistence for audit trails
410
-
411
- ## Related Resources
412
-
413
- - [Stonyx Framework](https://github.com/abofs/stonyx)
414
- - [QUnit Documentation](https://qunitjs.com/)
415
- - [Sinon.js Documentation](https://sinonjs.org/)
416
- - [Node.js ES Modules](https://nodejs.org/api/esm.html)
417
- - [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0)
418
-
419
- ---
420
-
421
- This document is maintained by the Stonyx team and should be updated whenever architectural changes are made to the @stonyx/events module.
@@ -1,24 +0,0 @@
1
- name: CI
2
-
3
- on:
4
- pull_request:
5
- branches:
6
- - dev
7
- - main
8
-
9
- concurrency:
10
- group: ${{ github.head_ref }}
11
- cancel-in-progress: true
12
-
13
- jobs:
14
- test:
15
- runs-on: ubuntu-latest
16
- steps:
17
- - uses: actions/checkout@v4
18
- - uses: pnpm/action-setup@v4
19
- - uses: actions/setup-node@v4
20
- with:
21
- node-version: '24.13.0'
22
- cache: 'pnpm'
23
- - run: pnpm install --frozen-lockfile
24
- - run: pnpm test
@@ -1,94 +0,0 @@
1
- name: Publish to NPM
2
-
3
- on:
4
- workflow_dispatch:
5
- inputs:
6
- version-type:
7
- description: 'Version type'
8
- required: true
9
- type: choice
10
- options:
11
- - alpha
12
- - patch
13
- - minor
14
- - major
15
- custom-version:
16
- description: 'Custom version (optional, overrides version-type)'
17
- required: false
18
- type: string
19
-
20
- permissions:
21
- contents: write
22
- id-token: write # Required for npm provenance
23
-
24
- jobs:
25
- publish:
26
- runs-on: ubuntu-latest
27
-
28
- steps:
29
- - name: Checkout code
30
- uses: actions/checkout@v3
31
- with:
32
- fetch-depth: 0
33
-
34
- - name: Setup pnpm
35
- uses: pnpm/action-setup@v4
36
- with:
37
- version: 9
38
-
39
- - name: Set up Node.js
40
- uses: actions/setup-node@v3
41
- with:
42
- node-version: 24.13.0
43
- cache: 'pnpm'
44
- registry-url: 'https://registry.npmjs.org'
45
-
46
- - name: Install dependencies
47
- run: pnpm install --frozen-lockfile
48
-
49
- - name: Run tests
50
- run: pnpm test
51
-
52
- - name: Configure git
53
- run: |
54
- git config user.name "github-actions[bot]"
55
- git config user.email "github-actions[bot]@users.noreply.github.com"
56
-
57
- - name: Bump version (custom)
58
- if: ${{ github.event.inputs.custom-version != '' }}
59
- run: npm version ${{ github.event.inputs.custom-version }} --no-git-tag-version
60
-
61
- - name: Bump version (prerelease alpha)
62
- if: ${{ github.event.inputs.version-type == 'alpha' && github.event.inputs.custom-version == '' }}
63
- run: npm version prerelease --preid=alpha --no-git-tag-version
64
-
65
- - name: Bump version (standard)
66
- if: ${{ github.event.inputs.version-type != 'alpha' && github.event.inputs.custom-version == '' }}
67
- run: npm version ${{ github.event.inputs.version-type }} --no-git-tag-version
68
-
69
- - name: Get package version
70
- id: package-version
71
- run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT
72
-
73
- - name: Publish to NPM (alpha)
74
- if: ${{ github.event.inputs.version-type == 'alpha' || contains(steps.package-version.outputs.version, 'alpha') }}
75
- run: npm publish --tag alpha --access public
76
- - name: Publish to NPM (stable)
77
- if: ${{ github.event.inputs.version-type != 'alpha' && !contains(steps.package-version.outputs.version, 'alpha') }}
78
- run: npm publish --access public
79
- - name: Commit version bump
80
- run: |
81
- git add package.json
82
- git commit -m "chore: release v${{ steps.package-version.outputs.version }}"
83
- git tag v${{ steps.package-version.outputs.version }}
84
- git push origin main --tags
85
-
86
- - name: Create GitHub Release
87
- uses: actions/create-release@v1
88
- env:
89
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
90
- with:
91
- tag_name: v${{ steps.package-version.outputs.version }}
92
- release_name: v${{ steps.package-version.outputs.version }}
93
- draft: false
94
- prerelease: ${{ contains(steps.package-version.outputs.version, 'alpha') }}
package/.gitignore DELETED
@@ -1,9 +0,0 @@
1
- node_modules/
2
- config/environment.js
3
- *logs/*
4
- .vscode/*
5
- *.vsix
6
- *DS_Store*
7
-
8
- # npm auth (never commit tokens)
9
- .npmrc
package/.npmignore DELETED
@@ -1,2 +0,0 @@
1
- test/
2
- .nvmrc
package/.nvmrc DELETED
@@ -1 +0,0 @@
1
- v24.13.0
@@ -1,9 +0,0 @@
1
- /**
2
- * commonJS Bootstrap loading - Stonyx must be loaded first, prior to the rest of the application
3
- */
4
- const { default:Stonyx } = require('stonyx');
5
- const { default:config } = require('./config/environment.js');
6
-
7
- new Stonyx(config, __dirname);
8
-
9
- module.exports = Stonyx;
@@ -1,341 +0,0 @@
1
- import QUnit from 'qunit';
2
- import Events from '../../src/main.js';
3
-
4
- const { module, test } = QUnit;
5
-
6
- module('[Unit] Events', function () {
7
-
8
- test('Events: setup() registers event names', function (assert) {
9
- const events = new Events();
10
- events.reset();
11
-
12
- events.setup(['testEvent1', 'testEvent2']);
13
-
14
- assert.ok(events.registeredEvents.has('testEvent1'), 'testEvent1 is registered');
15
- assert.ok(events.registeredEvents.has('testEvent2'), 'testEvent2 is registered');
16
- assert.strictEqual(events.registeredEvents.size, 2, 'Two events are registered');
17
-
18
- events.reset();
19
- });
20
-
21
- test('Events: setup() throws on invalid input', function (assert) {
22
- const events = new Events();
23
- events.reset();
24
-
25
- assert.throws(
26
- () => events.setup('not-an-array'),
27
- /setup\(\) requires an array/,
28
- 'Throws error for non-array input'
29
- );
30
-
31
- assert.throws(
32
- () => events.setup([123]),
33
- /Event names must be strings/,
34
- 'Throws error for non-string event names'
35
- );
36
-
37
- events.reset();
38
- });
39
-
40
- test('Events: subscribe() adds callbacks', function (assert) {
41
- const events = new Events();
42
- events.reset();
43
-
44
- events.setup(['testEvent']);
45
-
46
- const callback1 = () => {};
47
- const callback2 = () => {};
48
-
49
- events.subscribe('testEvent', callback1);
50
- events.subscribe('testEvent', callback2);
51
-
52
- const subscribers = events.events.get('testEvent');
53
- assert.strictEqual(subscribers.size, 2, 'Two callbacks subscribed');
54
- assert.ok(subscribers.has(callback1), 'callback1 is subscribed');
55
- assert.ok(subscribers.has(callback2), 'callback2 is subscribed');
56
-
57
- events.reset();
58
- });
59
-
60
- test('Events: subscribe() throws for unregistered events', function (assert) {
61
- const events = new Events();
62
- events.reset();
63
-
64
- assert.throws(
65
- () => events.subscribe('unregisteredEvent', () => {}),
66
- /Event "unregisteredEvent" is not registered/,
67
- 'Throws error for unregistered event'
68
- );
69
-
70
- events.reset();
71
- });
72
-
73
- test('Events: subscribe() throws for non-function callbacks', function (assert) {
74
- const events = new Events();
75
- events.reset();
76
-
77
- events.setup(['testEvent']);
78
-
79
- assert.throws(
80
- () => events.subscribe('testEvent', 'not-a-function'),
81
- /Callback must be a function/,
82
- 'Throws error for non-function callback'
83
- );
84
-
85
- events.reset();
86
- });
87
-
88
- test('Events: emit() calls all subscribed callbacks', async function (assert) {
89
- const events = new Events();
90
- events.reset();
91
-
92
- events.setup(['testEvent']);
93
-
94
- let call1 = false;
95
- let call2 = false;
96
- let receivedData = null;
97
-
98
- events.subscribe('testEvent', (data) => {
99
- call1 = true;
100
- receivedData = data;
101
- });
102
-
103
- events.subscribe('testEvent', () => {
104
- call2 = true;
105
- });
106
-
107
- await events.emit('testEvent', { value: 42 });
108
-
109
- assert.ok(call1, 'First callback was called');
110
- assert.ok(call2, 'Second callback was called');
111
- assert.deepEqual(receivedData, { value: 42 }, 'Callback received correct data');
112
-
113
- events.reset();
114
- });
115
-
116
- test('Events: emit() supports async handlers', async function (assert) {
117
- const events = new Events();
118
- events.reset();
119
-
120
- events.setup(['testEvent']);
121
-
122
- let asyncComplete = false;
123
-
124
- events.subscribe('testEvent', async () => {
125
- await new Promise((resolve) => setTimeout(resolve, 10));
126
- asyncComplete = true;
127
- });
128
-
129
- await events.emit('testEvent');
130
-
131
- assert.ok(asyncComplete, 'Async handler completed');
132
-
133
- events.reset();
134
- });
135
-
136
- test('Events: emit() isolates errors per handler', async function (assert) {
137
- const events = new Events();
138
- events.reset();
139
-
140
- events.setup(['testEvent']);
141
-
142
- let handler1Called = false;
143
- let handler2Called = false;
144
- let handler3Called = false;
145
-
146
- events.subscribe('testEvent', () => {
147
- handler1Called = true;
148
- });
149
-
150
- events.subscribe('testEvent', () => {
151
- handler2Called = true;
152
- throw new Error('Handler 2 failed');
153
- });
154
-
155
- events.subscribe('testEvent', () => {
156
- handler3Called = true;
157
- });
158
-
159
- // Suppress console.error during test
160
- const originalConsoleError = console.error;
161
- console.error = () => {};
162
-
163
- await events.emit('testEvent');
164
-
165
- console.error = originalConsoleError;
166
-
167
- assert.ok(handler1Called, 'Handler 1 was called');
168
- assert.ok(handler2Called, 'Handler 2 was called (even though it threw)');
169
- assert.ok(handler3Called, 'Handler 3 was called (despite handler 2 throwing)');
170
-
171
- events.reset();
172
- });
173
-
174
- test('Events: once() subscribes and auto-unsubscribes after first emit', async function (assert) {
175
- const events = new Events();
176
- events.reset();
177
-
178
- events.setup(['testEvent']);
179
-
180
- let callCount = 0;
181
-
182
- events.once('testEvent', () => {
183
- callCount++;
184
- });
185
-
186
- await events.emit('testEvent');
187
- assert.strictEqual(callCount, 1, 'Callback called on first emit');
188
-
189
- await events.emit('testEvent');
190
- assert.strictEqual(callCount, 1, 'Callback not called on second emit');
191
-
192
- events.reset();
193
- });
194
-
195
- test('Events: once() throws for unregistered events', function (assert) {
196
- const events = new Events();
197
- events.reset();
198
-
199
- assert.throws(
200
- () => events.once('unregisteredEvent', () => {}),
201
- /Event "unregisteredEvent" is not registered/,
202
- 'Throws error for unregistered event'
203
- );
204
-
205
- events.reset();
206
- });
207
-
208
- test('Events: unsubscribe() removes specific callback', async function (assert) {
209
- const events = new Events();
210
- events.reset();
211
-
212
- events.setup(['testEvent']);
213
-
214
- let call1 = false;
215
- let call2 = false;
216
-
217
- const callback1 = () => {
218
- call1 = true;
219
- };
220
- const callback2 = () => {
221
- call2 = true;
222
- };
223
-
224
- events.subscribe('testEvent', callback1);
225
- events.subscribe('testEvent', callback2);
226
-
227
- events.unsubscribe('testEvent', callback1);
228
-
229
- await events.emit('testEvent');
230
-
231
- assert.notOk(call1, 'Unsubscribed callback1 was not called');
232
- assert.ok(call2, 'Callback2 was still called');
233
-
234
- events.reset();
235
- });
236
-
237
- test('Events: subscribe() returns unsubscribe function', async function (assert) {
238
- const events = new Events();
239
- events.reset();
240
-
241
- events.setup(['testEvent']);
242
-
243
- let callCount = 0;
244
-
245
- const unsubscribe = events.subscribe('testEvent', () => {
246
- callCount++;
247
- });
248
-
249
- await events.emit('testEvent');
250
- assert.strictEqual(callCount, 1, 'Callback called before unsubscribe');
251
-
252
- unsubscribe();
253
-
254
- await events.emit('testEvent');
255
- assert.strictEqual(callCount, 1, 'Callback not called after unsubscribe');
256
-
257
- events.reset();
258
- });
259
-
260
- test('Events: clear() removes all subscriptions for an event', async function (assert) {
261
- const events = new Events();
262
- events.reset();
263
-
264
- events.setup(['testEvent']);
265
-
266
- let call1 = false;
267
- let call2 = false;
268
-
269
- events.subscribe('testEvent', () => {
270
- call1 = true;
271
- });
272
- events.subscribe('testEvent', () => {
273
- call2 = true;
274
- });
275
-
276
- events.clear('testEvent');
277
-
278
- await events.emit('testEvent');
279
-
280
- assert.notOk(call1, 'Callback1 was not called after clear');
281
- assert.notOk(call2, 'Callback2 was not called after clear');
282
-
283
- events.reset();
284
- });
285
-
286
- test('Events: reset() clears all subscriptions and events', function (assert) {
287
- const events = new Events();
288
- events.reset();
289
-
290
- events.setup(['testEvent1', 'testEvent2']);
291
- events.subscribe('testEvent1', () => {});
292
-
293
- events.reset();
294
-
295
- assert.strictEqual(events.registeredEvents.size, 0, 'No events registered after reset');
296
- assert.strictEqual(events.events.size, 0, 'No subscriptions after reset');
297
-
298
- events.reset();
299
- });
300
-
301
- test('Events: singleton pattern works', function (assert) {
302
- const events1 = new Events();
303
- events1.reset();
304
-
305
- events1.setup(['testEvent']);
306
-
307
- const events2 = new Events();
308
-
309
- assert.strictEqual(events1, events2, 'Both instances are the same');
310
- assert.ok(events2.registeredEvents.has('testEvent'), 'Second instance has same registered events');
311
-
312
- events1.reset();
313
- });
314
-
315
- test('Events: emit() does nothing for events with no subscribers', async function (assert) {
316
- const events = new Events();
317
- events.reset();
318
-
319
- events.setup(['testEvent']);
320
-
321
- // Should not throw
322
- await events.emit('testEvent');
323
-
324
- assert.ok(true, 'No error when emitting to event with no subscribers');
325
-
326
- events.reset();
327
- });
328
-
329
- test('Events: emit() does nothing for unregistered events', async function (assert) {
330
- const events = new Events();
331
- events.reset();
332
-
333
- // Should not throw
334
- await events.emit('unregisteredEvent');
335
-
336
- assert.ok(true, 'No error when emitting unregistered event');
337
-
338
- events.reset();
339
- });
340
-
341
- });