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
package/src/index.js CHANGED
@@ -1,16 +1,14 @@
1
- import Dopamine from './dopamine/index.js';
2
-
3
- // Re-export legacy systems
4
- export * from './dopamine/index.js';
5
-
6
- // Export New Kernel Architecture (Phase 0)
7
- export { DopamineKernel } from './core/DopamineKernel.js';
8
- export { EventBus } from './core/EventBus.js';
9
- export { SystemRegistry } from './core/SystemRegistry.js';
10
- export { PluginRegistry } from './core/PluginRegistry.js';
11
-
12
- // Export System Interfaces
13
- export * from './interfaces/index.js';
1
+ // Importing this module does nothing. Styles come from `dopaminejs/style.css`
2
+ // or RewardUI's `injectCss` option.
3
+ export { createDopamine, HOST_API } from './dopamine/host.js';
4
+ export { RewardSystem } from './dopamine/core/RewardSystem.js';
5
+ export { DataService } from './dopamine/core/DataService.js';
6
+ export { DopamineError } from './dopamine/core/DopamineError.js';
7
+ export { merge } from './dopamine/core/merge.js';
8
+ export { validate } from './dopamine/core/store.js';
9
+ export { RewardUI } from './dopamine/ui/RewardUI.js';
10
+ export { ParticleSystem } from './dopamine/effects/ParticleSystem.js';
11
+ export { SoundManager } from './dopamine/audio/SoundManager.js';
14
12
 
15
13
  // The emitter RewardSystem extends, so consumers can type their listeners.
16
14
  export { EventEmitter } from './dopamine/core/EventEmitter.js';
@@ -21,24 +19,3 @@ export { createMemoryStorage, resolveStorage } from './dopamine/utils/storage.js
21
19
  // Feel helpers: vibration and the reduced-motion preference
22
20
  export { createHaptics } from './dopamine/feel/haptics.js';
23
21
  export { prefersReducedMotion } from './dopamine/feel/motion.js';
24
-
25
- // Export New Engine Core
26
- export { Game } from './core/Game.js';
27
- export { Scene } from './core/Scene.js';
28
- export { GameObject } from './core/GameObject.js';
29
- export { Component } from './core/Component.js';
30
- export { Renderer } from './renderer/Renderer.js';
31
- export { Ticker } from './systems/Ticker.js';
32
- export { Loader, GlobalLoader } from './systems/Loader.js';
33
- export { Input, GlobalInput } from './systems/Input.js';
34
- export { Director } from './systems/Director.js';
35
- export { Physics, GlobalPhysics } from './systems/Physics.js';
36
- export { Vector2 } from './core/Vector2.js';
37
- export { Collider } from './core/Collider.js';
38
- export { Sprite } from './core/Sprite.js';
39
- export { Animator } from './core/Animator.js';
40
- export { TextureGenerator } from './dopamine/utils/TextureGenerator.js';
41
- export { ParticleEmitter, ScreenShake } from './dopamine/components/index.js';
42
-
43
- // Export default for backward compatibility
44
- export default Dopamine;
@@ -8,6 +8,9 @@
8
8
  */
9
9
 
10
10
  export { RewardSystem } from './dopamine/core/RewardSystem.js';
11
+ export { DopamineError } from './dopamine/core/DopamineError.js';
12
+ export { merge } from './dopamine/core/merge.js';
13
+ export { validate } from './dopamine/core/store.js';
11
14
  export { DataService } from './dopamine/core/DataService.js';
12
15
  export { EventEmitter } from './dopamine/core/EventEmitter.js';
13
16
  export { createMemoryStorage, resolveStorage } from './dopamine/utils/storage.js';
package/src/testing.js ADDED
@@ -0,0 +1,490 @@
1
+ /**
2
+ * Test kit for parts and plugins: a host that records what it is asked to
3
+ * show, the part conformance suites, and a loader for the spec fixtures.
4
+ * Needs vitest for the suites. Not for production code.
5
+ */
6
+
7
+ import { describe, it } from 'vitest';
8
+ import { readdirSync, readFileSync, existsSync } from 'node:fs';
9
+ import { dirname, join, resolve } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { createDopamine, HOST_API } from './dopamine/host.js';
12
+ import { createMemoryStorage } from './dopamine/utils/storage.js';
13
+ import { systemClock } from './dopamine/core/clock.js';
14
+
15
+ const CORE_EVENTS = {
16
+ xp_gained: { amount: 10, reason: 'test', totalXP: 10, leveledUp: false },
17
+ level_up: { oldLevel: 1, newLevel: 2, totalXP: 50 },
18
+ achievement_unlocked: { id: 'test', name: 'Test', description: 'Test', icon: '', xp: 5 },
19
+ personal_best: { activity: 'test', score: 10 },
20
+ streak_updated: { current: 1, longest: 1 },
21
+ player_reset: {},
22
+ save_failed: { error: new Error('save failed') },
23
+ load_failed: { reason: 'corrupt' }
24
+ };
25
+ const BURST_KINDS = ['confetti', 'sparkle', 'fire', 'stars', 'coins'];
26
+ const SOUND_KEYS = ['xp', 'level_up', 'achievement', 'personal_best', 'click', 'error'];
27
+ const ODD_KEYS = ['', 'nope', '__proto__', 'constructor', 'toString', 'hasOwnProperty', undefined, null, 42, {}];
28
+ const CLOCK_FORMAT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/;
29
+
30
+ const fail = (message) => {
31
+ throw new Error(message);
32
+ };
33
+ const assert = (condition, message) => {
34
+ if (!condition) fail(message);
35
+ };
36
+
37
+ // --- Test host ---------------------------------------------------------------
38
+
39
+ function makeClock(start) {
40
+ if (start !== null && typeof start === 'object') {
41
+ return { clock: start, move: () => fail('this clock is not a test clock, it cannot advance') };
42
+ }
43
+ const at = start === undefined ? '2026-01-15T09:00:00' : start;
44
+ if (typeof at !== 'string' || !CLOCK_FORMAT.test(at)) fail('clock must be YYYY-MM-DDTHH:MM:SS local time');
45
+ let ms = new Date(at).getTime();
46
+ return {
47
+ clock: { now: () => ms, localDate: (value = ms) => systemClock.localDate(value) },
48
+ move: (next) => { ms = next(ms); }
49
+ };
50
+ }
51
+
52
+ /**
53
+ * @param {Object} [options]
54
+ * @param {string|{now(): number, localDate(ms?: number): string}} [options.clock]
55
+ * Local time `YYYY-MM-DDTHH:MM:SS`, default 2026-01-15T09:00:00.
56
+ * @param {Object} [options.storage]
57
+ * @param {Object} [options.parts] - Replaces the recording part of the same name.
58
+ * `false` means none. Other createDopamine options (`plugins`, `streakDays`) pass through.
59
+ */
60
+ export function createTestHost(options = {}) {
61
+ const { clock: clockOption, storage, parts: overrides = {}, ...rest } = options || {};
62
+ const { clock, move } = makeClock(clockOption);
63
+
64
+ const popups = [];
65
+ const texts = [];
66
+ const huds = [];
67
+ const bursts = [];
68
+ const sounds = [];
69
+ const soundKeys = new Set();
70
+ const haptics = [];
71
+
72
+ const recorders = {
73
+ ui: () => ({
74
+ root: null,
75
+ hud: (state) => { huds.push(state); },
76
+ popup: (popup) => { popups.push(popup); },
77
+ text: (text) => { texts.push(text); },
78
+ destroy() {}
79
+ }),
80
+ particles: () => ({
81
+ burst: (kind, at, opts) => { bursts.push({ kind, at, opts }); },
82
+ destroy() {}
83
+ }),
84
+ sound: () => ({
85
+ play: (key) => { sounds.push(key); },
86
+ register(key) {
87
+ soundKeys.add(key);
88
+ return () => { soundKeys.delete(key); };
89
+ },
90
+ destroy() {}
91
+ }),
92
+ haptics: () => ({
93
+ tap: () => { haptics.push('tap'); },
94
+ double: () => { haptics.push('double'); },
95
+ setEnabled() {},
96
+ destroy() {}
97
+ })
98
+ };
99
+ const chosen = {};
100
+ for (const name of Object.keys(recorders)) {
101
+ const own = Object.prototype.hasOwnProperty.call(overrides, name);
102
+ chosen[name] = own ? overrides[name] : recorders[name]();
103
+ }
104
+
105
+ const host = createDopamine({
106
+ ...rest,
107
+ ...chosen,
108
+ storage: storage || createMemoryStorage(),
109
+ clock,
110
+ log: { warn: () => {}, error: () => {}, ...(rest.log || {}) }
111
+ });
112
+
113
+ // Every event on the bus, plugin events included.
114
+ const log = [];
115
+ const emit = host.progress.emit;
116
+ host.progress.emit = function recordedEmit(event, data) {
117
+ log.push({ event, data });
118
+ return emit.call(this, event, data);
119
+ };
120
+
121
+ const dispose = () => {
122
+ host.dispose();
123
+ host.progress.emit = emit;
124
+ };
125
+
126
+ return {
127
+ host,
128
+ progress: host.progress,
129
+ parts: host.parts,
130
+ ready: host.ready,
131
+ use: host.use,
132
+ dispose,
133
+ clock,
134
+ popups,
135
+ texts,
136
+ huds,
137
+ bursts,
138
+ sounds,
139
+ soundKeys,
140
+ haptics,
141
+ events: {
142
+ log,
143
+ on: (event, callback) => host.progress.on(event, callback),
144
+ off: (event, callback) => host.progress.off(event, callback),
145
+ emit: (event, data) => host.progress.emit(event, data)
146
+ },
147
+ advance: (ms) => move((now) => now + ms),
148
+ advanceDays(days) {
149
+ move((now) => {
150
+ const date = new Date(now);
151
+ date.setDate(date.getDate() + days);
152
+ return date.getTime();
153
+ });
154
+ },
155
+ setClock(at) {
156
+ if (!CLOCK_FORMAT.test(at)) fail('clock must be YYYY-MM-DDTHH:MM:SS local time');
157
+ move(() => new Date(at).getTime());
158
+ }
159
+ };
160
+ }
161
+
162
+ // --- Conformance -------------------------------------------------------------
163
+
164
+ const settle = async (value) => { await value; };
165
+
166
+ const domSnapshot = () => (typeof document === 'undefined' ? null : document.body.innerHTML);
167
+
168
+ const withParts = () => createTestHost().parts;
169
+
170
+ const particles = (make) => [
171
+ ['draws every burst kind without throwing', async () => {
172
+ const part = make();
173
+ try {
174
+ for (const kind of BURST_KINDS) {
175
+ part.burst(kind);
176
+ part.burst(kind, { x: 10, y: 20 });
177
+ part.burst(kind, { x: 10, y: 20 }, { count: 3, color: '#fff' });
178
+ }
179
+ } finally {
180
+ part.destroy();
181
+ }
182
+ }],
183
+ ['treats an unknown kind as a no-op', async () => {
184
+ const part = make();
185
+ try {
186
+ for (const kind of ODD_KEYS) part.burst(kind, { x: 1, y: 1 });
187
+ } finally {
188
+ part.destroy();
189
+ }
190
+ }],
191
+ ['has destroy', async () => {
192
+ const part = make();
193
+ assert(typeof part.destroy === 'function', 'a particle part needs destroy()');
194
+ part.destroy();
195
+ }]
196
+ ];
197
+
198
+ const sound = (make) => [
199
+ ['plays every preset key without throwing', async () => {
200
+ const part = make();
201
+ try {
202
+ for (const key of SOUND_KEYS) await settle(part.play(key));
203
+ } finally {
204
+ part.destroy();
205
+ }
206
+ }],
207
+ ['treats an unknown key as a no-op', async () => {
208
+ const part = make();
209
+ try {
210
+ for (const key of ODD_KEYS) await settle(part.play(key));
211
+ } finally {
212
+ part.destroy();
213
+ }
214
+ }],
215
+ ['stops a registered key after its remover runs', async () => {
216
+ const part = make();
217
+ try {
218
+ if (typeof part.register !== 'function') return;
219
+ let calls = 0;
220
+ const remove = part.register('conformance_key', () => { calls += 1; });
221
+ assert(typeof remove === 'function', 'register() must return a remover');
222
+ remove();
223
+ await settle(part.play('conformance_key'));
224
+ assert(calls === 0, 'a removed key still played');
225
+ } finally {
226
+ part.destroy();
227
+ }
228
+ }]
229
+ ];
230
+
231
+ const ui = (make) => [
232
+ ['draws the hud', async () => {
233
+ const part = make(withParts());
234
+ try {
235
+ part.hud({ xp: 10, level: 1, progress: 0.2, streak: 0, next: 50 });
236
+ part.hud({ xp: 0, level: 1, streak: 3 });
237
+ } finally {
238
+ part.destroy();
239
+ }
240
+ }],
241
+ ['shows every popup kind and tier', async () => {
242
+ const part = make(withParts());
243
+ try {
244
+ for (const kind of ['achievement', 'level', 'notice', 'custom']) {
245
+ for (const tier of [undefined, 'common', 'rare', 'legendary']) {
246
+ part.popup({ kind, title: 'T', body: 'B', icon: 'I', meta: 'M', tier });
247
+ }
248
+ }
249
+ } finally {
250
+ part.destroy();
251
+ }
252
+ }],
253
+ ['ignores a popup it cannot read', async () => {
254
+ const part = make(withParts());
255
+ try {
256
+ for (const bad of [undefined, null, 42, 'text', {}, { kind: '__proto__' }]) part.popup(bad);
257
+ } finally {
258
+ part.destroy();
259
+ }
260
+ }],
261
+ ['floats text', async () => {
262
+ const part = make(withParts());
263
+ try {
264
+ part.text({ text: 'hello', x: 5, y: 5, color: '#fff' });
265
+ part.text({ text: 'hello' });
266
+ } finally {
267
+ part.destroy();
268
+ }
269
+ }],
270
+ ['has a root that is an element or null', async () => {
271
+ const part = make(withParts());
272
+ try {
273
+ const root = part.root;
274
+ assert(root === null || (typeof root === 'object' && typeof root.nodeType === 'number'), 'root must be an element or null');
275
+ } finally {
276
+ part.destroy();
277
+ }
278
+ }],
279
+ ['leaves no DOM behind after destroy', async () => {
280
+ const before = domSnapshot();
281
+ const part = make(withParts());
282
+ part.hud({ xp: 1, level: 1, streak: 1 });
283
+ part.popup({ kind: 'achievement', title: 'T' });
284
+ part.text({ text: 'x' });
285
+ part.destroy();
286
+ assert(domSnapshot() === before, 'the page changed after destroy()');
287
+ }]
288
+ ];
289
+
290
+ const STORAGE_KEY = 'conformance_key';
291
+
292
+ const storage = (make) => [
293
+ ['returns null for a missing key', async () => {
294
+ const store = make();
295
+ for (const key of [STORAGE_KEY, '__proto__', 'constructor', 'toString']) {
296
+ assert((await store.getItem(key)) === null, `getItem(${key}) should be null`);
297
+ }
298
+ }],
299
+ ['keeps what setItem stores and overwrites it', async () => {
300
+ const store = make();
301
+ await store.setItem(STORAGE_KEY, 'one');
302
+ assert((await store.getItem(STORAGE_KEY)) === 'one', 'getItem should return the stored value');
303
+ await store.setItem(STORAGE_KEY, 'two');
304
+ assert((await store.getItem(STORAGE_KEY)) === 'two', 'setItem should overwrite');
305
+ }],
306
+ ['keeps keys apart', async () => {
307
+ const store = make();
308
+ await store.setItem('a', '1');
309
+ await store.setItem('b', '2');
310
+ assert((await store.getItem('a')) === '1' && (await store.getItem('b')) === '2', 'keys must not share a value');
311
+ }],
312
+ ['forgets a key after removeItem', async () => {
313
+ const store = make();
314
+ await store.setItem(STORAGE_KEY, 'one');
315
+ await store.removeItem(STORAGE_KEY);
316
+ assert((await store.getItem(STORAGE_KEY)) === null, 'removeItem should clear the key');
317
+ await store.removeItem(STORAGE_KEY);
318
+ }]
319
+ ];
320
+
321
+ // Timers a case starts and does not clear or finish.
322
+ function watchTimers() {
323
+ const live = new Set();
324
+ const real = {};
325
+ const names = ['setTimeout', 'setInterval', 'requestAnimationFrame'];
326
+ const clears = { setTimeout: 'clearTimeout', setInterval: 'clearInterval', requestAnimationFrame: 'cancelAnimationFrame' };
327
+ for (const name of names) {
328
+ real[name] = globalThis[name];
329
+ real[clears[name]] = globalThis[clears[name]];
330
+ if (typeof real[name] !== 'function') continue;
331
+ globalThis[name] = (callback, ...args) => {
332
+ const once = name !== 'setInterval';
333
+ let id;
334
+ const wrapped = (...inner) => {
335
+ if (once) live.delete(id);
336
+ return callback(...inner);
337
+ };
338
+ id = real[name](wrapped, ...args);
339
+ live.add(id);
340
+ return id;
341
+ };
342
+ if (typeof real[clears[name]] === 'function') {
343
+ globalThis[clears[name]] = (id) => {
344
+ live.delete(id);
345
+ return real[clears[name]](id);
346
+ };
347
+ }
348
+ }
349
+ return {
350
+ live: () => live.size,
351
+ stop() {
352
+ for (const id of live) {
353
+ real.clearTimeout?.(id);
354
+ real.clearInterval?.(id);
355
+ real.cancelAnimationFrame?.(id);
356
+ }
357
+ for (const name of Object.keys(real)) {
358
+ if (typeof real[name] === 'function') globalThis[name] = real[name];
359
+ }
360
+ }
361
+ };
362
+ }
363
+
364
+ const countListeners = (progress) => {
365
+ let total = 0;
366
+ for (const set of progress.listeners.values()) total += set.size;
367
+ return total;
368
+ };
369
+
370
+ async function withPluginHost(make, run) {
371
+ const watch = watchTimers();
372
+ const errors = [];
373
+ const realError = console.error;
374
+ console.error = (...args) => { errors.push(args); };
375
+ const test = createTestHost();
376
+ try {
377
+ await test.ready;
378
+ await run(test, { watch, errors });
379
+ } finally {
380
+ console.error = realError;
381
+ test.dispose();
382
+ watch.stop();
383
+ }
384
+ }
385
+
386
+ const plugin = (make) => [
387
+ ['has a name, a version and the host api', async () => {
388
+ const p = make();
389
+ assert(typeof p.name === 'string' && p.name !== '', 'a plugin needs a name');
390
+ assert(typeof p.version === 'string' && p.version !== '', 'a plugin needs a version');
391
+ assert(p.api === HOST_API, `a plugin needs api ${HOST_API}`);
392
+ assert(typeof p.install === 'function', 'a plugin needs install()');
393
+ }],
394
+ ['installs on a host and survives every core event', async () => {
395
+ await withPluginHost(make, async (test, { errors }) => {
396
+ test.use(make());
397
+ await test.ready;
398
+ for (const event of Object.keys(CORE_EVENTS)) test.progress.emit(event, CORE_EVENTS[event]);
399
+ await test.progress.addXP(5, 'conformance');
400
+ assert(errors.length === 0, `a listener threw: ${String(errors[0]?.[1] ?? errors[0]?.[0])}`);
401
+ });
402
+ }],
403
+ ['leaves no listeners, timers or DOM behind once disposed', async () => {
404
+ await withPluginHost(make, async (test, { watch }) => {
405
+ await test.ready;
406
+ const listeners = countListeners(test.progress);
407
+ const dom = domSnapshot();
408
+ const timers = watch.live();
409
+
410
+ const dispose = test.use(make());
411
+ await test.progress.addXP(1, 'conformance');
412
+ for (const event of Object.keys(CORE_EVENTS)) test.progress.emit(event, CORE_EVENTS[event]);
413
+ await test.ready;
414
+ dispose();
415
+
416
+ assert(countListeners(test.progress) === listeners, 'the plugin left listeners on the bus');
417
+ assert(watch.live() <= timers, 'the plugin left timers running');
418
+ assert(domSnapshot() === dom, 'the plugin left DOM in the page');
419
+ });
420
+ }]
421
+ ];
422
+
423
+ const SUITES = { particles, sound, ui, storage, plugin };
424
+
425
+ const suite = (name) => (make) => {
426
+ describe(`conformance.${name}`, () => {
427
+ for (const [title, run] of SUITES[name](make)) it(title, run);
428
+ });
429
+ };
430
+
431
+ /** Each suite is a vitest `describe` block. */
432
+ export const conformance = {
433
+ particles: suite('particles'),
434
+ sound: suite('sound'),
435
+ ui: suite('ui'),
436
+ storage: suite('storage'),
437
+ plugin: suite('plugin')
438
+ };
439
+
440
+ /**
441
+ * Runs a suite without vitest's describe and returns the titles that failed,
442
+ * so a test can prove a bad part is caught.
443
+ * @param {'particles'|'sound'|'ui'|'storage'|'plugin'} name
444
+ * @param {Function} make
445
+ * @returns {Promise<string[]>}
446
+ */
447
+ export async function conformanceFailures(name, make) {
448
+ if (!Object.prototype.hasOwnProperty.call(SUITES, name)) fail(`unknown suite ${String(name)}`);
449
+ const failed = [];
450
+ for (const [title, run] of SUITES[name](make)) {
451
+ try {
452
+ await run();
453
+ } catch {
454
+ failed.push(title);
455
+ }
456
+ }
457
+ return failed;
458
+ }
459
+
460
+ // --- Fixtures ----------------------------------------------------------------
461
+
462
+ function specDir() {
463
+ // dist/ and the built package keep spec/ one level up. From src/ in the
464
+ // repo, the copy may not exist yet, so fall back to the repo root.
465
+ // The CommonJS build has __dirname and no import.meta.
466
+ const here = typeof __dirname === 'string' ? __dirname : dirname(fileURLToPath(import.meta.url));
467
+ for (const path of ['../spec', '../../../spec']) {
468
+ const dir = resolve(here, path);
469
+ if (existsSync(join(dir, 'VERSION'))) return dir;
470
+ }
471
+ return fail('spec/ was not found next to this package');
472
+ }
473
+
474
+ /**
475
+ * Reads the conformance fixtures shipped in `spec/`.
476
+ * @param {string} [dir] - A spec folder, default the one in this package.
477
+ * @returns {{ contract: number, schema: Object, suites: Object }} `suites` is keyed by suite name.
478
+ */
479
+ export function loadFixtures(dir) {
480
+ const root = dir || specDir();
481
+ const contract = Number(/contract:\s*(\d+)/.exec(readFileSync(join(root, 'VERSION'), 'utf8'))?.[1]);
482
+ const schema = JSON.parse(readFileSync(join(root, 'schema.json'), 'utf8'));
483
+ const suites = {};
484
+ for (const file of readdirSync(join(root, 'fixtures')).sort()) {
485
+ if (!file.endsWith('.json')) continue;
486
+ const fixture = JSON.parse(readFileSync(join(root, 'fixtures', file), 'utf8'));
487
+ suites[fixture.suite] = fixture;
488
+ }
489
+ return { contract, schema, suites };
490
+ }
package/types/core.d.ts CHANGED
@@ -1,19 +1,27 @@
1
1
  /**
2
2
  * Types for the `dopaminejs/core` subpath. Only what that entry exports at
3
- * runtime, plus the types those values use, so importing GameUI or another
3
+ * runtime, plus the types those values use, so importing RewardUI or another
4
4
  * web-only name from it fails to compile instead of being undefined.
5
5
  */
6
6
  export {
7
7
  RewardSystem,
8
8
  DataService,
9
9
  EventEmitter,
10
+ DopamineError,
11
+ merge,
12
+ validate,
10
13
  createMemoryStorage,
11
14
  resolveStorage
12
15
  } from './index';
13
16
 
14
17
  export type {
15
18
  Player,
19
+ PlayerDocument,
16
20
  PlayerStreak,
21
+ Clock,
22
+ DopamineErrorCode,
23
+ ValidateOptions,
24
+ Middleware,
17
25
  UnlockedAchievement,
18
26
  AchievementDefinition,
19
27
  GameResult,
@@ -0,0 +1,46 @@
1
+ import type { DopaminePlugin } from './index';
2
+
3
+ export interface GameFeedbackText {
4
+ /** Default `{n}× COMBO!`. `{n}` is the multiplier. */
5
+ combo?: string;
6
+ /** Default `CLOSE CALL!`. */
7
+ nearMiss?: string;
8
+ /** Default `LUCKY {n}×!`. */
9
+ luckyMoment?: string;
10
+ /** Default `Game Over`. */
11
+ gameOver?: string;
12
+ /** Default `Play Again`. */
13
+ playAgain?: string;
14
+ /** Default `Exit`. */
15
+ exit?: string;
16
+ }
17
+
18
+ export interface GameFeedbackOptions {
19
+ /** Replaces the built-in strings, rendered as text. An empty string hides one. */
20
+ text?: GameFeedbackText;
21
+ }
22
+
23
+ export interface RunSummary {
24
+ score: number | string;
25
+ /** Label and value pairs listed under the score. */
26
+ metrics?: Record<string, number | string>;
27
+ /** Default: reload the page. */
28
+ onReplay?: () => void;
29
+ /** The button is left out without it. */
30
+ onExit?: () => void;
31
+ }
32
+
33
+ /**
34
+ * Needs the `ui` part. The methods do nothing before install and after dispose.
35
+ */
36
+ export interface GameFeedback extends DopaminePlugin {
37
+ requires: ['ui'];
38
+ combo(multiplier: number, x: number, y: number): void;
39
+ nearMiss(x: number, y: number): void;
40
+ luckyMoment(multiplier: number, x: number, y: number): void;
41
+ /** Returns the overlay, which is removed when the plugin is disposed. Null without a DOM. */
42
+ summary(data: RunSummary): HTMLElement | null;
43
+ }
44
+
45
+ /** Adds the `jump`, `score` and `gameover` sound keys to `parts.sound` while installed. */
46
+ export function gameFeedback(options?: GameFeedbackOptions): GameFeedback;