dracosh 0.6.0 → 0.8.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/README.md +45 -8
- package/locales/de.json +359 -11
- package/locales/en.json +359 -11
- package/locales/fr.json +375 -11
- package/locales/pl.json +391 -11
- package/locales/uk.json +391 -11
- package/package.json +1 -1
- package/src/ai.js +245 -0
- package/src/alerts.js +77 -23
- package/src/assist.js +232 -0
- package/src/cli.js +9 -5
- package/src/commands.js +3 -0
- package/src/firstwords.js +49 -0
- package/src/language.js +11 -6
- package/src/library.js +135 -3
- package/src/lock.js +1 -1
- package/src/manage.js +160 -4
- package/src/progress.js +8 -0
- package/src/session.js +38 -6
- package/src/settings.js +11 -1
- package/src/store.js +10 -4
- package/src/transfer.js +22 -5
- package/src/ui/AddCard.js +236 -38
- package/src/ui/Ai.js +284 -0
- package/src/ui/AnswerInput.js +35 -7
- package/src/ui/App.js +263 -18
- package/src/ui/Cards.js +350 -0
- package/src/ui/Choice.js +6 -1
- package/src/ui/Decks.js +181 -15
- package/src/ui/Import.js +316 -0
- package/src/ui/Languages.js +48 -9
- package/src/ui/Preview.js +22 -1
- package/src/ui/Settings.js +23 -7
- package/src/ui/Trash.js +63 -0
- package/src/ui/Voice.js +238 -0
- package/src/ui/Welcome.js +80 -0
- package/src/voice.js +129 -0
- package/src/words.js +27 -4
package/src/ai.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { t } from "./i18n.js";
|
|
4
|
+
import { HOME } from "./store.js";
|
|
5
|
+
|
|
6
|
+
// Where AI help comes from. Anthropic speaks its own API; everything else the OpenAI-compatible one
|
|
7
|
+
// (`/chat/completions`, `/models`), local servers included. `keyEnv`: the environment variable read
|
|
8
|
+
// for the key; `local`: runs on this computer, free and with no key.
|
|
9
|
+
export const PROVIDERS = {
|
|
10
|
+
anthropic: { api: "anthropic", url: "https://api.anthropic.com/v1", keyEnv: "ANTHROPIC_API_KEY", needsKey: true, model: "claude-haiku-5-5", site: "console.anthropic.com" },
|
|
11
|
+
openai: { api: "openai", url: "https://api.openai.com/v1", keyEnv: "OPENAI_API_KEY", needsKey: true, site: "platform.openai.com/api-keys" },
|
|
12
|
+
openrouter: { api: "openai", url: "https://openrouter.ai/api/v1", keyEnv: "OPENROUTER_API_KEY", needsKey: true, site: "openrouter.ai/keys" },
|
|
13
|
+
ollama: { api: "openai", url: "http://localhost:11434/v1", local: true },
|
|
14
|
+
lmstudio: { api: "openai", url: "http://localhost:1234/v1", local: true },
|
|
15
|
+
custom: { api: "openai", keyEnv: "DRACOSH_AI_KEY" } // any OpenAI-compatible address; a key only if it asks
|
|
16
|
+
};
|
|
17
|
+
export const PROVIDER_NAMES = { anthropic: "Anthropic", openai: "OpenAI", openrouter: "OpenRouter", ollama: "Ollama", lmstudio: "LM Studio", custom: null };
|
|
18
|
+
|
|
19
|
+
export const isUrl = (text) => typeof text === "string" && /^https?:\/\/[^\s/]+\S*$/i.test(text.trim());
|
|
20
|
+
export const cleanUrl = (text) => String(text).trim().replace(/\/+$/, "");
|
|
21
|
+
|
|
22
|
+
// settings.ai, as saved: { provider, model, url? } (url: the custom address, or a local server moved
|
|
23
|
+
// to another port), or null for no AI
|
|
24
|
+
export function normalizeAi(raw) {
|
|
25
|
+
if (!raw || typeof raw !== "object" || !Object.hasOwn(PROVIDERS, raw.provider)) return null;
|
|
26
|
+
const model = typeof raw.model === "string" && raw.model.trim() ? raw.model.trim() : null;
|
|
27
|
+
const url = isUrl(raw.url) && PROVIDERS[raw.provider].api === "openai" ? cleanUrl(raw.url) : null;
|
|
28
|
+
if (!model || (raw.provider === "custom" && !url)) return null;
|
|
29
|
+
return { provider: raw.provider, model, ...(url ? { url } : {}) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const providerName = (provider) => PROVIDER_NAMES[provider] ?? t("ai.customName");
|
|
33
|
+
// the endpoint as the screens show it: "✦ ollama · llama3.2"
|
|
34
|
+
export const aiLabel = (ai) => (ai ? `${providerName(ai.provider)} · ${ai.model}` : t("settings.off"));
|
|
35
|
+
export const urlOf = (ai) => ai.url ?? PROVIDERS[ai.provider].url;
|
|
36
|
+
// the settings row: the endpoint and what it costs, "LM Studio · free · qwen3" (the model last, as the
|
|
37
|
+
// part a narrow row can lose)
|
|
38
|
+
export const aiCostLabel = (ai) => (ai ? `${providerName(ai.provider)} · ${t(PROVIDERS[ai.provider].local ? "ai.free" : PROVIDERS[ai.provider].needsKey ? "ai.paid" : "ai.yourServer")} · ${ai.model}` : t("settings.off"));
|
|
39
|
+
// a small, cheap model by its name (mini, nano, haiku, flash, lite…): offered first where you pay per use
|
|
40
|
+
export const isSmallModel = (name) => /(^|[^a-z])(mini|ministral|nano|micro|haiku|flash|lite|small|tiny)([^a-z]|$)/i.test(name);
|
|
41
|
+
|
|
42
|
+
// Keys live in keys.json next to the data, readable by you only, and are never part of a backup or an
|
|
43
|
+
// export (DATA_FILES leaves the file out). A key in the environment wins over a saved one.
|
|
44
|
+
const KEYS_FILE = join(HOME, "keys.json");
|
|
45
|
+
|
|
46
|
+
async function readKeys() {
|
|
47
|
+
try {
|
|
48
|
+
const keys = JSON.parse(await readFile(KEYS_FILE, "utf8"));
|
|
49
|
+
return keys && typeof keys === "object" && !Array.isArray(keys) ? keys : {};
|
|
50
|
+
} catch {
|
|
51
|
+
return {}; // missing or broken: no saved keys, typed again when needed
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function writeKeys(keys) {
|
|
56
|
+
await mkdir(HOME, { recursive: true });
|
|
57
|
+
const tmp = `${KEYS_FILE}.${process.pid}.tmp`;
|
|
58
|
+
await writeFile(tmp, JSON.stringify(keys, null, 2), { mode: 0o600 });
|
|
59
|
+
await chmod(tmp, 0o600); // the mode above only counts for a file that wasn't there
|
|
60
|
+
await rename(tmp, KEYS_FILE);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// a key for "other" belongs to its address: it's never sent to another server
|
|
64
|
+
const slot = (provider, url) => (provider === "custom" ? `custom ${cleanUrl(url ?? "")}` : provider);
|
|
65
|
+
|
|
66
|
+
// keys kept here for more than AI help: natural voices (voice.js)
|
|
67
|
+
const OTHER_KEY_ENVS = { elevenlabs: "ELEVENLABS_API_KEY" };
|
|
68
|
+
|
|
69
|
+
const envKey = (provider) => {
|
|
70
|
+
const name = PROVIDERS[provider]?.keyEnv ?? OTHER_KEY_ENVS[provider];
|
|
71
|
+
const value = name && process.env[name]?.trim();
|
|
72
|
+
return value ? { key: value, from: "env", env: name } : null;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// → { key, from: "env" | "saved", env? } or null; `url`: the address, for "other"
|
|
76
|
+
export async function findKey(provider, url) {
|
|
77
|
+
const fromEnv = envKey(provider);
|
|
78
|
+
if (fromEnv) return fromEnv;
|
|
79
|
+
const saved = (await readKeys())[slot(provider, url)];
|
|
80
|
+
return typeof saved === "string" && saved ? { key: saved, from: "saved" } : null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function saveKey(provider, key, url) {
|
|
84
|
+
const keys = await readKeys();
|
|
85
|
+
keys[slot(provider, url)] = key.trim();
|
|
86
|
+
await writeKeys(keys);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function forgetKey(provider, url) {
|
|
90
|
+
const keys = await readKeys();
|
|
91
|
+
if (!(slot(provider, url) in keys)) return;
|
|
92
|
+
delete keys[slot(provider, url)];
|
|
93
|
+
await writeKeys(keys);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// a key shown without giving it away: "sk-a…f3c9"
|
|
97
|
+
export const maskKey = (key) => (key.length <= 10 ? "•".repeat(key.length) : `${key.slice(0, 4)}…${key.slice(-4)}`);
|
|
98
|
+
|
|
99
|
+
// What went wrong, said as what to do: `code` is noKey, badKey, noModel, noApi (an address that isn't
|
|
100
|
+
// such an API), rateLimit, noCredit (the account is out of credit), offline, offlineLocal (a server on this computer that isn't running),
|
|
101
|
+
// timeout, server or failed. The key is never part of the message.
|
|
102
|
+
export class AiError extends Error {
|
|
103
|
+
constructor(code, vars = {}) {
|
|
104
|
+
super(t(`ai.errors.${code}`, vars));
|
|
105
|
+
this.code = code;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const TIMEOUT_MS = 30_000;
|
|
110
|
+
|
|
111
|
+
// `onText`: the request streams (server-sent events), each piece of the answer heard as it comes; → the
|
|
112
|
+
// whole text then, the parsed JSON otherwise
|
|
113
|
+
async function call(ai, key, path, body, { signal, timeoutMs = TIMEOUT_MS, onText } = {}) {
|
|
114
|
+
const { api } = PROVIDERS[ai.provider];
|
|
115
|
+
const url = `${urlOf(ai)}${path}`;
|
|
116
|
+
const headers = { "content-type": "application/json" };
|
|
117
|
+
if (api === "anthropic") Object.assign(headers, { "x-api-key": key ?? "", "anthropic-version": "2023-06-01" });
|
|
118
|
+
else if (key) headers.authorization = `Bearer ${key}`;
|
|
119
|
+
if (ai.provider === "openrouter") headers["x-title"] = "Dracosh";
|
|
120
|
+
const vars = { provider: providerName(ai.provider), model: ai.model, url: urlOf(ai) };
|
|
121
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
122
|
+
let response;
|
|
123
|
+
try {
|
|
124
|
+
response = await fetch(url, { method: body ? "POST" : "GET", headers, body: body && JSON.stringify(body), signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
|
|
125
|
+
} catch (err) {
|
|
126
|
+
if (signal?.aborted) throw err; // cancelled by the caller: not a problem to show
|
|
127
|
+
if (timeout.aborted) throw new AiError("timeout", vars);
|
|
128
|
+
throw new AiError(PROVIDERS[ai.provider].local ? "offlineLocal" : "offline", vars);
|
|
129
|
+
}
|
|
130
|
+
let text;
|
|
131
|
+
try {
|
|
132
|
+
// a server that doesn't stream answers whole: its text, all at once
|
|
133
|
+
if (onText && response.ok && !/event-stream/i.test(response.headers.get("content-type") ?? "")) {
|
|
134
|
+
const whole = textOf(api, JSON.parse(await response.text()));
|
|
135
|
+
onText(whole, whole);
|
|
136
|
+
return whole;
|
|
137
|
+
}
|
|
138
|
+
if (onText && response.ok) return await readStream(response, api, onText, { ...vars, key });
|
|
139
|
+
text = await response.text();
|
|
140
|
+
} catch (err) {
|
|
141
|
+
if (err instanceof AiError) throw err;
|
|
142
|
+
if (signal?.aborted) throw err;
|
|
143
|
+
throw new AiError(timeout.aborted ? "timeout" : "offline", vars);
|
|
144
|
+
}
|
|
145
|
+
let data = null;
|
|
146
|
+
try {
|
|
147
|
+
data = JSON.parse(text);
|
|
148
|
+
} catch {}
|
|
149
|
+
if (response.ok && data) return data;
|
|
150
|
+
const said = reasonOf(data, key);
|
|
151
|
+
if (response.ok) throw new AiError("failed", { ...vars, status: response.status, detail: t("ai.errors.notJson") });
|
|
152
|
+
// out of credit: 402, OpenAI's insufficient_quota (a 429, like a passing rate limit, told apart by its
|
|
153
|
+
// code), or a refusal that says so (Anthropic: "Your credit balance is too low")
|
|
154
|
+
const code = data?.error?.code ?? data?.error?.type;
|
|
155
|
+
if (response.status === 402 || code === "insufficient_quota" || ([400, 403].includes(response.status) && /credit|quota|billing|balance/i.test(said))) throw new AiError("noCredit", vars);
|
|
156
|
+
if (response.status === 401 || response.status === 403) throw new AiError("badKey", vars);
|
|
157
|
+
if (response.status === 404 && !body) throw new AiError("noApi", vars); // listing models: the address is wrong
|
|
158
|
+
if (response.status === 404 || (response.status === 400 && /model/i.test(said) && /not|unknown|invalid|exist/i.test(said))) throw new AiError("noModel", vars);
|
|
159
|
+
if (response.status === 429) throw new AiError("rateLimit", vars);
|
|
160
|
+
if (response.status >= 500) throw new AiError("server", { ...vars, status: response.status });
|
|
161
|
+
throw new AiError("failed", { ...vars, status: response.status, detail: said || response.statusText });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// what a server said went wrong, never with the key in it (a server may repeat it)
|
|
165
|
+
function reasonOf(data, key) {
|
|
166
|
+
const reason = data?.error?.message ?? data?.error ?? data?.message ?? "";
|
|
167
|
+
return (typeof reason === "string" ? reason : JSON.stringify(reason)).split(key || "\u0000").join("…").slice(0, 200);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const textOf = (api, data) => (api === "anthropic" ? (data.content ?? []).filter((part) => part.type === "text").map((part) => part.text).join("") : String(data.choices?.[0]?.message?.content ?? ""));
|
|
171
|
+
|
|
172
|
+
// the text of a streamed answer: Anthropic's content_block_delta events, or OpenAI's chunks
|
|
173
|
+
async function readStream(response, api, onText, { key, ...vars }) {
|
|
174
|
+
const decoder = new TextDecoder();
|
|
175
|
+
let pending = "";
|
|
176
|
+
let whole = "";
|
|
177
|
+
const event = (line) => {
|
|
178
|
+
if (!line.startsWith("data:")) return;
|
|
179
|
+
const payload = line.slice(5).trim();
|
|
180
|
+
if (!payload || payload === "[DONE]") return;
|
|
181
|
+
let data;
|
|
182
|
+
try {
|
|
183
|
+
data = JSON.parse(payload);
|
|
184
|
+
} catch {
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (data.type === "error" || data.error) throw new AiError("failed", { ...vars, status: 200, detail: reasonOf(data, key) });
|
|
188
|
+
const piece = api === "anthropic" ? (data.type === "content_block_delta" && data.delta?.type === "text_delta" ? data.delta.text : "") : (data.choices?.[0]?.delta?.content ?? "");
|
|
189
|
+
if (piece) {
|
|
190
|
+
whole += piece;
|
|
191
|
+
onText(piece, whole);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
for await (const chunk of response.body) {
|
|
195
|
+
pending += decoder.decode(chunk, { stream: true });
|
|
196
|
+
const lines = pending.split(/\r\n|\r|\n/);
|
|
197
|
+
pending = lines.pop();
|
|
198
|
+
lines.forEach(event);
|
|
199
|
+
}
|
|
200
|
+
event(pending);
|
|
201
|
+
return whole;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function keyFor(ai) {
|
|
205
|
+
const found = await findKey(ai.provider, urlOf(ai));
|
|
206
|
+
if (!found && PROVIDERS[ai.provider].needsKey) throw new AiError("noKey", { provider: providerName(ai.provider), env: PROVIDERS[ai.provider].keyEnv });
|
|
207
|
+
return found?.key ?? null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// One answer from the model: `system` sets the task, `prompt` is the message. → the text. `key`: the
|
|
211
|
+
// key to use, null for none; left out, the saved one (or the environment's)
|
|
212
|
+
export async function ask(ai, { system, prompt, maxTokens = 400, signal, timeoutMs, key }) {
|
|
213
|
+
if (key === undefined) key = await keyFor(ai);
|
|
214
|
+
if (PROVIDERS[ai.provider].api === "anthropic") {
|
|
215
|
+
const data = await call(ai, key, "/messages", { model: ai.model, max_tokens: maxTokens, system, messages: [{ role: "user", content: prompt }] }, { signal, timeoutMs });
|
|
216
|
+
return textOf("anthropic", data).trim();
|
|
217
|
+
}
|
|
218
|
+
// OpenAI's newer models take max_completion_tokens; the compatible servers know max_tokens
|
|
219
|
+
const limit = ai.provider === "openai" ? { max_completion_tokens: maxTokens } : { max_tokens: maxTokens };
|
|
220
|
+
const data = await call(ai, key, "/chat/completions", { model: ai.model, ...limit, messages: [{ role: "system", content: system }, { role: "user", content: prompt }] }, { signal, timeoutMs });
|
|
221
|
+
return textOf("openai", data).trim();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// One answer, streamed: `onText`(piece, sofar) hears it as it's written. → the whole text
|
|
225
|
+
export async function stream(ai, { system, prompt, maxTokens = 2000, signal, timeoutMs = 120_000, key, onText }) {
|
|
226
|
+
if (key === undefined) key = await keyFor(ai);
|
|
227
|
+
if (PROVIDERS[ai.provider].api === "anthropic") return call(ai, key, "/messages", { model: ai.model, max_tokens: maxTokens, system, messages: [{ role: "user", content: prompt }], stream: true }, { signal, timeoutMs, onText });
|
|
228
|
+
const limit = ai.provider === "openai" ? { max_completion_tokens: maxTokens } : { max_tokens: maxTokens };
|
|
229
|
+
return call(ai, key, "/chat/completions", { model: ai.model, ...limit, messages: [{ role: "system", content: system }, { role: "user", content: prompt }], stream: true }, { signal, timeoutMs, onText });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// models that don't write text (embeddings, speech, images, moderation) can't suggest a card
|
|
233
|
+
const NOT_CHAT = /embed|tts|whisper|transcribe|dall-e|image|moderation|rerank|audio|realtime|search|codex/i;
|
|
234
|
+
|
|
235
|
+
// the models the endpoint offers, by name (a local server lists the ones downloaded)
|
|
236
|
+
export async function listModels(ai, { key, signal } = {}) {
|
|
237
|
+
if (key === undefined) key = await keyFor(ai);
|
|
238
|
+
const data = await call({ ...ai, model: ai.model ?? "" }, key, PROVIDERS[ai.provider].api === "anthropic" ? "/models?limit=1000" : "/models", null, { signal, timeoutMs: 15_000 });
|
|
239
|
+
const list = Array.isArray(data.data) ? data.data : Array.isArray(data.models) ? data.models : [];
|
|
240
|
+
const names = list.map((model) => model?.id ?? model?.name).filter((id) => typeof id === "string" && id && !NOT_CHAT.test(id));
|
|
241
|
+
return [...new Set(names)].sort((a, b) => a.localeCompare(b));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// a tiny request that proves the key, the address and the model work together
|
|
245
|
+
export const checkAi = (ai, { key } = {}) => ask(ai, { key, system: "Reply with the single word OK.", prompt: "OK?", maxTokens: 16 });
|
package/src/alerts.js
CHANGED
|
@@ -4,6 +4,7 @@ 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 { speaksLanguage, speech } from "./voice.js";
|
|
7
8
|
|
|
8
9
|
// 8-bit chiptune effects generated by scripts/make-sounds.js (see `npm run sounds`)
|
|
9
10
|
const SOUND_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "sounds");
|
|
@@ -15,6 +16,8 @@ const NOVELTY = new Set(["Albert", "Bad News", "Bahh", "Bells", "Boing", "Bubble
|
|
|
15
16
|
const MAX_SPOKEN = 200; // characters: a long definition isn't read out whole
|
|
16
17
|
const SPEECH_CODE = { no: "nb", nn: "nb" }; // macOS reads Norwegian as Bokmål
|
|
17
18
|
const SPEAK_AFTER_MS = 500; // after the answer's chime, not over it
|
|
19
|
+
const VOICE_WAIT_MS = 8_000; // a natural voice that takes longer gives the word to the system's
|
|
20
|
+
const LATE_MS = 2_000; // a word that would come this much after its moment isn't read at all
|
|
18
21
|
let voices = null;
|
|
19
22
|
function voicesOnce() {
|
|
20
23
|
voices ??= new Promise((resolve) =>
|
|
@@ -38,61 +41,112 @@ export async function voiceFor(lang) {
|
|
|
38
41
|
return found.sort((a, b) => rank(a) - rank(b))[0]?.name ?? null;
|
|
39
42
|
}
|
|
40
43
|
|
|
44
|
+
// a voice that can't work until something is changed in /settings: not asked again this run
|
|
45
|
+
const VOICE_STOPS = new Set(["noKey", "badKey", "noCredit", "noVoice"]);
|
|
46
|
+
|
|
41
47
|
export function createAlerts(initial = {}) {
|
|
42
48
|
const enabled = process.platform === "darwin";
|
|
43
|
-
|
|
49
|
+
// voice: settings.voice (null: the system's voices); onVoiceProblem(message): told once when it stops
|
|
50
|
+
const config = { sound: true, volume: 0.5, speak: false, voice: null, onVoiceProblem: null, ...initial };
|
|
44
51
|
// one word at a time: a newer one (or switching pronunciation off) cancels the one waiting or playing
|
|
52
|
+
let turn = 0;
|
|
45
53
|
let waiting = null;
|
|
46
54
|
let speaking = null;
|
|
55
|
+
let fetching = null;
|
|
56
|
+
let voiceDown = false;
|
|
47
57
|
const hush = () => {
|
|
58
|
+
turn += 1;
|
|
48
59
|
clearTimeout(waiting);
|
|
49
60
|
speaking?.kill();
|
|
50
|
-
|
|
61
|
+
fetching?.abort();
|
|
62
|
+
waiting = speaking = fetching = null;
|
|
51
63
|
};
|
|
52
64
|
|
|
53
65
|
const play = (name) => {
|
|
54
66
|
if (!config.sound || !enabled) return;
|
|
55
67
|
execFile("afplay", ["-v", String(config.volume), path.join(SOUND_DIR, `${name}.wav`)], () => {});
|
|
56
68
|
};
|
|
69
|
+
const playVoice = (file, done = () => {}) => {
|
|
70
|
+
const voiceOut = (speaking = execFile("afplay", ["-v", String(config.volume), file], done));
|
|
71
|
+
voiceOut.unref();
|
|
72
|
+
};
|
|
73
|
+
|
|
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)
|
|
76
|
+
async function sayIt(words, lang, mine, at) {
|
|
77
|
+
const voice = await voiceFor(lang);
|
|
78
|
+
if (!voice || mine !== turn) return;
|
|
79
|
+
const file = path.join(tmpdir(), `dracosh-${process.pid}-${Date.now()}.aiff`);
|
|
80
|
+
waiting = setTimeout(() => {
|
|
81
|
+
waiting = null;
|
|
82
|
+
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();
|
|
88
|
+
}, Math.max(0, at - Date.now()));
|
|
89
|
+
waiting.unref(); // quitting right after an answer doesn't wait for the word
|
|
90
|
+
}
|
|
57
91
|
|
|
58
92
|
return {
|
|
59
93
|
play,
|
|
60
94
|
configure(patch) {
|
|
95
|
+
// a voice picked again in /settings (a new key, say) is a new object: tried again
|
|
96
|
+
if ("voice" in patch && patch.voice !== config.voice) voiceDown = false;
|
|
61
97
|
Object.assign(config, patch);
|
|
62
98
|
if (!config.speak) hush();
|
|
63
99
|
},
|
|
100
|
+
// an audio file played now at the set volume, whatever the settings (a voice heard while picking it)
|
|
101
|
+
playFile(file) {
|
|
102
|
+
if (!enabled) return;
|
|
103
|
+
hush();
|
|
104
|
+
playVoice(file);
|
|
105
|
+
},
|
|
64
106
|
// a new question while you're in another window: sound plus a Notification Center banner
|
|
65
107
|
ask() {
|
|
66
108
|
play("ask");
|
|
67
109
|
// the text goes to AppleScript as an argument, never into the script itself
|
|
68
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")], () => {});
|
|
69
111
|
},
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
//
|
|
73
|
-
// a word read aloud in its language (/settings → Pronunciation); nothing when macOS has no voice for it
|
|
74
|
-
// Rendered to a file and played with afplay, so it follows the volume like the sounds do (say's own
|
|
75
|
-
// volume command is ignored by today's voices).
|
|
112
|
+
// 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.
|
|
76
115
|
async speak(text, lang) {
|
|
77
116
|
hush();
|
|
78
117
|
if (!config.speak || !enabled || !text || !lang) return;
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
hush(); // another word may have come meanwhile
|
|
118
|
+
const mine = turn;
|
|
119
|
+
const at = Date.now() + SPEAK_AFTER_MS;
|
|
82
120
|
const words = text.replace(/\[\[|\]\]|[{}\\]/g, "").slice(0, MAX_SPOKEN); // [[…]] would be a command; cloze braces aren't words
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
121
|
+
if (!words.trim()) return;
|
|
122
|
+
// a voice that stopped working still plays the words it made before (no request: no key needed)
|
|
123
|
+
if (config.voice && speaksLanguage(lang)) {
|
|
124
|
+
const controller = (fetching = new AbortController());
|
|
125
|
+
try {
|
|
126
|
+
const file = await speech(config.voice, words.trim(), lang, { signal: controller.signal, timeoutMs: VOICE_WAIT_MS, ...(voiceDown ? { key: null } : {}) });
|
|
127
|
+
if (mine !== turn) return;
|
|
128
|
+
fetching = null;
|
|
129
|
+
waiting = setTimeout(() => {
|
|
130
|
+
waiting = null;
|
|
131
|
+
if (config.speak && mine === turn) playVoice(file);
|
|
132
|
+
}, Math.max(0, at - Date.now()));
|
|
133
|
+
waiting.unref();
|
|
134
|
+
return;
|
|
135
|
+
} catch (err) {
|
|
136
|
+
if (controller.signal.aborted || mine !== turn) return;
|
|
137
|
+
fetching = null;
|
|
138
|
+
if (VOICE_STOPS.has(err.code) && !voiceDown) {
|
|
139
|
+
voiceDown = true;
|
|
140
|
+
config.onVoiceProblem?.(err.message);
|
|
141
|
+
}
|
|
142
|
+
if (Date.now() > at + LATE_MS) return; // the moment has passed: better quiet than late
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
await sayIt(words, lang, mine, at);
|
|
95
146
|
},
|
|
147
|
+
// The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
|
|
148
|
+
// On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
|
|
149
|
+
// on their own, each as its line lights up (see BadgeUnlock).
|
|
96
150
|
result(result, { cheers = [], combo = 0 } = {}) {
|
|
97
151
|
if (result === "wrong") return play("wrong");
|
|
98
152
|
for (const kind of ["evolve", "goal", "combo"]) {
|
package/src/assist.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { ask, PROVIDERS, stream } from "./ai.js";
|
|
2
|
+
import { parseLine } from "./cardline.js";
|
|
3
|
+
import { isKnown, languageName } from "./language.js";
|
|
4
|
+
|
|
5
|
+
// What AI help writes for a card, and how it's asked. It completes what you start: the back (and an
|
|
6
|
+
// example) for a front you typed, in the style of the deck's own cards. Only that front and a few
|
|
7
|
+
// cards of the same deck are sent.
|
|
8
|
+
const EXAMPLES = 5; // cards of the deck shown to the model as the style to follow
|
|
9
|
+
const MAX_TEXT = 200; // a definition can be a sentence
|
|
10
|
+
|
|
11
|
+
const MAX_CARDS = 50; // a list asked for in one go
|
|
12
|
+
const AVOID = 80; // fronts of the deck the model is told not to repeat
|
|
13
|
+
|
|
14
|
+
const english = (code) => (isKnown(code) ? languageName(code, "en") : null);
|
|
15
|
+
|
|
16
|
+
// a line of text from the model, safe to put into a card line: one line, no separators of its own
|
|
17
|
+
const clean = (text) => String(text ?? "").replace(/\s+/g, " ").replace(/ = /g, " ").replace(/ \/\/ /g, " ").trim().slice(0, MAX_TEXT);
|
|
18
|
+
const answer = (text) => clean(text).replace(/;/g, ","); // one answer; ";" would split it in two
|
|
19
|
+
|
|
20
|
+
// the model's answer → { back: [...], example }; JSON when it followed the instructions, a card line
|
|
21
|
+
// ("cat; kitty // The cat sleeps.") when it didn't
|
|
22
|
+
// A reasoning model's thoughts aren't the answer: <think>…</think> goes, and so does everything before a
|
|
23
|
+
// lone </think> (some templates open the thoughts in the prompt)
|
|
24
|
+
const answerPart = (text) => {
|
|
25
|
+
const end = text.lastIndexOf("</think>");
|
|
26
|
+
return (end >= 0 ? text.slice(end + 8) : text).replace(/<think>[\s\S]*?(<\/think>|$)/g, "");
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// the JSON object in a model's answer → the object, or null: the whole span from the first { to the
|
|
30
|
+
// last }, or when that isn't JSON (text with two objects), the last flat object that is
|
|
31
|
+
function jsonIn(text) {
|
|
32
|
+
const tries = [text.match(/\{[\s\S]*\}/)?.[0], ...(text.match(/\{[^{}]*\}/g) ?? []).reverse()].filter(Boolean);
|
|
33
|
+
for (const candidate of tries) {
|
|
34
|
+
try {
|
|
35
|
+
const data = JSON.parse(candidate);
|
|
36
|
+
if (data && typeof data === "object" && !Array.isArray(data)) return data;
|
|
37
|
+
} catch {}
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function readSuggestion(text) {
|
|
43
|
+
text = answerPart(String(text ?? ""));
|
|
44
|
+
const data = jsonIn(text);
|
|
45
|
+
if (data) {
|
|
46
|
+
const back = [data.back].flat().map(answer).filter(Boolean).slice(0, 3);
|
|
47
|
+
if (back.length) return { back, example: clean(data.example) };
|
|
48
|
+
}
|
|
49
|
+
const line = String(text ?? "").split(/\r?\n/).map((part) => part.trim()).find(Boolean) ?? "";
|
|
50
|
+
if (!line || line.startsWith("{")) return null;
|
|
51
|
+
const [backPart, example = ""] = line.split(" // ");
|
|
52
|
+
const back = backPart.split(";").map(clean).filter(Boolean).slice(0, 3);
|
|
53
|
+
return back.length ? { back, example: clean(example) } : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// What a deck holds, from its newest cards (the front being written, while it has none): "question"
|
|
57
|
+
// (most fronts ask something), "definition" (terms explained in one language) or "word". A deck in two
|
|
58
|
+
// languages is always words: its questions and sentences are to be translated, not answered.
|
|
59
|
+
export function deckKind({ front = "", languages = {}, cards = [] }) {
|
|
60
|
+
if (isKnown(languages.front) && isKnown(languages.back) && languages.front !== languages.back) return "word";
|
|
61
|
+
const recent = cards.filter((card) => !card.cloze && card.back?.length).slice(-10);
|
|
62
|
+
const asks = (text) => /\?\s*$/.test(text);
|
|
63
|
+
if (recent.length ? recent.filter((card) => asks(card.front)).length * 2 > recent.length : asks(front)) return "question";
|
|
64
|
+
const long = recent.length > 0 && recent.reduce((sum, card) => sum + card.back[0].length, 0) / recent.length > 30;
|
|
65
|
+
if ((isKnown(languages.front) && languages.front === languages.back) || long) return "definition";
|
|
66
|
+
return "word";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// `languages`: the deck's { front, back, learning } (codes, any of them unknown); `cards`: the deck's
|
|
70
|
+
// cards, the newest are the examples
|
|
71
|
+
export function suggestionPrompt({ front, languages = {}, cards = [] }) {
|
|
72
|
+
const frontLanguage = english(languages.front);
|
|
73
|
+
const backLanguage = english(languages.back);
|
|
74
|
+
const learning = english(languages.learning?.lang);
|
|
75
|
+
const examples = cards
|
|
76
|
+
.filter((card) => !card.cloze && card.back?.length)
|
|
77
|
+
.slice(-EXAMPLES)
|
|
78
|
+
.map((card) => JSON.stringify({ front: card.front, back: card.back, ...(card.example ? { example: card.example } : {}) }));
|
|
79
|
+
const withExamples = examples.some((line) => line.includes('"example"'));
|
|
80
|
+
const task = {
|
|
81
|
+
word: [
|
|
82
|
+
"You complete flashcards in a learner's vocabulary deck. Given the front of a card, write its back:",
|
|
83
|
+
"the usual translation or answer first, then up to two other accepted answers; keep each short, without",
|
|
84
|
+
"explanations. Add one short, natural example sentence that uses the word" + (learning ? ` in ${learning}.` : ".")
|
|
85
|
+
],
|
|
86
|
+
definition: [
|
|
87
|
+
"You complete flashcards in a learner's deck of terms and their definitions. Given the term on the front,",
|
|
88
|
+
"write a short, accurate definition for the back: one sentence, at most about 20 words, the way a good",
|
|
89
|
+
"dictionary or textbook puts it, without repeating the term.",
|
|
90
|
+
withExamples ? "Add one short example sentence that uses the term." : 'Leave "example" empty.'
|
|
91
|
+
],
|
|
92
|
+
question: [
|
|
93
|
+
"You complete flashcards in a learner's deck of questions and answers. Given the question on the front,",
|
|
94
|
+
"write its correct answer for the back: as short as it can be (a name, a number, a few words), then up to",
|
|
95
|
+
'two other accepted forms of the same answer. Leave "example" empty.'
|
|
96
|
+
]
|
|
97
|
+
}[deckKind({ front, languages, cards })];
|
|
98
|
+
const system = [
|
|
99
|
+
...task,
|
|
100
|
+
frontLanguage || backLanguage ? `The deck's fronts are in ${frontLanguage ?? "the same language as the examples"}, its backs in ${backLanguage ?? "the same language as the examples"}.` : "Follow the languages of the deck's cards.",
|
|
101
|
+
"Match the deck's own cards: their articles, capitalisation and style.",
|
|
102
|
+
'Reply with JSON only: {"back": ["..."], "example": "..."}'
|
|
103
|
+
].join(" ");
|
|
104
|
+
const prompt = [examples.length ? `Cards already in the deck:\n${examples.join("\n")}` : "", `Front: ${front}`].filter(Boolean).join("\n\n");
|
|
105
|
+
return { system, prompt };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// → { back, example } or null when the answer had nothing usable
|
|
109
|
+
export async function suggestCard(ai, { front, languages, cards, signal }) {
|
|
110
|
+
const { system, prompt } = suggestionPrompt({ front, languages, cards });
|
|
111
|
+
// room for a reasoning model's thinking (paid only as used); a model on this computer may be slow to load
|
|
112
|
+
const local = PROVIDERS[ai.provider].local;
|
|
113
|
+
return readSuggestion(await ask(ai, { system, prompt, maxTokens: local ? 2000 : 800, signal, timeoutMs: local ? 60_000 : 20_000 }));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// How the deck is written, for the model: its languages and a few of its cards as JSON
|
|
117
|
+
function deckContext({ languages = {}, cards = [] }) {
|
|
118
|
+
const frontLanguage = english(languages.front);
|
|
119
|
+
const backLanguage = english(languages.back);
|
|
120
|
+
const examples = cards
|
|
121
|
+
.filter((card) => !card.cloze && card.back?.length)
|
|
122
|
+
.slice(-EXAMPLES)
|
|
123
|
+
.map((card) => JSON.stringify({ front: card.front, back: card.back, ...(card.example ? { example: card.example } : {}) }));
|
|
124
|
+
const sides = frontLanguage || backLanguage ? `Fronts are in ${frontLanguage ?? "the language of the deck's fronts"}, backs in ${backLanguage ?? "the language of the deck's backs"}.` : "";
|
|
125
|
+
return { sides, examples, learning: english(languages.learning?.lang) };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// A list of new cards on a topic: `request` as you typed it ("20 words for the kitchen")
|
|
129
|
+
export function listPrompt({ request, languages, cards = [] }) {
|
|
130
|
+
const { sides, examples, learning } = deckContext({ languages, cards });
|
|
131
|
+
const fronts = cards.filter((card) => !card.cloze).slice(-AVOID).map((card) => card.front);
|
|
132
|
+
const system = [
|
|
133
|
+
"You write flashcards for a learner's vocabulary deck, on the topic or list they ask for.",
|
|
134
|
+
`Write as many cards as asked; if no number is given, write 10; never more than ${MAX_CARDS}.`,
|
|
135
|
+
"One card per line, in exactly this format and nothing else:",
|
|
136
|
+
"front = main answer; other accepted answer // one short example sentence",
|
|
137
|
+
"No numbering, bullets, headings, markdown or explanations. Keep answers short.",
|
|
138
|
+
sides || "If the deck has cards, follow their languages; otherwise use the languages the request implies.",
|
|
139
|
+
learning ? `The example sentence is in ${learning}.` : "",
|
|
140
|
+
"Match the deck's own cards: their articles, capitalisation and style. Everyday, useful words first."
|
|
141
|
+
].filter(Boolean).join(" ");
|
|
142
|
+
const prompt = [
|
|
143
|
+
examples.length ? `Cards already in the deck:\n${examples.join("\n")}` : "",
|
|
144
|
+
fronts.length ? `Don't repeat these fronts: ${fronts.join(", ")}` : "",
|
|
145
|
+
`Request: ${request}`
|
|
146
|
+
].filter(Boolean).join("\n\n");
|
|
147
|
+
return { system, prompt };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// a line of the model's list → card fields, or null for anything that isn't a card
|
|
151
|
+
export function readListLine(line) {
|
|
152
|
+
const text = String(line ?? "").replace(/^\s*(?:[-*•]|\d+[.)])\s+/, "").replace(/\*\*/g, "").trim();
|
|
153
|
+
if (!text.includes(" = ") || /^```/.test(text)) return null;
|
|
154
|
+
const fields = parseLine(text);
|
|
155
|
+
if (!fields.front || !fields.back.length || fields.cloze) return null;
|
|
156
|
+
return { front: clean(fields.front), back: fields.back.map(answer).filter(Boolean).slice(0, 3), example: clean(fields.example) };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Asks for a list, each card heard (`onCard`) as soon as its line is complete; thoughts of a reasoning
|
|
160
|
+
// model are skipped. → the number of cards
|
|
161
|
+
export async function suggestCards(ai, { request, languages, cards, signal, onCard }) {
|
|
162
|
+
const { system, prompt } = listPrompt({ request, languages, cards });
|
|
163
|
+
let sent = 0;
|
|
164
|
+
const enough = new AbortController(); // MAX_CARDS heard: the rest isn't read (or paid for)
|
|
165
|
+
const hear = (text, all = false) => {
|
|
166
|
+
const parts = answerPart(text).split(/\r\n|\r|\n/);
|
|
167
|
+
if (!all) {
|
|
168
|
+
parts.pop(); // the last line may still be coming
|
|
169
|
+
// prose before any </think> may be thoughts whose template opened them in the prompt: its
|
|
170
|
+
// cards wait for the end (a preamble like "Here are 10 words:" doesn't count)
|
|
171
|
+
if (!text.includes("</think>") && parts.some((line) => line.trim() && !readListLine(line) && !/:\s*$/.test(line))) return;
|
|
172
|
+
}
|
|
173
|
+
const found = parts.map(readListLine).filter(Boolean);
|
|
174
|
+
while (sent < found.length && sent < MAX_CARDS) onCard(found[sent++]);
|
|
175
|
+
if (sent >= MAX_CARDS) enough.abort();
|
|
176
|
+
};
|
|
177
|
+
const local = PROVIDERS[ai.provider].local;
|
|
178
|
+
try {
|
|
179
|
+
const whole = await stream(ai, { system, prompt, signal: signal ? AbortSignal.any([signal, enough.signal]) : enough.signal, maxTokens: local ? 6000 : 8000, timeoutMs: local ? 300_000 : 120_000, onText: (piece, sofar) => hear(sofar) });
|
|
180
|
+
hear(whole, true);
|
|
181
|
+
} catch (err) {
|
|
182
|
+
if (!enough.signal.aborted || signal?.aborted) throw err;
|
|
183
|
+
}
|
|
184
|
+
return sent;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Checking a card that's already written: is it right? `language`: the code of the language Dracosh
|
|
188
|
+
// speaks, for the note. → { system, prompt }
|
|
189
|
+
export function checkPrompt({ card, languages, cards = [], language = "en" }) {
|
|
190
|
+
const { sides, examples } = deckContext({ languages, cards: cards.filter((other) => other.id !== card.id) });
|
|
191
|
+
const system = [
|
|
192
|
+
"You check one flashcard from a learner's deck for mistakes: a wrong translation, definition or answer,",
|
|
193
|
+
"a misspelling, a wrong article or gender, an example sentence with an error, or a question so unclear",
|
|
194
|
+
"that more than one answer would be right. Don't change what isn't wrong: other wording, style or a",
|
|
195
|
+
"missing synonym is fine.",
|
|
196
|
+
sides,
|
|
197
|
+
`Reply with JSON only. If the card is right: {"ok": true}. If not: {"ok": false, "note": "one short sentence`,
|
|
198
|
+
`in ${english(language) ?? "English"} on what is wrong", "front": "...", "back": ["..."], "example": "..."},`,
|
|
199
|
+
"the whole card with the mistake fixed, in the deck's own style."
|
|
200
|
+
].filter(Boolean).join(" ");
|
|
201
|
+
const prompt = [examples.length ? `Other cards in the deck:\n${examples.join("\n")}` : "", `Card: ${JSON.stringify({ front: card.front, back: card.back, ...(card.example ? { example: card.example } : {}) })}`].filter(Boolean).join("\n\n");
|
|
202
|
+
return { system, prompt };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// the model's verdict → { ok: true } | { ok: false, note, fix } | null (unreadable). `fix`: the card
|
|
206
|
+
// as AI would have it, { front, back, example }, or null when it only says what's wrong. What the model
|
|
207
|
+
// gives back unchanged stays exactly as it was (not shortened or tidied).
|
|
208
|
+
export function readCheck(text, card) {
|
|
209
|
+
const data = jsonIn(answerPart(String(text ?? "")));
|
|
210
|
+
if (!data) return null;
|
|
211
|
+
if (data.ok === true || data.ok === "true") return { ok: true };
|
|
212
|
+
if (data.ok !== false && data.ok !== "false") return null;
|
|
213
|
+
const tidy = (value) => String(value).replace(/\s+/g, " ").trim();
|
|
214
|
+
const keep = (value, old, fresh) => (typeof value !== "string" || !value.trim() ? old : tidy(value) === tidy(old) ? old : fresh(value));
|
|
215
|
+
const given = (Array.isArray(data.back) ? data.back : typeof data.back === "string" ? data.back.split(";") : []).filter((value) => typeof value === "string" && value.trim());
|
|
216
|
+
const back = given.length ? given.map((value) => card.back.find((old) => tidy(old) === tidy(value)) ?? answer(value)).filter(Boolean) : card.back;
|
|
217
|
+
const fix = { front: keep(data.front, card.front, clean), back, example: data.example === undefined ? card.example ?? "" : keep(data.example, card.example ?? "", clean) };
|
|
218
|
+
if (data.example === "") fix.example = "";
|
|
219
|
+
const same = fix.front === card.front && fix.back.join("\n") === card.back.join("\n") && fix.example === (card.example ?? "");
|
|
220
|
+
const note = typeof data.note === "string" ? clean(data.note) : "";
|
|
221
|
+
if (same) return note ? { ok: false, note, fix: null } : { ok: true };
|
|
222
|
+
return { ok: false, note, fix };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// → the verdict on a card (see readCheck); throws AiError, or a plain one when the answer was unreadable
|
|
226
|
+
export async function checkCard(ai, { card, languages, cards, language, signal }) {
|
|
227
|
+
const { system, prompt } = checkPrompt({ card, languages, cards, language });
|
|
228
|
+
const local = PROVIDERS[ai.provider].local;
|
|
229
|
+
const verdict = readCheck(await ask(ai, { system, prompt, maxTokens: local ? 3000 : 1000, signal, timeoutMs: local ? 90_000 : 30_000 }), card);
|
|
230
|
+
if (!verdict) throw Object.assign(new Error("unreadable"), { code: "unreadable" });
|
|
231
|
+
return verdict;
|
|
232
|
+
}
|