mihomo-cli 4.7.7 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,60 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // node_modules/compare-versions/lib/esm/utils.js
4
+ var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
5
+ var validateAndParse = (version) => {
6
+ if (typeof version !== "string") {
7
+ throw new TypeError("Invalid argument expected string");
8
+ }
9
+ const match = version.match(semver);
10
+ if (!match) {
11
+ throw new Error(`Invalid argument not valid semver ('${version}' received)`);
12
+ }
13
+ match.shift();
14
+ return match;
15
+ };
16
+ var isWildcard = (s) => s === "*" || s === "x" || s === "X";
17
+ var tryParse = (v) => {
18
+ const n = parseInt(v, 10);
19
+ return isNaN(n) ? v : n;
20
+ };
21
+ var forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];
22
+ var compareStrings = (a, b) => {
23
+ if (isWildcard(a) || isWildcard(b))
24
+ return 0;
25
+ const [ap, bp] = forceType(tryParse(a), tryParse(b));
26
+ if (ap > bp)
27
+ return 1;
28
+ if (ap < bp)
29
+ return -1;
30
+ return 0;
31
+ };
32
+ var compareSegments = (a, b) => {
33
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
34
+ const r = compareStrings(a[i] || "0", b[i] || "0");
35
+ if (r !== 0)
36
+ return r;
37
+ }
38
+ return 0;
39
+ };
40
+
41
+ // node_modules/compare-versions/lib/esm/compareVersions.js
42
+ var compareVersions = (v1, v2) => {
43
+ const n1 = validateAndParse(v1);
44
+ const n2 = validateAndParse(v2);
45
+ const p1 = n1.pop();
46
+ const p2 = n2.pop();
47
+ const r = compareSegments(n1, n2);
48
+ if (r !== 0)
49
+ return r;
50
+ if (p1 && p2) {
51
+ return compareSegments(p1.split("."), p2.split("."));
52
+ } else if (p1 || p2) {
53
+ return p1 ? -1 : 1;
54
+ }
55
+ return 0;
56
+ };
57
+
3
58
  // src/colors.ts
4
59
  var NO_COLOR = process.env.NO_COLOR !== void 0 || !process.stdout.isTTY;
5
60
  function colorize(code, str) {
@@ -16,8 +71,10 @@ var colors = {
16
71
  };
17
72
 
18
73
  // src/config.ts
19
- import { spawnSync } from "child_process";
74
+ import { execFile, spawnSync } from "child_process";
20
75
  import fs4 from "fs";
76
+ import path4 from "path";
77
+ import { promisify } from "util";
21
78
 
22
79
  // node_modules/js-yaml/dist/js-yaml.mjs
23
80
  var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
@@ -3060,6 +3117,12 @@ var require2 = createRequire(import.meta.url);
3060
3117
  var pkg = require2("../package.json");
3061
3118
  var VERSION = pkg.version;
3062
3119
  var PKG_NAME = pkg.name;
3120
+ var MIN_NODE_VERSION = (() => {
3121
+ const raw = pkg.engines?.node;
3122
+ if (typeof raw !== "string") return null;
3123
+ const m = raw.trim().match(/^>=\s*(\d+\.\d+\.\d+)$/);
3124
+ return m ? m[1] : null;
3125
+ })();
3063
3126
  var MIRROR_HOST = "gh-proxy.org";
3064
3127
  var MIRROR_ALIASES = {
3065
3128
  v4: `https://v4.${MIRROR_HOST}/`,
@@ -3224,9 +3287,6 @@ var PATHS = {
3224
3287
  * 它不是锁,不该进 `paths.spec.ts` 那条锁位置断言的枚举。
3225
3288
  */
3226
3289
  serviceStopEpoch: path.join(USER_DATA_DIR, "service-stop-epoch"),
3227
- configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
3228
- configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
3229
- configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
3230
3290
  // 用户级 LaunchAgent(默认):gui/<uid> 域,全程免 sudo。随 homedir 走
3231
3291
  userAgentPlist: path.join(os.homedir(), "Library/LaunchAgents", `${SERVICE_LABEL}.plist`),
3232
3292
  // 旧版本(v3.0–v4.0 的 daemon on)装的系统级 LaunchDaemon:root:wheel 拥有。
@@ -3333,35 +3393,20 @@ function sleepSyncMs(ms) {
3333
3393
  // src/settings.ts
3334
3394
  import fs2 from "fs";
3335
3395
  import path2 from "path";
3336
- var settingsCache = null;
3337
3396
  function readSettings() {
3338
- if (settingsCache !== null) return settingsCache;
3339
- ensureDirs();
3340
- if (fs2.existsSync(PATHS.settingsFile)) {
3341
- let parsed;
3342
- try {
3343
- parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
3344
- } catch {
3345
- return recoverCorruptedSettings();
3346
- }
3347
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
3348
- return recoverCorruptedSettings();
3349
- }
3350
- settingsCache = parsed;
3351
- return settingsCache;
3397
+ if (!fs2.existsSync(PATHS.settingsFile)) return {};
3398
+ try {
3399
+ const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
3400
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
3401
+ } catch {
3352
3402
  }
3353
- settingsCache = {};
3354
- return settingsCache;
3355
- }
3356
- function recoverCorruptedSettings() {
3357
3403
  try {
3358
3404
  fs2.copyFileSync(PATHS.settingsFile, `${PATHS.settingsFile}.bak`);
3359
3405
  console.warn(`\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5907\u4EFD\u5230 ${PATHS.settingsFile}.bak\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3360
3406
  } catch {
3361
3407
  console.warn("\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
3362
3408
  }
3363
- settingsCache = {};
3364
- return settingsCache;
3409
+ return {};
3365
3410
  }
3366
3411
  function isValidSettingsContent(content) {
3367
3412
  try {
@@ -3372,31 +3417,22 @@ function isValidSettingsContent(content) {
3372
3417
  }
3373
3418
  }
3374
3419
  function writeSettings(settings) {
3375
- ensureDirs();
3376
- return withFileLock(PATHS.settingsLock, () => writeSettingsUnlocked(settings));
3377
- }
3378
- function writeSettingsUnlocked(settings) {
3379
- settingsCache = null;
3380
- const existing = readSettings();
3381
- const merged = { ...existing, ...settings };
3382
- for (const key of Object.keys(settings)) {
3383
- if (settings[key] === void 0) delete merged[key];
3384
- }
3385
- atomicWriteFileSync(PATHS.settingsFile, JSON.stringify(merged, null, 2), { mode: 384 });
3386
- settingsCache = merged;
3387
- return settingsCache;
3420
+ return updateSettings(() => settings);
3388
3421
  }
3389
3422
  function updateSettings(mutate) {
3390
3423
  ensureDirs();
3391
3424
  return withFileLock(PATHS.settingsLock, () => {
3392
- settingsCache = null;
3393
3425
  const current = readSettings();
3394
- return writeSettingsUnlocked(mutate(current));
3426
+ const patch = mutate(current);
3427
+ if (Object.keys(patch).length === 0) return current;
3428
+ const merged = { ...current, ...patch };
3429
+ for (const [key, value] of Object.entries(patch)) {
3430
+ if (value === void 0) delete merged[key];
3431
+ }
3432
+ atomicWriteFileSync(PATHS.settingsFile, JSON.stringify(merged, null, 2), { mode: 384 });
3433
+ return merged;
3395
3434
  });
3396
3435
  }
3397
- function invalidateSettingsCache() {
3398
- settingsCache = null;
3399
- }
3400
3436
  function validatePort(value, key) {
3401
3437
  if (value === void 0) return void 0;
3402
3438
  if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 65535) {
@@ -3407,8 +3443,8 @@ function validatePort(value, key) {
3407
3443
  }
3408
3444
  return value;
3409
3445
  }
3410
- function getPorts() {
3411
- const ports = readSettings().ports;
3446
+ function getPorts(settings = readSettings()) {
3447
+ const ports = settings.ports;
3412
3448
  if (ports === void 0) return { mixed: DEFAULT_MIXED_PORT, controller: CONTROLLER_PORT };
3413
3449
  if (ports === null || typeof ports !== "object" || Array.isArray(ports)) {
3414
3450
  throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
@@ -3512,8 +3548,8 @@ function deleteSubscriptionCache(subName) {
3512
3548
  function isValidSubscription(s) {
3513
3549
  return s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string";
3514
3550
  }
3515
- function getSubscriptions() {
3516
- const list = readSettings().subscriptions;
3551
+ function getSubscriptions(settings = readSettings()) {
3552
+ const list = settings.subscriptions;
3517
3553
  if (!Array.isArray(list)) {
3518
3554
  if (list !== void 0) {
3519
3555
  console.warn("\u8B66\u544A: settings.json \u7684 subscriptions \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0\uFF09");
@@ -3538,29 +3574,22 @@ function validateSubscriptionName(name) {
3538
3574
  }
3539
3575
  function addSubscription(url, name = "default") {
3540
3576
  validateSubscriptionName(name);
3541
- let duplicate = false;
3542
3577
  updateSettings((settings) => {
3543
- const subs = [...getSubscriptions()];
3578
+ const subs = getSubscriptions(settings);
3544
3579
  if (subs.some((s) => s.name === name)) {
3545
- duplicate = true;
3546
- return {};
3580
+ throw new CliError(`\u8BA2\u9605 "${name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo sub remove ${name}\uFF09`);
3547
3581
  }
3548
3582
  subs.push({ name, url });
3549
3583
  const updates = { subscriptions: subs };
3550
- if (!settings.active_subscription && subs.length === 1) {
3551
- updates.active_subscription = name;
3552
- }
3584
+ if (!settings.active_subscription && subs.length === 1) updates.active_subscription = name;
3553
3585
  return updates;
3554
3586
  });
3555
- if (duplicate) {
3556
- throw new CliError(`\u8BA2\u9605 "${name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo sub remove ${name}\uFF09`);
3557
- }
3558
3587
  }
3559
3588
  function removeSubscription(name) {
3560
3589
  let switchedTo = null;
3561
3590
  let found = false;
3562
3591
  updateSettings((settings) => {
3563
- const subs = [...getSubscriptions()];
3592
+ const subs = getSubscriptions(settings);
3564
3593
  const idx = subs.findIndex((s) => s.name === name);
3565
3594
  if (idx < 0) return {};
3566
3595
  found = true;
@@ -3581,13 +3610,12 @@ function removeSubscription(name) {
3581
3610
  return switchedTo;
3582
3611
  }
3583
3612
  function setDefaultSubscription(name) {
3584
- const settings = readSettings();
3585
- const subs = getSubscriptions();
3586
- const idx = subs.findIndex((s) => s.name === name);
3587
- if (idx < 0) return false;
3588
- if (settings.active_subscription === name) return true;
3589
- writeSettings({ active_subscription: name });
3590
- return true;
3613
+ let found = false;
3614
+ updateSettings((settings) => {
3615
+ found = getSubscriptions(settings).some((s) => s.name === name);
3616
+ return found ? { active_subscription: name } : {};
3617
+ });
3618
+ return found;
3591
3619
  }
3592
3620
  function getSubscriptionRawConfigPath(subName) {
3593
3621
  if (!SAFE_NAME_RE.test(subName)) {
@@ -3838,14 +3866,9 @@ function loadOverwriteFile() {
3838
3866
  }
3839
3867
  return results;
3840
3868
  }
3841
- function applyOverwrite(baseConfig, preloadedFiles) {
3842
- if (!isOverwriteEnabled()) return { ...baseConfig };
3843
- const overwriteFiles = preloadedFiles || loadOverwriteFile();
3844
- if (overwriteFiles.length === 0) return { ...baseConfig };
3869
+ function applyOverwrite(baseConfig, files) {
3845
3870
  let result = { ...baseConfig };
3846
- for (const file of overwriteFiles) {
3847
- result = deepMergeWithOverrides(result, file.config);
3848
- }
3871
+ for (const file of files) result = deepMergeWithOverrides(result, file.config);
3849
3872
  return result;
3850
3873
  }
3851
3874
  function listOverwriteFile() {
@@ -3875,7 +3898,7 @@ var FLAGS = [
3875
3898
  { forms: ["-n", "--lines"], takesValue: true }
3876
3899
  // 注意:`--mirror`(kernel)是可选值选项——`--mirror`、`--mirror=url`、`--mirror url`
3877
3900
  // 三种形式都合法,只走 parseMirrorArg。故意不在此登记:登记了 getNonFlagArg 反而会
3878
- // 把它的值吞掉。它的移除/校验由 parseMirrorArg 自己负责。
3901
+ // 把它的值吞掉。它的解析与校验由 parseMirrorArg 自己负责。
3879
3902
  ];
3880
3903
  var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
3881
3904
  var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
@@ -3995,8 +4018,8 @@ function assertKnownFlags(args, known, command) {
3995
4018
  if (!a.startsWith("-") || a === "-") continue;
3996
4019
  if (knownSet.has(a)) continue;
3997
4020
  const eqIdx = a.indexOf("=");
3998
- if (eqIdx > 0 && knownSet.has(a.slice(0, eqIdx))) continue;
3999
- if (a.length > 2 && a.startsWith("-") && !a.startsWith("--") && knownSet.has(a.slice(0, 2))) continue;
4021
+ if (eqIdx > 0 && knownSet.has(a.slice(0, eqIdx)) && (VALUE_FLAGS.has(a.slice(0, eqIdx)) || a.slice(0, eqIdx) === "--mirror")) continue;
4022
+ if (a.length > 2 && a.startsWith("-") && !a.startsWith("--") && knownSet.has(a.slice(0, 2)) && VALUE_FLAGS.has(a.slice(0, 2))) continue;
4000
4023
  throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
4001
4024
  label: "\u53C2\u6570\u9519\u8BEF",
4002
4025
  hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
@@ -4031,17 +4054,6 @@ function parseIntArg(args, short, long, defaultValue) {
4031
4054
  }
4032
4055
  return defaultValue;
4033
4056
  }
4034
- function assertNoRemovedSshFlag(args) {
4035
- if (!args?.some((a) => a === "--no-ssh" || a.startsWith("--no-ssh="))) return;
4036
- throw new CliError("--no-ssh \u5DF2\u79FB\u9664\uFF08v4.0.0\uFF09", {
4037
- label: "\u53C2\u6570\u9519\u8BEF",
4038
- hint: [
4039
- "ssh \u96A7\u9053\u529F\u80FD\u5DF2\u6574\u4F53\u79FB\u9664\uFF0C\u8BE5\u9009\u9879\u4E0D\u518D\u6709\u5BF9\u5E94\u884C\u4E3A\u3002",
4040
- "\u5982\u4ECD\u9700\u5185\u7F51\u51FA\u53E3\uFF1A\u81EA\u884C\u8FD0\u884C ssh -D 127.0.0.1:<\u7AEF\u53E3> -N <\u4E3B\u673A>\uFF0C",
4041
- "\u8282\u70B9\u4E0E\u5206\u6D41\u89C4\u5219\u5199\u5728 overwrite.yaml \u91CC\uFF08\u5199\u6CD5\u89C1 CHANGELOG \u7684 4.0.0 \u5347\u7EA7\u987B\u77E5\uFF09\u3002"
4042
- ]
4043
- });
4044
- }
4045
4057
  function extractStartOptions(args) {
4046
4058
  if (!args) return [];
4047
4059
  const out = [];
@@ -4139,23 +4151,7 @@ function parseMirrorArg(args) {
4139
4151
  if (!args || args.length < 2) {
4140
4152
  return { mirror: null, isOverride: false };
4141
4153
  }
4142
- if (args.some((a) => a === "--mirror-all" || a.startsWith("--mirror-all="))) {
4143
- throw new CliError("--mirror-all \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF09", {
4144
- label: "\u53C2\u6570\u9519\u8BEF",
4145
- hint: [
4146
- "\u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09\u7EDD\u4E0D\u7ECF\u8FC7\u955C\u50CF\uFF0C\u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4EA7\u7269\u4E0B\u8F7D\u3002",
4147
- "API \u82E5\u8D70\u955C\u50CF\uFF0C\u4E0B\u8F7D\u5730\u5740\u5C31\u7531\u955C\u50CF\u8BF4\u4E86\u7B97\uFF0C\u800C\u5185\u6838\u968F\u540E\u4EE5 root \u8FD0\u884C\u3002",
4148
- "",
4149
- "\u6539\u7528: mihomo kernel --mirror [\u955C\u50CF]"
4150
- ]
4151
- });
4152
- }
4153
- if (args.includes("--no-mirror") || args.includes("--direct")) {
4154
- throw new CliError("--no-mirror/--direct \u5DF2\u79FB\u9664\uFF08v4.7.0\uFF09", {
4155
- label: "\u53C2\u6570\u9519\u8BEF",
4156
- hint: ["\u5F3A\u5236\u76F4\u8FDE\u6539\u7528: mihomo kernel --mirror direct", "\u4E0D\u5E26\u9009\u9879\u65F6\u81EA\u52A8\u9009\u62E9\u901A\u9053: gh > \u672C\u673A\u4EE3\u7406 > \u955C\u50CF > \u76F4\u8FDE"]
4157
- });
4158
- }
4154
+ assertKnownFlags(args.slice(1), ["--mirror"], "kernel [--mirror [\u955C\u50CF]]");
4159
4155
  const mirrorEq = args.find((a) => a.startsWith("--mirror="));
4160
4156
  const mirrorIdx = args.indexOf("--mirror");
4161
4157
  if (mirrorIdx >= 0 || mirrorEq) {
@@ -4194,64 +4190,6 @@ function parseConfigContent(content, errorMsg) {
4194
4190
  function dumpYaml(obj) {
4195
4191
  return dump(obj, { indent: 2, lineWidth: -1 });
4196
4192
  }
4197
- function collectOverwriteProxyNames(overwriteFiles, baseProxyNames) {
4198
- const names = [];
4199
- for (const file of overwriteFiles) {
4200
- for (const [key, value] of Object.entries(file.config)) {
4201
- if ((key === "+proxies" || key === "proxies+" || key === "~proxies") && Array.isArray(value)) {
4202
- for (const proxy of value) {
4203
- if (proxy && typeof proxy === "object" && "name" in proxy) {
4204
- const name = proxy.name;
4205
- if (typeof name !== "string" || name.length === 0) continue;
4206
- if (key === "~proxies" && baseProxyNames.has(name)) continue;
4207
- names.push(name);
4208
- }
4209
- }
4210
- }
4211
- }
4212
- }
4213
- return names;
4214
- }
4215
- function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, baseProxyNames = /* @__PURE__ */ new Set()) {
4216
- const injectedNames = collectOverwriteProxyNames(overwriteFiles, baseProxyNames);
4217
- if (injectedNames.length === 0) return;
4218
- const groups = config["proxy-groups"];
4219
- if (!groups) return;
4220
- const excludePattern = `^(?:${injectedNames.map((n) => escapeRegExp(n)).join("|")})$`;
4221
- for (const group of groups) {
4222
- if (!group["include-all"] && !group["include-all-proxies"]) continue;
4223
- const existing = group["exclude-filter"];
4224
- if (existing) {
4225
- group["exclude-filter"] = `${existing}|${excludePattern}`;
4226
- } else {
4227
- group["exclude-filter"] = excludePattern;
4228
- }
4229
- }
4230
- }
4231
- var BUILTIN_PROXY_NAMES = /* @__PURE__ */ new Set(["DIRECT", "REJECT", "REJECT-DROP", "PASS", "COMPATIBLE"]);
4232
- function deduplicateByName(items) {
4233
- const names = /* @__PURE__ */ new Set();
4234
- const duplicates = [];
4235
- const result = items.filter((item) => {
4236
- if (names.has(item.name)) {
4237
- duplicates.push(item.name);
4238
- return false;
4239
- }
4240
- names.add(item.name);
4241
- return true;
4242
- });
4243
- return { result, names, duplicates };
4244
- }
4245
- var NON_TARGET_RULE_TYPES = /* @__PURE__ */ new Set(["SUB-RULE"]);
4246
- function getRuleTarget(rule) {
4247
- const parts = rule.split(",");
4248
- if (parts.length < 2) return "";
4249
- const last = parts[parts.length - 1].trim();
4250
- if (last.toLowerCase() === "no-resolve" && parts.length >= 3) {
4251
- return parts[parts.length - 2].trim();
4252
- }
4253
- return last;
4254
- }
4255
4193
  function assertDnsShape(dnsRaw) {
4256
4194
  if (dnsRaw === void 0 || dnsRaw === null) return;
4257
4195
  if (typeof dnsRaw !== "object" || Array.isArray(dnsRaw)) {
@@ -4312,109 +4250,12 @@ function assertConfigShape(config) {
4312
4250
  }
4313
4251
  }
4314
4252
  }
4315
- function validateConfig(config) {
4316
- assertConfigShape(config);
4317
- const warnings = [];
4318
- const proxies = config.proxies || [];
4319
- const groups = config["proxy-groups"] || [];
4320
- const rules = config.rules || [];
4321
- const proxyDedup = deduplicateByName(proxies);
4322
- config.proxies = proxyDedup.result;
4323
- if (proxyDedup.duplicates.length > 0) {
4324
- const preview = proxyDedup.duplicates.slice(0, 3).map((n) => `"${n}"`).join(", ");
4325
- warnings.push(`\u79FB\u9664\u4E86 ${proxyDedup.duplicates.length} \u4E2A\u91CD\u540D\u8282\u70B9: ${preview}${proxyDedup.duplicates.length > 3 ? " ..." : ""}`);
4326
- }
4327
- const groupDedup = deduplicateByName(groups);
4328
- config["proxy-groups"] = groupDedup.result;
4329
- if (groupDedup.duplicates.length > 0) {
4330
- warnings.push(`\u79FB\u9664\u4E86 ${groupDedup.duplicates.length} \u4E2A\u91CD\u540D\u5206\u7EC4: ${groupDedup.duplicates.map((n) => `"${n}"`).join(", ")}`);
4331
- }
4332
- const validNames = /* @__PURE__ */ new Set([...BUILTIN_PROXY_NAMES, ...proxyDedup.names, ...groupDedup.names]);
4333
- for (const name of groupDedup.names) {
4334
- if (proxyDedup.names.has(name)) {
4335
- warnings.push(`\u540D\u79F0\u51B2\u7A81: "${name}" \u540C\u65F6\u662F\u8282\u70B9\u548C\u5206\u7EC4\u540D\uFF0Cmihomo \u4F1A\u62D2\u7EDD\u52A0\u8F7D\uFF08\u8BF7\u91CD\u547D\u540D\u5176\u4E00\uFF09`);
4336
- }
4337
- }
4338
- const providerNames = new Set(
4339
- config["proxy-providers"] && typeof config["proxy-providers"] === "object" && !Array.isArray(config["proxy-providers"]) ? Object.keys(config["proxy-providers"]) : []
4340
- );
4341
- const activeGroups = groupDedup.result;
4342
- const removedGroups = /* @__PURE__ */ new Set();
4343
- let changed = true;
4344
- while (changed) {
4345
- changed = false;
4346
- for (const group of activeGroups) {
4347
- if (removedGroups.has(group.name)) continue;
4348
- if (group.proxies !== void 0 && !Array.isArray(group.proxies)) {
4349
- if (typeof group.proxies === "string") {
4350
- warnings.push(`proxy-group "${group.name}": proxies \u5E94\u4E3A\u5217\u8868\uFF0C\u5DF2\u6309\u5355\u5143\u7D20\u5904\u7406\uFF08"${group.proxies}"\uFF09`);
4351
- group.proxies = [group.proxies];
4352
- } else {
4353
- warnings.push(`proxy-group "${group.name}": proxies \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5B57\u6BB5`);
4354
- group.proxies = [];
4355
- }
4356
- }
4357
- if (!Array.isArray(group.proxies)) continue;
4358
- if (Array.isArray(group.use)) {
4359
- const ghosts = group.use.filter((u) => typeof u === "string" && !providerNames.has(u));
4360
- if (ghosts.length > 0) {
4361
- group.use = group.use.filter((u) => providerNames.has(u));
4362
- warnings.push(`proxy-group "${group.name}": \u79FB\u9664\u4E86\u4E0D\u5B58\u5728\u7684 provider \u5F15\u7528 ${ghosts.map((n) => `"${n}"`).join(", ")}`);
4363
- }
4364
- }
4365
- const invalid = group.proxies.filter((name) => !validNames.has(name));
4366
- if (invalid.length > 0) {
4367
- group.proxies = group.proxies.filter((name) => validNames.has(name));
4368
- warnings.push(`proxy-group "${group.name}": \u79FB\u9664\u4E86\u4E0D\u5B58\u5728\u7684\u5F15\u7528 ${invalid.map((n) => `"${n}"`).join(", ")}`);
4369
- }
4370
- const hasUse = Array.isArray(group.use) ? group.use.length > 0 : Boolean(group.use);
4371
- const includesAll = Boolean(group["include-all"] || group["include-all-proxies"]);
4372
- const includeAllUsable = includesAll && proxyDedup.result.length > 0;
4373
- const hasOtherSource = hasUse || includeAllUsable;
4374
- if (group.proxies.length === 0 && !hasOtherSource) {
4375
- removedGroups.add(group.name);
4376
- validNames.delete(group.name);
4377
- warnings.push(`proxy-group "${group.name}": \u5DF2\u79FB\u9664\uFF08\u65E0\u53EF\u7528\u8282\u70B9\uFF09`);
4378
- changed = true;
4379
- }
4380
- }
4381
- }
4382
- if (removedGroups.size > 0) {
4383
- config["proxy-groups"] = activeGroups.filter((g) => !removedGroups.has(g.name));
4384
- }
4385
- if (rules.length > 0) {
4386
- const removedRules = [];
4387
- config.rules = rules.filter((rule) => {
4388
- const ruleType = rule.split(",")[0]?.trim().toUpperCase();
4389
- if (NON_TARGET_RULE_TYPES.has(ruleType)) return true;
4390
- const target = getRuleTarget(rule);
4391
- if (!target || validNames.has(target)) return true;
4392
- removedRules.push(rule);
4393
- return false;
4394
- });
4395
- if (removedRules.length > 0) {
4396
- warnings.push(`\u79FB\u9664\u4E86 ${removedRules.length} \u6761\u5F15\u7528\u4E0D\u5B58\u5728\u76EE\u6807\u7684\u89C4\u5219`);
4397
- }
4398
- }
4399
- return warnings;
4400
- }
4401
4253
  function buildConfig(subRawContent, mode, scope) {
4402
4254
  const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
4403
- if (!subscriptionConfig) {
4404
- throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
4405
- }
4406
- const overwriteEnabled = isOverwriteEnabled();
4407
- const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
4255
+ const settings = readSettings();
4256
+ const allFiles = settings.overwrite_enabled !== false ? loadOverwriteFile() : [];
4408
4257
  const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
4409
- const working = structuredClone(subscriptionConfig);
4410
- const withOverwrites = applyOverwrite(working, overwriteFiles);
4411
- if (overwriteFiles.length > 0) {
4412
- const baseProxies = Array.isArray(subscriptionConfig.proxies) ? subscriptionConfig.proxies : [];
4413
- const baseProxyNames = new Set(
4414
- baseProxies.filter((p) => p && typeof p === "object" && typeof p.name === "string").map((p) => p.name)
4415
- );
4416
- excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles, baseProxyNames);
4417
- }
4258
+ const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
4418
4259
  const systemConfig = {};
4419
4260
  const lockedWarnings = [];
4420
4261
  for (const [key, value] of Object.entries(BASE_CONFIG)) {
@@ -4422,7 +4263,7 @@ function buildConfig(subRawContent, mode, scope) {
4422
4263
  systemConfig[key] = value;
4423
4264
  }
4424
4265
  }
4425
- const ports = getPorts();
4266
+ const ports = getPorts(settings);
4426
4267
  systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
4427
4268
  systemConfig["mixed-port"] = ports.mixed;
4428
4269
  delete withOverwrites["mixed-port"];
@@ -4432,7 +4273,7 @@ function buildConfig(subRawContent, mode, scope) {
4432
4273
  delete withOverwrites["external-ui-name"];
4433
4274
  delete withOverwrites["external-ui-url"];
4434
4275
  delete withOverwrites.secret;
4435
- const controllerSecret = readSettings().controller_secret;
4276
+ const controllerSecret = settings.controller_secret;
4436
4277
  if (controllerSecret) {
4437
4278
  systemConfig.secret = controllerSecret;
4438
4279
  }
@@ -4468,24 +4309,39 @@ function buildConfig(subRawContent, mode, scope) {
4468
4309
  "skip-domain": ["+.push.apple.com"]
4469
4310
  };
4470
4311
  }
4471
- const warnings = [...lockedWarnings, ...validateConfig(merged)];
4472
- return { config: merged, subscriptionConfig, overwriteFiles, systemConfig, warnings };
4312
+ assertConfigShape(merged);
4313
+ return { config: merged, warnings: lockedWarnings };
4473
4314
  }
4474
4315
  function writeMihomoConfig(configObj) {
4475
4316
  ensureDirs();
4476
4317
  const content = dumpYaml(configObj);
4477
4318
  atomicWriteFileSync(PATHS.configFile, content, { mode: 384 });
4478
4319
  }
4479
- function writeDebugConfig(buildResult) {
4320
+ async function validateConfigWithKernel(config) {
4321
+ if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
4480
4322
  ensureDirs();
4481
- fs4.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
4482
- const overwriteMerged = {};
4483
- for (const f of buildResult.overwriteFiles) {
4484
- Object.assign(overwriteMerged, f.config);
4323
+ const stageDir = fs4.mkdtempSync(path4.join(DIRS.runtime, "check-"));
4324
+ const stageFile = path4.join(stageDir, "config.yaml");
4325
+ try {
4326
+ fs4.writeFileSync(stageFile, dumpYaml(config), { mode: 384 });
4327
+ try {
4328
+ await promisify(execFile)(PATHS.mihomoBinary, ["-t", "-d", DIRS.data, "-f", stageFile], {
4329
+ encoding: "utf8",
4330
+ timeout: 3e4,
4331
+ maxBuffer: 1024 * 1024
4332
+ });
4333
+ } catch (e) {
4334
+ const error = e;
4335
+ const detail = sanitizeTerminal(`${error.stdout || ""}
4336
+ ${error.stderr || ""}`).trim();
4337
+ throw new CliError(error.killed ? "\u5185\u6838\u914D\u7F6E\u6821\u9A8C\u8D85\u65F6" : "\u5185\u6838\u62D2\u7EDD\u52A0\u8F7D\u914D\u7F6E", {
4338
+ label: "\u914D\u7F6E\u9519\u8BEF",
4339
+ hint: [detail || error.message, "", "\u8BF7\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002"]
4340
+ });
4341
+ }
4342
+ } finally {
4343
+ fs4.rmSync(stageDir, { recursive: true, force: true });
4485
4344
  }
4486
- const overwriteContent = buildResult.overwriteFiles.length > 0 ? dumpYaml(overwriteMerged) : "# overwrite \u5DF2\u7981\u7528\u6216\u65E0\u8986\u5199\u6587\u4EF6\n";
4487
- fs4.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
4488
- fs4.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
4489
4345
  }
4490
4346
  function hasConfig() {
4491
4347
  return fs4.existsSync(PATHS.configFile);
@@ -4503,8 +4359,6 @@ function getConfigInfo() {
4503
4359
  proxies: proxies ? proxies.length : 0,
4504
4360
  proxyGroups: proxyGroups ? proxyGroups.length : 0,
4505
4361
  mixedPort: cfg["mixed-port"] || null,
4506
- httpPort: cfg.port || null,
4507
- socksPort: cfg["socks-port"] || null,
4508
4362
  tun: tun ? !!tun.enable : false
4509
4363
  };
4510
4364
  } catch {
@@ -4546,11 +4400,11 @@ function clearKernelVersionCache() {
4546
4400
  // src/service.ts
4547
4401
  import { spawnSync as spawnSync4 } from "child_process";
4548
4402
  import fs8 from "fs";
4549
- import path6 from "path";
4403
+ import path7 from "path";
4550
4404
 
4551
4405
  // src/log-files.ts
4552
4406
  import fs5 from "fs";
4553
- import path4 from "path";
4407
+ import path5 from "path";
4554
4408
  var DEFAULT_LOG_RETENTION_DAYS = 7;
4555
4409
  var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
4556
4410
  function isArchiveLogFilename(filename) {
@@ -4588,10 +4442,10 @@ function readLogTail(maxLines = 15) {
4588
4442
  }
4589
4443
  function allocateArchivePath() {
4590
4444
  const timestamp = formatLocalTimestamp();
4591
- let archivePath = path4.join(DIRS.logs, `mihomo.${timestamp}.log`);
4445
+ let archivePath = path5.join(DIRS.logs, `mihomo.${timestamp}.log`);
4592
4446
  let seq = 1;
4593
4447
  while (fs5.existsSync(archivePath)) {
4594
- archivePath = path4.join(DIRS.logs, `mihomo.${timestamp}.${seq}.log`);
4448
+ archivePath = path5.join(DIRS.logs, `mihomo.${timestamp}.${seq}.log`);
4595
4449
  seq++;
4596
4450
  }
4597
4451
  return archivePath;
@@ -4616,7 +4470,7 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4616
4470
  for (const file of files) {
4617
4471
  if (!isArchiveLogFilename(file)) continue;
4618
4472
  try {
4619
- const filePath = path4.join(logsDir, file);
4473
+ const filePath = path5.join(logsDir, file);
4620
4474
  const stat = fs5.statSync(filePath);
4621
4475
  if (now - stat.mtimeMs > maxAgeMs) {
4622
4476
  fs5.unlinkSync(filePath);
@@ -4646,7 +4500,7 @@ function listLogs() {
4646
4500
  for (const file of files) {
4647
4501
  if (!isArchiveLogFilename(file)) continue;
4648
4502
  try {
4649
- const filePath = path4.join(logsDir, file);
4503
+ const filePath = path5.join(logsDir, file);
4650
4504
  const stat = fs5.statSync(filePath);
4651
4505
  result.archives.push({
4652
4506
  name: file,
@@ -4768,24 +4622,21 @@ function getStatus() {
4768
4622
  return {
4769
4623
  running,
4770
4624
  pid: running ? pid : null,
4771
- processInfo: running && pid ? getProcessInfo(pid) : null,
4772
- hasConfig: hasConfig(),
4773
- hasKernel: hasKernel(),
4774
- kernelVersion: getKernelVersion()
4625
+ processInfo: running && pid ? getProcessInfo(pid) : null
4775
4626
  };
4776
4627
  }
4777
4628
 
4778
4629
  // src/sudo.ts
4779
4630
  import { spawnSync as spawnSync3 } from "child_process";
4780
4631
  import fs7 from "fs";
4781
- import path5 from "path";
4632
+ import path6 from "path";
4782
4633
  var SUDO_TIMEOUT_MS = 6e4;
4783
4634
  function runSudoScript(scriptBody, opts) {
4784
4635
  if (!process.stdin.isTTY) {
4785
4636
  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");
4786
4637
  }
4787
4638
  ensureDirs();
4788
- const scriptPath = path5.join(DIRS.runtime, opts.file);
4639
+ const scriptPath = path6.join(DIRS.runtime, opts.file);
4789
4640
  fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
4790
4641
  fs7.chmodSync(scriptPath, 448);
4791
4642
  try {
@@ -5042,12 +4893,12 @@ function killResidualKernels() {
5042
4893
  }
5043
4894
  if (rootPids.length > 0) cleanupRootResidue();
5044
4895
  }
5045
- async function installService(wasRunning) {
4896
+ async function installService(wasRunning, stopEpochBefore) {
5046
4897
  assertServiceLabelSafe();
5047
4898
  ensureDirs();
5048
4899
  ensureServiceSymlink();
5049
4900
  let restoreSkipped = false;
5050
- const stagePath = path6.join(DIRS.runtime, "service.plist.stage");
4901
+ const stagePath = path7.join(DIRS.runtime, "service.plist.stage");
5051
4902
  atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
5052
4903
  try {
5053
4904
  const lint = spawnSync4("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
@@ -5058,11 +4909,10 @@ async function installService(wasRunning) {
5058
4909
  }
5059
4910
  bootoutService();
5060
4911
  await waitUntilUnloaded();
5061
- fs8.mkdirSync(path6.dirname(PATHS.userAgentPlist), { recursive: true });
4912
+ fs8.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5062
4913
  fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
5063
4914
  fs8.chmodSync(PATHS.userAgentPlist, 420);
5064
4915
  if (wasRunning) {
5065
- const stopEpochBefore = readStopEpoch();
5066
4916
  withFileLock(PATHS.serviceLock, () => {
5067
4917
  if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
5068
4918
  restoreSkipped = true;
@@ -5098,6 +4948,9 @@ function bumpStopEpoch() {
5098
4948
  } catch {
5099
4949
  }
5100
4950
  }
4951
+ function recordServiceStopped() {
4952
+ bumpStopEpoch();
4953
+ }
5101
4954
  function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5102
4955
  return stopEpochNow !== stopEpochBefore;
5103
4956
  }
@@ -5245,11 +5098,11 @@ async function tryHotReload() {
5245
5098
  clearTimeout(timer);
5246
5099
  }
5247
5100
  }
5248
- async function restartService() {
5101
+ async function restartService(stopEpochBefore) {
5249
5102
  if (!isServiceInstalled()) {
5250
5103
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
5251
5104
  }
5252
- if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
5105
+ if (!logOversized() && await tryHotReload()) return { hotReloaded: true, started: true };
5253
5106
  if (logOversized()) {
5254
5107
  const archiveFile = allocateArchivePath();
5255
5108
  try {
@@ -5259,12 +5112,20 @@ async function restartService() {
5259
5112
  }
5260
5113
  }
5261
5114
  const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
5115
+ let started = true;
5262
5116
  if (kick.status !== 0) {
5263
- runLaunchctl(["enable", serviceTarget()]);
5264
- runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u91CD\u542F\u670D\u52A1");
5117
+ withFileLock(PATHS.serviceLock, () => {
5118
+ if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
5119
+ started = false;
5120
+ return;
5121
+ }
5122
+ runLaunchctl(["enable", serviceTarget()]);
5123
+ runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u91CD\u542F\u670D\u52A1");
5124
+ });
5125
+ if (!started) return { hotReloaded: false, started: false };
5265
5126
  }
5266
5127
  cleanupOldLogs();
5267
- return { hotReloaded: false };
5128
+ return { hotReloaded: false, started: true };
5268
5129
  }
5269
5130
 
5270
5131
  // src/commands/help.ts
@@ -5353,7 +5214,7 @@ function printVersion() {
5353
5214
  // src/commands/completion.ts
5354
5215
  import fs10 from "fs";
5355
5216
  import os3 from "os";
5356
- import path8 from "path";
5217
+ import path9 from "path";
5357
5218
 
5358
5219
  // src/open.ts
5359
5220
  import { spawn } from "child_process";
@@ -5544,19 +5405,31 @@ async function launchOrRestart(mode, stopEpochBefore) {
5544
5405
  return result.pid;
5545
5406
  }
5546
5407
  const status = getServiceStatus();
5408
+ let hotReloaded = false;
5409
+ let started;
5547
5410
  if (status.running && !status.disabled) {
5548
- const { hotReloaded } = await restartService();
5549
- if (hotReloaded) return getServiceStatus().pid;
5411
+ ({ hotReloaded, started } = await restartService(stopEpochBefore));
5550
5412
  } else {
5551
- const { started } = await startService(stopEpochBefore ?? readStopEpoch());
5552
- if (!started) {
5553
- throw new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230 stop", {
5554
- label: "\u542F\u52A8\u5931\u8D25",
5555
- hint: ["\u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5728\u672C\u6B21\u542F\u52A8\u8FC7\u7A0B\u4E2D\u6267\u884C\u4E86 mihomo stop\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62\u3002", "", "\u786E\u5B9E\u8981\u542F\u52A8: mihomo start"]
5556
- });
5557
- }
5413
+ ({ started } = await startService(stopEpochBefore));
5414
+ }
5415
+ if (!started) throw cancelledByConcurrentStop();
5416
+ if (hotReloaded) return getServiceStatus().pid;
5417
+ try {
5418
+ return await assertServiceHealthy();
5419
+ } catch (e) {
5420
+ if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) throw cancelledByConcurrentStop();
5421
+ throw e;
5558
5422
  }
5559
- return assertServiceHealthy();
5423
+ }
5424
+ function cancelledByConcurrentStop() {
5425
+ return new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C", {
5426
+ label: "\u542F\u52A8\u5931\u8D25",
5427
+ hint: [
5428
+ "\u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5728\u672C\u6B21\u542F\u52A8\u8FC7\u7A0B\u4E2D\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF08mihomo stop\uFF0C\u6216 tun / install \u7B49\u540C\u6837\u4F1A\u5173\u95ED\u81EA\u542F\u7684\u547D\u4EE4\uFF09\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62\u3002",
5429
+ "",
5430
+ "\u786E\u5B9E\u8981\u542F\u52A8: mihomo start"
5431
+ ]
5432
+ });
5560
5433
  }
5561
5434
  async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
5562
5435
  const health = await waitServiceHealthy();
@@ -5744,9 +5617,9 @@ function formatProxySummary(info) {
5744
5617
  return parts.join(", ");
5745
5618
  }
5746
5619
  function getActiveSubscription() {
5747
- const subs = getSubscriptions();
5748
- if (subs.length === 0) return null;
5749
5620
  const settings = readSettings();
5621
+ const subs = getSubscriptions(settings);
5622
+ if (subs.length === 0) return null;
5750
5623
  const activeName = settings.active_subscription;
5751
5624
  if (activeName) {
5752
5625
  const found = subs.find((s) => s.name === activeName);
@@ -5831,7 +5704,6 @@ async function downloadSubscription(url, subName = "default", signal) {
5831
5704
  throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
5832
5705
  }
5833
5706
  const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
5834
- if (!parsed) throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
5835
5707
  assertLooksLikeSubscription(parsed, maskUrl(url));
5836
5708
  saveSubscriptionRawConfig(subName, content);
5837
5709
  const meta = extractSubscriptionMeta(response.headers);
@@ -5847,13 +5719,14 @@ async function downloadSubscription(url, subName = "default", signal) {
5847
5719
  username: meta.username
5848
5720
  };
5849
5721
  }
5850
- function prepareConfigForStart(mode, subName = "default") {
5722
+ async function prepareConfigForStart(mode, subName = "default") {
5851
5723
  const rawContent = readSubscriptionRawConfig(subName);
5852
5724
  if (!rawContent) {
5853
5725
  throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605\u914D\u7F6E "${subName}"\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605`);
5854
5726
  }
5855
5727
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
5856
5728
  const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
5729
+ await validateConfigWithKernel(buildResult.config);
5857
5730
  const proxies = buildResult.config.proxies;
5858
5731
  const proxyGroups = buildResult.config["proxy-groups"];
5859
5732
  return {
@@ -5868,12 +5741,11 @@ function commitPreparedConfig(prepared) {
5868
5741
  const { buildResult } = prepared;
5869
5742
  if (buildResult.warnings.length > 0) {
5870
5743
  for (const warning of buildResult.warnings) {
5871
- console.log(`${colors.yellow("\u81EA\u52A8\u4FEE\u590D:")} ${warning}`);
5744
+ console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
5872
5745
  }
5873
5746
  console.log("");
5874
5747
  }
5875
5748
  writeMihomoConfig(buildResult.config);
5876
- writeDebugConfig(buildResult);
5877
5749
  return prepared.info;
5878
5750
  }
5879
5751
  function needsAutoUpdate(sub) {
@@ -5942,9 +5814,9 @@ async function autoUpdateStaleSubscription(options = {}) {
5942
5814
  }
5943
5815
 
5944
5816
  // src/proxy-probe.ts
5945
- import { execFile } from "child_process";
5946
- import { promisify } from "util";
5947
- var execFileAsync = promisify(execFile);
5817
+ import { execFile as execFile2 } from "child_process";
5818
+ import { promisify as promisify2 } from "util";
5819
+ var execFileAsync = promisify2(execFile2);
5948
5820
  var PROBE_URL = "https://www.gstatic.com/generate_204";
5949
5821
  function isProbeSuccessStatus(code) {
5950
5822
  return code !== null && code >= 200 && code < 300;
@@ -6019,9 +5891,7 @@ function buildStatusJson(args) {
6019
5891
  kernel: getKernelVersion(),
6020
5892
  kernelInstalled: hasKernel(),
6021
5893
  ports: args.info ? args.info.tun ? { tun: true, ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {} } : {
6022
- ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {},
6023
- ...args.info.httpPort ? { http: args.info.httpPort } : {},
6024
- ...args.info.socksPort ? { socks: args.info.socksPort } : {}
5894
+ ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {}
6025
5895
  } : {},
6026
5896
  subscription: args.activeSub ? {
6027
5897
  name: args.activeSub.name,
@@ -6054,8 +5924,7 @@ async function printStatus(args = []) {
6054
5924
  const service = getServiceStatus();
6055
5925
  const state = getRunningState(service);
6056
5926
  const info = getConfigInfo();
6057
- const overwriteEnabled = isOverwriteEnabled();
6058
- const overwriteFiles = listOverwriteFile().files;
5927
+ const { enabled: overwriteEnabled, files: overwriteFiles } = listOverwriteFile();
6059
5928
  const activeSub = getActiveSubscription();
6060
5929
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6061
5930
  const legacy = detectLegacySystemInstall();
@@ -6128,10 +5997,7 @@ async function printStatus(args = []) {
6128
5997
  } else if (info.mixedPort) {
6129
5998
  console.log(`${colors.gray("\u7AEF\u53E3: ")}${info.mixedPort}`);
6130
5999
  } else {
6131
- const ports = [];
6132
- if (info.httpPort) ports.push(`HTTP:${info.httpPort}`);
6133
- if (info.socksPort) ports.push(`SOCKS:${info.socksPort}`);
6134
- console.log(`${colors.gray("\u7AEF\u53E3: ")}${ports.length > 0 ? ports.join(", ") : "\u672A\u77E5"}`);
6000
+ console.log(`${colors.gray("\u7AEF\u53E3: ")}\u672A\u77E5`);
6135
6001
  }
6136
6002
  }
6137
6003
  if (activeSub) {
@@ -6207,8 +6073,8 @@ async function cmdStart(args) {
6207
6073
  }
6208
6074
  const skipUpdate = hasFlag(args, "-s", "--no-update");
6209
6075
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
6210
- const serviceBefore = getServiceStatus();
6211
6076
  const stopEpochBefore = readStopEpoch();
6077
+ const serviceBefore = getServiceStatus();
6212
6078
  if (targetMode === "tun") {
6213
6079
  if (detectLegacySystemInstall()) {
6214
6080
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406"));
@@ -6244,7 +6110,7 @@ async function cmdStart(args) {
6244
6110
  }
6245
6111
  let prepared;
6246
6112
  try {
6247
- prepared = prepareConfigForStart(targetMode, sub.name);
6113
+ prepared = await prepareConfigForStart(targetMode, sub.name);
6248
6114
  } catch (e) {
6249
6115
  if (e instanceof CliError) throw e;
6250
6116
  throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
@@ -6273,7 +6139,7 @@ async function dispatchSubcommand(args, table, options) {
6273
6139
  if (action) {
6274
6140
  const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
6275
6141
  if (cmd) return cmd.handler(args);
6276
- if (options.onUnknown) return options.onUnknown(action);
6142
+ return options.onUnknown(action);
6277
6143
  }
6278
6144
  return options.fallback(args);
6279
6145
  }
@@ -6343,6 +6209,7 @@ function printDirectoryInfo() {
6343
6209
  }
6344
6210
  var SUBCOMMANDS = [{ name: "open", description: "\u6253\u5F00\u76EE\u5F55", handler: openDirectory }];
6345
6211
  async function cmdDirectory(args) {
6212
+ assertKnownFlags(args.slice(1), [], "dir");
6346
6213
  await dispatchSubcommand(args, SUBCOMMANDS, {
6347
6214
  fallback: printDirectoryInfo,
6348
6215
  onUnknown: (action) => {
@@ -6356,7 +6223,7 @@ async function cmdDirectory(args) {
6356
6223
  }
6357
6224
 
6358
6225
  // src/commands/overwrite.ts
6359
- import path7 from "path";
6226
+ import path8 from "path";
6360
6227
  function printOverwriteList() {
6361
6228
  const info = listOverwriteFile();
6362
6229
  const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
@@ -6366,8 +6233,8 @@ function printOverwriteList() {
6366
6233
  if (info.files.length === 0) {
6367
6234
  console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6368
6235
  console.log("");
6369
- console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path7.join(info.dir, "overwrite.yaml")}`);
6370
- console.log(` \u6216 ${path7.join(info.dir, "overwrite.dns.yaml")}`);
6236
+ console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path8.join(info.dir, "overwrite.yaml")}`);
6237
+ console.log(` \u6216 ${path8.join(info.dir, "overwrite.dns.yaml")}`);
6371
6238
  console.log("");
6372
6239
  } else {
6373
6240
  console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
@@ -6641,7 +6508,10 @@ async function cmdSubscription(args) {
6641
6508
 
6642
6509
  // src/commands/completion.ts
6643
6510
  function commandWords(commands) {
6644
- return commands.filter((c) => !c.hidden).flatMap((c) => [{ word: c.name, desc: c.usage[0]?.description ?? "" }, ...c.aliases.map((a) => ({ word: a, desc: c.usage[0]?.description ?? "" }))]);
6511
+ return commands.flatMap((c) => [
6512
+ { word: c.name, desc: c.usage[0]?.description ?? "" },
6513
+ ...c.aliases.map((a) => ({ word: a, desc: c.usage[0]?.description ?? "" }))
6514
+ ]);
6645
6515
  }
6646
6516
  function subWords(subs) {
6647
6517
  return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
@@ -6716,8 +6586,8 @@ function buildZsh(commands, groups) {
6716
6586
  " ;;",
6717
6587
  " completion)",
6718
6588
  " if (( CURRENT == 2 )); then",
6719
- ` _values 'action' install ${SHELLS.join(" ")}`,
6720
- " elif (( CURRENT == 3 )) && [[ ${words[2]} == install ]]; then",
6589
+ ` _values 'action' install uninstall ${SHELLS.join(" ")}`,
6590
+ " elif (( CURRENT == 3 )) && [[ ${words[2]} == (install|uninstall) ]]; then",
6721
6591
  ` _values 'shell' ${SHELLS.join(" ")}`,
6722
6592
  " fi",
6723
6593
  " ;;",
@@ -6782,8 +6652,8 @@ ${subCase}
6782
6652
  ;;
6783
6653
  completion)
6784
6654
  if [[ \${COMP_CWORD} -eq 2 ]]; then
6785
- COMPREPLY=( $(compgen -W "install ${SHELLS.join(" ")}" -- "\${cur}") )
6786
- elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install ]]; then
6655
+ COMPREPLY=( $(compgen -W "install uninstall ${SHELLS.join(" ")}" -- "\${cur}") )
6656
+ elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install || "\${COMP_WORDS[2]}" == uninstall ]]; then
6787
6657
  COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
6788
6658
  fi
6789
6659
  ;;
@@ -6809,8 +6679,8 @@ function buildFish(commands, groups) {
6809
6679
  }
6810
6680
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
6811
6681
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
6812
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install ${SHELLS.join(" ")}' -d '\u5B89\u88C5\u8865\u5168\u5230\u9ED8\u8BA4\u4F4D\u7F6E'`);
6813
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install" -a '${SHELLS.join(" ")}'`);
6682
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
6683
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
6814
6684
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
6815
6685
  lines.push("end");
6816
6686
  return lines.join("\n");
@@ -6838,11 +6708,11 @@ function completionInstallPath(shell) {
6838
6708
  const home = os3.homedir();
6839
6709
  switch (shell) {
6840
6710
  case "zsh":
6841
- return path8.join(home, ".zsh", "completions", "_mihomo");
6711
+ return path9.join(home, ".zsh", "completions", "_mihomo");
6842
6712
  case "bash":
6843
- return path8.join(home, ".bash_completion");
6713
+ return path9.join(home, ".bash_completion");
6844
6714
  case "fish":
6845
- return path8.join(home, ".config", "fish", "completions", "mihomo.fish");
6715
+ return path9.join(home, ".config", "fish", "completions", "mihomo.fish");
6846
6716
  default:
6847
6717
  return null;
6848
6718
  }
@@ -6865,7 +6735,7 @@ function installCompletion(shell, commands) {
6865
6735
  console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
6866
6736
  return;
6867
6737
  }
6868
- fs10.mkdirSync(path8.dirname(target), { recursive: true });
6738
+ fs10.mkdirSync(path9.dirname(target), { recursive: true });
6869
6739
  fs10.appendFileSync(target, `
6870
6740
  ${BASH_MARKER}
6871
6741
  ${script}${BASH_MARKER.replace(">>>", "<<<")}
@@ -6873,7 +6743,7 @@ ${script}${BASH_MARKER.replace(">>>", "<<<")}
6873
6743
  console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6874
6744
  return;
6875
6745
  }
6876
- fs10.mkdirSync(path8.dirname(target), { recursive: true });
6746
+ fs10.mkdirSync(path9.dirname(target), { recursive: true });
6877
6747
  fs10.writeFileSync(target, script, { mode: 420 });
6878
6748
  console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6879
6749
  } catch (e) {
@@ -6886,17 +6756,78 @@ ${script}${BASH_MARKER.replace(">>>", "<<<")}
6886
6756
  console.log(colors.gray("\u82E5\u8865\u5168\u4E0D\u751F\u6548\uFF0C\u5728 ~/.zshrc \u4E2D\u52A0\u4E00\u884C: fpath=(~/.zsh/completions $fpath)"));
6887
6757
  }
6888
6758
  }
6759
+ function uninstallCompletion(shell, commands) {
6760
+ if (!shell) {
6761
+ throw new CliError("\u8BF7\u6307\u5B9A shell", { hint: [`\u7528\u6CD5: mihomo completion uninstall <${SHELLS.join("|")}>`] });
6762
+ }
6763
+ const target = completionInstallPath(shell);
6764
+ if (!target) {
6765
+ buildCompletionScript(shell, commands);
6766
+ return;
6767
+ }
6768
+ if (!fs10.existsSync(target)) {
6769
+ console.log(`\u672A\u5B89\u88C5 ${shell} \u8865\u5168\uFF08${target} \u4E0D\u5B58\u5728\uFF09`);
6770
+ return;
6771
+ }
6772
+ console.log(`\u5378\u8F7D ${shell} \u8865\u5168: ${target}`);
6773
+ try {
6774
+ if (shell === "bash") {
6775
+ const existing2 = fs10.readFileSync(target, "utf8");
6776
+ const endMarker = BASH_MARKER.replace(">>>", "<<<");
6777
+ const start = existing2.indexOf(BASH_MARKER);
6778
+ const end = existing2.indexOf(endMarker);
6779
+ if (start === -1 || end === -1 || end < start) {
6780
+ console.log(colors.yellow("\u672A\u627E\u5230 mihomo \u8865\u5168\u6807\u8BB0\uFF0C\u672A\u505A\u6539\u52A8"));
6781
+ console.log(colors.gray(` \u82E5\u66FE\u624B\u52A8\u5B89\u88C5\uFF0C\u8BF7\u81EA\u884C\u7F16\u8F91 ${target}`));
6782
+ return;
6783
+ }
6784
+ const before = existing2.slice(0, start).replace(/\n+$/, "\n");
6785
+ const after = existing2.slice(end + endMarker.length).replace(/^\n/, "");
6786
+ const rest = `${before}${after}`;
6787
+ if (rest.trim() === "") {
6788
+ fs10.rmSync(target);
6789
+ console.log(colors.green("\u5DF2\u79FB\u9664\uFF08\u6587\u4EF6\u5DF2\u7A7A\uFF0C\u4E00\u5E76\u5220\u9664\uFF1B\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6790
+ return;
6791
+ }
6792
+ fs10.writeFileSync(target, rest);
6793
+ console.log(colors.green("\u5DF2\u79FB\u9664 mihomo \u8865\u5168\u6BB5\uFF0C\u4FDD\u7559\u6587\u4EF6\u4E2D\u5176\u4F59\u5185\u5BB9\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6794
+ return;
6795
+ }
6796
+ const existing = fs10.readFileSync(target, "utf8");
6797
+ const fingerprint = shell === "zsh" ? "#compdef mihomo" : "for cmd in mihomo";
6798
+ if (!existing.includes(fingerprint)) {
6799
+ throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
6800
+ label: "\u5378\u8F7D\u4E2D\u6B62",
6801
+ hint: ["\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\u3002\u786E\u8BA4\u65E0\u7528\u540E\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
6802
+ });
6803
+ }
6804
+ fs10.rmSync(target);
6805
+ console.log(colors.green("\u5DF2\u5220\u9664\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6806
+ } catch (e) {
6807
+ if (e instanceof CliError) throw e;
6808
+ throw new CliError(`\u8865\u5168\u5378\u8F7D\u5931\u8D25: ${e.message}`, {
6809
+ label: "\u5378\u8F7D\u5931\u8D25",
6810
+ hint: ["\u8BF7\u68C0\u67E5\u76EE\u6807\u6587\u4EF6\u7684\u6743\u9650\uFF0C\u6216\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
6811
+ });
6812
+ }
6813
+ }
6889
6814
  function cmdCompletion(args, commands) {
6815
+ assertKnownFlags(args.slice(1), [], "completion");
6890
6816
  if (args[1] === "install") {
6891
6817
  installCompletion(args[2], commands);
6892
6818
  return;
6893
6819
  }
6820
+ if (args[1] === "uninstall") {
6821
+ uninstallCompletion(args[2], commands);
6822
+ return;
6823
+ }
6894
6824
  const shell = args[1];
6895
6825
  if (!shell) {
6896
6826
  throw new CliError("\u8BF7\u6307\u5B9A shell", {
6897
6827
  hint: [
6898
6828
  `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`,
6899
6829
  `\u5B89\u88C5\u5230\u9ED8\u8BA4\u4F4D\u7F6E: mihomo completion install <${SHELLS.join("|")}>`,
6830
+ `\u5378\u8F7D: mihomo completion uninstall <${SHELLS.join("|")}>`,
6900
6831
  '\u4E34\u65F6\u542F\u7528: eval "$(mihomo completion zsh)"'
6901
6832
  ]
6902
6833
  });
@@ -6904,69 +6835,47 @@ function cmdCompletion(args, commands) {
6904
6835
  console.log(buildCompletionScript(shell, commands));
6905
6836
  }
6906
6837
 
6907
- // src/commands/doctor.ts
6908
- import { spawnSync as spawnSync6 } from "child_process";
6909
- import fs11 from "fs";
6910
-
6911
- // node_modules/compare-versions/lib/esm/utils.js
6912
- var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
6913
- var validateAndParse = (version) => {
6914
- if (typeof version !== "string") {
6915
- throw new TypeError("Invalid argument expected string");
6838
+ // src/commands/config.ts
6839
+ function cmdConfig(args = []) {
6840
+ assertKnownFlags(args.slice(1), ["-j", "--json"], "config [--json]");
6841
+ const asJson = hasFlag(args, "-j", "--json");
6842
+ const active = getActiveSubscription();
6843
+ if (!active) {
6844
+ throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
6916
6845
  }
6917
- const match = version.match(semver);
6918
- if (!match) {
6919
- throw new Error(`Invalid argument not valid semver ('${version}' received)`);
6846
+ const rawContent = readSubscriptionRawConfig(active.name);
6847
+ if (!rawContent) {
6848
+ throw new CliError(`\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo sub update ${active.name}` });
6920
6849
  }
6921
- match.shift();
6922
- return match;
6923
- };
6924
- var isWildcard = (s) => s === "*" || s === "x" || s === "X";
6925
- var tryParse = (v) => {
6926
- const n = parseInt(v, 10);
6927
- return isNaN(n) ? v : n;
6928
- };
6929
- var forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];
6930
- var compareStrings = (a, b) => {
6931
- if (isWildcard(a) || isWildcard(b))
6932
- return 0;
6933
- const [ap, bp] = forceType(tryParse(a), tryParse(b));
6934
- if (ap > bp)
6935
- return 1;
6936
- if (ap < bp)
6937
- return -1;
6938
- return 0;
6939
- };
6940
- var compareSegments = (a, b) => {
6941
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
6942
- const r = compareStrings(a[i] || "0", b[i] || "0");
6943
- if (r !== 0)
6944
- return r;
6850
+ const mode = getConfigInfo()?.tun ? "tun" : "mixed";
6851
+ const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
6852
+ const shown = { ...config };
6853
+ if (typeof shown.secret === "string" && shown.secret) shown.secret = "***";
6854
+ if (asJson) {
6855
+ console.log(JSON.stringify(shown, null, 2));
6856
+ return;
6945
6857
  }
6946
- return 0;
6947
- };
6948
-
6949
- // node_modules/compare-versions/lib/esm/compareVersions.js
6950
- var compareVersions = (v1, v2) => {
6951
- const n1 = validateAndParse(v1);
6952
- const n2 = validateAndParse(v2);
6953
- const p1 = n1.pop();
6954
- const p2 = n2.pop();
6955
- const r = compareSegments(n1, n2);
6956
- if (r !== 0)
6957
- return r;
6958
- if (p1 && p2) {
6959
- return compareSegments(p1.split("."), p2.split("."));
6960
- } else if (p1 || p2) {
6961
- return p1 ? -1 : 1;
6858
+ console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
6859
+ 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"));
6860
+ if (typeof config.secret === "string" && config.secret) {
6861
+ console.log(colors.gray("# secret \u5DF2\u8131\u654F\u663E\u793A"));
6962
6862
  }
6963
- return 0;
6964
- };
6863
+ console.log("");
6864
+ console.log(dumpYaml(shown).trimEnd());
6865
+ if (warnings.length > 0) {
6866
+ console.log("");
6867
+ for (const w of warnings) console.log(colors.yellow(`# ${w}`));
6868
+ }
6869
+ }
6870
+
6871
+ // src/commands/doctor.ts
6872
+ import { spawnSync as spawnSync6 } from "child_process";
6873
+ import fs11 from "fs";
6965
6874
 
6966
6875
  // src/commands/update.ts
6967
- import { execFile as execFile2, spawn as spawn2 } from "child_process";
6968
- import { promisify as promisify2 } from "util";
6969
- var execFileAsync2 = promisify2(execFile2);
6876
+ import { execFile as execFile3, spawn as spawn2 } from "child_process";
6877
+ import { promisify as promisify3 } from "util";
6878
+ var execFileAsync2 = promisify3(execFile3);
6970
6879
  var NPM_VIEW_TIMEOUT_MS = 15e3;
6971
6880
  async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
6972
6881
  try {
@@ -6977,7 +6886,8 @@ async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
6977
6886
  return null;
6978
6887
  }
6979
6888
  }
6980
- async function cmdUpdate() {
6889
+ async function cmdUpdate(args = []) {
6890
+ assertKnownFlags(args.slice(1), [], "update");
6981
6891
  console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
6982
6892
  console.log("");
6983
6893
  const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
@@ -7140,16 +7050,16 @@ async function collectChecks() {
7140
7050
  } else {
7141
7051
  push("\u7AEF\u53E3", "ok", `${mixedPort} \u7A7A\u95F2`);
7142
7052
  }
7143
- if (active) {
7053
+ if (active && hasKernel()) {
7144
7054
  try {
7145
7055
  const mode = info?.tun ? "tun" : "mixed";
7146
- prepareConfigForStart(mode, active.name);
7147
- push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u53EF\u6B63\u5E38\u6784\u5EFA\uFF08${mode}\uFF09`);
7056
+ await prepareConfigForStart(mode, active.name);
7057
+ push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09`);
7148
7058
  } catch (e) {
7149
7059
  push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start");
7150
7060
  }
7151
7061
  } else {
7152
- push("\u914D\u7F6E\u6784\u5EFA", "warn", "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
7062
+ push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
7153
7063
  }
7154
7064
  if (state.running && info?.mixedPort) {
7155
7065
  const probe = await probeProxyConnectivity(info.mixedPort);
@@ -7171,7 +7081,8 @@ async function collectChecks() {
7171
7081
  }
7172
7082
  return checks;
7173
7083
  }
7174
- async function cmdDoctor() {
7084
+ async function cmdDoctor(args = []) {
7085
+ assertKnownFlags(args.slice(1), [], "doctor");
7175
7086
  const checks = await collectChecks();
7176
7087
  console.log("");
7177
7088
  for (const c of checks) {
@@ -7199,7 +7110,7 @@ async function cmdDoctor() {
7199
7110
  // src/kernel.ts
7200
7111
  import { spawnSync as spawnSync7 } from "child_process";
7201
7112
  import fs12 from "fs";
7202
- import path9 from "path";
7113
+ import path10 from "path";
7203
7114
  var GITHUB_REPO = "MetaCubeX/mihomo";
7204
7115
  var KERNEL_HTTP_TIMEOUT = 12e4;
7205
7116
  var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
@@ -7338,7 +7249,7 @@ function findBinaryInDir(dir, maxDepth = 4) {
7338
7249
  if (maxDepth <= 0) return null;
7339
7250
  const files = fs12.readdirSync(dir);
7340
7251
  for (const f of files) {
7341
- const fullPath = path9.join(dir, f);
7252
+ const fullPath = path10.join(dir, f);
7342
7253
  const stat = fs12.lstatSync(fullPath);
7343
7254
  if (stat.isDirectory()) {
7344
7255
  const found = findBinaryInDir(fullPath, maxDepth - 1);
@@ -7391,8 +7302,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7391
7302
  }
7392
7303
  assertTrustedAssetUrl(asset.browser_download_url);
7393
7304
  const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
7394
- const tempDir = fs12.mkdtempSync(path9.join(DIRS.kernel, ".tmp-"));
7395
- const tempPath = path9.join(tempDir, path9.basename(asset.name));
7305
+ const tempDir = fs12.mkdtempSync(path10.join(DIRS.kernel, ".tmp-"));
7306
+ const tempPath = path10.join(tempDir, path10.basename(asset.name));
7396
7307
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
7397
7308
  try {
7398
7309
  if (channel.kind === "mirror" && progressCallback) {
@@ -7402,7 +7313,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7402
7313
  progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
7403
7314
  }
7404
7315
  if (channel.kind === "gh") {
7405
- if (/[*?[\]]/.test(asset.name) || asset.name !== path9.basename(asset.name)) {
7316
+ if (/[*?[\]]/.test(asset.name) || asset.name !== path10.basename(asset.name)) {
7406
7317
  throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
7407
7318
  }
7408
7319
  const ghResult = spawnSync7("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
@@ -7484,8 +7395,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7484
7395
  if (tarResult.error) throw tarResult.error;
7485
7396
  if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
7486
7397
  } else if (tempPath.endsWith(".gz")) {
7487
- const baseName = path9.basename(tempPath, ".gz");
7488
- const outputPath = path9.join(tempDir, baseName);
7398
+ const baseName = path10.basename(tempPath, ".gz");
7399
+ const outputPath = path10.join(tempDir, baseName);
7489
7400
  const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7490
7401
  if (gzipResult.error) throw gzipResult.error;
7491
7402
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
@@ -7529,27 +7440,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7529
7440
  }
7530
7441
 
7531
7442
  // src/commands/kernel.ts
7532
- function assertKnownKernelFlags(args) {
7533
- const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--mirror"]);
7534
- const unknown = args.slice(1).filter((a) => a.startsWith("-") && !KNOWN_FLAGS.has(a) && !a.startsWith("--mirror=")).filter((a) => a !== "--mirror-all" && !a.startsWith("--mirror-all=")).filter((a) => a !== "--no-mirror" && a !== "--direct");
7535
- if (unknown.length > 0) {
7536
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${unknown.join(", ")}`, {
7537
- label: "\u53C2\u6570\u9519\u8BEF",
7538
- hint: [
7539
- "",
7540
- "\u53EF\u7528\u9009\u9879:",
7541
- " --mirror [\u955C\u50CF] \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4\u6309\u7F51\u7EDC\u9009 v6/\u88F8\u57DF\uFF09",
7542
- "",
7543
- "\u4E0D\u5E26\u9009\u9879\u65F6\u81EA\u52A8\u9009\u62E9\u901A\u9053: gh > \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE",
7544
- "",
7545
- `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`,
7546
- "\u77ED\u522B\u540D: --mirror cdn | v4 | v6 | axisnow"
7547
- ]
7548
- });
7549
- }
7550
- }
7551
7443
  async function cmdKernel(args) {
7552
- assertKnownKernelFlags(args);
7553
7444
  const mirrorInfo = parseMirrorArg(args);
7554
7445
  const effectiveMirror = mirrorInfo.mirror;
7555
7446
  const proxyRunning = getRunningState().running;
@@ -7617,7 +7508,7 @@ async function cmdKernel(args) {
7617
7508
  label: "\u4E0B\u8F7D\u5931\u8D25",
7618
7509
  hint: [
7619
7510
  "",
7620
- "\u4E0B\u8F7D\u901A\u9053\u6309\u4F18\u5148\u7EA7\u81EA\u52A8\u9009\u62E9: gh\uFF08GitHub CLI\uFF09> \u672C\u673A\u4EE3\u7406 > \u955C\u50CF > \u76F4\u8FDE",
7511
+ "\u4E0B\u8F7D\u901A\u9053\u6309\u4F18\u5148\u7EA7\u81EA\u52A8\u9009\u62E9: gh\uFF08GitHub CLI\uFF09> \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE",
7621
7512
  "\u624B\u52A8\u6307\u5B9A: mihomo kernel --mirror [\u955C\u50CF]\uFF08\u5F3A\u5236\u955C\u50CF\uFF09/ mihomo kernel --mirror direct\uFF08\u5F3A\u5236\u76F4\u8FDE\uFF09"
7622
7513
  ]
7623
7514
  });
@@ -7701,13 +7592,6 @@ function cmdLogs(args) {
7701
7592
  console.log("");
7702
7593
  }
7703
7594
 
7704
- // src/commands/removed.ts
7705
- function removedCommand(name, version, hint) {
7706
- return () => {
7707
- throw new CliError(`${name} \u5DF2\u79FB\u9664\uFF08${version}\uFF09`, { label: "\u547D\u4EE4\u4E0D\u5B58\u5728", hint });
7708
- };
7709
- }
7710
-
7711
7595
  // src/commands/reset.ts
7712
7596
  import fs14 from "fs";
7713
7597
 
@@ -7821,235 +7705,125 @@ async function stop(forceSudo = false) {
7821
7705
 
7822
7706
  // src/commands/reset.ts
7823
7707
  var RESET_TARGETS = [
7824
- {
7825
- id: "subs",
7826
- aliases: ["sub", "subs", "subscription", "subscriptions"],
7827
- label: "\u8BA2\u9605",
7828
- paths: () => [DIRS.subscriptions],
7829
- needsStop: true,
7830
- onAfter: () => {
7831
- writeSettings({ subscriptions: void 0, active_subscription: void 0 });
7832
- }
7833
- },
7834
- {
7835
- id: "logs",
7836
- aliases: ["log", "logs"],
7837
- label: "\u65E5\u5FD7",
7838
- paths: () => [DIRS.logs],
7839
- // 内核运行时持有日志 fd,删文件后内核继续写已删 inode,logs 0 会 tail 不存在的路径
7840
- needsStop: true
7841
- },
7842
- {
7843
- id: "data",
7844
- aliases: ["data"],
7845
- label: "\u8FD0\u884C\u6570\u636E",
7846
- paths: () => [DIRS.data],
7847
- needsStop: true
7848
- },
7849
- {
7850
- id: "runtime",
7851
- aliases: ["runtime"],
7852
- label: "\u8FD0\u884C\u65F6",
7853
- paths: () => [DIRS.runtime],
7854
- needsStop: true
7855
- },
7708
+ { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
7709
+ { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
7710
+ { id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
7711
+ { id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
7856
7712
  {
7857
7713
  id: "overwrites",
7858
7714
  aliases: ["overwrite", "overwrites", "ow"],
7859
7715
  label: "\u8986\u5199",
7860
- paths: () => {
7861
- const dir = USER_DATA_DIR;
7862
- if (!fs14.existsSync(dir)) return [];
7863
- return fs14.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
7864
- },
7865
7716
  needsStop: false,
7866
- onAfter: () => {
7867
- writeSettings({ overwrite_enabled: false });
7868
- }
7717
+ preserveOnBare: true,
7718
+ paths: () => fs14.existsSync(USER_DATA_DIR) ? fs14.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
7869
7719
  },
7870
7720
  {
7871
7721
  id: "settings",
7872
7722
  aliases: ["setting", "settings", "config"],
7873
7723
  label: "\u8BBE\u7F6E",
7874
- // 同时删 .bak:readSettings 遇格式损坏会备份原文件(settings.ts),里面含
7875
- // controller_secret 与订阅 URL 的 token。只删主文件会让 "已重置: 设置" 名不副实,
7876
- // 凭据仍明文留在数据目录(cache.json.bak 在 subscriptions/ 内,随整目录删除,无需单列)
7877
- paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`],
7878
- needsStop: false
7879
- },
7880
- {
7881
- id: "kernel",
7882
- aliases: ["kernel", "core"],
7883
- label: "\u5185\u6838",
7884
- paths: () => [DIRS.kernel],
7885
7724
  needsStop: false,
7886
- onAfter: () => clearKernelVersionCache(),
7887
- checkEmpty: () => !hasKernel(),
7888
- emptyMsg: "\u5185\u6838\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664",
7889
- warnIfRunning: true
7725
+ preserveOnBare: true,
7726
+ // 损坏备份也包含订阅凭据,需要一起删除
7727
+ paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
7890
7728
  },
7891
- {
7892
- id: "service",
7893
- aliases: ["service", "daemon"],
7894
- label: "\u670D\u52A1",
7895
- // 卸载由确认后的 uninstallsService 段统一处理;此处 paths 返回空
7896
- // (plist 不在数据目录里,且不应提前删破坏卸载),
7897
- // onAfter 因幂等守卫成为 no-op,仅作单独 reset 未走前段时的兜底。
7898
- paths: () => [],
7899
- needsStop: false,
7900
- onAfter: async () => {
7901
- const st = getServiceStatus();
7902
- if (st.installed || st.loaded) await uninstallService();
7903
- if (detectLegacySystemInstall()) cleanupLegacyInstallOrThrow();
7904
- },
7905
- checkEmpty: () => !isServiceInstalled() && !getServiceStatus().loaded && !detectLegacySystemInstall(),
7906
- emptyMsg: "\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664"
7907
- }
7729
+ { id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
7730
+ { id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
7908
7731
  ];
7909
- var RESET_PRESERVED_ON_BARE = ["settings", "kernel", "overwrites", "service"];
7910
7732
  function resolveResetTargets(names) {
7911
- const matched = [];
7912
- const unmatched = [];
7733
+ const matched = /* @__PURE__ */ new Set();
7913
7734
  for (const name of names) {
7914
- const t = RESET_TARGETS.find((t2) => t2.aliases.includes(name.toLowerCase()));
7915
- if (t) {
7916
- if (!matched.find((m) => m.id === t.id)) matched.push(t);
7917
- } else {
7918
- unmatched.push(name);
7735
+ const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
7736
+ if (!target) {
7737
+ throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
7919
7738
  }
7739
+ matched.add(target);
7920
7740
  }
7921
- matched.sort((a, b) => RESET_TARGETS.indexOf(a) - RESET_TARGETS.indexOf(b));
7922
- return { matched, unmatched };
7741
+ return [...matched];
7923
7742
  }
7924
7743
  async function cmdReset(args) {
7925
- const flags = (args || []).filter((a) => a.startsWith("-"));
7926
- const names = (args || []).slice(1).filter((a) => !a.startsWith("-"));
7927
- const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--full", "--yes", "-y"]);
7928
- const unknownFlags = flags.filter((f) => !KNOWN_FLAGS.has(f));
7929
- if (unknownFlags.length > 0) {
7930
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${unknownFlags.join(", ")}`, { hint: ["", "\u53EF\u7528\u9009\u9879: --full\uFF08\u5220\u5168\u90E8\uFF09, -y/--yes\uFF08\u8DF3\u8FC7\u786E\u8BA4\uFF09"] });
7931
- }
7932
- const fullReset = flags.includes("--full");
7933
- const skipConfirm = flags.includes("--yes") || flags.includes("-y");
7934
- let targets;
7935
- if (fullReset) {
7936
- targets = RESET_TARGETS;
7937
- } else if (names.length > 0) {
7938
- const { matched, unmatched } = resolveResetTargets(names);
7939
- if (unmatched.length > 0) {
7940
- throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${unmatched.join(", ")}`, {
7941
- hint: [
7942
- "",
7943
- `\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.aliases[0]).join(", ")}`,
7944
- "",
7945
- "\u793A\u4F8B:",
7946
- " mihomo reset sub log # \u5220\u9664\u8BA2\u9605\u548C\u65E5\u5FD7",
7947
- " mihomo reset kernel # \u53EA\u5220\u5185\u6838",
7948
- " mihomo reset --full # \u5220\u9664\u5168\u90E8",
7949
- " mihomo reset # \u5220\u9664\u5168\u90E8\uFF08\u4FDD\u7559\u8BBE\u7F6E\u3001\u5185\u6838\u3001\u8986\u5199\uFF09"
7950
- ]
7951
- });
7744
+ assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
7745
+ const names = args.slice(1).filter((a) => !a.startsWith("-"));
7746
+ const namedTargets = resolveResetTargets(names);
7747
+ const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
7748
+ const ids = new Set(targets.map((t) => t.id));
7749
+ const needsStop = targets.some((t) => t.needsStop);
7750
+ const serviceTargeted = ids.has("service");
7751
+ const service = getServiceStatus();
7752
+ const serviceActive = service.installed || service.loaded;
7753
+ const legacy = detectLegacySystemInstall();
7754
+ if (targets.length === 1) {
7755
+ if (serviceTargeted && !serviceActive && !legacy) {
7756
+ console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
7757
+ return;
7952
7758
  }
7953
- targets = matched;
7954
- } else {
7955
- targets = RESET_TARGETS.filter((t) => !RESET_PRESERVED_ON_BARE.includes(t.id));
7956
7759
  }
7957
- for (const t of targets) {
7958
- if (t.checkEmpty?.()) {
7959
- if (targets.length === 1) {
7960
- console.log(t.emptyMsg);
7961
- return;
7962
- }
7963
- }
7760
+ if (ids.has("kernel") && getMihomoPids().length > 0) {
7761
+ console.log(colors.yellow("\u5C06\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u5185\u6838\uFF0C\u5220\u9664\u540E\u9700\u91CD\u65B0\u4E0B\u8F7D\u624D\u80FD\u542F\u52A8"));
7964
7762
  }
7965
- const needsStop = targets.some((t) => t.needsStop);
7966
- const warnRunning = targets.some((t) => t.warnIfRunning);
7967
- const kernelTargeted = targets.some((t) => t.id === "kernel");
7968
- const serviceTargeted = targets.some((t) => t.id === "service");
7969
- const uninstallsService = serviceTargeted;
7970
- const stopsService = needsStop || kernelTargeted;
7971
- const serviceStatus = getServiceStatus();
7972
- const serviceActive = serviceStatus.installed || serviceStatus.loaded;
7973
- const pids = needsStop || warnRunning ? getMihomoPids() : [];
7974
- if (warnRunning && pids.length > 0) {
7975
- console.log(colors.yellow(`\u8B66\u544A: mihomo \u6B63\u5728\u8FD0\u884C (PID ${pids.join(", ")})\uFF0C\u5220\u9664\u5185\u6838\u540E\u5C06\u65E0\u6CD5\u91CD\u65B0\u542F\u52A8`));
7976
- }
7977
- if (uninstallsService && serviceActive) {
7978
- console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08\u79FB\u9664\u767B\u5F55\u81EA\u542F\uFF0CMixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
7979
- } else if (stopsService && serviceActive) {
7763
+ if (serviceTargeted && serviceActive) {
7764
+ console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
7765
+ } else if (needsStop && serviceActive) {
7980
7766
  console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
7981
7767
  }
7982
- if (uninstallsService && detectLegacySystemInstall()) {
7983
- console.log(colors.yellow("\u5C06\u6E05\u7406\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
7768
+ if ((needsStop || serviceTargeted) && legacy) {
7769
+ console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
7984
7770
  }
7985
7771
  console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
7986
- if (!skipConfirm) {
7987
- if (!await confirmOrThrow("\u786E\u8BA4?", {
7988
- nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
7989
- hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
7990
- })) {
7991
- console.log("\u5DF2\u53D6\u6D88");
7992
- return;
7993
- }
7772
+ if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
7773
+ nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
7774
+ hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
7775
+ })) {
7776
+ console.log("\u5DF2\u53D6\u6D88");
7777
+ return;
7994
7778
  }
7995
- if ((uninstallsService || stopsService) && serviceActive) {
7996
- try {
7997
- if (uninstallsService) {
7998
- await uninstallService();
7999
- } else {
8000
- await stopService();
8001
- }
8002
- } catch (e) {
8003
- if (e instanceof CliError) throw e;
8004
- throw new CliError(e.message.split("\n")[0], { label: "\u670D\u52A1\u64CD\u4F5C\u5DF2\u53D6\u6D88\uFF0C\u91CD\u7F6E\u4E2D\u6B62" });
8005
- }
7779
+ if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
7780
+ if (serviceActive) {
7781
+ if (serviceTargeted) await uninstallService();
7782
+ else if (needsStop) await stopService();
8006
7783
  }
8007
- if (needsStop && getMihomoPids().length > 0) {
8008
- console.log("\u505C\u6B62\u8FDB\u7A0B...");
7784
+ if (needsStop) {
8009
7785
  const cleanup = await cleanupAll();
8010
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
8011
- if (getMihomoPids().length === 0) break;
8012
- await new Promise((r) => setTimeout(r, PROCESS_WAIT_INTERVAL));
8013
- }
8014
- const remaining = getMihomoPids();
8015
- if (remaining.length > 0) {
8016
- throw new CliError(remaining.join(", "), {
7786
+ if (cleanup.remaining.length > 0) {
7787
+ throw new CliError(cleanup.remaining.join(", "), {
8017
7788
  label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
8018
- hint: [
8019
- `\u672A\u7EC8\u6B62\u7684\u8FDB\u7A0B: ${remaining.join(", ")}${cleanup.failed > 0 ? `\uFF08${cleanup.failed} \u4E2A\u7EC8\u6B62\u5931\u8D25\uFF09` : ""}`,
8020
- "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo",
8021
- "\u5426\u5219\u6B8B\u7559\u8FDB\u7A0B\u4F1A\u7EE7\u7EED\u4F7F\u7528\u5373\u5C06\u5220\u9664\u7684\u914D\u7F6E\u3002"
8022
- ]
7789
+ hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
8023
7790
  });
8024
7791
  }
7792
+ recordServiceStopped();
8025
7793
  }
8026
- const deleted = [];
8027
- for (const t of targets) {
8028
- let hadContent = false;
8029
- for (const p of t.paths()) {
8030
- if (fs14.existsSync(p)) {
8031
- hadContent = true;
8032
- try {
8033
- rmrf(p);
8034
- } catch (e) {
8035
- console.warn(` \u8B66\u544A: \u65E0\u6CD5\u5220\u9664 ${p}: ${e.message}`);
8036
- }
7794
+ const deleted = /* @__PURE__ */ new Set();
7795
+ for (const target of targets) {
7796
+ let hadContent = target.id === "service" && (serviceActive || legacy);
7797
+ for (const filePath of target.paths()) {
7798
+ if (!fs14.existsSync(filePath)) continue;
7799
+ try {
7800
+ rmrf(filePath);
7801
+ } catch (e) {
7802
+ throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
8037
7803
  }
7804
+ hadContent = true;
8038
7805
  }
8039
- await t.onAfter?.();
8040
- if (hadContent || !t.checkEmpty) {
8041
- deleted.push(t.label);
8042
- }
8043
- }
8044
- ensureDirs();
8045
- if (targets.some((t) => t.id === "settings")) {
8046
- invalidateSettingsCache();
7806
+ if (hadContent) deleted.add(target.id);
8047
7807
  }
8048
- if (deleted.length > 0) {
8049
- console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${deleted.join("\u3001")}`));
8050
- } else {
8051
- console.log("\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
7808
+ if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
7809
+ updateSettings((settings) => {
7810
+ const patch = {};
7811
+ if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
7812
+ patch.subscriptions = void 0;
7813
+ patch.active_subscription = void 0;
7814
+ deleted.add("subs");
7815
+ }
7816
+ if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
7817
+ patch.overwrite_enabled = void 0;
7818
+ deleted.add("overwrites");
7819
+ }
7820
+ return patch;
7821
+ });
8052
7822
  }
7823
+ if (ids.has("kernel")) clearKernelVersionCache();
7824
+ ensureDirs();
7825
+ const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
7826
+ console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
8053
7827
  }
8054
7828
 
8055
7829
  // src/commands/service.ts
@@ -8064,22 +7838,27 @@ async function handleLegacyInstall() {
8064
7838
  console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
8065
7839
  console.log("");
8066
7840
  }
8067
- async function cmdInstall(_args) {
7841
+ function printRestoreSkipped() {
7842
+ console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
7843
+ console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
7844
+ console.log(colors.gray(" \u542F\u52A8: mihomo start"));
7845
+ console.log("");
7846
+ }
7847
+ async function cmdInstall(args) {
7848
+ assertKnownFlags(args.slice(1), [], "install");
8068
7849
  if (!hasKernel()) {
8069
7850
  throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
8070
7851
  }
7852
+ const stopEpochBefore = readStopEpoch();
8071
7853
  await handleLegacyInstall();
8072
7854
  const wasRunning = getServiceStatus().running;
8073
- const { restoreSkipped } = await installService(wasRunning);
7855
+ const { restoreSkipped } = await installService(wasRunning, stopEpochBefore);
8074
7856
  console.log(`${colors.green("\u5DF2\u5B89\u88C5\u670D\u52A1")}`);
8075
7857
  console.log(colors.gray(` plist: ${PATHS.userAgentPlist}`));
8076
7858
  console.log(colors.gray(` \u767B\u5F55\u9879\u4E0E\u6269\u5C55\u4E2D\u663E\u793A\u4E3A: ${SERVICE_BINARY_NAME}`));
8077
7859
  console.log("");
8078
7860
  if (restoreSkipped) {
8079
- console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230 stop"));
8080
- console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u6267\u884C\u4E86 mihomo stop\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
8081
- console.log(colors.gray(" \u542F\u52A8: mihomo start"));
8082
- console.log("");
7861
+ printRestoreSkipped();
8083
7862
  return;
8084
7863
  }
8085
7864
  if (wasRunning) {
@@ -8087,6 +7866,10 @@ async function cmdInstall(_args) {
8087
7866
  await assertServiceHealthy("\u6062\u590D\u8FD0\u884C\u5931\u8D25");
8088
7867
  } catch (e) {
8089
7868
  if (!(e instanceof CliError)) throw e;
7869
+ if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
7870
+ printRestoreSkipped();
7871
+ return;
7872
+ }
8090
7873
  throw new CliError(e.message, {
8091
7874
  label: e.label,
8092
7875
  hint: [...e.hint, "", "\u670D\u52A1\u5DF2\u5B89\u88C5\u6210\u529F\uFF0C\u4EC5\u6062\u590D\u8FD0\u884C\u5931\u8D25\uFF1B\u4FEE\u6B63\u914D\u7F6E\u540E\u53EF\u6267\u884C mihomo start \u91CD\u8BD5\u3002"]
@@ -8101,7 +7884,8 @@ async function cmdInstall(_args) {
8101
7884
  }
8102
7885
  console.log("");
8103
7886
  }
8104
- async function cmdUninstall(_args) {
7887
+ async function cmdUninstall(args) {
7888
+ assertKnownFlags(args.slice(1), [], "uninstall");
8105
7889
  const status = getServiceStatus();
8106
7890
  const legacy = detectLegacySystemInstall();
8107
7891
  const residue = getMihomoPids();
@@ -8141,7 +7925,8 @@ function handleStopResult(result) {
8141
7925
  throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
8142
7926
  }
8143
7927
  }
8144
- async function cmdStop(_args) {
7928
+ async function cmdStop(args) {
7929
+ assertKnownFlags(args.slice(1), [], "stop");
8145
7930
  if (detectLegacySystemInstall()) {
8146
7931
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u505C\u6B62\u524D\u9700\u6E05\u7406"));
8147
7932
  console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
@@ -8153,12 +7938,14 @@ async function cmdStop(_args) {
8153
7938
  const pids = getMihomoPids();
8154
7939
  const needsServiceWork = status.loaded || status.installed && !status.disabled;
8155
7940
  if (!needsServiceWork && pids.length === 0) {
7941
+ recordServiceStopped();
8156
7942
  console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
8157
7943
  return;
8158
7944
  }
8159
7945
  if (!needsServiceWork) {
8160
7946
  console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
8161
7947
  handleStopResult(await stop());
7948
+ recordServiceStopped();
8162
7949
  console.log(colors.green("\u5DF2\u505C\u6B62"));
8163
7950
  return;
8164
7951
  }
@@ -8183,6 +7970,7 @@ function copyToClipboard(text) {
8183
7970
  }
8184
7971
  }
8185
7972
  function cmdUI(args) {
7973
+ assertKnownFlags(args.slice(1), [], "ui");
8186
7974
  const uiName = args[1] || "zash";
8187
7975
  if (!Object.hasOwn(UI_URLS, uiName)) {
8188
7976
  throw new CliError(`\u672A\u77E5\u7684 UI "${uiName}"`, { hint: "\u53EF\u7528 UI: zash (\u9ED8\u8BA4), dash, yacd" });
@@ -8249,38 +8037,6 @@ var COMMANDS = [
8249
8037
  group: "control",
8250
8038
  usage: [{ signature: "status [-j|--json] [--no-probe]", description: "\u67E5\u770B\u72B6\u6001" }]
8251
8039
  },
8252
- // === 已移除(墓碑:显式报错指引迁移,不在帮助中列出) ===
8253
- {
8254
- name: "daemon",
8255
- aliases: [],
8256
- handler: removedCommand("daemon", "v4.1.0", [
8257
- "\u4FDD\u6D3B\u5DF2\u6210\u4E3A Mixed \u6A21\u5F0F\u7684\u552F\u4E00\u8FD0\u884C\u65B9\u5F0F\uFF0C\u6539\u7528\u670D\u52A1\u547D\u4EE4\u65CF\uFF1A",
8258
- " mihomo daemon on \u2192 mihomo install\uFF08\u4E00\u6B21\uFF09+ mihomo start",
8259
- " mihomo daemon off \u2192 mihomo stop\uFF08\u505C\u6B62\u5E76\u5173\u95ED\u81EA\u542F\uFF09",
8260
- " mihomo daemon \u2192 mihomo status",
8261
- "",
8262
- "\u5F7B\u5E95\u79FB\u9664\u670D\u52A1: mihomo uninstall"
8263
- ]),
8264
- group: "meta",
8265
- usage: [],
8266
- hidden: true
8267
- },
8268
- {
8269
- name: "up",
8270
- aliases: [],
8271
- handler: removedCommand("up", "v4.1.0", ["\u8BF7\u7528: mihomo start"]),
8272
- group: "meta",
8273
- usage: [],
8274
- hidden: true
8275
- },
8276
- {
8277
- name: "down",
8278
- aliases: [],
8279
- handler: removedCommand("down", "v4.1.0", ["\u8BF7\u7528: mihomo stop"]),
8280
- group: "meta",
8281
- usage: [],
8282
- hidden: true
8283
- },
8284
8040
  // === 界面 ===
8285
8041
  {
8286
8042
  name: "ui",
@@ -8289,23 +8045,6 @@ var COMMANDS = [
8289
8045
  group: "interface",
8290
8046
  usage: [{ signature: "ui [zash|dash|yacd]", description: "\u6253\u5F00 Web UI\uFF08\u9ED8\u8BA4 zash\uFF09" }]
8291
8047
  },
8292
- {
8293
- // 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空),也不进补全词表
8294
- name: "log",
8295
- aliases: [],
8296
- handler: cmdLogs,
8297
- // 隐藏别名:log = logs 0 -f。用户传了编号时尊重编号(log 1 = logs 1 -f),
8298
- // 而非恒为 0——此前编号被 '0' 顶掉,log 1 跟随的是当前日志而非归档 1
8299
- rewrite: (args) => {
8300
- const hasNum = args[1] !== void 0 && /^\d+$/.test(args[1]);
8301
- const num = hasNum ? args[1] : "0";
8302
- const rest = hasNum ? args.slice(2) : args.slice(1);
8303
- return ["logs", num, "-f", ...rest];
8304
- },
8305
- group: "interface",
8306
- usage: [],
8307
- hidden: true
8308
- },
8309
8048
  {
8310
8049
  name: "logs",
8311
8050
  aliases: [],
@@ -8337,6 +8076,13 @@ var COMMANDS = [
8337
8076
  ]
8338
8077
  },
8339
8078
  // === 配置 ===
8079
+ {
8080
+ name: "config",
8081
+ aliases: [],
8082
+ handler: cmdConfig,
8083
+ group: "config",
8084
+ usage: [{ signature: "config [--json]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF09" }]
8085
+ },
8340
8086
  {
8341
8087
  name: "overwrite",
8342
8088
  aliases: ["ow"],
@@ -8363,7 +8109,7 @@ var COMMANDS = [
8363
8109
  aliases: [],
8364
8110
  handler: cmdKernel,
8365
8111
  group: "system",
8366
- usage: [{ signature: "kernel [--mirror [\u955C\u50CF]]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1Agh > \u672C\u673A\u4EE3\u7406 > \u955C\u50CF > \u76F4\u8FDE\uFF09" }]
8112
+ usage: [{ signature: "kernel [--mirror [\u955C\u50CF]]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1Agh > \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE\uFF09" }]
8367
8113
  },
8368
8114
  {
8369
8115
  name: "update",
@@ -8393,6 +8139,7 @@ var COMMANDS = [
8393
8139
  group: "system",
8394
8140
  usage: [
8395
8141
  { signature: "completion install <zsh|bash|fish>", description: "\u5B89\u88C5\u8865\u5168\u5230\u5BF9\u5E94 shell \u7684\u9ED8\u8BA4\u4F4D\u7F6E" },
8142
+ { signature: "completion uninstall <zsh|bash|fish>", description: "\u79FB\u9664\u5DF2\u5B89\u88C5\u7684\u8865\u5168" },
8396
8143
  { signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA\u8865\u5168\u811A\u672C\uFF08\u91CD\u5B9A\u5411\u6216 eval \u4F7F\u7528\uFF09" }
8397
8144
  ]
8398
8145
  },
@@ -8481,6 +8228,16 @@ function assertNotRoot(commandName) {
8481
8228
  ]
8482
8229
  });
8483
8230
  }
8231
+ function assertSupportedNodeVersion(commandName) {
8232
+ if (!MIN_NODE_VERSION) return;
8233
+ if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
8234
+ const current = process.versions.node;
8235
+ if (compareVersions(current, MIN_NODE_VERSION) >= 0) return;
8236
+ throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 >= ${MIN_NODE_VERSION}\uFF09`, {
8237
+ label: "Node \u7248\u672C\u4E0D\u652F\u6301",
8238
+ 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}`]
8239
+ });
8240
+ }
8484
8241
  function assertSupportedPlatform(commandName) {
8485
8242
  if (process.platform === "darwin") return;
8486
8243
  if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
@@ -8498,6 +8255,7 @@ async function main() {
8498
8255
  clearProxyEnv();
8499
8256
  const args = process.argv.slice(2);
8500
8257
  if (args.length === 0) {
8258
+ assertSupportedNodeVersion("status");
8501
8259
  assertSupportedPlatform("status");
8502
8260
  assertNotRoot("status");
8503
8261
  ensureDirs();
@@ -8513,10 +8271,11 @@ async function main() {
8513
8271
  hint: [suggestion.length > 0 ? `\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?` : '\u4F7F\u7528 "mihomo help" \u67E5\u770B\u5E2E\u52A9']
8514
8272
  });
8515
8273
  }
8274
+ assertSupportedNodeVersion(command.name);
8516
8275
  assertSupportedPlatform(command.name);
8517
8276
  assertNotRoot(command.name);
8518
8277
  ensureDirs();
8519
- assertNoRemovedSshFlag(args);
8278
+ if (command.group === "meta") assertKnownFlags(args.slice(1), [], command.name);
8520
8279
  await command.handler(command.rewrite ? command.rewrite(args) : args);
8521
8280
  }
8522
8281
  main().catch((e) => {