dracosh 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,167 @@
1
+ import { Fragment, useState } from "react";
2
+ import { Box, useInput } from "ink";
3
+ import { language, t } from "../i18n.js";
4
+ import { fold } from "../judge.js";
5
+ import { DECK_LANGUAGES, GENDERED_LANGUAGES, isKnown, languageName, learningSide, UNKNOWN } from "../language.js";
6
+ import { cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
7
+
8
+ const SHOWN = 7; // rows of the list at a time
9
+
10
+ // One side as read: "polski"; a side you said is none in particular, "other or mixed"; one the cards
11
+ // didn't tell yet, "not sure yet"
12
+ const sideName = (code, guessed) => languageName(code) ?? t(guessed ? "languages.notYet" : "languages.mixed");
13
+ export const pairText = ({ front, back, guessed }) =>
14
+ guessed && !isKnown(front) && !isKnown(back) ? t("languages.notYet") : `${sideName(front, guessed)} → ${sideName(back, guessed)}`;
15
+
16
+ const look = (text) => fold(text.toLowerCase());
17
+
18
+ // a code as Intl writes it today ("iw" is "he", "in" is "id"), or null when it names no language
19
+ function canonical(code) {
20
+ try {
21
+ const [lang] = Intl.getCanonicalLocales(code)[0].split("-"); // "sh" is "sr-Latn": Serbian
22
+ return /^[a-z]{2,3}$/.test(lang) && languageName(lang, "en") !== lang ? lang : null;
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ // The languages whose name matches what's typed: in the UI's language, in English or in the language
29
+ // itself ("deutsch", "español"), or by code. The ones set or guessed and your own language come first;
30
+ // "other or mixed" last.
31
+ function matching(query, first) {
32
+ const all = [...new Set([...first.filter(isKnown), language(), ...DECK_LANGUAGES]), UNKNOWN];
33
+ const q = look(query.trim());
34
+ if (!q) return all;
35
+ const names = (code) => (code === UNKNOWN ? [t("languages.mixed")] : [languageName(code), languageName(code, "en"), languageName(code, code), code]);
36
+ const found = all.filter((code) => names(code).some((name) => name && look(name).includes(q)));
37
+ const starts = found.filter((code) => names(code).some((name) => name && look(name).startsWith(q)));
38
+ const ordered = [...new Set([...starts, ...found])];
39
+ const typed = /^[a-z]{2}$/.test(q) ? canonical(q) : null;
40
+ if (typed && !ordered.includes(typed)) ordered.unshift(typed);
41
+ return ordered;
42
+ }
43
+
44
+ // Which language the front and the back are in, one side after the other: type to search, ↑/↓ and Enter.
45
+ // `languages` holds what's set or guessed now (`guessed` marks a guess). With two different languages a
46
+ // third question follows: which one you're learning (`learning`: { lang } now, see learningSide).
47
+ // `start: "learning"` asks only that. → onDone({ front, back, learning }), `learning` a language code,
48
+ // null for a deck in one language. Esc clears the search, then goes back a step, then leaves (onCancel).
49
+ export function LanguagePicker({ deck, sample, languages, learning = null, home, start = "front", onDone, onCancel }) {
50
+ const panel = usePanelWidth();
51
+ const [side, setSide] = useState(start);
52
+ const [chosen, setChosen] = useState({ front: languages.front, back: languages.back });
53
+ const [query, setQuery] = useState("");
54
+ const listFor = (text, which = side) => matching(text, [chosen[which], languages[which]]);
55
+ const options = listFor(query);
56
+ // the language chosen so far stays selected until you search; then the best match is; never
57
+ // "other or mixed" by itself
58
+ const selectedIn = (list, which = side, text = query) => (text ? 0 : Math.max(0, isKnown(chosen[which]) ? list.indexOf(chosen[which]) : 0));
59
+ // the language you're learning stays selected; for a pair just picked, the guess for it
60
+ const learningIndex = (pair) => {
61
+ if (learning?.lang === pair.front) return 0;
62
+ if (learning?.lang === pair.back) return 1;
63
+ return learningSide(pair, { name: deck }, home)?.side === "front" ? 0 : 1;
64
+ };
65
+ const [selected, setSelected] = useState(() => (start === "learning" ? learningIndex(chosen) : selectedIn(options)));
66
+
67
+ function search(text, which = side) {
68
+ setQuery(text);
69
+ setSelected(selectedIn(listFor(text, which), which, text));
70
+ }
71
+
72
+ function turnTo(which) {
73
+ setSide(which);
74
+ search("", which);
75
+ }
76
+
77
+ function pick() {
78
+ const code = options[selected];
79
+ if (!code) return;
80
+ const next = { ...chosen, [side]: code };
81
+ setChosen(next);
82
+ if (side === "front") {
83
+ setSide("back");
84
+ setQuery("");
85
+ const list = matching("", [next.back, languages.back]);
86
+ return setSelected(Math.max(0, isKnown(next.back) ? list.indexOf(next.back) : 0));
87
+ }
88
+ if (isKnown(next.front) && isKnown(next.back) && next.front !== next.back) {
89
+ setSide("learning");
90
+ return setSelected(learningIndex(next));
91
+ }
92
+ onDone({ ...next, learning: null });
93
+ }
94
+
95
+ useInput((input, key) => {
96
+ if (side === "learning") {
97
+ if (key.escape || key.leftArrow) return start === "learning" ? onCancel() : turnTo("back");
98
+ if (key.upArrow || key.downArrow) return setSelected((i) => 1 - i);
99
+ if (input === "1" || input === "2") return onDone({ ...chosen, learning: input === "1" ? chosen.front : chosen.back });
100
+ if (key.return) return onDone({ ...chosen, learning: selected === 1 ? chosen.back : chosen.front });
101
+ return;
102
+ }
103
+ if (key.escape || key.leftArrow) {
104
+ if (query) return search("");
105
+ return side === "back" ? turnTo("front") : onCancel();
106
+ }
107
+ if (key.return) return pick();
108
+ if (key.upArrow) return setSelected((i) => Math.max(0, i - 1));
109
+ if (key.downArrow) return setSelected((i) => Math.max(0, Math.min(options.length - 1, i + 1)));
110
+ if (key.backspace || key.delete) return query && search(query.slice(0, -1));
111
+ if (key.ctrl && input === "u") return search("");
112
+ const text = input.replace(/[\u0000-\u001f\u007f]/g, ""); // a paste's line breaks and tabs aren't a name
113
+ if (text && !key.ctrl && !key.meta) search(query + text);
114
+ });
115
+
116
+ if (side === "learning")
117
+ return html`
118
+ <${Fragment}>
119
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
120
+ <${Text} bold color=${theme.accent}>${t("languages.learningQuestion", { deck })}<//>
121
+ <${Text} dimColor>${t("languages.learningNote")}${[chosen.front, chosen.back].some((code) => GENDERED_LANGUAGES.includes(code)) ? ` ${t("languages.learningArticles")}` : ""}${[chosen.front, chosen.back].includes("de") ? ` ${t("languages.learningUmlauts")}` : ""}<//>
122
+ <${Box} marginTop=${1} flexDirection="column">
123
+ ${["front", "back"].map((which, i) => html`<${Text} key=${which} color=${i === selected ? theme.accent : undefined} bold=${i === selected}>${i === selected ? "❯" : " "} ${i + 1}. ${languageName(chosen[which])}<//>`)}
124
+ <//>
125
+ <//>
126
+ <${Box} paddingX=${1}><${KeyHints} text=${t("keyHints.choiceLeft", { choose: t("choice.keys") })} /><//>
127
+ <//>
128
+ `;
129
+
130
+ const example = sample ? cutToWidth(side === "front" ? sample.front : sample.back.join(" / "), 24) : "";
131
+ const top = Math.max(0, Math.min(selected - Math.floor(SHOWN / 2), options.length - SHOWN));
132
+ const noteOf = (code) => {
133
+ if (code === UNKNOWN) return t("languages.mixedNote");
134
+ if (code !== languages[side]) return "";
135
+ return languages.guessed ? t("languages.guessed") : t("languages.current");
136
+ };
137
+ return html`
138
+ <${Fragment}>
139
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
140
+ <${Text} bold color=${theme.accent}>${t(side === "front" ? "languages.frontQuestion" : "languages.backQuestion", { deck })}<//>
141
+ ${example && html`<${Text} dimColor>${t("languages.example", { sample: example })}<//>`}
142
+ <${Box} marginTop=${1}>
143
+ <${Box} flexShrink=${0}><${Text} dimColor>${t("languages.search")} <//><//>
144
+ <${Text} wrap="truncate-start">${query}<//>
145
+ <${Box} flexShrink=${0}><${Text} inverse> <//><//>
146
+ <//>
147
+ <${Box} flexDirection="column">
148
+ ${options.length === 0 && html`<${Text} dimColor wrap="truncate-end">${t("languages.noMatch", { query: cutToWidth(query, 20) })}<//>`}
149
+ <${Text} dimColor>${top > 0 ? " ↑" : " "}<//>
150
+ ${options.slice(top, top + SHOWN).map((code, i) => {
151
+ const on = top + i === selected;
152
+ const name = code === UNKNOWN ? t("languages.mixed") : languageName(code);
153
+ const note = noteOf(code);
154
+ return html`
155
+ <${Box} key=${code}>
156
+ <${Box} flexShrink=${0}><${Text} color=${on ? theme.accent : undefined} bold=${on}>${on ? "❯" : " "} ${name}<//><//>
157
+ ${note && html`<${Text} dimColor wrap="truncate-end"> ${note}<//>`}
158
+ <//>
159
+ `;
160
+ })}
161
+ <${Text} dimColor>${top + SHOWN < options.length ? " ↓" : " "}<//>
162
+ <//>
163
+ <//>
164
+ <${Box} paddingX=${1}><${KeyHints} text=${t("keyHints.languagePick")} /><//>
165
+ <//>
166
+ `;
167
+ }
@@ -15,6 +15,7 @@ const ALL_ROWS = [
15
15
  { key: "rhythm", options: RHYTHMS, format: (v) => t(`settings.rhythms.${v}`) },
16
16
  { key: "everyMs", options: INTERVALS, format: formatInterval },
17
17
  { key: "sound", options: [true, false], format: (v) => t(v ? "settings.on" : "settings.off"), toggle: true },
18
+ { key: "speak", options: [false, true], format: (v) => t(v ? "settings.on" : "settings.off"), toggle: true },
18
19
  { key: "volume", options: VOLUMES, format: (v) => html`<${VolumeValue} value=${v} />` },
19
20
  { key: "dailyGoal", options: GOALS, format: (n) => t("settings.goal", { n }) },
20
21
  { key: "tips", options: TIP_MODES, format: (v) => t(`settings.tipModes.${v}`) },
package/src/ui/Summary.js CHANGED
@@ -1,34 +1,48 @@
1
1
  import { t } from "../i18n.js";
2
2
  import { Fragment } from "react";
3
3
  import { Box, useInput } from "ink";
4
- import { Bar, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
4
+ import { Bar, cellWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
5
5
  import { dragonName } from "../progress.js";
6
6
  import { Flame } from "./icons.js";
7
7
  import { Mascot, MASCOT_WIDTH } from "./Mascot.js";
8
8
 
9
+ const BAR = 12;
10
+ const MIN_BAR = 4;
11
+
9
12
  // The end-of-session screen: how this run went, shown on quit. Any key leaves for real.
10
13
  export function Summary({ stats, totals, bestCombo, onDone }) {
11
14
  const panel = usePanelWidth();
12
- useInput(() => onDone());
13
15
  const { streak, today, goal, companion } = stats;
16
+ // the "today" row fits beside the dragon: the bar shrinks first, then "goal reached" goes
17
+ const room = panel - 6 - (MASCOT_WIDTH + 3);
18
+ const count = ` ${Math.min(today.correct, goal)}/${goal}`;
19
+ const reached = today.goalMet ? cellWidth(t("summary.goalReached")) : 0;
20
+ const fitBar = (extra) => Math.min(BAR, room - cellWidth(t("summary.today")) - cellWidth(count) - extra);
21
+ const showReached = reached > 0 && fitBar(reached) >= MIN_BAR;
22
+ const barWidth = fitBar(showReached ? reached : 0);
23
+ useInput(() => onDone());
14
24
  const accuracy = totals.asked ? Math.round((totals.correct / totals.asked) * 100) : 0;
15
25
  const face = today.goalMet ? "happy" : totals.correct > 0 ? "smile" : "idle";
16
26
 
17
27
  return html`
18
28
  <${Fragment}>
19
29
  <${Box} borderStyle="round" borderColor=${theme.accent} paddingX=${2} paddingY=${1} width=${panel}>
20
- <${Box} flexDirection="column" width=${MASCOT_WIDTH + 3}>
30
+ <${Box} flexDirection="column" width=${MASCOT_WIDTH + 3} flexShrink=${0}>
21
31
  <${Mascot} face=${face} stage=${companion.index} element=${companion.element} />
22
32
  <//>
23
33
  <${Box} flexDirection="column" justifyContent="center">
24
34
  <${Box}><${Text} bold color=${theme.accent}>${t("summary.title")}<//><//>
25
35
  <${Box}><${Text}>${t("summary.result", { correct: totals.correct, asked: totals.asked, percent: accuracy })}${bestCombo >= 2 ? t("summary.bestCombo", { count: bestCombo }) : ""}<//><//>
26
- <${Box}>
27
- <${Text} dimColor>${t("summary.today")}<//>
28
- <${Bar} value=${today.correct} max=${goal} width=${12} color=${today.goalMet ? theme.good : theme.accent} />
29
- <${Text} dimColor> ${Math.min(today.correct, goal)}/${goal}<//>
30
- ${today.goalMet && html`<${Text} color=${theme.good}>${t("summary.goalReached")}<//>`}
31
- <//>
36
+ ${barWidth >= MIN_BAR
37
+ ? html`
38
+ <${Box}>
39
+ <${Text} dimColor>${t("summary.today")}<//>
40
+ <${Bar} value=${today.correct} max=${goal} width=${barWidth} color=${today.goalMet ? theme.good : theme.accent} />
41
+ <${Text} dimColor>${count}<//>
42
+ ${today.goalMet && showReached && html`<${Text} color=${theme.good}>${t("summary.goalReached")}<//>`}
43
+ <//>
44
+ `
45
+ : html`<${Text} dimColor>${t("summary.today").trim()} ${count.trim()}<//>`}
32
46
  <${Box}>
33
47
  ${streak.days > 0 && html`<${Box}><${Flame} /><${Text}> <//><//>`}
34
48
  <${Text} dimColor>${streak.days > 0 ? t("summary.streak", { count: streak.days }) : t("summary.noStreak")}${streak.atRisk ? t("summary.atRisk") : ""}<//>
package/src/words.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { t } from "./i18n.js";
2
+ import { deckLanguages, homeLanguages, learningSide } from "./language.js";
2
3
  import { cardsOf, findDeck, toWords } from "./library.js";
3
4
  import { loadLibrary } from "./store.js";
4
5
 
@@ -14,7 +15,11 @@ export async function loadWords(deckRef) {
14
15
  const library = await loadLibrary();
15
16
  const deck = deckRef ? findDeck(library, deckRef) : (library.decks.find((d) => !d.tour) ?? library.decks[0]);
16
17
  if (!deck) throw missingDeck(library, deckRef);
17
- return { words: toWords(cardsOf(library, deck.id)), deck: { name: deck.name, languages: deck.languages, directions: deck.directions, tour: Boolean(deck.tour) } };
18
+ const cards = cardsOf(library, deck.id);
19
+ // the tour is written in the UI's language on both sides: no pair to show or check by
20
+ const languages = deck.tour ? null : deckLanguages(deck, cards);
21
+ const home = homeLanguages({ others: library.decks.filter((d) => d !== deck && d.languages).map((d) => d.languages) });
22
+ return { words: toWords(cards), deck: { name: deck.name, languages, learning: deck.tour ? null : learningSide(languages, deck, home), directions: deck.directions, tour: Boolean(deck.tour) } };
18
23
  }
19
24
 
20
25
  // every deck of yours (not the tour), for "is anything still waiting today?"
package/src/zip.js ADDED
@@ -0,0 +1,157 @@
1
+ import { open } from "node:fs/promises";
2
+ import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
3
+
4
+ // A zip file (PKWARE APPNOTE 6.3), the container of an Anki package: each file deflated, names in
5
+ // UTF-8, no zip64 (an export never comes near 4 GB).
6
+ // writeZip([{ name: "media", data: Buffer }], { date }) → Buffer
7
+
8
+ const dosTime = (date) => (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
9
+ const dosDate = (date) => ((Math.max(date.getFullYear(), 1980) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
10
+ const UTF8_NAMES = 0x0800;
11
+ const DEFLATE = 8;
12
+ const VERSION = 20; // 2.0: deflate
13
+
14
+ export function writeZip(entries, { date = new Date() } = {}) {
15
+ const locals = [];
16
+ const centrals = [];
17
+ let offset = 0;
18
+ for (const { name, data } of entries) {
19
+ const nameBytes = Buffer.from(name, "utf8");
20
+ const packed = deflateRawSync(data);
21
+ if (packed.length > 0xffffffff || data.length > 0xffffffff || offset > 0xffffffff) throw new Error("Too big for a zip without zip64");
22
+ const crc = crc32(data);
23
+
24
+ const local = Buffer.alloc(30);
25
+ local.writeUInt32LE(0x04034b50, 0);
26
+ local.writeUInt16LE(VERSION, 4);
27
+ local.writeUInt16LE(UTF8_NAMES, 6);
28
+ local.writeUInt16LE(DEFLATE, 8);
29
+ local.writeUInt16LE(dosTime(date), 10);
30
+ local.writeUInt16LE(dosDate(date), 12);
31
+ local.writeUInt32LE(crc, 14);
32
+ local.writeUInt32LE(packed.length, 18);
33
+ local.writeUInt32LE(data.length, 22);
34
+ local.writeUInt16LE(nameBytes.length, 26);
35
+ local.writeUInt16LE(0, 28);
36
+ locals.push(local, nameBytes, packed);
37
+
38
+ const central = Buffer.alloc(46);
39
+ central.writeUInt32LE(0x02014b50, 0);
40
+ central.writeUInt16LE(VERSION, 4);
41
+ central.writeUInt16LE(VERSION, 6);
42
+ central.writeUInt16LE(UTF8_NAMES, 8);
43
+ central.writeUInt16LE(DEFLATE, 10);
44
+ central.writeUInt16LE(dosTime(date), 12);
45
+ central.writeUInt16LE(dosDate(date), 14);
46
+ central.writeUInt32LE(crc, 16);
47
+ central.writeUInt32LE(packed.length, 20);
48
+ central.writeUInt32LE(data.length, 24);
49
+ central.writeUInt16LE(nameBytes.length, 28);
50
+ // extra field, comment, disk number, internal and external attributes: all zero
51
+ central.writeUInt32LE(offset, 42);
52
+ centrals.push(central, nameBytes);
53
+
54
+ offset += local.length + nameBytes.length + packed.length;
55
+ }
56
+ const directory = Buffer.concat(centrals);
57
+ const end = Buffer.alloc(22);
58
+ end.writeUInt32LE(0x06054b50, 0);
59
+ end.writeUInt16LE(entries.length, 8);
60
+ end.writeUInt16LE(entries.length, 10);
61
+ end.writeUInt32LE(directory.length, 12);
62
+ end.writeUInt32LE(offset, 16);
63
+ return Buffer.concat([...locals, directory, end]);
64
+ }
65
+
66
+ const STORED = 0;
67
+ const END = 0x06054b50;
68
+ const END64 = 0x06064b50;
69
+ const END64_LOCATOR = 0x07064b50;
70
+ const CENTRAL = 0x02014b50;
71
+ const LOCAL = 0x04034b50;
72
+ const ZIP64_EXTRA = 0x0001;
73
+ const damaged = (why) => Object.assign(new Error(`Damaged zip file: ${why}`), { code: "DAMAGED_ZIP" });
74
+
75
+ // readZip(file, names, { first }) → Map of name → Buffer, for just the files asked for (an Anki
76
+ // package can hold gigabytes of media next to the collection); `first`: only the first of `names`
77
+ // there is. Stored or deflated files, zip64 too (what Anki writes past 4 GB).
78
+ export async function readZip(file, names, { first = false } = {}) {
79
+ const handle = await open(file, "r");
80
+ try {
81
+ const { size } = await handle.stat();
82
+ const read = async (position, length) => {
83
+ if (position < 0 || length < 0 || position + length > size) throw damaged("a part points outside the file");
84
+ const buffer = Buffer.alloc(length);
85
+ const { bytesRead } = await handle.read(buffer, 0, length, position);
86
+ if (bytesRead < length) throw damaged("the file ends early");
87
+ return buffer;
88
+ };
89
+ // the end record is in the last 22 bytes, or before a comment of up to 64 KB
90
+ const tailStart = Math.max(0, size - 22 - 0xffff);
91
+ const tail = await read(tailStart, size - tailStart);
92
+ let endAt = -1;
93
+ for (let i = tail.length - 22; i >= 0 && endAt < 0; i--) if (tail.readUInt32LE(i) === END) endAt = i;
94
+ if (endAt < 0) throw Object.assign(new Error("Not a zip file"), { code: "NOT_ZIP" });
95
+ let count = tail.readUInt16LE(endAt + 10);
96
+ let directorySize = tail.readUInt32LE(endAt + 12);
97
+ let directoryAt = tail.readUInt32LE(endAt + 16);
98
+ // zip64: the real numbers are in a record of their own, which a locator just before this one finds
99
+ if (count === 0xffff || directorySize === 0xffffffff || directoryAt === 0xffffffff) {
100
+ const locator = endAt - 20;
101
+ if (locator < 0 || tail.readUInt32LE(locator) !== END64_LOCATOR) throw damaged("no zip64 end record");
102
+ const end64 = await read(Number(tail.readBigUInt64LE(locator + 8)), 56);
103
+ if (end64.readUInt32LE(0) !== END64) throw damaged("no zip64 end record");
104
+ count = Number(end64.readBigUInt64LE(32));
105
+ directorySize = Number(end64.readBigUInt64LE(40));
106
+ directoryAt = Number(end64.readBigUInt64LE(48));
107
+ }
108
+ const directory = await read(directoryAt, directorySize);
109
+ const found = new Map();
110
+ for (let at = 0, i = 0; i < count; i++) {
111
+ if (at + 46 > directory.length || directory.readUInt32LE(at) !== CENTRAL) throw damaged("a broken directory");
112
+ const nameLength = directory.readUInt16LE(at + 28);
113
+ const extraLength = directory.readUInt16LE(at + 30);
114
+ const next = at + 46 + nameLength + extraLength + directory.readUInt16LE(at + 32);
115
+ if (next > directory.length) throw damaged("a broken directory");
116
+ const name = directory.toString("utf8", at + 46, at + 46 + nameLength);
117
+ if (names.includes(name)) {
118
+ const entry = { method: directory.readUInt16LE(at + 10), packed: directory.readUInt32LE(at + 20), size: directory.readUInt32LE(at + 24), local: directory.readUInt32LE(at + 42) };
119
+ // zip64 sizes and offset, in that order, only for the ones that didn't fit
120
+ let extra = at + 46 + nameLength;
121
+ const extraEnd = extra + extraLength;
122
+ while (extra + 4 <= extraEnd) {
123
+ const [id, length] = [directory.readUInt16LE(extra), directory.readUInt16LE(extra + 2)];
124
+ if (id === ZIP64_EXTRA) {
125
+ let field = extra + 4;
126
+ for (const key of ["size", "packed", "local"]) {
127
+ if (entry[key] !== 0xffffffff) continue;
128
+ if (field + 8 > extra + 4 + length) throw damaged("a broken zip64 field");
129
+ entry[key] = Number(directory.readBigUInt64LE(field));
130
+ field += 8;
131
+ }
132
+ }
133
+ extra += 4 + length;
134
+ }
135
+ found.set(name, entry);
136
+ }
137
+ at = next;
138
+ }
139
+ const wanted = first ? names.filter((name) => found.has(name)).slice(0, 1) : names.filter((name) => found.has(name));
140
+ const files = new Map();
141
+ for (const name of wanted) {
142
+ const { method, packed: packedSize, size: unpackedSize, local } = found.get(name);
143
+ const header = await read(local, 30);
144
+ if (header.readUInt32LE(0) !== LOCAL) throw damaged(`no header for ${name}`);
145
+ const packed = await read(local + 30 + header.readUInt16LE(26) + header.readUInt16LE(28), packedSize);
146
+ if (method === STORED) files.set(name, packed);
147
+ else if (method === DEFLATE) {
148
+ const data = inflateRawSync(packed);
149
+ if (data.length !== unpackedSize) throw damaged(`${name} unpacks to the wrong size`);
150
+ files.set(name, data);
151
+ } else throw damaged(`unsupported compression in ${name}`);
152
+ }
153
+ return files;
154
+ } finally {
155
+ await handle.close();
156
+ }
157
+ }