@reldens/skills 0.45.0 → 0.47.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.
Files changed (41) hide show
  1. package/.claude/architecture.md +472 -0
  2. package/.claude/class-hierarchy.md +982 -0
  3. package/.claude/event-system-architecture.md +475 -0
  4. package/.claude/level-progression.md +1259 -0
  5. package/.claude/skill-execution-flow.md +979 -0
  6. package/.claude/testing-guide.md +356 -0
  7. package/.claude/testing-patterns.md +1096 -0
  8. package/CLAUDE.md +164 -29
  9. package/lib/class-path.js +13 -10
  10. package/lib/client/receiver.js +1 -3
  11. package/lib/levels-set.js +24 -17
  12. package/lib/server/sender.js +1 -1
  13. package/lib/skill.js +19 -16
  14. package/lib/types/attack.js +28 -11
  15. package/lib/types/effect.js +10 -4
  16. package/lib/types/physical-attack.js +2 -2
  17. package/lib/types/physical-effect.js +2 -2
  18. package/lib/types/physical-properties-validator.js +1 -1
  19. package/lib/types/physical-skill-runner.js +5 -5
  20. package/package.json +9 -3
  21. package/tests/fixtures/levels/base-levels.js +89 -0
  22. package/tests/fixtures/mocks/mock-client.js +44 -0
  23. package/tests/fixtures/mocks/mock-owner.js +60 -0
  24. package/tests/fixtures/mocks/mock-target.js +50 -0
  25. package/tests/fixtures/skills/base-skills.js +80 -0
  26. package/tests/run-tests.js +88 -0
  27. package/tests/unit/client/test-receiver.js +249 -0
  28. package/tests/unit/server/test-sender.js +527 -0
  29. package/tests/unit/test-class-path.js +1239 -0
  30. package/tests/unit/test-level.js +176 -0
  31. package/tests/unit/test-levels-set.js +1227 -0
  32. package/tests/unit/test-server.js +266 -0
  33. package/tests/unit/test-skill.js +1302 -0
  34. package/tests/unit/types/test-attack.js +1195 -0
  35. package/tests/unit/types/test-effect.js +587 -0
  36. package/tests/unit/types/test-physical-attack.js +564 -0
  37. package/tests/unit/types/test-physical-effect.js +769 -0
  38. package/tests/unit/types/test-physical-properties-validator.js +203 -0
  39. package/tests/unit/types/test-physical-skill-runner.js +348 -0
  40. package/tests/utils/test-helpers.js +122 -0
  41. package/migrations/production/reldens-skills-install.sql +0 -275
@@ -0,0 +1,475 @@
1
+ # EVENT SYSTEM ARCHITECTURE
2
+ ## @reldens/skills Package Event Flow
3
+
4
+ ---
5
+
6
+ ## OVERVIEW
7
+
8
+ The @reldens/skills package uses a sophisticated event-driven architecture based on `EventsManagerSingleton` from `@reldens/utils`. Understanding this system is critical for proper implementation and testing.
9
+
10
+ ---
11
+
12
+ ## EVENT MANAGER SINGLETON
13
+
14
+ **File:** `@reldens/utils` package
15
+ **Instance:** `EventsManagerSingleton`
16
+
17
+ ### Key Characteristics
18
+
19
+ 1. **Global Singleton**: Only ONE instance exists across the entire application
20
+ 2. **Shared by ALL entities**: Skills, ClassPath, LevelsSet, Sender, etc. all use the SAME EventsManager
21
+ 3. **removeKey Registry**: Maintains a GLOBAL registry of removeKeys that persists between listener registrations
22
+ 4. **Owner-Namespaced Events**: Events are prefixed with owner identifiers to avoid cross-owner collisions
23
+
24
+ ---
25
+
26
+ ## EVENT NAMING CONVENTION
27
+
28
+ ### Event Name Construction
29
+
30
+ ```javascript
31
+ // File: lib/levels-set.js:267-272
32
+ eventFullName(eventName) {
33
+ return this.getOwnerEventKey() + '.' + eventName;
34
+ }
35
+
36
+ getOwnerEventKey() {
37
+ return sc.get(this.owner, 'eventsPrefix', 'skills.ownerId.' + this.getOwnerId());
38
+ }
39
+ ```
40
+
41
+ ### Example Event Names
42
+
43
+ Given:
44
+ - Owner ID: `'player-123'`
45
+ - Owner eventsPrefix: `'skills.ownerId.player-123'`
46
+ - Event: `'reldens.skills.levelUp'`
47
+
48
+ **Full Event Name:**
49
+ ```
50
+ skills.ownerId.player-123.reldens.skills.levelUp
51
+ ```
52
+
53
+ This ensures events for Player 123 don't trigger listeners registered for Player 456.
54
+
55
+ ---
56
+
57
+ ## LISTENER REGISTRATION
58
+
59
+ ### Method Signature
60
+
61
+ ```javascript
62
+ // File: lib/levels-set.js:262-265
63
+ listenEvent(eventName, callback, removeKey, masterKey) {
64
+ return this.events.onWithKey(
65
+ this.eventFullName(eventName), // Full namespaced event name
66
+ callback, // Function to execute
67
+ removeKey, // Unique identifier for removal
68
+ masterKey // Master removal key (optional)
69
+ );
70
+ }
71
+ ```
72
+
73
+ ### Parameters Explained
74
+
75
+ | Parameter | Type | Required | Purpose |
76
+ |-----------|------|----------|---------|
77
+ | `eventName` | string | Yes | Base event name (e.g., `SkillsEvents.LEVEL_UP`) |
78
+ | `callback` | function | Yes | Function to execute when event fires |
79
+ | `removeKey` | string | No | **UNIQUE** identifier for this specific listener |
80
+ | `masterKey` | string | No | Master key for bulk removal (unused in current codebase) |
81
+
82
+ ### Critical: removeKey Uniqueness
83
+
84
+ **IMPORTANT:** The `removeKey` parameter MUST be globally unique across your entire application!
85
+
86
+ **WHY:** EventsManagerSingleton maintains a global removeKey registry that is NOT cleared by `removeAllListeners()`.
87
+
88
+ **Bad Example (Causes Collisions):**
89
+ ```javascript
90
+ // Test 1
91
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'before-listener');
92
+
93
+ // afterEach() calls EventsManagerSingleton.removeAllListeners()
94
+
95
+ // Test 2 - COLLISION!
96
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'before-listener');
97
+ // ❌ Registration fails silently - removeKey 'before-listener' already exists
98
+ ```
99
+
100
+ **Good Example:**
101
+ ```javascript
102
+ // Test 1
103
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'add-before-listener');
104
+
105
+ // Test 2
106
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'remove-before-listener');
107
+ // ✓ Different removeKey - works correctly
108
+ ```
109
+
110
+ ---
111
+
112
+ ## EVENT FIRING
113
+
114
+ ### Method Signature
115
+
116
+ ```javascript
117
+ // File: lib/levels-set.js:257-260
118
+ async fireEvent(eventName, ...args) {
119
+ return await this.events.emit(this.eventFullName(eventName), ...args);
120
+ }
121
+ ```
122
+
123
+ ### Execution Flow
124
+
125
+ 1. **Build Full Event Name**: `eventFullName()` adds owner prefix
126
+ 2. **Emit to EventsManager**: `emit()` finds all registered listeners for that exact event name
127
+ 3. **Execute Callbacks**: All matching listeners execute (synchronously in callback, but emit is async)
128
+ 4. **Return**: After all listeners complete
129
+
130
+ ### Key Points
131
+
132
+ - `fireEvent` is `async` and should be `awaited`
133
+ - Callbacks execute in registration order
134
+ - If no listeners exist, emit() completes immediately (no error)
135
+ - Listeners execute **synchronously** within the emit call (despite async emit method)
136
+
137
+ ---
138
+
139
+ ## COMMON EVENT PATTERNS
140
+
141
+ ### Pattern 1: Skill Execution Events
142
+
143
+ ```javascript
144
+ // Before skill execution
145
+ await this.fireEvent(SkillsEvents.SKILL_BEFORE_EXECUTE, this, target);
146
+
147
+ // Execute skill logic
148
+ let result = await this.doSomething();
149
+
150
+ // After skill execution
151
+ await this.fireEvent(SkillsEvents.SKILL_AFTER_EXECUTE, this, target);
152
+ ```
153
+
154
+ ### Pattern 2: Modifier Application Events
155
+
156
+ ```javascript
157
+ // Before applying modifiers
158
+ await this.fireEvent(SkillsEvents.SKILL_APPLY_OWNER_EFFECTS, this, target);
159
+
160
+ // Apply modifiers
161
+ this.applyModifiers(this.ownerEffects, this.owner, true);
162
+
163
+ // Modifiers applied (no after event - fire within applyModifiers if needed)
164
+ ```
165
+
166
+ ### Pattern 3: Level Progression Events
167
+
168
+ ```javascript
169
+ // Before level up
170
+ await this.fireEvent(SkillsEvents.LEVEL_UP, this);
171
+
172
+ // Apply level modifiers
173
+ await this.applyLevelModifiers();
174
+
175
+ // Level up complete (no explicit after event)
176
+ ```
177
+
178
+ ---
179
+
180
+ ## EVENT PARAMETERS
181
+
182
+ ### Common Parameter Patterns
183
+
184
+ Most events pass:
185
+ 1. **`this`** - The object firing the event (Skill, ClassPath, etc.)
186
+ 2. **Additional context** - Target, skills, damage, etc.
187
+
188
+ ### Example Event Parameters
189
+
190
+ ```javascript
191
+ // SKILL_BEFORE_EXECUTE
192
+ await this.fireEvent(SkillsEvents.SKILL_BEFORE_EXECUTE, this, target);
193
+ // Params: (skill, target)
194
+
195
+ // SKILL_ATTACK_APPLY_DAMAGE
196
+ await this.fireEvent(SkillsEvents.SKILL_ATTACK_APPLY_DAMAGE, this, target, damage, newValue);
197
+ // Params: (skill, target, damage, newValue)
198
+
199
+ // LEVEL_EXPERIENCE_ADDED
200
+ await this.fireEvent(SkillsEvents.LEVEL_EXPERIENCE_ADDED,
201
+ this, // levelsSet
202
+ number, // xp added
203
+ newTotalExp, // new total
204
+ currentLevelIndex, // index
205
+ nextLevelIndex, // next index
206
+ nextLevelKey, // next key
207
+ nextLevel, // next Level object
208
+ nextLevelExp, // xp required
209
+ isLevelUp // boolean
210
+ );
211
+ // Params: (levelsSet, number, newTotal, currentIdx, nextIdx, nextKey, nextLevel, nextExp, isLevelUp)
212
+ ```
213
+
214
+ ---
215
+
216
+ ## SERVER-CLIENT EVENT SYNCHRONIZATION
217
+
218
+ ### Sender Pattern (Server-Side)
219
+
220
+ **File:** `lib/server/sender.js`
221
+
222
+ The Sender class listens to ClassPath events and broadcasts them to connected clients:
223
+
224
+ ```javascript
225
+ // Example: Level Up
226
+ this.classPath.listenEvent(SkillsEvents.LEVEL_UP, async (classPath) => {
227
+ await this.sendLevelUpData(classPath);
228
+ }, this.getOwnerUniqueEventKey('sender.level.up'));
229
+ ```
230
+
231
+ **Flow:**
232
+ 1. Server: ClassPath.levelUp() fires LEVEL_UP event
233
+ 2. Server: Sender listener catches event
234
+ 3. Server: Sender.sendLevelUpData() constructs message
235
+ 4. Server: Client.send() or Client.broadcast() transmits message
236
+ 5. Client: Receives message
237
+ 6. Client: Receiver.processMessage() handles it
238
+
239
+ ### Message Format
240
+
241
+ ```javascript
242
+ {
243
+ act: 'rski.Lu', // Action constant (LEVEL_UP)
244
+ owner: 'player-123',
245
+ data: {
246
+ lvl: 5, // Current level
247
+ lab: 'Warrior', // Label
248
+ ne: 2000, // Next level XP
249
+ skl: ['sword', 'shield'] // Skill keys
250
+ }
251
+ }
252
+ ```
253
+
254
+ ### Receiver Pattern (Client-Side)
255
+
256
+ **File:** `lib/client/receiver.js`
257
+
258
+ The Receiver processes incoming messages and maps them to handler methods:
259
+
260
+ ```javascript
261
+ // In your client code:
262
+ class MyGameClient extends Receiver {
263
+ onLevelUp(message) {
264
+ console.log('Level up!', message.data.lvl);
265
+ // Update UI, play animation, etc.
266
+ }
267
+ }
268
+
269
+ // Process all incoming messages
270
+ gameServer.onMessage('*', (message) => {
271
+ receiver.processMessage(message);
272
+ });
273
+ ```
274
+
275
+ ---
276
+
277
+ ## TESTING ANTI-PATTERNS
278
+
279
+ ### ❌ ANTI-PATTERN 1: Testing Through Events (Race Conditions)
280
+
281
+ **BAD:**
282
+ ```javascript
283
+ it('should send level up message', async () => {
284
+ let sender = new Sender(classPath, mockClient);
285
+ sender.registerListeners(); // Registers event listener
286
+
287
+ await classPath.levelUp(); // Fires event asynchronously
288
+
289
+ // Race condition! Event may not have completed yet
290
+ assert.strictEqual(mockClient.sentMessages.length, 1); // ❌ May fail randomly
291
+ });
292
+ ```
293
+
294
+ **GOOD:**
295
+ ```javascript
296
+ it('should send level up message', async () => {
297
+ let sender = new Sender(classPath, mockClient);
298
+ sender.registerListeners();
299
+
300
+ // Call method directly, not through events
301
+ await sender.sendLevelUpData(classPath); // ✓ Deterministic
302
+
303
+ assert.strictEqual(mockClient.sentMessages.length, 1); // ✓ Always works
304
+ });
305
+ ```
306
+
307
+ ### ❌ ANTI-PATTERN 2: Using sleep() to Fix Race Conditions
308
+
309
+ **BAD:**
310
+ ```javascript
311
+ await classPath.levelUp();
312
+ await TestHelpers.sleep(10); // ❌ Hack to wait for async events
313
+ assert.strictEqual(eventFired, true);
314
+ ```
315
+
316
+ **GOOD:**
317
+ ```javascript
318
+ await sender.sendLevelUpData(classPath); // ✓ Call directly
319
+ assert.strictEqual(eventFired, true);
320
+ ```
321
+
322
+ **When sleep() IS Appropriate:**
323
+ ```javascript
324
+ // Testing actual timer features (skillDelay, castTime)
325
+ skill.validate(); // Sets skillActivationTimer
326
+ await TestHelpers.sleep(skill.skillDelay + 10); // ✓ Testing timer behavior
327
+ assert.strictEqual(skill.canActivate, true);
328
+ ```
329
+
330
+ ### ❌ ANTI-PATTERN 3: Reusing removeKeys
331
+
332
+ **BAD:**
333
+ ```javascript
334
+ // Test 1
335
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'listener');
336
+
337
+ // Test 2 (after clearEventListeners)
338
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'listener');
339
+ // ❌ removeKey collision!
340
+ ```
341
+
342
+ **GOOD:**
343
+ ```javascript
344
+ // Test 1
345
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'add-listener');
346
+
347
+ // Test 2
348
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'remove-listener');
349
+ // ✓ Unique removeKeys
350
+ ```
351
+
352
+ ---
353
+
354
+ ## EVENT LIFECYCLE
355
+
356
+ ### Skill Execution Event Sequence
357
+
358
+ ```
359
+ 1. VALIDATE_BEFORE
360
+ 2. VALIDATE_SUCCESS (or VALIDATE_FAIL)
361
+ 3. SKILL_BEFORE_EXECUTE
362
+ 4. SKILL_APPLY_OWNER_EFFECTS (if ownerEffects exist)
363
+ 5. SKILL_BEFORE_CAST (if castTime > 0)
364
+ 6. SKILL_BEFORE_RUN_LOGIC
365
+ 7. SKILL_AFTER_RUN_LOGIC
366
+ 8. SKILL_AFTER_CAST (if castTime > 0)
367
+ 9. SKILL_AFTER_EXECUTE
368
+ ```
369
+
370
+ ### Attack Skill Additional Events
371
+
372
+ ```
373
+ 10. SKILL_ATTACK_APPLY_DAMAGE (when damage is applied)
374
+ ```
375
+
376
+ ### Effect Skill Additional Events
377
+
378
+ ```
379
+ 10. SKILL_EFFECT_TARGET_MODIFIERS (when modifiers are applied)
380
+ ```
381
+
382
+ ### Physical Skill Additional Events
383
+
384
+ ```
385
+ 10. SKILL_PHYSICAL_ATTACK_HIT (on collision)
386
+ 11. SKILL_PHYSICAL_EFFECT_HIT (on collision)
387
+ ```
388
+
389
+ ### Level Progression Event Sequence
390
+
391
+ ```
392
+ 1. INIT_LEVEL_SET_START
393
+ 2. SET_LEVELS
394
+ 3. GENERATED_LEVELS (for each auto-filled level range)
395
+ 4. INIT_LEVEL_SET_END
396
+ 5. LEVEL_EXPERIENCE_ADDED (when XP is added)
397
+ 6. LEVEL_UP (when level increases)
398
+ 7. LEVEL_DOWN (when level decreases)
399
+ 8. LEVEL_APPLY_MODIFIERS (before modifiers are applied/reverted)
400
+ ```
401
+
402
+ ### ClassPath Event Sequence
403
+
404
+ ```
405
+ 1. INIT_CLASS_PATH_END (after initialization)
406
+ 2. SET_SKILLS (after setOwnerSkills)
407
+ 3. ADD_SKILLS_BEFORE
408
+ 4. ADD_SKILLS_AFTER
409
+ 5. REMOVE_SKILLS_BEFORE
410
+ 6. REMOVE_SKILLS_AFTER
411
+ ```
412
+
413
+ ---
414
+
415
+ ## EVENT DEBUGGING TIPS
416
+
417
+ ### 1. Check Event Name Construction
418
+
419
+ ```javascript
420
+ // Add logging in development
421
+ async fireEvent(eventName, ...args) {
422
+ let fullName = this.eventFullName(eventName);
423
+ console.log('[EVENT]', fullName, args);
424
+ return await this.events.emit(fullName, ...args);
425
+ }
426
+ ```
427
+
428
+ ### 2. Verify Listener Registration
429
+
430
+ ```javascript
431
+ // Log when registering
432
+ listenEvent(eventName, callback, removeKey, masterKey) {
433
+ let fullName = this.eventFullName(eventName);
434
+ console.log('[LISTEN]', fullName, 'key:', removeKey);
435
+ return this.events.onWithKey(fullName, callback, removeKey, masterKey);
436
+ }
437
+ ```
438
+
439
+ ### 3. Check removeKey Collisions
440
+
441
+ ```javascript
442
+ // Ensure all removeKeys are unique in your tests
443
+ let removeKeys = new Set();
444
+
445
+ function registerListener(event, callback, removeKey) {
446
+ if (removeKeys.has(removeKey)) {
447
+ throw new Error(`removeKey collision: ${removeKey}`);
448
+ }
449
+ removeKeys.add(removeKey);
450
+ return classPath.listenEvent(event, callback, removeKey);
451
+ }
452
+ ```
453
+
454
+ ---
455
+
456
+ ## CRITICAL RULES
457
+
458
+ 1. **Always await fireEvent()** - It's async for a reason
459
+ 2. **Use unique removeKeys** - Never reuse removeKeys across tests
460
+ 3. **Test methods directly** - Don't test through events unless testing the event system itself
461
+ 4. **Never use sleep() for race conditions** - Fix the test pattern instead
462
+ 5. **Clear listeners properly** - Call TestHelpers.clearEventListeners() in afterEach
463
+ 6. **Namespace by owner** - Event names automatically include owner prefix
464
+ 7. **Pass complete context** - Include all relevant data as event parameters
465
+ 8. **Document event parameters** - Comment what each event passes to listeners
466
+
467
+ ---
468
+
469
+ ## REFERENCES
470
+
471
+ - Event Names: `lib/skills-events.js`
472
+ - Event Methods: `lib/levels-set.js:257-272`
473
+ - Sender Integration: `lib/server/sender.js`
474
+ - Receiver Integration: `lib/client/receiver.js`
475
+ - Test Helpers: `tests/utils/test-helpers.js`