dracosh 0.1.0 → 0.2.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.
Files changed (51) hide show
  1. package/README.md +42 -20
  2. package/assets/sounds/badge-1.wav +0 -0
  3. package/assets/sounds/badge-2.wav +0 -0
  4. package/assets/sounds/badge-3.wav +0 -0
  5. package/assets/sounds/badge-4.wav +0 -0
  6. package/data/tips.json +31 -1361
  7. package/package.json +1 -1
  8. package/src/alerts.js +4 -3
  9. package/src/backup.js +95 -0
  10. package/src/cli.js +97 -16
  11. package/src/commands.js +7 -7
  12. package/src/judge.js +33 -12
  13. package/src/library.js +127 -0
  14. package/src/lock.js +63 -0
  15. package/src/manage.js +75 -0
  16. package/src/pause.js +23 -0
  17. package/src/progress.js +145 -53
  18. package/src/quiet.js +1 -1
  19. package/src/scheduler.js +38 -26
  20. package/src/session.js +128 -30
  21. package/src/settings.js +4 -9
  22. package/src/starter.js +38 -0
  23. package/src/store.js +55 -16
  24. package/src/tips.js +7 -24
  25. package/src/ui/AddCard.js +172 -0
  26. package/src/ui/AnswerInput.js +8 -5
  27. package/src/ui/App.js +211 -71
  28. package/src/ui/BadgeUnlock.js +50 -0
  29. package/src/ui/Badges.js +75 -17
  30. package/src/ui/Choice.js +33 -0
  31. package/src/ui/Companion.js +20 -35
  32. package/src/ui/Decks.js +49 -0
  33. package/src/ui/DieRoll.js +104 -0
  34. package/src/ui/Evolution.js +6 -5
  35. package/src/ui/Hatch.js +5 -4
  36. package/src/ui/Header.js +7 -6
  37. package/src/ui/Help.js +68 -0
  38. package/src/ui/Mascot.js +88 -38
  39. package/src/ui/Missed.js +6 -5
  40. package/src/ui/Preview.js +92 -17
  41. package/src/ui/Reset.js +72 -0
  42. package/src/ui/Settings.js +15 -11
  43. package/src/ui/Stats.js +10 -7
  44. package/src/ui/Summary.js +12 -5
  45. package/src/ui/TheOne.js +121 -0
  46. package/src/ui/icons.js +156 -24
  47. package/src/ui/kit.js +58 -1
  48. package/src/vacation.js +7 -2
  49. package/src/words.js +21 -14
  50. package/assets/sounds/badge.wav +0 -0
  51. package/src/ui/Tip.js +0 -25
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dracosh",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A gamified language or definitions trainer for your terminal. Your personal pixel dragon grows with your progress.",
5
5
  "author": "Tomasz Przyborowski (https://github.com/lynthius)",
6
6
  "license": "Apache-2.0",
package/src/alerts.js CHANGED
@@ -23,11 +23,12 @@ export function createAlerts(initial = {}) {
23
23
  play("ask");
24
24
  if (enabled) execFile("osascript", ["-e", 'display notification "A new word is waiting" with title "Dracosh"'], () => {});
25
25
  },
26
- // The biggest thing that just happened wins: evolution > badge > goal > combo cheer > the answer itself.
27
- // On a plain correct answer the pitch rises with the combo and resets on a miss.
26
+ // The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
27
+ // On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
28
+ // on their own, each as its line lights up (see BadgeUnlock).
28
29
  result(result, { cheers = [], combo = 0 } = {}) {
29
30
  if (result === "wrong") return play("wrong");
30
- for (const kind of ["evolve", "badge", "goal", "combo"]) {
31
+ for (const kind of ["evolve", "goal", "combo"]) {
31
32
  if (cheers.includes(kind)) return play(kind);
32
33
  }
33
34
  if (result === "typo") return play("close");
package/src/backup.js ADDED
@@ -0,0 +1,95 @@
1
+ import { copyFile, readdir, rm } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { dayKey } from "./dates.js";
4
+ import { DATA_FILES, HOME, readJson, writeJson } from "./store.js";
5
+
6
+ // A backup is one JSON file in ~/.dracosh/backups holding the library, progress and settings as they
7
+ // were. One is taken on the first start of each day, and right before anything that changes a lot at
8
+ // once (a restore now; imports, deletions and resets later).
9
+ export const BACKUP_DIR = join(HOME, "backups");
10
+ const BACKUP_FORMAT = 1;
11
+ export const KEEP = 7; // per kind: the last 7 daily ones, and the last 7 taken before an operation
12
+
13
+ // "2026-10-09T21:15:03.120Z" → "2026-10-09_21-15-03", so file names sort by time
14
+ const stamp = (now) => new Date(now).toISOString().slice(0, 19).replace("T", "_").replaceAll(":", "-");
15
+
16
+ // → the file it wrote, or null when there is nothing to back up (or, with `skipDamaged`, when a data file
17
+ // is too damaged to read: a backup missing the library would push the good ones out). Otherwise a damaged
18
+ // file is set aside as it is (library.json.damaged-<day>, one a day) and the backup goes on, so a
19
+ // restore still works.
20
+ export async function backupNow(reason, now = Date.now(), { skipDamaged = false } = {}) {
21
+ const files = {};
22
+ for (const [name, file] of Object.entries(DATA_FILES)) {
23
+ try {
24
+ const data = await readJson(file, null);
25
+ if (data) files[name] = data;
26
+ } catch {
27
+ if (name === "settings") continue; // broken settings just mean the defaults: back up the rest
28
+ if (skipDamaged) return null;
29
+ await copyFile(file, `${file}.damaged-${dayKey(now)}`);
30
+ }
31
+ }
32
+ if (!Object.keys(files).length) return null;
33
+ const file = join(BACKUP_DIR, `${stamp(now)}-${reason}.json`);
34
+ await writeJson(file, { format: BACKUP_FORMAT, created: now, reason, files });
35
+ await prune();
36
+ return file;
37
+ }
38
+
39
+ async function backupFiles() {
40
+ try {
41
+ return (await readdir(BACKUP_DIR)).filter((name) => name.endsWith(".json")).sort().reverse(); // newest first
42
+ } catch (err) {
43
+ if (err.code === "ENOENT") return [];
44
+ throw err;
45
+ }
46
+ }
47
+
48
+ const isDaily = (name) => name.endsWith("-daily.json");
49
+
50
+ async function prune() {
51
+ const names = await backupFiles();
52
+ const old = [...names.filter(isDaily).slice(KEEP), ...names.filter((name) => !isDaily(name)).slice(KEEP)];
53
+ await Promise.all(old.map((name) => rm(join(BACKUP_DIR, name), { force: true })));
54
+ }
55
+
56
+ // the first start of a day backs up what the day before left behind
57
+ export async function dailyBackup(now = Date.now()) {
58
+ const today = dayKey(now);
59
+ const backups = await listBackups();
60
+ if (backups.some((b) => b.reason === "daily" && dayKey(b.created) === today)) return null;
61
+ return backupNow("daily", now, { skipDamaged: true });
62
+ }
63
+
64
+ // → newest first: { file, created, reason, decks, cards, practiced }
65
+ export async function listBackups() {
66
+ const list = [];
67
+ for (const name of await backupFiles()) {
68
+ const file = join(BACKUP_DIR, name);
69
+ const backup = await readJson(file, null).catch(() => null); // a damaged file just isn't offered
70
+ if (backup?.format !== BACKUP_FORMAT || !backup.files || typeof backup.files !== "object") continue;
71
+ const { library, state } = backup.files;
72
+ list.push({
73
+ file,
74
+ created: backup.created,
75
+ reason: backup.reason,
76
+ decks: library?.decks?.length ?? 0,
77
+ cards: library?.cards?.length ?? 0,
78
+ practiced: Object.keys(state?.items ?? {}).length,
79
+ hasState: Boolean(state),
80
+ hasSettings: Boolean(backup.files.settings)
81
+ });
82
+ }
83
+ return list.sort((a, b) => b.created - a.created); // file names only go down to the second
84
+ }
85
+
86
+ // Puts a backup's files back. What's there now is backed up first, so a restore can be undone too.
87
+ // A file the backup doesn't have is left as it is: a restore never deletes your cards or progress.
88
+ export async function restoreBackup(file, now = Date.now()) {
89
+ const backup = await readJson(file, null);
90
+ if (backup?.format !== BACKUP_FORMAT || !backup.files) throw new Error(`${file} isn't a Dracosh backup.`);
91
+ await backupNow("before-restore", now);
92
+ for (const [name, target] of Object.entries(DATA_FILES)) {
93
+ if (backup.files[name]) await writeJson(target, backup.files[name]);
94
+ }
95
+ }
package/src/cli.js CHANGED
@@ -2,35 +2,43 @@
2
2
  import { render } from "ink";
3
3
  import React from "react";
4
4
  import { parseArgs } from "node:util";
5
+ import { createInterface } from "node:readline/promises";
5
6
  import { createAlerts } from "./alerts.js";
7
+ import { existsSync } from "node:fs";
8
+ import { BACKUP_DIR, dailyBackup, listBackups, restoreBackup } from "./backup.js";
6
9
  import { ensureProgress, snapshot } from "./progress.js";
7
10
  import { BOX_INTERVALS_DAYS } from "./scheduler.js";
8
11
  import { createSession } from "./session.js";
9
12
  import { DEFAULTS, formatInterval, normalizeSettings } from "./settings.js";
10
- import { loadSettingsRaw, loadState, patchSettings } from "./store.js";
13
+ import { seedLibrary } from "./starter.js";
14
+ import { DATA_FILES, HOME, loadLibrary, loadSettingsRaw, loadState, patchSettings, saveLibrary } from "./store.js";
11
15
  import { App } from "./ui/App.js";
12
16
  import { Preview } from "./ui/Preview.js";
13
- import { loadWords } from "./words.js";
17
+ import { ALREADY_RUNNING, acquireLock, runningPid } from "./lock.js";
18
+ import * as manage from "./manage.js";
19
+ import { findDeck } from "./library.js";
20
+ import { loadAllWords, loadWords, missingDeck } from "./words.js";
14
21
 
15
- const DEFAULT_DECK = "English";
16
-
17
- const HELP = `Dracosh: vocabulary quiz from your Anki deck (read-only)
22
+ const HELP = `Dracosh: a vocabulary and quiz trainer for your terminal
18
23
 
19
24
  Usage: dracosh [options]
25
+ dracosh restore [number] list your backups, or bring one back
20
26
 
21
- --deck <name> Anki deck to take words from (default: ${DEFAULT_DECK})
27
+ --deck <name> quiz this deck, this run only (otherwise the one picked in /decks)
22
28
  --every <time> pause between questions: 30s, 10m, 1h (default: ${formatInterval(DEFAULTS.everyMs)})
23
29
  --no-sound turn sound effects off
24
30
  --volume <0-1> sound volume (default: ${DEFAULTS.volume})
25
31
  --stats print progress and exit
32
+ --data show where your cards, progress and backups are kept
26
33
  --preview browse every animation and screen on made-up data (nothing is saved)
34
+ -y, --yes restore without asking first
27
35
  -h, --help show this help
28
36
 
29
37
  Flags override your saved settings for this run only. Change the saved ones with /settings.
30
38
 
31
- While running: Enter submits, "/" opens the command menu (/settings, /stats, /badges, /skip, /quit),
39
+ While running: Enter submits, "/" opens the command menu (/add, /decks, /settings, /stats, /help…),
32
40
  Esc quits (clears the line first if you typed something). Ctrl+C also works.
33
- Between questions: Enter asks the next word right away, q quits.`;
41
+ Between cards: Enter asks the next one right away, q quits. /help explains the rest.`;
34
42
 
35
43
  function parseEvery(value) {
36
44
  const match = /^(\d+(?:\.\d+)?)(s|m|h)$/.exec(value);
@@ -57,23 +65,83 @@ function printStats(state, settings) {
57
65
  const perBox = BOX_INTERVALS_DAYS.map((days, i) => `box ${i + 1} (${days}d): ${entries.filter((e) => e.box === i + 1).length}`);
58
66
  const correct = entries.reduce((sum, e) => sum + e.correct, 0);
59
67
  const total = entries.reduce((sum, e) => sum + e.seen, 0);
60
- console.log(`${entries.length} cards practiced, ${correct}/${total} correct (${Math.round((correct / total) * 100)}%)`);
68
+ console.log(`${entries.length} cards practised, ${correct}/${total} correct (${Math.round((correct / total) * 100)}%)`);
61
69
  console.log(perBox.join(" "));
62
70
  }
63
71
 
72
+ const formatTime = (ms) => new Date(ms).toLocaleString("sv").slice(0, 16);
73
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
74
+
75
+ async function confirm(question) {
76
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
77
+ try {
78
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
79
+ } finally {
80
+ rl.close();
81
+ }
82
+ }
83
+
84
+ // --data: where everything lives, and what's in it
85
+ async function printData() {
86
+ const library = await loadLibrary();
87
+ const state = await loadState();
88
+ const backups = await listBackups();
89
+ const at = (file) => (existsSync(file) ? "" : " (not created yet)");
90
+ console.log(`Dracosh keeps everything in ${HOME}\n`);
91
+ console.log(` library.json your decks and cards: ${plural(library.decks.length, "deck")} · ${plural(library.cards.length, "card")}${at(DATA_FILES.library)}`);
92
+ console.log(` state.json progress, streak and badges: ${Object.keys(state.items).length} practised${at(DATA_FILES.state)}`);
93
+ console.log(` settings.json your settings${at(DATA_FILES.settings)}`);
94
+ console.log(` backups/ ${backups.length ? `${plural(backups.length, "backup")}, the newest from ${formatTime(backups[0].created)}` : "none yet"}`);
95
+ console.log(`\nTo keep it somewhere else (a synced folder, say), set DRACOSH_HOME. dracosh restore brings a backup back.`);
96
+ }
97
+
98
+ async function restore(choice, { yes }) {
99
+ const backups = await listBackups();
100
+ if (!backups.length) return console.log(`No backups yet. Dracosh makes one every day you use it, in ${BACKUP_DIR}`);
101
+ if (!choice) {
102
+ console.log(`Backups in ${BACKUP_DIR}, newest first:\n`);
103
+ backups.forEach((b, i) => {
104
+ const what = `${plural(b.decks, "deck")} · ${plural(b.cards, "card")} · ${b.practiced} practised`;
105
+ console.log(` ${String(i + 1).padStart(2)} ${formatTime(b.created)} ${b.reason.padEnd(14)} ${what}`);
106
+ });
107
+ return console.log(`\nBring one back with: dracosh restore <number>`);
108
+ }
109
+
110
+ const backup = backups[Number(choice) - 1];
111
+ if (!backup) throw new Error(`There's no backup number ${choice}. Run "dracosh restore" to see the list.`);
112
+ const running = runningPid();
113
+ if (running) throw new Error(ALREADY_RUNNING(running));
114
+ const has = ["cards", "progress", "settings"].filter((_, i) => [backup.cards || backup.decks, backup.hasState, backup.hasSettings][i]);
115
+ console.log(`This brings back your ${has.join(", ").replace(/, (?=[^,]*$)/, " and ")} from the backup of ${formatTime(backup.created)}.`);
116
+ console.log("What you have now is backed up first, so you can undo this.");
117
+ if (!yes) {
118
+ if (!process.stdin.isTTY) throw new Error("Add --yes to restore without a prompt.");
119
+ if (!(await confirm("Restore it?"))) return console.log("Nothing changed.");
120
+ }
121
+ await restoreBackup(backup.file);
122
+ console.log("Restored.");
123
+ }
124
+
64
125
  async function main() {
65
- const { values } = parseArgs({
126
+ const { values, positionals } = parseArgs({
127
+ allowPositionals: true,
66
128
  options: {
67
- deck: { type: "string", default: DEFAULT_DECK },
129
+ deck: { type: "string" },
68
130
  every: { type: "string" },
69
131
  volume: { type: "string" },
70
132
  "no-sound": { type: "boolean", default: false },
71
133
  stats: { type: "boolean", default: false },
134
+ data: { type: "boolean", default: false },
72
135
  preview: { type: "boolean", default: false },
136
+ yes: { type: "boolean", short: "y", default: false },
73
137
  help: { type: "boolean", short: "h", default: false }
74
138
  }
75
139
  });
76
140
  if (values.help) return console.log(HELP);
141
+ const [command, ...args] = positionals;
142
+ if (command === "restore") return restore(args[0], values);
143
+ if (command) throw new Error(`Unknown command "${command}". See dracosh --help.`);
144
+ if (values.data) return printData();
77
145
 
78
146
  const saved = normalizeSettings(await loadSettingsRaw());
79
147
  const settings = {
@@ -92,13 +160,22 @@ async function main() {
92
160
  const state = await loadState();
93
161
  if (values.stats) return printStats(state, settings);
94
162
  if (!process.stdin.isTTY) throw new Error("dracosh needs an interactive terminal.");
163
+ // a fresh install starts with the "Getting started" deck
164
+ const library = await loadLibrary();
165
+ const seeded = seedLibrary(library);
166
+ if (values.deck && !findDeck(library, values.deck)) throw missingDeck(library, values.deck); // before anything is written
167
+
168
+ acquireLock();
169
+ await dailyBackup();
170
+ if (seeded) await saveLibrary(library);
95
171
 
96
- // fail fast (and readably) when there is nothing to quiz on, before taking over the screen
97
- const { words } = await loadWords(values.deck);
98
- if (!words.length) throw new Error(`No translation cards found in deck "${values.deck}".`);
172
+ // --deck must exist (fail fast, before taking over the screen); a deck saved in /decks that has
173
+ // since gone just falls back to the first one
174
+ const { deck } = values.deck ? await loadWords(values.deck) : await loadWords(settings.deck).catch(() => loadWords());
99
175
 
100
176
  let current = settings; // the session reads settings live, so /settings changes apply immediately
101
- const session = createSession({ loadWords: () => loadWords(values.deck), state, getSettings: () => current });
177
+ let active = deck.name; // /add can switch to your first own deck
178
+ const session = createSession({ loadWords: () => loadWords(active), loadAllWords, state, getSettings: () => current });
102
179
  const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
103
180
  const persistSettings = async (patch) => {
104
181
  current = { ...current, ...patch };
@@ -106,11 +183,15 @@ async function main() {
106
183
  };
107
184
 
108
185
  // the session summary screen stays on screen after exit, so nothing more to print here
109
- const app = render(React.createElement(App, { session, deck: values.deck, initialSettings: settings, alerts, persistSettings }));
186
+ const app = render(React.createElement(App, { session, deck: deck.name, initialSettings: settings, alerts, persistSettings, library: manage, onSwitchDeck: (name) => (active = name) }));
110
187
  await app.waitUntilExit();
111
188
  }
112
189
 
113
190
  main().catch((err) => {
191
+ if (["EACCES", "EPERM", "ENOTDIR", "EEXIST"].includes(err.code)) {
192
+ console.error(`Dracosh can't use ${HOME} for its data (${err.code}). Point DRACOSH_HOME at a folder you can write to.`);
193
+ process.exit(1);
194
+ }
114
195
  console.error(err.message);
115
196
  process.exit(1);
116
197
  });
package/src/commands.js CHANGED
@@ -1,15 +1,15 @@
1
1
  // `only` limits a command to one phase: "asking" (a question is open) or "waiting" (between questions)
2
2
  export const COMMANDS = [
3
3
  { name: "/hint", only: "asking", hint: "Reveal another letter (the card won't climb a box)" },
4
+ { name: "/add", hint: "Add cards to a deck, or start a new one" },
5
+ { name: "/decks", hint: "Switch to another deck, or start a new one" },
4
6
  { name: "/settings", hint: "Interval, quiet hours, sound, goal, tips" },
5
7
  { name: "/stats", hint: "Streak, month calendar and badges summary" },
6
8
  { name: "/badges", hint: "All badges and what unlocks them" },
7
- { name: "/companion", hint: "Your companion's forms and moods" },
8
- { name: "/tip", aliases: ["/grammar"], hint: "Grammar tip: show a random one" },
9
- { name: "/missed", hint: "Words you got wrong today" },
10
- { name: "/snooze", hint: "Pause questions: /snooze 30m, 2h, off" },
11
- { name: "/vacation", hint: "Days off that keep your streak: 7, 24.12 2.01, off" },
12
- { name: "/skip", only: "asking", hint: "Skip this word" },
9
+ { name: "/companion", hint: "Your dragon, its element and the forms ahead" },
10
+ { name: "/missed", hint: "Cards you got wrong today" },
11
+ { name: "/pause", hint: "A break (30m, 2h) or days off (3d, 24.12 2.01)" },
12
+ { name: "/help", aliases: ["/?"], hint: "Keys, how cards come back, the streak" },
13
13
  { name: "/quit", hint: "Exit Dracosh" }
14
14
  ];
15
15
 
@@ -21,7 +21,7 @@ export function commandsFor({ phase, canOverrule = false }) {
21
21
  return canOverrule ? [CORRECT, ...base] : base;
22
22
  }
23
23
 
24
- // "/s" narrows to commands starting with it (aliases count: "/gram" finds /tip). Arguments are ignored: "/snooze 30m" matches /snooze.
24
+ // "/s" narrows to commands starting with it (aliases count: "/?" finds /help). Arguments are ignored: "/pause 30m" matches /pause.
25
25
  export function matchCommands(value, commands = COMMANDS) {
26
26
  const query = value.trim().split(/\s+/)[0].toLowerCase();
27
27
  return commands.filter((command) => command.name.startsWith(query) || command.aliases?.some((alias) => alias.startsWith(query)));
package/src/judge.js CHANGED
@@ -1,16 +1,30 @@
1
1
  // Typos are forgiven only on longer answers: on short words one edit often makes a different word
2
2
  const TYPO_MIN_LENGTH = 6;
3
3
 
4
- // lowercase, strip diacritics (ł doesn't decompose, so it is mapped by hand), drop punctuation
5
- export function normalize(s) {
6
- return s
4
+ // Sentence punctuation that never changes what an answer means ("Hello, world!" = "hello world").
5
+ // Everything else stays: "3.14" isn't "31.4", "-5" isn't "5", "C#" isn't "C", and 🐉 is an answer too.
6
+ const LOOSE = /[;!?¡¿"“”„«»()[\]'’`]/g;
7
+
8
+ // lowercase, loose punctuation dropped, a trailing full stop dropped, hyphens between letters as spaces.
9
+ // Commas and colons count between digits only: "3,14" is "3.14" (a decimal comma), "10:30" stays.
10
+ function plain(s) {
11
+ const text = s
12
+ .normalize("NFC") // "café" typed or pasted with a separate accent mark is the same word
7
13
  .toLowerCase()
8
- .replace(/ł/g, "l")
9
- .normalize("NFD")
10
- .replace(/[̀-ͯ]/g, "")
11
- .replace(/[^\p{L}\p{N}\s]/gu, "")
14
+ .replace(/(?<=\d),(?=\d)/g, ".")
15
+ .replace(/,/g, " ")
16
+ .replace(/(?<!\d):|:(?!\d)/g, "")
17
+ .replace(LOOSE, "")
18
+ .replace(/(?<=\p{L})[-‐–—](?=\p{L})/gu, " ")
19
+ .replace(/\.+$/, "")
12
20
  .replace(/\s+/g, " ")
13
21
  .trim();
22
+ return text || s.trim().toLowerCase(); // an answer made only of punctuation ("?") is still itself
23
+ }
24
+
25
+ // plain(), and diacritics folded too (ł doesn't decompose, so it is mapped by hand)
26
+ export function normalize(s) {
27
+ return plain(s).replace(/ł/g, "l").normalize("NFD").replace(/[\u0300-\u036f]/g, "");
14
28
  }
15
29
 
16
30
  // Damerau-Levenshtein (optimal string alignment): a swap of two neighbours counts as one edit
@@ -46,12 +60,19 @@ export function closestCandidate(answer, candidates) {
46
60
  return best;
47
61
  }
48
62
 
49
- // → "exact" | "typo" | "wrong"; accepts any one of the candidate answers
63
+ // → "exact" | "typo" | "wrong"; accepts any one of the candidate answers. Missing or wrong
64
+ // diacritics ("zolw" for "żółw") count, as "typo", so the right spelling is shown. One more typo is
65
+ // forgiven on longer answers, but never in numbers: "123457" isn't "123456".
50
66
  export function judge(answer, candidates) {
67
+ if (!answer.trim()) return "wrong";
51
68
  const given = normalize(answer);
52
- if (!given) return "wrong";
53
- const targets = candidates.map(normalize).filter(Boolean);
54
- if (targets.includes(given)) return "exact";
55
- const close = targets.some((t) => t.length >= TYPO_MIN_LENGTH && editDistance(given, t) <= 1);
69
+ if (candidates.some((c) => plain(c) === plain(answer))) return "exact";
70
+ const targets = candidates.map(normalize);
71
+ if (targets.includes(given)) return "typo";
72
+ // "email" for "e-mail", "icecream" for "ice cream": right, but shown with the spelling
73
+ const compact = (s) => s.replace(/\s/g, ""); // hyphens between letters are spaces by now
74
+ if (targets.some((t) => compact(t) === compact(given))) return "typo";
75
+ const numbers = /\d/.test(given);
76
+ const close = targets.some((t) => t.length >= TYPO_MIN_LENGTH && !numbers && !/\d/.test(t) && editDistance(given, t) <= 1);
56
77
  return close ? "typo" : "wrong";
57
78
  }
package/src/library.js ADDED
@@ -0,0 +1,127 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { normalize } from "./judge.js";
3
+
4
+ // The card library: decks and their cards. Pure functions over a plain object; saving is the caller's job.
5
+ //
6
+ // Progress (state.items) is keyed by `${card.id}:${direction}`. Cards that came from Anki use the Anki
7
+ // note id as their id, so progress recorded by 0.1.0 (keyed by note id) carries over unchanged.
8
+ // New cards get a "c"-prefixed id, which can never collide with Anki's numeric ids.
9
+
10
+ export const LIBRARY_VERSION = 1;
11
+
12
+ export const CARD_TYPES = ["translation", "definition", "qa"];
13
+ export const ANSWER_MODES = ["typed", "self"];
14
+ const DEFAULT_ANSWER_MODE = { translation: "typed", definition: "typed", qa: "self" };
15
+
16
+ export const MAX_DECK_NAME = 40; // it has to fit the card's border and the header
17
+
18
+ export const emptyLibrary = () => ({ version: LIBRARY_VERSION, decks: [], cards: [] });
19
+
20
+ export const newId = (prefix) => `${prefix}${Date.now().toString(36)}${randomBytes(3).toString("hex")}`;
21
+
22
+ const sameName = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
23
+
24
+ function cleanList(values) {
25
+ const list = (Array.isArray(values) ? values : [values]).map((v) => String(v ?? "").trim()).filter(Boolean);
26
+ return [...new Set(list)];
27
+ }
28
+
29
+ const isText = (value) => typeof value === "string";
30
+ const filled = (value) => isText(value) && value.trim() !== "";
31
+ const validLanguages = (languages) => languages == null || (typeof languages === "object" && filled(languages.front) && filled(languages.back));
32
+ const validDeck = (deck) => deck && isText(deck.id) && filled(deck.name) && validLanguages(deck.languages);
33
+ const validCard = (card) => card && isText(card.id) && isText(card.deckId) && filled(card.front) && Array.isArray(card.back) && card.back.length > 0 && card.back.every(filled);
34
+ const broken = (why) => Object.assign(new Error(why), { damaged: true });
35
+
36
+ // → the library in its current shape (undefined: there's none yet). Throws on a file written by a newer
37
+ // Dracosh, so it's never overwritten, and on one that isn't a library, so nothing is lost by saving over it.
38
+ export function upgradeLibrary(raw) {
39
+ if (raw === undefined) return emptyLibrary();
40
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw broken("not a library");
41
+ if (raw.version > LIBRARY_VERSION) {
42
+ throw new Error(`This library was saved by a newer version of Dracosh (format ${raw.version}). Please update Dracosh.`);
43
+ }
44
+ const decks = raw.decks ?? [];
45
+ const cards = raw.cards ?? [];
46
+ if (!Array.isArray(decks) || !decks.every(validDeck)) throw broken("a deck without a name or an id");
47
+ if (!Array.isArray(cards) || !cards.every(validCard)) throw broken("a card without a front or an answer");
48
+ const deckIds = new Set(decks.map((deck) => deck.id));
49
+ if (!cards.every((card) => deckIds.has(card.deckId))) throw broken("a card in a deck that doesn't exist");
50
+ if (new Set(cards.map((card) => card.id)).size !== cards.length) throw broken("two cards with the same id");
51
+ return { version: LIBRARY_VERSION, decks, cards };
52
+ }
53
+
54
+ export const findDeck = (library, nameOrId) =>
55
+ library.decks.find((deck) => deck.id === nameOrId) ?? library.decks.find((deck) => sameName(deck.name, nameOrId)) ?? null;
56
+
57
+ export function createDeck(library, { name, type = "translation", languages = { front: "en", back: "pl" }, answerMode, directions = "both", tour = false, now = Date.now() }) {
58
+ const trimmed = String(name ?? "").trim();
59
+ if (!trimmed) throw new Error("A deck needs a name.");
60
+ if (Array.from(trimmed).length > MAX_DECK_NAME) throw new Error(`Keep the deck name to ${MAX_DECK_NAME} characters or fewer.`);
61
+ const existing = findDeck(library, trimmed);
62
+ if (existing) throw new Error(`There is already a deck called "${existing.name}".`);
63
+ if (!CARD_TYPES.includes(type)) throw new Error(`Unknown card type "${type}".`);
64
+ const mode = answerMode ?? DEFAULT_ANSWER_MODE[type];
65
+ if (!ANSWER_MODES.includes(mode)) throw new Error(`Unknown answer mode "${mode}".`);
66
+
67
+ const deck = { id: newId("d"), name: trimmed, type, languages: languages ? { ...languages } : null, answerMode: mode, directions, tour, created: now };
68
+ library.decks.push(deck);
69
+ return deck;
70
+ }
71
+
72
+ // → the ids of the cards that went with it, so their progress can be dropped too
73
+ export function removeDeck(library, deckId) {
74
+ const removed = cardsOf(library, deckId).map((card) => card.id);
75
+ library.decks = library.decks.filter((deck) => deck.id !== deckId);
76
+ library.cards = library.cards.filter((card) => card.deckId !== deckId);
77
+ return removed;
78
+ }
79
+
80
+ export const cardsOf = (library, deckId) => library.cards.filter((card) => card.deckId === deckId);
81
+
82
+ // a card with the same front (ignoring case, accents and punctuation) in the same deck
83
+ export const findDuplicate = (library, deckId, front) => {
84
+ const key = normalize(front);
85
+ return library.cards.find((card) => card.deckId === deckId && normalize(card.front) === key) ?? null;
86
+ };
87
+
88
+ // → { card, duplicate }: `duplicate` is the existing card when the front is already in the deck (nothing is added then)
89
+ export function addCard(library, deckId, { front, back, example = "", tags = [], id, now = Date.now() }) {
90
+ if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
91
+ const cleanFront = String(front ?? "").trim();
92
+ const cleanBack = cleanList(back);
93
+ if (!cleanFront) throw new Error("A card needs a front.");
94
+ if (!cleanBack.length) throw new Error("A card needs at least one answer on the back.");
95
+
96
+ const duplicate = findDuplicate(library, deckId, cleanFront);
97
+ if (duplicate) return { card: null, duplicate };
98
+
99
+ const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), created: now, updated: now };
100
+ if (library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
101
+ library.cards.push(card);
102
+ return { card, duplicate: null };
103
+ }
104
+
105
+ export function updateCard(library, cardId, patch, now = Date.now()) {
106
+ const card = library.cards.find((c) => c.id === cardId);
107
+ if (!card) throw new Error("That card doesn't exist.");
108
+ if (patch.front !== undefined) {
109
+ const front = String(patch.front).trim();
110
+ if (!front) throw new Error("A card needs a front.");
111
+ const duplicate = findDuplicate(library, card.deckId, front);
112
+ if (duplicate && duplicate.id !== card.id) throw new Error(`"${front}" is already in this deck.`);
113
+ card.front = front;
114
+ }
115
+ if (patch.back !== undefined) {
116
+ const back = cleanList(patch.back);
117
+ if (!back.length) throw new Error("A card needs at least one answer on the back.");
118
+ card.back = back;
119
+ }
120
+ if (patch.example !== undefined) card.example = String(patch.example).trim();
121
+ if (patch.tags !== undefined) card.tags = cleanList(patch.tags);
122
+ card.updated = now;
123
+ return card;
124
+ }
125
+
126
+ // The quiz's word shape, so the scheduler and session keep working unchanged.
127
+ export const toWords = (cards) => cards.map((card) => ({ noteId: card.id, word: card.front, translations: card.back, example: card.example }));
package/src/lock.js ADDED
@@ -0,0 +1,63 @@
1
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { HOME } from "./store.js";
4
+
5
+ // One quiz at a time per data folder: each window keeps the progress in memory and saves all of it,
6
+ // so two windows would overwrite each other's answers. The lock file holds the running window's pid.
7
+ const LOCK_FILE = join(HOME, "dracosh.lock");
8
+
9
+ const alive = (pid) => {
10
+ try {
11
+ process.kill(pid, 0);
12
+ return true;
13
+ } catch (err) {
14
+ return err.code === "EPERM"; // running, but someone else's process
15
+ }
16
+ };
17
+
18
+ const readPid = () => {
19
+ try {
20
+ return Number(JSON.parse(readFileSync(LOCK_FILE, "utf8")).pid) || null;
21
+ } catch {
22
+ return null; // no lock, or an unreadable one
23
+ }
24
+ };
25
+
26
+ // the pid of a Dracosh quiz running on this data folder, or null
27
+ export function runningPid() {
28
+ const pid = readPid();
29
+ return pid && pid !== process.pid && alive(pid) ? pid : null; // a lock left by a crash doesn't count
30
+ }
31
+
32
+ export const ALREADY_RUNNING = (pid) => `Dracosh is already running in another window (process ${pid}). Close it first: two windows would overwrite each other's progress.`;
33
+
34
+ // → a release function; throws when another quiz holds the lock. The lock file is created exclusively
35
+ // ("wx"), so of two windows started at the same moment only one gets it; a stale one is replaced once.
36
+ export function acquireLock() {
37
+ mkdirSync(HOME, { recursive: true });
38
+ const lock = JSON.stringify({ pid: process.pid, since: new Date().toISOString() });
39
+ for (let attempt = 0; ; attempt++) {
40
+ try {
41
+ writeFileSync(LOCK_FILE, lock, { flag: "wx" });
42
+ break;
43
+ } catch (err) {
44
+ if (err.code !== "EEXIST" || attempt > 0) throw err.code === "EEXIST" ? new Error(ALREADY_RUNNING(runningPid() ?? "?")) : err;
45
+ const pid = runningPid();
46
+ if (pid) throw new Error(ALREADY_RUNNING(pid));
47
+ rmSync(LOCK_FILE, { force: true }); // left behind by a window that crashed
48
+ }
49
+ }
50
+ // Two windows that both found the same stale lock may each have removed it and written their own:
51
+ // after a moment only one of them is still in the file, and the other one stops here.
52
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 60);
53
+ if (readPid() !== process.pid) throw new Error(ALREADY_RUNNING(readPid() ?? "?"));
54
+ const release = () => {
55
+ try {
56
+ if (Number(JSON.parse(readFileSync(LOCK_FILE, "utf8")).pid) === process.pid) rmSync(LOCK_FILE);
57
+ } catch {}
58
+ };
59
+ process.on("exit", release);
60
+ // with the lock held no other window writes here: temp files left by a crash can go
61
+ for (const name of readdirSync(HOME)) if (/^(library|state|settings)\.json\.\d+\.tmp$/.test(name)) rmSync(join(HOME, name), { force: true });
62
+ return release;
63
+ }