dracosh 0.4.0 → 0.6.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/store.js CHANGED
@@ -4,7 +4,7 @@ import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { dayKey } from "./dates.js";
6
6
  import { upgradeLibrary } from "./library.js";
7
- import { itemKey, newToday } from "./scheduler.js";
7
+ import { fromBox, itemKey, newToday } from "./scheduler.js";
8
8
 
9
9
  export const HOME = process.env.DRACOSH_HOME || join(homedir(), ".dracosh");
10
10
  const LIBRARY_FILE = join(HOME, "library.json");
@@ -13,7 +13,8 @@ const SETTINGS_FILE = join(HOME, "settings.json");
13
13
  // everything a backup holds, by name
14
14
  export const DATA_FILES = { library: LIBRARY_FILE, state: STATE_FILE, settings: SETTINGS_FILE };
15
15
 
16
- export const STATE_VERSION = 1;
16
+ // 1: Leitner boxes (Dracosh 0.5 and older); 2: FSRS
17
+ export const STATE_VERSION = 2;
17
18
  const emptyState = () => ({ version: STATE_VERSION, items: {}, newToday: { date: "", count: 0 } });
18
19
 
19
20
  const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -57,12 +58,37 @@ export async function loadLibrary() {
57
58
  }
58
59
  export const saveLibrary = (library) => writeJson(LIBRARY_FILE, library);
59
60
 
60
- // Progress, checked for the shape the quiz relies on; a file from a newer Dracosh is never overwritten
61
+ // Progress, checked for the shape the quiz relies on; a file from a newer Dracosh is never overwritten.
62
+ // An older one is brought up to date in memory, `upgraded` saying so: it's written with the next save,
63
+ // once a backup holds the file as it was (see upgradeState).
61
64
  export async function loadState() {
62
65
  const state = await readJson(STATE_FILE, undefined);
63
66
  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"));
67
+ checkState(state, STATE_FILE);
68
+ if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
69
+ return upgradeState(state);
70
+ }
71
+
72
+ // progress of an older version → this one's (the same object); `upgraded` (not saved) says it changed
73
+ export function upgradeState(state) {
74
+ if ((state.version ?? 1) >= STATE_VERSION) return state;
75
+ for (const [key, entry] of Object.entries(state.items)) if (!("phase" in entry)) state.items[key] = fromBox(entry);
76
+ state.version = STATE_VERSION;
77
+ Object.defineProperty(state, "upgraded", { value: true, enumerable: false });
78
+ return state;
79
+ }
80
+
81
+ // a card's progress: Leitner's box in version 1, FSRS's memory since 2
82
+ const PHASES = new Set(["learning", "review", "relearning"]);
83
+ const fsrsEntry = (entry) => PHASES.has(entry.phase) && entry.stability > 0 && entry.difficulty > 0 && Number.isFinite(entry.last) && Number.isFinite(entry.seen);
84
+ const validEntry = (entry, version) => isObject(entry) && Number.isFinite(entry.due) && (fsrsEntry(entry) || (version < 2 && Number.isFinite(entry.box)));
85
+
86
+ // throws when `state` (read from `file`) isn't progress the quiz can use
87
+ export function checkState(state, file = STATE_FILE) {
88
+ if (!isObject(state) || !isObject(state.items)) throw damaged(file, t("errors.why.noProgress"));
89
+ // a newer Dracosh's progress may look different: said as that, not as damage
90
+ if (state.version > STATE_VERSION) throw new Error(t("errors.newerState", { file }));
91
+ if (!Object.values(state.items).every((entry) => validEntry(entry, state.version ?? 1))) throw damaged(file, t("errors.why.progressEntry"));
66
92
  const { progress } = state;
67
93
  const validProgress =
68
94
  isObject(progress) &&
@@ -72,10 +98,7 @@ export async function loadState() {
72
98
  ["count", "best", "freezes"].every((key) => Number.isFinite(progress.streak[key])) &&
73
99
  isObject(progress.badges) &&
74
100
  (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;
101
+ if (progress !== undefined && !validProgress) throw damaged(file, t("errors.why.streak"));
79
102
  }
80
103
  export const saveState = (state) => writeJson(STATE_FILE, state);
81
104
 
@@ -0,0 +1,557 @@
1
+ import { t } from "./i18n.js";
2
+ import { existsSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { readFile, stat, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { backupData, backupNow, restoreBackup } from "./backup.js";
8
+ import { plainFront } from "./cardline.js";
9
+ import { readCardList, separatorNamed } from "./cardlist.js";
10
+ import { applyImport, decodeText, markFromAnki, planCounts, planImport } from "./importer.js";
11
+ import { NOTE_TYPE_FIELDS, readApkg, toApkg } from "./apkg.js";
12
+ import { ankiDecks, connect, exportDeck, importIntoAnki, noteType } from "./ankiconnect.js";
13
+ import { loadSqlite } from "./sqlite.js";
14
+ import { EXPORT_FORMATS, toAnki, toCsv, toDracoshText } from "./exporter.js";
15
+ import { deckLanguages, isKnown, languageName } from "./language.js";
16
+ import { cardsOf, findDeck, MAX_DECK_NAME } from "./library.js";
17
+ import { ALREADY_RUNNING, runningPid } from "./lock.js";
18
+ import { checkState, damaged, DATA_FILES, HOME, loadLibrary, loadState, readJson, saveLibrary, saveState } from "./store.js";
19
+ import { upgradeLibrary } from "./library.js";
20
+ import { missingDeck } from "./words.js";
21
+
22
+ // `dracosh import` and `dracosh export`. An import always shows what it will do and asks first (in a
23
+ // terminal; elsewhere --yes says go), takes a backup before writing, and says how to undo it.
24
+
25
+ const SHOWN = 8; // problems or changed cards listed before "… and N more"
26
+ const MAX_FILE = 20e6; // a deck of a few hundred thousand cards; anything bigger is likely not one
27
+
28
+ // UTF-16 without a BOM: every other byte is zero
29
+ const looksUtf16 = (bytes) => {
30
+ const sample = bytes.subarray(0, 4000);
31
+ const zeros = (offset) => sample.filter((byte, i) => i % 2 === offset && byte === 0).length;
32
+ return sample.length >= 4 && Math.max(zeros(0), zeros(1)) > sample.length * 0.3 && Math.min(zeros(0), zeros(1)) === 0;
33
+ };
34
+ const out = (text = "") => console.log(text);
35
+
36
+ // Ctrl+C or Ctrl+D at a question stops here, before anything is written
37
+ async function ask(question) {
38
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
39
+ try {
40
+ return (await rl.question(question)).trim();
41
+ } catch {
42
+ out();
43
+ throw new Error(t("cli.restore.nothingChanged"));
44
+ } finally {
45
+ rl.close();
46
+ }
47
+ }
48
+
49
+ // A yes or no question: Enter takes the default, anything that's neither is asked again
50
+ async function confirm(question, byDefault) {
51
+ const words = (key) => t(key).split("|");
52
+ for (;;) {
53
+ const answer = (await ask(`${question} ${byDefault ? t("import.askSuffix") : t("cli.restore.askSuffix")} `)).toLowerCase();
54
+ if (!answer) return byDefault;
55
+ if (words("cli.restore.yes").includes(answer)) return true;
56
+ if (words("import.no").includes(answer)) return false;
57
+ }
58
+ }
59
+ const answers = (back) => back.join("; ");
60
+ // a cloze card keeps its {{gaps}} in the preview, so you see what will be asked
61
+ // a cloze card's back is a hint, not an answer: "Ella {{come}} pan. (hint: verb)"
62
+ const cardText = (fields) => (!fields.back.length ? fields.front : fields.cloze ? `${fields.front} ${t("import.hint", { hint: fields.back[0] })}` : `${fields.front} = ${answers(fields.back)}`);
63
+ const cut = (text, max = 60) => (Array.from(text).length > max ? `${Array.from(text).slice(0, max - 1).join("")}…` : text);
64
+ const more = (count) => count > 0 && out(` ${t("import.more", { count })}`);
65
+
66
+ // a file's name without its extension, as a deck name: "spanish-verbs.csv" → "spanish-verbs"
67
+ const deckFromFile = (file) => Array.from(basename(file, extname(file)).trim()).slice(0, MAX_DECK_NAME).join("");
68
+
69
+ const SEPARATOR_NAMES = { "\t": "tab", ",": "comma", ";": "semicolon", "|": "pipe", ":": "colon", " ": "space" };
70
+ function describeRead(read) {
71
+ if (read.format !== "table") return t(`import.formats.${read.format}`);
72
+ const separator = SEPARATOR_NAMES[read.separator] ? t(`import.separators.${SEPARATOR_NAMES[read.separator]}`) : `"${read.separator}"`;
73
+ const roles = ["deck", "front", "back", "example"].filter((role) => read.columns?.[role] !== null && read.columns?.[role] !== undefined);
74
+ const columns = roles.map((role) => t("import.column", { number: read.columns[role] + 1, role: t(`import.roles.${role}`) })).join(", ");
75
+ return t("import.formats.table", { separator, columns });
76
+ }
77
+
78
+ // `notes`: the cards came from an Anki package, so a place in it is a note's number, not a line
79
+ function issueText(problem, notes) {
80
+ if (problem.issue === "twice") return t(notes ? "import.issues.twiceNote" : "import.issues.twice", { line: problem.first });
81
+ if (problem.issue === "tooLong") return t("import.issues.tooLong", { max: MAX_DECK_NAME, deck: cut(problem.deck, 30) });
82
+ if (problem.issue === "tour") return t("import.issues.tour", { deck: problem.deck });
83
+ return t(`import.issues.${problem.issue}`);
84
+ }
85
+
86
+ const readError = (err, file) => {
87
+ const why = { ENOENT: "import.noFile", EISDIR: "import.isFolder", EACCES: "import.noPermission", EPERM: "import.noPermission", TOO_BIG: "import.tooBig" }[err.code];
88
+ return new Error(why ? t(why, { file, max: MAX_FILE / 1e6 }) : t("errors.cantRead", { file, error: err.message }));
89
+ };
90
+
91
+ // Anki's own packages need what Node has from 22.15 on (sqlite.js)
92
+ const needsNode = (err, key) => (err.code === "NEEDS_NODE" ? new Error(t(key, { version: err.version, current: process.versions.node })) : err);
93
+
94
+ // an Anki package (.apkg, .colpkg): read whole, however big its media (only the collection is unpacked)
95
+ async function readPackage(file) {
96
+ try {
97
+ if (!(await stat(file)).isFile()) throw Object.assign(new Error(), { code: "EISDIR" });
98
+ return await readApkg(file);
99
+ } catch (err) {
100
+ if (err.code === "NOT_ANKI") throw new Error(t("import.notAnki", { file }));
101
+ if (err.code === "NEEDS_NODE") throw needsNode(err, "import.needsNode");
102
+ throw ["ENOENT", "EISDIR", "EACCES", "EPERM"].includes(err.code) ? readError(err, file) : err;
103
+ }
104
+ }
105
+
106
+ async function readInput(file, encoding) {
107
+ let bytes;
108
+ if (file === "-") {
109
+ const chunks = [];
110
+ for await (const chunk of process.stdin) chunks.push(chunk);
111
+ bytes = Buffer.concat(chunks);
112
+ } else {
113
+ try {
114
+ if ((await stat(file)).size > MAX_FILE) throw Object.assign(new Error(), { code: "TOO_BIG" });
115
+ bytes = await readFile(file);
116
+ } catch (err) {
117
+ throw readError(err, file);
118
+ }
119
+ }
120
+ const name = file === "-" ? t("import.stdin") : file;
121
+ // a picture or a zip has zero bytes where text never does (UTF-16 is read before this)
122
+ const bom16 = (bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff);
123
+ if (!bom16 && !looksUtf16(bytes) && bytes.subarray(0, 8000).includes(0)) throw new Error(t("import.notText", { file: name }));
124
+ try {
125
+ return decodeText(bytes, encoding);
126
+ } catch (err) {
127
+ if (!err.samples) throw err;
128
+ const lines = err.samples.map((sample) => ` --encoding ${sample.encoding} ${sample.line}`);
129
+ throw new Error([t("import.notUtf8", { file: name }), ...lines, t("import.notUtf8Hint")].join("\n"));
130
+ }
131
+ }
132
+
133
+ // a full backup made by `dracosh export x.json`: brought back like `dracosh restore`, once each of its
134
+ // files is known to be one Dracosh can use (nothing is written otherwise)
135
+ async function importBackup(file, { yes: sure }) {
136
+ const running = runningPid();
137
+ if (running) throw new Error(ALREADY_RUNNING(running));
138
+ const backup = await readJson(file, null);
139
+ if (!backup) throw new Error(t("import.noFile", { file }));
140
+ if (backup.format !== 1 || !backup.files || typeof backup.files !== "object") throw new Error(t("errors.notABackup", { file }));
141
+ const { library, state, settings } = backup.files;
142
+ if (library !== undefined) {
143
+ try {
144
+ upgradeLibrary(library);
145
+ } catch (err) {
146
+ throw err.damaged ? damaged(file, err.message) : err;
147
+ }
148
+ }
149
+ if (state !== undefined) checkState(state, file);
150
+ if (settings !== undefined && (settings === null || typeof settings !== "object" || Array.isArray(settings))) throw damaged(file, t("errors.why.notLibrary"));
151
+ out(t("import.backupFile", { file }));
152
+ const now = await loadLibrary().catch(() => null);
153
+ if (now?.decks.some((deck) => !deck.tour)) out(t("import.backupReplaces", { decks: t("count.decks", { count: now.decks.filter((d) => !d.tour).length }), cards: t("count.cards", { count: now.cards.length }) }));
154
+ out(` ${t("cli.restore.row", { decks: t("count.decks", { count: library?.decks?.length ?? 0 }), cards: t("count.cards", { count: library?.cards?.length ?? 0 }), practised: Object.keys(state?.items ?? {}).length })}`);
155
+ if (Object.values(DATA_FILES).some((data) => existsSync(data))) out(t("cli.restore.undo"));
156
+ if (!sure) {
157
+ if (!process.stdin.isTTY) return out(t("cli.restore.needsYes"));
158
+ if (!(await confirm(t("import.backupAsk"), false))) return out(t("cli.restore.nothingChanged"));
159
+ }
160
+ await restoreBackup(file);
161
+ out(t("cli.restore.done"));
162
+ }
163
+
164
+ // a word for the shell, as typed: quoted when it needs to be ("Spanish verbs", it's, $5)
165
+ const shellQuote = (word) => (/^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, "'\\''")}'`);
166
+
167
+ // Anki's add-on said no, or nobody answered → what to do about it
168
+ function ankiError(err) {
169
+ if (err.code === "NEEDS_NODE") return needsNode(err, "import.needsNode");
170
+ const key = { NO_ANKI: "anki.notRunning", ANKI_BUSY: "anki.busy", BAD_URL: "anki.badUrl", OLD_ANKICONNECT: "anki.old", ANKI_KEY: "anki.key", NO_DECK: "anki.noDeck", NOT_IMPORTED: "anki.notImported", ANKI_ERROR: "anki.said" }[err.code];
171
+ return key ? new Error(t(key, { detail: err.detail })) : err;
172
+ }
173
+
174
+ // `dracosh import --anki ["Deck"]`: decks copied from a running Anki, as packages Anki writes itself
175
+ // and read like an .apkg. Without a deck, a terminal asks which; otherwise it's all of them.
176
+ // → the card list, and which decks it came from
177
+ async function readFromAnki(deckName, { interactive, yes }) {
178
+ const folder = mkdtempSync(join(tmpdir(), "dracosh-anki-"));
179
+ try {
180
+ await loadSqlite(); // what reading Anki's packages needs, before Anki is asked for any
181
+ const anki = connect();
182
+ const all = await ankiDecks(anki);
183
+ const decks = all.filter((deck) => deck.notes > 0 && !deck.filtered);
184
+ if (!decks.length) throw new Error(t("import.anki.empty"));
185
+ let chosen;
186
+ if (deckName) {
187
+ const deck = decks.find((each) => each.name.toLowerCase() === deckName.trim().toLowerCase());
188
+ if (!deck) throw new Error(t("import.anki.noDeck", { deck: deckName, decks: decks.map((each) => each.name).join(", ") }));
189
+ chosen = [deck.name];
190
+ } else if (interactive && !yes) {
191
+ out(t("import.anki.yourDecks"));
192
+ decks.forEach((deck, i) => out(` ${i + 1}. ${deck.name} (${t("count.cards", { count: deck.notes })})`));
193
+ for (;;) {
194
+ const answer = await ask(t("import.anki.which"));
195
+ if (/^q(uit)?$/i.test(answer)) throw new Error(t("cli.restore.nothingChanged"));
196
+ const numbers = answer.split(/[\s,]+/).filter(Boolean).map(Number);
197
+ if (!numbers.length) chosen = decks.map((deck) => deck.name);
198
+ else if (numbers.every((n) => Number.isInteger(n) && n >= 1 && n <= decks.length)) chosen = numbers.map((n) => decks[n - 1].name);
199
+ if (chosen) break;
200
+ }
201
+ } else chosen = decks.map((deck) => deck.name);
202
+ // a deck comes with its subdecks, so a subdeck of one already chosen isn't asked for again
203
+ chosen = [...new Set(chosen)].filter((name) => !chosen.some((other) => name.startsWith(`${other}::`)));
204
+ const list = { format: "apkg", separator: null, header: {}, items: [], columns: null, ignored: [], unknown: [], anki: true, html: true, media: 0 };
205
+ const inChosen = (deck) => chosen.some((name) => deck === name || deck?.startsWith(`${name}::`));
206
+ // a deck's export leaves out its cards lent to a filtered deck: those come from the filtered one
207
+ // (one inside a chosen deck comes with it); and a filtered deck inside a chosen one may hold
208
+ // other decks' cards, which stay out
209
+ const lending = all.filter((deck) => deck.filtered && deck.notes > 0 && !inChosen(deck.name)).map((deck) => deck.name);
210
+ for (const [i, name] of [...chosen, ...lending].entries()) {
211
+ if (i < chosen.length) out(t("import.anki.asking", { deck: name }));
212
+ const path = join(folder, `${i}.apkg`);
213
+ await exportDeck(anki, name, path);
214
+ const part = await readApkg(path);
215
+ const items = part.items.filter((item) => inChosen(item.deck));
216
+ list.items.push(...items.map((item, j) => ({ ...item, line: list.items.length + j + 1 })));
217
+ if (i < chosen.length) list.media += part.media;
218
+ }
219
+ return { list, decks: chosen };
220
+ } catch (err) {
221
+ throw ankiError(err);
222
+ } finally {
223
+ rmSync(folder, { recursive: true, force: true });
224
+ }
225
+ }
226
+
227
+ export async function runImport(file, options) {
228
+ const viaAnki = Boolean(options.anki);
229
+ if (!file && !viaAnki) throw new Error(t("import.needFile"));
230
+ const ending = viaAnki || file === "-" ? "" : extname(file).toLowerCase();
231
+ if (ending === ".json") return importBackup(file, options);
232
+ const isPackage = viaAnki || ending === ".apkg" || ending === ".colpkg";
233
+ if (isPackage && (options.separator !== undefined || options.encoding !== undefined)) throw new Error(t("import.notForPackage"));
234
+ const interactive = process.stdin.isTTY && file !== "-";
235
+ if (options.separator !== undefined && !separatorNamed(options.separator)) throw new Error(t("import.badSeparator", { value: options.separator }));
236
+ const anki = viaAnki ? await readFromAnki(file, { interactive, yes: options.yes }) : null;
237
+ const { text, encoding, list } = anki ? { text: null, encoding: "utf-8", list: anki.list } : isPackage ? { text: null, encoding: "utf-8", list: await readPackage(file) } : await readInput(file, options.encoding);
238
+ const library = await loadLibrary();
239
+ const csv = ending === ".csv";
240
+ const choices = { deck: options.deck ?? null, deckName: null, separator: options.separator, csv, directions: {}, split: Boolean(options.split), list };
241
+ const read = (from) => planImport(from, text, choices);
242
+ let plan = read(library);
243
+
244
+ if (anki) out(t("import.anki.read", { decks: anki.decks.join(", ") }));
245
+ else out(t("import.reading", { file: file === "-" ? t("import.stdin") : file, what: describeRead(plan.read) }) + (encoding === "utf-8" ? "" : t("import.encoding", { encoding: encoding.toUpperCase() })));
246
+ if (!plan.read.count) throw new Error(t("import.empty"));
247
+ if (plan.read.ignored.length) out(t("import.ignored", { count: plan.read.ignored.length, lines: lineList(plan.read.ignored) }));
248
+ if (plan.read.media) out(t("import.mediaLeft", { count: plan.read.media }));
249
+ // Dracosh's decks don't nest: "Spanish::Verbs" is a deck of its own
250
+ const nested = plan.decks.find((deck) => !deck.deck && deck.name.includes("::"));
251
+ if (isPackage && nested) out(t("import.subdecks", { deck: nested.name }));
252
+ // Anki's export without HTML runs an answer and its example together
253
+ if (plan.read.anki && !plan.read.html) out(t("import.ankiNoHtml"));
254
+
255
+ // the deck for cards the file doesn't put in one: --deck, or asked once the cards are on screen,
256
+ // or named after the file
257
+ if (plan.problems.some((p) => p.issue === "noDeck")) {
258
+ const suggested = file === "-" ? "" : deckFromFile(file);
259
+ if (interactive) {
260
+ const sample = readSample(text, choices);
261
+ out();
262
+ for (const fields of sample.slice(0, 3)) out(` ${cut(cardText(fields))}`);
263
+ more(sample.length - 3);
264
+ const own = library.decks.filter((d) => !d.tour);
265
+ const existing = suggested && own.find((d) => d.name.toLowerCase() === suggested.toLowerCase());
266
+ out();
267
+ if (own.length) out(t("import.yourDecks", { decks: own.map((d) => d.name).join(", ") }));
268
+ const question = existing
269
+ ? t("import.askDeckYours", { deck: existing.name, cards: t("count.cards", { count: cardsOf(library, existing.id).length }) })
270
+ : suggested
271
+ ? t("import.askDeck", { deck: suggested })
272
+ : t("import.askDeckEmpty");
273
+ choices.deckName = (await ask(question)) || existing?.name || suggested;
274
+ } else choices.deckName = suggested;
275
+ if (!choices.deckName) throw new Error(t("import.needDeck"));
276
+ plan = read(library);
277
+ }
278
+
279
+ // "cat, kitty": one answer listing several, as Anki and Quizlet decks often have them
280
+ if (plan.read.splittable && !choices.split) {
281
+ out();
282
+ out(t("import.listed", { count: plan.read.splittable, example: cut(plan.read.splitExample, 40) }));
283
+ if (interactive && !options.yes) {
284
+ choices.split = await confirm(t("import.splitAsk"), true);
285
+ if (choices.split) plan = read(library);
286
+ } else out(t("import.splitHint"));
287
+ }
288
+
289
+ const showPlan = () => {
290
+ for (const target of plan.decks) {
291
+ const added = target.items.filter((item) => item.kind === "new");
292
+ if (target.deck && !added.length) continue; // what's there already or changed is told below
293
+ out();
294
+ out(target.deck ? t("import.intoDeck", { deck: target.name, cards: t("count.cards", { count: cardsOf(library, target.deck.id).length }) }) : t("import.intoNewDeck", { deck: target.name }));
295
+ for (const item of added.slice(0, 3)) out(` + ${cut(cardText(item.fields))}${item.fields.example ? ` // ${cut(item.fields.example, 30)}` : ""}`);
296
+ more(added.length - 3);
297
+ // a new deck's languages, as they'll be guessed: seen before saving, and fixed in /decks
298
+ if (!target.deck) {
299
+ const languages = deckLanguages({ name: target.name }, target.items.map((item) => item.fields));
300
+ const sure = isKnown(languages.front) && isKnown(languages.back) && languages.front !== languages.back;
301
+ out(` ${sure ? t("import.languagesGuess", { front: languageName(languages.front), back: languageName(languages.back) }) : t("import.languagesUnsure")}`);
302
+ }
303
+ }
304
+ const counts = planCounts(plan);
305
+ out();
306
+ out([t("import.counts.new", { count: counts.new }), counts.same && t("import.counts.same", { count: counts.same }), counts.changed && t("import.counts.changed", { count: counts.changed })].filter(Boolean).join(" · "));
307
+ showProblems(plan.problems.filter((p) => p.issue !== "noDeck"), isPackage);
308
+ };
309
+ showPlan();
310
+
311
+ // cards already in the deck with other answers: never updated without asking
312
+ // true: every changed card; a Set: the ones shown here and agreed to
313
+ let update = Boolean(options.update);
314
+ const changed = plan.decks.flatMap((deck) => deck.items.filter((item) => item.kind === "changed"));
315
+ if (changed.length) {
316
+ out();
317
+ out(t("import.changedTitle", { count: changed.length }));
318
+ for (const item of changed.slice(0, SHOWN)) {
319
+ const before = item.card.cloze ? plainFront(item.card.front) : answers(item.card.back);
320
+ const after = item.fields.cloze ? plainFront(item.fields.front) : answers(item.fields.back);
321
+ const example = item.fields.example && item.fields.example !== item.card.example ? ` // ${cut(item.fields.example, 30)}` : "";
322
+ out(` ${cut(plainFront(item.card.front), 30)}: ${cut(before, 30)} → ${cut(after, 30)}${example}`);
323
+ }
324
+ more(changed.length - SHOWN);
325
+ if (!options.update && interactive && !options.yes) update = (await confirm(t("import.updateAsk", { count: changed.length }), false)) && new Set(changed.map((item) => item.card.id));
326
+ else if (!options.update) out(t("import.changedLeft"));
327
+ }
328
+
329
+ const adding = planCounts(plan).new;
330
+ const updating = update ? changed.length : 0;
331
+ if (!adding && !updating) {
332
+ // nothing to add, but cards found in Anki are remembered as such (a preview saves nothing)
333
+ if ((interactive || options.yes) && markFromAnki(structuredClone(library), plan)) {
334
+ const fresh = await loadLibrary();
335
+ if (markFromAnki(fresh, read(fresh))) await saveLibrary(fresh);
336
+ }
337
+ out();
338
+ return out(t("import.nothing"));
339
+ }
340
+
341
+ // how the new decks ask, unless the file says (#direction:): one question for all of them
342
+ const unasked = plan.decks.filter((deck) => !deck.deck && !deck.direction);
343
+ const sample = unasked.flatMap((deck) => deck.items).find((item) => !item.fields.cloze)?.fields;
344
+ if (sample && interactive && !options.yes) {
345
+ out();
346
+ out(unasked.length === 1 ? t("import.directionTitle", { deck: unasked[0].name }) : t("import.directionTitleMany", { count: unasked.length }));
347
+ out(` 1 ${cut(sample.front, 30)} → ? ${t("add.youType", { answer: cut(answers(sample.back), 30) })}`);
348
+ out(` 2 ${cut(answers(sample.back), 30)} → ? ${t("add.youType", { answer: cut(sample.front, 30) })}`);
349
+ out(` 3 ${t("add.bothWays")}`);
350
+ let picked = null;
351
+ while (!picked) picked = { "": "forward", 1: "forward", 2: "backward", 3: "both" }[await ask(t("import.directionAsk"))] ?? null;
352
+ for (const deck of unasked) choices.directions[deck.name] = picked;
353
+ // the answers typed now may start with "/": those cards are named before anything is saved
354
+ const before = plan.problems.length;
355
+ plan = read(library);
356
+ showProblems(plan.problems.slice(before).filter((p) => p.issue === "slash"), isPackage);
357
+ }
358
+
359
+ const counts = planCounts(plan);
360
+ const willUpdate = update ? counts.changed : 0;
361
+ if (!options.yes) {
362
+ if (!interactive) {
363
+ out();
364
+ const deckFlag = options.deck ? ` --deck ${shellQuote(options.deck)}` : file === "-" ? ` --deck ${shellQuote(choices.deckName)}` : "";
365
+ const source = anki ? `--anki${file ? ` ${shellQuote(file)}` : ""}` : shellQuote(file);
366
+ return out(t("import.previewOnly", { command: `dracosh import ${source}${deckFlag}${choices.split ? " --split" : ""} --yes` }));
367
+ }
368
+ out();
369
+ const question = !willUpdate
370
+ ? t("import.confirmAdd", { count: counts.new })
371
+ : !counts.new
372
+ ? t("import.confirmUpdate", { count: willUpdate })
373
+ : t("import.confirmBoth", { cards: t("count.cards", { count: counts.new }), count: willUpdate });
374
+ if (!(await confirm(question, true))) return out(t("cli.restore.nothingChanged"));
375
+ }
376
+
377
+ // the backup first, then read, change and save in one go: a quiz running meanwhile may have added cards
378
+ const backup = await backupNow("before-import"); // null on a first run: there's nothing to lose yet
379
+ const running = runningPid();
380
+ const state = running ? null : await loadState(); // read (and checked) before anything is written
381
+ const fresh = await loadLibrary();
382
+ const final = read(fresh);
383
+ const result = applyImport(fresh, final, { update, directions: choices.directions, keepTour: !state });
384
+ await saveLibrary(fresh);
385
+ // the tour's progress goes with it (a running quiz keeps the progress in memory: the tour stays then)
386
+ if (result.removedTour.length) {
387
+ const gone = new Set(result.removedTour);
388
+ for (const key of Object.keys(state.items)) if (gone.has(key.split(":")[0])) delete state.items[key];
389
+ await saveState(state);
390
+ }
391
+
392
+ out();
393
+ for (const deck of result.decks) {
394
+ if (deck.isNew) out(t("import.doneNew", { deck: deck.name, count: deck.added }));
395
+ else if (!deck.added) out(t("import.doneOnlyUpdated", { deck: deck.name, count: deck.updated }));
396
+ else out(t("import.done", { deck: deck.name, count: deck.added }) + (deck.updated ? t("import.doneUpdated", { count: deck.updated }) : ""));
397
+ }
398
+ for (const left of result.slash) out(` ${t("import.problemLine", { line: left.line, issue: t("import.issues.slash"), text: cut(left.text, 50) })}`);
399
+ if (result.removedTour.length) out(t("import.tourGone"));
400
+ if (backup) out(t("import.undo"));
401
+ const first = result.decks.find((d) => d.isNew) ?? result.decks[0];
402
+ // a name with a quote in it is quoted the other way, so the command can be pasted as it is
403
+ const quoted = (name) => (name.includes('"') ? `'${name.replace(/'/g, "'\\''")}'` : `"${name}"`);
404
+ if (first) out(running ? t("import.inDecks") : t("import.start", { deck: quoted(first.name) }));
405
+ }
406
+
407
+ // "3, 7, 9…": the first few line numbers of a list
408
+ const lineList = (lines) => lines.slice(0, 5).join(", ") + (lines.length > 5 ? "…" : "");
409
+
410
+ function showProblems(problems, notes = false) {
411
+ if (!problems.length) return;
412
+ out(t(notes ? "import.problemsNotes" : "import.problems", { count: problems.length }));
413
+ for (const problem of problems.slice(0, SHOWN)) out(` ${t(notes ? "import.problemNote" : "import.problemLine", { line: problem.line, issue: issueText(problem, notes), text: cut(problem.text.replace(/\t/g, " "), 50) })}`);
414
+ more(problems.length - SHOWN);
415
+ }
416
+
417
+ // the cards as read, before any deck is picked: for the question which deck they go into
418
+ const readSample = (text, { separator, csv, list }) => (list ?? readCardList(text, { separator, csv })).items.map((item) => item.fields).filter((fields) => fields.front);
419
+
420
+ // a file in Dracosh's own folder (library.json, a backup…) is never written over by an export
421
+ function insideData(file) {
422
+ const real = (path) => {
423
+ try {
424
+ return realpathSync(path);
425
+ } catch {
426
+ return existsSync(dirname(path)) ? resolve(realpathSync(dirname(path)), basename(path)) : resolve(path);
427
+ }
428
+ };
429
+ const home = real(HOME);
430
+ const target = real(file);
431
+ const inside = relative(home, target);
432
+ return target === home || (!inside.startsWith("..") && !inside.startsWith("/") && inside !== "") || Object.values(DATA_FILES).some((data) => real(data) === target);
433
+ }
434
+
435
+ export async function runExport(file, options) {
436
+ if (options.anki) return exportToAnki(file, options);
437
+ if (!file) throw new Error(t("export.needFile"));
438
+ const format = file === "-" ? "txt" : extname(file).slice(1).toLowerCase();
439
+ if (!EXPORT_FORMATS.includes(format)) throw new Error(t("export.unknownFormat", { file }));
440
+ if (format === "json" && options.deck) throw new Error(t("export.jsonAll"));
441
+ // a Node without what Anki packages need is said before anything is asked
442
+ if (format === "apkg") {
443
+ try {
444
+ await loadSqlite();
445
+ } catch (err) {
446
+ throw needsNode(err, "export.needsNode");
447
+ }
448
+ }
449
+
450
+ const library = await loadLibrary();
451
+ let decks = library.decks.filter((deck) => !deck.tour);
452
+ if (options.deck) {
453
+ const deck = findDeck(library, options.deck);
454
+ if (!deck) throw missingDeck(library, options.deck);
455
+ decks = [deck];
456
+ }
457
+ if (format !== "json" && !decks.length) throw new Error(t("export.noDecks"));
458
+
459
+ if (file !== "-" && insideData(file)) throw new Error(t("export.inData", { home: HOME }));
460
+ if (file !== "-" && existsSync(file) && !options.yes) {
461
+ if (!process.stdin.isTTY) throw new Error(t("export.existsNeedsYes", { file }));
462
+ if (!(await confirm(t("export.exists", { file }), false))) return out(t("cli.restore.nothingChanged"));
463
+ }
464
+
465
+ const write = async (path, text) => {
466
+ try {
467
+ await writeFile(path, format === "csv" ? `\uFEFF${text}` : text); // the BOM tells Excel it's UTF-8
468
+ } catch (err) {
469
+ throw new Error(t("export.cantWrite", { file: path, error: err.code === "ENOENT" ? t("export.noFolder") : err.message }));
470
+ }
471
+ };
472
+ const count = (cloze) => decks.reduce((sum, deck) => sum + cardsOf(library, deck.id).filter((card) => cloze === undefined || Boolean(card.cloze) === cloze).length, 0);
473
+
474
+ // for Anki, cloze cards go into a file of their own, next to the others ("spanish-cloze.tsv")
475
+ if (format === "tsv" && count(true)) {
476
+ const clozeFile = count(false) ? file.replace(/\.tsv$/i, "-cloze.tsv") : file;
477
+ if (clozeFile !== file && !options.yes && existsSync(clozeFile)) {
478
+ if (!process.stdin.isTTY) throw new Error(t("export.existsNeedsYes", { file: clozeFile }));
479
+ if (!(await confirm(t("export.exists", { file: clozeFile }), false))) return out(t("cli.restore.nothingChanged"));
480
+ }
481
+ if (count(false)) {
482
+ await write(file, toAnki(library, decks));
483
+ out(t("export.wrote", { count: count(false), file }));
484
+ out(t("export.next.tsv", { file }));
485
+ }
486
+ await write(clozeFile, toAnki(library, decks, { cloze: true }));
487
+ out(t("export.wroteCloze", { count: count(true), file: clozeFile }));
488
+ return out(t("export.nextCloze", { file: clozeFile }));
489
+ }
490
+
491
+ const contents = {
492
+ json: async () => `${JSON.stringify(await backupData("export"), null, 2)}\n`,
493
+ apkg: () => toApkg(library, decks),
494
+ tsv: () => toAnki(library, decks),
495
+ csv: () => toCsv(library, decks),
496
+ txt: () => toDracoshText(library, decks)
497
+ };
498
+ const text = await contents[format]();
499
+ if (file === "-") return process.stdout.write(text);
500
+ await write(file, text);
501
+ out(format === "json" ? t("export.wroteAll", { file }) : t("export.wrote", { count: count(), file }));
502
+ out(t(`export.next.${format}`, { file }));
503
+ const fromAnki = decks.reduce((sum, deck) => sum + cardsOf(library, deck.id).filter((card) => card.fromAnki).length, 0);
504
+ if (format === "apkg" && fromAnki) out(t("export.fromAnkiCopies", { count: fromAnki }));
505
+ }
506
+
507
+ // `dracosh export --anki`: the decks sent straight to a running Anki, as an .apkg its own importer
508
+ // takes (what File → Import does). It changes Anki's collection, so it's asked first.
509
+ async function exportToAnki(file, options) {
510
+ if (file) throw new Error(t("export.anki.noFile"));
511
+ try {
512
+ await loadSqlite();
513
+ } catch (err) {
514
+ throw needsNode(err, "export.needsNode");
515
+ }
516
+ const library = await loadLibrary();
517
+ // cards from Anki's own notes are there already: sent again they'd be a second copy
518
+ const sendable = (deck) => cardsOf(library, deck.id).filter((card) => !card.fromAnki);
519
+ let decks = library.decks.filter((deck) => !deck.tour);
520
+ if (options.deck) {
521
+ const deck = findDeck(library, options.deck);
522
+ if (!deck) throw missingDeck(library, options.deck);
523
+ decks = [deck];
524
+ }
525
+ const fromAnki = decks.reduce((sum, deck) => sum + cardsOf(library, deck.id).length - sendable(deck).length, 0);
526
+ decks = decks.filter((deck) => sendable(deck).length);
527
+ if (fromAnki) out(t("export.anki.fromAnki", { count: fromAnki }));
528
+ if (!decks.length) throw new Error(t(fromAnki ? "export.anki.nothingNew" : "export.noDecks"));
529
+ const cards = t("count.cards", { count: decks.reduce((sum, deck) => sum + sendable(deck).length, 0) });
530
+ const names = decks.map((deck) => deck.name).join(", ");
531
+ const anki = connect();
532
+ try {
533
+ // Anki is there before anything is asked, and its Dracosh note types are as Dracosh writes them:
534
+ // a note type someone changed in Anki would lose what they added when its notes are updated
535
+ for (const { id, fields } of NOTE_TYPE_FIELDS) {
536
+ const inAnki = await noteType(anki, id);
537
+ if (inAnki && inAnki.fields.join("\u0001") !== fields.join("\u0001")) throw new Error(t("export.anki.changedNoteType", { type: inAnki.name, fields: inAnki.fields.join(", ") }));
538
+ }
539
+ } catch (err) {
540
+ throw ankiError(err);
541
+ }
542
+ if (!options.yes) {
543
+ if (!process.stdin.isTTY) throw new Error(t("export.anki.needsYes"));
544
+ if (!(await confirm(t("export.anki.ask", { cards, decks: names }), true))) return out(t("cli.restore.nothingChanged"));
545
+ }
546
+ const folder = mkdtempSync(join(tmpdir(), "dracosh-anki-"));
547
+ try {
548
+ const path = join(folder, "dracosh.apkg");
549
+ await writeFile(path, await toApkg(library, decks, { skip: (card) => card.fromAnki }));
550
+ await importIntoAnki(anki, path);
551
+ } catch (err) {
552
+ throw ankiError(err);
553
+ } finally {
554
+ rmSync(folder, { recursive: true, force: true });
555
+ }
556
+ out(t("export.anki.sent", { cards, decks: names }));
557
+ }