dopaminejs 2.5.0 → 3.1.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 (81) hide show
  1. package/README.md +55 -50
  2. package/dist/DataService-D1uL6E8R.cjs +1 -0
  3. package/dist/DataService-DN6xwvXU.js +745 -0
  4. package/dist/core.cjs +1 -1
  5. package/dist/core.js +2 -2
  6. package/dist/dopamine.cjs +1 -37
  7. package/dist/dopamine.js +3 -635
  8. package/dist/games.cjs +1 -0
  9. package/dist/games.js +82 -0
  10. package/dist/host-7FzZ-yO7.cjs +37 -0
  11. package/dist/host-CdjhXPy-.js +815 -0
  12. package/dist/style.css +395 -2
  13. package/dist/testing.cjs +1 -0
  14. package/dist/testing.js +475 -0
  15. package/package.json +24 -9
  16. package/spec/README.md +228 -0
  17. package/spec/VERSION +1 -0
  18. package/spec/fixtures/achievements.json +611 -0
  19. package/spec/fixtures/levels.json +421 -0
  20. package/spec/fixtures/merge.json +1739 -0
  21. package/spec/fixtures/migrate.json +957 -0
  22. package/spec/fixtures/scores.json +755 -0
  23. package/spec/fixtures/streaks.json +967 -0
  24. package/spec/schema.json +61 -0
  25. package/src/dopamine/audio/SoundManager.js +54 -24
  26. package/src/dopamine/core/DopamineError.js +7 -0
  27. package/src/dopamine/core/RewardSystem.js +359 -374
  28. package/src/dopamine/core/achievements.js +49 -0
  29. package/src/dopamine/core/clock.js +11 -0
  30. package/src/dopamine/core/levels.js +4 -0
  31. package/src/dopamine/core/merge.js +68 -0
  32. package/src/dopamine/core/middleware.js +58 -0
  33. package/src/dopamine/core/store.js +261 -0
  34. package/src/dopamine/core/streaks.js +55 -0
  35. package/src/dopamine/effects/ParticleSystem.js +30 -0
  36. package/src/dopamine/host.js +360 -0
  37. package/src/dopamine/ui/{GameUI.js → RewardUI.js} +166 -202
  38. package/src/games.js +138 -0
  39. package/src/index.js +11 -34
  40. package/src/progression.js +3 -0
  41. package/src/testing.js +490 -0
  42. package/types/core.d.ts +9 -1
  43. package/types/games.d.ts +46 -0
  44. package/types/index.d.ts +311 -385
  45. package/types/testing.d.ts +96 -0
  46. package/dist/DataService-BPXCldpo.cjs +0 -1
  47. package/dist/DataService-CH9_gv_8.js +0 -398
  48. package/dist/ScreenShake-9jgNXPS6.cjs +0 -1
  49. package/dist/ScreenShake-CLvO1wx4.js +0 -827
  50. package/dist/engine.cjs +0 -1
  51. package/dist/engine.js +0 -2
  52. package/src/core/Animator.js +0 -62
  53. package/src/core/Collider.js +0 -86
  54. package/src/core/Component.js +0 -38
  55. package/src/core/DopamineKernel.js +0 -170
  56. package/src/core/EventBus.js +0 -206
  57. package/src/core/Game.js +0 -90
  58. package/src/core/GameObject.js +0 -99
  59. package/src/core/PluginRegistry.js +0 -359
  60. package/src/core/Scene.js +0 -107
  61. package/src/core/Sprite.js +0 -51
  62. package/src/core/SystemRegistry.js +0 -263
  63. package/src/core/Vector2.js +0 -50
  64. package/src/dopamine/components/ParticleEmitter.js +0 -50
  65. package/src/dopamine/components/ScreenShake.js +0 -50
  66. package/src/dopamine/components/index.js +0 -2
  67. package/src/dopamine/index.js +0 -93
  68. package/src/dopamine/utils/TextureGenerator.js +0 -90
  69. package/src/engine.js +0 -38
  70. package/src/interfaces/IAudioSystem.js +0 -58
  71. package/src/interfaces/IParticleSystem.js +0 -51
  72. package/src/interfaces/IPhysicsSystem.js +0 -52
  73. package/src/interfaces/ISystem.js +0 -48
  74. package/src/interfaces/index.js +0 -7
  75. package/src/renderer/Renderer.js +0 -45
  76. package/src/systems/Director.js +0 -34
  77. package/src/systems/Input.js +0 -81
  78. package/src/systems/Loader.js +0 -48
  79. package/src/systems/Physics.js +0 -210
  80. package/src/systems/Ticker.js +0 -91
  81. package/src/systems/deprecate.js +0 -38
@@ -1,57 +1,79 @@
1
1
  /**
2
2
  * Reward System Module
3
3
  * Manages achievements, XP, levels, streaks, and rewards
4
+ *
5
+ * The saved player is a document that merges (see merge.js). Nothing hands
6
+ * the document out: callers get frozen snapshots.
4
7
  */
5
8
 
6
9
  import { EventEmitter } from './EventEmitter.js';
7
-
8
- // Keys that resolve to something on Object.prototype. Game names and
9
- // achievement ids index plain objects, so these must never be used as one.
10
- const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
11
-
12
- const isSafeKey = (key) => typeof key === 'string' && key.length > 0 && !UNSAFE_KEYS.has(key);
13
- const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
14
- const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
15
-
16
- const toCount = (value, fallback, min = 0) => {
17
- const number = Number(value);
18
- return Number.isInteger(number) && number >= min ? number : fallback;
10
+ import { DopamineError } from './DopamineError.js';
11
+ import { systemClock } from './clock.js';
12
+ import { levelFor, thresholdFor } from './levels.js';
13
+ import { BUILTIN_REWARDS, builtinAchievements, rewardsOf } from './achievements.js';
14
+ import { Middleware } from './middleware.js';
15
+ import { merge } from './merge.js';
16
+ import { currentStreak, longestRun, trimDays } from './streaks.js';
17
+ import {
18
+ LEGACY, MAX_DEVICES, cap, deviceIds, emptyDoc, validate, view, xpOf, levelOf, clone, freeze, isSafeKey, hasOwn, isRecord
19
+ } from './store.js';
20
+
21
+ const DEVICE_KEY = 'device';
22
+
23
+ const randomId = () => {
24
+ const bytes = new Uint8Array(8);
25
+ const random = globalThis.crypto;
26
+ if (typeof random?.getRandomValues === 'function') {
27
+ random.getRandomValues(bytes);
28
+ } else {
29
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
30
+ }
31
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
19
32
  };
20
33
 
34
+ const isDeviceId = (id) => isSafeKey(id) && id !== LEGACY;
35
+
21
36
  export class RewardSystem extends EventEmitter {
22
37
  /**
23
38
  * @param {Object} dataService - Persistence, see DataService
24
39
  * @param {Object} [config]
25
40
  * @param {Object} [config.achievements] - Extra achievement definitions
26
- * @param {Object} [config.events] - Kernel EventBus to mirror events onto
27
- * @param {Object} [config.kernel] - Kernel; its `events` bus is used if present
41
+ * @param {boolean} [config.builtinAchievements] - false defines none of the five built-ins
42
+ * (first_game, level_5, level_10, streak_3, streak_7). Default true. A save that
43
+ * already holds one keeps it and its XP. Any value but false means true.
44
+ * @param {{ now(): number, localDate(ms?: number): string }} [config.clock] - Time source
45
+ * @param {'any'|'record'} [config.streakDays] - What marks today as a play day.
46
+ * 'any' (default): record() or addXP(). 'record': record() only. XP from an
47
+ * achievement reward never marks a day.
28
48
  */
29
49
  constructor(dataService, config = {}) {
30
50
  super();
31
51
  this.dataService = dataService;
32
- this.player = null;
33
- this.achievements = { ...this._initAchievements(), ...(config.achievements || {}) };
34
-
35
- // Optional bridge to the kernel bus. EventBus.Events already declared
36
- // XP_GAINED, LEVEL_UP and ACHIEVEMENT_UNLOCKED with nothing emitting
37
- // them; this connects the two event systems without changing the
38
- // existing rewardSystem.on(...) surface that games already use.
39
- this.events = config.events || config.kernel?.events || null;
40
-
41
- // Write batching. Every mutation used to hit storage directly, so one
42
- // recordGame produced four full serializations of the player object.
52
+ this.clock = config.clock && typeof config.clock.now === 'function' && typeof config.clock.localDate === 'function'
53
+ ? config.clock
54
+ : systemClock;
55
+ this.achievements = { ...(config.builtinAchievements === false ? {} : builtinAchievements()), ...(config.achievements || {}) };
56
+ this.streakDays = config.streakDays === 'record' ? 'record' : 'any';
57
+
58
+ this._doc = null;
59
+ this._deviceId = null;
60
+ this._deviceSaved = false;
61
+ this._middleware = new Middleware();
62
+
63
+ // Write batching: one record is one write.
43
64
  this._batchDepth = 0;
44
65
  this._pendingSave = false;
45
66
 
46
67
  // Set when init() could not read storage. Saving stays off until a
47
- // later init() reads it, so the saved player is never replaced.
68
+ // later init() reads it or reset() is called, so the saved player is
69
+ // never replaced by accident.
48
70
  this._loadFailed = false;
49
71
  this._readFailed = false;
50
72
  }
51
73
 
52
74
  /**
53
75
  * True when the last init() could not read the saved player, so nothing
54
- * is saved until init() is called again and the read works.
76
+ * is saved until init() is called again and the read works, or reset() is called.
55
77
  * @returns {boolean}
56
78
  */
57
79
  get loadFailed() {
@@ -59,25 +81,14 @@ export class RewardSystem extends EventEmitter {
59
81
  }
60
82
 
61
83
  /**
62
- * Emit locally, and mirror onto the kernel bus when one is attached.
84
+ * Emit a frozen copy of the payload.
63
85
  * @private
64
86
  */
65
87
  _publish(event, data) {
66
- this.emit(event, data);
67
- if (this.events) {
68
- this.events.emit(event, data);
69
- }
88
+ const payload = Object.freeze({ ...data });
89
+ this.emit(event, payload);
70
90
  }
71
91
 
72
- /**
73
- * Run `fn` with saves collapsed into a single write at the end.
74
- *
75
- * Nested batches are counted, so an inner operation that batches on its
76
- * own still results in exactly one write for the outermost call.
77
- *
78
- * @param {Function} fn
79
- * @private
80
- */
81
92
  async _batch(fn) {
82
93
  this._batchDepth++;
83
94
  try {
@@ -91,26 +102,23 @@ export class RewardSystem extends EventEmitter {
91
102
  }
92
103
  }
93
104
 
105
+ _options() {
106
+ // The built-in rewards stay the base: a save that holds a built-in
107
+ // must read the same whether or not it is defined here.
108
+ return { now: this.clock.now(), today: this.clock.localDate(), rewards: { ...BUILTIN_REWARDS, ...rewardsOf(this.achievements) } };
109
+ }
110
+
94
111
  /**
95
112
  * Initialize the reward system for current player
96
- * @returns {Promise<Object>} Player data
113
+ * @returns {Promise<Object>} Frozen snapshot of the player
97
114
  */
98
115
  async init() {
99
116
  const saved = await this._readSaved();
100
117
  // A failed retry keeps the progress made since the first init.
101
- if (!(this._loadFailed && this.player)) this.player = this._migrate(saved);
102
-
103
- // Check daily streak
104
- const streakChanged = this._updateDailyStreak();
105
-
106
- // Save updated player data
118
+ if (!(this._loadFailed && this._doc)) this._doc = this._load(saved);
119
+ await this._readDevice();
107
120
  await this.save();
108
-
109
- if (streakChanged) {
110
- this._publishStreak();
111
- }
112
-
113
- return this.player;
121
+ return this.snapshot();
114
122
  }
115
123
 
116
124
  /**
@@ -124,8 +132,6 @@ export class RewardSystem extends EventEmitter {
124
132
  // retry is in flight cannot land.
125
133
  this._loadFailed = true;
126
134
  try {
127
- // A custom data service that ignores the option still works,
128
- // without this protection.
129
135
  const saved = await this.dataService.load('player', null, { strict: true });
130
136
  this._loadFailed = false;
131
137
  this._readFailed = false;
@@ -146,149 +152,182 @@ export class RewardSystem extends EventEmitter {
146
152
  }
147
153
 
148
154
  /**
155
+ * Saved state is untrusted: it goes through validate. A document from a
156
+ * newer version or with too many devices is left alone in storage.
157
+ * @private
158
+ */
159
+ _load(saved) {
160
+ if (!isRecord(saved)) return emptyDoc(this.clock.now());
161
+ try {
162
+ return validate(saved, this._options());
163
+ } catch (error) {
164
+ if (!(error instanceof DopamineError)) throw error;
165
+ this._loadFailed = true;
166
+ this._readFailed = true;
167
+ this._publish('load_failed', { key: 'player', reason: error.code, error });
168
+ return emptyDoc(this.clock.now());
169
+ }
170
+ }
171
+
172
+ /**
173
+ * The device id is made once, kept under its own key and never part of
174
+ * the merged document.
149
175
  * @private
150
176
  */
177
+ async _readDevice() {
178
+ if (this._deviceId) return;
179
+ let stored = null;
180
+ try {
181
+ stored = await this.dataService.load(DEVICE_KEY, null, { strict: true });
182
+ } catch {
183
+ // Unreadable: use a fresh id, saved with the first write that works.
184
+ this._deviceId = randomId();
185
+ return;
186
+ }
187
+ if (isDeviceId(stored)) {
188
+ this._deviceId = stored;
189
+ this._deviceSaved = true;
190
+ } else {
191
+ this._deviceId = randomId();
192
+ }
193
+ }
194
+
195
+ /**
196
+ * A write that would add a device past the cap is refused, so the stored
197
+ * save never becomes one that validate rejects.
198
+ * @private
199
+ */
200
+ _hasSlot() {
201
+ const ids = deviceIds(this._doc);
202
+ if (ids.has(this._deviceId) || ids.size < MAX_DEVICES) return true;
203
+ this._publish('load_failed', { key: 'player', reason: 'too_many_devices' });
204
+ return false;
205
+ }
206
+
151
207
  _requirePlayer() {
152
- if (!this.player) {
208
+ if (!this._doc) {
153
209
  throw new Error('[DopamineJS] RewardSystem.init() must be awaited before use');
154
210
  }
155
211
  }
156
212
 
157
213
  /**
158
- * @private
214
+ * A frozen copy of the player with the derived values: xp, level,
215
+ * totalGamesPlayed, streak and per-activity stats.
159
216
  */
160
- _publishStreak() {
161
- const { current, longest } = this.player.streak;
162
- this._publish('streak_updated', { current, longest });
217
+ snapshot() {
218
+ this._requirePlayer();
219
+ return freeze(view(this._doc, this.clock.localDate()));
163
220
  }
164
221
 
165
222
  /**
166
- * Get default player data structure
223
+ * The versioned document, a detached copy.
167
224
  */
168
- _getDefaultPlayer() {
169
- return {
170
- name: 'Player',
171
- xp: 0,
172
- level: 1,
173
- totalGamesPlayed: 0,
174
- createdAt: Date.now(),
175
- lastPlayedAt: Date.now(),
176
- streak: {
177
- current: 1,
178
- longest: 1,
179
- lastPlayDate: this._getTodayDateString()
180
- },
181
- achievements: {}, // achievement_id: { unlockedAt: timestamp, seen: boolean }
182
- stats: {
183
- // Dynamic stats object, games will add their own keys
184
- }
185
- };
225
+ export() {
226
+ this._requirePlayer();
227
+ return clone(this._doc);
186
228
  }
187
229
 
188
230
  /**
189
- * Merge a persisted player record onto the current default shape.
190
- *
191
- * Saves written by older versions are missing whatever fields were added
192
- * since. Without this the first property access on a new field throws
193
- * before the game has drawn a frame.
231
+ * Merge a document from elsewhere into this player. It is validated the
232
+ * same way a load is. Unless `silent`, the XP, level and achievements
233
+ * that went up are announced.
194
234
  *
195
- * @param {Object|null} saved - Previously persisted player, if any
196
- * @returns {Object} Player object guaranteed to have every field
197
- * @private
235
+ * @param {Object} doc
236
+ * @param {{ silent?: boolean }} [options]
198
237
  */
199
- _migrate(saved) {
200
- const defaults = this._getDefaultPlayer();
238
+ async import(doc, { silent = false } = {}) {
239
+ this._requirePlayer();
240
+ const before = this.snapshot();
241
+ const incoming = validate(doc, this._options());
242
+ const merged = merge(this._doc, incoming, this._options());
243
+ merged.level = levelOf(merged);
244
+ this._doc = merged;
201
245
 
202
- if (!isRecord(saved)) {
203
- return defaults;
246
+ const after = this.snapshot();
247
+ await this.save();
248
+ if (silent) return after;
249
+
250
+ const gained = after.xp - before.xp;
251
+ const leveledUp = after.level > before.level;
252
+ if (gained > 0) {
253
+ this._publish('xp_gained', {
254
+ amount: gained, reason: 'import', leveledUp, newLevel: after.level, total: after.xp
255
+ });
204
256
  }
205
-
206
- // Storage is writable by the player and by anything else on the
207
- // origin, so every field is checked. A string xp would concatenate on
208
- // the next addXP, and a non-object stats would throw on first use.
209
- const xpValue = Number(saved.xp);
210
- const xp = Number.isFinite(xpValue) && xpValue >= 0 ? xpValue : 0;
211
- const earned = this._calculateLevel(xp);
212
-
213
- const savedStreak = isRecord(saved.streak) ? saved.streak : {};
214
- const current = toCount(savedStreak.current, 1, 1);
215
- const lastPlayDate = typeof savedStreak.lastPlayDate === 'string'
216
- && /^\d{4}-\d{2}-\d{2}$/.test(savedStreak.lastPlayDate)
217
- ? savedStreak.lastPlayDate
218
- : defaults.streak.lastPlayDate;
219
-
220
- return {
221
- ...defaults,
222
- ...saved,
223
- name: typeof saved.name === 'string' ? saved.name : defaults.name,
224
- xp,
225
- // A level above the curve is kept: older versions banked levels
226
- // at half the XP and those players keep what they earned.
227
- level: Math.max(earned, toCount(saved.level, earned, 1)),
228
- totalGamesPlayed: toCount(saved.totalGamesPlayed, 0),
229
- createdAt: Number.isFinite(saved.createdAt) ? saved.createdAt : defaults.createdAt,
230
- lastPlayedAt: Number.isFinite(saved.lastPlayedAt) ? saved.lastPlayedAt : defaults.lastPlayedAt,
231
- streak: {
232
- current,
233
- longest: Math.max(current, toCount(savedStreak.longest, current, 1)),
234
- lastPlayDate
235
- },
236
- achievements: this._migrateAchievements(saved.achievements),
237
- stats: this._migrateStats(saved.stats)
238
- };
257
+ if (leveledUp) {
258
+ this._publish('level_up', { oldLevel: before.level, newLevel: after.level, totalXP: after.xp });
259
+ }
260
+ for (const id of Object.keys(after.achievements)) {
261
+ // An id with no definition stays in the save but has nothing to announce.
262
+ if (!hasOwn(before.achievements, id) && hasOwn(this.achievements, id)) {
263
+ this._publish('achievement_unlocked', { ...this.achievements[id], id });
264
+ }
265
+ }
266
+ return after;
239
267
  }
240
268
 
241
269
  /**
242
- * @private
270
+ * Replace the player with a new one and save it. The device id stays, so
271
+ * the new player counts under the same device. After the save it emits
272
+ * `player_reset`, so wrappers can refresh.
273
+ *
274
+ * This is an explicit request, so it also writes when the last init()
275
+ * could not read the saved player: the stored player is replaced, without
276
+ * a backup, and `loadFailed` goes back to false.
277
+ *
278
+ * Timing: call it after init() has resolved, not while init() is pending.
279
+ * A record() already in flight when reset() runs lands in the new player.
280
+ * Called from inside a hook, the write happens when the outer record or
281
+ * unlock finishes.
282
+ *
283
+ * @returns {Promise<Object>} Frozen snapshot of the new player
243
284
  */
244
- _migrateAchievements(saved) {
245
- const achievements = {};
246
- if (!isRecord(saved)) return achievements;
247
-
248
- for (const id of Object.keys(saved)) {
249
- const entry = saved[id];
250
- if (!isSafeKey(id) || !isRecord(entry)) continue;
251
-
252
- achievements[id] = {
253
- unlockedAt: Number.isFinite(entry.unlockedAt) ? entry.unlockedAt : Date.now(),
254
- seen: entry.seen === true
255
- };
256
- }
257
-
258
- return achievements;
285
+ async reset() {
286
+ this._requirePlayer();
287
+ await this._batch(async () => {
288
+ this._doc = emptyDoc(this.clock.now());
289
+ this._loadFailed = false;
290
+ this._readFailed = false;
291
+ await this.save();
292
+ });
293
+ this._publish('player_reset', {});
294
+ return this.snapshot();
259
295
  }
260
296
 
261
297
  /**
262
- * @private
298
+ * Add a middleware object with any of beforeXP, afterXP, beforeRecord,
299
+ * afterRecord, beforeUnlock and afterUnlock. Hooks run in `use` order.
300
+ * @returns {Function} Removes it again
263
301
  */
264
- _migrateStats(saved) {
265
- const stats = {};
266
- if (!isRecord(saved)) return stats;
267
-
268
- for (const gameName of Object.keys(saved)) {
269
- const entry = saved[gameName];
270
- if (!isSafeKey(gameName) || !isRecord(entry)) continue;
271
-
272
- const game = {};
273
- for (const key of Object.keys(entry)) {
274
- if (isSafeKey(key) && Number.isFinite(entry[key])) {
275
- game[key] = entry[key];
276
- }
277
- }
278
- game.totalPlays = toCount(entry.totalPlays, 0);
279
- game.highScore = Number.isFinite(entry.highScore) ? entry.highScore : 0;
302
+ use(middleware) {
303
+ return this._middleware.use(middleware);
304
+ }
280
305
 
281
- stats[gameName] = game;
306
+ /**
307
+ * Add an achievement rule at runtime.
308
+ * @returns {Function} Removes it again
309
+ */
310
+ defineAchievement(id, definition) {
311
+ if (!isSafeKey(id)) {
312
+ throw new TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(id)}`);
282
313
  }
283
-
284
- return stats;
314
+ if (!isRecord(definition) || typeof definition.check !== 'function') {
315
+ throw new TypeError('[DopamineJS] defineAchievement expects a definition with a check function');
316
+ }
317
+ const previous = hasOwn(this.achievements, id) ? this.achievements[id] : undefined;
318
+ this.achievements[id] = definition;
319
+ return () => {
320
+ if (this.achievements[id] !== definition) return;
321
+ if (previous) this.achievements[id] = previous;
322
+ else delete this.achievements[id];
323
+ };
285
324
  }
286
325
 
287
326
  /**
288
327
  * Save player data
289
328
  */
290
329
  async save() {
291
- if (!this.player) return;
330
+ if (!this._doc) return;
292
331
 
293
332
  // Inside a batch, mark dirty and let the outermost call do the write.
294
333
  if (this._batchDepth > 0) {
@@ -305,8 +344,11 @@ export class RewardSystem extends EventEmitter {
305
344
  */
306
345
  async _write() {
307
346
  if (this._loadFailed) return;
308
- this.player.lastPlayedAt = Date.now();
309
- const saved = await this.dataService.save('player', this.player);
347
+ this._doc.lastPlayedAt = this.clock.now();
348
+ if (!this._deviceSaved) {
349
+ this._deviceSaved = (await this.dataService.save(DEVICE_KEY, this._deviceId)) !== false;
350
+ }
351
+ const saved = await this.dataService.save('player', this._doc);
310
352
 
311
353
  // DataService logs and returns false rather than throwing, so a full
312
354
  // or blocked storage would otherwise lose progress without a sign.
@@ -316,42 +358,69 @@ export class RewardSystem extends EventEmitter {
316
358
  }
317
359
 
318
360
  /**
319
- * Add XP and handle level ups
361
+ * Add XP and handle level ups. A negative amount is kept as XP spent on
362
+ * this device and stops at zero.
320
363
  * @param {number} amount - XP to add
321
364
  * @param {string} reason - Why XP was awarded (for notifications)
322
365
  * @returns {Object} { leveledUp: boolean, newLevel: number, xpGained: number }
323
366
  */
324
367
  async addXP(amount, reason = '') {
325
368
  if (!Number.isFinite(amount)) {
326
- // Adding undefined/NaN here would poison player.xp permanently:
369
+ // Adding undefined/NaN here would poison the total permanently:
327
370
  // NaN survives every subsequent arithmetic op and gets persisted.
328
371
  throw new TypeError(`[DopamineJS] addXP expects a finite number, received ${amount}`);
329
372
  }
330
373
 
331
374
  this._requirePlayer();
375
+ if (!this._hasSlot()) return { leveledUp: false, newLevel: levelOf(this._doc), xpGained: 0 };
332
376
 
333
- const oldLevel = this.player.level;
377
+ const context = await this._middleware.before('beforeXP', { amount, reason }, (next) => Number.isFinite(next.amount));
378
+ if (context === false) {
379
+ return { leveledUp: false, newLevel: levelOf(this._doc), xpGained: 0 };
380
+ }
334
381
 
335
- // XP stops at zero, so a large negative amount removes less than
336
- // asked. Report what changed.
337
- amount = Math.max(amount, -this.player.xp);
338
- this.player.xp += amount;
382
+ if (this.streakDays === 'any' && context.amount > 0) this._markDay();
339
383
 
340
- // Check for level up. Levels are never taken back, so a negative
341
- // amount or a level banked under an older curve reports the stored one.
342
- const newLevel = Math.max(oldLevel, this._calculateLevel(this.player.xp));
343
- const leveledUp = newLevel > oldLevel;
384
+ const result = await this._applyXP(context.amount, context.reason, (doc, applied) => {
385
+ if (applied >= 0) {
386
+ doc.xpBy[this._deviceId] = cap((hasOwn(doc.xpBy, this._deviceId) ? doc.xpBy[this._deviceId] : 0) + applied);
387
+ } else {
388
+ doc.xpSpentBy[this._deviceId] = cap((hasOwn(doc.xpSpentBy, this._deviceId) ? doc.xpSpentBy[this._deviceId] : 0) - applied);
389
+ }
390
+ });
344
391
 
345
- if (leveledUp) {
346
- this.player.level = newLevel;
347
- }
392
+ await this._middleware.after('afterXP', {
393
+ amount: result.xpGained, reason: context.reason, total: xpOf(this._doc), level: result.newLevel
394
+ });
395
+ return result;
396
+ }
397
+
398
+ /**
399
+ * Change the total, then announce it. Levels are never taken back, so a
400
+ * negative amount or a level banked under an older curve reports the
401
+ * stored one.
402
+ * @private
403
+ */
404
+ async _applyXP(amount, reason, change) {
405
+ const doc = this._doc;
406
+ const oldLevel = levelOf(doc);
407
+
408
+ // XP stops at zero, so a large negative amount removes less than asked.
409
+ amount = Math.max(amount, -xpOf(doc));
410
+ change(doc, amount);
411
+ return this._announceXP(oldLevel, amount, reason);
412
+ }
413
+
414
+ async _announceXP(oldLevel, amount, reason) {
415
+ const doc = this._doc;
416
+ const total = xpOf(doc);
417
+ const newLevel = Math.max(oldLevel, levelFor(total));
418
+ const leveledUp = newLevel > oldLevel;
419
+ if (newLevel > doc.level) doc.level = newLevel;
348
420
 
349
421
  await this.save();
350
422
 
351
- // Notify listeners
352
- const total = this.player.xp;
353
423
  this._publish('xp_gained', { amount, reason, leveledUp, newLevel, total });
354
-
355
424
  if (leveledUp) {
356
425
  this._publish('level_up', { oldLevel, newLevel, totalXP: total });
357
426
  }
@@ -359,140 +428,158 @@ export class RewardSystem extends EventEmitter {
359
428
  return { leveledUp, newLevel, xpGained: amount };
360
429
  }
361
430
 
362
- /**
363
- * Calculate level from XP (exponential curve)
364
- */
365
- _calculateLevel(xp) {
366
- // Curve: XP = 50 * level * (level - 1)
367
- // 50L² - 50L - xp = 0 => L = (1 + sqrt(1 + 4*xp/50)) / 2
368
- if (!(xp > 0)) return 1;
369
-
370
- const level = Math.floor((1 + Math.sqrt(1 + 4 * xp / 50)) / 2);
371
- return Math.max(1, level);
372
- }
373
-
374
431
  /**
375
432
  * Get XP needed for next level
376
433
  */
377
434
  getXPForNextLevel() {
378
435
  this._requirePlayer();
379
436
 
380
- const nextLevel = this.player.level + 1;
381
- const xpNeeded = 50 * nextLevel * (nextLevel - 1);
382
- const currentLevelXP = 50 * this.player.level * (this.player.level - 1);
437
+ const level = levelOf(this._doc);
438
+ const xp = xpOf(this._doc);
439
+ const xpNeeded = thresholdFor(level + 1);
440
+ const currentLevelXP = thresholdFor(level);
383
441
  const band = xpNeeded - currentLevelXP;
384
442
 
385
- // Clamped: a save written before the curve fix banked levels at half
386
- // the XP, so player.xp can sit below its own level's floor. Those
387
- // players keep the level they earned and start the band at 0.
443
+ // Clamped: a level banked under an older curve can sit above its own
444
+ // XP floor. Those players keep the level and start the band at 0.
388
445
  const progress = band > 0
389
- ? Math.max(0, Math.min(1, (this.player.xp - currentLevelXP) / band))
446
+ ? Math.max(0, Math.min(1, (xp - currentLevelXP) / band))
390
447
  : 0;
391
448
 
392
449
  return {
393
450
  total: xpNeeded,
394
- needed: Math.max(0, xpNeeded - this.player.xp),
451
+ needed: Math.max(0, xpNeeded - xp),
395
452
  progress
396
453
  };
397
454
  }
398
455
 
399
- /**
400
- * Record game result and award XP
401
- * @param {string} gameName - Unique ID for the game
402
- * @param {Object} result - Game-specific result data
403
- */
404
- async recordGame(gameName, result = {}) {
405
- this._requirePlayer();
406
-
407
- if (!isSafeKey(gameName)) {
408
- throw new TypeError(`[DopamineJS] recordGame expects a game name, received ${String(gameName)}`);
456
+ _checkRecord(activity, result) {
457
+ if (!isSafeKey(activity)) {
458
+ throw new TypeError(`[DopamineJS] record expects an activity name, received ${String(activity)}`);
409
459
  }
410
460
 
411
461
  if (!isRecord(result)) {
412
- throw new TypeError('[DopamineJS] recordGame expects a result object');
462
+ throw new TypeError('[DopamineJS] record expects a result object');
413
463
  }
414
464
 
415
465
  // Checked before anything is touched, so a bad score cannot leave the
416
466
  // play counted and the XP missing.
417
467
  if (result.score !== undefined && !Number.isFinite(result.score)) {
418
- throw new TypeError(`[DopamineJS] recordGame expects a finite score, received ${String(result.score)}`);
468
+ throw new TypeError(`[DopamineJS] record expects a finite score, received ${String(result.score)}`);
419
469
  }
470
+ }
471
+
472
+ /**
473
+ * Record a play and award XP
474
+ * @param {string} activity - Unique ID for the game or activity
475
+ * @param {Object} result - Result data. `score` sets the best; other numbers add up.
476
+ * @returns {Promise<boolean>} False when a beforeRecord hook rejected it
477
+ */
478
+ async record(activity, result = {}) {
479
+ this._requirePlayer();
480
+ this._checkRecord(activity, result);
481
+ if (!this._hasSlot()) return false;
420
482
 
421
- // Batched: addXP and each unlockAchievement below also save, which
422
- // meant four full serializations of the player object per game.
423
- return this._batch(() => this._recordGame(gameName, result));
483
+ const context = await this._middleware.before('beforeRecord', { activity, result }, (next) => {
484
+ try {
485
+ this._checkRecord(next.activity, next.result);
486
+ return true;
487
+ } catch {
488
+ return false;
489
+ }
490
+ });
491
+ if (context === false) return false;
492
+
493
+ // Batched: addXP and each unlockAchievement below also save.
494
+ const xp = await this._batch(() => this._record(context.activity, context.result));
495
+ await this._middleware.after('afterRecord', { activity: context.activity, result: context.result, xp });
496
+ return true;
424
497
  }
425
498
 
426
499
  /**
500
+ * Count today as a play day. A new player starts at 1 without an event.
427
501
  * @private
428
502
  */
429
- async _recordGame(gameName, result) {
430
- // A game played on a new day counts for the streak, not only a
431
- // page load. A tab left open past midnight used to miss the day.
432
- if (this._updateDailyStreak()) {
433
- this._publishStreak();
503
+ _markDay() {
504
+ const doc = this._doc;
505
+ const today = this.clock.localDate();
506
+ if (doc.playDates.includes(today)) return;
507
+ const firstEver = doc.playDates.length === 0;
508
+ doc.playDates = trimDays([...doc.playDates, today], today);
509
+ doc.longest = Math.max(doc.longest, longestRun(doc.playDates));
510
+ if (!firstEver) {
511
+ this._publish('streak_updated', {
512
+ current: currentStreak(doc.playDates, today),
513
+ longest: Math.max(doc.longest, longestRun(doc.playDates))
514
+ });
434
515
  }
516
+ }
435
517
 
436
- // Initialize stats for this game if not exists
437
- if (!hasOwn(this.player.stats, gameName)) {
438
- this.player.stats[gameName] = { totalPlays: 0, highScore: 0 };
439
- }
518
+ /**
519
+ * @private
520
+ */
521
+ async _record(activity, result) {
522
+ const doc = this._doc;
523
+ const device = this._deviceId;
524
+ const bump = (map, by) => {
525
+ map[device] = cap((hasOwn(map, device) ? map[device] : 0) + by);
526
+ };
527
+
528
+ this._markDay();
440
529
 
441
- const stats = this.player.stats[gameName];
530
+ if (!hasOwn(doc.playsBy, activity)) {
531
+ doc.playsBy[activity] = {};
532
+ doc.best[activity] = 0;
533
+ doc.sumsBy[activity] = {};
534
+ }
442
535
 
443
- // Update stats
444
- stats.totalPlays++;
445
- this.player.totalGamesPlayed++;
536
+ bump(doc.playsBy[activity], 1);
537
+ bump(doc.gamesBy, 1);
446
538
 
447
- // Update high score if applicable
448
- if (result.score !== undefined && result.score > stats.highScore) {
449
- stats.highScore = result.score;
450
- this._publish('new_high_score', { gameName, score: result.score });
539
+ if (result.score !== undefined && result.score > doc.best[activity]) {
540
+ doc.best[activity] = result.score;
541
+ this._publish('personal_best', { activity, score: result.score });
451
542
  }
452
543
 
453
- // Merge other result data into stats
454
- Object.keys(result).forEach(key => {
455
- if (key !== 'score' && isSafeKey(key)) {
456
- const current = hasOwn(stats, key) && Number.isFinite(stats[key]) ? stats[key] : 0;
457
- stats[key] = current + (Number.isFinite(result[key]) ? result[key] : 0);
458
- }
459
- });
544
+ // Other numbers add up per device. A negative or non-numeric value
545
+ // adds nothing, so a device's total only grows.
546
+ for (const key of Object.keys(result)) {
547
+ if (key === 'score' || key === 'plays' || key === 'best' || !isSafeKey(key)) continue;
548
+ if (!hasOwn(doc.sumsBy[activity], key)) doc.sumsBy[activity][key] = {};
549
+ bump(doc.sumsBy[activity][key], Number.isFinite(result[key]) && result[key] > 0 ? result[key] : 0);
550
+ }
460
551
 
461
552
  // Base XP for playing
462
553
  let xp = 10;
463
554
 
464
- // Score-based bonus. A negative score earns nothing extra; it does
465
- // not take XP away.
555
+ // Score-based bonus. A negative score earns nothing extra.
466
556
  if (result.score) {
467
557
  xp += Math.max(0, Math.floor(result.score / 5));
468
558
  }
469
559
 
470
- // Streak multiplier
471
560
  xp = Math.floor(xp * this.getStreakMultiplier());
472
561
 
473
- await this.addXP(xp, `Played ${gameName}`);
474
-
475
- // Check for achievements
476
- await this.checkAchievements(gameName, result);
477
-
562
+ await this.addXP(xp, `Played ${activity}`);
563
+ await this.checkAchievements(activity, result);
478
564
  await this.save();
565
+ return xp;
479
566
  }
480
567
 
481
568
  /**
482
569
  * Check and unlock achievements
483
570
  */
484
- async checkAchievements(gameName, result) {
571
+ async checkAchievements(activity, result) {
485
572
  const unlockedAchievements = [];
486
573
 
487
574
  for (const [id, achievement] of Object.entries(this.achievements)) {
488
575
  // Skip if already unlocked
489
- if (hasOwn(this.player.achievements, id)) continue;
576
+ if (hasOwn(this._doc.achievements, id)) continue;
490
577
 
491
578
  // Check conditions are user-supplied; one throwing must not stop
492
579
  // the others from ever unlocking.
493
580
  let met = false;
494
581
  try {
495
- met = achievement.check(this.player, gameName, result);
582
+ met = achievement.check(this.snapshot(), activity, result);
496
583
  } catch (error) {
497
584
  console.error(`[DopamineJS] Achievement "${id}" check threw:`, error);
498
585
  continue;
@@ -515,23 +602,29 @@ export class RewardSystem extends EventEmitter {
515
602
  if (!isSafeKey(achievementId) || !hasOwn(this.achievements, achievementId)) return false;
516
603
 
517
604
  // Already unlocked: paying the XP again would let one call farm levels.
518
- if (hasOwn(this.player.achievements, achievementId)) return false;
605
+ if (hasOwn(this._doc.achievements, achievementId)) return false;
519
606
 
520
607
  const achievement = this.achievements[achievementId];
521
608
  if (!achievement) return false;
522
609
 
523
- // Mark as unlocked
524
- this.player.achievements[achievementId] = {
525
- unlockedAt: Date.now(),
526
- seen: false
527
- };
610
+ const { [achievementId]: reward } = rewardsOf(this.achievements);
611
+ const context = await this._middleware.before(
612
+ 'beforeUnlock',
613
+ { id: achievementId, reward },
614
+ (next) => Number.isFinite(next.reward) && next.reward >= 0
615
+ );
616
+ if (context === false) return false;
617
+
618
+ const doc = this._doc;
619
+ const oldLevel = levelOf(doc);
620
+ doc.achievements[achievementId] = { unlockedAt: this.clock.now(), seen: false, reward: context.reward };
528
621
 
529
- // Award XP. `xp` is optional in a user-defined achievement.
530
- await this.addXP(Number.isFinite(achievement.xp) ? achievement.xp : 0,
531
- `Achievement: ${achievement.name}`);
622
+ // The reward is part of the achievement, not of any device's XP.
623
+ await this._announceXP(oldLevel, context.reward, `Achievement: ${achievement.name}`);
532
624
 
533
625
  this._publish('achievement_unlocked', { ...achievement, id: achievementId });
534
626
  await this.save();
627
+ await this._middleware.after('afterUnlock', { id: achievementId, reward: context.reward });
535
628
 
536
629
  return true;
537
630
  }
@@ -540,7 +633,8 @@ export class RewardSystem extends EventEmitter {
540
633
  * Get all unlocked achievements
541
634
  */
542
635
  getUnlockedAchievements() {
543
- return Object.entries(this.player.achievements)
636
+ this._requirePlayer();
637
+ return Object.entries(this._doc.achievements)
544
638
  .map(([id, data]) => ({
545
639
  ...this.achievements[id],
546
640
  id,
@@ -560,130 +654,21 @@ export class RewardSystem extends EventEmitter {
560
654
  */
561
655
  async markAchievementsSeen(achievementIds) {
562
656
  for (const id of achievementIds) {
563
- if (hasOwn(this.player.achievements, id)) {
564
- this.player.achievements[id].seen = true;
657
+ if (hasOwn(this._doc.achievements, id)) {
658
+ this._doc.achievements[id].seen = true;
565
659
  }
566
660
  }
567
661
  await this.save();
568
662
  }
569
663
 
570
- /**
571
- * Update daily streak
572
- * @returns {boolean} True when the calendar day changed
573
- */
574
- _updateDailyStreak() {
575
- const today = this._getTodayDateString();
576
- const lastPlayed = this.player.streak.lastPlayDate;
577
-
578
- if (lastPlayed === today) {
579
- // Already played today
580
- return false;
581
- }
582
-
583
- const yesterday = this._getYesterdayDateString();
584
-
585
- if (lastPlayed === yesterday) {
586
- // Streak continues!
587
- this.player.streak.current++;
588
- if (this.player.streak.current > this.player.streak.longest) {
589
- this.player.streak.longest = this.player.streak.current;
590
- }
591
- } else {
592
- // Streak broken
593
- this.player.streak.current = 1;
594
- }
595
-
596
- this.player.streak.lastPlayDate = today;
597
- return true;
598
- }
599
-
600
664
  /**
601
665
  * Get streak multiplier for XP
602
666
  */
603
667
  getStreakMultiplier() {
604
- const streak = this.player.streak.current;
668
+ const streak = this.snapshot().streak.current;
605
669
  if (streak >= 7) return 2.0; // 2× at 7 days
606
670
  if (streak >= 5) return 1.5; // 1.5× at 5 days
607
671
  if (streak >= 3) return 1.25; // 1.25× at 3 days
608
672
  return 1.0;
609
673
  }
610
-
611
- /**
612
- * Format a Date as a YYYY-MM-DD string in the player's local timezone.
613
- *
614
- * Deliberately not toISOString(), which formats in UTC. For anyone east or
615
- * west of Greenwich that shifts the calendar day for part of every day and
616
- * makes streaks reset or double-count.
617
- *
618
- * @param {Date} date
619
- * @returns {string}
620
- * @private
621
- */
622
- _toLocalDateString(date) {
623
- const year = date.getFullYear();
624
- const month = String(date.getMonth() + 1).padStart(2, '0');
625
- const day = String(date.getDate()).padStart(2, '0');
626
- return `${year}-${month}-${day}`;
627
- }
628
-
629
- /**
630
- * Get today's local date as YYYY-MM-DD string
631
- */
632
- _getTodayDateString() {
633
- return this._toLocalDateString(new Date());
634
- }
635
-
636
- /**
637
- * Get yesterday's local date as YYYY-MM-DD string
638
- */
639
- _getYesterdayDateString() {
640
- const yesterday = new Date();
641
- yesterday.setDate(yesterday.getDate() - 1);
642
- return this._toLocalDateString(yesterday);
643
- }
644
-
645
- /**
646
- * Initialize achievement definitions
647
- * Can be extended by games
648
- */
649
- _initAchievements() {
650
- return {
651
- // Universal achievements
652
- 'first_game': {
653
- name: 'First Steps',
654
- description: 'Play your first game',
655
- icon: '🎮',
656
- xp: 50,
657
- check: (player) => player.totalGamesPlayed >= 1
658
- },
659
- 'level_5': {
660
- name: 'Rising Star',
661
- description: 'Reach level 5',
662
- icon: '⭐',
663
- xp: 100,
664
- check: (player) => player.level >= 5
665
- },
666
- 'level_10': {
667
- name: 'Expert Player',
668
- description: 'Reach level 10',
669
- icon: '🏆',
670
- xp: 250,
671
- check: (player) => player.level >= 10
672
- },
673
- 'streak_3': {
674
- name: 'Dedicated',
675
- description: 'Play 3 days in a row',
676
- icon: '🔥',
677
- xp: 100,
678
- check: (player) => player.streak.current >= 3
679
- },
680
- 'streak_7': {
681
- name: 'Unstoppable',
682
- description: 'Play 7 days in a row',
683
- icon: '💥',
684
- xp: 300,
685
- check: (player) => player.streak.current >= 7
686
- }
687
- };
688
- }
689
674
  }