vanspod 0.3.2 → 0.4.3

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,158 @@
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 = exports.REBOOT_REQUIRED = void 0;
7
+ exports.abortedResult = abortedResult;
8
+ exports.failedResult = failedResult;
9
+ exports.runEntry = runEntry;
10
+ exports.installOfficialInstaller = installOfficialInstaller;
11
+ const promises_1 = __importDefault(require("node:fs/promises"));
12
+ const node_path_1 = __importDefault(require("node:path"));
13
+ /** 安裝程式的結束碼:0 成功、3010 需要重新開機(Inno Setup 與 msiexec 相同);成敗仍以驗證為準。 */
14
+ exports.REBOOT_REQUIRED = 3010;
15
+ const ACCEPTED_EXIT = [0, exports.REBOOT_REQUIRED];
16
+ /** Abort Install 停下的安裝:之後由 ClassroomApp 重新檢查全部工具。 */
17
+ function abortedResult(output = "") {
18
+ return { output, exitCode: undefined, aborted: true, exitAccepted: false };
19
+ }
20
+ /** 安裝程式沒有執行(例如下載失敗、簽章不符):failure 是給學生看的原因。 */
21
+ function failedResult(failure) {
22
+ return { output: failure, exitCode: undefined, exitAccepted: false, failure };
23
+ }
24
+ function runEntry(label, command, args, result) {
25
+ const quote = (value) => (/[\s"]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value);
26
+ const outcome = result.aborted ? "已中止" : result.notFound ? "無法啟動" : `${result.exitCode ?? "未知"}`;
27
+ return [`== ${label} ==`, `指令:${[command, ...args].map(quote).join(" ")}`, `結束碼:${outcome}`, "輸出:", result.output.trimEnd(), ""].join("\r\n");
28
+ }
29
+ /** 下載最多嘗試 3 次;中止不重試。 */
30
+ const DOWNLOAD_ATTEMPTS = 3;
31
+ async function exists(file) {
32
+ return promises_1.default.stat(file).then((stat) => stat.isFile(), () => false);
33
+ }
34
+ /** Authenticode 必須為 Valid 且簽署者符合;通過回傳 undefined,否則回傳原因。 */
35
+ async function checkSignature(system, file, signer) {
36
+ const { status, subject } = await system.signature(file).catch(() => ({ status: "UnknownError", subject: "" }));
37
+ if (status === "Valid" && signer.test(subject))
38
+ return undefined;
39
+ return `安裝檔簽章驗證失敗(${status || "未知"}${subject ? `,簽署者 ${subject}` : ""}),為了安全不執行`;
40
+ }
41
+ function wait(ms, signal) {
42
+ return new Promise((resolve) => {
43
+ if (signal?.aborted)
44
+ return resolve();
45
+ const done = () => { clearTimeout(timer); signal?.removeEventListener("abort", done); resolve(); };
46
+ const timer = setTimeout(done, ms);
47
+ signal?.addEventListener("abort", done, { once: true });
48
+ });
49
+ }
50
+ /** 下載時伺服器回覆非 2xx:帶著 HTTP 狀態,讓重試只針對暫時性的失敗。 */
51
+ class DownloadHttpError extends Error {
52
+ status;
53
+ constructor(status) {
54
+ super(`下載失敗(HTTP ${status})`);
55
+ this.status = status;
56
+ }
57
+ }
58
+ exports.DownloadHttpError = DownloadHttpError;
59
+ /** 值得重試的下載失敗:連線錯誤、下載不完整、5xx、408、429;其他 4xx(例如 404)重試也不會好。 */
60
+ function isTemporary(error) {
61
+ if (!(error instanceof DownloadHttpError))
62
+ return true;
63
+ return error.status >= 500 || error.status === 408 || error.status === 429;
64
+ }
65
+ /** 串流下載並回報進度;暫時失敗等一下再試。成功或中止回傳 undefined,失敗回傳最後的錯誤訊息。 */
66
+ async function downloadWithRetry(installer, file, context) {
67
+ const { system, signal, onProgress } = context;
68
+ let lastError = "";
69
+ for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt += 1) {
70
+ if (signal?.aborted)
71
+ return undefined;
72
+ try {
73
+ await system.download(installer.url, file, {
74
+ signal,
75
+ onProgress: (downloaded, total) => onProgress?.({ stage: "downloading", downloaded, ...(total === undefined ? {} : { total }) }),
76
+ });
77
+ return undefined;
78
+ }
79
+ catch (error) {
80
+ // 系統動作已刪除下載一半的檔案;這裡再確認一次。
81
+ await promises_1.default.rm(file, { force: true }).catch(() => { });
82
+ if (signal?.aborted)
83
+ return undefined;
84
+ lastError = error instanceof Error ? error.message : String(error);
85
+ await context.log(`第 ${attempt} 次下載失敗:${lastError}\r\n`);
86
+ if (!isTemporary(error))
87
+ return { error: lastError, attempts: attempt };
88
+ if (attempt < DOWNLOAD_ATTEMPTS)
89
+ await wait(context.retryDelayMs, signal);
90
+ }
91
+ }
92
+ return { error: lastError, attempts: DOWNLOAD_ATTEMPTS };
93
+ }
94
+ /**
95
+ * 直接下載官方安裝檔並靜默安裝(ADR-0011):串流下載到下載快取並回報進度,執行前確認簽章,
96
+ * 結束後驗證工具,驗證通過才刪除安裝檔。
97
+ */
98
+ async function installOfficialInstaller(installer, context) {
99
+ const { system, signal, onProgress } = context;
100
+ const file = node_path_1.default.join(context.cacheFolder, installer.fileName);
101
+ const remove = () => promises_1.default.rm(file, { force: true }).catch(() => { });
102
+ const aborted = async (output = "") => {
103
+ // 中止時立即刪除安裝檔,下次重新下載(ADR-0008 補充)。
104
+ await remove();
105
+ await context.log(`${installer.label}:已中止,已刪除安裝檔\r\n\r\n`);
106
+ return abortedResult(output);
107
+ };
108
+ const failed = async (failure) => {
109
+ await context.log(`${installer.label}:${failure}\r\n\r\n`);
110
+ return failedResult(failure);
111
+ };
112
+ await promises_1.default.mkdir(context.cacheFolder, { recursive: true });
113
+ // 上次驗證沒過而保留的安裝檔:簽章仍然正確才沿用,否則重新下載。
114
+ let reused = false;
115
+ if (await exists(file)) {
116
+ reused = (await checkSignature(system, file, installer.signer)) === undefined;
117
+ await context.log(reused ? `沿用下載快取裡的安裝檔:${file}\r\n` : `下載快取裡的安裝檔簽章不符,重新下載\r\n`);
118
+ if (!reused)
119
+ await remove();
120
+ }
121
+ if (!reused) {
122
+ await context.log(`== ${installer.label} 下載 ==\r\n網址:${installer.url}\r\n存放:${file}\r\n`);
123
+ const failure = await downloadWithRetry(installer, file, context);
124
+ if (signal?.aborted)
125
+ return aborted();
126
+ if (failure !== undefined)
127
+ return failed(`下載失敗:${failure.error}(已嘗試 ${failure.attempts} 次)`);
128
+ // 執行前確認簽章:不是預期發行者簽署的檔案一律不執行,也不留下。
129
+ const rejected = await checkSignature(system, file, installer.signer);
130
+ if (rejected !== undefined) {
131
+ await remove();
132
+ return failed(rejected);
133
+ }
134
+ }
135
+ if (signal?.aborted)
136
+ return aborted();
137
+ const { command, args } = installer.launch(file);
138
+ onProgress?.({ stage: "installing" });
139
+ // 安裝不設逾時(ADR-0008):卡住時由學生 Abort Install,結束整個程序樹。
140
+ const result = await system.run(command, args, { signal });
141
+ await context.log(runEntry(installer.label, command, args, result));
142
+ if (result.aborted)
143
+ return aborted(result.output);
144
+ if (result.notFound)
145
+ return failed("安裝檔無法啟動");
146
+ onProgress?.({ stage: "verifying" });
147
+ // 驗證通過才刪除安裝檔;沒過就保留,重試時重新驗證簽章後沿用。
148
+ const verified = await context.verify().catch(() => ({ readiness: "missing" }));
149
+ if (verified.readiness === "ready")
150
+ await remove();
151
+ return {
152
+ output: result.output,
153
+ exitCode: result.exitCode,
154
+ exitAccepted: result.exitCode !== undefined && ACCEPTED_EXIT.includes(result.exitCode),
155
+ ...(result.exitCode === exports.REBOOT_REQUIRED ? { rebootRequired: true } : {}),
156
+ verified,
157
+ };
158
+ }
package/dist/page.js CHANGED
@@ -1,12 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.modelStatus = modelStatus;
4
+ exports.environmentStageText = environmentStageText;
5
+ exports.environmentStatus = environmentStatus;
4
6
  exports.classroomBlocks = classroomBlocks;
5
7
  exports.renderPage = renderPage;
6
8
  exports.renderInspectorPage = renderInspectorPage;
7
9
  const version_1 = require("./version");
8
10
  const appearance_1 = require("./appearance");
9
11
  const installProgress_1 = require("./installProgress");
12
+ const environmentProgress_1 = require("./environmentProgress");
10
13
  const settingsActions_1 = require("./settingsActions");
11
14
  const modelStatus_1 = require("./modelStatus");
12
15
  const classroomUpdate_1 = require("./classroomUpdate");
@@ -156,27 +159,85 @@ function adapterForms(view) {
156
159
  return forms +
157
160
  (view.adapterNotice ? `<p class="hint">${escapeHtml(view.adapterNotice)}</p>` : "");
158
161
  }
162
+ /** Environment Tool Readiness 與按下「確認安裝」後對該工具做的事。 */
163
+ const READINESS_MARK = {
164
+ ready: "<em>已就緒</em>",
165
+ needsRepair: `<em class="needs-repair">需要修復</em><span class="tool-action">修復</span>`,
166
+ missing: `<em>未安裝</em><span class="tool-action">安裝</span>`,
167
+ checking: `<em class="checking">檢查中</em>`,
168
+ };
169
+ /** 第一次檢查還沒有結果的工具不算缺,整張卡顯示「檢查中」。 */
170
+ function environmentChecking(view) {
171
+ return view.tools.some((tool) => tool.readiness === "checking");
172
+ }
173
+ const STAGE_TEXT = {
174
+ waiting: "等待中",
175
+ preparing: "準備中",
176
+ downloading: "下載中",
177
+ installing: "安裝中",
178
+ verifying: "驗證中",
179
+ done: "完成",
180
+ failed: "失敗",
181
+ };
182
+ function megabytes(bytes) {
183
+ return (bytes / (1024 * 1024)).toFixed(1);
184
+ }
185
+ /** 一個工具在 Environment Install 中的階段文字;下載中附已下載量,知道總量時再附總量與百分比。 */
186
+ function environmentStageText(progress) {
187
+ const text = STAGE_TEXT[progress.stage];
188
+ if (progress.stage !== "downloading" || progress.downloaded === undefined)
189
+ return text;
190
+ if (!progress.total)
191
+ return `${text} ${megabytes(progress.downloaded)} MB`;
192
+ const percent = Math.min(100, Math.floor((progress.downloaded / progress.total) * 100));
193
+ return `${text} ${megabytes(progress.downloaded)} / ${megabytes(progress.total)} MB(${percent}%)`;
194
+ }
195
+ /** 背景安裝或第一次檢查還沒結束時,頁面要輪詢,結束後重新整理顯示結果。 */
196
+ function environmentPolling(view) {
197
+ return view.environmentInstalling || environmentChecking(view);
198
+ }
199
+ /** GET /environment-status:背景 Environment Install 或第一次檢查是否還在跑,以及這次安裝裡每個工具的階段文字。 */
200
+ function environmentStatus(view) {
201
+ return {
202
+ running: environmentPolling(view),
203
+ tools: view.tools.flatMap((tool) => (tool.progress ? [{ id: tool.id, stage: environmentStageText(tool.progress) }] : [])),
204
+ };
205
+ }
159
206
  function environmentInner(view) {
160
207
  const off = locked(view);
161
- const confirmOff = view.installAvailable && !view.commandRunning ? "" : " disabled";
208
+ // 開發工具與 Project Folder 無關:沒選資料夾也能安裝。
209
+ const confirmOff = view.commandRunning ? " disabled" : "";
162
210
  const tools = view.tools
163
211
  .map((tool) => {
164
212
  const checked = tool.selected ? " checked" : "";
165
- const mark = tool.installed ? "已安裝" : "未安裝";
166
- return `<label class="tool"><input type="checkbox" name="tool" value="${escapeHtml(tool.id)}"${checked}${off}> ${environmentIcons_1.environmentIcons[tool.id]}<span>${escapeHtml(tool.label)}</span> <em>${mark}</em></label>`;
213
+ const title = tool.reason ? ` title="${escapeHtml(tool.reason)}"` : "";
214
+ // 安裝中的工具顯示階段;頁面輪詢 /environment-status 更新這段文字。
215
+ const mark = view.environmentInstalling && tool.progress
216
+ ? `<span class="tool-stage" data-environment-stage="${escapeHtml(tool.id)}">${escapeHtml(environmentStageText(tool.progress))}</span>`
217
+ : READINESS_MARK[tool.readiness];
218
+ return `<label class="tool"><input type="checkbox" name="tool" value="${escapeHtml(tool.id)}"${checked}${off}> ${environmentIcons_1.environmentIcons[tool.id]}<span${title}>${escapeHtml(tool.label)}</span> ${mark}</label>`;
167
219
  })
168
220
  .join("");
221
+ const polling = environmentPolling(view) ? " data-environment-progress" : "";
169
222
  const note = view.environmentNotice
170
223
  ? `<p class="hint">${escapeHtml(view.environmentNotice)}</p>`
171
224
  : "";
225
+ // 紀錄資料夾的路徑不放進頁面;伺服器開啟 ClassroomApp 記得的最近一次。
226
+ const openLog = view.environmentLogFolder && !view.commandRunning
227
+ ? `<form method="post" action="/environment-log"><button type="submit" class="quiet">開啟紀錄資料夾</button></form>`
228
+ : "";
229
+ // 有 Project Folder 時伺服器以該資料夾開啟 VS Code。
230
+ const openVsCode = view.tools.some((tool) => tool.id === "vscode" && tool.readiness === "ready")
231
+ ? `<form method="post" action="/open-vscode"><button type="submit" class="quiet">開啟 VS Code</button></form>`
232
+ : "";
172
233
  return `<form method="post" action="/environment-check">
173
234
  <button type="submit" class="quiet"${off}>重新檢查</button>
174
235
  </form>
175
- <form class="stack" method="post" action="/environment">
236
+ <form class="stack" method="post" action="/environment"${polling}>
176
237
  <div class="tools">${tools}</div>
177
238
  <button type="submit" class="go"${confirmOff}${view.commandRunning ? " hidden" : ""}>確認安裝</button>
178
239
  </form>
179
- ${note}${abortInstallForm(view)}`;
240
+ ${note}${openVsCode}${openLog}${abortInstallForm(view)}`;
180
241
  }
181
242
  /** Abort Install 入口;僅在安裝執行中顯示,送出前由 installProgressScript 確認。 */
182
243
  function abortInstallForm(view) {
@@ -850,9 +911,14 @@ function organizeSettings(html, view) {
850
911
  actions += abort;
851
912
  return "";
852
913
  });
853
- const missing = view.tools.filter((tool) => !tool.installed).length;
854
- const summary = !view.tools.length ? "尚未檢查工具" : missing ? `尚缺 ${missing} 項工具` : "所有工具已安裝";
855
- body = body.replace(/<div class="tools">([\s\S]*?)<\/div>/, `<p class="environment-summary">${summary}</p><details class="environment-tools"><summary>查看與選擇工具</summary><div class="tools">$1</div></details>`);
914
+ const missing = view.tools.filter((tool) => tool.readiness !== "ready").length;
915
+ const summary = !view.tools.length ? "尚未檢查工具"
916
+ : view.environmentInstalling ? "正在安裝工具…"
917
+ : environmentChecking(view) ? "正在檢查工具…"
918
+ : missing ? `尚缺 ${missing} 項工具` : "所有工具已就緒";
919
+ // 安裝中展開工具清單,學生直接看到每個工具的階段。
920
+ const open = view.environmentInstalling ? " open" : "";
921
+ body = body.replace(/<div class="tools">([\s\S]*?)<\/div>/, `<p class="environment-summary">${summary}</p><details class="environment-tools"${open}><summary>查看與選擇工具</summary><div class="tools">$1</div></details>`);
856
922
  }
857
923
  cards.push(`<section class="tile settings-card${title === "環境" ? " environment-card" : ""}" data-setting="${title}">${head}<div class="settings-content">${body}</div>${reminder}<div class="settings-actions">${actions}</div></section>`);
858
924
  return "";
@@ -876,10 +942,11 @@ function renderPage(view) {
876
942
  html = html.replace(/<p class="mode-line">[\s\S]*?<\/p>/, "");
877
943
  html = html.replaceAll(">Classroom</button>", ">課堂</button>");
878
944
  html = html.replaceAll(">Native</button>", ">個人</button>");
879
- const envReady = view.tools.length > 0 && view.tools.every((tool) => tool.installed);
945
+ const envReady = view.tools.length > 0 && view.tools.every((tool) => tool.readiness === "ready");
880
946
  const envTag = envReady
881
947
  ? `<span class="badge">已就緒</span>`
882
- : `<span class="badge off">未完成</span>`;
948
+ : environmentChecking(view) ? `<span class="badge off">檢查中</span>`
949
+ : `<span class="badge off">未完成</span>`;
883
950
  html = html.replace(`<section class="tile"><h2>環境</h2>`, `<section class="tile"><div class="tile-head"><h2>環境</h2>${envTag}</div>`);
884
951
  html = html.replaceAll(`<em>未安裝</em>`, `<em class="missing">未安裝</em>`);
885
952
  if (!view.tools.some((tool) => tool.selected)) {
@@ -932,6 +999,8 @@ function renderPage(view) {
932
999
  .connection-separator { opacity: 0.5; }
933
1000
  .tool em { color: var(--text); }
934
1001
  .tool em.missing { color: var(--muted); }
1002
+ .tool em.needs-repair { color: light-dark(#9a4a08, #fbbf24); }
1003
+ .tool-action { flex-shrink: 0; padding: 1px 8px; border: 1px solid light-dark(#dfe3e8, #404044); border-radius: 999px; color: var(--muted); font-size: 12px; }
935
1004
  .install-card { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 12px; width: 100%; padding: 12px; border: 1px solid light-dark(#dfe3e8, #404044); border-radius: 12px; background: light-dark(#f8fafc, #252528); }
936
1005
  .install-card.installed { border-color: light-dark(#6ee7b7, #1f5a45); }
937
1006
  .install-number { flex-shrink: 0; display: grid; place-items: center; width: 32px; height: 32px; border-radius: 8px; background: light-dark(#0d0d0d, #ececec); color: light-dark(#ffffff, #0d0d0d); font: 700 16px Consolas, "Cascadia Mono", monospace; }
@@ -1027,6 +1096,7 @@ function renderPage(view) {
1027
1096
  .environment-summary { font-weight: 600; }
1028
1097
  .environment-tools > summary { cursor: pointer; color: var(--muted); font-size: 13px; }
1029
1098
  .environment-tools .tools { margin-top: 12px; }
1099
+ .tool-stage { color: var(--muted); font-size: 13px; }
1030
1100
  @media (max-width: 40rem) { .settings-grid { grid-template-columns: 1fr; } }
1031
1101
  .key-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
1032
1102
  .key-row p { color: var(--muted); font-size: 13px; }
@@ -1044,7 +1114,7 @@ function renderPage(view) {
1044
1114
  main button.connection-clear:hover:not(:disabled) { color: light-dark(#b91c1c, #f87171); }
1045
1115
  ${classroomUpdate_1.classroomUpdateStyles}
1046
1116
  </style>
1047
- <script>${drawerScript()}${installProgress_1.installProgressScript}${snippetCopyScript()}${courseSectionScript()}${connectionMascot_1.connectionMascotScript}${classroomUpdate_1.classroomUpdateScript}${settingsActions_1.settingsActionsScript}${modelStatus_1.modelStatusScript}
1117
+ <script>${drawerScript()}${installProgress_1.installProgressScript}${environmentProgress_1.environmentProgressScript}${snippetCopyScript()}${courseSectionScript()}${connectionMascot_1.connectionMascotScript}${classroomUpdate_1.classroomUpdateScript}${settingsActions_1.settingsActionsScript}${modelStatus_1.modelStatusScript}
1048
1118
  </script>`;
1049
1119
  return html.replace("</body>", `${extra}</body>`);
1050
1120
  }
@@ -45,7 +45,7 @@ function stateText(view) {
45
45
  snippets: view.catalog?.snippets?.length ?? 0,
46
46
  tools: view.tools.map((tool) => ({
47
47
  id: tool.id,
48
- installed: tool.installed,
48
+ readiness: tool.readiness,
49
49
  selected: tool.selected,
50
50
  })),
51
51
  mustRestart: view.mustRestart ?? [],
package/dist/start.js CHANGED
@@ -18,6 +18,8 @@ const promptCapture_1 = require("./promptCapture");
18
18
  const clipboard_1 = require("./clipboard");
19
19
  const folderPicker_1 = require("./folderPicker");
20
20
  const commandRunner_1 = require("./commandRunner");
21
+ const windowsEnvironment_1 = require("./windowsEnvironment");
22
+ const windowsEnvironmentSystem_1 = require("./windowsEnvironmentSystem");
21
23
  const exitGuard_1 = require("./exitGuard");
22
24
  const pagePrototype_1 = require("./pagePrototype");
23
25
  const routeFiles_1 = require("./routeFiles");
@@ -177,19 +179,26 @@ function isEnvironmentTool(value) {
177
179
  return classroomApp_1.ENVIRONMENT_TOOLS.includes(value);
178
180
  }
179
181
  const MAC_PWSH_PAGE = "https://learn.microsoft.com/powershell/scripting/install/installing-powershell-on-macos";
180
- function probeEnvironment(tool) {
181
- return (0, commandRunner_1.collectOutput)(tool, ["--version"]).then((result) => {
182
+ // VS Code 的直接下載安裝只做 Windows;macOS 開啟官方下載頁,由學生自己安裝。
183
+ const MAC_VSCODE_PAGE = "https://code.visualstudio.com/download";
184
+ /** macOS 維持原本的偵測:找得到且有輸出版本就算已就緒(ADR-0008:第一版只完整支援 Windows)。 */
185
+ function probeMacEnvironment(tool) {
186
+ return (0, commandRunner_1.collectOutput)(tool === "vscode" ? "code" : tool, ["--version"]).then((result) => {
182
187
  if (result.spawnError) {
183
- return { installed: false };
188
+ return { readiness: "missing" };
184
189
  }
185
- return { installed: result.exitCode === 0 || /\d/.test(result.output) };
190
+ return { readiness: result.exitCode === 0 || /\d/.test(result.output) ? "ready" : "missing" };
186
191
  });
187
192
  }
188
- function installEnvironment(tool, cwd, signal) {
189
- const launch = process.platform === "darwin" && tool === "pwsh"
193
+ /** 開發工具與 Project Folder 無關,安裝一律在使用者家目錄執行。 */
194
+ function installMacEnvironment(tool, signal, onProgress) {
195
+ onProgress?.({ stage: "installing" });
196
+ const launch = tool === "pwsh"
190
197
  ? { command: "open", args: [MAC_PWSH_PAGE] }
191
- : (0, commandRunner_1.shellLaunch)(environmentInstallCommand(tool));
192
- return (0, commandRunner_1.collectOutput)(launch.command, launch.args, cwd, undefined, signal).then((result) => {
198
+ : tool === "vscode"
199
+ ? { command: "open", args: [MAC_VSCODE_PAGE] }
200
+ : (0, commandRunner_1.shellLaunch)(macEnvironmentInstallCommand(tool));
201
+ return (0, commandRunner_1.collectOutput)(launch.command, launch.args, node_os_1.default.homedir(), undefined, signal).then((result) => {
193
202
  if (result.aborted)
194
203
  return { exitCode: result.exitCode, output: result.output, aborted: true };
195
204
  if (result.spawnError) {
@@ -198,30 +207,17 @@ function installEnvironment(tool, cwd, signal) {
198
207
  return { exitCode: result.exitCode, output: result.output };
199
208
  });
200
209
  }
201
- function environmentInstallCommand(tool) {
202
- if (process.platform === "darwin") {
203
- if (tool === "uv") {
204
- return "curl -LsSf https://astral.sh/uv/install.sh | sh";
205
- }
206
- if (tool === "git") {
207
- return "xcode-select --install";
208
- }
209
- if (tool === "node") {
210
- return 'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash && . "$HOME/.nvm/nvm.sh" && nvm install --lts && nvm alias default \'lts/*\'';
211
- }
212
- return "";
213
- }
214
- const quiet = "--source winget --disable-interactivity -h --accept-package-agreements --accept-source-agreements";
210
+ function macEnvironmentInstallCommand(tool) {
215
211
  if (tool === "uv") {
216
- return 'powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"';
212
+ return "curl -LsSf https://astral.sh/uv/install.sh | sh";
217
213
  }
218
214
  if (tool === "git") {
219
- return `winget install --id Git.Git -e ${quiet}`;
215
+ return "xcode-select --install";
220
216
  }
221
217
  if (tool === "node") {
222
- return `winget install --id OpenJS.NodeJS.LTS -e ${quiet}`;
218
+ return 'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash && . "$HOME/.nvm/nvm.sh" && nvm install --lts && nvm alias default \'lts/*\'';
223
219
  }
224
- return `winget install --id Microsoft.PowerShell -e ${quiet}`;
220
+ return "";
225
221
  }
226
222
  function readBody(req, max = 16_384) {
227
223
  return new Promise((resolve, reject) => {
@@ -429,10 +425,9 @@ async function main(instance) {
429
425
  projectFiles: { readClassroomInstalls },
430
426
  clipboard: { write: clipboard_1.writeClipboard },
431
427
  commands: { run: commandRunner_1.runCommand },
432
- environment: {
433
- probe: probeEnvironment,
434
- install: installEnvironment,
435
- },
428
+ environment: process.platform === "win32"
429
+ ? (0, windowsEnvironment_1.createWindowsEnvironment)(windowsEnvironmentSystem_1.windowsEnvironmentSystem)
430
+ : { probe: probeMacEnvironment, install: installMacEnvironment },
436
431
  files: {
437
432
  async write() {
438
433
  throw new Error("VansPod 不寫 MCP 設定");
@@ -548,6 +543,14 @@ async function main(instance) {
548
543
  res.end(JSON.stringify({ running: view.commandRunning, output: view.commandOutput ?? "" }));
549
544
  return;
550
545
  }
546
+ if (req.method === "GET" && pathname === "/environment-status") {
547
+ res.writeHead(200, {
548
+ "Content-Type": "application/json; charset=utf-8",
549
+ "Cache-Control": "no-store",
550
+ });
551
+ res.end(JSON.stringify((0, page_1.environmentStatus)(app.view())));
552
+ return;
553
+ }
551
554
  if (req.method === "GET" && pathname === "/model-status") {
552
555
  res.writeHead(200, {
553
556
  "Content-Type": "application/json; charset=utf-8",
@@ -676,13 +679,27 @@ async function main(instance) {
676
679
  goHome(params);
677
680
  return;
678
681
  }
682
+ if (req.method === "POST" && pathname === "/environment-log") {
683
+ const params = new URLSearchParams(await readBody(req));
684
+ await app.openEnvironmentLog();
685
+ goHome(params);
686
+ return;
687
+ }
688
+ if (req.method === "POST" && pathname === "/open-vscode") {
689
+ const params = new URLSearchParams(await readBody(req));
690
+ await app.openVsCode().catch(() => { });
691
+ goHome(params);
692
+ return;
693
+ }
679
694
  if (req.method === "POST" && pathname === "/environment") {
680
695
  const params = new URLSearchParams(await readBody(req));
681
696
  const tools = params
682
697
  .getAll("tool")
683
698
  .filter((value) => isEnvironmentTool(value));
684
699
  app.selectEnvironment(tools);
685
- await app.confirmEnvironment();
700
+ // 背景安裝:請求立刻回來,頁面輪詢 /environment-status。commandRunning 在 confirmEnvironment 同步開頭就設好,
701
+ // 轉回首頁時已顯示進行中,exit guard、版本更新與移除也照常看得到這次安裝。
702
+ void app.confirmEnvironment().catch(() => { });
686
703
  goHome(params);
687
704
  return;
688
705
  }
@@ -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.2";
4
+ exports.VERSION = "0.4.3";