dopaminejs 3.3.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -1,10 +1,10 @@
1
- import { n as e, s as t } from "./DataService-Bd1S-C1N.js";
2
- import { n } from "./host-CSnyl6nv.js";
1
+ import { n as e } from "./host-_essSMef.js";
2
+ import { n as t, s as n } from "./DataService-QQBNqJtN.js";
3
3
  import { describe as r, it as i } from "vitest";
4
4
  import { existsSync as a, readFileSync as o, readdirSync as s } from "node:fs";
5
5
  import { dirname as c, join as l, resolve as u } from "node:path";
6
6
  import { fileURLToPath as d } from "node:url";
7
- //#region src/testing.js
7
+ // src/testing.js
8
8
  var f = {
9
9
  xp_gained: {
10
10
  amount: 10,
@@ -34,7 +34,8 @@ var f = {
34
34
  },
35
35
  player_reset: {},
36
36
  save_failed: { error: /* @__PURE__ */ Error("save failed") },
37
- load_failed: { reason: "corrupt" }
37
+ load_failed: { reason: "corrupt" },
38
+ load_recovered: { key: "player" }
38
39
  }, p = [
39
40
  "confetti",
40
41
  "sparkle",
@@ -69,21 +70,21 @@ function y(e) {
69
70
  clock: e,
70
71
  move: () => _("this clock is not a test clock, it cannot advance")
71
72
  };
72
- let n = e === void 0 ? "2026-01-15T09:00:00" : e;
73
- (typeof n != "string" || !g.test(n)) && _("clock must be YYYY-MM-DDTHH:MM:SS local time");
74
- let r = new Date(n).getTime();
73
+ let t = e === void 0 ? "2026-01-15T09:00:00" : e;
74
+ typeof t == "string" && g.test(t) || _("clock must be YYYY-MM-DDTHH:MM:SS local time");
75
+ let r = new Date(t).getTime();
75
76
  return {
76
77
  clock: {
77
78
  now: () => r,
78
- localDate: (e = r) => t.localDate(e)
79
+ localDate: (e = r) => n.localDate(e)
79
80
  },
80
81
  move: (e) => {
81
82
  r = e(r);
82
83
  }
83
84
  };
84
85
  }
85
- function b(t = {}) {
86
- let { clock: r, storage: i, parts: a = {}, ...o } = t || {}, { clock: s, move: c } = y(r), l = [], u = [], d = [], f = [], p = [], m = /* @__PURE__ */ new Set(), h = [], v = {
86
+ function b(n = {}) {
87
+ let { clock: r, storage: i, parts: a = {}, ...o } = n || {}, { clock: s, move: c } = y(r), l = [], u = [], d = [], f = [], p = [], m = /* @__PURE__ */ new Set(), h = [], v = {
87
88
  ui: () => ({
88
89
  root: null,
89
90
  hud: (e) => {
@@ -130,10 +131,10 @@ function b(t = {}) {
130
131
  })
131
132
  }, b = {};
132
133
  for (let e of Object.keys(v)) b[e] = Object.prototype.hasOwnProperty.call(a, e) ? a[e] : v[e]();
133
- let x = n({
134
+ let x = e({
134
135
  ...o,
135
136
  ...b,
136
- storage: i || e(),
137
+ storage: i || t(),
137
138
  clock: s,
138
139
  log: {
139
140
  warn: () => {},
@@ -471,5 +472,4 @@ function L(e) {
471
472
  suites: i
472
473
  };
473
474
  }
474
- //#endregion
475
475
  export { P as conformance, F as conformanceFailures, b as createTestHost, L as loadFixtures };
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "dopaminejs",
3
- "version": "3.3.0",
3
+ "version": "3.5.0",
4
4
  "description": "Progression mechanics for web apps: XP, levels, achievements and timezone-correct daily streaks, with the particles and sound to make them land. Zero dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/dopamine.cjs",
7
7
  "module": "./dist/dopamine.js",
8
+ "unpkg": "./dist/dopamine.global.js",
9
+ "jsdelivr": "./dist/dopamine.global.js",
8
10
  "exports": {
9
11
  ".": {
10
12
  "types": "./types/index.d.ts",
@@ -38,7 +40,7 @@
38
40
  ],
39
41
  "scripts": {
40
42
  "dev": "vite",
41
- "build": "vite build",
43
+ "build": "vite build && vite build --config vite.config.iife.js",
42
44
  "test": "vitest run",
43
45
  "test:watch": "vitest",
44
46
  "preview": "vite preview"
package/spec/README.md CHANGED
@@ -29,7 +29,7 @@ caught up goes red.
29
29
  | `clock` | Required. Start time, local `YYYY-MM-DDTHH:MM:SS`. No offset. |
30
30
  | `config` | Optional. See below. |
31
31
  | `device` | Optional. A device id stored before `init`, so the document has known keys. Without it a random id is made. |
32
- | `storage` | Optional. `{ "failWrites": true }` makes every storage write throw, to exercise `save_failed`. Reads still work and `savedJson`/`savedRaw` are seeded first. |
32
+ | `storage` | Optional. `{ "failWrites": true }` makes every storage write throw, to exercise `save_failed`. `{ "failReads": N }` makes the first N reads of the player throw, to exercise `load_failed` with reason `read` and the retry. `{ "failDeviceReads": N }` does the same for the first N reads of the device id, and `{ "failDeviceWrites": true }` makes every write of the device id throw. The count lasts for the whole case, so a `reload` reads normally once it is used up. Writes and other reads work, and `savedJson`/`savedRaw` are seeded first. |
33
33
  | `savedJson` | Optional. Any JSON value, stored as `JSON.stringify(value)`. |
34
34
  | `savedRaw` | Optional. A string stored as is, for corrupt data. |
35
35
  | `afterInit` | Optional. Expectation checked after the first `init`. |
@@ -64,6 +64,7 @@ UTC.
64
64
  takes it as `RewardSystem` config. A save that already holds a built-in keeps
65
65
  it and its reward XP when the option is off.
66
66
  - `streakDays`: `"any"` (default) or `"record"`. With `any`, `record` and `addXP` mark today as a play day. With `record`, only `record` does. XP from an achievement reward never marks a day.
67
+ - `loadRetryMs`: a number of 0 or more. After a failed read, a blocked save retries the read at most this often, measured on the case clock. Default 30000. See "After a failed read".
67
68
  - `achievements`: extra achievements by id, `{ name, description?, icon?, xp?, when }`.
68
69
 
69
70
  `when` replaces the check function. One of:
@@ -94,12 +95,14 @@ except for `setClock`, where it is accepted and checked if present.
94
95
  | op | args | Does |
95
96
  |---|---|---|
96
97
  | `setClock` | `at` | Moves the clock. |
98
+ | `init` | none | Calls `init` again on the same reward system, like a retry after a failed read. |
99
+ | `failReads` | `count` | The next `count` reads of the player throw. No `expect`. |
97
100
  | `reload` | `device?` | Builds a new reward system on the same storage and runs `init`, like a page load. `device` stores a new device id first, as a second device sharing the save. |
98
101
  | `addXP` | `amount`, `reason?` | `addXP(amount, reason)`. |
99
102
  | `record` | `activity`, `result?` | `record(activity, result)`. A missing `result` means the default. `null` is passed as `null`. Returns `true`. |
100
103
  | `unlockAchievement` | `id` | `unlockAchievement(id)`. |
101
104
  | `markAchievementsSeen` | `ids` | `markAchievementsSeen(ids)`. |
102
- | `reset` | `overwrite?` | `reset({ overwrite })`, or `reset()` when `overwrite` is missing. Replaces the player with an empty document, keeps the device id, saves, and returns the new snapshot. Fires `player_reset` after the save. With `overwrite` false and a failed load, nothing is saved: the stored document stays as it was and later writes stay blocked. After a load that worked, `overwrite` false saves like a plain reset. |
105
+ | `reset` | `overwrite?` | `reset({ overwrite })`, or `reset()` when `overwrite` is missing. Replaces the player with an empty document, keeps the device id, saves, and returns the new snapshot. Fires `player_reset` after the save. With `overwrite` false and a failed load, nothing is saved: the stored document stays as it was and a later write may retry the read and merge the new session into whatever it returns. After a load that worked, `overwrite` false saves like a plain reset. |
103
106
  | `getXPForNextLevel` | none | Reads `{ total, needed, progress }`. |
104
107
  | `export` | `as` | `export()`. Keeps the document under the name `as`. |
105
108
  | `import` | `doc` or `from`, `silent?` | `import(doc, { silent })`. `from` names a kept document. Returns the snapshot. Achievement ids with no definition are kept but fire no event. |
@@ -123,6 +126,7 @@ Events are collected from the start of each step (and from construction for
123
126
  | `doc` | Subset match against `export()`, the saved document. |
124
127
  | `docExact` | Like `playerExact`, against `export()`. |
125
128
  | `absent` | Dotted paths under the snapshot that must not exist as own keys. |
129
+ | `docAbsent` | Dotted paths under `export()` that must not exist as own keys. |
126
130
  | `achievements` | Ids in `player.achievements`, as a set. |
127
131
  | `events` | The complete ordered list of events since the step began. Each is `{ "event": name, ...payload fields }`, matched as a subset. The list length must match. |
128
132
  | `returns` | Subset match against the operation's return value. |
@@ -131,7 +135,7 @@ Events are collected from the start of each step (and from construction for
131
135
  | `throws` | An error with this name (`TypeError`, `DopamineError`) is raised. State checks still run afterwards. |
132
136
  | `code` | With `throws`: the `code` of the `DopamineError`. |
133
137
 
134
- An empty `player`, `playerExact`, `doc`, `docExact`, `returns`, `returnsExact` or `absent`, or an empty `expect`,
138
+ An empty `player`, `playerExact`, `doc`, `docExact`, `returns`, `returnsExact`, `absent` or `docAbsent`, or an empty `expect`,
135
139
  is an error because it checks nothing. An empty `events` or `achievements`
136
140
  list is a real check (nothing fired, nothing unlocked).
137
141
 
@@ -144,10 +148,11 @@ CI also runs the conformance file once in `America/Los_Angeles`
144
148
  (`DOPAMINE_TEST_TZ`), so the daylight saving case can fail.
145
149
 
146
150
  Event names: `xp_gained`, `level_up`, `achievement_unlocked`, `personal_best`
147
- (payload `{ activity, score }`), `streak_updated`, `player_reset` (empty payload), `save_failed` and
148
- `load_failed`. `load_failed` is covered for a corrupt value and for a document
151
+ (payload `{ activity, score }`), `streak_updated`, `player_reset` (empty payload), `save_failed`,
152
+ `load_failed` and `load_recovered` (payload `{ key }`). `load_failed` is covered for a corrupt value, for a document
149
153
  the core refuses (`reason` is `corrupt`, `unsupported_version` or
150
- `too_many_devices`). A read that fails in storage cannot be made by a fixture.
154
+ `too_many_devices`) and for a read that fails in storage (`reason: 'read'`, made with `storage.failReads`). A saved value that is valid JSON but not an object counts as corrupt, and is kept
155
+ under `player_corrupt`.
151
156
 
152
157
  Payloads are frozen copies, and `snapshot()` is a frozen deep copy.
153
158
 
@@ -158,7 +163,7 @@ Fixture paths use `.` as the separator, so keys in fixtures contain no dots.
158
163
 
159
164
  1. Load every `spec/fixtures/*.json`.
160
165
  2. For each case, build a clock at the local time given, seed storage,
161
- construct the system with the config and the clock, subscribe to the seven
166
+ construct the system with the config and the clock, subscribe to the nine
162
167
  events, run `init`.
163
168
  3. Check `afterInit`, then run each step and check its `expect`.
164
169
  4. Fail on any unknown op, step key, expectation key or condition. A fixture
@@ -183,6 +188,7 @@ a save join by taking the larger number per key. That is what `merge` does.
183
188
  | `achievements` | Union. The earliest `unlockedAt` decides the entry and its stored `reward`. `seen` is true if either side has it true. |
184
189
  | `name` | From the side with the later `lastPlayedAt`, ties take the larger string. |
185
190
  | `createdAt`, `lastPlayedAt` | Min of the set values, max. |
191
+ | Any other top level field | One side only: kept. Both: the larger number if both are finite numbers, else the larger canonical JSON text. No recency. |
186
192
 
187
193
  XP is derived: the sum of `xpBy`, plus the stored `reward` of every unlocked
188
194
  achievement, minus the sum of `xpSpentBy`, and not below 0. An achievement's
@@ -196,7 +202,79 @@ More than 20 devices across the per-device maps is refused with a
196
202
  write: `addXP` and `record` leave the stored save alone and publish `load_failed`
197
203
  with reason `too_many_devices`. A document with a `v` other than 3 is refused
198
204
  with `unsupported_version`. A value that is not an object is `invalid_document`. Counters and sums stop at
199
- `Number.MAX_SAFE_INTEGER`.
205
+ `Number.MAX_SAFE_INTEGER`. A negative or non-finite value in a map (`xpBy`, `sumsBy` and the rest) is dropped.
206
+
207
+ ### After a failed read
208
+
209
+ When the read of the saved player fails (`load_failed` with reason `read`), the
210
+ session starts with an empty player and saving is off, so the real player is
211
+ never replaced. Progress made in that session is kept for the real player:
212
+
213
+ - Before a blocked save, the core retries the read, at most once per
214
+ `loadRetryMs` (default 30000) of the clock. The failed read at `init` counts as
215
+ the last read. Nothing is read on a save that is not blocked.
216
+ - The retry only succeeds when the read works and the value is a player that
217
+ `validate` accepts, or nothing is saved. A value that is not an object, a
218
+ `v` other than 3, a value that is not valid JSON, a document that would hold more than 20 devices once merged,
219
+ and a read that fails again all leave saving off and the session as it is. They
220
+ fire no event.
221
+ - On success the session player is merged into the saved one, saved, `loadFailed`
222
+ goes back to false and `load_recovered` fires after the write. The merge is not
223
+ the plain `merge`, because the session started empty: its counters for this
224
+ device are new progress.
225
+
226
+ | Field | Rule after a retry |
227
+ |---|---|
228
+ | `xpBy`, `xpSpentBy`, `gamesBy`, `playsBy`, `sumsBy` | This device's entries are added (saved plus session). Other devices' entries are the max, as in `merge`. |
229
+ | `best` | Max. |
230
+ | `level` | Max, and never below the curve for the merged XP. |
231
+ | `longest` | Max. |
232
+ | `playDates` | Union. The streak is derived from it, so it counts from the saved last play date and today's visit is one day, or none when the saved player already has today. |
233
+ | `achievements` | As in `merge`. The earliest `unlockedAt` and its `reward` win, `seen` is true if either has it, and a reward counts once. |
234
+ | `name` | The saved player's. |
235
+ | Unknown top level fields | The saved player's, as read. |
236
+ | `createdAt`, `lastPlayedAt` | As in `merge`. |
237
+
238
+ Everything read goes through `validate`, and achievement ids are looked up by own
239
+ property. If the device id could not be read at `init`, the retry reads it again
240
+ and moves the session's entries under the stored id, so no second device is made.
241
+ `fixtures/recovery.json` pins these rules.
242
+
243
+ Only the write that starts a retry waits for it. A second `addXP` or `record`
244
+ that lands while the read is in flight returns at once, writes nothing and
245
+ starts no other read. A read that never settles therefore stalls only the call
246
+ that started it. The session is merged as it stands when the read returns.
247
+
248
+ An `import` while the read is failed counts as known progress, not a gain, for
249
+ this device's counters. The core remembers the imported counters as a baseline,
250
+ so after a retry each of this device's counters is
251
+ `max(saved, imported) + (session - imported)`. A backup of this device that is
252
+ ahead of the saved player is kept, and the backup is never added twice. An
253
+ import at or below what the session already holds for a counter changes nothing,
254
+ so importing the session's own `export()` does not count it twice. An `init()`
255
+ that fails after one that worked treats the player it loaded as the baseline,
256
+ because that progress is already stored. If the device id is only found at the
257
+ retry and the session already holds entries under that stored id (from an
258
+ import, or from a player the session read), the core cannot tell them from new
259
+ gains and moving them would count them twice, so the retry fails closed:
260
+ nothing is saved and the session stays blocked. A session holding no entries
261
+ under the stored id, including one that only imported nothing, zeros or other
262
+ devices, recovers. The way out of a blocked session is `reset({ overwrite: false })`,
263
+ which drops the session and keeps the stored player. `init()` is the other
264
+ way, and it stays blocked if its read fails again. `reset()` with no option
265
+ replaces the stored player with an empty one and keeps no backup.
266
+ `init()` that reads, `reset()` and a recovery forget the baseline.
267
+
268
+ The `xp_gained` event and the return value of the `addXP` that recovers describe
269
+ the merged player when the call is a direct `addXP` (`record` reports its batch total as before): `total`, `newLevel` and `leveledUp` come from it, and
270
+ `level_up` fires only when this gain raises the merged level, compared with the merged player before the gain. A player who was already at that level gets no `level_up`.
271
+
272
+ `init()` called again behaves as before: it reads, and on success replaces the
273
+ session player with the saved one.
274
+
275
+ Two tabs: each tab merges its own session once. The second tab reads what the
276
+ first saved, so nothing is lost and each session's progress is added once, but
277
+ nothing links the two sessions. This is a known limit.
200
278
 
201
279
  ### From 2.x
202
280
 
@@ -206,7 +284,10 @@ unlocked, so the legacy entry is the old `xp` minus those rewards, not below 0.
206
284
  Two devices that read the same 2.x save get the same entries and merge without
207
285
  doubling. 2.x progress made separately on two devices before migration merges
208
286
  by max, not by sum. `playDates` is rebuilt from `streak.current` and
209
- `streak.lastPlayDate`. A level above the curve is kept.
287
+ `streak.lastPlayDate`. A level above the curve is kept. A `lastPlayDate` after
288
+ today counts as today, so a clock change keeps the streak. One that is not a
289
+ real day counts as no date: there is no current run, and the larger of
290
+ `current` and `longest` stays as `longest`.
210
291
 
211
292
  ## Quirks pinned on purpose
212
293
 
@@ -218,11 +299,30 @@ rule change and needs a fixture change.
218
299
  `streak_updated` for a player with no earlier play. Loading a save counts no
219
300
  day.
220
301
  - Only `record` marks a day as played. `addXP` does not.
221
- - Numbers must be finite numbers. A numeric string is dropped to the default.
302
+ - A number is a finite number, or a plain decimal string (`"250"`, `" 12 "`,
303
+ `"-1.5"`) in every field that expects a number. Counts must also be whole and
304
+ none may be negative. Anything else falls back to the default: a blank
305
+ string, `"Infinity"`, `"0x10"`, `"0b11"`, `"0o7"`, `"1e3"`, `"+5"`, `"5."`
306
+ and any other text.
222
307
  - Dates must be real calendar days. `9999-99-99` and `2026-02-30` are dropped.
223
- - A play date after today is kept and ignored for the current streak.
224
- - Fields the core does not know are not carried.
225
- - `__proto__`, `constructor` and `prototype` are never kept as a key.
226
- - Achievement ids the core does not define are kept.
308
+ - A play date after today is kept and ignored for the current streak. In a 2.x
309
+ save, `streak.lastPlayDate` after today counts as today.
310
+ - Fields the core does not know are kept as read, at the top level of the
311
+ document, and are not part of the player view. Intended: a newer version
312
+ wrote them, and dropping them loses data. `merge` joins them by a fixed
313
+ rule. A field on one side only is kept. On both sides, two finite numbers
314
+ keep the larger value, and anything else keeps the one with the larger
315
+ canonical JSON text (keys sorted). Recency is not used: no field has its own
316
+ timestamp, and a rule based on `lastPlayedAt` gives a different result
317
+ depending on how three saves are grouped. The rule above is the same in any
318
+ order, any grouping and when repeated.
319
+ - `__proto__`, `constructor` and `prototype` are never kept as a key, at the
320
+ top level or inside a kept value.
321
+ - Achievement ids the core does not define are kept. Intended: a mod or a
322
+ newer version may define them, so dropping one loses a real unlock.
323
+ - A 2.x streak of 0 with a real date counts that date as one play day. Intended:
324
+ no play is lost, so the same day gives 1 and the next day gives 2.
325
+ - `load_recovered` fires after the merged player is written. If that write fails,
326
+ `save_failed` fires too and the merged player stays in memory.
227
327
  - Extra numbers in a `record` result add up per device. A value that is not a
228
328
  positive finite number adds 0.