vanspod 0.2.0 → 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 CHANGED
@@ -38,7 +38,7 @@ npm run dist
38
38
  npm pack --pack-destination dist
39
39
  ```
40
40
 
41
- exe 產物為 `dist/VansPod.exe`,本機套件為 `dist/vanspod-0.2.0.tgz`;可在 Windows 用 `npm install -g <套件路徑>` 安裝測試。圖片、favicon、系統匣與移除腳本均包含在發佈產物中。更新 logo 後執行 `powershell.exe -NoProfile -File scripts/build-icon.ps1` 重建多尺寸 Windows icon。
41
+ exe 產物為 `dist/VansPod.exe`,本機套件為 `dist/vanspod-0.3.0.tgz`;可在 Windows 用 `npm install -g <套件路徑>` 安裝測試。圖片、favicon、系統匣與移除腳本均包含在發佈產物中。更新 logo 後執行 `powershell.exe -NoProfile -File scripts/build-icon.ps1` 重建多尺寸 Windows icon。
42
42
 
43
43
  exe 發佈管道為本專案 GitHub Releases,npm 為公開 registry 的 [`vanspod`](https://www.npmjs.com/package/vanspod) 套件。更新時不要執行完整移除,否則會清除課堂資料。
44
44
 
@@ -46,12 +46,12 @@ exe 發佈管道為本專案 GitHub Releases,npm 為公開 registry 的 [`vans
46
46
 
47
47
  一般 push 不發佈;推送 `v*` tag 會在 Windows runner 安裝 Node.js 24、檢查型別、執行測試、打包並驗證 exe/npm 生命週期,全部通過後才建立 GitHub Release,最後發佈 npm 套件。學生從 Release 下載 `VansPod.exe`,同頁提供 `SHA256SUMS.txt`。
48
48
 
49
- 發版前同步 `package.json`、`package-lock.json` 與 `src/version.ts` 的版本;tag 必須等於 `v` 加版本號,否則流程失敗。以 `0.2.0` 為例:
49
+ 發版前同步 `package.json`、`package-lock.json` 與 `src/version.ts` 的版本;tag 必須等於 `v` 加版本號,否則流程失敗。以 `0.3.0` 為例:
50
50
 
51
51
  ```powershell
52
52
  git push origin master
53
- git tag -a v0.2.0 -m "VansPod 0.2.0"
54
- git push origin v0.2.0
53
+ git tag -a v0.3.0 -m "VansPod 0.3.0"
54
+ git push origin v0.3.0
55
55
  ```
56
56
 
57
57
  新版本使用新的版本號與 tag。相同 tag 的 Actions 重跑會更新該 Release 的產物。
package/dist/desktop.js CHANGED
@@ -5,6 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.openBrowser = openBrowser;
7
7
  exports.asset = asset;
8
+ exports.writeTool = writeTool;
9
+ exports.startHiddenTool = startHiddenTool;
8
10
  const node_child_process_1 = require("node:child_process");
9
11
  const node_sea_1 = require("node:sea");
10
12
  const promises_1 = __importDefault(require("node:fs/promises"));
@@ -23,3 +25,23 @@ function asset(name) {
23
25
  ? Promise.resolve(Buffer.from((0, node_sea_1.getAsset)(name)))
24
26
  : promises_1.default.readFile(node_path_1.default.join(__dirname, "..", name.startsWith("brand-") || name.startsWith("fadou-superhero") ? "media" : "scripts", name));
25
27
  }
28
+ /** 把內嵌的 PowerShell 工具寫到磁碟;Windows PowerShell 5.1 需要 BOM 才會以 UTF-8 讀中文。 */
29
+ async function writeTool(file, name) {
30
+ await promises_1.default.writeFile(file, Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), await asset(name)]));
31
+ }
32
+ /** 啟動一個在 VansPod 結束後仍會繼續執行的 PowerShell 工具,等它寫出 ready 檔才返回。 */
33
+ async function startHiddenTool(script, plan, ready, name) {
34
+ await promises_1.default.rm(ready, { force: true });
35
+ // Start-Process gives the helper its own hidden console. A PowerShell child
36
+ // attached to the worker's console would die when that worker exits.
37
+ const literal = (value) => `'${value.replaceAll("'", "''")}'`;
38
+ const command = `Start-Process -FilePath powershell.exe -WindowStyle Hidden -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ${literal(`"${script}"`)}, '-Plan', ${literal(`"${plan}"`)})`;
39
+ const child = (0, node_child_process_1.spawn)("powershell.exe", ["-NoProfile", "-EncodedCommand", Buffer.from(command, "utf16le").toString("base64")], { windowsHide: true, stdio: "ignore" });
40
+ await new Promise((resolve, reject) => { child.once("error", reject); child.once("exit", code => code === 0 ? resolve() : reject(new Error(`無法啟動${name}。`))); });
41
+ for (let attempt = 0; attempt < 100; attempt++) {
42
+ if (await promises_1.default.stat(ready).catch(() => undefined))
43
+ return;
44
+ await new Promise(resolve => setTimeout(resolve, 100));
45
+ }
46
+ throw new Error(`${name}未回應,請重試。`);
47
+ }
package/dist/exitGuard.js CHANGED
@@ -10,7 +10,7 @@ function exitDecision(action, work, confirmed) {
10
10
  ];
11
11
  if (!running.length || confirmed)
12
12
  return { proceed: true };
13
- return { proceed: false, message: `${running.join("、")},確認中止並${action === "stop" ? "結束" : "移除"} VansPod?` };
13
+ return { proceed: false, message: `${running.join("、")},確認中止並${{ stop: "結束", uninstall: "移除", update: "更新" }[action]} VansPod?` };
14
14
  }
15
15
  function removalInterruptions(work) {
16
16
  return `${work.installing ? "\n安裝仍在執行,移除前將中止安裝。" : ""}${work.activeRequests ? "\n仍有模型回答,移除將中斷目前回答。" : ""}`;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.installations = installations;
7
+ exports.detectInstallation = detectInstallation;
7
8
  exports.registerInstallation = registerInstallation;
8
9
  const node_crypto_1 = require("node:crypto");
9
10
  const node_sea_1 = require("node:sea");
@@ -24,21 +25,21 @@ async function installations() {
24
25
  throw error;
25
26
  }
26
27
  }
28
+ /** 目前這個行程是哪一份可登記的安裝;原始碼執行時沒有。 */
29
+ async function detectInstallation() {
30
+ if ((0, node_sea_1.isSea)())
31
+ return { kind: "exe", file: process.execPath, sha256: (0, node_crypto_1.createHash)("sha256").update(await promises_1.default.readFile(process.execPath)).digest("hex") };
32
+ const root = node_path_1.default.resolve(__dirname, "..");
33
+ if (node_path_1.default.basename(root).toLowerCase() !== "vanspod" || node_path_1.default.basename(node_path_1.default.dirname(root)) !== "node_modules")
34
+ return undefined;
35
+ const npmCli = process.env.npm_execpath && node_path_1.default.basename(process.env.npm_execpath) === "npm-cli.js"
36
+ ? process.env.npm_execpath : node_path_1.default.join(node_path_1.default.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
37
+ return await promises_1.default.stat(npmCli).catch(() => undefined) ? { kind: "npm", root, prefix: node_path_1.default.dirname(node_path_1.default.dirname(root)), node: process.execPath, npmCli } : undefined;
38
+ }
27
39
  async function registerInstallation() {
28
40
  if (await (0, instance_1.removalInProgress)())
29
41
  throw new Error("VansPod 完整移除中,請稍後重試。");
30
- let installation;
31
- if ((0, node_sea_1.isSea)())
32
- installation = { kind: "exe", file: process.execPath, sha256: (0, node_crypto_1.createHash)("sha256").update(await promises_1.default.readFile(process.execPath)).digest("hex") };
33
- else {
34
- const root = node_path_1.default.resolve(__dirname, "..");
35
- if (node_path_1.default.basename(root).toLowerCase() === "vanspod" && node_path_1.default.basename(node_path_1.default.dirname(root)) === "node_modules") {
36
- const npmCli = process.env.npm_execpath && node_path_1.default.basename(process.env.npm_execpath) === "npm-cli.js"
37
- ? process.env.npm_execpath : node_path_1.default.join(node_path_1.default.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
38
- if (await promises_1.default.stat(npmCli).catch(() => undefined))
39
- installation = { kind: "npm", root, prefix: node_path_1.default.dirname(node_path_1.default.dirname(root)), node: process.execPath, npmCli };
40
- }
41
- }
42
+ const installation = await detectInstallation();
42
43
  if (!installation)
43
44
  return;
44
45
  await promises_1.default.mkdir((0, instance_1.managementDirectory)(), { recursive: true });
package/dist/launcher.js CHANGED
@@ -137,7 +137,9 @@ async function runCli(args = process.argv.slice(2)) {
137
137
  throw new Error("VansPod 啟動逾時,請稍後用 vanspod status 檢查。");
138
138
  const live = (await (0, instance_1.readInstance)());
139
139
  await (0, instance_1.control)(live, "open", { version: version_1.VERSION });
140
- (0, desktop_1.openBrowser)(`${ready.origin}/`);
140
+ // 版本更新的工具重新啟動時,原本的分頁會自己重新連線。
141
+ if (process.env.VANSPOD_RESTART !== "1")
142
+ (0, desktop_1.openBrowser)(`${ready.origin}/`);
141
143
  process.stdout.write(`VansPod ${ready.version}: ${ready.origin}/\n`);
142
144
  if (ready.version !== version_1.VERSION)
143
145
  process.stdout.write(`本次開啟版本 ${version_1.VERSION},目前執行版本 ${ready.version};換版請先結束 VansPod。\n`);
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.lifecyclePage = lifecyclePage;
4
+ const versionUpdateView_1 = require("./versionUpdateView");
4
5
  function lifecyclePage(html, token) {
5
6
  const controls = `<div style="margin-top:16px"><button type="button" data-lifecycle="stop">結束 VansPod</button> <button type="button" data-lifecycle="uninstall">移除 VansPod</button><p role="status" data-lifecycle-message></p></div>`;
6
7
  const script = `<script>
@@ -37,5 +38,5 @@ function lifecyclePage(html, token) {
37
38
  }).catch(function () {});
38
39
  })();
39
40
  </script>`;
40
- return html.replace(/<form method="post" action="\/stop">[\s\S]*?<\/form>/, controls).replace('</body>', `${script}</body>`);
41
+ return html.replace(/<form method="post" action="\/stop">[\s\S]*?<\/form>/, controls).replace('</body>', `${script}${(0, versionUpdateView_1.versionUpdateScript)(token)}</body>`);
41
42
  }
package/dist/page.js CHANGED
@@ -15,6 +15,7 @@ const clientIcons_1 = require("./clientIcons");
15
15
  const environmentIcons_1 = require("./environmentIcons");
16
16
  const promptCapture_1 = require("./promptCapture");
17
17
  const inspectorView_1 = require("./inspectorView");
18
+ const versionUpdateView_1 = require("./versionUpdateView");
18
19
  const courseCatalog_1 = require("./courseCatalog");
19
20
  const PRODUCT = "VansPod";
20
21
  const VERSION = `v${version_1.VERSION}`;
@@ -577,7 +578,7 @@ const BRAND = `<div class="brand"><div class="logo-badge"><img src="/brand-logo.
577
578
  /** 兩頁共用的側欄:行動版頂列、抽屜遮罩、選單與外觀切換。 */
578
579
  function sideMenu(current) {
579
580
  const items = SIDE_PAGES.map((page) => `<a class="side-item" href="${page.href}"${page.id === current ? ' aria-current="page"' : ""}>${page.icon}<span>${page.label}</span></a>`).join("");
580
- return `<div class="mobile-top"><button type="button" class="menu-toggle" aria-label="開啟選單" aria-expanded="false" aria-controls="side-menu"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>${BRAND}</div><button type="button" class="drawer-scrim" aria-label="關閉選單"></button><header class="bar" id="side-menu">${BRAND}<nav aria-label="選單">${items}</nav><button type="button" data-appearance-toggle aria-label="切換外觀"></button></header>`;
581
+ return `<div class="mobile-top"><button type="button" class="menu-toggle" aria-label="開啟選單" aria-expanded="false" aria-controls="side-menu"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>${BRAND}</div><button type="button" class="drawer-scrim" aria-label="關閉選單"></button><header class="bar" id="side-menu">${BRAND}<nav aria-label="選單">${items}</nav><div class="side-foot"><button type="button" data-appearance-toggle aria-label="切換外觀"></button>${versionUpdateView_1.UPDATE_BUTTON}</div></header>`;
581
582
  }
582
583
  /** 兩頁共用的頁殼版面:側欄、行動版抽屜。 */
583
584
  const SHELL_LAYOUT_STYLES = `
@@ -594,7 +595,7 @@ const SHELL_LAYOUT_STYLES = `
594
595
  .side-item[aria-current="page"] { background: light-dark(rgba(13, 13, 13, 0.06), rgba(255, 255, 255, 0.09)); font-weight: 600; }
595
596
  .side-item:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
596
597
  .side-item svg { width: 18px; height: 18px; flex-shrink: 0; }
597
- .bar [data-appearance-toggle] { margin-top: auto; align-self: flex-start; }
598
+ ${versionUpdateView_1.VERSION_UPDATE_STYLES}
598
599
  .mobile-top, .drawer-scrim, .menu-toggle { display: none; }
599
600
  main { justify-self: center; width: min(52rem, 100%); }
600
601
  @media (max-width: 760px) {
package/dist/removal.js CHANGED
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.removalPreview = removalPreview;
7
7
  exports.prepareRemoval = prepareRemoval;
8
- const node_child_process_1 = require("node:child_process");
9
8
  const promises_1 = __importDefault(require("node:fs/promises"));
10
9
  const node_path_1 = __importDefault(require("node:path"));
11
10
  const node_os_1 = __importDefault(require("node:os"));
@@ -21,21 +20,7 @@ async function prepareRemoval(waitForPid, instanceId) {
21
20
  const root = (0, instance_1.managementDirectory)();
22
21
  const script = node_path_1.default.join(root, "uninstall-tool.ps1");
23
22
  const plan = node_path_1.default.join(root, "uninstall-plan.json");
24
- await promises_1.default.writeFile(script, Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), await (0, desktop_1.asset)("uninstall.ps1")]));
23
+ await (0, desktop_1.writeTool)(script, "uninstall.ps1");
25
24
  await promises_1.default.writeFile(plan, JSON.stringify({ version: 1, root, dataRoot: (0, instance_1.dataDirectory)(), instanceId, pid: process.pid, waitForPid, headless: process.env.CLASSROOM_APP_HEADLESS === "1", installations: await (0, installations_1.installations)() }), { mode: 0o600 });
26
- return async () => {
27
- await promises_1.default.rm(node_path_1.default.join(root, "uninstall-ready"), { force: true });
28
- // Start-Process gives the helper its own hidden console. A PowerShell child
29
- // attached to the worker's console would die when that worker exits.
30
- const literal = (value) => `'${value.replaceAll("'", "''")}'`;
31
- const command = `Start-Process -FilePath powershell.exe -WindowStyle Hidden -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ${literal(`"${script}"`)}, '-Plan', ${literal(`"${plan}"`)})`;
32
- const child = (0, node_child_process_1.spawn)("powershell.exe", ["-NoProfile", "-EncodedCommand", Buffer.from(command, "utf16le").toString("base64")], { windowsHide: true, stdio: "ignore" });
33
- await new Promise((resolve, reject) => { child.once("error", reject); child.once("exit", code => code === 0 ? resolve() : reject(new Error("無法啟動移除工具。"))); });
34
- for (let attempt = 0; attempt < 100; attempt++) {
35
- if (await promises_1.default.stat(node_path_1.default.join(root, "uninstall-ready")).catch(() => undefined))
36
- return;
37
- await new Promise(resolve => setTimeout(resolve, 100));
38
- }
39
- throw new Error("移除工具未回應,請重試。");
40
- };
25
+ return () => (0, desktop_1.startHiddenTool)(script, plan, node_path_1.default.join(root, "uninstall-ready"), "移除工具");
41
26
  }
package/dist/start.js CHANGED
@@ -33,6 +33,9 @@ const instance_1 = require("./instance");
33
33
  const desktop_1 = require("./desktop");
34
34
  const lifecyclePage_1 = require("./lifecyclePage");
35
35
  const removal_1 = require("./removal");
36
+ const installations_1 = require("./installations");
37
+ const versionUpdate_1 = require("./versionUpdate");
38
+ const version_1 = require("./version");
36
39
  const runtimeOptions = (0, runtimeOptions_1.readRuntimeOptions)(process.env);
37
40
  const port = runtimeOptions.port;
38
41
  const pageUrl = `http://127.0.0.1:${port}/`;
@@ -349,6 +352,45 @@ async function main(instance) {
349
352
  let exitRequested = false;
350
353
  const exitWork = () => ({ installing: app.view().commandRunning, activeRequests: activeRequests.size });
351
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
+ });
352
394
  let ready = false;
353
395
  let startupError;
354
396
  let tray;
@@ -445,11 +487,19 @@ async function main(instance) {
445
487
  }
446
488
  if (req.method === "POST" && pathname === "/_vanspod/open") {
447
489
  const body = JSON.parse(await readBody(req));
448
- if (typeof body.version === "string" && /^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(body.version))
490
+ if (typeof body.version === "string" && versionUpdate_1.VERSION_PATTERN.test(body.version))
449
491
  launchVersion = body.version;
450
492
  reply({ ok: true });
451
493
  return;
452
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
+ }
453
503
  if (req.method === "GET" && pathname === "/_vanspod/uninstall-preview") {
454
504
  reply({ ok: true, message: `${await (0, removal_1.removalPreview)()}${(0, exitGuard_1.removalInterruptions)(exitWork())}` });
455
505
  return;
@@ -470,24 +520,15 @@ async function main(instance) {
470
520
  reply({ ok: false, message: "正在結束 VansPod。" });
471
521
  return;
472
522
  }
473
- exitRequested = true;
474
- await app.abortInstall();
475
- abortRequests();
476
- let restored = false;
477
- try {
478
- await app.stop();
479
- restored = true;
480
- if (uninstall) {
481
- const launchRemoval = await (0, removal_1.prepareRemoval)(Number.isSafeInteger(body.waitForPid) && body.waitForPid > 0 ? body.waitForPid : undefined, instance.id);
482
- await launchRemoval();
483
- }
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) {
484
527
  reply({ ok: true, message: uninstall ? "完整移除已開始;結果會以 Windows 訊息顯示。未完成時會保留移除工具供重試。" : "VansPod 已結束,可關閉此分頁。" });
485
528
  res.once("finish", () => { void exit(); });
486
529
  }
487
- catch (error) {
488
- exitRequested = false;
489
- reply({ ok: false, message: restored ? `移除未完成:${error instanceof Error ? error.message : "移除工具啟動失敗"}。請重試移除。` : `客戶端設定恢復失敗(${Object.entries(app.view().clientRoutes ?? {}).filter(([, route]) => route.health === "red").map(([id]) => id).join("、")}),備份已保留,請重試結束。` });
490
- }
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("、")}),備份已保留,請重試結束。` });
491
532
  return;
492
533
  }
493
534
  reply({ ok: false, message: "管理操作無效。" });
@@ -809,6 +850,7 @@ async function main(instance) {
809
850
  }
810
851
  startupError += " 設定恢復未完成,服務已保留;修復後請重試 vanspod stop。";
811
852
  }
853
+ versionUpdate.start();
812
854
  tray = runtimeOptions.desktop && process.platform === "win32" && instance ? await openTray(home) : undefined;
813
855
  if (runtimeOptions.desktop && !process.env.VANSPOD_WORKER_TOKEN)
814
856
  (0, desktop_1.openBrowser)(home);
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
- exports.VERSION = "0.2.0";
4
+ exports.VERSION = "0.3.0";
@@ -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.2.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" },
@@ -0,0 +1,105 @@
1
+ param([string]$Plan = (Join-Path $PSScriptRoot 'update-plan.json'))
2
+ $ErrorActionPreference = 'Stop'
3
+ $utf8 = New-Object System.Text.UTF8Encoding($false)
4
+ $planData = [System.IO.File]::ReadAllText($Plan, $utf8) | ConvertFrom-Json
5
+ $localRoot = if ($env:LOCALAPPDATA) { $env:LOCALAPPDATA } else { $env:USERPROFILE }
6
+ $root = [System.IO.Path]::GetFullPath($planData.root)
7
+ $installation = $planData.installation
8
+ if ($planData.version -ne 1 -or $root -ne [System.IO.Path]::GetFullPath((Join-Path $localRoot 'VansPod')) -or [System.IO.Path]::GetFullPath($Plan) -ne (Join-Path $root 'update-plan.json') -or $planData.target -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$' -or $planData.from -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$') { throw 'Invalid update plan' }
9
+ if ($installation.kind -eq 'exe') {
10
+ $file = [System.IO.Path]::GetFullPath($installation.file)
11
+ if ([System.IO.Path]::GetExtension($file) -ne '.exe' -or [System.IO.Path]::GetFullPath($planData.download) -ne "$file.new") { throw 'Invalid update plan' }
12
+ } elseif ($installation.kind -ne 'npm') { throw 'Invalid update plan' }
13
+ [System.IO.File]::WriteAllText((Join-Path $root 'update-ready'), (@{pid = $PID} | ConvertTo-Json -Compress), $utf8)
14
+
15
+ function Write-Result([bool]$Ok, [string]$Message) {
16
+ $value = [ordered]@{ ok = $Ok; from = $planData.from; target = $planData.target }
17
+ if ($Message) { $value.message = $Message }
18
+ [System.IO.File]::WriteAllText((Join-Path $root 'update-result.json'), ($value | ConvertTo-Json -Compress), $utf8)
19
+ }
20
+
21
+ function Read-Instance {
22
+ try { return [System.IO.File]::ReadAllText((Join-Path $root 'runtime/instance.json'), $utf8) | ConvertFrom-Json } catch { return $null }
23
+ }
24
+
25
+ # 啟動指令等到 VansPod 就緒才結束;以結束碼與登記的版本判斷是否成功。
26
+ function Start-VansPod([string]$Expected) {
27
+ $env:VANSPOD_RESTART = '1'
28
+ # 工具是舊 worker 啟動的;帶著它的 token,launcher 會誤以為自己是 worker 而拒絕啟動。
29
+ Remove-Item Env:VANSPOD_WORKER_TOKEN -ErrorAction SilentlyContinue
30
+ $quoted = @($planData.start.args | ForEach-Object { '"' + ($_ -replace '"', '\"') + '"' }) -join ' '
31
+ $process = Start-Process -FilePath $planData.start.file -ArgumentList $quoted -WindowStyle Hidden -PassThru
32
+ $null = $process.Handle # 先取得 handle,結束後才讀得到 ExitCode。
33
+ if (-not $process.WaitForExit(120000)) { try { $process.Kill() } catch {}; return $false }
34
+ if ($process.ExitCode -ne 0) { return $false }
35
+ $instance = Read-Instance
36
+ return $instance -and $instance.version -eq $Expected
37
+ }
38
+
39
+ # 新版沒有就緒時,確保它的背景服務不會繼續佔用檔案。
40
+ function Stop-Target {
41
+ $instance = Read-Instance
42
+ if ($instance -and $instance.version -eq $planData.target) { Stop-Process -Id $instance.pid -Force -ErrorAction SilentlyContinue; Start-Sleep -Milliseconds 500 }
43
+ if ($installation.kind -eq 'exe') { Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $file } | Stop-Process -Force -ErrorAction SilentlyContinue }
44
+ }
45
+
46
+ # 把 .old 換回原位;檔案可能還被剛結束的新版佔著,所以重試一陣子。學生不能因此失去 VansPod.exe。
47
+ function Restore-Exe {
48
+ for ($attempt = 0; $attempt -lt 20; $attempt++) {
49
+ try {
50
+ if (Test-Path -LiteralPath $file) { Remove-Item -LiteralPath $file -Force }
51
+ Move-Item -LiteralPath "$file.old" -Destination $file
52
+ return
53
+ } catch { Start-Sleep -Milliseconds 250 }
54
+ }
55
+ throw "無法換回 v$($planData.from),舊版保留在 $file.old。"
56
+ }
57
+
58
+ $restarted = $true
59
+ $stopped = $false
60
+ try {
61
+ for ($attempt = 0; $attempt -lt 600 -and (Get-Process -Id $planData.pid -ErrorAction SilentlyContinue); $attempt++) { Start-Sleep -Milliseconds 100 }
62
+ if (Get-Process -Id $planData.pid -ErrorAction SilentlyContinue) { throw '舊版 VansPod 沒有結束,更新已取消。' }
63
+ $stopped = $true
64
+ if ($installation.kind -eq 'exe') {
65
+ $old = "$file.old"
66
+ if (Test-Path -LiteralPath $old) { Remove-Item -LiteralPath $old -Force }
67
+ Move-Item -LiteralPath $file -Destination $old
68
+ try { Move-Item -LiteralPath "$file.new" -Destination $file }
69
+ catch { Restore-Exe; throw "新版 VansPod.exe 無法放到原位置($($_.Exception.Message))" }
70
+ if (Start-VansPod $planData.target) { Remove-Item -LiteralPath $old -Force; Write-Result $true }
71
+ else {
72
+ Stop-Target
73
+ Restore-Exe
74
+ $restarted = Start-VansPod $planData.from
75
+ Write-Result $false "v$($planData.target) 無法啟動,已換回 v$($planData.from)。"
76
+ }
77
+ } else {
78
+ $ErrorActionPreference = 'Continue'
79
+ $output = & $installation.node $installation.npmCli install --global --prefix $installation.prefix "vanspod@$($planData.target)" 2>&1
80
+ $installed = $LASTEXITCODE -eq 0
81
+ $ErrorActionPreference = 'Stop'
82
+ if (-not $installed) {
83
+ $restarted = Start-VansPod $planData.from
84
+ $reason = @($output | ForEach-Object { "$_" } | Where-Object { $_.Trim() }) | Select-Object -Last 1
85
+ Write-Result $false "npm 安裝失敗($reason)。已保留 v$($planData.from)。可改用:npm install -g vanspod@$($planData.target)"
86
+ } elseif (Start-VansPod $planData.target) { Write-Result $true }
87
+ else {
88
+ Stop-Target
89
+ $restarted = $false
90
+ Write-Result $false "已安裝 v$($planData.target),但無法啟動。請執行 vanspod start 查看錯誤,或用 npm install -g vanspod@$($planData.from) 換回舊版。"
91
+ }
92
+ }
93
+ } catch {
94
+ Write-Result $false "更新未完成:$($_.Exception.Message)"
95
+ # 舊版已經結束時,盡量讓學生回到原本的版本。
96
+ $restarted = $stopped -and (Start-VansPod $planData.from)
97
+ if ($installation.kind -eq 'exe') { Remove-Item -LiteralPath "$file.new" -Force -ErrorAction SilentlyContinue }
98
+ } finally {
99
+ foreach ($name in @('update-plan.json', 'update-ready')) { Remove-Item -LiteralPath (Join-Path $root $name) -Force -ErrorAction SilentlyContinue }
100
+ Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
101
+ }
102
+ $result = [System.IO.File]::ReadAllText((Join-Path $root 'update-result.json'), $utf8) | ConvertFrom-Json
103
+ # VansPod 沒有重新啟動時,頁面看不到結果,改用 Windows 訊息告知。
104
+ if (-not $restarted -and -not $planData.headless) { Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show($result.message, 'VansPod') | Out-Null }
105
+ if (-not $result.ok) { exit 1 }