dsh-external-toolbox 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +189 -2
- package/cordis.patch.yml +9 -0
- package/helper/capture.ps1 +3291 -0
- package/icon.png +0 -0
- package/lib/client.js +264 -0
- package/lib/index.js +860 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +67 -4
- package/tools/say.mjs +52 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,860 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-external-toolbox - host half.
|
|
3
|
+
*
|
|
4
|
+
* 1. Runs `helper/capture.ps1` as a long-lived child process. That helper owns a
|
|
5
|
+
* system-wide hotkey, grabs the selection in whatever application has focus,
|
|
6
|
+
* and shows its own floating card - so translating never needs the DSH
|
|
7
|
+
* window to be visible.
|
|
8
|
+
* 2. Serves two exact same-origin GET routes for that helper and for the web
|
|
9
|
+
* half:
|
|
10
|
+
* /toolbox/translate?id=<id>&to=<lang> -> JSON { ok, text } / { ok:false, error }
|
|
11
|
+
* /toolbox/latest -> JSON { seq, id, text, via, at, intent }
|
|
12
|
+
*/
|
|
13
|
+
import { spawn } from "node:child_process";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { createRequire } from "node:module";
|
|
17
|
+
import { homedir, tmpdir } from "node:os";
|
|
18
|
+
import { dirname, join } from "node:path";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
|
|
21
|
+
export const name = "dsh-external-toolbox";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Hard-depend on the HTTP server: the helper needs a real origin for its
|
|
25
|
+
* translate URL, and registering before the listener exists would race. `llm`
|
|
26
|
+
* is looked up lazily with ctx.get(), so a profile without a model still gets
|
|
27
|
+
* the card and only the translate button reports "no model".
|
|
28
|
+
*/
|
|
29
|
+
export const inject = ["webServer"];
|
|
30
|
+
|
|
31
|
+
// Evaluated at import time: the one signal that proves the loader actually
|
|
32
|
+
// picked this package up (a plugin that never imports writes nothing).
|
|
33
|
+
try {
|
|
34
|
+
appendFileSync(join(tmpdir(), "dsh-external-toolbox-host.log"), `${new Date().toISOString()} module evaluated\n`);
|
|
35
|
+
} catch {
|
|
36
|
+
/* diagnostics must never break the import */
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const LIB_DIR = dirname(fileURLToPath(import.meta.url));
|
|
40
|
+
const HELPER_PATH = join(LIB_DIR, "..", "helper", "capture.ps1");
|
|
41
|
+
const TRANSLATE_ROUTE = "/toolbox/translate";
|
|
42
|
+
const RUN_ROUTE = "/toolbox/run";
|
|
43
|
+
const LATEST_ROUTE = "/toolbox/latest";
|
|
44
|
+
const ACTIVATE_ROUTE = "/toolbox/activate";
|
|
45
|
+
const RESTART_DELAY_MS = 2000;
|
|
46
|
+
const LOG_PATH = join(tmpdir(), "dsh-external-toolbox-host.log");
|
|
47
|
+
const MAX_TEXT_CHARS = 20000;
|
|
48
|
+
const MAX_TRANSLATE_CHARS = 100000;
|
|
49
|
+
const TRANSLATE_TIMEOUT_MS = 90000;
|
|
50
|
+
const HISTORY = 8;
|
|
51
|
+
const VOCAB_ROUTE = "/toolbox/vocab";
|
|
52
|
+
const REVIEW_ROUTE = "/toolbox/review";
|
|
53
|
+
// %APPDATA% on Windows, ~/.config elsewhere: the vocabulary book has to outlive
|
|
54
|
+
// profile reinstalls, so it does not live next to the plugin.
|
|
55
|
+
const VOCAB_DIR = join(process.env.APPDATA ?? join(homedir(), ".config"), "dsh-external-toolbox");
|
|
56
|
+
const VOCAB_JSONL = join(VOCAB_DIR, "vocab.jsonl");
|
|
57
|
+
const VOCAB_MARKDOWN = join(VOCAB_DIR, "生词本.md");
|
|
58
|
+
|
|
59
|
+
// The desktop shell runs this plugin inside the Electron main process, so the
|
|
60
|
+
// real BrowserWindow API is reachable. Showing the window through it is the
|
|
61
|
+
// same code path the tray icon takes - the only one where Electron's visibility
|
|
62
|
+
// state and the native HWND agree.
|
|
63
|
+
const nodeRequire = createRequire(import.meta.url);
|
|
64
|
+
const electronApi = () => {
|
|
65
|
+
try {
|
|
66
|
+
return nodeRequire("electron");
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Bring the DSH window back the way the app itself does it.
|
|
74
|
+
* @returns {{ ok: boolean, windows?: number, visible?: boolean, error?: string }}
|
|
75
|
+
*/
|
|
76
|
+
function showHostWindow() {
|
|
77
|
+
const electron = electronApi();
|
|
78
|
+
if (electron === null || electron === undefined || typeof electron.BrowserWindow?.getAllWindows !== "function") {
|
|
79
|
+
return { ok: false, error: "electron api unavailable" };
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const windows = electron.BrowserWindow.getAllWindows().filter((window) => window.isDestroyed() !== true);
|
|
83
|
+
if (windows.length === 0) return { ok: false, error: "no window" };
|
|
84
|
+
// Prefer the biggest window: devtools and helper windows must not win.
|
|
85
|
+
const area = (window) => {
|
|
86
|
+
try {
|
|
87
|
+
const [width, height] = window.getSize();
|
|
88
|
+
return width * height;
|
|
89
|
+
} catch {
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const target = windows.reduce((best, window) => (area(window) > area(best) ? window : best), windows[0]);
|
|
94
|
+
if (target.isMinimized()) target.restore();
|
|
95
|
+
target.show();
|
|
96
|
+
target.focus();
|
|
97
|
+
try {
|
|
98
|
+
electron.app?.focus?.({ steal: true });
|
|
99
|
+
} catch {
|
|
100
|
+
/* app.focus is best effort */
|
|
101
|
+
}
|
|
102
|
+
// A window that was hidden or occluded can come back showing its last
|
|
103
|
+
// frame: Windows throttles compositing for windows it considers occluded,
|
|
104
|
+
// and re-showing does not always clear that. Ask for a repaint, then nudge
|
|
105
|
+
// the size by a pixel and back so the compositor has to recompute.
|
|
106
|
+
try {
|
|
107
|
+
target.webContents?.invalidate?.();
|
|
108
|
+
} catch {
|
|
109
|
+
/* invalidate is optional */
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
const [width, height] = target.getContentSize();
|
|
113
|
+
target.setContentSize(width + 1, height);
|
|
114
|
+
target.setContentSize(width, height);
|
|
115
|
+
} catch {
|
|
116
|
+
/* the nudge is best effort */
|
|
117
|
+
}
|
|
118
|
+
return { ok: true, windows: windows.length, visible: target.isVisible() };
|
|
119
|
+
} catch (error) {
|
|
120
|
+
return { ok: false, error: describe(error) };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const LANGUAGES = new Set(["zh", "en", "ja", "ko", "es", "fr", "de", "ru", "pt", "it"]);
|
|
125
|
+
|
|
126
|
+
const LANGUAGE_NAMES = {
|
|
127
|
+
zh: "Simplified Chinese",
|
|
128
|
+
en: "English",
|
|
129
|
+
ja: "Japanese",
|
|
130
|
+
ko: "Korean",
|
|
131
|
+
es: "Spanish",
|
|
132
|
+
fr: "French",
|
|
133
|
+
de: "German",
|
|
134
|
+
ru: "Russian",
|
|
135
|
+
pt: "Portuguese",
|
|
136
|
+
it: "Italian",
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// Han, Hiragana/Katakana, and Hangul: text built mostly from these is not
|
|
140
|
+
// English, so the automatic direction goes the other way.
|
|
141
|
+
const CJK_RE = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]/g;
|
|
142
|
+
const LATIN_RE = /[A-Za-z]/g;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Bilingual default: Chinese (and Japanese/Korean) selections translate to
|
|
146
|
+
* English, everything else translates to Chinese. Explicit `to=` still wins.
|
|
147
|
+
*/
|
|
148
|
+
export function detectTarget(text) {
|
|
149
|
+
const cjk = (text.match(CJK_RE) ?? []).length;
|
|
150
|
+
const latin = (text.match(LATIN_RE) ?? []).length;
|
|
151
|
+
if (cjk === 0) return "zh";
|
|
152
|
+
if (latin === 0) return "en";
|
|
153
|
+
return cjk >= latin ? "en" : "zh";
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function apply(ctx, config) {
|
|
157
|
+
const options = config ?? {};
|
|
158
|
+
const hotkey = typeof options.hotkey === "string" && options.hotkey.trim() !== "" ? options.hotkey.trim() : "Ctrl+Alt+Q";
|
|
159
|
+
const defaultTarget = options.target === "auto" || LANGUAGES.has(options.target) ? options.target : "auto";
|
|
160
|
+
|
|
161
|
+
const log = (...args) => {
|
|
162
|
+
const line = `${new Date().toISOString()} ${args.map((part) => (typeof part === "string" ? part : describe(part))).join(" ")}`;
|
|
163
|
+
// The desktop app's stderr is not reachable from outside, so keep a file the
|
|
164
|
+
// user (and support) can read after a restart.
|
|
165
|
+
try {
|
|
166
|
+
appendFileSync(LOG_PATH, `${line}\n`);
|
|
167
|
+
} catch {
|
|
168
|
+
/* logging must never take the plugin down */
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
console.error("[select-translate]", ...args);
|
|
172
|
+
} catch {
|
|
173
|
+
/* logging must never take the plugin down */
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
log(`apply (helper=${HELPER_PATH})`);
|
|
178
|
+
|
|
179
|
+
/** id -> { text, at }, newest last; the helper translates by id. */
|
|
180
|
+
const captures = new Map();
|
|
181
|
+
let latest = { seq: 0, id: "", text: "", via: "", at: 0, intent: "" };
|
|
182
|
+
let child = null;
|
|
183
|
+
let stopped = false;
|
|
184
|
+
let restartTimer = null;
|
|
185
|
+
let leftover = "";
|
|
186
|
+
|
|
187
|
+
/** Resolved on demand: the llm service may mount after this plugin. */
|
|
188
|
+
const takeLlm = () => {
|
|
189
|
+
try {
|
|
190
|
+
return ctx.get("llm");
|
|
191
|
+
} catch (error) {
|
|
192
|
+
log("llm service unavailable:", describe(error));
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const remember = (text, via, id) => {
|
|
198
|
+
captures.set(id, { text, at: Date.now() });
|
|
199
|
+
while (captures.size > HISTORY) {
|
|
200
|
+
const oldest = captures.keys().next();
|
|
201
|
+
if (oldest.done) break;
|
|
202
|
+
captures.delete(oldest.value);
|
|
203
|
+
}
|
|
204
|
+
latest = { seq: latest.seq + 1, id, text, via, at: Date.now(), intent: "" };
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const resolveRoute = () => {
|
|
208
|
+
try {
|
|
209
|
+
const selection = ctx.get("agentDefaultModel")?.currentSelection?.();
|
|
210
|
+
if (selection?.provider !== undefined && selection.model !== undefined) {
|
|
211
|
+
return { provider: selection.provider, model: selection.model };
|
|
212
|
+
}
|
|
213
|
+
} catch (error) {
|
|
214
|
+
log("default model lookup failed:", describe(error));
|
|
215
|
+
}
|
|
216
|
+
return undefined;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const prepareCall = async (llm, route, signal, limits) => {
|
|
220
|
+
const prepared = { provider: route.provider, model: route.model, reasoningEffort: "off" };
|
|
221
|
+
if (limits !== undefined) Object.assign(prepared, limits);
|
|
222
|
+
try {
|
|
223
|
+
return await llm.prepareCall(prepared, signal);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
signal.throwIfAborted();
|
|
226
|
+
log(`call config rejected (${route.provider}/${route.model}): ${describe(error)}`);
|
|
227
|
+
return llm.prepareCall(route, signal);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const runTask = async (text, task, target) => {
|
|
232
|
+
const route = resolveRoute();
|
|
233
|
+
if (route === undefined) throw new Error("没有可用的默认模型,请先在 DSH 里选好模型");
|
|
234
|
+
const llmService = takeLlm();
|
|
235
|
+
if (llmService === undefined) throw new Error("模型服务不可用");
|
|
236
|
+
const controller = new AbortController();
|
|
237
|
+
const timer = setTimeout(() => controller.abort(new Error("翻译超时")), TRANSLATE_TIMEOUT_MS);
|
|
238
|
+
try {
|
|
239
|
+
const call = await prepareCall(llmService, route, controller.signal, { maxTokens: 8192 });
|
|
240
|
+
const language = LANGUAGE_NAMES[target] ?? LANGUAGE_NAMES.zh;
|
|
241
|
+
const system =
|
|
242
|
+
task === "explain"
|
|
243
|
+
? `You explain things for a working developer. Explain the user's text in ${language}: what it is, what it does, and anything worth knowing (syntax, intent, pitfalls). Match the input: source code gets a code-level walkthrough, an error message gets cause and fix, a term gets a two-sentence definition. Keep it short and concrete, no preamble, no restating the input.`
|
|
244
|
+
: `You are a translation engine. Translate the user's text into ${language}. Preserve the original formatting and paragraph breaks. Output only the translation, with no preamble, notes or quotation marks.`;
|
|
245
|
+
const messages = [
|
|
246
|
+
{
|
|
247
|
+
id: randomUUID(),
|
|
248
|
+
role: "user",
|
|
249
|
+
content: [{ type: "text", text }],
|
|
250
|
+
source: { kind: "dsh-external-toolbox" },
|
|
251
|
+
},
|
|
252
|
+
];
|
|
253
|
+
let accumulated = "";
|
|
254
|
+
let failure;
|
|
255
|
+
for await (const chunk of call.stream({
|
|
256
|
+
...call.config,
|
|
257
|
+
messages,
|
|
258
|
+
system,
|
|
259
|
+
purpose: "select-translate",
|
|
260
|
+
signal: controller.signal,
|
|
261
|
+
})) {
|
|
262
|
+
if (chunk.type === "text-delta") accumulated += chunk.text ?? "";
|
|
263
|
+
else if (chunk.type === "block-end" && chunk.block?.type === "text" && accumulated === "") accumulated = chunk.block.text ?? "";
|
|
264
|
+
else if (chunk.type === "finish") { failure = chunk.reason; if (chunk.reason?.kind === "max-tokens") log("output hit max-tokens"); }
|
|
265
|
+
}
|
|
266
|
+
controller.signal.throwIfAborted();
|
|
267
|
+
if (failure?.kind === "error" || failure?.kind === "aborted") {
|
|
268
|
+
const detail = failure.failure?.message ?? "翻译失败";
|
|
269
|
+
throw new Error(failure.failure?.code === undefined ? detail : `${failure.failure.code}: ${detail}`);
|
|
270
|
+
}
|
|
271
|
+
const translated = accumulated.trim();
|
|
272
|
+
if (translated === "") throw new Error("模型没有返回译文");
|
|
273
|
+
return translated;
|
|
274
|
+
} finally {
|
|
275
|
+
clearTimeout(timer);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* A dictionary entry for one saved word. Runs after the word is already on
|
|
281
|
+
* disk, so a slow or missing model never blocks the card.
|
|
282
|
+
*/
|
|
283
|
+
const describeWord = async (word, sentence) => {
|
|
284
|
+
const route = resolveRoute();
|
|
285
|
+
if (route === undefined) return "";
|
|
286
|
+
const llmService = takeLlm();
|
|
287
|
+
if (llmService === undefined) return "";
|
|
288
|
+
const controller = new AbortController();
|
|
289
|
+
const timer = setTimeout(() => controller.abort(new Error("lookup timeout")), TRANSLATE_TIMEOUT_MS);
|
|
290
|
+
try {
|
|
291
|
+
const call = await prepareCall(llmService, route, controller.signal);
|
|
292
|
+
const system = [
|
|
293
|
+
"You are a compact learner's dictionary for a Chinese-speaking developer.",
|
|
294
|
+
"For the given word or phrase, answer in Chinese except for the word itself.",
|
|
295
|
+
"Output exactly these lines, skipping a line only when it does not apply:",
|
|
296
|
+
"词性: <part of speech>",
|
|
297
|
+
"释义: <one or two short Chinese senses, separated by ;>",
|
|
298
|
+
"例句: <one short English example sentence>",
|
|
299
|
+
"译文: <its Chinese translation>",
|
|
300
|
+
"搭配: <two or three short collocations or 词根/词缀 notes>",
|
|
301
|
+
"No preamble, no bullet symbols, no blank lines, no markdown.",
|
|
302
|
+
].join("\n");
|
|
303
|
+
const messages = [
|
|
304
|
+
{
|
|
305
|
+
id: randomUUID(),
|
|
306
|
+
role: "user",
|
|
307
|
+
content: [{ type: "text", text: sentence.trim() === "" ? word : `${word}\n(出现在这句话里:${sentence})` }],
|
|
308
|
+
source: { kind: "dsh-external-toolbox" },
|
|
309
|
+
},
|
|
310
|
+
];
|
|
311
|
+
let accumulated = "";
|
|
312
|
+
for await (const chunk of call.stream({
|
|
313
|
+
...call.config,
|
|
314
|
+
messages,
|
|
315
|
+
system,
|
|
316
|
+
purpose: "select-translate",
|
|
317
|
+
signal: controller.signal,
|
|
318
|
+
})) {
|
|
319
|
+
if (chunk.type === "text-delta") accumulated += chunk.text ?? "";
|
|
320
|
+
else if (chunk.type === "block-end" && chunk.block?.type === "text" && accumulated === "") accumulated = chunk.block.text ?? "";
|
|
321
|
+
}
|
|
322
|
+
return accumulated.trim();
|
|
323
|
+
} catch (error) {
|
|
324
|
+
log("describe failed:", describe(error));
|
|
325
|
+
return "";
|
|
326
|
+
} finally {
|
|
327
|
+
clearTimeout(timer);
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
const json = (payload, status = 200) =>
|
|
331
|
+
new Response(JSON.stringify(payload), {
|
|
332
|
+
status,
|
|
333
|
+
headers: {
|
|
334
|
+
"content-type": "application/json; charset=utf-8",
|
|
335
|
+
"cache-control": "no-store",
|
|
336
|
+
"access-control-allow-origin": "*",
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* One handler for every text task. `translate` keeps working for older
|
|
342
|
+
* helpers; `run` takes a `task` parameter so new actions do not need a route.
|
|
343
|
+
*/
|
|
344
|
+
const taskResource = async (request, forcedTask) => {
|
|
345
|
+
let url;
|
|
346
|
+
try {
|
|
347
|
+
url = new URL(request.url);
|
|
348
|
+
} catch {
|
|
349
|
+
return json({ ok: false, error: "bad request" }, 400);
|
|
350
|
+
}
|
|
351
|
+
const task = forcedTask ?? (url.searchParams.get("task") ?? "translate");
|
|
352
|
+
if (task !== "translate" && task !== "explain") return json({ ok: false, error: "unsupported task" }, 400);
|
|
353
|
+
const requested = url.searchParams.get("to") ?? defaultTarget;
|
|
354
|
+
if (requested !== "auto" && !LANGUAGES.has(requested)) return json({ ok: false, error: "unsupported target" }, 400);
|
|
355
|
+
const id = url.searchParams.get("id");
|
|
356
|
+
let text = "";
|
|
357
|
+
if (id !== null && captures.has(id)) text = captures.get(id).text;
|
|
358
|
+
else text = url.searchParams.get("q") ?? "";
|
|
359
|
+
if (text.trim() === "") return json({ ok: false, error: "没有可处理的文本" }, 400);
|
|
360
|
+
if (text.length > MAX_TRANSLATE_CHARS) {
|
|
361
|
+
log(`input truncated ${String(text.length)} -> ${String(MAX_TRANSLATE_CHARS)}`);
|
|
362
|
+
text = text.slice(0, MAX_TRANSLATE_CHARS);
|
|
363
|
+
}
|
|
364
|
+
// Translation aims at the opposite language; an explanation is for the
|
|
365
|
+
// reader, so "auto" means "explain in Chinese" there.
|
|
366
|
+
const target = requested !== "auto" ? requested : task === "explain" ? "zh" : detectTarget(text);
|
|
367
|
+
try {
|
|
368
|
+
const output = await runTask(text, task, target);
|
|
369
|
+
return json({ ok: true, task, target, auto: requested === "auto", text: output });
|
|
370
|
+
} catch (error) {
|
|
371
|
+
log(`${task} failed:`, describe(error));
|
|
372
|
+
return json({ ok: false, error: describe(error) }, 200);
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
const translateResource = (request) => taskResource(request, "translate");
|
|
377
|
+
const runResource = (request) => taskResource(request, undefined);
|
|
378
|
+
|
|
379
|
+
// At most once: once a consumer reads the ask intent, clear it so a stale
|
|
380
|
+
// intent cannot be re-applied by a component that re-mounted.
|
|
381
|
+
let pollCount = 0;
|
|
382
|
+
const latestResource = () => {
|
|
383
|
+
// The browser half polls every 800ms. A gap in these counts means the
|
|
384
|
+
// renderer stopped running, which is not the same as the window hanging.
|
|
385
|
+
pollCount += 1;
|
|
386
|
+
if (pollCount % 25 === 0) log(`client poll ${String(pollCount)}`);
|
|
387
|
+
return json(latest);
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Vocabulary book: one JSON line per saved pair, plus a Markdown mirror so
|
|
392
|
+
* the file can be opened (and reviewed) without any tooling.
|
|
393
|
+
*/
|
|
394
|
+
const readVocab = () => {
|
|
395
|
+
try {
|
|
396
|
+
const raw = readFileSync(VOCAB_JSONL, "utf8");
|
|
397
|
+
const latest = new Map();
|
|
398
|
+
for (const line of raw.split("\n")) {
|
|
399
|
+
const trimmed = line.trim();
|
|
400
|
+
if (trimmed === "") continue;
|
|
401
|
+
let entry;
|
|
402
|
+
try {
|
|
403
|
+
entry = JSON.parse(trimmed);
|
|
404
|
+
} catch {
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
if (entry === null || typeof entry !== "object") continue;
|
|
408
|
+
if (typeof entry.word !== "string" || entry.word.trim() === "") continue;
|
|
409
|
+
// The log is append-only: a later line for the same word replaces it.
|
|
410
|
+
latest.set(entry.word.trim().toLowerCase(), entry);
|
|
411
|
+
}
|
|
412
|
+
return [...latest.values()].map((entry) => ({
|
|
413
|
+
...entry,
|
|
414
|
+
due: Number(entry.due ?? entry.at ?? Date.now()),
|
|
415
|
+
interval: Number(entry.interval ?? 0),
|
|
416
|
+
ease: Number(entry.ease ?? 2.5),
|
|
417
|
+
reps: Number(entry.reps ?? 0),
|
|
418
|
+
}));
|
|
419
|
+
} catch {
|
|
420
|
+
return [];
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
// Spaced repetition, three grades. `again` puts the word back in ten minutes,
|
|
425
|
+
// `hard` tomorrow, `good` multiplies the current interval.
|
|
426
|
+
const enriching = new Set();
|
|
427
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
428
|
+
const TEN_MIN_MS = 10 * 60 * 1000;
|
|
429
|
+
const MAX_INTERVAL_DAYS = 120;
|
|
430
|
+
|
|
431
|
+
const scheduleAfter = (entry, grade) => {
|
|
432
|
+
const ease = Math.max(1.3, Number(entry.ease ?? 2.5));
|
|
433
|
+
const interval = Math.max(0, Number(entry.interval ?? 0));
|
|
434
|
+
const reps = Math.max(0, Number(entry.reps ?? 0));
|
|
435
|
+
const next = { ...entry, reviewedAt: Date.now(), reps, ease, interval };
|
|
436
|
+
if (grade === "again") {
|
|
437
|
+
next.reps = 0;
|
|
438
|
+
next.ease = Math.max(1.3, ease - 0.2);
|
|
439
|
+
next.interval = 0;
|
|
440
|
+
next.due = Date.now() + TEN_MIN_MS;
|
|
441
|
+
} else if (grade === "hard") {
|
|
442
|
+
next.reps = reps;
|
|
443
|
+
next.ease = Math.max(1.3, ease - 0.15);
|
|
444
|
+
next.interval = 1;
|
|
445
|
+
next.due = Date.now() + DAY_MS;
|
|
446
|
+
} else {
|
|
447
|
+
next.reps = reps + 1;
|
|
448
|
+
next.interval =
|
|
449
|
+
next.reps === 1 ? 1 : next.reps === 2 ? 3 : Math.min(MAX_INTERVAL_DAYS, Math.max(1, interval) * ease);
|
|
450
|
+
next.due = Date.now() + next.interval * DAY_MS;
|
|
451
|
+
}
|
|
452
|
+
next.at = entry.at;
|
|
453
|
+
return next;
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
/** Markdown mirror: readable straight from notepad, newest word first. */
|
|
457
|
+
const writeBook = () => {
|
|
458
|
+
try {
|
|
459
|
+
const rows = readVocab().sort((a, b) => Number(b.at ?? 0) - Number(a.at ?? 0));
|
|
460
|
+
const lines = ["# 生词本", "", `共 ${rows.length} 条 · 更新于 ${new Date().toLocaleString()}`, ""];
|
|
461
|
+
for (const row of rows) {
|
|
462
|
+
const when = new Date(Number(row.at ?? Date.now())).toLocaleDateString();
|
|
463
|
+
const meaning = String(row.translation ?? "").replace(/\s+/g, " ").trim();
|
|
464
|
+
lines.push(`## ${row.word}`);
|
|
465
|
+
lines.push("");
|
|
466
|
+
if (meaning !== "") lines.push(`- 释义:${meaning}`);
|
|
467
|
+
const detail = String(row.detail ?? "").trim();
|
|
468
|
+
if (detail !== "") {
|
|
469
|
+
for (const line of detail.split("\n")) {
|
|
470
|
+
if (line.trim() !== "") lines.push(`- ${line.trim()}`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
const state = `下次复习 ${Number(row.due ?? 0) <= Date.now() ? "现在" : new Date(Number(row.due)).toLocaleDateString()}`;
|
|
474
|
+
lines.push(`- 收藏于 ${when} · ${state}`);
|
|
475
|
+
lines.push("");
|
|
476
|
+
}
|
|
477
|
+
writeFileSync(VOCAB_MARKDOWN, `${lines.join("\n")}\n`);
|
|
478
|
+
} catch (error) {
|
|
479
|
+
log("vocab markdown failed:", describe(error));
|
|
480
|
+
}
|
|
481
|
+
};
|
|
482
|
+
const saveVocab = (raw) => {
|
|
483
|
+
const existing = readVocab().find(
|
|
484
|
+
(item) => item.word.trim().toLowerCase() === String(raw.word).trim().toLowerCase(),
|
|
485
|
+
);
|
|
486
|
+
const entry = {
|
|
487
|
+
...raw,
|
|
488
|
+
due: existing?.due ?? Date.now(),
|
|
489
|
+
interval: existing?.interval ?? 0,
|
|
490
|
+
ease: existing?.ease ?? 2.5,
|
|
491
|
+
reps: existing?.reps ?? 0,
|
|
492
|
+
};
|
|
493
|
+
try {
|
|
494
|
+
mkdirSync(VOCAB_DIR, { recursive: true });
|
|
495
|
+
} catch (error) {
|
|
496
|
+
log("vocab dir failed:", describe(error));
|
|
497
|
+
return false;
|
|
498
|
+
}
|
|
499
|
+
// Same word twice within a minute is a double click, not two new words.
|
|
500
|
+
const previous = readVocab().slice(-20);
|
|
501
|
+
const duplicate = previous.find(
|
|
502
|
+
(item) =>
|
|
503
|
+
typeof item.word === "string" &&
|
|
504
|
+
item.word.trim().toLowerCase() === entry.word.trim().toLowerCase() &&
|
|
505
|
+
Date.now() - Number(item.at ?? 0) < 60_000,
|
|
506
|
+
);
|
|
507
|
+
if (duplicate !== undefined) return true;
|
|
508
|
+
try {
|
|
509
|
+
appendFileSync(VOCAB_JSONL, `${JSON.stringify(entry)}\n`);
|
|
510
|
+
} catch (error) {
|
|
511
|
+
log("vocab append failed:", describe(error));
|
|
512
|
+
return false;
|
|
513
|
+
}
|
|
514
|
+
writeBook();
|
|
515
|
+
return true;
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Review endpoint: `GET /toolbox/review` returns the next due word,
|
|
520
|
+
* `GET /toolbox/review?word=<w>&grade=again|hard|good` records an answer and
|
|
521
|
+
* returns the following card.
|
|
522
|
+
*/
|
|
523
|
+
const reviewResource = (request) => {
|
|
524
|
+
let url;
|
|
525
|
+
try {
|
|
526
|
+
url = new URL(request.url);
|
|
527
|
+
} catch {
|
|
528
|
+
return json({ ok: false, error: "bad request" }, 400);
|
|
529
|
+
}
|
|
530
|
+
const word = (url.searchParams.get("word") ?? "").trim();
|
|
531
|
+
const grade = (url.searchParams.get("grade") ?? "").trim();
|
|
532
|
+
if (word !== "" && (grade === "again" || grade === "hard" || grade === "good")) {
|
|
533
|
+
const entries = readVocab();
|
|
534
|
+
const current = entries.find((item) => item.word.trim().toLowerCase() === word.toLowerCase());
|
|
535
|
+
if (current !== undefined) {
|
|
536
|
+
const next = scheduleAfter(current, grade);
|
|
537
|
+
try {
|
|
538
|
+
appendFileSync(VOCAB_JSONL, `${JSON.stringify(next)}\n`);
|
|
539
|
+
} catch (error) {
|
|
540
|
+
log("review append failed:", describe(error));
|
|
541
|
+
return json({ ok: false, error: "cannot write vocabulary file" }, 500);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
const entries = readVocab();
|
|
546
|
+
const now = Date.now();
|
|
547
|
+
const due = entries
|
|
548
|
+
.filter((item) => Number(item.due ?? 0) <= now)
|
|
549
|
+
.sort((a, b) => Number(a.due ?? 0) - Number(b.due ?? 0));
|
|
550
|
+
const upcoming = entries
|
|
551
|
+
.filter((item) => Number(item.due ?? 0) > now)
|
|
552
|
+
.sort((a, b) => Number(a.due ?? 0) - Number(b.due ?? 0));
|
|
553
|
+
const next = due[0] ?? upcoming[0];
|
|
554
|
+
if (next !== undefined && String(next.detail ?? "").trim() === "" && !enriching.has(next.word)) {
|
|
555
|
+
// Backfill entries saved before the dictionary lookup existed (or while no
|
|
556
|
+
// model was selected): the next look at the word fills it in.
|
|
557
|
+
enriching.add(next.word);
|
|
558
|
+
void describeWord(next.word, String(next.context ?? "")).then((detail) => {
|
|
559
|
+
enriching.delete(next.word);
|
|
560
|
+
if (detail === "") return;
|
|
561
|
+
const current = readVocab().find((item) => item.word.trim().toLowerCase() === next.word.trim().toLowerCase());
|
|
562
|
+
if (current === undefined) return;
|
|
563
|
+
try {
|
|
564
|
+
appendFileSync(VOCAB_JSONL, `${JSON.stringify({ ...current, detail, enrichedAt: Date.now() })}\n`);
|
|
565
|
+
writeBook();
|
|
566
|
+
log(`vocab backfilled: ${String(next.word).slice(0, 60)}`);
|
|
567
|
+
} catch (error) {
|
|
568
|
+
log("vocab backfill failed:", describe(error));
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
return json({
|
|
573
|
+
ok: true,
|
|
574
|
+
total: entries.length,
|
|
575
|
+
due: due.length,
|
|
576
|
+
nextDue: upcoming[0]?.due ?? 0,
|
|
577
|
+
// The card only needs the word and its meaning; the schedule stays home.
|
|
578
|
+
item:
|
|
579
|
+
next === undefined
|
|
580
|
+
? null
|
|
581
|
+
: {
|
|
582
|
+
word: next.word,
|
|
583
|
+
translation: next.translation ?? "",
|
|
584
|
+
context: next.context ?? "",
|
|
585
|
+
detail: next.detail ?? "",
|
|
586
|
+
lang: next.lang ?? "",
|
|
587
|
+
},
|
|
588
|
+
});
|
|
589
|
+
};
|
|
590
|
+
const vocabResource = (request) => {
|
|
591
|
+
// GET /toolbox/vocab?word=...&translation=... saves; plain GET lists.
|
|
592
|
+
try {
|
|
593
|
+
const url = new URL(request.url);
|
|
594
|
+
const word = url.searchParams.get("word");
|
|
595
|
+
if (word !== null && word.trim() !== "") {
|
|
596
|
+
const saved = saveVocab({
|
|
597
|
+
word: word.trim().slice(0, 200),
|
|
598
|
+
translation: (url.searchParams.get("translation") ?? "").slice(0, 2000),
|
|
599
|
+
lang: url.searchParams.get("lang") ?? "",
|
|
600
|
+
task: url.searchParams.get("task") ?? "",
|
|
601
|
+
at: Date.now(),
|
|
602
|
+
});
|
|
603
|
+
return json({ ok: saved, count: readVocab().length }, saved ? 200 : 500);
|
|
604
|
+
}
|
|
605
|
+
} catch (error) {
|
|
606
|
+
log("vocab request failed:", describe(error));
|
|
607
|
+
}
|
|
608
|
+
const entries = readVocab();
|
|
609
|
+
return json({ ok: true, count: entries.length, file: VOCAB_MARKDOWN, entries });
|
|
610
|
+
};
|
|
611
|
+
// The browser half reports lifecycle events here: an unbounded number of
|
|
612
|
+
// "mount" lines would mean the overlay seat is re-mounting the bridge. An
|
|
613
|
+
// "ask" beat doubles as the acknowledgement, so the intent is cleared only
|
|
614
|
+
// after the composer actually received the draft.
|
|
615
|
+
const BEAT_ROUTE = "/toolbox/beat";
|
|
616
|
+
const beatResource = (request) => {
|
|
617
|
+
try {
|
|
618
|
+
const url = new URL(request.url);
|
|
619
|
+
const kind = url.searchParams.get("kind") ?? "?";
|
|
620
|
+
if (kind === "ask") latest = { ...latest, intent: "" };
|
|
621
|
+
log(`client ${kind} ${url.searchParams.get("id") ?? ""}`);
|
|
622
|
+
} catch {
|
|
623
|
+
/* diagnostics only */
|
|
624
|
+
}
|
|
625
|
+
return json({ ok: true });
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
// Activation goes through Electron, not Win32: the helper asks here instead
|
|
629
|
+
// of forcing a hidden HWND visible, which used to leave a frozen, unrepainted
|
|
630
|
+
// window behind.
|
|
631
|
+
const activateResource = () => {
|
|
632
|
+
const result = showHostWindow();
|
|
633
|
+
log(`activate ${result.ok ? "ok" : "failed"} ${result.error ?? ""}`.trim());
|
|
634
|
+
return json(result, result.ok === true ? 200 : 503);
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
const handleLine = (raw) => {
|
|
638
|
+
const line = raw.trim();
|
|
639
|
+
if (line === "") return;
|
|
640
|
+
let message;
|
|
641
|
+
try {
|
|
642
|
+
message = JSON.parse(line);
|
|
643
|
+
} catch {
|
|
644
|
+
log("helper printed a non-JSON line:", line.slice(0, 200));
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if (message === null || typeof message !== "object") return;
|
|
648
|
+
if (message.type === "ready") {
|
|
649
|
+
log(`hotkey ready: ${String(message.hotkey)}`);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
if (message.type === "error") {
|
|
653
|
+
log(`helper error: ${String(message.message)}`);
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
if (message.type === "vocab" && typeof message.word === "string" && message.word.trim() !== "") {
|
|
657
|
+
const context = typeof message.context === "string" ? message.context.slice(0, 2000) : "";
|
|
658
|
+
const saved = saveVocab({
|
|
659
|
+
word: message.word.trim().slice(0, 200),
|
|
660
|
+
translation: typeof message.translation === "string" ? message.translation.slice(0, 2000) : "",
|
|
661
|
+
context,
|
|
662
|
+
lang: typeof message.lang === "string" ? message.lang : "",
|
|
663
|
+
task: typeof message.task === "string" ? message.task : "",
|
|
664
|
+
at: Date.now(),
|
|
665
|
+
});
|
|
666
|
+
log(`vocab ${saved ? "saved" : "failed"}: ${message.word.trim().slice(0, 60)}`);
|
|
667
|
+
if (saved) {
|
|
668
|
+
// Enrich in the background: the card already closed with a plain meaning,
|
|
669
|
+
// and the review window picks up the fuller entry next time it opens.
|
|
670
|
+
const word = String(message.word).trim();
|
|
671
|
+
void describeWord(word, context).then((detail) => {
|
|
672
|
+
if (detail === "") return;
|
|
673
|
+
const existing = readVocab().find((item) => item.word.trim().toLowerCase() === word.toLowerCase());
|
|
674
|
+
if (existing === undefined) return;
|
|
675
|
+
try {
|
|
676
|
+
appendFileSync(VOCAB_JSONL, `${JSON.stringify({ ...existing, detail, enrichedAt: Date.now() })}\n`);
|
|
677
|
+
writeBook();
|
|
678
|
+
log(`vocab enriched: ${word.slice(0, 60)}`);
|
|
679
|
+
} catch (error) {
|
|
680
|
+
log("vocab enrich append failed:", describe(error));
|
|
681
|
+
}
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
if (message.type === "intent" && message.intent === "ask") {
|
|
687
|
+
latest = { ...latest, intent: "ask", at: Date.now() };
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
if (message.type !== "selection" || typeof message.text !== "string") return;
|
|
691
|
+
const text = message.text.length > MAX_TEXT_CHARS ? message.text.slice(0, MAX_TEXT_CHARS) : message.text;
|
|
692
|
+
if (text.trim() === "") return;
|
|
693
|
+
const id = typeof message.id === "string" && message.id !== "" ? message.id : randomUUID();
|
|
694
|
+
remember(text, typeof message.via === "string" ? message.via : "", id);
|
|
695
|
+
};
|
|
696
|
+
|
|
697
|
+
const startHelper = (base) => {
|
|
698
|
+
if (stopped) return;
|
|
699
|
+
if (child !== null) return;
|
|
700
|
+
if (!existsSync(HELPER_PATH)) {
|
|
701
|
+
log("helper script missing:", HELPER_PATH);
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
try {
|
|
705
|
+
child = spawn(
|
|
706
|
+
"powershell.exe",
|
|
707
|
+
[
|
|
708
|
+
"-NoProfile",
|
|
709
|
+
"-NonInteractive",
|
|
710
|
+
"-ExecutionPolicy",
|
|
711
|
+
"Bypass",
|
|
712
|
+
"-STA",
|
|
713
|
+
"-File",
|
|
714
|
+
HELPER_PATH,
|
|
715
|
+
"-Hotkey",
|
|
716
|
+
hotkey,
|
|
717
|
+
"-TranslateUrl",
|
|
718
|
+
`${base}${TRANSLATE_ROUTE}`,
|
|
719
|
+
"-ParentPid",
|
|
720
|
+
String(process.pid),
|
|
721
|
+
],
|
|
722
|
+
{ windowsHide: true, stdio: ["ignore", "pipe", "pipe"] },
|
|
723
|
+
);
|
|
724
|
+
} catch (error) {
|
|
725
|
+
log("helper spawn failed:", describe(error));
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
child.stdout?.setEncoding("utf8");
|
|
729
|
+
child.stdout?.on("data", (chunk) => {
|
|
730
|
+
leftover += chunk;
|
|
731
|
+
const lines = leftover.split(/\r?\n/);
|
|
732
|
+
leftover = lines.pop() ?? "";
|
|
733
|
+
for (const line of lines) handleLine(line);
|
|
734
|
+
});
|
|
735
|
+
log(`helper spawned pid=${String(child.pid)} base=${base}`);
|
|
736
|
+
child.stderr?.setEncoding("utf8");
|
|
737
|
+
child.stderr?.on("data", (chunk) => {
|
|
738
|
+
const text = String(chunk).trim();
|
|
739
|
+
if (text !== "") log("helper stderr:", text.slice(0, 400));
|
|
740
|
+
});
|
|
741
|
+
child.on("error", (error) => log("helper process error:", describe(error)));
|
|
742
|
+
child.on("exit", (code, signal) => {
|
|
743
|
+
child = null;
|
|
744
|
+
leftover = "";
|
|
745
|
+
if (stopped) return;
|
|
746
|
+
log(`helper exited (code=${String(code)} signal=${String(signal)}), restarting in ${RESTART_DELAY_MS}ms`);
|
|
747
|
+
restartTimer = setTimeout(() => {
|
|
748
|
+
restartTimer = null;
|
|
749
|
+
startHelper(base);
|
|
750
|
+
}, RESTART_DELAY_MS);
|
|
751
|
+
});
|
|
752
|
+
};
|
|
753
|
+
|
|
754
|
+
const stopHelper = () => {
|
|
755
|
+
stopped = true;
|
|
756
|
+
if (restartTimer !== null) {
|
|
757
|
+
clearTimeout(restartTimer);
|
|
758
|
+
restartTimer = null;
|
|
759
|
+
}
|
|
760
|
+
try {
|
|
761
|
+
child?.kill();
|
|
762
|
+
} catch {
|
|
763
|
+
/* already gone */
|
|
764
|
+
}
|
|
765
|
+
child = null;
|
|
766
|
+
};
|
|
767
|
+
|
|
768
|
+
const onDispose = (dispose) => {
|
|
769
|
+
try {
|
|
770
|
+
ctx.effect(() => dispose);
|
|
771
|
+
} catch (error) {
|
|
772
|
+
log("effect registration failed:", describe(error));
|
|
773
|
+
}
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
const routeDisposers = [];
|
|
777
|
+
|
|
778
|
+
const registerRoutes = (webServer) => {
|
|
779
|
+
if (webServer === null || webServer === undefined || typeof webServer.register !== "function") return false;
|
|
780
|
+
try {
|
|
781
|
+
const registered = [
|
|
782
|
+
webServer.register({ kind: "exact", path: TRANSLATE_ROUTE, resource: translateResource }),
|
|
783
|
+
webServer.register({ kind: "exact", path: RUN_ROUTE, resource: runResource }),
|
|
784
|
+
webServer.register({ kind: "exact", path: VOCAB_ROUTE, resource: vocabResource }),
|
|
785
|
+
webServer.register({ kind: "exact", path: REVIEW_ROUTE, resource: reviewResource }),
|
|
786
|
+
webServer.register({ kind: "exact", path: LATEST_ROUTE, resource: latestResource }),
|
|
787
|
+
webServer.register({ kind: "exact", path: BEAT_ROUTE, resource: beatResource }),
|
|
788
|
+
webServer.register({ kind: "exact", path: ACTIVATE_ROUTE, resource: activateResource }),
|
|
789
|
+
];
|
|
790
|
+
for (const disposer of registered) {
|
|
791
|
+
if (typeof disposer === "function") routeDisposers.push(disposer);
|
|
792
|
+
}
|
|
793
|
+
log("routes registered");
|
|
794
|
+
return true;
|
|
795
|
+
} catch (error) {
|
|
796
|
+
log("route registration failed:", describe(error));
|
|
797
|
+
return false;
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
const helperBase = () => {
|
|
802
|
+
try {
|
|
803
|
+
const port = ctx.webServer?.port;
|
|
804
|
+
if (typeof port === "number" && port > 0) return `http://127.0.0.1:${port}`;
|
|
805
|
+
} catch {
|
|
806
|
+
/* not bound yet */
|
|
807
|
+
}
|
|
808
|
+
return "";
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
// The helper needs a real origin in its command line, so wait until the
|
|
812
|
+
// listener has a port: routes first, then the child process.
|
|
813
|
+
let routesReady = false;
|
|
814
|
+
let polling = false;
|
|
815
|
+
let attempts = 0;
|
|
816
|
+
const registerOnce = () => {
|
|
817
|
+
if (routesReady) return true;
|
|
818
|
+
routesReady = registerRoutes(ctx.webServer);
|
|
819
|
+
return routesReady;
|
|
820
|
+
};
|
|
821
|
+
const poll = () => {
|
|
822
|
+
if (stopped || child !== null) {
|
|
823
|
+
polling = false;
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
const base = helperBase();
|
|
827
|
+
if (registerOnce() && base !== "") {
|
|
828
|
+
polling = false;
|
|
829
|
+
startHelper(base);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
attempts += 1;
|
|
833
|
+
if (attempts > 240) {
|
|
834
|
+
polling = false;
|
|
835
|
+
log("giving up waiting for the web server port");
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
setTimeout(poll, 250);
|
|
839
|
+
};
|
|
840
|
+
polling = true;
|
|
841
|
+
poll();
|
|
842
|
+
|
|
843
|
+
onDispose(() => {
|
|
844
|
+
stopHelper();
|
|
845
|
+
for (const dispose of routeDisposers) {
|
|
846
|
+
try {
|
|
847
|
+
dispose();
|
|
848
|
+
} catch {
|
|
849
|
+
/* the server may already be gone */
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
function describe(error) {
|
|
856
|
+
if (error instanceof Error) {
|
|
857
|
+
const code = error.code;
|
|
858
|
+
return typeof code === "string" ? `${code}: ${error.message}` : error.message;
|
|
859
|
+
}
|
|
860
|
+
}
|