dopaminejs 3.5.0 → 3.7.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/README.md +52 -2
- package/dist/{DataService-QQBNqJtN.js → DataService-B5noGvMr.js} +228 -254
- package/dist/DataService-DKCk0nOu.cjs +1 -0
- package/dist/SoundManager-C6VdZEFo.js +308 -0
- package/dist/SoundManager-DBGDYIkz.cjs +1 -0
- package/dist/celebrate.cjs +1 -0
- package/dist/celebrate.js +103 -0
- package/dist/certificate.cjs +1 -0
- package/dist/certificate.js +234 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +3 -1
- package/dist/dopamine.cjs +1 -1
- package/dist/dopamine.global.js +4 -4
- package/dist/dopamine.js +5 -3
- package/dist/host-BWKiYtjY.cjs +37 -0
- package/dist/host-Bhf9EqSk.js +457 -0
- package/dist/icon-BakWSiz_.js +89 -0
- package/dist/icon-gkpxMw48.cjs +1 -0
- package/dist/storage-B6z-zaBe.cjs +1 -0
- package/dist/storage-C2s4Da9b.js +26 -0
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +3 -2
- package/package.json +15 -3
- package/src/celebrate.js +213 -0
- package/src/certificate.js +391 -0
- package/src/dopamine/effects/ParticleSystem.js +5 -1
- package/src/dopamine/ui/RewardUI.js +13 -154
- package/src/dopamine/ui/icon.js +157 -0
- package/types/celebrate.d.ts +39 -0
- package/types/certificate.d.ts +30 -0
- package/types/index.d.ts +2 -0
- package/dist/DataService-Xk7egYXe.cjs +0 -1
- package/dist/host-1c7QSAKI.cjs +0 -37
- package/dist/host-_essSMef.js +0 -835
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { n as e, t } from "./icon-BakWSiz_.js";
|
|
2
|
+
// src/certificate.js
|
|
3
|
+
var n = 1200, r = 850, i = 960, a = 110, o = ["#667eea", "#764ba2"], s = {
|
|
4
|
+
title: "margin:16px 0 0;font-size:32px;font-weight:700;line-height:1.2",
|
|
5
|
+
recipient: "margin:20px 0 0;font-size:26px;line-height:1.3;color:var(--dopamine-toast-accent,#ffd700)",
|
|
6
|
+
date: "margin:20px 0 0;font-size:16px;color:var(--dopamine-toast-muted,rgba(255,255,255,0.85))",
|
|
7
|
+
issuer: "margin:8px 0 0;font-size:16px;color:var(--dopamine-toast-muted,rgba(255,255,255,0.85))"
|
|
8
|
+
}, c = "display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden;", l = {
|
|
9
|
+
title: 2,
|
|
10
|
+
recipient: 3,
|
|
11
|
+
date: 1,
|
|
12
|
+
issuer: 2
|
|
13
|
+
}, u = "position:fixed;top:0;right:0;bottom:0;left:0;z-index:10001;display:flex;align-items:center;justify-content:center;padding:16px;overflow:auto;background:rgba(0,0,0,0.6)", d = "box-sizing:border-box;width:min(100%,720px);padding:36px 32px 24px;text-align:center;overflow-wrap:anywhere;border-radius:var(--dopamine-toast-radius,16px);background:var(--dopamine-toast-bg,linear-gradient(135deg,#667eea 0%,#764ba2 100%));color:var(--dopamine-toast-text,#fff);border:4px double var(--dopamine-toast-accent,#ffd700);box-shadow:var(--dopamine-toast-shadow,0 8px 32px rgba(0,0,0,0.4));font:16px/1.4 system-ui,sans-serif", f = "margin:0 6px;padding:8px 16px;border-radius:8px;font:inherit;cursor:pointer;color:inherit;background:rgba(255,255,255,0.15);border:1px solid var(--dopamine-toast-accent,#ffd700)", p = "@media print{body>*:not(.dopamine-certificate-overlay){display:none!important}.dopamine-certificate-overlay{position:static!important;display:block!important;padding:0!important;background:none!important}.dopamine-certificate-card{margin:0 auto;box-shadow:none!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}.dopamine-certificate-actions{display:none!important}}", m = (e, t) => Object.prototype.hasOwnProperty.call(e, t), h = (e, t) => typeof e == "object" && e && m(e, t) ? e[t] : void 0, g = (e) => e == null ? "" : String(e), _ = null, v = 0;
|
|
14
|
+
function y(e, t, n) {
|
|
15
|
+
let r = document.createElement(e);
|
|
16
|
+
return t && (r.style.cssText = t), n !== void 0 && (r.textContent = n), r;
|
|
17
|
+
}
|
|
18
|
+
function b(e, t, n) {
|
|
19
|
+
let r = (t) => e.measureText(t).width <= i, a = [], o = "", s = !1, c = () => a.length === n ? (s = !0, !1) : (a.push(o), o = "", !0);
|
|
20
|
+
scan: for (let e of t.split(/\s+/)) {
|
|
21
|
+
if (e === "") continue;
|
|
22
|
+
let t = o === "" ? e : `${o} ${e}`;
|
|
23
|
+
if (r(t)) o = t;
|
|
24
|
+
else {
|
|
25
|
+
if (o !== "" && !c()) break;
|
|
26
|
+
for (let t of e) {
|
|
27
|
+
if (o !== "" && !r(o + t) && !c()) break scan;
|
|
28
|
+
o += t;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (!s && o !== "" && (s = !c()), s) {
|
|
33
|
+
let e = a[n - 1];
|
|
34
|
+
for (; e !== "" && !r(`${e}\u2026`);) e = Array.from(e).slice(0, -1).join("");
|
|
35
|
+
a[n - 1] = `${e}\u2026`;
|
|
36
|
+
}
|
|
37
|
+
return a;
|
|
38
|
+
}
|
|
39
|
+
function x(e, t, s) {
|
|
40
|
+
let { fields: c, look: u } = t, d = u.bg && ((t) => {
|
|
41
|
+
for (let n of ["#000000", "#ffffff"]) if (e.fillStyle = n, e.fillStyle = t, e.fillStyle !== n) return !0;
|
|
42
|
+
return !1;
|
|
43
|
+
})(u.bg) ? u.bg : null;
|
|
44
|
+
d || (d = e.createLinearGradient?.(0, 0, n, r), d?.addColorStop(0, o[0]), d?.addColorStop(1, o[1])), e.fillStyle = d ?? o[0], e.fillRect(0, 0, n, r), e.strokeStyle = u.accent, e.lineWidth = 8, e.strokeRect(24, 24, 1152, 802), e.textAlign = "center", e.textBaseline = "top";
|
|
45
|
+
let f = n / 2, p = 90;
|
|
46
|
+
if (s) {
|
|
47
|
+
if (typeof s == "string") e.fillStyle = u.text, e.font = `${a / 2}px system-ui, sans-serif`, e.fillText(s, f, p, i);
|
|
48
|
+
else {
|
|
49
|
+
let t = s.naturalWidth || s.width || a, n = s.naturalHeight || s.height || a, r = Math.min(i / t, a / n), o = Math.min(i, t * r), c = Math.min(a, n * r);
|
|
50
|
+
e.drawImage(s, f - o / 2, p, o, c);
|
|
51
|
+
}
|
|
52
|
+
p += 140;
|
|
53
|
+
}
|
|
54
|
+
let m = [
|
|
55
|
+
[
|
|
56
|
+
"title",
|
|
57
|
+
56,
|
|
58
|
+
"bold",
|
|
59
|
+
u.text,
|
|
60
|
+
40
|
|
61
|
+
],
|
|
62
|
+
[
|
|
63
|
+
"recipient",
|
|
64
|
+
44,
|
|
65
|
+
"",
|
|
66
|
+
u.accent,
|
|
67
|
+
40
|
|
68
|
+
],
|
|
69
|
+
[
|
|
70
|
+
"date",
|
|
71
|
+
28,
|
|
72
|
+
"",
|
|
73
|
+
u.muted,
|
|
74
|
+
30
|
|
75
|
+
],
|
|
76
|
+
[
|
|
77
|
+
"issuer",
|
|
78
|
+
28,
|
|
79
|
+
"",
|
|
80
|
+
u.muted,
|
|
81
|
+
0
|
|
82
|
+
]
|
|
83
|
+
];
|
|
84
|
+
for (let [t, n, r, a, o] of m) {
|
|
85
|
+
e.fillStyle = a, e.font = `${r} ${n}px system-ui, sans-serif`.trim();
|
|
86
|
+
for (let r of b(e, c[t], l[t])) e.fillText(r, f, p, i), p += n * 1.25;
|
|
87
|
+
p += o;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function S(e) {
|
|
91
|
+
let t = () => (console.warn("[DopamineJS] The certificate logo had not loaded, so the PNG has no logo."), null), n = e.querySelector("img");
|
|
92
|
+
if (n) return Promise.resolve(n.naturalWidth > 0 ? n : t());
|
|
93
|
+
let r = e.querySelector("svg");
|
|
94
|
+
return r ? new Promise((e) => {
|
|
95
|
+
let n = new Image();
|
|
96
|
+
n.onload = () => e(n), n.onerror = () => e(t()), n.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(r))}`;
|
|
97
|
+
}) : Promise.resolve(e.textContent.trim() || null);
|
|
98
|
+
}
|
|
99
|
+
function C(e) {
|
|
100
|
+
return new Promise((t) => e.toBlob(t, "image/png"));
|
|
101
|
+
}
|
|
102
|
+
async function w(e) {
|
|
103
|
+
let t = e.logoHolder ? await S(e.logoHolder) : null, i = async (t) => {
|
|
104
|
+
let i = document.createElement("canvas");
|
|
105
|
+
i.width = n, i.height = r;
|
|
106
|
+
let a = i.getContext("2d");
|
|
107
|
+
if (!a) throw Error("[DopamineJS] This canvas has no 2d context");
|
|
108
|
+
return x(a, e, t), C(i);
|
|
109
|
+
}, a;
|
|
110
|
+
try {
|
|
111
|
+
a = await i(t);
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (!t || e?.name !== "SecurityError") throw e;
|
|
114
|
+
console.warn("[DopamineJS] The certificate logo could not be saved (cross-origin), so the PNG has no logo."), a = await i(null);
|
|
115
|
+
}
|
|
116
|
+
if (!a) {
|
|
117
|
+
console.error(/* @__PURE__ */ Error("[DopamineJS] The canvas gave no PNG"));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
let o = URL.createObjectURL(a), s = document.createElement("a");
|
|
121
|
+
s.href = o, s.download = "certificate.png", s.click(), setTimeout(() => URL.revokeObjectURL(o), 1e3);
|
|
122
|
+
}
|
|
123
|
+
function T() {
|
|
124
|
+
let e = _;
|
|
125
|
+
if (!e) return;
|
|
126
|
+
_ = null;
|
|
127
|
+
for (let t of e.undo) t();
|
|
128
|
+
e.overlay.remove(), e.style.remove();
|
|
129
|
+
let t = e.previous;
|
|
130
|
+
_ ? e.overlay.contains(_.previous) && (_.previous = t) : t && t.isConnected && typeof t.focus == "function" && t.focus();
|
|
131
|
+
}
|
|
132
|
+
function E(n, r) {
|
|
133
|
+
if (typeof document > "u") return;
|
|
134
|
+
if (typeof n != "object" || !n || Array.isArray(n)) {
|
|
135
|
+
console.warn("[DopamineJS] showCertificate needs an object of fields.");
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
let i = ++v;
|
|
139
|
+
T();
|
|
140
|
+
let o = document.activeElement, m = null;
|
|
141
|
+
try {
|
|
142
|
+
let b = (e) => g(h(n, e)), x = {
|
|
143
|
+
title: b("title"),
|
|
144
|
+
recipient: b("recipient"),
|
|
145
|
+
date: b("date"),
|
|
146
|
+
issuer: b("issuer")
|
|
147
|
+
}, S = h(n, "logo"), C = h(r, "safeIcons") !== !1, E = y("div", u);
|
|
148
|
+
E.className = "dopamine-certificate-overlay";
|
|
149
|
+
let D = y("div", d);
|
|
150
|
+
D.className = "dopamine-certificate-card", D.setAttribute("role", "dialog"), D.setAttribute("aria-modal", "true"), x.title.trim() ? D.setAttribute("aria-labelledby", "dopamine-certificate-title") : D.setAttribute("aria-label", "Completion certificate"), D.tabIndex = -1;
|
|
151
|
+
let O = null;
|
|
152
|
+
if (S != null && S !== "") {
|
|
153
|
+
O = y("div", `height:${a}px;font-size:56px;line-height:${a}px`), O.className = "dopamine-certificate-logo";
|
|
154
|
+
let n = t(S), r = n ? S.parentNode : null, i = r ? S.nextSibling : null, o = n && S.nodeType === 11 ? [...S.childNodes] : null, s = [];
|
|
155
|
+
e(O, S, C);
|
|
156
|
+
for (let e of O.querySelectorAll("img,svg")) s.push([e, e.getAttribute("style")]), e.style.maxWidth = "100%", e.style.maxHeight = `${a}px`;
|
|
157
|
+
n && (m = () => {
|
|
158
|
+
m = null;
|
|
159
|
+
for (let [e, t] of s) t === null ? e.removeAttribute("style") : e.setAttribute("style", t);
|
|
160
|
+
o ? S.append(...o) : (S.parentNode?.removeChild(S), r?.insertBefore(S, i && i.parentNode === r ? i : null));
|
|
161
|
+
}), O.firstChild ? D.appendChild(O) : O = null;
|
|
162
|
+
}
|
|
163
|
+
for (let e of [
|
|
164
|
+
"title",
|
|
165
|
+
"recipient",
|
|
166
|
+
"date",
|
|
167
|
+
"issuer"
|
|
168
|
+
]) {
|
|
169
|
+
let t = y(e === "title" ? "h2" : "p", `${c}-webkit-line-clamp:${l[e]};${s[e]}`, x[e]);
|
|
170
|
+
t.className = `dopamine-certificate-${e}`, e === "title" && (t.id = "dopamine-certificate-title"), D.appendChild(t);
|
|
171
|
+
}
|
|
172
|
+
let k = y("div", "margin-top:28px");
|
|
173
|
+
k.className = "dopamine-certificate-actions";
|
|
174
|
+
let A = {};
|
|
175
|
+
for (let [e, t] of [
|
|
176
|
+
["download", "Download"],
|
|
177
|
+
["print", "Print"],
|
|
178
|
+
["close", "Close"]
|
|
179
|
+
]) A[e] = y("button", f, t), A[e].type = "button", A[e].className = `dopamine-certificate-${e}`, k.appendChild(A[e]);
|
|
180
|
+
D.appendChild(k), E.appendChild(D);
|
|
181
|
+
let j = document.createElement("style");
|
|
182
|
+
j.textContent = p;
|
|
183
|
+
let M = {
|
|
184
|
+
fields: x,
|
|
185
|
+
logoHolder: O,
|
|
186
|
+
look: null,
|
|
187
|
+
overlay: E,
|
|
188
|
+
style: j,
|
|
189
|
+
undo: [],
|
|
190
|
+
previous: o
|
|
191
|
+
};
|
|
192
|
+
if (i !== v) {
|
|
193
|
+
m?.();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
_ = M, m && M.undo.push(m);
|
|
197
|
+
let N = (e, t) => getComputedStyle(D).getPropertyValue(e).trim() || t, P = () => {
|
|
198
|
+
M.look = {
|
|
199
|
+
bg: N("--dopamine-toast-bg", ""),
|
|
200
|
+
text: N("--dopamine-toast-text", "#fff"),
|
|
201
|
+
muted: N("--dopamine-toast-muted", "rgba(255,255,255,0.85)"),
|
|
202
|
+
accent: N("--dopamine-toast-accent", "#ffd700")
|
|
203
|
+
};
|
|
204
|
+
}, F = (e, t, n) => {
|
|
205
|
+
e.addEventListener(t, n), M.undo.push(() => e.removeEventListener(t, n));
|
|
206
|
+
};
|
|
207
|
+
F(document, "keydown", (e) => {
|
|
208
|
+
if (e.key === "Escape") {
|
|
209
|
+
if (e.defaultPrevented) return;
|
|
210
|
+
e.preventDefault(), T();
|
|
211
|
+
} else if (e.key === "Tab" && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
|
212
|
+
let t = [
|
|
213
|
+
A.download,
|
|
214
|
+
A.print,
|
|
215
|
+
A.close
|
|
216
|
+
], n = t.indexOf(document.activeElement), r = e.shiftKey ? t.length - 1 : 1, i = n === -1 ? e.shiftKey ? t.length - 1 : 0 : (n + r) % t.length;
|
|
217
|
+
e.preventDefault(), t[i].focus();
|
|
218
|
+
}
|
|
219
|
+
}), F(document, "focusin", (e) => {
|
|
220
|
+
_ === M && !E.contains(e.target) && D.focus();
|
|
221
|
+
}), F(E, "click", (e) => {
|
|
222
|
+
let t = e.target;
|
|
223
|
+
t === E || t === A.close ? T() : t === A.print ? window.print() : t === A.download && !M.saving && (M.saving = !0, P(), w(M).catch((e) => console.error(e)).finally(() => {
|
|
224
|
+
M.saving = !1;
|
|
225
|
+
}));
|
|
226
|
+
}), document.head.appendChild(j), document.body.appendChild(E), D.focus();
|
|
227
|
+
} catch (e) {
|
|
228
|
+
console.error(e), i === v && T(), m?.();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function D() {
|
|
232
|
+
T();
|
|
233
|
+
}
|
|
234
|
+
export { D as destroyCertificate, E as showCertificate };
|
package/dist/core.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-DKCk0nOu.cjs"),t=require("./storage-B6z-zaBe.cjs");exports.DataService=e.t,exports.DopamineError=e.o,exports.EventEmitter=e.s,exports.RewardSystem=e.n,exports.createMemoryStorage=t.t,exports.merge=e.r,exports.resolveStorage=t.n,exports.validate=e.i;
|
package/dist/core.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import { i as e, n as t, o as n, r, s as i, t as a } from "./DataService-B5noGvMr.js";
|
|
2
|
+
import { n as o, t as s } from "./storage-C2s4Da9b.js";
|
|
3
|
+
export { a as DataService, n as DopamineError, i as EventEmitter, t as RewardSystem, s as createMemoryStorage, r as merge, o as resolveStorage, e as validate };
|
package/dist/dopamine.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./host-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./host-BWKiYtjY.cjs"),t=require("./DataService-DKCk0nOu.cjs"),n=require("./SoundManager-DBGDYIkz.cjs"),r=require("./storage-B6z-zaBe.cjs");exports.DataService=t.t,exports.DopamineError=t.o,exports.EventEmitter=t.s,exports.HOST_API=e.t,exports.ParticleSystem=n.n,exports.RewardSystem=t.n,exports.RewardUI=e.i,exports.SoundManager=n.t,exports.createDopamine=e.n,exports.createHaptics=e.r,exports.createMemoryStorage=r.t,exports.merge=t.r,exports.prefersReducedMotion=n.r,exports.resolveStorage=r.n,exports.validate=t.i;
|
package/dist/dopamine.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Dopamine=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.has(e)&&this.listeners.get(e).delete(t)}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(n=>{try{n(t)}catch(t){console.error(`Error in listener for event '${e}':`,t)}})}clear(){this.listeners.clear()}},n=class extends Error{constructor(e,t){super(t||e),this.name=`DopamineError`,this.code=e}},r=(e,t=2)=>String(e).padStart(t,`0`),i={now:()=>Date.now(),localDate(e=Date.now()){let t=new Date(e);return`${r(t.getFullYear(),4)}-${r(t.getMonth()+1)}-${r(t.getDate())}`}},a=e=>e>0?Math.max(1,Math.floor((1+Math.sqrt(1+4*e/50))/2)):1,o=e=>50*e*(e-1),s=()=>({first_game:{name:`First Steps`,description:`Play your first game`,icon:`🎮`,xp:50,check:e=>e.totalGamesPlayed>=1},level_5:{name:`Rising Star`,description:`Reach level 5`,icon:`⭐`,xp:100,check:e=>e.level>=5},level_10:{name:`Expert Player`,description:`Reach level 10`,icon:`🏆`,xp:250,check:e=>e.level>=10},streak_3:{name:`Dedicated`,description:`Play 3 days in a row`,icon:`🔥`,xp:100,check:e=>e.streak.current>=3},streak_7:{name:`Unstoppable`,description:`Play 7 days in a row`,icon:`💥`,xp:300,check:e=>e.streak.current>=7}}),c={first_game:50,level_5:100,level_10:250,streak_3:100,streak_7:300},l=e=>{let t={};for(let n of Object.keys(e))t[n]=Number.isFinite(e[n]?.xp)&&e[n].xp>0?e[n].xp:0;return t},u=864e5,d=/^\d{4}-\d{2}-\d{2}$/,f=e=>{let t=new Date(0);return t.setUTCFullYear(+e.slice(0,4),e.slice(5,7)-1,+e.slice(8)),t.getTime()/u},p=e=>new Date(e*u).toISOString().slice(0,10),m=e=>typeof e==`string`&&d.test(e)&&p(f(e))===e,h=(e,t)=>p(f(e)+t);function g(e,t){let n=[...new Set(e)].sort();if(!t)return n;let r=f(t)-399,i=f(t)+1;return n.filter(e=>f(e)>=r&&f(e)<=i)}function _(e,t){let n=new Set(e),r=n.has(t)?t:h(t,-1),i=0;for(;n.has(r);)i++,r=h(r,-1);return i}function v(e){let t=0,n=0,r=NaN;for(let i of[...e].sort()){let e=f(i);n=e===r+1?n+1:1,r=e,n>t&&(t=n)}return t}var y=(e,t)=>e.reduce((e,n)=>n<=t&&(!e||n>e)?n:e,void 0),b=`legacy`,ee=new Set([`__proto__`,`constructor`,`prototype`]),x=e=>typeof e==`string`&&e.length>0&&!ee.has(e),S=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),C=e=>typeof e==`object`&&!!e&&!Array.isArray(e),w=/^\s*-?\d+(\.\d+)?\s*$/;function T(e){return typeof e==`string`&&(e=w.test(e)?Number(e):void 0),typeof e==`number`&&Number.isFinite(e)?e:void 0}var E=e=>Math.min(e,2**53-1),D=T,O=e=>{let t=T(e);return t!==void 0&&t>=0?t:void 0},k=e=>{let t=T(e);return Number.isInteger(t)&&t>=0?t:void 0},A=(e,t)=>D(e)??t,j=(e,t)=>O(e)??t,M=(e,t,n=0)=>{let r=T(e);return Number.isInteger(r)&&r>=n?E(r):t},N=(e,t=e=>e)=>Object.keys(e).sort().reduce((n,r)=>E(n+t(e[r])),0),P=(e=0)=>({v:3,name:`Player`,createdAt:e,lastPlayedAt:e,level:1,longest:0,playDates:[],xpBy:{},xpSpentBy:{},gamesBy:{},playsBy:{},best:{},sumsBy:{},achievements:{}});function F(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e)){let i=x(r)?t(e[r]):void 0;i!==void 0&&(n[r]=E(i))}return n}function te(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e))x(r)&&(n[r]=F(e[r],t));return n}function ne(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e)){let i=e[r];x(r)&&C(i)&&(n[r]={unlockedAt:A(i.unlockedAt,t),seen:i.seen===!0,reward:E(j(i.reward,0))})}return n}var re=new Set([`v`,`name`,`createdAt`,`lastPlayedAt`,`level`,`longest`,`playDates`,`xpBy`,`xpSpentBy`,`gamesBy`,`playsBy`,`best`,`sumsBy`,`achievements`]),ie=new Set([...re,`xp`,`totalGamesPlayed`,`stats`,`streak`]);function I(e,t=0){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(t>=32)return;if(Array.isArray(e))return e.map(e=>I(e,t+1)??null);if(!C(e))return;let n={};for(let r of Object.keys(e)){let i=x(r)?I(e[r],t+1):void 0;i!==void 0&&(n[r]=i)}return n}function ae(e,t){for(let n of Object.keys(e)){if(ie.has(n)||!x(n))continue;let r=I(e[n]);r!==void 0&&(t[n]=r)}return t}var L=e=>Object.keys(e).filter(e=>!re.has(e));function oe(e){let t=e.sumsBy,n=new Set([...Object.keys(e.playsBy),...Object.keys(e.best),...Object.keys(t)]);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]={});return e}function se(e,t,n){return ae(e,oe({v:3,name:typeof e.name==`string`?e.name:`Player`,createdAt:A(e.createdAt,t),lastPlayedAt:A(e.lastPlayedAt,t),level:M(e.level,1,1),longest:M(e.longest,0),playDates:g(Array.isArray(e.playDates)?e.playDates.filter(m):[],n),xpBy:F(e.xpBy,O),xpSpentBy:F(e.xpSpentBy,O),gamesBy:F(e.gamesBy,k),playsBy:te(e.playsBy,k),best:F(e.best,O),sumsBy:ce(e.sumsBy),achievements:ne(e.achievements,t)}))}function ce(e){let t={};if(!C(e))return t;for(let n of Object.keys(e))x(n)&&(t[n]=te(e[n],O));return t}function le(e,t,n,r){let i=P(t);i.name=typeof e.name==`string`?e.name:`Player`,i.createdAt=A(e.createdAt,t),i.lastPlayedAt=A(e.lastPlayedAt,t),i.achievements=ne(e.achievements,t);let o=0;for(let e of Object.keys(i.achievements)){let t=S(n,e)?E(j(n[e],0)):0;i.achievements[e].reward=t,o+=t}let s=E(j(e.xp,0)),c=Math.max(0,s-o);c>0&&(i.xpBy[b]=c),i.level=Math.max(a(s),M(e.level,1,1));let l=M(e.totalGamesPlayed,0);if(l>0&&(i.gamesBy[b]=l),C(e.stats))for(let t of Object.keys(e.stats)){let n=e.stats[t];if(!x(t)||!C(n))continue;let r=M(n.totalPlays,0);i.playsBy[t]=r>0?{[b]:r}:{},i.best[t]=E(j(n.highScore,0)),i.sumsBy[t]={};for(let e of Object.keys(n)){if(!x(e)||e===`totalPlays`||e===`highScore`)continue;let r=O(n[e]);r!==void 0&&(i.sumsBy[t][e]={[b]:E(r)})}}let u=C(e.streak)?e.streak:{},d=M(u.current,1,1);if(i.longest=Math.max(d,M(u.longest,0)),m(u.lastPlayDate)){let e=r&&u.lastPlayDate>r?r:u.lastPlayDate;for(let t=0;t<Math.min(d,400);t++)i.playDates.push(h(e,-t));i.playDates=g(i.playDates,r)}else i.longest=Math.max(M(u.current,0),M(u.longest,0));return ae(e,oe(i))}function ue(e){let t=new Set([...Object.keys(e.xpBy),...Object.keys(e.xpSpentBy),...Object.keys(e.gamesBy)]);for(let n of Object.keys(e.playsBy))for(let r of Object.keys(e.playsBy[n]))t.add(r);for(let n of Object.keys(e.sumsBy))for(let r of Object.keys(e.sumsBy[n]))for(let i of Object.keys(e.sumsBy[n][r]))t.add(i);return t}function de(e){if(ue(e).size>20)throw new n(`too_many_devices`,`[DopamineJS] a save holds at most 20 devices`)}function R(e,t={}){if(!C(e))throw new n(`invalid_document`,`[DopamineJS] a save must be an object`);if(e.v!==void 0&&e.v!==3)throw new n(`unsupported_version`,`[DopamineJS] save version ${String(e.v)} is not 3`);let r=Number.isFinite(t.now)?t.now:0,i=m(t.today)?t.today:void 0,a=e.v===3?se(e,r,i):le(e,r,C(t.rewards)?t.rewards:c,i);return de(a),a}var z=e=>E(Math.max(0,N(e.xpBy)+N(e.achievements,e=>e.reward)-N(e.xpSpentBy))),B=e=>Math.max(e.level,a(z(e)));function fe(e,t){let n={};for(let t of Object.keys(e.playsBy)){let r={plays:N(e.playsBy[t]),best:e.best[t]};for(let n of Object.keys(e.sumsBy[t]))n!==`plays`&&n!==`best`&&(r[n]=N(e.sumsBy[t][n]));n[t]=r}let r={};for(let t of Object.keys(e.achievements))r[t]={...e.achievements[t]};let i={current:_(e.playDates,t),longest:Math.max(e.longest,v(e.playDates))},a=y(e.playDates,t);return a&&(i.lastPlayDate=a),{name:e.name,xp:z(e),level:B(e),totalGamesPlayed:N(e.gamesBy),createdAt:e.createdAt,lastPlayedAt:e.lastPlayedAt,streak:i,achievements:r,stats:n}}var V=e=>JSON.parse(JSON.stringify(e));function pe(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))pe(e[t])}return e}var me=[`beforeXP`,`afterXP`,`beforeRecord`,`afterRecord`,`beforeUnlock`,`afterUnlock`],he=class{constructor(){this._list=[]}use(e){if(!C(e)||!me.some(t=>typeof e[t]==`function`))throw TypeError(`[DopamineJS] use expects an object with one of: ${me.join(`, `)}`);return this._list.push(e),()=>{let t=this._list.indexOf(e);t>=0&&this._list.splice(t,1)}}async before(e,t,n=()=>!0){for(let r of[...this._list]){if(typeof r[e]!=`function`)continue;let i;try{i=await r[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t);continue}if(i===!1)return!1;if(!C(i))continue;let a={...t};for(let e of Object.keys(t))Object.prototype.hasOwnProperty.call(i,e)&&(a[e]=i[e]);n(a)&&(t=a)}return t}async after(e,t){for(let n of[...this._list])if(typeof n[e]==`function`)try{await n[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t)}}};function H(e,t,n){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let a=S(e,i)?e[i]:void 0,o=S(t,i)?t[i]:void 0;r[i]=n>0?H(a||{},o||{},n-1):a===void 0?o:o===void 0?a:Math.max(a,o)}return r}function ge(e,t){let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let i=S(e,r)?e[r]:void 0,a=S(t,r)?t[r]:void 0;if(!i||!a){n[r]={...i||a};continue}let o=i.unlockedAt<a.unlockedAt||i.unlockedAt===a.unlockedAt&&i.reward>=a.reward?i:a;n[r]={unlockedAt:o.unlockedAt,seen:i.seen||a.seen,reward:o.reward}}return n}var U=e=>Array.isArray(e)?`[${e.map(U).join(`,`)}]`:typeof e==`object`&&e?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${U(e[t])}`).join(`,`)}}`:JSON.stringify(e),_e=(e,t)=>(Number.isFinite(e)&&Number.isFinite(t)&&e!==t?e>t:U(e)>=U(t))?e:t;function ve(e,t,n){for(let r of new Set([...L(e),...L(t)])){let i=S(e,r)?e[r]:void 0,a=S(t,r)?t[r]:void 0;n[r]=i===void 0?a:a===void 0?i:_e(i,a)}}var ye=(e,t)=>e>0&&t>0?Math.min(e,t):Math.max(e,t);function W(e,t,n){let r=R(e,n),i=R(t,n),a={v:3,name:(r.lastPlayedAt===i.lastPlayedAt?r.name>=i.name?r:i:r.lastPlayedAt>i.lastPlayedAt?r:i).name,createdAt:ye(r.createdAt,i.createdAt),lastPlayedAt:Math.max(r.lastPlayedAt,i.lastPlayedAt),level:Math.max(r.level,i.level),longest:Math.max(r.longest,i.longest),playDates:g([...r.playDates,...i.playDates],m(n?.today)?n.today:void 0),xpBy:H(r.xpBy,i.xpBy,0),xpSpentBy:H(r.xpSpentBy,i.xpSpentBy,0),gamesBy:H(r.gamesBy,i.gamesBy,0),playsBy:H(r.playsBy,i.playsBy,1),best:H(r.best,i.best,0),sumsBy:H(r.sumsBy,i.sumsBy,2),achievements:ge(r.achievements,i.achievements)};return ve(r,i,a),de(a),a}function G(e){let t=new Map([[JSON.stringify([`xpBy`]),e.xpBy],[JSON.stringify([`xpSpentBy`]),e.xpSpentBy],[JSON.stringify([`gamesBy`]),e.gamesBy]]);for(let n of Object.keys(e.playsBy))t.set(JSON.stringify([`playsBy`,n]),e.playsBy[n]);for(let n of Object.keys(e.sumsBy))for(let r of Object.keys(e.sumsBy[n]))t.set(JSON.stringify([`sumsBy`,n,r]),e.sumsBy[n][r]);return t}function be(e){let t=new Set;for(let n of G(e).values())for(let e in n)n[e]>0&&t.add(e);return t}function K(e,t){let n=new Map;for(let[r,i]of G(e))S(i,t)&&n.set(r,i[t]);return n}function xe(e,t,n){for(let[r,i]of n){let n=e;for(let e of JSON.parse(r))S(n,e)||(n[e]={}),n=n[e];n[t]=E((S(n,t)?n[t]:0)+i)}}function Se(e,t,n,r,i=new Map){let a=R(e,r),o=R(t,r),s=W(a,o,r);s.name=a.name;for(let e of L(a))s[e]=a[e];let c=G(s),l=G(a);for(let[e,t]of G(o)){if(!S(t,n))continue;let r=Math.min(i.get(e)??0,t[n]),a=l.has(e)&&S(l.get(e),n)?l.get(e)[n]:0;c.get(e)[n]=E(Math.max(a,r)+(t[n]-r))}return s}function Ce(e,t,n){let r=V(e),i=e=>{S(e,t)&&(e[n]=S(e,n)?Math.max(e[n],e[t]):e[t],delete e[t])};for(let e of[r.xpBy,r.xpSpentBy,r.gamesBy])i(e);for(let e of Object.keys(r.playsBy))i(r.playsBy[e]);for(let e of Object.keys(r.sumsBy))for(let t of Object.keys(r.sumsBy[e]))i(r.sumsBy[e][t]);return r}var q=`device`,we=()=>{let e=new Uint8Array(8),t=globalThis.crypto;if(typeof t?.getRandomValues==`function`)t.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)},Te=e=>x(e)&&e!==`legacy`,Ee=class extends t{constructor(e,t={}){super(),this.dataService=e,this.clock=t.clock&&typeof t.clock.now==`function`&&typeof t.clock.localDate==`function`?t.clock:i,this.achievements={...t.builtinAchievements===!1?{}:s(),...t.achievements||{}},this.streakDays=t.streakDays===`record`?`record`:`any`,this._doc=null,this._deviceId=null,this._deviceSaved=!1,this._middleware=new he,this._unlocking=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}get loadFailed(){return this._readFailed}_publish(e,t){let n=Object.freeze({...t});this.emit(e,n)}async _batch(e){this._batchDepth++;try{return await e()}finally{this._batchDepth--,this._batchDepth===0&&this._pendingSave&&(this._pendingSave=!1,await this._write())}}_options(){return{now:this.clock.now(),today:this.clock.localDate(),rewards:{...c,...l(this.achievements)}}}async init(){let e=this._doc&&!this._loadFailed&&K(this._doc,this._deviceId),t=await this._readSaved();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()}async _readSaved(){this._loadFailed=!0,this._reading=!0,this._epoch++,this._recovering=null,this._lastRead=this.clock.now();try{let e=await this.dataService.load(`player`,null,{strict:!0});return e!==null&&!C(e)?await this._keepCorrupt(e):(this._loadFailed=!1,this._readFailed=!1,e)}catch(e){return e?.code===`DOPAMINE_CORRUPT`?this._keepCorrupt(e.raw):(this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:`read`,error:e}),null)}finally{this._reading=!1}}_recover(){if(this._recovering||!this._readFailed||this._reading)return Promise.resolve(!1);let e=this.clock.now()-this._lastRead;if(e>=0&&e<this.loadRetryMs)return Promise.resolve(!1);this._lastRead=this.clock.now();let t=this._retryRead(this._epoch).finally(()=>{this._recovering===t&&(this._recovering=null)});return this._recovering=t,t}async _retryRead(e){let t,n=null;try{if(t=await this.dataService.load(`player`,null,{strict:!0}),t!==null&&!C(t))return!1;if(!this._deviceSaved){let e=await this.dataService.load(q,null,{strict:!0});Te(e)&&e!==this._deviceId&&(n=e)}}catch{return!1}if(e!==this._epoch||!this._loadFailed||be(this._doc).has(n))return!1;let r;try{let e=this._options(),i=n??this._deviceId,a=n?Ce(this._doc,this._deviceId,n):this._doc;r=t===null?V(a):Se(t,a,i,e,this._base),de(r),r.level=B(r)}catch{return!1}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}_forgetImports(){this._base=new Map}async _keepCorrupt(e){this._loadFailed=!0;let t=await this.dataService.save(`player_corrupt`,e);return t&&(this._loadFailed=!1),this._readFailed=!t,this._publish(`load_failed`,{key:`player`,reason:`corrupt`,backedUp:t}),null}_load(e){if(!C(e))return P(this.clock.now());try{return R(e,this._options())}catch(e){if(!(e instanceof n))throw e;return this._loadFailed=!0,this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:e.code,error:e}),P(this.clock.now())}}async _readDevice(){if(this._deviceId)return;let e=null;try{e=await this.dataService.load(q,null,{strict:!0})}catch{this._deviceId=we();return}Te(e)?(this._deviceId=e,this._deviceSaved=!0):this._deviceId=we()}_hasSlot(){let e=ue(this._doc);return e.has(this._deviceId)||e.size<20?!0:(this._publish(`load_failed`,{key:`player`,reason:`too_many_devices`}),!1)}_requirePlayer(){if(!this._doc)throw Error(`[DopamineJS] RewardSystem.init() must be awaited before use`)}snapshot(){return this._requirePlayer(),pe(fe(this._doc,this.clock.localDate()))}export(){return this._requirePlayer(),V(this._doc)}async import(e,{silent:t=!1}={}){this._requirePlayer();let n=this.snapshot(),r=R(e,this._options()),i=this._doc,a=null;if(this._readFailed){a=new Map(this._base);let e=new Map,t=K(this._doc,this._deviceId);K(r,this._deviceId).forEach((n,r)=>{n>(t.get(r)??0)&&(e.set(r,n-(a.get(r)??0)),a.set(r,n))}),i=V(this._doc),xe(i,this._deviceId,e)}let o=W(i,r,this._options());o.level=B(o),this._doc=o,a&&(this._base=a);let s=this.snapshot();if(await this.save(),t)return s;let c=s.xp-n.xp,l=s.level>n.level;c>0&&this._publish(`xp_gained`,{amount:c,reason:`import`,leveledUp:l,newLevel:s.level,total:s.xp}),l&&this._publish(`level_up`,{oldLevel:n.level,newLevel:s.level,totalXP:s.xp});for(let e of Object.keys(s.achievements))!S(n.achievements,e)&&S(this.achievements,e)&&this._publish(`achievement_unlocked`,{...this.achievements[e],id:e});return s}async reset(e){let t=e?.overwrite;if(e!==void 0&&(typeof e!=`object`||!e||Array.isArray(e))||t!==void 0&&typeof t!=`boolean`)throw TypeError(`[DopamineJS] reset expects { overwrite?: boolean }`);return this._requirePlayer(),t===!1&&this._readFailed?(this._doc=P(this.clock.now()),this._forgetImports(),this._publish(`player_reset`,{}),this.snapshot()):(await this._batch(async()=>{this._doc=P(this.clock.now()),this._loadFailed=!1,this._readFailed=!1,this._forgetImports(),await this.save()}),this._publish(`player_reset`,{}),this.snapshot())}use(e){return this._middleware.use(e)}defineAchievement(e,t){if(!x(e))throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);if(!C(t)||typeof t.check!=`function`)throw TypeError(`[DopamineJS] defineAchievement expects a definition with a check function`);let n=S(this.achievements,e)?this.achievements[e]:void 0;return this.achievements[e]=t,()=>{this.achievements[e]===t&&(n?this.achievements[e]=n:delete this.achievements[e])}}async save(){this._doc&&(this._batchDepth>0?this._pendingSave=!0:await this._write())}async _write(){this._loadFailed?await this._recover():(this._doc.lastPlayedAt=this.clock.now(),this._deviceSaved||=await this.dataService.save(q,this._deviceId)!==!1,await this.dataService.save(`player`,this._doc)===!1&&this._publish(`save_failed`,{key:`player`}))}async addXP(e,t=``){if(!Number.isFinite(e))throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);if(this._requirePlayer(),!this._hasSlot())return{leveledUp:!1,newLevel:B(this._doc),xpGained:0};let n=await this._middleware.before(`beforeXP`,{amount:e,reason:t},e=>Number.isFinite(e.amount));if(n===!1)return{leveledUp:!1,newLevel:B(this._doc),xpGained:0};this.streakDays===`any`&&n.amount>0&&this._markDay();let r=await this._applyXP(n.amount,n.reason,(e,t)=>{t>=0?e.xpBy[this._deviceId]=E((S(e.xpBy,this._deviceId)?e.xpBy[this._deviceId]:0)+t):e.xpSpentBy[this._deviceId]=E((S(e.xpSpentBy,this._deviceId)?e.xpSpentBy[this._deviceId]:0)-t)});return await this._middleware.after(`afterXP`,{amount:r.xpGained,reason:n.reason,total:z(this._doc),level:r.newLevel}),r}async _applyXP(e,t,n){let r=this._doc,i=B(r);return e=Math.max(e,-z(r)),n(r,e),this._announceXP(i,e,t)}async _announceXP(e,t,n){let r=this._doc,i=z(r),o=Math.max(e,a(i));o>r.level&&(r.level=o);let s=this._recoveries;await this.save(),this._recoveries!==s&&(i=z(this._doc),o=Math.max(o,B(this._doc)),e=Math.max(e,this._savedLevel,a(i-t)));let c=o>e;return this._publish(`xp_gained`,{amount:t,reason:n,leveledUp:c,newLevel:o,total:i}),c&&this._publish(`level_up`,{oldLevel:e,newLevel:o,totalXP:i}),{leveledUp:c,newLevel:o,xpGained:t}}getXPForNextLevel(){this._requirePlayer();let e=B(this._doc),t=z(this._doc),n=o(e+1),r=o(e),i=n-r,a=i>0?Math.max(0,Math.min(1,(t-r)/i)):0;return{total:n,needed:Math.max(0,n-t),progress:a}}_checkRecord(e,t){if(!x(e))throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);if(!C(t))throw TypeError(`[DopamineJS] record expects a result object`);if(t.score!==void 0&&!Number.isFinite(t.score))throw TypeError(`[DopamineJS] record expects a finite score, received ${String(t.score)}`)}async record(e,t={}){if(this._requirePlayer(),this._checkRecord(e,t),!this._hasSlot())return!1;let n=await this._middleware.before(`beforeRecord`,{activity:e,result:t},e=>{try{return this._checkRecord(e.activity,e.result),!0}catch{return!1}});if(n===!1)return!1;let r=await this._batch(()=>this._record(n.activity,n.result));return await this._middleware.after(`afterRecord`,{activity:n.activity,result:n.result,xp:r}),!0}_markDay(){let e=this._doc,t=this.clock.localDate();if(e.playDates.includes(t))return;let n=e.playDates.length===0;e.playDates=g([...e.playDates,t],t),e.longest=Math.max(e.longest,v(e.playDates)),n||this._publish(`streak_updated`,{current:_(e.playDates,t),longest:Math.max(e.longest,v(e.playDates))})}async _record(e,t){let n=this._doc,r=this._deviceId,i=(e,t)=>{e[r]=E((S(e,r)?e[r]:0)+t)};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`,{activity:e,score:t.score}));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));let a=10;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}async checkAchievements(e,t){let n=[];for(let[r,i]of Object.entries(this.achievements)){if(S(this._doc.achievements,r))continue;let a=!1;try{a=i.check(this.snapshot(),e,t)}catch(e){console.error(`[DopamineJS] Achievement "${r}" check threw:`,e);continue}a&&await this.unlockAchievement(r)&&n.push(i)}return n}async unlockAchievement(e){if(this._requirePlayer(),!x(e)||!S(this.achievements,e)||S(this._doc.achievements,e)||this._unlocking.has(e))return!1;let t=this.achievements[e];if(!t)return!1;let{[e]:n}=l(this.achievements);this._unlocking.add(e);let r;try{r=await this._middleware.before(`beforeUnlock`,{id:e,reward:n},e=>Number.isFinite(e.reward)&&e.reward>=0)}finally{this._unlocking.delete(e)}if(r===!1||S(this._doc.achievements,e))return!1;let i=this._doc,a=B(i);return i.achievements[e]={unlockedAt:this.clock.now(),seen:!1,reward:r.reward},await this._announceXP(a,r.reward,`Achievement: ${t.name}`),this._publish(`achievement_unlocked`,{...t,id:e}),await this.save(),await this._middleware.after(`afterUnlock`,{id:e,reward:r.reward}),!0}getUnlockedAchievements(){return this._requirePlayer(),Object.entries(this._doc.achievements).map(([e,t])=>({...this.achievements[e],id:e,...t}))}getUnseenAchievements(){return this.getUnlockedAchievements().filter(e=>!e.seen)}async markAchievementsSeen(e){this._requirePlayer();for(let t of e)S(this._doc.achievements,t)&&(this._doc.achievements[t].seen=!0);await this.save()}getStreakMultiplier(){let e=this.snapshot().streak.current;return e>=7?2:e>=5?1.5:e>=3?1.25:1}};function J(){let e=new Map;return{getItem:t=>e.has(t)?e.get(t):null,setItem:(t,n)=>{e.set(t,String(n))},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()}}}function Y(){try{if(typeof localStorage>`u`)return J();let e=`__dopamine_probe__`;return localStorage.setItem(e,`1`),localStorage.removeItem(e),localStorage}catch{return J()}}var De=class{constructor(e={}){this.storage=e.storage||Y(),this.prefix=e.prefix||`dopamine_`,this._tail=null}_write(e){let t=this._tail?this._tail.then(e):e();if(typeof t?.then==`function`){let e=Promise.resolve(t).catch(()=>{}).then(()=>{this._tail===e&&(this._tail=null)});this._tail=e}return t}async save(e,t){try{let n=JSON.stringify(t);return await this._write(()=>this.storage.setItem(this.prefix+e,n)),!0}catch(e){return console.error(`Error saving data:`,e),!1}}async load(e,t=null,n={}){let r;try{await this._tail,r=await this.storage.getItem(this.prefix+e)}catch(e){if(n.strict)throw e;return console.error(`Error loading data:`,e),t}if(!r)return t;try{return JSON.parse(r)}catch(i){if(n.strict)throw Object.assign(Error(`[DopamineJS] saved "${e}" is not valid JSON`),{code:`DOPAMINE_CORRUPT`,raw:r});return console.error(`Error loading data:`,i),t}}async clear(e){await this._write(()=>this.storage.removeItem(this.prefix+e))}},Oe=`#game-ui-overlay,.game-ui-overlay{pointer-events:none;z-index:1000;width:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;position:fixed;top:0;left:0}.game-ui-top-bar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0000004d;align-items:center;gap:12px;padding:12px 16px;display:flex}.level-badge{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:12px;flex-direction:column;align-items:center;min-width:60px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #667eea66}.level-label{color:#fffc;letter-spacing:.5px;font-size:10px;font-weight:600}.level-number{color:#fff;font-size:24px;font-weight:800;line-height:1}.xp-container{flex-direction:column;flex:1;gap:4px;display:flex}.xp-bar-bg{background:#fff3;border-radius:6px;height:12px;overflow:hidden;box-shadow:inset 0 2px 4px #0003}.xp-bar-fill{background:linear-gradient(90deg,#4facfe 0%,#00f2fe 100%);border-radius:6px;height:100%;transition:width .5s ease-out;box-shadow:0 0 10px #4facfe99}.xp-text{color:#fff;text-align:center;text-shadow:0 1px 2px #00000080;font-size:11px;font-weight:600}.streak-badge{background:linear-gradient(135deg,#f80 0%,#f40 100%);border-radius:12px;align-items:center;gap:6px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #f806}.streak-icon{font-size:20px;animation:2s infinite flicker}.streak-number{color:#fff;font-size:18px;font-weight:800}.achievement-popup{top:calc(var(--dopamine-toast-top,80px) + env(safe-area-inset-top,0px));right:var(--dopamine-toast-right,20px);left:var(--dopamine-toast-left,auto);background:var(--dopamine-toast-bg,linear-gradient(135deg, #667eea 0%, #764ba2 100%));border-radius:var(--dopamine-toast-radius,16px);box-shadow:var(--dopamine-toast-shadow,0 8px 32px #0006);z-index:10000;max-width:var(--dopamine-toast-max-width,320px);padding:16px;animation:.5s cubic-bezier(.68,-.55,.265,1.55) slideIn;position:fixed;overflow:hidden}.achievement-shine{background:linear-gradient(90deg,#0000,#ffffff4d,#0000);width:100%;height:100%;animation:2s infinite shine;position:absolute;top:0;left:-100%}.achievement-content{align-items:center;gap:12px;display:flex;position:relative}.achievement-icon{font-size:48px;animation:.6s ease-out bounce}.achievement-info{flex:1}.achievement-title{color:var(--dopamine-toast-muted,#ffffffe6);text-transform:uppercase;letter-spacing:.5px;font-size:12px;font-weight:600}.achievement-name{color:var(--dopamine-toast-text,white);margin:2px 0;font-size:18px;font-weight:800}.achievement-desc{color:var(--dopamine-toast-muted,#fffc);margin-bottom:4px;font-size:13px}.achievement-xp{color:var(--dopamine-toast-accent,gold);background:#fff3;border-radius:8px;padding:4px 8px;font-size:12px;font-weight:700;display:inline-block}.level-up-overlay{z-index:10001;background:#000000d9;justify-content:center;align-items:center;width:100%;height:100%;animation:.3s ease-out fadeIn;display:flex;position:fixed;top:0;left:0}.level-up-content{text-align:center;animation:.5s cubic-bezier(.68,-.55,.265,1.55) scaleIn}.level-up-title{background:linear-gradient(135deg,gold 0%,#ffed4e 100%);-webkit-text-fill-color:transparent;text-transform:uppercase;letter-spacing:4px;-webkit-background-clip:text;background-clip:text;margin-bottom:16px;font-size:32px;font-weight:800}.level-up-number{color:#fff;text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066;font-size:120px;font-weight:900;animation:1s ease-in-out infinite alternate glow}.level-up-subtitle{color:#fffc;margin-top:16px;font-size:24px;font-weight:600}.floating-text{text-shadow:2px 2px #000,-1px -1px #000,1px -1px #000,-1px 1px #000;pointer-events:none;z-index:9998;font-weight:800;animation:2s ease-out forwards floatUp;position:fixed}@keyframes slideIn{0%{opacity:0;transform:translate(400px)}to{opacity:1;transform:translate(0)}}@keyframes slideOut{0%{opacity:1;transform:translate(0)}to{opacity:0;transform:translate(400px)}}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes scaleIn{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes glow{0%{text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066}to{text-shadow:0 0 30px gold,0 0 60px #ffd700cc,0 0 90px #ffd70099}}@keyframes shine{0%{left:-100%}30%{left:100%}to{left:100%}}@keyframes flicker{0%,to{opacity:1}50%{opacity:.8}}@keyframes floatUp{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-100px)}}@keyframes xp-pulse{0%{transform:scaleY(1)}50%{transform:scaleY(1.2)}to{transform:scaleY(1)}}@keyframes level-pulse{0%{transform:scale(1)}50%{transform:scale(1.1)}to{transform:scale(1)}}@media (width<=480px){.game-ui-top-bar{gap:8px;padding:10px 12px}.level-badge{min-width:50px;padding:6px 10px}.level-number{font-size:20px}.xp-bar-bg{height:10px}.xp-text{font-size:10px}.achievement-popup{right:var(--dopamine-toast-right,12px);max-width:min(var(--dopamine-toast-max-width,320px), calc(100% - 24px))}.level-up-number{font-size:80px}}@media (prefers-reduced-motion:reduce){.game-ui-overlay *,.achievement-popup,.achievement-popup *,.level-up-overlay,.level-up-overlay *{transition:none!important;animation:none!important}.floating-text{animation:none!important}}`,ke=`game-ui-overlay`,Ae={levelUp:`LEVEL UP!`,achievementUnlocked:`Achievement Unlocked!`},je=`dopamine-reward-ui-css`,Me=`🔥`,X=e=>e==null?``:String(e),Ne=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Z=(e,t)=>typeof e==`object`&&e&&Ne(e,t)?e[t]:void 0,Q=`http://www.w3.org/2000/svg`,Pe=new Set([`svg`,`g`,`path`,`circle`,`ellipse`,`rect`,`line`,`polyline`,`polygon`,`text`,`tspan`,`title`,`desc`,`defs`,`linearGradient`,`radialGradient`,`stop`,`clipPath`,`mask`]),Fe=new Set(`viewBox.width.height.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.d.points.transform.fill.fill-opacity.fill-rule.stroke.stroke-width.stroke-linecap.stroke-linejoin.stroke-opacity.opacity.offset.stop-color.stop-opacity.gradientUnits.gradientTransform.clip-path.mask.clip-rule.font-size.font-family.font-weight.text-anchor.id.aria-hidden.aria-label.role`.split(`.`)),Ie=new Set([`fill`,`stroke`,`clip-path`,`mask`]),Le=new Set([`transform`,`gradientTransform`]),Re=/^url\(\s*#([A-Za-z][\w.:-]*)\s*\)$/,ze=/^[#a-zA-Z0-9(),.%\s-]+$/,Be=/^[a-zA-Z0-9(),.\s-]+$/,Ve=/^[A-Za-z][\w.:-]*$/,He=0;function Ue(e,t){if(e.nodeType!==1||e.namespaceURI!==Q||!Pe.has(e.localName))return;let n=e.getAttribute(`id`);n&&Ve.test(n)&&t.add(n);for(let n of Array.from(e.childNodes))Ue(n,t)}function We(e,t,n){if(t.includes(`\\`))return null;let r=t.trim();if(e===`id`)return Ve.test(r)?n.prefix+r:null;if(Ie.has(e)){let e=Re.exec(r);return e?n.ids.has(e[1])?`url(#${n.prefix}${e[1]})`:null:ze.test(r)&&!/url/i.test(r)?r:null}return Le.has(e)?Be.test(r)&&!/url/i.test(r)?r:null:t.includes(`(`)?e===`stop-color`&&ze.test(r)&&!/url/i.test(r)?r:null:t}function Ge(e,t){if(e.nodeType===3||e.nodeType===4)return document.createTextNode(e.data);if(e.nodeType!==1||e.namespaceURI!==Q||!Pe.has(e.localName))return null;let n=document.createElementNS(Q,e.localName);for(let r of Array.from(e.attributes)){if(r.namespaceURI!==null||!Fe.has(r.name))continue;let e=We(r.name,r.value,t);e!==null&&n.setAttribute(r.name,e)}for(let r of Array.from(e.childNodes)){let e=Ge(r,t);e&&n.appendChild(e)}return n}function Ke(e){let t,n=/^\s*<svg[\s>]/.test(e)&&!/^\s*<svg\b[^>]*\sxmlns\s*=/.test(e)?e.replace(/^(\s*<svg)/,`$1 xmlns="${Q}"`):e;try{t=new DOMParser().parseFromString(n,`image/svg+xml`)}catch{return null}let r=t.documentElement;if(!r||r.localName!==`svg`||t.getElementsByTagName(`parsererror`).length>0)return null;let i=new Set;return Ue(r,i),Ge(r,{ids:i,prefix:`dj-icon-${++He}-`})}var qe=class{constructor(e={},t={}){this.parts=e||{};let n=Z(t,`text`);this.strings={...Ae};for(let e of Object.keys(Ae)){let t=Z(n,e);typeof t==`string`&&(this.strings[e]=t)}this.safeIcons=Z(t,`safeIcons`)!==!1,this._streakIcon=Z(Z(t,`icons`),`streak`)??Me,this._injectCss=Z(t,`injectCss`),this.container=null,this.xpBar=null,this.levelDisplay=null,this.streakDisplay=null,this._style=null,this._xp=null,this._level=null,this._timers=new Set,this._detached=[],this._cardQueue=[],this._cardActive=!1,this._build()}get root(){return this.container}_build(){this._injectCss&&this._addStyles(),this.container=document.createElement(`div`),this.container.className=`game-ui-overlay`,document.getElementById(ke)||(this.container.id=ke),this.container.innerHTML=`
|
|
1
|
+
var Dopamine=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.has(e)&&this.listeners.get(e).delete(t)}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(n=>{try{n(t)}catch(t){console.error(`Error in listener for event '${e}':`,t)}})}clear(){this.listeners.clear()}},n=class extends Error{constructor(e,t){super(t||e),this.name=`DopamineError`,this.code=e}},r=(e,t=2)=>String(e).padStart(t,`0`),i={now:()=>Date.now(),localDate(e=Date.now()){let t=new Date(e);return`${r(t.getFullYear(),4)}-${r(t.getMonth()+1)}-${r(t.getDate())}`}},a=e=>e>0?Math.max(1,Math.floor((1+Math.sqrt(1+4*e/50))/2)):1,o=e=>50*e*(e-1),s=()=>({first_game:{name:`First Steps`,description:`Play your first game`,icon:`🎮`,xp:50,check:e=>e.totalGamesPlayed>=1},level_5:{name:`Rising Star`,description:`Reach level 5`,icon:`⭐`,xp:100,check:e=>e.level>=5},level_10:{name:`Expert Player`,description:`Reach level 10`,icon:`🏆`,xp:250,check:e=>e.level>=10},streak_3:{name:`Dedicated`,description:`Play 3 days in a row`,icon:`🔥`,xp:100,check:e=>e.streak.current>=3},streak_7:{name:`Unstoppable`,description:`Play 7 days in a row`,icon:`💥`,xp:300,check:e=>e.streak.current>=7}}),c={first_game:50,level_5:100,level_10:250,streak_3:100,streak_7:300},l=e=>{let t={};for(let n of Object.keys(e))t[n]=Number.isFinite(e[n]?.xp)&&e[n].xp>0?e[n].xp:0;return t},u=864e5,d=/^\d{4}-\d{2}-\d{2}$/,f=e=>{let t=new Date(0);return t.setUTCFullYear(+e.slice(0,4),e.slice(5,7)-1,+e.slice(8)),t.getTime()/u},p=e=>new Date(e*u).toISOString().slice(0,10),m=e=>typeof e==`string`&&d.test(e)&&p(f(e))===e,h=(e,t)=>p(f(e)+t);function g(e,t){let n=[...new Set(e)].sort();if(!t)return n;let r=f(t)-399,i=f(t)+1;return n.filter(e=>f(e)>=r&&f(e)<=i)}function _(e,t){let n=new Set(e),r=n.has(t)?t:h(t,-1),i=0;for(;n.has(r);)i++,r=h(r,-1);return i}function v(e){let t=0,n=0,r=NaN;for(let i of[...e].sort()){let e=f(i);n=e===r+1?n+1:1,r=e,n>t&&(t=n)}return t}var y=(e,t)=>e.reduce((e,n)=>n<=t&&(!e||n>e)?n:e,void 0),b=`legacy`,x=new Set([`__proto__`,`constructor`,`prototype`]),S=e=>typeof e==`string`&&e.length>0&&!x.has(e),C=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),w=e=>typeof e==`object`&&!!e&&!Array.isArray(e),T=/^\s*-?\d+(\.\d+)?\s*$/;function E(e){return typeof e==`string`&&(e=T.test(e)?Number(e):void 0),typeof e==`number`&&Number.isFinite(e)?e:void 0}var D=e=>Math.min(e,2**53-1),O=E,k=e=>{let t=E(e);return t!==void 0&&t>=0?t:void 0},A=e=>{let t=E(e);return Number.isInteger(t)&&t>=0?t:void 0},j=(e,t)=>O(e)??t,M=(e,t)=>k(e)??t,N=(e,t,n=0)=>{let r=E(e);return Number.isInteger(r)&&r>=n?D(r):t},P=(e,t=e=>e)=>Object.keys(e).sort().reduce((n,r)=>D(n+t(e[r])),0),F=(e=0)=>({v:3,name:`Player`,createdAt:e,lastPlayedAt:e,level:1,longest:0,playDates:[],xpBy:{},xpSpentBy:{},gamesBy:{},playsBy:{},best:{},sumsBy:{},achievements:{}});function I(e,t){let n={};if(!w(e))return n;for(let r of Object.keys(e)){let i=S(r)?t(e[r]):void 0;i!==void 0&&(n[r]=D(i))}return n}function ee(e,t){let n={};if(!w(e))return n;for(let r of Object.keys(e))S(r)&&(n[r]=I(e[r],t));return n}function te(e,t){let n={};if(!w(e))return n;for(let r of Object.keys(e)){let i=e[r];S(r)&&w(i)&&(n[r]={unlockedAt:j(i.unlockedAt,t),seen:i.seen===!0,reward:D(M(i.reward,0))})}return n}var ne=new Set([`v`,`name`,`createdAt`,`lastPlayedAt`,`level`,`longest`,`playDates`,`xpBy`,`xpSpentBy`,`gamesBy`,`playsBy`,`best`,`sumsBy`,`achievements`]),re=new Set([...ne,`xp`,`totalGamesPlayed`,`stats`,`streak`]);function L(e,t=0){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(t>=32)return;if(Array.isArray(e))return e.map(e=>L(e,t+1)??null);if(!w(e))return;let n={};for(let r of Object.keys(e)){let i=S(r)?L(e[r],t+1):void 0;i!==void 0&&(n[r]=i)}return n}function ie(e,t){for(let n of Object.keys(e)){if(re.has(n)||!S(n))continue;let r=L(e[n]);r!==void 0&&(t[n]=r)}return t}var R=e=>Object.keys(e).filter(e=>!ne.has(e));function ae(e){let t=e.sumsBy,n=new Set([...Object.keys(e.playsBy),...Object.keys(e.best),...Object.keys(t)]);for(let r of n)C(e.playsBy,r)||(e.playsBy[r]={}),C(e.best,r)||(e.best[r]=0),C(t,r)||(t[r]={});return e}function oe(e,t,n){return ie(e,ae({v:3,name:typeof e.name==`string`?e.name:`Player`,createdAt:j(e.createdAt,t),lastPlayedAt:j(e.lastPlayedAt,t),level:N(e.level,1,1),longest:N(e.longest,0),playDates:g(Array.isArray(e.playDates)?e.playDates.filter(m):[],n),xpBy:I(e.xpBy,k),xpSpentBy:I(e.xpSpentBy,k),gamesBy:I(e.gamesBy,A),playsBy:ee(e.playsBy,A),best:I(e.best,k),sumsBy:se(e.sumsBy),achievements:te(e.achievements,t)}))}function se(e){let t={};if(!w(e))return t;for(let n of Object.keys(e))S(n)&&(t[n]=ee(e[n],k));return t}function ce(e,t,n,r){let i=F(t);i.name=typeof e.name==`string`?e.name:`Player`,i.createdAt=j(e.createdAt,t),i.lastPlayedAt=j(e.lastPlayedAt,t),i.achievements=te(e.achievements,t);let o=0;for(let e of Object.keys(i.achievements)){let t=C(n,e)?D(M(n[e],0)):0;i.achievements[e].reward=t,o+=t}let s=D(M(e.xp,0)),c=Math.max(0,s-o);c>0&&(i.xpBy[b]=c),i.level=Math.max(a(s),N(e.level,1,1));let l=N(e.totalGamesPlayed,0);if(l>0&&(i.gamesBy[b]=l),w(e.stats))for(let t of Object.keys(e.stats)){let n=e.stats[t];if(!S(t)||!w(n))continue;let r=N(n.totalPlays,0);i.playsBy[t]=r>0?{[b]:r}:{},i.best[t]=D(M(n.highScore,0)),i.sumsBy[t]={};for(let e of Object.keys(n)){if(!S(e)||e===`totalPlays`||e===`highScore`)continue;let r=k(n[e]);r!==void 0&&(i.sumsBy[t][e]={[b]:D(r)})}}let u=w(e.streak)?e.streak:{},d=N(u.current,1,1);if(i.longest=Math.max(d,N(u.longest,0)),m(u.lastPlayDate)){let e=r&&u.lastPlayDate>r?r:u.lastPlayDate;for(let t=0;t<Math.min(d,400);t++)i.playDates.push(h(e,-t));i.playDates=g(i.playDates,r)}else i.longest=Math.max(N(u.current,0),N(u.longest,0));return ie(e,ae(i))}function le(e){let t=new Set([...Object.keys(e.xpBy),...Object.keys(e.xpSpentBy),...Object.keys(e.gamesBy)]);for(let n of Object.keys(e.playsBy))for(let r of Object.keys(e.playsBy[n]))t.add(r);for(let n of Object.keys(e.sumsBy))for(let r of Object.keys(e.sumsBy[n]))for(let i of Object.keys(e.sumsBy[n][r]))t.add(i);return t}function ue(e){if(le(e).size>20)throw new n(`too_many_devices`,`[DopamineJS] a save holds at most 20 devices`)}function z(e,t={}){if(!w(e))throw new n(`invalid_document`,`[DopamineJS] a save must be an object`);if(e.v!==void 0&&e.v!==3)throw new n(`unsupported_version`,`[DopamineJS] save version ${String(e.v)} is not 3`);let r=Number.isFinite(t.now)?t.now:0,i=m(t.today)?t.today:void 0,a=e.v===3?oe(e,r,i):ce(e,r,w(t.rewards)?t.rewards:c,i);return ue(a),a}var B=e=>D(Math.max(0,P(e.xpBy)+P(e.achievements,e=>e.reward)-P(e.xpSpentBy))),V=e=>Math.max(e.level,a(B(e)));function de(e,t){let n={};for(let t of Object.keys(e.playsBy)){let r={plays:P(e.playsBy[t]),best:e.best[t]};for(let n of Object.keys(e.sumsBy[t]))n!==`plays`&&n!==`best`&&(r[n]=P(e.sumsBy[t][n]));n[t]=r}let r={};for(let t of Object.keys(e.achievements))r[t]={...e.achievements[t]};let i={current:_(e.playDates,t),longest:Math.max(e.longest,v(e.playDates))},a=y(e.playDates,t);return a&&(i.lastPlayDate=a),{name:e.name,xp:B(e),level:V(e),totalGamesPlayed:P(e.gamesBy),createdAt:e.createdAt,lastPlayedAt:e.lastPlayedAt,streak:i,achievements:r,stats:n}}var H=e=>JSON.parse(JSON.stringify(e));function fe(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))fe(e[t])}return e}var pe=[`beforeXP`,`afterXP`,`beforeRecord`,`afterRecord`,`beforeUnlock`,`afterUnlock`],me=class{constructor(){this._list=[]}use(e){if(!w(e)||!pe.some(t=>typeof e[t]==`function`))throw TypeError(`[DopamineJS] use expects an object with one of: ${pe.join(`, `)}`);return this._list.push(e),()=>{let t=this._list.indexOf(e);t>=0&&this._list.splice(t,1)}}async before(e,t,n=()=>!0){for(let r of[...this._list]){if(typeof r[e]!=`function`)continue;let i;try{i=await r[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t);continue}if(i===!1)return!1;if(!w(i))continue;let a={...t};for(let e of Object.keys(t))Object.prototype.hasOwnProperty.call(i,e)&&(a[e]=i[e]);n(a)&&(t=a)}return t}async after(e,t){for(let n of[...this._list])if(typeof n[e]==`function`)try{await n[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t)}}};function U(e,t,n){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let a=C(e,i)?e[i]:void 0,o=C(t,i)?t[i]:void 0;r[i]=n>0?U(a||{},o||{},n-1):a===void 0?o:o===void 0?a:Math.max(a,o)}return r}function he(e,t){let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let i=C(e,r)?e[r]:void 0,a=C(t,r)?t[r]:void 0;if(!i||!a){n[r]={...i||a};continue}let o=i.unlockedAt<a.unlockedAt||i.unlockedAt===a.unlockedAt&&i.reward>=a.reward?i:a;n[r]={unlockedAt:o.unlockedAt,seen:i.seen||a.seen,reward:o.reward}}return n}var W=e=>Array.isArray(e)?`[${e.map(W).join(`,`)}]`:typeof e==`object`&&e?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${W(e[t])}`).join(`,`)}}`:JSON.stringify(e),ge=(e,t)=>(Number.isFinite(e)&&Number.isFinite(t)&&e!==t?e>t:W(e)>=W(t))?e:t;function _e(e,t,n){for(let r of new Set([...R(e),...R(t)])){let i=C(e,r)?e[r]:void 0,a=C(t,r)?t[r]:void 0;n[r]=i===void 0?a:a===void 0?i:ge(i,a)}}var ve=(e,t)=>e>0&&t>0?Math.min(e,t):Math.max(e,t);function G(e,t,n){let r=z(e,n),i=z(t,n),a={v:3,name:(r.lastPlayedAt===i.lastPlayedAt?r.name>=i.name?r:i:r.lastPlayedAt>i.lastPlayedAt?r:i).name,createdAt:ve(r.createdAt,i.createdAt),lastPlayedAt:Math.max(r.lastPlayedAt,i.lastPlayedAt),level:Math.max(r.level,i.level),longest:Math.max(r.longest,i.longest),playDates:g([...r.playDates,...i.playDates],m(n?.today)?n.today:void 0),xpBy:U(r.xpBy,i.xpBy,0),xpSpentBy:U(r.xpSpentBy,i.xpSpentBy,0),gamesBy:U(r.gamesBy,i.gamesBy,0),playsBy:U(r.playsBy,i.playsBy,1),best:U(r.best,i.best,0),sumsBy:U(r.sumsBy,i.sumsBy,2),achievements:he(r.achievements,i.achievements)};return _e(r,i,a),ue(a),a}function K(e){let t=new Map([[JSON.stringify([`xpBy`]),e.xpBy],[JSON.stringify([`xpSpentBy`]),e.xpSpentBy],[JSON.stringify([`gamesBy`]),e.gamesBy]]);for(let n of Object.keys(e.playsBy))t.set(JSON.stringify([`playsBy`,n]),e.playsBy[n]);for(let n of Object.keys(e.sumsBy))for(let r of Object.keys(e.sumsBy[n]))t.set(JSON.stringify([`sumsBy`,n,r]),e.sumsBy[n][r]);return t}function ye(e){let t=new Set;for(let n of K(e).values())for(let e in n)n[e]>0&&t.add(e);return t}function be(e,t){let n=new Map;for(let[r,i]of K(e))C(i,t)&&n.set(r,i[t]);return n}function xe(e,t,n){for(let[r,i]of n){let n=e;for(let e of JSON.parse(r))C(n,e)||(n[e]={}),n=n[e];n[t]=D((C(n,t)?n[t]:0)+i)}}function Se(e,t,n,r,i=new Map){let a=z(e,r),o=z(t,r),s=G(a,o,r);s.name=a.name;for(let e of R(a))s[e]=a[e];let c=K(s),l=K(a);for(let[e,t]of K(o)){if(!C(t,n))continue;let r=Math.min(i.get(e)??0,t[n]),a=l.has(e)&&C(l.get(e),n)?l.get(e)[n]:0;c.get(e)[n]=D(Math.max(a,r)+(t[n]-r))}return s}function Ce(e,t,n){let r=H(e),i=e=>{C(e,t)&&(e[n]=C(e,n)?Math.max(e[n],e[t]):e[t],delete e[t])};for(let e of[r.xpBy,r.xpSpentBy,r.gamesBy])i(e);for(let e of Object.keys(r.playsBy))i(r.playsBy[e]);for(let e of Object.keys(r.sumsBy))for(let t of Object.keys(r.sumsBy[e]))i(r.sumsBy[e][t]);return r}var q=`device`,we=()=>{let e=new Uint8Array(8),t=globalThis.crypto;if(typeof t?.getRandomValues==`function`)t.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)},Te=e=>S(e)&&e!==`legacy`,Ee=class extends t{constructor(e,t={}){super(),this.dataService=e,this.clock=t.clock&&typeof t.clock.now==`function`&&typeof t.clock.localDate==`function`?t.clock:i,this.achievements={...t.builtinAchievements===!1?{}:s(),...t.achievements||{}},this.streakDays=t.streakDays===`record`?`record`:`any`,this._doc=null,this._deviceId=null,this._deviceSaved=!1,this._middleware=new me,this._unlocking=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}get loadFailed(){return this._readFailed}_publish(e,t){let n=Object.freeze({...t});this.emit(e,n)}async _batch(e){this._batchDepth++;try{return await e()}finally{this._batchDepth--,this._batchDepth===0&&this._pendingSave&&(this._pendingSave=!1,await this._write())}}_options(){return{now:this.clock.now(),today:this.clock.localDate(),rewards:{...c,...l(this.achievements)}}}async init(){let e=this._doc&&!this._loadFailed&&be(this._doc,this._deviceId),t=await this._readSaved();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()}async _readSaved(){this._loadFailed=!0,this._reading=!0,this._epoch++,this._recovering=null,this._lastRead=this.clock.now();try{let e=await this.dataService.load(`player`,null,{strict:!0});return e!==null&&!w(e)?await this._keepCorrupt(e):(this._loadFailed=!1,this._readFailed=!1,e)}catch(e){return e?.code===`DOPAMINE_CORRUPT`?this._keepCorrupt(e.raw):(this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:`read`,error:e}),null)}finally{this._reading=!1}}_recover(){if(this._recovering||!this._readFailed||this._reading)return Promise.resolve(!1);let e=this.clock.now()-this._lastRead;if(e>=0&&e<this.loadRetryMs)return Promise.resolve(!1);this._lastRead=this.clock.now();let t=this._retryRead(this._epoch).finally(()=>{this._recovering===t&&(this._recovering=null)});return this._recovering=t,t}async _retryRead(e){let t,n=null;try{if(t=await this.dataService.load(`player`,null,{strict:!0}),t!==null&&!w(t))return!1;if(!this._deviceSaved){let e=await this.dataService.load(q,null,{strict:!0});Te(e)&&e!==this._deviceId&&(n=e)}}catch{return!1}if(e!==this._epoch||!this._loadFailed||ye(this._doc).has(n))return!1;let r;try{let e=this._options(),i=n??this._deviceId,a=n?Ce(this._doc,this._deviceId,n):this._doc;r=t===null?H(a):Se(t,a,i,e,this._base),ue(r),r.level=V(r)}catch{return!1}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}_forgetImports(){this._base=new Map}async _keepCorrupt(e){this._loadFailed=!0;let t=await this.dataService.save(`player_corrupt`,e);return t&&(this._loadFailed=!1),this._readFailed=!t,this._publish(`load_failed`,{key:`player`,reason:`corrupt`,backedUp:t}),null}_load(e){if(!w(e))return F(this.clock.now());try{return z(e,this._options())}catch(e){if(!(e instanceof n))throw e;return this._loadFailed=!0,this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:e.code,error:e}),F(this.clock.now())}}async _readDevice(){if(this._deviceId)return;let e=null;try{e=await this.dataService.load(q,null,{strict:!0})}catch{this._deviceId=we();return}Te(e)?(this._deviceId=e,this._deviceSaved=!0):this._deviceId=we()}_hasSlot(){let e=le(this._doc);return e.has(this._deviceId)||e.size<20?!0:(this._publish(`load_failed`,{key:`player`,reason:`too_many_devices`}),!1)}_requirePlayer(){if(!this._doc)throw Error(`[DopamineJS] RewardSystem.init() must be awaited before use`)}snapshot(){return this._requirePlayer(),fe(de(this._doc,this.clock.localDate()))}export(){return this._requirePlayer(),H(this._doc)}async import(e,{silent:t=!1}={}){this._requirePlayer();let n=this.snapshot(),r=z(e,this._options()),i=this._doc,a=null;if(this._readFailed){a=new Map(this._base);let e=new Map,t=be(this._doc,this._deviceId);be(r,this._deviceId).forEach((n,r)=>{n>(t.get(r)??0)&&(e.set(r,n-(a.get(r)??0)),a.set(r,n))}),i=H(this._doc),xe(i,this._deviceId,e)}let o=G(i,r,this._options());o.level=V(o),this._doc=o,a&&(this._base=a);let s=this.snapshot();if(await this.save(),t)return s;let c=s.xp-n.xp,l=s.level>n.level;c>0&&this._publish(`xp_gained`,{amount:c,reason:`import`,leveledUp:l,newLevel:s.level,total:s.xp}),l&&this._publish(`level_up`,{oldLevel:n.level,newLevel:s.level,totalXP:s.xp});for(let e of Object.keys(s.achievements))!C(n.achievements,e)&&C(this.achievements,e)&&this._publish(`achievement_unlocked`,{...this.achievements[e],id:e});return s}async reset(e){let t=e?.overwrite;if(e!==void 0&&(typeof e!=`object`||!e||Array.isArray(e))||t!==void 0&&typeof t!=`boolean`)throw TypeError(`[DopamineJS] reset expects { overwrite?: boolean }`);return this._requirePlayer(),t===!1&&this._readFailed?(this._doc=F(this.clock.now()),this._forgetImports(),this._publish(`player_reset`,{}),this.snapshot()):(await this._batch(async()=>{this._doc=F(this.clock.now()),this._loadFailed=!1,this._readFailed=!1,this._forgetImports(),await this.save()}),this._publish(`player_reset`,{}),this.snapshot())}use(e){return this._middleware.use(e)}defineAchievement(e,t){if(!S(e))throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);if(!w(t)||typeof t.check!=`function`)throw TypeError(`[DopamineJS] defineAchievement expects a definition with a check function`);let n=C(this.achievements,e)?this.achievements[e]:void 0;return this.achievements[e]=t,()=>{this.achievements[e]===t&&(n?this.achievements[e]=n:delete this.achievements[e])}}async save(){this._doc&&(this._batchDepth>0?this._pendingSave=!0:await this._write())}async _write(){this._loadFailed?await this._recover():(this._doc.lastPlayedAt=this.clock.now(),this._deviceSaved||=await this.dataService.save(q,this._deviceId)!==!1,await this.dataService.save(`player`,this._doc)===!1&&this._publish(`save_failed`,{key:`player`}))}async addXP(e,t=``){if(!Number.isFinite(e))throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);if(this._requirePlayer(),!this._hasSlot())return{leveledUp:!1,newLevel:V(this._doc),xpGained:0};let n=await this._middleware.before(`beforeXP`,{amount:e,reason:t},e=>Number.isFinite(e.amount));if(n===!1)return{leveledUp:!1,newLevel:V(this._doc),xpGained:0};this.streakDays===`any`&&n.amount>0&&this._markDay();let r=await this._applyXP(n.amount,n.reason,(e,t)=>{t>=0?e.xpBy[this._deviceId]=D((C(e.xpBy,this._deviceId)?e.xpBy[this._deviceId]:0)+t):e.xpSpentBy[this._deviceId]=D((C(e.xpSpentBy,this._deviceId)?e.xpSpentBy[this._deviceId]:0)-t)});return await this._middleware.after(`afterXP`,{amount:r.xpGained,reason:n.reason,total:B(this._doc),level:r.newLevel}),r}async _applyXP(e,t,n){let r=this._doc,i=V(r);return e=Math.max(e,-B(r)),n(r,e),this._announceXP(i,e,t)}async _announceXP(e,t,n){let r=this._doc,i=B(r),o=Math.max(e,a(i));o>r.level&&(r.level=o);let s=this._recoveries;await this.save(),this._recoveries!==s&&(i=B(this._doc),o=Math.max(o,V(this._doc)),e=Math.max(e,this._savedLevel,a(i-t)));let c=o>e;return this._publish(`xp_gained`,{amount:t,reason:n,leveledUp:c,newLevel:o,total:i}),c&&this._publish(`level_up`,{oldLevel:e,newLevel:o,totalXP:i}),{leveledUp:c,newLevel:o,xpGained:t}}getXPForNextLevel(){this._requirePlayer();let e=V(this._doc),t=B(this._doc),n=o(e+1),r=o(e),i=n-r,a=i>0?Math.max(0,Math.min(1,(t-r)/i)):0;return{total:n,needed:Math.max(0,n-t),progress:a}}_checkRecord(e,t){if(!S(e))throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);if(!w(t))throw TypeError(`[DopamineJS] record expects a result object`);if(t.score!==void 0&&!Number.isFinite(t.score))throw TypeError(`[DopamineJS] record expects a finite score, received ${String(t.score)}`)}async record(e,t={}){if(this._requirePlayer(),this._checkRecord(e,t),!this._hasSlot())return!1;let n=await this._middleware.before(`beforeRecord`,{activity:e,result:t},e=>{try{return this._checkRecord(e.activity,e.result),!0}catch{return!1}});if(n===!1)return!1;let r=await this._batch(()=>this._record(n.activity,n.result));return await this._middleware.after(`afterRecord`,{activity:n.activity,result:n.result,xp:r}),!0}_markDay(){let e=this._doc,t=this.clock.localDate();if(e.playDates.includes(t))return;let n=e.playDates.length===0;e.playDates=g([...e.playDates,t],t),e.longest=Math.max(e.longest,v(e.playDates)),n||this._publish(`streak_updated`,{current:_(e.playDates,t),longest:Math.max(e.longest,v(e.playDates))})}async _record(e,t){let n=this._doc,r=this._deviceId,i=(e,t)=>{e[r]=D((C(e,r)?e[r]:0)+t)};this._markDay(),C(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`,{activity:e,score:t.score}));for(let r of Object.keys(t))r!==`score`&&r!==`plays`&&r!==`best`&&S(r)&&(C(n.sumsBy[e],r)||(n.sumsBy[e][r]={}),i(n.sumsBy[e][r],Number.isFinite(t[r])&&t[r]>0?t[r]:0));let a=10;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}async checkAchievements(e,t){let n=[];for(let[r,i]of Object.entries(this.achievements)){if(C(this._doc.achievements,r))continue;let a=!1;try{a=i.check(this.snapshot(),e,t)}catch(e){console.error(`[DopamineJS] Achievement "${r}" check threw:`,e);continue}a&&await this.unlockAchievement(r)&&n.push(i)}return n}async unlockAchievement(e){if(this._requirePlayer(),!S(e)||!C(this.achievements,e)||C(this._doc.achievements,e)||this._unlocking.has(e))return!1;let t=this.achievements[e];if(!t)return!1;let{[e]:n}=l(this.achievements);this._unlocking.add(e);let r;try{r=await this._middleware.before(`beforeUnlock`,{id:e,reward:n},e=>Number.isFinite(e.reward)&&e.reward>=0)}finally{this._unlocking.delete(e)}if(r===!1||C(this._doc.achievements,e))return!1;let i=this._doc,a=V(i);return i.achievements[e]={unlockedAt:this.clock.now(),seen:!1,reward:r.reward},await this._announceXP(a,r.reward,`Achievement: ${t.name}`),this._publish(`achievement_unlocked`,{...t,id:e}),await this.save(),await this._middleware.after(`afterUnlock`,{id:e,reward:r.reward}),!0}getUnlockedAchievements(){return this._requirePlayer(),Object.entries(this._doc.achievements).map(([e,t])=>({...this.achievements[e],id:e,...t}))}getUnseenAchievements(){return this.getUnlockedAchievements().filter(e=>!e.seen)}async markAchievementsSeen(e){this._requirePlayer();for(let t of e)C(this._doc.achievements,t)&&(this._doc.achievements[t].seen=!0);await this.save()}getStreakMultiplier(){let e=this.snapshot().streak.current;return e>=7?2:e>=5?1.5:e>=3?1.25:1}};function J(){let e=new Map;return{getItem:t=>e.has(t)?e.get(t):null,setItem:(t,n)=>{e.set(t,String(n))},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()}}}function Y(){try{if(typeof localStorage>`u`)return J();let e=`__dopamine_probe__`;return localStorage.setItem(e,`1`),localStorage.removeItem(e),localStorage}catch{return J()}}var De=class{constructor(e={}){this.storage=e.storage||Y(),this.prefix=e.prefix||`dopamine_`,this._tail=null}_write(e){let t=this._tail?this._tail.then(e):e();if(typeof t?.then==`function`){let e=Promise.resolve(t).catch(()=>{}).then(()=>{this._tail===e&&(this._tail=null)});this._tail=e}return t}async save(e,t){try{let n=JSON.stringify(t);return await this._write(()=>this.storage.setItem(this.prefix+e,n)),!0}catch(e){return console.error(`Error saving data:`,e),!1}}async load(e,t=null,n={}){let r;try{await this._tail,r=await this.storage.getItem(this.prefix+e)}catch(e){if(n.strict)throw e;return console.error(`Error loading data:`,e),t}if(!r)return t;try{return JSON.parse(r)}catch(i){if(n.strict)throw Object.assign(Error(`[DopamineJS] saved "${e}" is not valid JSON`),{code:`DOPAMINE_CORRUPT`,raw:r});return console.error(`Error loading data:`,i),t}}async clear(e){await this._write(()=>this.storage.removeItem(this.prefix+e))}},Oe=`#game-ui-overlay,.game-ui-overlay{pointer-events:none;z-index:1000;width:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;position:fixed;top:0;left:0}.game-ui-top-bar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0000004d;align-items:center;gap:12px;padding:12px 16px;display:flex}.level-badge{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:12px;flex-direction:column;align-items:center;min-width:60px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #667eea66}.level-label{color:#fffc;letter-spacing:.5px;font-size:10px;font-weight:600}.level-number{color:#fff;font-size:24px;font-weight:800;line-height:1}.xp-container{flex-direction:column;flex:1;gap:4px;display:flex}.xp-bar-bg{background:#fff3;border-radius:6px;height:12px;overflow:hidden;box-shadow:inset 0 2px 4px #0003}.xp-bar-fill{background:linear-gradient(90deg,#4facfe 0%,#00f2fe 100%);border-radius:6px;height:100%;transition:width .5s ease-out;box-shadow:0 0 10px #4facfe99}.xp-text{color:#fff;text-align:center;text-shadow:0 1px 2px #00000080;font-size:11px;font-weight:600}.streak-badge{background:linear-gradient(135deg,#f80 0%,#f40 100%);border-radius:12px;align-items:center;gap:6px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #f806}.streak-icon{font-size:20px;animation:2s infinite flicker}.streak-number{color:#fff;font-size:18px;font-weight:800}.achievement-popup{top:calc(var(--dopamine-toast-top,80px) + env(safe-area-inset-top,0px));right:var(--dopamine-toast-right,20px);left:var(--dopamine-toast-left,auto);background:var(--dopamine-toast-bg,linear-gradient(135deg, #667eea 0%, #764ba2 100%));border-radius:var(--dopamine-toast-radius,16px);box-shadow:var(--dopamine-toast-shadow,0 8px 32px #0006);z-index:10000;max-width:var(--dopamine-toast-max-width,320px);padding:16px;animation:.5s cubic-bezier(.68,-.55,.265,1.55) slideIn;position:fixed;overflow:hidden}.achievement-shine{background:linear-gradient(90deg,#0000,#ffffff4d,#0000);width:100%;height:100%;animation:2s infinite shine;position:absolute;top:0;left:-100%}.achievement-content{align-items:center;gap:12px;display:flex;position:relative}.achievement-icon{font-size:48px;animation:.6s ease-out bounce}.achievement-info{flex:1}.achievement-title{color:var(--dopamine-toast-muted,#ffffffe6);text-transform:uppercase;letter-spacing:.5px;font-size:12px;font-weight:600}.achievement-name{color:var(--dopamine-toast-text,white);margin:2px 0;font-size:18px;font-weight:800}.achievement-desc{color:var(--dopamine-toast-muted,#fffc);margin-bottom:4px;font-size:13px}.achievement-xp{color:var(--dopamine-toast-accent,gold);background:#fff3;border-radius:8px;padding:4px 8px;font-size:12px;font-weight:700;display:inline-block}.level-up-overlay{z-index:10001;background:#000000d9;justify-content:center;align-items:center;width:100%;height:100%;animation:.3s ease-out fadeIn;display:flex;position:fixed;top:0;left:0}.level-up-content{text-align:center;animation:.5s cubic-bezier(.68,-.55,.265,1.55) scaleIn}.level-up-title{background:linear-gradient(135deg,gold 0%,#ffed4e 100%);-webkit-text-fill-color:transparent;text-transform:uppercase;letter-spacing:4px;-webkit-background-clip:text;background-clip:text;margin-bottom:16px;font-size:32px;font-weight:800}.level-up-number{color:#fff;text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066;font-size:120px;font-weight:900;animation:1s ease-in-out infinite alternate glow}.level-up-subtitle{color:#fffc;margin-top:16px;font-size:24px;font-weight:600}.floating-text{text-shadow:2px 2px #000,-1px -1px #000,1px -1px #000,-1px 1px #000;pointer-events:none;z-index:9998;font-weight:800;animation:2s ease-out forwards floatUp;position:fixed}@keyframes slideIn{0%{opacity:0;transform:translate(400px)}to{opacity:1;transform:translate(0)}}@keyframes slideOut{0%{opacity:1;transform:translate(0)}to{opacity:0;transform:translate(400px)}}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes scaleIn{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes glow{0%{text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066}to{text-shadow:0 0 30px gold,0 0 60px #ffd700cc,0 0 90px #ffd70099}}@keyframes shine{0%{left:-100%}30%{left:100%}to{left:100%}}@keyframes flicker{0%,to{opacity:1}50%{opacity:.8}}@keyframes floatUp{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-100px)}}@keyframes xp-pulse{0%{transform:scaleY(1)}50%{transform:scaleY(1.2)}to{transform:scaleY(1)}}@keyframes level-pulse{0%{transform:scale(1)}50%{transform:scale(1.1)}to{transform:scale(1)}}@media (width<=480px){.game-ui-top-bar{gap:8px;padding:10px 12px}.level-badge{min-width:50px;padding:6px 10px}.level-number{font-size:20px}.xp-bar-bg{height:10px}.xp-text{font-size:10px}.achievement-popup{right:var(--dopamine-toast-right,12px);max-width:min(var(--dopamine-toast-max-width,320px), calc(100% - 24px))}.level-up-number{font-size:80px}}@media (prefers-reduced-motion:reduce){.game-ui-overlay *,.achievement-popup,.achievement-popup *,.level-up-overlay,.level-up-overlay *{transition:none!important;animation:none!important}.floating-text{animation:none!important}}`,X=`http://www.w3.org/2000/svg`,ke=new Set([`svg`,`g`,`path`,`circle`,`ellipse`,`rect`,`line`,`polyline`,`polygon`,`text`,`tspan`,`title`,`desc`,`defs`,`linearGradient`,`radialGradient`,`stop`,`clipPath`,`mask`]),Ae=new Set(`viewBox.width.height.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.d.points.transform.fill.fill-opacity.fill-rule.stroke.stroke-width.stroke-linecap.stroke-linejoin.stroke-opacity.opacity.offset.stop-color.stop-opacity.gradientUnits.gradientTransform.clip-path.mask.clip-rule.font-size.font-family.font-weight.text-anchor.id.aria-hidden.aria-label.role`.split(`.`)),je=new Set([`fill`,`stroke`,`clip-path`,`mask`]),Me=new Set([`transform`,`gradientTransform`]),Ne=/^url\(\s*#([A-Za-z][\w.:-]*)\s*\)$/,Pe=/^[#a-zA-Z0-9(),.%\s-]+$/,Fe=/^[a-zA-Z0-9(),.\s-]+$/,Ie=/^[A-Za-z][\w.:-]*$/,Le=0;function Re(e,t){if(e.nodeType!==1||e.namespaceURI!==X||!ke.has(e.localName))return;let n=e.getAttribute(`id`);n&&Ie.test(n)&&t.add(n);for(let n of Array.from(e.childNodes))Re(n,t)}function ze(e,t,n){if(t.includes(`\\`))return null;let r=t.trim();if(e===`id`)return Ie.test(r)?n.prefix+r:null;if(je.has(e)){let e=Ne.exec(r);return e?n.ids.has(e[1])?`url(#${n.prefix}${e[1]})`:null:Pe.test(r)&&!/url/i.test(r)?r:null}return Me.has(e)?Fe.test(r)&&!/url/i.test(r)?r:null:t.includes(`(`)?e===`stop-color`&&Pe.test(r)&&!/url/i.test(r)?r:null:t}function Be(e,t){if(e.nodeType===3||e.nodeType===4)return document.createTextNode(e.data);if(e.nodeType!==1||e.namespaceURI!==X||!ke.has(e.localName))return null;let n=document.createElementNS(X,e.localName);for(let r of Array.from(e.attributes)){if(r.namespaceURI!==null||!Ae.has(r.name))continue;let e=ze(r.name,r.value,t);e!==null&&n.setAttribute(r.name,e)}for(let r of Array.from(e.childNodes)){let e=Be(r,t);e&&n.appendChild(e)}return n}function Ve(e){let t,n=/^\s*<svg[\s>]/.test(e)&&!/^\s*<svg\b[^>]*\sxmlns\s*=/.test(e)?e.replace(/^(\s*<svg)/,`$1 xmlns="${X}"`):e;try{t=new DOMParser().parseFromString(n,`image/svg+xml`)}catch{return null}let r=t.documentElement;if(!r||r.localName!==`svg`||t.getElementsByTagName(`parsererror`).length>0)return null;let i=new Set;return Re(r,i),Be(r,{ids:i,prefix:`dj-icon-${++Le}-`})}function He(e){if(typeof e!=`object`||!e)return!1;if(typeof Node<`u`&&e instanceof Node)return!0;let t=e.ownerDocument?.defaultView?.Node;return typeof t==`function`&&e instanceof t}function Ue(e,t,n){if(e.textContent=``,He(t))e.appendChild(t);else if(typeof t!=`string`)return;else if(!n)e.innerHTML=t;else{let n=Ve(t);n?e.appendChild(n):e.textContent=t}}var We=`game-ui-overlay`,Ge={levelUp:`LEVEL UP!`,achievementUnlocked:`Achievement Unlocked!`},Ke=`dopamine-reward-ui-css`,qe=`🔥`,Z=e=>e==null?``:String(e),Je=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Q=(e,t)=>typeof e==`object`&&e&&Je(e,t)?e[t]:void 0,Ye=class{constructor(e={},t={}){this.parts=e||{};let n=Q(t,`text`);this.strings={...Ge};for(let e of Object.keys(Ge)){let t=Q(n,e);typeof t==`string`&&(this.strings[e]=t)}this.safeIcons=Q(t,`safeIcons`)!==!1,this._streakIcon=Q(Q(t,`icons`),`streak`)??qe,this._injectCss=Q(t,`injectCss`),this.container=null,this.xpBar=null,this.levelDisplay=null,this.streakDisplay=null,this._style=null,this._xp=null,this._level=null,this._timers=new Set,this._detached=[],this._cardQueue=[],this._cardActive=!1,this._build()}get root(){return this.container}_build(){this._injectCss&&this._addStyles(),this.container=document.createElement(`div`),this.container.className=`game-ui-overlay`,document.getElementById(We)||(this.container.id=We),this.container.innerHTML=`
|
|
2
2
|
<div class="game-ui-top-bar">
|
|
3
3
|
<div class="level-badge">
|
|
4
4
|
<span class="level-label">LVL</span>
|
|
@@ -17,7 +17,7 @@ var Dopamine=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Mod
|
|
|
17
17
|
<span class="streak-number">1</span>
|
|
18
18
|
</div>
|
|
19
19
|
</div>
|
|
20
|
-
`,this.liveRegion=document.createElement(`div`),this.liveRegion.className=`dopamine-live-region`,this.liveRegion.setAttribute(`aria-live`,`polite`),this.liveRegion.setAttribute(`role`,`status`),Object.assign(this.liveRegion.style,{position:`absolute`,width:`1px`,height:`1px`,overflow:`hidden`,clipPath:`inset(50%)`,whiteSpace:`nowrap`}),this.container.appendChild(this.liveRegion),document.body.appendChild(this.container),this.levelBadge=this.container.querySelector(`.level-badge`),this.streakBadge=this.container.querySelector(`.streak-badge`),this.xpBar=this.container.querySelector(`.xp-bar-fill`),this.xpText=this.container.querySelector(`.xp-text`),this.levelDisplay=this.container.querySelector(`.level-number`),this.streakDisplay=this.container.querySelector(`.streak-number`),
|
|
20
|
+
`,this.liveRegion=document.createElement(`div`),this.liveRegion.className=`dopamine-live-region`,this.liveRegion.setAttribute(`aria-live`,`polite`),this.liveRegion.setAttribute(`role`,`status`),Object.assign(this.liveRegion.style,{position:`absolute`,width:`1px`,height:`1px`,overflow:`hidden`,clipPath:`inset(50%)`,whiteSpace:`nowrap`}),this.container.appendChild(this.liveRegion),document.body.appendChild(this.container),this.levelBadge=this.container.querySelector(`.level-badge`),this.streakBadge=this.container.querySelector(`.streak-badge`),this.xpBar=this.container.querySelector(`.xp-bar-fill`),this.xpText=this.container.querySelector(`.xp-text`),this.levelDisplay=this.container.querySelector(`.level-number`),this.streakDisplay=this.container.querySelector(`.streak-number`),Ue(this.container.querySelector(`.streak-icon`),this._streakIcon,this.safeIcons)}_addStyles(){if(document.getElementById(Ke))return;let e=typeof this._injectCss==`string`?this._injectCss:Oe;this._style=document.createElement(`style`),this._style.id=Ke,this._style.textContent=e,document.head.appendChild(this._style)}_defer(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);return this._timers.add(n),n}_mount(e){return document.body.appendChild(e),this._detached.push(e),e}_announce(e){this.liveRegion&&(this.liveRegion.textContent=e)}_burst(e,t,n){this.parts.particles?.burst?.(e,t,n)}_replayAnimation(e,t){e&&(e.style.animation=`none`,this._defer(()=>{e.style.animation=t},10))}hud(e){if(!this.container||!e)return;let{xp:t,level:n,progress:r,streak:i,next:a}=e,o=Number.isFinite(r)?r:a>0?t/a:0;this.xpBar.style.width=`${Math.max(0,Math.min(100,o*100))}%`,this.xpText.textContent=Number.isFinite(a)?`${t} / ${a} XP`:`${t} XP`,t!==this._xp&&this._replayAnimation(this.xpBar,`xp-pulse 0.3s ease-out`),this._xp=t,this.levelDisplay.textContent=n,n!==this._level&&this._replayAnimation(this.levelBadge,`level-pulse 0.5s ease-out`),this._level=n,this.streakDisplay.textContent=i,i>=7?this.streakBadge.style.background=`linear-gradient(135deg, #ff6b00 0%, #ff4400 100%)`:i>=3?this.streakBadge.style.background=`linear-gradient(135deg, #ff8800 0%, #ff6b00 100%)`:this.streakBadge.style.background=``}popup(e){if(!this.container||!e||typeof e!=`object`)return;let t=Q(e,`kind`);t===`level`?this._levelPopup(e):t===`notice`?this._notice(e):this._card(e,t===`achievement`)}_card(e,t){let{title:n,body:r,meta:i,icon:a}=e;this._cardQueue.push([{title:n,body:r,meta:i,icon:a,burst:Q(e,`burst`)},t]),this._nextCard()}_nextCard(){if(this._cardActive)return;let e=this._cardQueue.shift();if(e){this._cardActive=!0;try{this._showCard(e[0],e[1])}catch(e){throw this._cardActive=!1,this._nextCard(),e}}}_showCard(e,t){let n=document.createElement(`div`);n.className=`achievement-popup`,n.innerHTML=`
|
|
21
21
|
<div class="achievement-shine"></div>
|
|
22
22
|
<div class="achievement-content">
|
|
23
23
|
<div class="achievement-icon"></div>
|
|
@@ -28,10 +28,10 @@ var Dopamine=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Mod
|
|
|
28
28
|
<div class="achievement-xp"></div>
|
|
29
29
|
</div>
|
|
30
30
|
</div>
|
|
31
|
-
`;let r=
|
|
31
|
+
`;let r=Z(e.title);n.querySelector(`.achievement-title`).textContent=t?this.strings.achievementUnlocked:``,Ue(n.querySelector(`.achievement-icon`),e.icon,this.safeIcons),n.querySelector(`.achievement-name`).textContent=r,n.querySelector(`.achievement-desc`).textContent=Z(e.body),n.querySelector(`.achievement-xp`).textContent=Z(e.meta),this._mount(n),this._announce(t?`${this.strings.achievementUnlocked}: ${r}`:r),e.burst!==!1&&this._defer(()=>{let e=n.getBoundingClientRect();this._burst(`confetti`,{x:e.left+e.width/2,y:e.top+e.height/2},{count:40})},300),this._defer(()=>{n.style.animation=`slideOut 0.3s ease-in forwards`,this._defer(()=>{this._remove(n),this._cardActive=!1,this._nextCard()},300)},4e3)}_levelPopup(e){let t=typeof e.title==`string`&&e.title!==``?e.title:this.strings.levelUp,n=Z(e.body),r=document.createElement(`div`);r.className=`level-up-overlay`,r.innerHTML=`
|
|
32
32
|
<div class="level-up-content">
|
|
33
33
|
<div class="level-up-title"></div>
|
|
34
34
|
<div class="level-up-number"></div>
|
|
35
35
|
<div class="level-up-subtitle">Amazing progress!</div>
|
|
36
36
|
</div>
|
|
37
|
-
`,r.querySelector(`.level-up-title`).textContent=t,r.querySelector(`.level-up-number`).textContent=n,this._mount(r),this._announce(`Level up: ${n}`),this._defer(()=>{for(let e=0;e<5;e++)this._defer(()=>{this._burst(`confetti`,{x:Math.random()*window.innerWidth,y:Math.random()*window.innerHeight*.6},{count:30})},e*200)},300),this._defer(()=>{r.style.opacity=`0`,this._defer(()=>this._remove(r),500)},2500)}_notice(e){let t=window.innerWidth/2,n=window.innerHeight/3,r=X(e.title);e.tier===`legendary`?(this._floatText({text:r,x:t,y:n,color:`#ffd700`,size:`36px`}),this._burst(`stars`,{x:t,y:n},{count:12}),this._burst(`confetti`,{x:t,y:n},{count:25})):e.tier===`rare`?(this._floatText({text:r,x:t,y:n,color:`#ff6b6b`,size:`32px`}),this._burst(`fire`,{x:t,y:n},{count:20})):this._floatText({text:r,x:t,y:n,color:`#fff`,size:`24px`}),this._announce(r)}text(e){this._floatText({...e})}_floatText({text:e,x:t,y:n,color:r=`#ffd700`,size:i=`24px`}){if(!this.container)return;let a=document.createElement(`div`);a.className=`floating-text`,a.textContent=X(e),a.style.left=(Number.isFinite(t)?t:window.innerWidth/2)+`px`,a.style.top=(Number.isFinite(n)?n:window.innerHeight/3)+`px`,a.style.color=r,a.style.fontSize=i,this._mount(a),this._defer(()=>this._remove(a),2e3)}_remove(e){e.remove();let t=this._detached.indexOf(e);t>-1&&this._detached.splice(t,1)}destroy(){for(let e of this._timers)clearTimeout(e);this._timers.clear(),this._cardQueue=[],this._cardActive=!1;for(let e of this._detached)e.remove();this._detached=[],this.container?.remove(),this._style?.remove(),this._style=null,this.container=null,this.liveRegion=null,this.xpBar=null,this.xpText=null,this.levelBadge=null,this.streakBadge=null,this.levelDisplay=null,this.streakDisplay=null,this._streakIcon=null}},Je=Object.freeze({matches:!1});function Ye(e=globalThis.window){return typeof e?.matchMedia==`function`&&e.matchMedia(`(prefers-reduced-motion: reduce)`)||Je}var Xe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ze={confetti:(e,t,n,r)=>e.confetti(t,n,r),sparkle:(e,t,n,r,i)=>e.sparkle(t,n,r,i),fire:(e,t,n,r)=>e.fire(t,n,r),stars:(e,t,n,r)=>e.starBurst(t,n,r),coins:(e,t,n,r)=>e.coinShower(t,n,r)},Qe=class{constructor(e={}){this.container=e.container?typeof e.container==`string`?document.querySelector(e.container):e.container:document.body,this.container||=(console.warn(`[DopamineJS] Particle container '${e.container}' not found. Using document.body.`),document.body),this.maxParticles=Number.isFinite(e.maxParticles)?Math.max(0,Math.floor(e.maxParticles)):5e3,this._reducedMotion=e.respectReducedMotion===!1?null:Ye(window),this.canvasId=e.canvasId||`dopamine-particle-canvas`,this.canvas=document.createElement(`canvas`),this.canvas.classList.add(`dopamine-particle-canvas`),document.getElementById(this.canvasId)||(this.canvas.id=this.canvasId),this.canvas.style.pointerEvents=`none`,this.canvas.style.zIndex=e.zIndex||`9999`,this.container===document.body?(this.canvas.style.position=`fixed`,this.canvas.style.top=`0`,this.canvas.style.left=`0`):(this.canvas.style.position=`absolute`,this.canvas.style.top=`0`,this.canvas.style.left=`0`,window.getComputedStyle(this.container).position===`static`&&(this.container.style.position=`relative`)),this.container.appendChild(this.canvas),this.ctx=this.canvas.getContext(`2d`),this.particles=[],this.pool=[],this.sprites=new Map,this.customEffects=new Map,this.isAnimating=!1,this._onResize=()=>this._resize(),this._resizeObserver=null,this._frameHandle=null,this._lastFrameTime=null,this._resize(),window.ResizeObserver&&this.container!==document.body?(this._resizeObserver=new ResizeObserver(this._onResize),this._resizeObserver.observe(this.container)):window.addEventListener(`resize`,this._onResize)}_resize(){let e=this.container===document.body?window.innerWidth:this.container.clientWidth,t=this.container===document.body?window.innerHeight:this.container.clientHeight,n=window.devicePixelRatio||1;this.width=e,this.height=t,this.canvas.width=Math.round(e*n),this.canvas.height=Math.round(t*n),this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.ctx.setTransform(n,0,0,n,0,0)}registerSprite(e,t){let n=new Image;n.src=t,this.sprites.set(e,n)}registerEffect(e,t){this.customEffects.set(e,t)}play(e,t,n,...r){typeof t==`object`&&t&&(r=n===void 0?[]:[n,...r],{x:t,y:n}=t);let i=this.customEffects.get(e);i?i(t,n,...r):console.warn(`[DopamineJS] Effect '${e}' not found.`)}emit(e){let{x:t,y:n,count:r=10,speed:i=5,gravity:a=.1,decay:o=.02,life:s=1,color:c=`#ffd700`,sprite:l=null,spread:u=Math.PI*2,angle:d=0,size:f=5,type:p=null}=e,m=this._allowed(r);for(let e=0;e<m;e++){let e=this._getParticle(),r=d+(Math.random()-.5)*u,m=Math.random()*i;e.x=t,e.y=n,e.vx=Math.cos(r)*m,e.vy=Math.sin(r)*m,e.life=s,e.decay=o*(.8+Math.random()*.4),e.gravity=a,e.color=Array.isArray(c)?c[Math.floor(Math.random()*c.length)]:c,e.size=f*(.8+Math.random()*.4),e.sprite=l,e.type=p,e.rotation=Math.random()*Math.PI*2,e.rotationSpeed=(Math.random()-.5)*.2,this.particles.push(e)}m>0&&this._startAnimation()}_allowed(e){if(this._reducedMotion?.matches||!Number.isFinite(e))return 0;let t=this.maxParticles-this.particles.length;return Math.max(0,Math.min(Math.floor(e),t))}_getParticle(){return this.pool.length>0?this.pool.pop():{}}_recycleParticle(e){this.pool.push(e)}burst(e,t,n){if(typeof e!=`string`||!Xe(Ze,e))return;let r=Number.isFinite(t?.x)?t.x:this.width/2,i=Number.isFinite(t?.y)?t.y:this.height/2,a=Number.isFinite(n?.count)?n.count:void 0;Ze[e](this,r,i,a,n?.color)}confetti(e,t,n=50){this.emit({x:e,y:t,count:n,color:[`#ff6b6b`,`#4ecdc4`,`#45b7d1`,`#f7dc6f`,`#c06c84`,`#6c5ce7`],speed:10,gravity:.3,decay:.015,size:8,spread:Math.PI*2})}coinShower(e,t,n=10){this.emit({x:e,y:t,count:n,color:`#ffd700`,speed:4,gravity:.4,decay:.012,size:12,angle:-Math.PI/2,spread:Math.PI/2})}sparkle(e,t,n=20,r=`#ffd700`){this.emit({x:e,y:t,count:n,color:r,speed:3,gravity:-.05,decay:.03,size:3})}fire(e,t,n=15){this.emit({x:e,y:t,count:n,color:[`#ff6b00`,`#ff8800`,`#ffaa00`,`#ff4400`],speed:3,gravity:-.2,decay:.04,size:5,angle:-Math.PI/2,spread:Math.PI/4})}starBurst(e,t,n=8){let r=this._allowed(n);for(let n=0;n<r;n++){let i=this._getParticle(),a=Math.PI*2/r*n;i.x=e,i.y=t,i.vx=Math.cos(a)*4,i.vy=Math.sin(a)*4,i.life=1,i.decay=.03,i.gravity=0,i.color=`#ffffff`,i.size=15,i.sprite=null,i.type=`star`,i.rotation=a,i.rotationSpeed=0,this.particles.push(i)}r>0&&this._startAnimation()}_startAnimation(){this.isAnimating||(this.isAnimating=!0,this._lastFrameTime=null,this._animate())}_animate(e){this._frameHandle=null,this.ctx.clearRect(0,0,this.width,this.height);let t=1;Number.isFinite(e)&&(this._lastFrameTime!==null&&(t=Math.max(0,Math.min(3,(e-this._lastFrameTime)/(1e3/60)))),this._lastFrameTime=e);for(let e=this.particles.length-1;e>=0;e--){let n=this.particles[e];if(n.vy+=n.gravity*t,n.x+=n.vx*t,n.y+=n.vy*t,n.life-=n.decay*t,n.rotationSpeed&&(n.rotation+=n.rotationSpeed*t),n.life<=0){this._recycleParticle(n);let t=this.particles.pop();e<this.particles.length&&(this.particles[e]=t)}else{if(this.ctx.save(),this.ctx.globalAlpha=n.life,this.ctx.translate(n.x,n.y),this.ctx.rotate(n.rotation),n.sprite&&this.sprites.has(n.sprite)){let e=this.sprites.get(n.sprite);e.complete&&this.ctx.drawImage(e,-n.size/2,-n.size/2,n.size,n.size)}else n.type===`star`?(this.ctx.fillStyle=n.color,this._drawStarPath(0,0,5,n.size,n.size/2),this.ctx.fill()):(this.ctx.fillStyle=n.color,this.ctx.beginPath(),this.ctx.arc(0,0,n.size,0,Math.PI*2),this.ctx.fill());this.ctx.restore()}}this.particles.length>0?this._frameHandle=requestAnimationFrame(e=>this._animate(e)):this.isAnimating=!1}_drawStarPath(e,t,n,r,i){let a=Math.PI/2*3,o=e,s=t,c=Math.PI/n;this.ctx.beginPath(),this.ctx.moveTo(e,t-r);for(let l=0;l<n;l++)o=e+Math.cos(a)*r,s=t+Math.sin(a)*r,this.ctx.lineTo(o,s),a+=c,o=e+Math.cos(a)*i,s=t+Math.sin(a)*i,this.ctx.lineTo(o,s),a+=c;this.ctx.lineTo(e,t-r),this.ctx.closePath()}clear(){this.particles.forEach(e=>this._recycleParticle(e)),this.particles=[],this.ctx.clearRect(0,0,this.width,this.height)}destroy(){this.clear(),this.isAnimating=!1,this._frameHandle!==null&&(cancelAnimationFrame(this._frameHandle),this._frameHandle=null),this._resizeObserver&&=(this._resizeObserver.disconnect(),null),window.removeEventListener(`resize`,this._onResize),this.canvas.remove(),this.sprites.clear(),this.customEffects.clear(),this.pool=[]}},$e=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),et=class{constructor(e={}){this.audioContext=null,this.storageKey=e.storageKey||`dopamineSoundsMuted`,this.storage=e.storage||Y(),this.muted=this.storage.getItem(this.storageKey)===`true`,this.assets=new Map,this.customSounds=e.customSounds||{},this.masterGain=null,this._volume=1,this.setVolume(e.volume??1),this._loading=new Map,this._timers=new Set,this._synths=new Map,this._unlocks=new Set}unlockOn(e,t=[`pointerup`,`touchend`,`keydown`]){let n=()=>{for(let n of t)e.removeEventListener(n,r);this._unlocks.delete(n)},r=()=>{n(),this.initAudio()};for(let n of t)e.addEventListener(n,r);return this._unlocks.add(n),n}_later(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}initAudio(){if(!this.audioContext){let e=typeof window<`u`?window.AudioContext||window.webkitAudioContext:void 0;if(!e)return!1;this.audioContext=new e,this.masterGain=this.audioContext.createGain(),this.masterGain.gain.value=this._volume,this.masterGain.connect(this.audioContext.destination),this.preloadSounds(this.customSounds)}return this.audioContext.state===`suspended`&&this.audioContext.resume(),!0}setVolume(e){return Number.isFinite(e)&&(this._volume=Math.max(0,Math.min(1,e)),this.masterGain&&(this.masterGain.gain.value=this._volume)),this._volume}getVolume(){return this._volume}_output(){return this.masterGain||this.audioContext.destination}toggleMute(){return this.muted=!this.muted,this.storage.setItem(this.storageKey,this.muted),this.muted}registerSound(e,t){this.customSounds[e]=t,this.audioContext&&this.loadSound(e,t)}register(e,t){return typeof e!=`string`||e===``?()=>{}:typeof t==`string`?(this.registerSound(e,t),()=>{this.customSounds[e]===t&&delete this.customSounds[e],this.assets.delete(e)}):typeof t==`function`?(this._synths.set(e,t),()=>{this._synths.get(e)===t&&this._synths.delete(e)}):()=>{}}async preloadSounds(e){let t=Object.entries(e).map(([e,t])=>(this.customSounds[e]=t,this.loadSound(e,t)));await Promise.allSettled(t)}async loadSound(e,t){if(!this.audioContext)return;if(this._loading.has(e))return this._loading.get(e);let n=this._load(e,t).finally(()=>this._loading.delete(e));return this._loading.set(e,n),n}async _load(e,t){try{let n=this.audioContext,r=await fetch(t);if(r.ok===!1)throw Error(`HTTP ${r.status}`);let i=await r.arrayBuffer(),a=await n.decodeAudioData(i);this.audioContext===n&&this.assets.set(e,a)}catch(t){console.warn(`[DopamineJS] Failed to load sound '${e}':`,t)}}async play(e){if(this.muted||!this.initAudio())return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}if($e(this.customSounds,e)&&!this.assets.has(e)){let t=this.audioContext;if(await this.loadSound(e,this.customSounds[e]),this.audioContext!==t)return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}}let t={xp:()=>this.playXP(!0),level_up:()=>this.playLevelUp(!0),achievement:()=>this.playAchievement(!0),personal_best:()=>this.playPersonalBest(!0),click:()=>this.playClick(!0),error:()=>this.playError(!0)};this._synths.has(e)?this._synths.get(e)(this,(e,t)=>this._later(e,t)):$e(t,e)&&t[e]()}_playBuffer(e){let t=this.audioContext.createBufferSource();t.buffer=e,t.connect(this._output()),t.start(0)}playTone(e,t,n=`sine`,r=.3){if(this.muted||!this.initAudio())return;let i=this.audioContext.createOscillator(),a=this.audioContext.createGain();i.connect(a),a.connect(this._output()),i.frequency.value=e,i.type=n;let o=Math.max(1e-4,r);a.gain.setValueAtTime(o,this.audioContext.currentTime),a.gain.exponentialRampToValueAtTime(.01,this.audioContext.currentTime+t),i.start(this.audioContext.currentTime),i.stop(this.audioContext.currentTime+t)}playClick(e=!1){if(!e&&this.assets.has(`click`))return this.play(`click`);this.playTone(600,.05,`sine`,.1)}playXP(e=!1){if(!e&&this.assets.has(`xp`))return this.play(`xp`);this.playTone(700,.06,`sine`,.12)}playLevelUp(e=!1){if(!e&&this.assets.has(`level_up`))return this.play(`level_up`);this.playTone(500,.12,`sine`,.2),this._later(()=>this.playTone(700,.12,`sine`,.2),110),this._later(()=>this.playTone(900,.25,`sine`,.2),220)}playAchievement(e=!1){if(!e&&this.assets.has(`achievement`))return this.play(`achievement`);this.playTone(660,.1,`triangle`,.2),this._later(()=>this.playTone(990,.25,`triangle`,.2),100)}playPersonalBest(e=!1){if(!e&&this.assets.has(`personal_best`))return this.play(`personal_best`);this.playTone(600,.1,`sine`,.2),this._later(()=>this.playTone(800,.2,`sine`,.2),100)}playError(e=!1){if(!e&&this.assets.has(`error`))return this.play(`error`);this.playTone(200,.2,`sawtooth`,.3)}destroy(){for(let e of[...this._unlocks])e();for(let e of this._timers)clearTimeout(e);this._timers.clear(),this.audioContext&&(this.audioContext.close?.())?.catch?.(()=>{}),this.audioContext=null,this.masterGain=null,this.assets.clear(),this._loading.clear(),this._synths.clear()}};function tt({nav:e=globalThis.navigator,enabled:t=!0}={}){let n=!!t,r=t=>{if(n)try{e.vibrate(t)}catch{}};return{tap:()=>r(10),double:()=>r([10,40,10]),setEnabled(e){n=!!e}}}var nt=3,rt=[`ui`,`particles`,`sound`,`haptics`],it=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,at=(e,t)=>{it(e)&&e.then(void 0,e=>t.error(e))};function ot(){let e=typeof document<`u`&&typeof window<`u`;return{hasDom:e,reducedMotion:e?Ye(window).matches===!0:!1}}function $(e,t,n){if(e===!1)return null;let r=e;return typeof e==`function`&&(r=e(t)),r??n()}function st(e,t){let n=`dopamine_plugin_${t}:`;return{getItem:t=>e.getItem(n+t),setItem:(t,r)=>e.setItem(n+t,r),removeItem:t=>e.removeItem(n+t)}}function ct(e={}){let t=e||{},r=ot(),a={debug:()=>{},info:()=>{},warn:(...e)=>console.warn(...e),error:(...e)=>console.error(...e),...t.log||{}},o=t.storage||Y(),s=t.clock||i,c={ui:null,particles:null,sound:null,haptics:null},l={};for(let e of rt)Object.defineProperty(l,e,{enumerable:!0,get:()=>c[e]});Object.freeze(l);let u={...r,parts:l,storage:o,clock:s},d=$(t.progress,u,()=>new Ee(new De({storage:o}),{clock:s,streakDays:t.streakDays,builtinAchievements:t.builtinAchievements,loadRetryMs:t.loadRetryMs}));if(typeof d?.on!=`function`||typeof d?.off!=`function`)throw new n(`invalid_progress`,`progress needs on() and off()`);c.particles=$(t.particles,u,()=>r.hasDom?new Qe:null),c.sound=$(t.sound,u,()=>new et({storage:o})),c.haptics=$(t.haptics,u,()=>tt());try{c.ui=$(t.ui,u,()=>r.hasDom?new qe(l):null)}catch(e){throw f(),e}function f(){for(let e of rt)try{c[e]?.destroy?.()}catch(e){a.error(e)}}let p=d,m=[],h=!1,g=e=>t=>{try{at(e(t),a)}catch(e){a.error(e)}},_=()=>{let e=c.ui;if(!e||typeof d.snapshot!=`function`||typeof d.getXPForNextLevel!=`function`)return;let t=d.snapshot(),{total:n,progress:r}=d.getXPForNextLevel();e.hud({xp:t.xp,level:t.level,progress:r,streak:t.streak.current,next:n})};m.push(p.on(`xp_gained`,g(e=>{_(),e.leveledUp||c.sound?.play(`xp`)})),p.on(`level_up`,g(e=>{_(),c.ui?.popup({kind:`level`,title:``,body:String(e.newLevel)}),c.sound?.play(`level_up`)})),p.on(`achievement_unlocked`,g(e=>{c.ui?.popup({kind:`achievement`,title:e.name,body:e.description,icon:e.icon,meta:`+${e.xp??0} XP`}),c.sound?.play(`achievement`)})),p.on(`streak_updated`,g(_)),p.on(`player_reset`,g(_)),p.on(`load_recovered`,g(_)),p.on(`personal_best`,g(e=>{c.ui?.popup({kind:`notice`,title:`New High Score: ${e.score}!`,tier:`legendary`}),c.sound?.play(`personal_best`)})));let v=new Map,y=[];function b(e){if(typeof e!=`object`||!e||typeof e.name!=`string`||!/^[a-z0-9-]+$/.test(e.name)||typeof e.install!=`function`)throw new n(`plugin_invalid`,`a plugin needs a name (a-z, 0-9 and -) and an install function`);if(e.api!==3)throw new n(`plugin_api`,`${e.name} was built for api ${e.api}, this host is api 3`);if(v.has(e.name))throw new n(`plugin_duplicate`,`${e.name} is already installed`);for(let t of e.after||[])if(!v.has(t)||!v.get(t).done)throw new n(`plugin_order`,`${e.name} must come after ${t}`);for(let t of e.requires||[])if(!rt.includes(t)||c[t]===null)throw new n(`plugin_requires`,`${e.name} requires the ${t} part, which is not set`)}function ee(e){for(let t of e.offs)t();e.offs.clear(),v.delete(e.name);let t=y.indexOf(e);t>-1&&y.splice(t,1)}function x(e){if(e.removed)return;e.removed=!0;let t=e.disposer;e.disposer=null;try{t?.()}catch(e){a.error(e)}ee(e)}function S(e){let{name:t}=e;return{progress:d,parts:l,events:{on(t,n){let r=p.on(t,n),i=()=>{r(),e.offs.delete(i)};return e.offs.add(i),i},off:(e,t)=>p.off(e,t),emit(e,r){if(typeof e!=`string`||!e.startsWith(`${t}:`))throw new n(`plugin_event`,`${t} may only emit events named ${t}:<event>`);p.emit(e,r)}},storage:st(o,t),clock:s,log:a,env:{hasDom:r.hasDom,reducedMotion:r.reducedMotion},plugin:e=>v.has(e)&&v.get(e).done?v.get(e).handle:null,expose:t=>{e.handle=t}}}function C(e){if(h)throw new n(`disposed`,`the host was disposed`);b(e);let t={name:e.name,done:!1,removed:!1,disposer:null,handle:null,offs:new Set};v.set(e.name,t);let r=e=>(t.done=!0,typeof e==`function`&&(t.disposer=e),t.removed||h?(t.removed=!1,x(t),t):(y.push(t),t)),i=e=>{throw ee(t),e},a;try{a=e.install(S(t))}catch(e){return i(e)}return it(a)?a.then(r,i):r(a)}let w=null;function T(e){if(h)throw new n(`disposed`,`the host was disposed`);if(w===null){let t=C(e);if(it(t)){let e=t.then(e=>e,e=>{throw e});return w=e.then(()=>{w=null},()=>{w=null}),{record:null,done:e}}return{record:t,done:Promise.resolve(t)}}let t=w.then(()=>C(e));return w=t.then(()=>{w=null},()=>{w=null}),{record:null,done:t}}function E(e){let{record:t,done:n}=T(e);if(t)return()=>x(t);let r=null,i=!1;return n.then(e=>{r=e,i&&x(e)},e=>a.error(e)),()=>{r?x(r):i=!0}}let D=Promise.resolve();try{for(let e of t.plugins||[]){let{done:t}=T(e);D=D.then(()=>t)}}catch(e){throw O(),e}D=D.catch(e=>{throw O(),e});function O(){if(!h){h=!0;for(let e of[...y].reverse())x(e);for(let e of[...v.values()])x(e);for(let e of m)e();m.length=0,f(),d.clear?.()}}let k=D.then(()=>typeof d.init==`function`?d.init():void 0).then(()=>(h||_(),A));k.catch(()=>{});let A={progress:d,parts:l,events:p,ready:k,use:E,dispose:O};return A}return e.DataService=De,e.DopamineError=n,e.EventEmitter=t,e.HOST_API=nt,e.ParticleSystem=Qe,e.RewardSystem=Ee,e.RewardUI=qe,e.SoundManager=et,e.createDopamine=ct,e.createHaptics=tt,e.createMemoryStorage=J,e.merge=W,e.prefersReducedMotion=Ye,e.resolveStorage=Y,e.validate=R,e})({});
|
|
37
|
+
`,r.querySelector(`.level-up-title`).textContent=t,r.querySelector(`.level-up-number`).textContent=n,this._mount(r),this._announce(`Level up: ${n}`),this._defer(()=>{for(let e=0;e<5;e++)this._defer(()=>{this._burst(`confetti`,{x:Math.random()*window.innerWidth,y:Math.random()*window.innerHeight*.6},{count:30})},e*200)},300),this._defer(()=>{r.style.opacity=`0`,this._defer(()=>this._remove(r),500)},2500)}_notice(e){let t=window.innerWidth/2,n=window.innerHeight/3,r=Z(e.title);e.tier===`legendary`?(this._floatText({text:r,x:t,y:n,color:`#ffd700`,size:`36px`}),this._burst(`stars`,{x:t,y:n},{count:12}),this._burst(`confetti`,{x:t,y:n},{count:25})):e.tier===`rare`?(this._floatText({text:r,x:t,y:n,color:`#ff6b6b`,size:`32px`}),this._burst(`fire`,{x:t,y:n},{count:20})):this._floatText({text:r,x:t,y:n,color:`#fff`,size:`24px`}),this._announce(r)}text(e){this._floatText({...e})}_floatText({text:e,x:t,y:n,color:r=`#ffd700`,size:i=`24px`}){if(!this.container)return;let a=document.createElement(`div`);a.className=`floating-text`,a.textContent=Z(e),a.style.left=(Number.isFinite(t)?t:window.innerWidth/2)+`px`,a.style.top=(Number.isFinite(n)?n:window.innerHeight/3)+`px`,a.style.color=r,a.style.fontSize=i,this._mount(a),this._defer(()=>this._remove(a),2e3)}_remove(e){e.remove();let t=this._detached.indexOf(e);t>-1&&this._detached.splice(t,1)}destroy(){for(let e of this._timers)clearTimeout(e);this._timers.clear(),this._cardQueue=[],this._cardActive=!1;for(let e of this._detached)e.remove();this._detached=[],this.container?.remove(),this._style?.remove(),this._style=null,this.container=null,this.liveRegion=null,this.xpBar=null,this.xpText=null,this.levelBadge=null,this.streakBadge=null,this.levelDisplay=null,this.streakDisplay=null,this._streakIcon=null}},Xe=Object.freeze({matches:!1});function Ze(e=globalThis.window){return typeof e?.matchMedia==`function`&&e.matchMedia(`(prefers-reduced-motion: reduce)`)||Xe}var Qe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),$e={confetti:(e,t,n,r)=>e.confetti(t,n,r),sparkle:(e,t,n,r,i)=>e.sparkle(t,n,r,i),fire:(e,t,n,r)=>e.fire(t,n,r),stars:(e,t,n,r)=>e.starBurst(t,n,r),coins:(e,t,n,r)=>e.coinShower(t,n,r)},et=class{constructor(e={}){this.container=e.container?typeof e.container==`string`?document.querySelector(e.container):e.container:document.body,this.container||=(console.warn(`[DopamineJS] Particle container '${e.container}' not found. Using document.body.`),document.body),this.maxParticles=Number.isFinite(e.maxParticles)?Math.max(0,Math.floor(e.maxParticles)):5e3,this._reducedMotion=e.respectReducedMotion===!1?null:Ze(window),this.canvasId=e.canvasId||`dopamine-particle-canvas`,this.canvas=document.createElement(`canvas`),this.canvas.classList.add(`dopamine-particle-canvas`),document.getElementById(this.canvasId)||(this.canvas.id=this.canvasId),this.canvas.style.pointerEvents=`none`,this.canvas.style.zIndex=e.zIndex||`9999`,this.container===document.body?(this.canvas.style.position=`fixed`,this.canvas.style.top=`0`,this.canvas.style.left=`0`):(this.canvas.style.position=`absolute`,this.canvas.style.top=`0`,this.canvas.style.left=`0`,window.getComputedStyle(this.container).position===`static`&&(this.container.style.position=`relative`));let t=this.canvas.getContext(`2d`);if(!t)throw Error(`[DopamineJS] This canvas has no 2d context`);this.container.appendChild(this.canvas),this.ctx=t,this.particles=[],this.pool=[],this.sprites=new Map,this.customEffects=new Map,this.isAnimating=!1,this._onResize=()=>this._resize(),this._resizeObserver=null,this._frameHandle=null,this._lastFrameTime=null,this._resize(),window.ResizeObserver&&this.container!==document.body?(this._resizeObserver=new ResizeObserver(this._onResize),this._resizeObserver.observe(this.container)):window.addEventListener(`resize`,this._onResize)}_resize(){let e=this.container===document.body?window.innerWidth:this.container.clientWidth,t=this.container===document.body?window.innerHeight:this.container.clientHeight,n=window.devicePixelRatio||1;this.width=e,this.height=t,this.canvas.width=Math.round(e*n),this.canvas.height=Math.round(t*n),this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.ctx.setTransform(n,0,0,n,0,0)}registerSprite(e,t){let n=new Image;n.src=t,this.sprites.set(e,n)}registerEffect(e,t){this.customEffects.set(e,t)}play(e,t,n,...r){typeof t==`object`&&t&&(r=n===void 0?[]:[n,...r],{x:t,y:n}=t);let i=this.customEffects.get(e);i?i(t,n,...r):console.warn(`[DopamineJS] Effect '${e}' not found.`)}emit(e){let{x:t,y:n,count:r=10,speed:i=5,gravity:a=.1,decay:o=.02,life:s=1,color:c=`#ffd700`,sprite:l=null,spread:u=Math.PI*2,angle:d=0,size:f=5,type:p=null}=e,m=this._allowed(r);for(let e=0;e<m;e++){let e=this._getParticle(),r=d+(Math.random()-.5)*u,m=Math.random()*i;e.x=t,e.y=n,e.vx=Math.cos(r)*m,e.vy=Math.sin(r)*m,e.life=s,e.decay=o*(.8+Math.random()*.4),e.gravity=a,e.color=Array.isArray(c)?c[Math.floor(Math.random()*c.length)]:c,e.size=f*(.8+Math.random()*.4),e.sprite=l,e.type=p,e.rotation=Math.random()*Math.PI*2,e.rotationSpeed=(Math.random()-.5)*.2,this.particles.push(e)}m>0&&this._startAnimation()}_allowed(e){if(this._reducedMotion?.matches||!Number.isFinite(e))return 0;let t=this.maxParticles-this.particles.length;return Math.max(0,Math.min(Math.floor(e),t))}_getParticle(){return this.pool.length>0?this.pool.pop():{}}_recycleParticle(e){this.pool.push(e)}burst(e,t,n){if(typeof e!=`string`||!Qe($e,e))return;let r=Number.isFinite(t?.x)?t.x:this.width/2,i=Number.isFinite(t?.y)?t.y:this.height/2,a=Number.isFinite(n?.count)?n.count:void 0;$e[e](this,r,i,a,n?.color)}confetti(e,t,n=50){this.emit({x:e,y:t,count:n,color:[`#ff6b6b`,`#4ecdc4`,`#45b7d1`,`#f7dc6f`,`#c06c84`,`#6c5ce7`],speed:10,gravity:.3,decay:.015,size:8,spread:Math.PI*2})}coinShower(e,t,n=10){this.emit({x:e,y:t,count:n,color:`#ffd700`,speed:4,gravity:.4,decay:.012,size:12,angle:-Math.PI/2,spread:Math.PI/2})}sparkle(e,t,n=20,r=`#ffd700`){this.emit({x:e,y:t,count:n,color:r,speed:3,gravity:-.05,decay:.03,size:3})}fire(e,t,n=15){this.emit({x:e,y:t,count:n,color:[`#ff6b00`,`#ff8800`,`#ffaa00`,`#ff4400`],speed:3,gravity:-.2,decay:.04,size:5,angle:-Math.PI/2,spread:Math.PI/4})}starBurst(e,t,n=8){let r=this._allowed(n);for(let n=0;n<r;n++){let i=this._getParticle(),a=Math.PI*2/r*n;i.x=e,i.y=t,i.vx=Math.cos(a)*4,i.vy=Math.sin(a)*4,i.life=1,i.decay=.03,i.gravity=0,i.color=`#ffffff`,i.size=15,i.sprite=null,i.type=`star`,i.rotation=a,i.rotationSpeed=0,this.particles.push(i)}r>0&&this._startAnimation()}_startAnimation(){this.isAnimating||(this.isAnimating=!0,this._lastFrameTime=null,this._animate())}_animate(e){this._frameHandle=null,this.ctx.clearRect(0,0,this.width,this.height);let t=1;Number.isFinite(e)&&(this._lastFrameTime!==null&&(t=Math.max(0,Math.min(3,(e-this._lastFrameTime)/(1e3/60)))),this._lastFrameTime=e);for(let e=this.particles.length-1;e>=0;e--){let n=this.particles[e];if(n.vy+=n.gravity*t,n.x+=n.vx*t,n.y+=n.vy*t,n.life-=n.decay*t,n.rotationSpeed&&(n.rotation+=n.rotationSpeed*t),n.life<=0){this._recycleParticle(n);let t=this.particles.pop();e<this.particles.length&&(this.particles[e]=t)}else{if(this.ctx.save(),this.ctx.globalAlpha=n.life,this.ctx.translate(n.x,n.y),this.ctx.rotate(n.rotation),n.sprite&&this.sprites.has(n.sprite)){let e=this.sprites.get(n.sprite);e.complete&&this.ctx.drawImage(e,-n.size/2,-n.size/2,n.size,n.size)}else n.type===`star`?(this.ctx.fillStyle=n.color,this._drawStarPath(0,0,5,n.size,n.size/2),this.ctx.fill()):(this.ctx.fillStyle=n.color,this.ctx.beginPath(),this.ctx.arc(0,0,n.size,0,Math.PI*2),this.ctx.fill());this.ctx.restore()}}this.particles.length>0?this._frameHandle=requestAnimationFrame(e=>this._animate(e)):this.isAnimating=!1}_drawStarPath(e,t,n,r,i){let a=Math.PI/2*3,o=e,s=t,c=Math.PI/n;this.ctx.beginPath(),this.ctx.moveTo(e,t-r);for(let l=0;l<n;l++)o=e+Math.cos(a)*r,s=t+Math.sin(a)*r,this.ctx.lineTo(o,s),a+=c,o=e+Math.cos(a)*i,s=t+Math.sin(a)*i,this.ctx.lineTo(o,s),a+=c;this.ctx.lineTo(e,t-r),this.ctx.closePath()}clear(){this.particles.forEach(e=>this._recycleParticle(e)),this.particles=[],this.ctx.clearRect(0,0,this.width,this.height)}destroy(){this.clear(),this.isAnimating=!1,this._frameHandle!==null&&(cancelAnimationFrame(this._frameHandle),this._frameHandle=null),this._resizeObserver&&=(this._resizeObserver.disconnect(),null),window.removeEventListener(`resize`,this._onResize),this.canvas.remove(),this.sprites.clear(),this.customEffects.clear(),this.pool=[]}},tt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),nt=class{constructor(e={}){this.audioContext=null,this.storageKey=e.storageKey||`dopamineSoundsMuted`,this.storage=e.storage||Y(),this.muted=this.storage.getItem(this.storageKey)===`true`,this.assets=new Map,this.customSounds=e.customSounds||{},this.masterGain=null,this._volume=1,this.setVolume(e.volume??1),this._loading=new Map,this._timers=new Set,this._synths=new Map,this._unlocks=new Set}unlockOn(e,t=[`pointerup`,`touchend`,`keydown`]){let n=()=>{for(let n of t)e.removeEventListener(n,r);this._unlocks.delete(n)},r=()=>{n(),this.initAudio()};for(let n of t)e.addEventListener(n,r);return this._unlocks.add(n),n}_later(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}initAudio(){if(!this.audioContext){let e=typeof window<`u`?window.AudioContext||window.webkitAudioContext:void 0;if(!e)return!1;this.audioContext=new e,this.masterGain=this.audioContext.createGain(),this.masterGain.gain.value=this._volume,this.masterGain.connect(this.audioContext.destination),this.preloadSounds(this.customSounds)}return this.audioContext.state===`suspended`&&this.audioContext.resume(),!0}setVolume(e){return Number.isFinite(e)&&(this._volume=Math.max(0,Math.min(1,e)),this.masterGain&&(this.masterGain.gain.value=this._volume)),this._volume}getVolume(){return this._volume}_output(){return this.masterGain||this.audioContext.destination}toggleMute(){return this.muted=!this.muted,this.storage.setItem(this.storageKey,this.muted),this.muted}registerSound(e,t){this.customSounds[e]=t,this.audioContext&&this.loadSound(e,t)}register(e,t){return typeof e!=`string`||e===``?()=>{}:typeof t==`string`?(this.registerSound(e,t),()=>{this.customSounds[e]===t&&delete this.customSounds[e],this.assets.delete(e)}):typeof t==`function`?(this._synths.set(e,t),()=>{this._synths.get(e)===t&&this._synths.delete(e)}):()=>{}}async preloadSounds(e){let t=Object.entries(e).map(([e,t])=>(this.customSounds[e]=t,this.loadSound(e,t)));await Promise.allSettled(t)}async loadSound(e,t){if(!this.audioContext)return;if(this._loading.has(e))return this._loading.get(e);let n=this._load(e,t).finally(()=>this._loading.delete(e));return this._loading.set(e,n),n}async _load(e,t){try{let n=this.audioContext,r=await fetch(t);if(r.ok===!1)throw Error(`HTTP ${r.status}`);let i=await r.arrayBuffer(),a=await n.decodeAudioData(i);this.audioContext===n&&this.assets.set(e,a)}catch(t){console.warn(`[DopamineJS] Failed to load sound '${e}':`,t)}}async play(e){if(this.muted||!this.initAudio())return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}if(tt(this.customSounds,e)&&!this.assets.has(e)){let t=this.audioContext;if(await this.loadSound(e,this.customSounds[e]),this.audioContext!==t)return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}}let t={xp:()=>this.playXP(!0),level_up:()=>this.playLevelUp(!0),achievement:()=>this.playAchievement(!0),personal_best:()=>this.playPersonalBest(!0),click:()=>this.playClick(!0),error:()=>this.playError(!0)};this._synths.has(e)?this._synths.get(e)(this,(e,t)=>this._later(e,t)):tt(t,e)&&t[e]()}_playBuffer(e){let t=this.audioContext.createBufferSource();t.buffer=e,t.connect(this._output()),t.start(0)}playTone(e,t,n=`sine`,r=.3){if(this.muted||!this.initAudio())return;let i=this.audioContext.createOscillator(),a=this.audioContext.createGain();i.connect(a),a.connect(this._output()),i.frequency.value=e,i.type=n;let o=Math.max(1e-4,r);a.gain.setValueAtTime(o,this.audioContext.currentTime),a.gain.exponentialRampToValueAtTime(.01,this.audioContext.currentTime+t),i.start(this.audioContext.currentTime),i.stop(this.audioContext.currentTime+t)}playClick(e=!1){if(!e&&this.assets.has(`click`))return this.play(`click`);this.playTone(600,.05,`sine`,.1)}playXP(e=!1){if(!e&&this.assets.has(`xp`))return this.play(`xp`);this.playTone(700,.06,`sine`,.12)}playLevelUp(e=!1){if(!e&&this.assets.has(`level_up`))return this.play(`level_up`);this.playTone(500,.12,`sine`,.2),this._later(()=>this.playTone(700,.12,`sine`,.2),110),this._later(()=>this.playTone(900,.25,`sine`,.2),220)}playAchievement(e=!1){if(!e&&this.assets.has(`achievement`))return this.play(`achievement`);this.playTone(660,.1,`triangle`,.2),this._later(()=>this.playTone(990,.25,`triangle`,.2),100)}playPersonalBest(e=!1){if(!e&&this.assets.has(`personal_best`))return this.play(`personal_best`);this.playTone(600,.1,`sine`,.2),this._later(()=>this.playTone(800,.2,`sine`,.2),100)}playError(e=!1){if(!e&&this.assets.has(`error`))return this.play(`error`);this.playTone(200,.2,`sawtooth`,.3)}destroy(){for(let e of[...this._unlocks])e();for(let e of this._timers)clearTimeout(e);this._timers.clear(),this.audioContext&&(this.audioContext.close?.())?.catch?.(()=>{}),this.audioContext=null,this.masterGain=null,this.assets.clear(),this._loading.clear(),this._synths.clear()}};function rt({nav:e=globalThis.navigator,enabled:t=!0}={}){let n=!!t,r=t=>{if(n)try{e.vibrate(t)}catch{}};return{tap:()=>r(10),double:()=>r([10,40,10]),setEnabled(e){n=!!e}}}var it=3,at=[`ui`,`particles`,`sound`,`haptics`],ot=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,st=(e,t)=>{ot(e)&&e.then(void 0,e=>t.error(e))};function ct(){let e=typeof document<`u`&&typeof window<`u`;return{hasDom:e,reducedMotion:e?Ze(window).matches===!0:!1}}function $(e,t,n){if(e===!1)return null;let r=e;return typeof e==`function`&&(r=e(t)),r??n()}function lt(e,t){let n=`dopamine_plugin_${t}:`;return{getItem:t=>e.getItem(n+t),setItem:(t,r)=>e.setItem(n+t,r),removeItem:t=>e.removeItem(n+t)}}function ut(e={}){let t=e||{},r=ct(),a={debug:()=>{},info:()=>{},warn:(...e)=>console.warn(...e),error:(...e)=>console.error(...e),...t.log||{}},o=t.storage||Y(),s=t.clock||i,c={ui:null,particles:null,sound:null,haptics:null},l={};for(let e of at)Object.defineProperty(l,e,{enumerable:!0,get:()=>c[e]});Object.freeze(l);let u={...r,parts:l,storage:o,clock:s},d=$(t.progress,u,()=>new Ee(new De({storage:o}),{clock:s,streakDays:t.streakDays,builtinAchievements:t.builtinAchievements,loadRetryMs:t.loadRetryMs}));if(typeof d?.on!=`function`||typeof d?.off!=`function`)throw new n(`invalid_progress`,`progress needs on() and off()`);c.particles=$(t.particles,u,()=>r.hasDom?new et:null),c.sound=$(t.sound,u,()=>new nt({storage:o})),c.haptics=$(t.haptics,u,()=>rt());try{c.ui=$(t.ui,u,()=>r.hasDom?new Ye(l):null)}catch(e){throw f(),e}function f(){for(let e of at)try{c[e]?.destroy?.()}catch(e){a.error(e)}}let p=d,m=[],h=!1,g=e=>t=>{try{st(e(t),a)}catch(e){a.error(e)}},_=()=>{let e=c.ui;if(!e||typeof d.snapshot!=`function`||typeof d.getXPForNextLevel!=`function`)return;let t=d.snapshot(),{total:n,progress:r}=d.getXPForNextLevel();e.hud({xp:t.xp,level:t.level,progress:r,streak:t.streak.current,next:n})};m.push(p.on(`xp_gained`,g(e=>{_(),e.leveledUp||c.sound?.play(`xp`)})),p.on(`level_up`,g(e=>{_(),c.ui?.popup({kind:`level`,title:``,body:String(e.newLevel)}),c.sound?.play(`level_up`)})),p.on(`achievement_unlocked`,g(e=>{c.ui?.popup({kind:`achievement`,title:e.name,body:e.description,icon:e.icon,meta:`+${e.xp??0} XP`}),c.sound?.play(`achievement`)})),p.on(`streak_updated`,g(_)),p.on(`player_reset`,g(_)),p.on(`load_recovered`,g(_)),p.on(`personal_best`,g(e=>{c.ui?.popup({kind:`notice`,title:`New High Score: ${e.score}!`,tier:`legendary`}),c.sound?.play(`personal_best`)})));let v=new Map,y=[];function b(e){if(typeof e!=`object`||!e||typeof e.name!=`string`||!/^[a-z0-9-]+$/.test(e.name)||typeof e.install!=`function`)throw new n(`plugin_invalid`,`a plugin needs a name (a-z, 0-9 and -) and an install function`);if(e.api!==3)throw new n(`plugin_api`,`${e.name} was built for api ${e.api}, this host is api 3`);if(v.has(e.name))throw new n(`plugin_duplicate`,`${e.name} is already installed`);for(let t of e.after||[])if(!v.has(t)||!v.get(t).done)throw new n(`plugin_order`,`${e.name} must come after ${t}`);for(let t of e.requires||[])if(!at.includes(t)||c[t]===null)throw new n(`plugin_requires`,`${e.name} requires the ${t} part, which is not set`)}function x(e){for(let t of e.offs)t();e.offs.clear(),v.delete(e.name);let t=y.indexOf(e);t>-1&&y.splice(t,1)}function S(e){if(e.removed)return;e.removed=!0;let t=e.disposer;e.disposer=null;try{t?.()}catch(e){a.error(e)}x(e)}function C(e){let{name:t}=e;return{progress:d,parts:l,events:{on(t,n){let r=p.on(t,n),i=()=>{r(),e.offs.delete(i)};return e.offs.add(i),i},off:(e,t)=>p.off(e,t),emit(e,r){if(typeof e!=`string`||!e.startsWith(`${t}:`))throw new n(`plugin_event`,`${t} may only emit events named ${t}:<event>`);p.emit(e,r)}},storage:lt(o,t),clock:s,log:a,env:{hasDom:r.hasDom,reducedMotion:r.reducedMotion},plugin:e=>v.has(e)&&v.get(e).done?v.get(e).handle:null,expose:t=>{e.handle=t}}}function w(e){if(h)throw new n(`disposed`,`the host was disposed`);b(e);let t={name:e.name,done:!1,removed:!1,disposer:null,handle:null,offs:new Set};v.set(e.name,t);let r=e=>(t.done=!0,typeof e==`function`&&(t.disposer=e),t.removed||h?(t.removed=!1,S(t),t):(y.push(t),t)),i=e=>{throw x(t),e},a;try{a=e.install(C(t))}catch(e){return i(e)}return ot(a)?a.then(r,i):r(a)}let T=null;function E(e){if(h)throw new n(`disposed`,`the host was disposed`);if(T===null){let t=w(e);if(ot(t)){let e=t.then(e=>e,e=>{throw e});return T=e.then(()=>{T=null},()=>{T=null}),{record:null,done:e}}return{record:t,done:Promise.resolve(t)}}let t=T.then(()=>w(e));return T=t.then(()=>{T=null},()=>{T=null}),{record:null,done:t}}function D(e){let{record:t,done:n}=E(e);if(t)return()=>S(t);let r=null,i=!1;return n.then(e=>{r=e,i&&S(e)},e=>a.error(e)),()=>{r?S(r):i=!0}}let O=Promise.resolve();try{for(let e of t.plugins||[]){let{done:t}=E(e);O=O.then(()=>t)}}catch(e){throw k(),e}O=O.catch(e=>{throw k(),e});function k(){if(!h){h=!0;for(let e of[...y].reverse())S(e);for(let e of[...v.values()])S(e);for(let e of m)e();m.length=0,f(),d.clear?.()}}let A=O.then(()=>typeof d.init==`function`?d.init():void 0).then(()=>(h||_(),j));A.catch(()=>{});let j={progress:d,parts:l,events:p,ready:A,use:D,dispose:k};return j}return e.DataService=De,e.DopamineError=n,e.EventEmitter=t,e.HOST_API=it,e.ParticleSystem=et,e.RewardSystem=Ee,e.RewardUI=Ye,e.SoundManager=nt,e.createDopamine=ut,e.createHaptics=rt,e.createMemoryStorage=J,e.merge=G,e.prefersReducedMotion=Ze,e.resolveStorage=Y,e.validate=z,e})({});
|
package/dist/dopamine.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { i as e, n as t, r as n, t as r } from "./host-Bhf9EqSk.js";
|
|
2
|
+
import { i, n as a, o, r as s, s as c, t as l } from "./DataService-B5noGvMr.js";
|
|
3
|
+
import { n as u, r as d, t as f } from "./SoundManager-C6VdZEFo.js";
|
|
4
|
+
import { n as p, t as m } from "./storage-C2s4Da9b.js";
|
|
5
|
+
export { l as DataService, o as DopamineError, c as EventEmitter, r as HOST_API, u as ParticleSystem, a as RewardSystem, e as RewardUI, f as SoundManager, t as createDopamine, n as createHaptics, m as createMemoryStorage, s as merge, d as prefersReducedMotion, p as resolveStorage, i as validate };
|