mihomo-cli 26.10.111 → 26.10.113

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/dist/index.js CHANGED
@@ -58,6 +58,66 @@ var compareVersions = (v1, v2) => {
58
58
  return 0;
59
59
  };
60
60
 
61
+ // node_modules/compare-versions/lib/esm/compare.js
62
+ var compare = (v1, v2, operator) => {
63
+ assertValidOperator(operator);
64
+ const res = compareVersions(v1, v2);
65
+ return operatorResMap[operator].includes(res);
66
+ };
67
+ var operatorResMap = {
68
+ ">": [1],
69
+ ">=": [0, 1],
70
+ "=": [0],
71
+ "<=": [-1, 0],
72
+ "<": [-1],
73
+ "!=": [-1, 1]
74
+ };
75
+ var allowedOperators = Object.keys(operatorResMap);
76
+ var assertValidOperator = (op) => {
77
+ if (typeof op !== "string") {
78
+ throw new TypeError(`Invalid operator type, expected string but got ${typeof op}`);
79
+ }
80
+ if (allowedOperators.indexOf(op) === -1) {
81
+ throw new Error(`Invalid operator, expected one of ${allowedOperators.join("|")}`);
82
+ }
83
+ };
84
+
85
+ // node_modules/compare-versions/lib/esm/satisfies.js
86
+ var satisfies = (version, range) => {
87
+ range = range.replace(/([><=]+)\s+/g, "$1");
88
+ if (range.includes("||")) {
89
+ return range.split("||").some((r4) => satisfies(version, r4));
90
+ } else if (range.includes(" - ")) {
91
+ const [a, b] = range.split(" - ", 2);
92
+ return satisfies(version, `>=${a} <=${b}`);
93
+ } else if (range.includes(" ")) {
94
+ return range.trim().replace(/\s{2,}/g, " ").split(" ").every((r4) => satisfies(version, r4));
95
+ }
96
+ const m = range.match(/^([<>=~^]+)/);
97
+ const op = m ? m[1] : "=";
98
+ if (op !== "^" && op !== "~")
99
+ return compare(version, range, op);
100
+ const [v1, v2, v3, , vp] = validateAndParse(version);
101
+ const [r1, r2, r3, , rp] = validateAndParse(range);
102
+ const v = [v1, v2, v3];
103
+ const r = [r1, r2 !== null && r2 !== void 0 ? r2 : "x", r3 !== null && r3 !== void 0 ? r3 : "x"];
104
+ if (rp) {
105
+ if (!vp)
106
+ return false;
107
+ if (compareSegments(v, r) !== 0)
108
+ return false;
109
+ if (compareSegments(vp.split("."), rp.split(".")) === -1)
110
+ return false;
111
+ }
112
+ const nonZero = r.findIndex((v4) => v4 !== "0") + 1;
113
+ const i = op === "~" ? 2 : nonZero > 1 ? nonZero : 1;
114
+ if (compareSegments(v.slice(0, i), r.slice(0, i)) !== 0)
115
+ return false;
116
+ if (compareSegments(v.slice(i), r.slice(i)) === -1)
117
+ return false;
118
+ return true;
119
+ };
120
+
61
121
  // src/constants.ts
62
122
  import { createRequire } from "module";
63
123
 
@@ -108,12 +168,7 @@ var pkg = require2("../package.json");
108
168
  var YAML_MAX_ALIASES = 200;
109
169
  var VERSION = pkg.version;
110
170
  var PKG_NAME = pkg.name;
111
- var MIN_NODE_VERSION = (() => {
112
- const raw = pkg.engines?.node;
113
- if (typeof raw !== "string") return null;
114
- const m = raw.trim().match(/^>=\s*(\d+\.\d+\.\d+)$/);
115
- return m ? m[1] : null;
116
- })();
171
+ var NODE_ENGINES = typeof pkg.engines?.node === "string" ? pkg.engines.node : null;
117
172
  var MIRROR_HOST = "gh-proxy.org";
118
173
  var MIRROR_ALIASES = {
119
174
  v4: `https://v4.${MIRROR_HOST}/`,
@@ -134,7 +189,6 @@ function isValidServiceLabel(label) {
134
189
  return SERVICE_LABEL_RE.test(label) && !label.includes("..");
135
190
  }
136
191
  var RAW_SERVICE_LABEL = process.env.MIHOMO_CLI_DAEMON_LABEL;
137
- var RAW_SERVICE_LABEL_INPUT = RAW_SERVICE_LABEL;
138
192
  var SERVICE_LABEL = RAW_SERVICE_LABEL && isValidServiceLabel(RAW_SERVICE_LABEL) ? RAW_SERVICE_LABEL : DEFAULT_SERVICE_LABEL;
139
193
  var SERVICE_BINARY_NAME = "mihomo-cli-service";
140
194
  var DEFAULT_MIXED_PORT = 7890;
@@ -235,8 +289,8 @@ var BASE_CONFIG = {
235
289
  var DEFAULT_UPDATE_INTERVAL_HOURS = 12;
236
290
  var DEFAULT_AUTO_UPDATE_TIMEOUT = 1e4;
237
291
  function assertServiceLabelSafe() {
238
- if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
239
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
292
+ if (RAW_SERVICE_LABEL !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL)) {
293
+ throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL}"`, {
240
294
  label: "\u914D\u7F6E\u9519\u8BEF",
241
295
  hint: ['\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002', "\u8BE5\u503C\u4F1A\u6210\u4E3A launchd plist \u7684\u6587\u4EF6\u540D\uFF0C\u53C2\u4E0E plist \u5199\u5165\u4E0E\u5220\u9664\u8DEF\u5F84\u3002"]
242
296
  });
@@ -4095,16 +4149,10 @@ function lockedKeysReferencedBy(rawKeys) {
4095
4149
  return [...hit];
4096
4150
  }
4097
4151
  function assertValidParsedKey(rawKey, parsed) {
4098
- if (rawKey.startsWith("~") || parsed.key.includes("~")) {
4099
- throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684 ~ \u64CD\u4F5C\u7B26`, {
4152
+ if (/[~<>]/.test(rawKey)) {
4153
+ throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684\u64CD\u4F5C\u7B26\uFF08~ / ~? / <key>\uFF09`, {
4100
4154
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4101
- hint: ["\u6309 name \u5408\u5E76/\u8FFD\u52A0\u6570\u7EC4\u5143\u7D20\u7684 ~ \u4E0E ~? \u5DF2\u79FB\u9664\uFF0C\u6539\u7528 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\u7684\u811A\u672C\u4E00\u8282\uFF09\u3002"]
4102
- });
4103
- }
4104
- if (rawKey.includes("<") || rawKey.includes(">")) {
4105
- throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684\u5C16\u62EC\u53F7\u8F6C\u4E49`, {
4106
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4107
- hint: ["<key> \u8F6C\u4E49\u5DF2\u968F ~ \u64CD\u4F5C\u7B26\u79FB\u9664\u2014\u2014mihomo-cli \u9876\u5C42\u952E\u4E0D\u542B\u5C16\u62EC\u53F7\uFF0C\u76F4\u63A5\u5199\u952E\u540D\u5373\u53EF\u3002"]
4155
+ hint: ["\u6309 name \u5408\u5E76\u6570\u7EC4\u5143\u7D20\u6539\u7528 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\uFF09\uFF1B<key> \u8F6C\u4E49\u4E0D\u518D\u9700\u8981\uFF0C\u76F4\u63A5\u5199\u952E\u540D\u3002"]
4108
4156
  });
4109
4157
  }
4110
4158
  if (parsed.key === "") {
@@ -4257,12 +4305,6 @@ function normalizeMatch(raw, fileName) {
4257
4305
  throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u5FC5\u987B\u662F\u5BF9\u8C61\uFF08name / url-domain\uFF09`, { label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF" });
4258
4306
  }
4259
4307
  const rawEntries = raw;
4260
- if ("subscription" in rawEntries) {
4261
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u7528\u4E86 subscription \u952E`, {
4262
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4263
- hint: ["subscription \u952E\u5DF2\u6536\u6389\uFF08\u4E0E name \u540C\u4E49\u4F46\u4E24\u5957\u5199\u6CD5\uFF09\uFF0C\u8BF7\u6539\u5199 name\uFF0C\u5339\u914D\u8BED\u4E49\u4E0D\u53D8:", " match:", " name: edu*"]
4264
- });
4265
- }
4266
4308
  const result = {};
4267
4309
  const problems = [];
4268
4310
  for (const [key, value] of Object.entries(rawEntries)) {
@@ -4293,16 +4335,6 @@ function normalizeMatch(raw, fileName) {
4293
4335
  ]
4294
4336
  });
4295
4337
  }
4296
- const impossible = arr.find((v) => !v.includes("*") && !SAFE_NAME_RE.test(v));
4297
- if (impossible !== void 0) {
4298
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 name \u503C\u4E0D\u53EF\u80FD\u5339\u914D\u4EFB\u4F55\u8BA2\u9605: "${impossible}"`, {
4299
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4300
- hint: [
4301
- "\u8BA2\u9605\u540D\u53EA\u80FD\u542B\u5B57\u6BCD\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u8FDE\u5B57\u7B26\u4E0E\u4E2D\u6587\uFF081-64 \u5B57\u7B26\uFF09\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u8BEF\u5E26\u4E86 /\u3001~\u3001\u7A7A\u683C\u3001\u70B9\u53F7\u7B49\u5B57\u7B26\u3002",
4302
- "\u66F4\u590D\u6742\u7684\u5339\u914D\u5199 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\uFF09\u3002"
4303
- ]
4304
- });
4305
- }
4306
4338
  }
4307
4339
  result[key] = arr;
4308
4340
  }
@@ -4332,14 +4364,8 @@ function isValidNamePattern(value) {
4332
4364
  return star === 0 || star === value.length - 1;
4333
4365
  }
4334
4366
  function urlDomainValueProblem(value) {
4335
- if (value.includes("*") || value.includes("?")) {
4336
- return `url-domain \u4E0D\u652F\u6301\u901A\u914D\u7B26\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF0C\u53EA\u505A\u5B57\u9762\u540E\u7F00\u6BD4\u5BF9`;
4337
- }
4338
- if (/[:/]/.test(value)) {
4339
- return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF1A\u4E0D\u8981\u5E26\u534F\u8BAE\u3001\u8DEF\u5F84\u6216\u7AEF\u53E3\uFF0C\u8BF7\u53BB\u6389 https://\u3001\u5C3E\u659C\u6760\u4E0E\u7AEF\u53E3`;
4340
- }
4341
- if (/\s/.test(value)) {
4342
- return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF1A\u503C\u4E2D\u4E0D\u80FD\u542B\u7A7A\u683C`;
4367
+ if (/[*?:/\s]/.test(value)) {
4368
+ return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\u3001\u4E0D\u652F\u6301\u901A\u914D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF0C\u53BB\u6389 https://\u3001\u8DEF\u5F84\u3001\u7AEF\u53E3\u3001* \u4E0E\u7A7A\u683C`;
4343
4369
  }
4344
4370
  return void 0;
4345
4371
  }
@@ -4395,24 +4421,11 @@ function selectActiveOverwriteFiles(files, scope) {
4395
4421
  var METADATA_KEYS = /* @__PURE__ */ new Set(["match", "enabled"]);
4396
4422
  function assertNoMetadataKeyLookalikes(config, fileName) {
4397
4423
  for (const rawKey of Object.keys(config)) {
4398
- const parsed = parseOverrideKey(rawKey).key;
4399
- if (parsed !== rawKey && METADATA_KEYS.has(parsed)) {
4400
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684\u5143\u6570\u636E\u952E "${rawKey}" \u4E0D\u652F\u6301\u64CD\u4F5C\u7B26`, {
4401
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4402
- hint: [
4403
- `match \u4E0E enabled \u662F\u672C CLI \u7684\u5143\u6570\u636E\u952E\uFF0C\u5728\u5408\u5E76\u524D\u5C31\u88AB\u5265\u79BB\uFF0C\u5E26\u64CD\u4F5C\u7B26\u5199\u6CD5\uFF08\u5982 ${rawKey}\uFF09\u4E0D\u4F1A\u751F\u6548\uFF0C\u53CD\u800C\u4F1A\u628A ${parsed} \u5F53\u666E\u901A\u914D\u7F6E\u952E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\u3002`,
4404
- `\u8BF7\u76F4\u63A5\u5199 ${parsed}: <\u503C>\u3002`
4405
- ]
4406
- });
4407
- }
4408
- const normalized = rawKey.trim().toLowerCase();
4424
+ const normalized = parseOverrideKey(rawKey.trim().toLowerCase()).key;
4409
4425
  if (normalized !== rawKey && METADATA_KEYS.has(normalized)) {
4410
4426
  throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 "${rawKey}" \u7591\u4F3C\u60F3\u5199\u5143\u6570\u636E\u952E ${normalized}`, {
4411
4427
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4412
- hint: [
4413
- `YAML \u952E\u533A\u5206\u5927\u5C0F\u5199\u4E0E\u7A7A\u767D\uFF0C"${rawKey}" \u4E0D\u4F1A\u88AB\u8BC6\u522B\u4E3A ${normalized}\u2014\u2014\u6587\u4EF6\u4E0D\u4F1A\u88AB\u505C\u7528/\u9650\u5B9A\u4F5C\u7528\u57DF\uFF0C\u8BE5\u952E\u53CD\u800C\u4F1A\u5F53\u666E\u901A\u914D\u7F6E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\uFF08\u5185\u6838\u5BF9\u672A\u77E5\u9876\u5C42\u952E\u4E0D\u62A5\u9519\uFF0C\u4E0D\u4F1A\u6709\u4EFB\u4F55\u63D0\u793A\uFF09\u3002`,
4414
- `\u8BF7\u5199\u6210 ${normalized}: <\u503C>\u3002`
4415
- ]
4428
+ hint: [`\u5143\u6570\u636E\u952E\u53EA\u8BA4\u7CBE\u786E\u5199\u6CD5\uFF08\u533A\u5206\u5927\u5C0F\u5199\u3001\u4E0D\u5E26\u64CD\u4F5C\u7B26\uFF09\uFF0C"${rawKey}" \u4E0D\u4F1A\u751F\u6548\uFF0C\u53CD\u800C\u4F1A\u5F53\u666E\u901A\u952E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\u3002`, `\u8BF7\u5199\u6210 ${normalized}: <\u503C>\u3002`]
4416
4429
  });
4417
4430
  }
4418
4431
  }
@@ -4474,7 +4487,7 @@ function loadOverwriteScript(filePath, fileName) {
4474
4487
  throw new CliError(`\u8986\u5199\u811A\u672C "${fileName}" \u7F3A\u5C11\u53D8\u6362\u51FD\u6570`, {
4475
4488
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4476
4489
  hint: [
4477
- "\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF1Breturn true \u8868\u793A\u547D\u4E2D\u5F53\u524D\u8BA2\u9605\uFF0C\u5176\u4F59\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
4490
+ "\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF0C\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
4478
4491
  " export default function (config, ctx) { ... }",
4479
4492
  "CommonJS \u5199\u6CD5 module.exports = function (config, ctx) { ... } \u540C\u6837\u8BA4\u3002"
4480
4493
  ]
@@ -4558,7 +4571,6 @@ function applyOverwrite(baseConfig, files, opts) {
4558
4571
  let result = { ...baseConfig };
4559
4572
  const scriptWarnings = [];
4560
4573
  const scriptLockedHits = [];
4561
- const scriptMatches = [];
4562
4574
  const host = hostFromSubUrl(opts.scope?.subUrl) ?? "";
4563
4575
  const subscription = { name: opts.scope?.subName ?? "", url: opts.scope?.subUrl ?? "", host };
4564
4576
  for (const file of files) {
@@ -4582,14 +4594,13 @@ function applyOverwrite(baseConfig, files, opts) {
4582
4594
  });
4583
4595
  }
4584
4596
  scriptWarnings.push(...notes.map((message) => `${message}\uFF08\u811A\u672C ${file.name}\uFF09`));
4585
- scriptMatches.push({ file: file.name, matched: returned === true });
4586
4597
  const keys = diffLockedKeys(before, result);
4587
4598
  if (keys.length > 0) scriptLockedHits.push({ file: file.name, keys });
4588
4599
  continue;
4589
4600
  }
4590
4601
  result = mergeConfigLevel(result, file.config ?? {}, true);
4591
4602
  }
4592
- return { config: result, scriptWarnings, scriptLockedHits, scriptMatches };
4603
+ return { config: result, scriptWarnings, scriptLockedHits };
4593
4604
  }
4594
4605
  function listOverwriteFile(scope) {
4595
4606
  const { ok, broken } = readOverwriteFiles();
@@ -4597,23 +4608,21 @@ function listOverwriteFile(scope) {
4597
4608
  return {
4598
4609
  enabled,
4599
4610
  dir: USER_DATA_DIR,
4600
- entries: ok,
4601
4611
  files: ok.map((f) => ({
4602
4612
  name: f.name,
4603
4613
  kind: f.transform ? "script" : "yaml",
4604
4614
  keys: f.transform ? [] : Object.keys(f.config || {}),
4605
4615
  scope: summarizeMatch(f.match),
4606
4616
  enabled: f.enabled !== false,
4607
- ...scope ? { matched: matchesScope(f.match, scope) } : {}
4617
+ ...scope && !f.transform ? { matched: matchesScope(f.match, scope) } : {}
4608
4618
  })),
4609
4619
  broken
4610
4620
  };
4611
4621
  }
4612
4622
 
4613
4623
  // src/config.ts
4614
- var SAFE_YAML_LOAD_OPTIONS = { maxAliases: YAML_MAX_ALIASES };
4615
4624
  function loadYamlSafe(content) {
4616
- return load(content, SAFE_YAML_LOAD_OPTIONS);
4625
+ return load(content, { maxAliases: YAML_MAX_ALIASES });
4617
4626
  }
4618
4627
  function parseConfigContent(content, errorMsg) {
4619
4628
  const label = errorMsg || "\u5185\u5BB9";
@@ -4781,20 +4790,6 @@ function buildConfig(subRawContent, mode, scope) {
4781
4790
  function renderLockedWarning(source, keys) {
4782
4791
  return `${source}\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${keys.join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u3001\u63A7\u5236\u5668\u8BC1\u4E66\u4E0E\u5C40\u57DF\u7F51/\u5165\u7AD9\u9274\u6743\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF0C\u5165\u7AD9\u56FA\u5B9A\u53EA\u76D1\u542C\u56DE\u73AF\uFF0C\u9700\u8981\u5C40\u57DF\u7F51\u5165\u7AD9\u8BF7\u5728\u672C\u673A\u53E6\u8D77\u4E00\u4E2A mihomo-cli \u5B9E\u4F8B\uFF09`;
4783
4792
  }
4784
- function judgeScriptMatches(subRawContent, mode, scope, entries) {
4785
- try {
4786
- const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
4787
- const settings = readSettings();
4788
- const active = settings.overwrite_enabled !== false ? selectActiveOverwriteFiles(entries, scope) : [];
4789
- const { scriptMatches } = applyOverwrite(subscriptionConfig, active, {
4790
- mode,
4791
- scope
4792
- });
4793
- return { matches: scriptMatches };
4794
- } catch {
4795
- return { matches: [] };
4796
- }
4797
- }
4798
4793
  function deriveRuntimeMode(info) {
4799
4794
  return info?.tun ? "tun" : "mixed";
4800
4795
  }
@@ -4821,7 +4816,7 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
4821
4816
  }
4822
4817
  const hint = ["", ...detail.split("\n").map((line) => line.trim() ? `${HINT_INDENT}${line}` : "")];
4823
4818
  if (overwriteSummaries.length > 0) {
4824
- hint.push("", `${HINT_INDENT}\u5F53\u524D\u751F\u6548\u7684\u8986\u5199\u6587\u4EF6:`);
4819
+ hint.push("", `${HINT_INDENT}\u672C\u6B21\u53C2\u4E0E\u6784\u5EFA\u7684\u8986\u5199\u6587\u4EF6:`);
4825
4820
  for (const summary of overwriteSummaries) hint.push(sanitizeTerminal(`${HINT_INDENT.repeat(2)}${summary}`));
4826
4821
  hint.push(`${HINT_INDENT}\u82E5\u62A5\u9519\u7684\u5143\u7D20\u6765\u81EA\u8986\u5199\uFF08YAML \u8FFD\u52A0\u6216 JS \u811A\u672C\u6CE8\u5165\uFF09\uFF0C\u68C0\u67E5\u5BF9\u5E94\u7684\u8986\u5199\u6587\u4EF6\u4E0E\u811A\u672C\u3002`);
4827
4822
  }
@@ -4999,14 +4994,6 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
4999
4994
  return `${Math.floor(month / 12)} \u5E74\u524D`;
5000
4995
  }
5001
4996
 
5002
- // src/service.ts
5003
- import { spawnSync as spawnSync7 } from "child_process";
5004
- import fs12 from "fs";
5005
- import path7 from "path";
5006
-
5007
- // src/hot-reload.ts
5008
- import fs8 from "fs";
5009
-
5010
4997
  // src/launchctl.ts
5011
4998
  import { spawnSync as spawnSync2 } from "child_process";
5012
4999
  import fs5 from "fs";
@@ -5144,1529 +5131,1489 @@ async function waitUntilUnloaded(target = serviceTarget()) {
5144
5131
  });
5145
5132
  }
5146
5133
 
5147
- // src/proxy-probe.ts
5148
- import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
5149
- import { promisify as promisify2 } from "util";
5150
-
5151
- // src/curl-spawn.ts
5152
- function buildCurlSpawnEnv() {
5153
- const env = { ...process.env };
5154
- env.no_proxy = "";
5155
- env.NO_PROXY = "";
5156
- return env;
5134
+ // src/suggest.ts
5135
+ function levenshtein(a, b) {
5136
+ if (a === b) return 0;
5137
+ if (a.length === 0) return b.length;
5138
+ if (b.length === 0) return a.length;
5139
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
5140
+ for (let i = 1; i <= a.length; i++) {
5141
+ const curr = [i];
5142
+ for (let j = 1; j <= b.length; j++) {
5143
+ curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
5144
+ }
5145
+ prev = curr;
5146
+ }
5147
+ return prev[b.length];
5148
+ }
5149
+ function suggestSimilar(input, candidates) {
5150
+ const lower = input.toLowerCase();
5151
+ if (lower === "") return [];
5152
+ const scored = [];
5153
+ for (const cand of candidates) {
5154
+ const c = cand.toLowerCase();
5155
+ if (cand === input) continue;
5156
+ if (c.startsWith(lower)) {
5157
+ scored.push({ name: cand, score: 0, lenDiff: Math.abs(cand.length - input.length) });
5158
+ } else if (lower.length >= 3) {
5159
+ const d = levenshtein(lower, c);
5160
+ if (d <= 2) scored.push({ name: cand, score: d, lenDiff: Math.abs(cand.length - input.length) });
5161
+ }
5162
+ }
5163
+ scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
5164
+ return scored.slice(0, 3).map((s) => s.name);
5157
5165
  }
5158
5166
 
5159
- // src/process-probe.ts
5160
- import { spawnSync as spawnSync3 } from "child_process";
5161
- import fs6 from "fs";
5162
- var PS_TIMEOUT_MS = 5e3;
5163
- var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
5164
- function probeProcess(pid) {
5165
- if (!pid) return NOT_RUNNING;
5166
- try {
5167
- const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
5168
- encoding: "utf8",
5169
- timeout: PS_TIMEOUT_MS
5167
+ // src/commands/help.ts
5168
+ function printShortHelp() {
5169
+ console.log(`
5170
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo-cli help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
5171
+ `);
5172
+ const steps = [];
5173
+ if (!hasKernel()) steps.push(["mihomo-cli kernel", "\u4E0B\u8F7D\u5185\u6838"]);
5174
+ if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
5175
+ if (!isServiceInstalled()) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
5176
+ if (steps.length > 0) {
5177
+ steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
5178
+ const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
5179
+ console.log("\u5F00\u59CB\u4F7F\u7528:");
5180
+ steps.forEach(([cmd, desc], i) => {
5181
+ console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
5170
5182
  });
5171
- const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
5172
- if (!match) return NOT_RUNNING;
5173
- return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
5174
- } catch {
5175
- return NOT_RUNNING;
5183
+ console.log("");
5184
+ return;
5176
5185
  }
5186
+ console.log(
5187
+ `\u5E38\u7528\u547D\u4EE4:
5188
+ ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
5189
+ ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
5190
+ ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
5191
+ ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
5192
+ `
5193
+ );
5177
5194
  }
5178
- function isProbedMihomo(p) {
5179
- return p.alive && (p.command.includes(PATHS.mihomoBinary) || p.command.includes(PATHS.serviceBinary));
5180
- }
5181
- var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
5182
- var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
5183
- function getPid() {
5184
- if (!fs6.existsSync(PATHS.pidFile)) return null;
5185
- try {
5186
- const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5187
- return pid > 0 ? pid : null;
5188
- } catch {
5189
- return null;
5195
+ var GROUP_TITLES = [
5196
+ ["control", "\u63A7\u5236:"],
5197
+ ["interface", "\u754C\u9762:"],
5198
+ ["subscription", "\u8BA2\u9605:"],
5199
+ ["config", "\u914D\u7F6E:"],
5200
+ ["system", "\u7CFB\u7EDF:"]
5201
+ ];
5202
+ function printHelp(commands) {
5203
+ const lines = [`
5204
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mh", "", "\u7528\u6CD5:", " mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"];
5205
+ const allUsage = commands.flatMap((c) => c.usage);
5206
+ const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
5207
+ const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
5208
+ for (const [group, title] of GROUP_TITLES) {
5209
+ const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
5210
+ if (usageLines.length === 0) continue;
5211
+ lines.push("", colors.cyan(title));
5212
+ for (const u of usageLines) lines.push(formatUsage(u));
5190
5213
  }
5214
+ const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
5215
+ if (meta.length > 0) {
5216
+ lines.push("", colors.cyan("\u5143:"));
5217
+ for (const u of meta) lines.push(formatUsage(u));
5218
+ }
5219
+ lines.push(
5220
+ "",
5221
+ `${colors.cyan("\u793A\u4F8B:")}`,
5222
+ // 顺序即首次使用的依赖顺序(kernel → 订阅 → 服务 → 启动):install 在无内核时会被
5223
+ // 拦下提示先跑 kernel,示例若把 install 放第一条,照着敲的新用户第一步就撞墙
5224
+ " mihomo-cli kernel # \u4E0B\u8F7D\u5185\u6838\uFF08\u9996\u6B21\u4F7F\u7528\u7684\u7B2C\u4E00\u6B65\uFF09",
5225
+ " mihomo-cli sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
5226
+ " mihomo-cli install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
5227
+ " mihomo-cli start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
5228
+ " mihomo-cli stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
5229
+ " mihomo-cli start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
5230
+ " mihomo-cli start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
5231
+ " mihomo-cli ui # \u6253\u5F00 Web UI",
5232
+ "",
5233
+ `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
5234
+ " tun = start tun",
5235
+ " use <name> = subscription use <name>",
5236
+ " restart = start\uFF08start \u672C\u8EAB\u5373\u91CD\u542F\uFF09",
5237
+ "",
5238
+ `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
5239
+ " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
5240
+ " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
5241
+ "",
5242
+ `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
5243
+ " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
5244
+ ` \u9ED8\u8BA4: ${USER_DATA_DIR}`
5245
+ );
5246
+ console.log(lines.join("\n"));
5191
5247
  }
5192
- function isRunning() {
5193
- const pid = getPid();
5194
- if (!pid) return false;
5195
- return isMihomoProcess(pid);
5196
- }
5197
- function isMihomoProcess(pid) {
5198
- return isProbedMihomo(probeProcess(pid));
5248
+ function printCommandHelp(command) {
5249
+ const aliasText = command.aliases.length > 0 ? colors.gray(`\uFF08\u522B\u540D: ${command.aliases.join(", ")}\uFF09`) : "";
5250
+ const lines = ["", `${colors.cyan(colors.bold(`mihomo-cli ${command.name}`))}${aliasText}`];
5251
+ if (command.usage.length > 0) {
5252
+ lines.push("", "\u7528\u6CD5:");
5253
+ const width = Math.max(...command.usage.map((u) => displayWidth(u.signature)));
5254
+ for (const u of command.usage) {
5255
+ lines.push(` ${colors.bold(padEndDisplay(u.signature, width))} ${u.description}`);
5256
+ }
5257
+ } else {
5258
+ lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo-cli help"));
5259
+ }
5260
+ console.log(lines.join("\n"));
5199
5261
  }
5200
- function getMihomoPids() {
5201
- const result = spawnSync3("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5202
- if (result.error || result.status === null) {
5203
- throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5204
- hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
5205
- });
5262
+ function printHelpEntry(args, commands, finder) {
5263
+ const token = args[1];
5264
+ if (!token) {
5265
+ printHelp(commands);
5266
+ return;
5206
5267
  }
5207
- if (result.status !== 0 && result.status !== 1) {
5208
- throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
5209
- hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
5268
+ const command = finder(token.toLowerCase());
5269
+ if (!command) {
5270
+ const suggestion = suggestSimilar(
5271
+ token,
5272
+ commands.flatMap((c) => [c.name, ...c.aliases])
5273
+ );
5274
+ throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
5275
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
5210
5276
  });
5211
5277
  }
5212
- return parsePidList(result.stdout);
5278
+ printCommandHelp(command);
5213
5279
  }
5214
- function parsePidList(stdout) {
5215
- const output = stdout.trim();
5216
- if (!output) return [];
5217
- return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5280
+ function printVersion() {
5281
+ const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
5282
+ console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
5283
+ console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
5284
+ console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
5218
5285
  }
5219
- function isPidFileOwnedByRoot() {
5220
- if (!fs6.existsSync(PATHS.pidFile)) return false;
5221
- try {
5222
- const stat = fs6.statSync(PATHS.pidFile);
5223
- return stat.uid === 0;
5224
- } catch {
5225
- return false;
5286
+
5287
+ // src/redact.ts
5288
+ var SECRET_KEYS = /* @__PURE__ */ new Set(["password", "uuid", "private-key", "pre-shared-key", "auth-str", "auth", "obfs-password", "token", "secret"]);
5289
+ var URL_PROVIDER_KEYS = /* @__PURE__ */ new Set(["proxy-providers", "rule-providers"]);
5290
+ function walk(node, withinProvider, state) {
5291
+ if (Array.isArray(node)) {
5292
+ return node.map((item) => walk(item, withinProvider, state));
5226
5293
  }
5294
+ if (node !== null && typeof node === "object") {
5295
+ const out = {};
5296
+ for (const [key, value] of Object.entries(node)) {
5297
+ const assign = (v) => {
5298
+ if (key === "__proto__") {
5299
+ Object.defineProperty(out, key, { value: v, enumerable: true, writable: true, configurable: true });
5300
+ } else {
5301
+ out[key] = v;
5302
+ }
5303
+ };
5304
+ if (typeof value === "string" && SECRET_KEYS.has(key.toLowerCase())) {
5305
+ assign("***");
5306
+ state.changed = true;
5307
+ } else if (typeof value === "string" && withinProvider && key === "url") {
5308
+ const masked = maskUrl(value);
5309
+ assign(masked);
5310
+ if (masked !== value) state.changed = true;
5311
+ } else {
5312
+ assign(walk(value, withinProvider || URL_PROVIDER_KEYS.has(key), state));
5313
+ }
5314
+ }
5315
+ return out;
5316
+ }
5317
+ return node;
5318
+ }
5319
+ function redactConfigSecrets(config) {
5320
+ const state = { changed: false };
5321
+ return { config: walk(config, false, state), changed: state.changed };
5227
5322
  }
5228
- function getStatus() {
5229
- const pid = getPid();
5230
- if (!pid) return { running: false, pid: null, memory: null };
5231
- const p = probeProcess(pid);
5232
- if (!isProbedMihomo(p)) return { running: false, pid: null, memory: null };
5233
- return {
5234
- running: true,
5235
- pid,
5236
- memory: p.rss ? `${(p.rss / 1024).toFixed(1)} MB` : "\u672A\u77E5"
5237
- };
5238
- }
5239
5323
 
5240
- // src/proxy-probe.ts
5241
- var execFileAsync = promisify2(execFile2);
5242
- function lsofListenPids(port) {
5324
+ // src/http.ts
5325
+ var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
5326
+ var MAX_REDIRECTS = 20;
5327
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
5328
+ var MAX_ERROR_BODY_BYTES = 64 * 1024;
5329
+ function isHttpsUrl(url) {
5243
5330
  try {
5244
- const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5245
- if (r.status !== 0) return null;
5246
- return parsePidList(r.stdout);
5331
+ return new URL(url).protocol === "https:";
5247
5332
  } catch {
5248
- return null;
5333
+ return false;
5249
5334
  }
5250
5335
  }
5251
- var PROBE_URL = "https://www.gstatic.com/generate_204";
5252
- function isProbeSuccessStatus(code) {
5253
- return code !== null && code >= 200 && code < 300;
5336
+ function createHttpError(status, bodyText) {
5337
+ const error = new Error(`HTTP ${status}`);
5338
+ error.response = { status };
5339
+ try {
5340
+ error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
5341
+ } catch {
5342
+ }
5343
+ return error;
5254
5344
  }
5255
- var PROBE_TIMEOUT_MS = 2e3;
5256
- async function probeProxyConnectivity(port) {
5257
- const start = Date.now();
5345
+ function createHttpClient(options = {}) {
5346
+ const { timeout = 6e4 } = options;
5347
+ return {
5348
+ async get(url, config) {
5349
+ const controller = new AbortController();
5350
+ const timer = setTimeout(() => controller.abort(), timeout);
5351
+ const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
5352
+ try {
5353
+ let currentUrl = url;
5354
+ let response;
5355
+ for (let hop = 0; ; hop++) {
5356
+ response = await fetch(currentUrl, {
5357
+ signal,
5358
+ redirect: "manual",
5359
+ headers: { "User-Agent": `mihomo-cli/${VERSION}` }
5360
+ });
5361
+ if (!REDIRECT_STATUSES.has(response.status)) break;
5362
+ if (hop >= MAX_REDIRECTS) {
5363
+ throw new Error(`\u91CD\u5B9A\u5411\u6B21\u6570\u8D85\u8FC7 ${MAX_REDIRECTS}\uFF0C\u5DF2\u4E2D\u6B62: ${maskUrl(url)}`);
5364
+ }
5365
+ const location = response.headers.get("location");
5366
+ if (!location) break;
5367
+ const nextUrl = new URL(location, currentUrl).toString();
5368
+ if (isHttpsUrl(url) && !isHttpsUrl(nextUrl)) {
5369
+ throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(nextUrl)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
5370
+ }
5371
+ await response.body?.cancel().catch(() => void 0);
5372
+ currentUrl = nextUrl;
5373
+ }
5374
+ if (!response.ok) {
5375
+ let text2 = "";
5376
+ try {
5377
+ text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
5378
+ } catch {
5379
+ }
5380
+ throw createHttpError(response.status, text2);
5381
+ }
5382
+ const declaredLen = Number(response.headers.get("content-length"));
5383
+ if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
5384
+ throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
5385
+ }
5386
+ const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
5387
+ const data = config?.responseType === "json" ? JSON.parse(text) : text;
5388
+ return { data, headers: response.headers };
5389
+ } catch (e) {
5390
+ if (controller.signal.aborted && e.name === "AbortError") {
5391
+ throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
5392
+ }
5393
+ throw e;
5394
+ } finally {
5395
+ clearTimeout(timer);
5396
+ }
5397
+ }
5398
+ };
5399
+ }
5400
+ async function readBodyWithLimit(response, controller, limit) {
5401
+ if (!response.body) return response.text();
5402
+ const reader = response.body.getReader();
5403
+ const chunks = [];
5404
+ let total = 0;
5258
5405
  try {
5259
- const { stdout } = await execFileAsync(
5260
- "curl",
5261
- ["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
5262
- {
5263
- timeout: PROBE_TIMEOUT_MS + 2e3,
5264
- // 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
5265
- env: buildCurlSpawnEnv()
5406
+ while (true) {
5407
+ const { done, value } = await reader.read();
5408
+ if (done) break;
5409
+ if (value) {
5410
+ total += value.byteLength;
5411
+ if (total > limit) {
5412
+ controller.abort();
5413
+ throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
5414
+ }
5415
+ chunks.push(value);
5266
5416
  }
5267
- );
5268
- const code = Number.parseInt(stdout.trim(), 10);
5269
- const statusCode = Number.isFinite(code) ? code : null;
5270
- const ok = isProbeSuccessStatus(statusCode);
5271
- return {
5272
- ok,
5273
- statusCode,
5274
- error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
5275
- durationMs: Date.now() - start
5276
- };
5277
- } catch (e) {
5278
- const err = e;
5279
- const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
5280
- return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
5417
+ }
5418
+ } finally {
5419
+ reader.releaseLock();
5281
5420
  }
5421
+ return Buffer.concat(chunks).toString("utf8");
5282
5422
  }
5283
5423
 
5284
- // src/stop-epoch.ts
5285
- import fs7 from "fs";
5286
- function readStopEpoch() {
5424
+ // src/spinner.ts
5425
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
5426
+ var INTERVAL_MS = 80;
5427
+ async function withSpinner(label, fn) {
5428
+ if (!process.stdout.isTTY) {
5429
+ console.log(label);
5430
+ return fn();
5431
+ }
5432
+ const start = Date.now();
5433
+ let frame = 0;
5434
+ const render = () => {
5435
+ const secs = ((Date.now() - start) / 1e3).toFixed(0);
5436
+ process.stdout.write(`\r${colors.cyan(FRAMES[frame])} ${label} ${colors.gray(`${secs}s`)}\x1B[K`);
5437
+ frame = (frame + 1) % FRAMES.length;
5438
+ };
5439
+ render();
5440
+ const timer = setInterval(render, INTERVAL_MS);
5287
5441
  try {
5288
- const n = Number.parseInt(fs7.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5289
- return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5290
- } catch {
5291
- return 0;
5442
+ return await fn();
5443
+ } finally {
5444
+ clearInterval(timer);
5445
+ process.stdout.write("\r\x1B[K");
5292
5446
  }
5293
5447
  }
5294
- var stopEpochBaselineCaptured = null;
5295
- function captureStopEpochBaseline() {
5296
- stopEpochBaselineCaptured = readStopEpoch();
5297
- return stopEpochBaselineCaptured;
5448
+
5449
+ // src/subscription.ts
5450
+ function resolveUpdateInterval(cachedInterval) {
5451
+ return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
5298
5452
  }
5299
- function stopEpochBaseline() {
5300
- return stopEpochBaselineCaptured ?? readStopEpoch();
5453
+ function isSubscriptionStale(cached, nowMs = Date.now()) {
5454
+ if (!cached.updated_at) return false;
5455
+ const t = new Date(cached.updated_at).getTime();
5456
+ if (Number.isNaN(t) || t > nowMs) return false;
5457
+ const ageHours = (nowMs - t) / 36e5;
5458
+ return ageHours > resolveUpdateInterval(cached.update_interval);
5301
5459
  }
5302
- function bumpStopEpoch() {
5460
+ var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
5461
+ function isValidHttpUrl(url) {
5303
5462
  try {
5304
- ensureDirs();
5305
- atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
5463
+ const u = new URL(url.trim());
5464
+ return u.protocol === "http:" || u.protocol === "https:";
5306
5465
  } catch {
5466
+ return false;
5307
5467
  }
5308
5468
  }
5309
- function recordServiceStopped() {
5310
- bumpStopEpoch();
5311
- }
5312
- function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5313
- return stopEpochNow !== stopEpochBefore;
5469
+ function parseUserInfo(header) {
5470
+ if (!header) return null;
5471
+ const info = {};
5472
+ let hasAny = false;
5473
+ for (const part of header.split(";")) {
5474
+ const [rawKey, rawVal] = part.split("=");
5475
+ const key = rawKey?.trim();
5476
+ const val = rawVal?.trim();
5477
+ if (!key || val === void 0 || val === "") continue;
5478
+ const numVal = Number(val);
5479
+ if (!Number.isFinite(numVal) || numVal < 0) continue;
5480
+ info[key] = numVal;
5481
+ hasAny = true;
5482
+ }
5483
+ return hasAny ? info : null;
5314
5484
  }
5315
- function startAbortedByConcurrentStop() {
5316
- return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
5485
+ function parsePositiveInterval(header) {
5486
+ if (!header) return null;
5487
+ const n = parseInt(header, 10);
5488
+ return Number.isFinite(n) && n > 0 ? n : null;
5317
5489
  }
5318
-
5319
- // src/hot-reload.ts
5320
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
5321
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5322
- function logOversized() {
5323
- try {
5324
- return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5325
- } catch {
5326
- return false;
5327
- }
5490
+ function parseUsernameFromContentDisposition(header) {
5491
+ if (!header) return null;
5492
+ const match = header.match(/filename\s*=\s*["']?([^"';\s]+)["']?/i);
5493
+ if (!match) return null;
5494
+ const filename = match[1];
5495
+ const parts = filename.split("/");
5496
+ return parts[parts.length - 1] || null;
5328
5497
  }
5329
- async function tryHotReload(prefetched) {
5330
- const controller = new AbortController();
5331
- try {
5332
- const status = prefetched ?? getServiceStatus({ withDisabled: false });
5333
- if (!status.running || status.pid === null) return false;
5334
- const endpoint = getControllerEndpoint();
5335
- if (endpoint.port === null) return false;
5336
- const baseUrl = `http://127.0.0.1:${endpoint.port}`;
5337
- const headers = { "Content-Type": "application/json" };
5338
- if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
5339
- const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
5340
- try {
5341
- const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
5342
- if (!probe.ok) return false;
5343
- const info = await probe.json();
5344
- if (typeof info?.version !== "string") return false;
5345
- const listenerPids = lsofListenPids(endpoint.port);
5346
- if (listenerPids === null || listenerPids[0] !== status.pid) return false;
5347
- const res = await fetch(`${baseUrl}/configs?force=true`, {
5348
- method: "PUT",
5349
- headers,
5350
- body: "{}",
5351
- signal: controller.signal
5352
- });
5353
- return res.ok;
5354
- } finally {
5355
- clearTimeout(timer);
5356
- }
5357
- } catch {
5358
- return false;
5498
+ function extractSubscriptionMeta(headers) {
5499
+ return {
5500
+ userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
5501
+ updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
5502
+ // 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
5503
+ webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
5504
+ username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
5505
+ };
5506
+ }
5507
+ function saveSubscriptionMeta(subName, meta) {
5508
+ const cacheData = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
5509
+ if (meta.userInfo) {
5510
+ const { upload, download, total, expire } = meta.userInfo;
5511
+ if (upload !== void 0) cacheData.upload = upload;
5512
+ if (download !== void 0) cacheData.download = download;
5513
+ if (total !== void 0) cacheData.total = total;
5514
+ if (expire !== void 0) cacheData.expire = expire;
5359
5515
  }
5516
+ if (meta.updateInterval) cacheData.update_interval = meta.updateInterval;
5517
+ if (meta.webPageUrl) cacheData.web_page_url = meta.webPageUrl;
5518
+ if (meta.username) cacheData.username = meta.username;
5519
+ saveSubscriptionCache(subName, cacheData);
5360
5520
  }
5361
- function concludeHotReload(stopEpochBefore, stopEpochNow) {
5362
- return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5521
+ function formatProxySummary(info) {
5522
+ const parts = [];
5523
+ if (info.proxyGroups && info.proxyGroups > 0) parts.push(`${info.proxyGroups} \u7EC4`);
5524
+ parts.push(`${info.proxies || 0} \u8282\u70B9`);
5525
+ return parts.join(", ");
5363
5526
  }
5364
-
5365
- // src/log-files.ts
5366
- import fs9 from "fs";
5367
- import path5 from "path";
5368
- var DEFAULT_LOG_RETENTION_DAYS = 7;
5369
- var LOG_TAIL_LINES = 15;
5370
- var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5371
- function isArchiveLogFilename(filename) {
5372
- return ARCHIVE_LOG_RE.test(filename);
5527
+ function getActiveSubscription() {
5528
+ const settings = readSettings();
5529
+ const subs = getSubscriptions(settings);
5530
+ if (subs.length === 0) return null;
5531
+ const activeName = settings.active_subscription;
5532
+ if (activeName) {
5533
+ const found = subs.find((s) => s.name === activeName);
5534
+ if (found) return found;
5535
+ }
5536
+ return subs[0];
5373
5537
  }
5374
- function rotateAndCleanupLogs() {
5375
- rotateLog();
5376
- cleanupOldLogs();
5538
+ function noSubscriptionsError() {
5539
+ return new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
5377
5540
  }
5378
- function readLogTail() {
5379
- const TAIL_BYTES = 64 * 1024;
5380
- let fd = null;
5381
- try {
5382
- const size = fs9.statSync(PATHS.logFile).size;
5383
- if (size === 0) return [];
5384
- const start = Math.max(0, size - TAIL_BYTES);
5385
- const length = size - start;
5386
- const buf = Buffer.alloc(length);
5387
- fd = fs9.openSync(PATHS.logFile, "r");
5388
- const bytesRead = fs9.readSync(fd, buf, 0, length, start);
5389
- return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5390
- } catch {
5391
- return [];
5392
- } finally {
5393
- if (fd !== null) {
5394
- try {
5395
- fs9.closeSync(fd);
5396
- } catch {
5397
- }
5398
- }
5541
+ function requireActiveSubscription() {
5542
+ const sub = getActiveSubscription();
5543
+ if (!sub) {
5544
+ throw noSubscriptionsError();
5399
5545
  }
5546
+ return sub;
5400
5547
  }
5401
- var MAX_ARCHIVE_SEQ = 1e3;
5402
- function allocateArchivePath() {
5403
- const timestamp = formatLocalTimestamp();
5404
- for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5405
- const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5406
- const archivePath = path5.join(DIRS.logs, name);
5407
- let fd = null;
5408
- try {
5409
- fd = fs9.openSync(archivePath, "wx");
5410
- } catch (e) {
5411
- if (e.code === "EEXIST") continue;
5412
- throw e;
5413
- }
5414
- try {
5415
- fs9.closeSync(fd);
5416
- } catch {
5548
+ function resolveSubscription(subs, pattern) {
5549
+ const lowerPattern = pattern.toLowerCase();
5550
+ const exact = [];
5551
+ const prefix = [];
5552
+ const includes = [];
5553
+ for (const s of subs) {
5554
+ const name = s.name.toLowerCase();
5555
+ if (name === lowerPattern) {
5556
+ exact.push(s);
5557
+ } else if (name.startsWith(lowerPattern)) {
5558
+ prefix.push(s);
5559
+ } else if (name.includes(lowerPattern)) {
5560
+ includes.push(s);
5417
5561
  }
5418
- return archivePath;
5419
5562
  }
5420
- throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
5421
- label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5422
- hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
5563
+ const matched = exact.length > 0 ? exact : prefix.length > 0 ? prefix : includes;
5564
+ if (matched.length === 0) {
5565
+ throw new CliError(`\u672A\u627E\u5230\u5339\u914D "${pattern}" \u7684\u8BA2\u9605`);
5566
+ }
5567
+ if (matched.length === 1) return matched[0];
5568
+ throw new CliError("\u5339\u914D\u5230\u591A\u4E2A\u8BA2\u9605\uFF0C\u8BF7\u66F4\u7CBE\u786E\u6307\u5B9A", {
5569
+ hint: ["", "\u5339\u914D\u7684\u8BA2\u9605:", ...matched.map((s) => ` ${s.name}`)]
5423
5570
  });
5424
5571
  }
5425
- function rotateLog() {
5426
- const logFile = PATHS.logFile;
5427
- let stat;
5572
+ function assertLooksLikeSubscription(parsed, maskedUrl) {
5573
+ const hasProxies = Array.isArray(parsed.proxies) && parsed.proxies.length > 0;
5574
+ const hasGroups = Array.isArray(parsed["proxy-groups"]) && parsed["proxy-groups"].length > 0;
5575
+ const providers = parsed["proxy-providers"];
5576
+ const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
5577
+ if (hasProxies || hasGroups || hasProviders) return;
5578
+ const serverMsg = sanitizeTerminal(
5579
+ ["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
5580
+ );
5581
+ throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
5582
+ label: "\u8BA2\u9605\u65E0\u6548",
5583
+ hint: [
5584
+ ...serverMsg ? [`\u670D\u52A1\u7AEF\u8FD4\u56DE: ${serverMsg}`] : [],
5585
+ `URL: ${maskedUrl}`,
5586
+ "\u5E38\u89C1\u539F\u56E0\uFF1A\u8BA2\u9605\u94FE\u63A5\u8FC7\u671F\u3001\u6D41\u91CF\u8017\u5C3D\u3001\u9700\u8981\u91CD\u65B0\u83B7\u53D6\u8BA2\u9605\u5730\u5740\u3002",
5587
+ "\u78C1\u76D8\u4E0A\u539F\u6709\u7684\u8BA2\u9605\u914D\u7F6E\u672A\u88AB\u8986\u76D6\u3002"
5588
+ ]
5589
+ });
5590
+ }
5591
+ async function downloadSubscription(url, subName, signal) {
5592
+ let response;
5428
5593
  try {
5429
- stat = fs9.statSync(logFile);
5594
+ response = await HTTP_CLIENT.get(url, { responseType: "text", signal });
5430
5595
  } catch (e) {
5431
- if (e.code === "ENOENT") return;
5432
- throw e;
5596
+ const maskedUrl = maskUrl(url);
5597
+ let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
5598
+ const err = e;
5599
+ if (err.response) {
5600
+ errorMsg += ` (HTTP ${err.response.status})`;
5601
+ }
5602
+ errorMsg += `
5603
+ URL: ${maskedUrl}`;
5604
+ throw new Error(errorMsg);
5433
5605
  }
5434
- if (stat.size === 0) return;
5435
- const rotatedPath = allocateArchivePath();
5606
+ const content = response.data;
5607
+ if (!content?.trim()) {
5608
+ throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
5609
+ }
5610
+ const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
5611
+ assertLooksLikeSubscription(parsed, maskUrl(url));
5612
+ saveSubscriptionRawConfig(subName, content);
5613
+ const meta = extractSubscriptionMeta(response.headers);
5436
5614
  try {
5437
- fs9.renameSync(logFile, rotatedPath);
5615
+ saveSubscriptionMeta(subName, meta);
5438
5616
  } catch (e) {
5439
5617
  try {
5440
- fs9.unlinkSync(rotatedPath);
5618
+ removeSubscriptionRawConfig(subName);
5441
5619
  } catch {
5442
5620
  }
5443
- if (e.code === "ENOENT") return;
5444
- throw e;
5621
+ throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
5622
+ label: "\u66F4\u65B0\u5931\u8D25",
5623
+ // 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
5624
+ // 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
5625
+ hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
5626
+ });
5445
5627
  }
5628
+ const { proxies, proxyGroups } = countConfigNodes(parsed);
5629
+ return { proxies, proxyGroups };
5446
5630
  }
5447
- function cleanupOldLogs() {
5448
- const logsDir = DIRS.logs;
5449
- if (!fs9.existsSync(logsDir)) return;
5450
- const files = fs9.readdirSync(logsDir);
5451
- const now = Date.now();
5452
- const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5453
- for (const file of files) {
5454
- if (!isArchiveLogFilename(file)) continue;
5455
- try {
5456
- const filePath = path5.join(logsDir, file);
5457
- const stat = fs9.statSync(filePath);
5458
- if (now - stat.mtimeMs > maxAgeMs) {
5459
- fs9.unlinkSync(filePath);
5460
- }
5461
- } catch {
5631
+ async function prepareConfigForStart(mode, subName) {
5632
+ let rawContent;
5633
+ try {
5634
+ rawContent = requireSubscriptionRawConfig(subName);
5635
+ } catch (e) {
5636
+ if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
5637
+ throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
5638
+ hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
5639
+ });
5462
5640
  }
5641
+ throw e;
5463
5642
  }
5643
+ const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
5644
+ const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
5645
+ await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
5646
+ return {
5647
+ buildResult,
5648
+ info: countConfigNodes(buildResult.config)
5649
+ };
5464
5650
  }
5465
- function listLogs() {
5466
- const logsDir = DIRS.logs;
5467
- const result = { current: null, archives: [] };
5468
- if (fs9.existsSync(PATHS.logFile)) {
5469
- const stat = fs9.statSync(PATHS.logFile);
5470
- result.current = {
5471
- name: "mihomo.log (\u5F53\u524D)",
5472
- path: PATHS.logFile,
5473
- size: stat.size,
5474
- mtime: stat.mtime,
5475
- isCurrent: true
5476
- };
5477
- }
5478
- if (!fs9.existsSync(logsDir)) return result;
5479
- const files = fs9.readdirSync(logsDir);
5480
- for (const file of files) {
5481
- if (!isArchiveLogFilename(file)) continue;
5482
- try {
5483
- const filePath = path5.join(logsDir, file);
5484
- const stat = fs9.statSync(filePath);
5485
- result.archives.push({
5486
- name: file,
5487
- path: filePath,
5488
- size: stat.size,
5489
- mtime: stat.mtime,
5490
- isCurrent: false
5491
- });
5492
- } catch {
5651
+ function commitPreparedConfig(prepared) {
5652
+ const { buildResult } = prepared;
5653
+ if (buildResult.warnings.length > 0) {
5654
+ for (const warning of buildResult.warnings) {
5655
+ console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
5493
5656
  }
5657
+ console.log("");
5494
5658
  }
5495
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5496
- return result;
5659
+ writeMihomoConfig(buildResult.config);
5660
+ return prepared.info;
5497
5661
  }
5498
-
5499
- // src/process-stop.ts
5500
- import { spawnSync as spawnSync6 } from "child_process";
5501
- import fs11 from "fs";
5502
-
5503
- // src/sudo.ts
5504
- import { spawnSync as spawnSync5 } from "child_process";
5505
- import fs10 from "fs";
5506
- import path6 from "path";
5507
- var SUDO_TIMEOUT_MS = 6e4;
5508
- var SudoAuthError = class extends Error {
5509
- constructor() {
5510
- super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
5511
- this.name = "SudoAuthError";
5512
- }
5513
- };
5514
- function describeSudoFailure(e) {
5515
- return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
5662
+ function needsAutoUpdate(sub) {
5663
+ if (!sub.updated_at) return true;
5664
+ const lastUpdate = new Date(sub.updated_at).getTime();
5665
+ if (Number.isNaN(lastUpdate)) return true;
5666
+ if (lastUpdate > Date.now()) return true;
5667
+ const intervalHours = resolveUpdateInterval(sub.update_interval);
5668
+ const intervalMs = intervalHours * 60 * 60 * 1e3;
5669
+ return Date.now() - lastUpdate > intervalMs;
5516
5670
  }
5517
- function sudoExitToError(action, status, codeMessages) {
5518
- if (status === 1) return new SudoAuthError();
5519
- if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
5520
- const custom = codeMessages?.[status];
5521
- return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
5671
+ async function tryUpdateOne(sub, signal) {
5672
+ try {
5673
+ const info = await downloadSubscription(sub.url, sub.name, signal);
5674
+ return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
5675
+ } catch (e) {
5676
+ return { name: sub.name, success: false, aborted: signal?.aborted === true, error: e.message };
5677
+ }
5522
5678
  }
5523
- function sudoTimeoutError(action) {
5524
- return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
5679
+ function printUpdateResult(r) {
5680
+ if (r.success) {
5681
+ console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
5682
+ } else if (r.aborted) {
5683
+ console.log(`${colors.gray("\xB7")} ${r.name}: ${colors.gray("\u8DF3\u8FC7\uFF08\u66F4\u65B0\u8D85\u65F6\uFF0C\u4F7F\u7528\u672C\u5730\u7F13\u5B58\uFF09")}`);
5684
+ } else {
5685
+ console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${firstLine(r.error || "")})`);
5686
+ }
5525
5687
  }
5526
- function runSudoScript(scriptBody, opts) {
5527
- if (!process.stdin.isTTY) {
5528
- throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
5688
+ async function autoUpdateStaleSubscription(options = {}) {
5689
+ const allSubs = getSubscriptionsWithCache();
5690
+ const staleSubs = allSubs.filter(needsAutoUpdate);
5691
+ if (staleSubs.length === 0) {
5692
+ return;
5529
5693
  }
5530
- ensureDirs();
5531
- const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
5532
- fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5533
- fs10.chmodSync(scriptPath, 448);
5694
+ if (staleSubs.length === 1) {
5695
+ const sub = staleSubs[0];
5696
+ const interval = resolveUpdateInterval(sub.update_interval);
5697
+ console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
5698
+ } else {
5699
+ console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
5700
+ }
5701
+ const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
5702
+ const controller = new AbortController();
5703
+ const results = [];
5704
+ const updatePromise = Promise.all(
5705
+ staleSubs.map(
5706
+ (sub) => tryUpdateOne(sub, controller.signal).then((r) => {
5707
+ results.push(r);
5708
+ return r;
5709
+ })
5710
+ )
5711
+ );
5534
5712
  try {
5535
- const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5536
- if (result.error) {
5537
- if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
5538
- throw result.error;
5539
- }
5540
- if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
5541
- } finally {
5542
- try {
5543
- fs10.unlinkSync(scriptPath);
5544
- } catch {
5545
- }
5713
+ await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
5714
+ } catch (e) {
5715
+ if (!(e instanceof TimeoutError)) throw e;
5716
+ controller.abort();
5717
+ await updatePromise.catch(() => {
5718
+ });
5719
+ console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
5720
+ }
5721
+ for (const r of results) {
5722
+ printUpdateResult(r);
5546
5723
  }
5547
5724
  }
5548
5725
 
5549
- // src/process-stop.ts
5550
- var PROCESS_WAIT_ATTEMPTS = 50;
5551
- var PROCESS_WAIT_INTERVAL = 100;
5552
- var BATCH_KILL_THRESHOLD = 3;
5553
- function clearRuntime() {
5554
- if (fs11.existsSync(DIRS.runtime)) {
5555
- rmrf(DIRS.runtime);
5726
+ // src/commands/config.ts
5727
+ function cmdConfig(args = []) {
5728
+ assertKnownFlags(args.slice(1), ["-j", "--json", "--reveal"], "config [--json] [--reveal]");
5729
+ assertPositionalCount(args, 0, 1, "mihomo-cli config [--json] [--reveal]");
5730
+ const asJson = hasFlag(args, "-j", "--json");
5731
+ const reveal = hasFlag(args, "--reveal");
5732
+ const active = getActiveSubscription();
5733
+ if (!active) {
5734
+ throw noSubscriptionsError();
5735
+ }
5736
+ const rawContent = requireSubscriptionRawConfig(active.name);
5737
+ const mode = deriveRuntimeMode(getConfigInfo());
5738
+ const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
5739
+ const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
5740
+ const shown = redacted.config;
5741
+ if (asJson) {
5742
+ console.log(JSON.stringify({ config: shown, warnings, redacted: !reveal && redacted.changed }, null, 2));
5743
+ return;
5744
+ }
5745
+ console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
5746
+ console.log(colors.gray("# \u914D\u7F6E\u9884\u89C8\uFF1A\u672A\u5199\u76D8\u3001\u672A\u6821\u9A8C\u3001\u672A\u5E94\u7528"));
5747
+ if (!reveal && redacted.changed) {
5748
+ console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
5749
+ }
5750
+ console.log("");
5751
+ console.log(dumpYaml(shown).trimEnd());
5752
+ if (warnings.length > 0) {
5753
+ console.log("");
5754
+ for (const w of warnings) console.log(colors.yellow(`# ${w}`));
5556
5755
  }
5557
- ensureDirs();
5558
- }
5559
- function describePidCleanupFailure(err) {
5560
- return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
5561
5756
  }
5562
- var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
5563
- function printResidueWarning(remaining) {
5564
- console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
5565
- console.log(MANUAL_PKILL_HINT);
5757
+
5758
+ // src/open.ts
5759
+ import { spawn } from "child_process";
5760
+
5761
+ // src/lifecycle.ts
5762
+ var silentSigint = false;
5763
+ function setSilentSigint(value) {
5764
+ silentSigint = value;
5566
5765
  }
5567
- function warnPidCleanupFailed(err) {
5568
- if (!err) return;
5569
- console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5766
+ function isSilentSigint() {
5767
+ return silentSigint;
5570
5768
  }
5571
- function clearPid() {
5769
+
5770
+ // src/open.ts
5771
+ function openUrl(url) {
5572
5772
  try {
5573
- fs11.unlinkSync(PATHS.pidFile);
5574
- return null;
5575
- } catch (e) {
5576
- if (e.code === "ENOENT") return null;
5577
- return e;
5773
+ const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
5774
+ child.unref();
5775
+ child.on("error", () => {
5776
+ });
5777
+ } catch {
5578
5778
  }
5579
5779
  }
5580
- function pidAlive(pid) {
5581
- try {
5582
- process.kill(pid, 0);
5583
- return true;
5584
- } catch (e) {
5585
- return e.code !== "ESRCH";
5780
+ function viewLogWithTail(logPath, options) {
5781
+ const follow = options?.follow;
5782
+ const lines = options?.lines || 100;
5783
+ console.log(`\u65E5\u5FD7: ${logPath}`);
5784
+ if (follow) {
5785
+ console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5786
+ } else {
5787
+ console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5788
+ `);
5586
5789
  }
5790
+ const tailArgs = [];
5791
+ if (follow) tailArgs.push("-f");
5792
+ tailArgs.push("-n", lines.toString());
5793
+ tailArgs.push(logPath);
5794
+ const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5795
+ if (follow) setSilentSigint(true);
5796
+ tail.on("close", (code) => process.exit(code ?? 0));
5797
+ tail.on("error", (e) => {
5798
+ console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5799
+ process.exit(1);
5800
+ });
5587
5801
  }
5588
- async function waitUntilNoMihomo(pids) {
5589
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
5590
- if (!pids.some(pidAlive)) return;
5591
- await sleep(PROCESS_WAIT_INTERVAL);
5592
- }
5802
+
5803
+ // src/commands/shared.ts
5804
+ import readline from "readline";
5805
+
5806
+ // src/log-files.ts
5807
+ import fs6 from "fs";
5808
+ import path5 from "path";
5809
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
5810
+ var LOG_TAIL_LINES = 15;
5811
+ var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5812
+ function isArchiveLogFilename(filename) {
5813
+ return ARCHIVE_LOG_RE.test(filename);
5593
5814
  }
5594
- function killProcess(pid) {
5595
- try {
5596
- process.kill(pid, "SIGKILL");
5597
- return true;
5598
- } catch {
5599
- return false;
5600
- }
5815
+ function rotateAndCleanupLogs() {
5816
+ rotateLog();
5817
+ cleanupOldLogs();
5601
5818
  }
5602
- function killAllMihomo() {
5819
+ function readLogTail() {
5820
+ const TAIL_BYTES = 64 * 1024;
5821
+ let fd = null;
5603
5822
  try {
5604
- const result = spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
5605
- if (result.error) return false;
5606
- return result.status === 0 || result.status === 1;
5823
+ const size = fs6.statSync(PATHS.logFile).size;
5824
+ if (size === 0) return [];
5825
+ const start = Math.max(0, size - TAIL_BYTES);
5826
+ const length = size - start;
5827
+ const buf = Buffer.alloc(length);
5828
+ fd = fs6.openSync(PATHS.logFile, "r");
5829
+ const bytesRead = fs6.readSync(fd, buf, 0, length, start);
5830
+ return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5607
5831
  } catch {
5608
- return false;
5832
+ return [];
5833
+ } finally {
5834
+ if (fd !== null) {
5835
+ try {
5836
+ fs6.closeSync(fd);
5837
+ } catch {
5838
+ }
5839
+ }
5609
5840
  }
5610
5841
  }
5611
- function buildKernelCleanupScript() {
5612
- return [
5613
- "#!/bin/bash",
5614
- // pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
5615
- `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
5616
- "rc=$?",
5617
- "[ $rc -le 1 ] || exit 2",
5618
- "exit 0",
5619
- ""
5620
- ].join("\n");
5621
- }
5622
- async function cleanupAll() {
5623
- const pids = getMihomoPids();
5624
- if (pids.length === 0) {
5625
- return { killed: 0, failed: 0, remaining: [], scriptError: null, pidError: clearPid() };
5626
- }
5627
- let killedCount = 0;
5628
- const failedPids = [];
5629
- let scriptError = null;
5630
- const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
5631
- const rootPids = pids.filter((pid) => probes.get(pid)?.uid === "0");
5632
- if (rootPids.length > 0) {
5633
- console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
5842
+ var MAX_ARCHIVE_SEQ = 1e3;
5843
+ function allocateArchivePath() {
5844
+ const timestamp = formatLocalTimestamp();
5845
+ for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5846
+ const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5847
+ const archivePath = path5.join(DIRS.logs, name);
5848
+ let fd = null;
5634
5849
  try {
5635
- runSudoScript(buildKernelCleanupScript(), {
5636
- action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B",
5637
- file: "cleanup-residue.sh",
5638
- codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" }
5639
- });
5640
- killedCount = pids.length;
5850
+ fd = fs6.openSync(archivePath, "wx");
5641
5851
  } catch (e) {
5642
- scriptError = e;
5643
- }
5644
- } else if (pids.length > BATCH_KILL_THRESHOLD) {
5645
- if (killAllMihomo()) {
5646
- killedCount = pids.length;
5647
- } else {
5648
- failedPids.push(...pids);
5852
+ if (e.code === "EEXIST") continue;
5853
+ throw e;
5649
5854
  }
5650
- } else {
5651
- for (const pid of pids) {
5652
- const probed = probes.get(pid);
5653
- if (!probed || !isProbedMihomo(probed)) {
5654
- killedCount++;
5655
- continue;
5656
- }
5657
- if (killProcess(pid)) {
5658
- killedCount++;
5659
- } else {
5660
- failedPids.push(pid);
5661
- }
5855
+ try {
5856
+ fs6.closeSync(fd);
5857
+ } catch {
5662
5858
  }
5859
+ return archivePath;
5663
5860
  }
5664
- await waitUntilNoMihomo(pids);
5665
- const remaining = getMihomoPids();
5666
- const pidError = remaining.length === 0 ? clearPid() : null;
5667
- return { killed: killedCount, failed: failedPids.length, remaining, scriptError, pidError };
5668
- }
5669
- function buildRootResidueCleanupError(result, ctx) {
5670
- const { scriptError, pidError } = result;
5671
- const hasKernelResidue = result.remaining.length > 0;
5672
- const pidList = `PID ${result.remaining.join(", ")}`;
5673
- const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
5674
- const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
5675
- hint.push(hasKernelResidue || scriptError ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
5676
- if (scriptError instanceof SudoAuthError) {
5677
- return new CliError(`${describeSudoFailure(scriptError)}\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406`, { label: "\u5DF2\u53D6\u6D88", hint });
5678
- }
5679
- return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
5680
- }
5681
- function classifyResidueCleanup(result) {
5682
- if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
5683
- return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
5684
- }
5685
- function warnResidueCleanup(result, ctx) {
5686
- const err = buildRootResidueCleanupError(result, ctx);
5687
- console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
5688
- for (const line of err.hint) console.warn(colors.gray(line));
5689
- }
5690
- async function cleanupKernelsOrThrow(ctx) {
5691
- const result = await cleanupAll();
5692
- const verdict = classifyResidueCleanup(result);
5693
- if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
5694
- if (verdict === "warn") warnResidueCleanup(result, ctx);
5695
- return result;
5861
+ throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
5862
+ label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5863
+ hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
5864
+ });
5696
5865
  }
5697
- async function stop() {
5698
- const allPids = getMihomoPids();
5699
- if (allPids.length === 0) {
5700
- warnPidCleanupFailed(clearPid());
5701
- clearRuntime();
5702
- return {};
5866
+ function rotateLog() {
5867
+ const logFile = PATHS.logFile;
5868
+ let stat;
5869
+ try {
5870
+ stat = fs6.statSync(logFile);
5871
+ } catch (e) {
5872
+ if (e.code === "ENOENT") return;
5873
+ throw e;
5703
5874
  }
5704
- const result = await cleanupAll();
5705
- if (result.remaining.length === 0) {
5706
- warnPidCleanupFailed(result.pidError);
5707
- if (result.scriptError) {
5708
- console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo-cli stop`));
5875
+ if (stat.size === 0) return;
5876
+ const rotatedPath = allocateArchivePath();
5877
+ try {
5878
+ fs6.renameSync(logFile, rotatedPath);
5879
+ } catch (e) {
5880
+ try {
5881
+ fs6.unlinkSync(rotatedPath);
5882
+ } catch {
5709
5883
  }
5884
+ if (e.code === "ENOENT") return;
5885
+ throw e;
5710
5886
  }
5711
- const remaining = result.remaining;
5712
- if (remaining.length > 0) {
5713
- console.log("");
5714
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
5715
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5716
- console.log(MANUAL_PKILL_HINT);
5717
- console.log("");
5718
- return { remaining };
5719
- }
5720
- clearRuntime();
5721
- return {};
5722
5887
  }
5723
-
5724
- // src/service.ts
5725
- var SERVICE_HEALTH_INTERVAL_MS = 100;
5726
- var SERVICE_OBSERVE_MS = 1200;
5727
- var SERVICE_HEALTH_GRACE_MS = 1800;
5728
- async function waitServiceHealthy() {
5729
- const deadline = Date.now() + SERVICE_OBSERVE_MS;
5730
- const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
5731
- let last = null;
5732
- const unhealthy = (state, crashed, pid = null) => ({
5733
- healthy: false,
5734
- crashed,
5735
- pid,
5736
- exitCode: state.lastExitCode,
5737
- terminatingSignal: state.lastTerminatingSignal
5738
- });
5739
- do {
5740
- await sleep(SERVICE_HEALTH_INTERVAL_MS);
5888
+ function cleanupOldLogs() {
5889
+ const logsDir = DIRS.logs;
5890
+ if (!fs6.existsSync(logsDir)) return;
5891
+ const files = fs6.readdirSync(logsDir);
5892
+ const now = Date.now();
5893
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5894
+ for (const file of files) {
5895
+ if (!isArchiveLogFilename(file)) continue;
5741
5896
  try {
5742
- last = getServiceStatus({ withDisabled: false });
5897
+ const filePath = path5.join(logsDir, file);
5898
+ const stat = fs6.statSync(filePath);
5899
+ if (now - stat.mtimeMs > maxAgeMs) {
5900
+ fs6.unlinkSync(filePath);
5901
+ }
5743
5902
  } catch {
5744
- continue;
5745
- }
5746
- if (isCrashed(last)) {
5747
- return unhealthy(last, true);
5748
- }
5749
- if (!last.loaded) {
5750
- return unhealthy(last, false);
5751
5903
  }
5752
- } while (Date.now() < deadline);
5753
- if (last === null) return healthViaProcessProbe();
5754
- if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
5755
- let graceQueried = false;
5756
- while (Date.now() < graceDeadline) {
5757
- await sleep(SERVICE_HEALTH_INTERVAL_MS);
5904
+ }
5905
+ }
5906
+ function listLogs() {
5907
+ const logsDir = DIRS.logs;
5908
+ const result = { current: null, archives: [] };
5909
+ if (fs6.existsSync(PATHS.logFile)) {
5910
+ const stat = fs6.statSync(PATHS.logFile);
5911
+ result.current = {
5912
+ name: "mihomo.log (\u5F53\u524D)",
5913
+ path: PATHS.logFile,
5914
+ size: stat.size,
5915
+ mtime: stat.mtime,
5916
+ isCurrent: true
5917
+ };
5918
+ }
5919
+ if (!fs6.existsSync(logsDir)) return result;
5920
+ const files = fs6.readdirSync(logsDir);
5921
+ for (const file of files) {
5922
+ if (!isArchiveLogFilename(file)) continue;
5758
5923
  try {
5759
- last = getServiceStatus({ withDisabled: false });
5924
+ const filePath = path5.join(logsDir, file);
5925
+ const stat = fs6.statSync(filePath);
5926
+ result.archives.push({
5927
+ name: file,
5928
+ path: filePath,
5929
+ size: stat.size,
5930
+ mtime: stat.mtime,
5931
+ isCurrent: false
5932
+ });
5760
5933
  } catch {
5761
- continue;
5762
- }
5763
- graceQueried = true;
5764
- if (isCrashed(last)) {
5765
- return unhealthy(last, true);
5766
5934
  }
5767
- if (!last.loaded) break;
5768
- if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
5769
5935
  }
5770
- if (!graceQueried) return healthViaProcessProbe();
5771
- return unhealthy(last, false, last.pid);
5936
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5937
+ return result;
5772
5938
  }
5773
- function healthViaProcessProbe() {
5939
+
5940
+ // src/process-probe.ts
5941
+ import { spawnSync as spawnSync3 } from "child_process";
5942
+ import fs7 from "fs";
5943
+ var PS_TIMEOUT_MS = 5e3;
5944
+ var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
5945
+ function probeProcess(pid) {
5946
+ if (!pid) return NOT_RUNNING;
5774
5947
  try {
5775
- const pids = getMihomoPids();
5776
- if (pids.length > 0) return { healthy: true, crashed: false, pid: pids[0], exitCode: null, terminatingSignal: null };
5948
+ const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
5949
+ encoding: "utf8",
5950
+ timeout: PS_TIMEOUT_MS
5951
+ });
5952
+ const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
5953
+ if (!match) return NOT_RUNNING;
5954
+ return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
5777
5955
  } catch {
5956
+ return NOT_RUNNING;
5778
5957
  }
5779
- return { healthy: false, crashed: false, pid: null, exitCode: null, terminatingSignal: null };
5780
5958
  }
5781
- function describeExitCause(exitCode, terminatingSignal) {
5782
- if (terminatingSignal !== null) return `\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF08${terminatingSignal}\uFF09`;
5783
- if (exitCode !== null && exitCode !== 0) return `\u9000\u51FA\u7801 ${exitCode}`;
5784
- return null;
5959
+ function isProbedMihomo(p) {
5960
+ return p.alive && (p.command.includes(PATHS.mihomoBinary) || p.command.includes(PATHS.serviceBinary));
5785
5961
  }
5786
- function isCrashed(status) {
5787
- if (status.running) return false;
5788
- return describeExitCause(status.lastExitCode, status.lastTerminatingSignal) !== null;
5962
+ var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
5963
+ var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
5964
+ function getPid() {
5965
+ if (!fs7.existsSync(PATHS.pidFile)) return null;
5966
+ try {
5967
+ const pid = parseInt(fs7.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5968
+ return pid > 0 ? pid : null;
5969
+ } catch {
5970
+ return null;
5971
+ }
5789
5972
  }
5790
- function describeAbnormalExit(status) {
5791
- return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
5973
+ function isRunning() {
5974
+ const pid = getPid();
5975
+ if (!pid) return false;
5976
+ return isMihomoProcess(pid);
5792
5977
  }
5793
- function tunBlockedHint(lastLine) {
5794
- return ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", lastLine];
5978
+ function isMihomoProcess(pid) {
5979
+ return isProbedMihomo(probeProcess(pid));
5795
5980
  }
5796
- function tunBlockedByRunningService() {
5797
- return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
5798
- hint: tunBlockedHint("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1")
5799
- });
5981
+ function getMihomoPids() {
5982
+ const result = spawnSync3("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5983
+ if (result.error || result.status === null) {
5984
+ throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5985
+ hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
5986
+ });
5987
+ }
5988
+ if (result.status !== 0 && result.status !== 1) {
5989
+ throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
5990
+ hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
5991
+ });
5992
+ }
5993
+ return parsePidList(result.stdout);
5800
5994
  }
5801
- function tunBlockedByConcurrentStart() {
5802
- return new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
5803
- hint: tunBlockedHint("\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun")
5804
- });
5995
+ function parsePidList(stdout) {
5996
+ const output = stdout.trim();
5997
+ if (!output) return [];
5998
+ return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5805
5999
  }
5806
- function ensureServiceSymlink() {
5807
- assertKernelInstalled();
5808
- try {
5809
- const current = fs12.readlinkSync(PATHS.serviceBinary);
5810
- if (current === "mihomo") return;
5811
- fs12.unlinkSync(PATHS.serviceBinary);
5812
- } catch (e) {
5813
- const code = e.code;
5814
- if (code === "EINVAL") {
5815
- try {
5816
- fs12.unlinkSync(PATHS.serviceBinary);
5817
- } catch {
5818
- }
5819
- } else if (code !== "ENOENT") {
5820
- throw e;
5821
- }
5822
- }
6000
+ function isPidFileOwnedByRoot() {
6001
+ if (!fs7.existsSync(PATHS.pidFile)) return false;
5823
6002
  try {
5824
- fs12.symlinkSync("mihomo", PATHS.serviceBinary);
5825
- } catch (e) {
5826
- if (e.code !== "EEXIST") throw e;
5827
- let existing;
5828
- try {
5829
- existing = fs12.readlinkSync(PATHS.serviceBinary);
5830
- } catch {
5831
- throw e;
5832
- }
5833
- if (existing !== "mihomo") throw e;
6003
+ const stat = fs7.statSync(PATHS.pidFile);
6004
+ return stat.uid === 0;
6005
+ } catch {
6006
+ return false;
5834
6007
  }
5835
6008
  }
5836
- function bootstrapServiceIdempotentOrThrow(what) {
5837
- const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5838
- if (result.status === 0) return;
5839
- if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
5840
- const detail = result.stderr.trim();
5841
- throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5842
- hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5843
- });
5844
- }
5845
- function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5846
- const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
5847
- if (result.status === 0 || isBootoutNotLoaded(result.status)) return;
5848
- const detail = result.stderr.trim();
5849
- throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5850
- hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5851
- });
5852
- }
5853
- async function installService(wasRunning) {
5854
- assertServiceLabelSafe();
5855
- ensureDirs();
5856
- ensureServiceSymlink();
5857
- let restoreSkipped = false;
5858
- const stagePath = PATHS.servicePlistStage;
5859
- atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
5860
- try {
5861
- const lint = spawnSync7("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5862
- if (lint.status !== 0) {
5863
- throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
5864
- hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
5865
- });
5866
- }
5867
- bootoutService();
5868
- await waitUntilUnloaded();
5869
- fs12.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5870
- atomicWriteFileSync(PATHS.userAgentPlist, fs12.readFileSync(stagePath, "utf8"), { mode: 420 });
5871
- if (wasRunning) {
5872
- withFileLock(PATHS.serviceLock, () => {
5873
- if (startAbortedByConcurrentStop()) {
5874
- restoreSkipped = true;
5875
- return;
5876
- }
5877
- runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5878
- bootstrapServiceIdempotentOrThrow("\u88C5\u8F7D\u670D\u52A1");
5879
- });
5880
- }
5881
- } finally {
5882
- try {
5883
- fs12.unlinkSync(stagePath);
5884
- } catch {
5885
- }
5886
- }
5887
- if (!wasRunning) {
5888
- disableServiceAutoStart();
5889
- }
5890
- return { restoreSkipped };
6009
+ function getStatus() {
6010
+ const pid = getPid();
6011
+ if (!pid) return { running: false, pid: null, memory: null };
6012
+ const p = probeProcess(pid);
6013
+ if (!isProbedMihomo(p)) return { running: false, pid: null, memory: null };
6014
+ return {
6015
+ running: true,
6016
+ pid,
6017
+ memory: p.rss ? `${(p.rss / 1024).toFixed(1)} MB` : "\u672A\u77E5"
6018
+ };
5891
6019
  }
5892
- async function startService() {
5893
- assertServiceLabelSafe();
5894
- ensureServiceSymlink();
5895
- if (!isServiceInstalled()) {
5896
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5897
- }
5898
- assertRuntimeConfigPresent();
5899
- if (getConfigInfo()?.tun) {
5900
- throw new CliError("\u8FD0\u884C\u65F6\u914D\u7F6E\u4E3A TUN \u6A21\u5F0F\uFF0C\u670D\u52A1\u65E0\u6CD5\u4F7F\u7528", {
5901
- hint: [
5902
- "\u670D\u52A1\u4EE5\u666E\u901A\u7528\u6237\u8EAB\u4EFD\u8FD0\u884C\uFF08\u7528\u6237\u7EA7 LaunchAgent\uFF09\uFF0C\u65E0\u6743\u521B\u5EFA TUN \u8BBE\u5907\uFF0C",
5903
- "\u5F3A\u884C\u542F\u52A8\u53EA\u4F1A\u8BA9\u5185\u6838\u53CD\u590D\u5D29\u6E83\u91CD\u542F\u3002",
5904
- "",
5905
- "\u6309 Mixed \u91CD\u5EFA\u914D\u7F6E\u5E76\u542F\u52A8: mihomo-cli start mixed",
5906
- "\u786E\u5B9E\u8981\u7528 TUN: mihomo-cli tun"
5907
- ]
5908
- });
5909
- }
5910
- await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
5911
- bootoutService();
5912
- await waitUntilUnloaded();
5913
- rotateAndCleanupLogs();
5914
- let started = true;
5915
- withFileLock(PATHS.serviceLock, () => {
5916
- if (startAbortedByConcurrentStop()) {
5917
- started = false;
5918
- return;
5919
- }
5920
- runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5921
- bootstrapServiceIdempotentOrThrow("\u542F\u52A8\u670D\u52A1");
5922
- });
5923
- return { started };
6020
+
6021
+ // src/process-start.ts
6022
+ import fs13 from "fs";
6023
+
6024
+ // src/service.ts
6025
+ import { spawnSync as spawnSync7 } from "child_process";
6026
+ import fs12 from "fs";
6027
+ import path7 from "path";
6028
+
6029
+ // src/hot-reload.ts
6030
+ import fs8 from "fs";
6031
+
6032
+ // src/proxy-probe.ts
6033
+ import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
6034
+ import { promisify as promisify2 } from "util";
6035
+
6036
+ // src/curl-spawn.ts
6037
+ function buildCurlSpawnEnv() {
6038
+ const env = { ...process.env };
6039
+ env.no_proxy = "";
6040
+ env.NO_PROXY = "";
6041
+ return env;
5924
6042
  }
5925
- function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5926
- assertServiceLabelSafe();
5927
- runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F", timeoutMs);
5928
- if (!isServiceDisabledInLaunchd(timeoutMs)) {
5929
- throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
5930
- hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
5931
- });
6043
+
6044
+ // src/proxy-probe.ts
6045
+ var execFileAsync = promisify2(execFile2);
6046
+ function lsofListenPids(port) {
6047
+ try {
6048
+ const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
6049
+ if (r.status !== 0) return null;
6050
+ return parsePidList(r.stdout);
6051
+ } catch {
6052
+ return null;
5932
6053
  }
5933
- bumpStopEpoch();
5934
- }
5935
- async function bootoutAndDisableInLock() {
5936
- withFileLock(PATHS.serviceLock, () => {
5937
- bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5938
- disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5939
- });
5940
- await waitUntilUnloaded();
5941
6054
  }
5942
- async function stopService() {
5943
- assertServiceLabelSafe();
5944
- await bootoutAndDisableInLock();
5945
- return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
6055
+ var PROBE_URL = "https://www.gstatic.com/generate_204";
6056
+ function isProbeSuccessStatus(code) {
6057
+ return code !== null && code >= 200 && code < 300;
5946
6058
  }
5947
- async function uninstallService() {
5948
- assertServiceLabelSafe();
5949
- await bootoutAndDisableInLock();
6059
+ var PROBE_TIMEOUT_MS = 2e3;
6060
+ async function probeProxyConnectivity(port) {
6061
+ const start = Date.now();
5950
6062
  try {
5951
- fs12.rmSync(PATHS.userAgentPlist, { force: true });
6063
+ const { stdout } = await execFileAsync(
6064
+ "curl",
6065
+ ["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
6066
+ {
6067
+ timeout: PROBE_TIMEOUT_MS + 2e3,
6068
+ // 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
6069
+ env: buildCurlSpawnEnv()
6070
+ }
6071
+ );
6072
+ const code = Number.parseInt(stdout.trim(), 10);
6073
+ const statusCode = Number.isFinite(code) ? code : null;
6074
+ const ok = isProbeSuccessStatus(statusCode);
6075
+ return {
6076
+ ok,
6077
+ statusCode,
6078
+ error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
6079
+ durationMs: Date.now() - start
6080
+ };
5952
6081
  } catch (e) {
5953
- throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
6082
+ const err = e;
6083
+ const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
6084
+ return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
5954
6085
  }
5955
- const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
6086
+ }
6087
+
6088
+ // src/hot-reload.ts
6089
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
6090
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
6091
+ function logOversized() {
5956
6092
  try {
5957
- fs12.rmSync(PATHS.serviceBinary, { force: true });
6093
+ return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5958
6094
  } catch {
6095
+ return false;
5959
6096
  }
5960
- return cleanup;
5961
6097
  }
5962
- async function restartService(prefetched) {
5963
- assertServiceLabelSafe();
5964
- if (!isServiceInstalled()) {
5965
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5966
- }
5967
- const oversized = logOversized();
5968
- if (!oversized && await tryHotReload(prefetched)) {
5969
- return concludeHotReload(stopEpochBaseline(), readStopEpoch());
5970
- }
5971
- if (oversized) {
5972
- const archiveFile = allocateArchivePath();
6098
+ async function tryHotReload(prefetched) {
6099
+ const controller = new AbortController();
6100
+ try {
6101
+ const status = prefetched ?? getServiceStatus({ withDisabled: false });
6102
+ if (!status.running || status.pid === null) return false;
6103
+ const endpoint = getControllerEndpoint();
6104
+ if (endpoint.port === null) return false;
6105
+ const baseUrl = `http://127.0.0.1:${endpoint.port}`;
6106
+ const headers = { "Content-Type": "application/json" };
6107
+ if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
6108
+ const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
5973
6109
  try {
5974
- fs12.copyFileSync(PATHS.logFile, archiveFile);
5975
- fs12.writeFileSync(PATHS.logFile, "");
5976
- } catch {
6110
+ const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
6111
+ if (!probe.ok) return false;
6112
+ const info = await probe.json();
6113
+ if (typeof info?.version !== "string") return false;
6114
+ const listenerPids = lsofListenPids(endpoint.port);
6115
+ if (listenerPids === null || listenerPids[0] !== status.pid) return false;
6116
+ const res = await fetch(`${baseUrl}/configs?force=true`, {
6117
+ method: "PUT",
6118
+ headers,
6119
+ body: "{}",
6120
+ signal: controller.signal
6121
+ });
6122
+ return res.ok;
6123
+ } finally {
6124
+ clearTimeout(timer);
5977
6125
  }
6126
+ } catch {
6127
+ return false;
5978
6128
  }
5979
- const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
5980
- let started = true;
5981
- if (kick.status !== 0) {
5982
- withFileLock(PATHS.serviceLock, () => {
5983
- if (startAbortedByConcurrentStop()) {
5984
- started = false;
5985
- return;
5986
- }
5987
- runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5988
- bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
5989
- });
5990
- if (!started) return { hotReloaded: false, started: false };
5991
- }
5992
- cleanupOldLogs();
5993
- return { hotReloaded: false, started: true };
5994
6129
  }
5995
6130
 
5996
- // src/suggest.ts
5997
- function levenshtein(a, b) {
5998
- if (a === b) return 0;
5999
- if (a.length === 0) return b.length;
6000
- if (b.length === 0) return a.length;
6001
- let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
6002
- for (let i = 1; i <= a.length; i++) {
6003
- const curr = [i];
6004
- for (let j = 1; j <= b.length; j++) {
6005
- curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
6006
- }
6007
- prev = curr;
6131
+ // src/process-stop.ts
6132
+ import { spawnSync as spawnSync6 } from "child_process";
6133
+ import fs10 from "fs";
6134
+
6135
+ // src/sudo.ts
6136
+ import { spawnSync as spawnSync5 } from "child_process";
6137
+ import fs9 from "fs";
6138
+ import path6 from "path";
6139
+ var SUDO_TIMEOUT_MS = 6e4;
6140
+ var SudoAuthError = class extends Error {
6141
+ constructor() {
6142
+ super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
6143
+ this.name = "SudoAuthError";
6008
6144
  }
6009
- return prev[b.length];
6145
+ };
6146
+ function describeSudoFailure(e) {
6147
+ return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
6010
6148
  }
6011
- function suggestSimilar(input, candidates) {
6012
- const lower = input.toLowerCase();
6013
- if (lower === "") return [];
6014
- const scored = [];
6015
- for (const cand of candidates) {
6016
- const c = cand.toLowerCase();
6017
- if (cand === input) continue;
6018
- if (c.startsWith(lower)) {
6019
- scored.push({ name: cand, score: 0, lenDiff: Math.abs(cand.length - input.length) });
6020
- } else if (lower.length >= 3) {
6021
- const d = levenshtein(lower, c);
6022
- if (d <= 2) scored.push({ name: cand, score: d, lenDiff: Math.abs(cand.length - input.length) });
6023
- }
6024
- }
6025
- scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
6026
- return scored.slice(0, 3).map((s) => s.name);
6149
+ function sudoExitToError(action, status, codeMessages) {
6150
+ if (status === 1) return new SudoAuthError();
6151
+ if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
6152
+ const custom = codeMessages?.[status];
6153
+ return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
6027
6154
  }
6028
-
6029
- // src/commands/help.ts
6030
- function printShortHelp() {
6031
- console.log(`
6032
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo-cli help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
6033
- `);
6034
- const steps = [];
6035
- if (!hasKernel()) steps.push(["mihomo-cli kernel", "\u4E0B\u8F7D\u5185\u6838"]);
6036
- if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
6037
- if (!isServiceInstalled()) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
6038
- if (steps.length > 0) {
6039
- steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
6040
- const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
6041
- console.log("\u5F00\u59CB\u4F7F\u7528:");
6042
- steps.forEach(([cmd, desc], i) => {
6043
- console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
6044
- });
6045
- console.log("");
6046
- return;
6047
- }
6048
- console.log(
6049
- `\u5E38\u7528\u547D\u4EE4:
6050
- ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
6051
- ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
6052
- ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
6053
- ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
6054
- `
6055
- );
6155
+ function sudoTimeoutError(action) {
6156
+ return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
6056
6157
  }
6057
- var GROUP_TITLES = [
6058
- ["control", "\u63A7\u5236:"],
6059
- ["interface", "\u754C\u9762:"],
6060
- ["subscription", "\u8BA2\u9605:"],
6061
- ["config", "\u914D\u7F6E:"],
6062
- ["system", "\u7CFB\u7EDF:"]
6063
- ];
6064
- function printHelp(commands) {
6065
- const lines = [`
6066
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mh", "", "\u7528\u6CD5:", " mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"];
6067
- const allUsage = commands.flatMap((c) => c.usage);
6068
- const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
6069
- const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
6070
- for (const [group, title] of GROUP_TITLES) {
6071
- const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
6072
- if (usageLines.length === 0) continue;
6073
- lines.push("", colors.cyan(title));
6074
- for (const u of usageLines) lines.push(formatUsage(u));
6075
- }
6076
- const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
6077
- if (meta.length > 0) {
6078
- lines.push("", colors.cyan("\u5143:"));
6079
- for (const u of meta) lines.push(formatUsage(u));
6158
+ function runSudoScript(scriptBody, opts) {
6159
+ if (!process.stdin.isTTY) {
6160
+ throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
6080
6161
  }
6081
- lines.push(
6082
- "",
6083
- `${colors.cyan("\u793A\u4F8B:")}`,
6084
- // 顺序即首次使用的依赖顺序(kernel → 订阅 → 服务 → 启动):install 在无内核时会被
6085
- // 拦下提示先跑 kernel,示例若把 install 放第一条,照着敲的新用户第一步就撞墙
6086
- " mihomo-cli kernel # \u4E0B\u8F7D\u5185\u6838\uFF08\u9996\u6B21\u4F7F\u7528\u7684\u7B2C\u4E00\u6B65\uFF09",
6087
- " mihomo-cli sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
6088
- " mihomo-cli install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
6089
- " mihomo-cli start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
6090
- " mihomo-cli stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
6091
- " mihomo-cli start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
6092
- " mihomo-cli start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
6093
- " mihomo-cli ui # \u6253\u5F00 Web UI",
6094
- "",
6095
- `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
6096
- " tun = start tun",
6097
- " use <name> = subscription use <name>",
6098
- " restart = start\uFF08start \u672C\u8EAB\u5373\u91CD\u542F\uFF09",
6099
- "",
6100
- `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
6101
- " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
6102
- " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
6103
- "",
6104
- `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
6105
- " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
6106
- ` \u9ED8\u8BA4: ${USER_DATA_DIR}`
6107
- );
6108
- console.log(lines.join("\n"));
6109
- }
6110
- function printCommandHelp(command) {
6111
- const aliasText = command.aliases.length > 0 ? colors.gray(`\uFF08\u522B\u540D: ${command.aliases.join(", ")}\uFF09`) : "";
6112
- const lines = ["", `${colors.cyan(colors.bold(`mihomo-cli ${command.name}`))}${aliasText}`];
6113
- if (command.usage.length > 0) {
6114
- lines.push("", "\u7528\u6CD5:");
6115
- const width = Math.max(...command.usage.map((u) => displayWidth(u.signature)));
6116
- for (const u of command.usage) {
6117
- lines.push(` ${colors.bold(padEndDisplay(u.signature, width))} ${u.description}`);
6162
+ ensureDirs();
6163
+ const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
6164
+ fs9.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6165
+ fs9.chmodSync(scriptPath, 448);
6166
+ try {
6167
+ const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
6168
+ if (result.error) {
6169
+ if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
6170
+ throw result.error;
6171
+ }
6172
+ if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
6173
+ } finally {
6174
+ try {
6175
+ fs9.unlinkSync(scriptPath);
6176
+ } catch {
6118
6177
  }
6119
- } else {
6120
- lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo-cli help"));
6121
6178
  }
6122
- console.log(lines.join("\n"));
6123
6179
  }
6124
- function printHelpEntry(args, commands, finder) {
6125
- const token = args[1];
6126
- if (!token) {
6127
- printHelp(commands);
6128
- return;
6129
- }
6130
- const command = finder(token.toLowerCase());
6131
- if (!command) {
6132
- const suggestion = suggestSimilar(
6133
- token,
6134
- commands.flatMap((c) => [c.name, ...c.aliases])
6135
- );
6136
- throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
6137
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
6138
- });
6180
+
6181
+ // src/process-stop.ts
6182
+ var PROCESS_WAIT_ATTEMPTS = 50;
6183
+ var PROCESS_WAIT_INTERVAL = 100;
6184
+ var BATCH_KILL_THRESHOLD = 3;
6185
+ function clearRuntime() {
6186
+ if (fs10.existsSync(DIRS.runtime)) {
6187
+ rmrf(DIRS.runtime);
6139
6188
  }
6140
- printCommandHelp(command);
6189
+ ensureDirs();
6141
6190
  }
6142
- function printVersion() {
6143
- const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
6144
- console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
6145
- console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
6146
- console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
6191
+ var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
6192
+ function printResidueWarning(remaining) {
6193
+ console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
6194
+ console.log(MANUAL_PKILL_HINT);
6147
6195
  }
6148
-
6149
- // src/redact.ts
6150
- var SECRET_KEYS = /* @__PURE__ */ new Set(["password", "uuid", "private-key", "pre-shared-key", "auth-str", "auth", "obfs-password", "token", "secret"]);
6151
- var URL_PROVIDER_KEYS = /* @__PURE__ */ new Set(["proxy-providers", "rule-providers"]);
6152
- function walk(node, withinProvider, state) {
6153
- if (Array.isArray(node)) {
6154
- return node.map((item) => walk(item, withinProvider, state));
6155
- }
6156
- if (node !== null && typeof node === "object") {
6157
- const out = {};
6158
- for (const [key, value] of Object.entries(node)) {
6159
- const assign = (v) => {
6160
- if (key === "__proto__") {
6161
- Object.defineProperty(out, key, { value: v, enumerable: true, writable: true, configurable: true });
6162
- } else {
6163
- out[key] = v;
6164
- }
6165
- };
6166
- if (typeof value === "string" && SECRET_KEYS.has(key.toLowerCase())) {
6167
- assign("***");
6168
- state.changed = true;
6169
- } else if (typeof value === "string" && withinProvider && key === "url") {
6170
- const masked = maskUrl(value);
6171
- assign(masked);
6172
- if (masked !== value) state.changed = true;
6173
- } else {
6174
- assign(walk(value, withinProvider || URL_PROVIDER_KEYS.has(key), state));
6175
- }
6176
- }
6177
- return out;
6196
+ function clearPid() {
6197
+ try {
6198
+ fs10.unlinkSync(PATHS.pidFile);
6199
+ return null;
6200
+ } catch (e) {
6201
+ if (e.code === "ENOENT") return null;
6202
+ return e;
6178
6203
  }
6179
- return node;
6180
6204
  }
6181
- function redactConfigSecrets(config) {
6182
- const state = { changed: false };
6183
- return { config: walk(config, false, state), changed: state.changed };
6184
- }
6185
-
6186
- // src/http.ts
6187
- var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
6188
- var MAX_REDIRECTS = 20;
6189
- var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
6190
- var MAX_ERROR_BODY_BYTES = 64 * 1024;
6191
- function isHttpsUrl(url) {
6205
+ function pidAlive(pid) {
6192
6206
  try {
6193
- return new URL(url).protocol === "https:";
6194
- } catch {
6195
- return false;
6207
+ process.kill(pid, 0);
6208
+ return true;
6209
+ } catch (e) {
6210
+ return e.code !== "ESRCH";
6211
+ }
6212
+ }
6213
+ async function waitUntilNoMihomo(pids) {
6214
+ for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
6215
+ if (!pids.some(pidAlive)) return;
6216
+ await sleep(PROCESS_WAIT_INTERVAL);
6196
6217
  }
6197
6218
  }
6198
- function createHttpError(status, bodyText) {
6199
- const error = new Error(`HTTP ${status}`);
6200
- error.response = { status };
6219
+ function killProcess(pid) {
6201
6220
  try {
6202
- error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
6221
+ process.kill(pid, "SIGKILL");
6203
6222
  } catch {
6204
6223
  }
6205
- return error;
6206
6224
  }
6207
- function createHttpClient(options = {}) {
6208
- const { timeout = 6e4 } = options;
6209
- return {
6210
- async get(url, config) {
6211
- const controller = new AbortController();
6212
- const timer = setTimeout(() => controller.abort(), timeout);
6213
- const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
6214
- try {
6215
- let currentUrl = url;
6216
- let response;
6217
- for (let hop = 0; ; hop++) {
6218
- response = await fetch(currentUrl, {
6219
- signal,
6220
- redirect: "manual",
6221
- headers: { "User-Agent": `mihomo-cli/${VERSION}` }
6222
- });
6223
- if (!REDIRECT_STATUSES.has(response.status)) break;
6224
- if (hop >= MAX_REDIRECTS) {
6225
- throw new Error(`\u91CD\u5B9A\u5411\u6B21\u6570\u8D85\u8FC7 ${MAX_REDIRECTS}\uFF0C\u5DF2\u4E2D\u6B62: ${maskUrl(url)}`);
6226
- }
6227
- const location = response.headers.get("location");
6228
- if (!location) break;
6229
- const nextUrl = new URL(location, currentUrl).toString();
6230
- if (isHttpsUrl(url) && !isHttpsUrl(nextUrl)) {
6231
- throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(nextUrl)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
6232
- }
6233
- await response.body?.cancel().catch(() => void 0);
6234
- currentUrl = nextUrl;
6235
- }
6236
- if (!response.ok) {
6237
- let text2 = "";
6238
- try {
6239
- text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
6240
- } catch {
6241
- }
6242
- throw createHttpError(response.status, text2);
6243
- }
6244
- const declaredLen = Number(response.headers.get("content-length"));
6245
- if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
6246
- throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
6247
- }
6248
- const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
6249
- const data = config?.responseType === "json" ? JSON.parse(text) : text;
6250
- return { data, headers: response.headers };
6251
- } catch (e) {
6252
- if (controller.signal.aborted && e.name === "AbortError") {
6253
- throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
6254
- }
6255
- throw e;
6256
- } finally {
6257
- clearTimeout(timer);
6258
- }
6259
- }
6260
- };
6225
+ function killAllMihomo() {
6226
+ spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
6261
6227
  }
6262
- async function readBodyWithLimit(response, controller, limit) {
6263
- if (!response.body) return response.text();
6264
- const reader = response.body.getReader();
6265
- const chunks = [];
6266
- let total = 0;
6267
- try {
6268
- while (true) {
6269
- const { done, value } = await reader.read();
6270
- if (done) break;
6271
- if (value) {
6272
- total += value.byteLength;
6273
- if (total > limit) {
6274
- controller.abort();
6275
- throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
6276
- }
6277
- chunks.push(value);
6278
- }
6228
+ function buildKernelCleanupScript() {
6229
+ return [
6230
+ "#!/bin/bash",
6231
+ // pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
6232
+ `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
6233
+ "rc=$?",
6234
+ "[ $rc -le 1 ] || exit 2",
6235
+ "exit 0",
6236
+ ""
6237
+ ].join("\n");
6238
+ }
6239
+ async function cleanupAll() {
6240
+ const pids = getMihomoPids();
6241
+ if (pids.length === 0) {
6242
+ return { remaining: [], incomplete: clearPid() };
6243
+ }
6244
+ let scriptError = null;
6245
+ const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
6246
+ const rootPids = pids.filter((pid) => probes.get(pid)?.uid === "0");
6247
+ if (rootPids.length > 0) {
6248
+ console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
6249
+ try {
6250
+ runSudoScript(buildKernelCleanupScript(), {
6251
+ action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B",
6252
+ file: "cleanup-residue.sh",
6253
+ codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" }
6254
+ });
6255
+ } catch (e) {
6256
+ scriptError = e;
6257
+ }
6258
+ } else if (pids.length > BATCH_KILL_THRESHOLD) {
6259
+ killAllMihomo();
6260
+ } else {
6261
+ for (const pid of pids) {
6262
+ const probed = probes.get(pid);
6263
+ if (probed && isProbedMihomo(probed)) killProcess(pid);
6279
6264
  }
6280
- } finally {
6281
- reader.releaseLock();
6282
6265
  }
6283
- return Buffer.concat(chunks).toString("utf8");
6266
+ await waitUntilNoMihomo(pids);
6267
+ const remaining = getMihomoPids();
6268
+ const pidError = remaining.length === 0 ? clearPid() : null;
6269
+ return { remaining, incomplete: scriptError ?? pidError };
6284
6270
  }
6285
-
6286
- // src/spinner.ts
6287
- var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
6288
- var INTERVAL_MS = 80;
6289
- async function withSpinner(label, fn) {
6290
- if (!process.stdout.isTTY) {
6291
- console.log(label);
6292
- return fn();
6271
+ function buildRootResidueCleanupError(result, ctx) {
6272
+ const alive = result.remaining.length > 0;
6273
+ const state = alive ? `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${result.remaining.join(", ")}\uFF09` : "\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF0C\u4F46\u6E05\u7406\u672A\u8D70\u5B8C";
6274
+ const manual = alive ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: rm -f ${PATHS.pidFile}`;
6275
+ const hint = [ctx.mainOutcome, state, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`, manual];
6276
+ if (result.incomplete instanceof SudoAuthError) {
6277
+ const message = `${describeSudoFailure(result.incomplete)}\uFF0C${alive ? "\u6B8B\u7559\u672A\u88AB\u6E05\u7406" : "\u6E05\u7406\u672A\u5B8C\u6210"}`;
6278
+ return new CliError(message, { label: "\u5DF2\u53D6\u6D88", hint });
6293
6279
  }
6294
- const start = Date.now();
6295
- let frame = 0;
6296
- const render = () => {
6297
- const secs = ((Date.now() - start) / 1e3).toFixed(0);
6298
- process.stdout.write(`\r${colors.cyan(FRAMES[frame])} ${label} ${colors.gray(`${secs}s`)}\x1B[K`);
6299
- frame = (frame + 1) % FRAMES.length;
6300
- };
6301
- render();
6302
- const timer = setInterval(render, INTERVAL_MS);
6303
- try {
6304
- return await fn();
6305
- } finally {
6306
- clearInterval(timer);
6307
- process.stdout.write("\r\x1B[K");
6280
+ return new CliError(result.incomplete?.message ?? "\u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
6281
+ }
6282
+ function warnResidueCleanup(result, ctx) {
6283
+ const err = buildRootResidueCleanupError(result, ctx);
6284
+ console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
6285
+ for (const line of err.hint) console.warn(colors.gray(line));
6286
+ }
6287
+ async function cleanupKernelsOrThrow(ctx) {
6288
+ const result = await cleanupAll();
6289
+ if (result.incomplete !== null) {
6290
+ if (result.remaining.length > 0) throw buildRootResidueCleanupError(result, ctx);
6291
+ warnResidueCleanup(result, ctx);
6292
+ }
6293
+ return result;
6294
+ }
6295
+ async function stop() {
6296
+ const allPids = getMihomoPids();
6297
+ if (allPids.length === 0) {
6298
+ const pidError = clearPid();
6299
+ if (pidError) console.warn(colors.yellow(`\u8B66\u544A: pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${pidError.message}\uFF09\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
6300
+ clearRuntime();
6301
+ return {};
6302
+ }
6303
+ const result = await cleanupAll();
6304
+ if (result.remaining.length === 0 && result.incomplete !== null) {
6305
+ warnResidueCleanup(result, { mainOutcome: "\u5185\u6838\u5DF2\u505C\u6B62", retryCommand: "mihomo-cli stop" });
6308
6306
  }
6307
+ if (result.remaining.length > 0) return { remaining: result.remaining };
6308
+ clearRuntime();
6309
+ return {};
6309
6310
  }
6310
6311
 
6311
- // src/subscription.ts
6312
- function resolveUpdateInterval(cachedInterval) {
6313
- return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
6312
+ // src/stop-epoch.ts
6313
+ import fs11 from "fs";
6314
+ function readStopEpoch() {
6315
+ try {
6316
+ const n = Number.parseInt(fs11.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
6317
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
6318
+ } catch {
6319
+ return 0;
6320
+ }
6314
6321
  }
6315
- function isSubscriptionStale(cached, nowMs = Date.now()) {
6316
- if (!cached.updated_at) return false;
6317
- const t = new Date(cached.updated_at).getTime();
6318
- if (Number.isNaN(t) || t > nowMs) return false;
6319
- const ageHours = (nowMs - t) / 36e5;
6320
- return ageHours > resolveUpdateInterval(cached.update_interval);
6322
+ var stopEpochBaselineCaptured = null;
6323
+ function captureStopEpochBaseline() {
6324
+ stopEpochBaselineCaptured = readStopEpoch();
6325
+ return stopEpochBaselineCaptured;
6321
6326
  }
6322
- var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
6323
- function isValidHttpUrl(url) {
6327
+ function stopEpochBaseline() {
6328
+ return stopEpochBaselineCaptured ?? readStopEpoch();
6329
+ }
6330
+ function bumpStopEpoch() {
6324
6331
  try {
6325
- const u = new URL(url.trim());
6326
- return u.protocol === "http:" || u.protocol === "https:";
6332
+ ensureDirs();
6333
+ atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
6327
6334
  } catch {
6328
- return false;
6329
6335
  }
6330
6336
  }
6331
- function parseUserInfo(header) {
6332
- if (!header) return null;
6333
- const info = {};
6334
- let hasAny = false;
6335
- for (const part of header.split(";")) {
6336
- const [rawKey, rawVal] = part.split("=");
6337
- const key = rawKey?.trim();
6338
- const val = rawVal?.trim();
6339
- if (!key || val === void 0 || val === "") continue;
6340
- const numVal = Number(val);
6341
- if (!Number.isFinite(numVal) || numVal < 0) continue;
6342
- info[key] = numVal;
6343
- hasAny = true;
6337
+ function epochChanged(before, now) {
6338
+ return now !== before;
6339
+ }
6340
+ function startAbortedByConcurrentStop() {
6341
+ return epochChanged(stopEpochBaseline(), readStopEpoch());
6342
+ }
6343
+
6344
+ // src/service.ts
6345
+ var SERVICE_HEALTH_INTERVAL_MS = 100;
6346
+ var SERVICE_OBSERVE_MS = 1200;
6347
+ var SERVICE_HEALTH_GRACE_MS = 1800;
6348
+ async function waitServiceHealthy() {
6349
+ const deadline = Date.now() + SERVICE_OBSERVE_MS;
6350
+ const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
6351
+ let last = null;
6352
+ const unhealthy = (state, crashed, pid = null) => ({
6353
+ healthy: false,
6354
+ crashed,
6355
+ pid,
6356
+ exitCode: state.lastExitCode,
6357
+ terminatingSignal: state.lastTerminatingSignal
6358
+ });
6359
+ do {
6360
+ await sleep(SERVICE_HEALTH_INTERVAL_MS);
6361
+ try {
6362
+ last = getServiceStatus({ withDisabled: false });
6363
+ } catch {
6364
+ continue;
6365
+ }
6366
+ if (isCrashed(last)) {
6367
+ return unhealthy(last, true);
6368
+ }
6369
+ if (!last.loaded) {
6370
+ return unhealthy(last, false);
6371
+ }
6372
+ } while (Date.now() < deadline);
6373
+ if (last === null) return healthViaProcessProbe();
6374
+ if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
6375
+ let graceQueried = false;
6376
+ while (Date.now() < graceDeadline) {
6377
+ await sleep(SERVICE_HEALTH_INTERVAL_MS);
6378
+ try {
6379
+ last = getServiceStatus({ withDisabled: false });
6380
+ } catch {
6381
+ continue;
6382
+ }
6383
+ graceQueried = true;
6384
+ if (isCrashed(last)) {
6385
+ return unhealthy(last, true);
6386
+ }
6387
+ if (!last.loaded) break;
6388
+ if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
6344
6389
  }
6345
- return hasAny ? info : null;
6346
- }
6347
- function parsePositiveInterval(header) {
6348
- if (!header) return null;
6349
- const n = parseInt(header, 10);
6350
- return Number.isFinite(n) && n > 0 ? n : null;
6351
- }
6352
- function parseUsernameFromContentDisposition(header) {
6353
- if (!header) return null;
6354
- const match = header.match(/filename\s*=\s*["']?([^"';\s]+)["']?/i);
6355
- if (!match) return null;
6356
- const filename = match[1];
6357
- const parts = filename.split("/");
6358
- return parts[parts.length - 1] || null;
6359
- }
6360
- function extractSubscriptionMeta(headers) {
6361
- return {
6362
- userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
6363
- updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
6364
- // 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
6365
- webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
6366
- username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
6367
- };
6390
+ if (!graceQueried) return healthViaProcessProbe();
6391
+ return unhealthy(last, false, last.pid);
6368
6392
  }
6369
- function saveSubscriptionMeta(subName, meta) {
6370
- const cacheData = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
6371
- if (meta.userInfo) {
6372
- const { upload, download, total, expire } = meta.userInfo;
6373
- if (upload !== void 0) cacheData.upload = upload;
6374
- if (download !== void 0) cacheData.download = download;
6375
- if (total !== void 0) cacheData.total = total;
6376
- if (expire !== void 0) cacheData.expire = expire;
6393
+ function healthViaProcessProbe() {
6394
+ try {
6395
+ const pids = getMihomoPids();
6396
+ if (pids.length > 0) return { healthy: true, crashed: false, pid: pids[0], exitCode: null, terminatingSignal: null };
6397
+ } catch {
6377
6398
  }
6378
- if (meta.updateInterval) cacheData.update_interval = meta.updateInterval;
6379
- if (meta.webPageUrl) cacheData.web_page_url = meta.webPageUrl;
6380
- if (meta.username) cacheData.username = meta.username;
6381
- saveSubscriptionCache(subName, cacheData);
6399
+ return { healthy: false, crashed: false, pid: null, exitCode: null, terminatingSignal: null };
6382
6400
  }
6383
- function formatProxySummary(info) {
6384
- const parts = [];
6385
- if (info.proxyGroups && info.proxyGroups > 0) parts.push(`${info.proxyGroups} \u7EC4`);
6386
- parts.push(`${info.proxies || 0} \u8282\u70B9`);
6387
- return parts.join(", ");
6401
+ function describeExitCause(exitCode, terminatingSignal) {
6402
+ if (terminatingSignal !== null) return `\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF08${terminatingSignal}\uFF09`;
6403
+ if (exitCode !== null && exitCode !== 0) return `\u9000\u51FA\u7801 ${exitCode}`;
6404
+ return null;
6388
6405
  }
6389
- function getActiveSubscription() {
6390
- const settings = readSettings();
6391
- const subs = getSubscriptions(settings);
6392
- if (subs.length === 0) return null;
6393
- const activeName = settings.active_subscription;
6394
- if (activeName) {
6395
- const found = subs.find((s) => s.name === activeName);
6396
- if (found) return found;
6397
- }
6398
- return subs[0];
6406
+ function isCrashed(status) {
6407
+ if (status.running) return false;
6408
+ return describeExitCause(status.lastExitCode, status.lastTerminatingSignal) !== null;
6399
6409
  }
6400
- function noSubscriptionsError() {
6401
- return new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
6410
+ function describeAbnormalExit(status) {
6411
+ return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
6402
6412
  }
6403
- function requireActiveSubscription() {
6404
- const sub = getActiveSubscription();
6405
- if (!sub) {
6406
- throw noSubscriptionsError();
6407
- }
6408
- return sub;
6413
+ function tunBlockedHint(lastLine) {
6414
+ return ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", lastLine];
6409
6415
  }
6410
- function resolveSubscription(subs, pattern) {
6411
- const lowerPattern = pattern.toLowerCase();
6412
- const exact = [];
6413
- const prefix = [];
6414
- const includes = [];
6415
- for (const s of subs) {
6416
- const name = s.name.toLowerCase();
6417
- if (name === lowerPattern) {
6418
- exact.push(s);
6419
- } else if (name.startsWith(lowerPattern)) {
6420
- prefix.push(s);
6421
- } else if (name.includes(lowerPattern)) {
6422
- includes.push(s);
6423
- }
6424
- }
6425
- const matched = exact.length > 0 ? exact : prefix.length > 0 ? prefix : includes;
6426
- if (matched.length === 0) {
6427
- throw new CliError(`\u672A\u627E\u5230\u5339\u914D "${pattern}" \u7684\u8BA2\u9605`);
6428
- }
6429
- if (matched.length === 1) return matched[0];
6430
- throw new CliError("\u5339\u914D\u5230\u591A\u4E2A\u8BA2\u9605\uFF0C\u8BF7\u66F4\u7CBE\u786E\u6307\u5B9A", {
6431
- hint: ["", "\u5339\u914D\u7684\u8BA2\u9605:", ...matched.map((s) => ` ${s.name}`)]
6416
+ function tunBlockedByRunningService() {
6417
+ return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
6418
+ hint: tunBlockedHint("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1")
6432
6419
  });
6433
6420
  }
6434
- function assertLooksLikeSubscription(parsed, maskedUrl) {
6435
- const hasProxies = Array.isArray(parsed.proxies) && parsed.proxies.length > 0;
6436
- const hasGroups = Array.isArray(parsed["proxy-groups"]) && parsed["proxy-groups"].length > 0;
6437
- const providers = parsed["proxy-providers"];
6438
- const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
6439
- if (hasProxies || hasGroups || hasProviders) return;
6440
- const serverMsg = sanitizeTerminal(
6441
- ["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
6442
- );
6443
- throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
6444
- label: "\u8BA2\u9605\u65E0\u6548",
6445
- hint: [
6446
- ...serverMsg ? [`\u670D\u52A1\u7AEF\u8FD4\u56DE: ${serverMsg}`] : [],
6447
- `URL: ${maskedUrl}`,
6448
- "\u5E38\u89C1\u539F\u56E0\uFF1A\u8BA2\u9605\u94FE\u63A5\u8FC7\u671F\u3001\u6D41\u91CF\u8017\u5C3D\u3001\u9700\u8981\u91CD\u65B0\u83B7\u53D6\u8BA2\u9605\u5730\u5740\u3002",
6449
- "\u78C1\u76D8\u4E0A\u539F\u6709\u7684\u8BA2\u9605\u914D\u7F6E\u672A\u88AB\u8986\u76D6\u3002"
6450
- ]
6421
+ function tunBlockedByConcurrentStart() {
6422
+ return new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
6423
+ hint: tunBlockedHint("\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun")
6451
6424
  });
6452
6425
  }
6453
- async function downloadSubscription(url, subName, signal) {
6454
- let response;
6426
+ function ensureServiceSymlink() {
6427
+ assertKernelInstalled();
6455
6428
  try {
6456
- response = await HTTP_CLIENT.get(url, { responseType: "text", signal });
6429
+ const current = fs12.readlinkSync(PATHS.serviceBinary);
6430
+ if (current === "mihomo") return;
6431
+ fs12.unlinkSync(PATHS.serviceBinary);
6457
6432
  } catch (e) {
6458
- const maskedUrl = maskUrl(url);
6459
- let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
6460
- const err = e;
6461
- if (err.response) {
6462
- errorMsg += ` (HTTP ${err.response.status})`;
6433
+ const code = e.code;
6434
+ if (code === "EINVAL") {
6435
+ try {
6436
+ fs12.unlinkSync(PATHS.serviceBinary);
6437
+ } catch {
6438
+ }
6439
+ } else if (code !== "ENOENT") {
6440
+ throw e;
6463
6441
  }
6464
- errorMsg += `
6465
- URL: ${maskedUrl}`;
6466
- throw new Error(errorMsg);
6467
- }
6468
- const content = response.data;
6469
- if (!content?.trim()) {
6470
- throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
6471
6442
  }
6472
- const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
6473
- assertLooksLikeSubscription(parsed, maskUrl(url));
6474
- saveSubscriptionRawConfig(subName, content);
6475
- const meta = extractSubscriptionMeta(response.headers);
6476
6443
  try {
6477
- saveSubscriptionMeta(subName, meta);
6444
+ fs12.symlinkSync("mihomo", PATHS.serviceBinary);
6478
6445
  } catch (e) {
6446
+ if (e.code !== "EEXIST") throw e;
6447
+ let existing;
6479
6448
  try {
6480
- removeSubscriptionRawConfig(subName);
6449
+ existing = fs12.readlinkSync(PATHS.serviceBinary);
6481
6450
  } catch {
6451
+ throw e;
6482
6452
  }
6483
- throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
6484
- label: "\u66F4\u65B0\u5931\u8D25",
6485
- // 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
6486
- // 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
6487
- hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
6488
- });
6453
+ if (existing !== "mihomo") throw e;
6489
6454
  }
6490
- const { proxies, proxyGroups } = countConfigNodes(parsed);
6491
- return { proxies, proxyGroups };
6492
6455
  }
6493
- async function prepareConfigForStart(mode, subName) {
6494
- let rawContent;
6456
+ function bootstrapServiceIdempotentOrThrow(what) {
6457
+ const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6458
+ if (result.status === 0) return;
6459
+ if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
6460
+ const detail = result.stderr.trim();
6461
+ throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
6462
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
6463
+ });
6464
+ }
6465
+ function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
6466
+ const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
6467
+ if (result.status === 0 || isBootoutNotLoaded(result.status)) return;
6468
+ const detail = result.stderr.trim();
6469
+ throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
6470
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
6471
+ });
6472
+ }
6473
+ async function installService(wasRunning) {
6474
+ assertServiceLabelSafe();
6475
+ ensureDirs();
6476
+ ensureServiceSymlink();
6477
+ let restoreSkipped = false;
6478
+ const stagePath = PATHS.servicePlistStage;
6479
+ atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
6495
6480
  try {
6496
- rawContent = requireSubscriptionRawConfig(subName);
6497
- } catch (e) {
6498
- if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
6499
- throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
6500
- hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
6481
+ const lint = spawnSync7("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
6482
+ if (lint.status !== 0) {
6483
+ throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
6484
+ hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
6501
6485
  });
6502
6486
  }
6503
- throw e;
6504
- }
6505
- const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
6506
- const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
6507
- await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
6508
- return {
6509
- buildResult,
6510
- info: countConfigNodes(buildResult.config)
6511
- };
6512
- }
6513
- function commitPreparedConfig(prepared) {
6514
- const { buildResult } = prepared;
6515
- if (buildResult.warnings.length > 0) {
6516
- for (const warning of buildResult.warnings) {
6517
- console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
6487
+ bootoutService();
6488
+ await waitUntilUnloaded();
6489
+ fs12.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
6490
+ atomicWriteFileSync(PATHS.userAgentPlist, fs12.readFileSync(stagePath, "utf8"), { mode: 420 });
6491
+ if (wasRunning) {
6492
+ withFileLock(PATHS.serviceLock, () => {
6493
+ if (startAbortedByConcurrentStop()) {
6494
+ restoreSkipped = true;
6495
+ return;
6496
+ }
6497
+ runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6498
+ bootstrapServiceIdempotentOrThrow("\u88C5\u8F7D\u670D\u52A1");
6499
+ });
6500
+ }
6501
+ } finally {
6502
+ try {
6503
+ fs12.unlinkSync(stagePath);
6504
+ } catch {
6518
6505
  }
6519
- console.log("");
6520
- }
6521
- writeMihomoConfig(buildResult.config);
6522
- return prepared.info;
6523
- }
6524
- function needsAutoUpdate(sub) {
6525
- if (!sub.updated_at) return true;
6526
- const lastUpdate = new Date(sub.updated_at).getTime();
6527
- if (Number.isNaN(lastUpdate)) return true;
6528
- if (lastUpdate > Date.now()) return true;
6529
- const intervalHours = resolveUpdateInterval(sub.update_interval);
6530
- const intervalMs = intervalHours * 60 * 60 * 1e3;
6531
- return Date.now() - lastUpdate > intervalMs;
6532
- }
6533
- async function tryUpdateOne(sub, signal) {
6534
- try {
6535
- const info = await downloadSubscription(sub.url, sub.name, signal);
6536
- return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
6537
- } catch (e) {
6538
- return { name: sub.name, success: false, aborted: signal?.aborted === true, error: e.message };
6539
6506
  }
6540
- }
6541
- function printUpdateResult(r) {
6542
- if (r.success) {
6543
- console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
6544
- } else if (r.aborted) {
6545
- console.log(`${colors.gray("\xB7")} ${r.name}: ${colors.gray("\u8DF3\u8FC7\uFF08\u66F4\u65B0\u8D85\u65F6\uFF0C\u4F7F\u7528\u672C\u5730\u7F13\u5B58\uFF09")}`);
6546
- } else {
6547
- console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${firstLine(r.error || "")})`);
6507
+ if (!wasRunning) {
6508
+ disableServiceAutoStart();
6548
6509
  }
6510
+ return { restoreSkipped };
6549
6511
  }
6550
- async function autoUpdateStaleSubscription(options = {}) {
6551
- const allSubs = getSubscriptionsWithCache();
6552
- const staleSubs = allSubs.filter(needsAutoUpdate);
6553
- if (staleSubs.length === 0) {
6554
- return;
6555
- }
6556
- if (staleSubs.length === 1) {
6557
- const sub = staleSubs[0];
6558
- const interval = resolveUpdateInterval(sub.update_interval);
6559
- console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
6560
- } else {
6561
- console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
6512
+ async function startService() {
6513
+ assertServiceLabelSafe();
6514
+ ensureServiceSymlink();
6515
+ if (!isServiceInstalled()) {
6516
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
6562
6517
  }
6563
- const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
6564
- const controller = new AbortController();
6565
- const results = [];
6566
- const updatePromise = Promise.all(
6567
- staleSubs.map(
6568
- (sub) => tryUpdateOne(sub, controller.signal).then((r) => {
6569
- results.push(r);
6570
- return r;
6571
- })
6572
- )
6573
- );
6574
- try {
6575
- await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
6576
- } catch (e) {
6577
- if (!(e instanceof TimeoutError)) throw e;
6578
- controller.abort();
6579
- await updatePromise.catch(() => {
6518
+ assertRuntimeConfigPresent();
6519
+ if (getConfigInfo()?.tun) {
6520
+ throw new CliError("\u8FD0\u884C\u65F6\u914D\u7F6E\u4E3A TUN \u6A21\u5F0F\uFF0C\u670D\u52A1\u65E0\u6CD5\u4F7F\u7528", {
6521
+ hint: [
6522
+ "\u670D\u52A1\u4EE5\u666E\u901A\u7528\u6237\u8EAB\u4EFD\u8FD0\u884C\uFF08\u7528\u6237\u7EA7 LaunchAgent\uFF09\uFF0C\u65E0\u6743\u521B\u5EFA TUN \u8BBE\u5907\uFF0C",
6523
+ "\u5F3A\u884C\u542F\u52A8\u53EA\u4F1A\u8BA9\u5185\u6838\u53CD\u590D\u5D29\u6E83\u91CD\u542F\u3002",
6524
+ "",
6525
+ "\u6309 Mixed \u91CD\u5EFA\u914D\u7F6E\u5E76\u542F\u52A8: mihomo-cli start mixed",
6526
+ "\u786E\u5B9E\u8981\u7528 TUN: mihomo-cli tun"
6527
+ ]
6580
6528
  });
6581
- console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
6582
- }
6583
- for (const r of results) {
6584
- printUpdateResult(r);
6585
6529
  }
6530
+ await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
6531
+ bootoutService();
6532
+ await waitUntilUnloaded();
6533
+ rotateAndCleanupLogs();
6534
+ let started = true;
6535
+ withFileLock(PATHS.serviceLock, () => {
6536
+ if (startAbortedByConcurrentStop()) {
6537
+ started = false;
6538
+ return;
6539
+ }
6540
+ runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6541
+ bootstrapServiceIdempotentOrThrow("\u542F\u52A8\u670D\u52A1");
6542
+ });
6543
+ return { started };
6586
6544
  }
6587
-
6588
- // src/commands/config.ts
6589
- function cmdConfig(args = []) {
6590
- assertKnownFlags(args.slice(1), ["-j", "--json", "--reveal"], "config [--json] [--reveal]");
6591
- assertPositionalCount(args, 0, 1, "mihomo-cli config [--json] [--reveal]");
6592
- const asJson = hasFlag(args, "-j", "--json");
6593
- const reveal = hasFlag(args, "--reveal");
6594
- const active = getActiveSubscription();
6595
- if (!active) {
6596
- throw noSubscriptionsError();
6597
- }
6598
- const rawContent = requireSubscriptionRawConfig(active.name);
6599
- const mode = deriveRuntimeMode(getConfigInfo());
6600
- const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
6601
- const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
6602
- const shown = redacted.config;
6603
- if (asJson) {
6604
- console.log(JSON.stringify({ config: shown, warnings, redacted: !reveal && redacted.changed }, null, 2));
6605
- return;
6606
- }
6607
- console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
6608
- console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
6609
- if (!reveal && redacted.changed) {
6610
- console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
6611
- }
6612
- console.log("");
6613
- console.log(dumpYaml(shown).trimEnd());
6614
- if (warnings.length > 0) {
6615
- console.log("");
6616
- for (const w of warnings) console.log(colors.yellow(`# ${w}`));
6545
+ function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
6546
+ assertServiceLabelSafe();
6547
+ runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F", timeoutMs);
6548
+ if (!isServiceDisabledInLaunchd(timeoutMs)) {
6549
+ throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
6550
+ hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
6551
+ });
6617
6552
  }
6553
+ bumpStopEpoch();
6618
6554
  }
6619
-
6620
- // src/open.ts
6621
- import { spawn } from "child_process";
6622
-
6623
- // src/lifecycle.ts
6624
- var silentSigint = false;
6625
- function setSilentSigint(value) {
6626
- silentSigint = value;
6555
+ async function bootoutAndDisableInLock() {
6556
+ withFileLock(PATHS.serviceLock, () => {
6557
+ bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6558
+ disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6559
+ });
6560
+ await waitUntilUnloaded();
6627
6561
  }
6628
- function isSilentSigint() {
6629
- return silentSigint;
6562
+ async function stopService() {
6563
+ assertServiceLabelSafe();
6564
+ await bootoutAndDisableInLock();
6565
+ return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
6630
6566
  }
6631
-
6632
- // src/open.ts
6633
- function openUrl(url) {
6567
+ async function uninstallService() {
6568
+ assertServiceLabelSafe();
6569
+ await bootoutAndDisableInLock();
6634
6570
  try {
6635
- const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
6636
- child.unref();
6637
- child.on("error", () => {
6638
- });
6571
+ fs12.rmSync(PATHS.userAgentPlist, { force: true });
6572
+ } catch (e) {
6573
+ throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
6574
+ }
6575
+ const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
6576
+ try {
6577
+ fs12.rmSync(PATHS.serviceBinary, { force: true });
6639
6578
  } catch {
6640
6579
  }
6580
+ return cleanup;
6641
6581
  }
6642
- function viewLogWithTail(logPath, options) {
6643
- const follow = options?.follow;
6644
- const lines = options?.lines || 100;
6645
- console.log(`\u65E5\u5FD7: ${logPath}`);
6646
- if (follow) {
6647
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
6648
- } else {
6649
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
6650
- `);
6582
+ async function restartService(prefetched) {
6583
+ assertServiceLabelSafe();
6584
+ if (!isServiceInstalled()) {
6585
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
6651
6586
  }
6652
- const tailArgs = [];
6653
- if (follow) tailArgs.push("-f");
6654
- tailArgs.push("-n", lines.toString());
6655
- tailArgs.push(logPath);
6656
- const tail = spawn("tail", tailArgs, { stdio: "inherit" });
6657
- if (follow) setSilentSigint(true);
6658
- tail.on("close", (code) => process.exit(code ?? 0));
6659
- tail.on("error", (e) => {
6660
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
6661
- process.exit(1);
6662
- });
6587
+ const oversized = logOversized();
6588
+ if (!oversized && await tryHotReload(prefetched)) {
6589
+ return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
6590
+ }
6591
+ if (oversized) {
6592
+ const archiveFile = allocateArchivePath();
6593
+ try {
6594
+ fs12.copyFileSync(PATHS.logFile, archiveFile);
6595
+ fs12.writeFileSync(PATHS.logFile, "");
6596
+ } catch {
6597
+ }
6598
+ }
6599
+ const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
6600
+ let started = true;
6601
+ if (kick.status !== 0) {
6602
+ withFileLock(PATHS.serviceLock, () => {
6603
+ if (startAbortedByConcurrentStop()) {
6604
+ started = false;
6605
+ return;
6606
+ }
6607
+ runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6608
+ bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
6609
+ });
6610
+ if (!started) return { hotReloaded: false, started: false };
6611
+ }
6612
+ cleanupOldLogs();
6613
+ return { hotReloaded: false, started: true };
6663
6614
  }
6664
6615
 
6665
- // src/commands/shared.ts
6666
- import readline from "readline";
6667
-
6668
6616
  // src/process-start.ts
6669
- import fs13 from "fs";
6670
6617
  var TUN_MODE_POST_WAIT_MS = 500;
6671
6618
  function buildTunLaunchScript() {
6672
6619
  const binary = shellQuote(PATHS.mihomoBinary);
@@ -6943,31 +6890,33 @@ function detectSystemProxy(mixedPort) {
6943
6890
  if (r.error || r.status !== 0 || typeof r.stdout !== "string" || !r.stdout.includes("<dictionary>")) return null;
6944
6891
  return summarizeSystemProxy(parseScutilProxy(r.stdout), mixedPort);
6945
6892
  }
6946
- function printSystemProxyHint(mixedPort) {
6947
- const summary = detectSystemProxy(mixedPort);
6893
+ function buildSystemProxyHint(summary, mixedPort) {
6894
+ const applicationGuide = `\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`;
6948
6895
  if (summary === null) {
6949
- console.log(colors.gray(`\u63D0\u793A: Mixed \u6A21\u5F0F\u9700\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u914D\u7F6E HTTP/SOCKS \u4EE3\u7406 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
6950
- return;
6896
+ return { text: `\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B${applicationGuide}`, warning: false };
6951
6897
  }
6952
6898
  if (summary.pac) {
6953
6899
  const desc = summary.pac.wpad ? "WPAD \u81EA\u52A8\u53D1\u73B0" : `PAC \u6587\u4EF6${summary.pac.source ? `\uFF08${summary.pac.source}\uFF09` : ""}`;
6954
- console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u662F\u5426\u8D70 mihomo-cli \u7531\u811A\u672C\u51B3\u5B9A\uFF1B\u5982\u9700\u56FA\u5B9A\u5168\u91CF\u8D70\u4EE3\u7406\uFF0C\u53EF\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u6539\u7528\u624B\u52A8\u4EE3\u7406 127.0.0.1:${mixedPort}`));
6955
- return;
6900
+ return { text: `\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`, warning: false };
6956
6901
  }
6957
6902
  if (summary.matched) {
6958
6903
  if (summary.diverged.length > 0) {
6959
- console.log(colors.yellow(`\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\u2014\u2014\u5BF9\u5E94\u6D41\u91CF\u53EF\u80FD\u4E0D\u7ECF mihomo-cli`));
6960
- } else {
6961
- console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}`));
6904
+ return {
6905
+ text: `\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\uFF1B\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u8FD9\u4E9B\u8BBE\u7F6E\uFF0C\u5177\u4F53\u5E94\u7528\u4EE5\u81EA\u8EAB\u4EE3\u7406\u914D\u7F6E\u4E3A\u51C6`,
6906
+ warning: true
6907
+ };
6962
6908
  }
6963
- return;
6909
+ return { text: `\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF08\u53EA\u8BFB\u68C0\u6D4B\uFF09\uFF1B\u5177\u4F53\u5E94\u7528\u4ECD\u4EE5\u81EA\u8EAB\u4EE3\u7406\u914D\u7F6E\u4E3A\u51C6`, warning: false };
6964
6910
  }
6965
6911
  const pointing = summary.active.length > 0 ? `\uFF0C\u5F53\u524D\u6307\u5411 ${summary.active.join("\u3001")}` : "";
6966
- console.log(colors.yellow(`\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF1B\u9700\u8981\u4EE3\u7406\u7684\u5E94\u7528\u8BF7\u914D\u7F6E\u540E\u4F7F\u7528\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
6967
- console.log(colors.gray(" \u8BBE\u7F6E\u547D\u4EE4\uFF08\u628A Wi-Fi \u6362\u6210\u5B9E\u9645\u7F51\u7EDC\u670D\u52A1\uFF0C\u5168\u90E8\u670D\u52A1\u89C1 networksetup -listallnetworkservices\uFF09:"));
6968
- console.log(colors.gray(` networksetup -setwebproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6969
- console.log(colors.gray(` networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6970
- console.log(colors.gray(` networksetup -setsocksfirewallproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6912
+ return {
6913
+ text: `\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`,
6914
+ warning: true
6915
+ };
6916
+ }
6917
+ function printSystemProxyHint(mixedPort) {
6918
+ const hint = buildSystemProxyHint(detectSystemProxy(mixedPort), mixedPort);
6919
+ console.log(hint.warning ? colors.yellow(hint.text) : colors.gray(hint.text));
6971
6920
  }
6972
6921
 
6973
6922
  // src/commands/status.ts
@@ -7018,11 +6967,10 @@ function buildStatusJson(args) {
7018
6967
  } : null,
7019
6968
  overwrite: {
7020
6969
  enabled: args.overwriteEnabled,
7021
- files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
7022
- // 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
7023
- // 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
6970
+ // 全局关闭时 buildConfig 不加载任何覆写,applied 必须为空;只滤文件 enabled/match
6971
+ // 会与同一份 JSON 里的 overwrite.enabled:false 自相矛盾
7024
6972
  applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
7025
- // 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors。
6973
+ // 加载失败的文件不属于 applied(既没合并也无法判 enabled/match),单列 errors。
7026
6974
  // hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
7027
6975
  // 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
7028
6976
  errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message, hint: b.hint }))
@@ -7049,23 +6997,8 @@ async function printStatus(args = []) {
7049
6997
  const {
7050
6998
  enabled: overwriteEnabled,
7051
6999
  files: overwriteFiles,
7052
- entries: overwriteEntries,
7053
7000
  broken: overwriteBroken
7054
7001
  } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
7055
- if (activeSub && overwriteEnabled && overwriteFiles.some((f) => f.kind === "script")) {
7056
- try {
7057
- const rawContent = readSubscriptionRawConfig(activeSub.name);
7058
- if (rawContent) {
7059
- const { matches } = judgeScriptMatches(rawContent, deriveRuntimeMode(info), { subName: activeSub.name, subUrl: activeSub.url }, overwriteEntries);
7060
- const matchedByName = new Map(matches.map((m) => [m.file, m.matched]));
7061
- for (const f of overwriteFiles) {
7062
- if (f.kind === "script" && matchedByName.has(f.name)) f.matched = matchedByName.get(f.name);
7063
- }
7064
- }
7065
- } catch (e) {
7066
- if (!(e instanceof CliError)) throw e;
7067
- }
7068
- }
7069
7002
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
7070
7003
  const controllerPort = getPortsOrNull()?.controller ?? null;
7071
7004
  const { running, pid, kind } = state;
@@ -7086,8 +7019,6 @@ async function printStatus(args = []) {
7086
7019
  activeSub,
7087
7020
  cached,
7088
7021
  overwriteEnabled,
7089
- // 两个数组在 buildStatusJson 里分出来:files 仍是旧契约(只滤文件级 enabled,
7090
- // 不按 match、不随全局开关变空),applied 才是本次真正参与合并的
7091
7022
  overwriteFiles,
7092
7023
  overwriteBroken,
7093
7024
  service
@@ -7190,7 +7121,7 @@ function printOverwriteLines(enabled, files, broken) {
7190
7121
  if (active.length > 0) {
7191
7122
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${active.map((f) => shortOverwriteName(f.name)).join(", ")}${suffix})`);
7192
7123
  } else {
7193
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
7124
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u9009\u4E2D\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
7194
7125
  }
7195
7126
  for (const b of broken) {
7196
7127
  console.log(colors.red(` ${b.message}`));
@@ -7243,7 +7174,7 @@ async function cmdStart(args) {
7243
7174
  console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D"));
7244
7175
  console.log("");
7245
7176
  } else {
7246
- recordServiceStopped();
7177
+ bumpStopEpoch();
7247
7178
  }
7248
7179
  captureStopEpochBaseline();
7249
7180
  } else if (!serviceBefore.installed) {
@@ -7424,7 +7355,6 @@ var GITHUB_REPO = "MetaCubeX/mihomo";
7424
7355
  var KERNEL_HTTP_TIMEOUT = 12e4;
7425
7356
  var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
7426
7357
  var GH_DOWNLOAD_TIMEOUT = 1e5;
7427
- var HTTP_CLIENT2 = createHttpClient({ timeout: KERNEL_HTTP_TIMEOUT });
7428
7358
  var execFileAsync2 = promisify3(execFile3);
7429
7359
  function withMirror(url, mirror) {
7430
7360
  if (mirror && url.startsWith("https://github.com/")) {
@@ -7505,8 +7435,7 @@ function pickLatestRelease(releases) {
7505
7435
  function buildReleaseApiCurlArgs(proxy, url) {
7506
7436
  return [
7507
7437
  "-s",
7508
- "-x",
7509
- proxy,
7438
+ ...proxy ? ["-x", proxy] : ["--noproxy", "*"],
7510
7439
  "--proto",
7511
7440
  "=https",
7512
7441
  "--proto-redir",
@@ -7561,7 +7490,6 @@ async function getLatestReleaseViaGh(repo, signal) {
7561
7490
  return pickLatestRelease(JSON.parse(result.stdout));
7562
7491
  }
7563
7492
  async function getLatestRelease(repo, opts) {
7564
- const url = `https://api.github.com/repos/${repo}/releases`;
7565
7493
  if (opts.useGh) {
7566
7494
  try {
7567
7495
  return await getLatestReleaseViaGh(repo, opts.signal);
@@ -7570,35 +7498,33 @@ async function getLatestRelease(repo, opts) {
7570
7498
  opts.onGhFallback?.();
7571
7499
  }
7572
7500
  }
7573
- if (opts.proxy) {
7574
- let stdout;
7575
- try {
7576
- const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(opts.proxy, url), {
7577
- encoding: "utf8",
7578
- maxBuffer: 50 * 1024 * 1024,
7579
- timeout: KERNEL_HTTP_TIMEOUT + 1e4,
7580
- signal: opts.signal,
7581
- // no_proxy 例外表会绕过显式 -x——统一出口置空,保 -x 权威(curl-spawn.ts)
7582
- env: buildCurlSpawnEnv()
7583
- });
7584
- stdout = result.stdout;
7585
- } catch (e) {
7586
- throw translateReleaseApiCurlError(e);
7587
- }
7588
- const { body, statusCode } = parseCurlStatusOutput(stdout);
7589
- if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
7590
- throw createHttpError(statusCode, body);
7591
- }
7592
- let releases;
7593
- try {
7594
- releases = JSON.parse(body);
7595
- } catch {
7596
- throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
7597
- }
7598
- return pickLatestRelease(releases);
7501
+ const url = `https://api.github.com/repos/${repo}/releases`;
7502
+ let stdout;
7503
+ try {
7504
+ const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(opts.proxy, url), {
7505
+ encoding: "utf8",
7506
+ maxBuffer: 50 * 1024 * 1024,
7507
+ timeout: KERNEL_HTTP_TIMEOUT + 1e4,
7508
+ signal: opts.signal,
7509
+ // no_proxy 例外表会绕过显式 -x——统一出口置空,保 -x 权威(curl-spawn.ts)
7510
+ env: buildCurlSpawnEnv()
7511
+ });
7512
+ stdout = result.stdout;
7513
+ } catch (e) {
7514
+ if (opts.signal?.aborted) throw e;
7515
+ throw translateReleaseApiCurlError(e);
7516
+ }
7517
+ const { body, statusCode } = parseCurlStatusOutput(stdout);
7518
+ if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
7519
+ throw createHttpError(statusCode, body);
7599
7520
  }
7600
- const response = await HTTP_CLIENT2.get(url, { responseType: "json", signal: opts.signal });
7601
- return pickLatestRelease(response.data);
7521
+ let releases;
7522
+ try {
7523
+ releases = JSON.parse(body);
7524
+ } catch {
7525
+ throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
7526
+ }
7527
+ return pickLatestRelease(releases);
7602
7528
  }
7603
7529
  async function checkUpdate(opts) {
7604
7530
  const currentVersion = opts.currentVersion !== void 0 ? opts.currentVersion : getKernelVersion();
@@ -7624,7 +7550,6 @@ async function checkUpdate(opts) {
7624
7550
  current: currentDisplay,
7625
7551
  latest: latestVersion,
7626
7552
  needsUpdate,
7627
- assets: latest.assets,
7628
7553
  release: latest,
7629
7554
  ghFallbackToDirect
7630
7555
  };
@@ -7683,18 +7608,9 @@ function buildGhDownloadEnv(proxy) {
7683
7608
  }
7684
7609
  return env;
7685
7610
  }
7686
- function resolveFallbackQueryOptions(channel) {
7687
- if (channel.kind === "gh") {
7688
- return channel.proxy ? { proxy: channel.proxy, useGh: false } : { proxy: null, useGh: true };
7689
- }
7690
- if (channel.kind === "proxy") return { proxy: channel.proxy, useGh: false };
7691
- if (channel.kind === "mirror") return { proxy: channel.proxy ?? null, useGh: false };
7692
- return { proxy: null, useGh: false };
7693
- }
7694
- async function downloadKernel(progressCallback, channel, releaseInfo) {
7611
+ async function downloadKernel(progressCallback, channel, latest) {
7695
7612
  ensureDirs();
7696
- const apiProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
7697
- const latest = releaseInfo || await getLatestRelease(GITHUB_REPO, resolveFallbackQueryOptions(channel));
7613
+ const downloadProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
7698
7614
  const arch = getArch();
7699
7615
  const platform = process.platform;
7700
7616
  const asset = findMatchingAsset(latest.assets, platform, arch);
@@ -7750,7 +7666,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7750
7666
  "curl",
7751
7667
  buildKernelCurlArgs({
7752
7668
  url: downloadUrl,
7753
- proxy: apiProxy,
7669
+ proxy: downloadProxy,
7754
7670
  maxBytes,
7755
7671
  outputPath: tempPath
7756
7672
  }),
@@ -8283,6 +8199,9 @@ function parseProxyArg(args) {
8283
8199
  }
8284
8200
 
8285
8201
  // src/commands/kernel.ts
8202
+ function kernelRestartCommand(state) {
8203
+ return `mihomo-cli stop && ${startCommandForCurrentMode(state)}`;
8204
+ }
8286
8205
  function channelLabel(channel, isExplicitProxy) {
8287
8206
  switch (channel.kind) {
8288
8207
  case "gh":
@@ -8389,30 +8308,16 @@ async function cmdKernel(args) {
8389
8308
  if (useGh) {
8390
8309
  hint.push("", "\u672C\u6B21\u5DF2\u5148\u5C1D\u8BD5 gh \u8BA4\u8BC1\u901A\u9053\u3001\u5931\u8D25\u540E\u624D\u56DE\u9000\u76F4\u8FDE\uFF0C\u53EF\u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8391
8310
  }
8392
- } else if (!mirrorInfo.mirror) {
8393
- if (apiProxy) {
8394
- hint.push("", "\u63D0\u793A: \u7ECF\u4EE3\u7406\u67E5\u8BE2 GitHub \u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u662F\u5426\u53EF\u7528\uFF0C\u6216 mihomo-cli kernel --mirror direct \u91CD\u8BD5\u76F4\u8FDE");
8395
- } else {
8396
- hint.push(
8397
- "",
8398
- "\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF\u6216\u4EE3\u7406:",
8399
- " mihomo-cli kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u88F8 --mirror \u56FA\u5B9A\u88F8\u57DF\uFF0C\u53EF\u7528 v6/v4/cdn \u7B49\u522B\u540D\uFF09",
8400
- ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`,
8401
- " mihomo-cli kernel --proxy <\u7AEF\u53E3> # \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u51FA\u7F51"
8402
- );
8403
- }
8404
8311
  } else if (apiProxy) {
8405
8312
  hint.push("", "\u63D0\u793A: \u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09\u7ECF\u4EE3\u7406\u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u662F\u5426\u53EF\u7528\uFF1B\u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4E0B\u8F7D\uFF0C\u4E0E\u67E5\u8BE2\u65E0\u5173");
8406
- } else if (useGh) {
8407
- hint.push("", "\u63D0\u793A: gh \u8BA4\u8BC1\u901A\u9053\u4E0E\u76F4\u8FDE\u90FD\u5931\u8D25\u4E86\uFF0C\u53EF\u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8408
8313
  } else {
8409
- hint.push(
8410
- "",
8411
- "\u63D0\u793A: \u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4E0B\u8F7D\uFF0C\u7248\u672C\u67E5\u8BE2\u4ECD\u9700\u76F4\u8FDE GitHub API\uFF08\u5F53\u524D\u4E0D\u901A\uFF09\u3002\u51FA\u8DEF:",
8412
- " \u5B89\u88C5\u5E76\u767B\u5F55 GitHub CLI\uFF08\u8BA4\u8BC1\u914D\u989D 5000 \u6B21/\u65F6\uFF09:",
8413
- " brew install gh && gh auth login",
8414
- " \u6216\u7ECF\u672C\u673A\u4EE3\u7406\u5DE5\u5177\u67E5\u8BE2: mihomo-cli kernel --proxy <\u7AEF\u53E3>"
8415
- );
8314
+ hint.push("", `\u63D0\u793A: \u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09${useGh ? "gh \u8BA4\u8BC1\u901A\u9053\u4E0E\u76F4\u8FDE\u90FD" : "\u76F4\u8FDE"}\u5931\u8D25\u3002\u51FA\u8DEF:`);
8315
+ if (useGh) hint.push(" \u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8316
+ else hint.push(" \u5B89\u88C5\u5E76\u767B\u5F55 GitHub CLI\uFF08\u8BA4\u8BC1\u914D\u989D 5000 \u6B21/\u65F6\uFF09: brew install gh && gh auth login");
8317
+ hint.push(" \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u67E5\u8BE2: mihomo-cli kernel --proxy <\u7AEF\u53E3>");
8318
+ if (!mirrorInfo.mirror) {
8319
+ hint.push(` \u4E0B\u8F7D\u8FC7\u6162\u53EF\u52A0\u955C\u50CF: mihomo-cli kernel --mirror [\u955C\u50CF]\uFF08\u53EF\u7528: ${AVAILABLE_MIRRORS.join(", ")}\uFF1B\u955C\u50CF\u4E0D\u4F5C\u7528\u4E8E\u7248\u672C\u67E5\u8BE2\uFF09`);
8320
+ }
8416
8321
  }
8417
8322
  throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
8418
8323
  }
@@ -8447,8 +8352,7 @@ async function cmdKernel(args) {
8447
8352
  \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
8448
8353
  const state = getRunningState();
8449
8354
  if (state.running) {
8450
- const restartCommand = startCommandForCurrentMode(state);
8451
- console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${restartCommand} \u91CD\u542F\u540E\u751F\u6548`));
8355
+ console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${kernelRestartCommand(state)} \u540E\u751F\u6548`));
8452
8356
  }
8453
8357
  console.log(colors.gray("\u63D0\u793A: \u82E5\u4F7F\u7528\u5C40\u57DF\u7F51\u8282\u70B9\uFF08192.168/10.x/*.local\uFF09\uFF0C\u9996\u6B21\u542F\u52A8\u53EF\u80FD\u91CD\u65B0\u5F39\u51FA\u300C\u672C\u5730\u7F51\u7EDC\u300D\u6388\u6743"));
8454
8358
  }
@@ -8560,7 +8464,7 @@ function printOverwriteList() {
8560
8464
  console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
8561
8465
  }
8562
8466
  if (f.kind === "script") {
8563
- console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF1B\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605\u65F6\u672B\u5C3E return true\uFF0Cstatus \u636E\u6B64\u533A\u5206\u751F\u6548\u4E0E\u4E0D\u9002\u7528\uFF09`);
8467
+ console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF1B\u4F5C\u7528\u57DF\u7531\u811A\u672C\u81EA\u884C\u5224\u65AD\uFF09`);
8564
8468
  } else if (f.keys.length > 0) {
8565
8469
  console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
8566
8470
  }
@@ -8715,10 +8619,10 @@ async function cmdReset(args) {
8715
8619
  hint: [MANUAL_PKILL_HINT]
8716
8620
  });
8717
8621
  }
8718
- if (!serviceActive && (cleanup.scriptError !== null || cleanup.pidError !== null)) {
8622
+ if (!serviceActive && cleanup.incomplete !== null) {
8719
8623
  warnResidueCleanup(cleanup, { mainOutcome: "\u91CD\u7F6E\u7EE7\u7EED\u6267\u884C", retryCommand: "mihomo-cli stop" });
8720
8624
  }
8721
- recordServiceStopped();
8625
+ bumpStopEpoch();
8722
8626
  }
8723
8627
  if (!needsStop && serviceTargeted && cleanup !== null && cleanup.remaining.length > 0) {
8724
8628
  printResidueWarning(cleanup.remaining);
@@ -8835,7 +8739,7 @@ async function cmdUninstall(args) {
8835
8739
  }
8836
8740
  console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo-cli install"));
8837
8741
  console.log(colors.gray("\u5F7B\u5E95\u79FB\u9664 mihomo-cli:"));
8838
- console.log(colors.gray(" mihomo-cli reset --full # \u5220\u9664\u5168\u90E8\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
8742
+ console.log(colors.gray(" mihomo-cli reset --full # \u5220\u9664\u53D7\u7BA1\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
8839
8743
  console.log(colors.gray(" npm uninstall -g mihomo-cli"));
8840
8744
  console.log("");
8841
8745
  }
@@ -8853,14 +8757,14 @@ async function cmdStop(args) {
8853
8757
  const pids = getMihomoPids();
8854
8758
  const needsServiceWork = status.loaded || status.installed && !status.disabled;
8855
8759
  if (!needsServiceWork && pids.length === 0) {
8856
- recordServiceStopped();
8760
+ bumpStopEpoch();
8857
8761
  console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
8858
8762
  return;
8859
8763
  }
8860
8764
  if (!needsServiceWork) {
8861
8765
  console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
8862
8766
  handleStopResult(await stop());
8863
- recordServiceStopped();
8767
+ bumpStopEpoch();
8864
8768
  console.log(colors.green("\u5DF2\u505C\u6B62"));
8865
8769
  return;
8866
8770
  }
@@ -9250,7 +9154,7 @@ var COMMANDS = [
9250
9154
  aliases: [],
9251
9155
  handler: cmdConfig,
9252
9156
  group: "config",
9253
- usage: [{ signature: "config [-j|--json] [--reveal]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9157
+ usage: [{ signature: "config [-j|--json] [--reveal]", description: "\u9884\u89C8\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u7F13\u5B58\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9254
9158
  },
9255
9159
  {
9256
9160
  name: "overwrite",
@@ -9278,7 +9182,7 @@ var COMMANDS = [
9278
9182
  aliases: [],
9279
9183
  handler: cmdKernel,
9280
9184
  group: "system",
9281
- usage: [{ signature: "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1A\u672C\u673A\u4EE3\u7406 > gh > \u76F4\u8FDE\uFF09" }]
9185
+ usage: [{ signature: "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u6309\u73AF\u5883\u9009\u62E9\u672C\u673A\u4EE3\u7406\u3001gh \u6216\u76F4\u8FDE\uFF09" }]
9282
9186
  },
9283
9187
  {
9284
9188
  name: "update",
@@ -9292,7 +9196,9 @@ var COMMANDS = [
9292
9196
  aliases: [],
9293
9197
  handler: cmdReset,
9294
9198
  group: "system",
9295
- usage: [{ signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199/\u670D\u52A1\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }]
9199
+ usage: [
9200
+ { signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199/\u670D\u52A1\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\u53D7\u7BA1\u76EE\u6807\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }
9201
+ ]
9296
9202
  },
9297
9203
  {
9298
9204
  name: "doctor",
@@ -9400,11 +9306,11 @@ function assertNotRoot(commandName) {
9400
9306
  });
9401
9307
  }
9402
9308
  function assertSupportedNodeVersion(commandName) {
9403
- if (!MIN_NODE_VERSION) return;
9309
+ if (!NODE_ENGINES) return;
9404
9310
  if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
9405
9311
  const current = process.versions.node;
9406
- if (compareVersions(current, MIN_NODE_VERSION) >= 0) return;
9407
- throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 >= ${MIN_NODE_VERSION}\uFF09`, {
9312
+ if (satisfies(current, NODE_ENGINES)) return;
9313
+ throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 ${NODE_ENGINES}\uFF09`, {
9408
9314
  label: "Node \u7248\u672C\u4E0D\u652F\u6301",
9409
9315
  hint: ["\u5347\u7EA7 Node \u540E\u91CD\u8BD5\uFF0C\u4F8B\u5982:", " brew upgrade node", " \u6216\u7528 nvm: nvm install --lts && nvm use --lts", "", `\u5F53\u524D\u89E3\u91CA\u5668: ${process.execPath}`]
9410
9316
  });