@reldens/skills 0.56.0 → 0.59.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/CLAUDE.md CHANGED
@@ -1,619 +1,619 @@
1
- ## Package Overview
2
-
3
- **@reldens/skills** (v0.47.0) is a comprehensive skills, leveling, and combat system that provides:
4
- - Level sets with automatic progression and experience management
5
- - Class paths with skill trees and level-dependent unlocks
6
- - Multiple skill types (base, attack, effect, physical variants)
7
- - Combat mechanics (damage calculation, critical hits, dodge system)
8
- - Real-time server-client synchronization via Sender/Receiver pattern
9
- - Event-driven architecture for custom logic integration
10
- - Modifiers system integration via @reldens/modifiers
11
-
12
- This package is part of the Reldens MMORPG Platform ecosystem and can be attached to any entity owner with position methods.
13
-
14
- ## Comprehensive Documentation
15
-
16
- **Detailed technical documentation is available in the `.claude/` directory:**
17
-
18
- - **[Event System Architecture](.claude/event-system-architecture.md)** - Complete event system documentation including EventsManagerSingleton, removeKey registry, event naming, and testing anti-patterns
19
- - **[Skill Execution Flow](.claude/skill-execution-flow.md)** - Step-by-step skill execution phases, type-specific logic, and complete sequence diagrams
20
- - **[Testing Patterns](.claude/testing-patterns.md)** - Best practices, anti-patterns, and critical lessons learned from test suite debugging
21
- - **[Level Progression](.claude/level-progression.md)** - Complete leveling system guide including auto-fill, experience management, and class paths
22
- - **[Class Hierarchy](.claude/class-hierarchy.md)** - Architecture reference with inheritance, composition, and integration patterns
23
-
24
- **Always consult these documents when working with the corresponding systems.**
25
-
26
- ## Key Commands
27
-
28
- ```bash
29
- # Run all tests
30
- npm test
31
-
32
- # Run tests in watch mode
33
- npm run test:watch
34
-
35
- # Run specific tests with filter
36
- npm run test:filter=skill
37
-
38
- # Run tests with coverage
39
- npm run test:coverage
40
- ```
41
-
42
- ## Architecture
43
-
44
- ### Package Structure
45
-
46
- ```
47
- lib/
48
- ├── skill.js # Base Skill class
49
- ├── level.js # Single level with modifiers
50
- ├── levels-set.js # Level progression system
51
- ├── class-path.js # Skill tree with class progression
52
- ├── server.js # SkillsServer wrapper
53
- ├── constants.js # Shared constants and action names
54
- ├── skills-events.js # Event name definitions
55
- ├── server/
56
- │ └── sender.js # Server-to-client message sender
57
- ├── client/
58
- │ └── receiver.js # Client message receiver
59
- └── types/
60
- ├── attack.js # Damage-based skills
61
- ├── effect.js # Modifier-based skills
62
- ├── physical-attack.js # Physics-enabled attacks
63
- ├── physical-effect.js # Physics-enabled effects
64
- ├── physical-properties-validator.js
65
- └── physical-skill-runner.js
66
- ```
67
-
68
- ### Core Classes
69
-
70
- **Skill** (`lib/skill.js:12`):
71
- - Base class for all skills
72
- - Provides validation, execution, range checking
73
- - Event system integration
74
- - Owner/target relationship management
75
- - Critical hit system (chance, multiplier, fixed value)
76
- - Cooldown/delay system (`skillDelay`, `canActivate`)
77
- - Cast time support with `castTime` property
78
- - Owner conditions validation
79
- - Owner effects application
80
- - Properties:
81
- - `key`: Unique skill identifier
82
- - `owner`: Entity that owns the skill (must have `getPosition()` method)
83
- - `target`: Target entity (can be fixed or passed on execution)
84
- - `range`: Skill range (0 = infinite range)
85
- - `rangeAutomaticValidation`: Auto-validate range before execution
86
- - `allowSelfTarget`: Allow targeting the owner
87
- - `usesLimit`: Maximum uses (0 = unlimited)
88
- - `ownerConditions`: Array of Condition instances
89
- - `ownerEffects`: Array of modifiers applied to owner on execution
90
- - `criticalChance`, `criticalMultiplier`, `criticalFixedValue`
91
-
92
- **Level** (`lib/level.js:9`):
93
- - Represents a single level with:
94
- - `key`: Integer level number
95
- - `modifiers`: Array of modifiers applied at this level
96
- - `label`: Display name for the level
97
- - `requiredExperience`: XP required to reach this level
98
-
99
- **LevelsSet** (`lib/levels-set.js:11`):
100
- - Manages level progression and experience
101
- - Auto-fills level ranges if `autoFillRanges` enabled
102
- - Experience-based automatic leveling
103
- - Modifier application/reversion on level up/down
104
- - Properties:
105
- - `owner`: Entity with `getPosition()` method
106
- - `levels`: Object of Level instances
107
- - `currentLevel`: Current level number
108
- - `currentExp`: Current experience points
109
- - `autoFillRanges`: Auto-generate intermediate levels
110
- - `autoFillExperienceMultiplier`: XP multiplier for auto-generated levels (default: 1.5)
111
- - `increaseLevelsWithExperience`: Auto level up when XP threshold reached
112
- - `levelsByExperience`: Sorted array of level keys by required XP
113
- - `setRequiredExperienceLimit`: Cap XP at max level requirement
114
- - Methods:
115
- - `levelUp()`: Increase level, apply modifiers
116
- - `levelDown()`: Decrease level, revert modifiers
117
- - `addExperience(number)`: Add XP, auto-level if enabled
118
- - `getNextLevelExperience()`: Get XP required for next level
119
-
120
- **ClassPath** (`lib/class-path.js:11`):
121
- - Extends LevelsSet
122
- - Provides skill tree functionality
123
- - Level-based skill unlocking
124
- - Dynamic label changes per level
125
- - Properties:
126
- - `key`: Class path identifier
127
- - `label`: Base display name
128
- - `labelsByLevel`: Object of {levelKey: 'label'} for level-specific names
129
- - `currentLabel`: Active display name
130
- - `skillsByLevel`: Object of {levelKey: [Skill instances]}
131
- - `skillsByLevelKeys`: Object of {levelKey: [skill keys]}
132
- - `currentSkills`: Object of currently available skills
133
- - `affectedProperty`: Property affected by class skills (e.g., 'hp')
134
- - Methods:
135
- - `addSkills(skills)`: Add skills to current set
136
- - `removeSkills(skills)`: Remove skills from current set
137
- - `setOwnerSkills(skills)`: Initialize owner's skill set based on current level
138
-
139
- **SkillsServer** (`lib/server.js:11`):
140
- - Server-side wrapper for ClassPath
141
- - Integrates Sender for client communication
142
- - Validates client has `send()` and `broadcast()` methods
143
- - Automatically initializes ClassPath and registers listeners
144
-
145
- ### Skill Types
146
-
147
- **Attack** (`lib/types/attack.js:14`):
148
- - Extends Skill for damage-based skills
149
- - Damage calculation with attack vs defense properties
150
- - Dodge system with aim vs dodge properties
151
- - Critical damage affected by aim/dodge ratio
152
- - Properties:
153
- - `affectedProperty`: Target property to modify (e.g., 'hp')
154
- - `hitDamage`: Base damage at 100%
155
- - `applyDirectDamage`: Skip calculations, apply hitDamage directly
156
- - `attackProperties`: Array of owner properties for attack total
157
- - `defenseProperties`: Array of target properties for defense total
158
- - `aimProperties`: Array of owner properties for aim total
159
- - `dodgeProperties`: Array of target properties for dodge total
160
- - `dodgeFullEnabled`: Enable complete dodge if dodge > (aim * dodgeOverAimSuccess)
161
- - `dodgeOverAimSuccess`: Dodge threshold multiplier (default: 1)
162
- - `damageAffected`: Apply dodge/aim ratio to damage
163
- - `criticalAffected`: Apply dodge/aim ratio to critical damage
164
- - `propertiesTotalOperators`: Custom operators for property totals
165
- - `allowEffectBelowZero`: Allow negative values on affected property
166
- - Damage Calculation:
167
- 1. Calculate owner aim and target dodge totals
168
- 2. Check full dodge: `dodge > (aim * dodgeOverAimSuccess)`
169
- 3. Calculate base damage: `hitDamage` modified by attack vs defense diff
170
- 4. Apply dodge/aim ratio if `damageAffected` enabled
171
- 5. Calculate critical damage with dodge/aim ratio if `criticalAffected`
172
- 6. Apply total damage to `affectedProperty`
173
-
174
- **Effect** (`lib/types/effect.js:14`):
175
- - Extends Skill for modifier-based skills (buffs/debuffs)
176
- - Applies modifiers to target with critical chance
177
- - Properties:
178
- - `targetEffects`: Array of modifiers applied to target
179
- - Logic: Validates range, applies modifiers with critical calculation
180
-
181
- **PhysicalAttack** (`lib/types/physical-attack.js:16`):
182
- - Extends Attack for physics-enabled attacks
183
- - Requires collision detection system
184
- - Properties:
185
- - `magnitude`: Physics force/magnitude
186
- - `objectWidth`: Collision object width
187
- - `objectHeight`: Collision object height
188
- - `validateTargetOnHit`: Verify target matches on collision
189
- - Requires owner to implement `executePhysicalSkill(target, skill)` method
190
- - Uses PhysicalSkillRunner for execution
191
- - Fires `SKILL_PHYSICAL_ATTACK_HIT` event on collision
192
- - Calls parent `runSkillLogic()` in `executeOnHit(target)` callback
193
-
194
- **PhysicalEffect** (`lib/types/physical-effect.js:16`):
195
- - Extends Effect for physics-enabled effects
196
- - Same physics properties as PhysicalAttack
197
- - Uses PhysicalSkillRunner for execution
198
- - Fires `SKILL_PHYSICAL_EFFECT_HIT` event on collision
199
-
200
- ### Communication System
201
-
202
- **Sender** (`lib/server/sender.js:11`):
203
- - Server-to-client message broadcaster
204
- - Registers event listeners on ClassPath events
205
- - Sends compressed data to client
206
- - Behaviors:
207
- - `BEHAVIOR_SEND`: Send to owner client only
208
- - `BEHAVIOR_BROADCAST`: Broadcast to all clients
209
- - `BEHAVIOR_BOTH`: Both send and broadcast
210
- - Registered Events:
211
- - `INIT_CLASS_PATH_END`: Send initial class data (level, label, XP, skills)
212
- - `LEVEL_UP`: Send level up data (new level, label, skills, next XP)
213
- - `LEVEL_EXPERIENCE_ADDED`: Send current XP
214
- - `SKILL_BEFORE_CAST`: Broadcast skill cast start
215
- - `SKILL_ATTACK_APPLY_DAMAGE`: Broadcast damage application
216
- - Message Format:
217
- ```javascript
218
- {
219
- act: 'rski.ICpe', // Action constant
220
- owner: ownerId, // Owner ID
221
- data: { // Compressed data
222
- lvl: 5, // Level
223
- lab: 'Warrior', // Label
224
- exp: 1500, // Current XP
225
- ne: 2000, // Next level XP
226
- skl: ['sword', 'shield'] // Skill keys
227
- }
228
- }
229
- ```
230
-
231
- **Receiver** (`lib/client/receiver.js:10`):
232
- - Client-side message processor
233
- - Maps action constants to method names
234
- - Validates message action prefix (`rski.`)
235
- - Properties:
236
- - `actions`: Object mapping action constants to method names
237
- - `avoidDefaults`: Skip default action-to-method mapping
238
- - Default Method Mapping: Each action constant maps to `on[ActionName]` method
239
- - Usage: Extend and implement handler methods (e.g., `onLevelUp(message)`)
240
-
241
- ### Events System
242
-
243
- All events are prefixed with `reldens.skills.` and appended with owner event key.
244
-
245
- **IMPORTANT:** See `.claude/event-system-architecture.md` for complete event system documentation including:
246
- - EventsManagerSingleton architecture and removeKey registry
247
- - Event naming conventions (owner-namespaced)
248
- - Listener registration patterns
249
- - Testing anti-patterns and race conditions
250
- - Critical rules for event usage
251
-
252
- **Level Set Events** (fired by LevelsSet):
253
- - `INIT_LEVEL_SET_START`: Before level set initialization
254
- - `INIT_LEVEL_SET_END`: After level set initialization
255
- - `SET_LEVELS`: After levels are set
256
- - `GENERATED_LEVELS`: After auto-filling a level range
257
- - `LEVEL_UP`: After level increases
258
- - `LEVEL_DOWN`: After level decreases
259
- - `LEVEL_APPLY_MODIFIERS`: Before applying level modifiers
260
- - `LEVEL_EXPERIENCE_ADDED`: After XP added (args: number, newTotal, currentLevelIndex, nextLevelIndex, nextLevelKey, nextLevel, nextLevelExp, isLevelUp)
261
-
262
- **Class Path Events** (fired by ClassPath):
263
- - `INIT_CLASS_PATH_END`: After class path initialization
264
- - `SET_SKILLS`: After owner skills set
265
- - `ADD_SKILLS_BEFORE`: Before adding skills
266
- - `ADD_SKILLS_AFTER`: After adding skills
267
- - `REMOVE_SKILLS_BEFORE`: Before removing skills
268
- - `REMOVE_SKILLS_AFTER`: After removing skills
269
-
270
- **Skill Execution Events** (fired by Skill):
271
- - `VALIDATE_BEFORE`: Before skill validation
272
- - `VALIDATE_SUCCESS`: After successful validation
273
- - `VALIDATE_FAIL`: After validation failure (args: skill, failedCondition)
274
- - `SKILL_BEFORE_IN_RANGE`: Before range check
275
- - `SKILL_AFTER_IN_RANGE`: After range check (args: skill, interactionResult)
276
- - `SKILL_BEFORE_EXECUTE`: Before skill execution
277
- - `SKILL_APPLY_OWNER_EFFECTS`: After applying owner effects
278
- - `SKILL_BEFORE_CAST`: Before cast time starts
279
- - `SKILL_AFTER_CAST`: After cast time completes
280
- - `SKILL_BEFORE_RUN_LOGIC`: Before skill logic execution
281
- - `SKILL_AFTER_RUN_LOGIC`: After skill logic execution
282
- - `SKILL_AFTER_EXECUTE`: After skill execution complete
283
-
284
- **Attack/Effect Events**:
285
- - `SKILL_ATTACK_APPLY_DAMAGE`: After damage applied (args: skill, target, damage, newValue)
286
- - `SKILL_EFFECT_TARGET_MODIFIERS`: After effect modifiers applied
287
- - `SKILL_PHYSICAL_ATTACK_HIT`: On physical attack collision
288
- - `SKILL_PHYSICAL_EFFECT_HIT`: On physical effect collision
289
-
290
- **Event Naming Convention**:
291
- Events are automatically namespaced by owner:
292
- ```javascript
293
- // Event fired as: 'skills.ownerId.123.reldens.skills.levelUp'
294
- skill.fireEvent(SkillsEvents.LEVEL_UP, this);
295
-
296
- // Listen to specific owner's events:
297
- skill.listenEvent(SkillsEvents.LEVEL_UP, callback, removeKey, masterKey);
298
- ```
299
-
300
- ### Constants
301
-
302
- **Skill Types** (`constants.js:10`):
303
- - `SKILL.TYPE.BASE`: Base skill (1)
304
- - `SKILL.TYPE.ATTACK`: Attack skill (2)
305
- - `SKILL.TYPE.EFFECT`: Effect skill (3)
306
- - `SKILL.TYPE.PHYSICAL_ATTACK`: Physical attack (4)
307
- - `SKILL.TYPE.PHYSICAL_EFFECT`: Physical effect (5)
308
-
309
- **Skill States** (`constants.js:53`):
310
- - `PHYSICAL_SKILL_INVALID_TARGET`: Target validation failed
311
- - `PHYSICAL_SKILL_RUN_LOGIC`: Running physical skill logic
312
- - `OUT_OF_RANGE`: Target out of range
313
- - `CAN_NOT_ACTIVATE`: Skill on cooldown or owner casting
314
- - `DODGED`: Attack dodged
315
- - `APPLYING_DAMAGE`: Damage calculation in progress
316
- - `APPLIED_DAMAGE`: Damage applied successfully
317
- - `APPLIED_CRITICAL_DAMAGE`: Critical damage applied
318
- - `APPLYING_EFFECTS`: Effects being applied
319
- - `APPLIED_EFFECTS`: Effects applied successfully
320
- - `EXECUTE_PHYSICAL_ATTACK`: Physical attack executing
321
- - `TARGET_NOT_AVAILABLE`: Target undefined or invalid
322
-
323
- **Action Constants** (`constants.js:7`):
324
- All action constants use `rski.` prefix (Reldens Skills) for network messages:
325
- - `ACTION_INIT_CLASS_PATH_END`: 'rski.ICpe'
326
- - `ACTION_LEVEL_UP`: 'rski.Lu'
327
- - `ACTION_LEVEL_EXPERIENCE_ADDED`: 'rski.Ea'
328
- - (See constants.js:24-51 for complete list)
329
-
330
- **Behaviors** (`constants.js:20`):
331
- - `BEHAVIOR_SEND`: Send to owner only
332
- - `BEHAVIOR_BROADCAST`: Broadcast to all
333
- - `BEHAVIOR_BOTH`: Both send and broadcast
334
-
335
- ## Dependencies
336
-
337
- - **@reldens/modifiers** (^0.33.0): Provides PropertyManager, Condition, Calculator, and modifier system
338
- - **@reldens/utils** (^0.54.0): Provides Shortcuts (sc), Logger, EventsManagerSingleton, InteractionArea
339
-
340
- ## Test Suite
341
-
342
- The package includes a comprehensive test suite using Node.js built-in test runner.
343
-
344
- **See `.claude/testing-patterns.md` for comprehensive testing best practices, anti-patterns, and lessons learned.**
345
-
346
- ### Test Structure
347
-
348
- ```
349
- tests/
350
- ├── run-tests.js # Test runner with filtering and coverage support
351
- ├── utils/
352
- │ └── test-helpers.js # Helper functions for tests
353
- ├── fixtures/
354
- │ ├── mocks/ # Mock classes (MockOwner, MockTarget, MockClient)
355
- │ ├── skills/ # Skill test data fixtures
356
- │ └── levels/ # Level test data fixtures
357
- └── unit/
358
- ├── test-skill.js # Skill class tests
359
- ├── test-level.js # Level class tests
360
- ├── test-levels-set.js # LevelsSet class tests
361
- ├── test-class-path.js # ClassPath class tests
362
- ├── test-server.js # SkillsServer tests
363
- ├── types/
364
- │ ├── test-attack.js # Attack skill type tests
365
- │ ├── test-effect.js # Effect skill type tests
366
- │ ├── test-physical-attack.js # PhysicalAttack tests
367
- │ └── test-physical-effect.js # PhysicalEffect tests
368
- ├── server/
369
- │ └── test-sender.js # Sender tests
370
- └── client/
371
- └── test-receiver.js # Receiver tests
372
- ```
373
-
374
- ### Running Tests
375
-
376
- ```bash
377
- # Run all tests
378
- npm test
379
-
380
- # Watch mode for development
381
- npm run test:watch
382
-
383
- # Filter specific tests
384
- npm run test:filter=attack # Run only attack-related tests
385
- npm run test:filter=skill # Run only skill tests
386
-
387
- # Coverage report
388
- npm run test:coverage
389
- ```
390
-
391
- ### Test Patterns
392
-
393
- - **Unit Tests**: Test individual classes and methods in isolation
394
- - **Mock Objects**: Use MockOwner, MockTarget, and MockClient for testing
395
- - **Fixtures**: Reusable test data in fixtures directory
396
- - **Event Testing**: Verify event firing and listening
397
- - **Async Testing**: Proper handling of async/await patterns
398
- - **Edge Cases**: Test boundary conditions and error states
399
-
400
- ### Critical Testing Rules
401
-
402
- #### Rule #1: NEVER Test Through Events Unless Testing the Event System
403
-
404
- **❌ WRONG:**
405
- ```javascript
406
- it('should send level up message', async () => {
407
- await classPath.levelUp(); // Fires event asynchronously
408
- assert.strictEqual(mockClient.sentMessages.length, 1); // Race condition!
409
- });
410
- ```
411
-
412
- **✅ CORRECT:**
413
- ```javascript
414
- it('should send level up message', async () => {
415
- await sender.sendLevelUpData(classPath); // Direct method call
416
- assert.strictEqual(mockClient.sentMessages.length, 1); // Deterministic
417
- });
418
- ```
419
-
420
- #### Rule #2: NEVER Use sleep() to Fix Race Conditions
421
-
422
- **❌ WRONG:**
423
- ```javascript
424
- await classPath.levelUp();
425
- await TestHelpers.sleep(10); // DON'T DO THIS!
426
- assert.strictEqual(mockClient.sentMessages.length, 1);
427
- ```
428
-
429
- **✅ CORRECT (for testing methods):**
430
- ```javascript
431
- await sender.sendLevelUpData(classPath); // Direct method call
432
- assert.strictEqual(mockClient.sentMessages.length, 1);
433
- ```
434
-
435
- **✅ CORRECT (for testing timers):**
436
- ```javascript
437
- it('should restore canActivate after delay', async () => {
438
- skill.validate();
439
- await TestHelpers.sleep(150); // Testing actual timer feature
440
- assert.strictEqual(skill.canActivate, true);
441
- });
442
- ```
443
-
444
- #### Rule #3: ALWAYS Use Unique removeKeys
445
-
446
- **❌ WRONG:**
447
- ```javascript
448
- // Test 1
449
- classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'before-listener');
450
-
451
- // Test 2 (after clearEventListeners)
452
- classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'before-listener');
453
- // ❌ removeKey collision - registration fails silently
454
- ```
455
-
456
- **✅ CORRECT:**
457
- ```javascript
458
- // Test 1
459
- classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'add-before-listener');
460
-
461
- // Test 2
462
- classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'remove-before-listener');
463
- // ✓ Unique removeKeys
464
- ```
465
-
466
- **Summary:**
467
- - ❌ Don't test through events (use direct method calls)
468
- - ❌ Don't use `sleep()` to fix race conditions
469
- - ✅ Do use `sleep()` to test timer features (skillDelay, castTime)
470
- - ✅ Always use unique removeKeys across all tests
471
-
472
- ## Common Development Patterns
473
-
474
- ### Creating a Custom Skill
475
-
476
- ```javascript
477
- const { Skill } = require('@reldens/skills');
478
-
479
- class MyCustomSkill extends Skill
480
- {
481
- constructor(props)
482
- {
483
- super(props);
484
- // Custom properties
485
- }
486
-
487
- async runSkillLogic()
488
- {
489
- // Implement skill behavior
490
- // Access this.owner, this.target
491
- // Use this.applyModifiers(), this.applyCriticalValue()
492
- return true; // Success
493
- }
494
-
495
- onExecuteConditions()
496
- {
497
- // Custom validation before execution
498
- return true; // Valid
499
- }
500
- }
501
- ```
502
-
503
- ### Setting Up a Class Path
504
-
505
- ```javascript
506
- const { ClassPath, Level } = require('@reldens/skills');
507
-
508
- let levels = {
509
- 1: new Level({
510
- key: 1,
511
- modifiers: [/* modifier instances */],
512
- requiredExperience: 0
513
- }),
514
- 5: new Level({
515
- key: 5,
516
- modifiers: [/* modifier instances */],
517
- requiredExperience: 1000
518
- })
519
- };
520
-
521
- let classPath = new ClassPath({
522
- owner: playerEntity,
523
- key: 'warrior',
524
- label: 'Warrior',
525
- levels: levels,
526
- autoFillRanges: true, // Auto-generate levels 2, 3, 4
527
- currentLevel: 1,
528
- currentExp: 0,
529
- skillsByLevel: {
530
- 1: [swordSkill],
531
- 5: [shieldSkill]
532
- }
533
- });
534
-
535
- await classPath.init({
536
- owner: playerEntity,
537
- key: 'warrior',
538
- levels: levels
539
- });
540
- ```
541
-
542
- ### Server-Side Integration
543
-
544
- ```javascript
545
- const { SkillsServer } = require('@reldens/skills');
546
-
547
- let skillsServer = new SkillsServer({
548
- owner: playerEntity,
549
- client: roomClient, // Must have send() and broadcast() methods
550
- key: 'warrior',
551
- levels: levels,
552
- skillsByLevel: skillsByLevel
553
- });
554
- ```
555
-
556
- ### Client-Side Integration
557
-
558
- ```javascript
559
- const { Receiver } = require('@reldens/skills/lib/client/receiver');
560
-
561
- class MySkillsUI extends Receiver
562
- {
563
- onLevelUp(message)
564
- {
565
- console.log('Level up!', message.data.lvl);
566
- // Update UI with new level, label, skills
567
- }
568
-
569
- onLevelExperienceAdded(message)
570
- {
571
- console.log('XP gained:', message.data.exp);
572
- // Update XP bar
573
- }
574
- }
575
-
576
- let receiver = new MySkillsUI({owner: playerEntity});
577
- gameClient.onMessage('*', (message) => receiver.processMessage(message));
578
- ```
579
-
580
- ### Hooking into Events
581
-
582
- ```javascript
583
- // Listen to skill events
584
- skill.listenEvent(SkillsEvents.SKILL_AFTER_EXECUTE, async (skill, target) => {
585
- console.log('Skill executed:', skill.key);
586
- // Custom logic after skill execution
587
- }, 'myUniqueKey', skill.getOwnerEventKey());
588
-
589
- // Listen to level events
590
- classPath.listenEvent(SkillsEvents.LEVEL_UP, async (classPath) => {
591
- console.log('Leveled up to:', classPath.currentLevel);
592
- // Award achievement, show animation, etc.
593
- }, 'levelUpListener', classPath.getOwnerEventKey());
594
- ```
595
-
596
- ## Important Notes
597
-
598
- - **Owner Requirements**: All owners must implement `getPosition()` returning `{x, y}` object
599
- - **Physical Skills**: Require owner to implement `executePhysicalSkill(target, skill)` method
600
- - **Event-Driven**: All major operations fire events for custom logic integration
601
- - **Standalone Package**: Can be used independently from main Reldens platform
602
- - **Server Authoritative**: For multiplayer games, always validate skills on server
603
- - **Modifiers Integration**: Uses @reldens/modifiers Condition and Modifier instances
604
- - **Range System**: Range 0 = infinite range, uses InteractionArea for circular validation
605
- - **Critical System**: Independent chance, multiplier, and fixed value properties
606
- - **Auto-Leveling**: Automatically levels up when XP threshold reached if enabled
607
- - **Experience Cap**: Can limit XP to max level requirement with `setRequiredExperienceLimit`
608
-
609
- ## Analysis Approach
610
-
611
- When working on code issues:
612
- - Always investigate thoroughly before making changes
613
- - Read related files completely before proposing solutions
614
- - Trace execution flows and dependencies
615
- - Provide proof for issues, never guess or assume
616
- - Verify file contents before creating patches
617
- - Never jump to early conclusions
618
- - A variable with an unexpected value is not an issue, it is the result of a previous issue
619
- - Consult `.claude/` documentation for detailed technical information on each system
1
+ ## Package Overview
2
+
3
+ **@reldens/skills** (v0.47.0) is a comprehensive skills, leveling, and combat system that provides:
4
+ - Level sets with automatic progression and experience management
5
+ - Class paths with skill trees and level-dependent unlocks
6
+ - Multiple skill types (base, attack, effect, physical variants)
7
+ - Combat mechanics (damage calculation, critical hits, dodge system)
8
+ - Real-time server-client synchronization via Sender/Receiver pattern
9
+ - Event-driven architecture for custom logic integration
10
+ - Modifiers system integration via @reldens/modifiers
11
+
12
+ This package is part of the Reldens MMORPG Platform ecosystem and can be attached to any entity owner with position methods.
13
+
14
+ ## Comprehensive Documentation
15
+
16
+ **Detailed technical documentation is available in the `.claude/` directory:**
17
+
18
+ - **[Event System Architecture](.claude/event-system-architecture.md)** - Complete event system documentation including EventsManagerSingleton, removeKey registry, event naming, and testing anti-patterns
19
+ - **[Skill Execution Flow](.claude/skill-execution-flow.md)** - Step-by-step skill execution phases, type-specific logic, and complete sequence diagrams
20
+ - **[Testing Patterns](.claude/testing-patterns.md)** - Best practices, anti-patterns, and critical lessons learned from test suite debugging
21
+ - **[Level Progression](.claude/level-progression.md)** - Complete leveling system guide including auto-fill, experience management, and class paths
22
+ - **[Class Hierarchy](.claude/class-hierarchy.md)** - Architecture reference with inheritance, composition, and integration patterns
23
+
24
+ **Always consult these documents when working with the corresponding systems.**
25
+
26
+ ## Key Commands
27
+
28
+ ```bash
29
+ # Run all tests
30
+ npm test
31
+
32
+ # Run tests in watch mode
33
+ npm run test:watch
34
+
35
+ # Run specific tests with filter
36
+ npm run test:filter=skill
37
+
38
+ # Run tests with coverage
39
+ npm run test:coverage
40
+ ```
41
+
42
+ ## Architecture
43
+
44
+ ### Package Structure
45
+
46
+ ```
47
+ lib/
48
+ ├── skill.js # Base Skill class
49
+ ├── level.js # Single level with modifiers
50
+ ├── levels-set.js # Level progression system
51
+ ├── class-path.js # Skill tree with class progression
52
+ ├── server.js # SkillsServer wrapper
53
+ ├── constants.js # Shared constants and action names
54
+ ├── skills-events.js # Event name definitions
55
+ ├── server/
56
+ │ └── sender.js # Server-to-client message sender
57
+ ├── client/
58
+ │ └── receiver.js # Client message receiver
59
+ └── types/
60
+ ├── attack.js # Damage-based skills
61
+ ├── effect.js # Modifier-based skills
62
+ ├── physical-attack.js # Physics-enabled attacks
63
+ ├── physical-effect.js # Physics-enabled effects
64
+ ├── physical-properties-validator.js
65
+ └── physical-skill-runner.js
66
+ ```
67
+
68
+ ### Core Classes
69
+
70
+ **Skill** (`lib/skill.js:12`):
71
+ - Base class for all skills
72
+ - Provides validation, execution, range checking
73
+ - Event system integration
74
+ - Owner/target relationship management
75
+ - Critical hit system (chance, multiplier, fixed value)
76
+ - Cooldown/delay system (`skillDelay`, `canActivate`)
77
+ - Cast time support with `castTime` property
78
+ - Owner conditions validation
79
+ - Owner effects application
80
+ - Properties:
81
+ - `key`: Unique skill identifier
82
+ - `owner`: Entity that owns the skill (must have `getPosition()` method)
83
+ - `target`: Target entity (can be fixed or passed on execution)
84
+ - `range`: Skill range (0 = infinite range)
85
+ - `rangeAutomaticValidation`: Auto-validate range before execution
86
+ - `allowSelfTarget`: Allow targeting the owner
87
+ - `usesLimit`: Maximum uses (0 = unlimited)
88
+ - `ownerConditions`: Array of Condition instances
89
+ - `ownerEffects`: Array of modifiers applied to owner on execution
90
+ - `criticalChance`, `criticalMultiplier`, `criticalFixedValue`
91
+
92
+ **Level** (`lib/level.js:9`):
93
+ - Represents a single level with:
94
+ - `key`: Integer level number
95
+ - `modifiers`: Array of modifiers applied at this level
96
+ - `label`: Display name for the level
97
+ - `requiredExperience`: XP required to reach this level
98
+
99
+ **LevelsSet** (`lib/levels-set.js:11`):
100
+ - Manages level progression and experience
101
+ - Auto-fills level ranges if `autoFillRanges` enabled
102
+ - Experience-based automatic leveling
103
+ - Modifier application/reversion on level up/down
104
+ - Properties:
105
+ - `owner`: Entity with `getPosition()` method
106
+ - `levels`: Object of Level instances
107
+ - `currentLevel`: Current level number
108
+ - `currentExp`: Current experience points
109
+ - `autoFillRanges`: Auto-generate intermediate levels
110
+ - `autoFillExperienceMultiplier`: XP multiplier for auto-generated levels (default: 1.5)
111
+ - `increaseLevelsWithExperience`: Auto level up when XP threshold reached
112
+ - `levelsByExperience`: Sorted array of level keys by required XP
113
+ - `setRequiredExperienceLimit`: Cap XP at max level requirement
114
+ - Methods:
115
+ - `levelUp()`: Increase level, apply modifiers
116
+ - `levelDown()`: Decrease level, revert modifiers
117
+ - `addExperience(number)`: Add XP, auto-level if enabled
118
+ - `getNextLevelExperience()`: Get XP required for next level
119
+
120
+ **ClassPath** (`lib/class-path.js:11`):
121
+ - Extends LevelsSet
122
+ - Provides skill tree functionality
123
+ - Level-based skill unlocking
124
+ - Dynamic label changes per level
125
+ - Properties:
126
+ - `key`: Class path identifier
127
+ - `label`: Base display name
128
+ - `labelsByLevel`: Object of {levelKey: 'label'} for level-specific names
129
+ - `currentLabel`: Active display name
130
+ - `skillsByLevel`: Object of {levelKey: [Skill instances]}
131
+ - `skillsByLevelKeys`: Object of {levelKey: [skill keys]}
132
+ - `currentSkills`: Object of currently available skills
133
+ - `affectedProperty`: Property affected by class skills (e.g., 'hp')
134
+ - Methods:
135
+ - `addSkills(skills)`: Add skills to current set
136
+ - `removeSkills(skills)`: Remove skills from current set
137
+ - `setOwnerSkills(skills)`: Initialize owner's skill set based on current level
138
+
139
+ **SkillsServer** (`lib/server.js:11`):
140
+ - Server-side wrapper for ClassPath
141
+ - Integrates Sender for client communication
142
+ - Validates client has `send()` and `broadcast()` methods
143
+ - Automatically initializes ClassPath and registers listeners
144
+
145
+ ### Skill Types
146
+
147
+ **Attack** (`lib/types/attack.js:14`):
148
+ - Extends Skill for damage-based skills
149
+ - Damage calculation with attack vs defense properties
150
+ - Dodge system with aim vs dodge properties
151
+ - Critical damage affected by aim/dodge ratio
152
+ - Properties:
153
+ - `affectedProperty`: Target property to modify (e.g., 'hp')
154
+ - `hitDamage`: Base damage at 100%
155
+ - `applyDirectDamage`: Skip calculations, apply hitDamage directly
156
+ - `attackProperties`: Array of owner properties for attack total
157
+ - `defenseProperties`: Array of target properties for defense total
158
+ - `aimProperties`: Array of owner properties for aim total
159
+ - `dodgeProperties`: Array of target properties for dodge total
160
+ - `dodgeFullEnabled`: Enable complete dodge if dodge > (aim * dodgeOverAimSuccess)
161
+ - `dodgeOverAimSuccess`: Dodge threshold multiplier (default: 1)
162
+ - `damageAffected`: Apply dodge/aim ratio to damage
163
+ - `criticalAffected`: Apply dodge/aim ratio to critical damage
164
+ - `propertiesTotalOperators`: Custom operators for property totals
165
+ - `allowEffectBelowZero`: Allow negative values on affected property
166
+ - Damage Calculation:
167
+ 1. Calculate owner aim and target dodge totals
168
+ 2. Check full dodge: `dodge > (aim * dodgeOverAimSuccess)`
169
+ 3. Calculate base damage: `hitDamage` modified by attack vs defense diff
170
+ 4. Apply dodge/aim ratio if `damageAffected` enabled
171
+ 5. Calculate critical damage with dodge/aim ratio if `criticalAffected`
172
+ 6. Apply total damage to `affectedProperty`
173
+
174
+ **Effect** (`lib/types/effect.js:14`):
175
+ - Extends Skill for modifier-based skills (buffs/debuffs)
176
+ - Applies modifiers to target with critical chance
177
+ - Properties:
178
+ - `targetEffects`: Array of modifiers applied to target
179
+ - Logic: Validates range, applies modifiers with critical calculation
180
+
181
+ **PhysicalAttack** (`lib/types/physical-attack.js:16`):
182
+ - Extends Attack for physics-enabled attacks
183
+ - Requires collision detection system
184
+ - Properties:
185
+ - `magnitude`: Physics force/magnitude
186
+ - `objectWidth`: Collision object width
187
+ - `objectHeight`: Collision object height
188
+ - `validateTargetOnHit`: Verify target matches on collision
189
+ - Requires owner to implement `executePhysicalSkill(target, skill)` method
190
+ - Uses PhysicalSkillRunner for execution
191
+ - Fires `SKILL_PHYSICAL_ATTACK_HIT` event on collision
192
+ - Calls parent `runSkillLogic()` in `executeOnHit(target)` callback
193
+
194
+ **PhysicalEffect** (`lib/types/physical-effect.js:16`):
195
+ - Extends Effect for physics-enabled effects
196
+ - Same physics properties as PhysicalAttack
197
+ - Uses PhysicalSkillRunner for execution
198
+ - Fires `SKILL_PHYSICAL_EFFECT_HIT` event on collision
199
+
200
+ ### Communication System
201
+
202
+ **Sender** (`lib/server/sender.js:11`):
203
+ - Server-to-client message broadcaster
204
+ - Registers event listeners on ClassPath events
205
+ - Sends compressed data to client
206
+ - Behaviors:
207
+ - `BEHAVIOR_SEND`: Send to owner client only
208
+ - `BEHAVIOR_BROADCAST`: Broadcast to all clients
209
+ - `BEHAVIOR_BOTH`: Both send and broadcast
210
+ - Registered Events:
211
+ - `INIT_CLASS_PATH_END`: Send initial class data (level, label, XP, skills)
212
+ - `LEVEL_UP`: Send level up data (new level, label, skills, next XP)
213
+ - `LEVEL_EXPERIENCE_ADDED`: Send current XP
214
+ - `SKILL_BEFORE_CAST`: Broadcast skill cast start
215
+ - `SKILL_ATTACK_APPLY_DAMAGE`: Broadcast damage application
216
+ - Message Format:
217
+ ```javascript
218
+ {
219
+ act: 'rski.ICpe', // Action constant
220
+ owner: ownerId, // Owner ID
221
+ data: { // Compressed data
222
+ lvl: 5, // Level
223
+ lab: 'Warrior', // Label
224
+ exp: 1500, // Current XP
225
+ ne: 2000, // Next level XP
226
+ skl: ['sword', 'shield'] // Skill keys
227
+ }
228
+ }
229
+ ```
230
+
231
+ **Receiver** (`lib/client/receiver.js:10`):
232
+ - Client-side message processor
233
+ - Maps action constants to method names
234
+ - Validates message action prefix (`rski.`)
235
+ - Properties:
236
+ - `actions`: Object mapping action constants to method names
237
+ - `avoidDefaults`: Skip default action-to-method mapping
238
+ - Default Method Mapping: Each action constant maps to `on[ActionName]` method
239
+ - Usage: Extend and implement handler methods (e.g., `onLevelUp(message)`)
240
+
241
+ ### Events System
242
+
243
+ All events are prefixed with `reldens.skills.` and appended with owner event key.
244
+
245
+ **IMPORTANT:** See `.claude/event-system-architecture.md` for complete event system documentation including:
246
+ - EventsManagerSingleton architecture and removeKey registry
247
+ - Event naming conventions (owner-namespaced)
248
+ - Listener registration patterns
249
+ - Testing anti-patterns and race conditions
250
+ - Critical rules for event usage
251
+
252
+ **Level Set Events** (fired by LevelsSet):
253
+ - `INIT_LEVEL_SET_START`: Before level set initialization
254
+ - `INIT_LEVEL_SET_END`: After level set initialization
255
+ - `SET_LEVELS`: After levels are set
256
+ - `GENERATED_LEVELS`: After auto-filling a level range
257
+ - `LEVEL_UP`: After level increases
258
+ - `LEVEL_DOWN`: After level decreases
259
+ - `LEVEL_APPLY_MODIFIERS`: Before applying level modifiers
260
+ - `LEVEL_EXPERIENCE_ADDED`: After XP added (args: number, newTotal, currentLevelIndex, nextLevelIndex, nextLevelKey, nextLevel, nextLevelExp, isLevelUp)
261
+
262
+ **Class Path Events** (fired by ClassPath):
263
+ - `INIT_CLASS_PATH_END`: After class path initialization
264
+ - `SET_SKILLS`: After owner skills set
265
+ - `ADD_SKILLS_BEFORE`: Before adding skills
266
+ - `ADD_SKILLS_AFTER`: After adding skills
267
+ - `REMOVE_SKILLS_BEFORE`: Before removing skills
268
+ - `REMOVE_SKILLS_AFTER`: After removing skills
269
+
270
+ **Skill Execution Events** (fired by Skill):
271
+ - `VALIDATE_BEFORE`: Before skill validation
272
+ - `VALIDATE_SUCCESS`: After successful validation
273
+ - `VALIDATE_FAIL`: After validation failure (args: skill, failedCondition)
274
+ - `SKILL_BEFORE_IN_RANGE`: Before range check
275
+ - `SKILL_AFTER_IN_RANGE`: After range check (args: skill, interactionResult)
276
+ - `SKILL_BEFORE_EXECUTE`: Before skill execution
277
+ - `SKILL_APPLY_OWNER_EFFECTS`: After applying owner effects
278
+ - `SKILL_BEFORE_CAST`: Before cast time starts
279
+ - `SKILL_AFTER_CAST`: After cast time completes
280
+ - `SKILL_BEFORE_RUN_LOGIC`: Before skill logic execution
281
+ - `SKILL_AFTER_RUN_LOGIC`: After skill logic execution
282
+ - `SKILL_AFTER_EXECUTE`: After skill execution complete
283
+
284
+ **Attack/Effect Events**:
285
+ - `SKILL_ATTACK_APPLY_DAMAGE`: After damage applied (args: skill, target, damage, newValue)
286
+ - `SKILL_EFFECT_TARGET_MODIFIERS`: After effect modifiers applied
287
+ - `SKILL_PHYSICAL_ATTACK_HIT`: On physical attack collision
288
+ - `SKILL_PHYSICAL_EFFECT_HIT`: On physical effect collision
289
+
290
+ **Event Naming Convention**:
291
+ Events are automatically namespaced by owner:
292
+ ```javascript
293
+ // Event fired as: 'skills.ownerId.123.reldens.skills.levelUp'
294
+ skill.fireEvent(SkillsEvents.LEVEL_UP, this);
295
+
296
+ // Listen to specific owner's events:
297
+ skill.listenEvent(SkillsEvents.LEVEL_UP, callback, removeKey, masterKey);
298
+ ```
299
+
300
+ ### Constants
301
+
302
+ **Skill Types** (`constants.js:10`):
303
+ - `SKILL.TYPE.BASE`: Base skill (1)
304
+ - `SKILL.TYPE.ATTACK`: Attack skill (2)
305
+ - `SKILL.TYPE.EFFECT`: Effect skill (3)
306
+ - `SKILL.TYPE.PHYSICAL_ATTACK`: Physical attack (4)
307
+ - `SKILL.TYPE.PHYSICAL_EFFECT`: Physical effect (5)
308
+
309
+ **Skill States** (`constants.js:53`):
310
+ - `PHYSICAL_SKILL_INVALID_TARGET`: Target validation failed
311
+ - `PHYSICAL_SKILL_RUN_LOGIC`: Running physical skill logic
312
+ - `OUT_OF_RANGE`: Target out of range
313
+ - `CAN_NOT_ACTIVATE`: Skill on cooldown or owner casting
314
+ - `DODGED`: Attack dodged
315
+ - `APPLYING_DAMAGE`: Damage calculation in progress
316
+ - `APPLIED_DAMAGE`: Damage applied successfully
317
+ - `APPLIED_CRITICAL_DAMAGE`: Critical damage applied
318
+ - `APPLYING_EFFECTS`: Effects being applied
319
+ - `APPLIED_EFFECTS`: Effects applied successfully
320
+ - `EXECUTE_PHYSICAL_ATTACK`: Physical attack executing
321
+ - `TARGET_NOT_AVAILABLE`: Target undefined or invalid
322
+
323
+ **Action Constants** (`constants.js:7`):
324
+ All action constants use `rski.` prefix (Reldens Skills) for network messages:
325
+ - `ACTION_INIT_CLASS_PATH_END`: 'rski.ICpe'
326
+ - `ACTION_LEVEL_UP`: 'rski.Lu'
327
+ - `ACTION_LEVEL_EXPERIENCE_ADDED`: 'rski.Ea'
328
+ - (See constants.js:24-51 for complete list)
329
+
330
+ **Behaviors** (`constants.js:20`):
331
+ - `BEHAVIOR_SEND`: Send to owner only
332
+ - `BEHAVIOR_BROADCAST`: Broadcast to all
333
+ - `BEHAVIOR_BOTH`: Both send and broadcast
334
+
335
+ ## Dependencies
336
+
337
+ - **@reldens/modifiers** (^0.33.0): Provides PropertyManager, Condition, Calculator, and modifier system
338
+ - **@reldens/utils** (^0.54.0): Provides Shortcuts (sc), Logger, EventsManagerSingleton, InteractionArea
339
+
340
+ ## Test Suite
341
+
342
+ The package includes a comprehensive test suite using Node.js built-in test runner.
343
+
344
+ **See `.claude/testing-patterns.md` for comprehensive testing best practices, anti-patterns, and lessons learned.**
345
+
346
+ ### Test Structure
347
+
348
+ ```
349
+ tests/
350
+ ├── run-tests.js # Test runner with filtering and coverage support
351
+ ├── utils/
352
+ │ └── test-helpers.js # Helper functions for tests
353
+ ├── fixtures/
354
+ │ ├── mocks/ # Mock classes (MockOwner, MockTarget, MockClient)
355
+ │ ├── skills/ # Skill test data fixtures
356
+ │ └── levels/ # Level test data fixtures
357
+ └── unit/
358
+ ├── test-skill.js # Skill class tests
359
+ ├── test-level.js # Level class tests
360
+ ├── test-levels-set.js # LevelsSet class tests
361
+ ├── test-class-path.js # ClassPath class tests
362
+ ├── test-server.js # SkillsServer tests
363
+ ├── types/
364
+ │ ├── test-attack.js # Attack skill type tests
365
+ │ ├── test-effect.js # Effect skill type tests
366
+ │ ├── test-physical-attack.js # PhysicalAttack tests
367
+ │ └── test-physical-effect.js # PhysicalEffect tests
368
+ ├── server/
369
+ │ └── test-sender.js # Sender tests
370
+ └── client/
371
+ └── test-receiver.js # Receiver tests
372
+ ```
373
+
374
+ ### Running Tests
375
+
376
+ ```bash
377
+ # Run all tests
378
+ npm test
379
+
380
+ # Watch mode for development
381
+ npm run test:watch
382
+
383
+ # Filter specific tests
384
+ npm run test:filter=attack # Run only attack-related tests
385
+ npm run test:filter=skill # Run only skill tests
386
+
387
+ # Coverage report
388
+ npm run test:coverage
389
+ ```
390
+
391
+ ### Test Patterns
392
+
393
+ - **Unit Tests**: Test individual classes and methods in isolation
394
+ - **Mock Objects**: Use MockOwner, MockTarget, and MockClient for testing
395
+ - **Fixtures**: Reusable test data in fixtures directory
396
+ - **Event Testing**: Verify event firing and listening
397
+ - **Async Testing**: Proper handling of async/await patterns
398
+ - **Edge Cases**: Test boundary conditions and error states
399
+
400
+ ### Critical Testing Rules
401
+
402
+ #### Rule #1: NEVER Test Through Events Unless Testing the Event System
403
+
404
+ **❌ WRONG:**
405
+ ```javascript
406
+ it('should send level up message', async () => {
407
+ await classPath.levelUp(); // Fires event asynchronously
408
+ assert.strictEqual(mockClient.sentMessages.length, 1); // Race condition!
409
+ });
410
+ ```
411
+
412
+ **✅ CORRECT:**
413
+ ```javascript
414
+ it('should send level up message', async () => {
415
+ await sender.sendLevelUpData(classPath); // Direct method call
416
+ assert.strictEqual(mockClient.sentMessages.length, 1); // Deterministic
417
+ });
418
+ ```
419
+
420
+ #### Rule #2: NEVER Use sleep() to Fix Race Conditions
421
+
422
+ **❌ WRONG:**
423
+ ```javascript
424
+ await classPath.levelUp();
425
+ await TestHelpers.sleep(10); // DON'T DO THIS!
426
+ assert.strictEqual(mockClient.sentMessages.length, 1);
427
+ ```
428
+
429
+ **✅ CORRECT (for testing methods):**
430
+ ```javascript
431
+ await sender.sendLevelUpData(classPath); // Direct method call
432
+ assert.strictEqual(mockClient.sentMessages.length, 1);
433
+ ```
434
+
435
+ **✅ CORRECT (for testing timers):**
436
+ ```javascript
437
+ it('should restore canActivate after delay', async () => {
438
+ skill.validate();
439
+ await TestHelpers.sleep(150); // Testing actual timer feature
440
+ assert.strictEqual(skill.canActivate, true);
441
+ });
442
+ ```
443
+
444
+ #### Rule #3: ALWAYS Use Unique removeKeys
445
+
446
+ **❌ WRONG:**
447
+ ```javascript
448
+ // Test 1
449
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'before-listener');
450
+
451
+ // Test 2 (after clearEventListeners)
452
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'before-listener');
453
+ // ❌ removeKey collision - registration fails silently
454
+ ```
455
+
456
+ **✅ CORRECT:**
457
+ ```javascript
458
+ // Test 1
459
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'add-before-listener');
460
+
461
+ // Test 2
462
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'remove-before-listener');
463
+ // ✓ Unique removeKeys
464
+ ```
465
+
466
+ **Summary:**
467
+ - ❌ Don't test through events (use direct method calls)
468
+ - ❌ Don't use `sleep()` to fix race conditions
469
+ - ✅ Do use `sleep()` to test timer features (skillDelay, castTime)
470
+ - ✅ Always use unique removeKeys across all tests
471
+
472
+ ## Common Development Patterns
473
+
474
+ ### Creating a Custom Skill
475
+
476
+ ```javascript
477
+ const { Skill } = require('@reldens/skills');
478
+
479
+ class MyCustomSkill extends Skill
480
+ {
481
+ constructor(props)
482
+ {
483
+ super(props);
484
+ // Custom properties
485
+ }
486
+
487
+ async runSkillLogic()
488
+ {
489
+ // Implement skill behavior
490
+ // Access this.owner, this.target
491
+ // Use this.applyModifiers(), this.applyCriticalValue()
492
+ return true; // Success
493
+ }
494
+
495
+ onExecuteConditions()
496
+ {
497
+ // Custom validation before execution
498
+ return true; // Valid
499
+ }
500
+ }
501
+ ```
502
+
503
+ ### Setting Up a Class Path
504
+
505
+ ```javascript
506
+ const { ClassPath, Level } = require('@reldens/skills');
507
+
508
+ let levels = {
509
+ 1: new Level({
510
+ key: 1,
511
+ modifiers: [/* modifier instances */],
512
+ requiredExperience: 0
513
+ }),
514
+ 5: new Level({
515
+ key: 5,
516
+ modifiers: [/* modifier instances */],
517
+ requiredExperience: 1000
518
+ })
519
+ };
520
+
521
+ let classPath = new ClassPath({
522
+ owner: playerEntity,
523
+ key: 'warrior',
524
+ label: 'Warrior',
525
+ levels: levels,
526
+ autoFillRanges: true, // Auto-generate levels 2, 3, 4
527
+ currentLevel: 1,
528
+ currentExp: 0,
529
+ skillsByLevel: {
530
+ 1: [swordSkill],
531
+ 5: [shieldSkill]
532
+ }
533
+ });
534
+
535
+ await classPath.init({
536
+ owner: playerEntity,
537
+ key: 'warrior',
538
+ levels: levels
539
+ });
540
+ ```
541
+
542
+ ### Server-Side Integration
543
+
544
+ ```javascript
545
+ const { SkillsServer } = require('@reldens/skills');
546
+
547
+ let skillsServer = new SkillsServer({
548
+ owner: playerEntity,
549
+ client: roomClient, // Must have send() and broadcast() methods
550
+ key: 'warrior',
551
+ levels: levels,
552
+ skillsByLevel: skillsByLevel
553
+ });
554
+ ```
555
+
556
+ ### Client-Side Integration
557
+
558
+ ```javascript
559
+ const { Receiver } = require('@reldens/skills/lib/client/receiver');
560
+
561
+ class MySkillsUI extends Receiver
562
+ {
563
+ onLevelUp(message)
564
+ {
565
+ console.log('Level up!', message.data.lvl);
566
+ // Update UI with new level, label, skills
567
+ }
568
+
569
+ onLevelExperienceAdded(message)
570
+ {
571
+ console.log('XP gained:', message.data.exp);
572
+ // Update XP bar
573
+ }
574
+ }
575
+
576
+ let receiver = new MySkillsUI({owner: playerEntity});
577
+ gameClient.onMessage('*', (message) => receiver.processMessage(message));
578
+ ```
579
+
580
+ ### Hooking into Events
581
+
582
+ ```javascript
583
+ // Listen to skill events
584
+ skill.listenEvent(SkillsEvents.SKILL_AFTER_EXECUTE, async (skill, target) => {
585
+ console.log('Skill executed:', skill.key);
586
+ // Custom logic after skill execution
587
+ }, 'myUniqueKey', skill.getOwnerEventKey());
588
+
589
+ // Listen to level events
590
+ classPath.listenEvent(SkillsEvents.LEVEL_UP, async (classPath) => {
591
+ console.log('Leveled up to:', classPath.currentLevel);
592
+ // Award achievement, show animation, etc.
593
+ }, 'levelUpListener', classPath.getOwnerEventKey());
594
+ ```
595
+
596
+ ## Important Notes
597
+
598
+ - **Owner Requirements**: All owners must implement `getPosition()` returning `{x, y}` object
599
+ - **Physical Skills**: Require owner to implement `executePhysicalSkill(target, skill)` method
600
+ - **Event-Driven**: All major operations fire events for custom logic integration
601
+ - **Standalone Package**: Can be used independently from main Reldens platform
602
+ - **Server Authoritative**: For multiplayer games, always validate skills on server
603
+ - **Modifiers Integration**: Uses @reldens/modifiers Condition and Modifier instances
604
+ - **Range System**: Range 0 = infinite range, uses InteractionArea for circular validation
605
+ - **Critical System**: Independent chance, multiplier, and fixed value properties
606
+ - **Auto-Leveling**: Automatically levels up when XP threshold reached if enabled
607
+ - **Experience Cap**: Can limit XP to max level requirement with `setRequiredExperienceLimit`
608
+
609
+ ## Analysis Approach
610
+
611
+ When working on code issues:
612
+ - Always investigate thoroughly before making changes
613
+ - Read related files completely before proposing solutions
614
+ - Trace execution flows and dependencies
615
+ - Provide proof for issues, never guess or assume
616
+ - Verify file contents before creating patches
617
+ - Never jump to early conclusions
618
+ - A variable with an unexpected value is not an issue, it is the result of a previous issue
619
+ - Consult `.claude/` documentation for detailed technical information on each system