dopaminejs 3.3.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.
@@ -1,4 +1,4 @@
1
- //#region src/dopamine/core/EventEmitter.js
1
+ // src/dopamine/core/EventEmitter.js
2
2
  var e = class {
3
3
  constructor() {
4
4
  this.listeners = /* @__PURE__ */ new Map();
@@ -100,11 +100,24 @@ function _(e) {
100
100
  }
101
101
  return t;
102
102
  }
103
- var v = (e, t) => e.reduce((e, n) => n <= t && (!e || n > e) ? n : e, void 0), y = "legacy", b = /* @__PURE__ */ new Set([
103
+ var ee = (e, t) => e.reduce((e, n) => n <= t && (!e || n > e) ? n : e, void 0), v = "legacy", te = /* @__PURE__ */ new Set([
104
104
  "__proto__",
105
105
  "constructor",
106
106
  "prototype"
107
- ]), x = (e) => typeof e == "string" && e.length > 0 && !b.has(e), S = (e, t) => Object.prototype.hasOwnProperty.call(e, t), C = (e) => typeof e == "object" && !!e && !Array.isArray(e), w = (e) => Number.isInteger(e) && e >= 0, T = (e) => Number.isFinite(e) && e >= 0, E = (e) => Number.isFinite(e), D = (e) => Math.min(e, 2 ** 53 - 1), O = (e, t, n = 0) => Number.isInteger(e) && e >= n ? D(e) : t, k = (e, t = (e) => e) => Object.keys(e).sort().reduce((n, r) => D(n + t(e[r])), 0), A = (e = 0) => ({
107
+ ]), y = (e) => typeof e == "string" && e.length > 0 && !te.has(e), b = (e, t) => Object.prototype.hasOwnProperty.call(e, t), x = (e) => typeof e == "object" && !!e && !Array.isArray(e), ne = /^\s*-?\d+(\.\d+)?\s*$/;
108
+ function S(e) {
109
+ return typeof e == "string" && (e = ne.test(e) ? Number(e) : void 0), typeof e == "number" && Number.isFinite(e) ? e : void 0;
110
+ }
111
+ var C = (e) => Math.min(e, 2 ** 53 - 1), re = S, w = (e) => {
112
+ let t = S(e);
113
+ return t !== void 0 && t >= 0 ? t : void 0;
114
+ }, T = (e) => {
115
+ let t = S(e);
116
+ return Number.isInteger(t) && t >= 0 ? t : void 0;
117
+ }, E = (e, t) => re(e) ?? t, D = (e, t) => w(e) ?? t, O = (e, t, n = 0) => {
118
+ let r = S(e);
119
+ return Number.isInteger(r) && r >= n ? C(r) : t;
120
+ }, k = (e, t = (e) => e) => Object.keys(e).sort().reduce((n, r) => C(n + t(e[r])), 0), A = (e = 0) => ({
108
121
  v: 3,
109
122
  name: "Player",
110
123
  createdAt: e,
@@ -122,86 +135,138 @@ var v = (e, t) => e.reduce((e, n) => n <= t && (!e || n > e) ? n : e, void 0), y
122
135
  });
123
136
  function j(e, t) {
124
137
  let n = {};
125
- if (!C(e)) return n;
126
- for (let r of Object.keys(e)) x(r) && t(e[r]) && (n[r] = D(e[r]));
138
+ if (!x(e)) return n;
139
+ for (let r of Object.keys(e)) {
140
+ let i = y(r) ? t(e[r]) : void 0;
141
+ i !== void 0 && (n[r] = C(i));
142
+ }
127
143
  return n;
128
144
  }
129
145
  function M(e, t) {
130
146
  let n = {};
131
- if (!C(e)) return n;
132
- for (let r of Object.keys(e)) x(r) && (n[r] = j(e[r], t));
147
+ if (!x(e)) return n;
148
+ for (let r of Object.keys(e)) y(r) && (n[r] = j(e[r], t));
133
149
  return n;
134
150
  }
135
151
  function N(e, t) {
136
152
  let n = {};
137
- if (!C(e)) return n;
153
+ if (!x(e)) return n;
138
154
  for (let r of Object.keys(e)) {
139
155
  let i = e[r];
140
- x(r) && C(i) && (n[r] = {
141
- unlockedAt: E(i.unlockedAt) ? i.unlockedAt : t,
156
+ y(r) && x(i) && (n[r] = {
157
+ unlockedAt: E(i.unlockedAt, t),
142
158
  seen: i.seen === !0,
143
- reward: T(i.reward) ? D(i.reward) : 0
159
+ reward: C(D(i.reward, 0))
144
160
  });
145
161
  }
146
162
  return n;
147
163
  }
148
- function P(e) {
164
+ var P = /* @__PURE__ */ new Set([
165
+ "v",
166
+ "name",
167
+ "createdAt",
168
+ "lastPlayedAt",
169
+ "level",
170
+ "longest",
171
+ "playDates",
172
+ "xpBy",
173
+ "xpSpentBy",
174
+ "gamesBy",
175
+ "playsBy",
176
+ "best",
177
+ "sumsBy",
178
+ "achievements"
179
+ ]), ie = /* @__PURE__ */ new Set([
180
+ ...P,
181
+ "xp",
182
+ "totalGamesPlayed",
183
+ "stats",
184
+ "streak"
185
+ ]);
186
+ function F(e, t = 0) {
187
+ if (e === null || typeof e == "string" || typeof e == "boolean") return e;
188
+ if (typeof e == "number") return Number.isFinite(e) ? e : void 0;
189
+ if (t >= 32) return;
190
+ if (Array.isArray(e)) return e.map((e) => F(e, t + 1) ?? null);
191
+ if (!x(e)) return;
192
+ let n = {};
193
+ for (let r of Object.keys(e)) {
194
+ let i = y(r) ? F(e[r], t + 1) : void 0;
195
+ i !== void 0 && (n[r] = i);
196
+ }
197
+ return n;
198
+ }
199
+ function I(e, t) {
200
+ for (let n of Object.keys(e)) {
201
+ if (ie.has(n) || !y(n)) continue;
202
+ let r = F(e[n]);
203
+ r !== void 0 && (t[n] = r);
204
+ }
205
+ return t;
206
+ }
207
+ var L = (e) => Object.keys(e).filter((e) => !P.has(e));
208
+ function ae(e) {
149
209
  let t = e.sumsBy, n = /* @__PURE__ */ new Set([
150
210
  ...Object.keys(e.playsBy),
151
211
  ...Object.keys(e.best),
152
212
  ...Object.keys(t)
153
213
  ]);
154
- for (let r of n) S(e.playsBy, r) || (e.playsBy[r] = {}), S(e.best, r) || (e.best[r] = 0), S(t, r) || (t[r] = {});
214
+ for (let r of n) b(e.playsBy, r) || (e.playsBy[r] = {}), b(e.best, r) || (e.best[r] = 0), b(t, r) || (t[r] = {});
155
215
  return e;
156
216
  }
157
- function F(e, t, n) {
158
- return P({
217
+ function oe(e, t, n) {
218
+ return I(e, ae({
159
219
  v: 3,
160
220
  name: typeof e.name == "string" ? e.name : "Player",
161
- createdAt: E(e.createdAt) ? e.createdAt : t,
162
- lastPlayedAt: E(e.lastPlayedAt) ? e.lastPlayedAt : t,
221
+ createdAt: E(e.createdAt, t),
222
+ lastPlayedAt: E(e.lastPlayedAt, t),
163
223
  level: O(e.level, 1, 1),
164
224
  longest: O(e.longest, 0),
165
225
  playDates: h(Array.isArray(e.playDates) ? e.playDates.filter(p) : [], n),
166
- xpBy: j(e.xpBy, T),
167
- xpSpentBy: j(e.xpSpentBy, T),
168
- gamesBy: j(e.gamesBy, w),
169
- playsBy: M(e.playsBy, w),
170
- best: j(e.best, T),
171
- sumsBy: I(e.sumsBy),
226
+ xpBy: j(e.xpBy, w),
227
+ xpSpentBy: j(e.xpSpentBy, w),
228
+ gamesBy: j(e.gamesBy, T),
229
+ playsBy: M(e.playsBy, T),
230
+ best: j(e.best, w),
231
+ sumsBy: se(e.sumsBy),
172
232
  achievements: N(e.achievements, t)
173
- });
233
+ }));
174
234
  }
175
- function I(e) {
235
+ function se(e) {
176
236
  let t = {};
177
- if (!C(e)) return t;
178
- for (let n of Object.keys(e)) x(n) && (t[n] = M(e[n], E));
237
+ if (!x(e)) return t;
238
+ for (let n of Object.keys(e)) y(n) && (t[n] = M(e[n], w));
179
239
  return t;
180
240
  }
181
- function L(e, t, n, r) {
241
+ function ce(e, t, n, r) {
182
242
  let a = A(t);
183
- a.name = typeof e.name == "string" ? e.name : "Player", a.createdAt = E(e.createdAt) ? e.createdAt : t, a.lastPlayedAt = E(e.lastPlayedAt) ? e.lastPlayedAt : t, a.achievements = N(e.achievements, t);
243
+ a.name = typeof e.name == "string" ? e.name : "Player", a.createdAt = E(e.createdAt, t), a.lastPlayedAt = E(e.lastPlayedAt, t), a.achievements = N(e.achievements, t);
184
244
  let o = 0;
185
245
  for (let e of Object.keys(a.achievements)) {
186
- let t = S(n, e) && T(n[e]) ? D(n[e]) : 0;
246
+ let t = b(n, e) ? C(D(n[e], 0)) : 0;
187
247
  a.achievements[e].reward = t, o += t;
188
248
  }
189
- let s = T(e.xp) ? D(e.xp) : 0, c = Math.max(0, s - o);
190
- c > 0 && (a.xpBy[y] = c), a.level = Math.max(i(s), O(e.level, 1, 1));
249
+ let s = C(D(e.xp, 0)), c = Math.max(0, s - o);
250
+ c > 0 && (a.xpBy[v] = c), a.level = Math.max(i(s), O(e.level, 1, 1));
191
251
  let l = O(e.totalGamesPlayed, 0);
192
- if (l > 0 && (a.gamesBy[y] = l), C(e.stats)) for (let t of Object.keys(e.stats)) {
252
+ if (l > 0 && (a.gamesBy[v] = l), x(e.stats)) for (let t of Object.keys(e.stats)) {
193
253
  let n = e.stats[t];
194
- if (!x(t) || !C(n)) continue;
254
+ if (!y(t) || !x(n)) continue;
195
255
  let r = O(n.totalPlays, 0);
196
- a.playsBy[t] = r > 0 ? { [y]: r } : {}, a.best[t] = T(n.highScore) ? D(n.highScore) : 0, a.sumsBy[t] = {};
197
- for (let e of Object.keys(n)) x(e) && e !== "totalPlays" && e !== "highScore" && E(n[e]) && (a.sumsBy[t][e] = { [y]: D(n[e]) });
256
+ a.playsBy[t] = r > 0 ? { [v]: r } : {}, a.best[t] = C(D(n.highScore, 0)), a.sumsBy[t] = {};
257
+ for (let e of Object.keys(n)) {
258
+ if (!y(e) || e === "totalPlays" || e === "highScore") continue;
259
+ let r = w(n[e]);
260
+ r !== void 0 && (a.sumsBy[t][e] = { [v]: C(r) });
261
+ }
198
262
  }
199
- let u = C(e.streak) ? e.streak : {}, d = O(u.current, 1, 1);
263
+ let u = x(e.streak) ? e.streak : {}, d = O(u.current, 1, 1);
200
264
  if (a.longest = Math.max(d, O(u.longest, 0)), p(u.lastPlayDate)) {
201
- for (let e = 0; e < Math.min(d, 400); e++) a.playDates.push(m(u.lastPlayDate, -e));
265
+ let e = r && u.lastPlayDate > r ? r : u.lastPlayDate;
266
+ for (let t = 0; t < Math.min(d, 400); t++) a.playDates.push(m(e, -t));
202
267
  a.playDates = h(a.playDates, r);
203
- } else a.longest = O(u.longest, 0);
204
- return P(a);
268
+ } else a.longest = Math.max(O(u.current, 0), O(u.longest, 0));
269
+ return I(e, ae(a));
205
270
  }
206
271
  function R(e) {
207
272
  let t = /* @__PURE__ */ new Set([
@@ -217,13 +282,13 @@ function z(e) {
217
282
  if (R(e).size > 20) throw new t("too_many_devices", "[DopamineJS] a save holds at most 20 devices");
218
283
  }
219
284
  function B(e, n = {}) {
220
- if (!C(e)) throw new t("invalid_document", "[DopamineJS] a save must be an object");
285
+ if (!x(e)) throw new t("invalid_document", "[DopamineJS] a save must be an object");
221
286
  if (e.v !== void 0 && e.v !== 3) throw new t("unsupported_version", `[DopamineJS] save version ${String(e.v)} is not 3`);
222
- let r = E(n.now) ? n.now : 0, i = p(n.today) ? n.today : void 0, a = e.v === 3 ? F(e, r, i) : L(e, r, C(n.rewards) ? n.rewards : s, i);
287
+ let r = Number.isFinite(n.now) ? n.now : 0, i = p(n.today) ? n.today : void 0, a = e.v === 3 ? oe(e, r, i) : ce(e, r, x(n.rewards) ? n.rewards : s, i);
223
288
  return z(a), a;
224
289
  }
225
- var V = (e) => D(Math.max(0, k(e.xpBy) + k(e.achievements, (e) => e.reward) - k(e.xpSpentBy))), H = (e) => Math.max(e.level, i(V(e)));
226
- function U(e, t) {
290
+ var V = (e) => C(Math.max(0, k(e.xpBy) + k(e.achievements, (e) => e.reward) - k(e.xpSpentBy))), H = (e) => Math.max(e.level, i(V(e)));
291
+ function le(e, t) {
227
292
  let n = {};
228
293
  for (let t of Object.keys(e.playsBy)) {
229
294
  let r = {
@@ -238,7 +303,7 @@ function U(e, t) {
238
303
  let i = {
239
304
  current: g(e.playDates, t),
240
305
  longest: Math.max(e.longest, _(e.playDates))
241
- }, a = v(e.playDates, t);
306
+ }, a = ee(e.playDates, t);
242
307
  return a && (i.lastPlayDate = a), {
243
308
  name: e.name,
244
309
  xp: V(e),
@@ -251,29 +316,28 @@ function U(e, t) {
251
316
  stats: n
252
317
  };
253
318
  }
254
- var W = (e) => JSON.parse(JSON.stringify(e));
255
- function G(e) {
319
+ var U = (e) => JSON.parse(JSON.stringify(e));
320
+ function W(e) {
256
321
  if (typeof e == "object" && e && !Object.isFrozen(e)) {
257
322
  Object.freeze(e);
258
- for (let t of Object.keys(e)) G(e[t]);
323
+ for (let t of Object.keys(e)) W(e[t]);
259
324
  }
260
325
  return e;
261
326
  }
262
- //#endregion
263
- //#region src/dopamine/core/middleware.js
264
- var K = [
327
+ // src/dopamine/core/middleware.js
328
+ var G = [
265
329
  "beforeXP",
266
330
  "afterXP",
267
331
  "beforeRecord",
268
332
  "afterRecord",
269
333
  "beforeUnlock",
270
334
  "afterUnlock"
271
- ], q = class {
335
+ ], ue = class {
272
336
  constructor() {
273
337
  this._list = [];
274
338
  }
275
339
  use(e) {
276
- if (!C(e) || !K.some((t) => typeof e[t] == "function")) throw TypeError(`[DopamineJS] use expects an object with one of: ${K.join(", ")}`);
340
+ if (!x(e) || !G.some((t) => typeof e[t] == "function")) throw TypeError(`[DopamineJS] use expects an object with one of: ${G.join(", ")}`);
277
341
  return this._list.push(e), () => {
278
342
  let t = this._list.indexOf(e);
279
343
  t >= 0 && this._list.splice(t, 1);
@@ -290,7 +354,7 @@ var K = [
290
354
  continue;
291
355
  }
292
356
  if (i === !1) return !1;
293
- if (!C(i)) continue;
357
+ if (!x(i)) continue;
294
358
  let a = { ...t };
295
359
  for (let e of Object.keys(t)) Object.prototype.hasOwnProperty.call(i, e) && (a[e] = i[e]);
296
360
  n(a) && (t = a);
@@ -305,20 +369,19 @@ var K = [
305
369
  }
306
370
  }
307
371
  };
308
- //#endregion
309
- //#region src/dopamine/core/merge.js
310
- function J(e, t, n) {
372
+ // src/dopamine/core/merge.js
373
+ function K(e, t, n) {
311
374
  let r = {};
312
375
  for (let i of /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)])) {
313
- let a = S(e, i) ? e[i] : void 0, o = S(t, i) ? t[i] : void 0;
314
- r[i] = n > 0 ? J(a || {}, o || {}, n - 1) : a === void 0 ? o : o === void 0 ? a : Math.max(a, o);
376
+ let a = b(e, i) ? e[i] : void 0, o = b(t, i) ? t[i] : void 0;
377
+ r[i] = n > 0 ? K(a || {}, o || {}, n - 1) : a === void 0 ? o : o === void 0 ? a : Math.max(a, o);
315
378
  }
316
379
  return r;
317
380
  }
318
- function ee(e, t) {
381
+ function de(e, t) {
319
382
  let n = {};
320
383
  for (let r of /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)])) {
321
- let i = S(e, r) ? e[r] : void 0, a = S(t, r) ? t[r] : void 0;
384
+ let i = b(e, r) ? e[r] : void 0, a = b(t, r) ? t[r] : void 0;
322
385
  if (!i || !a) {
323
386
  n[r] = { ...i || a };
324
387
  continue;
@@ -332,39 +395,101 @@ function ee(e, t) {
332
395
  }
333
396
  return n;
334
397
  }
335
- var te = (e, t) => e > 0 && t > 0 ? Math.min(e, t) : Math.max(e, t);
336
- function Y(e, t, n) {
398
+ var q = (e) => Array.isArray(e) ? `[${e.map(q).join(",")}]` : typeof e == "object" && e ? `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${q(e[t])}`).join(",")}}` : JSON.stringify(e), fe = (e, t) => (Number.isFinite(e) && Number.isFinite(t) && e !== t ? e > t : q(e) >= q(t)) ? e : t;
399
+ function pe(e, t, n) {
400
+ for (let r of /* @__PURE__ */ new Set([...L(e), ...L(t)])) {
401
+ let i = b(e, r) ? e[r] : void 0, a = b(t, r) ? t[r] : void 0;
402
+ n[r] = i === void 0 ? a : a === void 0 ? i : fe(i, a);
403
+ }
404
+ }
405
+ var me = (e, t) => e > 0 && t > 0 ? Math.min(e, t) : Math.max(e, t);
406
+ function J(e, t, n) {
337
407
  let r = B(e, n), i = B(t, n), a = {
338
408
  v: 3,
339
409
  name: (r.lastPlayedAt === i.lastPlayedAt ? r.name >= i.name ? r : i : r.lastPlayedAt > i.lastPlayedAt ? r : i).name,
340
- createdAt: te(r.createdAt, i.createdAt),
410
+ createdAt: me(r.createdAt, i.createdAt),
341
411
  lastPlayedAt: Math.max(r.lastPlayedAt, i.lastPlayedAt),
342
412
  level: Math.max(r.level, i.level),
343
413
  longest: Math.max(r.longest, i.longest),
344
414
  playDates: h([...r.playDates, ...i.playDates], p(n?.today) ? n.today : void 0),
345
- xpBy: J(r.xpBy, i.xpBy, 0),
346
- xpSpentBy: J(r.xpSpentBy, i.xpSpentBy, 0),
347
- gamesBy: J(r.gamesBy, i.gamesBy, 0),
348
- playsBy: J(r.playsBy, i.playsBy, 1),
349
- best: J(r.best, i.best, 0),
350
- sumsBy: J(r.sumsBy, i.sumsBy, 2),
351
- achievements: ee(r.achievements, i.achievements)
415
+ xpBy: K(r.xpBy, i.xpBy, 0),
416
+ xpSpentBy: K(r.xpSpentBy, i.xpSpentBy, 0),
417
+ gamesBy: K(r.gamesBy, i.gamesBy, 0),
418
+ playsBy: K(r.playsBy, i.playsBy, 1),
419
+ best: K(r.best, i.best, 0),
420
+ sumsBy: K(r.sumsBy, i.sumsBy, 2),
421
+ achievements: de(r.achievements, i.achievements)
352
422
  };
353
- return z(a), a;
423
+ return pe(r, i, a), z(a), a;
424
+ }
425
+ function Y(e) {
426
+ let t = /* @__PURE__ */ new Map([
427
+ [JSON.stringify(["xpBy"]), e.xpBy],
428
+ [JSON.stringify(["xpSpentBy"]), e.xpSpentBy],
429
+ [JSON.stringify(["gamesBy"]), e.gamesBy]
430
+ ]);
431
+ for (let n of Object.keys(e.playsBy)) t.set(JSON.stringify(["playsBy", n]), e.playsBy[n]);
432
+ for (let n of Object.keys(e.sumsBy)) for (let r of Object.keys(e.sumsBy[n])) t.set(JSON.stringify([
433
+ "sumsBy",
434
+ n,
435
+ r
436
+ ]), e.sumsBy[n][r]);
437
+ return t;
438
+ }
439
+ function he(e) {
440
+ let t = /* @__PURE__ */ new Set();
441
+ for (let n of Y(e).values()) for (let e in n) n[e] > 0 && t.add(e);
442
+ return t;
354
443
  }
355
- //#endregion
356
- //#region src/dopamine/core/RewardSystem.js
357
- var X = "device", Z = () => {
444
+ function X(e, t) {
445
+ let n = /* @__PURE__ */ new Map();
446
+ for (let [r, i] of Y(e)) b(i, t) && n.set(r, i[t]);
447
+ return n;
448
+ }
449
+ function ge(e, t, n) {
450
+ for (let [r, i] of n) {
451
+ let n = e;
452
+ for (let e of JSON.parse(r)) b(n, e) || (n[e] = {}), n = n[e];
453
+ n[t] = C((b(n, t) ? n[t] : 0) + i);
454
+ }
455
+ }
456
+ function _e(e, t, n, r, i = /* @__PURE__ */ new Map()) {
457
+ let a = B(e, r), o = B(t, r), s = J(a, o, r);
458
+ s.name = a.name;
459
+ for (let e of L(a)) s[e] = a[e];
460
+ let c = Y(s), l = Y(a);
461
+ for (let [e, t] of Y(o)) {
462
+ if (!b(t, n)) continue;
463
+ let r = Math.min(i.get(e) ?? 0, t[n]), a = l.has(e) && b(l.get(e), n) ? l.get(e)[n] : 0;
464
+ c.get(e)[n] = C(Math.max(a, r) + (t[n] - r));
465
+ }
466
+ return s;
467
+ }
468
+ function ve(e, t, n) {
469
+ let r = U(e), i = (e) => {
470
+ b(e, t) && (e[n] = b(e, n) ? Math.max(e[n], e[t]) : e[t], delete e[t]);
471
+ };
472
+ for (let e of [
473
+ r.xpBy,
474
+ r.xpSpentBy,
475
+ r.gamesBy
476
+ ]) i(e);
477
+ for (let e of Object.keys(r.playsBy)) i(r.playsBy[e]);
478
+ for (let e of Object.keys(r.sumsBy)) for (let t of Object.keys(r.sumsBy[e])) i(r.sumsBy[e][t]);
479
+ return r;
480
+ }
481
+ // src/dopamine/core/RewardSystem.js
482
+ var Z = "device", ye = () => {
358
483
  let e = /* @__PURE__ */ new Uint8Array(8), t = globalThis.crypto;
359
484
  if (typeof t?.getRandomValues == "function") t.getRandomValues(e);
360
485
  else for (let t = 0; t < e.length; t++) e[t] = Math.floor(Math.random() * 256);
361
486
  return Array.from(e, (e) => e.toString(16).padStart(2, "0")).join("");
362
- }, ne = (e) => x(e) && e !== "legacy", re = class extends e {
487
+ }, be = (e) => y(e) && e !== "legacy", xe = class extends e {
363
488
  constructor(e, t = {}) {
364
489
  super(), this.dataService = e, this.clock = t.clock && typeof t.clock.now == "function" && typeof t.clock.localDate == "function" ? t.clock : r, this.achievements = {
365
490
  ...t.builtinAchievements === !1 ? {} : o(),
366
491
  ...t.achievements || {}
367
- }, this.streakDays = t.streakDays === "record" ? "record" : "any", this._doc = null, this._deviceId = null, this._deviceSaved = !1, this._middleware = new q(), this._batchDepth = 0, this._pendingSave = !1, this._loadFailed = !1, this._readFailed = !1;
492
+ }, this.streakDays = t.streakDays === "record" ? "record" : "any", this._doc = null, this._deviceId = null, this._deviceSaved = !1, this._middleware = new ue(), this._unlocking = /* @__PURE__ */ new Set(), this._batchDepth = 0, this._pendingSave = !1, this._loadFailed = !1, this._readFailed = !1, this.loadRetryMs = Number.isFinite(t.loadRetryMs) && t.loadRetryMs >= 0 ? t.loadRetryMs : 3e4, this._lastRead = 0, this._reading = !1, this._recovering = null, this._epoch = 0, this._forgetImports(), this._recoveries = 0;
368
493
  }
369
494
  get loadFailed() {
370
495
  return this._readFailed;
@@ -392,32 +517,69 @@ var X = "device", Z = () => {
392
517
  };
393
518
  }
394
519
  async init() {
395
- let e = await this._readSaved();
396
- return this._loadFailed && this._doc || (this._doc = this._load(e)), await this._readDevice(), await this.save(), this.snapshot();
520
+ let e = this._doc && !this._loadFailed && X(this._doc, this._deviceId), t = await this._readSaved();
521
+ return this._loadFailed && this._doc ? e && e.forEach((e, t) => this._base.set(t, Math.max(this._base.get(t) ?? 0, e))) : (this._doc = this._load(t), this._forgetImports()), await this._readDevice(), await this.save(), this.snapshot();
397
522
  }
398
523
  async _readSaved() {
399
- this._loadFailed = !0;
524
+ this._loadFailed = !0, this._reading = !0, this._epoch++, this._recovering = null, this._lastRead = this.clock.now();
400
525
  try {
401
526
  let e = await this.dataService.load("player", null, { strict: !0 });
402
- return this._loadFailed = !1, this._readFailed = !1, e;
527
+ return e !== null && !x(e) ? await this._keepCorrupt(e) : (this._loadFailed = !1, this._readFailed = !1, e);
403
528
  } catch (e) {
404
- if (e?.code === "DOPAMINE_CORRUPT") {
405
- let t = await this.dataService.save("player_corrupt", e.raw);
406
- return t && (this._loadFailed = !1), this._readFailed = !t, this._publish("load_failed", {
407
- key: "player",
408
- reason: "corrupt",
409
- backedUp: t
410
- }), null;
411
- }
412
- return this._readFailed = !0, this._publish("load_failed", {
529
+ return e?.code === "DOPAMINE_CORRUPT" ? this._keepCorrupt(e.raw) : (this._readFailed = !0, this._publish("load_failed", {
413
530
  key: "player",
414
531
  reason: "read",
415
532
  error: e
416
- }), null;
533
+ }), null);
534
+ } finally {
535
+ this._reading = !1;
536
+ }
537
+ }
538
+ _recover() {
539
+ if (this._recovering || !this._readFailed || this._reading) return Promise.resolve(!1);
540
+ let e = this.clock.now() - this._lastRead;
541
+ if (e >= 0 && e < this.loadRetryMs) return Promise.resolve(!1);
542
+ this._lastRead = this.clock.now();
543
+ let t = this._retryRead(this._epoch).finally(() => {
544
+ this._recovering === t && (this._recovering = null);
545
+ });
546
+ return this._recovering = t, t;
547
+ }
548
+ async _retryRead(e) {
549
+ let t, n = null;
550
+ try {
551
+ if (t = await this.dataService.load("player", null, { strict: !0 }), t !== null && !x(t)) return !1;
552
+ if (!this._deviceSaved) {
553
+ let e = await this.dataService.load(Z, null, { strict: !0 });
554
+ be(e) && e !== this._deviceId && (n = e);
555
+ }
556
+ } catch {
557
+ return !1;
558
+ }
559
+ if (e !== this._epoch || !this._loadFailed || he(this._doc).has(n)) return !1;
560
+ let r;
561
+ try {
562
+ let e = this._options(), i = n ?? this._deviceId, a = n ? ve(this._doc, this._deviceId, n) : this._doc;
563
+ r = t === null ? U(a) : _e(t, a, i, e, this._base), z(r), r.level = H(r);
564
+ } catch {
565
+ return !1;
417
566
  }
567
+ return n && (this._deviceId = n, this._deviceSaved = !0), this._doc = r, this._recoveries++, this._savedLevel = Number(t?.level) || 0, this._loadFailed = !1, this._readFailed = !1, this._forgetImports(), await this._write(), this._publish("load_recovered", { key: "player" }), !0;
568
+ }
569
+ _forgetImports() {
570
+ this._base = /* @__PURE__ */ new Map();
571
+ }
572
+ async _keepCorrupt(e) {
573
+ this._loadFailed = !0;
574
+ let t = await this.dataService.save("player_corrupt", e);
575
+ return t && (this._loadFailed = !1), this._readFailed = !t, this._publish("load_failed", {
576
+ key: "player",
577
+ reason: "corrupt",
578
+ backedUp: t
579
+ }), null;
418
580
  }
419
581
  _load(e) {
420
- if (!C(e)) return A(this.clock.now());
582
+ if (!x(e)) return A(this.clock.now());
421
583
  try {
422
584
  return B(e, this._options());
423
585
  } catch (e) {
@@ -433,12 +595,12 @@ var X = "device", Z = () => {
433
595
  if (this._deviceId) return;
434
596
  let e = null;
435
597
  try {
436
- e = await this.dataService.load(X, null, { strict: !0 });
598
+ e = await this.dataService.load(Z, null, { strict: !0 });
437
599
  } catch {
438
- this._deviceId = Z();
600
+ this._deviceId = ye();
439
601
  return;
440
602
  }
441
- ne(e) ? (this._deviceId = e, this._deviceSaved = !0) : this._deviceId = Z();
603
+ be(e) ? (this._deviceId = e, this._deviceSaved = !0) : this._deviceId = ye();
442
604
  }
443
605
  _hasSlot() {
444
606
  let e = R(this._doc);
@@ -451,64 +613,66 @@ var X = "device", Z = () => {
451
613
  if (!this._doc) throw Error("[DopamineJS] RewardSystem.init() must be awaited before use");
452
614
  }
453
615
  snapshot() {
454
- return this._requirePlayer(), G(U(this._doc, this.clock.localDate()));
616
+ return this._requirePlayer(), W(le(this._doc, this.clock.localDate()));
455
617
  }
456
618
  export() {
457
- return this._requirePlayer(), W(this._doc);
619
+ return this._requirePlayer(), U(this._doc);
458
620
  }
459
621
  async import(e, { silent: t = !1 } = {}) {
460
622
  this._requirePlayer();
461
- let n = this.snapshot(), r = B(e, this._options()), i = Y(this._doc, r, this._options());
462
- i.level = H(i), this._doc = i;
463
- let a = this.snapshot();
464
- if (await this.save(), t) return a;
465
- let o = a.xp - n.xp, s = a.level > n.level;
466
- o > 0 && this._publish("xp_gained", {
467
- amount: o,
623
+ let n = this.snapshot(), r = B(e, this._options()), i = this._doc, a = null;
624
+ if (this._readFailed) {
625
+ a = new Map(this._base);
626
+ let e = /* @__PURE__ */ new Map(), t = X(this._doc, this._deviceId);
627
+ X(r, this._deviceId).forEach((n, r) => {
628
+ n > (t.get(r) ?? 0) && (e.set(r, n - (a.get(r) ?? 0)), a.set(r, n));
629
+ }), i = U(this._doc), ge(i, this._deviceId, e);
630
+ }
631
+ let o = J(i, r, this._options());
632
+ o.level = H(o), this._doc = o, a && (this._base = a);
633
+ let s = this.snapshot();
634
+ if (await this.save(), t) return s;
635
+ let c = s.xp - n.xp, l = s.level > n.level;
636
+ c > 0 && this._publish("xp_gained", {
637
+ amount: c,
468
638
  reason: "import",
469
- leveledUp: s,
470
- newLevel: a.level,
471
- total: a.xp
472
- }), s && this._publish("level_up", {
639
+ leveledUp: l,
640
+ newLevel: s.level,
641
+ total: s.xp
642
+ }), l && this._publish("level_up", {
473
643
  oldLevel: n.level,
474
- newLevel: a.level,
475
- totalXP: a.xp
644
+ newLevel: s.level,
645
+ totalXP: s.xp
476
646
  });
477
- for (let e of Object.keys(a.achievements)) !S(n.achievements, e) && S(this.achievements, e) && this._publish("achievement_unlocked", {
647
+ for (let e of Object.keys(s.achievements)) !b(n.achievements, e) && b(this.achievements, e) && this._publish("achievement_unlocked", {
478
648
  ...this.achievements[e],
479
649
  id: e
480
650
  });
481
- return a;
651
+ return s;
482
652
  }
483
653
  async reset(e) {
484
654
  let t = e?.overwrite;
485
655
  if (e !== void 0 && (typeof e != "object" || !e || Array.isArray(e)) || t !== void 0 && typeof t != "boolean") throw TypeError("[DopamineJS] reset expects { overwrite?: boolean }");
486
- return this._requirePlayer(), t === !1 && this._readFailed ? (this._doc = A(this.clock.now()), this._publish("player_reset", {}), this.snapshot()) : (await this._batch(async () => {
487
- this._doc = A(this.clock.now()), this._loadFailed = !1, this._readFailed = !1, await this.save();
656
+ return this._requirePlayer(), t === !1 && this._readFailed ? (this._doc = A(this.clock.now()), this._forgetImports(), this._publish("player_reset", {}), this.snapshot()) : (await this._batch(async () => {
657
+ this._doc = A(this.clock.now()), this._loadFailed = !1, this._readFailed = !1, this._forgetImports(), await this.save();
488
658
  }), this._publish("player_reset", {}), this.snapshot());
489
659
  }
490
660
  use(e) {
491
661
  return this._middleware.use(e);
492
662
  }
493
663
  defineAchievement(e, t) {
494
- if (!x(e)) throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);
495
- if (!C(t) || typeof t.check != "function") throw TypeError("[DopamineJS] defineAchievement expects a definition with a check function");
496
- let n = S(this.achievements, e) ? this.achievements[e] : void 0;
664
+ if (!y(e)) throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);
665
+ if (!x(t) || typeof t.check != "function") throw TypeError("[DopamineJS] defineAchievement expects a definition with a check function");
666
+ let n = b(this.achievements, e) ? this.achievements[e] : void 0;
497
667
  return this.achievements[e] = t, () => {
498
668
  this.achievements[e] === t && (n ? this.achievements[e] = n : delete this.achievements[e]);
499
669
  };
500
670
  }
501
671
  async save() {
502
- if (this._doc) {
503
- if (this._batchDepth > 0) {
504
- this._pendingSave = !0;
505
- return;
506
- }
507
- await this._write();
508
- }
672
+ this._doc && (this._batchDepth > 0 ? this._pendingSave = !0 : await this._write());
509
673
  }
510
674
  async _write() {
511
- this._loadFailed || (this._doc.lastPlayedAt = this.clock.now(), this._deviceSaved ||= await this.dataService.save(X, this._deviceId) !== !1, await this.dataService.save("player", this._doc) === !1 && this._publish("save_failed", { key: "player" }));
675
+ this._loadFailed ? await this._recover() : (this._doc.lastPlayedAt = this.clock.now(), this._deviceSaved ||= await this.dataService.save(Z, this._deviceId) !== !1, await this.dataService.save("player", this._doc) === !1 && this._publish("save_failed", { key: "player" }));
512
676
  }
513
677
  async addXP(e, t = "") {
514
678
  if (!Number.isFinite(e)) throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);
@@ -528,7 +692,7 @@ var X = "device", Z = () => {
528
692
  };
529
693
  this.streakDays === "any" && n.amount > 0 && this._markDay();
530
694
  let r = await this._applyXP(n.amount, n.reason, (e, t) => {
531
- t >= 0 ? e.xpBy[this._deviceId] = D((S(e.xpBy, this._deviceId) ? e.xpBy[this._deviceId] : 0) + t) : e.xpSpentBy[this._deviceId] = D((S(e.xpSpentBy, this._deviceId) ? e.xpSpentBy[this._deviceId] : 0) - t);
695
+ t >= 0 ? e.xpBy[this._deviceId] = C((b(e.xpBy, this._deviceId) ? e.xpBy[this._deviceId] : 0) + t) : e.xpSpentBy[this._deviceId] = C((b(e.xpSpentBy, this._deviceId) ? e.xpSpentBy[this._deviceId] : 0) - t);
532
696
  });
533
697
  return await this._middleware.after("afterXP", {
534
698
  amount: r.xpGained,
@@ -542,19 +706,23 @@ var X = "device", Z = () => {
542
706
  return e = Math.max(e, -V(r)), n(r, e), this._announceXP(i, e, t);
543
707
  }
544
708
  async _announceXP(e, t, n) {
545
- let r = this._doc, a = V(r), o = Math.max(e, i(a)), s = o > e;
546
- return o > r.level && (r.level = o), await this.save(), this._publish("xp_gained", {
709
+ let r = this._doc, a = V(r), o = Math.max(e, i(a));
710
+ o > r.level && (r.level = o);
711
+ let s = this._recoveries;
712
+ await this.save(), this._recoveries !== s && (a = V(this._doc), o = Math.max(o, H(this._doc)), e = Math.max(e, this._savedLevel, i(a - t)));
713
+ let c = o > e;
714
+ return this._publish("xp_gained", {
547
715
  amount: t,
548
716
  reason: n,
549
- leveledUp: s,
717
+ leveledUp: c,
550
718
  newLevel: o,
551
719
  total: a
552
- }), s && this._publish("level_up", {
720
+ }), c && this._publish("level_up", {
553
721
  oldLevel: e,
554
722
  newLevel: o,
555
723
  totalXP: a
556
724
  }), {
557
- leveledUp: s,
725
+ leveledUp: c,
558
726
  newLevel: o,
559
727
  xpGained: t
560
728
  };
@@ -569,8 +737,8 @@ var X = "device", Z = () => {
569
737
  };
570
738
  }
571
739
  _checkRecord(e, t) {
572
- if (!x(e)) throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);
573
- if (!C(t)) throw TypeError("[DopamineJS] record expects a result object");
740
+ if (!y(e)) throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);
741
+ if (!x(t)) throw TypeError("[DopamineJS] record expects a result object");
574
742
  if (t.score !== void 0 && !Number.isFinite(t.score)) throw TypeError(`[DopamineJS] record expects a finite score, received ${String(t.score)}`);
575
743
  }
576
744
  async record(e, t = {}) {
@@ -604,20 +772,20 @@ var X = "device", Z = () => {
604
772
  }
605
773
  async _record(e, t) {
606
774
  let n = this._doc, r = this._deviceId, i = (e, t) => {
607
- e[r] = D((S(e, r) ? e[r] : 0) + t);
775
+ e[r] = C((b(e, r) ? e[r] : 0) + t);
608
776
  };
609
- this._markDay(), S(n.playsBy, e) || (n.playsBy[e] = {}, n.best[e] = 0, n.sumsBy[e] = {}), i(n.playsBy[e], 1), i(n.gamesBy, 1), t.score !== void 0 && t.score > n.best[e] && (n.best[e] = t.score, this._publish("personal_best", {
777
+ this._markDay(), b(n.playsBy, e) || (n.playsBy[e] = {}, n.best[e] = 0, n.sumsBy[e] = {}), i(n.playsBy[e], 1), i(n.gamesBy, 1), t.score !== void 0 && t.score > n.best[e] && (n.best[e] = t.score, this._publish("personal_best", {
610
778
  activity: e,
611
779
  score: t.score
612
780
  }));
613
- for (let r of Object.keys(t)) r !== "score" && r !== "plays" && r !== "best" && x(r) && (S(n.sumsBy[e], r) || (n.sumsBy[e][r] = {}), i(n.sumsBy[e][r], Number.isFinite(t[r]) && t[r] > 0 ? t[r] : 0));
781
+ for (let r of Object.keys(t)) r !== "score" && r !== "plays" && r !== "best" && y(r) && (b(n.sumsBy[e], r) || (n.sumsBy[e][r] = {}), i(n.sumsBy[e][r], Number.isFinite(t[r]) && t[r] > 0 ? t[r] : 0));
614
782
  let a = 10;
615
783
  return t.score && (a += Math.max(0, Math.floor(t.score / 5))), a = Math.floor(a * this.getStreakMultiplier()), await this.addXP(a, `Played ${e}`), await this.checkAchievements(e, t), await this.save(), a;
616
784
  }
617
785
  async checkAchievements(e, t) {
618
786
  let n = [];
619
787
  for (let [r, i] of Object.entries(this.achievements)) {
620
- if (S(this._doc.achievements, r)) continue;
788
+ if (b(this._doc.achievements, r)) continue;
621
789
  let a = !1;
622
790
  try {
623
791
  a = i.check(this.snapshot(), e, t);
@@ -630,14 +798,21 @@ var X = "device", Z = () => {
630
798
  return n;
631
799
  }
632
800
  async unlockAchievement(e) {
633
- if (this._requirePlayer(), !x(e) || !S(this.achievements, e) || S(this._doc.achievements, e)) return !1;
801
+ if (this._requirePlayer(), !y(e) || !b(this.achievements, e) || b(this._doc.achievements, e) || this._unlocking.has(e)) return !1;
634
802
  let t = this.achievements[e];
635
803
  if (!t) return !1;
636
- let { [e]: n } = c(this.achievements), r = await this._middleware.before("beforeUnlock", {
637
- id: e,
638
- reward: n
639
- }, (e) => Number.isFinite(e.reward) && e.reward >= 0);
640
- if (r === !1) return !1;
804
+ let { [e]: n } = c(this.achievements);
805
+ this._unlocking.add(e);
806
+ let r;
807
+ try {
808
+ r = await this._middleware.before("beforeUnlock", {
809
+ id: e,
810
+ reward: n
811
+ }, (e) => Number.isFinite(e.reward) && e.reward >= 0);
812
+ } finally {
813
+ this._unlocking.delete(e);
814
+ }
815
+ if (r === !1 || b(this._doc.achievements, e)) return !1;
641
816
  let i = this._doc, a = H(i);
642
817
  return i.achievements[e] = {
643
818
  unlockedAt: this.clock.now(),
@@ -662,7 +837,8 @@ var X = "device", Z = () => {
662
837
  return this.getUnlockedAchievements().filter((e) => !e.seen);
663
838
  }
664
839
  async markAchievementsSeen(e) {
665
- for (let t of e) S(this._doc.achievements, t) && (this._doc.achievements[t].seen = !0);
840
+ this._requirePlayer();
841
+ for (let t of e) b(this._doc.achievements, t) && (this._doc.achievements[t].seen = !0);
666
842
  await this.save();
667
843
  }
668
844
  getStreakMultiplier() {
@@ -670,8 +846,7 @@ var X = "device", Z = () => {
670
846
  return e >= 7 ? 2 : e >= 5 ? 1.5 : e >= 3 ? 1.25 : 1;
671
847
  }
672
848
  };
673
- //#endregion
674
- //#region src/dopamine/utils/storage.js
849
+ // src/dopamine/utils/storage.js
675
850
  function Q() {
676
851
  let e = /* @__PURE__ */ new Map();
677
852
  return {
@@ -696,9 +871,8 @@ function $() {
696
871
  return Q();
697
872
  }
698
873
  }
699
- //#endregion
700
- //#region src/dopamine/core/DataService.js
701
- var ie = class {
874
+ // src/dopamine/core/DataService.js
875
+ var Se = class {
702
876
  constructor(e = {}) {
703
877
  this.storage = e.storage || $(), this.prefix = e.prefix || "dopamine_", this._tail = null;
704
878
  }
@@ -743,5 +917,4 @@ var ie = class {
743
917
  await this._write(() => this.storage.removeItem(this.prefix + e));
744
918
  }
745
919
  };
746
- //#endregion
747
- export { Y as a, t as c, re as i, e as l, Q as n, B as o, $ as r, r as s, ie as t };
920
+ export { J as a, t as c, xe as i, e as l, Q as n, B as o, $ as r, r as s, Se as t };