vanspod 0.1.3 → 0.3.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 +4 -4
- package/dist/adapters/transport.js +4 -0
- package/dist/claudeWebSearch.js +7 -2
- package/dist/connectionMascot.js +103 -28
- package/dist/desktop.js +22 -0
- package/dist/exitGuard.js +1 -1
- package/dist/inspectorView.js +172 -0
- package/dist/installations.js +13 -12
- package/dist/launcher.js +3 -1
- package/dist/lifecyclePage.js +2 -1
- package/dist/modelProxy.js +44 -4
- package/dist/page.js +149 -43
- package/dist/promptCapture.js +246 -0
- package/dist/removal.js +2 -17
- package/dist/start.js +94 -46
- package/dist/version.js +1 -1
- package/dist/versionUpdate.js +235 -0
- package/dist/versionUpdateView.js +157 -0
- package/package.json +2 -2
- package/scripts/update.ps1 +105 -0
package/dist/start.js
CHANGED
|
@@ -14,6 +14,7 @@ const node_os_1 = __importDefault(require("node:os"));
|
|
|
14
14
|
const node_path_1 = __importDefault(require("node:path"));
|
|
15
15
|
const classroomApp_1 = require("./classroomApp");
|
|
16
16
|
const page_1 = require("./page");
|
|
17
|
+
const promptCapture_1 = require("./promptCapture");
|
|
17
18
|
const clipboard_1 = require("./clipboard");
|
|
18
19
|
const folderPicker_1 = require("./folderPicker");
|
|
19
20
|
const commandRunner_1 = require("./commandRunner");
|
|
@@ -32,6 +33,9 @@ const instance_1 = require("./instance");
|
|
|
32
33
|
const desktop_1 = require("./desktop");
|
|
33
34
|
const lifecyclePage_1 = require("./lifecyclePage");
|
|
34
35
|
const removal_1 = require("./removal");
|
|
36
|
+
const installations_1 = require("./installations");
|
|
37
|
+
const versionUpdate_1 = require("./versionUpdate");
|
|
38
|
+
const version_1 = require("./version");
|
|
35
39
|
const runtimeOptions = (0, runtimeOptions_1.readRuntimeOptions)(process.env);
|
|
36
40
|
const port = runtimeOptions.port;
|
|
37
41
|
const pageUrl = `http://127.0.0.1:${port}/`;
|
|
@@ -40,6 +44,13 @@ const activeRequests = new Set();
|
|
|
40
44
|
function abortRequests() { for (const controller of activeRequests)
|
|
41
45
|
controller.abort(); }
|
|
42
46
|
const traffic = (0, clientTraffic_1.createClientTraffic)();
|
|
47
|
+
// 只存在記憶體;每次啟動錄製都是關閉(ADR-0009)。
|
|
48
|
+
const promptCapture = (0, promptCapture_1.createPromptCapture)();
|
|
49
|
+
const promptCaptureActions = new Map([
|
|
50
|
+
["/prompt-capture/start", () => promptCapture.start()],
|
|
51
|
+
["/prompt-capture/pause", () => promptCapture.pause()],
|
|
52
|
+
["/prompt-capture/clear", () => promptCapture.clear()],
|
|
53
|
+
]);
|
|
43
54
|
function routerBaseUrl() {
|
|
44
55
|
return (process.env.CLASSROOM_ROUTER_BASE_URL ?? "https://ai.vanscoding.com").replace(/\/+$/, "");
|
|
45
56
|
}
|
|
@@ -299,22 +310,7 @@ function modelFromBody(body) {
|
|
|
299
310
|
}
|
|
300
311
|
return "";
|
|
301
312
|
}
|
|
302
|
-
function rewriteModel(body, model) {
|
|
303
|
-
try {
|
|
304
|
-
const parsed = JSON.parse(body);
|
|
305
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
306
|
-
return JSON.stringify({ ...parsed, model });
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
catch {
|
|
310
|
-
return body;
|
|
311
|
-
}
|
|
312
|
-
return body;
|
|
313
|
-
}
|
|
314
313
|
function upstreamOrigin(target) {
|
|
315
|
-
if (target === "router") {
|
|
316
|
-
return routerBaseUrl();
|
|
317
|
-
}
|
|
318
314
|
if (target === "chatgpt") {
|
|
319
315
|
return "https://chatgpt.com";
|
|
320
316
|
}
|
|
@@ -327,25 +323,18 @@ async function sendUpstream(upstream) {
|
|
|
327
323
|
const slot = responseSlot.getStore();
|
|
328
324
|
if (!slot)
|
|
329
325
|
return { ok: false };
|
|
330
|
-
if (upstream.target === "router"
|
|
331
|
-
|
|
326
|
+
if (upstream.target === "router") {
|
|
327
|
+
// VS Code Chat already speaks Router's protocol; Codex and Claude Code go through a Model API Adapter.
|
|
328
|
+
slot.response = upstream.client === "copilot"
|
|
329
|
+
? await (0, modelProxy_1.forwardRouter)(upstream, routerBaseUrl(), promptCapture)
|
|
330
|
+
: await (0, modelProxy_1.sendRouter)(upstream, routerBaseUrl(), promptCapture);
|
|
332
331
|
return { ok: slot.response.ok };
|
|
333
332
|
}
|
|
334
333
|
try {
|
|
335
|
-
const
|
|
336
|
-
"Content-Type": "application/json",
|
|
337
|
-
};
|
|
338
|
-
if (upstream.target === "router" && upstream.apiKey) {
|
|
339
|
-
headers.Authorization = `Bearer ${upstream.apiKey}`;
|
|
340
|
-
}
|
|
341
|
-
const body = upstream.target === "router"
|
|
342
|
-
? rewriteModel(upstream.body ?? "", upstream.model)
|
|
343
|
-
: upstream.body;
|
|
344
|
-
const url = `${upstreamOrigin(upstream.target)}${upstream.path}`;
|
|
345
|
-
const response = await fetch(url, {
|
|
334
|
+
const response = await fetch(`${upstreamOrigin(upstream.target)}${upstream.path}`, {
|
|
346
335
|
method: upstream.method ?? "POST",
|
|
347
|
-
headers,
|
|
348
|
-
body,
|
|
336
|
+
headers: { "Content-Type": "application/json" },
|
|
337
|
+
body: upstream.body,
|
|
349
338
|
signal: upstream.signal,
|
|
350
339
|
});
|
|
351
340
|
slot.response = response;
|
|
@@ -363,6 +352,45 @@ async function main(instance) {
|
|
|
363
352
|
let exitRequested = false;
|
|
364
353
|
const exitWork = () => ({ installing: app.view().commandRunning, activeRequests: activeRequests.size });
|
|
365
354
|
let launchVersion;
|
|
355
|
+
/**
|
|
356
|
+
* 結束、移除與版本更新共同的交接:中止安裝與模型回答、恢復客戶端設定,再啟動接手的工具。
|
|
357
|
+
* 失敗時不結束;`restored` 表示客戶端設定是否已恢復。
|
|
358
|
+
*/
|
|
359
|
+
const handOff = async (launchTool) => {
|
|
360
|
+
exitRequested = true;
|
|
361
|
+
await app.abortInstall();
|
|
362
|
+
abortRequests();
|
|
363
|
+
let restored = false;
|
|
364
|
+
try {
|
|
365
|
+
await app.stop();
|
|
366
|
+
restored = true;
|
|
367
|
+
await launchTool?.();
|
|
368
|
+
return { ok: true };
|
|
369
|
+
}
|
|
370
|
+
catch (error) {
|
|
371
|
+
exitRequested = false;
|
|
372
|
+
return { ok: false, restored, error };
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
const versionUpdate = (0, versionUpdate_1.createVersionUpdate)({
|
|
376
|
+
current: version_1.VERSION,
|
|
377
|
+
source: (await (0, installations_1.detectInstallation)()) ?? { kind: "source" },
|
|
378
|
+
work: exitWork,
|
|
379
|
+
async exit(launchTool) {
|
|
380
|
+
if (exitRequested)
|
|
381
|
+
throw new Error("正在結束 VansPod。");
|
|
382
|
+
// 下載期間學生可能開始了安裝;更新不中止安裝。
|
|
383
|
+
if (exitWork().installing)
|
|
384
|
+
throw new Error("安裝進行中,更新已取消。");
|
|
385
|
+
const handed = await handOff(launchTool);
|
|
386
|
+
if (!handed.ok) {
|
|
387
|
+
if (handed.restored)
|
|
388
|
+
await app.start().catch(() => undefined);
|
|
389
|
+
throw handed.error;
|
|
390
|
+
}
|
|
391
|
+
void exit();
|
|
392
|
+
},
|
|
393
|
+
});
|
|
366
394
|
let ready = false;
|
|
367
395
|
let startupError;
|
|
368
396
|
let tray;
|
|
@@ -459,11 +487,19 @@ async function main(instance) {
|
|
|
459
487
|
}
|
|
460
488
|
if (req.method === "POST" && pathname === "/_vanspod/open") {
|
|
461
489
|
const body = JSON.parse(await readBody(req));
|
|
462
|
-
if (typeof body.version === "string" &&
|
|
490
|
+
if (typeof body.version === "string" && versionUpdate_1.VERSION_PATTERN.test(body.version))
|
|
463
491
|
launchVersion = body.version;
|
|
464
492
|
reply({ ok: true });
|
|
465
493
|
return;
|
|
466
494
|
}
|
|
495
|
+
if (req.method === "GET" && pathname === "/_vanspod/update") {
|
|
496
|
+
reply(await versionUpdate.status({ refresh: parsed.searchParams.get("refresh") === "1", takeResult: parsed.searchParams.get("result") === "1" }));
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
if (req.method === "POST" && pathname === "/_vanspod/update") {
|
|
500
|
+
reply(await versionUpdate.run(JSON.parse(await readBody(req) || "{}")));
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
467
503
|
if (req.method === "GET" && pathname === "/_vanspod/uninstall-preview") {
|
|
468
504
|
reply({ ok: true, message: `${await (0, removal_1.removalPreview)()}${(0, exitGuard_1.removalInterruptions)(exitWork())}` });
|
|
469
505
|
return;
|
|
@@ -484,24 +520,15 @@ async function main(instance) {
|
|
|
484
520
|
reply({ ok: false, message: "正在結束 VansPod。" });
|
|
485
521
|
return;
|
|
486
522
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
try {
|
|
492
|
-
await app.stop();
|
|
493
|
-
restored = true;
|
|
494
|
-
if (uninstall) {
|
|
495
|
-
const launchRemoval = await (0, removal_1.prepareRemoval)(Number.isSafeInteger(body.waitForPid) && body.waitForPid > 0 ? body.waitForPid : undefined, instance.id);
|
|
496
|
-
await launchRemoval();
|
|
497
|
-
}
|
|
523
|
+
const handed = await handOff(uninstall
|
|
524
|
+
? async () => (await (0, removal_1.prepareRemoval)(Number.isSafeInteger(body.waitForPid) && body.waitForPid > 0 ? body.waitForPid : undefined, instance.id))()
|
|
525
|
+
: undefined);
|
|
526
|
+
if (handed.ok) {
|
|
498
527
|
reply({ ok: true, message: uninstall ? "完整移除已開始;結果會以 Windows 訊息顯示。未完成時會保留移除工具供重試。" : "VansPod 已結束,可關閉此分頁。" });
|
|
499
528
|
res.once("finish", () => { void exit(); });
|
|
500
529
|
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
reply({ ok: false, message: restored ? `移除未完成:${error instanceof Error ? error.message : "移除工具啟動失敗"}。請重試移除。` : `客戶端設定恢復失敗(${Object.entries(app.view().clientRoutes ?? {}).filter(([, route]) => route.health === "red").map(([id]) => id).join("、")}),備份已保留,請重試結束。` });
|
|
504
|
-
}
|
|
530
|
+
else
|
|
531
|
+
reply({ ok: false, message: handed.restored ? `移除未完成:${handed.error instanceof Error ? handed.error.message : "移除工具啟動失敗"}。請重試移除。` : `客戶端設定恢復失敗(${Object.entries(app.view().clientRoutes ?? {}).filter(([, route]) => route.health === "red").map(([id]) => id).join("、")}),備份已保留,請重試結束。` });
|
|
505
532
|
return;
|
|
506
533
|
}
|
|
507
534
|
reply({ ok: false, message: "管理操作無效。" });
|
|
@@ -529,6 +556,26 @@ async function main(instance) {
|
|
|
529
556
|
res.end(JSON.stringify({ ...(0, page_1.modelStatus)(app.view()), traffic: traffic.flowing() }));
|
|
530
557
|
return;
|
|
531
558
|
}
|
|
559
|
+
const captureAction = req.method === "POST" ? promptCaptureActions.get(pathname) : undefined;
|
|
560
|
+
if (captureAction) {
|
|
561
|
+
await readBody(req);
|
|
562
|
+
captureAction();
|
|
563
|
+
if (!(req.headers.accept ?? "").includes("application/json")) {
|
|
564
|
+
redirect(res, "/prompt-inspector");
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
if (captureAction || (req.method === "GET" && pathname === "/prompt-capture")) {
|
|
569
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
570
|
+
res.end(JSON.stringify({ recording: promptCapture.recording, ...promptCapture.list() }));
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
if (req.method === "GET" && pathname === "/prompt-inspector") {
|
|
574
|
+
const html = (0, page_1.renderInspectorPage)({ recording: promptCapture.recording, ...promptCapture.list() });
|
|
575
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
|
|
576
|
+
res.end(instance ? (0, lifecyclePage_1.lifecyclePage)(html, instance.token) : html);
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
532
579
|
if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
533
580
|
const variant = parsed.searchParams.get("variant") ?? "";
|
|
534
581
|
const html = process.env.NODE_ENV !== "production" && (0, pagePrototype_1.isPrototypeVariant)(variant)
|
|
@@ -803,6 +850,7 @@ async function main(instance) {
|
|
|
803
850
|
}
|
|
804
851
|
startupError += " 設定恢復未完成,服務已保留;修復後請重試 vanspod stop。";
|
|
805
852
|
}
|
|
853
|
+
versionUpdate.start();
|
|
806
854
|
tray = runtimeOptions.desktop && process.platform === "win32" && instance ? await openTray(home) : undefined;
|
|
807
855
|
if (runtimeOptions.desktop && !process.env.VANSPOD_WORKER_TOKEN)
|
|
808
856
|
(0, desktop_1.openBrowser)(home);
|
package/dist/version.js
CHANGED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.VERSION_PATTERN = void 0;
|
|
7
|
+
exports.compareVersions = compareVersions;
|
|
8
|
+
exports.downloadExe = downloadExe;
|
|
9
|
+
exports.createVersionUpdate = createVersionUpdate;
|
|
10
|
+
const node_crypto_1 = require("node:crypto");
|
|
11
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
12
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
13
|
+
const desktop_1 = require("./desktop");
|
|
14
|
+
const exitGuard_1 = require("./exitGuard");
|
|
15
|
+
const instance_1 = require("./instance");
|
|
16
|
+
const installations_1 = require("./installations");
|
|
17
|
+
const RELEASES_URL = "https://github.com/mz038197/VansPod/releases";
|
|
18
|
+
// 測試與手動驗證以環境變數換成本機的假 registry 與下載來源(docs/verification/version-update.md)。
|
|
19
|
+
const registryUrl = () => process.env.VANSPOD_UPDATE_REGISTRY ?? "https://registry.npmjs.org/vanspod/latest";
|
|
20
|
+
const downloadBase = (version) => `${process.env.VANSPOD_UPDATE_DOWNLOADS ?? `${RELEASES_URL}/download`}/v${version}`;
|
|
21
|
+
exports.VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
22
|
+
const CHECK_DELAY_MS = 30_000;
|
|
23
|
+
const CHECK_INTERVAL_MS = 6 * 60 * 60_000;
|
|
24
|
+
/** 依 semver 比較;同號時預發佈版本比正式版舊。 */
|
|
25
|
+
function compareVersions(a, b) {
|
|
26
|
+
const split = (value) => {
|
|
27
|
+
const dash = value.indexOf("-");
|
|
28
|
+
return { core: (dash < 0 ? value : value.slice(0, dash)).split(".").map(Number), pre: dash < 0 ? "" : value.slice(dash + 1) };
|
|
29
|
+
};
|
|
30
|
+
const left = split(a), right = split(b);
|
|
31
|
+
for (let index = 0; index < 3; index++)
|
|
32
|
+
if (left.core[index] !== right.core[index])
|
|
33
|
+
return Math.sign(left.core[index] - right.core[index]);
|
|
34
|
+
if (left.pre === right.pre)
|
|
35
|
+
return 0;
|
|
36
|
+
if (!left.pre)
|
|
37
|
+
return 1;
|
|
38
|
+
if (!right.pre)
|
|
39
|
+
return -1;
|
|
40
|
+
return Math.sign(left.pre.localeCompare(right.pre, "en", { numeric: true }));
|
|
41
|
+
}
|
|
42
|
+
async function fetchLatestVersion() {
|
|
43
|
+
const response = await fetch(registryUrl(), { headers: { accept: "application/json" }, signal: AbortSignal.timeout(15_000) });
|
|
44
|
+
if (!response.ok)
|
|
45
|
+
throw new Error(`npm registry 回應 ${response.status}`);
|
|
46
|
+
const version = (await response.json()).version;
|
|
47
|
+
if (typeof version !== "string" || !exports.VERSION_PATTERN.test(version))
|
|
48
|
+
throw new Error("npm registry 回應格式無效");
|
|
49
|
+
return version;
|
|
50
|
+
}
|
|
51
|
+
/** 不能更新的原因;可以更新時為 undefined。模型回答中不算,改由確認處理。 */
|
|
52
|
+
function updateBlock(source, installing, writable) {
|
|
53
|
+
if (source.kind === "source")
|
|
54
|
+
return "從原始碼執行的 VansPod 無法自動更新,請用 git pull 後重新建置。";
|
|
55
|
+
if (installing)
|
|
56
|
+
return "安裝進行中,完成後才能更新。";
|
|
57
|
+
if (source.kind === "exe" && !writable)
|
|
58
|
+
return "VansPod.exe 所在的資料夾無法寫入,請到 GitHub 下載新版。";
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
/** exe 與 npm 的不同之處:告訴學生會做什麼,以及換好之後怎麼啟動 VansPod。 */
|
|
62
|
+
function updateSteps(installation, version) {
|
|
63
|
+
return installation.kind === "exe"
|
|
64
|
+
? { action: `將下載 VansPod.exe v${version} 並驗證,接著取代 ${installation.file},完成後重新啟動 VansPod。`, start: { file: installation.file, args: ["start"] } }
|
|
65
|
+
: { action: `將執行 npm install -g vanspod@${version},完成後重新啟動 VansPod。`, start: { file: installation.node, args: [node_path_1.default.join(installation.root, "bin", "vanspod.cjs"), "start"] } };
|
|
66
|
+
}
|
|
67
|
+
/** 背景檢查:啟動後延遲一次,之後固定間隔;結果只放記憶體,失敗時保留上次查到的版本。 */
|
|
68
|
+
function createUpdateChecker() {
|
|
69
|
+
let state = {};
|
|
70
|
+
let pending;
|
|
71
|
+
const check = () => pending ??= fetchLatestVersion()
|
|
72
|
+
.then(latest => { state = { latest }; })
|
|
73
|
+
.catch((error) => { state = { latest: state.latest, error: error instanceof Error ? error.message : "檢查失敗" }; })
|
|
74
|
+
.finally(() => { pending = undefined; });
|
|
75
|
+
return {
|
|
76
|
+
check,
|
|
77
|
+
state: () => state,
|
|
78
|
+
start() {
|
|
79
|
+
const first = setTimeout(() => { void check(); }, CHECK_DELAY_MS);
|
|
80
|
+
const every = setInterval(() => { void check(); }, CHECK_INTERVAL_MS);
|
|
81
|
+
first.unref();
|
|
82
|
+
every.unref();
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function checksumFor(sums, name) {
|
|
87
|
+
for (const line of sums.split(/\r?\n/)) {
|
|
88
|
+
const match = /^([a-f0-9]{64})\s+\*?(.+)$/i.exec(line.trim());
|
|
89
|
+
if (match && match[2] === name)
|
|
90
|
+
return match[1].toLowerCase();
|
|
91
|
+
}
|
|
92
|
+
throw new Error(`SHA256SUMS.txt 沒有 ${name}`);
|
|
93
|
+
}
|
|
94
|
+
/** 從 GitHub Release 下載新版 exe 到原檔旁的 `.new`;SHA-256 不符就刪掉並失敗。 */
|
|
95
|
+
async function downloadExe(version, file, onProgress, fetcher = fetch) {
|
|
96
|
+
const get = async (name) => {
|
|
97
|
+
const response = await fetcher(`${downloadBase(version)}/${name}`, { signal: AbortSignal.timeout(10 * 60_000) });
|
|
98
|
+
if (!response.ok || !response.body)
|
|
99
|
+
throw new Error(`下載 ${name} 失敗(${response.status})`);
|
|
100
|
+
return response;
|
|
101
|
+
};
|
|
102
|
+
const expected = checksumFor(await (await get("SHA256SUMS.txt")).text(), "VansPod.exe");
|
|
103
|
+
const response = await get("VansPod.exe");
|
|
104
|
+
const total = Number(response.headers.get("content-length")) || 0;
|
|
105
|
+
const target = `${file}.new`;
|
|
106
|
+
const hash = (0, node_crypto_1.createHash)("sha256");
|
|
107
|
+
const handle = await promises_1.default.open(target, "w");
|
|
108
|
+
let received = 0;
|
|
109
|
+
try {
|
|
110
|
+
const reader = response.body.getReader();
|
|
111
|
+
for (;;) {
|
|
112
|
+
const { done, value } = await reader.read();
|
|
113
|
+
if (done)
|
|
114
|
+
break;
|
|
115
|
+
hash.update(value);
|
|
116
|
+
await handle.write(value);
|
|
117
|
+
received += value.length;
|
|
118
|
+
if (total)
|
|
119
|
+
onProgress(Math.min(100, Math.floor(received * 100 / total)));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
await handle.close();
|
|
124
|
+
}
|
|
125
|
+
if (hash.digest("hex") !== expected) {
|
|
126
|
+
await promises_1.default.rm(target, { force: true });
|
|
127
|
+
throw new Error("下載的 VansPod.exe 驗證失敗,已刪除。");
|
|
128
|
+
}
|
|
129
|
+
return target;
|
|
130
|
+
}
|
|
131
|
+
async function folderWritable(file) {
|
|
132
|
+
const probe = node_path_1.default.join(node_path_1.default.dirname(file), `.vanspod-write-${process.pid}.tmp`);
|
|
133
|
+
try {
|
|
134
|
+
await promises_1.default.writeFile(probe, "");
|
|
135
|
+
await promises_1.default.rm(probe);
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** 讀出並清掉上一次更新工具留下的結果。 */
|
|
143
|
+
async function takeUpdateResult() {
|
|
144
|
+
const file = node_path_1.default.join((0, instance_1.managementDirectory)(), "update-result.json");
|
|
145
|
+
try {
|
|
146
|
+
const raw = (await promises_1.default.readFile(file, "utf8")).replace(/^/, "");
|
|
147
|
+
await promises_1.default.rm(file, { force: true });
|
|
148
|
+
const value = JSON.parse(raw);
|
|
149
|
+
return typeof value.ok === "boolean" && typeof value.target === "string" ? value : undefined;
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** 寫出更新工具與計畫;回傳的函式啟動工具,之後 VansPod 必須自己結束。 */
|
|
156
|
+
async function prepareUpdate(plan) {
|
|
157
|
+
const root = (0, instance_1.managementDirectory)();
|
|
158
|
+
const script = node_path_1.default.join(root, "update-tool.ps1");
|
|
159
|
+
const file = node_path_1.default.join(root, "update-plan.json");
|
|
160
|
+
await (0, desktop_1.writeTool)(script, "update.ps1");
|
|
161
|
+
const full = { version: 1, root, start: updateSteps(plan.installation, plan.target).start, ...plan };
|
|
162
|
+
await promises_1.default.writeFile(file, JSON.stringify(full), { mode: 0o600 });
|
|
163
|
+
return () => (0, desktop_1.startHiddenTool)(script, file, node_path_1.default.join(root, "update-ready"), "更新工具");
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* 側欄更新按鈕背後的版本更新:查狀態、按下更新。
|
|
167
|
+
* 按下後在背景下載與驗證,再由 `exit` 恢復客戶端設定、啟動更新工具並結束 VansPod。
|
|
168
|
+
*/
|
|
169
|
+
function createVersionUpdate(options) {
|
|
170
|
+
const checker = createUpdateChecker();
|
|
171
|
+
const { current, source } = options;
|
|
172
|
+
let phase = "idle";
|
|
173
|
+
let progress;
|
|
174
|
+
let error;
|
|
175
|
+
const snapshot = async (refresh) => {
|
|
176
|
+
if (refresh)
|
|
177
|
+
await checker.check();
|
|
178
|
+
const check = checker.state();
|
|
179
|
+
const available = !!check.latest && compareVersions(check.latest, current) > 0;
|
|
180
|
+
const writable = source.kind === "exe" ? await folderWritable(source.file) : true;
|
|
181
|
+
return {
|
|
182
|
+
ok: true, current, latest: check.latest, available, source: source.kind,
|
|
183
|
+
block: updateBlock(source, options.work().installing, writable),
|
|
184
|
+
action: available && source.kind !== "source" ? updateSteps(source, check.latest).action : undefined,
|
|
185
|
+
checkError: check.error, releasesUrl: RELEASES_URL, phase, progress, error,
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
const install = async (running, target) => {
|
|
189
|
+
try {
|
|
190
|
+
// npm 用登記時的 node 與 npm,跟完整移除一樣。
|
|
191
|
+
const installation = running.kind === "npm"
|
|
192
|
+
? (await (0, installations_1.installations)()).find(item => item.kind === "npm" && item.root.toLowerCase() === running.root.toLowerCase()) ?? running
|
|
193
|
+
: running;
|
|
194
|
+
let download;
|
|
195
|
+
if (installation.kind === "exe")
|
|
196
|
+
download = await downloadExe(target, installation.file, percent => { progress = percent; });
|
|
197
|
+
phase = "restarting";
|
|
198
|
+
await options.exit(await prepareUpdate({ pid: process.pid, from: current, target, headless: process.env.CLASSROOM_APP_HEADLESS === "1", installation, download }));
|
|
199
|
+
}
|
|
200
|
+
catch (failure) {
|
|
201
|
+
phase = "idle";
|
|
202
|
+
progress = undefined;
|
|
203
|
+
error = `更新未完成:${failure instanceof Error ? failure.message : "未知錯誤"}`;
|
|
204
|
+
if (running.kind === "exe")
|
|
205
|
+
await promises_1.default.rm(`${running.file}.new`, { force: true });
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
return {
|
|
209
|
+
/** `takeResult`:剛更新完重新載入的頁面才讀走上一次的結果;背景輪詢不碰它。 */
|
|
210
|
+
async status(request = {}) {
|
|
211
|
+
// 更新工具等新版就緒後才寫出結果,所以要讀的時候每次都讀;讀到就刪,只回報一次。
|
|
212
|
+
const lastResult = request.takeResult ? await takeUpdateResult() : undefined;
|
|
213
|
+
return { ...await snapshot(request.refresh === true), lastResult };
|
|
214
|
+
},
|
|
215
|
+
start: () => checker.start(),
|
|
216
|
+
async run(body) {
|
|
217
|
+
if (phase !== "idle")
|
|
218
|
+
return { ok: false, message: "更新已在進行中。" };
|
|
219
|
+
const now = await snapshot(true);
|
|
220
|
+
if (!now.available)
|
|
221
|
+
return { ok: false, message: now.latest ? `v${current} 已是最新版本。` : "暫時查不到最新版本,請稍後再試。" };
|
|
222
|
+
if (now.block || source.kind === "source")
|
|
223
|
+
return { ok: false, message: now.block };
|
|
224
|
+
// 安裝中已經擋下,這裡只剩模型回答需要確認。
|
|
225
|
+
const decision = (0, exitGuard_1.exitDecision)("update", { installing: false, activeRequests: options.work().activeRequests }, body.interruptConfirmed === true);
|
|
226
|
+
if (!decision.proceed)
|
|
227
|
+
return { ok: false, confirmation: true, message: decision.message };
|
|
228
|
+
phase = source.kind === "exe" ? "downloading" : "restarting";
|
|
229
|
+
progress = undefined;
|
|
230
|
+
error = undefined;
|
|
231
|
+
void install(source, now.latest);
|
|
232
|
+
return { ok: true };
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// 側欄底部的版本更新按鈕與確認對話框(原型 A)。按鈕預設隱藏,管理 API 可用時由腳本顯示。
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.VERSION_UPDATE_STYLES = exports.UPDATE_BUTTON = void 0;
|
|
5
|
+
exports.versionUpdateScript = versionUpdateScript;
|
|
6
|
+
const DOWNLOAD_ICON = `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4v11m0 0-4.5-4.5M12 15l4.5-4.5M5 19h14"/></svg>`;
|
|
7
|
+
exports.UPDATE_BUTTON = `<button type="button" class="update-button" data-version-update hidden aria-label="檢查更新" title="檢查更新">${DOWNLOAD_ICON}<span class="update-dot"></span></button>`;
|
|
8
|
+
exports.VERSION_UPDATE_STYLES = `
|
|
9
|
+
.bar .side-foot { margin-top: auto; display: flex; align-items: center; gap: 6px; }
|
|
10
|
+
.update-button { position: relative; display: grid; place-items: center; width: 34px; height: 34px; min-height: 34px; padding: 0; border-radius: 999px; border: 1px solid var(--line); background: transparent; color: var(--muted); cursor: pointer; }
|
|
11
|
+
.update-button[hidden] { display: none; }
|
|
12
|
+
.update-button:hover { color: var(--text); background: light-dark(rgba(13, 13, 13, 0.04), rgba(255, 255, 255, 0.06)); }
|
|
13
|
+
.update-button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
|
14
|
+
.update-button svg { width: 18px; height: 18px; }
|
|
15
|
+
.update-button .update-dot { display: none; position: absolute; top: 3px; right: 3px; width: 7px; height: 7px; border-radius: 999px; background: #2563eb; box-shadow: 0 0 0 2px var(--bg); }
|
|
16
|
+
.update-button.available { color: #2563eb; border-color: rgba(37, 99, 235, 0.45); background: rgba(37, 99, 235, 0.08); }
|
|
17
|
+
.update-button.available .update-dot { display: block; }
|
|
18
|
+
.update-scrim { position: fixed; inset: 0; z-index: 60; display: grid; place-items: center; padding: 16px; background: light-dark(rgba(20, 20, 20, 0.32), rgba(0, 0, 0, 0.55)); }
|
|
19
|
+
.update-dialog { width: min(440px, 100%); background: light-dark(#ffffff, #2a2a2a); color: var(--text); border: 1px solid var(--line); border-radius: 16px; padding: 22px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25); }
|
|
20
|
+
.update-dialog h3 { margin: 0 0 14px; font-size: 17px; font-weight: 600; }
|
|
21
|
+
.update-versions { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 10px; padding: 14px; border-radius: 12px; background: light-dark(#f6f6f6, #333333); margin-bottom: 12px; }
|
|
22
|
+
.update-versions small { display: block; color: var(--muted); font-size: 11px; }
|
|
23
|
+
.update-versions b { font-family: Consolas, "Cascadia Mono", monospace; font-size: 16px; }
|
|
24
|
+
.update-versions span { color: var(--muted); }
|
|
25
|
+
.update-text { margin: 0 0 8px; font-size: 12.5px; line-height: 1.55; color: var(--muted); overflow-wrap: anywhere; }
|
|
26
|
+
.update-note { margin: 8px 0; padding: 9px 11px; border-radius: 10px; font-size: 12.5px; line-height: 1.5; overflow-wrap: anywhere; }
|
|
27
|
+
.update-note.ok { background: light-dark(#e9f7ef, #1d3527); color: light-dark(#17703d, #8be0ad); }
|
|
28
|
+
.update-note.warn { background: light-dark(#fff7e6, #3a2f17); color: light-dark(#8a5300, #f5c46b); }
|
|
29
|
+
.update-note.block { background: light-dark(#fdecec, #3d1f1f); color: light-dark(#b91c1c, #f8a5a5); }
|
|
30
|
+
.update-note a, .update-actions a { color: inherit; font-weight: 600; }
|
|
31
|
+
.update-meter { height: 6px; margin: 10px 0 4px; border-radius: 999px; background: light-dark(#ececec, #3a3a3a); overflow: hidden; }
|
|
32
|
+
.update-meter i { display: block; height: 100%; background: #2563eb; transition: width 0.2s; }
|
|
33
|
+
.update-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin-top: 16px; }
|
|
34
|
+
.update-actions a { margin-right: auto; font-size: 12.5px; font-weight: 400; color: var(--muted); }
|
|
35
|
+
.update-actions button { min-height: 34px; padding: 8px 16px; border-radius: 999px; border: 1px solid var(--line); background: transparent; color: var(--text); font-size: 13px; font-weight: 500; cursor: pointer; }
|
|
36
|
+
.update-actions button.primary { background: var(--accent); color: var(--on-accent); border-color: transparent; }
|
|
37
|
+
.update-actions button.danger { background: light-dark(#b91c1c, #dc2626); color: #ffffff; border-color: transparent; }
|
|
38
|
+
.update-actions button:disabled { opacity: 0.45; cursor: not-allowed; }
|
|
39
|
+
.update-reconnect { position: fixed; inset: 0; z-index: 80; display: grid; place-items: center; padding: 16px; text-align: center; color: var(--text); background: light-dark(rgba(255, 255, 255, 0.9), rgba(20, 20, 20, 0.9)); backdrop-filter: blur(4px); }
|
|
40
|
+
.update-reconnect p { margin-top: 6px; color: var(--muted); font-size: 13px; }
|
|
41
|
+
.update-spinner { width: 28px; height: 28px; margin: 0 auto 12px; border-radius: 999px; border: 3px solid var(--line); border-top-color: #2563eb; animation: update-spin 0.8s linear infinite; }
|
|
42
|
+
@keyframes update-spin { to { transform: rotate(360deg); } }
|
|
43
|
+
.update-toast { position: fixed; top: 18px; left: 50%; z-index: 90; transform: translateX(-50%); padding: 9px 16px; border-radius: 999px; background: #16a34a; color: #ffffff; font-size: 13px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2); }`;
|
|
44
|
+
/** 按鈕與對話框的行為;需要管理 API 的 token,所以由 lifecyclePage 注入。 */
|
|
45
|
+
function versionUpdateScript(token) {
|
|
46
|
+
return `<script>
|
|
47
|
+
(function () {
|
|
48
|
+
var token = ${JSON.stringify(token)};
|
|
49
|
+
var button = document.querySelector('[data-version-update]');
|
|
50
|
+
if (!button) return;
|
|
51
|
+
var state = null, open = false, checking = false, confirming = '', message = '', busy = false;
|
|
52
|
+
function esc(value) { return String(value).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; }); }
|
|
53
|
+
async function api(body, query) {
|
|
54
|
+
var response = await fetch('/_vanspod/update' + (query ? '?' + query : ''), {method: body ? 'POST' : 'GET', headers: {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}, body: body ? JSON.stringify(body) : undefined, cache: 'no-store'});
|
|
55
|
+
if (!response.ok) throw new Error('VansPod 沒有回應。');
|
|
56
|
+
return response.json();
|
|
57
|
+
}
|
|
58
|
+
function paintButton() {
|
|
59
|
+
button.hidden = false;
|
|
60
|
+
var available = !!(state && state.available);
|
|
61
|
+
button.classList.toggle('available', available);
|
|
62
|
+
var label = available ? '有新版本 v' + state.latest : '檢查更新';
|
|
63
|
+
button.title = label; button.setAttribute('aria-label', label);
|
|
64
|
+
}
|
|
65
|
+
function close() { if (busy) return; open = false; confirming = ''; message = ''; render(); }
|
|
66
|
+
function render() {
|
|
67
|
+
paintButton();
|
|
68
|
+
var scrim = document.querySelector('.update-scrim');
|
|
69
|
+
if (!open) { if (scrim) scrim.remove(); return; }
|
|
70
|
+
if (!scrim) {
|
|
71
|
+
scrim = document.createElement('div'); scrim.className = 'update-scrim';
|
|
72
|
+
scrim.addEventListener('click', function (event) { if (event.target === scrim) close(); });
|
|
73
|
+
document.body.appendChild(scrim);
|
|
74
|
+
}
|
|
75
|
+
var s = state || {};
|
|
76
|
+
var html = '<div class="update-dialog" role="dialog" aria-modal="true" aria-label="版本更新"><h3>版本更新</h3>'
|
|
77
|
+
+ '<div class="update-versions"><div><small>目前版本</small><b>v' + esc(s.current || '') + '</b></div><span>→</span><div><small>最新版本</small><b>' + (s.latest ? 'v' + esc(s.latest) : '—') + '</b></div></div>';
|
|
78
|
+
if (checking) html += '<p class="update-text">檢查最新版本…</p>';
|
|
79
|
+
else if (!s.latest) html += '<div class="update-note warn">暫時查不到最新版本,請確認網路後再試。</div>';
|
|
80
|
+
else if (!s.available) html += '<div class="update-note ok">v' + esc(s.current) + ' 已是最新版本。</div>';
|
|
81
|
+
if (message) html += '<div class="update-note block">' + esc(message) + '</div>';
|
|
82
|
+
if (s.error && !message) html += '<div class="update-note block">' + esc(s.error) + '</div>';
|
|
83
|
+
if (s.available && s.block) html += '<div class="update-note block">' + esc(s.block) + (s.source === 'exe' ? ' <a href="' + esc(s.releasesUrl) + '/latest" target="_blank" rel="noopener">前往 GitHub 下載</a>' : '') + '</div>';
|
|
84
|
+
if (s.available && !s.block) html += '<p class="update-text">' + esc(s.action || '') + '</p><p class="update-text">重新啟動後,Prompt 觀察室的觀察紀錄會清空。</p>';
|
|
85
|
+
if (confirming) html += '<div class="update-note warn">' + esc(confirming) + '</div>';
|
|
86
|
+
if (s.phase === 'downloading') html += '<div class="update-meter"><i style="width:' + (s.progress || 2) + '%"></i></div><p class="update-text">下載並驗證 VansPod.exe… ' + (s.progress ? s.progress + '%' : '') + '</p>';
|
|
87
|
+
var canRun = s.available && !s.block && !checking && !busy && s.phase === 'idle';
|
|
88
|
+
html += '<div class="update-actions">' + (s.latest ? '<a href="' + esc(s.releasesUrl) + '/tag/v' + esc(s.latest) + '" target="_blank" rel="noopener">版本說明</a>' : '')
|
|
89
|
+
+ '<button type="button" data-update-cancel' + (busy ? ' disabled' : '') + '>取消</button>'
|
|
90
|
+
+ '<button type="button" class="' + (confirming ? 'danger' : 'primary') + '" data-update-run' + (canRun ? '' : ' disabled') + '>' + (confirming ? '中斷回答並更新' : '立即更新') + '</button></div></div>';
|
|
91
|
+
scrim.innerHTML = html;
|
|
92
|
+
}
|
|
93
|
+
var pendingKey = 'vanspod-update-target';
|
|
94
|
+
function reconnect() {
|
|
95
|
+
try { if (state && state.latest) sessionStorage.setItem(pendingKey, state.latest); } catch (error) {}
|
|
96
|
+
open = false; render();
|
|
97
|
+
var overlay = document.createElement('div'); overlay.className = 'update-reconnect';
|
|
98
|
+
overlay.innerHTML = '<div><div class="update-spinner"></div><b>VansPod 正在更新並重新啟動</b><p>重新連線中…</p></div>';
|
|
99
|
+
document.body.appendChild(overlay);
|
|
100
|
+
var started = Date.now(), wentDown = false;
|
|
101
|
+
(function poll() {
|
|
102
|
+
var done = wentDown ? fetch('/', {cache: 'no-store'}).then(function (response) { if (response.ok) location.reload(); else throw new Error(); }) : api().then(function () { throw new Error(); }, function () { wentDown = true; throw new Error(); });
|
|
103
|
+
done.catch(function () {
|
|
104
|
+
if (Date.now() - started > 180000) { overlay.querySelector('p').textContent = '更新似乎沒有完成,請重新開啟 VansPod。'; return; }
|
|
105
|
+
setTimeout(poll, 1000);
|
|
106
|
+
});
|
|
107
|
+
})();
|
|
108
|
+
}
|
|
109
|
+
async function follow() {
|
|
110
|
+
try { state = await api(); } catch (error) { reconnect(); return; }
|
|
111
|
+
if (state.phase === 'restarting') { reconnect(); return; }
|
|
112
|
+
if (state.phase === 'idle') { busy = false; render(); return; }
|
|
113
|
+
render(); setTimeout(follow, 500);
|
|
114
|
+
}
|
|
115
|
+
async function run() {
|
|
116
|
+
busy = true; message = ''; render();
|
|
117
|
+
try {
|
|
118
|
+
var result = await api({interruptConfirmed: !!confirming});
|
|
119
|
+
if (result.confirmation) { busy = false; confirming = result.message; render(); return; }
|
|
120
|
+
confirming = '';
|
|
121
|
+
if (!result.ok) { busy = false; message = result.message || '無法更新,請稍後再試。'; render(); return; }
|
|
122
|
+
follow();
|
|
123
|
+
} catch (error) { busy = false; message = error.message; render(); }
|
|
124
|
+
}
|
|
125
|
+
button.addEventListener('click', async function () {
|
|
126
|
+
open = true; checking = true; message = ''; render();
|
|
127
|
+
try { state = await api(null, 'refresh=1'); } catch (error) { message = error.message; }
|
|
128
|
+
checking = false; render();
|
|
129
|
+
});
|
|
130
|
+
document.addEventListener('click', function (event) {
|
|
131
|
+
if (!event.target.closest) return;
|
|
132
|
+
if (event.target.closest('[data-update-cancel]')) close();
|
|
133
|
+
if (event.target.closest('[data-update-run]')) run();
|
|
134
|
+
});
|
|
135
|
+
document.addEventListener('keydown', function (event) { if (event.key === 'Escape' && open) close(); });
|
|
136
|
+
function toast(text) {
|
|
137
|
+
var element = document.createElement('div'); element.className = 'update-toast'; element.textContent = text;
|
|
138
|
+
document.body.appendChild(element); setTimeout(function () { element.remove(); }, 4000);
|
|
139
|
+
}
|
|
140
|
+
// 只有這裡讀走上一次的結果。剛更新完重新載入時,更新工具可能還沒寫出結果,最多等 60 秒。
|
|
141
|
+
function load(attempt) {
|
|
142
|
+
var pending = null;
|
|
143
|
+
try { pending = sessionStorage.getItem(pendingKey); } catch (error) {}
|
|
144
|
+
api(null, 'result=1').then(function (next) {
|
|
145
|
+
state = next; render();
|
|
146
|
+
var last = next.lastResult;
|
|
147
|
+
if (!last && pending && attempt < 60) { setTimeout(function () { load(attempt + 1); }, 1000); return; }
|
|
148
|
+
try { sessionStorage.removeItem(pendingKey); } catch (error) {}
|
|
149
|
+
if (last && !last.ok) { open = true; message = last.message || '更新未完成。'; render(); }
|
|
150
|
+
else if ((last && last.target === next.current) || pending === next.current) toast('已更新到 v' + next.current);
|
|
151
|
+
}).catch(function () {});
|
|
152
|
+
}
|
|
153
|
+
load(0);
|
|
154
|
+
setInterval(function () { if (!open) api().then(function (next) { state = next; render(); }).catch(function () {}); }, 600000);
|
|
155
|
+
})();
|
|
156
|
+
</script>`;
|
|
157
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vanspod",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"bin": { "vanspod": "bin/vanspod.cjs" },
|
|
5
5
|
"engines": { "node": ">=24" },
|
|
6
6
|
"os": ["win32"],
|
|
7
|
-
"files": ["bin/", "dist/**/*.js", "!dist/test/**", "!dist/sea-*.js", "media/brand-logo.png", "media/brand-icon.ico", "media/fadou-superhero.png", "media/fadou-superhero-blink.png", "scripts/tray.ps1", "scripts/uninstall.ps1", "README.md"],
|
|
7
|
+
"files": ["bin/", "dist/**/*.js", "!dist/test/**", "!dist/sea-*.js", "media/brand-logo.png", "media/brand-icon.ico", "media/fadou-superhero.png", "media/fadou-superhero-blink.png", "scripts/tray.ps1", "scripts/uninstall.ps1", "scripts/update.ps1", "README.md"],
|
|
8
8
|
"publishConfig": { "access": "public" },
|
|
9
9
|
"description": "本機 VansPod。學生用系統瀏覽器兌換課堂連線。",
|
|
10
10
|
"repository": { "type": "git", "url": "git+https://github.com/mz038197/VansPod.git" },
|