dopaminejs 3.4.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DataService-CydwGT_D.js → DataService-QQBNqJtN.js} +291 -115
- package/dist/DataService-Xk7egYXe.cjs +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/dopamine.cjs +1 -1
- package/dist/dopamine.global.js +4 -4
- package/dist/dopamine.js +2 -2
- package/dist/{host-MPzunSej.cjs → host-1c7QSAKI.cjs} +2 -2
- package/dist/{host-DOvdGHZL.js → host-_essSMef.js} +4 -3
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +4 -3
- package/package.json +1 -1
- package/spec/README.md +113 -14
- package/spec/fixtures/merge.json +345 -0
- package/spec/fixtures/migrate.json +345 -22
- package/spec/fixtures/recovery.json +1861 -0
- package/spec/schema.json +2 -2
- package/src/dopamine/core/RewardSystem.js +150 -11
- package/src/dopamine/core/merge.js +116 -1
- package/src/dopamine/core/store.js +90 -32
- package/src/dopamine/host.js +3 -1
- package/src/testing.js +2 -1
- package/types/index.d.ts +25 -4
- package/dist/DataService-EJeOPnbo.cjs +0 -1
package/spec/schema.json
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
3
|
"$id": "https://github.com/BaryoDev/dopaminejs/spec/schema.json",
|
|
4
4
|
"title": "DopamineJS player document, contract 3",
|
|
5
|
-
"description": "What export() returns and what validate() and merge() accept. Only v is required on input; validate fills in the rest. Keys inside the per-device maps are device ids, which are never __proto__, constructor or prototype, and a document holds at most 20 of them across xpBy, xpSpentBy, gamesBy, playsBy and sumsBy.",
|
|
5
|
+
"description": "What export() returns and what validate() and merge() accept. Only v is required on input; validate fills in the rest. Any other top level field is kept as read (never __proto__, constructor or prototype). merge joins such a field by value: the larger number if both sides hold a finite number, otherwise the larger canonical JSON text. Recency is not used, since no field has its own timestamp and merge must not depend on order. Keys inside the per-device maps are device ids, which are never __proto__, constructor or prototype, and a document holds at most 20 of them across xpBy, xpSpentBy, gamesBy, playsBy and sumsBy.",
|
|
6
6
|
"type": "object",
|
|
7
7
|
"required": ["v"],
|
|
8
|
-
"additionalProperties":
|
|
8
|
+
"additionalProperties": true,
|
|
9
9
|
"properties": {
|
|
10
10
|
"v": { "const": 3 },
|
|
11
11
|
"name": { "type": "string" },
|
|
@@ -12,10 +12,10 @@ import { systemClock } from './clock.js';
|
|
|
12
12
|
import { levelFor, thresholdFor } from './levels.js';
|
|
13
13
|
import { BUILTIN_REWARDS, builtinAchievements, rewardsOf } from './achievements.js';
|
|
14
14
|
import { Middleware } from './middleware.js';
|
|
15
|
-
import { merge } from './merge.js';
|
|
15
|
+
import { merge, mergeSession, rekey, ownCounters, raiseOwn, countedDevices } from './merge.js';
|
|
16
16
|
import { currentStreak, longestRun, trimDays } from './streaks.js';
|
|
17
17
|
import {
|
|
18
|
-
LEGACY, MAX_DEVICES, cap, deviceIds, emptyDoc, validate, view, xpOf, levelOf, clone, freeze, isSafeKey, hasOwn, isRecord
|
|
18
|
+
LEGACY, MAX_DEVICES, cap, checkDevices, deviceIds, emptyDoc, validate, view, xpOf, levelOf, clone, freeze, isSafeKey, hasOwn, isRecord
|
|
19
19
|
} from './store.js';
|
|
20
20
|
|
|
21
21
|
const DEVICE_KEY = 'device';
|
|
@@ -45,6 +45,8 @@ export class RewardSystem extends EventEmitter {
|
|
|
45
45
|
* @param {'any'|'record'} [config.streakDays] - What marks today as a play day.
|
|
46
46
|
* 'any' (default): record() or addXP(). 'record': record() only. XP from an
|
|
47
47
|
* achievement reward never marks a day.
|
|
48
|
+
* @param {number} [config.loadRetryMs] - After a failed read, a blocked save retries the
|
|
49
|
+
* read at most this often, in ms of the clock. Default 30000. 0 retries on every blocked save.
|
|
48
50
|
*/
|
|
49
51
|
constructor(dataService, config = {}) {
|
|
50
52
|
super();
|
|
@@ -73,11 +75,26 @@ export class RewardSystem extends EventEmitter {
|
|
|
73
75
|
// never replaced by accident.
|
|
74
76
|
this._loadFailed = false;
|
|
75
77
|
this._readFailed = false;
|
|
78
|
+
|
|
79
|
+
// Retry of a failed read: when it last read, the retry in flight, and a
|
|
80
|
+
// counter that lets init() cancel a retry it overtakes.
|
|
81
|
+
this.loadRetryMs = Number.isFinite(config.loadRetryMs) && config.loadRetryMs >= 0 ? config.loadRetryMs : 30000;
|
|
82
|
+
this._lastRead = 0;
|
|
83
|
+
this._reading = false;
|
|
84
|
+
this._recovering = null;
|
|
85
|
+
this._epoch = 0;
|
|
86
|
+
|
|
87
|
+
// What imports and good reads put into this device's counters while the
|
|
88
|
+
// read is blocked. It is not progress made here, so a recovery does not add it.
|
|
89
|
+
this._forgetImports();
|
|
90
|
+
this._recoveries = 0;
|
|
76
91
|
}
|
|
77
92
|
|
|
78
93
|
/**
|
|
79
94
|
* True when the last init() could not read the saved player, so nothing
|
|
80
|
-
* is saved until init()
|
|
95
|
+
* is saved until a retry or init() reads it, or reset() is called. A blocked
|
|
96
|
+
* save retries the read (see `loadRetryMs`) and, when it works, merges the
|
|
97
|
+
* progress made since into the saved player, saves it and fires `load_recovered`.
|
|
81
98
|
* @returns {boolean}
|
|
82
99
|
*/
|
|
83
100
|
get loadFailed() {
|
|
@@ -117,9 +134,16 @@ export class RewardSystem extends EventEmitter {
|
|
|
117
134
|
* @returns {Promise<Object>} Frozen snapshot of the player
|
|
118
135
|
*/
|
|
119
136
|
async init() {
|
|
137
|
+
const known = this._doc && !this._loadFailed && ownCounters(this._doc, this._deviceId);
|
|
120
138
|
const saved = await this._readSaved();
|
|
121
139
|
// A failed retry keeps the progress made since the first init.
|
|
122
|
-
if (!(this._loadFailed && this._doc))
|
|
140
|
+
if (!(this._loadFailed && this._doc)) {
|
|
141
|
+
this._doc = this._load(saved);
|
|
142
|
+
this._forgetImports();
|
|
143
|
+
} else if (known) {
|
|
144
|
+
// That player came from storage, so what it held is not new progress.
|
|
145
|
+
known.forEach((value, path) => this._base.set(path, Math.max(this._base.get(path) ?? 0, value)));
|
|
146
|
+
}
|
|
123
147
|
await this._readDevice();
|
|
124
148
|
await this.save();
|
|
125
149
|
return this.snapshot();
|
|
@@ -135,6 +159,10 @@ export class RewardSystem extends EventEmitter {
|
|
|
135
159
|
// Stay blocked until the read succeeds, so a write made while a
|
|
136
160
|
// retry is in flight cannot land.
|
|
137
161
|
this._loadFailed = true;
|
|
162
|
+
this._reading = true;
|
|
163
|
+
this._epoch++;
|
|
164
|
+
this._recovering = null;
|
|
165
|
+
this._lastRead = this.clock.now();
|
|
138
166
|
try {
|
|
139
167
|
const saved = await this.dataService.load('player', null, { strict: true });
|
|
140
168
|
if (saved !== null && !isRecord(saved)) {
|
|
@@ -149,7 +177,82 @@ export class RewardSystem extends EventEmitter {
|
|
|
149
177
|
this._readFailed = true;
|
|
150
178
|
this._publish('load_failed', { key: 'player', reason: 'read', error });
|
|
151
179
|
return null;
|
|
180
|
+
} finally {
|
|
181
|
+
this._reading = false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Retry the read for a blocked save, at most once per interval, and merge
|
|
187
|
+
* the session player into what it finds. Resolves true when it saved. A
|
|
188
|
+
* retry already in flight is reused. Any failure leaves saving blocked and
|
|
189
|
+
* the session player as it is.
|
|
190
|
+
* @private
|
|
191
|
+
*/
|
|
192
|
+
_recover() {
|
|
193
|
+
// A retry in flight belongs to the call that started it. Others return
|
|
194
|
+
// at once, as a blocked save always did, so a read that never settles
|
|
195
|
+
// stalls only that one call.
|
|
196
|
+
if (this._recovering || !this._readFailed || this._reading) return Promise.resolve(false);
|
|
197
|
+
const since = this.clock.now() - this._lastRead;
|
|
198
|
+
if (since >= 0 && since < this.loadRetryMs) return Promise.resolve(false);
|
|
199
|
+
this._lastRead = this.clock.now();
|
|
200
|
+
const retry = this._retryRead(this._epoch).finally(() => {
|
|
201
|
+
if (this._recovering === retry) this._recovering = null;
|
|
202
|
+
});
|
|
203
|
+
this._recovering = retry;
|
|
204
|
+
return retry;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async _retryRead(epoch) {
|
|
208
|
+
let saved;
|
|
209
|
+
let adopt = null;
|
|
210
|
+
try {
|
|
211
|
+
saved = await this.dataService.load('player', null, { strict: true });
|
|
212
|
+
if (saved !== null && !isRecord(saved)) return false;
|
|
213
|
+
if (!this._deviceSaved) {
|
|
214
|
+
const stored = await this.dataService.load(DEVICE_KEY, null, { strict: true });
|
|
215
|
+
if (isDeviceId(stored) && stored !== this._deviceId) adopt = stored;
|
|
216
|
+
}
|
|
217
|
+
} catch {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
// init() or reset() ran meanwhile and owns the state now.
|
|
221
|
+
if (epoch !== this._epoch || !this._loadFailed) return false;
|
|
222
|
+
// Entries under the stored id that came from an import or from a read
|
|
223
|
+
// cannot be told from progress made here, so the move would count them twice.
|
|
224
|
+
if (countedDevices(this._doc).has(adopt)) return false;
|
|
225
|
+
|
|
226
|
+
// No await from here to the assignment, so the session player is
|
|
227
|
+
// merged as it stands, including any XP added while the read was out.
|
|
228
|
+
let merged;
|
|
229
|
+
try {
|
|
230
|
+
const options = this._options();
|
|
231
|
+
const device = adopt ?? this._deviceId;
|
|
232
|
+
const session = adopt ? rekey(this._doc, this._deviceId, adopt) : this._doc;
|
|
233
|
+
merged = saved === null ? clone(session) : mergeSession(saved, session, device, options, this._base);
|
|
234
|
+
checkDevices(merged);
|
|
235
|
+
merged.level = levelOf(merged);
|
|
236
|
+
} catch {
|
|
237
|
+
return false;
|
|
238
|
+
}
|
|
239
|
+
if (adopt) {
|
|
240
|
+
this._deviceId = adopt;
|
|
241
|
+
this._deviceSaved = true;
|
|
152
242
|
}
|
|
243
|
+
this._doc = merged;
|
|
244
|
+
this._recoveries++;
|
|
245
|
+
this._savedLevel = Number(saved?.level) || 0;
|
|
246
|
+
this._loadFailed = false;
|
|
247
|
+
this._readFailed = false;
|
|
248
|
+
this._forgetImports();
|
|
249
|
+
await this._write();
|
|
250
|
+
this._publish('load_recovered', { key: 'player' });
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
_forgetImports() {
|
|
255
|
+
this._base = new Map();
|
|
153
256
|
}
|
|
154
257
|
|
|
155
258
|
/**
|
|
@@ -253,9 +356,28 @@ export class RewardSystem extends EventEmitter {
|
|
|
253
356
|
this._requirePlayer();
|
|
254
357
|
const before = this.snapshot();
|
|
255
358
|
const incoming = validate(doc, this._options());
|
|
256
|
-
|
|
359
|
+
let session = this._doc;
|
|
360
|
+
let base = null;
|
|
361
|
+
if (this._readFailed) {
|
|
362
|
+
// This device's counters in the import are not new progress. Count them
|
|
363
|
+
// as a baseline so a recovery adds only what the session earned on top.
|
|
364
|
+
base = new Map(this._base);
|
|
365
|
+
const raise = new Map();
|
|
366
|
+
const have = ownCounters(this._doc, this._deviceId);
|
|
367
|
+
ownCounters(incoming, this._deviceId).forEach((value, path) => {
|
|
368
|
+
// At or below what the session holds, it is the session's own export or older.
|
|
369
|
+
if (value > (have.get(path) ?? 0)) {
|
|
370
|
+
raise.set(path, value - (base.get(path) ?? 0));
|
|
371
|
+
base.set(path, value);
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
session = clone(this._doc);
|
|
375
|
+
raiseOwn(session, this._deviceId, raise);
|
|
376
|
+
}
|
|
377
|
+
const merged = merge(session, incoming, this._options());
|
|
257
378
|
merged.level = levelOf(merged);
|
|
258
379
|
this._doc = merged;
|
|
380
|
+
if (base) this._base = base;
|
|
259
381
|
|
|
260
382
|
const after = this.snapshot();
|
|
261
383
|
await this.save();
|
|
@@ -292,8 +414,9 @@ export class RewardSystem extends EventEmitter {
|
|
|
292
414
|
* Pass `{ overwrite: false }` to keep the stored player when the last
|
|
293
415
|
* init() could not read it (an unsupported newer version, or a read that
|
|
294
416
|
* keeps failing). The player in memory is replaced by a new empty one,
|
|
295
|
-
* nothing is written, `loadFailed` stays true
|
|
296
|
-
*
|
|
417
|
+
* nothing is written, `loadFailed` stays true and `player_reset` is still
|
|
418
|
+
* emitted. A later write may retry the read and, when it returns a
|
|
419
|
+
* player, merges the new session into it (see `loadRetryMs`). When the last init() did
|
|
297
420
|
* read the saved player, `overwrite: false` changes nothing: it saves
|
|
298
421
|
* like a plain reset(). A corrupt save that init() backed up to `player_corrupt` counts as loaded, so `overwrite: false` saves like a plain reset().
|
|
299
422
|
* If the backup failed, it counts as a failed load and nothing is written.
|
|
@@ -316,6 +439,7 @@ export class RewardSystem extends EventEmitter {
|
|
|
316
439
|
this._requirePlayer();
|
|
317
440
|
if (overwrite === false && this._readFailed) {
|
|
318
441
|
this._doc = emptyDoc(this.clock.now());
|
|
442
|
+
this._forgetImports();
|
|
319
443
|
this._publish('player_reset', {});
|
|
320
444
|
return this.snapshot();
|
|
321
445
|
}
|
|
@@ -323,6 +447,7 @@ export class RewardSystem extends EventEmitter {
|
|
|
323
447
|
this._doc = emptyDoc(this.clock.now());
|
|
324
448
|
this._loadFailed = false;
|
|
325
449
|
this._readFailed = false;
|
|
450
|
+
this._forgetImports();
|
|
326
451
|
await this.save();
|
|
327
452
|
});
|
|
328
453
|
this._publish('player_reset', {});
|
|
@@ -378,7 +503,11 @@ export class RewardSystem extends EventEmitter {
|
|
|
378
503
|
* @private
|
|
379
504
|
*/
|
|
380
505
|
async _write() {
|
|
381
|
-
if (this._loadFailed)
|
|
506
|
+
if (this._loadFailed) {
|
|
507
|
+
// The retry saves everything changed before it merged.
|
|
508
|
+
await this._recover();
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
382
511
|
this._doc.lastPlayedAt = this.clock.now();
|
|
383
512
|
if (!this._deviceSaved) {
|
|
384
513
|
this._deviceSaved = (await this.dataService.save(DEVICE_KEY, this._deviceId)) !== false;
|
|
@@ -448,13 +577,23 @@ export class RewardSystem extends EventEmitter {
|
|
|
448
577
|
|
|
449
578
|
async _announceXP(oldLevel, amount, reason) {
|
|
450
579
|
const doc = this._doc;
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
const leveledUp = newLevel > oldLevel;
|
|
580
|
+
let total = xpOf(doc);
|
|
581
|
+
let newLevel = Math.max(oldLevel, levelFor(total));
|
|
454
582
|
if (newLevel > doc.level) doc.level = newLevel;
|
|
455
583
|
|
|
584
|
+
const recoveries = this._recoveries;
|
|
456
585
|
await this.save();
|
|
457
586
|
|
|
587
|
+
// A save that recovered a failed read replaced the document with the
|
|
588
|
+
// merged one. Report that, and compare with the merged level before
|
|
589
|
+
// this gain, so a level the saved player already had is not announced.
|
|
590
|
+
if (this._recoveries !== recoveries) {
|
|
591
|
+
total = xpOf(this._doc);
|
|
592
|
+
newLevel = Math.max(newLevel, levelOf(this._doc));
|
|
593
|
+
oldLevel = Math.max(oldLevel, this._savedLevel, levelFor(total - amount));
|
|
594
|
+
}
|
|
595
|
+
const leveledUp = newLevel > oldLevel;
|
|
596
|
+
|
|
458
597
|
this._publish('xp_gained', { amount, reason, leveledUp, newLevel, total });
|
|
459
598
|
if (leveledUp) {
|
|
460
599
|
this._publish('level_up', { oldLevel, newLevel, totalXP: total });
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { validate, checkDevices, hasOwn, VERSION } from './store.js';
|
|
1
|
+
import { validate, checkDevices, hasOwn, extraKeys, cap, clone, VERSION } from './store.js';
|
|
2
2
|
import { isDay, trimDays } from './streaks.js';
|
|
3
3
|
|
|
4
4
|
// Join two maps that are `depth` levels deep, taking the larger number at the
|
|
@@ -30,6 +30,28 @@ function joinAchievements(a, b) {
|
|
|
30
30
|
return out;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
// Same text for the same value whatever the key order, so the choice below does
|
|
34
|
+
// not depend on which side a value came from.
|
|
35
|
+
const stable = (value) => {
|
|
36
|
+
if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
|
|
37
|
+
if (value !== null && typeof value === 'object') {
|
|
38
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`;
|
|
39
|
+
}
|
|
40
|
+
return JSON.stringify(value);
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// A field the core does not know has no rule to join by. One side only: kept.
|
|
44
|
+
// Both: the larger number, else the larger text, the same in any order.
|
|
45
|
+
const larger = (a, b) => (Number.isFinite(a) && Number.isFinite(b) && a !== b ? a > b : stable(a) >= stable(b)) ? a : b;
|
|
46
|
+
|
|
47
|
+
function joinExtras(x, y, doc) {
|
|
48
|
+
for (const key of new Set([...extraKeys(x), ...extraKeys(y)])) {
|
|
49
|
+
const a = hasOwn(x, key) ? x[key] : undefined;
|
|
50
|
+
const b = hasOwn(y, key) ? y[key] : undefined;
|
|
51
|
+
doc[key] = a === undefined ? b : b === undefined ? a : larger(a, b);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
33
55
|
const positive = (a, b) => (a > 0 && b > 0 ? Math.min(a, b) : Math.max(a, b));
|
|
34
56
|
|
|
35
57
|
/**
|
|
@@ -63,6 +85,99 @@ export function merge(a, b, options) {
|
|
|
63
85
|
sumsBy: join(x.sumsBy, y.sumsBy, 2),
|
|
64
86
|
achievements: joinAchievements(x.achievements, y.achievements)
|
|
65
87
|
};
|
|
88
|
+
joinExtras(x, y, doc);
|
|
66
89
|
checkDevices(doc);
|
|
67
90
|
return doc;
|
|
68
91
|
}
|
|
92
|
+
|
|
93
|
+
// Every counter map of a document by path, as a JSON array of keys.
|
|
94
|
+
function counterMaps(doc) {
|
|
95
|
+
const maps = new Map([[JSON.stringify(['xpBy']), doc.xpBy], [JSON.stringify(['xpSpentBy']), doc.xpSpentBy], [JSON.stringify(['gamesBy']), doc.gamesBy]]);
|
|
96
|
+
for (const activity of Object.keys(doc.playsBy)) maps.set(JSON.stringify(['playsBy', activity]), doc.playsBy[activity]);
|
|
97
|
+
for (const activity of Object.keys(doc.sumsBy)) {
|
|
98
|
+
for (const key of Object.keys(doc.sumsBy[activity])) {
|
|
99
|
+
maps.set(JSON.stringify(['sumsBy', activity, key]), doc.sumsBy[activity][key]);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return maps;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The device ids that hold a counter above zero. */
|
|
106
|
+
export function countedDevices(doc) {
|
|
107
|
+
const ids = new Set();
|
|
108
|
+
for (const map of counterMaps(doc).values()) {
|
|
109
|
+
for (const id in map) if (map[id] > 0) ids.add(id);
|
|
110
|
+
}
|
|
111
|
+
return ids;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** This device's counters in a document, by path. */
|
|
115
|
+
export function ownCounters(doc, device) {
|
|
116
|
+
const out = new Map();
|
|
117
|
+
for (const [path, map] of counterMaps(doc)) {
|
|
118
|
+
if (hasOwn(map, device)) out.set(path, map[device]);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Add `by` (a path to amount map) to this device's counters in `doc`, in place. */
|
|
124
|
+
export function raiseOwn(doc, device, by) {
|
|
125
|
+
for (const [path, amount] of by) {
|
|
126
|
+
let node = doc;
|
|
127
|
+
for (const key of JSON.parse(path)) {
|
|
128
|
+
if (!hasOwn(node, key)) node[key] = {};
|
|
129
|
+
node = node[key];
|
|
130
|
+
}
|
|
131
|
+
node[device] = cap((hasOwn(node, device) ? node[device] : 0) + amount);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Fold a session player into the saved one it could not read earlier. The
|
|
137
|
+
* session started empty, so its counters for this device are new progress and
|
|
138
|
+
* are added, not joined by max. Everything else joins like `merge`. The saved
|
|
139
|
+
* player keeps its name and its unknown fields. Pure.
|
|
140
|
+
*
|
|
141
|
+
* `base` holds what an import put into this device's session counters (path to
|
|
142
|
+
* amount, see `ownCounters`). That is not new progress, so it is joined by max
|
|
143
|
+
* with the saved counter, and only what the session added on top is added.
|
|
144
|
+
*
|
|
145
|
+
* @param {*} saved the player read from storage
|
|
146
|
+
* @param {*} session the player made since the failed read
|
|
147
|
+
* @param {string} device this device's id
|
|
148
|
+
* @param {{ today?: string, rewards?: Object }} [options] see validate
|
|
149
|
+
* @param {Map<string, number>} [base]
|
|
150
|
+
*/
|
|
151
|
+
export function mergeSession(saved, session, device, options, base = new Map()) {
|
|
152
|
+
const x = validate(saved, options);
|
|
153
|
+
const y = validate(session, options);
|
|
154
|
+
const doc = merge(x, y, options);
|
|
155
|
+
doc.name = x.name;
|
|
156
|
+
for (const key of extraKeys(x)) doc[key] = x[key];
|
|
157
|
+
|
|
158
|
+
const mine = counterMaps(doc);
|
|
159
|
+
const was = counterMaps(x);
|
|
160
|
+
for (const [path, map] of counterMaps(y)) {
|
|
161
|
+
if (!hasOwn(map, device)) continue;
|
|
162
|
+
const imported = Math.min(base.get(path) ?? 0, map[device]);
|
|
163
|
+
const stored = was.has(path) && hasOwn(was.get(path), device) ? was.get(path)[device] : 0;
|
|
164
|
+
mine.get(path)[device] = cap(Math.max(stored, imported) + (map[device] - imported));
|
|
165
|
+
}
|
|
166
|
+
return doc;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** A copy of a document with one device's entries moved under another id. */
|
|
170
|
+
export function rekey(doc, from, to) {
|
|
171
|
+
const out = clone(doc);
|
|
172
|
+
const move = (map) => {
|
|
173
|
+
if (!hasOwn(map, from)) return;
|
|
174
|
+
map[to] = hasOwn(map, to) ? Math.max(map[to], map[from]) : map[from];
|
|
175
|
+
delete map[from];
|
|
176
|
+
};
|
|
177
|
+
for (const map of [out.xpBy, out.xpSpentBy, out.gamesBy]) move(map);
|
|
178
|
+
for (const activity of Object.keys(out.playsBy)) move(out.playsBy[activity]);
|
|
179
|
+
for (const activity of Object.keys(out.sumsBy)) {
|
|
180
|
+
for (const key of Object.keys(out.sumsBy[activity])) move(out.sumsBy[activity][key]);
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
@@ -15,11 +15,33 @@ export const isSafeKey = (key) => typeof key === 'string' && key.length > 0 && !
|
|
|
15
15
|
export const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
16
16
|
export const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
// A number read from storage: a finite number, or a plain decimal string
|
|
19
|
+
// ("250", " -12 ", "1.5"). Hex, exponents, signs and the like are not read.
|
|
20
|
+
// Anything else is undefined and falls back to the default.
|
|
21
|
+
const DECIMAL = /^\s*-?\d+(\.\d+)?\s*$/;
|
|
22
|
+
export function toNumber(value) {
|
|
23
|
+
if (typeof value === 'string') value = DECIMAL.test(value) ? Number(value) : undefined;
|
|
24
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
21
27
|
export const cap = (value) => Math.min(value, Number.MAX_SAFE_INTEGER);
|
|
22
|
-
|
|
28
|
+
|
|
29
|
+
// Each reader returns the number, or undefined when the value does not fit.
|
|
30
|
+
const asNumber = toNumber;
|
|
31
|
+
const asAmount = (value) => {
|
|
32
|
+
const number = toNumber(value);
|
|
33
|
+
return number !== undefined && number >= 0 ? number : undefined;
|
|
34
|
+
};
|
|
35
|
+
const asCount = (value) => {
|
|
36
|
+
const number = toNumber(value);
|
|
37
|
+
return Number.isInteger(number) && number >= 0 ? number : undefined;
|
|
38
|
+
};
|
|
39
|
+
const numberOr = (value, fallback) => asNumber(value) ?? fallback;
|
|
40
|
+
const amountOr = (value, fallback) => asAmount(value) ?? fallback;
|
|
41
|
+
const count = (value, fallback, min = 0) => {
|
|
42
|
+
const number = toNumber(value);
|
|
43
|
+
return Number.isInteger(number) && number >= min ? cap(number) : fallback;
|
|
44
|
+
};
|
|
23
45
|
|
|
24
46
|
// Summed in key order, so the same document always gives the same float.
|
|
25
47
|
export const sum = (map, pick = (value) => value) => Object.keys(map).sort().reduce((total, key) => cap(total + pick(map[key])), 0);
|
|
@@ -41,20 +63,21 @@ export const emptyDoc = (now = 0) => ({
|
|
|
41
63
|
achievements: {}
|
|
42
64
|
});
|
|
43
65
|
|
|
44
|
-
function pickMap(source,
|
|
66
|
+
function pickMap(source, read) {
|
|
45
67
|
const map = {};
|
|
46
68
|
if (!isRecord(source)) return map;
|
|
47
69
|
for (const key of Object.keys(source)) {
|
|
48
|
-
|
|
70
|
+
const number = isSafeKey(key) ? read(source[key]) : undefined;
|
|
71
|
+
if (number !== undefined) map[key] = cap(number);
|
|
49
72
|
}
|
|
50
73
|
return map;
|
|
51
74
|
}
|
|
52
75
|
|
|
53
|
-
function pickNested(source,
|
|
76
|
+
function pickNested(source, read) {
|
|
54
77
|
const map = {};
|
|
55
78
|
if (!isRecord(source)) return map;
|
|
56
79
|
for (const key of Object.keys(source)) {
|
|
57
|
-
if (isSafeKey(key)) map[key] = pickMap(source[key],
|
|
80
|
+
if (isSafeKey(key)) map[key] = pickMap(source[key], read);
|
|
58
81
|
}
|
|
59
82
|
return map;
|
|
60
83
|
}
|
|
@@ -66,14 +89,46 @@ function pickAchievements(source, now) {
|
|
|
66
89
|
const entry = source[id];
|
|
67
90
|
if (!isSafeKey(id) || !isRecord(entry)) continue;
|
|
68
91
|
map[id] = {
|
|
69
|
-
unlockedAt:
|
|
92
|
+
unlockedAt: numberOr(entry.unlockedAt, now),
|
|
70
93
|
seen: entry.seen === true,
|
|
71
|
-
reward:
|
|
94
|
+
reward: cap(amountOr(entry.reward, 0))
|
|
72
95
|
};
|
|
73
96
|
}
|
|
74
97
|
return map;
|
|
75
98
|
}
|
|
76
99
|
|
|
100
|
+
// Fields of a document, and of a 2.x save, that the core reads. Any other
|
|
101
|
+
// top level field is kept as it was read, so a newer version's data survives.
|
|
102
|
+
export const DOC_KEYS = new Set(['v', 'name', 'createdAt', 'lastPlayedAt', 'level', 'longest', 'playDates', 'xpBy', 'xpSpentBy', 'gamesBy', 'playsBy', 'best', 'sumsBy', 'achievements']);
|
|
103
|
+
const READ_KEYS = new Set([...DOC_KEYS, 'xp', 'totalGamesPlayed', 'stats', 'streak']);
|
|
104
|
+
|
|
105
|
+
// A copy that holds only what JSON can: unsafe keys, functions, undefined and
|
|
106
|
+
// non-finite numbers are dropped. Deep input stops at 32 levels.
|
|
107
|
+
function plain(value, depth = 0) {
|
|
108
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
|
|
109
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
|
|
110
|
+
if (depth >= 32) return undefined;
|
|
111
|
+
if (Array.isArray(value)) return value.map((item) => plain(item, depth + 1) ?? null);
|
|
112
|
+
if (!isRecord(value)) return undefined;
|
|
113
|
+
const copy = {};
|
|
114
|
+
for (const key of Object.keys(value)) {
|
|
115
|
+
const item = isSafeKey(key) ? plain(value[key], depth + 1) : undefined;
|
|
116
|
+
if (item !== undefined) copy[key] = item;
|
|
117
|
+
}
|
|
118
|
+
return copy;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function keepExtras(input, doc) {
|
|
122
|
+
for (const key of Object.keys(input)) {
|
|
123
|
+
if (READ_KEYS.has(key) || !isSafeKey(key)) continue;
|
|
124
|
+
const value = plain(input[key]);
|
|
125
|
+
if (value !== undefined) doc[key] = value;
|
|
126
|
+
}
|
|
127
|
+
return doc;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export const extraKeys = (doc) => Object.keys(doc).filter((key) => !DOC_KEYS.has(key));
|
|
131
|
+
|
|
77
132
|
// Every activity has a play map, a best and a sum map, so merge never has to
|
|
78
133
|
// ask whether one exists.
|
|
79
134
|
function finish(doc) {
|
|
@@ -88,29 +143,29 @@ function finish(doc) {
|
|
|
88
143
|
}
|
|
89
144
|
|
|
90
145
|
function read3(input, now, today) {
|
|
91
|
-
return finish({
|
|
146
|
+
return keepExtras(input, finish({
|
|
92
147
|
v: VERSION,
|
|
93
148
|
name: typeof input.name === 'string' ? input.name : 'Player',
|
|
94
|
-
createdAt:
|
|
95
|
-
lastPlayedAt:
|
|
149
|
+
createdAt: numberOr(input.createdAt, now),
|
|
150
|
+
lastPlayedAt: numberOr(input.lastPlayedAt, now),
|
|
96
151
|
level: count(input.level, 1, 1),
|
|
97
152
|
longest: count(input.longest, 0),
|
|
98
153
|
playDates: trimDays(Array.isArray(input.playDates) ? input.playDates.filter(isDay) : [], today),
|
|
99
|
-
xpBy: pickMap(input.xpBy,
|
|
100
|
-
xpSpentBy: pickMap(input.xpSpentBy,
|
|
101
|
-
gamesBy: pickMap(input.gamesBy,
|
|
102
|
-
playsBy: pickNested(input.playsBy,
|
|
103
|
-
best: pickMap(input.best,
|
|
154
|
+
xpBy: pickMap(input.xpBy, asAmount),
|
|
155
|
+
xpSpentBy: pickMap(input.xpSpentBy, asAmount),
|
|
156
|
+
gamesBy: pickMap(input.gamesBy, asCount),
|
|
157
|
+
playsBy: pickNested(input.playsBy, asCount),
|
|
158
|
+
best: pickMap(input.best, asAmount),
|
|
104
159
|
sumsBy: nestedSums(input.sumsBy),
|
|
105
160
|
achievements: pickAchievements(input.achievements, now)
|
|
106
|
-
});
|
|
161
|
+
}));
|
|
107
162
|
}
|
|
108
163
|
|
|
109
164
|
function nestedSums(source) {
|
|
110
165
|
const map = {};
|
|
111
166
|
if (!isRecord(source)) return map;
|
|
112
167
|
for (const activity of Object.keys(source)) {
|
|
113
|
-
if (isSafeKey(activity)) map[activity] = pickNested(source[activity],
|
|
168
|
+
if (isSafeKey(activity)) map[activity] = pickNested(source[activity], asAmount);
|
|
114
169
|
}
|
|
115
170
|
return map;
|
|
116
171
|
}
|
|
@@ -120,19 +175,19 @@ function nestedSums(source) {
|
|
|
120
175
|
function read2(input, now, rewards, today) {
|
|
121
176
|
const doc = emptyDoc(now);
|
|
122
177
|
doc.name = typeof input.name === 'string' ? input.name : 'Player';
|
|
123
|
-
doc.createdAt =
|
|
124
|
-
doc.lastPlayedAt =
|
|
178
|
+
doc.createdAt = numberOr(input.createdAt, now);
|
|
179
|
+
doc.lastPlayedAt = numberOr(input.lastPlayedAt, now);
|
|
125
180
|
doc.achievements = pickAchievements(input.achievements, now);
|
|
126
181
|
|
|
127
182
|
let granted = 0;
|
|
128
183
|
for (const id of Object.keys(doc.achievements)) {
|
|
129
|
-
const reward = hasOwn(rewards, id)
|
|
184
|
+
const reward = hasOwn(rewards, id) ? cap(amountOr(rewards[id], 0)) : 0;
|
|
130
185
|
doc.achievements[id].reward = reward;
|
|
131
186
|
granted += reward;
|
|
132
187
|
}
|
|
133
188
|
|
|
134
189
|
// The old xp already holds the rewards of the unlocked achievements.
|
|
135
|
-
const xp =
|
|
190
|
+
const xp = cap(amountOr(input.xp, 0));
|
|
136
191
|
const own = Math.max(0, xp - granted);
|
|
137
192
|
if (own > 0) doc.xpBy[LEGACY] = own;
|
|
138
193
|
doc.level = Math.max(levelFor(xp), count(input.level, 1, 1));
|
|
@@ -145,12 +200,12 @@ function read2(input, now, rewards, today) {
|
|
|
145
200
|
if (!isSafeKey(activity) || !isRecord(entry)) continue;
|
|
146
201
|
const plays = count(entry.totalPlays, 0);
|
|
147
202
|
doc.playsBy[activity] = plays > 0 ? { [LEGACY]: plays } : {};
|
|
148
|
-
doc.best[activity] =
|
|
203
|
+
doc.best[activity] = cap(amountOr(entry.highScore, 0));
|
|
149
204
|
doc.sumsBy[activity] = {};
|
|
150
205
|
for (const key of Object.keys(entry)) {
|
|
151
|
-
if (isSafeKey(key)
|
|
152
|
-
|
|
153
|
-
}
|
|
206
|
+
if (!isSafeKey(key) || key === 'totalPlays' || key === 'highScore') continue;
|
|
207
|
+
const amount = asAmount(entry[key]);
|
|
208
|
+
if (amount !== undefined) doc.sumsBy[activity][key] = { [LEGACY]: cap(amount) };
|
|
154
209
|
}
|
|
155
210
|
}
|
|
156
211
|
}
|
|
@@ -159,13 +214,16 @@ function read2(input, now, rewards, today) {
|
|
|
159
214
|
const current = count(streak.current, 1, 1);
|
|
160
215
|
doc.longest = Math.max(current, count(streak.longest, 0));
|
|
161
216
|
if (isDay(streak.lastPlayDate)) {
|
|
162
|
-
|
|
217
|
+
// A date after today (a clock change) counts as today, so the streak stays.
|
|
218
|
+
const last = today && streak.lastPlayDate > today ? today : streak.lastPlayDate;
|
|
219
|
+
for (let back = 0; back < Math.min(current, 400); back++) doc.playDates.push(shiftDay(last, -back));
|
|
163
220
|
doc.playDates = trimDays(doc.playDates, today);
|
|
164
221
|
} else {
|
|
165
|
-
|
|
222
|
+
// No real date, so no current run. The counts stay as the best run.
|
|
223
|
+
doc.longest = Math.max(count(streak.current, 0), count(streak.longest, 0));
|
|
166
224
|
}
|
|
167
225
|
|
|
168
|
-
return finish(doc);
|
|
226
|
+
return keepExtras(input, finish(doc));
|
|
169
227
|
}
|
|
170
228
|
|
|
171
229
|
export function deviceIds(doc) {
|
|
@@ -203,7 +261,7 @@ export function validate(input, options = {}) {
|
|
|
203
261
|
if (input.v !== undefined && input.v !== VERSION) {
|
|
204
262
|
throw new DopamineError('unsupported_version', `[DopamineJS] save version ${String(input.v)} is not ${VERSION}`);
|
|
205
263
|
}
|
|
206
|
-
const now =
|
|
264
|
+
const now = Number.isFinite(options.now) ? options.now : 0;
|
|
207
265
|
const today = isDay(options.today) ? options.today : undefined;
|
|
208
266
|
const doc = input.v === VERSION
|
|
209
267
|
? read3(input, now, today)
|
package/src/dopamine/host.js
CHANGED
|
@@ -63,6 +63,7 @@ function namespacedStorage(storage, name) {
|
|
|
63
63
|
* @param {{ now(): number, localDate(ms?: number): string }} [options.clock]
|
|
64
64
|
* @param {'any'|'record'} [options.streakDays] - For the default progress object
|
|
65
65
|
* @param {boolean} [options.builtinAchievements] - For the default progress object, false defines no built-ins
|
|
66
|
+
* @param {number} [options.loadRetryMs] - For the default progress object, see RewardSystem
|
|
66
67
|
* @param {Object[]} [options.plugins]
|
|
67
68
|
* @param {{ debug?: Function, info?: Function, warn?: Function, error?: Function }} [options.log]
|
|
68
69
|
*/
|
|
@@ -90,7 +91,7 @@ export function createDopamine(options = {}) {
|
|
|
90
91
|
|
|
91
92
|
const factoryEnv = { ...env, parts, storage, clock };
|
|
92
93
|
|
|
93
|
-
const progress = resolvePart(opts.progress, factoryEnv, () => new RewardSystem(new DataService({ storage }), { clock, streakDays: opts.streakDays, builtinAchievements: opts.builtinAchievements }));
|
|
94
|
+
const progress = resolvePart(opts.progress, factoryEnv, () => new RewardSystem(new DataService({ storage }), { clock, streakDays: opts.streakDays, builtinAchievements: opts.builtinAchievements, loadRetryMs: opts.loadRetryMs }));
|
|
94
95
|
if (typeof progress?.on !== 'function' || typeof progress?.off !== 'function') {
|
|
95
96
|
throw new DopamineError('invalid_progress', 'progress needs on() and off()');
|
|
96
97
|
}
|
|
@@ -157,6 +158,7 @@ export function createDopamine(options = {}) {
|
|
|
157
158
|
})),
|
|
158
159
|
events.on('streak_updated', react(sync)),
|
|
159
160
|
events.on('player_reset', react(sync)),
|
|
161
|
+
events.on('load_recovered', react(sync)),
|
|
160
162
|
events.on('personal_best', react((e) => {
|
|
161
163
|
slots.ui?.popup({ kind: 'notice', title: `New High Score: ${e.score}!`, tier: 'legendary' });
|
|
162
164
|
slots.sound?.play('personal_best');
|
package/src/testing.js
CHANGED
|
@@ -20,7 +20,8 @@ const CORE_EVENTS = {
|
|
|
20
20
|
streak_updated: { current: 1, longest: 1 },
|
|
21
21
|
player_reset: {},
|
|
22
22
|
save_failed: { error: new Error('save failed') },
|
|
23
|
-
load_failed: { reason: 'corrupt' }
|
|
23
|
+
load_failed: { reason: 'corrupt' },
|
|
24
|
+
load_recovered: { key: 'player' }
|
|
24
25
|
};
|
|
25
26
|
const BURST_KINDS = ['confetti', 'sparkle', 'fire', 'stars', 'coins'];
|
|
26
27
|
const SOUND_KEYS = ['xp', 'level_up', 'achievement', 'personal_best', 'click', 'error'];
|