mihomo-cli 26.10.112 → 26.10.114

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -58,6 +58,66 @@ var compareVersions = (v1, v2) => {
58
58
  return 0;
59
59
  };
60
60
 
61
+ // node_modules/compare-versions/lib/esm/compare.js
62
+ var compare = (v1, v2, operator) => {
63
+ assertValidOperator(operator);
64
+ const res = compareVersions(v1, v2);
65
+ return operatorResMap[operator].includes(res);
66
+ };
67
+ var operatorResMap = {
68
+ ">": [1],
69
+ ">=": [0, 1],
70
+ "=": [0],
71
+ "<=": [-1, 0],
72
+ "<": [-1],
73
+ "!=": [-1, 1]
74
+ };
75
+ var allowedOperators = Object.keys(operatorResMap);
76
+ var assertValidOperator = (op) => {
77
+ if (typeof op !== "string") {
78
+ throw new TypeError(`Invalid operator type, expected string but got ${typeof op}`);
79
+ }
80
+ if (allowedOperators.indexOf(op) === -1) {
81
+ throw new Error(`Invalid operator, expected one of ${allowedOperators.join("|")}`);
82
+ }
83
+ };
84
+
85
+ // node_modules/compare-versions/lib/esm/satisfies.js
86
+ var satisfies = (version, range) => {
87
+ range = range.replace(/([><=]+)\s+/g, "$1");
88
+ if (range.includes("||")) {
89
+ return range.split("||").some((r4) => satisfies(version, r4));
90
+ } else if (range.includes(" - ")) {
91
+ const [a, b] = range.split(" - ", 2);
92
+ return satisfies(version, `>=${a} <=${b}`);
93
+ } else if (range.includes(" ")) {
94
+ return range.trim().replace(/\s{2,}/g, " ").split(" ").every((r4) => satisfies(version, r4));
95
+ }
96
+ const m = range.match(/^([<>=~^]+)/);
97
+ const op = m ? m[1] : "=";
98
+ if (op !== "^" && op !== "~")
99
+ return compare(version, range, op);
100
+ const [v1, v2, v3, , vp] = validateAndParse(version);
101
+ const [r1, r2, r3, , rp] = validateAndParse(range);
102
+ const v = [v1, v2, v3];
103
+ const r = [r1, r2 !== null && r2 !== void 0 ? r2 : "x", r3 !== null && r3 !== void 0 ? r3 : "x"];
104
+ if (rp) {
105
+ if (!vp)
106
+ return false;
107
+ if (compareSegments(v, r) !== 0)
108
+ return false;
109
+ if (compareSegments(vp.split("."), rp.split(".")) === -1)
110
+ return false;
111
+ }
112
+ const nonZero = r.findIndex((v4) => v4 !== "0") + 1;
113
+ const i = op === "~" ? 2 : nonZero > 1 ? nonZero : 1;
114
+ if (compareSegments(v.slice(0, i), r.slice(0, i)) !== 0)
115
+ return false;
116
+ if (compareSegments(v.slice(i), r.slice(i)) === -1)
117
+ return false;
118
+ return true;
119
+ };
120
+
61
121
  // src/constants.ts
62
122
  import { createRequire } from "module";
63
123
 
@@ -108,12 +168,7 @@ var pkg = require2("../package.json");
108
168
  var YAML_MAX_ALIASES = 200;
109
169
  var VERSION = pkg.version;
110
170
  var PKG_NAME = pkg.name;
111
- var MIN_NODE_VERSION = (() => {
112
- const raw = pkg.engines?.node;
113
- if (typeof raw !== "string") return null;
114
- const m = raw.trim().match(/^>=\s*(\d+\.\d+\.\d+)$/);
115
- return m ? m[1] : null;
116
- })();
171
+ var NODE_ENGINES = typeof pkg.engines?.node === "string" ? pkg.engines.node : null;
117
172
  var MIRROR_HOST = "gh-proxy.org";
118
173
  var MIRROR_ALIASES = {
119
174
  v4: `https://v4.${MIRROR_HOST}/`,
@@ -134,7 +189,6 @@ function isValidServiceLabel(label) {
134
189
  return SERVICE_LABEL_RE.test(label) && !label.includes("..");
135
190
  }
136
191
  var RAW_SERVICE_LABEL = process.env.MIHOMO_CLI_DAEMON_LABEL;
137
- var RAW_SERVICE_LABEL_INPUT = RAW_SERVICE_LABEL;
138
192
  var SERVICE_LABEL = RAW_SERVICE_LABEL && isValidServiceLabel(RAW_SERVICE_LABEL) ? RAW_SERVICE_LABEL : DEFAULT_SERVICE_LABEL;
139
193
  var SERVICE_BINARY_NAME = "mihomo-cli-service";
140
194
  var DEFAULT_MIXED_PORT = 7890;
@@ -235,8 +289,8 @@ var BASE_CONFIG = {
235
289
  var DEFAULT_UPDATE_INTERVAL_HOURS = 12;
236
290
  var DEFAULT_AUTO_UPDATE_TIMEOUT = 1e4;
237
291
  function assertServiceLabelSafe() {
238
- if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
239
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
292
+ if (RAW_SERVICE_LABEL !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL)) {
293
+ throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL}"`, {
240
294
  label: "\u914D\u7F6E\u9519\u8BEF",
241
295
  hint: ['\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002', "\u8BE5\u503C\u4F1A\u6210\u4E3A launchd plist \u7684\u6587\u4EF6\u540D\uFF0C\u53C2\u4E0E plist \u5199\u5165\u4E0E\u5220\u9664\u8DEF\u5F84\u3002"]
242
296
  });
@@ -1723,24 +1777,32 @@ function collectionTagName(state, event, defaultTagName) {
1723
1777
  function isMappingTag(tag) {
1724
1778
  return tag.nodeKind === "mapping";
1725
1779
  }
1780
+ function chargeMergeWork(state) {
1781
+ state.totalMergeKeys++;
1782
+ if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1783
+ }
1726
1784
  function mergeKeys(state, frame, source, sourceTag) {
1785
+ chargeMergeWork(state);
1727
1786
  for (const sourceKey of sourceTag.keys(source)) {
1728
- if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1787
+ chargeMergeWork(state);
1729
1788
  if (frame.tag.has(frame.value, sourceKey)) continue;
1730
1789
  const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
1731
1790
  if (err) throwError$1(state, err);
1732
- (frame.overridable ??= /* @__PURE__ */ new Set()).add(sourceKey);
1791
+ frame.overridable ??= /* @__PURE__ */ new Set();
1792
+ frame.overridable.add(sourceKey);
1733
1793
  }
1734
1794
  }
1735
1795
  function mergeSource(state, frame, source, sourceTag) {
1736
1796
  state.position = frame.keyPosition;
1737
1797
  if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag);
1738
- else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) for (const element of source) {
1739
- const elementTag = state.nodeTags.get(element);
1740
- if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1741
- mergeKeys(state, frame, element, elementTag);
1742
- }
1743
- else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1798
+ else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
1799
+ if (source.length > 100) throwError$1(state, "abnormal merge sequence size");
1800
+ for (const element of source) {
1801
+ const elementTag = state.nodeTags.get(element);
1802
+ if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1803
+ mergeKeys(state, frame, element, elementTag);
1804
+ }
1805
+ } else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1744
1806
  }
1745
1807
  function addMappingValue(state, frame, key, value, tag) {
1746
1808
  state.position = frame.keyPosition;
@@ -2083,6 +2145,24 @@ function testDocumentSeparator(state, position = state.position) {
2083
2145
  }
2084
2146
  return false;
2085
2147
  }
2148
+ function skipByteOrderMark(state) {
2149
+ if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
2150
+ state.position++;
2151
+ state.lineStart = state.position;
2152
+ }
2153
+ }
2154
+ function testDocumentBoundary(state) {
2155
+ if (state.position !== state.lineStart) return false;
2156
+ if (testDocumentSeparator(state)) return true;
2157
+ if (state.input.charCodeAt(state.position) !== 65279) return false;
2158
+ const snapshot = snapshotState(state);
2159
+ skipByteOrderMark(state);
2160
+ skipSeparationSpace(state, true);
2161
+ const ch = state.input.charCodeAt(state.position);
2162
+ const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
2163
+ restoreState(state, snapshot);
2164
+ return result;
2165
+ }
2086
2166
  function skipUntilLineEnd(state) {
2087
2167
  let ch = state.input.charCodeAt(state.position);
2088
2168
  while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
@@ -2266,14 +2346,14 @@ function readBlockScalar(state, parentIndent, props) {
2266
2346
  } else if (column > 0) valueEnd = linePosition + column;
2267
2347
  break;
2268
2348
  }
2269
- if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break;
2349
+ if (testDocumentBoundary(state)) break;
2270
2350
  if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column);
2271
2351
  if (!detectedIndent && contentIndent === -1 && !isEol(first)) {
2272
2352
  if (first === 9 && column < parentIndent) {
2273
2353
  state.position = linePosition + column;
2274
2354
  throwError(state, "tab characters must not be used in indentation");
2275
2355
  }
2276
- if (column < maxLeadingIndent) {
2356
+ if (column >= parentIndent && column < maxLeadingIndent) {
2277
2357
  state.position = linePosition + column;
2278
2358
  throwError(state, "bad indentation of a mapping entry");
2279
2359
  }
@@ -2319,7 +2399,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
2319
2399
  const inFlow = nodeContext === CONTEXT_FLOW_IN;
2320
2400
  let multiline = false;
2321
2401
  while (ch !== 0) {
2322
- if (state.position === state.lineStart && testDocumentSeparator(state)) break;
2402
+ if (testDocumentBoundary(state)) break;
2323
2403
  if (ch === 58) {
2324
2404
  const following = state.input.charCodeAt(state.position + 1);
2325
2405
  if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break;
@@ -2483,13 +2563,16 @@ function readBlockMapping(state, nodeIndent, flowIndent, props) {
2483
2563
  ch = state.input.charCodeAt(++state.position);
2484
2564
  if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2485
2565
  if (!mappingOpened) {
2486
- restoreState(state, beforeKey);
2487
- addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2566
+ state.events.splice(beforeKey.eventsLength, 0, {
2567
+ type: EVENT_ID.MAPPING,
2568
+ start: beforeKey.position,
2569
+ anchorStart: props.anchorStart,
2570
+ anchorEnd: props.anchorEnd,
2571
+ tagStart: props.tagStart,
2572
+ tagEnd: props.tagEnd,
2573
+ style: COLLECTION_STYLE.BLOCK
2574
+ });
2488
2575
  mappingOpened = true;
2489
- parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true);
2490
- ch = state.input.charCodeAt(state.position);
2491
- while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
2492
- state.position++;
2493
2576
  }
2494
2577
  detected = true;
2495
2578
  atExplicitKey = false;
@@ -2676,7 +2759,7 @@ function readDocument(state) {
2676
2759
  const documentEvent = state.events[documentEventIndex];
2677
2760
  if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd;
2678
2761
  addPopEvent(state);
2679
- if (!explicitEnd && state.position < state.length && !(state.position === state.lineStart && testDocumentSeparator(state))) throwError(state, "end of the stream or a document separator is expected");
2762
+ if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state)) throwError(state, "end of the stream or a document separator is expected");
2680
2763
  }
2681
2764
  function parseEvents(input, options) {
2682
2765
  const length = input.length;
@@ -2697,8 +2780,8 @@ function parseEvents(input, options) {
2697
2780
  };
2698
2781
  const nullpos = input.indexOf("\0");
2699
2782
  if (nullpos !== -1) YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename);
2700
- if (state.input.charCodeAt(state.position) === 65279) state.position++;
2701
2783
  while (state.position < state.length) {
2784
+ skipByteOrderMark(state);
2702
2785
  skipSeparationSpace(state, true);
2703
2786
  if (state.position >= state.length) break;
2704
2787
  const documentStart = state.position;
@@ -2731,15 +2814,6 @@ function load(input, options) {
2731
2814
  if (documents.length === 1) return documents[0];
2732
2815
  throw new YAMLException("expected a single document in the stream, but found more");
2733
2816
  }
2734
- var Style = class {
2735
- /** Whether to print the node's tag explicitly. */
2736
- tagged = false;
2737
- flow = false;
2738
- singleQuoted = false;
2739
- doubleQuoted = false;
2740
- literal = false;
2741
- folded = false;
2742
- };
2743
2817
  var INVALID = /* @__PURE__ */ Symbol("INVALID");
2744
2818
  function buildRepresentTypes(schema) {
2745
2819
  const defaultTags = new Set([
@@ -2788,8 +2862,6 @@ function build(state, object) {
2788
2862
  if (existing.anchor === void 0) existing.anchor = `ref_${state.refCounter++}`;
2789
2863
  return {
2790
2864
  kind: "alias",
2791
- tag: "",
2792
- style: new Style(),
2793
2865
  anchor: existing.anchor
2794
2866
  };
2795
2867
  }
@@ -2802,24 +2874,20 @@ function build(state, object) {
2802
2874
  }
2803
2875
  const { tag, tagName, implicitTag } = matched;
2804
2876
  const nodeTagName = implicitTag ? tagName : tagNameShort(tagName);
2805
- if (tag.nodeKind === "scalar") {
2806
- const style2 = new Style();
2807
- style2.tagged = !implicitTag;
2808
- return {
2809
- kind: "scalar",
2810
- tag: nodeTagName,
2811
- style: style2,
2812
- value: tag.represent(object)
2813
- };
2814
- }
2877
+ if (tag.nodeKind === "scalar") return {
2878
+ kind: "scalar",
2879
+ tag: nodeTagName,
2880
+ tagged: !implicitTag,
2881
+ style: SCALAR_STYLE.PLAIN,
2882
+ value: tag.represent(object)
2883
+ };
2815
2884
  if (tag.nodeKind === "sequence") {
2816
2885
  const container = tag.represent(object);
2817
- const style2 = new Style();
2818
- style2.tagged = !implicitTag;
2819
2886
  const node2 = {
2820
2887
  kind: "sequence",
2821
2888
  tag: nodeTagName,
2822
- style: style2,
2889
+ tagged: !implicitTag,
2890
+ style: COLLECTION_STYLE.BLOCK,
2823
2891
  items: []
2824
2892
  };
2825
2893
  if (!state.noRefs) state.refs.set(object, node2);
@@ -2832,12 +2900,11 @@ function build(state, object) {
2832
2900
  return node2;
2833
2901
  }
2834
2902
  const map = tag.represent(object);
2835
- const style = new Style();
2836
- style.tagged = !implicitTag;
2837
2903
  const node = {
2838
2904
  kind: "mapping",
2839
2905
  tag: nodeTagName,
2840
- style,
2906
+ tagged: !implicitTag,
2907
+ style: COLLECTION_STYLE.BLOCK,
2841
2908
  items: []
2842
2909
  };
2843
2910
  if (!state.noRefs) state.refs.set(object, node);
@@ -2905,82 +2972,204 @@ function visit(documents, visitor) {
2905
2972
  isKey: false
2906
2973
  })) return;
2907
2974
  }
2908
- var CHAR_BOM = 65279;
2909
- var CHAR_TAB = 9;
2910
- var CHAR_LINE_FEED = 10;
2911
- var CHAR_CARRIAGE_RETURN = 13;
2912
- var CHAR_SPACE = 32;
2913
- var CHAR_EXCLAMATION = 33;
2914
- var CHAR_DOUBLE_QUOTE = 34;
2915
- var CHAR_SHARP = 35;
2916
- var CHAR_PERCENT = 37;
2917
- var CHAR_AMPERSAND = 38;
2918
- var CHAR_SINGLE_QUOTE = 39;
2919
- var CHAR_ASTERISK = 42;
2920
- var CHAR_COMMA = 44;
2921
- var CHAR_MINUS = 45;
2922
- var CHAR_COLON = 58;
2923
- var CHAR_EQUALS = 61;
2924
- var CHAR_GREATER_THAN = 62;
2925
- var CHAR_QUESTION = 63;
2926
- var CHAR_COMMERCIAL_AT = 64;
2927
- var CHAR_LEFT_SQUARE_BRACKET = 91;
2928
- var CHAR_RIGHT_SQUARE_BRACKET = 93;
2929
- var CHAR_GRAVE_ACCENT = 96;
2930
- var CHAR_LEFT_CURLY_BRACKET = 123;
2931
- var CHAR_VERTICAL_LINE = 124;
2932
- var CHAR_RIGHT_CURLY_BRACKET = 125;
2933
- var ESCAPE_SEQUENCES = {};
2934
- ESCAPE_SEQUENCES[0] = "\\0";
2935
- ESCAPE_SEQUENCES[7] = "\\a";
2936
- ESCAPE_SEQUENCES[8] = "\\b";
2937
- ESCAPE_SEQUENCES[9] = "\\t";
2938
- ESCAPE_SEQUENCES[10] = "\\n";
2939
- ESCAPE_SEQUENCES[11] = "\\v";
2940
- ESCAPE_SEQUENCES[12] = "\\f";
2941
- ESCAPE_SEQUENCES[13] = "\\r";
2942
- ESCAPE_SEQUENCES[27] = "\\e";
2943
- ESCAPE_SEQUENCES[34] = '\\"';
2944
- ESCAPE_SEQUENCES[92] = "\\\\";
2945
- ESCAPE_SEQUENCES[133] = "\\N";
2946
- ESCAPE_SEQUENCES[160] = "\\_";
2947
- ESCAPE_SEQUENCES[8232] = "\\L";
2948
- ESCAPE_SEQUENCES[8233] = "\\P";
2949
- var DEFAULT_PRESENTER_OPTIONS = {
2950
- indent: 2,
2951
- seqNoIndent: false,
2952
- seqInlineFirst: true,
2953
- sortKeys: false,
2954
- lineWidth: 80,
2955
- flowBracketPadding: false,
2956
- flowSkipCommaSpace: false,
2957
- flowSkipColonSpace: false,
2958
- quoteFlowKeys: false,
2959
- quoteStyle: "single",
2960
- forceQuotes: false,
2961
- tagBeforeAnchor: false
2975
+ function hasBit(mask, bit) {
2976
+ return (mask & 1 << bit) !== 0;
2977
+ }
2978
+ var DEFAULT_SCALAR_STYLE_RULES = {
2979
+ applyQuoteFlowKeysOption,
2980
+ doubleQuoteForInvisibles,
2981
+ doubleQuoteWhitespaceOnly,
2982
+ applyForceQuotesOption,
2983
+ tryLongOrMultilineAsBlock,
2984
+ quoteInvalidPlain,
2985
+ fallbackToDoubleQuoted
2962
2986
  };
2963
- function nodeTagShort(node) {
2964
- return node.style.tagged ? node.tag : tagNameShort(node.tag);
2987
+ function _preferredQuotedStyle(layout) {
2988
+ if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED)) return SCALAR_STYLE.SINGLE_QUOTED;
2989
+ return SCALAR_STYLE.DOUBLE_QUOTED;
2990
+ }
2991
+ function applyQuoteFlowKeysOption(layout) {
2992
+ if (!layout.presenterOptions.quoteFlowKeys) return;
2993
+ if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN) return;
2994
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2995
+ }
2996
+ function doubleQuoteForInvisibles(layout) {
2997
+ if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2998
+ }
2999
+ function doubleQuoteWhitespaceOnly(layout) {
3000
+ if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
3001
+ }
3002
+ function applyForceQuotesOption(layout) {
3003
+ if (!layout.presenterOptions.forceQuotes) return;
3004
+ if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN) return;
3005
+ if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName) return;
3006
+ layout.style = layout.node.value.includes("\n") ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
3007
+ }
3008
+ function tryLongOrMultilineAsBlock(layout) {
3009
+ if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey) return;
3010
+ const value = layout.node.value;
3011
+ const multiline = value.indexOf("\n") !== -1;
3012
+ if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
3013
+ if (multiline) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
3014
+ return;
3015
+ }
3016
+ const w = layout.presenterOptions.lineWidth;
3017
+ if (w === -1) {
3018
+ if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
3019
+ return;
3020
+ }
3021
+ const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
3022
+ let position = 0;
3023
+ let shouldFold = false;
3024
+ while (position <= value.length) {
3025
+ let lineEnd = value.length;
3026
+ const nextLineBreak = value.indexOf("\n", position);
3027
+ if (nextLineBreak !== -1) lineEnd = nextLineBreak;
3028
+ const line = value.slice(position, lineEnd);
3029
+ if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line)) shouldFold = true;
3030
+ if (nextLineBreak === -1) break;
3031
+ position = nextLineBreak + 1;
3032
+ }
3033
+ if (shouldFold) layout.style = SCALAR_STYLE.FOLDED_BLOCK;
3034
+ else if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
3035
+ }
3036
+ function quoteInvalidPlain(layout) {
3037
+ if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN)) layout.style = _preferredQuotedStyle(layout);
3038
+ }
3039
+ function fallbackToDoubleQuoted(layout) {
3040
+ if (!hasBit(layout.allowedStylesMask, layout.style)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
3041
+ }
3042
+ function setBit(mask, bit) {
3043
+ return mask | 1 << bit;
3044
+ }
3045
+ var SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]";
3046
+ var SRC_B_CHAR = "[\\n\\r]";
3047
+ var SRC_C_BYTE_ORDER_MARK = "\\uFEFF";
3048
+ var SRC_S_WHITE = "[ \\t]";
3049
+ var SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
3050
+ var SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
3051
+ var SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]";
3052
+ var SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]";
3053
+ var SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]";
3054
+ var SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
3055
+ var SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
3056
+ var SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
3057
+ var SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
3058
+ var SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
3059
+ var SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
3060
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
3061
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
3062
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
3063
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
3064
+ var SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
3065
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
3066
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
3067
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
3068
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
3069
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
3070
+ var NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
3071
+ var NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
3072
+ var NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
3073
+ var NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
3074
+ var NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
3075
+ var NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
3076
+ var BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
3077
+ var C_FORBIDDEN_FIRST_LINE = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/;
3078
+ var C_FORBIDDEN_CONTENT = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/m;
3079
+ function canUsePlain(layout) {
3080
+ const str = layout.node.value;
3081
+ if (str !== "") {
3082
+ if (!(layout.isKey ? layout.flowOnly ? NS_PLAIN_FLOW_KEY : NS_PLAIN_BLOCK_KEY : layout.flowOnly ? NS_PLAIN_FLOW_IN : NS_PLAIN_FLOW_OUT).test(str)) return false;
3083
+ if (layout.shiftOfFirstLine === 0 && C_FORBIDDEN_FIRST_LINE.test(str)) return false;
3084
+ if (layout.shiftOfContent === 0) {
3085
+ const firstLineBreak = str.indexOf("\n");
3086
+ if (firstLineBreak !== -1) {
3087
+ const content = str.slice(firstLineBreak + 1);
3088
+ if (C_FORBIDDEN_CONTENT.test(content)) return false;
3089
+ }
3090
+ }
3091
+ }
3092
+ const resolvedTag = layout.presenterOptions.schema.resolveImplicitScalarTag(str).tag.tagName;
3093
+ if (!layout.node.tagged && resolvedTag !== layout.node.tag) return false;
3094
+ if (!layout.node.tagged && str === "=" && resolvedTag === layout.presenterOptions.schema.defaultScalarTag.tagName) return false;
3095
+ return true;
2965
3096
  }
2966
- function createPresenterState(options) {
2967
- const opts = {
2968
- ...DEFAULT_PRESENTER_OPTIONS,
2969
- ...options
2970
- };
2971
- return {
2972
- ...opts,
2973
- defaultScalarTagName: opts.schema.defaultScalarTag.tagName
2974
- };
3097
+ function canUseSingleQuoted(layout) {
3098
+ const str = layout.node.value;
3099
+ if (!(layout.isKey ? NB_SINGLE_ONE_LINE : NB_SINGLE_MULTI_LINE).test(str)) return false;
3100
+ if (/[ \t]\n|\n[ \t]/.test(str)) return false;
3101
+ if (!layout.isKey && layout.shiftOfContent === 0) {
3102
+ const firstLineBreak = str.indexOf("\n");
3103
+ if (firstLineBreak !== -1 && C_FORBIDDEN_CONTENT.test(str.slice(firstLineBreak + 1))) return false;
3104
+ }
3105
+ return true;
3106
+ }
3107
+ function canUseBlock(layout) {
3108
+ if (layout.flowOnly || !BLOCK_SCALAR_CONTENT.test(layout.node.value)) return false;
3109
+ const contentIndent = layout.shiftOfContent - layout.shiftOfParent;
3110
+ if (contentIndent < 1) return false;
3111
+ if (contentIndent > 9 && /^\n* /.test(layout.node.value)) return false;
3112
+ if (layout.shiftOfContent === 0 && C_FORBIDDEN_CONTENT.test(layout.node.value)) return false;
3113
+ return true;
3114
+ }
3115
+ function detectAllowedStyles(layout) {
3116
+ let mask = setBit(0, SCALAR_STYLE.DOUBLE_QUOTED);
3117
+ if (canUsePlain(layout)) mask = setBit(mask, SCALAR_STYLE.PLAIN);
3118
+ if (canUseSingleQuoted(layout)) mask = setBit(mask, SCALAR_STYLE.SINGLE_QUOTED);
3119
+ if (canUseBlock(layout)) mask = setBit(setBit(mask, SCALAR_STYLE.LITERAL_BLOCK), SCALAR_STYLE.FOLDED_BLOCK);
3120
+ layout.allowedStylesMask = mask;
3121
+ }
3122
+ function renderScalar(layout) {
3123
+ switch (layout.style) {
3124
+ case SCALAR_STYLE.PLAIN:
3125
+ return renderPlain(layout);
3126
+ case SCALAR_STYLE.SINGLE_QUOTED:
3127
+ return renderSingleQuoted(layout);
3128
+ case SCALAR_STYLE.LITERAL_BLOCK:
3129
+ return renderLiteralBlock(layout);
3130
+ case SCALAR_STYLE.FOLDED_BLOCK:
3131
+ return renderFoldedBlock(layout);
3132
+ case SCALAR_STYLE.DOUBLE_QUOTED:
3133
+ return renderDoubleQuoted(layout);
3134
+ }
3135
+ }
3136
+ function renderPlain(layout) {
3137
+ return encodeFlowBreaks(layout.node.value, layout.shiftOfContent);
3138
+ }
3139
+ function renderSingleQuoted(layout) {
3140
+ return `'${encodeFlowBreaks(layout.node.value, layout.shiftOfContent).replace(/'/g, "''")}'`;
3141
+ }
3142
+ function renderLiteralBlock(layout) {
3143
+ const value = layout.node.value;
3144
+ return "|" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(value, layout.shiftOfContent));
3145
+ }
3146
+ function renderFoldedBlock(layout) {
3147
+ const value = layout.node.value;
3148
+ const w = layout.presenterOptions.lineWidth;
3149
+ let availableWidth = Infinity;
3150
+ if (w !== -1) availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
3151
+ return ">" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(foldBlockScalar(value, availableWidth), layout.shiftOfContent));
3152
+ }
3153
+ function renderDoubleQuoted(layout) {
3154
+ return `"${escapeString(layout.node.value)}"`;
2975
3155
  }
2976
- function encodeNonPrintable(character) {
2977
- const string = character.toString(16).toUpperCase();
2978
- const handle = character <= 255 ? "x" : "u";
2979
- const length = character <= 255 ? 2 : 4;
2980
- return `\\${handle}${"0".repeat(length - string.length)}${string}`;
3156
+ function encodeFlowBreaks(string, shiftOfContent) {
3157
+ let nextLF = string.indexOf("\n");
3158
+ if (nextLF === -1) return string;
3159
+ const pad = " ".repeat(shiftOfContent);
3160
+ let result = string.slice(0, nextLF);
3161
+ const lineRe = /(\n+)([^\n]*)/g;
3162
+ lineRe.lastIndex = nextLF;
3163
+ let match;
3164
+ while (match = lineRe.exec(string)) {
3165
+ const breaks = match[1].length;
3166
+ const line = match[2];
3167
+ result += "\n".repeat(breaks + 1) + pad + line;
3168
+ }
3169
+ return result;
2981
3170
  }
2982
3171
  function indentString(string, spaces) {
2983
- const ind = " ".repeat(spaces);
3172
+ const indent = " ".repeat(spaces);
2984
3173
  let position = 0;
2985
3174
  let result = "";
2986
3175
  const length = string.length;
@@ -2994,191 +3183,26 @@ function indentString(string, spaces) {
2994
3183
  line = string.slice(position, next + 1);
2995
3184
  position = next + 1;
2996
3185
  }
2997
- if (line.length && line !== "\n") result += ind;
3186
+ if (line.length && line !== "\n") result += indent;
2998
3187
  result += line;
2999
3188
  }
3000
3189
  return result;
3001
3190
  }
3002
- function generateNextLine(state, level) {
3003
- return `
3004
- ${" ".repeat(state.indent * level)}`;
3005
- }
3006
- function scalarLayout(state, level) {
3007
- const indent = state.indent * Math.max(1, level);
3008
- return {
3009
- indent,
3010
- blockIndent: level === 0 ? state.indent + 1 : state.indent,
3011
- lineWidth: state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent)
3012
- };
3013
- }
3014
- function isWhitespace(c) {
3015
- return c === CHAR_SPACE || c === CHAR_TAB;
3016
- }
3017
- function startsWithDocumentSeparator(string) {
3018
- const marker = string.charCodeAt(0);
3019
- if (marker !== CHAR_MINUS && marker !== 46 || string.charCodeAt(1) !== marker || string.charCodeAt(2) !== marker) return false;
3020
- if (string.length === 3) return true;
3021
- const following = string.charCodeAt(3);
3022
- return isWhitespace(following) || following === CHAR_CARRIAGE_RETURN || following === CHAR_LINE_FEED;
3023
- }
3024
- function isPrintable(c) {
3025
- return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111;
3026
- }
3027
- function isNsCharOrWhitespace(c) {
3028
- return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
3029
- }
3030
- function isPlainSafe(c, prev, inblock) {
3031
- const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
3032
- const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
3033
- return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar && (inblock || c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET);
3034
- }
3035
- function isPlainSafeFirst(c) {
3036
- return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
3037
- }
3038
- function isPlainSafeAtStart(string, inblock) {
3039
- const first = codePointAt(string, 0);
3040
- if (isPlainSafeFirst(first)) return true;
3041
- if (string.length > 1 && (first === CHAR_MINUS || first === CHAR_QUESTION || first === CHAR_COLON)) {
3042
- const second = codePointAt(string, 1);
3043
- return !isWhitespace(second) && isPlainSafe(second, first, inblock);
3044
- }
3045
- return false;
3046
- }
3047
- function isPlainSafeLast(c) {
3048
- return !isWhitespace(c) && c !== CHAR_COLON;
3049
- }
3050
- function codePointAt(string, pos) {
3051
- const first = string.charCodeAt(pos);
3052
- let second;
3053
- if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
3054
- second = string.charCodeAt(pos + 1);
3055
- if (second >= 56320 && second <= 57343) return (first - 55296) * 1024 + second - 56320 + 65536;
3056
- }
3057
- return first;
3058
- }
3059
3191
  function needIndentIndicator(string) {
3060
3192
  return /^\n* /.test(string);
3061
3193
  }
3062
- var STYLE_PLAIN = 1;
3063
- var STYLE_SINGLE = 2;
3064
- var STYLE_LITERAL = 3;
3065
- var STYLE_FOLDED = 4;
3066
- var STYLE_DOUBLE = 5;
3067
- function chooseScalarStyle(state, string, layout, singleLineOnly, forceQuote, inblock) {
3068
- const { blockIndent, lineWidth } = layout;
3069
- let i;
3070
- let char = 0;
3071
- let prevChar = -1;
3072
- let hasLineBreak = false;
3073
- let hasFoldableLine = false;
3074
- const shouldTrackWidth = lineWidth !== -1;
3075
- let previousLineBreak = -1;
3076
- let plain = !startsWithDocumentSeparator(string) && isPlainSafeAtStart(string, inblock) && isPlainSafeLast(codePointAt(string, string.length - 1));
3077
- if (singleLineOnly || forceQuote) for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
3078
- char = codePointAt(string, i);
3079
- if (!isPrintable(char)) return STYLE_DOUBLE;
3080
- plain = plain && isPlainSafe(char, prevChar, inblock);
3081
- prevChar = char;
3082
- }
3083
- else {
3084
- for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
3085
- char = codePointAt(string, i);
3086
- if (char === CHAR_LINE_FEED) {
3087
- hasLineBreak = true;
3088
- if (shouldTrackWidth) {
3089
- hasFoldableLine = hasFoldableLine || i - previousLineBreak - 1 > lineWidth && !isMoreIndented(string[previousLineBreak + 1]);
3090
- previousLineBreak = i;
3091
- }
3092
- } else if (!isPrintable(char)) return STYLE_DOUBLE;
3093
- plain = plain && isPlainSafe(char, prevChar, inblock);
3094
- prevChar = char;
3095
- }
3096
- hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && !isMoreIndented(string[previousLineBreak + 1]);
3097
- }
3098
- if (!hasLineBreak && !hasFoldableLine) {
3099
- if (plain && !forceQuote) return STYLE_PLAIN;
3100
- return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
3101
- }
3102
- if (blockIndent > 9 && needIndentIndicator(string)) return STYLE_DOUBLE;
3103
- return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
3104
- }
3105
- function renderScalarStyle(string, style, layout) {
3106
- const { indent, blockIndent, lineWidth } = layout;
3107
- switch (style) {
3108
- case STYLE_PLAIN:
3109
- return encodeFlowBreaks(string, indent);
3110
- case STYLE_SINGLE:
3111
- return `'${encodeFlowBreaks(string, indent).replace(/'/g, "''")}'`;
3112
- case STYLE_LITERAL:
3113
- return "|" + blockHeader(string, blockIndent) + dropEndingNewline(indentString(string, indent));
3114
- case STYLE_FOLDED:
3115
- return ">" + blockHeader(string, blockIndent) + dropEndingNewline(indentString(foldBlockScalar(string, lineWidth), indent));
3116
- case STYLE_DOUBLE:
3117
- return `"${escapeString(string)}"`;
3118
- }
3119
- }
3120
- function resolveScalarStyle(state, node, layout, iskey, inblock) {
3121
- const singleLineOnly = iskey || !inblock;
3122
- if (node.style.singleQuoted) return STYLE_SINGLE;
3123
- if (node.style.doubleQuoted) return STYLE_DOUBLE;
3124
- if (!singleLineOnly) {
3125
- if (node.style.literal) return STYLE_LITERAL;
3126
- if (node.style.folded) return STYLE_FOLDED;
3127
- }
3128
- const string = node.value;
3129
- if (string.length === 0) {
3130
- if (node.style.tagged || state.schema.resolveImplicitScalarTag(string).tag.tagName === node.tag) return STYLE_PLAIN;
3131
- return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
3132
- }
3133
- const style = chooseScalarStyle(state, string, layout, singleLineOnly, state.forceQuotes && !iskey, inblock);
3134
- if (style === STYLE_PLAIN && !node.style.tagged && state.schema.resolveImplicitScalarTag(string).tag.tagName !== node.tag) return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
3135
- return style;
3136
- }
3137
- function blockHeader(string, indentPerLevel) {
3138
- const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
3194
+ function blockHeader(string, shiftOfParent, shiftOfContent) {
3195
+ const indentIndicator = needIndentIndicator(string) ? String(shiftOfContent - shiftOfParent) : "";
3139
3196
  const clip = string[string.length - 1] === "\n";
3140
3197
  return `${indentIndicator}${clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-"}
3141
3198
  `;
3142
3199
  }
3143
- function encodeFlowBreaks(string, indent) {
3144
- let nextLF = string.indexOf("\n");
3145
- if (nextLF === -1) return string;
3146
- const pad = " ".repeat(indent);
3147
- let result = string.slice(0, nextLF);
3148
- const lineRe = /(\n+)([^\n]*)/g;
3149
- lineRe.lastIndex = nextLF;
3150
- let match;
3151
- while (match = lineRe.exec(string)) {
3152
- const breaks = match[1].length;
3153
- const line = match[2];
3154
- result += "\n".repeat(breaks + 1) + pad + line;
3155
- }
3156
- return result;
3157
- }
3158
3200
  function dropEndingNewline(string) {
3159
3201
  return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
3160
3202
  }
3161
3203
  function isMoreIndented(char) {
3162
3204
  return char === " " || char === " ";
3163
3205
  }
3164
- function foldBlockScalar(string, width) {
3165
- const lineRe = /(\n+)([^\n]*)/g;
3166
- let nextLF = string.indexOf("\n");
3167
- if (nextLF === -1) nextLF = string.length;
3168
- lineRe.lastIndex = nextLF;
3169
- let result = foldLine(string.slice(0, nextLF), width);
3170
- let prevMoreIndented = string[0] === "\n" || isMoreIndented(string[0]);
3171
- let moreIndented;
3172
- let match;
3173
- while (match = lineRe.exec(string)) {
3174
- const prefix = match[1];
3175
- const line = match[2];
3176
- moreIndented = line !== "" && isMoreIndented(line[0]);
3177
- result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
3178
- prevMoreIndented = moreIndented;
3179
- }
3180
- return result;
3181
- }
3182
3206
  function foldLine(line, width) {
3183
3207
  if (line === "" || isMoreIndented(line[0])) return line;
3184
3208
  const breakRe = / [^ \t]/g;
@@ -3204,43 +3228,133 @@ ${line.slice(curr + 1)}`;
3204
3228
  else result += line.slice(start);
3205
3229
  return result.slice(1);
3206
3230
  }
3207
- function escapeString(string) {
3208
- let result = "";
3209
- let char = 0;
3210
- for (let i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
3211
- char = codePointAt(string, i);
3212
- const escapeSeq = ESCAPE_SEQUENCES[char];
3213
- if (escapeSeq) {
3214
- result += escapeSeq;
3215
- continue;
3216
- }
3217
- if (isPrintable(char)) {
3218
- result += string[i];
3219
- if (char >= 65536) result += string[i + 1];
3220
- continue;
3221
- }
3222
- result += encodeNonPrintable(char);
3231
+ function foldBlockScalar(string, width) {
3232
+ const lineRe = /(\n+)([^\n]*)/g;
3233
+ let nextLF = string.indexOf("\n");
3234
+ if (nextLF === -1) nextLF = string.length;
3235
+ lineRe.lastIndex = nextLF;
3236
+ let result = foldLine(string.slice(0, nextLF), width);
3237
+ let prevMoreIndented = string[0] === "\n" || isMoreIndented(string[0]);
3238
+ let moreIndented;
3239
+ let match;
3240
+ while (match = lineRe.exec(string)) {
3241
+ const prefix = match[1];
3242
+ const line = match[2];
3243
+ moreIndented = line !== "" && isMoreIndented(line[0]);
3244
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
3245
+ prevMoreIndented = moreIndented;
3223
3246
  }
3224
3247
  return result;
3225
3248
  }
3249
+ var CHARACTERS_TO_ESCAPE = /["\\\x00-\x1F\x7F-\xA0\u2028\u2029\uD800-\uDFFF\uFEFF\uFFFE\uFFFF]/gu;
3250
+ function escapeCharacter(character) {
3251
+ switch (character) {
3252
+ case "\0":
3253
+ return "\\0";
3254
+ case "\x07":
3255
+ return "\\a";
3256
+ case "\b":
3257
+ return "\\b";
3258
+ case " ":
3259
+ return "\\t";
3260
+ case "\n":
3261
+ return "\\n";
3262
+ case "\v":
3263
+ return "\\v";
3264
+ case "\f":
3265
+ return "\\f";
3266
+ case "\r":
3267
+ return "\\r";
3268
+ case "\x1B":
3269
+ return "\\e";
3270
+ case '"':
3271
+ return '\\"';
3272
+ case "\\":
3273
+ return "\\\\";
3274
+ case "\x85":
3275
+ return "\\N";
3276
+ case "\xA0":
3277
+ return "\\_";
3278
+ case "\u2028":
3279
+ return "\\L";
3280
+ case "\u2029":
3281
+ return "\\P";
3282
+ }
3283
+ const code = character.charCodeAt(0);
3284
+ const hex = code.toString(16).toUpperCase();
3285
+ if (code <= 255) return `\\x${"0".repeat(2 - hex.length)}${hex}`;
3286
+ return `\\u${"0".repeat(4 - hex.length)}${hex}`;
3287
+ }
3288
+ function escapeString(string) {
3289
+ return string.replace(CHARACTERS_TO_ESCAPE, escapeCharacter);
3290
+ }
3291
+ var CHAR_LINE_FEED = 10;
3292
+ var DEFAULT_PRESENTER_OPTIONS = {
3293
+ indent: 2,
3294
+ seqNoIndent: false,
3295
+ seqInlineFirst: true,
3296
+ lineWidth: 80,
3297
+ flowBracketPadding: false,
3298
+ flowSkipCommaSpace: false,
3299
+ flowSkipColonSpace: false,
3300
+ quoteFlowKeys: false,
3301
+ quoteStyle: "single",
3302
+ forceQuotes: false,
3303
+ scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
3304
+ tagBeforeAnchor: false
3305
+ };
3306
+ function nodeTagShort(node) {
3307
+ return node.tagged ? node.tag : tagNameShort(node.tag);
3308
+ }
3309
+ function createPresenterState(options) {
3310
+ const opts = {
3311
+ ...DEFAULT_PRESENTER_OPTIONS,
3312
+ ...options
3313
+ };
3314
+ if (opts.flowSkipColonSpace) opts.quoteFlowKeys = true;
3315
+ return {
3316
+ ...opts,
3317
+ defaultScalarTagName: opts.schema.defaultScalarTag.tagName,
3318
+ openEnded: false
3319
+ };
3320
+ }
3321
+ function generateNextLine(state, level) {
3322
+ return `
3323
+ ${" ".repeat(state.indent * level)}`;
3324
+ }
3325
+ function scalarLayout(state, node, parent, level, isKey, flowOnly) {
3326
+ return {
3327
+ node,
3328
+ parent,
3329
+ level,
3330
+ isKey,
3331
+ flowOnly,
3332
+ shiftOfParent: level === 0 ? -1 : state.indent * (level - 1),
3333
+ shiftOfContent: state.indent * Math.max(1, level),
3334
+ shiftOfFirstLine: level === 0 ? 0 : state.indent * level,
3335
+ presenterOptions: state,
3336
+ allowedStylesMask: 0,
3337
+ style: node.style
3338
+ };
3339
+ }
3226
3340
  function writeFlowSequence(state, level, node) {
3227
3341
  let result = "";
3228
3342
  for (let index = 0, length = node.items.length; index < length; index += 1) {
3229
- const item = writeNode(state, level, node.items[index], {});
3230
- if (result !== "") result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3343
+ const item = writeNode(state, level, node.items[index], node, {}).text;
3344
+ if (index > 0) result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3231
3345
  result += item;
3232
3346
  }
3233
- const pad = state.flowBracketPadding && result !== "" ? " " : "";
3347
+ const pad = state.flowBracketPadding && node.items.length > 0 ? " " : "";
3234
3348
  return `[${pad}${result}${pad}]`;
3235
3349
  }
3236
3350
  function writeBlockSequence(state, level, node, compact) {
3237
3351
  let result = "";
3238
3352
  for (let index = 0, length = node.items.length; index < length; index += 1) {
3239
- const item = writeNode(state, level + 1, node.items[index], {
3353
+ const item = writeNode(state, level + 1, node.items[index], node, {
3240
3354
  block: true,
3241
3355
  compact: state.seqInlineFirst,
3242
3356
  isblockseq: true
3243
- });
3357
+ }).text;
3244
3358
  if (!compact || result !== "") result += generateNextLine(state, level);
3245
3359
  if (item === "" || CHAR_LINE_FEED === item.charCodeAt(0)) result += "-";
3246
3360
  else result += "- ";
@@ -3250,70 +3364,51 @@ function writeBlockSequence(state, level, node, compact) {
3250
3364
  }
3251
3365
  function writeFlowMapping(state, level, node) {
3252
3366
  let result = "";
3253
- const items = sortMappingItems(state, node.items);
3254
- for (const { key, value } of items) {
3367
+ for (const { key, value } of node.items) {
3255
3368
  let pairBuffer = "";
3256
3369
  if (result !== "") pairBuffer += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3257
- const keyText = writeNode(state, level, key, { iskey: true });
3258
- const explicitPair = keyText.length > 1024;
3259
- if (explicitPair) pairBuffer += "? ";
3260
- else if (state.quoteFlowKeys) pairBuffer += '"';
3261
- const valueText = writeNode(state, level, value, {});
3370
+ const keyRender = writeNode(state, level, key, node, { iskey: true });
3371
+ const keyText = keyRender.text;
3372
+ const valueText = writeNode(state, level, value, node, {}).text;
3262
3373
  const sep = state.flowSkipColonSpace || valueText === "" ? "" : " ";
3263
- pairBuffer += `${keyText}${state.quoteFlowKeys && !explicitPair ? '"' : ""}:${sep}${valueText}`;
3374
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
3375
+ const keyColonSep = key.kind === "alias" || keyIsBareProps ? " " : "";
3376
+ pairBuffer += `${keyText}${keyColonSep}:${sep}${valueText}`;
3264
3377
  result += pairBuffer;
3265
3378
  }
3266
3379
  const pad = state.flowBracketPadding && result !== "" ? " " : "";
3267
3380
  return `{${pad}${result}${pad}}`;
3268
3381
  }
3269
- function sortKeyValue(key) {
3270
- return key.kind === "scalar" ? key.value : key;
3271
- }
3272
- function sortMappingItems(state, items) {
3273
- if (!state.sortKeys) return items;
3274
- const copy = items.slice();
3275
- if (state.sortKeys === true) copy.sort((a, b) => {
3276
- const x = sortKeyValue(a.key);
3277
- const y = sortKeyValue(b.key);
3278
- if (x < y) return -1;
3279
- if (x > y) return 1;
3280
- return 0;
3281
- });
3282
- else {
3283
- const fn = state.sortKeys;
3284
- copy.sort((a, b) => fn(sortKeyValue(a.key), sortKeyValue(b.key)));
3285
- }
3286
- return copy;
3287
- }
3288
3382
  function writeBlockMapping(state, level, node, compact) {
3289
3383
  let result = "";
3290
- const items = sortMappingItems(state, node.items);
3291
- for (let index = 0, length = items.length; index < length; index += 1) {
3384
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
3292
3385
  let pairBuffer = "";
3293
3386
  if (!compact || result !== "") pairBuffer += generateNextLine(state, level);
3294
- const { key, value } = items[index];
3295
- const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && !key.style.flow && key.items.length !== 0 || key.kind === "scalar" && (key.style.literal || key.style.folded);
3296
- const keyText = keyIsBlock ? writeNode(state, level + 1, key, {
3387
+ const { key, value } = node.items[index];
3388
+ const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && key.style === COLLECTION_STYLE.BLOCK && key.items.length !== 0 || key.kind === "scalar" && (key.style === SCALAR_STYLE.LITERAL_BLOCK || key.style === SCALAR_STYLE.FOLDED_BLOCK);
3389
+ const keyRender = keyIsBlock ? writeNode(state, level + 1, key, node, {
3297
3390
  block: true,
3298
3391
  compact: true,
3299
3392
  isblockseq: !cannotBeCompact(state, key, level + 1)
3300
- }) : writeNode(state, level + 1, key, {
3393
+ }) : writeNode(state, level + 1, key, node, {
3301
3394
  block: true,
3302
3395
  compact: true,
3303
3396
  iskey: true
3304
3397
  });
3398
+ const keyText = keyRender.text;
3305
3399
  const keyHasLineBreak = key.kind === "scalar" && key.value.indexOf("\n") !== -1;
3306
- const explicitPair = keyIsBlock || keyHasLineBreak || keyText.length > 1024;
3400
+ const keyIsTooLong = keyText.length > 1024 && /^[\s\S]{1025}/u.test(keyText);
3401
+ const explicitPair = keyIsBlock || keyHasLineBreak || keyIsTooLong;
3307
3402
  if (explicitPair) if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?";
3308
3403
  else pairBuffer += "? ";
3309
3404
  pairBuffer += keyText;
3310
3405
  if (explicitPair) pairBuffer += generateNextLine(state, level);
3311
- const valueText = writeNode(state, level + 1, value, {
3406
+ const valueText = writeNode(state, level + 1, value, node, {
3312
3407
  block: true,
3313
3408
  compact: explicitPair,
3314
3409
  isblockseq: explicitPair && !cannotBeCompact(state, value, level + 1)
3315
- });
3316
- const keyIsBareProps = key.kind === "scalar" && key.value === "" && keyText !== "" && keyText.charCodeAt(keyText.length - 1) !== CHAR_SINGLE_QUOTE && keyText.charCodeAt(keyText.length - 1) !== CHAR_DOUBLE_QUOTE;
3410
+ }).text;
3411
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
3317
3412
  const keyColonSep = !explicitPair && (key.kind === "alias" || keyIsBareProps) ? " " : "";
3318
3413
  if (valueText === "" || CHAR_LINE_FEED === valueText.charCodeAt(0)) pairBuffer += `${keyColonSep}:`;
3319
3414
  else pairBuffer += `${keyColonSep}: `;
@@ -3323,29 +3418,41 @@ function writeBlockMapping(state, level, node, compact) {
3323
3418
  return result;
3324
3419
  }
3325
3420
  function cannotBeCompact(state, node, level) {
3326
- return node.style.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3421
+ if (node.kind === "alias") return true;
3422
+ return node.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3327
3423
  }
3328
- function writeNode(state, level, node, ctx) {
3329
- if (node.kind === "alias") return `*${node.anchor}`;
3424
+ function writeNode(state, level, node, parent, ctx) {
3425
+ if (node.kind === "alias") {
3426
+ state.openEnded = false;
3427
+ return {
3428
+ text: `*${node.anchor}`,
3429
+ noBody: false
3430
+ };
3431
+ }
3330
3432
  const { block = false, iskey = false, isblockseq = false } = ctx;
3331
3433
  let compact = ctx.compact ?? false;
3332
3434
  const hasAnchor = node.anchor !== void 0;
3333
3435
  if (cannotBeCompact(state, node, level)) compact = false;
3334
3436
  let body;
3335
- let shouldPrintTag = node.style.tagged;
3336
- const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && !node.style.flow && node.items.length !== 0;
3437
+ let shouldPrintTag = node.tagged;
3438
+ const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0;
3337
3439
  if (node.kind === "mapping") if (useBlockCollection) body = writeBlockMapping(state, level, node, compact);
3338
3440
  else body = writeFlowMapping(state, level, node);
3339
3441
  else if (node.kind === "sequence") if (useBlockCollection) if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact);
3340
3442
  else body = writeBlockSequence(state, level, node, compact);
3341
3443
  else body = writeFlowSequence(state, level, node);
3342
3444
  else {
3343
- const layout = scalarLayout(state, level);
3344
- const style = resolveScalarStyle(state, node, layout, iskey, block);
3345
- body = renderScalarStyle(node.value, style, layout);
3346
- shouldPrintTag = node.style.tagged || style !== STYLE_PLAIN && node.tag !== state.defaultScalarTagName;
3347
- }
3445
+ const layout = scalarLayout(state, node, parent, level, iskey, !block);
3446
+ detectAllowedStyles(layout);
3447
+ for (const rule of state.scalarStyleRules) rule(layout);
3448
+ body = renderScalar(layout);
3449
+ state.openEnded = (layout.style === SCALAR_STYLE.LITERAL_BLOCK || layout.style === SCALAR_STYLE.FOLDED_BLOCK) && (node.value === "\n" || node.value.endsWith("\n\n"));
3450
+ shouldPrintTag = node.tagged || body === "" && layout.flowOnly && parent?.kind === "sequence" && !hasAnchor || layout.style !== SCALAR_STYLE.PLAIN && node.tag !== state.defaultScalarTagName;
3451
+ }
3452
+ if ((node.kind === "mapping" || node.kind === "sequence") && !useBlockCollection) state.openEnded = false;
3348
3453
  if (useBlockCollection && compact && level > 0 && state.indent > 2) body = `${" ".repeat(state.indent - 2)}${body}`;
3454
+ const noBody = body === "";
3455
+ let text = body;
3349
3456
  if (shouldPrintTag || hasAnchor) {
3350
3457
  const props = [];
3351
3458
  const tag = shouldPrintTag ? nodeTagShort(node) : null;
@@ -3358,19 +3465,15 @@ function writeNode(state, level, node, ctx) {
3358
3465
  if (tag !== null) props.push(tag);
3359
3466
  }
3360
3467
  const sep = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
3361
- body = `${props.join(" ")}${sep}${body}`;
3468
+ text = `${props.join(" ")}${sep}${body}`;
3362
3469
  }
3363
- return body;
3470
+ return {
3471
+ text,
3472
+ noBody
3473
+ };
3364
3474
  }
3365
3475
  function rootStartsOwnLine(node) {
3366
- return (node.kind === "sequence" || node.kind === "mapping") && !node.style.flow && node.items.length !== 0 && !node.style.tagged && node.anchor === void 0;
3367
- }
3368
- function isOpenEnded(node) {
3369
- let leaf = node;
3370
- while ((leaf.kind === "sequence" || leaf.kind === "mapping") && !leaf.style.flow && leaf.items.length !== 0) leaf = leaf.kind === "sequence" ? leaf.items[leaf.items.length - 1] : leaf.items[leaf.items.length - 1].value;
3371
- if (leaf.kind !== "scalar" || !(leaf.style.literal || leaf.style.folded)) return false;
3372
- const { value } = leaf;
3373
- return value.endsWith("\n\n") || value === "\n";
3476
+ return (node.kind === "sequence" || node.kind === "mapping") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0 && !node.tagged && node.anchor === void 0;
3374
3477
  }
3375
3478
  function writeDocumentDirectives(doc) {
3376
3479
  let result = "";
@@ -3392,6 +3495,7 @@ function present(documents, options) {
3392
3495
  let previousEnded = false;
3393
3496
  for (let index = 0; index < documents.length; index += 1) {
3394
3497
  const doc = documents[index];
3498
+ state.openEnded = false;
3395
3499
  const directives = writeDocumentDirectives(doc);
3396
3500
  const hasDirectives = directives !== "";
3397
3501
  const marker = doc.explicitStart || hasDirectives || index > 0 && !previousEnded;
@@ -3399,18 +3503,18 @@ function present(documents, options) {
3399
3503
  if (doc.contents === null) {
3400
3504
  if (marker) result += "---\n";
3401
3505
  } else if (marker) {
3402
- const body = writeNode(state, 0, doc.contents, {
3506
+ const body = writeNode(state, 0, doc.contents, null, {
3403
3507
  block: true,
3404
3508
  compact: true
3405
- });
3509
+ }).text;
3406
3510
  const sep = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
3407
3511
  result += `---${sep}${body}
3408
3512
  `;
3409
- } else result += writeNode(state, 0, doc.contents, {
3513
+ } else result += writeNode(state, 0, doc.contents, null, {
3410
3514
  block: true,
3411
3515
  compact: true
3412
- }) + "\n";
3413
- previousEnded = doc.explicitEnd || doc.contents !== null && isOpenEnded(doc.contents);
3516
+ }).text + "\n";
3517
+ previousEnded = doc.explicitEnd || state.openEnded;
3414
3518
  if (previousEnded) result += "...\n";
3415
3519
  }
3416
3520
  return result;
@@ -3421,9 +3525,17 @@ var DEFAULT_DUMP_OPTIONS = {
3421
3525
  skipInvalid: false,
3422
3526
  noRefs: false,
3423
3527
  flowLevel: -1,
3528
+ sortKeys: false,
3424
3529
  transform: () => {
3425
3530
  }
3426
3531
  };
3532
+ function defaultCompareFn(a, b) {
3533
+ const x = String(a);
3534
+ const y = String(b);
3535
+ if (x < y) return -1;
3536
+ if (x > y) return 1;
3537
+ return 0;
3538
+ }
3427
3539
  function dump(input, options = {}) {
3428
3540
  const opts = {
3429
3541
  ...DEFAULT_DUMP_OPTIONS,
@@ -3435,9 +3547,16 @@ function dump(input, options = {}) {
3435
3547
  });
3436
3548
  if (opts.flowLevel >= 0) visit(documents, (node, ctx) => {
3437
3549
  if (ctx.depth < opts.flowLevel) return;
3438
- node.style.flow = true;
3550
+ if (node.kind === "sequence" || node.kind === "mapping") node.style = COLLECTION_STYLE.FLOW;
3439
3551
  return VISIT_SKIP;
3440
3552
  });
3553
+ if (opts.sortKeys) {
3554
+ const compareFn = opts.sortKeys === true ? defaultCompareFn : opts.sortKeys;
3555
+ visit(documents, (node) => {
3556
+ if (node.kind !== "mapping") return;
3557
+ node.items.sort((a, b) => compareFn(a.key.kind === "scalar" ? a.key.value : "", b.key.kind === "scalar" ? b.key.value : ""));
3558
+ });
3559
+ }
3441
3560
  opts.transform(documents);
3442
3561
  return present(documents, {
3443
3562
  ...pick(opts, Object.keys(DEFAULT_PRESENTER_OPTIONS)),
@@ -3461,10 +3580,73 @@ var CHOMPING_CLIP = CHOMPING_MODE.CLIP;
3461
3580
  var CHOMPING_STRIP = CHOMPING_MODE.STRIP;
3462
3581
  var CHOMPING_KEEP = CHOMPING_MODE.KEEP;
3463
3582
 
3583
+ // src/config-graph.ts
3584
+ var CONFIG_GRAPH_MAX_EXPANDED_NODES = 1e5;
3585
+ var CONFIG_GRAPH_MAX_DEPTH = 200;
3586
+ var SCALAR_NODE = { cost: 1, height: 0 };
3587
+ function cycleError(source) {
3588
+ return new CliError(`${source}\u5305\u542B\u5FAA\u73AF\u5F15\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u5904\u7406\u914D\u7F6E\u56FE`, {
3589
+ label: "\u914D\u7F6E\u9519\u8BEF",
3590
+ hint: ["\u68C0\u67E5 YAML \u522B\u540D\u662F\u5426\u5F15\u7528\u4E86\u81EA\u8EAB\u6216\u7956\u5148\uFF1B\u82E5\u7531\u8986\u5199\u811A\u672C\u4EA7\u751F\uFF0C\u8BF7\u79FB\u9664\u5199\u56DE\u7956\u5148\u5BF9\u8C61\u7684\u5F15\u7528\u3002"]
3591
+ });
3592
+ }
3593
+ function depthError(source) {
3594
+ return new CliError(`${source}\u7684\u5D4C\u5957\u6DF1\u5EA6\u8D85\u8FC7 ${CONFIG_GRAPH_MAX_DEPTH} \u5C42\uFF0C\u65E0\u6CD5\u5B89\u5168\u9012\u5F52\u5904\u7406`, {
3595
+ label: "\u914D\u7F6E\u9519\u8BEF",
3596
+ hint: ["\u8BF7\u7F29\u51CF\u914D\u7F6E\u5D4C\u5957\uFF1BYAML \u522B\u540D\u4E0E\u8986\u5199\u811A\u672C\u90FD\u4E0D\u80FD\u751F\u6210\u8FC7\u6DF1\u7684\u914D\u7F6E\u56FE\u3002"]
3597
+ });
3598
+ }
3599
+ function budgetError(source) {
3600
+ return new CliError(`${source}\u5C55\u5F00\u540E\u7684\u8282\u70B9\u6570\u8D85\u8FC7 ${CONFIG_GRAPH_MAX_EXPANDED_NODES}\uFF0C\u5DF2\u62D2\u7EDD\u5904\u7406\u4EE5\u907F\u514D\u8D44\u6E90\u8017\u5C3D`, {
3601
+ label: "\u914D\u7F6E\u9519\u8BEF",
3602
+ hint: ["\u51CF\u5C11\u5171\u4EAB YAML \u522B\u540D\u6216\u8986\u5199\u811A\u672C\u4EA7\u751F\u7684\u91CD\u590D\u5F15\u7528\uFF1B\u914D\u7F6E\u5C55\u793A\u4E0E JSON \u5E8F\u5217\u5316\u9700\u8981\u5C55\u5F00\u8FD9\u4E9B\u5F15\u7528\u3002"]
3603
+ });
3604
+ }
3605
+ function addCost(left, right, source, checkExpansionBudget) {
3606
+ const total = left + right;
3607
+ if (checkExpansionBudget && total > CONFIG_GRAPH_MAX_EXPANDED_NODES) throw budgetError(source);
3608
+ return total;
3609
+ }
3610
+ function assertConfigGraphSafe(root, source = "\u914D\u7F6E") {
3611
+ assertConfigGraph(root, source, false);
3612
+ }
3613
+ function assertConfigGraphExpansionSafe(root, source = "\u914D\u7F6E") {
3614
+ assertConfigGraph(root, source, true);
3615
+ }
3616
+ function assertConfigGraph(root, source, checkExpansionBudget) {
3617
+ const active = /* @__PURE__ */ new WeakSet();
3618
+ const completed = /* @__PURE__ */ new WeakMap();
3619
+ const visit2 = (value, depth) => {
3620
+ if (depth > CONFIG_GRAPH_MAX_DEPTH) throw depthError(source);
3621
+ if (value === null || typeof value !== "object") return SCALAR_NODE;
3622
+ if (active.has(value)) throw cycleError(source);
3623
+ const cached = completed.get(value);
3624
+ if (cached !== void 0) {
3625
+ if (depth + cached.height > CONFIG_GRAPH_MAX_DEPTH) throw depthError(source);
3626
+ return cached;
3627
+ }
3628
+ active.add(value);
3629
+ const children = Array.isArray(value) ? value : Object.values(value);
3630
+ let cost = 1;
3631
+ let height = 0;
3632
+ for (const child of children) {
3633
+ const childResult = visit2(child, depth + 1);
3634
+ cost = addCost(cost, childResult.cost, source, checkExpansionBudget);
3635
+ height = Math.max(height, childResult.height + 1);
3636
+ }
3637
+ active.delete(value);
3638
+ const result = { cost, height };
3639
+ completed.set(value, result);
3640
+ return result;
3641
+ };
3642
+ visit2(root, 0);
3643
+ }
3644
+
3464
3645
  // src/overwrite.ts
3465
3646
  import fs3 from "fs";
3466
3647
  import { createRequire as createRequire2 } from "module";
3467
3648
  import path3 from "path";
3649
+ import { isDeepStrictEqual } from "util";
3468
3650
 
3469
3651
  // src/paths.ts
3470
3652
  import fs from "fs";
@@ -3524,9 +3706,11 @@ var PATHS = {
3524
3706
  * 各锁的可达竞态路径:
3525
3707
  * - serviceLock:慢速 start(订阅更新约 10s)持锁期间另一终端 stop
3526
3708
  * - subscriptionCacheLock:慢速 `sub update`(并行下载、逐条回写缓存)期间另一终端 `reset`
3709
+ * - subscriptionCommitLock:同一订阅的 YAML 与缓存提交、缓存失败回滚必须作为一个串行区间
3527
3710
  */
3528
3711
  settingsLock: path.join(USER_DATA_DIR, "settings.lock"),
3529
3712
  subscriptionCacheLock: path.join(USER_DATA_DIR, "subscription-cache.lock"),
3713
+ subscriptionCommitLock: path.join(USER_DATA_DIR, "subscription-commit.lock"),
3530
3714
  serviceLock: path.join(USER_DATA_DIR, "service.lock"),
3531
3715
  /**
3532
3716
  * 「服务被要求停止」的单调计数(`stop-epoch.ts` 的 `bumpStopEpoch`/`readStopEpoch`,
@@ -3590,6 +3774,10 @@ function rmrf(dir) {
3590
3774
  }
3591
3775
  function cleanupStaleTmpFiles() {
3592
3776
  const cutoff = Date.now() - 60 * 60 * 1e3;
3777
+ const isCliMkdtempEntry = (entry, prefix) => {
3778
+ const suffix = entry.startsWith(prefix) ? entry.slice(prefix.length) : "";
3779
+ return /^[A-Za-z0-9]{6}$/.test(suffix) && /[A-Z0-9]/.test(suffix);
3780
+ };
3593
3781
  for (const dir of [USER_DATA_DIR, DIRS.subscriptions, DIRS.runtime, DIRS.kernel]) {
3594
3782
  let entries;
3595
3783
  try {
@@ -3598,14 +3786,17 @@ function cleanupStaleTmpFiles() {
3598
3786
  continue;
3599
3787
  }
3600
3788
  for (const entry of entries) {
3601
- const isAtomicTmpFile = entry.endsWith(".tmp");
3602
- const isKernelTmpDir = dir === DIRS.kernel && entry.startsWith(".tmp-");
3603
- const isConfigCheckTmpDir = dir === USER_DATA_DIR && entry.startsWith("check-");
3789
+ const isAtomicTmpFile = /^.+\.\d+\.\d+\.tmp$/.test(entry);
3790
+ const isKernelTmpDir = dir === DIRS.kernel && isCliMkdtempEntry(entry, ".tmp-");
3791
+ const isConfigCheckTmpDir = dir === USER_DATA_DIR && isCliMkdtempEntry(entry, "check-");
3604
3792
  const isPlistStage = dir === USER_DATA_DIR && entry === "service.plist.stage";
3605
3793
  if (!isAtomicTmpFile && !isKernelTmpDir && !isConfigCheckTmpDir && !isPlistStage) continue;
3606
3794
  const full = path.join(dir, entry);
3607
3795
  try {
3608
- if (fs.statSync(full).mtimeMs >= cutoff) continue;
3796
+ const stat = fs.lstatSync(full);
3797
+ if ((isAtomicTmpFile || isPlistStage) && !stat.isFile()) continue;
3798
+ if ((isKernelTmpDir || isConfigCheckTmpDir) && !stat.isDirectory()) continue;
3799
+ if (stat.mtimeMs >= cutoff) continue;
3609
3800
  fs.rmSync(full, { recursive: true, force: true });
3610
3801
  } catch {
3611
3802
  }
@@ -3857,8 +4048,12 @@ function addSubscription(url, name) {
3857
4048
  validateSubscriptionName(name);
3858
4049
  updateSettings((settings) => {
3859
4050
  const subs = getSubscriptions(settings);
3860
- if (subs.some((s) => s.name === name)) {
3861
- throw new CliError(`\u8BA2\u9605 "${name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo-cli sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo-cli sub remove ${name}\uFF09`);
4051
+ const normalizedName = name.toLowerCase();
4052
+ const existing = subs.find((s) => s.name.toLowerCase() === normalizedName);
4053
+ if (existing) {
4054
+ throw new CliError(
4055
+ `\u8BA2\u9605\u540D\u79F0 "${name}" \u4E0E\u73B0\u6709\u8BA2\u9605 "${existing.name}" \u51B2\u7A81\uFF08\u540D\u79F0\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo-cli sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo-cli sub remove ${existing.name}\uFF09`
4056
+ );
3862
4057
  }
3863
4058
  subs.push({ name, url });
3864
4059
  const updates = { subscriptions: subs };
@@ -4030,16 +4225,10 @@ function lockedKeysReferencedBy(rawKeys) {
4030
4225
  return [...hit];
4031
4226
  }
4032
4227
  function assertValidParsedKey(rawKey, parsed) {
4033
- if (rawKey.startsWith("~") || parsed.key.includes("~")) {
4034
- throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684 ~ \u64CD\u4F5C\u7B26`, {
4228
+ if (/[~<>]/.test(rawKey)) {
4229
+ throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684\u64CD\u4F5C\u7B26\uFF08~ / ~? / <key>\uFF09`, {
4035
4230
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4036
- hint: ["\u6309 name \u5408\u5E76/\u8FFD\u52A0\u6570\u7EC4\u5143\u7D20\u7684 ~ \u4E0E ~? \u5DF2\u79FB\u9664\uFF0C\u6539\u7528 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\u7684\u811A\u672C\u4E00\u8282\uFF09\u3002"]
4037
- });
4038
- }
4039
- if (rawKey.includes("<") || rawKey.includes(">")) {
4040
- throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684\u5C16\u62EC\u53F7\u8F6C\u4E49`, {
4041
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4042
- hint: ["<key> \u8F6C\u4E49\u5DF2\u968F ~ \u64CD\u4F5C\u7B26\u79FB\u9664\u2014\u2014mihomo-cli \u9876\u5C42\u952E\u4E0D\u542B\u5C16\u62EC\u53F7\uFF0C\u76F4\u63A5\u5199\u952E\u540D\u5373\u53EF\u3002"]
4231
+ hint: ["\u6309 name \u5408\u5E76\u6570\u7EC4\u5143\u7D20\u6539\u7528 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\uFF09\uFF1B<key> \u8F6C\u4E49\u4E0D\u518D\u9700\u8981\uFF0C\u76F4\u63A5\u5199\u952E\u540D\u3002"]
4043
4232
  });
4044
4233
  }
4045
4234
  if (parsed.key === "") {
@@ -4192,12 +4381,6 @@ function normalizeMatch(raw, fileName) {
4192
4381
  throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u5FC5\u987B\u662F\u5BF9\u8C61\uFF08name / url-domain\uFF09`, { label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF" });
4193
4382
  }
4194
4383
  const rawEntries = raw;
4195
- if ("subscription" in rawEntries) {
4196
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u7528\u4E86 subscription \u952E`, {
4197
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4198
- hint: ["subscription \u952E\u5DF2\u6536\u6389\uFF08\u4E0E name \u540C\u4E49\u4F46\u4E24\u5957\u5199\u6CD5\uFF09\uFF0C\u8BF7\u6539\u5199 name\uFF0C\u5339\u914D\u8BED\u4E49\u4E0D\u53D8:", " match:", " name: edu*"]
4199
- });
4200
- }
4201
4384
  const result = {};
4202
4385
  const problems = [];
4203
4386
  for (const [key, value] of Object.entries(rawEntries)) {
@@ -4228,16 +4411,6 @@ function normalizeMatch(raw, fileName) {
4228
4411
  ]
4229
4412
  });
4230
4413
  }
4231
- const impossible = arr.find((v) => !v.includes("*") && !SAFE_NAME_RE.test(v));
4232
- if (impossible !== void 0) {
4233
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 name \u503C\u4E0D\u53EF\u80FD\u5339\u914D\u4EFB\u4F55\u8BA2\u9605: "${impossible}"`, {
4234
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4235
- hint: [
4236
- "\u8BA2\u9605\u540D\u53EA\u80FD\u542B\u5B57\u6BCD\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u8FDE\u5B57\u7B26\u4E0E\u4E2D\u6587\uFF081-64 \u5B57\u7B26\uFF09\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u8BEF\u5E26\u4E86 /\u3001~\u3001\u7A7A\u683C\u3001\u70B9\u53F7\u7B49\u5B57\u7B26\u3002",
4237
- "\u66F4\u590D\u6742\u7684\u5339\u914D\u5199 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\uFF09\u3002"
4238
- ]
4239
- });
4240
- }
4241
4414
  }
4242
4415
  result[key] = arr;
4243
4416
  }
@@ -4267,14 +4440,8 @@ function isValidNamePattern(value) {
4267
4440
  return star === 0 || star === value.length - 1;
4268
4441
  }
4269
4442
  function urlDomainValueProblem(value) {
4270
- if (value.includes("*") || value.includes("?")) {
4271
- return `url-domain \u4E0D\u652F\u6301\u901A\u914D\u7B26\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF0C\u53EA\u505A\u5B57\u9762\u540E\u7F00\u6BD4\u5BF9`;
4272
- }
4273
- if (/[:/]/.test(value)) {
4274
- return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF1A\u4E0D\u8981\u5E26\u534F\u8BAE\u3001\u8DEF\u5F84\u6216\u7AEF\u53E3\uFF0C\u8BF7\u53BB\u6389 https://\u3001\u5C3E\u659C\u6760\u4E0E\u7AEF\u53E3`;
4275
- }
4276
- if (/\s/.test(value)) {
4277
- return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF1A\u503C\u4E2D\u4E0D\u80FD\u542B\u7A7A\u683C`;
4443
+ if (/[*?:/\s]/.test(value)) {
4444
+ return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\u3001\u4E0D\u652F\u6301\u901A\u914D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF0C\u53BB\u6389 https://\u3001\u8DEF\u5F84\u3001\u7AEF\u53E3\u3001* \u4E0E\u7A7A\u683C`;
4278
4445
  }
4279
4446
  return void 0;
4280
4447
  }
@@ -4330,24 +4497,11 @@ function selectActiveOverwriteFiles(files, scope) {
4330
4497
  var METADATA_KEYS = /* @__PURE__ */ new Set(["match", "enabled"]);
4331
4498
  function assertNoMetadataKeyLookalikes(config, fileName) {
4332
4499
  for (const rawKey of Object.keys(config)) {
4333
- const parsed = parseOverrideKey(rawKey).key;
4334
- if (parsed !== rawKey && METADATA_KEYS.has(parsed)) {
4335
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684\u5143\u6570\u636E\u952E "${rawKey}" \u4E0D\u652F\u6301\u64CD\u4F5C\u7B26`, {
4336
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4337
- hint: [
4338
- `match \u4E0E enabled \u662F\u672C CLI \u7684\u5143\u6570\u636E\u952E\uFF0C\u5728\u5408\u5E76\u524D\u5C31\u88AB\u5265\u79BB\uFF0C\u5E26\u64CD\u4F5C\u7B26\u5199\u6CD5\uFF08\u5982 ${rawKey}\uFF09\u4E0D\u4F1A\u751F\u6548\uFF0C\u53CD\u800C\u4F1A\u628A ${parsed} \u5F53\u666E\u901A\u914D\u7F6E\u952E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\u3002`,
4339
- `\u8BF7\u76F4\u63A5\u5199 ${parsed}: <\u503C>\u3002`
4340
- ]
4341
- });
4342
- }
4343
- const normalized = rawKey.trim().toLowerCase();
4500
+ const normalized = parseOverrideKey(rawKey.trim().toLowerCase()).key;
4344
4501
  if (normalized !== rawKey && METADATA_KEYS.has(normalized)) {
4345
4502
  throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 "${rawKey}" \u7591\u4F3C\u60F3\u5199\u5143\u6570\u636E\u952E ${normalized}`, {
4346
4503
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4347
- hint: [
4348
- `YAML \u952E\u533A\u5206\u5927\u5C0F\u5199\u4E0E\u7A7A\u767D\uFF0C"${rawKey}" \u4E0D\u4F1A\u88AB\u8BC6\u522B\u4E3A ${normalized}\u2014\u2014\u6587\u4EF6\u4E0D\u4F1A\u88AB\u505C\u7528/\u9650\u5B9A\u4F5C\u7528\u57DF\uFF0C\u8BE5\u952E\u53CD\u800C\u4F1A\u5F53\u666E\u901A\u914D\u7F6E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\uFF08\u5185\u6838\u5BF9\u672A\u77E5\u9876\u5C42\u952E\u4E0D\u62A5\u9519\uFF0C\u4E0D\u4F1A\u6709\u4EFB\u4F55\u63D0\u793A\uFF09\u3002`,
4349
- `\u8BF7\u5199\u6210 ${normalized}: <\u503C>\u3002`
4350
- ]
4504
+ hint: [`\u5143\u6570\u636E\u952E\u53EA\u8BA4\u7CBE\u786E\u5199\u6CD5\uFF08\u533A\u5206\u5927\u5C0F\u5199\u3001\u4E0D\u5E26\u64CD\u4F5C\u7B26\uFF09\uFF0C"${rawKey}" \u4E0D\u4F1A\u751F\u6548\uFF0C\u53CD\u800C\u4F1A\u5F53\u666E\u901A\u952E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\u3002`, `\u8BF7\u5199\u6210 ${normalized}: <\u503C>\u3002`]
4351
4505
  });
4352
4506
  }
4353
4507
  }
@@ -4409,7 +4563,7 @@ function loadOverwriteScript(filePath, fileName) {
4409
4563
  throw new CliError(`\u8986\u5199\u811A\u672C "${fileName}" \u7F3A\u5C11\u53D8\u6362\u51FD\u6570`, {
4410
4564
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4411
4565
  hint: [
4412
- "\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF1Breturn true \u8868\u793A\u547D\u4E2D\u5F53\u524D\u8BA2\u9605\uFF0C\u5176\u4F59\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
4566
+ "\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF0C\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
4413
4567
  " export default function (config, ctx) { ... }",
4414
4568
  "CommonJS \u5199\u6CD5 module.exports = function (config, ctx) { ... } \u540C\u6837\u8BA4\u3002"
4415
4569
  ]
@@ -4438,6 +4592,7 @@ function readOverwriteFiles() {
4438
4592
  const content = fs3.readFileSync(filePath, "utf8");
4439
4593
  if (isBlankYamlDocument(content)) continue;
4440
4594
  const parsed = load(content, { maxAliases: YAML_MAX_ALIASES });
4595
+ assertConfigGraphSafe(parsed, `\u8986\u5199\u6587\u4EF6 "${file}"`);
4441
4596
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4442
4597
  const { match, enabled, ...config } = parsed;
4443
4598
  assertNoMetadataKeyLookalikes(config, file);
@@ -4480,30 +4635,31 @@ function snapshotLockedKeys(config) {
4480
4635
  for (const k of EFFECTIVELY_LOCKED_KEYS) {
4481
4636
  if (k in config) snap[k] = config[k];
4482
4637
  }
4483
- return snap;
4638
+ return structuredClone(snap);
4484
4639
  }
4485
4640
  function diffLockedKeys(before, after) {
4486
4641
  return EFFECTIVELY_LOCKED_KEYS.filter((k) => {
4487
4642
  const had = k in before;
4488
4643
  const has = k in after;
4489
- return had !== has ? has : had && before[k] !== after[k];
4644
+ return had !== has ? has : had && !isDeepStrictEqual(before[k], after[k]);
4490
4645
  });
4491
4646
  }
4492
4647
  function applyOverwrite(baseConfig, files, opts) {
4493
4648
  let result = { ...baseConfig };
4494
4649
  const scriptWarnings = [];
4495
4650
  const scriptLockedHits = [];
4496
- const scriptMatches = [];
4497
4651
  const host = hostFromSubUrl(opts.scope?.subUrl) ?? "";
4498
4652
  const subscription = { name: opts.scope?.subName ?? "", url: opts.scope?.subUrl ?? "", host };
4499
4653
  for (const file of files) {
4500
4654
  if (file.transform) {
4501
- const before = snapshotLockedKeys(result);
4502
4655
  const notes = [];
4503
4656
  const ctx = { subscription, mode: opts.mode, warn: (message) => notes.push(message) };
4657
+ let before;
4504
4658
  let returned;
4505
4659
  try {
4660
+ before = snapshotLockedKeys(result);
4506
4661
  returned = file.transform(result, ctx);
4662
+ assertConfigGraphSafe(result);
4507
4663
  } catch (e) {
4508
4664
  throw new CliError(`\u8986\u5199\u811A\u672C "${file.name}" \u6267\u884C\u5931\u8D25: ${firstLine(e.message ?? String(e))}`, {
4509
4665
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
@@ -4517,14 +4673,13 @@ function applyOverwrite(baseConfig, files, opts) {
4517
4673
  });
4518
4674
  }
4519
4675
  scriptWarnings.push(...notes.map((message) => `${message}\uFF08\u811A\u672C ${file.name}\uFF09`));
4520
- scriptMatches.push({ file: file.name, matched: returned === true });
4521
4676
  const keys = diffLockedKeys(before, result);
4522
4677
  if (keys.length > 0) scriptLockedHits.push({ file: file.name, keys });
4523
4678
  continue;
4524
4679
  }
4525
4680
  result = mergeConfigLevel(result, file.config ?? {}, true);
4526
4681
  }
4527
- return { config: result, scriptWarnings, scriptLockedHits, scriptMatches };
4682
+ return { config: result, scriptWarnings, scriptLockedHits };
4528
4683
  }
4529
4684
  function listOverwriteFile(scope) {
4530
4685
  const { ok, broken } = readOverwriteFiles();
@@ -4532,23 +4687,21 @@ function listOverwriteFile(scope) {
4532
4687
  return {
4533
4688
  enabled,
4534
4689
  dir: USER_DATA_DIR,
4535
- entries: ok,
4536
4690
  files: ok.map((f) => ({
4537
4691
  name: f.name,
4538
4692
  kind: f.transform ? "script" : "yaml",
4539
4693
  keys: f.transform ? [] : Object.keys(f.config || {}),
4540
4694
  scope: summarizeMatch(f.match),
4541
4695
  enabled: f.enabled !== false,
4542
- ...scope ? { matched: matchesScope(f.match, scope) } : {}
4696
+ ...scope && !f.transform ? { matched: matchesScope(f.match, scope) } : {}
4543
4697
  })),
4544
4698
  broken
4545
4699
  };
4546
4700
  }
4547
4701
 
4548
4702
  // src/config.ts
4549
- var SAFE_YAML_LOAD_OPTIONS = { maxAliases: YAML_MAX_ALIASES };
4550
4703
  function loadYamlSafe(content) {
4551
- return load(content, SAFE_YAML_LOAD_OPTIONS);
4704
+ return load(content, { maxAliases: YAML_MAX_ALIASES });
4552
4705
  }
4553
4706
  function parseConfigContent(content, errorMsg) {
4554
4707
  const label = errorMsg || "\u5185\u5BB9";
@@ -4564,6 +4717,7 @@ function parseConfigContent(content, errorMsg) {
4564
4717
  if (result == null || typeof result !== "object" || Array.isArray(result)) {
4565
4718
  throw new CliError(`${label}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61\uFF08\u9876\u5C42\u9700\u4E3A\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(result) ? "\u5217\u8868" : typeof result}\uFF09`, { label: "\u914D\u7F6E\u9519\u8BEF" });
4566
4719
  }
4720
+ assertConfigGraphSafe(result, label);
4567
4721
  return result;
4568
4722
  }
4569
4723
  function dumpYaml(obj) {
@@ -4710,26 +4864,13 @@ function buildConfig(subRawContent, mode, scope) {
4710
4864
  "skip-domain": ["+.push.apple.com"]
4711
4865
  };
4712
4866
  }
4867
+ if (overwriteFiles.some((file) => !file.transform)) assertConfigGraphSafe(merged, "\u5408\u5E76\u540E\u7684\u914D\u7F6E");
4713
4868
  assertConfigShape(merged);
4714
4869
  return { config: merged, warnings: lockedWarnings, overwriteSummaries };
4715
4870
  }
4716
4871
  function renderLockedWarning(source, keys) {
4717
4872
  return `${source}\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${keys.join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u3001\u63A7\u5236\u5668\u8BC1\u4E66\u4E0E\u5C40\u57DF\u7F51/\u5165\u7AD9\u9274\u6743\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF0C\u5165\u7AD9\u56FA\u5B9A\u53EA\u76D1\u542C\u56DE\u73AF\uFF0C\u9700\u8981\u5C40\u57DF\u7F51\u5165\u7AD9\u8BF7\u5728\u672C\u673A\u53E6\u8D77\u4E00\u4E2A mihomo-cli \u5B9E\u4F8B\uFF09`;
4718
4873
  }
4719
- function judgeScriptMatches(subRawContent, mode, scope, entries) {
4720
- try {
4721
- const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
4722
- const settings = readSettings();
4723
- const active = settings.overwrite_enabled !== false ? selectActiveOverwriteFiles(entries, scope) : [];
4724
- const { scriptMatches } = applyOverwrite(subscriptionConfig, active, {
4725
- mode,
4726
- scope
4727
- });
4728
- return { matches: scriptMatches };
4729
- } catch {
4730
- return { matches: [] };
4731
- }
4732
- }
4733
4874
  function deriveRuntimeMode(info) {
4734
4875
  return info?.tun ? "tun" : "mixed";
4735
4876
  }
@@ -4756,7 +4897,7 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
4756
4897
  }
4757
4898
  const hint = ["", ...detail.split("\n").map((line) => line.trim() ? `${HINT_INDENT}${line}` : "")];
4758
4899
  if (overwriteSummaries.length > 0) {
4759
- hint.push("", `${HINT_INDENT}\u5F53\u524D\u751F\u6548\u7684\u8986\u5199\u6587\u4EF6:`);
4900
+ hint.push("", `${HINT_INDENT}\u672C\u6B21\u53C2\u4E0E\u6784\u5EFA\u7684\u8986\u5199\u6587\u4EF6:`);
4760
4901
  for (const summary of overwriteSummaries) hint.push(sanitizeTerminal(`${HINT_INDENT.repeat(2)}${summary}`));
4761
4902
  hint.push(`${HINT_INDENT}\u82E5\u62A5\u9519\u7684\u5143\u7D20\u6765\u81EA\u8986\u5199\uFF08YAML \u8FFD\u52A0\u6216 JS \u811A\u672C\u6CE8\u5165\uFF09\uFF0C\u68C0\u67E5\u5BF9\u5E94\u7684\u8986\u5199\u6587\u4EF6\u4E0E\u811A\u672C\u3002`);
4762
4903
  }
@@ -4792,9 +4933,15 @@ ${error.stderr || ""}`).trim();
4792
4933
  hint: buildKernelRejectHint("", [], { timedOut: true })
4793
4934
  });
4794
4935
  }
4936
+ if (typeof error.code !== "number") {
4937
+ const reason = detail || sanitizeTerminal(error.message);
4938
+ const hint = ["", ...reason.split("\n").map((line) => line.trim() ? `${HINT_INDENT}${line}` : "")];
4939
+ hint.push("", `${HINT_INDENT}\u8BF7\u68C0\u67E5\u5185\u6838\u6587\u4EF6\u662F\u5426\u53EF\u6267\u884C\uFF08\u6743\u9650\u4E0E\u7CFB\u7EDF\u67B6\u6784\uFF09\uFF0C\u6216\u8FD0\u884C mihomo-cli kernel \u91CD\u65B0\u5B89\u88C5\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`);
4940
+ throw new CliError("\u5185\u6838\u672A\u6267\u884C\u6216\u5F02\u5E38\u7EC8\u6B62\uFF0C\u914D\u7F6E\u6821\u9A8C\u672A\u5B8C\u6210", { label: "\u5185\u6838\u9519\u8BEF", hint });
4941
+ }
4795
4942
  throw new CliError("\u5185\u6838\u62D2\u7EDD\u52A0\u8F7D\u914D\u7F6E", {
4796
4943
  label: "\u914D\u7F6E\u9519\u8BEF",
4797
- hint: buildKernelRejectHint(detail || error.message, overwriteSummaries)
4944
+ hint: buildKernelRejectHint(detail || sanitizeTerminal(error.message), overwriteSummaries)
4798
4945
  });
4799
4946
  }
4800
4947
  } finally {
@@ -5055,15 +5202,19 @@ function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5055
5202
  }
5056
5203
  var UNLOADED_POLL_ATTEMPTS = 25;
5057
5204
  var UNLOADED_POLL_INTERVAL_MS = 200;
5058
- async function waitUntilUnloaded(target = serviceTarget()) {
5205
+ async function waitUntilUnloaded(target = serviceTarget(), options = {}) {
5059
5206
  for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
5060
5207
  const result = runLaunchctl(["print", target]);
5061
- if (result.status === LAUNCHCTL_NOT_LOADED) return;
5208
+ if (result.status === LAUNCHCTL_NOT_LOADED) return "unloaded";
5062
5209
  if (result.status !== 0) {
5063
5210
  throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5064
5211
  hint: ["\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u4ECD\u88C5\u8F7D\uFF0C\u53EA\u8868\u793A\u67E5\u8BE2\u6CA1\u6210\u7ACB\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
5065
5212
  });
5066
5213
  }
5214
+ if (options.acceptReplacement) {
5215
+ const { state, pid } = parseServicePrint(result.stdout);
5216
+ if (state === "running" && pid !== null && options.acceptReplacement(pid)) return "replacement-running";
5217
+ }
5067
5218
  await sleep(UNLOADED_POLL_INTERVAL_MS);
5068
5219
  }
5069
5220
  throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
@@ -5257,6 +5408,7 @@ function walk(node, withinProvider, state) {
5257
5408
  return node;
5258
5409
  }
5259
5410
  function redactConfigSecrets(config) {
5411
+ assertConfigGraphExpansionSafe(config);
5260
5412
  const state = { changed: false };
5261
5413
  return { config: walk(config, false, state), changed: state.changed };
5262
5414
  }
@@ -5324,8 +5476,7 @@ function createHttpClient(options = {}) {
5324
5476
  throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
5325
5477
  }
5326
5478
  const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
5327
- const data = config?.responseType === "json" ? JSON.parse(text) : text;
5328
- return { data, headers: response.headers };
5479
+ return { data: text, headers: response.headers };
5329
5480
  } catch (e) {
5330
5481
  if (controller.signal.aborted && e.name === "AbortError") {
5331
5482
  throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
@@ -5500,6 +5651,15 @@ function resolveSubscription(subs, pattern) {
5500
5651
  includes.push(s);
5501
5652
  }
5502
5653
  }
5654
+ if (exact.length > 1) {
5655
+ throw new CliError(`\u8BA2\u9605\u540D\u79F0 "${pattern}" \u6709\u591A\u4E2A\u7CBE\u786E\u5339\u914D\uFF08\u540D\u79F0\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09`, {
5656
+ hint: [
5657
+ "\u8BF7\u624B\u5DE5\u7F16\u8F91 settings.json\uFF0C\u5220\u9664\u591A\u4F59\u6761\u76EE\uFF0C\u6216\u5C06\u540D\u79F0\u4E0E\u5BF9\u5E94 YAML \u6587\u4EF6\u4E00\u8D77\u6539\u540D\uFF0C\u786E\u4FDD\u5FFD\u7565\u5927\u5C0F\u5199\u540E\u4ECD\u552F\u4E00",
5658
+ "\u51B2\u7A81\u7684\u8BA2\u9605:",
5659
+ ...exact.map((s) => ` ${s.name}`)
5660
+ ]
5661
+ });
5662
+ }
5503
5663
  const matched = exact.length > 0 ? exact : prefix.length > 0 ? prefix : includes;
5504
5664
  if (matched.length === 0) {
5505
5665
  throw new CliError(`\u672A\u627E\u5230\u5339\u914D "${pattern}" \u7684\u8BA2\u9605`);
@@ -5531,7 +5691,7 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
5531
5691
  async function downloadSubscription(url, subName, signal) {
5532
5692
  let response;
5533
5693
  try {
5534
- response = await HTTP_CLIENT.get(url, { responseType: "text", signal });
5694
+ response = await HTTP_CLIENT.get(url, { signal });
5535
5695
  } catch (e) {
5536
5696
  const maskedUrl = maskUrl(url);
5537
5697
  let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
@@ -5549,22 +5709,33 @@ async function downloadSubscription(url, subName, signal) {
5549
5709
  }
5550
5710
  const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
5551
5711
  assertLooksLikeSubscription(parsed, maskUrl(url));
5552
- saveSubscriptionRawConfig(subName, content);
5553
5712
  const meta = extractSubscriptionMeta(response.headers);
5554
- try {
5555
- saveSubscriptionMeta(subName, meta);
5556
- } catch (e) {
5713
+ withFileLock(PATHS.subscriptionCommitLock, () => {
5714
+ const previousContent = readSubscriptionRawConfig(subName);
5715
+ saveSubscriptionRawConfig(subName, content);
5557
5716
  try {
5558
- removeSubscriptionRawConfig(subName);
5559
- } catch {
5717
+ saveSubscriptionMeta(subName, meta);
5718
+ } catch (e) {
5719
+ let rollbackHint;
5720
+ try {
5721
+ if (previousContent === null) {
5722
+ removeSubscriptionRawConfig(subName);
5723
+ rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664";
5724
+ } else {
5725
+ saveSubscriptionRawConfig(subName, previousContent);
5726
+ rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u6062\u590D\u4E3A\u66F4\u65B0\u524D\u5185\u5BB9";
5727
+ }
5728
+ } catch (rollbackError) {
5729
+ rollbackHint = `\u8BA2\u9605\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25\uFF08${rollbackError.message}\uFF09\uFF0C\u5F53\u524D\u5185\u5BB9\u672A\u786E\u8BA4\uFF0C\u8BF7\u624B\u5DE5\u68C0\u67E5`;
5730
+ }
5731
+ throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
5732
+ label: "\u66F4\u65B0\u5931\u8D25",
5733
+ // 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
5734
+ // 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
5735
+ hint: [rollbackHint, "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
5736
+ });
5560
5737
  }
5561
- throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
5562
- label: "\u66F4\u65B0\u5931\u8D25",
5563
- // 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
5564
- // 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
5565
- hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
5566
- });
5567
- }
5738
+ });
5568
5739
  const { proxies, proxyGroups } = countConfigNodes(parsed);
5569
5740
  return { proxies, proxyGroups };
5570
5741
  }
@@ -5676,6 +5847,7 @@ function cmdConfig(args = []) {
5676
5847
  const rawContent = requireSubscriptionRawConfig(active.name);
5677
5848
  const mode = deriveRuntimeMode(getConfigInfo());
5678
5849
  const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
5850
+ if (asJson && reveal) assertConfigGraphExpansionSafe(config);
5679
5851
  const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
5680
5852
  const shown = redacted.config;
5681
5853
  if (asJson) {
@@ -5683,7 +5855,7 @@ function cmdConfig(args = []) {
5683
5855
  return;
5684
5856
  }
5685
5857
  console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
5686
- 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"));
5858
+ console.log(colors.gray("# \u914D\u7F6E\u9884\u89C8\uFF1A\u672A\u5199\u76D8\u3001\u672A\u6821\u9A8C\u3001\u672A\u5E94\u7528"));
5687
5859
  if (!reveal && redacted.changed) {
5688
5860
  console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
5689
5861
  }
@@ -5697,6 +5869,7 @@ function cmdConfig(args = []) {
5697
5869
 
5698
5870
  // src/open.ts
5699
5871
  import { spawn } from "child_process";
5872
+ import os2 from "os";
5700
5873
 
5701
5874
  // src/lifecycle.ts
5702
5875
  var silentSigint = false;
@@ -5706,6 +5879,21 @@ function setSilentSigint(value) {
5706
5879
  function isSilentSigint() {
5707
5880
  return silentSigint;
5708
5881
  }
5882
+ var activeChildren = /* @__PURE__ */ new Set();
5883
+ function trackChildProcess(child) {
5884
+ activeChildren.add(child);
5885
+ const untrack = () => activeChildren.delete(child);
5886
+ child.once("close", untrack);
5887
+ return untrack;
5888
+ }
5889
+ function terminateActiveChildren(signal) {
5890
+ for (const child of activeChildren) {
5891
+ try {
5892
+ child.kill(signal);
5893
+ } catch {
5894
+ }
5895
+ }
5896
+ }
5709
5897
 
5710
5898
  // src/open.ts
5711
5899
  function openUrl(url) {
@@ -5717,6 +5905,14 @@ function openUrl(url) {
5717
5905
  } catch {
5718
5906
  }
5719
5907
  }
5908
+ function tailExitCode(code, signal) {
5909
+ if (code !== null) return code;
5910
+ if (signal !== null) {
5911
+ const signalNumber = os2.constants.signals[signal];
5912
+ if (typeof signalNumber === "number") return 128 + signalNumber;
5913
+ }
5914
+ return 1;
5915
+ }
5720
5916
  function viewLogWithTail(logPath, options) {
5721
5917
  const follow = options?.follow;
5722
5918
  const lines = options?.lines || 100;
@@ -5732,9 +5928,14 @@ function viewLogWithTail(logPath, options) {
5732
5928
  tailArgs.push("-n", lines.toString());
5733
5929
  tailArgs.push(logPath);
5734
5930
  const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5931
+ const untrackTail = trackChildProcess(tail);
5735
5932
  if (follow) setSilentSigint(true);
5736
- tail.on("close", (code) => process.exit(code ?? 0));
5933
+ tail.on("close", (code, signal) => {
5934
+ untrackTail();
5935
+ process.exit(tailExitCode(code, signal));
5936
+ });
5737
5937
  tail.on("error", (e) => {
5938
+ untrackTail();
5738
5939
  console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5739
5940
  process.exit(1);
5740
5941
  });
@@ -5967,7 +6168,7 @@ import fs12 from "fs";
5967
6168
  import path7 from "path";
5968
6169
 
5969
6170
  // src/hot-reload.ts
5970
- import fs9 from "fs";
6171
+ import fs8 from "fs";
5971
6172
 
5972
6173
  // src/proxy-probe.ts
5973
6174
  import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
@@ -6002,7 +6203,7 @@ async function probeProxyConnectivity(port) {
6002
6203
  try {
6003
6204
  const { stdout } = await execFileAsync(
6004
6205
  "curl",
6005
- ["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
6206
+ ["-x", `http://127.0.0.1:${port}`, "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
6006
6207
  {
6007
6208
  timeout: PROBE_TIMEOUT_MS + 2e3,
6008
6209
  // 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
@@ -6025,47 +6226,12 @@ async function probeProxyConnectivity(port) {
6025
6226
  }
6026
6227
  }
6027
6228
 
6028
- // src/stop-epoch.ts
6029
- import fs8 from "fs";
6030
- function readStopEpoch() {
6031
- try {
6032
- const n = Number.parseInt(fs8.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
6033
- return Number.isSafeInteger(n) && n >= 0 ? n : 0;
6034
- } catch {
6035
- return 0;
6036
- }
6037
- }
6038
- var stopEpochBaselineCaptured = null;
6039
- function captureStopEpochBaseline() {
6040
- stopEpochBaselineCaptured = readStopEpoch();
6041
- return stopEpochBaselineCaptured;
6042
- }
6043
- function stopEpochBaseline() {
6044
- return stopEpochBaselineCaptured ?? readStopEpoch();
6045
- }
6046
- function bumpStopEpoch() {
6047
- try {
6048
- ensureDirs();
6049
- atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
6050
- } catch {
6051
- }
6052
- }
6053
- function recordServiceStopped() {
6054
- bumpStopEpoch();
6055
- }
6056
- function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
6057
- return stopEpochNow !== stopEpochBefore;
6058
- }
6059
- function startAbortedByConcurrentStop() {
6060
- return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
6061
- }
6062
-
6063
6229
  // src/hot-reload.ts
6064
6230
  var HOT_RELOAD_TIMEOUT_MS = 5e3;
6065
6231
  var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
6066
6232
  function logOversized() {
6067
6233
  try {
6068
- return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
6234
+ return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
6069
6235
  } catch {
6070
6236
  return false;
6071
6237
  }
@@ -6102,17 +6268,14 @@ async function tryHotReload(prefetched) {
6102
6268
  return false;
6103
6269
  }
6104
6270
  }
6105
- function concludeHotReload(stopEpochBefore, stopEpochNow) {
6106
- return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
6107
- }
6108
6271
 
6109
6272
  // src/process-stop.ts
6110
6273
  import { spawnSync as spawnSync6 } from "child_process";
6111
- import fs11 from "fs";
6274
+ import fs10 from "fs";
6112
6275
 
6113
6276
  // src/sudo.ts
6114
6277
  import { spawnSync as spawnSync5 } from "child_process";
6115
- import fs10 from "fs";
6278
+ import fs9 from "fs";
6116
6279
  import path6 from "path";
6117
6280
  var SUDO_TIMEOUT_MS = 6e4;
6118
6281
  var SudoAuthError = class extends Error {
@@ -6139,8 +6302,8 @@ function runSudoScript(scriptBody, opts) {
6139
6302
  }
6140
6303
  ensureDirs();
6141
6304
  const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
6142
- fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6143
- fs10.chmodSync(scriptPath, 448);
6305
+ fs9.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6306
+ fs9.chmodSync(scriptPath, 448);
6144
6307
  try {
6145
6308
  const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
6146
6309
  if (result.error) {
@@ -6150,7 +6313,7 @@ function runSudoScript(scriptBody, opts) {
6150
6313
  if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
6151
6314
  } finally {
6152
6315
  try {
6153
- fs10.unlinkSync(scriptPath);
6316
+ fs9.unlinkSync(scriptPath);
6154
6317
  } catch {
6155
6318
  }
6156
6319
  }
@@ -6161,26 +6324,19 @@ var PROCESS_WAIT_ATTEMPTS = 50;
6161
6324
  var PROCESS_WAIT_INTERVAL = 100;
6162
6325
  var BATCH_KILL_THRESHOLD = 3;
6163
6326
  function clearRuntime() {
6164
- if (fs11.existsSync(DIRS.runtime)) {
6327
+ if (fs10.existsSync(DIRS.runtime)) {
6165
6328
  rmrf(DIRS.runtime);
6166
6329
  }
6167
6330
  ensureDirs();
6168
6331
  }
6169
- function describePidCleanupFailure(err) {
6170
- return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
6171
- }
6172
6332
  var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
6173
6333
  function printResidueWarning(remaining) {
6174
6334
  console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
6175
6335
  console.log(MANUAL_PKILL_HINT);
6176
6336
  }
6177
- function warnPidCleanupFailed(err) {
6178
- if (!err) return;
6179
- console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
6180
- }
6181
6337
  function clearPid() {
6182
6338
  try {
6183
- fs11.unlinkSync(PATHS.pidFile);
6339
+ fs10.unlinkSync(PATHS.pidFile);
6184
6340
  return null;
6185
6341
  } catch (e) {
6186
6342
  if (e.code === "ENOENT") return null;
@@ -6224,7 +6380,7 @@ function buildKernelCleanupScript() {
6224
6380
  async function cleanupAll() {
6225
6381
  const pids = getMihomoPids();
6226
6382
  if (pids.length === 0) {
6227
- return { remaining: [], scriptError: null, pidError: clearPid() };
6383
+ return { remaining: [], incomplete: clearPid() };
6228
6384
  }
6229
6385
  let scriptError = null;
6230
6386
  const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
@@ -6251,23 +6407,18 @@ async function cleanupAll() {
6251
6407
  await waitUntilNoMihomo(pids);
6252
6408
  const remaining = getMihomoPids();
6253
6409
  const pidError = remaining.length === 0 ? clearPid() : null;
6254
- return { remaining, scriptError, pidError };
6410
+ return { remaining, incomplete: scriptError ?? pidError };
6255
6411
  }
6256
6412
  function buildRootResidueCleanupError(result, ctx) {
6257
- const { scriptError, pidError } = result;
6258
- const hasKernelResidue = result.remaining.length > 0;
6259
- const pidList = `PID ${result.remaining.join(", ")}`;
6260
- const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
6261
- const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
6262
- hint.push(hasKernelResidue || scriptError ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
6263
- if (scriptError instanceof SudoAuthError) {
6264
- return new CliError(`${describeSudoFailure(scriptError)}\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406`, { label: "\u5DF2\u53D6\u6D88", hint });
6413
+ const alive = result.remaining.length > 0;
6414
+ const state = alive ? `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${result.remaining.join(", ")}\uFF09` : "\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF0C\u4F46\u6E05\u7406\u672A\u8D70\u5B8C";
6415
+ const manual = alive ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: rm -f ${PATHS.pidFile}`;
6416
+ const hint = [ctx.mainOutcome, state, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`, manual];
6417
+ if (result.incomplete instanceof SudoAuthError) {
6418
+ const message = `${describeSudoFailure(result.incomplete)}\uFF0C${alive ? "\u6B8B\u7559\u672A\u88AB\u6E05\u7406" : "\u6E05\u7406\u672A\u5B8C\u6210"}`;
6419
+ return new CliError(message, { label: "\u5DF2\u53D6\u6D88", hint });
6265
6420
  }
6266
- return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
6267
- }
6268
- function classifyResidueCleanup(result) {
6269
- if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
6270
- return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
6421
+ return new CliError(result.incomplete?.message ?? "\u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
6271
6422
  }
6272
6423
  function warnResidueCleanup(result, ctx) {
6273
6424
  const err = buildRootResidueCleanupError(result, ctx);
@@ -6276,38 +6427,61 @@ function warnResidueCleanup(result, ctx) {
6276
6427
  }
6277
6428
  async function cleanupKernelsOrThrow(ctx) {
6278
6429
  const result = await cleanupAll();
6279
- const verdict = classifyResidueCleanup(result);
6280
- if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
6281
- if (verdict === "warn") warnResidueCleanup(result, ctx);
6430
+ if (result.incomplete !== null) {
6431
+ if (result.remaining.length > 0) throw buildRootResidueCleanupError(result, ctx);
6432
+ warnResidueCleanup(result, ctx);
6433
+ }
6282
6434
  return result;
6283
6435
  }
6284
6436
  async function stop() {
6285
6437
  const allPids = getMihomoPids();
6286
6438
  if (allPids.length === 0) {
6287
- warnPidCleanupFailed(clearPid());
6439
+ const pidError = clearPid();
6440
+ if (pidError) console.warn(colors.yellow(`\u8B66\u544A: pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${pidError.message}\uFF09\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
6288
6441
  clearRuntime();
6289
6442
  return {};
6290
6443
  }
6291
6444
  const result = await cleanupAll();
6292
- if (result.remaining.length === 0) {
6293
- warnPidCleanupFailed(result.pidError);
6294
- if (result.scriptError) {
6295
- console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo-cli stop`));
6296
- }
6297
- }
6298
- const remaining = result.remaining;
6299
- if (remaining.length > 0) {
6300
- console.log("");
6301
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
6302
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
6303
- console.log(MANUAL_PKILL_HINT);
6304
- console.log("");
6305
- return { remaining };
6445
+ if (result.remaining.length === 0 && result.incomplete !== null) {
6446
+ warnResidueCleanup(result, { mainOutcome: "\u5185\u6838\u5DF2\u505C\u6B62", retryCommand: "mihomo-cli stop" });
6306
6447
  }
6448
+ if (result.remaining.length > 0) return { remaining: result.remaining };
6307
6449
  clearRuntime();
6308
6450
  return {};
6309
6451
  }
6310
6452
 
6453
+ // src/stop-epoch.ts
6454
+ import fs11 from "fs";
6455
+ function readStopEpoch() {
6456
+ try {
6457
+ const n = Number.parseInt(fs11.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
6458
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
6459
+ } catch {
6460
+ return 0;
6461
+ }
6462
+ }
6463
+ var stopEpochBaselineCaptured = null;
6464
+ function captureStopEpochBaseline() {
6465
+ stopEpochBaselineCaptured = readStopEpoch();
6466
+ return stopEpochBaselineCaptured;
6467
+ }
6468
+ function stopEpochBaseline() {
6469
+ return stopEpochBaselineCaptured ?? readStopEpoch();
6470
+ }
6471
+ function bumpStopEpoch() {
6472
+ try {
6473
+ ensureDirs();
6474
+ atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
6475
+ } catch {
6476
+ }
6477
+ }
6478
+ function epochChanged(before, now) {
6479
+ return now !== before;
6480
+ }
6481
+ function startAbortedByConcurrentStop() {
6482
+ return epochChanged(stopEpochBaseline(), readStopEpoch());
6483
+ }
6484
+
6311
6485
  // src/service.ts
6312
6486
  var SERVICE_HEALTH_INTERVAL_MS = 100;
6313
6487
  var SERVICE_OBSERVE_MS = 1200;
@@ -6422,8 +6596,8 @@ function ensureServiceSymlink() {
6422
6596
  }
6423
6597
  function bootstrapServiceIdempotentOrThrow(what) {
6424
6598
  const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6425
- if (result.status === 0) return;
6426
- if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
6599
+ if (result.status === 0) return true;
6600
+ if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return false;
6427
6601
  const detail = result.stderr.trim();
6428
6602
  throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
6429
6603
  hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
@@ -6495,15 +6669,19 @@ async function startService() {
6495
6669
  });
6496
6670
  }
6497
6671
  await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
6672
+ const previousPid = getServiceStatus({ withDisabled: false }).pid;
6498
6673
  bootoutService();
6499
- await waitUntilUnloaded();
6500
- rotateAndCleanupLogs();
6674
+ const unloadOutcome = await waitUntilUnloaded(serviceTarget(), {
6675
+ acceptReplacement: (pid) => pid !== previousPid && !isServiceDisabledInLaunchd()
6676
+ });
6677
+ if (unloadOutcome === "unloaded") rotateAndCleanupLogs();
6501
6678
  let started = true;
6502
6679
  withFileLock(PATHS.serviceLock, () => {
6503
6680
  if (startAbortedByConcurrentStop()) {
6504
6681
  started = false;
6505
6682
  return;
6506
6683
  }
6684
+ if (unloadOutcome === "replacement-running") return;
6507
6685
  runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6508
6686
  bootstrapServiceIdempotentOrThrow("\u542F\u52A8\u670D\u52A1");
6509
6687
  });
@@ -6553,7 +6731,7 @@ async function restartService(prefetched) {
6553
6731
  }
6554
6732
  const oversized = logOversized();
6555
6733
  if (!oversized && await tryHotReload(prefetched)) {
6556
- return concludeHotReload(stopEpochBaseline(), readStopEpoch());
6734
+ return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
6557
6735
  }
6558
6736
  if (oversized) {
6559
6737
  const archiveFile = allocateArchivePath();
@@ -6564,17 +6742,19 @@ async function restartService(prefetched) {
6564
6742
  }
6565
6743
  }
6566
6744
  const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
6567
- let started = true;
6568
6745
  if (kick.status !== 0) {
6569
- withFileLock(PATHS.serviceLock, () => {
6570
- if (startAbortedByConcurrentStop()) {
6571
- started = false;
6572
- return;
6573
- }
6746
+ const bootstrapped = withFileLock(PATHS.serviceLock, () => {
6747
+ if (startAbortedByConcurrentStop()) return null;
6574
6748
  runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6575
- bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
6749
+ return bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
6576
6750
  });
6577
- if (!started) return { hotReloaded: false, started: false };
6751
+ if (bootstrapped === null) return { hotReloaded: false, started: false };
6752
+ if (!bootstrapped) {
6753
+ const detail = kick.stderr.trim();
6754
+ throw new CliError(`\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08kickstart \u9000\u51FA\u7801 ${kick.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09\uFF1A\u670D\u52A1\u4ECD\u5DF2\u88C5\u8F7D\uFF0C\u672C\u6B21\u672A\u91CD\u65B0\u88C5\u8F7D`, {
6755
+ hint: [detail, "\u65E7\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF0C\u65B0\u914D\u7F6E\u672A\u786E\u8BA4\u751F\u6548\uFF1B\u8BF7\u91CD\u8BD5: mihomo-cli start", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
6756
+ });
6757
+ }
6578
6758
  }
6579
6759
  cleanupOldLogs();
6580
6760
  return { hotReloaded: false, started: true };
@@ -6713,7 +6893,16 @@ function restartModeOnChange() {
6713
6893
  }
6714
6894
  async function launchOrRestart(mode) {
6715
6895
  if (mode === "tun") {
6716
- return startTun(assertTunStartNotRaced());
6896
+ const prefetched = assertTunStartNotRaced();
6897
+ let pid;
6898
+ try {
6899
+ pid = await startTun(prefetched);
6900
+ } catch (e) {
6901
+ await throwIfTunStartCancelled();
6902
+ throw e;
6903
+ }
6904
+ await throwIfTunStartCancelled();
6905
+ return pid;
6717
6906
  }
6718
6907
  const status = getServiceStatus();
6719
6908
  let hotReloaded = false;
@@ -6738,6 +6927,20 @@ async function launchOrRestart(mode) {
6738
6927
  throw e;
6739
6928
  }
6740
6929
  }
6930
+ async function stopTunAfterConcurrentStop() {
6931
+ const result = await stop();
6932
+ if (result.remaining && result.remaining.length > 0) {
6933
+ throw new CliError(`\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C\uFF0C\u4F46 TUN \u8FDB\u7A0B\u672A\u80FD\u7EC8\u6B62\uFF08PID ${result.remaining.join(", ")}\uFF09`, {
6934
+ label: "\u505C\u6B62\u5931\u8D25",
6935
+ hint: [MANUAL_PKILL_HINT]
6936
+ });
6937
+ }
6938
+ }
6939
+ async function throwIfTunStartCancelled() {
6940
+ if (!startAbortedByConcurrentStop()) return;
6941
+ await stopTunAfterConcurrentStop();
6942
+ throw cancelledByConcurrentStop();
6943
+ }
6741
6944
  function cancelledByConcurrentStop() {
6742
6945
  return new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C", {
6743
6946
  label: "\u542F\u52A8\u5931\u8D25",
@@ -6857,31 +7060,33 @@ function detectSystemProxy(mixedPort) {
6857
7060
  if (r.error || r.status !== 0 || typeof r.stdout !== "string" || !r.stdout.includes("<dictionary>")) return null;
6858
7061
  return summarizeSystemProxy(parseScutilProxy(r.stdout), mixedPort);
6859
7062
  }
6860
- function printSystemProxyHint(mixedPort) {
6861
- const summary = detectSystemProxy(mixedPort);
7063
+ function buildSystemProxyHint(summary, mixedPort) {
7064
+ const applicationGuide = `\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`;
6862
7065
  if (summary === null) {
6863
- console.log(colors.gray(`\u63D0\u793A: Mixed \u6A21\u5F0F\u9700\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u914D\u7F6E HTTP/SOCKS \u4EE3\u7406 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
6864
- return;
7066
+ return { text: `\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B${applicationGuide}`, warning: false };
6865
7067
  }
6866
7068
  if (summary.pac) {
6867
7069
  const desc = summary.pac.wpad ? "WPAD \u81EA\u52A8\u53D1\u73B0" : `PAC \u6587\u4EF6${summary.pac.source ? `\uFF08${summary.pac.source}\uFF09` : ""}`;
6868
- console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u662F\u5426\u8D70 mihomo-cli \u7531\u811A\u672C\u51B3\u5B9A\uFF1B\u5982\u9700\u56FA\u5B9A\u5168\u91CF\u8D70\u4EE3\u7406\uFF0C\u53EF\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u6539\u7528\u624B\u52A8\u4EE3\u7406 127.0.0.1:${mixedPort}`));
6869
- return;
7070
+ return { text: `\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`, warning: false };
6870
7071
  }
6871
7072
  if (summary.matched) {
6872
7073
  if (summary.diverged.length > 0) {
6873
- console.log(colors.yellow(`\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\u2014\u2014\u5BF9\u5E94\u6D41\u91CF\u53EF\u80FD\u4E0D\u7ECF mihomo-cli`));
6874
- } else {
6875
- console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}`));
7074
+ return {
7075
+ text: `\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\uFF1B\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u8FD9\u4E9B\u8BBE\u7F6E\uFF0C\u5177\u4F53\u5E94\u7528\u4EE5\u81EA\u8EAB\u4EE3\u7406\u914D\u7F6E\u4E3A\u51C6`,
7076
+ warning: true
7077
+ };
6876
7078
  }
6877
- return;
7079
+ return { text: `\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF08\u53EA\u8BFB\u68C0\u6D4B\uFF09\uFF1B\u5177\u4F53\u5E94\u7528\u4ECD\u4EE5\u81EA\u8EAB\u4EE3\u7406\u914D\u7F6E\u4E3A\u51C6`, warning: false };
6878
7080
  }
6879
7081
  const pointing = summary.active.length > 0 ? `\uFF0C\u5F53\u524D\u6307\u5411 ${summary.active.join("\u3001")}` : "";
6880
- console.log(colors.yellow(`\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF1B\u9700\u8981\u4EE3\u7406\u7684\u5E94\u7528\u8BF7\u914D\u7F6E\u540E\u4F7F\u7528\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
6881
- console.log(colors.gray(" \u8BBE\u7F6E\u547D\u4EE4\uFF08\u628A Wi-Fi \u6362\u6210\u5B9E\u9645\u7F51\u7EDC\u670D\u52A1\uFF0C\u5168\u90E8\u670D\u52A1\u89C1 networksetup -listallnetworkservices\uFF09:"));
6882
- console.log(colors.gray(` networksetup -setwebproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6883
- console.log(colors.gray(` networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6884
- console.log(colors.gray(` networksetup -setsocksfirewallproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
7082
+ return {
7083
+ text: `\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`,
7084
+ warning: true
7085
+ };
7086
+ }
7087
+ function printSystemProxyHint(mixedPort) {
7088
+ const hint = buildSystemProxyHint(detectSystemProxy(mixedPort), mixedPort);
7089
+ console.log(hint.warning ? colors.yellow(hint.text) : colors.gray(hint.text));
6885
7090
  }
6886
7091
 
6887
7092
  // src/commands/status.ts
@@ -6932,11 +7137,10 @@ function buildStatusJson(args) {
6932
7137
  } : null,
6933
7138
  overwrite: {
6934
7139
  enabled: args.overwriteEnabled,
6935
- files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
6936
- // 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
6937
- // 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
7140
+ // 全局关闭时 buildConfig 不加载任何覆写,applied 必须为空;只滤文件 enabled/match
7141
+ // 会与同一份 JSON 里的 overwrite.enabled:false 自相矛盾
6938
7142
  applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
6939
- // 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors。
7143
+ // 加载失败的文件不属于 applied(既没合并也无法判 enabled/match),单列 errors。
6940
7144
  // hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
6941
7145
  // 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
6942
7146
  errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message, hint: b.hint }))
@@ -6963,23 +7167,8 @@ async function printStatus(args = []) {
6963
7167
  const {
6964
7168
  enabled: overwriteEnabled,
6965
7169
  files: overwriteFiles,
6966
- entries: overwriteEntries,
6967
7170
  broken: overwriteBroken
6968
7171
  } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
6969
- if (activeSub && overwriteEnabled && overwriteFiles.some((f) => f.kind === "script")) {
6970
- try {
6971
- const rawContent = readSubscriptionRawConfig(activeSub.name);
6972
- if (rawContent) {
6973
- const { matches } = judgeScriptMatches(rawContent, deriveRuntimeMode(info), { subName: activeSub.name, subUrl: activeSub.url }, overwriteEntries);
6974
- const matchedByName = new Map(matches.map((m) => [m.file, m.matched]));
6975
- for (const f of overwriteFiles) {
6976
- if (f.kind === "script" && matchedByName.has(f.name)) f.matched = matchedByName.get(f.name);
6977
- }
6978
- }
6979
- } catch (e) {
6980
- if (!(e instanceof CliError)) throw e;
6981
- }
6982
- }
6983
7172
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6984
7173
  const controllerPort = getPortsOrNull()?.controller ?? null;
6985
7174
  const { running, pid, kind } = state;
@@ -7000,8 +7189,6 @@ async function printStatus(args = []) {
7000
7189
  activeSub,
7001
7190
  cached,
7002
7191
  overwriteEnabled,
7003
- // 两个数组在 buildStatusJson 里分出来:files 仍是旧契约(只滤文件级 enabled,
7004
- // 不按 match、不随全局开关变空),applied 才是本次真正参与合并的
7005
7192
  overwriteFiles,
7006
7193
  overwriteBroken,
7007
7194
  service
@@ -7104,7 +7291,7 @@ function printOverwriteLines(enabled, files, broken) {
7104
7291
  if (active.length > 0) {
7105
7292
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${active.map((f) => shortOverwriteName(f.name)).join(", ")}${suffix})`);
7106
7293
  } else {
7107
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
7294
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u9009\u4E2D\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
7108
7295
  }
7109
7296
  for (const b of broken) {
7110
7297
  console.log(colors.red(` ${b.message}`));
@@ -7157,7 +7344,7 @@ async function cmdStart(args) {
7157
7344
  console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D"));
7158
7345
  console.log("");
7159
7346
  } else {
7160
- recordServiceStopped();
7347
+ bumpStopEpoch();
7161
7348
  }
7162
7349
  captureStopEpochBaseline();
7163
7350
  } else if (!serviceBefore.installed) {
@@ -7249,7 +7436,7 @@ function unknownSubcommandError(action, table, opts) {
7249
7436
  }
7250
7437
  async function confirmPrompt(question) {
7251
7438
  if (!process.stdin.isTTY) return false;
7252
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
7439
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
7253
7440
  const answer = await new Promise((resolve) => {
7254
7441
  rl.question(`${question} (y/N) `, (a) => {
7255
7442
  rl.close();
@@ -7330,7 +7517,7 @@ async function cmdDirectory(args) {
7330
7517
  import fs15 from "fs";
7331
7518
 
7332
7519
  // src/kernel.ts
7333
- import { execFile as execFile3, spawnSync as spawnSync9 } from "child_process";
7520
+ import { execFile as execFile3, spawn as spawn2, spawnSync as spawnSync9 } from "child_process";
7334
7521
  import fs14 from "fs";
7335
7522
  import path8 from "path";
7336
7523
  import { promisify as promisify3 } from "util";
@@ -7338,7 +7525,6 @@ var GITHUB_REPO = "MetaCubeX/mihomo";
7338
7525
  var KERNEL_HTTP_TIMEOUT = 12e4;
7339
7526
  var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
7340
7527
  var GH_DOWNLOAD_TIMEOUT = 1e5;
7341
- var HTTP_CLIENT2 = createHttpClient({ timeout: KERNEL_HTTP_TIMEOUT });
7342
7528
  var execFileAsync2 = promisify3(execFile3);
7343
7529
  function withMirror(url, mirror) {
7344
7530
  if (mirror && url.startsWith("https://github.com/")) {
@@ -7418,9 +7604,8 @@ function pickLatestRelease(releases) {
7418
7604
  }
7419
7605
  function buildReleaseApiCurlArgs(proxy, url) {
7420
7606
  return [
7421
- "-s",
7422
- "-x",
7423
- proxy,
7607
+ "-sS",
7608
+ ...proxy ? ["-x", proxy] : ["--noproxy", "*"],
7424
7609
  "--proto",
7425
7610
  "=https",
7426
7611
  "--proto-redir",
@@ -7475,7 +7660,6 @@ async function getLatestReleaseViaGh(repo, signal) {
7475
7660
  return pickLatestRelease(JSON.parse(result.stdout));
7476
7661
  }
7477
7662
  async function getLatestRelease(repo, opts) {
7478
- const url = `https://api.github.com/repos/${repo}/releases`;
7479
7663
  if (opts.useGh) {
7480
7664
  try {
7481
7665
  return await getLatestReleaseViaGh(repo, opts.signal);
@@ -7484,35 +7668,33 @@ async function getLatestRelease(repo, opts) {
7484
7668
  opts.onGhFallback?.();
7485
7669
  }
7486
7670
  }
7487
- if (opts.proxy) {
7488
- let stdout;
7489
- try {
7490
- const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(opts.proxy, url), {
7491
- encoding: "utf8",
7492
- maxBuffer: 50 * 1024 * 1024,
7493
- timeout: KERNEL_HTTP_TIMEOUT + 1e4,
7494
- signal: opts.signal,
7495
- // no_proxy 例外表会绕过显式 -x——统一出口置空,保 -x 权威(curl-spawn.ts)
7496
- env: buildCurlSpawnEnv()
7497
- });
7498
- stdout = result.stdout;
7499
- } catch (e) {
7500
- throw translateReleaseApiCurlError(e);
7501
- }
7502
- const { body, statusCode } = parseCurlStatusOutput(stdout);
7503
- if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
7504
- throw createHttpError(statusCode, body);
7505
- }
7506
- let releases;
7507
- try {
7508
- releases = JSON.parse(body);
7509
- } catch {
7510
- throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
7511
- }
7512
- return pickLatestRelease(releases);
7671
+ const url = `https://api.github.com/repos/${repo}/releases`;
7672
+ let stdout;
7673
+ try {
7674
+ const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(opts.proxy, url), {
7675
+ encoding: "utf8",
7676
+ maxBuffer: 50 * 1024 * 1024,
7677
+ timeout: KERNEL_HTTP_TIMEOUT + 1e4,
7678
+ signal: opts.signal,
7679
+ // no_proxy 例外表会绕过显式 -x——统一出口置空,保 -x 权威(curl-spawn.ts)
7680
+ env: buildCurlSpawnEnv()
7681
+ });
7682
+ stdout = result.stdout;
7683
+ } catch (e) {
7684
+ if (opts.signal?.aborted) throw e;
7685
+ throw translateReleaseApiCurlError(e);
7686
+ }
7687
+ const { body, statusCode } = parseCurlStatusOutput(stdout);
7688
+ if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
7689
+ throw createHttpError(statusCode, body);
7690
+ }
7691
+ let releases;
7692
+ try {
7693
+ releases = JSON.parse(body);
7694
+ } catch {
7695
+ throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
7513
7696
  }
7514
- const response = await HTTP_CLIENT2.get(url, { responseType: "json", signal: opts.signal });
7515
- return pickLatestRelease(response.data);
7697
+ return pickLatestRelease(releases);
7516
7698
  }
7517
7699
  async function checkUpdate(opts) {
7518
7700
  const currentVersion = opts.currentVersion !== void 0 ? opts.currentVersion : getKernelVersion();
@@ -7596,6 +7778,74 @@ function buildGhDownloadEnv(proxy) {
7596
7778
  }
7597
7779
  return env;
7598
7780
  }
7781
+ var CHILD_FORCE_KILL_GRACE_MS = 1e3;
7782
+ var GZIP_TIMEOUT_MS = 6e4;
7783
+ function scheduleChildForceKill(child, delayMs) {
7784
+ const timer = setTimeout(() => {
7785
+ try {
7786
+ child.kill("SIGKILL");
7787
+ } catch {
7788
+ }
7789
+ }, delayMs);
7790
+ timer.unref();
7791
+ return () => clearTimeout(timer);
7792
+ }
7793
+ function runInheritedChild(command, args, options) {
7794
+ return new Promise((resolve) => {
7795
+ const child = spawn2(command, args, { stdio: "inherit", env: options.env });
7796
+ const untrack = trackChildProcess(child);
7797
+ let childError = null;
7798
+ let timedOut = false;
7799
+ let settled = false;
7800
+ let timer;
7801
+ let cancelForceKill = () => {
7802
+ };
7803
+ const finish = (status) => {
7804
+ if (settled) return;
7805
+ settled = true;
7806
+ if (timer) clearTimeout(timer);
7807
+ cancelForceKill();
7808
+ untrack();
7809
+ if (timedOut && childError === null) {
7810
+ childError = Object.assign(new Error(`${command} timed out`), { code: "ETIMEDOUT" });
7811
+ }
7812
+ resolve({ error: childError, status });
7813
+ };
7814
+ child.on("error", (error) => {
7815
+ childError = error;
7816
+ if (child.pid === void 0) finish(null);
7817
+ });
7818
+ child.on("close", (status) => finish(status));
7819
+ if (options.timeout !== void 0) {
7820
+ timer = setTimeout(() => {
7821
+ timedOut = true;
7822
+ child.kill();
7823
+ cancelForceKill = scheduleChildForceKill(child, CHILD_FORCE_KILL_GRACE_MS);
7824
+ }, options.timeout);
7825
+ timer.unref();
7826
+ }
7827
+ });
7828
+ }
7829
+ async function decompressGzip(tempPath) {
7830
+ const execution = execFileAsync2("gzip", ["-dc", tempPath], {
7831
+ encoding: "buffer",
7832
+ maxBuffer: 256 * 1024 * 1024,
7833
+ timeout: GZIP_TIMEOUT_MS
7834
+ });
7835
+ const untrack = trackChildProcess(execution.child);
7836
+ const cancelForceKill = scheduleChildForceKill(execution.child, GZIP_TIMEOUT_MS + CHILD_FORCE_KILL_GRACE_MS);
7837
+ try {
7838
+ const { stdout } = await execution;
7839
+ return stdout;
7840
+ } catch (error) {
7841
+ const code = error.code;
7842
+ if (typeof code === "number") throw new Error(`gzip \u9000\u51FA\u7801 ${code}`);
7843
+ throw error;
7844
+ } finally {
7845
+ cancelForceKill();
7846
+ untrack();
7847
+ }
7848
+ }
7599
7849
  async function downloadKernel(progressCallback, channel, latest) {
7600
7850
  ensureDirs();
7601
7851
  const downloadProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
@@ -7630,8 +7880,7 @@ async function downloadKernel(progressCallback, channel, latest) {
7630
7880
  if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
7631
7881
  throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
7632
7882
  }
7633
- const ghResult = spawnSync9("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7634
- stdio: "inherit",
7883
+ const ghResult = await runInheritedChild("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7635
7884
  timeout: GH_DOWNLOAD_TIMEOUT,
7636
7885
  // gh 回退候选带本机代理:per-spawn 注入(buildGhDownloadEnv 注释述其与 D9 的关系)
7637
7886
  env: buildGhDownloadEnv(channel.proxy ?? null)
@@ -7650,7 +7899,7 @@ async function downloadKernel(progressCallback, channel, latest) {
7650
7899
  }
7651
7900
  } else {
7652
7901
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
7653
- const curlResult = spawnSync9(
7902
+ const curlResult = await runInheritedChild(
7654
7903
  "curl",
7655
7904
  buildKernelCurlArgs({
7656
7905
  url: downloadUrl,
@@ -7659,7 +7908,7 @@ async function downloadKernel(progressCallback, channel, latest) {
7659
7908
  outputPath: tempPath
7660
7909
  }),
7661
7910
  // no_proxy 例外表会绕过显式 -x——统一出口置空,保 -x 权威(curl-spawn.ts)
7662
- { stdio: "inherit", env: buildCurlSpawnEnv() }
7911
+ { env: buildCurlSpawnEnv() }
7663
7912
  );
7664
7913
  if (curlResult.error) {
7665
7914
  if (curlResult.error.code === "ENOENT") {
@@ -7686,14 +7935,9 @@ async function downloadKernel(progressCallback, channel, latest) {
7686
7935
  if (progressCallback) {
7687
7936
  progressCallback("\u89E3\u538B\u5185\u6838...");
7688
7937
  }
7689
- if (!tempPath.endsWith(".gz")) {
7690
- throw new Error(`\u4E0D\u652F\u6301\u7684\u5185\u6838\u8D44\u4EA7\u683C\u5F0F: ${asset.name}\uFF08\u671F\u671B\u5355\u6587\u4EF6 .gz\uFF09`);
7691
- }
7692
7938
  const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
7693
- const gzipResult = spawnSync9("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7694
- if (gzipResult.error) throw gzipResult.error;
7695
- if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
7696
- fs14.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7939
+ const gzipStdout = await decompressGzip(tempPath);
7940
+ fs14.writeFileSync(foundBinary, gzipStdout, { mode: 493 });
7697
7941
  if (progressCallback) {
7698
7942
  progressCallback("\u6821\u9A8C\u5185\u6838...");
7699
7943
  }
@@ -7711,8 +7955,7 @@ async function downloadKernel(progressCallback, channel, latest) {
7711
7955
  }
7712
7956
  const targetPath = PATHS.mihomoBinary;
7713
7957
  fs14.renameSync(foundBinary, targetPath);
7714
- fs14.chmodSync(targetPath, 493);
7715
- return { version: latest.tag_name, path: targetPath };
7958
+ return { version: latest.tag_name };
7716
7959
  } finally {
7717
7960
  try {
7718
7961
  fs14.rmSync(tempDir, { recursive: true, force: true });
@@ -7722,7 +7965,7 @@ async function downloadKernel(progressCallback, channel, latest) {
7722
7965
  }
7723
7966
 
7724
7967
  // src/commands/update.ts
7725
- import { execFile as execFile4, spawn as spawn2 } from "child_process";
7968
+ import { execFile as execFile4, spawn as spawn3 } from "child_process";
7726
7969
  import net from "net";
7727
7970
  import { promisify as promisify4 } from "util";
7728
7971
  var execFileAsync3 = promisify4(execFile4);
@@ -7803,7 +8046,7 @@ async function cmdUpdate(args = []) {
7803
8046
  console.log("");
7804
8047
  const installEnv = await buildNpmSpawnEnv();
7805
8048
  await new Promise((resolve, reject) => {
7806
- const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit", env: installEnv });
8049
+ const npm = spawn3("npm", ["install", "-g", PKG_NAME], { stdio: "inherit", env: installEnv });
7807
8050
  npm.on("close", (code) => {
7808
8051
  if (code === 0) {
7809
8052
  resolve();
@@ -8187,6 +8430,9 @@ function parseProxyArg(args) {
8187
8430
  }
8188
8431
 
8189
8432
  // src/commands/kernel.ts
8433
+ function kernelRestartCommand(state) {
8434
+ return `mihomo-cli stop && ${startCommandForCurrentMode(state)}`;
8435
+ }
8190
8436
  function channelLabel(channel, isExplicitProxy) {
8191
8437
  switch (channel.kind) {
8192
8438
  case "gh":
@@ -8212,7 +8458,7 @@ function printChannelLine(channel, isExplicitProxy) {
8212
8458
  console.log("");
8213
8459
  }
8214
8460
  function formatChannelSwitchLine(previousError) {
8215
- const reason = previousError ? firstLine(previousError.message) : "";
8461
+ const reason = firstLine(previousError.message);
8216
8462
  return reason ? `\u4E0A\u4E00\u901A\u9053\u5931\u8D25\uFF08${reason}\uFF09\uFF0C\u5207\u6362\u4E3A:` : "\u4E0A\u4E00\u901A\u9053\u5931\u8D25\uFF0C\u5207\u6362\u4E3A:";
8217
8463
  }
8218
8464
  function buildDownloadFailureError(attempts, isExplicitProxy) {
@@ -8293,30 +8539,16 @@ async function cmdKernel(args) {
8293
8539
  if (useGh) {
8294
8540
  hint.push("", "\u672C\u6B21\u5DF2\u5148\u5C1D\u8BD5 gh \u8BA4\u8BC1\u901A\u9053\u3001\u5931\u8D25\u540E\u624D\u56DE\u9000\u76F4\u8FDE\uFF0C\u53EF\u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8295
8541
  }
8296
- } else if (!mirrorInfo.mirror) {
8297
- if (apiProxy) {
8298
- hint.push("", "\u63D0\u793A: \u7ECF\u4EE3\u7406\u67E5\u8BE2 GitHub \u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u662F\u5426\u53EF\u7528\uFF0C\u6216 mihomo-cli kernel --mirror direct \u91CD\u8BD5\u76F4\u8FDE");
8299
- } else {
8300
- hint.push(
8301
- "",
8302
- "\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF\u6216\u4EE3\u7406:",
8303
- " mihomo-cli kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u88F8 --mirror \u56FA\u5B9A\u88F8\u57DF\uFF0C\u53EF\u7528 v6/v4/cdn \u7B49\u522B\u540D\uFF09",
8304
- ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`,
8305
- " mihomo-cli kernel --proxy <\u7AEF\u53E3> # \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u51FA\u7F51"
8306
- );
8307
- }
8308
8542
  } else if (apiProxy) {
8309
8543
  hint.push("", "\u63D0\u793A: \u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09\u7ECF\u4EE3\u7406\u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u662F\u5426\u53EF\u7528\uFF1B\u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4E0B\u8F7D\uFF0C\u4E0E\u67E5\u8BE2\u65E0\u5173");
8310
- } else if (useGh) {
8311
- hint.push("", "\u63D0\u793A: gh \u8BA4\u8BC1\u901A\u9053\u4E0E\u76F4\u8FDE\u90FD\u5931\u8D25\u4E86\uFF0C\u53EF\u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8312
8544
  } else {
8313
- hint.push(
8314
- "",
8315
- "\u63D0\u793A: \u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4E0B\u8F7D\uFF0C\u7248\u672C\u67E5\u8BE2\u4ECD\u9700\u76F4\u8FDE GitHub API\uFF08\u5F53\u524D\u4E0D\u901A\uFF09\u3002\u51FA\u8DEF:",
8316
- " \u5B89\u88C5\u5E76\u767B\u5F55 GitHub CLI\uFF08\u8BA4\u8BC1\u914D\u989D 5000 \u6B21/\u65F6\uFF09:",
8317
- " brew install gh && gh auth login",
8318
- " \u6216\u7ECF\u672C\u673A\u4EE3\u7406\u5DE5\u5177\u67E5\u8BE2: mihomo-cli kernel --proxy <\u7AEF\u53E3>"
8319
- );
8545
+ hint.push("", `\u63D0\u793A: \u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09${useGh ? "gh \u8BA4\u8BC1\u901A\u9053\u4E0E\u76F4\u8FDE\u90FD" : "\u76F4\u8FDE"}\u5931\u8D25\u3002\u51FA\u8DEF:`);
8546
+ if (useGh) hint.push(" \u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8547
+ else hint.push(" \u5B89\u88C5\u5E76\u767B\u5F55 GitHub CLI\uFF08\u8BA4\u8BC1\u914D\u989D 5000 \u6B21/\u65F6\uFF09: brew install gh && gh auth login");
8548
+ hint.push(" \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u67E5\u8BE2: mihomo-cli kernel --proxy <\u7AEF\u53E3>");
8549
+ if (!mirrorInfo.mirror) {
8550
+ hint.push(` \u4E0B\u8F7D\u8FC7\u6162\u53EF\u52A0\u955C\u50CF: mihomo-cli kernel --mirror [\u955C\u50CF]\uFF08\u53EF\u7528: ${AVAILABLE_MIRRORS.join(", ")}\uFF1B\u955C\u50CF\u4E0D\u4F5C\u7528\u4E8E\u7248\u672C\u67E5\u8BE2\uFF09`);
8551
+ }
8320
8552
  }
8321
8553
  throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
8322
8554
  }
@@ -8333,7 +8565,7 @@ async function cmdKernel(args) {
8333
8565
  const attempts = [];
8334
8566
  for (let attempt = 0; attempt < channels.length; attempt++) {
8335
8567
  if (attempt > 0) {
8336
- console.log(formatChannelSwitchLine(attempts[attempt - 1]?.error ?? null));
8568
+ console.log(formatChannelSwitchLine(attempts[attempt - 1].error));
8337
8569
  printChannelLine(channels[attempt], proxyInfo.proxy !== null);
8338
8570
  }
8339
8571
  try {
@@ -8351,8 +8583,7 @@ async function cmdKernel(args) {
8351
8583
  \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
8352
8584
  const state = getRunningState();
8353
8585
  if (state.running) {
8354
- const restartCommand = startCommandForCurrentMode(state);
8355
- console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${restartCommand} \u91CD\u542F\u540E\u751F\u6548`));
8586
+ console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${kernelRestartCommand(state)} \u540E\u751F\u6548`));
8356
8587
  }
8357
8588
  console.log(colors.gray("\u63D0\u793A: \u82E5\u4F7F\u7528\u5C40\u57DF\u7F51\u8282\u70B9\uFF08192.168/10.x/*.local\uFF09\uFF0C\u9996\u6B21\u542F\u52A8\u53EF\u80FD\u91CD\u65B0\u5F39\u51FA\u300C\u672C\u5730\u7F51\u7EDC\u300D\u6388\u6743"));
8358
8589
  }
@@ -8464,7 +8695,7 @@ function printOverwriteList() {
8464
8695
  console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
8465
8696
  }
8466
8697
  if (f.kind === "script") {
8467
- console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF1B\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605\u65F6\u672B\u5C3E return true\uFF0Cstatus \u636E\u6B64\u533A\u5206\u751F\u6548\u4E0E\u4E0D\u9002\u7528\uFF09`);
8698
+ console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF1B\u4F5C\u7528\u57DF\u7531\u811A\u672C\u81EA\u884C\u5224\u65AD\uFF09`);
8468
8699
  } else if (f.keys.length > 0) {
8469
8700
  console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
8470
8701
  }
@@ -8576,8 +8807,13 @@ async function cmdReset(args) {
8576
8807
  const ids = new Set(targets.map((t) => t.id));
8577
8808
  const needsStop = targets.some((t) => t.needsStop);
8578
8809
  const serviceTargeted = ids.has("service");
8579
- const service = getServiceStatus();
8580
- let serviceActive = service.installed || service.loaded;
8810
+ const needsServiceState = needsStop || serviceTargeted;
8811
+ const readServiceActive = () => {
8812
+ if (!needsServiceState) return false;
8813
+ const service = getServiceStatus();
8814
+ return service.installed || service.loaded;
8815
+ };
8816
+ let serviceActive = readServiceActive();
8581
8817
  if (targets.length === 1) {
8582
8818
  if (serviceTargeted && !serviceActive) {
8583
8819
  console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
@@ -8603,8 +8839,7 @@ async function cmdReset(args) {
8603
8839
  console.log("\u5DF2\u53D6\u6D88");
8604
8840
  return;
8605
8841
  }
8606
- const current = getServiceStatus();
8607
- serviceActive = current.installed || current.loaded;
8842
+ serviceActive = readServiceActive();
8608
8843
  let cleanup = null;
8609
8844
  if (serviceActive) {
8610
8845
  if (serviceTargeted) cleanup = await uninstallService();
@@ -8619,10 +8854,10 @@ async function cmdReset(args) {
8619
8854
  hint: [MANUAL_PKILL_HINT]
8620
8855
  });
8621
8856
  }
8622
- if (!serviceActive && (cleanup.scriptError !== null || cleanup.pidError !== null)) {
8857
+ if (!serviceActive && cleanup.incomplete !== null) {
8623
8858
  warnResidueCleanup(cleanup, { mainOutcome: "\u91CD\u7F6E\u7EE7\u7EED\u6267\u884C", retryCommand: "mihomo-cli stop" });
8624
8859
  }
8625
- recordServiceStopped();
8860
+ bumpStopEpoch();
8626
8861
  }
8627
8862
  if (!needsStop && serviceTargeted && cleanup !== null && cleanup.remaining.length > 0) {
8628
8863
  printResidueWarning(cleanup.remaining);
@@ -8739,7 +8974,7 @@ async function cmdUninstall(args) {
8739
8974
  }
8740
8975
  console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo-cli install"));
8741
8976
  console.log(colors.gray("\u5F7B\u5E95\u79FB\u9664 mihomo-cli:"));
8742
- console.log(colors.gray(" mihomo-cli reset --full # \u5220\u9664\u5168\u90E8\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
8977
+ console.log(colors.gray(" mihomo-cli reset --full # \u5220\u9664\u53D7\u7BA1\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
8743
8978
  console.log(colors.gray(" npm uninstall -g mihomo-cli"));
8744
8979
  console.log("");
8745
8980
  }
@@ -8757,14 +8992,14 @@ async function cmdStop(args) {
8757
8992
  const pids = getMihomoPids();
8758
8993
  const needsServiceWork = status.loaded || status.installed && !status.disabled;
8759
8994
  if (!needsServiceWork && pids.length === 0) {
8760
- recordServiceStopped();
8995
+ bumpStopEpoch();
8761
8996
  console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
8762
8997
  return;
8763
8998
  }
8764
8999
  if (!needsServiceWork) {
8765
9000
  console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
8766
9001
  handleStopResult(await stop());
8767
- recordServiceStopped();
9002
+ bumpStopEpoch();
8768
9003
  console.log(colors.green("\u5DF2\u505C\u6B62"));
8769
9004
  return;
8770
9005
  }
@@ -9154,7 +9389,7 @@ var COMMANDS = [
9154
9389
  aliases: [],
9155
9390
  handler: cmdConfig,
9156
9391
  group: "config",
9157
- usage: [{ signature: "config [-j|--json] [--reveal]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9392
+ usage: [{ signature: "config [-j|--json] [--reveal]", description: "\u9884\u89C8\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u7F13\u5B58\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9158
9393
  },
9159
9394
  {
9160
9395
  name: "overwrite",
@@ -9182,7 +9417,7 @@ var COMMANDS = [
9182
9417
  aliases: [],
9183
9418
  handler: cmdKernel,
9184
9419
  group: "system",
9185
- usage: [{ signature: "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1A\u672C\u673A\u4EE3\u7406 > gh > \u76F4\u8FDE\uFF09" }]
9420
+ usage: [{ signature: "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u6309\u73AF\u5883\u9009\u62E9\u672C\u673A\u4EE3\u7406\u3001gh \u6216\u76F4\u8FDE\uFF09" }]
9186
9421
  },
9187
9422
  {
9188
9423
  name: "update",
@@ -9196,7 +9431,9 @@ var COMMANDS = [
9196
9431
  aliases: [],
9197
9432
  handler: cmdReset,
9198
9433
  group: "system",
9199
- usage: [{ signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199/\u670D\u52A1\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }]
9434
+ usage: [
9435
+ { signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199/\u670D\u52A1\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\u53D7\u7BA1\u76EE\u6807\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }
9436
+ ]
9200
9437
  },
9201
9438
  {
9202
9439
  name: "doctor",
@@ -9242,12 +9479,14 @@ function allCommandTokens() {
9242
9479
 
9243
9480
  // src/index.ts
9244
9481
  process.on("SIGINT", () => {
9482
+ terminateActiveChildren("SIGINT");
9245
9483
  if (!isSilentSigint()) {
9246
9484
  console.error("\n\u6B63\u5728\u9000\u51FA...");
9247
9485
  }
9248
9486
  process.exit(130);
9249
9487
  });
9250
9488
  process.on("SIGTERM", () => {
9489
+ terminateActiveChildren("SIGTERM");
9251
9490
  process.exit(143);
9252
9491
  });
9253
9492
  process.on("uncaughtException", (e) => {
@@ -9304,11 +9543,11 @@ function assertNotRoot(commandName) {
9304
9543
  });
9305
9544
  }
9306
9545
  function assertSupportedNodeVersion(commandName) {
9307
- if (!MIN_NODE_VERSION) return;
9546
+ if (!NODE_ENGINES) return;
9308
9547
  if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
9309
9548
  const current = process.versions.node;
9310
- if (compareVersions(current, MIN_NODE_VERSION) >= 0) return;
9311
- throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 >= ${MIN_NODE_VERSION}\uFF09`, {
9549
+ if (satisfies(current, NODE_ENGINES)) return;
9550
+ throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 ${NODE_ENGINES}\uFF09`, {
9312
9551
  label: "Node \u7248\u672C\u4E0D\u652F\u6301",
9313
9552
  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}`]
9314
9553
  });
@@ -9378,5 +9617,5 @@ main().catch((e) => {
9378
9617
  /*! Bundled license information:
9379
9618
 
9380
9619
  js-yaml/dist/js-yaml.mjs:
9381
- (*! js-yaml 5.3.0 https://github.com/nodeca/js-yaml @license MIT *)
9620
+ (*! js-yaml 5.4.3 https://github.com/nodeca/js-yaml @license MIT *)
9382
9621
  */