mihomo-cli 26.10.108 → 26.10.110

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.
Files changed (4) hide show
  1. package/CHANGELOG.md +27 -162
  2. package/README.md +17 -19
  3. package/dist/index.js +689 -731
  4. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import fs19 from "fs";
4
+ import fs18 from "fs";
5
5
 
6
6
  // node_modules/compare-versions/lib/esm/utils.js
7
7
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
@@ -238,7 +238,7 @@ function assertServiceLabelSafe() {
238
238
  if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
239
239
  throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
240
240
  label: "\u914D\u7F6E\u9519\u8BEF",
241
- 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\u5E76\u53C2\u4E0E\u6E05\u7406\u9057\u7559\u5B89\u88C5\u65F6\u7684 root \u5220\u9664\u8DEF\u5F84\u3002"]
241
+ 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
242
  });
243
243
  }
244
244
  }
@@ -1723,24 +1723,32 @@ function collectionTagName(state, event, defaultTagName) {
1723
1723
  function isMappingTag(tag) {
1724
1724
  return tag.nodeKind === "mapping";
1725
1725
  }
1726
+ function chargeMergeWork(state) {
1727
+ state.totalMergeKeys++;
1728
+ if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1729
+ }
1726
1730
  function mergeKeys(state, frame, source, sourceTag) {
1731
+ chargeMergeWork(state);
1727
1732
  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})`);
1733
+ chargeMergeWork(state);
1729
1734
  if (frame.tag.has(frame.value, sourceKey)) continue;
1730
1735
  const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
1731
1736
  if (err) throwError$1(state, err);
1732
- (frame.overridable ??= /* @__PURE__ */ new Set()).add(sourceKey);
1737
+ frame.overridable ??= /* @__PURE__ */ new Set();
1738
+ frame.overridable.add(sourceKey);
1733
1739
  }
1734
1740
  }
1735
1741
  function mergeSource(state, frame, source, sourceTag) {
1736
1742
  state.position = frame.keyPosition;
1737
1743
  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");
1744
+ else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
1745
+ if (source.length > 100) throwError$1(state, "abnormal merge sequence size");
1746
+ for (const element of source) {
1747
+ const elementTag = state.nodeTags.get(element);
1748
+ if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1749
+ mergeKeys(state, frame, element, elementTag);
1750
+ }
1751
+ } else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1744
1752
  }
1745
1753
  function addMappingValue(state, frame, key, value, tag) {
1746
1754
  state.position = frame.keyPosition;
@@ -2083,6 +2091,24 @@ function testDocumentSeparator(state, position = state.position) {
2083
2091
  }
2084
2092
  return false;
2085
2093
  }
2094
+ function skipByteOrderMark(state) {
2095
+ if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
2096
+ state.position++;
2097
+ state.lineStart = state.position;
2098
+ }
2099
+ }
2100
+ function testDocumentBoundary(state) {
2101
+ if (state.position !== state.lineStart) return false;
2102
+ if (testDocumentSeparator(state)) return true;
2103
+ if (state.input.charCodeAt(state.position) !== 65279) return false;
2104
+ const snapshot = snapshotState(state);
2105
+ skipByteOrderMark(state);
2106
+ skipSeparationSpace(state, true);
2107
+ const ch = state.input.charCodeAt(state.position);
2108
+ const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
2109
+ restoreState(state, snapshot);
2110
+ return result;
2111
+ }
2086
2112
  function skipUntilLineEnd(state) {
2087
2113
  let ch = state.input.charCodeAt(state.position);
2088
2114
  while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
@@ -2266,14 +2292,14 @@ function readBlockScalar(state, parentIndent, props) {
2266
2292
  } else if (column > 0) valueEnd = linePosition + column;
2267
2293
  break;
2268
2294
  }
2269
- if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break;
2295
+ if (testDocumentBoundary(state)) break;
2270
2296
  if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column);
2271
2297
  if (!detectedIndent && contentIndent === -1 && !isEol(first)) {
2272
2298
  if (first === 9 && column < parentIndent) {
2273
2299
  state.position = linePosition + column;
2274
2300
  throwError(state, "tab characters must not be used in indentation");
2275
2301
  }
2276
- if (column < maxLeadingIndent) {
2302
+ if (column >= parentIndent && column < maxLeadingIndent) {
2277
2303
  state.position = linePosition + column;
2278
2304
  throwError(state, "bad indentation of a mapping entry");
2279
2305
  }
@@ -2319,7 +2345,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
2319
2345
  const inFlow = nodeContext === CONTEXT_FLOW_IN;
2320
2346
  let multiline = false;
2321
2347
  while (ch !== 0) {
2322
- if (state.position === state.lineStart && testDocumentSeparator(state)) break;
2348
+ if (testDocumentBoundary(state)) break;
2323
2349
  if (ch === 58) {
2324
2350
  const following = state.input.charCodeAt(state.position + 1);
2325
2351
  if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break;
@@ -2483,13 +2509,16 @@ function readBlockMapping(state, nodeIndent, flowIndent, props) {
2483
2509
  ch = state.input.charCodeAt(++state.position);
2484
2510
  if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2485
2511
  if (!mappingOpened) {
2486
- restoreState(state, beforeKey);
2487
- addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2512
+ state.events.splice(beforeKey.eventsLength, 0, {
2513
+ type: EVENT_ID.MAPPING,
2514
+ start: beforeKey.position,
2515
+ anchorStart: props.anchorStart,
2516
+ anchorEnd: props.anchorEnd,
2517
+ tagStart: props.tagStart,
2518
+ tagEnd: props.tagEnd,
2519
+ style: COLLECTION_STYLE.BLOCK
2520
+ });
2488
2521
  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
2522
  }
2494
2523
  detected = true;
2495
2524
  atExplicitKey = false;
@@ -2676,7 +2705,7 @@ function readDocument(state) {
2676
2705
  const documentEvent = state.events[documentEventIndex];
2677
2706
  if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd;
2678
2707
  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");
2708
+ if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state)) throwError(state, "end of the stream or a document separator is expected");
2680
2709
  }
2681
2710
  function parseEvents(input, options) {
2682
2711
  const length = input.length;
@@ -2697,8 +2726,8 @@ function parseEvents(input, options) {
2697
2726
  };
2698
2727
  const nullpos = input.indexOf("\0");
2699
2728
  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
2729
  while (state.position < state.length) {
2730
+ skipByteOrderMark(state);
2702
2731
  skipSeparationSpace(state, true);
2703
2732
  if (state.position >= state.length) break;
2704
2733
  const documentStart = state.position;
@@ -2731,15 +2760,6 @@ function load(input, options) {
2731
2760
  if (documents.length === 1) return documents[0];
2732
2761
  throw new YAMLException("expected a single document in the stream, but found more");
2733
2762
  }
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
2763
  var INVALID = /* @__PURE__ */ Symbol("INVALID");
2744
2764
  function buildRepresentTypes(schema) {
2745
2765
  const defaultTags = new Set([
@@ -2788,8 +2808,6 @@ function build(state, object) {
2788
2808
  if (existing.anchor === void 0) existing.anchor = `ref_${state.refCounter++}`;
2789
2809
  return {
2790
2810
  kind: "alias",
2791
- tag: "",
2792
- style: new Style(),
2793
2811
  anchor: existing.anchor
2794
2812
  };
2795
2813
  }
@@ -2802,24 +2820,20 @@ function build(state, object) {
2802
2820
  }
2803
2821
  const { tag, tagName, implicitTag } = matched;
2804
2822
  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
- }
2823
+ if (tag.nodeKind === "scalar") return {
2824
+ kind: "scalar",
2825
+ tag: nodeTagName,
2826
+ tagged: !implicitTag,
2827
+ style: SCALAR_STYLE.PLAIN,
2828
+ value: tag.represent(object)
2829
+ };
2815
2830
  if (tag.nodeKind === "sequence") {
2816
2831
  const container = tag.represent(object);
2817
- const style2 = new Style();
2818
- style2.tagged = !implicitTag;
2819
2832
  const node2 = {
2820
2833
  kind: "sequence",
2821
2834
  tag: nodeTagName,
2822
- style: style2,
2835
+ tagged: !implicitTag,
2836
+ style: COLLECTION_STYLE.BLOCK,
2823
2837
  items: []
2824
2838
  };
2825
2839
  if (!state.noRefs) state.refs.set(object, node2);
@@ -2832,12 +2846,11 @@ function build(state, object) {
2832
2846
  return node2;
2833
2847
  }
2834
2848
  const map = tag.represent(object);
2835
- const style = new Style();
2836
- style.tagged = !implicitTag;
2837
2849
  const node = {
2838
2850
  kind: "mapping",
2839
2851
  tag: nodeTagName,
2840
- style,
2852
+ tagged: !implicitTag,
2853
+ style: COLLECTION_STYLE.BLOCK,
2841
2854
  items: []
2842
2855
  };
2843
2856
  if (!state.noRefs) state.refs.set(object, node);
@@ -2905,82 +2918,204 @@ function visit(documents, visitor) {
2905
2918
  isKey: false
2906
2919
  })) return;
2907
2920
  }
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
2921
+ function hasBit(mask, bit) {
2922
+ return (mask & 1 << bit) !== 0;
2923
+ }
2924
+ var DEFAULT_SCALAR_STYLE_RULES = {
2925
+ applyQuoteFlowKeysOption,
2926
+ doubleQuoteForInvisibles,
2927
+ doubleQuoteWhitespaceOnly,
2928
+ applyForceQuotesOption,
2929
+ tryLongOrMultilineAsBlock,
2930
+ quoteInvalidPlain,
2931
+ fallbackToDoubleQuoted
2962
2932
  };
2963
- function nodeTagShort(node) {
2964
- return node.style.tagged ? node.tag : tagNameShort(node.tag);
2933
+ function _preferredQuotedStyle(layout) {
2934
+ if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED)) return SCALAR_STYLE.SINGLE_QUOTED;
2935
+ return SCALAR_STYLE.DOUBLE_QUOTED;
2936
+ }
2937
+ function applyQuoteFlowKeysOption(layout) {
2938
+ if (!layout.presenterOptions.quoteFlowKeys) return;
2939
+ if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN) return;
2940
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2941
+ }
2942
+ function doubleQuoteForInvisibles(layout) {
2943
+ if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2944
+ }
2945
+ function doubleQuoteWhitespaceOnly(layout) {
2946
+ if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2947
+ }
2948
+ function applyForceQuotesOption(layout) {
2949
+ if (!layout.presenterOptions.forceQuotes) return;
2950
+ if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN) return;
2951
+ if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName) return;
2952
+ layout.style = layout.node.value.includes("\n") ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
2953
+ }
2954
+ function tryLongOrMultilineAsBlock(layout) {
2955
+ if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey) return;
2956
+ const value = layout.node.value;
2957
+ const multiline = value.indexOf("\n") !== -1;
2958
+ if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
2959
+ if (multiline) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2960
+ return;
2961
+ }
2962
+ const w = layout.presenterOptions.lineWidth;
2963
+ if (w === -1) {
2964
+ if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
2965
+ return;
2966
+ }
2967
+ const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
2968
+ let position = 0;
2969
+ let shouldFold = false;
2970
+ while (position <= value.length) {
2971
+ let lineEnd = value.length;
2972
+ const nextLineBreak = value.indexOf("\n", position);
2973
+ if (nextLineBreak !== -1) lineEnd = nextLineBreak;
2974
+ const line = value.slice(position, lineEnd);
2975
+ if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line)) shouldFold = true;
2976
+ if (nextLineBreak === -1) break;
2977
+ position = nextLineBreak + 1;
2978
+ }
2979
+ if (shouldFold) layout.style = SCALAR_STYLE.FOLDED_BLOCK;
2980
+ else if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
2981
+ }
2982
+ function quoteInvalidPlain(layout) {
2983
+ if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN)) layout.style = _preferredQuotedStyle(layout);
2984
+ }
2985
+ function fallbackToDoubleQuoted(layout) {
2986
+ if (!hasBit(layout.allowedStylesMask, layout.style)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2987
+ }
2988
+ function setBit(mask, bit) {
2989
+ return mask | 1 << bit;
2990
+ }
2991
+ var SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]";
2992
+ var SRC_B_CHAR = "[\\n\\r]";
2993
+ var SRC_C_BYTE_ORDER_MARK = "\\uFEFF";
2994
+ var SRC_S_WHITE = "[ \\t]";
2995
+ var SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
2996
+ var SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
2997
+ var SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]";
2998
+ var SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]";
2999
+ var SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]";
3000
+ var SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
3001
+ var SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
3002
+ var SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
3003
+ var SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
3004
+ var SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
3005
+ var SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
3006
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
3007
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
3008
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
3009
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
3010
+ var SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
3011
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
3012
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
3013
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
3014
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
3015
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
3016
+ var NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
3017
+ var NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
3018
+ var NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
3019
+ var NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
3020
+ var NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
3021
+ var NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
3022
+ var BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
3023
+ var C_FORBIDDEN_FIRST_LINE = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/;
3024
+ var C_FORBIDDEN_CONTENT = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/m;
3025
+ function canUsePlain(layout) {
3026
+ const str = layout.node.value;
3027
+ if (str !== "") {
3028
+ 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;
3029
+ if (layout.shiftOfFirstLine === 0 && C_FORBIDDEN_FIRST_LINE.test(str)) return false;
3030
+ if (layout.shiftOfContent === 0) {
3031
+ const firstLineBreak = str.indexOf("\n");
3032
+ if (firstLineBreak !== -1) {
3033
+ const content = str.slice(firstLineBreak + 1);
3034
+ if (C_FORBIDDEN_CONTENT.test(content)) return false;
3035
+ }
3036
+ }
3037
+ }
3038
+ const resolvedTag = layout.presenterOptions.schema.resolveImplicitScalarTag(str).tag.tagName;
3039
+ if (!layout.node.tagged && resolvedTag !== layout.node.tag) return false;
3040
+ if (!layout.node.tagged && str === "=" && resolvedTag === layout.presenterOptions.schema.defaultScalarTag.tagName) return false;
3041
+ return true;
2965
3042
  }
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
- };
3043
+ function canUseSingleQuoted(layout) {
3044
+ const str = layout.node.value;
3045
+ if (!(layout.isKey ? NB_SINGLE_ONE_LINE : NB_SINGLE_MULTI_LINE).test(str)) return false;
3046
+ if (/[ \t]\n|\n[ \t]/.test(str)) return false;
3047
+ if (!layout.isKey && layout.shiftOfContent === 0) {
3048
+ const firstLineBreak = str.indexOf("\n");
3049
+ if (firstLineBreak !== -1 && C_FORBIDDEN_CONTENT.test(str.slice(firstLineBreak + 1))) return false;
3050
+ }
3051
+ return true;
3052
+ }
3053
+ function canUseBlock(layout) {
3054
+ if (layout.flowOnly || !BLOCK_SCALAR_CONTENT.test(layout.node.value)) return false;
3055
+ const contentIndent = layout.shiftOfContent - layout.shiftOfParent;
3056
+ if (contentIndent < 1) return false;
3057
+ if (contentIndent > 9 && /^\n* /.test(layout.node.value)) return false;
3058
+ if (layout.shiftOfContent === 0 && C_FORBIDDEN_CONTENT.test(layout.node.value)) return false;
3059
+ return true;
3060
+ }
3061
+ function detectAllowedStyles(layout) {
3062
+ let mask = setBit(0, SCALAR_STYLE.DOUBLE_QUOTED);
3063
+ if (canUsePlain(layout)) mask = setBit(mask, SCALAR_STYLE.PLAIN);
3064
+ if (canUseSingleQuoted(layout)) mask = setBit(mask, SCALAR_STYLE.SINGLE_QUOTED);
3065
+ if (canUseBlock(layout)) mask = setBit(setBit(mask, SCALAR_STYLE.LITERAL_BLOCK), SCALAR_STYLE.FOLDED_BLOCK);
3066
+ layout.allowedStylesMask = mask;
3067
+ }
3068
+ function renderScalar(layout) {
3069
+ switch (layout.style) {
3070
+ case SCALAR_STYLE.PLAIN:
3071
+ return renderPlain(layout);
3072
+ case SCALAR_STYLE.SINGLE_QUOTED:
3073
+ return renderSingleQuoted(layout);
3074
+ case SCALAR_STYLE.LITERAL_BLOCK:
3075
+ return renderLiteralBlock(layout);
3076
+ case SCALAR_STYLE.FOLDED_BLOCK:
3077
+ return renderFoldedBlock(layout);
3078
+ case SCALAR_STYLE.DOUBLE_QUOTED:
3079
+ return renderDoubleQuoted(layout);
3080
+ }
3081
+ }
3082
+ function renderPlain(layout) {
3083
+ return encodeFlowBreaks(layout.node.value, layout.shiftOfContent);
3084
+ }
3085
+ function renderSingleQuoted(layout) {
3086
+ return `'${encodeFlowBreaks(layout.node.value, layout.shiftOfContent).replace(/'/g, "''")}'`;
2975
3087
  }
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}`;
3088
+ function renderLiteralBlock(layout) {
3089
+ const value = layout.node.value;
3090
+ return "|" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(value, layout.shiftOfContent));
3091
+ }
3092
+ function renderFoldedBlock(layout) {
3093
+ const value = layout.node.value;
3094
+ const w = layout.presenterOptions.lineWidth;
3095
+ let availableWidth = Infinity;
3096
+ if (w !== -1) availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
3097
+ return ">" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(foldBlockScalar(value, availableWidth), layout.shiftOfContent));
3098
+ }
3099
+ function renderDoubleQuoted(layout) {
3100
+ return `"${escapeString(layout.node.value)}"`;
3101
+ }
3102
+ function encodeFlowBreaks(string, shiftOfContent) {
3103
+ let nextLF = string.indexOf("\n");
3104
+ if (nextLF === -1) return string;
3105
+ const pad = " ".repeat(shiftOfContent);
3106
+ let result = string.slice(0, nextLF);
3107
+ const lineRe = /(\n+)([^\n]*)/g;
3108
+ lineRe.lastIndex = nextLF;
3109
+ let match;
3110
+ while (match = lineRe.exec(string)) {
3111
+ const breaks = match[1].length;
3112
+ const line = match[2];
3113
+ result += "\n".repeat(breaks + 1) + pad + line;
3114
+ }
3115
+ return result;
2981
3116
  }
2982
3117
  function indentString(string, spaces) {
2983
- const ind = " ".repeat(spaces);
3118
+ const indent = " ".repeat(spaces);
2984
3119
  let position = 0;
2985
3120
  let result = "";
2986
3121
  const length = string.length;
@@ -2994,191 +3129,26 @@ function indentString(string, spaces) {
2994
3129
  line = string.slice(position, next + 1);
2995
3130
  position = next + 1;
2996
3131
  }
2997
- if (line.length && line !== "\n") result += ind;
3132
+ if (line.length && line !== "\n") result += indent;
2998
3133
  result += line;
2999
3134
  }
3000
3135
  return result;
3001
3136
  }
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
3137
  function needIndentIndicator(string) {
3060
3138
  return /^\n* /.test(string);
3061
3139
  }
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) : "";
3140
+ function blockHeader(string, shiftOfParent, shiftOfContent) {
3141
+ const indentIndicator = needIndentIndicator(string) ? String(shiftOfContent - shiftOfParent) : "";
3139
3142
  const clip = string[string.length - 1] === "\n";
3140
3143
  return `${indentIndicator}${clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-"}
3141
3144
  `;
3142
3145
  }
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
3146
  function dropEndingNewline(string) {
3159
3147
  return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
3160
3148
  }
3161
3149
  function isMoreIndented(char) {
3162
3150
  return char === " " || char === " ";
3163
3151
  }
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
3152
  function foldLine(line, width) {
3183
3153
  if (line === "" || isMoreIndented(line[0])) return line;
3184
3154
  const breakRe = / [^ \t]/g;
@@ -3204,43 +3174,133 @@ ${line.slice(curr + 1)}`;
3204
3174
  else result += line.slice(start);
3205
3175
  return result.slice(1);
3206
3176
  }
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);
3177
+ function foldBlockScalar(string, width) {
3178
+ const lineRe = /(\n+)([^\n]*)/g;
3179
+ let nextLF = string.indexOf("\n");
3180
+ if (nextLF === -1) nextLF = string.length;
3181
+ lineRe.lastIndex = nextLF;
3182
+ let result = foldLine(string.slice(0, nextLF), width);
3183
+ let prevMoreIndented = string[0] === "\n" || isMoreIndented(string[0]);
3184
+ let moreIndented;
3185
+ let match;
3186
+ while (match = lineRe.exec(string)) {
3187
+ const prefix = match[1];
3188
+ const line = match[2];
3189
+ moreIndented = line !== "" && isMoreIndented(line[0]);
3190
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
3191
+ prevMoreIndented = moreIndented;
3223
3192
  }
3224
3193
  return result;
3225
3194
  }
3195
+ var CHARACTERS_TO_ESCAPE = /["\\\x00-\x1F\x7F-\xA0\u2028\u2029\uD800-\uDFFF\uFEFF\uFFFE\uFFFF]/gu;
3196
+ function escapeCharacter(character) {
3197
+ switch (character) {
3198
+ case "\0":
3199
+ return "\\0";
3200
+ case "\x07":
3201
+ return "\\a";
3202
+ case "\b":
3203
+ return "\\b";
3204
+ case " ":
3205
+ return "\\t";
3206
+ case "\n":
3207
+ return "\\n";
3208
+ case "\v":
3209
+ return "\\v";
3210
+ case "\f":
3211
+ return "\\f";
3212
+ case "\r":
3213
+ return "\\r";
3214
+ case "\x1B":
3215
+ return "\\e";
3216
+ case '"':
3217
+ return '\\"';
3218
+ case "\\":
3219
+ return "\\\\";
3220
+ case "\x85":
3221
+ return "\\N";
3222
+ case "\xA0":
3223
+ return "\\_";
3224
+ case "\u2028":
3225
+ return "\\L";
3226
+ case "\u2029":
3227
+ return "\\P";
3228
+ }
3229
+ const code = character.charCodeAt(0);
3230
+ const hex = code.toString(16).toUpperCase();
3231
+ if (code <= 255) return `\\x${"0".repeat(2 - hex.length)}${hex}`;
3232
+ return `\\u${"0".repeat(4 - hex.length)}${hex}`;
3233
+ }
3234
+ function escapeString(string) {
3235
+ return string.replace(CHARACTERS_TO_ESCAPE, escapeCharacter);
3236
+ }
3237
+ var CHAR_LINE_FEED = 10;
3238
+ var DEFAULT_PRESENTER_OPTIONS = {
3239
+ indent: 2,
3240
+ seqNoIndent: false,
3241
+ seqInlineFirst: true,
3242
+ lineWidth: 80,
3243
+ flowBracketPadding: false,
3244
+ flowSkipCommaSpace: false,
3245
+ flowSkipColonSpace: false,
3246
+ quoteFlowKeys: false,
3247
+ quoteStyle: "single",
3248
+ forceQuotes: false,
3249
+ scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
3250
+ tagBeforeAnchor: false
3251
+ };
3252
+ function nodeTagShort(node) {
3253
+ return node.tagged ? node.tag : tagNameShort(node.tag);
3254
+ }
3255
+ function createPresenterState(options) {
3256
+ const opts = {
3257
+ ...DEFAULT_PRESENTER_OPTIONS,
3258
+ ...options
3259
+ };
3260
+ if (opts.flowSkipColonSpace) opts.quoteFlowKeys = true;
3261
+ return {
3262
+ ...opts,
3263
+ defaultScalarTagName: opts.schema.defaultScalarTag.tagName,
3264
+ openEnded: false
3265
+ };
3266
+ }
3267
+ function generateNextLine(state, level) {
3268
+ return `
3269
+ ${" ".repeat(state.indent * level)}`;
3270
+ }
3271
+ function scalarLayout(state, node, parent, level, isKey, flowOnly) {
3272
+ return {
3273
+ node,
3274
+ parent,
3275
+ level,
3276
+ isKey,
3277
+ flowOnly,
3278
+ shiftOfParent: level === 0 ? -1 : state.indent * (level - 1),
3279
+ shiftOfContent: state.indent * Math.max(1, level),
3280
+ shiftOfFirstLine: level === 0 ? 0 : state.indent * level,
3281
+ presenterOptions: state,
3282
+ allowedStylesMask: 0,
3283
+ style: node.style
3284
+ };
3285
+ }
3226
3286
  function writeFlowSequence(state, level, node) {
3227
3287
  let result = "";
3228
3288
  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 ? " " : ""}`;
3289
+ const item = writeNode(state, level, node.items[index], node, {}).text;
3290
+ if (index > 0) result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3231
3291
  result += item;
3232
3292
  }
3233
- const pad = state.flowBracketPadding && result !== "" ? " " : "";
3293
+ const pad = state.flowBracketPadding && node.items.length > 0 ? " " : "";
3234
3294
  return `[${pad}${result}${pad}]`;
3235
3295
  }
3236
3296
  function writeBlockSequence(state, level, node, compact) {
3237
3297
  let result = "";
3238
3298
  for (let index = 0, length = node.items.length; index < length; index += 1) {
3239
- const item = writeNode(state, level + 1, node.items[index], {
3299
+ const item = writeNode(state, level + 1, node.items[index], node, {
3240
3300
  block: true,
3241
3301
  compact: state.seqInlineFirst,
3242
3302
  isblockseq: true
3243
- });
3303
+ }).text;
3244
3304
  if (!compact || result !== "") result += generateNextLine(state, level);
3245
3305
  if (item === "" || CHAR_LINE_FEED === item.charCodeAt(0)) result += "-";
3246
3306
  else result += "- ";
@@ -3250,70 +3310,51 @@ function writeBlockSequence(state, level, node, compact) {
3250
3310
  }
3251
3311
  function writeFlowMapping(state, level, node) {
3252
3312
  let result = "";
3253
- const items = sortMappingItems(state, node.items);
3254
- for (const { key, value } of items) {
3313
+ for (const { key, value } of node.items) {
3255
3314
  let pairBuffer = "";
3256
3315
  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, {});
3316
+ const keyRender = writeNode(state, level, key, node, { iskey: true });
3317
+ const keyText = keyRender.text;
3318
+ const valueText = writeNode(state, level, value, node, {}).text;
3262
3319
  const sep = state.flowSkipColonSpace || valueText === "" ? "" : " ";
3263
- pairBuffer += `${keyText}${state.quoteFlowKeys && !explicitPair ? '"' : ""}:${sep}${valueText}`;
3320
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
3321
+ const keyColonSep = key.kind === "alias" || keyIsBareProps ? " " : "";
3322
+ pairBuffer += `${keyText}${keyColonSep}:${sep}${valueText}`;
3264
3323
  result += pairBuffer;
3265
3324
  }
3266
3325
  const pad = state.flowBracketPadding && result !== "" ? " " : "";
3267
3326
  return `{${pad}${result}${pad}}`;
3268
3327
  }
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
3328
  function writeBlockMapping(state, level, node, compact) {
3289
3329
  let result = "";
3290
- const items = sortMappingItems(state, node.items);
3291
- for (let index = 0, length = items.length; index < length; index += 1) {
3330
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
3292
3331
  let pairBuffer = "";
3293
3332
  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, {
3333
+ const { key, value } = node.items[index];
3334
+ 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);
3335
+ const keyRender = keyIsBlock ? writeNode(state, level + 1, key, node, {
3297
3336
  block: true,
3298
3337
  compact: true,
3299
3338
  isblockseq: !cannotBeCompact(state, key, level + 1)
3300
- }) : writeNode(state, level + 1, key, {
3339
+ }) : writeNode(state, level + 1, key, node, {
3301
3340
  block: true,
3302
3341
  compact: true,
3303
3342
  iskey: true
3304
3343
  });
3344
+ const keyText = keyRender.text;
3305
3345
  const keyHasLineBreak = key.kind === "scalar" && key.value.indexOf("\n") !== -1;
3306
- const explicitPair = keyIsBlock || keyHasLineBreak || keyText.length > 1024;
3346
+ const keyIsTooLong = keyText.length > 1024 && /^[\s\S]{1025}/u.test(keyText);
3347
+ const explicitPair = keyIsBlock || keyHasLineBreak || keyIsTooLong;
3307
3348
  if (explicitPair) if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?";
3308
3349
  else pairBuffer += "? ";
3309
3350
  pairBuffer += keyText;
3310
3351
  if (explicitPair) pairBuffer += generateNextLine(state, level);
3311
- const valueText = writeNode(state, level + 1, value, {
3352
+ const valueText = writeNode(state, level + 1, value, node, {
3312
3353
  block: true,
3313
3354
  compact: explicitPair,
3314
3355
  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;
3356
+ }).text;
3357
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
3317
3358
  const keyColonSep = !explicitPair && (key.kind === "alias" || keyIsBareProps) ? " " : "";
3318
3359
  if (valueText === "" || CHAR_LINE_FEED === valueText.charCodeAt(0)) pairBuffer += `${keyColonSep}:`;
3319
3360
  else pairBuffer += `${keyColonSep}: `;
@@ -3323,29 +3364,41 @@ function writeBlockMapping(state, level, node, compact) {
3323
3364
  return result;
3324
3365
  }
3325
3366
  function cannotBeCompact(state, node, level) {
3326
- return node.style.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3367
+ if (node.kind === "alias") return true;
3368
+ return node.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3327
3369
  }
3328
- function writeNode(state, level, node, ctx) {
3329
- if (node.kind === "alias") return `*${node.anchor}`;
3370
+ function writeNode(state, level, node, parent, ctx) {
3371
+ if (node.kind === "alias") {
3372
+ state.openEnded = false;
3373
+ return {
3374
+ text: `*${node.anchor}`,
3375
+ noBody: false
3376
+ };
3377
+ }
3330
3378
  const { block = false, iskey = false, isblockseq = false } = ctx;
3331
3379
  let compact = ctx.compact ?? false;
3332
3380
  const hasAnchor = node.anchor !== void 0;
3333
3381
  if (cannotBeCompact(state, node, level)) compact = false;
3334
3382
  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;
3383
+ let shouldPrintTag = node.tagged;
3384
+ const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0;
3337
3385
  if (node.kind === "mapping") if (useBlockCollection) body = writeBlockMapping(state, level, node, compact);
3338
3386
  else body = writeFlowMapping(state, level, node);
3339
3387
  else if (node.kind === "sequence") if (useBlockCollection) if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact);
3340
3388
  else body = writeBlockSequence(state, level, node, compact);
3341
3389
  else body = writeFlowSequence(state, level, node);
3342
3390
  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
- }
3391
+ const layout = scalarLayout(state, node, parent, level, iskey, !block);
3392
+ detectAllowedStyles(layout);
3393
+ for (const rule of state.scalarStyleRules) rule(layout);
3394
+ body = renderScalar(layout);
3395
+ state.openEnded = (layout.style === SCALAR_STYLE.LITERAL_BLOCK || layout.style === SCALAR_STYLE.FOLDED_BLOCK) && (node.value === "\n" || node.value.endsWith("\n\n"));
3396
+ shouldPrintTag = node.tagged || body === "" && layout.flowOnly && parent?.kind === "sequence" && !hasAnchor || layout.style !== SCALAR_STYLE.PLAIN && node.tag !== state.defaultScalarTagName;
3397
+ }
3398
+ if ((node.kind === "mapping" || node.kind === "sequence") && !useBlockCollection) state.openEnded = false;
3348
3399
  if (useBlockCollection && compact && level > 0 && state.indent > 2) body = `${" ".repeat(state.indent - 2)}${body}`;
3400
+ const noBody = body === "";
3401
+ let text = body;
3349
3402
  if (shouldPrintTag || hasAnchor) {
3350
3403
  const props = [];
3351
3404
  const tag = shouldPrintTag ? nodeTagShort(node) : null;
@@ -3358,19 +3411,15 @@ function writeNode(state, level, node, ctx) {
3358
3411
  if (tag !== null) props.push(tag);
3359
3412
  }
3360
3413
  const sep = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
3361
- body = `${props.join(" ")}${sep}${body}`;
3414
+ text = `${props.join(" ")}${sep}${body}`;
3362
3415
  }
3363
- return body;
3416
+ return {
3417
+ text,
3418
+ noBody
3419
+ };
3364
3420
  }
3365
3421
  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";
3422
+ return (node.kind === "sequence" || node.kind === "mapping") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0 && !node.tagged && node.anchor === void 0;
3374
3423
  }
3375
3424
  function writeDocumentDirectives(doc) {
3376
3425
  let result = "";
@@ -3392,6 +3441,7 @@ function present(documents, options) {
3392
3441
  let previousEnded = false;
3393
3442
  for (let index = 0; index < documents.length; index += 1) {
3394
3443
  const doc = documents[index];
3444
+ state.openEnded = false;
3395
3445
  const directives = writeDocumentDirectives(doc);
3396
3446
  const hasDirectives = directives !== "";
3397
3447
  const marker = doc.explicitStart || hasDirectives || index > 0 && !previousEnded;
@@ -3399,18 +3449,18 @@ function present(documents, options) {
3399
3449
  if (doc.contents === null) {
3400
3450
  if (marker) result += "---\n";
3401
3451
  } else if (marker) {
3402
- const body = writeNode(state, 0, doc.contents, {
3452
+ const body = writeNode(state, 0, doc.contents, null, {
3403
3453
  block: true,
3404
3454
  compact: true
3405
- });
3455
+ }).text;
3406
3456
  const sep = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
3407
3457
  result += `---${sep}${body}
3408
3458
  `;
3409
- } else result += writeNode(state, 0, doc.contents, {
3459
+ } else result += writeNode(state, 0, doc.contents, null, {
3410
3460
  block: true,
3411
3461
  compact: true
3412
- }) + "\n";
3413
- previousEnded = doc.explicitEnd || doc.contents !== null && isOpenEnded(doc.contents);
3462
+ }).text + "\n";
3463
+ previousEnded = doc.explicitEnd || state.openEnded;
3414
3464
  if (previousEnded) result += "...\n";
3415
3465
  }
3416
3466
  return result;
@@ -3421,9 +3471,17 @@ var DEFAULT_DUMP_OPTIONS = {
3421
3471
  skipInvalid: false,
3422
3472
  noRefs: false,
3423
3473
  flowLevel: -1,
3474
+ sortKeys: false,
3424
3475
  transform: () => {
3425
3476
  }
3426
3477
  };
3478
+ function defaultCompareFn(a, b) {
3479
+ const x = String(a);
3480
+ const y = String(b);
3481
+ if (x < y) return -1;
3482
+ if (x > y) return 1;
3483
+ return 0;
3484
+ }
3427
3485
  function dump(input, options = {}) {
3428
3486
  const opts = {
3429
3487
  ...DEFAULT_DUMP_OPTIONS,
@@ -3435,9 +3493,16 @@ function dump(input, options = {}) {
3435
3493
  });
3436
3494
  if (opts.flowLevel >= 0) visit(documents, (node, ctx) => {
3437
3495
  if (ctx.depth < opts.flowLevel) return;
3438
- node.style.flow = true;
3496
+ if (node.kind === "sequence" || node.kind === "mapping") node.style = COLLECTION_STYLE.FLOW;
3439
3497
  return VISIT_SKIP;
3440
3498
  });
3499
+ if (opts.sortKeys) {
3500
+ const compareFn = opts.sortKeys === true ? defaultCompareFn : opts.sortKeys;
3501
+ visit(documents, (node) => {
3502
+ if (node.kind !== "mapping") return;
3503
+ node.items.sort((a, b) => compareFn(a.key.kind === "scalar" ? a.key.value : "", b.key.kind === "scalar" ? b.key.value : ""));
3504
+ });
3505
+ }
3441
3506
  opts.transform(documents);
3442
3507
  return present(documents, {
3443
3508
  ...pick(opts, Object.keys(DEFAULT_PRESENTER_OPTIONS)),
@@ -3538,10 +3603,7 @@ var PATHS = {
3538
3603
  */
3539
3604
  serviceStopEpoch: path.join(USER_DATA_DIR, "service-stop-epoch"),
3540
3605
  // 用户级 LaunchAgent(默认):gui/<uid> 域,全程免 sudo。随 homedir 走
3541
- userAgentPlist: path.join(os.homedir(), "Library/LaunchAgents", `${SERVICE_LABEL}.plist`),
3542
- // 旧版本(v3.0–v4.0 的 daemon on)装的系统级 LaunchDaemon:root:wheel 拥有。
3543
- // 本版不再往这里安装,仅用于识别并清理遗留安装(它带 KeepAlive,不清就是抢端口的幽灵)
3544
- systemDaemonPlist: path.join("/Library/LaunchDaemons", `${SERVICE_LABEL}.plist`)
3606
+ userAgentPlist: path.join(os.homedir(), "Library/LaunchAgents", `${SERVICE_LABEL}.plist`)
3545
3607
  };
3546
3608
  var DIRECTORY_TARGETS = {
3547
3609
  root: { path: null, label: "\u6839\u76EE\u5F55" },
@@ -4940,7 +5002,7 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
4940
5002
 
4941
5003
  // src/service.ts
4942
5004
  import { spawnSync as spawnSync7 } from "child_process";
4943
- import fs13 from "fs";
5005
+ import fs12 from "fs";
4944
5006
  import path7 from "path";
4945
5007
 
4946
5008
  // src/hot-reload.ts
@@ -5312,46 +5374,177 @@ function concludeHotReload(stopEpochBefore, stopEpochNow) {
5312
5374
  return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5313
5375
  }
5314
5376
 
5315
- // src/legacy-cleanup.ts
5316
- import fs11 from "fs";
5317
-
5318
- // src/process-stop.ts
5319
- import { spawnSync as spawnSync6 } from "child_process";
5320
- import fs10 from "fs";
5321
-
5322
- // src/sudo.ts
5323
- import { spawnSync as spawnSync5 } from "child_process";
5377
+ // src/log-files.ts
5324
5378
  import fs9 from "fs";
5325
5379
  import path5 from "path";
5326
- var SUDO_TIMEOUT_MS = 6e4;
5327
- var SudoAuthError = class extends Error {
5328
- constructor() {
5329
- super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
5330
- this.name = "SudoAuthError";
5331
- }
5332
- };
5333
- function describeSudoFailure(e) {
5334
- return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
5335
- }
5336
- function sudoExitToError(action, status, codeMessages) {
5337
- if (status === 1) return new SudoAuthError();
5338
- if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
5339
- const custom = codeMessages?.[status];
5340
- return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
5380
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
5381
+ var LOG_TAIL_LINES = 15;
5382
+ var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5383
+ function isArchiveLogFilename(filename) {
5384
+ return ARCHIVE_LOG_RE.test(filename);
5341
5385
  }
5342
- function sudoTimeoutError(action) {
5343
- return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
5386
+ function rotateAndCleanupLogs() {
5387
+ rotateLog();
5388
+ cleanupOldLogs();
5344
5389
  }
5345
- function runSudoScript(scriptBody, opts) {
5346
- if (!process.stdin.isTTY) {
5347
- throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
5348
- }
5349
- ensureDirs();
5350
- const scriptPath = path5.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
5351
- fs9.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5352
- fs9.chmodSync(scriptPath, 448);
5390
+ function readLogTail() {
5391
+ const TAIL_BYTES = 64 * 1024;
5392
+ let fd = null;
5353
5393
  try {
5354
- const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5394
+ const size = fs9.statSync(PATHS.logFile).size;
5395
+ if (size === 0) return [];
5396
+ const start = Math.max(0, size - TAIL_BYTES);
5397
+ const length = size - start;
5398
+ const buf = Buffer.alloc(length);
5399
+ fd = fs9.openSync(PATHS.logFile, "r");
5400
+ const bytesRead = fs9.readSync(fd, buf, 0, length, start);
5401
+ return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5402
+ } catch {
5403
+ return [];
5404
+ } finally {
5405
+ if (fd !== null) {
5406
+ try {
5407
+ fs9.closeSync(fd);
5408
+ } catch {
5409
+ }
5410
+ }
5411
+ }
5412
+ }
5413
+ var MAX_ARCHIVE_SEQ = 1e3;
5414
+ function allocateArchivePath() {
5415
+ const timestamp = formatLocalTimestamp();
5416
+ for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5417
+ const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5418
+ const archivePath = path5.join(DIRS.logs, name);
5419
+ let fd = null;
5420
+ try {
5421
+ fd = fs9.openSync(archivePath, "wx");
5422
+ } catch (e) {
5423
+ if (e.code === "EEXIST") continue;
5424
+ throw e;
5425
+ }
5426
+ try {
5427
+ fs9.closeSync(fd);
5428
+ } catch {
5429
+ }
5430
+ return archivePath;
5431
+ }
5432
+ throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
5433
+ label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5434
+ hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
5435
+ });
5436
+ }
5437
+ function rotateLog() {
5438
+ const logFile = PATHS.logFile;
5439
+ let stat;
5440
+ try {
5441
+ stat = fs9.statSync(logFile);
5442
+ } catch (e) {
5443
+ if (e.code === "ENOENT") return;
5444
+ throw e;
5445
+ }
5446
+ if (stat.size === 0) return;
5447
+ const rotatedPath = allocateArchivePath();
5448
+ try {
5449
+ fs9.renameSync(logFile, rotatedPath);
5450
+ } catch (e) {
5451
+ try {
5452
+ fs9.unlinkSync(rotatedPath);
5453
+ } catch {
5454
+ }
5455
+ if (e.code === "ENOENT") return;
5456
+ throw e;
5457
+ }
5458
+ }
5459
+ function cleanupOldLogs() {
5460
+ const logsDir = DIRS.logs;
5461
+ if (!fs9.existsSync(logsDir)) return;
5462
+ const files = fs9.readdirSync(logsDir);
5463
+ const now = Date.now();
5464
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5465
+ for (const file of files) {
5466
+ if (!isArchiveLogFilename(file)) continue;
5467
+ try {
5468
+ const filePath = path5.join(logsDir, file);
5469
+ const stat = fs9.statSync(filePath);
5470
+ if (now - stat.mtimeMs > maxAgeMs) {
5471
+ fs9.unlinkSync(filePath);
5472
+ }
5473
+ } catch {
5474
+ }
5475
+ }
5476
+ }
5477
+ function listLogs() {
5478
+ const logsDir = DIRS.logs;
5479
+ const result = { current: null, archives: [] };
5480
+ if (fs9.existsSync(PATHS.logFile)) {
5481
+ const stat = fs9.statSync(PATHS.logFile);
5482
+ result.current = {
5483
+ name: "mihomo.log (\u5F53\u524D)",
5484
+ path: PATHS.logFile,
5485
+ size: stat.size,
5486
+ mtime: stat.mtime,
5487
+ isCurrent: true
5488
+ };
5489
+ }
5490
+ if (!fs9.existsSync(logsDir)) return result;
5491
+ const files = fs9.readdirSync(logsDir);
5492
+ for (const file of files) {
5493
+ if (!isArchiveLogFilename(file)) continue;
5494
+ try {
5495
+ const filePath = path5.join(logsDir, file);
5496
+ const stat = fs9.statSync(filePath);
5497
+ result.archives.push({
5498
+ name: file,
5499
+ path: filePath,
5500
+ size: stat.size,
5501
+ mtime: stat.mtime,
5502
+ isCurrent: false
5503
+ });
5504
+ } catch {
5505
+ }
5506
+ }
5507
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5508
+ return result;
5509
+ }
5510
+
5511
+ // src/process-stop.ts
5512
+ import { spawnSync as spawnSync6 } from "child_process";
5513
+ import fs11 from "fs";
5514
+
5515
+ // src/sudo.ts
5516
+ import { spawnSync as spawnSync5 } from "child_process";
5517
+ import fs10 from "fs";
5518
+ import path6 from "path";
5519
+ var SUDO_TIMEOUT_MS = 6e4;
5520
+ var SudoAuthError = class extends Error {
5521
+ constructor() {
5522
+ super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
5523
+ this.name = "SudoAuthError";
5524
+ }
5525
+ };
5526
+ function describeSudoFailure(e) {
5527
+ return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
5528
+ }
5529
+ function sudoExitToError(action, status, codeMessages) {
5530
+ if (status === 1) return new SudoAuthError();
5531
+ if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
5532
+ const custom = codeMessages?.[status];
5533
+ return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
5534
+ }
5535
+ function sudoTimeoutError(action) {
5536
+ return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
5537
+ }
5538
+ function runSudoScript(scriptBody, opts) {
5539
+ if (!process.stdin.isTTY) {
5540
+ throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
5541
+ }
5542
+ ensureDirs();
5543
+ const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
5544
+ fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5545
+ fs10.chmodSync(scriptPath, 448);
5546
+ try {
5547
+ const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5355
5548
  if (result.error) {
5356
5549
  if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
5357
5550
  throw result.error;
@@ -5359,7 +5552,7 @@ function runSudoScript(scriptBody, opts) {
5359
5552
  if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
5360
5553
  } finally {
5361
5554
  try {
5362
- fs9.unlinkSync(scriptPath);
5555
+ fs10.unlinkSync(scriptPath);
5363
5556
  } catch {
5364
5557
  }
5365
5558
  }
@@ -5370,7 +5563,7 @@ var PROCESS_WAIT_ATTEMPTS = 50;
5370
5563
  var PROCESS_WAIT_INTERVAL = 100;
5371
5564
  var BATCH_KILL_THRESHOLD = 3;
5372
5565
  function clearRuntime() {
5373
- if (fs10.existsSync(DIRS.runtime)) {
5566
+ if (fs11.existsSync(DIRS.runtime)) {
5374
5567
  rmrf(DIRS.runtime);
5375
5568
  }
5376
5569
  ensureDirs();
@@ -5389,7 +5582,7 @@ function warnPidCleanupFailed(err) {
5389
5582
  }
5390
5583
  function clearPid() {
5391
5584
  try {
5392
- fs10.unlinkSync(PATHS.pidFile);
5585
+ fs11.unlinkSync(PATHS.pidFile);
5393
5586
  return null;
5394
5587
  } catch (e) {
5395
5588
  if (e.code === "ENOENT") return null;
@@ -5406,16 +5599,10 @@ function pidAlive(pid) {
5406
5599
  }
5407
5600
  async function waitUntilNoMihomo(pids) {
5408
5601
  for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
5409
- const stillThere = pids ? pids.some(pidAlive) : getMihomoPids().length > 0;
5410
- if (!stillThere) return;
5602
+ if (!pids.some(pidAlive)) return;
5411
5603
  await sleep(PROCESS_WAIT_INTERVAL);
5412
5604
  }
5413
5605
  }
5414
- async function reapPidWhenQuiet() {
5415
- await waitUntilNoMihomo();
5416
- if (getMihomoPids().length > 0) return null;
5417
- return clearPid();
5418
- }
5419
5606
  function killProcess(pid) {
5420
5607
  try {
5421
5608
  process.kill(pid, "SIGKILL");
@@ -5491,47 +5678,15 @@ async function cleanupAll() {
5491
5678
  const pidError = remaining.length === 0 ? clearPid() : null;
5492
5679
  return { killed: killedCount, failed: failedPids.length, remaining, scriptError, pidError };
5493
5680
  }
5494
- async function stop() {
5495
- const allPids = getMihomoPids();
5496
- if (allPids.length === 0) {
5497
- warnPidCleanupFailed(clearPid());
5498
- clearRuntime();
5499
- return {};
5500
- }
5501
- const result = await cleanupAll();
5502
- if (result.remaining.length === 0) {
5503
- warnPidCleanupFailed(result.pidError);
5504
- if (result.scriptError) {
5505
- 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`));
5506
- }
5507
- }
5508
- const remaining = result.remaining;
5509
- if (remaining.length > 0) {
5510
- console.log("");
5511
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
5512
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5513
- console.log(MANUAL_PKILL_HINT);
5514
- console.log("");
5515
- return { remaining };
5516
- }
5517
- clearRuntime();
5518
- return {};
5519
- }
5520
-
5521
- // src/legacy-cleanup.ts
5522
- function detectLegacySystemInstall() {
5523
- return fs11.existsSync(PATHS.systemDaemonPlist);
5524
- }
5525
5681
  function buildRootResidueCleanupError(result, ctx) {
5526
5682
  const { scriptError, pidError } = result;
5527
- const cancelled = scriptError instanceof SudoAuthError;
5528
5683
  const hasKernelResidue = result.remaining.length > 0;
5529
5684
  const pidList = `PID ${result.remaining.join(", ")}`;
5530
5685
  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";
5531
5686
  const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
5532
5687
  hint.push(hasKernelResidue || scriptError ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
5533
- if (cancelled) {
5534
- return new CliError("\u7BA1\u7406\u5458\u5BC6\u7801\u672A\u8F93\u5165\u6216\u6709\u8BEF\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406", { label: "\u5DF2\u53D6\u6D88", hint });
5688
+ if (scriptError instanceof SudoAuthError) {
5689
+ return new CliError(`${describeSudoFailure(scriptError)}\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406`, { label: "\u5DF2\u53D6\u6D88", hint });
5535
5690
  }
5536
5691
  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 });
5537
5692
  }
@@ -5551,198 +5706,31 @@ async function cleanupKernelsOrThrow(ctx) {
5551
5706
  if (verdict === "warn") warnResidueCleanup(result, ctx);
5552
5707
  return result;
5553
5708
  }
5554
- function buildLegacyCleanupScript() {
5555
- const toleratedBootoutCodes = [0, ...BOOTOUT_NOT_LOADED_CODES].map((code) => `[ $bootout_code -ne ${code} ]`).join(" && ");
5556
- return [
5557
- "#!/bin/bash",
5558
- // bootout 退出码分级:0=成功,3/113=未装载(daemon 已不在,正常);其余是真实
5559
- // 失败,不能 || true 吞掉后照样 rm plist 报「已清理」
5560
- `bootout_code=0`,
5561
- `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
5562
- `if ${toleratedBootoutCodes}; then`,
5563
- ` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
5564
- ` exit 3`,
5565
- `fi`,
5566
- `rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
5567
- // rm -f 静默吞错:删失败(文件系统只读等极端态)不声不响,而残留 plist 会在
5568
- // 下次开机被 launchd 重新加载(KeepAlive 幽灵复活)——删除结果必须复核可见
5569
- `if [ -e ${shellQuote(PATHS.systemDaemonPlist)} ]; then`,
5570
- ` echo "\u9057\u7559\u670D\u52A1 plist \u5220\u9664\u5931\u8D25\uFF08rm \u540E\u4ECD\u5B58\u5728\uFF09" >&2`,
5571
- ` exit 4`,
5572
- `fi`,
5573
- `chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
5574
- `chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
5575
- "exit 0",
5576
- ""
5577
- ].join("\n");
5578
- }
5579
- function cleanupLegacySystemInstall() {
5580
- assertServiceLabelSafe();
5581
- runSudoScript(buildLegacyCleanupScript(), {
5582
- action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
5583
- file: "legacy-cleanup.sh",
5584
- // 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
5585
- // 4 = plist rm 后复核仍存在(rm -f 静默失败的可见化);
5586
- // 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
5587
- codeMessages: { 3: "launchctl bootout \u672A\u80FD\u5378\u8F7D\u65E7 daemon\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09", 4: "\u672A\u80FD\u5220\u9664\u9057\u7559\u670D\u52A1\u7684 plist\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09" }
5588
- });
5589
- }
5590
- async function cleanupLegacyInstallOrThrow() {
5591
- try {
5592
- cleanupLegacySystemInstall();
5593
- } catch (e) {
5594
- if (e instanceof CliError) throw e;
5595
- throw new CliError(e.message, {
5596
- label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5597
- hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5598
- });
5599
- }
5600
- const pidError = await reapPidWhenQuiet();
5601
- if (pidError) {
5602
- console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(pidError)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5603
- }
5604
- }
5605
- async function announceLegacyCleanupOrThrow(reason, extraNotes = []) {
5606
- console.log(colors.yellow(`\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C${reason}`));
5607
- for (const note of extraNotes) console.log(colors.gray(note));
5608
- console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
5609
- await cleanupLegacyInstallOrThrow();
5610
- console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
5611
- console.log("");
5612
- }
5613
-
5614
- // src/log-files.ts
5615
- import fs12 from "fs";
5616
- import path6 from "path";
5617
- var DEFAULT_LOG_RETENTION_DAYS = 7;
5618
- var LOG_TAIL_LINES = 15;
5619
- var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5620
- function isArchiveLogFilename(filename) {
5621
- return ARCHIVE_LOG_RE.test(filename);
5622
- }
5623
- function rotateAndCleanupLogs() {
5624
- rotateLog();
5625
- cleanupOldLogs();
5626
- }
5627
- function readLogTail() {
5628
- const TAIL_BYTES = 64 * 1024;
5629
- let fd = null;
5630
- try {
5631
- const size = fs12.statSync(PATHS.logFile).size;
5632
- if (size === 0) return [];
5633
- const start = Math.max(0, size - TAIL_BYTES);
5634
- const length = size - start;
5635
- const buf = Buffer.alloc(length);
5636
- fd = fs12.openSync(PATHS.logFile, "r");
5637
- const bytesRead = fs12.readSync(fd, buf, 0, length, start);
5638
- return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5639
- } catch {
5640
- return [];
5641
- } finally {
5642
- if (fd !== null) {
5643
- try {
5644
- fs12.closeSync(fd);
5645
- } catch {
5646
- }
5647
- }
5648
- }
5649
- }
5650
- var MAX_ARCHIVE_SEQ = 1e3;
5651
- function allocateArchivePath() {
5652
- const timestamp = formatLocalTimestamp();
5653
- for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5654
- const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5655
- const archivePath = path6.join(DIRS.logs, name);
5656
- let fd = null;
5657
- try {
5658
- fd = fs12.openSync(archivePath, "wx");
5659
- } catch (e) {
5660
- if (e.code === "EEXIST") continue;
5661
- throw e;
5662
- }
5663
- try {
5664
- fs12.closeSync(fd);
5665
- } catch {
5666
- }
5667
- return archivePath;
5668
- }
5669
- throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
5670
- label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5671
- hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
5672
- });
5673
- }
5674
- function rotateLog() {
5675
- const logFile = PATHS.logFile;
5676
- let stat;
5677
- try {
5678
- stat = fs12.statSync(logFile);
5679
- } catch (e) {
5680
- if (e.code === "ENOENT") return;
5681
- throw e;
5682
- }
5683
- if (stat.size === 0) return;
5684
- const rotatedPath = allocateArchivePath();
5685
- try {
5686
- fs12.renameSync(logFile, rotatedPath);
5687
- } catch (e) {
5688
- try {
5689
- fs12.unlinkSync(rotatedPath);
5690
- } catch {
5691
- }
5692
- if (e.code === "ENOENT") return;
5693
- throw e;
5709
+ async function stop() {
5710
+ const allPids = getMihomoPids();
5711
+ if (allPids.length === 0) {
5712
+ warnPidCleanupFailed(clearPid());
5713
+ clearRuntime();
5714
+ return {};
5694
5715
  }
5695
- }
5696
- function cleanupOldLogs() {
5697
- const logsDir = DIRS.logs;
5698
- if (!fs12.existsSync(logsDir)) return;
5699
- const files = fs12.readdirSync(logsDir);
5700
- const now = Date.now();
5701
- const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5702
- for (const file of files) {
5703
- if (!isArchiveLogFilename(file)) continue;
5704
- try {
5705
- const filePath = path6.join(logsDir, file);
5706
- const stat = fs12.statSync(filePath);
5707
- if (now - stat.mtimeMs > maxAgeMs) {
5708
- fs12.unlinkSync(filePath);
5709
- }
5710
- } catch {
5716
+ const result = await cleanupAll();
5717
+ if (result.remaining.length === 0) {
5718
+ warnPidCleanupFailed(result.pidError);
5719
+ if (result.scriptError) {
5720
+ 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`));
5711
5721
  }
5712
5722
  }
5713
- }
5714
- function listLogs() {
5715
- const logsDir = DIRS.logs;
5716
- const result = { current: null, archives: [] };
5717
- if (fs12.existsSync(PATHS.logFile)) {
5718
- const stat = fs12.statSync(PATHS.logFile);
5719
- result.current = {
5720
- name: "mihomo.log (\u5F53\u524D)",
5721
- path: PATHS.logFile,
5722
- size: stat.size,
5723
- mtime: stat.mtime,
5724
- isCurrent: true
5725
- };
5726
- }
5727
- if (!fs12.existsSync(logsDir)) return result;
5728
- const files = fs12.readdirSync(logsDir);
5729
- for (const file of files) {
5730
- if (!isArchiveLogFilename(file)) continue;
5731
- try {
5732
- const filePath = path6.join(logsDir, file);
5733
- const stat = fs12.statSync(filePath);
5734
- result.archives.push({
5735
- name: file,
5736
- path: filePath,
5737
- size: stat.size,
5738
- mtime: stat.mtime,
5739
- isCurrent: false
5740
- });
5741
- } catch {
5742
- }
5723
+ const remaining = result.remaining;
5724
+ if (remaining.length > 0) {
5725
+ console.log("");
5726
+ console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
5727
+ console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5728
+ console.log(MANUAL_PKILL_HINT);
5729
+ console.log("");
5730
+ return { remaining };
5743
5731
  }
5744
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5745
- return result;
5732
+ clearRuntime();
5733
+ return {};
5746
5734
  }
5747
5735
 
5748
5736
  // src/service.ts
@@ -5830,14 +5818,14 @@ function tunBlockedByConcurrentStart() {
5830
5818
  function ensureServiceSymlink() {
5831
5819
  assertKernelInstalled();
5832
5820
  try {
5833
- const current = fs13.readlinkSync(PATHS.serviceBinary);
5821
+ const current = fs12.readlinkSync(PATHS.serviceBinary);
5834
5822
  if (current === "mihomo") return;
5835
- fs13.unlinkSync(PATHS.serviceBinary);
5823
+ fs12.unlinkSync(PATHS.serviceBinary);
5836
5824
  } catch (e) {
5837
5825
  const code = e.code;
5838
5826
  if (code === "EINVAL") {
5839
5827
  try {
5840
- fs13.unlinkSync(PATHS.serviceBinary);
5828
+ fs12.unlinkSync(PATHS.serviceBinary);
5841
5829
  } catch {
5842
5830
  }
5843
5831
  } else if (code !== "ENOENT") {
@@ -5845,12 +5833,12 @@ function ensureServiceSymlink() {
5845
5833
  }
5846
5834
  }
5847
5835
  try {
5848
- fs13.symlinkSync("mihomo", PATHS.serviceBinary);
5836
+ fs12.symlinkSync("mihomo", PATHS.serviceBinary);
5849
5837
  } catch (e) {
5850
5838
  if (e.code !== "EEXIST") throw e;
5851
5839
  let existing;
5852
5840
  try {
5853
- existing = fs13.readlinkSync(PATHS.serviceBinary);
5841
+ existing = fs12.readlinkSync(PATHS.serviceBinary);
5854
5842
  } catch {
5855
5843
  throw e;
5856
5844
  }
@@ -5890,8 +5878,8 @@ async function installService(wasRunning) {
5890
5878
  }
5891
5879
  bootoutService();
5892
5880
  await waitUntilUnloaded();
5893
- fs13.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5894
- atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
5881
+ fs12.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5882
+ atomicWriteFileSync(PATHS.userAgentPlist, fs12.readFileSync(stagePath, "utf8"), { mode: 420 });
5895
5883
  if (wasRunning) {
5896
5884
  withFileLock(PATHS.serviceLock, () => {
5897
5885
  if (startAbortedByConcurrentStop()) {
@@ -5904,7 +5892,7 @@ async function installService(wasRunning) {
5904
5892
  }
5905
5893
  } finally {
5906
5894
  try {
5907
- fs13.unlinkSync(stagePath);
5895
+ fs12.unlinkSync(stagePath);
5908
5896
  } catch {
5909
5897
  }
5910
5898
  }
@@ -5972,13 +5960,13 @@ async function uninstallService() {
5972
5960
  assertServiceLabelSafe();
5973
5961
  await bootoutAndDisableInLock();
5974
5962
  try {
5975
- fs13.rmSync(PATHS.userAgentPlist, { force: true });
5963
+ fs12.rmSync(PATHS.userAgentPlist, { force: true });
5976
5964
  } catch (e) {
5977
5965
  throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
5978
5966
  }
5979
5967
  const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
5980
5968
  try {
5981
- fs13.rmSync(PATHS.serviceBinary, { force: true });
5969
+ fs12.rmSync(PATHS.serviceBinary, { force: true });
5982
5970
  } catch {
5983
5971
  }
5984
5972
  return cleanup;
@@ -5995,8 +5983,8 @@ async function restartService(prefetched) {
5995
5983
  if (oversized) {
5996
5984
  const archiveFile = allocateArchivePath();
5997
5985
  try {
5998
- fs13.copyFileSync(PATHS.logFile, archiveFile);
5999
- fs13.writeFileSync(PATHS.logFile, "");
5986
+ fs12.copyFileSync(PATHS.logFile, archiveFile);
5987
+ fs12.writeFileSync(PATHS.logFile, "");
6000
5988
  } catch {
6001
5989
  }
6002
5990
  }
@@ -6698,7 +6686,7 @@ function viewLogWithTail(logPath, options) {
6698
6686
  import readline from "readline";
6699
6687
 
6700
6688
  // src/process-start.ts
6701
- import fs14 from "fs";
6689
+ import fs13 from "fs";
6702
6690
  var TUN_MODE_POST_WAIT_MS = 500;
6703
6691
  function buildTunLaunchScript() {
6704
6692
  const binary = shellQuote(PATHS.mihomoBinary);
@@ -6773,12 +6761,12 @@ async function startTun(prefetched) {
6773
6761
  }
6774
6762
  rotateAndCleanupLogs();
6775
6763
  const logFile = PATHS.logFile;
6776
- if (fs14.existsSync(logFile)) {
6764
+ if (fs13.existsSync(logFile)) {
6777
6765
  try {
6778
- fs14.accessSync(logFile, fs14.constants.W_OK);
6766
+ fs13.accessSync(logFile, fs13.constants.W_OK);
6779
6767
  } catch {
6780
6768
  try {
6781
- fs14.unlinkSync(logFile);
6769
+ fs13.unlinkSync(logFile);
6782
6770
  } catch {
6783
6771
  }
6784
6772
  }
@@ -7027,7 +7015,7 @@ function buildStatusJson(args) {
7027
7015
  return {
7028
7016
  version: VERSION,
7029
7017
  running: args.running,
7030
- connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
7018
+ connectivity: args.probe,
7031
7019
  mode: args.info ? deriveRuntimeMode(args.info) : null,
7032
7020
  carrier: args.kind,
7033
7021
  pid: args.pid,
@@ -7067,8 +7055,7 @@ function buildStatusJson(args) {
7067
7055
  running: args.service.running,
7068
7056
  disabled: args.service.disabled,
7069
7057
  lastExitCode: args.service.lastExitCode,
7070
- lastTerminatingSignal: args.service.lastTerminatingSignal,
7071
- legacySystemInstall: args.legacy
7058
+ lastTerminatingSignal: args.service.lastTerminatingSignal
7072
7059
  }
7073
7060
  };
7074
7061
  }
@@ -7102,7 +7089,6 @@ async function printStatus(args = []) {
7102
7089
  }
7103
7090
  }
7104
7091
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
7105
- const legacy = detectLegacySystemInstall();
7106
7092
  const controllerPort = getPortsOrNull()?.controller ?? null;
7107
7093
  const { running, pid, kind } = state;
7108
7094
  let probe = null;
@@ -7126,8 +7112,7 @@ async function printStatus(args = []) {
7126
7112
  // 不按 match、不随全局开关变空),applied 才是本次真正参与合并的
7127
7113
  overwriteFiles,
7128
7114
  overwriteBroken,
7129
- service,
7130
- legacy
7115
+ service
7131
7116
  }),
7132
7117
  null,
7133
7118
  2
@@ -7206,7 +7191,7 @@ async function printStatus(args = []) {
7206
7191
  console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo-cli sub add <url>)")}`);
7207
7192
  }
7208
7193
  printOverwriteLines(overwriteEnabled, overwriteFiles, overwriteBroken);
7209
- printServiceLines(service, legacy);
7194
+ printServiceLines(service);
7210
7195
  if (kind === "tun") {
7211
7196
  console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF1B\u505C\u6B62: mihomo-cli stop\uFF08\u4E4B\u540E mihomo-cli start \u6062\u590D Mixed\uFF09"));
7212
7197
  }
@@ -7234,7 +7219,7 @@ function printOverwriteLines(enabled, files, broken) {
7234
7219
  for (const line of b.hint) console.log(colors.gray(` ${line}`));
7235
7220
  }
7236
7221
  }
7237
- function printServiceLines(service, legacy) {
7222
+ function printServiceLines(service) {
7238
7223
  if (!service.installed && !service.loaded) {
7239
7224
  console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo-cli install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
7240
7225
  } else if (!service.installed) {
@@ -7245,10 +7230,6 @@ function printServiceLines(service, legacy) {
7245
7230
  console.log(`${colors.gray("\u670D\u52A1: ")}${colors.green("\u5DF2\u5B89\u88C5")}`);
7246
7231
  printAutoStart(service);
7247
7232
  }
7248
- if (legacy) {
7249
- console.log(colors.yellow(" \u5F02\u5E38: \u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
7250
- console.log(colors.gray(" \u5B83\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u6E05\u7406: mihomo-cli uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
7251
- }
7252
7233
  }
7253
7234
  function printAutoStart(service) {
7254
7235
  const autoStart = service.disabled ? colors.yellow("\u5DF2\u5173\u95ED") : colors.green("\u5DF2\u5F00\u542F");
@@ -7274,9 +7255,6 @@ async function cmdStart(args) {
7274
7255
  assertKernelInstalled();
7275
7256
  const serviceBefore = getServiceStatus();
7276
7257
  if (targetMode === "tun") {
7277
- if (detectLegacySystemInstall()) {
7278
- await announceLegacyCleanupOrThrow("\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406");
7279
- }
7280
7258
  if (serviceBefore.loaded) {
7281
7259
  throw tunBlockedByRunningService();
7282
7260
  }
@@ -7457,11 +7435,11 @@ async function cmdDirectory(args) {
7457
7435
  }
7458
7436
 
7459
7437
  // src/commands/doctor.ts
7460
- import fs16 from "fs";
7438
+ import fs15 from "fs";
7461
7439
 
7462
7440
  // src/kernel.ts
7463
7441
  import { execFile as execFile3, spawnSync as spawnSync9 } from "child_process";
7464
- import fs15 from "fs";
7442
+ import fs14 from "fs";
7465
7443
  import path8 from "path";
7466
7444
  import { promisify as promisify3 } from "util";
7467
7445
  var GITHUB_REPO = "MetaCubeX/mihomo";
@@ -7756,7 +7734,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7756
7734
  if (mirrorIneffective) {
7757
7735
  console.warn("\u8B66\u544A: \u955C\u50CF\u524D\u7F00\u672A\u80FD\u4F5C\u7528\u4E8E\u8BE5\u8D44\u4EA7\u5730\u5740\uFF08host \u975E github.com\uFF09\uFF0C\u672C\u6B21\u4E3A\u76F4\u8FDE\u4E0B\u8F7D\uFF1B\u82E5\u76F4\u8FDE\u8D85\u65F6\u53EF\u6539\u7528 gh \u901A\u9053\uFF08mihomo-cli kernel\uFF09");
7758
7736
  }
7759
- const tempDir = fs15.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7737
+ const tempDir = fs14.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7760
7738
  const tempPath = path8.join(tempDir, path8.basename(asset.name));
7761
7739
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
7762
7740
  try {
@@ -7811,11 +7789,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7811
7789
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
7812
7790
  }
7813
7791
  }
7814
- if (!fs15.existsSync(tempPath)) {
7792
+ if (!fs14.existsSync(tempPath)) {
7815
7793
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
7816
7794
  }
7817
7795
  if (Number.isFinite(asset.size) && asset.size > 0) {
7818
- const actual = fs15.statSync(tempPath).size;
7796
+ const actual = fs14.statSync(tempPath).size;
7819
7797
  if (actual !== asset.size) {
7820
7798
  throw new Error(
7821
7799
  `\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
@@ -7833,11 +7811,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7833
7811
  const gzipResult = spawnSync9("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7834
7812
  if (gzipResult.error) throw gzipResult.error;
7835
7813
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
7836
- fs15.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7814
+ fs14.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7837
7815
  if (progressCallback) {
7838
7816
  progressCallback("\u6821\u9A8C\u5185\u6838...");
7839
7817
  }
7840
- fs15.chmodSync(foundBinary, 493);
7818
+ fs14.chmodSync(foundBinary, 493);
7841
7819
  const probe = probeKernelVersion(foundBinary);
7842
7820
  if (probe.spawnError || probe.status !== 0 || probe.version === null) {
7843
7821
  throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
@@ -7850,12 +7828,12 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7850
7828
  throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
7851
7829
  }
7852
7830
  const targetPath = PATHS.mihomoBinary;
7853
- fs15.renameSync(foundBinary, targetPath);
7854
- fs15.chmodSync(targetPath, 493);
7831
+ fs14.renameSync(foundBinary, targetPath);
7832
+ fs14.chmodSync(targetPath, 493);
7855
7833
  return { version: latest.tag_name, path: targetPath };
7856
7834
  } finally {
7857
7835
  try {
7858
- fs15.rmSync(tempDir, { recursive: true, force: true });
7836
+ fs14.rmSync(tempDir, { recursive: true, force: true });
7859
7837
  } catch {
7860
7838
  }
7861
7839
  }
@@ -8017,20 +7995,20 @@ async function collectChecks() {
8017
7995
  } else {
8018
7996
  push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
8019
7997
  }
8020
- if (fs16.existsSync(KERNEL_SELF_UPDATE_DIR)) {
7998
+ if (fs15.existsSync(KERNEL_SELF_UPDATE_DIR)) {
8021
7999
  push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
8022
8000
  }
8023
- if (fs16.existsSync(KERNEL_SELF_BACKUP_DIR)) {
8001
+ if (fs15.existsSync(KERNEL_SELF_BACKUP_DIR)) {
8024
8002
  push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf ${KERNEL_SELF_BACKUP_DIR}\uFF09`);
8025
8003
  }
8026
8004
  try {
8027
- fs16.accessSync(USER_DATA_DIR, fs16.constants.W_OK);
8005
+ fs15.accessSync(USER_DATA_DIR, fs15.constants.W_OK);
8028
8006
  push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
8029
8007
  } catch {
8030
8008
  push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
8031
8009
  }
8032
- if (fs16.existsSync(PATHS.settingsFile)) {
8033
- if (isValidSettingsContent(fs16.readFileSync(PATHS.settingsFile, "utf8"))) {
8010
+ if (fs15.existsSync(PATHS.settingsFile)) {
8011
+ if (isValidSettingsContent(fs15.readFileSync(PATHS.settingsFile, "utf8"))) {
8034
8012
  push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
8035
8013
  } else {
8036
8014
  push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
@@ -8063,10 +8041,7 @@ async function collectChecks() {
8063
8041
  }
8064
8042
  }
8065
8043
  }
8066
- const legacy = detectLegacySystemInstall();
8067
- if (legacy) {
8068
- push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo-cli uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
8069
- } else if (!earlyService.installed && !earlyService.loaded) {
8044
+ if (!earlyService.installed && !earlyService.loaded) {
8070
8045
  push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo-cli install");
8071
8046
  } else if (!earlyService.installed) {
8072
8047
  push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo-cli uninstall");
@@ -8379,7 +8354,7 @@ function buildDownloadFailureError(attempts, isExplicitProxy) {
8379
8354
  ...attempts.map((a) => ` ${channelLabel(a.channel, isExplicitProxy)}: ${firstLine(a.error.message)}`),
8380
8355
  "",
8381
8356
  "\u82E5\u4E24\u6761\u901A\u9053\u90FD\u662F\u4F4E\u901F\u5931\u8D25\uFF1A\u95EE\u9898\u5728\u5F53\u524D\u9009\u4E2D\u7684\u673A\u573A\u8282\u70B9\uFF08url-test \u53EA\u6309\u63E1\u624B\u5EF6\u8FDF\u9009\u3001\u4E0D\u6D4B\u5E26\u5BBD\uFF09\uFF0C",
8382
- "\u5728\u9762\u677F\u91CC\u624B\u52A8\u7ED9 Default Proxy \u6362\u4E2A\u7EBF\u8DEF\u6216\u8282\u70B9\u540E\u91CD\u8BD5\uFF1B\u4E5F\u53EF\u6362\u4E2A\u65F6\u95F4\u7B49 url-test \u91CD\u9009",
8357
+ "\u5728\u9762\u677F\u91CC\u624B\u52A8\u7ED9\u4E3B\u5206\u7EC4\uFF08\u901A\u5E38\u540D\u4E3A Default Proxy \u6216 PROXY\uFF09\u6362\u4E2A\u7EBF\u8DEF\u6216\u8282\u70B9\u540E\u91CD\u8BD5\uFF1B\u4E5F\u53EF\u6362\u4E2A\u65F6\u95F4\u7B49 url-test \u91CD\u9009",
8383
8358
  "",
8384
8359
  "\u901A\u9053\u9009\u62E9\uFF1A\u672C\u673A\u4EE3\u7406\u5728\u8DD1\u65F6\u81EA\u52A8\u4F18\u5148\uFF08\u542B\u4F4E\u901F\u5FEB\u901F\u5931\u8D25\uFF09\uFF0C\u5931\u8D25\u56DE\u9000 gh\uFF08\u4ECD\u7ECF\u540C\u4E00\u672C\u673A\u4EE3\u7406\uFF09\uFF1B",
8385
8360
  "\u624B\u52A8\u6307\u5B9A: mihomo-cli kernel --mirror [\u955C\u50CF]\uFF08\u5F3A\u5236\u955C\u50CF\uFF09/ mihomo-cli kernel --mirror direct\uFF08\u5F3A\u5236\u76F4\u8FDE\uFF09",
@@ -8665,7 +8640,7 @@ async function cmdOverwrite(args) {
8665
8640
  }
8666
8641
 
8667
8642
  // src/commands/reset.ts
8668
- import fs17 from "fs";
8643
+ import fs16 from "fs";
8669
8644
  var RESET_TARGETS = [
8670
8645
  { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
8671
8646
  { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
@@ -8677,7 +8652,7 @@ var RESET_TARGETS = [
8677
8652
  label: "\u8986\u5199",
8678
8653
  needsStop: false,
8679
8654
  preserveOnBare: true,
8680
- paths: () => fs17.existsSync(USER_DATA_DIR) ? fs17.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8655
+ paths: () => fs16.existsSync(USER_DATA_DIR) ? fs16.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8681
8656
  },
8682
8657
  {
8683
8658
  // 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
@@ -8720,9 +8695,8 @@ async function cmdReset(args) {
8720
8695
  const serviceTargeted = ids.has("service");
8721
8696
  const service = getServiceStatus();
8722
8697
  let serviceActive = service.installed || service.loaded;
8723
- const legacy = detectLegacySystemInstall();
8724
8698
  if (targets.length === 1) {
8725
- if (serviceTargeted && !serviceActive && !legacy) {
8699
+ if (serviceTargeted && !serviceActive) {
8726
8700
  console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
8727
8701
  return;
8728
8702
  }
@@ -8735,9 +8709,6 @@ async function cmdReset(args) {
8735
8709
  } else if (needsStop && serviceActive) {
8736
8710
  console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo-cli start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
8737
8711
  }
8738
- if ((needsStop || serviceTargeted) && legacy) {
8739
- console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
8740
- }
8741
8712
  console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
8742
8713
  if (ids.has("subs")) {
8743
8714
  console.log(colors.yellow("\u8BA2\u9605\u94FE\u63A5\u4E0E\u672C\u5730\u914D\u7F6E\u5C06\u88AB\u5220\u9664\u4E14\u65E0\u6CD5\u6062\u590D\uFF0C\u9700\u91CD\u65B0\u4ECE\u673A\u573A\u83B7\u53D6\u8BA2\u9605\u5730\u5740"));
@@ -8749,7 +8720,6 @@ async function cmdReset(args) {
8749
8720
  console.log("\u5DF2\u53D6\u6D88");
8750
8721
  return;
8751
8722
  }
8752
- if ((needsStop || serviceTargeted) && legacy) await cleanupLegacyInstallOrThrow();
8753
8723
  const current = getServiceStatus();
8754
8724
  serviceActive = current.installed || current.loaded;
8755
8725
  let cleanup = null;
@@ -8776,9 +8746,9 @@ async function cmdReset(args) {
8776
8746
  }
8777
8747
  const deleted = /* @__PURE__ */ new Set();
8778
8748
  for (const target of targets) {
8779
- let hadContent = target.id === "service" && (serviceActive || legacy);
8749
+ let hadContent = target.id === "service" && serviceActive;
8780
8750
  for (const filePath of target.paths()) {
8781
- if (!fs17.existsSync(filePath)) continue;
8751
+ if (!fs16.existsSync(filePath)) continue;
8782
8752
  try {
8783
8753
  rmrf(filePath);
8784
8754
  } catch (e) {
@@ -8816,11 +8786,7 @@ async function cmdReset(args) {
8816
8786
  }
8817
8787
 
8818
8788
  // src/commands/service.ts
8819
- import fs18 from "fs";
8820
- async function handleLegacyInstall() {
8821
- if (!detectLegacySystemInstall()) return;
8822
- await announceLegacyCleanupOrThrow("\u9700\u5148\u6E05\u7406", [" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3"]);
8823
- }
8789
+ import fs17 from "fs";
8824
8790
  function printRestoreSkipped() {
8825
8791
  console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
8826
8792
  console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
@@ -8831,7 +8797,6 @@ async function cmdInstall(args) {
8831
8797
  assertKnownFlags(args.slice(1), [], "install");
8832
8798
  assertPositionalCount(args, 0, 1, "mihomo-cli install");
8833
8799
  assertKernelInstalled();
8834
- await handleLegacyInstall();
8835
8800
  const wasRunning = getServiceStatus().running;
8836
8801
  const { restoreSkipped } = await installService(wasRunning);
8837
8802
  console.log(`${colors.green("\u5DF2\u5B89\u88C5\u670D\u52A1")}`);
@@ -8858,7 +8823,7 @@ async function cmdInstall(args) {
8858
8823
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
8859
8824
  } else {
8860
8825
  console.log("\u542F\u52A8: mihomo-cli start");
8861
- if (!fs18.existsSync(PATHS.configFile)) {
8826
+ if (!fs17.existsSync(PATHS.configFile)) {
8862
8827
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
8863
8828
  }
8864
8829
  }
@@ -8868,9 +8833,8 @@ async function cmdUninstall(args) {
8868
8833
  assertKnownFlags(args.slice(1), [], "uninstall");
8869
8834
  assertPositionalCount(args, 0, 1, "mihomo-cli uninstall");
8870
8835
  const status = getServiceStatus();
8871
- const legacy = detectLegacySystemInstall();
8872
8836
  const residue = getMihomoPids();
8873
- if (!status.installed && !status.loaded && !legacy && residue.length === 0) {
8837
+ if (!status.installed && !status.loaded && residue.length === 0) {
8874
8838
  console.log("\u670D\u52A1\u672A\u5B89\u88C5");
8875
8839
  return;
8876
8840
  }
@@ -8878,17 +8842,14 @@ async function cmdUninstall(args) {
8878
8842
  console.log(colors.yellow("\u672A\u627E\u5230 plist\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001\uFF08plist \u53EF\u80FD\u88AB\u624B\u52A8\u5220\u9664\uFF09"));
8879
8843
  console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
8880
8844
  }
8881
- let remaining = null;
8845
+ let remaining;
8882
8846
  if (status.installed || status.loaded) {
8883
8847
  const cleanup = await uninstallService();
8884
8848
  console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
8885
8849
  remaining = cleanup.remaining;
8850
+ } else {
8851
+ remaining = residue;
8886
8852
  }
8887
- if (legacy) {
8888
- await announceLegacyCleanupOrThrow("\u5378\u8F7D\u65F6\u4E00\u5E76\u6E05\u7406");
8889
- remaining = null;
8890
- }
8891
- if (remaining === null) remaining = getMihomoPids();
8892
8853
  if (remaining.length > 0) {
8893
8854
  console.log("");
8894
8855
  printResidueWarning(remaining);
@@ -8909,9 +8870,6 @@ function handleStopResult(result) {
8909
8870
  async function cmdStop(args) {
8910
8871
  assertKnownFlags(args.slice(1), [], "stop");
8911
8872
  assertPositionalCount(args, 0, 1, "mihomo-cli stop");
8912
- if (detectLegacySystemInstall()) {
8913
- await announceLegacyCleanupOrThrow("\u505C\u6B62\u524D\u9700\u6E05\u7406");
8914
- }
8915
8873
  const status = getServiceStatus();
8916
8874
  const pids = getMihomoPids();
8917
8875
  const needsServiceWork = status.loaded || status.installed && !status.disabled;
@@ -9208,7 +9166,7 @@ function cmdUI(args) {
9208
9166
  const endpoint = getControllerEndpoint();
9209
9167
  console.log(`\u6253\u5F00 Web UI: ${uiName}`);
9210
9168
  console.log(`\u9875\u9762: ${url}`);
9211
- console.log(`\u63A7\u5236\u5668: http://127.0.0.1:${endpoint.port ?? "\uFF08settings.json \u7684 ports \u914D\u7F6E\u975E\u6CD5\uFF0C\u65E0\u6CD5\u786E\u5B9A\uFF09"}`);
9169
+ console.log(endpoint.port !== null ? `\u63A7\u5236\u5668: http://127.0.0.1:${endpoint.port}` : "\u63A7\u5236\u5668: \u7AEF\u53E3\u65E0\u6CD5\u786E\u5B9A\uFF08settings.json \u7684 ports \u914D\u7F6E\u975E\u6CD5\uFF09");
9212
9170
  const secret = endpoint.secret;
9213
9171
  if (secret) {
9214
9172
  if (copySecret) {
@@ -9282,7 +9240,7 @@ var COMMANDS = [
9282
9240
  aliases: [],
9283
9241
  handler: cmdLogs,
9284
9242
  group: "interface",
9285
- usage: [{ signature: "logs [-f] [-n N] [\u7F16\u53F7] [-o]", description: "\u65E5\u5FD7\u5217\u8868/\u67E5\u770B\uFF08\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u5373\u5F53\u524D\uFF09" }]
9243
+ usage: [{ signature: "logs [-f] [-n N] [\u7F16\u53F7] [-o]", description: "\u65E5\u5FD7\u5217\u8868/\u67E5\u770B\uFF08\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u770B\u5F53\u524D\u65E5\u5FD7\uFF09" }]
9286
9244
  },
9287
9245
  // === 订阅 ===
9288
9246
  {
@@ -9292,7 +9250,7 @@ var COMMANDS = [
9292
9250
  handler: cmdSubscription,
9293
9251
  rewrite: (args) => ["subscription", "use", ...args.slice(1)],
9294
9252
  group: "subscription",
9295
- usage: [{ signature: "use <name>", description: "\u5207\u6362\u8BA2\u9605\uFF08subscription use \u5FEB\u6377\u65B9\u5F0F\uFF0C\u81EA\u52A8\u91CD\u542F\uFF09" }]
9253
+ usage: [{ signature: "use <name>", description: "\u5207\u6362\u8BA2\u9605\uFF08subscription use \u5FEB\u6377\u65B9\u5F0F\uFF0C\u8FD0\u884C\u4E2D\u81EA\u52A8\u91CD\u542F\uFF09" }]
9296
9254
  },
9297
9255
  {
9298
9256
  name: "subscription",
@@ -9301,7 +9259,7 @@ var COMMANDS = [
9301
9259
  group: "subscription",
9302
9260
  usage: [
9303
9261
  { signature: "subscription", description: "\u5217\u51FA\u6240\u6709\u8BA2\u9605\uFF08\u522B\u540D sub/subs\uFF09" },
9304
- { signature: "subscription use <name>", description: "\u5207\u6362\u5F53\u524D\u8BA2\u9605\uFF08\u81EA\u52A8\u91CD\u542F\uFF1B\u91CD\u542F\u900F\u4F20 -s/-u \u7B49\u542F\u52A8\u9009\u9879\uFF09" },
9262
+ { signature: "subscription use <name>", description: "\u5207\u6362\u5F53\u524D\u8BA2\u9605\uFF08\u8FD0\u884C\u4E2D\u81EA\u52A8\u91CD\u542F\uFF0C\u91CD\u542F\u65F6\u53EF\u7528 -s/-u \u7B49\u542F\u52A8\u9009\u9879\uFF09" },
9305
9263
  { signature: "subscription add [url] [name]", description: "\u6DFB\u52A0\u8BA2\u9605\uFF08\u65E0 url \u65F6\u4EA4\u4E92\u8BFB\u53D6\u526A\u8D34\u677F\uFF09" },
9306
9264
  { signature: "subscription update [name]", description: "\u66F4\u65B0\u8BA2\u9605\uFF08\u65E0\u53C2\u66F4\u65B0\u6240\u6709\uFF09" },
9307
9265
  { signature: "subscription remove <name>", description: "\u5220\u9664\u8BA2\u9605\uFF08\u6A21\u7CCA\u5339\u914D\u9700\u786E\u8BA4\uFF0C-y \u8DF3\u8FC7\uFF09" }
@@ -9322,7 +9280,7 @@ var COMMANDS = [
9322
9280
  group: "config",
9323
9281
  usage: [
9324
9282
  { signature: "overwrite", description: "\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF08\u522B\u540D ow\uFF09" },
9325
- { signature: "overwrite on|off [-s] [-u ms]", description: "\u542F\u7528/\u7981\u7528\u8986\u5199\u914D\u7F6E\uFF08\u8FD0\u884C\u4E2D\u81EA\u52A8\u91CD\u542F\uFF0C\u53EF\u900F\u4F20\u542F\u52A8\u9009\u9879\uFF09" }
9283
+ { signature: "overwrite on|off [-s] [-u ms]", description: "\u542F\u7528/\u7981\u7528\u8986\u5199\u914D\u7F6E\uFF08\u8FD0\u884C\u4E2D\u81EA\u52A8\u91CD\u542F\uFF0C\u53EF\u5E26 -s/-u \u7B49\u542F\u52A8\u9009\u9879\uFF09" }
9326
9284
  ]
9327
9285
  },
9328
9286
  {
@@ -9355,7 +9313,7 @@ var COMMANDS = [
9355
9313
  aliases: [],
9356
9314
  handler: cmdReset,
9357
9315
  group: "system",
9358
- usage: [{ signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }]
9316
+ 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" }]
9359
9317
  },
9360
9318
  {
9361
9319
  name: "doctor",
@@ -9425,7 +9383,7 @@ process.on("unhandledRejection", (reason) => {
9425
9383
  var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
9426
9384
  function readSelfMixedPortEarly() {
9427
9385
  try {
9428
- const raw = JSON.parse(fs19.readFileSync(PATHS.settingsFile, "utf8"));
9386
+ const raw = JSON.parse(fs18.readFileSync(PATHS.settingsFile, "utf8"));
9429
9387
  const mixed = raw?.ports?.mixed;
9430
9388
  if (isValidPortNumber(mixed)) return mixed;
9431
9389
  } catch {
@@ -9480,7 +9438,7 @@ function assertSupportedPlatform(commandName) {
9480
9438
  label: "\u5E73\u53F0\u4E0D\u652F\u6301",
9481
9439
  hint: [
9482
9440
  "\u670D\u52A1\u6258\u7BA1\u4F9D\u8D56 launchd\u3001\u76EE\u5F55/UI \u6253\u5F00\u4F9D\u8D56 open\u3001\u63D0\u6743\u4F9D\u8D56 sudo\uFF0C\u5747\u65E0\u5176\u4ED6\u5E73\u53F0\u5B9E\u73B0\u3002",
9483
- "Windows / Linux \u9002\u914D\u4ECD\u5728\u8FDB\u884C\u4E2D\u3002",
9441
+ "Windows / Linux \u9002\u914D\u5C1A\u65E0\u65F6\u95F4\u8868\u3002",
9484
9442
  "\u5982\u9700\u5728\u975E macOS \u4E0A\u5F00\u53D1\u8C03\u8BD5\uFF0C\u53EF\u8BBE MIHOMO_CLI_ALLOW_ANY_PLATFORM=1\uFF08\u529F\u80FD\u4E0D\u4FDD\u8BC1\u53EF\u7528\uFF09\u3002"
9485
9443
  ]
9486
9444
  });
@@ -9537,5 +9495,5 @@ main().catch((e) => {
9537
9495
  /*! Bundled license information:
9538
9496
 
9539
9497
  js-yaml/dist/js-yaml.mjs:
9540
- (*! js-yaml 5.3.0 https://github.com/nodeca/js-yaml @license MIT *)
9498
+ (*! js-yaml 5.4.3 https://github.com/nodeca/js-yaml @license MIT *)
9541
9499
  */