mihomo-cli 26.10.110 → 26.10.112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -304,13 +304,13 @@ function assertKnownFlags(args, known, command) {
304
304
  });
305
305
  }
306
306
  }
307
- function assertPositionalCount(args, max, startIdx, usage, valueFlags = VALUE_FLAGS) {
307
+ function assertPositionalCount(args, max, startIdx, usage) {
308
308
  if (!args) return;
309
309
  let count = 0;
310
310
  for (let i = startIdx; i < args.length; i++) {
311
311
  const a = args[i];
312
312
  if (a.startsWith("-")) {
313
- if (valueFlags.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++;
313
+ if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++;
314
314
  continue;
315
315
  }
316
316
  count++;
@@ -1723,32 +1723,24 @@ 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
- }
1730
1726
  function mergeKeys(state, frame, source, sourceTag) {
1731
- chargeMergeWork(state);
1732
1727
  for (const sourceKey of sourceTag.keys(source)) {
1733
- chargeMergeWork(state);
1728
+ if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1734
1729
  if (frame.tag.has(frame.value, sourceKey)) continue;
1735
1730
  const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
1736
1731
  if (err) throwError$1(state, err);
1737
- frame.overridable ??= /* @__PURE__ */ new Set();
1738
- frame.overridable.add(sourceKey);
1732
+ (frame.overridable ??= /* @__PURE__ */ new Set()).add(sourceKey);
1739
1733
  }
1740
1734
  }
1741
1735
  function mergeSource(state, frame, source, sourceTag) {
1742
1736
  state.position = frame.keyPosition;
1743
1737
  if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag);
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");
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");
1752
1744
  }
1753
1745
  function addMappingValue(state, frame, key, value, tag) {
1754
1746
  state.position = frame.keyPosition;
@@ -2091,24 +2083,6 @@ function testDocumentSeparator(state, position = state.position) {
2091
2083
  }
2092
2084
  return false;
2093
2085
  }
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
- }
2112
2086
  function skipUntilLineEnd(state) {
2113
2087
  let ch = state.input.charCodeAt(state.position);
2114
2088
  while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
@@ -2292,14 +2266,14 @@ function readBlockScalar(state, parentIndent, props) {
2292
2266
  } else if (column > 0) valueEnd = linePosition + column;
2293
2267
  break;
2294
2268
  }
2295
- if (testDocumentBoundary(state)) break;
2269
+ if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break;
2296
2270
  if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column);
2297
2271
  if (!detectedIndent && contentIndent === -1 && !isEol(first)) {
2298
2272
  if (first === 9 && column < parentIndent) {
2299
2273
  state.position = linePosition + column;
2300
2274
  throwError(state, "tab characters must not be used in indentation");
2301
2275
  }
2302
- if (column >= parentIndent && column < maxLeadingIndent) {
2276
+ if (column < maxLeadingIndent) {
2303
2277
  state.position = linePosition + column;
2304
2278
  throwError(state, "bad indentation of a mapping entry");
2305
2279
  }
@@ -2345,7 +2319,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
2345
2319
  const inFlow = nodeContext === CONTEXT_FLOW_IN;
2346
2320
  let multiline = false;
2347
2321
  while (ch !== 0) {
2348
- if (testDocumentBoundary(state)) break;
2322
+ if (state.position === state.lineStart && testDocumentSeparator(state)) break;
2349
2323
  if (ch === 58) {
2350
2324
  const following = state.input.charCodeAt(state.position + 1);
2351
2325
  if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break;
@@ -2509,16 +2483,13 @@ function readBlockMapping(state, nodeIndent, flowIndent, props) {
2509
2483
  ch = state.input.charCodeAt(++state.position);
2510
2484
  if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2511
2485
  if (!mappingOpened) {
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
- });
2486
+ restoreState(state, beforeKey);
2487
+ addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2521
2488
  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++;
2522
2493
  }
2523
2494
  detected = true;
2524
2495
  atExplicitKey = false;
@@ -2705,7 +2676,7 @@ function readDocument(state) {
2705
2676
  const documentEvent = state.events[documentEventIndex];
2706
2677
  if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd;
2707
2678
  addPopEvent(state);
2708
- if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state)) throwError(state, "end of the stream or a document separator is expected");
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");
2709
2680
  }
2710
2681
  function parseEvents(input, options) {
2711
2682
  const length = input.length;
@@ -2726,8 +2697,8 @@ function parseEvents(input, options) {
2726
2697
  };
2727
2698
  const nullpos = input.indexOf("\0");
2728
2699
  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++;
2729
2701
  while (state.position < state.length) {
2730
- skipByteOrderMark(state);
2731
2702
  skipSeparationSpace(state, true);
2732
2703
  if (state.position >= state.length) break;
2733
2704
  const documentStart = state.position;
@@ -2760,6 +2731,15 @@ function load(input, options) {
2760
2731
  if (documents.length === 1) return documents[0];
2761
2732
  throw new YAMLException("expected a single document in the stream, but found more");
2762
2733
  }
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
+ };
2763
2743
  var INVALID = /* @__PURE__ */ Symbol("INVALID");
2764
2744
  function buildRepresentTypes(schema) {
2765
2745
  const defaultTags = new Set([
@@ -2808,6 +2788,8 @@ function build(state, object) {
2808
2788
  if (existing.anchor === void 0) existing.anchor = `ref_${state.refCounter++}`;
2809
2789
  return {
2810
2790
  kind: "alias",
2791
+ tag: "",
2792
+ style: new Style(),
2811
2793
  anchor: existing.anchor
2812
2794
  };
2813
2795
  }
@@ -2820,20 +2802,24 @@ function build(state, object) {
2820
2802
  }
2821
2803
  const { tag, tagName, implicitTag } = matched;
2822
2804
  const nodeTagName = implicitTag ? tagName : tagNameShort(tagName);
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
- };
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
+ }
2830
2815
  if (tag.nodeKind === "sequence") {
2831
2816
  const container = tag.represent(object);
2817
+ const style2 = new Style();
2818
+ style2.tagged = !implicitTag;
2832
2819
  const node2 = {
2833
2820
  kind: "sequence",
2834
2821
  tag: nodeTagName,
2835
- tagged: !implicitTag,
2836
- style: COLLECTION_STYLE.BLOCK,
2822
+ style: style2,
2837
2823
  items: []
2838
2824
  };
2839
2825
  if (!state.noRefs) state.refs.set(object, node2);
@@ -2846,11 +2832,12 @@ function build(state, object) {
2846
2832
  return node2;
2847
2833
  }
2848
2834
  const map = tag.represent(object);
2835
+ const style = new Style();
2836
+ style.tagged = !implicitTag;
2849
2837
  const node = {
2850
2838
  kind: "mapping",
2851
2839
  tag: nodeTagName,
2852
- tagged: !implicitTag,
2853
- style: COLLECTION_STYLE.BLOCK,
2840
+ style,
2854
2841
  items: []
2855
2842
  };
2856
2843
  if (!state.noRefs) state.refs.set(object, node);
@@ -2918,204 +2905,82 @@ function visit(documents, visitor) {
2918
2905
  isKey: false
2919
2906
  })) return;
2920
2907
  }
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
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
2932
2962
  };
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;
3042
- }
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, "''")}'`;
3087
- }
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));
2963
+ function nodeTagShort(node) {
2964
+ return node.style.tagged ? node.tag : tagNameShort(node.tag);
3098
2965
  }
3099
- function renderDoubleQuoted(layout) {
3100
- return `"${escapeString(layout.node.value)}"`;
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
+ };
3101
2975
  }
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;
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}`;
3116
2981
  }
3117
2982
  function indentString(string, spaces) {
3118
- const indent = " ".repeat(spaces);
2983
+ const ind = " ".repeat(spaces);
3119
2984
  let position = 0;
3120
2985
  let result = "";
3121
2986
  const length = string.length;
@@ -3129,26 +2994,191 @@ function indentString(string, spaces) {
3129
2994
  line = string.slice(position, next + 1);
3130
2995
  position = next + 1;
3131
2996
  }
3132
- if (line.length && line !== "\n") result += indent;
2997
+ if (line.length && line !== "\n") result += ind;
3133
2998
  result += line;
3134
2999
  }
3135
3000
  return result;
3136
3001
  }
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
+ }
3137
3059
  function needIndentIndicator(string) {
3138
3060
  return /^\n* /.test(string);
3139
3061
  }
3140
- function blockHeader(string, shiftOfParent, shiftOfContent) {
3141
- const indentIndicator = needIndentIndicator(string) ? String(shiftOfContent - shiftOfParent) : "";
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) : "";
3142
3139
  const clip = string[string.length - 1] === "\n";
3143
3140
  return `${indentIndicator}${clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-"}
3144
3141
  `;
3145
3142
  }
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
+ }
3146
3158
  function dropEndingNewline(string) {
3147
3159
  return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
3148
3160
  }
3149
3161
  function isMoreIndented(char) {
3150
3162
  return char === " " || char === " ";
3151
3163
  }
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
+ }
3152
3182
  function foldLine(line, width) {
3153
3183
  if (line === "" || isMoreIndented(line[0])) return line;
3154
3184
  const breakRe = / [^ \t]/g;
@@ -3174,133 +3204,43 @@ ${line.slice(curr + 1)}`;
3174
3204
  else result += line.slice(start);
3175
3205
  return result.slice(1);
3176
3206
  }
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;
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);
3192
3223
  }
3193
3224
  return result;
3194
3225
  }
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
- }
3286
3226
  function writeFlowSequence(state, level, node) {
3287
3227
  let result = "";
3288
3228
  for (let index = 0, length = node.items.length; index < length; index += 1) {
3289
- const item = writeNode(state, level, node.items[index], node, {}).text;
3290
- if (index > 0) result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3229
+ const item = writeNode(state, level, node.items[index], {});
3230
+ if (result !== "") result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3291
3231
  result += item;
3292
3232
  }
3293
- const pad = state.flowBracketPadding && node.items.length > 0 ? " " : "";
3233
+ const pad = state.flowBracketPadding && result !== "" ? " " : "";
3294
3234
  return `[${pad}${result}${pad}]`;
3295
3235
  }
3296
3236
  function writeBlockSequence(state, level, node, compact) {
3297
3237
  let result = "";
3298
3238
  for (let index = 0, length = node.items.length; index < length; index += 1) {
3299
- const item = writeNode(state, level + 1, node.items[index], node, {
3239
+ const item = writeNode(state, level + 1, node.items[index], {
3300
3240
  block: true,
3301
3241
  compact: state.seqInlineFirst,
3302
3242
  isblockseq: true
3303
- }).text;
3243
+ });
3304
3244
  if (!compact || result !== "") result += generateNextLine(state, level);
3305
3245
  if (item === "" || CHAR_LINE_FEED === item.charCodeAt(0)) result += "-";
3306
3246
  else result += "- ";
@@ -3310,51 +3250,70 @@ function writeBlockSequence(state, level, node, compact) {
3310
3250
  }
3311
3251
  function writeFlowMapping(state, level, node) {
3312
3252
  let result = "";
3313
- for (const { key, value } of node.items) {
3253
+ const items = sortMappingItems(state, node.items);
3254
+ for (const { key, value } of items) {
3314
3255
  let pairBuffer = "";
3315
3256
  if (result !== "") pairBuffer += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3316
- const keyRender = writeNode(state, level, key, node, { iskey: true });
3317
- const keyText = keyRender.text;
3318
- const valueText = writeNode(state, level, value, node, {}).text;
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, {});
3319
3262
  const sep = state.flowSkipColonSpace || 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}`;
3263
+ pairBuffer += `${keyText}${state.quoteFlowKeys && !explicitPair ? '"' : ""}:${sep}${valueText}`;
3323
3264
  result += pairBuffer;
3324
3265
  }
3325
3266
  const pad = state.flowBracketPadding && result !== "" ? " " : "";
3326
3267
  return `{${pad}${result}${pad}}`;
3327
3268
  }
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
+ }
3328
3288
  function writeBlockMapping(state, level, node, compact) {
3329
3289
  let result = "";
3330
- for (let index = 0, length = node.items.length; index < length; index += 1) {
3290
+ const items = sortMappingItems(state, node.items);
3291
+ for (let index = 0, length = items.length; index < length; index += 1) {
3331
3292
  let pairBuffer = "";
3332
3293
  if (!compact || result !== "") pairBuffer += generateNextLine(state, level);
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, {
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, {
3336
3297
  block: true,
3337
3298
  compact: true,
3338
3299
  isblockseq: !cannotBeCompact(state, key, level + 1)
3339
- }) : writeNode(state, level + 1, key, node, {
3300
+ }) : writeNode(state, level + 1, key, {
3340
3301
  block: true,
3341
3302
  compact: true,
3342
3303
  iskey: true
3343
3304
  });
3344
- const keyText = keyRender.text;
3345
3305
  const keyHasLineBreak = key.kind === "scalar" && key.value.indexOf("\n") !== -1;
3346
- const keyIsTooLong = keyText.length > 1024 && /^[\s\S]{1025}/u.test(keyText);
3347
- const explicitPair = keyIsBlock || keyHasLineBreak || keyIsTooLong;
3306
+ const explicitPair = keyIsBlock || keyHasLineBreak || keyText.length > 1024;
3348
3307
  if (explicitPair) if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?";
3349
3308
  else pairBuffer += "? ";
3350
3309
  pairBuffer += keyText;
3351
3310
  if (explicitPair) pairBuffer += generateNextLine(state, level);
3352
- const valueText = writeNode(state, level + 1, value, node, {
3311
+ const valueText = writeNode(state, level + 1, value, {
3353
3312
  block: true,
3354
3313
  compact: explicitPair,
3355
3314
  isblockseq: explicitPair && !cannotBeCompact(state, value, level + 1)
3356
- }).text;
3357
- const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
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;
3358
3317
  const keyColonSep = !explicitPair && (key.kind === "alias" || keyIsBareProps) ? " " : "";
3359
3318
  if (valueText === "" || CHAR_LINE_FEED === valueText.charCodeAt(0)) pairBuffer += `${keyColonSep}:`;
3360
3319
  else pairBuffer += `${keyColonSep}: `;
@@ -3364,41 +3323,29 @@ function writeBlockMapping(state, level, node, compact) {
3364
3323
  return result;
3365
3324
  }
3366
3325
  function cannotBeCompact(state, node, level) {
3367
- if (node.kind === "alias") return true;
3368
- return node.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3326
+ return node.style.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3369
3327
  }
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
- }
3328
+ function writeNode(state, level, node, ctx) {
3329
+ if (node.kind === "alias") return `*${node.anchor}`;
3378
3330
  const { block = false, iskey = false, isblockseq = false } = ctx;
3379
3331
  let compact = ctx.compact ?? false;
3380
3332
  const hasAnchor = node.anchor !== void 0;
3381
3333
  if (cannotBeCompact(state, node, level)) compact = false;
3382
3334
  let body;
3383
- let shouldPrintTag = node.tagged;
3384
- const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0;
3335
+ let shouldPrintTag = node.style.tagged;
3336
+ const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && !node.style.flow && node.items.length !== 0;
3385
3337
  if (node.kind === "mapping") if (useBlockCollection) body = writeBlockMapping(state, level, node, compact);
3386
3338
  else body = writeFlowMapping(state, level, node);
3387
3339
  else if (node.kind === "sequence") if (useBlockCollection) if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact);
3388
3340
  else body = writeBlockSequence(state, level, node, compact);
3389
3341
  else body = writeFlowSequence(state, level, node);
3390
3342
  else {
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;
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
+ }
3399
3348
  if (useBlockCollection && compact && level > 0 && state.indent > 2) body = `${" ".repeat(state.indent - 2)}${body}`;
3400
- const noBody = body === "";
3401
- let text = body;
3402
3349
  if (shouldPrintTag || hasAnchor) {
3403
3350
  const props = [];
3404
3351
  const tag = shouldPrintTag ? nodeTagShort(node) : null;
@@ -3411,15 +3358,19 @@ function writeNode(state, level, node, parent, ctx) {
3411
3358
  if (tag !== null) props.push(tag);
3412
3359
  }
3413
3360
  const sep = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
3414
- text = `${props.join(" ")}${sep}${body}`;
3361
+ body = `${props.join(" ")}${sep}${body}`;
3415
3362
  }
3416
- return {
3417
- text,
3418
- noBody
3419
- };
3363
+ return body;
3420
3364
  }
3421
3365
  function rootStartsOwnLine(node) {
3422
- return (node.kind === "sequence" || node.kind === "mapping") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0 && !node.tagged && node.anchor === void 0;
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";
3423
3374
  }
3424
3375
  function writeDocumentDirectives(doc) {
3425
3376
  let result = "";
@@ -3441,7 +3392,6 @@ function present(documents, options) {
3441
3392
  let previousEnded = false;
3442
3393
  for (let index = 0; index < documents.length; index += 1) {
3443
3394
  const doc = documents[index];
3444
- state.openEnded = false;
3445
3395
  const directives = writeDocumentDirectives(doc);
3446
3396
  const hasDirectives = directives !== "";
3447
3397
  const marker = doc.explicitStart || hasDirectives || index > 0 && !previousEnded;
@@ -3449,18 +3399,18 @@ function present(documents, options) {
3449
3399
  if (doc.contents === null) {
3450
3400
  if (marker) result += "---\n";
3451
3401
  } else if (marker) {
3452
- const body = writeNode(state, 0, doc.contents, null, {
3402
+ const body = writeNode(state, 0, doc.contents, {
3453
3403
  block: true,
3454
3404
  compact: true
3455
- }).text;
3405
+ });
3456
3406
  const sep = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
3457
3407
  result += `---${sep}${body}
3458
3408
  `;
3459
- } else result += writeNode(state, 0, doc.contents, null, {
3409
+ } else result += writeNode(state, 0, doc.contents, {
3460
3410
  block: true,
3461
3411
  compact: true
3462
- }).text + "\n";
3463
- previousEnded = doc.explicitEnd || state.openEnded;
3412
+ }) + "\n";
3413
+ previousEnded = doc.explicitEnd || doc.contents !== null && isOpenEnded(doc.contents);
3464
3414
  if (previousEnded) result += "...\n";
3465
3415
  }
3466
3416
  return result;
@@ -3471,17 +3421,9 @@ var DEFAULT_DUMP_OPTIONS = {
3471
3421
  skipInvalid: false,
3472
3422
  noRefs: false,
3473
3423
  flowLevel: -1,
3474
- sortKeys: false,
3475
3424
  transform: () => {
3476
3425
  }
3477
3426
  };
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
- }
3485
3427
  function dump(input, options = {}) {
3486
3428
  const opts = {
3487
3429
  ...DEFAULT_DUMP_OPTIONS,
@@ -3493,16 +3435,9 @@ function dump(input, options = {}) {
3493
3435
  });
3494
3436
  if (opts.flowLevel >= 0) visit(documents, (node, ctx) => {
3495
3437
  if (ctx.depth < opts.flowLevel) return;
3496
- if (node.kind === "sequence" || node.kind === "mapping") node.style = COLLECTION_STYLE.FLOW;
3438
+ node.style.flow = true;
3497
3439
  return VISIT_SKIP;
3498
3440
  });
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
- }
3506
3441
  opts.transform(documents);
3507
3442
  return present(documents, {
3508
3443
  ...pick(opts, Object.keys(DEFAULT_PRESENTER_OPTIONS)),
@@ -3832,7 +3767,8 @@ function getPortsOrNull(settings = readSettings()) {
3832
3767
  return null;
3833
3768
  }
3834
3769
  }
3835
- function getControllerEndpoint(settings = readSettings()) {
3770
+ function getControllerEndpoint() {
3771
+ const settings = readSettings();
3836
3772
  const port = getPortsOrNull(settings)?.controller ?? null;
3837
3773
  const secret = settings.controller_secret;
3838
3774
  return { port, secret: typeof secret === "string" && secret ? secret : null };
@@ -3917,7 +3853,7 @@ function validateSubscriptionName(name) {
3917
3853
  throw new CliError(`\u8BA2\u9605\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
3918
3854
  }
3919
3855
  }
3920
- function addSubscription(url, name = "default") {
3856
+ function addSubscription(url, name) {
3921
3857
  validateSubscriptionName(name);
3922
3858
  updateSettings((settings) => {
3923
3859
  const subs = getSubscriptions(settings);
@@ -4790,8 +4726,8 @@ function judgeScriptMatches(subRawContent, mode, scope, entries) {
4790
4726
  scope
4791
4727
  });
4792
4728
  return { matches: scriptMatches };
4793
- } catch (e) {
4794
- return { matches: [], error: firstLine(e.message ?? String(e)) };
4729
+ } catch {
4730
+ return { matches: [] };
4795
4731
  }
4796
4732
  }
4797
4733
  function deriveRuntimeMode(info) {
@@ -4865,11 +4801,8 @@ ${error.stderr || ""}`).trim();
4865
4801
  fs4.rmSync(stageDir, { recursive: true, force: true });
4866
4802
  }
4867
4803
  }
4868
- function hasConfig() {
4869
- return fs4.existsSync(PATHS.configFile);
4870
- }
4871
4804
  function getConfigInfo() {
4872
- if (!hasConfig()) return null;
4805
+ if (!fs4.existsSync(PATHS.configFile)) return null;
4873
4806
  try {
4874
4807
  const content = fs4.readFileSync(PATHS.configFile, "utf8");
4875
4808
  const cfg = loadYamlSafe(content);
@@ -4963,7 +4896,8 @@ function formatTimestamp(ts) {
4963
4896
  return "\u672A\u77E5";
4964
4897
  }
4965
4898
  }
4966
- function formatLocalTimestamp(d = /* @__PURE__ */ new Date()) {
4899
+ function formatLocalTimestamp() {
4900
+ const d = /* @__PURE__ */ new Date();
4967
4901
  const p = (n) => String(n).padStart(2, "0");
4968
4902
  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}_${p(d.getHours())}-${p(d.getMinutes())}-${p(d.getSeconds())}`;
4969
4903
  }
@@ -5000,14 +4934,6 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
5000
4934
  return `${Math.floor(month / 12)} \u5E74\u524D`;
5001
4935
  }
5002
4936
 
5003
- // src/service.ts
5004
- import { spawnSync as spawnSync7 } from "child_process";
5005
- import fs12 from "fs";
5006
- import path7 from "path";
5007
-
5008
- // src/hot-reload.ts
5009
- import fs8 from "fs";
5010
-
5011
4937
  // src/launchctl.ts
5012
4938
  import { spawnSync as spawnSync2 } from "child_process";
5013
4939
  import fs5 from "fs";
@@ -5145,1548 +5071,1516 @@ async function waitUntilUnloaded(target = serviceTarget()) {
5145
5071
  });
5146
5072
  }
5147
5073
 
5148
- // src/proxy-probe.ts
5149
- import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
5150
- import { promisify as promisify2 } from "util";
5151
-
5152
- // src/curl-spawn.ts
5153
- function buildCurlSpawnEnv() {
5154
- const env = { ...process.env };
5155
- env.no_proxy = "";
5156
- env.NO_PROXY = "";
5157
- return env;
5074
+ // src/suggest.ts
5075
+ function levenshtein(a, b) {
5076
+ if (a === b) return 0;
5077
+ if (a.length === 0) return b.length;
5078
+ if (b.length === 0) return a.length;
5079
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
5080
+ for (let i = 1; i <= a.length; i++) {
5081
+ const curr = [i];
5082
+ for (let j = 1; j <= b.length; j++) {
5083
+ curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
5084
+ }
5085
+ prev = curr;
5086
+ }
5087
+ return prev[b.length];
5158
5088
  }
5159
-
5160
- // src/process-probe.ts
5161
- import { spawnSync as spawnSync3 } from "child_process";
5162
- import fs6 from "fs";
5163
- var PS_TIMEOUT_MS = 5e3;
5164
- var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
5165
- function probeProcess(pid) {
5166
- if (!pid) return NOT_RUNNING;
5167
- try {
5168
- const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
5169
- encoding: "utf8",
5170
- timeout: PS_TIMEOUT_MS
5089
+ function suggestSimilar(input, candidates) {
5090
+ const lower = input.toLowerCase();
5091
+ if (lower === "") return [];
5092
+ const scored = [];
5093
+ for (const cand of candidates) {
5094
+ const c = cand.toLowerCase();
5095
+ if (cand === input) continue;
5096
+ if (c.startsWith(lower)) {
5097
+ scored.push({ name: cand, score: 0, lenDiff: Math.abs(cand.length - input.length) });
5098
+ } else if (lower.length >= 3) {
5099
+ const d = levenshtein(lower, c);
5100
+ if (d <= 2) scored.push({ name: cand, score: d, lenDiff: Math.abs(cand.length - input.length) });
5101
+ }
5102
+ }
5103
+ scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
5104
+ return scored.slice(0, 3).map((s) => s.name);
5105
+ }
5106
+
5107
+ // src/commands/help.ts
5108
+ function printShortHelp() {
5109
+ console.log(`
5110
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo-cli help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
5111
+ `);
5112
+ const steps = [];
5113
+ if (!hasKernel()) steps.push(["mihomo-cli kernel", "\u4E0B\u8F7D\u5185\u6838"]);
5114
+ if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
5115
+ if (!isServiceInstalled()) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
5116
+ if (steps.length > 0) {
5117
+ steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
5118
+ const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
5119
+ console.log("\u5F00\u59CB\u4F7F\u7528:");
5120
+ steps.forEach(([cmd, desc], i) => {
5121
+ console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
5171
5122
  });
5172
- const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
5173
- if (!match) return NOT_RUNNING;
5174
- return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
5175
- } catch {
5176
- return NOT_RUNNING;
5123
+ console.log("");
5124
+ return;
5177
5125
  }
5126
+ console.log(
5127
+ `\u5E38\u7528\u547D\u4EE4:
5128
+ ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
5129
+ ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
5130
+ ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
5131
+ ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
5132
+ `
5133
+ );
5178
5134
  }
5179
- function isProbedMihomo(p) {
5180
- return p.alive && (p.command.includes(PATHS.mihomoBinary) || p.command.includes(PATHS.serviceBinary));
5135
+ var GROUP_TITLES = [
5136
+ ["control", "\u63A7\u5236:"],
5137
+ ["interface", "\u754C\u9762:"],
5138
+ ["subscription", "\u8BA2\u9605:"],
5139
+ ["config", "\u914D\u7F6E:"],
5140
+ ["system", "\u7CFB\u7EDF:"]
5141
+ ];
5142
+ function printHelp(commands) {
5143
+ const lines = [`
5144
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mh", "", "\u7528\u6CD5:", " mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"];
5145
+ const allUsage = commands.flatMap((c) => c.usage);
5146
+ const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
5147
+ const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
5148
+ for (const [group, title] of GROUP_TITLES) {
5149
+ const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
5150
+ if (usageLines.length === 0) continue;
5151
+ lines.push("", colors.cyan(title));
5152
+ for (const u of usageLines) lines.push(formatUsage(u));
5153
+ }
5154
+ const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
5155
+ if (meta.length > 0) {
5156
+ lines.push("", colors.cyan("\u5143:"));
5157
+ for (const u of meta) lines.push(formatUsage(u));
5158
+ }
5159
+ lines.push(
5160
+ "",
5161
+ `${colors.cyan("\u793A\u4F8B:")}`,
5162
+ // 顺序即首次使用的依赖顺序(kernel → 订阅 → 服务 → 启动):install 在无内核时会被
5163
+ // 拦下提示先跑 kernel,示例若把 install 放第一条,照着敲的新用户第一步就撞墙
5164
+ " mihomo-cli kernel # \u4E0B\u8F7D\u5185\u6838\uFF08\u9996\u6B21\u4F7F\u7528\u7684\u7B2C\u4E00\u6B65\uFF09",
5165
+ " mihomo-cli sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
5166
+ " mihomo-cli install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
5167
+ " mihomo-cli start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
5168
+ " mihomo-cli stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
5169
+ " mihomo-cli start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
5170
+ " mihomo-cli start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
5171
+ " mihomo-cli ui # \u6253\u5F00 Web UI",
5172
+ "",
5173
+ `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
5174
+ " tun = start tun",
5175
+ " use <name> = subscription use <name>",
5176
+ " restart = start\uFF08start \u672C\u8EAB\u5373\u91CD\u542F\uFF09",
5177
+ "",
5178
+ `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
5179
+ " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
5180
+ " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
5181
+ "",
5182
+ `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
5183
+ " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
5184
+ ` \u9ED8\u8BA4: ${USER_DATA_DIR}`
5185
+ );
5186
+ console.log(lines.join("\n"));
5181
5187
  }
5182
- var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
5183
- var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
5184
- function getPid() {
5185
- if (!fs6.existsSync(PATHS.pidFile)) return null;
5186
- try {
5187
- const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5188
- return pid > 0 ? pid : null;
5189
- } catch {
5190
- return null;
5188
+ function printCommandHelp(command) {
5189
+ const aliasText = command.aliases.length > 0 ? colors.gray(`\uFF08\u522B\u540D: ${command.aliases.join(", ")}\uFF09`) : "";
5190
+ const lines = ["", `${colors.cyan(colors.bold(`mihomo-cli ${command.name}`))}${aliasText}`];
5191
+ if (command.usage.length > 0) {
5192
+ lines.push("", "\u7528\u6CD5:");
5193
+ const width = Math.max(...command.usage.map((u) => displayWidth(u.signature)));
5194
+ for (const u of command.usage) {
5195
+ lines.push(` ${colors.bold(padEndDisplay(u.signature, width))} ${u.description}`);
5196
+ }
5197
+ } else {
5198
+ lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo-cli help"));
5191
5199
  }
5200
+ console.log(lines.join("\n"));
5192
5201
  }
5193
- function isRunning() {
5194
- const pid = getPid();
5195
- if (!pid) return false;
5196
- return isMihomoProcess(pid);
5202
+ function printHelpEntry(args, commands, finder) {
5203
+ const token = args[1];
5204
+ if (!token) {
5205
+ printHelp(commands);
5206
+ return;
5207
+ }
5208
+ const command = finder(token.toLowerCase());
5209
+ if (!command) {
5210
+ const suggestion = suggestSimilar(
5211
+ token,
5212
+ commands.flatMap((c) => [c.name, ...c.aliases])
5213
+ );
5214
+ throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
5215
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
5216
+ });
5217
+ }
5218
+ printCommandHelp(command);
5197
5219
  }
5198
- function isMihomoProcess(pid) {
5199
- return isProbedMihomo(probeProcess(pid));
5220
+ function printVersion() {
5221
+ const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
5222
+ console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
5223
+ console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
5224
+ console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
5200
5225
  }
5201
- function getMihomoPids() {
5202
- const result = spawnSync3("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5203
- if (result.error || result.status === null) {
5204
- throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5205
- hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
5206
- });
5226
+
5227
+ // src/redact.ts
5228
+ var SECRET_KEYS = /* @__PURE__ */ new Set(["password", "uuid", "private-key", "pre-shared-key", "auth-str", "auth", "obfs-password", "token", "secret"]);
5229
+ var URL_PROVIDER_KEYS = /* @__PURE__ */ new Set(["proxy-providers", "rule-providers"]);
5230
+ function walk(node, withinProvider, state) {
5231
+ if (Array.isArray(node)) {
5232
+ return node.map((item) => walk(item, withinProvider, state));
5207
5233
  }
5208
- if (result.status !== 0 && result.status !== 1) {
5209
- throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
5210
- hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
5211
- });
5234
+ if (node !== null && typeof node === "object") {
5235
+ const out = {};
5236
+ for (const [key, value] of Object.entries(node)) {
5237
+ const assign = (v) => {
5238
+ if (key === "__proto__") {
5239
+ Object.defineProperty(out, key, { value: v, enumerable: true, writable: true, configurable: true });
5240
+ } else {
5241
+ out[key] = v;
5242
+ }
5243
+ };
5244
+ if (typeof value === "string" && SECRET_KEYS.has(key.toLowerCase())) {
5245
+ assign("***");
5246
+ state.changed = true;
5247
+ } else if (typeof value === "string" && withinProvider && key === "url") {
5248
+ const masked = maskUrl(value);
5249
+ assign(masked);
5250
+ if (masked !== value) state.changed = true;
5251
+ } else {
5252
+ assign(walk(value, withinProvider || URL_PROVIDER_KEYS.has(key), state));
5253
+ }
5254
+ }
5255
+ return out;
5212
5256
  }
5213
- return parsePidList(result.stdout);
5257
+ return node;
5214
5258
  }
5215
- function parsePidList(stdout) {
5216
- const output = stdout.trim();
5217
- if (!output) return [];
5218
- return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5259
+ function redactConfigSecrets(config) {
5260
+ const state = { changed: false };
5261
+ return { config: walk(config, false, state), changed: state.changed };
5219
5262
  }
5220
- function isPidFileOwnedByRoot() {
5221
- if (!fs6.existsSync(PATHS.pidFile)) return false;
5263
+
5264
+ // src/http.ts
5265
+ var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
5266
+ var MAX_REDIRECTS = 20;
5267
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
5268
+ var MAX_ERROR_BODY_BYTES = 64 * 1024;
5269
+ function isHttpsUrl(url) {
5222
5270
  try {
5223
- const stat = fs6.statSync(PATHS.pidFile);
5224
- return stat.uid === 0;
5271
+ return new URL(url).protocol === "https:";
5225
5272
  } catch {
5226
5273
  return false;
5227
5274
  }
5228
5275
  }
5229
- function checkStaleState() {
5230
- const allPids = getMihomoPids();
5231
- return {
5232
- needsCleanup: allPids.length > 0 || isPidFileOwnedByRoot(),
5233
- allPids
5234
- };
5235
- }
5236
- function getStatus() {
5237
- const pid = getPid();
5238
- if (!pid) return { running: false, pid: null, processInfo: null };
5239
- const p = probeProcess(pid);
5240
- if (!isProbedMihomo(p)) return { running: false, pid: null, processInfo: null };
5241
- return {
5242
- running: true,
5243
- pid,
5244
- processInfo: {
5245
- pid,
5246
- memory: p.rss ? `${(p.rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
5247
- isRoot: p.uid === "0"
5248
- }
5249
- };
5250
- }
5251
-
5252
- // src/proxy-probe.ts
5253
- var execFileAsync = promisify2(execFile2);
5254
- function lsofListenPids(port) {
5276
+ function createHttpError(status, bodyText) {
5277
+ const error = new Error(`HTTP ${status}`);
5278
+ error.response = { status };
5255
5279
  try {
5256
- const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5257
- if (r.status !== 0) return null;
5258
- return parsePidList(r.stdout);
5280
+ error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
5259
5281
  } catch {
5260
- return null;
5261
5282
  }
5283
+ return error;
5262
5284
  }
5263
- var PROBE_URL = "https://www.gstatic.com/generate_204";
5264
- function isProbeSuccessStatus(code) {
5265
- return code !== null && code >= 200 && code < 300;
5266
- }
5267
- var PROBE_TIMEOUT_MS = 2e3;
5268
- async function probeProxyConnectivity(port) {
5269
- const start = Date.now();
5270
- try {
5271
- const { stdout } = await execFileAsync(
5272
- "curl",
5273
- ["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
5274
- {
5275
- timeout: PROBE_TIMEOUT_MS + 2e3,
5276
- // 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
5277
- env: buildCurlSpawnEnv()
5278
- }
5279
- );
5280
- const code = Number.parseInt(stdout.trim(), 10);
5281
- const statusCode = Number.isFinite(code) ? code : null;
5282
- const ok = isProbeSuccessStatus(statusCode);
5283
- return {
5284
- ok,
5285
- statusCode,
5286
- error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
5287
- durationMs: Date.now() - start
5288
- };
5289
- } catch (e) {
5290
- const err = e;
5291
- const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
5292
- return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
5285
+ function createHttpClient(options = {}) {
5286
+ const { timeout = 6e4 } = options;
5287
+ return {
5288
+ async get(url, config) {
5289
+ const controller = new AbortController();
5290
+ const timer = setTimeout(() => controller.abort(), timeout);
5291
+ const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
5292
+ try {
5293
+ let currentUrl = url;
5294
+ let response;
5295
+ for (let hop = 0; ; hop++) {
5296
+ response = await fetch(currentUrl, {
5297
+ signal,
5298
+ redirect: "manual",
5299
+ headers: { "User-Agent": `mihomo-cli/${VERSION}` }
5300
+ });
5301
+ if (!REDIRECT_STATUSES.has(response.status)) break;
5302
+ if (hop >= MAX_REDIRECTS) {
5303
+ throw new Error(`\u91CD\u5B9A\u5411\u6B21\u6570\u8D85\u8FC7 ${MAX_REDIRECTS}\uFF0C\u5DF2\u4E2D\u6B62: ${maskUrl(url)}`);
5304
+ }
5305
+ const location = response.headers.get("location");
5306
+ if (!location) break;
5307
+ const nextUrl = new URL(location, currentUrl).toString();
5308
+ if (isHttpsUrl(url) && !isHttpsUrl(nextUrl)) {
5309
+ throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(nextUrl)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
5310
+ }
5311
+ await response.body?.cancel().catch(() => void 0);
5312
+ currentUrl = nextUrl;
5313
+ }
5314
+ if (!response.ok) {
5315
+ let text2 = "";
5316
+ try {
5317
+ text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
5318
+ } catch {
5319
+ }
5320
+ throw createHttpError(response.status, text2);
5321
+ }
5322
+ const declaredLen = Number(response.headers.get("content-length"));
5323
+ if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
5324
+ throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
5325
+ }
5326
+ const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
5327
+ const data = config?.responseType === "json" ? JSON.parse(text) : text;
5328
+ return { data, headers: response.headers };
5329
+ } catch (e) {
5330
+ if (controller.signal.aborted && e.name === "AbortError") {
5331
+ throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
5332
+ }
5333
+ throw e;
5334
+ } finally {
5335
+ clearTimeout(timer);
5336
+ }
5337
+ }
5338
+ };
5339
+ }
5340
+ async function readBodyWithLimit(response, controller, limit) {
5341
+ if (!response.body) return response.text();
5342
+ const reader = response.body.getReader();
5343
+ const chunks = [];
5344
+ let total = 0;
5345
+ try {
5346
+ while (true) {
5347
+ const { done, value } = await reader.read();
5348
+ if (done) break;
5349
+ if (value) {
5350
+ total += value.byteLength;
5351
+ if (total > limit) {
5352
+ controller.abort();
5353
+ throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
5354
+ }
5355
+ chunks.push(value);
5356
+ }
5357
+ }
5358
+ } finally {
5359
+ reader.releaseLock();
5293
5360
  }
5361
+ return Buffer.concat(chunks).toString("utf8");
5294
5362
  }
5295
5363
 
5296
- // src/stop-epoch.ts
5297
- import fs7 from "fs";
5298
- function readStopEpoch() {
5364
+ // src/spinner.ts
5365
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
5366
+ var INTERVAL_MS = 80;
5367
+ async function withSpinner(label, fn) {
5368
+ if (!process.stdout.isTTY) {
5369
+ console.log(label);
5370
+ return fn();
5371
+ }
5372
+ const start = Date.now();
5373
+ let frame = 0;
5374
+ const render = () => {
5375
+ const secs = ((Date.now() - start) / 1e3).toFixed(0);
5376
+ process.stdout.write(`\r${colors.cyan(FRAMES[frame])} ${label} ${colors.gray(`${secs}s`)}\x1B[K`);
5377
+ frame = (frame + 1) % FRAMES.length;
5378
+ };
5379
+ render();
5380
+ const timer = setInterval(render, INTERVAL_MS);
5299
5381
  try {
5300
- const n = Number.parseInt(fs7.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5301
- return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5302
- } catch {
5303
- return 0;
5382
+ return await fn();
5383
+ } finally {
5384
+ clearInterval(timer);
5385
+ process.stdout.write("\r\x1B[K");
5304
5386
  }
5305
5387
  }
5306
- var stopEpochBaselineCaptured = null;
5307
- function captureStopEpochBaseline() {
5308
- stopEpochBaselineCaptured = readStopEpoch();
5309
- return stopEpochBaselineCaptured;
5388
+
5389
+ // src/subscription.ts
5390
+ function resolveUpdateInterval(cachedInterval) {
5391
+ return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
5310
5392
  }
5311
- function stopEpochBaseline() {
5312
- return stopEpochBaselineCaptured ?? readStopEpoch();
5393
+ function isSubscriptionStale(cached, nowMs = Date.now()) {
5394
+ if (!cached.updated_at) return false;
5395
+ const t = new Date(cached.updated_at).getTime();
5396
+ if (Number.isNaN(t) || t > nowMs) return false;
5397
+ const ageHours = (nowMs - t) / 36e5;
5398
+ return ageHours > resolveUpdateInterval(cached.update_interval);
5313
5399
  }
5314
- function bumpStopEpoch() {
5400
+ var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
5401
+ function isValidHttpUrl(url) {
5315
5402
  try {
5316
- ensureDirs();
5317
- atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
5403
+ const u = new URL(url.trim());
5404
+ return u.protocol === "http:" || u.protocol === "https:";
5318
5405
  } catch {
5406
+ return false;
5319
5407
  }
5320
5408
  }
5321
- function recordServiceStopped() {
5322
- bumpStopEpoch();
5409
+ function parseUserInfo(header) {
5410
+ if (!header) return null;
5411
+ const info = {};
5412
+ let hasAny = false;
5413
+ for (const part of header.split(";")) {
5414
+ const [rawKey, rawVal] = part.split("=");
5415
+ const key = rawKey?.trim();
5416
+ const val = rawVal?.trim();
5417
+ if (!key || val === void 0 || val === "") continue;
5418
+ const numVal = Number(val);
5419
+ if (!Number.isFinite(numVal) || numVal < 0) continue;
5420
+ info[key] = numVal;
5421
+ hasAny = true;
5422
+ }
5423
+ return hasAny ? info : null;
5323
5424
  }
5324
- function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5325
- return stopEpochNow !== stopEpochBefore;
5425
+ function parsePositiveInterval(header) {
5426
+ if (!header) return null;
5427
+ const n = parseInt(header, 10);
5428
+ return Number.isFinite(n) && n > 0 ? n : null;
5326
5429
  }
5327
- function startAbortedByConcurrentStop() {
5328
- return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
5430
+ function parseUsernameFromContentDisposition(header) {
5431
+ if (!header) return null;
5432
+ const match = header.match(/filename\s*=\s*["']?([^"';\s]+)["']?/i);
5433
+ if (!match) return null;
5434
+ const filename = match[1];
5435
+ const parts = filename.split("/");
5436
+ return parts[parts.length - 1] || null;
5329
5437
  }
5330
-
5331
- // src/hot-reload.ts
5332
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
5333
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5334
- function logOversized() {
5335
- try {
5336
- return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5337
- } catch {
5338
- return false;
5339
- }
5438
+ function extractSubscriptionMeta(headers) {
5439
+ return {
5440
+ userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
5441
+ updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
5442
+ // 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
5443
+ webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
5444
+ username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
5445
+ };
5340
5446
  }
5341
- async function tryHotReload(prefetched) {
5342
- const controller = new AbortController();
5343
- try {
5344
- const status = prefetched ?? getServiceStatus({ withDisabled: false });
5345
- if (!status.running || status.pid === null) return false;
5346
- const endpoint = getControllerEndpoint();
5347
- if (endpoint.port === null) return false;
5348
- const baseUrl = `http://127.0.0.1:${endpoint.port}`;
5349
- const headers = { "Content-Type": "application/json" };
5350
- if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
5351
- const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
5352
- try {
5353
- const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
5354
- if (!probe.ok) return false;
5355
- const info = await probe.json();
5356
- if (typeof info?.version !== "string") return false;
5357
- const listenerPids = lsofListenPids(endpoint.port);
5358
- if (listenerPids === null || listenerPids[0] !== status.pid) return false;
5359
- const res = await fetch(`${baseUrl}/configs?force=true`, {
5360
- method: "PUT",
5361
- headers,
5362
- body: "{}",
5363
- signal: controller.signal
5364
- });
5365
- return res.ok;
5366
- } finally {
5367
- clearTimeout(timer);
5368
- }
5369
- } catch {
5370
- return false;
5447
+ function saveSubscriptionMeta(subName, meta) {
5448
+ const cacheData = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
5449
+ if (meta.userInfo) {
5450
+ const { upload, download, total, expire } = meta.userInfo;
5451
+ if (upload !== void 0) cacheData.upload = upload;
5452
+ if (download !== void 0) cacheData.download = download;
5453
+ if (total !== void 0) cacheData.total = total;
5454
+ if (expire !== void 0) cacheData.expire = expire;
5371
5455
  }
5456
+ if (meta.updateInterval) cacheData.update_interval = meta.updateInterval;
5457
+ if (meta.webPageUrl) cacheData.web_page_url = meta.webPageUrl;
5458
+ if (meta.username) cacheData.username = meta.username;
5459
+ saveSubscriptionCache(subName, cacheData);
5372
5460
  }
5373
- function concludeHotReload(stopEpochBefore, stopEpochNow) {
5374
- return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5461
+ function formatProxySummary(info) {
5462
+ const parts = [];
5463
+ if (info.proxyGroups && info.proxyGroups > 0) parts.push(`${info.proxyGroups} \u7EC4`);
5464
+ parts.push(`${info.proxies || 0} \u8282\u70B9`);
5465
+ return parts.join(", ");
5375
5466
  }
5376
-
5377
- // src/log-files.ts
5378
- import fs9 from "fs";
5379
- import path5 from "path";
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);
5467
+ function getActiveSubscription() {
5468
+ const settings = readSettings();
5469
+ const subs = getSubscriptions(settings);
5470
+ if (subs.length === 0) return null;
5471
+ const activeName = settings.active_subscription;
5472
+ if (activeName) {
5473
+ const found = subs.find((s) => s.name === activeName);
5474
+ if (found) return found;
5475
+ }
5476
+ return subs[0];
5385
5477
  }
5386
- function rotateAndCleanupLogs() {
5387
- rotateLog();
5388
- cleanupOldLogs();
5478
+ function noSubscriptionsError() {
5479
+ return new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
5389
5480
  }
5390
- function readLogTail() {
5391
- const TAIL_BYTES = 64 * 1024;
5392
- let fd = null;
5393
- try {
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
- }
5481
+ function requireActiveSubscription() {
5482
+ const sub = getActiveSubscription();
5483
+ if (!sub) {
5484
+ throw noSubscriptionsError();
5411
5485
  }
5486
+ return sub;
5412
5487
  }
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 {
5488
+ function resolveSubscription(subs, pattern) {
5489
+ const lowerPattern = pattern.toLowerCase();
5490
+ const exact = [];
5491
+ const prefix = [];
5492
+ const includes = [];
5493
+ for (const s of subs) {
5494
+ const name = s.name.toLowerCase();
5495
+ if (name === lowerPattern) {
5496
+ exact.push(s);
5497
+ } else if (name.startsWith(lowerPattern)) {
5498
+ prefix.push(s);
5499
+ } else if (name.includes(lowerPattern)) {
5500
+ includes.push(s);
5429
5501
  }
5430
- return archivePath;
5431
5502
  }
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`]
5503
+ const matched = exact.length > 0 ? exact : prefix.length > 0 ? prefix : includes;
5504
+ if (matched.length === 0) {
5505
+ throw new CliError(`\u672A\u627E\u5230\u5339\u914D "${pattern}" \u7684\u8BA2\u9605`);
5506
+ }
5507
+ if (matched.length === 1) return matched[0];
5508
+ throw new CliError("\u5339\u914D\u5230\u591A\u4E2A\u8BA2\u9605\uFF0C\u8BF7\u66F4\u7CBE\u786E\u6307\u5B9A", {
5509
+ hint: ["", "\u5339\u914D\u7684\u8BA2\u9605:", ...matched.map((s) => ` ${s.name}`)]
5435
5510
  });
5436
5511
  }
5437
- function rotateLog() {
5438
- const logFile = PATHS.logFile;
5439
- let stat;
5512
+ function assertLooksLikeSubscription(parsed, maskedUrl) {
5513
+ const hasProxies = Array.isArray(parsed.proxies) && parsed.proxies.length > 0;
5514
+ const hasGroups = Array.isArray(parsed["proxy-groups"]) && parsed["proxy-groups"].length > 0;
5515
+ const providers = parsed["proxy-providers"];
5516
+ const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
5517
+ if (hasProxies || hasGroups || hasProviders) return;
5518
+ const serverMsg = sanitizeTerminal(
5519
+ ["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
5520
+ );
5521
+ throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
5522
+ label: "\u8BA2\u9605\u65E0\u6548",
5523
+ hint: [
5524
+ ...serverMsg ? [`\u670D\u52A1\u7AEF\u8FD4\u56DE: ${serverMsg}`] : [],
5525
+ `URL: ${maskedUrl}`,
5526
+ "\u5E38\u89C1\u539F\u56E0\uFF1A\u8BA2\u9605\u94FE\u63A5\u8FC7\u671F\u3001\u6D41\u91CF\u8017\u5C3D\u3001\u9700\u8981\u91CD\u65B0\u83B7\u53D6\u8BA2\u9605\u5730\u5740\u3002",
5527
+ "\u78C1\u76D8\u4E0A\u539F\u6709\u7684\u8BA2\u9605\u914D\u7F6E\u672A\u88AB\u8986\u76D6\u3002"
5528
+ ]
5529
+ });
5530
+ }
5531
+ async function downloadSubscription(url, subName, signal) {
5532
+ let response;
5440
5533
  try {
5441
- stat = fs9.statSync(logFile);
5534
+ response = await HTTP_CLIENT.get(url, { responseType: "text", signal });
5442
5535
  } catch (e) {
5443
- if (e.code === "ENOENT") return;
5444
- throw e;
5536
+ const maskedUrl = maskUrl(url);
5537
+ let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
5538
+ const err = e;
5539
+ if (err.response) {
5540
+ errorMsg += ` (HTTP ${err.response.status})`;
5541
+ }
5542
+ errorMsg += `
5543
+ URL: ${maskedUrl}`;
5544
+ throw new Error(errorMsg);
5445
5545
  }
5446
- if (stat.size === 0) return;
5447
- const rotatedPath = allocateArchivePath();
5546
+ const content = response.data;
5547
+ if (!content?.trim()) {
5548
+ throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
5549
+ }
5550
+ const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
5551
+ assertLooksLikeSubscription(parsed, maskUrl(url));
5552
+ saveSubscriptionRawConfig(subName, content);
5553
+ const meta = extractSubscriptionMeta(response.headers);
5448
5554
  try {
5449
- fs9.renameSync(logFile, rotatedPath);
5555
+ saveSubscriptionMeta(subName, meta);
5450
5556
  } catch (e) {
5451
5557
  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
- }
5558
+ removeSubscriptionRawConfig(subName);
5473
5559
  } catch {
5474
5560
  }
5561
+ throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
5562
+ label: "\u66F4\u65B0\u5931\u8D25",
5563
+ // 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
5564
+ // 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
5565
+ hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
5566
+ });
5475
5567
  }
5568
+ const { proxies, proxyGroups } = countConfigNodes(parsed);
5569
+ return { proxies, proxyGroups };
5476
5570
  }
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
5571
+ async function prepareConfigForStart(mode, subName) {
5572
+ let rawContent;
5573
+ try {
5574
+ rawContent = requireSubscriptionRawConfig(subName);
5575
+ } catch (e) {
5576
+ if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
5577
+ throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
5578
+ hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
5503
5579
  });
5504
- } catch {
5505
5580
  }
5581
+ throw e;
5506
5582
  }
5507
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5508
- return result;
5583
+ const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
5584
+ const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
5585
+ await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
5586
+ return {
5587
+ buildResult,
5588
+ info: countConfigNodes(buildResult.config)
5589
+ };
5509
5590
  }
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";
5591
+ function commitPreparedConfig(prepared) {
5592
+ const { buildResult } = prepared;
5593
+ if (buildResult.warnings.length > 0) {
5594
+ for (const warning of buildResult.warnings) {
5595
+ console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
5596
+ }
5597
+ console.log("");
5524
5598
  }
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`);
5599
+ writeMihomoConfig(buildResult.config);
5600
+ return prepared.info;
5534
5601
  }
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`);
5602
+ function needsAutoUpdate(sub) {
5603
+ if (!sub.updated_at) return true;
5604
+ const lastUpdate = new Date(sub.updated_at).getTime();
5605
+ if (Number.isNaN(lastUpdate)) return true;
5606
+ if (lastUpdate > Date.now()) return true;
5607
+ const intervalHours = resolveUpdateInterval(sub.update_interval);
5608
+ const intervalMs = intervalHours * 60 * 60 * 1e3;
5609
+ return Date.now() - lastUpdate > intervalMs;
5537
5610
  }
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);
5611
+ async function tryUpdateOne(sub, signal) {
5546
5612
  try {
5547
- const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5548
- if (result.error) {
5549
- if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
5550
- throw result.error;
5551
- }
5552
- if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
5553
- } finally {
5554
- try {
5555
- fs10.unlinkSync(scriptPath);
5556
- } catch {
5557
- }
5613
+ const info = await downloadSubscription(sub.url, sub.name, signal);
5614
+ return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
5615
+ } catch (e) {
5616
+ return { name: sub.name, success: false, aborted: signal?.aborted === true, error: e.message };
5558
5617
  }
5559
5618
  }
5560
-
5561
- // src/process-stop.ts
5562
- var PROCESS_WAIT_ATTEMPTS = 50;
5563
- var PROCESS_WAIT_INTERVAL = 100;
5564
- var BATCH_KILL_THRESHOLD = 3;
5565
- function clearRuntime() {
5566
- if (fs11.existsSync(DIRS.runtime)) {
5567
- rmrf(DIRS.runtime);
5619
+ function printUpdateResult(r) {
5620
+ if (r.success) {
5621
+ console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
5622
+ } else if (r.aborted) {
5623
+ console.log(`${colors.gray("\xB7")} ${r.name}: ${colors.gray("\u8DF3\u8FC7\uFF08\u66F4\u65B0\u8D85\u65F6\uFF0C\u4F7F\u7528\u672C\u5730\u7F13\u5B58\uFF09")}`);
5624
+ } else {
5625
+ console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${firstLine(r.error || "")})`);
5568
5626
  }
5569
- ensureDirs();
5570
- }
5571
- function describePidCleanupFailure(err) {
5572
- return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
5573
- }
5574
- var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
5575
- function printResidueWarning(remaining) {
5576
- console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
5577
- console.log(MANUAL_PKILL_HINT);
5578
5627
  }
5579
- function warnPidCleanupFailed(err) {
5580
- if (!err) return;
5581
- console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5582
- }
5583
- function clearPid() {
5584
- try {
5585
- fs11.unlinkSync(PATHS.pidFile);
5586
- return null;
5587
- } catch (e) {
5588
- if (e.code === "ENOENT") return null;
5589
- return e;
5628
+ async function autoUpdateStaleSubscription(options = {}) {
5629
+ const allSubs = getSubscriptionsWithCache();
5630
+ const staleSubs = allSubs.filter(needsAutoUpdate);
5631
+ if (staleSubs.length === 0) {
5632
+ return;
5590
5633
  }
5591
- }
5592
- function pidAlive(pid) {
5634
+ if (staleSubs.length === 1) {
5635
+ const sub = staleSubs[0];
5636
+ const interval = resolveUpdateInterval(sub.update_interval);
5637
+ console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
5638
+ } else {
5639
+ console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
5640
+ }
5641
+ const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
5642
+ const controller = new AbortController();
5643
+ const results = [];
5644
+ const updatePromise = Promise.all(
5645
+ staleSubs.map(
5646
+ (sub) => tryUpdateOne(sub, controller.signal).then((r) => {
5647
+ results.push(r);
5648
+ return r;
5649
+ })
5650
+ )
5651
+ );
5593
5652
  try {
5594
- process.kill(pid, 0);
5595
- return true;
5653
+ await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
5596
5654
  } catch (e) {
5597
- return e.code !== "ESRCH";
5655
+ if (!(e instanceof TimeoutError)) throw e;
5656
+ controller.abort();
5657
+ await updatePromise.catch(() => {
5658
+ });
5659
+ console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
5660
+ }
5661
+ for (const r of results) {
5662
+ printUpdateResult(r);
5598
5663
  }
5599
5664
  }
5600
- async function waitUntilNoMihomo(pids) {
5601
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
5602
- if (!pids.some(pidAlive)) return;
5603
- await sleep(PROCESS_WAIT_INTERVAL);
5665
+
5666
+ // src/commands/config.ts
5667
+ function cmdConfig(args = []) {
5668
+ assertKnownFlags(args.slice(1), ["-j", "--json", "--reveal"], "config [--json] [--reveal]");
5669
+ assertPositionalCount(args, 0, 1, "mihomo-cli config [--json] [--reveal]");
5670
+ const asJson = hasFlag(args, "-j", "--json");
5671
+ const reveal = hasFlag(args, "--reveal");
5672
+ const active = getActiveSubscription();
5673
+ if (!active) {
5674
+ throw noSubscriptionsError();
5675
+ }
5676
+ const rawContent = requireSubscriptionRawConfig(active.name);
5677
+ const mode = deriveRuntimeMode(getConfigInfo());
5678
+ const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
5679
+ const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
5680
+ const shown = redacted.config;
5681
+ if (asJson) {
5682
+ console.log(JSON.stringify({ config: shown, warnings, redacted: !reveal && redacted.changed }, null, 2));
5683
+ return;
5684
+ }
5685
+ console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
5686
+ console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
5687
+ if (!reveal && redacted.changed) {
5688
+ console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
5689
+ }
5690
+ console.log("");
5691
+ console.log(dumpYaml(shown).trimEnd());
5692
+ if (warnings.length > 0) {
5693
+ console.log("");
5694
+ for (const w of warnings) console.log(colors.yellow(`# ${w}`));
5604
5695
  }
5605
5696
  }
5606
- function killProcess(pid) {
5697
+
5698
+ // src/open.ts
5699
+ import { spawn } from "child_process";
5700
+
5701
+ // src/lifecycle.ts
5702
+ var silentSigint = false;
5703
+ function setSilentSigint(value) {
5704
+ silentSigint = value;
5705
+ }
5706
+ function isSilentSigint() {
5707
+ return silentSigint;
5708
+ }
5709
+
5710
+ // src/open.ts
5711
+ function openUrl(url) {
5607
5712
  try {
5608
- process.kill(pid, "SIGKILL");
5609
- return true;
5713
+ const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
5714
+ child.unref();
5715
+ child.on("error", () => {
5716
+ });
5610
5717
  } catch {
5611
- return false;
5612
5718
  }
5613
5719
  }
5614
- function killAllMihomo() {
5615
- try {
5616
- const result = spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
5617
- if (result.error) return false;
5618
- return result.status === 0 || result.status === 1;
5619
- } catch {
5620
- return false;
5720
+ function viewLogWithTail(logPath, options) {
5721
+ const follow = options?.follow;
5722
+ const lines = options?.lines || 100;
5723
+ console.log(`\u65E5\u5FD7: ${logPath}`);
5724
+ if (follow) {
5725
+ console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5726
+ } else {
5727
+ console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5728
+ `);
5621
5729
  }
5730
+ const tailArgs = [];
5731
+ if (follow) tailArgs.push("-f");
5732
+ tailArgs.push("-n", lines.toString());
5733
+ tailArgs.push(logPath);
5734
+ const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5735
+ if (follow) setSilentSigint(true);
5736
+ tail.on("close", (code) => process.exit(code ?? 0));
5737
+ tail.on("error", (e) => {
5738
+ console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5739
+ process.exit(1);
5740
+ });
5622
5741
  }
5623
- function buildKernelCleanupScript() {
5624
- return [
5625
- "#!/bin/bash",
5626
- // pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
5627
- `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
5628
- "rc=$?",
5629
- "[ $rc -le 1 ] || exit 2",
5630
- "exit 0",
5631
- ""
5632
- ].join("\n");
5742
+
5743
+ // src/commands/shared.ts
5744
+ import readline from "readline";
5745
+
5746
+ // src/log-files.ts
5747
+ import fs6 from "fs";
5748
+ import path5 from "path";
5749
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
5750
+ var LOG_TAIL_LINES = 15;
5751
+ var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5752
+ function isArchiveLogFilename(filename) {
5753
+ return ARCHIVE_LOG_RE.test(filename);
5633
5754
  }
5634
- async function cleanupAll() {
5635
- const pids = getMihomoPids();
5636
- if (pids.length === 0) {
5637
- return { killed: 0, failed: 0, remaining: [], scriptError: null, pidError: clearPid() };
5755
+ function rotateAndCleanupLogs() {
5756
+ rotateLog();
5757
+ cleanupOldLogs();
5758
+ }
5759
+ function readLogTail() {
5760
+ const TAIL_BYTES = 64 * 1024;
5761
+ let fd = null;
5762
+ try {
5763
+ const size = fs6.statSync(PATHS.logFile).size;
5764
+ if (size === 0) return [];
5765
+ const start = Math.max(0, size - TAIL_BYTES);
5766
+ const length = size - start;
5767
+ const buf = Buffer.alloc(length);
5768
+ fd = fs6.openSync(PATHS.logFile, "r");
5769
+ const bytesRead = fs6.readSync(fd, buf, 0, length, start);
5770
+ return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5771
+ } catch {
5772
+ return [];
5773
+ } finally {
5774
+ if (fd !== null) {
5775
+ try {
5776
+ fs6.closeSync(fd);
5777
+ } catch {
5778
+ }
5779
+ }
5638
5780
  }
5639
- let killedCount = 0;
5640
- const failedPids = [];
5641
- let scriptError = null;
5642
- const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
5643
- const rootPids = pids.filter((pid) => probes.get(pid)?.uid === "0");
5644
- if (rootPids.length > 0) {
5645
- console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
5781
+ }
5782
+ var MAX_ARCHIVE_SEQ = 1e3;
5783
+ function allocateArchivePath() {
5784
+ const timestamp = formatLocalTimestamp();
5785
+ for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5786
+ const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5787
+ const archivePath = path5.join(DIRS.logs, name);
5788
+ let fd = null;
5646
5789
  try {
5647
- runSudoScript(buildKernelCleanupScript(), {
5648
- action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B",
5649
- file: "cleanup-residue.sh",
5650
- codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" }
5651
- });
5652
- killedCount = pids.length;
5790
+ fd = fs6.openSync(archivePath, "wx");
5653
5791
  } catch (e) {
5654
- scriptError = e;
5792
+ if (e.code === "EEXIST") continue;
5793
+ throw e;
5655
5794
  }
5656
- } else if (pids.length > BATCH_KILL_THRESHOLD) {
5657
- if (killAllMihomo()) {
5658
- killedCount = pids.length;
5659
- } else {
5660
- failedPids.push(...pids);
5795
+ try {
5796
+ fs6.closeSync(fd);
5797
+ } catch {
5661
5798
  }
5662
- } else {
5663
- for (const pid of pids) {
5664
- const probed = probes.get(pid);
5665
- if (!probed || !isProbedMihomo(probed)) {
5666
- killedCount++;
5667
- continue;
5668
- }
5669
- if (killProcess(pid)) {
5670
- killedCount++;
5671
- } else {
5672
- failedPids.push(pid);
5673
- }
5799
+ return archivePath;
5800
+ }
5801
+ 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`, {
5802
+ label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5803
+ 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`]
5804
+ });
5805
+ }
5806
+ function rotateLog() {
5807
+ const logFile = PATHS.logFile;
5808
+ let stat;
5809
+ try {
5810
+ stat = fs6.statSync(logFile);
5811
+ } catch (e) {
5812
+ if (e.code === "ENOENT") return;
5813
+ throw e;
5814
+ }
5815
+ if (stat.size === 0) return;
5816
+ const rotatedPath = allocateArchivePath();
5817
+ try {
5818
+ fs6.renameSync(logFile, rotatedPath);
5819
+ } catch (e) {
5820
+ try {
5821
+ fs6.unlinkSync(rotatedPath);
5822
+ } catch {
5674
5823
  }
5824
+ if (e.code === "ENOENT") return;
5825
+ throw e;
5675
5826
  }
5676
- await waitUntilNoMihomo(pids);
5677
- const remaining = getMihomoPids();
5678
- const pidError = remaining.length === 0 ? clearPid() : null;
5679
- return { killed: killedCount, failed: failedPids.length, remaining, scriptError, pidError };
5680
5827
  }
5681
- function buildRootResidueCleanupError(result, ctx) {
5682
- const { scriptError, pidError } = result;
5683
- const hasKernelResidue = result.remaining.length > 0;
5684
- const pidList = `PID ${result.remaining.join(", ")}`;
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";
5686
- const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
5687
- hint.push(hasKernelResidue || scriptError ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
5688
- if (scriptError instanceof SudoAuthError) {
5689
- return new CliError(`${describeSudoFailure(scriptError)}\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406`, { label: "\u5DF2\u53D6\u6D88", hint });
5828
+ function cleanupOldLogs() {
5829
+ const logsDir = DIRS.logs;
5830
+ if (!fs6.existsSync(logsDir)) return;
5831
+ const files = fs6.readdirSync(logsDir);
5832
+ const now = Date.now();
5833
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5834
+ for (const file of files) {
5835
+ if (!isArchiveLogFilename(file)) continue;
5836
+ try {
5837
+ const filePath = path5.join(logsDir, file);
5838
+ const stat = fs6.statSync(filePath);
5839
+ if (now - stat.mtimeMs > maxAgeMs) {
5840
+ fs6.unlinkSync(filePath);
5841
+ }
5842
+ } catch {
5843
+ }
5690
5844
  }
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 });
5692
5845
  }
5693
- function classifyResidueCleanup(result) {
5694
- if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
5695
- return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
5696
- }
5697
- function warnResidueCleanup(result, ctx) {
5698
- const err = buildRootResidueCleanupError(result, ctx);
5699
- console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
5700
- for (const line of err.hint) console.warn(colors.gray(line));
5701
- }
5702
- async function cleanupKernelsOrThrow(ctx) {
5703
- const result = await cleanupAll();
5704
- const verdict = classifyResidueCleanup(result);
5705
- if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
5706
- if (verdict === "warn") warnResidueCleanup(result, ctx);
5707
- return result;
5708
- }
5709
- async function stop() {
5710
- const allPids = getMihomoPids();
5711
- if (allPids.length === 0) {
5712
- warnPidCleanupFailed(clearPid());
5713
- clearRuntime();
5714
- return {};
5715
- }
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`));
5721
- }
5722
- }
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 };
5846
+ function listLogs() {
5847
+ const logsDir = DIRS.logs;
5848
+ const result = { current: null, archives: [] };
5849
+ if (fs6.existsSync(PATHS.logFile)) {
5850
+ const stat = fs6.statSync(PATHS.logFile);
5851
+ result.current = {
5852
+ name: "mihomo.log (\u5F53\u524D)",
5853
+ path: PATHS.logFile,
5854
+ size: stat.size,
5855
+ mtime: stat.mtime,
5856
+ isCurrent: true
5857
+ };
5731
5858
  }
5732
- clearRuntime();
5733
- return {};
5734
- }
5735
-
5736
- // src/service.ts
5737
- var SERVICE_HEALTH_INTERVAL_MS = 100;
5738
- var SERVICE_OBSERVE_MS = 1200;
5739
- var SERVICE_HEALTH_GRACE_MS = 1800;
5740
- async function waitServiceHealthy() {
5741
- const deadline = Date.now() + SERVICE_OBSERVE_MS;
5742
- const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
5743
- let last = null;
5744
- const unhealthy = (state, crashed, pid = null) => ({
5745
- healthy: false,
5746
- crashed,
5747
- pid,
5748
- exitCode: state.lastExitCode,
5749
- terminatingSignal: state.lastTerminatingSignal
5750
- });
5751
- do {
5752
- await sleep(SERVICE_HEALTH_INTERVAL_MS);
5753
- try {
5754
- last = getServiceStatus({ withDisabled: false });
5755
- } catch {
5756
- continue;
5757
- }
5758
- if (isCrashed(last)) {
5759
- return unhealthy(last, true);
5760
- }
5761
- if (!last.loaded) {
5762
- return unhealthy(last, false);
5763
- }
5764
- } while (Date.now() < deadline);
5765
- if (last === null) return healthViaProcessProbe();
5766
- if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
5767
- let graceQueried = false;
5768
- while (Date.now() < graceDeadline) {
5769
- await sleep(SERVICE_HEALTH_INTERVAL_MS);
5859
+ if (!fs6.existsSync(logsDir)) return result;
5860
+ const files = fs6.readdirSync(logsDir);
5861
+ for (const file of files) {
5862
+ if (!isArchiveLogFilename(file)) continue;
5770
5863
  try {
5771
- last = getServiceStatus({ withDisabled: false });
5864
+ const filePath = path5.join(logsDir, file);
5865
+ const stat = fs6.statSync(filePath);
5866
+ result.archives.push({
5867
+ name: file,
5868
+ path: filePath,
5869
+ size: stat.size,
5870
+ mtime: stat.mtime,
5871
+ isCurrent: false
5872
+ });
5772
5873
  } catch {
5773
- continue;
5774
- }
5775
- graceQueried = true;
5776
- if (isCrashed(last)) {
5777
- return unhealthy(last, true);
5778
5874
  }
5779
- if (!last.loaded) break;
5780
- if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
5781
5875
  }
5782
- if (!graceQueried) return healthViaProcessProbe();
5783
- return unhealthy(last, false, last.pid);
5876
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5877
+ return result;
5784
5878
  }
5785
- function healthViaProcessProbe() {
5879
+
5880
+ // src/process-probe.ts
5881
+ import { spawnSync as spawnSync3 } from "child_process";
5882
+ import fs7 from "fs";
5883
+ var PS_TIMEOUT_MS = 5e3;
5884
+ var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
5885
+ function probeProcess(pid) {
5886
+ if (!pid) return NOT_RUNNING;
5786
5887
  try {
5787
- const pids = getMihomoPids();
5788
- if (pids.length > 0) return { healthy: true, crashed: false, pid: pids[0], exitCode: null, terminatingSignal: null };
5888
+ const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
5889
+ encoding: "utf8",
5890
+ timeout: PS_TIMEOUT_MS
5891
+ });
5892
+ const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
5893
+ if (!match) return NOT_RUNNING;
5894
+ return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
5789
5895
  } catch {
5896
+ return NOT_RUNNING;
5790
5897
  }
5791
- return { healthy: false, crashed: false, pid: null, exitCode: null, terminatingSignal: null };
5792
5898
  }
5793
- function describeExitCause(exitCode, terminatingSignal) {
5794
- if (terminatingSignal !== null) return `\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF08${terminatingSignal}\uFF09`;
5795
- if (exitCode !== null && exitCode !== 0) return `\u9000\u51FA\u7801 ${exitCode}`;
5796
- return null;
5899
+ function isProbedMihomo(p) {
5900
+ return p.alive && (p.command.includes(PATHS.mihomoBinary) || p.command.includes(PATHS.serviceBinary));
5797
5901
  }
5798
- function isCrashed(status) {
5799
- if (status.running) return false;
5800
- return describeExitCause(status.lastExitCode, status.lastTerminatingSignal) !== null;
5902
+ var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
5903
+ var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
5904
+ function getPid() {
5905
+ if (!fs7.existsSync(PATHS.pidFile)) return null;
5906
+ try {
5907
+ const pid = parseInt(fs7.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5908
+ return pid > 0 ? pid : null;
5909
+ } catch {
5910
+ return null;
5911
+ }
5801
5912
  }
5802
- function describeAbnormalExit(status) {
5803
- return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
5913
+ function isRunning() {
5914
+ const pid = getPid();
5915
+ if (!pid) return false;
5916
+ return isMihomoProcess(pid);
5804
5917
  }
5805
- function tunBlockedHint(lastLine) {
5806
- return ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", lastLine];
5918
+ function isMihomoProcess(pid) {
5919
+ return isProbedMihomo(probeProcess(pid));
5807
5920
  }
5808
- function tunBlockedByRunningService() {
5809
- return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
5810
- hint: tunBlockedHint("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1")
5811
- });
5921
+ function getMihomoPids() {
5922
+ const result = spawnSync3("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5923
+ if (result.error || result.status === null) {
5924
+ throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5925
+ hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
5926
+ });
5927
+ }
5928
+ if (result.status !== 0 && result.status !== 1) {
5929
+ throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
5930
+ hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
5931
+ });
5932
+ }
5933
+ return parsePidList(result.stdout);
5812
5934
  }
5813
- function tunBlockedByConcurrentStart() {
5814
- return new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
5815
- hint: tunBlockedHint("\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun")
5816
- });
5935
+ function parsePidList(stdout) {
5936
+ const output = stdout.trim();
5937
+ if (!output) return [];
5938
+ return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5817
5939
  }
5818
- function ensureServiceSymlink() {
5819
- assertKernelInstalled();
5820
- try {
5821
- const current = fs12.readlinkSync(PATHS.serviceBinary);
5822
- if (current === "mihomo") return;
5823
- fs12.unlinkSync(PATHS.serviceBinary);
5824
- } catch (e) {
5825
- const code = e.code;
5826
- if (code === "EINVAL") {
5827
- try {
5828
- fs12.unlinkSync(PATHS.serviceBinary);
5829
- } catch {
5830
- }
5831
- } else if (code !== "ENOENT") {
5832
- throw e;
5833
- }
5834
- }
5940
+ function isPidFileOwnedByRoot() {
5941
+ if (!fs7.existsSync(PATHS.pidFile)) return false;
5835
5942
  try {
5836
- fs12.symlinkSync("mihomo", PATHS.serviceBinary);
5837
- } catch (e) {
5838
- if (e.code !== "EEXIST") throw e;
5839
- let existing;
5840
- try {
5841
- existing = fs12.readlinkSync(PATHS.serviceBinary);
5842
- } catch {
5843
- throw e;
5844
- }
5845
- if (existing !== "mihomo") throw e;
5943
+ const stat = fs7.statSync(PATHS.pidFile);
5944
+ return stat.uid === 0;
5945
+ } catch {
5946
+ return false;
5846
5947
  }
5847
5948
  }
5848
- function bootstrapServiceIdempotentOrThrow(what) {
5849
- const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5850
- if (result.status === 0) return;
5851
- if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
5852
- const detail = result.stderr.trim();
5853
- throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5854
- hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5855
- });
5949
+ function getStatus() {
5950
+ const pid = getPid();
5951
+ if (!pid) return { running: false, pid: null, memory: null };
5952
+ const p = probeProcess(pid);
5953
+ if (!isProbedMihomo(p)) return { running: false, pid: null, memory: null };
5954
+ return {
5955
+ running: true,
5956
+ pid,
5957
+ memory: p.rss ? `${(p.rss / 1024).toFixed(1)} MB` : "\u672A\u77E5"
5958
+ };
5856
5959
  }
5857
- function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5858
- const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
5859
- if (result.status === 0 || isBootoutNotLoaded(result.status)) return;
5860
- const detail = result.stderr.trim();
5861
- throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5862
- hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5863
- });
5960
+
5961
+ // src/process-start.ts
5962
+ import fs13 from "fs";
5963
+
5964
+ // src/service.ts
5965
+ import { spawnSync as spawnSync7 } from "child_process";
5966
+ import fs12 from "fs";
5967
+ import path7 from "path";
5968
+
5969
+ // src/hot-reload.ts
5970
+ import fs9 from "fs";
5971
+
5972
+ // src/proxy-probe.ts
5973
+ import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
5974
+ import { promisify as promisify2 } from "util";
5975
+
5976
+ // src/curl-spawn.ts
5977
+ function buildCurlSpawnEnv() {
5978
+ const env = { ...process.env };
5979
+ env.no_proxy = "";
5980
+ env.NO_PROXY = "";
5981
+ return env;
5864
5982
  }
5865
- async function installService(wasRunning) {
5866
- assertServiceLabelSafe();
5867
- ensureDirs();
5868
- ensureServiceSymlink();
5869
- let restoreSkipped = false;
5870
- const stagePath = PATHS.servicePlistStage;
5871
- atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
5983
+
5984
+ // src/proxy-probe.ts
5985
+ var execFileAsync = promisify2(execFile2);
5986
+ function lsofListenPids(port) {
5872
5987
  try {
5873
- const lint = spawnSync7("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5874
- if (lint.status !== 0) {
5875
- throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
5876
- hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
5877
- });
5878
- }
5879
- bootoutService();
5880
- await waitUntilUnloaded();
5881
- fs12.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5882
- atomicWriteFileSync(PATHS.userAgentPlist, fs12.readFileSync(stagePath, "utf8"), { mode: 420 });
5883
- if (wasRunning) {
5884
- withFileLock(PATHS.serviceLock, () => {
5885
- if (startAbortedByConcurrentStop()) {
5886
- restoreSkipped = true;
5887
- return;
5888
- }
5889
- runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5890
- bootstrapServiceIdempotentOrThrow("\u88C5\u8F7D\u670D\u52A1");
5891
- });
5892
- }
5893
- } finally {
5894
- try {
5895
- fs12.unlinkSync(stagePath);
5896
- } catch {
5897
- }
5898
- }
5899
- if (!wasRunning) {
5900
- disableServiceAutoStart();
5988
+ const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5989
+ if (r.status !== 0) return null;
5990
+ return parsePidList(r.stdout);
5991
+ } catch {
5992
+ return null;
5901
5993
  }
5902
- return { restoreSkipped };
5903
5994
  }
5904
- async function startService() {
5905
- assertServiceLabelSafe();
5906
- ensureServiceSymlink();
5907
- if (!isServiceInstalled()) {
5908
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5995
+ var PROBE_URL = "https://www.gstatic.com/generate_204";
5996
+ function isProbeSuccessStatus(code) {
5997
+ return code !== null && code >= 200 && code < 300;
5998
+ }
5999
+ var PROBE_TIMEOUT_MS = 2e3;
6000
+ async function probeProxyConnectivity(port) {
6001
+ const start = Date.now();
6002
+ try {
6003
+ const { stdout } = await execFileAsync(
6004
+ "curl",
6005
+ ["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
6006
+ {
6007
+ timeout: PROBE_TIMEOUT_MS + 2e3,
6008
+ // 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
6009
+ env: buildCurlSpawnEnv()
6010
+ }
6011
+ );
6012
+ const code = Number.parseInt(stdout.trim(), 10);
6013
+ const statusCode = Number.isFinite(code) ? code : null;
6014
+ const ok = isProbeSuccessStatus(statusCode);
6015
+ return {
6016
+ ok,
6017
+ statusCode,
6018
+ error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
6019
+ durationMs: Date.now() - start
6020
+ };
6021
+ } catch (e) {
6022
+ const err = e;
6023
+ const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
6024
+ return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
5909
6025
  }
5910
- assertRuntimeConfigPresent();
5911
- if (getConfigInfo()?.tun) {
5912
- throw new CliError("\u8FD0\u884C\u65F6\u914D\u7F6E\u4E3A TUN \u6A21\u5F0F\uFF0C\u670D\u52A1\u65E0\u6CD5\u4F7F\u7528", {
5913
- hint: [
5914
- "\u670D\u52A1\u4EE5\u666E\u901A\u7528\u6237\u8EAB\u4EFD\u8FD0\u884C\uFF08\u7528\u6237\u7EA7 LaunchAgent\uFF09\uFF0C\u65E0\u6743\u521B\u5EFA TUN \u8BBE\u5907\uFF0C",
5915
- "\u5F3A\u884C\u542F\u52A8\u53EA\u4F1A\u8BA9\u5185\u6838\u53CD\u590D\u5D29\u6E83\u91CD\u542F\u3002",
5916
- "",
5917
- "\u6309 Mixed \u91CD\u5EFA\u914D\u7F6E\u5E76\u542F\u52A8: mihomo-cli start mixed",
5918
- "\u786E\u5B9E\u8981\u7528 TUN: mihomo-cli tun"
5919
- ]
5920
- });
6026
+ }
6027
+
6028
+ // src/stop-epoch.ts
6029
+ import fs8 from "fs";
6030
+ function readStopEpoch() {
6031
+ try {
6032
+ const n = Number.parseInt(fs8.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
6033
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
6034
+ } catch {
6035
+ return 0;
5921
6036
  }
5922
- await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
5923
- bootoutService();
5924
- await waitUntilUnloaded();
5925
- rotateAndCleanupLogs();
5926
- let started = true;
5927
- withFileLock(PATHS.serviceLock, () => {
5928
- if (startAbortedByConcurrentStop()) {
5929
- started = false;
5930
- return;
5931
- }
5932
- runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5933
- bootstrapServiceIdempotentOrThrow("\u542F\u52A8\u670D\u52A1");
5934
- });
5935
- return { started };
5936
6037
  }
5937
- function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5938
- assertServiceLabelSafe();
5939
- runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F", timeoutMs);
5940
- if (!isServiceDisabledInLaunchd(timeoutMs)) {
5941
- throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
5942
- hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
5943
- });
6038
+ var stopEpochBaselineCaptured = null;
6039
+ function captureStopEpochBaseline() {
6040
+ stopEpochBaselineCaptured = readStopEpoch();
6041
+ return stopEpochBaselineCaptured;
6042
+ }
6043
+ function stopEpochBaseline() {
6044
+ return stopEpochBaselineCaptured ?? readStopEpoch();
6045
+ }
6046
+ function bumpStopEpoch() {
6047
+ try {
6048
+ ensureDirs();
6049
+ atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
6050
+ } catch {
5944
6051
  }
6052
+ }
6053
+ function recordServiceStopped() {
5945
6054
  bumpStopEpoch();
5946
6055
  }
5947
- async function bootoutAndDisableInLock() {
5948
- withFileLock(PATHS.serviceLock, () => {
5949
- bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5950
- disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5951
- });
5952
- await waitUntilUnloaded();
6056
+ function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
6057
+ return stopEpochNow !== stopEpochBefore;
5953
6058
  }
5954
- async function stopService() {
5955
- assertServiceLabelSafe();
5956
- await bootoutAndDisableInLock();
5957
- return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
6059
+ function startAbortedByConcurrentStop() {
6060
+ return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
5958
6061
  }
5959
- async function uninstallService() {
5960
- assertServiceLabelSafe();
5961
- await bootoutAndDisableInLock();
6062
+
6063
+ // src/hot-reload.ts
6064
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
6065
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
6066
+ function logOversized() {
5962
6067
  try {
5963
- fs12.rmSync(PATHS.userAgentPlist, { force: true });
5964
- } catch (e) {
5965
- throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
6068
+ return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
6069
+ } catch {
6070
+ return false;
5966
6071
  }
5967
- const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
6072
+ }
6073
+ async function tryHotReload(prefetched) {
6074
+ const controller = new AbortController();
5968
6075
  try {
5969
- fs12.rmSync(PATHS.serviceBinary, { force: true });
6076
+ const status = prefetched ?? getServiceStatus({ withDisabled: false });
6077
+ if (!status.running || status.pid === null) return false;
6078
+ const endpoint = getControllerEndpoint();
6079
+ if (endpoint.port === null) return false;
6080
+ const baseUrl = `http://127.0.0.1:${endpoint.port}`;
6081
+ const headers = { "Content-Type": "application/json" };
6082
+ if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
6083
+ const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
6084
+ try {
6085
+ const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
6086
+ if (!probe.ok) return false;
6087
+ const info = await probe.json();
6088
+ if (typeof info?.version !== "string") return false;
6089
+ const listenerPids = lsofListenPids(endpoint.port);
6090
+ if (listenerPids === null || listenerPids[0] !== status.pid) return false;
6091
+ const res = await fetch(`${baseUrl}/configs?force=true`, {
6092
+ method: "PUT",
6093
+ headers,
6094
+ body: "{}",
6095
+ signal: controller.signal
6096
+ });
6097
+ return res.ok;
6098
+ } finally {
6099
+ clearTimeout(timer);
6100
+ }
5970
6101
  } catch {
6102
+ return false;
5971
6103
  }
5972
- return cleanup;
5973
6104
  }
5974
- async function restartService(prefetched) {
5975
- assertServiceLabelSafe();
5976
- if (!isServiceInstalled()) {
5977
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
6105
+ function concludeHotReload(stopEpochBefore, stopEpochNow) {
6106
+ return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
6107
+ }
6108
+
6109
+ // src/process-stop.ts
6110
+ import { spawnSync as spawnSync6 } from "child_process";
6111
+ import fs11 from "fs";
6112
+
6113
+ // src/sudo.ts
6114
+ import { spawnSync as spawnSync5 } from "child_process";
6115
+ import fs10 from "fs";
6116
+ import path6 from "path";
6117
+ var SUDO_TIMEOUT_MS = 6e4;
6118
+ var SudoAuthError = class extends Error {
6119
+ constructor() {
6120
+ super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
6121
+ this.name = "SudoAuthError";
5978
6122
  }
5979
- const oversized = logOversized();
5980
- if (!oversized && await tryHotReload(prefetched)) {
5981
- return concludeHotReload(stopEpochBaseline(), readStopEpoch());
6123
+ };
6124
+ function describeSudoFailure(e) {
6125
+ return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
6126
+ }
6127
+ function sudoExitToError(action, status, codeMessages) {
6128
+ if (status === 1) return new SudoAuthError();
6129
+ if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
6130
+ const custom = codeMessages?.[status];
6131
+ return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
6132
+ }
6133
+ function sudoTimeoutError(action) {
6134
+ 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`);
6135
+ }
6136
+ function runSudoScript(scriptBody, opts) {
6137
+ if (!process.stdin.isTTY) {
6138
+ 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");
5982
6139
  }
5983
- if (oversized) {
5984
- const archiveFile = allocateArchivePath();
6140
+ ensureDirs();
6141
+ const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
6142
+ fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6143
+ fs10.chmodSync(scriptPath, 448);
6144
+ try {
6145
+ const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
6146
+ if (result.error) {
6147
+ if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
6148
+ throw result.error;
6149
+ }
6150
+ if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
6151
+ } finally {
5985
6152
  try {
5986
- fs12.copyFileSync(PATHS.logFile, archiveFile);
5987
- fs12.writeFileSync(PATHS.logFile, "");
6153
+ fs10.unlinkSync(scriptPath);
5988
6154
  } catch {
5989
6155
  }
5990
6156
  }
5991
- const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
5992
- let started = true;
5993
- if (kick.status !== 0) {
5994
- withFileLock(PATHS.serviceLock, () => {
5995
- if (startAbortedByConcurrentStop()) {
5996
- started = false;
5997
- return;
5998
- }
5999
- runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6000
- bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
6001
- });
6002
- if (!started) return { hotReloaded: false, started: false };
6003
- }
6004
- cleanupOldLogs();
6005
- return { hotReloaded: false, started: true };
6006
6157
  }
6007
6158
 
6008
- // src/suggest.ts
6009
- function levenshtein(a, b) {
6010
- if (a === b) return 0;
6011
- if (a.length === 0) return b.length;
6012
- if (b.length === 0) return a.length;
6013
- let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
6014
- for (let i = 1; i <= a.length; i++) {
6015
- const curr = [i];
6016
- for (let j = 1; j <= b.length; j++) {
6017
- curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
6018
- }
6019
- prev = curr;
6159
+ // src/process-stop.ts
6160
+ var PROCESS_WAIT_ATTEMPTS = 50;
6161
+ var PROCESS_WAIT_INTERVAL = 100;
6162
+ var BATCH_KILL_THRESHOLD = 3;
6163
+ function clearRuntime() {
6164
+ if (fs11.existsSync(DIRS.runtime)) {
6165
+ rmrf(DIRS.runtime);
6020
6166
  }
6021
- return prev[b.length];
6167
+ ensureDirs();
6022
6168
  }
6023
- function suggestSimilar(input, candidates) {
6024
- const lower = input.toLowerCase();
6025
- if (lower === "") return [];
6026
- const scored = [];
6027
- for (const cand of candidates) {
6028
- const c = cand.toLowerCase();
6029
- if (cand === input) continue;
6030
- if (c.startsWith(lower)) {
6031
- scored.push({ name: cand, score: 0, lenDiff: Math.abs(cand.length - input.length) });
6032
- } else if (lower.length >= 3) {
6033
- const d = levenshtein(lower, c);
6034
- if (d <= 2) scored.push({ name: cand, score: d, lenDiff: Math.abs(cand.length - input.length) });
6035
- }
6036
- }
6037
- scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
6038
- return scored.slice(0, 3).map((s) => s.name);
6169
+ function describePidCleanupFailure(err) {
6170
+ return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
6039
6171
  }
6040
-
6041
- // src/commands/help.ts
6042
- function printShortHelp() {
6043
- console.log(`
6044
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo-cli help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
6045
- `);
6046
- const steps = [];
6047
- if (!hasKernel()) steps.push(["mihomo-cli kernel", "\u4E0B\u8F7D\u5185\u6838"]);
6048
- if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
6049
- if (!isServiceInstalled()) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
6050
- if (steps.length > 0) {
6051
- steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
6052
- const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
6053
- console.log("\u5F00\u59CB\u4F7F\u7528:");
6054
- steps.forEach(([cmd, desc], i) => {
6055
- console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
6056
- });
6057
- console.log("");
6058
- return;
6059
- }
6060
- console.log(
6061
- `\u5E38\u7528\u547D\u4EE4:
6062
- ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
6063
- ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
6064
- ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
6065
- ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
6066
- `
6067
- );
6172
+ var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
6173
+ function printResidueWarning(remaining) {
6174
+ console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
6175
+ console.log(MANUAL_PKILL_HINT);
6068
6176
  }
6069
- var GROUP_TITLES = [
6070
- ["control", "\u63A7\u5236:"],
6071
- ["interface", "\u754C\u9762:"],
6072
- ["subscription", "\u8BA2\u9605:"],
6073
- ["config", "\u914D\u7F6E:"],
6074
- ["system", "\u7CFB\u7EDF:"]
6075
- ];
6076
- function printHelp(commands) {
6077
- const lines = [`
6078
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mh", "", "\u7528\u6CD5:", " mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"];
6079
- const allUsage = commands.flatMap((c) => c.usage);
6080
- const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
6081
- const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
6082
- for (const [group, title] of GROUP_TITLES) {
6083
- const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
6084
- if (usageLines.length === 0) continue;
6085
- lines.push("", colors.cyan(title));
6086
- for (const u of usageLines) lines.push(formatUsage(u));
6087
- }
6088
- const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
6089
- if (meta.length > 0) {
6090
- lines.push("", colors.cyan("\u5143:"));
6091
- for (const u of meta) lines.push(formatUsage(u));
6177
+ function warnPidCleanupFailed(err) {
6178
+ if (!err) return;
6179
+ console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
6180
+ }
6181
+ function clearPid() {
6182
+ try {
6183
+ fs11.unlinkSync(PATHS.pidFile);
6184
+ return null;
6185
+ } catch (e) {
6186
+ if (e.code === "ENOENT") return null;
6187
+ return e;
6092
6188
  }
6093
- lines.push(
6094
- "",
6095
- `${colors.cyan("\u793A\u4F8B:")}`,
6096
- // 顺序即首次使用的依赖顺序(kernel → 订阅 → 服务 → 启动):install 在无内核时会被
6097
- // 拦下提示先跑 kernel,示例若把 install 放第一条,照着敲的新用户第一步就撞墙
6098
- " mihomo-cli kernel # \u4E0B\u8F7D\u5185\u6838\uFF08\u9996\u6B21\u4F7F\u7528\u7684\u7B2C\u4E00\u6B65\uFF09",
6099
- " mihomo-cli sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
6100
- " mihomo-cli install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
6101
- " mihomo-cli start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
6102
- " mihomo-cli stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
6103
- " mihomo-cli start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
6104
- " mihomo-cli start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
6105
- " mihomo-cli ui # \u6253\u5F00 Web UI",
6106
- "",
6107
- `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
6108
- " tun = start tun",
6109
- " use <name> = subscription use <name>",
6110
- " restart = start\uFF08start \u672C\u8EAB\u5373\u91CD\u542F\uFF09",
6111
- "",
6112
- `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
6113
- " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
6114
- " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
6115
- "",
6116
- `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
6117
- " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
6118
- ` \u9ED8\u8BA4: ${USER_DATA_DIR}`
6119
- );
6120
- console.log(lines.join("\n"));
6121
6189
  }
6122
- function printCommandHelp(command) {
6123
- const aliasText = command.aliases.length > 0 ? colors.gray(`\uFF08\u522B\u540D: ${command.aliases.join(", ")}\uFF09`) : "";
6124
- const lines = ["", `${colors.cyan(colors.bold(`mihomo-cli ${command.name}`))}${aliasText}`];
6125
- if (command.usage.length > 0) {
6126
- lines.push("", "\u7528\u6CD5:");
6127
- const width = Math.max(...command.usage.map((u) => displayWidth(u.signature)));
6128
- for (const u of command.usage) {
6129
- lines.push(` ${colors.bold(padEndDisplay(u.signature, width))} ${u.description}`);
6130
- }
6131
- } else {
6132
- lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo-cli help"));
6190
+ function pidAlive(pid) {
6191
+ try {
6192
+ process.kill(pid, 0);
6193
+ return true;
6194
+ } catch (e) {
6195
+ return e.code !== "ESRCH";
6133
6196
  }
6134
- console.log(lines.join("\n"));
6135
6197
  }
6136
- function printHelpEntry(args, commands, finder) {
6137
- const token = args[1];
6138
- if (!token) {
6139
- printHelp(commands);
6140
- return;
6198
+ async function waitUntilNoMihomo(pids) {
6199
+ for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
6200
+ if (!pids.some(pidAlive)) return;
6201
+ await sleep(PROCESS_WAIT_INTERVAL);
6141
6202
  }
6142
- const command = finder(token.toLowerCase());
6143
- if (!command) {
6144
- const suggestion = suggestSimilar(
6145
- token,
6146
- commands.flatMap((c) => [c.name, ...c.aliases])
6147
- );
6148
- throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
6149
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
6150
- });
6203
+ }
6204
+ function killProcess(pid) {
6205
+ try {
6206
+ process.kill(pid, "SIGKILL");
6207
+ } catch {
6151
6208
  }
6152
- printCommandHelp(command);
6153
6209
  }
6154
- function printVersion() {
6155
- const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
6156
- console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
6157
- console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
6158
- console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
6210
+ function killAllMihomo() {
6211
+ spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
6159
6212
  }
6160
-
6161
- // src/redact.ts
6162
- var SECRET_KEYS = /* @__PURE__ */ new Set(["password", "uuid", "private-key", "pre-shared-key", "auth-str", "auth", "obfs-password", "token", "secret"]);
6163
- var URL_PROVIDER_KEYS = /* @__PURE__ */ new Set(["proxy-providers", "rule-providers"]);
6164
- function walk(node, withinProvider, state) {
6165
- if (Array.isArray(node)) {
6166
- return node.map((item) => walk(item, withinProvider, state));
6213
+ function buildKernelCleanupScript() {
6214
+ return [
6215
+ "#!/bin/bash",
6216
+ // pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
6217
+ `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
6218
+ "rc=$?",
6219
+ "[ $rc -le 1 ] || exit 2",
6220
+ "exit 0",
6221
+ ""
6222
+ ].join("\n");
6223
+ }
6224
+ async function cleanupAll() {
6225
+ const pids = getMihomoPids();
6226
+ if (pids.length === 0) {
6227
+ return { remaining: [], scriptError: null, pidError: clearPid() };
6167
6228
  }
6168
- if (node !== null && typeof node === "object") {
6169
- const out = {};
6170
- for (const [key, value] of Object.entries(node)) {
6171
- const assign = (v) => {
6172
- if (key === "__proto__") {
6173
- Object.defineProperty(out, key, { value: v, enumerable: true, writable: true, configurable: true });
6174
- } else {
6175
- out[key] = v;
6176
- }
6177
- };
6178
- if (typeof value === "string" && SECRET_KEYS.has(key.toLowerCase())) {
6179
- assign("***");
6180
- state.changed = true;
6181
- } else if (typeof value === "string" && withinProvider && key === "url") {
6182
- const masked = maskUrl(value);
6183
- assign(masked);
6184
- if (masked !== value) state.changed = true;
6185
- } else {
6186
- assign(walk(value, withinProvider || URL_PROVIDER_KEYS.has(key), state));
6187
- }
6229
+ let scriptError = null;
6230
+ const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
6231
+ const rootPids = pids.filter((pid) => probes.get(pid)?.uid === "0");
6232
+ if (rootPids.length > 0) {
6233
+ console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
6234
+ try {
6235
+ runSudoScript(buildKernelCleanupScript(), {
6236
+ action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B",
6237
+ file: "cleanup-residue.sh",
6238
+ codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" }
6239
+ });
6240
+ } catch (e) {
6241
+ scriptError = e;
6242
+ }
6243
+ } else if (pids.length > BATCH_KILL_THRESHOLD) {
6244
+ killAllMihomo();
6245
+ } else {
6246
+ for (const pid of pids) {
6247
+ const probed = probes.get(pid);
6248
+ if (probed && isProbedMihomo(probed)) killProcess(pid);
6188
6249
  }
6189
- return out;
6190
6250
  }
6191
- return node;
6192
- }
6193
- function redactConfigSecrets(config) {
6194
- const state = { changed: false };
6195
- return { config: walk(config, false, state), changed: state.changed };
6251
+ await waitUntilNoMihomo(pids);
6252
+ const remaining = getMihomoPids();
6253
+ const pidError = remaining.length === 0 ? clearPid() : null;
6254
+ return { remaining, scriptError, pidError };
6196
6255
  }
6197
-
6198
- // src/http.ts
6199
- var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
6200
- var MAX_REDIRECTS = 20;
6201
- var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
6202
- var MAX_ERROR_BODY_BYTES = 64 * 1024;
6203
- function isHttpsUrl(url) {
6204
- try {
6205
- return new URL(url).protocol === "https:";
6206
- } catch {
6207
- return false;
6256
+ function buildRootResidueCleanupError(result, ctx) {
6257
+ const { scriptError, pidError } = result;
6258
+ const hasKernelResidue = result.remaining.length > 0;
6259
+ const pidList = `PID ${result.remaining.join(", ")}`;
6260
+ const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
6261
+ const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
6262
+ hint.push(hasKernelResidue || scriptError ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
6263
+ if (scriptError instanceof SudoAuthError) {
6264
+ return new CliError(`${describeSudoFailure(scriptError)}\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406`, { label: "\u5DF2\u53D6\u6D88", hint });
6208
6265
  }
6266
+ return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
6209
6267
  }
6210
- function createHttpError(status, bodyText) {
6211
- const error = new Error(`HTTP ${status}`);
6212
- error.response = { status };
6213
- try {
6214
- error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
6215
- } catch {
6216
- }
6217
- return error;
6268
+ function classifyResidueCleanup(result) {
6269
+ if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
6270
+ return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
6218
6271
  }
6219
- function createHttpClient(options = {}) {
6220
- const { timeout = 6e4 } = options;
6221
- return {
6222
- async get(url, config) {
6223
- const controller = new AbortController();
6224
- const timer = setTimeout(() => controller.abort(), timeout);
6225
- const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
6226
- try {
6227
- let currentUrl = url;
6228
- let response;
6229
- for (let hop = 0; ; hop++) {
6230
- response = await fetch(currentUrl, {
6231
- signal,
6232
- redirect: "manual",
6233
- headers: { "User-Agent": `mihomo-cli/${VERSION}` }
6234
- });
6235
- if (!REDIRECT_STATUSES.has(response.status)) break;
6236
- if (hop >= MAX_REDIRECTS) {
6237
- throw new Error(`\u91CD\u5B9A\u5411\u6B21\u6570\u8D85\u8FC7 ${MAX_REDIRECTS}\uFF0C\u5DF2\u4E2D\u6B62: ${maskUrl(url)}`);
6238
- }
6239
- const location = response.headers.get("location");
6240
- if (!location) break;
6241
- const nextUrl = new URL(location, currentUrl).toString();
6242
- if (isHttpsUrl(url) && !isHttpsUrl(nextUrl)) {
6243
- throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(nextUrl)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
6244
- }
6245
- await response.body?.cancel().catch(() => void 0);
6246
- currentUrl = nextUrl;
6247
- }
6248
- if (!response.ok) {
6249
- let text2 = "";
6250
- try {
6251
- text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
6252
- } catch {
6253
- }
6254
- throw createHttpError(response.status, text2);
6255
- }
6256
- const declaredLen = Number(response.headers.get("content-length"));
6257
- if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
6258
- throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
6259
- }
6260
- const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
6261
- const data = config?.responseType === "json" ? JSON.parse(text) : text;
6262
- return { data, headers: response.headers, status: response.status };
6263
- } catch (e) {
6264
- if (controller.signal.aborted && e.name === "AbortError") {
6265
- throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
6266
- }
6267
- throw e;
6268
- } finally {
6269
- clearTimeout(timer);
6270
- }
6271
- }
6272
- };
6272
+ function warnResidueCleanup(result, ctx) {
6273
+ const err = buildRootResidueCleanupError(result, ctx);
6274
+ console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
6275
+ for (const line of err.hint) console.warn(colors.gray(line));
6273
6276
  }
6274
- async function readBodyWithLimit(response, controller, limit) {
6275
- if (!response.body) return response.text();
6276
- const reader = response.body.getReader();
6277
- const chunks = [];
6278
- let total = 0;
6279
- try {
6280
- while (true) {
6281
- const { done, value } = await reader.read();
6282
- if (done) break;
6283
- if (value) {
6284
- total += value.byteLength;
6285
- if (total > limit) {
6286
- controller.abort();
6287
- throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
6288
- }
6289
- chunks.push(value);
6290
- }
6277
+ async function cleanupKernelsOrThrow(ctx) {
6278
+ const result = await cleanupAll();
6279
+ const verdict = classifyResidueCleanup(result);
6280
+ if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
6281
+ if (verdict === "warn") warnResidueCleanup(result, ctx);
6282
+ return result;
6283
+ }
6284
+ async function stop() {
6285
+ const allPids = getMihomoPids();
6286
+ if (allPids.length === 0) {
6287
+ warnPidCleanupFailed(clearPid());
6288
+ clearRuntime();
6289
+ return {};
6290
+ }
6291
+ const result = await cleanupAll();
6292
+ if (result.remaining.length === 0) {
6293
+ warnPidCleanupFailed(result.pidError);
6294
+ if (result.scriptError) {
6295
+ console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo-cli stop`));
6291
6296
  }
6292
- } finally {
6293
- reader.releaseLock();
6294
6297
  }
6295
- return Buffer.concat(chunks).toString("utf8");
6298
+ const remaining = result.remaining;
6299
+ if (remaining.length > 0) {
6300
+ console.log("");
6301
+ console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
6302
+ console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
6303
+ console.log(MANUAL_PKILL_HINT);
6304
+ console.log("");
6305
+ return { remaining };
6306
+ }
6307
+ clearRuntime();
6308
+ return {};
6296
6309
  }
6297
6310
 
6298
- // src/spinner.ts
6299
- var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
6300
- var INTERVAL_MS = 80;
6301
- async function withSpinner(label, fn) {
6302
- if (!process.stdout.isTTY) {
6303
- console.log(label);
6304
- return fn();
6305
- }
6306
- const start = Date.now();
6307
- let frame = 0;
6308
- const render = () => {
6309
- const secs = ((Date.now() - start) / 1e3).toFixed(0);
6310
- process.stdout.write(`\r${colors.cyan(FRAMES[frame])} ${label} ${colors.gray(`${secs}s`)}\x1B[K`);
6311
- frame = (frame + 1) % FRAMES.length;
6312
- };
6313
- render();
6314
- const timer = setInterval(render, INTERVAL_MS);
6315
- try {
6316
- return await fn();
6317
- } finally {
6318
- clearInterval(timer);
6319
- process.stdout.write("\r\x1B[K");
6311
+ // src/service.ts
6312
+ var SERVICE_HEALTH_INTERVAL_MS = 100;
6313
+ var SERVICE_OBSERVE_MS = 1200;
6314
+ var SERVICE_HEALTH_GRACE_MS = 1800;
6315
+ async function waitServiceHealthy() {
6316
+ const deadline = Date.now() + SERVICE_OBSERVE_MS;
6317
+ const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
6318
+ let last = null;
6319
+ const unhealthy = (state, crashed, pid = null) => ({
6320
+ healthy: false,
6321
+ crashed,
6322
+ pid,
6323
+ exitCode: state.lastExitCode,
6324
+ terminatingSignal: state.lastTerminatingSignal
6325
+ });
6326
+ do {
6327
+ await sleep(SERVICE_HEALTH_INTERVAL_MS);
6328
+ try {
6329
+ last = getServiceStatus({ withDisabled: false });
6330
+ } catch {
6331
+ continue;
6332
+ }
6333
+ if (isCrashed(last)) {
6334
+ return unhealthy(last, true);
6335
+ }
6336
+ if (!last.loaded) {
6337
+ return unhealthy(last, false);
6338
+ }
6339
+ } while (Date.now() < deadline);
6340
+ if (last === null) return healthViaProcessProbe();
6341
+ if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
6342
+ let graceQueried = false;
6343
+ while (Date.now() < graceDeadline) {
6344
+ await sleep(SERVICE_HEALTH_INTERVAL_MS);
6345
+ try {
6346
+ last = getServiceStatus({ withDisabled: false });
6347
+ } catch {
6348
+ continue;
6349
+ }
6350
+ graceQueried = true;
6351
+ if (isCrashed(last)) {
6352
+ return unhealthy(last, true);
6353
+ }
6354
+ if (!last.loaded) break;
6355
+ if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
6320
6356
  }
6357
+ if (!graceQueried) return healthViaProcessProbe();
6358
+ return unhealthy(last, false, last.pid);
6321
6359
  }
6322
-
6323
- // src/subscription.ts
6324
- function resolveUpdateInterval(cachedInterval) {
6325
- return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
6326
- }
6327
- function isSubscriptionStale(cached, nowMs = Date.now()) {
6328
- if (!cached.updated_at) return false;
6329
- const t = new Date(cached.updated_at).getTime();
6330
- if (Number.isNaN(t) || t > nowMs) return false;
6331
- const ageHours = (nowMs - t) / 36e5;
6332
- return ageHours > resolveUpdateInterval(cached.update_interval);
6333
- }
6334
- var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
6335
- function isValidHttpUrl(url) {
6360
+ function healthViaProcessProbe() {
6336
6361
  try {
6337
- const u = new URL(url.trim());
6338
- return u.protocol === "http:" || u.protocol === "https:";
6362
+ const pids = getMihomoPids();
6363
+ if (pids.length > 0) return { healthy: true, crashed: false, pid: pids[0], exitCode: null, terminatingSignal: null };
6339
6364
  } catch {
6340
- return false;
6341
- }
6342
- }
6343
- function parseUserInfo(header) {
6344
- if (!header) return null;
6345
- const info = {};
6346
- let hasAny = false;
6347
- for (const part of header.split(";")) {
6348
- const [rawKey, rawVal] = part.split("=");
6349
- const key = rawKey?.trim();
6350
- const val = rawVal?.trim();
6351
- if (!key || val === void 0 || val === "") continue;
6352
- const numVal = Number(val);
6353
- if (!Number.isFinite(numVal) || numVal < 0) continue;
6354
- info[key] = numVal;
6355
- hasAny = true;
6356
- }
6357
- return hasAny ? info : null;
6358
- }
6359
- function parsePositiveInterval(header) {
6360
- if (!header) return null;
6361
- const n = parseInt(header, 10);
6362
- return Number.isFinite(n) && n > 0 ? n : null;
6363
- }
6364
- function parseUsernameFromContentDisposition(header) {
6365
- if (!header) return null;
6366
- const match = header.match(/filename\s*=\s*["']?([^"';\s]+)["']?/i);
6367
- if (!match) return null;
6368
- const filename = match[1];
6369
- const parts = filename.split("/");
6370
- return parts[parts.length - 1] || null;
6371
- }
6372
- function extractSubscriptionMeta(headers) {
6373
- return {
6374
- userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
6375
- updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
6376
- // 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
6377
- webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
6378
- username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
6379
- };
6380
- }
6381
- function saveSubscriptionMeta(subName, meta) {
6382
- const cacheData = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
6383
- if (meta.userInfo) {
6384
- const { upload, download, total, expire } = meta.userInfo;
6385
- if (upload !== void 0) cacheData.upload = upload;
6386
- if (download !== void 0) cacheData.download = download;
6387
- if (total !== void 0) cacheData.total = total;
6388
- if (expire !== void 0) cacheData.expire = expire;
6389
6365
  }
6390
- if (meta.updateInterval) cacheData.update_interval = meta.updateInterval;
6391
- if (meta.webPageUrl) cacheData.web_page_url = meta.webPageUrl;
6392
- if (meta.username) cacheData.username = meta.username;
6393
- saveSubscriptionCache(subName, cacheData);
6366
+ return { healthy: false, crashed: false, pid: null, exitCode: null, terminatingSignal: null };
6394
6367
  }
6395
- function formatProxySummary(info) {
6396
- const parts = [];
6397
- if (info.proxyGroups && info.proxyGroups > 0) parts.push(`${info.proxyGroups} \u7EC4`);
6398
- parts.push(`${info.proxies || 0} \u8282\u70B9`);
6399
- return parts.join(", ");
6368
+ function describeExitCause(exitCode, terminatingSignal) {
6369
+ if (terminatingSignal !== null) return `\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF08${terminatingSignal}\uFF09`;
6370
+ if (exitCode !== null && exitCode !== 0) return `\u9000\u51FA\u7801 ${exitCode}`;
6371
+ return null;
6400
6372
  }
6401
- function getActiveSubscription() {
6402
- const settings = readSettings();
6403
- const subs = getSubscriptions(settings);
6404
- if (subs.length === 0) return null;
6405
- const activeName = settings.active_subscription;
6406
- if (activeName) {
6407
- const found = subs.find((s) => s.name === activeName);
6408
- if (found) return found;
6409
- }
6410
- return subs[0];
6373
+ function isCrashed(status) {
6374
+ if (status.running) return false;
6375
+ return describeExitCause(status.lastExitCode, status.lastTerminatingSignal) !== null;
6411
6376
  }
6412
- function requireActiveSubscription() {
6413
- const sub = getActiveSubscription();
6414
- if (!sub) {
6415
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
6416
- }
6417
- return sub;
6377
+ function describeAbnormalExit(status) {
6378
+ return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
6418
6379
  }
6419
- function findSubscriptionFuzzy(subs, pattern) {
6420
- const lowerPattern = pattern.toLowerCase();
6421
- const exact = [];
6422
- const prefix = [];
6423
- const includes = [];
6424
- for (const s of subs) {
6425
- const name = s.name.toLowerCase();
6426
- if (name === lowerPattern) {
6427
- exact.push(s);
6428
- } else if (name.startsWith(lowerPattern)) {
6429
- prefix.push(s);
6430
- } else if (name.includes(lowerPattern)) {
6431
- includes.push(s);
6432
- }
6433
- }
6434
- if (exact.length > 0) return exact;
6435
- if (prefix.length > 0) return prefix;
6436
- return includes;
6380
+ function tunBlockedHint(lastLine) {
6381
+ return ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", lastLine];
6437
6382
  }
6438
- function pickSingleSubscription(subs, pattern) {
6439
- if (subs.length === 0) {
6440
- throw new CliError(`\u672A\u627E\u5230\u5339\u914D "${pattern}" \u7684\u8BA2\u9605`);
6441
- }
6442
- if (subs.length === 1) return subs[0];
6443
- throw new CliError("\u5339\u914D\u5230\u591A\u4E2A\u8BA2\u9605\uFF0C\u8BF7\u66F4\u7CBE\u786E\u6307\u5B9A", {
6444
- hint: ["", "\u5339\u914D\u7684\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
6383
+ function tunBlockedByRunningService() {
6384
+ return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
6385
+ hint: tunBlockedHint("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1")
6445
6386
  });
6446
6387
  }
6447
- function resolveSubscription(subs, pattern) {
6448
- return pickSingleSubscription(findSubscriptionFuzzy(subs, pattern), pattern);
6449
- }
6450
- function assertLooksLikeSubscription(parsed, maskedUrl) {
6451
- const hasProxies = Array.isArray(parsed.proxies) && parsed.proxies.length > 0;
6452
- const hasGroups = Array.isArray(parsed["proxy-groups"]) && parsed["proxy-groups"].length > 0;
6453
- const providers = parsed["proxy-providers"];
6454
- const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
6455
- if (hasProxies || hasGroups || hasProviders) return;
6456
- const serverMsg = sanitizeTerminal(
6457
- ["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
6458
- );
6459
- throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
6460
- label: "\u8BA2\u9605\u65E0\u6548",
6461
- hint: [
6462
- ...serverMsg ? [`\u670D\u52A1\u7AEF\u8FD4\u56DE: ${serverMsg}`] : [],
6463
- `URL: ${maskedUrl}`,
6464
- "\u5E38\u89C1\u539F\u56E0\uFF1A\u8BA2\u9605\u94FE\u63A5\u8FC7\u671F\u3001\u6D41\u91CF\u8017\u5C3D\u3001\u9700\u8981\u91CD\u65B0\u83B7\u53D6\u8BA2\u9605\u5730\u5740\u3002",
6465
- "\u78C1\u76D8\u4E0A\u539F\u6709\u7684\u8BA2\u9605\u914D\u7F6E\u672A\u88AB\u8986\u76D6\u3002"
6466
- ]
6388
+ function tunBlockedByConcurrentStart() {
6389
+ return new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
6390
+ hint: tunBlockedHint("\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun")
6467
6391
  });
6468
6392
  }
6469
- async function downloadSubscription(url, subName = "default", signal) {
6470
- let response;
6393
+ function ensureServiceSymlink() {
6394
+ assertKernelInstalled();
6471
6395
  try {
6472
- response = await HTTP_CLIENT.get(url, { responseType: "text", signal });
6396
+ const current = fs12.readlinkSync(PATHS.serviceBinary);
6397
+ if (current === "mihomo") return;
6398
+ fs12.unlinkSync(PATHS.serviceBinary);
6473
6399
  } catch (e) {
6474
- const maskedUrl = maskUrl(url);
6475
- let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
6476
- const err = e;
6477
- if (err.response) {
6478
- errorMsg += ` (HTTP ${err.response.status})`;
6400
+ const code = e.code;
6401
+ if (code === "EINVAL") {
6402
+ try {
6403
+ fs12.unlinkSync(PATHS.serviceBinary);
6404
+ } catch {
6405
+ }
6406
+ } else if (code !== "ENOENT") {
6407
+ throw e;
6479
6408
  }
6480
- errorMsg += `
6481
- URL: ${maskedUrl}`;
6482
- throw new Error(errorMsg);
6483
6409
  }
6484
- const content = response.data;
6485
- if (!content?.trim()) {
6486
- throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
6487
- }
6488
- const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
6489
- assertLooksLikeSubscription(parsed, maskUrl(url));
6490
- saveSubscriptionRawConfig(subName, content);
6491
- const meta = extractSubscriptionMeta(response.headers);
6492
6410
  try {
6493
- saveSubscriptionMeta(subName, meta);
6411
+ fs12.symlinkSync("mihomo", PATHS.serviceBinary);
6494
6412
  } catch (e) {
6413
+ if (e.code !== "EEXIST") throw e;
6414
+ let existing;
6495
6415
  try {
6496
- removeSubscriptionRawConfig(subName);
6416
+ existing = fs12.readlinkSync(PATHS.serviceBinary);
6497
6417
  } catch {
6418
+ throw e;
6498
6419
  }
6499
- throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
6500
- label: "\u66F4\u65B0\u5931\u8D25",
6501
- // 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
6502
- // 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
6503
- hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
6504
- });
6420
+ if (existing !== "mihomo") throw e;
6505
6421
  }
6506
- const { proxies, proxyGroups } = countConfigNodes(parsed);
6507
- return { proxies, proxyGroups };
6508
6422
  }
6509
- async function prepareConfigForStart(mode, subName = "default") {
6510
- let rawContent;
6423
+ function bootstrapServiceIdempotentOrThrow(what) {
6424
+ const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6425
+ if (result.status === 0) return;
6426
+ if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
6427
+ const detail = result.stderr.trim();
6428
+ throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
6429
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
6430
+ });
6431
+ }
6432
+ function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
6433
+ const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
6434
+ if (result.status === 0 || isBootoutNotLoaded(result.status)) return;
6435
+ const detail = result.stderr.trim();
6436
+ throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
6437
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
6438
+ });
6439
+ }
6440
+ async function installService(wasRunning) {
6441
+ assertServiceLabelSafe();
6442
+ ensureDirs();
6443
+ ensureServiceSymlink();
6444
+ let restoreSkipped = false;
6445
+ const stagePath = PATHS.servicePlistStage;
6446
+ atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
6511
6447
  try {
6512
- rawContent = requireSubscriptionRawConfig(subName);
6513
- } catch (e) {
6514
- if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
6515
- throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
6516
- hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
6448
+ const lint = spawnSync7("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
6449
+ if (lint.status !== 0) {
6450
+ throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
6451
+ hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
6452
+ });
6453
+ }
6454
+ bootoutService();
6455
+ await waitUntilUnloaded();
6456
+ fs12.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
6457
+ atomicWriteFileSync(PATHS.userAgentPlist, fs12.readFileSync(stagePath, "utf8"), { mode: 420 });
6458
+ if (wasRunning) {
6459
+ withFileLock(PATHS.serviceLock, () => {
6460
+ if (startAbortedByConcurrentStop()) {
6461
+ restoreSkipped = true;
6462
+ return;
6463
+ }
6464
+ runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6465
+ bootstrapServiceIdempotentOrThrow("\u88C5\u8F7D\u670D\u52A1");
6517
6466
  });
6518
6467
  }
6519
- throw e;
6520
- }
6521
- const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
6522
- const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
6523
- await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
6524
- return {
6525
- buildResult,
6526
- info: countConfigNodes(buildResult.config)
6527
- };
6528
- }
6529
- function commitPreparedConfig(prepared) {
6530
- const { buildResult } = prepared;
6531
- if (buildResult.warnings.length > 0) {
6532
- for (const warning of buildResult.warnings) {
6533
- console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
6468
+ } finally {
6469
+ try {
6470
+ fs12.unlinkSync(stagePath);
6471
+ } catch {
6534
6472
  }
6535
- console.log("");
6536
- }
6537
- writeMihomoConfig(buildResult.config);
6538
- return prepared.info;
6539
- }
6540
- function needsAutoUpdate(sub) {
6541
- if (!sub.updated_at) return true;
6542
- const lastUpdate = new Date(sub.updated_at).getTime();
6543
- if (Number.isNaN(lastUpdate)) return true;
6544
- if (lastUpdate > Date.now()) return true;
6545
- const intervalHours = resolveUpdateInterval(sub.update_interval);
6546
- const intervalMs = intervalHours * 60 * 60 * 1e3;
6547
- return Date.now() - lastUpdate > intervalMs;
6548
- }
6549
- async function tryUpdateOne(sub, signal) {
6550
- try {
6551
- const info = await downloadSubscription(sub.url, sub.name, signal);
6552
- return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
6553
- } catch (e) {
6554
- return { name: sub.name, success: false, aborted: signal?.aborted === true, error: e.message };
6555
6473
  }
6556
- }
6557
- function printUpdateResult(r) {
6558
- if (r.success) {
6559
- console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
6560
- } else if (r.aborted) {
6561
- console.log(`${colors.gray("\xB7")} ${r.name}: ${colors.gray("\u8DF3\u8FC7\uFF08\u66F4\u65B0\u8D85\u65F6\uFF0C\u4F7F\u7528\u672C\u5730\u7F13\u5B58\uFF09")}`);
6562
- } else {
6563
- console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${firstLine(r.error || "")})`);
6474
+ if (!wasRunning) {
6475
+ disableServiceAutoStart();
6564
6476
  }
6477
+ return { restoreSkipped };
6565
6478
  }
6566
- async function autoUpdateStaleSubscription(options = {}) {
6567
- const allSubs = getSubscriptionsWithCache();
6568
- const staleSubs = allSubs.filter(needsAutoUpdate);
6569
- if (staleSubs.length === 0) {
6570
- return;
6571
- }
6572
- if (staleSubs.length === 1) {
6573
- const sub = staleSubs[0];
6574
- const interval = resolveUpdateInterval(sub.update_interval);
6575
- console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
6576
- } else {
6577
- console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
6479
+ async function startService() {
6480
+ assertServiceLabelSafe();
6481
+ ensureServiceSymlink();
6482
+ if (!isServiceInstalled()) {
6483
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
6578
6484
  }
6579
- const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
6580
- const controller = new AbortController();
6581
- const results = [];
6582
- const updatePromise = Promise.all(
6583
- staleSubs.map(
6584
- (sub) => tryUpdateOne(sub, controller.signal).then((r) => {
6585
- results.push(r);
6586
- return r;
6587
- })
6588
- )
6589
- );
6590
- try {
6591
- await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
6592
- } catch (e) {
6593
- if (!(e instanceof TimeoutError)) throw e;
6594
- controller.abort();
6595
- await updatePromise.catch(() => {
6485
+ assertRuntimeConfigPresent();
6486
+ if (getConfigInfo()?.tun) {
6487
+ throw new CliError("\u8FD0\u884C\u65F6\u914D\u7F6E\u4E3A TUN \u6A21\u5F0F\uFF0C\u670D\u52A1\u65E0\u6CD5\u4F7F\u7528", {
6488
+ hint: [
6489
+ "\u670D\u52A1\u4EE5\u666E\u901A\u7528\u6237\u8EAB\u4EFD\u8FD0\u884C\uFF08\u7528\u6237\u7EA7 LaunchAgent\uFF09\uFF0C\u65E0\u6743\u521B\u5EFA TUN \u8BBE\u5907\uFF0C",
6490
+ "\u5F3A\u884C\u542F\u52A8\u53EA\u4F1A\u8BA9\u5185\u6838\u53CD\u590D\u5D29\u6E83\u91CD\u542F\u3002",
6491
+ "",
6492
+ "\u6309 Mixed \u91CD\u5EFA\u914D\u7F6E\u5E76\u542F\u52A8: mihomo-cli start mixed",
6493
+ "\u786E\u5B9E\u8981\u7528 TUN: mihomo-cli tun"
6494
+ ]
6596
6495
  });
6597
- console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
6598
- }
6599
- for (const r of results) {
6600
- printUpdateResult(r);
6601
6496
  }
6497
+ await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
6498
+ bootoutService();
6499
+ await waitUntilUnloaded();
6500
+ rotateAndCleanupLogs();
6501
+ let started = true;
6502
+ withFileLock(PATHS.serviceLock, () => {
6503
+ if (startAbortedByConcurrentStop()) {
6504
+ started = false;
6505
+ return;
6506
+ }
6507
+ runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6508
+ bootstrapServiceIdempotentOrThrow("\u542F\u52A8\u670D\u52A1");
6509
+ });
6510
+ return { started };
6602
6511
  }
6603
-
6604
- // src/commands/config.ts
6605
- function cmdConfig(args = []) {
6606
- assertKnownFlags(args.slice(1), ["-j", "--json", "--reveal"], "config [--json] [--reveal]");
6607
- assertPositionalCount(args, 0, 1, "mihomo-cli config [--json] [--reveal]");
6608
- const asJson = hasFlag(args, "-j", "--json");
6609
- const reveal = hasFlag(args, "--reveal");
6610
- const active = getActiveSubscription();
6611
- if (!active) {
6612
- throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
6613
- }
6614
- const rawContent = requireSubscriptionRawConfig(active.name);
6615
- const mode = deriveRuntimeMode(getConfigInfo());
6616
- const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
6617
- const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
6618
- const shown = redacted.config;
6619
- if (asJson) {
6620
- console.log(JSON.stringify({ config: shown, warnings, redacted: !reveal && redacted.changed }, null, 2));
6621
- return;
6622
- }
6623
- console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
6624
- console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
6625
- if (!reveal && redacted.changed) {
6626
- console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
6627
- }
6628
- console.log("");
6629
- console.log(dumpYaml(shown).trimEnd());
6630
- if (warnings.length > 0) {
6631
- console.log("");
6632
- for (const w of warnings) console.log(colors.yellow(`# ${w}`));
6512
+ function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
6513
+ assertServiceLabelSafe();
6514
+ runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F", timeoutMs);
6515
+ if (!isServiceDisabledInLaunchd(timeoutMs)) {
6516
+ throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
6517
+ hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
6518
+ });
6633
6519
  }
6520
+ bumpStopEpoch();
6634
6521
  }
6635
-
6636
- // src/open.ts
6637
- import { spawn } from "child_process";
6638
-
6639
- // src/lifecycle.ts
6640
- var silentSigint = false;
6641
- function setSilentSigint(value) {
6642
- silentSigint = value;
6522
+ async function bootoutAndDisableInLock() {
6523
+ withFileLock(PATHS.serviceLock, () => {
6524
+ bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6525
+ disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6526
+ });
6527
+ await waitUntilUnloaded();
6643
6528
  }
6644
- function isSilentSigint() {
6645
- return silentSigint;
6529
+ async function stopService() {
6530
+ assertServiceLabelSafe();
6531
+ await bootoutAndDisableInLock();
6532
+ return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
6646
6533
  }
6647
-
6648
- // src/open.ts
6649
- function openUrl(url) {
6534
+ async function uninstallService() {
6535
+ assertServiceLabelSafe();
6536
+ await bootoutAndDisableInLock();
6650
6537
  try {
6651
- const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
6652
- child.unref();
6653
- child.on("error", () => {
6654
- });
6538
+ fs12.rmSync(PATHS.userAgentPlist, { force: true });
6539
+ } catch (e) {
6540
+ throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
6541
+ }
6542
+ const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
6543
+ try {
6544
+ fs12.rmSync(PATHS.serviceBinary, { force: true });
6655
6545
  } catch {
6656
6546
  }
6547
+ return cleanup;
6657
6548
  }
6658
- function openLogFile(logPath) {
6659
- console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${logPath}`);
6660
- openUrl(logPath);
6661
- }
6662
- function viewLogWithTail(logPath, options) {
6663
- const follow = options?.follow;
6664
- const lines = options?.lines || 100;
6665
- console.log(`\u65E5\u5FD7: ${logPath}`);
6666
- if (follow) {
6667
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
6668
- } else {
6669
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
6670
- `);
6549
+ async function restartService(prefetched) {
6550
+ assertServiceLabelSafe();
6551
+ if (!isServiceInstalled()) {
6552
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
6671
6553
  }
6672
- const tailArgs = [];
6673
- if (follow) tailArgs.push("-f");
6674
- tailArgs.push("-n", lines.toString());
6675
- tailArgs.push(logPath);
6676
- const tail = spawn("tail", tailArgs, { stdio: "inherit" });
6677
- if (follow) setSilentSigint(true);
6678
- tail.on("close", (code) => process.exit(code ?? 0));
6679
- tail.on("error", (e) => {
6680
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
6681
- process.exit(1);
6682
- });
6554
+ const oversized = logOversized();
6555
+ if (!oversized && await tryHotReload(prefetched)) {
6556
+ return concludeHotReload(stopEpochBaseline(), readStopEpoch());
6557
+ }
6558
+ if (oversized) {
6559
+ const archiveFile = allocateArchivePath();
6560
+ try {
6561
+ fs12.copyFileSync(PATHS.logFile, archiveFile);
6562
+ fs12.writeFileSync(PATHS.logFile, "");
6563
+ } catch {
6564
+ }
6565
+ }
6566
+ const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
6567
+ let started = true;
6568
+ if (kick.status !== 0) {
6569
+ withFileLock(PATHS.serviceLock, () => {
6570
+ if (startAbortedByConcurrentStop()) {
6571
+ started = false;
6572
+ return;
6573
+ }
6574
+ runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6575
+ bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
6576
+ });
6577
+ if (!started) return { hotReloaded: false, started: false };
6578
+ }
6579
+ cleanupOldLogs();
6580
+ return { hotReloaded: false, started: true };
6683
6581
  }
6684
6582
 
6685
- // src/commands/shared.ts
6686
- import readline from "readline";
6687
-
6688
6583
  // src/process-start.ts
6689
- import fs13 from "fs";
6690
6584
  var TUN_MODE_POST_WAIT_MS = 500;
6691
6585
  function buildTunLaunchScript() {
6692
6586
  const binary = shellQuote(PATHS.mihomoBinary);
@@ -6771,13 +6665,11 @@ async function startTun(prefetched) {
6771
6665
  }
6772
6666
  }
6773
6667
  }
6774
- const staleState = checkStaleState();
6775
- if (staleState.needsCleanup) {
6776
- if (staleState.allPids.length > 0) {
6777
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
6778
- } else {
6779
- console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
6780
- }
6668
+ const stalePids = getMihomoPids();
6669
+ if (stalePids.length > 0) {
6670
+ console.log(`\u6E05\u7406 ${stalePids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
6671
+ } else if (isPidFileOwnedByRoot()) {
6672
+ console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
6781
6673
  }
6782
6674
  console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
6783
6675
  runSudoScript(buildTunLaunchScript(), {
@@ -6804,13 +6696,13 @@ function getRuntimeMode() {
6804
6696
  function getRunningState(serviceStatus) {
6805
6697
  const service = serviceStatus ?? getServiceStatus({ withDisabled: false });
6806
6698
  if (service.running) {
6807
- return { running: true, pid: service.pid, kind: "service", processInfo: null };
6699
+ return { running: true, pid: service.pid, kind: "service", memory: null };
6808
6700
  }
6809
6701
  const status = getStatus();
6810
6702
  if (status.running) {
6811
- return { running: true, pid: status.pid, kind: "tun", processInfo: status.processInfo };
6703
+ return { running: true, pid: status.pid, kind: "tun", memory: status.memory };
6812
6704
  }
6813
- return { running: false, pid: null, kind: null, processInfo: null };
6705
+ return { running: false, pid: null, kind: null, memory: null };
6814
6706
  }
6815
6707
  function restartModeFor(state, fallbackMode) {
6816
6708
  return state.kind === "tun" ? "tun" : fallbackMode;
@@ -7151,8 +7043,8 @@ async function printStatus(args = []) {
7151
7043
  );
7152
7044
  if (pid) {
7153
7045
  console.log(`${colors.gray("PID: ")}${pid}`);
7154
- if (kind === "tun" && state.processInfo) {
7155
- console.log(`${colors.gray("\u5185\u5B58: ")}${state.processInfo.memory}`);
7046
+ if (kind === "tun" && state.memory) {
7047
+ console.log(`${colors.gray("\u5185\u5B58: ")}${state.memory}`);
7156
7048
  }
7157
7049
  }
7158
7050
  if (info) {
@@ -7646,7 +7538,6 @@ async function checkUpdate(opts) {
7646
7538
  current: currentDisplay,
7647
7539
  latest: latestVersion,
7648
7540
  needsUpdate,
7649
- assets: latest.assets,
7650
7541
  release: latest,
7651
7542
  ghFallbackToDirect
7652
7543
  };
@@ -7705,18 +7596,9 @@ function buildGhDownloadEnv(proxy) {
7705
7596
  }
7706
7597
  return env;
7707
7598
  }
7708
- function resolveFallbackQueryOptions(channel) {
7709
- if (channel.kind === "gh") {
7710
- return channel.proxy ? { proxy: channel.proxy, useGh: false } : { proxy: null, useGh: true };
7711
- }
7712
- if (channel.kind === "proxy") return { proxy: channel.proxy, useGh: false };
7713
- if (channel.kind === "mirror") return { proxy: channel.proxy ?? null, useGh: false };
7714
- return { proxy: null, useGh: false };
7715
- }
7716
- async function downloadKernel(progressCallback, channel, releaseInfo) {
7599
+ async function downloadKernel(progressCallback, channel, latest) {
7717
7600
  ensureDirs();
7718
- const apiProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
7719
- const latest = releaseInfo || await getLatestRelease(GITHUB_REPO, resolveFallbackQueryOptions(channel));
7601
+ const downloadProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
7720
7602
  const arch = getArch();
7721
7603
  const platform = process.platform;
7722
7604
  const asset = findMatchingAsset(latest.assets, platform, arch);
@@ -7772,7 +7654,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7772
7654
  "curl",
7773
7655
  buildKernelCurlArgs({
7774
7656
  url: downloadUrl,
7775
- proxy: apiProxy,
7657
+ proxy: downloadProxy,
7776
7658
  maxBytes,
7777
7659
  outputPath: tempPath
7778
7660
  }),
@@ -8511,7 +8393,8 @@ function cmdLogs(args) {
8511
8393
  hint: "\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo-cli logs 0 -f"
8512
8394
  });
8513
8395
  }
8514
- openLogFile(logPath);
8396
+ console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${logPath}`);
8397
+ openUrl(logPath);
8515
8398
  return;
8516
8399
  }
8517
8400
  viewLogWithTail(logPath, { follow, lines });
@@ -9002,7 +8885,7 @@ async function subUpdate(args) {
9002
8885
  const nameArg = getNonFlagArg(args, 2);
9003
8886
  const subs = getSubscriptions();
9004
8887
  if (subs.length === 0) {
9005
- throw new CliError("\u6CA1\u6709\u8BA2\u9605");
8888
+ throw noSubscriptionsError();
9006
8889
  }
9007
8890
  if (nameArg === "") {
9008
8891
  throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", { hint: ["\u66F4\u65B0\u6240\u6709\u8BA2\u9605\u76F4\u63A5\u6267\u884C: mihomo-cli sub update", `\u66F4\u65B0\u6307\u5B9A\u8BA2\u9605: mihomo-cli sub update <\u540D\u79F0>`] });
@@ -9047,7 +8930,7 @@ async function subUse(args) {
9047
8930
  const name = getNonFlagArg(args, 2);
9048
8931
  const subs = getSubscriptions();
9049
8932
  if (subs.length === 0) {
9050
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo-cli sub add <url> [name]" });
8933
+ throw noSubscriptionsError();
9051
8934
  }
9052
8935
  if (!name) {
9053
8936
  throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
@@ -9077,7 +8960,7 @@ async function subRemove(args) {
9077
8960
  const name = getNonFlagArg(args, 2);
9078
8961
  const subs = getSubscriptions();
9079
8962
  if (subs.length === 0) {
9080
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo-cli sub add <url> [name]" });
8963
+ throw noSubscriptionsError();
9081
8964
  }
9082
8965
  if (!name) {
9083
8966
  throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
@@ -9495,5 +9378,5 @@ main().catch((e) => {
9495
9378
  /*! Bundled license information:
9496
9379
 
9497
9380
  js-yaml/dist/js-yaml.mjs:
9498
- (*! js-yaml 5.4.3 https://github.com/nodeca/js-yaml @license MIT *)
9381
+ (*! js-yaml 5.3.0 https://github.com/nodeca/js-yaml @license MIT *)
9499
9382
  */