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