dracosh 0.8.0 → 0.9.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/locales/uk.json CHANGED
@@ -104,6 +104,10 @@
104
104
  "label": "Мова застосунку",
105
105
  "hint": "мова Dracosh; навчальний тур теж перемкнеться"
106
106
  },
107
+ "theme": {
108
+ "label": "Тема",
109
+ "hint": "автоматична підлаштовується під тло термінала; обери темну або світлу, якщо не вгадає"
110
+ },
107
111
  "homeLanguage": {
108
112
  "label": "Твоя мова",
109
113
  "hint": "мова, якою ти розмовляєш: за нею видно, яка сторона картки для тебе нова"
@@ -130,7 +134,7 @@
130
134
  },
131
135
  "voice": {
132
136
  "label": "Голос",
133
- "hint": "хто читає слова: голоси macOS або природний голос ElevenLabs із твоїм ключем"
137
+ "hint": "хто читає слова: системні голоси або природний голос ElevenLabs із твоїм ключем"
134
138
  },
135
139
  "volume": {
136
140
  "label": "Гучність",
@@ -169,6 +173,11 @@
169
173
  "sometimes": "іноді (кожне третє очікування)",
170
174
  "off": "вимк."
171
175
  },
176
+ "themes": {
177
+ "auto": "автоматична",
178
+ "dark": "темна",
179
+ "light": "світла"
180
+ },
172
181
  "weekendsRest": "дні відпочинку",
173
182
  "weekendsCount": "як інші дні",
174
183
  "pressEnter": "натисни enter",
@@ -905,7 +914,7 @@
905
914
  "notInTrash": "Цієї колоди вже немає в кошику."
906
915
  },
907
916
  "cli": {
908
- "help": "Dracosh: тренажер слів і вікторин у терміналі\n\nВикористання: dracosh [параметри]\n dracosh import <файл|-> додати картки з файлу (.txt, .csv, .tsv, пакет Anki .apkg чи .colpkg, текстові експорти з Anki чи Quizlet, резервна копія .json) або «-» зі стандартного введення\n dracosh export <файл> записати колоди в .apkg (Anki), .txt, .tsv, .csv або .json (усе)\n dracosh restore [номер] список резервних копій або відновлення однієї з них\n\n --deck <назва> вікторина з цієї колоди, лише цього разу (інакше та, що вибрана в /decks)\n з import і export: колода, яку поповнити чи записати\n --every <час> пауза між запитаннями: 30s, 10m, 1h (типово: {interval})\n --no-sound вимкнути звуки\n --volume <0-1> гучність (типово: {volume})\n --stats вивести прогрес і вийти\n --data показати, де лежать картки, прогрес і резервні копії\n --preview переглянути всі анімації та екрани на вигаданих даних (нічого не зберігається)\n --update import: наявні картки беруть відповіді з файлу (інакше буде запитання)\n --split import: відповідь із кількома варіантами («cat, kitty») стає кількома відповідями\n --separator <s> import: що розділяє стовпці: tab, comma, semicolon, pipe, colon, space або символ\n --encoding <e> import: файл не в UTF-8, напр. windows-1251\n --anki імпорт чи експорт: просто з відкритого Anki або в нього (доповнення AnkiConnect)\n -y, --yes імпорт, експорт чи відновлення без запитання\n -h, --help показати цю довідку\n\nПараметри змінюють збережені налаштування лише для цього запуску. Збережені змінюй у /settings.\n\nПід час роботи: Enter надсилає (порожній показує відповідь, потім 1 або 2), «/» відкриває меню команд (/add, /decks, /settings, /stats, /help…),\nEsc виходить (спершу стирає введене). Ctrl+C теж працює.\nМіж картками: Enter одразу ставить наступну, q виходить. Решту пояснює /help.",
917
+ "help": "Dracosh: тренажер слів і вікторин у терміналі\n\nВикористання: dracosh [параметри]\n dracosh import <файл|-> додати картки з файлу (.txt, .csv, .tsv, пакет Anki .apkg чи .colpkg, текстові експорти з Anki чи Quizlet, резервна копія .json) або «-» зі стандартного введення\n dracosh export <файл> записати колоди в .apkg (Anki), .txt, .tsv, .csv або .json (усе)\n dracosh restore [номер] список резервних копій або відновлення однієї з них\n dracosh doctor перевірити звук, голоси, сповіщення, ШІ і твої дані\n dracosh bug повідомити про помилку: відкриває звіт на GitHub із даними про твою систему\n\n --deck <назва> вікторина з цієї колоди, лише цього разу (інакше та, що вибрана в /decks)\n з import і export: колода, яку поповнити чи записати\n --every <час> пауза між запитаннями: 30s, 10m, 1h (типово: {interval})\n --no-sound вимкнути звуки\n --volume <0-1> гучність (типово: {volume})\n --stats вивести прогрес і вийти\n --data показати, де лежать картки, прогрес і резервні копії\n --preview переглянути всі анімації та екрани на вигаданих даних (нічого не зберігається)\n --update import: наявні картки беруть відповіді з файлу (інакше буде запитання)\n --split import: відповідь із кількома варіантами («cat, kitty») стає кількома відповідями\n --separator <s> import: що розділяє стовпці: tab, comma, semicolon, pipe, colon, space або символ\n --encoding <e> import: файл не в UTF-8, напр. windows-1251\n --anki імпорт чи експорт: просто з відкритого Anki або в нього (доповнення AnkiConnect)\n -y, --yes імпорт, експорт чи відновлення без запитання\n -h, --help показати цю довідку\n\nПараметри змінюють збережені налаштування лише для цього запуску. Збережені змінюй у /settings.\n\nПід час роботи: Enter надсилає (порожній показує відповідь, потім 1 або 2), «/» відкриває меню команд (/add, /decks, /settings, /stats, /help…),\nEsc виходить (спершу стирає введене). Ctrl+C теж працює.\nМіж картками: Enter одразу ставить наступну, q виходить. Решту пояснює /help.",
909
918
  "badEvery": "Неправильне значення --every «{value}». Використай, напр., 30s, 10m, 1h.",
910
919
  "badVolume": "Неправильне значення --volume «{value}». Вкажи число від 0 до 1.",
911
920
  "unknownCommand": "Невідома команда «{command}». Див. dracosh --help.",
@@ -975,7 +984,38 @@
975
984
  "other": "{count} резервної копії"
976
985
  },
977
986
  "unknownOption": "Невідомий параметр {option}. Див. dracosh --help.",
978
- "oneFile": "dracosh {command} бере один файл за раз."
987
+ "oneFile": "dracosh {command} бере один файл за раз.",
988
+ "doctor": {
989
+ "title": "Dracosh doctor: що працює на цьому комп'ютері",
990
+ "data": "Дані",
991
+ "dataNew": "{home} (ще не створено: це станеться під час першого запуску)",
992
+ "dataReadOnly": "у {home} не можна записувати: перевір права доступу",
993
+ "nodeOld": "{version}: Dracosh потребує Node {needed} або новішої версії",
994
+ "noSoundWindows": "не на Windows",
995
+ "noPlayer": "програвач не знайдено: встанови paplay, aplay або ffplay",
996
+ "notifications": "Сповіщення",
997
+ "notifier": {
998
+ "osascript": "Центр сповіщень",
999
+ "notify-send": "сповіщення робочого столу (notify-send)",
1000
+ "bell": "дзвіночок термінала",
1001
+ "bellLinux": "дзвіночок термінала: встанови notify-send (libnotify), щоб отримувати сповіщення робочого столу"
1002
+ },
1003
+ "noSpeech": "системний голос не знайдено: встанови espeak-ng",
1004
+ "noMp3Player": "{voice} потребує програвача для аудіофайлів: встанови ffplay (ffmpeg) або paplay",
1005
+ "aiNoModel": "{label}: сервер не пропонує {model}, вибери інший у /settings → Допомога ШІ",
1006
+ "allGood": "Усе гаразд.",
1007
+ "problems": {
1008
+ "one": "{count} річ треба виправити.",
1009
+ "few": "{count} речі треба виправити.",
1010
+ "many": "{count} речей треба виправити.",
1011
+ "other": "{count} речі треба виправити."
1012
+ }
1013
+ },
1014
+ "bug": {
1015
+ "checking": "Збираю дані про систему для звіту…",
1016
+ "opened": "У браузері відкрито новий звіт на GitHub із даними про твою систему: без карток і ключів, домашню теку записано як ~. Опиши, що сталося, і надішли; до того нічого не надсилається. Адреса звіту:",
1017
+ "notOpened": "Не вдалося відкрити браузер. Щоб повідомити про проблему, відкрий цю адресу: звіт уже містить дані про твою систему (без карток і ключів, домашню теку записано як ~), і нічого не надсилається, доки ти його не надішлеш."
1018
+ }
979
1019
  },
980
1020
  "tips": {
981
1021
  "keys-enter": {
@@ -1114,7 +1154,7 @@
1114
1154
  "preview": {
1115
1155
  "title": "Попередній перегляд",
1116
1156
  "subtitle": " вигадані дані · нічого не зберігається",
1117
- "keys": "↑/↓ вибрати · enter відтворити · esc вийти",
1157
+ "keys": "↑/↓ вибрати · enter відтворити · t тема · esc вийти",
1118
1158
  "replay": "enter ще раз · esc назад",
1119
1159
  "evolution": "Еволюція → {name}",
1120
1160
  "evolutionHint": {
@@ -1794,10 +1834,10 @@
1794
1834
  "title": "Голос",
1795
1835
  "note": "Голос, який читає слова, коли вимову ввімкнено. ElevenLabs необов'язковий: кожне слово створюється один раз і зберігається на цьому комп'ютері, тож ти платиш один раз за нову картку, а не за кожне повторення.",
1796
1836
  "now": "Зараз: {label}",
1797
- "system": "Голоси macOS",
1798
- "systemNote": "безкоштовно, вбудовані",
1837
+ "system": "Системні голоси",
1838
+ "systemNote": "безкоштовно, без інтернету",
1799
1839
  "elevenNote": "природні голоси, твій ключ, оплата за символи",
1800
- "systemSet": "Слова знову читають голоси macOS.",
1840
+ "systemSet": "Слова знову читають системні голоси.",
1801
1841
  "keyTitle": "Ключ ElevenLabs",
1802
1842
  "keyNote": "Ключ можна створити на {site}; ElevenLabs бере плату за використання. Встав його сюди: він зберігається в теці Dracosh, доступний лише тобі, і ніколи не потрапляє до резервних копій чи експорту. Або задай {env} у своїй оболонці.",
1803
1843
  "pickTitle": "Вибери голос",
@@ -1806,8 +1846,8 @@
1806
1846
  "noVoices": "У твоєму обліковому записі ElevenLabs немає голосів для вибору. Додай голос на elevenlabs.io і повернися сюди.",
1807
1847
  "current": "поточний",
1808
1848
  "checking": "Читання зразка голосом {label}…",
1809
- "ready": "Слова читає {label}. Мови, яких цей голос не знає, лишаються за голосами macOS.",
1810
- "readyOn": "Вимову ввімкнено: слова читає {label}. Мови, яких цей голос не знає, лишаються за голосами macOS.",
1849
+ "ready": "Слова читає {label}. Мови, яких цей голос не знає, лишаються за системними голосами.",
1850
+ "readyOn": "Вимову ввімкнено: слова читає {label}. Мови, яких цей голос не знає, лишаються за системними голосами.",
1811
1851
  "failedTitle": "{label} не працює",
1812
1852
  "otherVoice": "Вибрати інший голос",
1813
1853
  "sample": "Привіт! Я читатиму твої слова вголос.",
@@ -1818,10 +1858,10 @@
1818
1858
  "noVoice": "В ElevenLabs більше немає цього голосу: вибери інший."
1819
1859
  },
1820
1860
  "errors": {
1821
- "noKey": "Немає ключа ElevenLabs: додай його в /settings → Голос або задай {env}. Поки що слова читають голоси macOS.",
1822
- "badKey": "ElevenLabs не прийняв ключ. Встав новий у /settings → Голос. Поки що слова читають голоси macOS.",
1823
- "noCredit": "ElevenLabs: на рахунку закінчилися кошти. Поповни його на сайті ElevenLabs. Поки що слова читають голоси macOS.",
1824
- "noVoice": "В ElevenLabs більше немає цього голосу: вибери інший у /settings → Голос. Поки що слова читають голоси macOS.",
1861
+ "noKey": "Немає ключа ElevenLabs: додай його в /settings → Голос або задай {env}. Поки що слова читають системні голоси.",
1862
+ "badKey": "ElevenLabs не прийняв ключ. Встав новий у /settings → Голос. Поки що слова читають системні голоси.",
1863
+ "noCredit": "ElevenLabs: на рахунку закінчилися кошти. Поповни його на сайті ElevenLabs. Поки що слова читають системні голоси.",
1864
+ "noVoice": "В ElevenLabs більше немає цього голосу: вибери інший у /settings → Голос. Поки що слова читають системні голоси.",
1825
1865
  "rateLimit": "ElevenLabs: забагато запитів. Зачекай трохи й спробуй ще раз.",
1826
1866
  "offline": "Не вдається з'єднатися з ElevenLabs. Ти в мережі?",
1827
1867
  "timeout": "ElevenLabs надто довго не відповідає.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dracosh",
3
- "version": "0.8.0",
3
+ "version": "0.9.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",
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "scripts": {
40
40
  "start": "node src/cli.js",
41
- "test": "node --test test/",
41
+ "test": "node --test \"test/*.test.js\"",
42
42
  "sounds": "node scripts/make-sounds.js"
43
43
  },
44
44
  "dependencies": {
package/src/alerts.js CHANGED
@@ -4,48 +4,43 @@ import path from "node:path";
4
4
  import { tmpdir } from "node:os";
5
5
  import { rm } from "node:fs/promises";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { createNotifier } from "./notify.js";
8
+ import { createPlayer, findPlayers } from "./player.js";
9
+ import { createSpeech } from "./speech.js";
7
10
  import { speaksLanguage, speech } from "./voice.js";
8
11
 
9
12
  // 8-bit chiptune effects generated by scripts/make-sounds.js (see `npm run sounds`)
10
13
  const SOUND_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "sounds");
11
14
  const LADDER_STEPS = 6; // correct-0 … correct-5: the pitch climbs with your combo
12
15
 
13
- // Voices macOS has for a language (`say -v ?`), the novelty ones left out, the best first: a premium or
14
- // enhanced voice, then a plain named one. Read once, when the first word is spoken.
15
- const NOVELTY = new Set(["Albert", "Bad News", "Bahh", "Bells", "Boing", "Bubbles", "Cellos", "Good News", "Jester", "Organ", "Superstar", "Trinoids", "Whisper", "Wobble", "Zarvox", "Fred", "Junior", "Kathy", "Ralph", "Grandma", "Grandpa", "Rocko"]);
16
16
  const MAX_SPOKEN = 200; // characters: a long definition isn't read out whole
17
- const SPEECH_CODE = { no: "nb", nn: "nb" }; // macOS reads Norwegian as Bokmål
18
17
  const SPEAK_AFTER_MS = 500; // after the answer's chime, not over it
19
18
  const VOICE_WAIT_MS = 8_000; // a natural voice that takes longer gives the word to the system's
20
19
  const LATE_MS = 2_000; // a word that would come this much after its moment isn't read at all
21
- let voices = null;
22
- function voicesOnce() {
23
- voices ??= new Promise((resolve) =>
24
- execFile("say", ["-v", "?"], (err, out) =>
25
- resolve(err ? [] : String(out).split("\n").map((line) => line.match(/^(.+?)\s+([a-z]{2,3})_([A-Za-z0-9]+)\s+#/)).filter(Boolean).map(([, name, lang, region]) => ({ name: name.trim(), lang, region })))
26
- )
27
- );
28
- return voices;
29
- }
30
- // the region most learners mean (English from the US or Britain, not India; Chinese from the mainland)
31
- const REGIONS = { en: ["US", "GB"], zh: ["CN", "TW"], pt: ["PT", "BR"], es: ["ES", "MX"], fr: ["FR"], de: ["DE"], nl: ["NL"] };
32
- const rank = (voice) => {
33
- const regions = REGIONS[voice.lang] ?? [];
34
- const region = regions.includes(voice.region) ? regions.indexOf(voice.region) : regions.length;
35
- const quality = /\((Premium|Enhanced)\)/.test(voice.name) ? 0 : /\(/.test(voice.name) ? 2 : 1;
36
- return region * 10 + quality;
20
+
21
+ // a voice plays in the background: quitting right after an answer doesn't wait for it (the pipes would
22
+ // hold the app open too)
23
+ const runInBackground = (command, args, done) => {
24
+ const child = execFile(command, args, done);
25
+ for (const handle of [child, child.stdin, child.stdout, child.stderr]) handle?.unref?.();
26
+ return child;
37
27
  };
38
- export async function voiceFor(lang) {
39
- const code = SPEECH_CODE[lang] ?? lang;
40
- const found = (await voicesOnce()).filter((voice) => voice.lang === code && !NOVELTY.has(voice.name));
41
- return found.sort((a, b) => rank(a) - rank(b))[0]?.name ?? null;
42
- }
28
+ let spoken = 0; // numbers the words' temp files, so two in the same millisecond never share one
43
29
 
44
30
  // a voice that can't work until something is changed in /settings: not asked again this run
45
31
  const VOICE_STOPS = new Set(["noKey", "badKey", "noCredit", "noVoice"]);
46
32
 
47
- export function createAlerts(initial = {}) {
48
- const enabled = process.platform === "darwin";
33
+ // player, notifier: what plays the sounds and shows notifications; voicePlayer: what plays a voice's
34
+ // file (a natural voice's is an mp3); system: the system's voices, null without any (tests give their own)
35
+ export function createAlerts({
36
+ player = createPlayer(),
37
+ voicePlayer = createPlayer({ players: findPlayers({ mp3: true }), run: runInBackground }),
38
+ system = createSpeech({ run: runInBackground }),
39
+ notifier = createNotifier(),
40
+ ...initial
41
+ } = {}) {
42
+ // espeak-ng's .wav plays like the sounds (aplay included); say's .aiff the way a voice's file does
43
+ const systemPlayer = system?.ext === "wav" ? player : voicePlayer;
49
44
  // voice: settings.voice (null: the system's voices); onVoiceProblem(message): told once when it stops
50
45
  const config = { sound: true, volume: 0.5, speak: false, voice: null, onVoiceProblem: null, ...initial };
51
46
  // one word at a time: a newer one (or switching pronunciation off) cancels the one waiting or playing
@@ -63,28 +58,30 @@ export function createAlerts(initial = {}) {
63
58
  };
64
59
 
65
60
  const play = (name) => {
66
- if (!config.sound || !enabled) return;
67
- execFile("afplay", ["-v", String(config.volume), path.join(SOUND_DIR, `${name}.wav`)], () => {});
61
+ if (config.sound) player.play(path.join(SOUND_DIR, `${name}.wav`), config.volume);
68
62
  };
69
- const playVoice = (file, done = () => {}) => {
70
- const voiceOut = (speaking = execFile("afplay", ["-v", String(config.volume), file], done));
71
- voiceOut.unref();
63
+ const playVoice = (file, done) => {
64
+ speaking = voicePlayer.play(file, config.volume, done);
72
65
  };
73
66
 
74
- // the word in the system's voice: rendered to a file and played with afplay, so it follows the volume
75
- // like the sounds do (say's own volume command is ignored by today's voices)
67
+ // the word in the system's voice: rendered to a file, then played like the sounds are, so it follows
68
+ // the volume and can be cut off
76
69
  async function sayIt(words, lang, mine, at) {
77
- const voice = await voiceFor(lang);
70
+ const voice = await system?.voiceFor(lang);
78
71
  if (!voice || mine !== turn) return;
79
- const file = path.join(tmpdir(), `dracosh-${process.pid}-${Date.now()}.aiff`);
72
+ const file = path.join(tmpdir(), `dracosh-${process.pid}-${(spoken += 1)}.${system.ext}`);
73
+ const cleanUp = () => rm(file, { force: true }).catch(() => {});
80
74
  waiting = setTimeout(() => {
81
75
  waiting = null;
82
76
  if (!config.speak || mine !== turn) return;
83
- const render = (speaking = execFile("say", ["-v", voice, "-o", file, "--", words], (err) => {
84
- if (err || speaking !== render) return void rm(file, { force: true }).catch(() => {});
85
- playVoice(file, () => rm(file, { force: true }).catch(() => {}));
86
- }));
87
- render.unref();
77
+ try {
78
+ const render = (speaking = system.render(voice, words, file, config.volume, (err) => {
79
+ if (err || speaking !== render) return void cleanUp();
80
+ speaking = systemPlayer.play(file, system.playVolume(config.volume), cleanUp);
81
+ }));
82
+ } catch {
83
+ speaking = null; // a word the system can't take as an argument: better unread than a crash
84
+ }
88
85
  }, Math.max(0, at - Date.now()));
89
86
  waiting.unref(); // quitting right after an answer doesn't wait for the word
90
87
  }
@@ -99,28 +96,28 @@ export function createAlerts(initial = {}) {
99
96
  },
100
97
  // an audio file played now at the set volume, whatever the settings (a voice heard while picking it)
101
98
  playFile(file) {
102
- if (!enabled) return;
103
99
  hush();
104
100
  playVoice(file);
105
101
  },
106
- // a new question while you're in another window: sound plus a Notification Center banner
102
+ // a new question while you're in another window: sound plus a notification (the terminal's bell
103
+ // only stands in for the sound when none plays, so the two don't ring together)
107
104
  ask() {
108
105
  play("ask");
109
- // the text goes to AppleScript as an argument, never into the script itself
110
- if (enabled) execFile("osascript", ["-e", "on run argv", "-e", 'display notification (item 1 of argv) with title "Dracosh"', "-e", "end run", t("alerts.newCard")], () => {});
106
+ notifier.notify(t("alerts.newCard"), { bell: !config.sound || Boolean(player.silent) });
111
107
  },
112
108
  // a word read aloud in its language (/settings → Pronunciation), after the answer's chime, not over
113
- // it: in the natural voice when one is set and speaks the language, else in the system's (nothing
114
- // when macOS has no voice for it). A natural voice that fails leaves the word to the system's.
109
+ // it: in the natural voice when one is set, speaks the language and something can play it, else in
110
+ // the system's (nothing when the system has no voice for it). A natural voice that fails leaves the
111
+ // word to the system's.
115
112
  async speak(text, lang) {
116
113
  hush();
117
- if (!config.speak || !enabled || !text || !lang) return;
114
+ if (!config.speak || !text || !lang) return;
118
115
  const mine = turn;
119
116
  const at = Date.now() + SPEAK_AFTER_MS;
120
- const words = text.replace(/\[\[|\]\]|[{}\\]/g, "").slice(0, MAX_SPOKEN); // [[…]] would be a command; cloze braces aren't words
117
+ const words = text.replace(/\[\[|\]\]|[{}\\\0]/g, "").slice(0, MAX_SPOKEN); // [[…]] would be a command; cloze braces aren't words
121
118
  if (!words.trim()) return;
122
119
  // a voice that stopped working still plays the words it made before (no request: no key needed)
123
- if (config.voice && speaksLanguage(lang)) {
120
+ if (config.voice && speaksLanguage(lang) && !voicePlayer.silent) {
124
121
  const controller = (fetching = new AbortController());
125
122
  try {
126
123
  const file = await speech(config.voice, words.trim(), lang, { signal: controller.signal, timeoutMs: VOICE_WAIT_MS, ...(voiceDown ? { key: null } : {}) });
@@ -0,0 +1,63 @@
1
+ // Is the terminal's background light or dark? Asked once at start, for the auto theme.
2
+ //
3
+ // The terminal is asked for its background color (OSC 11) and then for its attributes (DA1). Every
4
+ // terminal answers DA1, and in order, so its answer means the color reply has come or never will:
5
+ // nothing is left to arrive later and show up as typed keys. A terminal that answers neither (an old
6
+ // console, a pipe) gets a short timeout, longer over SSH, where answers take a round trip. COLORFGBG,
7
+ // set by some terminals, is the fallback. Nothing here can stop the app: any failure means "not known".
8
+
9
+ const QUERY = "\x1b]11;?\x1b\\\x1b[c";
10
+ const COLOR = /\x1b\]11;rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i;
11
+ const ATTRIBUTES = /\x1b\[\?[\d;]*c/;
12
+ const TIMEOUT_MS = 200;
13
+ const SSH_TIMEOUT_MS = 1_000;
14
+
15
+ // "rgb:ffff/ffff/ffff" (1 to 4 hex digits per channel) to light or dark, by relative luminance
16
+ export function parseBackground(reply) {
17
+ const match = COLOR.exec(reply);
18
+ if (!match) return null;
19
+ const [r, g, b] = match.slice(1).map((hex) => {
20
+ const c = parseInt(hex, 16) / (16 ** hex.length - 1);
21
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
22
+ });
23
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.4 ? "light" : "dark";
24
+ }
25
+
26
+ // "15;0" (foreground;background, ANSI color numbers): 7 and 9 to 15 are light backgrounds
27
+ export function backgroundFromEnv(env = process.env) {
28
+ const last = env.COLORFGBG?.split(";").pop();
29
+ if (!last || !/^\d+$/.test(last)) return null;
30
+ const color = Number(last);
31
+ return color === 7 || (color >= 9 && color <= 15) ? "light" : "dark";
32
+ }
33
+
34
+ export function detectBackground({ stdin = process.stdin, stdout = process.stdout, env = process.env, timeoutMs = env.SSH_CONNECTION || env.SSH_TTY ? SSH_TIMEOUT_MS : TIMEOUT_MS } = {}) {
35
+ const fallback = backgroundFromEnv(env);
36
+ if (!stdin.isTTY || !stdout.isTTY || typeof stdin.setRawMode !== "function") return Promise.resolve(fallback);
37
+ return new Promise((resolve) => {
38
+ let reply = "";
39
+ const wasRaw = stdin.isRaw;
40
+ const finish = () => {
41
+ clearTimeout(timer);
42
+ stdin.removeListener("data", onData);
43
+ try {
44
+ stdin.setRawMode(wasRaw);
45
+ stdin.pause();
46
+ } catch {}
47
+ resolve(parseBackground(reply) ?? fallback);
48
+ };
49
+ const onData = (chunk) => {
50
+ reply += chunk.toString("latin1");
51
+ if (ATTRIBUTES.test(reply)) finish();
52
+ };
53
+ const timer = setTimeout(finish, timeoutMs);
54
+ try {
55
+ stdin.setRawMode(true);
56
+ stdin.on("data", onData);
57
+ stdin.resume();
58
+ stdout.write(QUERY);
59
+ } catch {
60
+ finish();
61
+ }
62
+ });
63
+ }
package/src/bug.js ADDED
@@ -0,0 +1,112 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { arch, release, version as osVersion } from "node:os";
4
+ import { checkAll, report } from "./doctor.js";
5
+ import { language, setLanguage } from "./i18n.js";
6
+
7
+ // `dracosh bug`: a new GitHub issue, filled in with the version, the system, Node, the terminal and the
8
+ // doctor's report, in English. Nothing personal: the report's safe lines carry no paths, addresses, names
9
+ // or what a server said. Nothing is sent: the browser opens the issue, and the person reads it and decides.
10
+
11
+ export const ISSUES = "https://github.com/lynthius/dracosh/issues/new";
12
+ const PACKAGE = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
13
+
14
+ const quiet = (command, args) => {
15
+ try {
16
+ return execFileSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3_000 }).trim();
17
+ } catch {
18
+ return "";
19
+ }
20
+ };
21
+
22
+ // "macOS 15.2", "Ubuntu 24.04.1 LTS", "Windows 11 Pro", with the kernel and the processor
23
+ export function systemName({ platform = process.platform, run = quiet, readOsRelease = () => readFileSync("/etc/os-release", "utf8") } = {}) {
24
+ let name = "";
25
+ if (platform === "darwin") {
26
+ const version = run("sw_vers", ["-productVersion"]);
27
+ name = version && `macOS ${version}`;
28
+ } else if (platform === "win32") name = osVersion();
29
+ else {
30
+ try {
31
+ name = readOsRelease().match(/^PRETTY_NAME="?([^"\n]*)"?/m)?.[1] ?? "";
32
+ } catch {}
33
+ }
34
+ return `${name || platform} (${platform} ${release()}, ${arch()})`;
35
+ }
36
+
37
+ // what the terminal says it is: iTerm, Apple Terminal, VS Code, kitty, Windows Terminal…
38
+ export function terminalName(env = process.env) {
39
+ if (env.WT_SESSION) return "Windows Terminal";
40
+ if (env.TERM_PROGRAM) return [env.TERM_PROGRAM, env.TERM_PROGRAM_VERSION].filter(Boolean).join(" ");
41
+ if (env.KITTY_WINDOW_ID) return "kitty";
42
+ if (env.ALACRITTY_SOCKET || env.ALACRITTY_LOG) return "Alacritty";
43
+ if (env.GNOME_TERMINAL_SCREEN || env.VTE_VERSION) return `VTE ${env.VTE_VERSION ?? ""}`.trim();
44
+ return env.TERM || "unknown";
45
+ }
46
+
47
+ export async function issueBody(settings, { system = systemName(), terminal = terminalName(), node = process.versions.node, checks } = {}) {
48
+ const own = language();
49
+ setLanguage("en"); // the report is read by the person fixing it
50
+ try {
51
+ const doctor = report(checks ?? (await checkAll(settings)), { safe: true });
52
+ return [
53
+ "**What happened?**",
54
+ "",
55
+ "",
56
+ "**What did you expect instead?**",
57
+ "",
58
+ "",
59
+ "**Steps to get there**",
60
+ "1. ",
61
+ "",
62
+ "**System**",
63
+ `- Dracosh ${PACKAGE.version}`,
64
+ `- ${system}`,
65
+ `- Node ${node}`,
66
+ `- Terminal: ${terminal}`,
67
+ `- App language: ${own}`,
68
+ "",
69
+ "**dracosh doctor**",
70
+ "```",
71
+ doctor,
72
+ "```"
73
+ ].join("\n");
74
+ } finally {
75
+ setLanguage(own);
76
+ }
77
+ }
78
+
79
+ // GitHub answers an address much longer than this with an error: the report then stays out
80
+ const MAX_URL = 7_000;
81
+ export function issueUrl(body) {
82
+ const url = (text) => `${ISSUES}?${new URLSearchParams({ labels: "bug", body: text })}`;
83
+ const full = url(body);
84
+ return full.length <= MAX_URL ? full : url(body.replace(/\*\*dracosh doctor\*\*[\s\S]*$/, "**dracosh doctor**\n(paste what `dracosh doctor` prints)"));
85
+ }
86
+
87
+ // The browser, the system's own way: open (macOS), xdg-open (Linux), the URL handler (Windows). Not over
88
+ // SSH (it would open on the other computer) or on Linux with no desktop (xdg-open would start a text
89
+ // browser in this terminal): the address is printed either way. The browser is left to start on its
90
+ // own; a program still running after a moment counts as opened.
91
+ const OPENERS = { darwin: ["open", []], win32: ["rundll32.exe", ["url.dll,FileProtocolHandler"]] };
92
+ const SETTLE_MS = 3_000;
93
+ export function canOpen({ platform = process.platform, env = process.env } = {}) {
94
+ if (env.SSH_CONNECTION || env.SSH_TTY) return false;
95
+ return platform === "darwin" || platform === "win32" || Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
96
+ }
97
+ export function openInBrowser(url, { platform = process.platform, env = process.env, run = spawn } = {}) {
98
+ if (!canOpen({ platform, env })) return Promise.resolve(false);
99
+ const [command, args] = OPENERS[platform] ?? ["xdg-open", []];
100
+ return new Promise((resolve) => {
101
+ try {
102
+ const child = run(command, [...args, url], { detached: true, stdio: "ignore", windowsHide: true });
103
+ const timer = setTimeout(() => resolve(true), SETTLE_MS);
104
+ timer.unref();
105
+ child.once("error", () => (clearTimeout(timer), resolve(false)));
106
+ child.once("exit", (code) => (clearTimeout(timer), resolve(code === 0)));
107
+ child.unref();
108
+ } catch {
109
+ resolve(false);
110
+ }
111
+ });
112
+ }
package/src/cli.js CHANGED
@@ -4,6 +4,9 @@ import React from "react";
4
4
  import { parseArgs } from "node:util";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import { createAlerts } from "./alerts.js";
7
+ import { detectBackground } from "./background.js";
8
+ import { issueBody, issueUrl, openInBrowser } from "./bug.js";
9
+ import { checkAll, report } from "./doctor.js";
7
10
  import { existsSync } from "node:fs";
8
11
  import { language, setLanguage, t } from "./i18n.js";
9
12
  import { BACKUP_DIR, dailyBackup, listBackups, restoreBackup, saveUpgraded } from "./backup.js";
@@ -16,6 +19,7 @@ import { seedLibrary } from "./starter.js";
16
19
  import { DATA_FILES, HOME, loadLibrary, loadSettingsRaw, loadState, patchSettings, saveLibrary } from "./store.js";
17
20
  import { App } from "./ui/App.js";
18
21
  import { Preview } from "./ui/Preview.js";
22
+ import { setBackground } from "./ui/kit.js";
19
23
  import { ALREADY_RUNNING, acquireLock, runningPid } from "./lock.js";
20
24
  import * as manage from "./manage.js";
21
25
  import { findDeck } from "./library.js";
@@ -82,6 +86,19 @@ async function printData() {
82
86
  console.log(`\n${t("cli.data.footer")}`);
83
87
  }
84
88
 
89
+ async function doctor(settings) {
90
+ const checks = await checkAll(settings);
91
+ console.log(report(checks));
92
+ if (checks.some((check) => check.status === "fail")) process.exitCode = 1;
93
+ }
94
+
95
+ async function bug(settings) {
96
+ console.log(t("cli.bug.checking"));
97
+ const url = issueUrl(await issueBody(settings));
98
+ const opened = await openInBrowser(url);
99
+ console.log(`${t(opened ? "cli.bug.opened" : "cli.bug.notOpened")}\n\n${url}`);
100
+ }
101
+
85
102
  async function restore(choice, { yes }) {
86
103
  const backups = await listBackups();
87
104
  if (!backups.length) return console.log(t("cli.restore.none", { dir: BACKUP_DIR }));
@@ -138,6 +155,8 @@ async function main() {
138
155
  if (values.help) return console.log(help());
139
156
  const [command, ...args] = positionals;
140
157
  if (command === "restore") return restore(args[0], values);
158
+ if (command === "doctor") return doctor(early);
159
+ if (command === "bug") return bug(early);
141
160
  if ((command === "import" || command === "export") && args.length > 1) throw new Error(t("cli.oneFile", { command }));
142
161
  if (command === "import") return runImport(args[0], values);
143
162
  if (command === "export") return runExport(args[0], values);
@@ -155,7 +174,8 @@ async function main() {
155
174
  if (values.preview) {
156
175
  if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
157
176
  const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak, voice: settings.voice });
158
- return render(React.createElement(Preview, { alerts })).waitUntilExit();
177
+ if (settings.theme === "auto") setBackground(await detectBackground());
178
+ return render(React.createElement(Preview, { alerts, theme: settings.theme })).waitUntilExit();
159
179
  }
160
180
 
161
181
  const state = await loadState();
@@ -185,6 +205,9 @@ async function main() {
185
205
  await patchSettings(patch);
186
206
  };
187
207
 
208
+ // only for the auto theme: a picked one needs no question, and auto picked later in /settings is dark
209
+ if (settings.theme === "auto") setBackground(await detectBackground());
210
+
188
211
  // the session summary screen stays on screen after exit, so nothing more to print here
189
212
  const app = render(React.createElement(App, { session, deck: deck.name, initialSettings: settings, initialMix: mix, alerts, persistSettings, library: manage, onSwitchDeck: (name) => (active = name), onMix: (decks) => (mix = decks) }));
190
213
  await app.waitUntilExit();