vanspod 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
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.readSystemPath = readSystemPath;
7
+ exports.sharedWhileRunning = sharedWhileRunning;
8
+ exports.envWithRegistryPath = envWithRegistryPath;
9
+ exports.withSystemPath = withSystemPath;
10
+ const node_child_process_1 = require("node:child_process");
11
+ const node_path_1 = __importDefault(require("node:path"));
12
+ /** 登錄檔裡 Machine 與 User 的 PATH,已展開變數;讀不到時回傳空陣列,沿用目前的 PATH。 */
13
+ function readSystemPath() {
14
+ // 走 PowerShell 而不是 reg.exe:reg.exe 以系統字碼頁輸出,中文使用者資料夾會變成亂碼。
15
+ const script = "[Console]::OutputEncoding = [Text.Encoding]::UTF8; [Environment]::GetEnvironmentVariable('Path', 'Machine'); [Environment]::GetEnvironmentVariable('Path', 'User')";
16
+ // 用完整路徑:要修的正是可能過時的 PATH。
17
+ const powershell = node_path_1.default.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
18
+ return new Promise(resolve => {
19
+ (0, node_child_process_1.execFile)(powershell, ["-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", timeout: 8000, windowsHide: true }, (error, stdout) => {
20
+ resolve(error ? [] : stdout.split(/[;\r\n]+/).map(entry => entry.trim()).filter(Boolean));
21
+ });
22
+ });
23
+ }
24
+ /** 同時發出的呼叫共用同一次執行;執行結束後的下一次呼叫會重新執行,剛裝好的工具仍找得到。 */
25
+ function sharedWhileRunning(run) {
26
+ let running;
27
+ return () => running ??= run().finally(() => { running = undefined; });
28
+ }
29
+ // 啟動時客戶端偵測與開發工具檢查會同時要 PATH;共用一個 PowerShell,避免一次開很多個拖慢啟動。
30
+ const readSharedSystemPath = sharedWhileRunning(readSystemPath);
31
+ /** 子程序要用的環境:Windows 上補進登錄檔裡最新的 PATH(同時的呼叫共用一次 PowerShell)。 */
32
+ async function envWithRegistryPath() {
33
+ return process.platform === "win32" ? withSystemPath(process.env, await readSharedSystemPath()) : process.env;
34
+ }
35
+ /**
36
+ * 安裝程式(例如 winget 裝 Node.js)只改登錄檔裡的 PATH;已經在執行的背景服務還留著啟動時的舊 PATH。
37
+ * 保留舊 PATH 的順序,把登錄檔裡多出來的資料夾補在後面,剛裝好的工具不必重新啟動 VansPod 就找得到。
38
+ */
39
+ function withSystemPath(env, systemPath) {
40
+ const key = Object.keys(env).find(name => name.toUpperCase() === "PATH") ?? "Path";
41
+ const lookup = new Map(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));
42
+ const expand = (entry) => entry.replace(/%([^%]+)%/g, (whole, name) => lookup.get(name.toUpperCase()) ?? whole);
43
+ const normalize = (entry) => entry.replace(/[\\/]+$/, "").toLowerCase();
44
+ const entries = (env[key] ?? "").split(";").filter(Boolean);
45
+ const seen = new Set(entries.map(normalize));
46
+ for (const entry of systemPath.map(expand)) {
47
+ if (!entry || seen.has(normalize(entry)))
48
+ continue;
49
+ seen.add(normalize(entry));
50
+ entries.push(entry);
51
+ }
52
+ return { ...env, [key]: entries.join(";") };
53
+ }
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.3.1";
4
+ exports.VERSION = "0.4.1";
@@ -7,11 +7,12 @@ const DOWNLOAD_ICON = `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" s
7
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
8
  exports.VERSION_UPDATE_STYLES = `
9
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; }
10
+ .bar .side-foot > button { align-self: center; }
11
+ .update-button { position: relative; display: grid; place-items: center; width: 2.75rem; height: 2.75rem; min-height: 2.75rem; flex: 0 0 auto; padding: 0; border-radius: 999px; border: 1px solid var(--line); background: transparent; color: var(--muted); cursor: pointer; }
11
12
  .update-button[hidden] { display: none; }
12
13
  .update-button:hover { color: var(--text); background: light-dark(rgba(13, 13, 13, 0.04), rgba(255, 255, 255, 0.06)); }
13
14
  .update-button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
14
- .update-button svg { width: 18px; height: 18px; }
15
+ .update-button svg { width: 1.25rem; height: 1.25rem; }
15
16
  .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
17
  .update-button.available { color: #2563eb; border-color: rgba(37, 99, 235, 0.45); background: rgba(37, 99, 235, 0.08); }
17
18
  .update-button.available .update-dot { display: block; }
@@ -0,0 +1,193 @@
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.DownloadHttpError = void 0;
7
+ exports.createWindowsEnvironment = createWindowsEnvironment;
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const classroomApp_1 = require("./classroomApp");
10
+ const environmentInstallLog_1 = require("./environmentInstallLog");
11
+ const instance_1 = require("./instance");
12
+ const officialDownloads_1 = require("./officialDownloads");
13
+ const officialInstaller_1 = require("./officialInstaller");
14
+ var officialInstaller_2 = require("./officialInstaller");
15
+ Object.defineProperty(exports, "DownloadHttpError", { enumerable: true, get: function () { return officialInstaller_2.DownloadHttpError; } });
16
+ const VERSION_CHECK = {
17
+ uv: { command: "uv", pattern: /^uv \d+\.\d+\.\d+/ },
18
+ git: { command: "git", pattern: /^git version \d+\.\d+/ },
19
+ node: { command: "node", pattern: /^v\d+\.\d+\.\d+$/ },
20
+ pwsh: { command: "pwsh", pattern: /^PowerShell 7\.\d+\.\d+/ },
21
+ // code --version 印出版本、commit 與架構三行;只看第一行。
22
+ vscode: { command: "code", pattern: /^\d+\.\d+\.\d+(?:[-+]\S+)?(?:\r?\n|$)/ },
23
+ };
24
+ const CHECK_TIMEOUT_MS = 15_000;
25
+ const NODE_LTS_REASON = "需要 Node.js LTS,且 npm 必須可正常執行";
26
+ /** 一次檢查:結束碼必須為 0,且完整輸出符合格式;版本文字掩蓋不了非 0 結束碼。 */
27
+ async function check(system, command, args, pattern) {
28
+ const result = await system.run(command, args, { timeoutMs: CHECK_TIMEOUT_MS });
29
+ const shown = [command, ...args].join(" ");
30
+ if (result.notFound)
31
+ return { ok: false, readiness: "missing", reason: `找不到 ${command}` };
32
+ if (result.timedOut) {
33
+ return { ok: false, readiness: "needsRepair", reason: `${shown} 檢查超過 ${CHECK_TIMEOUT_MS / 1000} 秒,建議修復此工具` };
34
+ }
35
+ if (result.exitCode !== 0)
36
+ return { ok: false, readiness: "needsRepair", reason: `${shown} 失敗(結束碼 ${result.exitCode ?? "未知"})` };
37
+ const output = result.output.trim();
38
+ if (!pattern.test(output))
39
+ return { ok: false, readiness: "needsRepair", reason: `${shown} 的輸出不是版本號` };
40
+ return { ok: true, output };
41
+ }
42
+ const WINGET_ID = {
43
+ git: "Git.Git",
44
+ node: "OpenJS.NodeJS.LTS",
45
+ pwsh: "Microsoft.PowerShell",
46
+ };
47
+ function isWingetTool(tool) {
48
+ return tool in WINGET_ID;
49
+ }
50
+ const WINGET_QUIET = ["--source", "winget", "--disable-interactivity", "-h", "--accept-package-agreements", "--accept-source-agreements"];
51
+ // 0x8A15002B:winget 回報已安裝、沒有可用的升級;有號與無號兩種寫法都可能出現。
52
+ const WINGET_ALREADY_INSTALLED = [-1978335189, 2316632107];
53
+ const WINGET_ACCEPTED = [0, officialInstaller_1.REBOOT_REQUIRED, ...WINGET_ALREADY_INSTALLED];
54
+ function installLaunch(tool) {
55
+ if (tool === "uv") {
56
+ return { command: "powershell.exe", args: ["-ExecutionPolicy", "ByPass", "-c", "irm https://astral.sh/uv/install.ps1 | iex"] };
57
+ }
58
+ return { command: "winget", args: ["install", "--id", WINGET_ID[tool], "-e", ...WINGET_QUIET] };
59
+ }
60
+ /** OS 的實際架構:32 位元行程看到的 PROCESSOR_ARCHITECTURE 是 x86,真正的架構在 PROCESSOR_ARCHITEW6432。 */
61
+ function windowsArchitecture(env) {
62
+ const value = (env.PROCESSOR_ARCHITEW6432 || env.PROCESSOR_ARCHITECTURE || "").toUpperCase();
63
+ if (value === "AMD64")
64
+ return "x64";
65
+ if (value === "ARM64")
66
+ return "arm64";
67
+ return value || "未知";
68
+ }
69
+ function readinessText(readiness) {
70
+ const detail = (text) => (text ? `:${text}` : "");
71
+ if (readiness.readiness === "ready")
72
+ return `已就緒${readiness.version ? `(${readiness.version})` : ""}`;
73
+ return `${readiness.readiness === "needsRepair" ? "需要修復" : "未安裝"}${detail(readiness.reason)}`;
74
+ }
75
+ function createWindowsEnvironment(system, options = {}) {
76
+ // 目前這次 Environment Install 的紀錄;startLog() 開始新的一次。
77
+ let currentLog;
78
+ return {
79
+ probe,
80
+ /** 開始一次 Environment Install 的紀錄,之後每個工具的安裝都寫進同一個資料夾。 */
81
+ async startLog() {
82
+ const now = options.now?.() ?? new Date();
83
+ const log = await (0, environmentInstallLog_1.startInstallLogFile)(options.managementDirectory ?? (0, instance_1.managementDirectory)(), now);
84
+ currentLog = log;
85
+ await log.append(`VansPod Environment Install ${now.toISOString()}\r\n\r\n`);
86
+ return {
87
+ folder: log.folder,
88
+ verified: (tool, readiness) => log.append(`驗證 ${classroomApp_1.ENVIRONMENT_LABEL[tool]}:${readinessText(readiness)}\r\n\r\n`),
89
+ finish: (summary) => log.append(`結果:${summary}\r\n`),
90
+ };
91
+ },
92
+ async openLogFolder(folder) {
93
+ await system.openFolder(folder);
94
+ },
95
+ /** 「開啟 VS Code」:有資料夾就以它開啟。 */
96
+ async openVsCode(folder) {
97
+ await system.start("code", folder ? [folder] : []);
98
+ },
99
+ /** 開發工具與 Project Folder 無關;程序在使用者家目錄執行(見 windowsEnvironmentSystem)。 */
100
+ async install(tool, signal, onProgress) {
101
+ if (tool === "vscode")
102
+ return installVsCode(signal, onProgress);
103
+ // 有 winget 時維持 winget,避免教室共用 IP 撞到 GitHub API 次數上限(ADR-0011)。
104
+ if (isWingetTool(tool) && !(await system.wingetAvailable()))
105
+ return installWithoutWinget(tool, signal, onProgress);
106
+ const { command, args } = installLaunch(tool);
107
+ onProgress?.({ stage: "installing" });
108
+ // 安裝不設逾時(ADR-0008):卡住時由學生 Abort Install。
109
+ const result = await system.run(command, args, { signal });
110
+ await currentLog?.append((0, officialInstaller_1.runEntry)(classroomApp_1.ENVIRONMENT_LABEL[tool], command, args, result));
111
+ if (result.aborted)
112
+ return (0, officialInstaller_1.abortedResult)(result.output);
113
+ if (result.notFound)
114
+ return { output: "安裝命令無法啟動。", exitCode: undefined, exitAccepted: false };
115
+ // 安裝程式結束後由 ClassroomApp 立刻驗證。
116
+ onProgress?.({ stage: "verifying" });
117
+ const exitAccepted = result.exitCode !== undefined && WINGET_ACCEPTED.includes(result.exitCode);
118
+ return {
119
+ output: result.output,
120
+ exitCode: result.exitCode,
121
+ exitAccepted,
122
+ ...(result.exitCode === officialInstaller_1.REBOOT_REQUIRED ? { rebootRequired: true } : {}),
123
+ };
124
+ },
125
+ };
126
+ async function probe(tool) {
127
+ const { command, pattern } = VERSION_CHECK[tool];
128
+ const result = await check(system, command, ["--version"], pattern);
129
+ if (!result.ok)
130
+ return { readiness: result.readiness, reason: result.reason };
131
+ const version = result.output.split(/\r?\n/)[0];
132
+ if (tool === "node") {
133
+ // 課程套件只保證 LTS;npm 壞掉等於 Node.js 不能用。
134
+ const lts = await check(system, "node", ["-p", "Boolean(process.release.lts)"], /^true$/);
135
+ if (!lts.ok)
136
+ return { readiness: "needsRepair", version, reason: NODE_LTS_REASON };
137
+ const npm = await check(system, "npm", ["--version"], /^\d+\.\d+\.\d+$/);
138
+ if (!npm.ok)
139
+ return { readiness: "needsRepair", version, reason: `${NODE_LTS_REASON}(${npm.reason})` };
140
+ }
141
+ return { readiness: "ready", version };
142
+ }
143
+ /** 直接下載官方安裝檔的共用設定:下載快取、紀錄、驗證通過才刪除安裝檔。 */
144
+ function officialContext(tool, signal, onProgress) {
145
+ return {
146
+ system,
147
+ cacheFolder: node_path_1.default.join(options.managementDirectory ?? (0, instance_1.managementDirectory)(), "Downloads"),
148
+ retryDelayMs: options.retryDelayMs ?? 2000,
149
+ signal,
150
+ onProgress,
151
+ log: async (text) => { await currentLog?.append(text); },
152
+ verify: () => probe(tool),
153
+ };
154
+ }
155
+ async function failed(tool, failure) {
156
+ await currentLog?.append(`== ${classroomApp_1.ENVIRONMENT_LABEL[tool]} ==\r\n${failure}\r\n\r\n`);
157
+ return (0, officialInstaller_1.failedResult)(failure);
158
+ }
159
+ /** 官方安裝檔只有 x64 與 arm64;回傳架構,無法判斷時回傳失敗原因。 */
160
+ function officialArchitecture(tool) {
161
+ const architecture = windowsArchitecture(options.env ?? process.env);
162
+ if (architecture === "x64" || architecture === "arm64")
163
+ return architecture;
164
+ return { failure: `無法判斷 Windows 架構(${architecture}),${classroomApp_1.ENVIRONMENT_LABEL[tool]} 只提供 x64 與 arm64 安裝檔` };
165
+ }
166
+ /** 安裝器自己的 log 併入本次安裝紀錄;沒有紀錄時放在下載快取旁。 */
167
+ function setupLogFile(tool, cacheFolder) {
168
+ return node_path_1.default.join(currentLog?.folder ?? cacheFolder, `${tool}-setup.log`);
169
+ }
170
+ async function installVsCode(signal, onProgress) {
171
+ const context = officialContext("vscode", signal, onProgress);
172
+ const architecture = officialArchitecture("vscode");
173
+ if (typeof architecture !== "string")
174
+ return failed("vscode", architecture.failure);
175
+ return (0, officialInstaller_1.installOfficialInstaller)((0, officialDownloads_1.vsCodeInstaller)(architecture, setupLogFile("vscode", context.cacheFolder)), context);
176
+ }
177
+ /** 沒有 winget:查官方最新穩定版,下載安裝檔、確認簽章後靜默安裝。 */
178
+ async function installWithoutWinget(tool, signal, onProgress) {
179
+ const context = officialContext(tool, signal, onProgress);
180
+ await context.log(`找不到 winget,${classroomApp_1.ENVIRONMENT_LABEL[tool]} 改從官方網站下載安裝檔\r\n`);
181
+ const architecture = officialArchitecture(tool);
182
+ if (typeof architecture !== "string")
183
+ return failed(tool, architecture.failure);
184
+ const lookup = await (0, officialDownloads_1.lookupDownload)(system, tool, architecture, signal);
185
+ if ("aborted" in lookup) {
186
+ await context.log(`${classroomApp_1.ENVIRONMENT_LABEL[tool]}:查詢最新版本時已中止\r\n\r\n`);
187
+ return (0, officialInstaller_1.abortedResult)();
188
+ }
189
+ if ("failure" in lookup)
190
+ return failed(tool, lookup.failure);
191
+ return (0, officialInstaller_1.installOfficialInstaller)((0, officialDownloads_1.wingetToolInstaller)(tool, lookup.download, setupLogFile(tool, context.cacheFolder)), context);
192
+ }
193
+ }
@@ -0,0 +1,201 @@
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.windowsEnvironmentSystem = void 0;
7
+ exports.createWindowsEnvironmentSystem = createWindowsEnvironmentSystem;
8
+ const node_child_process_1 = require("node:child_process");
9
+ const promises_1 = __importDefault(require("node:fs/promises"));
10
+ const node_os_1 = __importDefault(require("node:os"));
11
+ const node_path_1 = __importDefault(require("node:path"));
12
+ const commandRunner_1 = require("./commandRunner");
13
+ const officialInstaller_1 = require("./officialInstaller");
14
+ const systemPath_1 = require("./systemPath");
15
+ const version_1 = require("./version");
16
+ function envValue(env, name) {
17
+ const key = Object.keys(env).find((candidate) => candidate.toUpperCase() === name);
18
+ return (key && env[key]) || "";
19
+ }
20
+ async function isFile(file) {
21
+ try {
22
+ return (await promises_1.default.stat(file)).isFile();
23
+ }
24
+ catch { /* 可能是無法 stat 的應用程式執行別名 */ }
25
+ // winget 是 WindowsApps 裡的應用程式執行別名:stat 會得到 EACCES,但 lstat 看得到、也能直接執行。
26
+ try {
27
+ return (await promises_1.default.lstat(file)).isSymbolicLink();
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ /** 像 cmd.exe 一樣在 PATH × PATHEXT 找指令;找不到回傳 undefined。 */
34
+ async function resolveCommand(command, env) {
35
+ if (node_path_1.default.isAbsolute(command))
36
+ return (await isFile(command)) ? command : undefined;
37
+ const extensions = (envValue(env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
38
+ const candidates = node_path_1.default.extname(command) ? [command] : extensions.map((extension) => command + extension.toLowerCase());
39
+ for (const folder of envValue(env, "PATH").split(";").filter(Boolean)) {
40
+ for (const candidate of candidates) {
41
+ const file = node_path_1.default.join(folder.replace(/^"|"$/g, ""), candidate);
42
+ if (await isFile(file))
43
+ return file;
44
+ }
45
+ }
46
+ return undefined;
47
+ }
48
+ function cmdQuote(value) {
49
+ return /[\s"&|<>^()%!,;=]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
50
+ }
51
+ /** .cmd/.bat 只能交給 cmd.exe;/v:off 讓路徑裡的驚嘆號保持原樣。 */
52
+ function launch(file, args) {
53
+ if (/\.(cmd|bat)$/i.test(file)) {
54
+ return { command: "cmd.exe", args: ["/d", "/v:off", "/s", "/c", `"${[`"${file}"`, ...args.map(cmdQuote)].join(" ")}"`] };
55
+ }
56
+ return { command: file, args };
57
+ }
58
+ /** 等 promise,但 signal 先中止時立即回傳 undefined。 */
59
+ function unlessAborted(promise, signal) {
60
+ if (signal.aborted)
61
+ return Promise.resolve(undefined);
62
+ return new Promise((resolve, reject) => {
63
+ const done = () => resolve(undefined);
64
+ signal.addEventListener("abort", done, { once: true });
65
+ promise.then((value) => { signal.removeEventListener("abort", done); resolve(value); }, (error) => { signal.removeEventListener("abort", done); reject(error); });
66
+ });
67
+ }
68
+ async function run(environment, command, args, options = {}) {
69
+ const controller = new AbortController();
70
+ const stop = () => controller.abort();
71
+ if (options.signal?.aborted)
72
+ stop();
73
+ else
74
+ options.signal?.addEventListener("abort", stop, { once: true });
75
+ let timedOut = false;
76
+ // 逾時從呼叫就開始算:讀登錄檔 PATH 與找指令也算在檢查的 15 秒內。
77
+ const timer = options.timeoutMs === undefined ? undefined : setTimeout(() => { timedOut = true; stop(); }, options.timeoutMs);
78
+ try {
79
+ const resolved = await unlessAborted(environment().then(async (env) => ({ env, file: await resolveCommand(command, env) })), controller.signal);
80
+ if (!resolved)
81
+ return { exitCode: undefined, output: "", notFound: false, timedOut, aborted: !timedOut };
82
+ const { env, file } = resolved;
83
+ if (!file)
84
+ return { exitCode: undefined, output: "", notFound: true, timedOut: false, aborted: false };
85
+ const target = launch(file, args);
86
+ // 開發工具與 Project Folder 無關:一律以使用者家目錄為工作目錄。
87
+ const result = await (0, commandRunner_1.collectOutput)(target.command, target.args, node_os_1.default.homedir(), options.onOutput, controller.signal, env);
88
+ return {
89
+ exitCode: result.exitCode,
90
+ output: result.output,
91
+ notFound: result.spawnError,
92
+ timedOut,
93
+ aborted: result.aborted && !timedOut,
94
+ };
95
+ }
96
+ finally {
97
+ clearTimeout(timer);
98
+ options.signal?.removeEventListener("abort", stop);
99
+ }
100
+ }
101
+ // GitHub API 拒絕沒有 User-Agent 的請求;官方下載也一併帶上。
102
+ const USER_AGENT = `VansPod/${version_1.VERSION}`;
103
+ async function download(url, destination, options = {}) {
104
+ const file = await promises_1.default.open(destination, "w");
105
+ try {
106
+ const response = await fetch(url, { signal: options.signal, headers: { "User-Agent": USER_AGENT } });
107
+ if (!response.ok || !response.body)
108
+ throw new officialInstaller_1.DownloadHttpError(response.status);
109
+ const length = Number(response.headers.get("content-length"));
110
+ const total = Number.isFinite(length) && length > 0 ? length : undefined;
111
+ let received = 0;
112
+ for await (const chunk of response.body) {
113
+ await file.write(chunk);
114
+ received += chunk.byteLength;
115
+ options.onProgress?.(received, total);
116
+ }
117
+ if (received === 0 || (total !== undefined && received !== total))
118
+ throw new Error("下載未完成");
119
+ await file.close();
120
+ }
121
+ catch (error) {
122
+ await file.close().catch(() => { });
123
+ await promises_1.default.rm(destination, { force: true });
124
+ throw error;
125
+ }
126
+ }
127
+ /** 查詢官方最新版本資訊;30 秒沒有回應視為失敗。非 200 時不解析內容。 */
128
+ async function fetchJson(url, options = {}) {
129
+ const timeout = AbortSignal.timeout(30_000);
130
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
131
+ const response = await fetch(url, { signal, headers: { "User-Agent": USER_AGENT, Accept: "application/json" } });
132
+ if (response.status !== 200) {
133
+ await response.body?.cancel().catch(() => { });
134
+ return { status: response.status, body: undefined };
135
+ }
136
+ return { status: response.status, body: await response.json() };
137
+ }
138
+ function signature(file) {
139
+ const script = "[Console]::OutputEncoding = [Text.Encoding]::UTF8; $s = Get-AuthenticodeSignature -LiteralPath $env:VANSPOD_SIGNED_FILE; @{ status = [string]$s.Status; subject = [string]$s.SignerCertificate.Subject } | ConvertTo-Json -Compress";
140
+ const powershell = node_path_1.default.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
141
+ // 路徑走環境變數,不必處理引號裡的中文、空白、驚嘆號、單引號。
142
+ // 從 PowerShell 7 啟動時繼承的 PSModulePath 會讓 Windows PowerShell 載不到自己的 Security 模組。
143
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== "PSMODULEPATH"));
144
+ env.VANSPOD_SIGNED_FILE = file;
145
+ return new Promise((resolve) => {
146
+ (0, node_child_process_1.execFile)(powershell, ["-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", env, timeout: 30_000, windowsHide: true }, (error, stdout) => {
147
+ try {
148
+ if (error)
149
+ throw error;
150
+ const parsed = JSON.parse(stdout);
151
+ resolve({ status: String(parsed.status ?? ""), subject: String(parsed.subject ?? "") });
152
+ }
153
+ catch {
154
+ resolve({ status: "UnknownError", subject: "" });
155
+ }
156
+ });
157
+ });
158
+ }
159
+ /** 真正的 Windows 系統動作。 */
160
+ function createWindowsEnvironmentSystem(options = {}) {
161
+ const environment = options.environment ?? systemPath_1.envWithRegistryPath;
162
+ return {
163
+ run: (command, args, runOptions) => run(environment, command, args, runOptions),
164
+ download,
165
+ signature,
166
+ fetchJson,
167
+ async wingetAvailable() {
168
+ return (await resolveCommand("winget", await environment())) !== undefined;
169
+ },
170
+ async openFolder(folder) {
171
+ if (process.env.CLASSROOM_APP_HEADLESS === "1")
172
+ return;
173
+ // explorer.exe 直接收路徑參數,中文、空白、驚嘆號都不必經過 cmd.exe 的引號規則。
174
+ const explorer = node_path_1.default.join(process.env.SystemRoot ?? "C:\\Windows", "explorer.exe");
175
+ const child = (0, node_child_process_1.spawn)(explorer, [folder], { detached: true, stdio: "ignore", windowsHide: false });
176
+ child.on("error", () => { });
177
+ child.unref();
178
+ },
179
+ async start(command, args) {
180
+ if (process.env.CLASSROOM_APP_HEADLESS === "1")
181
+ return;
182
+ const env = await environment();
183
+ const file = await resolveCommand(command, env);
184
+ if (!file)
185
+ throw new Error(`找不到 ${command}`);
186
+ const target = launch(file, args);
187
+ // code.cmd 經由 cmd.exe 轉手:隱藏 cmd 視窗,VS Code 自己的視窗照常出現。
188
+ const child = (0, node_child_process_1.spawn)(target.command, target.args, {
189
+ cwd: node_os_1.default.homedir(),
190
+ env,
191
+ detached: true,
192
+ stdio: "ignore",
193
+ windowsHide: true,
194
+ windowsVerbatimArguments: target.command === "cmd.exe",
195
+ });
196
+ child.on("error", () => { });
197
+ child.unref();
198
+ },
199
+ };
200
+ }
201
+ exports.windowsEnvironmentSystem = createWindowsEnvironmentSystem();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vanspod",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "bin": { "vanspod": "bin/vanspod.cjs" },
5
5
  "engines": { "node": ">=24" },
6
6
  "os": ["win32"],