@hex4c59/pi-ext-config-sync 0.1.0 → 0.1.2

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/src/github.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { isRecord, normalizeRelativePath } from "./files.ts";
2
2
  import { sha256Hex } from "./hash.ts";
3
+ import { delay, describeFailure, NetworkError, Transport } from "./transport.ts";
4
+ import type { HttpResponse } from "./transport.ts";
3
5
  import {
4
6
  AGENT_PATH_PREFIX,
5
7
  MANIFEST_PATH,
@@ -12,11 +14,27 @@ import type { RemoteFile, RemoteSnapshot, SyncManifest } from "./types.ts";
12
14
  const GITHUB_API = "https://api.github.com";
13
15
  const GITHUB_WEB = "https://github.com";
14
16
  const USER_AGENT = "pi-config-sync";
15
- const REQUEST_TIMEOUT_MS = 30_000;
17
+ const REQUEST_TIMEOUT_MS = 20_000;
16
18
  const MAX_BLOB_BYTES = 10 * 1024 * 1024;
17
19
  const MAX_SNAPSHOT_BYTES = 60 * 1024 * 1024;
18
20
  const MAX_MANIFEST_FILES = 2000;
19
21
  const BLOB_UPLOAD_CONCURRENCY = 4;
22
+ const MAX_LOGIN_NETWORK_FAILURES = 6;
23
+
24
+ let activeTransport: Transport | null = null;
25
+
26
+ // 每次命令开始时由 operations 用当前设置重建;不使用全局 fetch,
27
+ // 以便明确控制超时、重试和代理。
28
+ export function useTransport(transport: Transport): void {
29
+ activeTransport = transport;
30
+ }
31
+
32
+ function transport(): Transport {
33
+ if (activeTransport === null) {
34
+ throw new GithubError("config-sync transport was not configured.");
35
+ }
36
+ return activeTransport;
37
+ }
20
38
 
21
39
  export class GithubError extends SyncError {
22
40
  readonly status: number | undefined;
@@ -104,19 +122,37 @@ export async function pollDeviceToken(
104
122
  ): Promise<string> {
105
123
  let interval = device.interval;
106
124
  const deadline = Date.now() + device.expiresIn * 1000;
125
+ // 轮询期间短暂断网很常见;单次请求失败不应结束整个登录流程。
126
+ let consecutiveFailures = 0;
107
127
  while (true) {
108
128
  if (Date.now() >= deadline) throw new GithubError(expiredLoginMessage());
109
129
  await delay(interval * 1000, signal);
110
130
  if (Date.now() >= deadline) throw new GithubError(expiredLoginMessage());
111
- const data = await postForm(
112
- `${GITHUB_WEB}/login/oauth/access_token`,
113
- {
114
- client_id: clientId,
115
- device_code: device.deviceCode,
116
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
117
- },
118
- signal,
119
- );
131
+ let data: unknown;
132
+ try {
133
+ data = await postForm(
134
+ `${GITHUB_WEB}/login/oauth/access_token`,
135
+ {
136
+ client_id: clientId,
137
+ device_code: device.deviceCode,
138
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
139
+ },
140
+ signal,
141
+ );
142
+ } catch (error) {
143
+ if (signal?.aborted === true) throw error;
144
+ if (!isNetworkFailure(error)) throw error;
145
+ consecutiveFailures++;
146
+ if (consecutiveFailures >= MAX_LOGIN_NETWORK_FAILURES) {
147
+ throw new GithubError(
148
+ `GitHub is unreachable; login stopped after ${consecutiveFailures} failed attempts. `
149
+ + `${error instanceof Error ? error.message : String(error)}`,
150
+ );
151
+ }
152
+ onPending();
153
+ continue;
154
+ }
155
+ consecutiveFailures = 0;
120
156
  if (!isRecord(data)) throw new GithubError("GitHub returned an unreadable token response.");
121
157
  if (typeof data.access_token === "string" && data.access_token.length > 0) {
122
158
  return data.access_token;
@@ -137,13 +173,32 @@ export async function pollDeviceToken(
137
173
  }
138
174
  }
139
175
 
176
+ export interface PingResult {
177
+ status: number;
178
+ ms: number;
179
+ }
180
+
181
+ // 不需要登录令牌和 OAuth App 的可达性探测。
182
+ export async function ping(): Promise<PingResult> {
183
+ const started = Date.now();
184
+ const response = await send(`${GITHUB_API}/rate_limit`, {
185
+ method: "GET",
186
+ headers: {
187
+ Accept: "application/vnd.github+json",
188
+ "User-Agent": USER_AGENT,
189
+ },
190
+ });
191
+ if (!isSuccess(response.status)) throw apiError(response, parseJsonBody(response.text));
192
+ return { status: response.status, ms: Date.now() - started };
193
+ }
194
+
140
195
  export async function getViewer(token: string, signal?: AbortSignal): Promise<ViewerInfo> {
141
196
  const { data, headers } = await apiRequest(token, "GET", "/user", undefined, signal);
142
197
  if (!isRecord(data) || typeof data.login !== "string") {
143
198
  throw new GithubError("GitHub did not return a login name.", 500);
144
199
  }
145
200
  const scopeHeader = headers.get("x-oauth-scopes");
146
- const scopes = scopeHeader === null
201
+ const scopes = scopeHeader === undefined
147
202
  ? []
148
203
  : scopeHeader.split(",").map((scope) => scope.trim()).filter((scope) => scope.length > 0);
149
204
  return { login: data.login, scopes };
@@ -520,7 +575,7 @@ async function apiRequest(
520
575
  path: string,
521
576
  body: unknown,
522
577
  signal?: AbortSignal,
523
- ): Promise<{ data: unknown; headers: Headers }> {
578
+ ): Promise<{ data: unknown; headers: Map<string, string> }> {
524
579
  const headers: Record<string, string> = {
525
580
  Accept: "application/vnd.github+json",
526
581
  Authorization: `Bearer ${token}`,
@@ -528,49 +583,39 @@ async function apiRequest(
528
583
  "User-Agent": USER_AGENT,
529
584
  };
530
585
  if (body !== undefined) headers["Content-Type"] = "application/json";
531
- let response: Response;
532
- try {
533
- response = await fetch(`${GITHUB_API}${path}`, {
534
- method,
535
- headers,
536
- body: body === undefined ? undefined : JSON.stringify(body),
537
- signal: requestSignal(signal),
538
- });
539
- } catch (error) {
540
- if (isTimeoutError(error)) throw new GithubError("GitHub request timed out.", 408);
541
- throw error;
542
- }
543
- const text = await response.text();
544
- let data: unknown;
545
- try {
546
- data = text.length === 0 ? undefined : JSON.parse(text);
547
- } catch {
548
- data = undefined;
549
- }
550
- if (!response.ok) {
551
- throw apiError(response, data);
586
+ const response = await send(`${GITHUB_API}${path}`, {
587
+ method,
588
+ headers,
589
+ body: body === undefined ? undefined : JSON.stringify(body),
590
+ signal,
591
+ });
592
+ const data = parseJsonBody(response.text);
593
+ if (!isSuccess(response.status)) throw apiError(response, data);
594
+ const map = new Map<string, string>();
595
+ for (const [name, value] of Object.entries(response.headers)) {
596
+ if (typeof value === "string") map.set(name.toLowerCase(), value);
597
+ else if (Array.isArray(value)) map.set(name.toLowerCase(), value.join(", "));
552
598
  }
553
- return { data, headers: response.headers };
599
+ return { data, headers: map };
554
600
  }
555
601
 
556
- function apiError(response: Response, data: unknown): GithubError {
557
- if (response.status === 401) {
602
+ function apiError(response: HttpResponse, data: unknown): GithubError {
603
+ const status = response.status;
604
+ if (status === 401) {
558
605
  return new GithubError("GitHub token is invalid or expired. Run /sync login.", 401);
559
606
  }
560
- if (response.headers.get("x-ratelimit-remaining") === "0") {
561
- const reset = response.headers.get("x-ratelimit-reset");
562
- const when = reset === null ? "later" : new Date(Number(reset) * 1000).toISOString();
563
- return new GithubError(`GitHub API rate limit reached; resets at ${when}.`, response.status);
607
+ if (response.headers["x-ratelimit-remaining"] === "0") {
608
+ const reset = response.headers["x-ratelimit-reset"];
609
+ const when = reset === undefined ? "later" : new Date(Number(reset) * 1000).toISOString();
610
+ return new GithubError(`GitHub API rate limit reached; resets at ${when}.`, status);
564
611
  }
565
612
  const message = isRecord(data) && typeof data.message === "string"
566
613
  ? data.message
567
614
  : response.statusText;
568
- return new GithubError(`GitHub request failed (${response.status}): ${message}`, response.status);
569
- }
570
-
571
- function requestSignal(signal?: AbortSignal): AbortSignal {
572
- const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
573
- return signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
615
+ return new GithubError(
616
+ `GitHub request failed (${status}): ${message.length > 0 ? message : "no message"}.`,
617
+ status,
618
+ );
574
619
  }
575
620
 
576
621
  async function postForm(
@@ -578,31 +623,53 @@ async function postForm(
578
623
  fields: Record<string, string>,
579
624
  signal?: AbortSignal,
580
625
  ): Promise<unknown> {
581
- let response: Response;
626
+ const response = await send(url, {
627
+ method: "POST",
628
+ headers: {
629
+ Accept: "application/json",
630
+ "Content-Type": "application/x-www-form-urlencoded",
631
+ "User-Agent": USER_AGENT,
632
+ },
633
+ body: new URLSearchParams(fields).toString(),
634
+ signal,
635
+ });
636
+ const data = parseJsonBody(response.text);
637
+ if (data === undefined && response.text.length > 0) {
638
+ throw new GithubError("GitHub returned an unreadable response.", response.status);
639
+ }
640
+ if (!isSuccess(response.status)) throw apiError(response, data);
641
+ return data;
642
+ }
643
+
644
+ async function send(
645
+ url: string,
646
+ options: {
647
+ method: string;
648
+ headers: Record<string, string>;
649
+ body?: string;
650
+ signal?: AbortSignal;
651
+ },
652
+ ): Promise<HttpResponse> {
582
653
  try {
583
- response = await fetch(url, {
584
- method: "POST",
585
- headers: {
586
- Accept: "application/json",
587
- "Content-Type": "application/x-www-form-urlencoded",
588
- "User-Agent": USER_AGENT,
589
- },
590
- body: new URLSearchParams(fields),
591
- signal: requestSignal(signal),
592
- });
654
+ return await transport().request({ ...options, url, timeoutMs: REQUEST_TIMEOUT_MS });
593
655
  } catch (error) {
594
- if (isTimeoutError(error)) throw new GithubError("GitHub request timed out.", 408);
595
- throw error;
656
+ if (error instanceof NetworkError) throw new GithubError(error.message, 408);
657
+ if (error instanceof Error && error.name === "AbortError") throw error;
658
+ throw new GithubError(describeFailure(error, "", 1).message, 408);
596
659
  }
597
- const text = await response.text();
598
- let data: unknown;
660
+ }
661
+
662
+ function isSuccess(status: number): boolean {
663
+ return status >= 200 && status < 300;
664
+ }
665
+
666
+ function parseJsonBody(text: string): unknown {
667
+ if (text.length === 0) return undefined;
599
668
  try {
600
- data = text.length === 0 ? undefined : JSON.parse(text);
669
+ return JSON.parse(text);
601
670
  } catch {
602
- throw new GithubError("GitHub returned an unreadable response.", response.status);
671
+ return undefined;
603
672
  }
604
- if (!response.ok) throw apiError(response, data);
605
- return data;
606
673
  }
607
674
 
608
675
  function deviceFlowError(code: string): string {
@@ -620,29 +687,8 @@ function expiredLoginMessage(): string {
620
687
  return "The GitHub login code expired. Run /sync login again.";
621
688
  }
622
689
 
623
- function isTimeoutError(error: unknown): boolean {
624
- return typeof error === "object"
625
- && error !== null
626
- && "name" in error
627
- && error.name === "TimeoutError";
628
- }
629
-
630
- function delay(ms: number, signal?: AbortSignal): Promise<void> {
631
- return new Promise((resolve, reject) => {
632
- if (signal?.aborted === true) {
633
- reject(signal.reason);
634
- return;
635
- }
636
- const timer = setTimeout(() => {
637
- signal?.removeEventListener("abort", onAbort);
638
- resolve();
639
- }, ms);
640
- const onAbort = () => {
641
- clearTimeout(timer);
642
- reject(signal?.reason);
643
- };
644
- signal?.addEventListener("abort", onAbort, { once: true });
645
- });
690
+ function isNetworkFailure(error: unknown): boolean {
691
+ return error instanceof GithubError && error.status === 408;
646
692
  }
647
693
 
648
694
  async function mapLimit<T, R>(
package/src/operations.ts CHANGED
@@ -28,6 +28,8 @@ import {
28
28
  } from "./crypto.ts";
29
29
  import * as github from "./github.ts";
30
30
  import { sha256Hex } from "./hash.ts";
31
+ import { isProxyReachable, resolveProxySettings } from "./proxy.ts";
32
+ import { Transport } from "./transport.ts";
31
33
  import { planPull, planPush, takeRemoteForConflicts } from "./plan.ts";
32
34
  import {
33
35
  AGENT_PATH_PREFIX,
@@ -92,12 +94,25 @@ export function clearPassphraseCache(): void {
92
94
  cachedPassphrase = null;
93
95
  }
94
96
 
97
+ // 每次联网命令前重建传输层:读取当前代理设置,避免沿用上一次命令的连接池。
98
+ async function prepareNetwork(config: SyncConfig): Promise<void> {
99
+ const settings = await resolveProxySettings({ configuredProxy: config.proxy });
100
+ if (settings.proxy.length > 0 && !await isProxyReachable(settings.proxy)) {
101
+ throw new SyncError(
102
+ `The proxy ${settings.proxy} (from ${describeProxySource(settings.source)}) is not accepting `
103
+ + "connections. Start the proxy program, or run /sync proxy default to connect directly.",
104
+ );
105
+ }
106
+ github.useTransport(new Transport({ proxy: settings.proxy, noProxy: settings.noProxy }));
107
+ }
108
+
95
109
  export async function runLogin(ui: SyncUi, agentDir: string): Promise<void> {
96
110
  const config = await loadConfig(agentDir);
97
111
  const clientId = config.clientId.trim();
98
112
  if (clientId.length === 0) {
99
113
  throw new SyncError("No OAuth client ID configured. Run /sync setup <client-id> first.");
100
114
  }
115
+ await prepareNetwork(config);
101
116
  const device = await github.requestDeviceCode(clientId);
102
117
  ui.copyText(device.userCode);
103
118
  ui.notify(
@@ -240,11 +255,46 @@ export async function runSetAuto(
240
255
  ui.notify(`Automatic pull on startup is ${config.autoPull ? "on" : "off"}.`, "info");
241
256
  }
242
257
 
258
+ export async function runSetProxy(
259
+ ui: SyncUi,
260
+ agentDir: string,
261
+ valueArg: string,
262
+ ): Promise<void> {
263
+ const answer = valueArg.trim().length > 0
264
+ ? valueArg.trim()
265
+ : await ui.askText("Proxy URL, 'system' to follow the OS setting, or 'default' to auto-detect");
266
+ if (answer === undefined || answer.trim().length === 0) {
267
+ ui.notify("Proxy unchanged.", "info");
268
+ return;
269
+ }
270
+ const value = answer.trim();
271
+ const config = await loadConfig(agentDir);
272
+ config.proxy = value === "default" || value === "system" ? "" : value;
273
+ await saveConfig(agentDir, config);
274
+ if (value === "default" || value === "system") {
275
+ const settings = await resolveProxySettings({
276
+ configuredProxy: "",
277
+ systemOnly: value === "system",
278
+ });
279
+ ui.notify(
280
+ settings.proxy.length === 0
281
+ ? `Proxy cleared; direct connections will be used${
282
+ value === "system" ? ", because no Windows system proxy is enabled" : ""
283
+ }.`
284
+ : `Proxy cleared; ${settings.proxy} from ${describeProxySource(settings.source)} will be used.`,
285
+ "info",
286
+ );
287
+ return;
288
+ }
289
+ ui.notify(`Proxy set to ${config.proxy}.`, "info");
290
+ }
291
+
243
292
  export async function runStatus(ui: SyncUi, agentDir: string): Promise<void> {
244
293
  const config = await loadConfig(agentDir);
245
294
  const { state, warning } = await loadState(agentDir);
246
295
  if (warning !== undefined) ui.notify(warning, "warning");
247
296
  const token = await readSyncToken(agentDir);
297
+ const proxy = await resolveProxySettings({ configuredProxy: config.proxy });
248
298
  const repo = config.repo.length > 0
249
299
  ? config.repo
250
300
  : state.login.length > 0
@@ -256,6 +306,9 @@ export async function runStatus(ui: SyncUi, agentDir: string): Promise<void> {
256
306
  `Repository: ${repo}`,
257
307
  `Branch: ${config.branch.length > 0 ? config.branch : "(repository default)"}`,
258
308
  `Auto pull: ${config.autoPull ? "on" : "off"}`,
309
+ `Proxy: ${proxy.proxy.length === 0
310
+ ? "direct"
311
+ : `${proxy.proxy} (${describeProxySource(proxy.source)})`}`,
259
312
  `Credential filter: ${config.includeAuthProviders.length > 0
260
313
  ? `only ${config.includeAuthProviders.join(", ")}`
261
314
  : "API-key providers only"}`,
@@ -267,6 +320,24 @@ export async function runStatus(ui: SyncUi, agentDir: string): Promise<void> {
267
320
  ui.notify(lines.join("\n"), "info");
268
321
  }
269
322
 
323
+ export async function runPing(ui: SyncUi, agentDir: string): Promise<void> {
324
+ const config = await loadConfig(agentDir);
325
+ const proxy = await resolveProxySettings({ configuredProxy: config.proxy });
326
+ const via = proxy.proxy.length === 0
327
+ ? "direct"
328
+ : `${proxy.proxy} (${describeProxySource(proxy.source)})`;
329
+ await prepareNetwork(config);
330
+ const probe = await github.ping();
331
+ ui.notify(`GitHub is reachable via ${via} in ${probe.ms} ms (HTTP ${probe.status}).`, "info");
332
+ }
333
+
334
+ function describeProxySource(source: "config" | "environment" | "system" | "none"): string {
335
+ if (source === "config") return "config.json";
336
+ if (source === "environment") return "environment";
337
+ if (source === "system") return "Windows system proxy";
338
+ return "direct";
339
+ }
340
+
270
341
  export async function runPull(
271
342
  ui: SyncUi,
272
343
  agentDir: string,
@@ -275,6 +346,7 @@ export async function runPull(
275
346
  const config = await loadConfig(agentDir);
276
347
  const token = await readSyncToken(agentDir);
277
348
  if (token === null) throw new SyncError("Not signed in. Run /sync login first.");
349
+ await prepareNetwork(config);
278
350
  const { state, warning } = await loadState(agentDir);
279
351
  if (warning !== undefined) ui.notify(warning, "warning");
280
352
  const target = await resolveTarget(token, config, state, options.signal);
@@ -410,6 +482,7 @@ export async function runPush(
410
482
  const config = await loadConfig(agentDir);
411
483
  const token = await readSyncToken(agentDir);
412
484
  if (token === null) throw new SyncError("Not signed in. Run /sync login first.");
485
+ await prepareNetwork(config);
413
486
  const { state, warning } = await loadState(agentDir);
414
487
  if (warning !== undefined) ui.notify(warning, "warning");
415
488
  const target = await resolveTarget(token, config, state, options.signal);
package/src/proxy.ts ADDED
@@ -0,0 +1,162 @@
1
+ import { execFile } from "node:child_process";
2
+ import net from "node:net";
3
+
4
+ const REG_PATH = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
5
+ const PROBE_TIMEOUT_MS = 400;
6
+
7
+ export interface ProxySettings {
8
+ proxy: string;
9
+ noProxy: string;
10
+ source: "config" | "environment" | "system" | "none";
11
+ }
12
+
13
+ export interface ProxyResolutionInput {
14
+ configuredProxy: string;
15
+ /** 为 true 时跳过环境变量,直接读取系统代理。 */
16
+ systemOnly?: boolean;
17
+ }
18
+
19
+ export async function resolveProxySettings(input: ProxyResolutionInput): Promise<ProxySettings> {
20
+ const configured = input.configuredProxy.trim();
21
+ if (configured.length > 0) {
22
+ return {
23
+ proxy: normalizeProxyUrl(configured),
24
+ noProxy: environmentNoProxy(),
25
+ source: "config",
26
+ };
27
+ }
28
+ if (input.systemOnly !== true) {
29
+ const fromEnvironment = environmentProxy();
30
+ if (fromEnvironment !== undefined) {
31
+ return {
32
+ proxy: normalizeProxyUrl(fromEnvironment),
33
+ noProxy: environmentNoProxy(),
34
+ source: "environment",
35
+ };
36
+ }
37
+ }
38
+ const fromSystem = await readSystemProxy();
39
+ if (fromSystem !== undefined) {
40
+ return { ...fromSystem, source: "system" };
41
+ }
42
+ return { proxy: "", noProxy: environmentNoProxy(), source: "none" };
43
+ }
44
+
45
+ // 返回 false 表示本地代理端口没有在监听,通常代表代理程序已退出。
46
+ export async function isProxyReachable(proxy: string): Promise<boolean> {
47
+ if (proxy.length === 0) return false;
48
+ let target: URL;
49
+ try {
50
+ target = new URL(proxy);
51
+ } catch {
52
+ return false;
53
+ }
54
+ const port = target.port.length > 0 ? Number(target.port) : 80;
55
+ return new Promise((resolve) => {
56
+ const socket = net.connect({ host: target.hostname, port, timeout: PROBE_TIMEOUT_MS });
57
+ socket.once("connect", () => {
58
+ socket.destroy();
59
+ resolve(true);
60
+ });
61
+ socket.once("timeout", () => {
62
+ socket.destroy();
63
+ resolve(false);
64
+ });
65
+ socket.once("error", () => resolve(false));
66
+ });
67
+ }
68
+
69
+ function environmentProxy(): string | undefined {
70
+ const value = process.env.HTTPS_PROXY
71
+ ?? process.env.https_proxy
72
+ ?? process.env.HTTP_PROXY
73
+ ?? process.env.http_proxy
74
+ ?? "";
75
+ return value.trim().length > 0 ? value.trim() : undefined;
76
+ }
77
+
78
+ function environmentNoProxy(): string {
79
+ return process.env.NO_PROXY ?? process.env.no_proxy ?? "";
80
+ }
81
+
82
+ function normalizeProxyUrl(value: string): string {
83
+ const trimmed = value.trim();
84
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) return trimmed;
85
+ return `http://${trimmed}`;
86
+ }
87
+
88
+ interface SystemProxy {
89
+ proxy: string;
90
+ noProxy: string;
91
+ }
92
+
93
+ async function readSystemProxy(): Promise<SystemProxy | undefined> {
94
+ if (process.platform !== "win32") return undefined;
95
+ let output: string;
96
+ try {
97
+ output = await queryRegistry();
98
+ } catch {
99
+ return undefined;
100
+ }
101
+ const values = parseRegistryValues(output);
102
+ if (values.get("ProxyEnable") !== "0x1") return undefined;
103
+ const server = values.get("ProxyServer") ?? "";
104
+ const proxy = pickProxyServer(server);
105
+ if (proxy === undefined) return undefined;
106
+ return {
107
+ proxy: normalizeProxyUrl(proxy),
108
+ noProxy: convertProxyOverride(values.get("ProxyOverride") ?? ""),
109
+ };
110
+ }
111
+
112
+ function queryRegistry(): Promise<string> {
113
+ return new Promise((resolve, reject) => {
114
+ execFile(
115
+ "reg",
116
+ ["query", REG_PATH],
117
+ { windowsHide: true, timeout: 3000 },
118
+ (error, stdout) => {
119
+ if (error !== null) {
120
+ reject(error);
121
+ return;
122
+ }
123
+ resolve(stdout);
124
+ },
125
+ );
126
+ });
127
+ }
128
+
129
+ function parseRegistryValues(output: string): Map<string, string> {
130
+ const values = new Map<string, string>();
131
+ for (const line of output.split(/\r?\n/)) {
132
+ const match = /^\s{2,}(\S+)\s+(REG_\w+)\s+(.*)$/.exec(line);
133
+ if (match === null) continue;
134
+ values.set(match[1] ?? "", (match[3] ?? "").trim());
135
+ }
136
+ return values;
137
+ }
138
+
139
+ // ProxyServer 可能是 host:port,也可能是 http=host:port;https=host:port。
140
+ function pickProxyServer(value: string): string | undefined {
141
+ const entries = value.split(";").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
142
+ if (entries.length === 0) return undefined;
143
+ for (const scheme of ["https", "http"]) {
144
+ for (const entry of entries) {
145
+ const separator = entry.indexOf("=");
146
+ if (separator === -1) continue;
147
+ if (entry.slice(0, separator).trim().toLowerCase() !== scheme) continue;
148
+ const address = entry.slice(separator + 1).trim();
149
+ if (address.length > 0) return scheme === "http" ? `http://${address}` : `https://${address}`;
150
+ }
151
+ }
152
+ const first = entries[0] ?? "";
153
+ return first.includes("=") ? undefined : first;
154
+ }
155
+
156
+ function convertProxyOverride(value: string): string {
157
+ return value
158
+ .split(";")
159
+ .map((entry) => entry.trim())
160
+ .filter((entry) => entry.length > 0 && entry !== "<local>")
161
+ .join(",");
162
+ }