dracosh 0.3.0 → 0.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/src/progress.js CHANGED
@@ -52,6 +52,7 @@ export function ensureProgress(state, now = Date.now()) {
52
52
  vacations: []
53
53
  };
54
54
  state.progress.vacations ??= [];
55
+ delete state.progress.quiet; // a test build's single stretch, before quietDays
55
56
  // badges already shown in /badges; ones unlocked before this was tracked count as seen, so they don't all flash at once
56
57
  state.progress.seenBadges ??= Object.keys(state.progress.badges);
57
58
  return state.progress;
@@ -61,8 +62,35 @@ export function ensureProgress(state, now = Date.now()) {
61
62
 
62
63
  const NO_RULES = { skipWeekends: false };
63
64
 
65
+ // A day with nothing to practise: opened and nothing was waiting, or, after a day done, before the next
66
+ // card came back, whether Dracosh was opened or not. Each such stretch is kept in `quietDays` as
67
+ // { from, until } (the days strictly between); a later one never wipes an earlier one out.
68
+ const KEPT_QUIET = 30;
69
+ function nothingToDo(progress, key) {
70
+ if (progress.days?.[key]?.nothingDue) return true;
71
+ return (progress.quietDays ?? []).some((q) => key > q.from && key < q.until);
72
+ }
73
+
74
+ // The day is done and nothing comes back before `until` (a day key): the days between are rest days.
75
+ // Settling again inside a stretch moves its end, never its start.
76
+ export function markQuiet(progress, today, until) {
77
+ if (!until || until <= today) return;
78
+ const list = (progress.quietDays ??= []);
79
+ const last = list.at(-1);
80
+ if (last && today >= last.from && today < last.until) last.until = until;
81
+ else list.push({ from: today, until });
82
+ progress.quietDays = list.slice(-KEPT_QUIET);
83
+ }
84
+
85
+ // Something turned up to practise today (cards added, a deck or a direction switched on): the stretch
86
+ // it falls in ends here, so the days ahead aren't rest days any more
87
+ export function markWorkWaiting(progress, today) {
88
+ const last = progress.quietDays?.at(-1);
89
+ if (last && today >= last.from && today < last.until) last.until = today > last.from ? today : addDays(today, 1);
90
+ }
91
+
64
92
  export function isRestDay(progress, key, rules = NO_RULES) {
65
- if (progress.days?.[key]?.nothingDue) return true; // opened, but no card anywhere was waiting
93
+ if (nothingToDo(progress, key)) return true;
66
94
  if (rules.skipWeekends) {
67
95
  const weekday = new Date(`${key}T12:00:00`).getDay();
68
96
  if (weekday === 0 || weekday === 6) return true;
@@ -318,7 +346,7 @@ export function applyAnswer(state, { result, goal, rules = NO_RULES, combo = 0,
318
346
  const day = dayOf(progress, today);
319
347
  const correct = result !== "wrong";
320
348
  // full days away since the last correct answer (a wrong first answer back doesn't end the absence)
321
- const daysAway = progress.lastActiveDay ? daysBetween(progress.lastActiveDay, today) - 1 : 0;
349
+ const daysAway = awayDays(progress, today);
322
350
 
323
351
  day.asked += 1;
324
352
  day.correct += correct ? 1 : 0;
@@ -327,13 +355,22 @@ export function applyAnswer(state, { result, goal, rules = NO_RULES, combo = 0,
327
355
  return { cheers: award(state, progress, day, today, { correct, goal, rules, now, daysAway, random }) };
328
356
  }
329
357
 
358
+ // full days since the last correct answer, not counting days with nothing to practise: coming back after
359
+ // those isn't a comeback (a vacation still is)
360
+ function awayDays(progress, today) {
361
+ if (!progress.lastActiveDay) return 0;
362
+ let away = 0;
363
+ for (let key = addDays(progress.lastActiveDay, 1); key < today; key = addDays(key, 1)) if (!nothingToDo(progress, key)) away += 1;
364
+ return away;
365
+ }
366
+
330
367
  // A wrong answer the user then declared right: it was already counted as asked, so only credit the correct one
331
368
  export function applyOverrule(state, { goal, rules = NO_RULES, combo = 0, now = Date.now(), random = Math.random }) {
332
369
  const progress = ensureProgress(state, now);
333
370
  const today = dayKey(now);
334
371
  const day = dayOf(progress, today);
335
372
 
336
- const daysAway = progress.lastActiveDay ? daysBetween(progress.lastActiveDay, today) - 1 : 0;
373
+ const daysAway = awayDays(progress, today);
337
374
  day.correct += 1;
338
375
  progress.bestCombo = Math.max(progress.bestCombo ?? 0, combo);
339
376
  progress.lastActiveDay = today;
@@ -343,10 +380,12 @@ export function applyOverrule(state, { goal, rules = NO_RULES, combo = 0, now =
343
380
  // Nothing left to practise today in the whole library → cheers. After at least one right answer today
344
381
  // that counts as the goal (see award); with nothing answered at all the day only becomes a rest day, so just
345
382
  // opening Dracosh never builds a streak. Nothing happens once the goal is met.
346
- export function applyCaughtUp(state, { goal, rules = NO_RULES, now = Date.now(), random = Math.random }) {
383
+ // `nextDue`: when the next card anywhere comes back (null: none ever), so the days until then count as rest.
384
+ export function applyCaughtUp(state, { goal, rules = NO_RULES, now = Date.now(), nextDue, random = Math.random }) {
347
385
  const progress = ensureProgress(state, now);
348
386
  const today = dayKey(now);
349
387
  const day = dayOf(progress, today);
388
+ if (nextDue) markQuiet(progress, today, dayKey(nextDue));
350
389
  if (day.goalMet) return { cheers: [] };
351
390
  if (!day.asked) {
352
391
  day.nothingDue = true;
package/src/scheduler.js CHANGED
@@ -15,6 +15,24 @@ export function newToday(state, now) {
15
15
  return state.newToday?.date === dayKey(now) ? state.newToday.count : 0;
16
16
  }
17
17
 
18
+ // A review is waiting for the whole day it falls due, from midnight: a card answered at 17:00 yesterday
19
+ // can be done this morning. But never sooner than half a day after it was answered, so a sitting across
20
+ // midnight doesn't ask it again minutes later. A card just missed (streak 0) comes back at its minute.
21
+ const MIN_GAP = 12 * 60 * MINUTE;
22
+ export function readyAt(entry) {
23
+ if (!entry.streak) return entry.due;
24
+ const day = new Date(entry.due);
25
+ day.setHours(0, 0, 0, 0);
26
+ return Math.min(entry.due, Math.max(day.getTime(), (entry.last ?? 0) + MIN_GAP));
27
+ }
28
+
29
+ // the same time of day, `days` calendar days later (a day with a clock change is still one day)
30
+ function daysLater(now, days) {
31
+ const date = new Date(now);
32
+ date.setDate(date.getDate() + days);
33
+ return date.getTime();
34
+ }
35
+
18
36
  const NEW_RATIO = 0.3; // when both due and unseen items exist, this share of questions introduces a new one
19
37
  const MAX_OVERDUE_WEIGHT_DAYS = 3;
20
38
 
@@ -42,7 +60,9 @@ export function pickNext({ words, state, now = Date.now(), lastNoteId = null, di
42
60
  if (tour) return candidates.find((c) => !c.entry) ?? null;
43
61
 
44
62
  const canIntroduce = newToday(state, now) < NEW_PER_DAY;
45
- const waiting = candidates.filter((c) => (c.entry ? c.entry.due <= now : canIntroduce));
63
+ // the other way round of a card already started is no new card: the daily limit counts cards
64
+ const started = new Set(candidates.filter((c) => c.entry).map((c) => c.word.noteId));
65
+ const waiting = candidates.filter((c) => (c.entry ? readyAt(c.entry) <= now : canIntroduce || started.has(c.word.noteId)));
46
66
  if (!waiting.length) return null;
47
67
  const pool = waiting.some((c) => c.word.noteId !== lastNoteId) ? waiting.filter((c) => c.word.noteId !== lastNoteId) : waiting;
48
68
 
@@ -59,7 +79,7 @@ export function nextDueAt({ words, state, now = Date.now(), directions = DIRECTI
59
79
  for (const word of words) {
60
80
  for (const direction of word.directions ?? directions) {
61
81
  const entry = state.items[itemKey(word.noteId, direction)];
62
- const at = entry ? entry.due : startOfTomorrow(now);
82
+ const at = entry ? readyAt(entry) : startOfTomorrow(now);
63
83
  if (next === null || at < next) next = at;
64
84
  }
65
85
  }
@@ -78,7 +98,7 @@ export function grade(entry, correct, now = Date.now(), { hinted = false } = {})
78
98
  // right after a miss the card starts over at box 1 (back tomorrow) instead of skipping ahead
79
99
  const relearning = prev.seen > 0 && prev.streak === 0;
80
100
  const box = hinted || relearning ? Math.max(prev.box, 1) : Math.min(prev.box + 1, BOX_INTERVALS_DAYS.length);
81
- return { ...prev, box, due: now + BOX_INTERVALS_DAYS[box - 1] * DAY, seen: prev.seen + 1, correct: prev.correct + 1, streak: prev.streak + 1, last: now };
101
+ return { ...prev, box, due: daysLater(now, BOX_INTERVALS_DAYS[box - 1]), seen: prev.seen + 1, correct: prev.correct + 1, streak: prev.streak + 1, last: now };
82
102
  }
83
103
  return { ...prev, box: 1, due: now + RELEARN_DELAY, seen: prev.seen + 1, wrong: prev.wrong + 1, streak: 0, last: now };
84
104
  }
package/src/session.js CHANGED
@@ -1,27 +1,35 @@
1
1
  import { t as say } from "./i18n.js"; // `t` and `text` are taken here (the clock, an answer)
2
- import { blankGap } from "./cardline.js";
3
- import { closestCandidate, judge } from "./judge.js";
4
- import { addVacation, applyAnswer, applyCaughtUp, applyOverrule, calendarMonth, cancelVacations, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
5
- import { describeDue, grade, itemKey, nextDueAt, pickNext, startOfTomorrow } from "./scheduler.js";
2
+ import { blankGap, plainFront } from "./cardline.js";
3
+ import { ALMOST, closestCandidate, judge } from "./judge.js";
4
+ import { addVacation, applyAnswer, applyCaughtUp, markWorkWaiting, applyOverrule, calendarMonth, cancelVacations, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
5
+ import { BOX_INTERVALS_DAYS, describeDue, grade, itemKey, nextDueAt, pickNext, startOfTomorrow } from "./scheduler.js";
6
6
  import { recordAnswer, saveState } from "./store.js";
7
7
  import { createTipDeck } from "./tips.js";
8
8
  import { dayKey } from "./dates.js";
9
9
  import { parsePause } from "./pause.js";
10
10
  import { formatRange } from "./vacation.js";
11
11
 
12
- const LABELS = { "en-pl": "EN → PL", "pl-en": "PL → EN" };
13
12
 
14
- // the tag on the card's border: the language pair for a language deck, the deck's name otherwise
15
- function labelOf(deck, direction) {
16
- if (!deck) return LABELS[direction] ?? "";
17
- if (direction.startsWith("c")) return deck.name; // a cloze gap: no direction to show
18
- if (!deck.languages) return deck.name;
19
- const { front, back } = deck.languages;
20
- const [from, to] = direction === "en-pl" ? [front, back] : [back, front];
21
- return `${from.toUpperCase()} → ${to.toUpperCase()}`;
13
+ // the tag on the card's border: the deck's name (language codes like "DE → UK" read as countries)
14
+ function labelOf(deck) {
15
+ return deck?.name ?? "";
22
16
  }
23
17
  const COMBO_CHEER_EVERY = 5;
24
18
 
19
+ // Pronunciation reads the side in the language you're learning in this deck (learningSide), whichever way
20
+ // the card asks: the answer (a cloze card: its whole sentence), or the question. Nothing in a deck that
21
+ // isn't for a language. `answer`: the right answer you gave (one of several), read instead of the first.
22
+ export function toSpeak(question, answer = null) {
23
+ const lang = question.learningLanguage;
24
+ if (question.tour || !lang) return null;
25
+ const cloze = question.direction.startsWith("c");
26
+ const given = answer && question.expected.includes(answer) ? answer : question.expected[0];
27
+ if (question.answerLanguage === lang) return { text: cloze ? plainFront(question.word.word) : given, lang };
28
+ // a cloze card's prompt is its sentence with a gap: nothing to read there
29
+ if (!cloze && question.promptLanguage === lang) return { text: question.prompt.split(" / ")[0], lang };
30
+ return null;
31
+ }
32
+
25
33
  // Quiz logic without any I/O of its own: words, settings and persistence are injected, the UI only renders what this returns.
26
34
  // `loadAllWords` → [{ words, deck }] for every deck of yours: "all done for today" means the whole library.
27
35
  export function createSession({ loadWords, loadAllWords, state, getSettings, save = saveState, now = Date.now, tipDeck = createTipDeck({ state }) }) {
@@ -36,13 +44,18 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
36
44
  async function settleDay() {
37
45
  const decks = loadAllWords ? await loadAllWords() : [current].filter((d) => !d.deck?.tour);
38
46
  const t = now();
47
+ let nextDue = null;
39
48
  for (const { words, deck } of decks) {
40
49
  const directions = directionsOf(deck);
41
- if (pickNext({ words, state, now: t, directions })) return { done: false, cheers: [] };
50
+ if (pickNext({ words, state, now: t, directions })) {
51
+ markWorkWaiting(ensureProgress(state, t), dayKey(t));
52
+ return { done: false, cheers: [] };
53
+ }
42
54
  const due = nextDueAt({ words, state, now: t, directions });
43
55
  if (due !== null && due < startOfTomorrow(t)) return { done: false, cheers: [] };
56
+ if (due !== null && (nextDue === null || due < nextDue)) nextDue = due;
44
57
  }
45
- const { cheers } = applyCaughtUp(state, { goal: getSettings().dailyGoal, rules: rules(), now: t });
58
+ const { cheers } = applyCaughtUp(state, { goal: getSettings().dailyGoal, rules: rules(), now: t, nextDue });
46
59
  await save(state);
47
60
  return { done: true, cheers };
48
61
  }
@@ -59,10 +72,13 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
59
72
  current = { words, deck };
60
73
  inTour = Boolean(deck?.tour);
61
74
  const item = pickNext({ words, state, now: now(), lastNoteId, directions: directionsOf(deck), tour: deck?.tour });
75
+ if (item && !deck?.tour) markWorkWaiting(ensureProgress(state, now()), dayKey(now())); // not a rest day after all
62
76
  // nothing to ask is a normal state, not an error: the UI shows a way on (a finished tour, a new
63
77
  // deck) or when the next card is due. Done with everything for today counts as the daily goal.
64
78
  if (!item) {
65
- const empty = { empty: true, tour: Boolean(deck?.tour), count: words.length, nextDue: null, cheers: [], dayDone: false };
79
+ // new cards held back by the daily limit, so "all done" doesn't hide them
80
+ const heldNew = deck?.tour ? 0 : words.filter((word) => !(word.directions ?? directionsOf(deck)).some((d) => state.items[itemKey(word.noteId, d)])).length;
81
+ const empty = { empty: true, tour: Boolean(deck?.tour), count: words.length, nextDue: null, cheers: [], dayDone: false, heldNew };
66
82
  if (!deck?.tour && words.length) {
67
83
  empty.nextDue = nextDueAt({ words, state, now: now(), directions: directionsOf(deck) });
68
84
  const day = await settleDay();
@@ -86,11 +102,15 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
86
102
  return {
87
103
  word: item.word,
88
104
  direction: item.direction,
89
- label: labelOf(deck, item.direction),
105
+ label: labelOf(deck),
90
106
  prompt,
91
107
  expected,
92
108
  // a cloze card's back is a hint under the sentence ("Cieszę się na to")
93
109
  context: gap !== null ? item.word.translations.join(" / ") : "",
110
+ // what the answer is written in, when the deck's languages are known: its own spellings count
111
+ answerLanguage: (forward ? deck?.languages?.back : deck?.languages?.front) ?? null,
112
+ promptLanguage: (forward ? deck?.languages?.front : deck?.languages?.back) ?? null,
113
+ learningLanguage: deck?.learning?.lang ?? null,
94
114
  wordCount: words.length,
95
115
  tour: Boolean(deck?.tour) // the tour marks what to type with `backticks`
96
116
  };
@@ -107,7 +127,7 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
107
127
  async function answer(question, text, { hinted = false } = {}) {
108
128
  const key = itemKey(question.word.noteId, question.direction);
109
129
  // answers you once declared right (/correct) count for this card from now on
110
- const result = judge(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
130
+ const result = judge(text, [...question.expected, ...(state.accepted?.[key] ?? [])], { lang: question.answerLanguage, otherLang: question.promptLanguage, learning: question.learningLanguage ?? null });
111
131
  return record(question, { result, text, hinted });
112
132
  }
113
133
 
@@ -126,7 +146,11 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
126
146
  const t = now();
127
147
  const before = state.items[key];
128
148
  const comboBefore = totals.combo;
129
- const entry = grade(before, correct, t, { hinted });
149
+ // almost right (an article left out, an umlaut left plain) counts, but the card doesn't move up, like with a hint
150
+ const almost = ALMOST.includes(result);
151
+ const entry = grade(before, correct, t, { hinted: hinted || almost });
152
+ const would = almost ? grade(before, true, t, { hinted }) : entry; // a hint alone would have held it too
153
+ const held = would.box > entry.box ? { days: BOX_INTERVALS_DAYS[entry.box - 1], would: BOX_INTERVALS_DAYS[would.box - 1] } : null;
130
154
  recordAnswer(state, question.word.noteId, question.direction, entry, t, { countNew: !question.tour });
131
155
 
132
156
  totals.asked += 1;
@@ -145,8 +169,8 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
145
169
  // the last card of the day settles it right away, so quitting now doesn't lose the goal
146
170
  if (!question.tour) cheers.push(...(await settleDay()).cheers);
147
171
  // given/closest feed the per-letter diff the UI shows after a miss or a forgiven typo
148
- const closest = result === "exact" || !text ? null : closestCandidate(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
149
- return { result, hinted: hinted && correct, dueIn: describeDue(entry, t), combo: totals.combo, cheers, given: text, closest, nextDue: upNext() };
172
+ const closest = result === "exact" || !text ? null : closestCandidate(text, [...question.expected, ...(state.accepted?.[key] ?? [])], { lang: question.answerLanguage });
173
+ return { result, held, hinted: hinted && correct, dueIn: describeDue(entry, t), combo: totals.combo, cheers, given: text, closest, nextDue: upNext() };
150
174
  }
151
175
 
152
176
  // Re-grade the last wrong answer as correct and remember the answer for this card.
@@ -273,5 +297,13 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
273
297
  return fresh;
274
298
  }
275
299
 
276
- return { totals, next, answer, reveal, selfGrade, setDirections, forgetKeys, overrule, canOverrule, wrongAnswer, stats, month, missed, nextTip, pause, isFirstRun, markHatched, openBadges, forget, reset, inTour: () => inTour };
300
+ // cards added (or a direction switched on): there's work today, whether or not it's asked yet, so a
301
+ // quiet stretch ends here
302
+ async function workAdded() {
303
+ markWorkWaiting(ensureProgress(state, now()), dayKey(now()));
304
+ await save(state);
305
+ await settleDay(); // nothing askable after all (a direction switched off): the quiet stretch goes on
306
+ }
307
+
308
+ return { totals, next, answer, workAdded, reveal, selfGrade, setDirections, forgetKeys, overrule, canOverrule, wrongAnswer, stats, month, missed, nextTip, pause, isFirstRun, markHatched, openBadges, forget, reset, inTour: () => inTour };
277
309
  }
package/src/settings.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { LANGUAGES, systemLanguage, t } from "./i18n.js";
2
2
 
3
- export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null };
3
+ export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null };
4
4
 
5
5
  export const INTERVALS = [60_000, 120_000, 300_000, 600_000, 900_000, 1_200_000, 1_800_000, 2_700_000, 3_600_000];
6
6
  export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
@@ -33,6 +33,7 @@ export function normalizeSettings(raw = {}) {
33
33
  everyMs: isNumber(raw.everyMs) && raw.everyMs >= 1000 ? raw.everyMs : DEFAULTS.everyMs,
34
34
  rhythm: RHYTHMS.includes(raw.rhythm) ? raw.rhythm : DEFAULTS.rhythm,
35
35
  sound: typeof raw.sound === "boolean" ? raw.sound : DEFAULTS.sound,
36
+ speak: typeof raw.speak === "boolean" ? raw.speak : DEFAULTS.speak,
36
37
  volume: isNumber(raw.volume) && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
37
38
  dailyGoal: isNumber(raw.dailyGoal) && raw.dailyGoal >= 1 ? Math.round(raw.dailyGoal) : DEFAULTS.dailyGoal,
38
39
  tips: normalizeTips(raw.tips),
package/src/sqlite.js ADDED
@@ -0,0 +1,28 @@
1
+ import * as zlib from "node:zlib";
2
+
3
+ // What Anki packages need from Node: its built-in SQLite (node:sqlite, there without a flag since
4
+ // 22.13) and zstd (22.15), which newer Anki packages are compressed with. Node 22 and 24 still print
5
+ // "SQLite is an experimental feature" when it loads, which tells someone moving a deck nothing, so
6
+ // that one warning is left out. Any other warning still shows.
7
+ export const ANKI_NODE = "22.15";
8
+
9
+ const needsNode = () => Object.assign(new Error(`Anki packages need Node ${ANKI_NODE}`), { code: "NEEDS_NODE", version: ANKI_NODE });
10
+
11
+ export async function loadSqlite() {
12
+ if (typeof zlib.zstdDecompressSync !== "function") throw needsNode();
13
+ const emitWarning = process.emitWarning;
14
+ process.emitWarning = function (warning, ...rest) {
15
+ const type = typeof rest[0] === "string" ? rest[0] : rest[0]?.type;
16
+ if (type === "ExperimentalWarning" && String(warning?.message ?? warning).includes("SQLite")) return;
17
+ return emitWarning.call(this, warning, ...rest);
18
+ };
19
+ try {
20
+ return await import("node:sqlite");
21
+ } catch (err) {
22
+ throw err.code === "ERR_UNKNOWN_BUILTIN_MODULE" ? needsNode() : err;
23
+ } finally {
24
+ process.emitWarning = emitWarning;
25
+ }
26
+ }
27
+
28
+ export const unzstd = (buffer) => zlib.zstdDecompressSync(buffer);
package/src/store.js CHANGED
@@ -61,8 +61,15 @@ export const saveLibrary = (library) => writeJson(LIBRARY_FILE, library);
61
61
  export async function loadState() {
62
62
  const state = await readJson(STATE_FILE, undefined);
63
63
  if (state === undefined) return emptyState();
64
- if (!isObject(state) || !isObject(state.items)) throw damaged(STATE_FILE, t("errors.why.noProgress"));
65
- if (!Object.values(state.items).every((entry) => isObject(entry) && Number.isFinite(entry.box) && Number.isFinite(entry.due))) throw damaged(STATE_FILE, t("errors.why.progressEntry"));
64
+ checkState(state, STATE_FILE);
65
+ if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
66
+ return state;
67
+ }
68
+
69
+ // throws when `state` (read from `file`) isn't progress the quiz can use
70
+ export function checkState(state, file = STATE_FILE) {
71
+ if (!isObject(state) || !isObject(state.items)) throw damaged(file, t("errors.why.noProgress"));
72
+ if (!Object.values(state.items).every((entry) => isObject(entry) && Number.isFinite(entry.box) && Number.isFinite(entry.due))) throw damaged(file, t("errors.why.progressEntry"));
66
73
  const { progress } = state;
67
74
  const validProgress =
68
75
  isObject(progress) &&
@@ -72,17 +79,16 @@ export async function loadState() {
72
79
  ["count", "best", "freezes"].every((key) => Number.isFinite(progress.streak[key])) &&
73
80
  isObject(progress.badges) &&
74
81
  (progress.vacations === undefined || Array.isArray(progress.vacations));
75
- if (progress !== undefined && !validProgress) throw damaged(STATE_FILE, t("errors.why.streak"));
76
- if (state.version > STATE_VERSION) throw new Error(t("errors.newerState", { file: STATE_FILE }));
77
- if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
78
- return state;
82
+ if (progress !== undefined && !validProgress) throw damaged(file, t("errors.why.streak"));
83
+ if (state.version > STATE_VERSION) throw new Error(t("errors.newerState", { file }));
79
84
  }
80
85
  export const saveState = (state) => writeJson(STATE_FILE, state);
81
86
 
82
87
  // `countNew: false` keeps a card out of the daily cap on new cards (the tour's don't use it up)
83
88
  export function recordAnswer(state, noteId, direction, entry, now = Date.now(), { countNew = true } = {}) {
84
89
  const key = itemKey(noteId, direction);
85
- const isNew = countNew && !state.items[key];
90
+ // a new card counts once towards the daily limit, whichever way it's asked first
91
+ const isNew = countNew && !state.items[key] && !Object.keys(state.items).some((k) => k.startsWith(`${noteId}:`));
86
92
  const date = dayKey(now);
87
93
  state.items[key] = entry;
88
94
  if (isNew) state.newToday = { date, count: newToday(state, now) + 1 };