mihomo-cli 26.10.112 → 26.10.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -58,6 +58,66 @@ var compareVersions = (v1, v2) => {
58
58
  return 0;
59
59
  };
60
60
 
61
+ // node_modules/compare-versions/lib/esm/compare.js
62
+ var compare = (v1, v2, operator) => {
63
+ assertValidOperator(operator);
64
+ const res = compareVersions(v1, v2);
65
+ return operatorResMap[operator].includes(res);
66
+ };
67
+ var operatorResMap = {
68
+ ">": [1],
69
+ ">=": [0, 1],
70
+ "=": [0],
71
+ "<=": [-1, 0],
72
+ "<": [-1],
73
+ "!=": [-1, 1]
74
+ };
75
+ var allowedOperators = Object.keys(operatorResMap);
76
+ var assertValidOperator = (op) => {
77
+ if (typeof op !== "string") {
78
+ throw new TypeError(`Invalid operator type, expected string but got ${typeof op}`);
79
+ }
80
+ if (allowedOperators.indexOf(op) === -1) {
81
+ throw new Error(`Invalid operator, expected one of ${allowedOperators.join("|")}`);
82
+ }
83
+ };
84
+
85
+ // node_modules/compare-versions/lib/esm/satisfies.js
86
+ var satisfies = (version, range) => {
87
+ range = range.replace(/([><=]+)\s+/g, "$1");
88
+ if (range.includes("||")) {
89
+ return range.split("||").some((r4) => satisfies(version, r4));
90
+ } else if (range.includes(" - ")) {
91
+ const [a, b] = range.split(" - ", 2);
92
+ return satisfies(version, `>=${a} <=${b}`);
93
+ } else if (range.includes(" ")) {
94
+ return range.trim().replace(/\s{2,}/g, " ").split(" ").every((r4) => satisfies(version, r4));
95
+ }
96
+ const m = range.match(/^([<>=~^]+)/);
97
+ const op = m ? m[1] : "=";
98
+ if (op !== "^" && op !== "~")
99
+ return compare(version, range, op);
100
+ const [v1, v2, v3, , vp] = validateAndParse(version);
101
+ const [r1, r2, r3, , rp] = validateAndParse(range);
102
+ const v = [v1, v2, v3];
103
+ const r = [r1, r2 !== null && r2 !== void 0 ? r2 : "x", r3 !== null && r3 !== void 0 ? r3 : "x"];
104
+ if (rp) {
105
+ if (!vp)
106
+ return false;
107
+ if (compareSegments(v, r) !== 0)
108
+ return false;
109
+ if (compareSegments(vp.split("."), rp.split(".")) === -1)
110
+ return false;
111
+ }
112
+ const nonZero = r.findIndex((v4) => v4 !== "0") + 1;
113
+ const i = op === "~" ? 2 : nonZero > 1 ? nonZero : 1;
114
+ if (compareSegments(v.slice(0, i), r.slice(0, i)) !== 0)
115
+ return false;
116
+ if (compareSegments(v.slice(i), r.slice(i)) === -1)
117
+ return false;
118
+ return true;
119
+ };
120
+
61
121
  // src/constants.ts
62
122
  import { createRequire } from "module";
63
123
 
@@ -108,12 +168,7 @@ var pkg = require2("../package.json");
108
168
  var YAML_MAX_ALIASES = 200;
109
169
  var VERSION = pkg.version;
110
170
  var PKG_NAME = pkg.name;
111
- var MIN_NODE_VERSION = (() => {
112
- const raw = pkg.engines?.node;
113
- if (typeof raw !== "string") return null;
114
- const m = raw.trim().match(/^>=\s*(\d+\.\d+\.\d+)$/);
115
- return m ? m[1] : null;
116
- })();
171
+ var NODE_ENGINES = typeof pkg.engines?.node === "string" ? pkg.engines.node : null;
117
172
  var MIRROR_HOST = "gh-proxy.org";
118
173
  var MIRROR_ALIASES = {
119
174
  v4: `https://v4.${MIRROR_HOST}/`,
@@ -134,7 +189,6 @@ function isValidServiceLabel(label) {
134
189
  return SERVICE_LABEL_RE.test(label) && !label.includes("..");
135
190
  }
136
191
  var RAW_SERVICE_LABEL = process.env.MIHOMO_CLI_DAEMON_LABEL;
137
- var RAW_SERVICE_LABEL_INPUT = RAW_SERVICE_LABEL;
138
192
  var SERVICE_LABEL = RAW_SERVICE_LABEL && isValidServiceLabel(RAW_SERVICE_LABEL) ? RAW_SERVICE_LABEL : DEFAULT_SERVICE_LABEL;
139
193
  var SERVICE_BINARY_NAME = "mihomo-cli-service";
140
194
  var DEFAULT_MIXED_PORT = 7890;
@@ -235,8 +289,8 @@ var BASE_CONFIG = {
235
289
  var DEFAULT_UPDATE_INTERVAL_HOURS = 12;
236
290
  var DEFAULT_AUTO_UPDATE_TIMEOUT = 1e4;
237
291
  function assertServiceLabelSafe() {
238
- if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
239
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
292
+ if (RAW_SERVICE_LABEL !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL)) {
293
+ throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL}"`, {
240
294
  label: "\u914D\u7F6E\u9519\u8BEF",
241
295
  hint: ['\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002', "\u8BE5\u503C\u4F1A\u6210\u4E3A launchd plist \u7684\u6587\u4EF6\u540D\uFF0C\u53C2\u4E0E plist \u5199\u5165\u4E0E\u5220\u9664\u8DEF\u5F84\u3002"]
242
296
  });
@@ -1723,24 +1777,32 @@ function collectionTagName(state, event, defaultTagName) {
1723
1777
  function isMappingTag(tag) {
1724
1778
  return tag.nodeKind === "mapping";
1725
1779
  }
1780
+ function chargeMergeWork(state) {
1781
+ state.totalMergeKeys++;
1782
+ if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1783
+ }
1726
1784
  function mergeKeys(state, frame, source, sourceTag) {
1785
+ chargeMergeWork(state);
1727
1786
  for (const sourceKey of sourceTag.keys(source)) {
1728
- if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1787
+ chargeMergeWork(state);
1729
1788
  if (frame.tag.has(frame.value, sourceKey)) continue;
1730
1789
  const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
1731
1790
  if (err) throwError$1(state, err);
1732
- (frame.overridable ??= /* @__PURE__ */ new Set()).add(sourceKey);
1791
+ frame.overridable ??= /* @__PURE__ */ new Set();
1792
+ frame.overridable.add(sourceKey);
1733
1793
  }
1734
1794
  }
1735
1795
  function mergeSource(state, frame, source, sourceTag) {
1736
1796
  state.position = frame.keyPosition;
1737
1797
  if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag);
1738
- else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) for (const element of source) {
1739
- const elementTag = state.nodeTags.get(element);
1740
- if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1741
- mergeKeys(state, frame, element, elementTag);
1742
- }
1743
- else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1798
+ else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
1799
+ if (source.length > 100) throwError$1(state, "abnormal merge sequence size");
1800
+ for (const element of source) {
1801
+ const elementTag = state.nodeTags.get(element);
1802
+ if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1803
+ mergeKeys(state, frame, element, elementTag);
1804
+ }
1805
+ } else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1744
1806
  }
1745
1807
  function addMappingValue(state, frame, key, value, tag) {
1746
1808
  state.position = frame.keyPosition;
@@ -2083,6 +2145,24 @@ function testDocumentSeparator(state, position = state.position) {
2083
2145
  }
2084
2146
  return false;
2085
2147
  }
2148
+ function skipByteOrderMark(state) {
2149
+ if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
2150
+ state.position++;
2151
+ state.lineStart = state.position;
2152
+ }
2153
+ }
2154
+ function testDocumentBoundary(state) {
2155
+ if (state.position !== state.lineStart) return false;
2156
+ if (testDocumentSeparator(state)) return true;
2157
+ if (state.input.charCodeAt(state.position) !== 65279) return false;
2158
+ const snapshot = snapshotState(state);
2159
+ skipByteOrderMark(state);
2160
+ skipSeparationSpace(state, true);
2161
+ const ch = state.input.charCodeAt(state.position);
2162
+ const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
2163
+ restoreState(state, snapshot);
2164
+ return result;
2165
+ }
2086
2166
  function skipUntilLineEnd(state) {
2087
2167
  let ch = state.input.charCodeAt(state.position);
2088
2168
  while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
@@ -2266,14 +2346,14 @@ function readBlockScalar(state, parentIndent, props) {
2266
2346
  } else if (column > 0) valueEnd = linePosition + column;
2267
2347
  break;
2268
2348
  }
2269
- if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break;
2349
+ if (testDocumentBoundary(state)) break;
2270
2350
  if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column);
2271
2351
  if (!detectedIndent && contentIndent === -1 && !isEol(first)) {
2272
2352
  if (first === 9 && column < parentIndent) {
2273
2353
  state.position = linePosition + column;
2274
2354
  throwError(state, "tab characters must not be used in indentation");
2275
2355
  }
2276
- if (column < maxLeadingIndent) {
2356
+ if (column >= parentIndent && column < maxLeadingIndent) {
2277
2357
  state.position = linePosition + column;
2278
2358
  throwError(state, "bad indentation of a mapping entry");
2279
2359
  }
@@ -2319,7 +2399,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
2319
2399
  const inFlow = nodeContext === CONTEXT_FLOW_IN;
2320
2400
  let multiline = false;
2321
2401
  while (ch !== 0) {
2322
- if (state.position === state.lineStart && testDocumentSeparator(state)) break;
2402
+ if (testDocumentBoundary(state)) break;
2323
2403
  if (ch === 58) {
2324
2404
  const following = state.input.charCodeAt(state.position + 1);
2325
2405
  if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break;
@@ -2483,13 +2563,16 @@ function readBlockMapping(state, nodeIndent, flowIndent, props) {
2483
2563
  ch = state.input.charCodeAt(++state.position);
2484
2564
  if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2485
2565
  if (!mappingOpened) {
2486
- restoreState(state, beforeKey);
2487
- addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2566
+ state.events.splice(beforeKey.eventsLength, 0, {
2567
+ type: EVENT_ID.MAPPING,
2568
+ start: beforeKey.position,
2569
+ anchorStart: props.anchorStart,
2570
+ anchorEnd: props.anchorEnd,
2571
+ tagStart: props.tagStart,
2572
+ tagEnd: props.tagEnd,
2573
+ style: COLLECTION_STYLE.BLOCK
2574
+ });
2488
2575
  mappingOpened = true;
2489
- parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true);
2490
- ch = state.input.charCodeAt(state.position);
2491
- while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
2492
- state.position++;
2493
2576
  }
2494
2577
  detected = true;
2495
2578
  atExplicitKey = false;
@@ -2676,7 +2759,7 @@ function readDocument(state) {
2676
2759
  const documentEvent = state.events[documentEventIndex];
2677
2760
  if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd;
2678
2761
  addPopEvent(state);
2679
- if (!explicitEnd && state.position < state.length && !(state.position === state.lineStart && testDocumentSeparator(state))) throwError(state, "end of the stream or a document separator is expected");
2762
+ if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state)) throwError(state, "end of the stream or a document separator is expected");
2680
2763
  }
2681
2764
  function parseEvents(input, options) {
2682
2765
  const length = input.length;
@@ -2697,8 +2780,8 @@ function parseEvents(input, options) {
2697
2780
  };
2698
2781
  const nullpos = input.indexOf("\0");
2699
2782
  if (nullpos !== -1) YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename);
2700
- if (state.input.charCodeAt(state.position) === 65279) state.position++;
2701
2783
  while (state.position < state.length) {
2784
+ skipByteOrderMark(state);
2702
2785
  skipSeparationSpace(state, true);
2703
2786
  if (state.position >= state.length) break;
2704
2787
  const documentStart = state.position;
@@ -2731,15 +2814,6 @@ function load(input, options) {
2731
2814
  if (documents.length === 1) return documents[0];
2732
2815
  throw new YAMLException("expected a single document in the stream, but found more");
2733
2816
  }
2734
- var Style = class {
2735
- /** Whether to print the node's tag explicitly. */
2736
- tagged = false;
2737
- flow = false;
2738
- singleQuoted = false;
2739
- doubleQuoted = false;
2740
- literal = false;
2741
- folded = false;
2742
- };
2743
2817
  var INVALID = /* @__PURE__ */ Symbol("INVALID");
2744
2818
  function buildRepresentTypes(schema) {
2745
2819
  const defaultTags = new Set([
@@ -2788,8 +2862,6 @@ function build(state, object) {
2788
2862
  if (existing.anchor === void 0) existing.anchor = `ref_${state.refCounter++}`;
2789
2863
  return {
2790
2864
  kind: "alias",
2791
- tag: "",
2792
- style: new Style(),
2793
2865
  anchor: existing.anchor
2794
2866
  };
2795
2867
  }
@@ -2802,24 +2874,20 @@ function build(state, object) {
2802
2874
  }
2803
2875
  const { tag, tagName, implicitTag } = matched;
2804
2876
  const nodeTagName = implicitTag ? tagName : tagNameShort(tagName);
2805
- if (tag.nodeKind === "scalar") {
2806
- const style2 = new Style();
2807
- style2.tagged = !implicitTag;
2808
- return {
2809
- kind: "scalar",
2810
- tag: nodeTagName,
2811
- style: style2,
2812
- value: tag.represent(object)
2813
- };
2814
- }
2877
+ if (tag.nodeKind === "scalar") return {
2878
+ kind: "scalar",
2879
+ tag: nodeTagName,
2880
+ tagged: !implicitTag,
2881
+ style: SCALAR_STYLE.PLAIN,
2882
+ value: tag.represent(object)
2883
+ };
2815
2884
  if (tag.nodeKind === "sequence") {
2816
2885
  const container = tag.represent(object);
2817
- const style2 = new Style();
2818
- style2.tagged = !implicitTag;
2819
2886
  const node2 = {
2820
2887
  kind: "sequence",
2821
2888
  tag: nodeTagName,
2822
- style: style2,
2889
+ tagged: !implicitTag,
2890
+ style: COLLECTION_STYLE.BLOCK,
2823
2891
  items: []
2824
2892
  };
2825
2893
  if (!state.noRefs) state.refs.set(object, node2);
@@ -2832,12 +2900,11 @@ function build(state, object) {
2832
2900
  return node2;
2833
2901
  }
2834
2902
  const map = tag.represent(object);
2835
- const style = new Style();
2836
- style.tagged = !implicitTag;
2837
2903
  const node = {
2838
2904
  kind: "mapping",
2839
2905
  tag: nodeTagName,
2840
- style,
2906
+ tagged: !implicitTag,
2907
+ style: COLLECTION_STYLE.BLOCK,
2841
2908
  items: []
2842
2909
  };
2843
2910
  if (!state.noRefs) state.refs.set(object, node);
@@ -2905,82 +2972,204 @@ function visit(documents, visitor) {
2905
2972
  isKey: false
2906
2973
  })) return;
2907
2974
  }
2908
- var CHAR_BOM = 65279;
2909
- var CHAR_TAB = 9;
2910
- var CHAR_LINE_FEED = 10;
2911
- var CHAR_CARRIAGE_RETURN = 13;
2912
- var CHAR_SPACE = 32;
2913
- var CHAR_EXCLAMATION = 33;
2914
- var CHAR_DOUBLE_QUOTE = 34;
2915
- var CHAR_SHARP = 35;
2916
- var CHAR_PERCENT = 37;
2917
- var CHAR_AMPERSAND = 38;
2918
- var CHAR_SINGLE_QUOTE = 39;
2919
- var CHAR_ASTERISK = 42;
2920
- var CHAR_COMMA = 44;
2921
- var CHAR_MINUS = 45;
2922
- var CHAR_COLON = 58;
2923
- var CHAR_EQUALS = 61;
2924
- var CHAR_GREATER_THAN = 62;
2925
- var CHAR_QUESTION = 63;
2926
- var CHAR_COMMERCIAL_AT = 64;
2927
- var CHAR_LEFT_SQUARE_BRACKET = 91;
2928
- var CHAR_RIGHT_SQUARE_BRACKET = 93;
2929
- var CHAR_GRAVE_ACCENT = 96;
2930
- var CHAR_LEFT_CURLY_BRACKET = 123;
2931
- var CHAR_VERTICAL_LINE = 124;
2932
- var CHAR_RIGHT_CURLY_BRACKET = 125;
2933
- var ESCAPE_SEQUENCES = {};
2934
- ESCAPE_SEQUENCES[0] = "\\0";
2935
- ESCAPE_SEQUENCES[7] = "\\a";
2936
- ESCAPE_SEQUENCES[8] = "\\b";
2937
- ESCAPE_SEQUENCES[9] = "\\t";
2938
- ESCAPE_SEQUENCES[10] = "\\n";
2939
- ESCAPE_SEQUENCES[11] = "\\v";
2940
- ESCAPE_SEQUENCES[12] = "\\f";
2941
- ESCAPE_SEQUENCES[13] = "\\r";
2942
- ESCAPE_SEQUENCES[27] = "\\e";
2943
- ESCAPE_SEQUENCES[34] = '\\"';
2944
- ESCAPE_SEQUENCES[92] = "\\\\";
2945
- ESCAPE_SEQUENCES[133] = "\\N";
2946
- ESCAPE_SEQUENCES[160] = "\\_";
2947
- ESCAPE_SEQUENCES[8232] = "\\L";
2948
- ESCAPE_SEQUENCES[8233] = "\\P";
2949
- var DEFAULT_PRESENTER_OPTIONS = {
2950
- indent: 2,
2951
- seqNoIndent: false,
2952
- seqInlineFirst: true,
2953
- sortKeys: false,
2954
- lineWidth: 80,
2955
- flowBracketPadding: false,
2956
- flowSkipCommaSpace: false,
2957
- flowSkipColonSpace: false,
2958
- quoteFlowKeys: false,
2959
- quoteStyle: "single",
2960
- forceQuotes: false,
2961
- tagBeforeAnchor: false
2975
+ function hasBit(mask, bit) {
2976
+ return (mask & 1 << bit) !== 0;
2977
+ }
2978
+ var DEFAULT_SCALAR_STYLE_RULES = {
2979
+ applyQuoteFlowKeysOption,
2980
+ doubleQuoteForInvisibles,
2981
+ doubleQuoteWhitespaceOnly,
2982
+ applyForceQuotesOption,
2983
+ tryLongOrMultilineAsBlock,
2984
+ quoteInvalidPlain,
2985
+ fallbackToDoubleQuoted
2962
2986
  };
2963
- function nodeTagShort(node) {
2964
- return node.style.tagged ? node.tag : tagNameShort(node.tag);
2987
+ function _preferredQuotedStyle(layout) {
2988
+ if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED)) return SCALAR_STYLE.SINGLE_QUOTED;
2989
+ return SCALAR_STYLE.DOUBLE_QUOTED;
2990
+ }
2991
+ function applyQuoteFlowKeysOption(layout) {
2992
+ if (!layout.presenterOptions.quoteFlowKeys) return;
2993
+ if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN) return;
2994
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2995
+ }
2996
+ function doubleQuoteForInvisibles(layout) {
2997
+ if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2998
+ }
2999
+ function doubleQuoteWhitespaceOnly(layout) {
3000
+ if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
3001
+ }
3002
+ function applyForceQuotesOption(layout) {
3003
+ if (!layout.presenterOptions.forceQuotes) return;
3004
+ if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN) return;
3005
+ if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName) return;
3006
+ layout.style = layout.node.value.includes("\n") ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
3007
+ }
3008
+ function tryLongOrMultilineAsBlock(layout) {
3009
+ if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey) return;
3010
+ const value = layout.node.value;
3011
+ const multiline = value.indexOf("\n") !== -1;
3012
+ if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
3013
+ if (multiline) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
3014
+ return;
3015
+ }
3016
+ const w = layout.presenterOptions.lineWidth;
3017
+ if (w === -1) {
3018
+ if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
3019
+ return;
3020
+ }
3021
+ const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
3022
+ let position = 0;
3023
+ let shouldFold = false;
3024
+ while (position <= value.length) {
3025
+ let lineEnd = value.length;
3026
+ const nextLineBreak = value.indexOf("\n", position);
3027
+ if (nextLineBreak !== -1) lineEnd = nextLineBreak;
3028
+ const line = value.slice(position, lineEnd);
3029
+ if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line)) shouldFold = true;
3030
+ if (nextLineBreak === -1) break;
3031
+ position = nextLineBreak + 1;
3032
+ }
3033
+ if (shouldFold) layout.style = SCALAR_STYLE.FOLDED_BLOCK;
3034
+ else if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
3035
+ }
3036
+ function quoteInvalidPlain(layout) {
3037
+ if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN)) layout.style = _preferredQuotedStyle(layout);
3038
+ }
3039
+ function fallbackToDoubleQuoted(layout) {
3040
+ if (!hasBit(layout.allowedStylesMask, layout.style)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
3041
+ }
3042
+ function setBit(mask, bit) {
3043
+ return mask | 1 << bit;
3044
+ }
3045
+ var SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]";
3046
+ var SRC_B_CHAR = "[\\n\\r]";
3047
+ var SRC_C_BYTE_ORDER_MARK = "\\uFEFF";
3048
+ var SRC_S_WHITE = "[ \\t]";
3049
+ var SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
3050
+ var SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
3051
+ var SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]";
3052
+ var SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]";
3053
+ var SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]";
3054
+ var SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
3055
+ var SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
3056
+ var SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
3057
+ var SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
3058
+ var SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
3059
+ var SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
3060
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
3061
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
3062
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
3063
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
3064
+ var SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
3065
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
3066
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
3067
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
3068
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
3069
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
3070
+ var NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
3071
+ var NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
3072
+ var NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
3073
+ var NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
3074
+ var NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
3075
+ var NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
3076
+ var BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
3077
+ var C_FORBIDDEN_FIRST_LINE = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/;
3078
+ var C_FORBIDDEN_CONTENT = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/m;
3079
+ function canUsePlain(layout) {
3080
+ const str = layout.node.value;
3081
+ if (str !== "") {
3082
+ if (!(layout.isKey ? layout.flowOnly ? NS_PLAIN_FLOW_KEY : NS_PLAIN_BLOCK_KEY : layout.flowOnly ? NS_PLAIN_FLOW_IN : NS_PLAIN_FLOW_OUT).test(str)) return false;
3083
+ if (layout.shiftOfFirstLine === 0 && C_FORBIDDEN_FIRST_LINE.test(str)) return false;
3084
+ if (layout.shiftOfContent === 0) {
3085
+ const firstLineBreak = str.indexOf("\n");
3086
+ if (firstLineBreak !== -1) {
3087
+ const content = str.slice(firstLineBreak + 1);
3088
+ if (C_FORBIDDEN_CONTENT.test(content)) return false;
3089
+ }
3090
+ }
3091
+ }
3092
+ const resolvedTag = layout.presenterOptions.schema.resolveImplicitScalarTag(str).tag.tagName;
3093
+ if (!layout.node.tagged && resolvedTag !== layout.node.tag) return false;
3094
+ if (!layout.node.tagged && str === "=" && resolvedTag === layout.presenterOptions.schema.defaultScalarTag.tagName) return false;
3095
+ return true;
2965
3096
  }
2966
- function createPresenterState(options) {
2967
- const opts = {
2968
- ...DEFAULT_PRESENTER_OPTIONS,
2969
- ...options
2970
- };
2971
- return {
2972
- ...opts,
2973
- defaultScalarTagName: opts.schema.defaultScalarTag.tagName
2974
- };
3097
+ function canUseSingleQuoted(layout) {
3098
+ const str = layout.node.value;
3099
+ if (!(layout.isKey ? NB_SINGLE_ONE_LINE : NB_SINGLE_MULTI_LINE).test(str)) return false;
3100
+ if (/[ \t]\n|\n[ \t]/.test(str)) return false;
3101
+ if (!layout.isKey && layout.shiftOfContent === 0) {
3102
+ const firstLineBreak = str.indexOf("\n");
3103
+ if (firstLineBreak !== -1 && C_FORBIDDEN_CONTENT.test(str.slice(firstLineBreak + 1))) return false;
3104
+ }
3105
+ return true;
3106
+ }
3107
+ function canUseBlock(layout) {
3108
+ if (layout.flowOnly || !BLOCK_SCALAR_CONTENT.test(layout.node.value)) return false;
3109
+ const contentIndent = layout.shiftOfContent - layout.shiftOfParent;
3110
+ if (contentIndent < 1) return false;
3111
+ if (contentIndent > 9 && /^\n* /.test(layout.node.value)) return false;
3112
+ if (layout.shiftOfContent === 0 && C_FORBIDDEN_CONTENT.test(layout.node.value)) return false;
3113
+ return true;
3114
+ }
3115
+ function detectAllowedStyles(layout) {
3116
+ let mask = setBit(0, SCALAR_STYLE.DOUBLE_QUOTED);
3117
+ if (canUsePlain(layout)) mask = setBit(mask, SCALAR_STYLE.PLAIN);
3118
+ if (canUseSingleQuoted(layout)) mask = setBit(mask, SCALAR_STYLE.SINGLE_QUOTED);
3119
+ if (canUseBlock(layout)) mask = setBit(setBit(mask, SCALAR_STYLE.LITERAL_BLOCK), SCALAR_STYLE.FOLDED_BLOCK);
3120
+ layout.allowedStylesMask = mask;
3121
+ }
3122
+ function renderScalar(layout) {
3123
+ switch (layout.style) {
3124
+ case SCALAR_STYLE.PLAIN:
3125
+ return renderPlain(layout);
3126
+ case SCALAR_STYLE.SINGLE_QUOTED:
3127
+ return renderSingleQuoted(layout);
3128
+ case SCALAR_STYLE.LITERAL_BLOCK:
3129
+ return renderLiteralBlock(layout);
3130
+ case SCALAR_STYLE.FOLDED_BLOCK:
3131
+ return renderFoldedBlock(layout);
3132
+ case SCALAR_STYLE.DOUBLE_QUOTED:
3133
+ return renderDoubleQuoted(layout);
3134
+ }
3135
+ }
3136
+ function renderPlain(layout) {
3137
+ return encodeFlowBreaks(layout.node.value, layout.shiftOfContent);
3138
+ }
3139
+ function renderSingleQuoted(layout) {
3140
+ return `'${encodeFlowBreaks(layout.node.value, layout.shiftOfContent).replace(/'/g, "''")}'`;
3141
+ }
3142
+ function renderLiteralBlock(layout) {
3143
+ const value = layout.node.value;
3144
+ return "|" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(value, layout.shiftOfContent));
2975
3145
  }
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}`;
3146
+ function renderFoldedBlock(layout) {
3147
+ const value = layout.node.value;
3148
+ const w = layout.presenterOptions.lineWidth;
3149
+ let availableWidth = Infinity;
3150
+ if (w !== -1) availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
3151
+ return ">" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(foldBlockScalar(value, availableWidth), layout.shiftOfContent));
3152
+ }
3153
+ function renderDoubleQuoted(layout) {
3154
+ return `"${escapeString(layout.node.value)}"`;
3155
+ }
3156
+ function encodeFlowBreaks(string, shiftOfContent) {
3157
+ let nextLF = string.indexOf("\n");
3158
+ if (nextLF === -1) return string;
3159
+ const pad = " ".repeat(shiftOfContent);
3160
+ let result = string.slice(0, nextLF);
3161
+ const lineRe = /(\n+)([^\n]*)/g;
3162
+ lineRe.lastIndex = nextLF;
3163
+ let match;
3164
+ while (match = lineRe.exec(string)) {
3165
+ const breaks = match[1].length;
3166
+ const line = match[2];
3167
+ result += "\n".repeat(breaks + 1) + pad + line;
3168
+ }
3169
+ return result;
2981
3170
  }
2982
3171
  function indentString(string, spaces) {
2983
- const ind = " ".repeat(spaces);
3172
+ const indent = " ".repeat(spaces);
2984
3173
  let position = 0;
2985
3174
  let result = "";
2986
3175
  const length = string.length;
@@ -2994,191 +3183,26 @@ function indentString(string, spaces) {
2994
3183
  line = string.slice(position, next + 1);
2995
3184
  position = next + 1;
2996
3185
  }
2997
- if (line.length && line !== "\n") result += ind;
3186
+ if (line.length && line !== "\n") result += indent;
2998
3187
  result += line;
2999
3188
  }
3000
3189
  return result;
3001
3190
  }
3002
- function generateNextLine(state, level) {
3003
- return `
3004
- ${" ".repeat(state.indent * level)}`;
3005
- }
3006
- function scalarLayout(state, level) {
3007
- const indent = state.indent * Math.max(1, level);
3008
- return {
3009
- indent,
3010
- blockIndent: level === 0 ? state.indent + 1 : state.indent,
3011
- lineWidth: state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent)
3012
- };
3013
- }
3014
- function isWhitespace(c) {
3015
- return c === CHAR_SPACE || c === CHAR_TAB;
3016
- }
3017
- function startsWithDocumentSeparator(string) {
3018
- const marker = string.charCodeAt(0);
3019
- if (marker !== CHAR_MINUS && marker !== 46 || string.charCodeAt(1) !== marker || string.charCodeAt(2) !== marker) return false;
3020
- if (string.length === 3) return true;
3021
- const following = string.charCodeAt(3);
3022
- return isWhitespace(following) || following === CHAR_CARRIAGE_RETURN || following === CHAR_LINE_FEED;
3023
- }
3024
- function isPrintable(c) {
3025
- return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111;
3026
- }
3027
- function isNsCharOrWhitespace(c) {
3028
- return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
3029
- }
3030
- function isPlainSafe(c, prev, inblock) {
3031
- const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
3032
- const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
3033
- return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar && (inblock || c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET);
3034
- }
3035
- function isPlainSafeFirst(c) {
3036
- return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
3037
- }
3038
- function isPlainSafeAtStart(string, inblock) {
3039
- const first = codePointAt(string, 0);
3040
- if (isPlainSafeFirst(first)) return true;
3041
- if (string.length > 1 && (first === CHAR_MINUS || first === CHAR_QUESTION || first === CHAR_COLON)) {
3042
- const second = codePointAt(string, 1);
3043
- return !isWhitespace(second) && isPlainSafe(second, first, inblock);
3044
- }
3045
- return false;
3046
- }
3047
- function isPlainSafeLast(c) {
3048
- return !isWhitespace(c) && c !== CHAR_COLON;
3049
- }
3050
- function codePointAt(string, pos) {
3051
- const first = string.charCodeAt(pos);
3052
- let second;
3053
- if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
3054
- second = string.charCodeAt(pos + 1);
3055
- if (second >= 56320 && second <= 57343) return (first - 55296) * 1024 + second - 56320 + 65536;
3056
- }
3057
- return first;
3058
- }
3059
3191
  function needIndentIndicator(string) {
3060
3192
  return /^\n* /.test(string);
3061
3193
  }
3062
- var STYLE_PLAIN = 1;
3063
- var STYLE_SINGLE = 2;
3064
- var STYLE_LITERAL = 3;
3065
- var STYLE_FOLDED = 4;
3066
- var STYLE_DOUBLE = 5;
3067
- function chooseScalarStyle(state, string, layout, singleLineOnly, forceQuote, inblock) {
3068
- const { blockIndent, lineWidth } = layout;
3069
- let i;
3070
- let char = 0;
3071
- let prevChar = -1;
3072
- let hasLineBreak = false;
3073
- let hasFoldableLine = false;
3074
- const shouldTrackWidth = lineWidth !== -1;
3075
- let previousLineBreak = -1;
3076
- let plain = !startsWithDocumentSeparator(string) && isPlainSafeAtStart(string, inblock) && isPlainSafeLast(codePointAt(string, string.length - 1));
3077
- if (singleLineOnly || forceQuote) for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
3078
- char = codePointAt(string, i);
3079
- if (!isPrintable(char)) return STYLE_DOUBLE;
3080
- plain = plain && isPlainSafe(char, prevChar, inblock);
3081
- prevChar = char;
3082
- }
3083
- else {
3084
- for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
3085
- char = codePointAt(string, i);
3086
- if (char === CHAR_LINE_FEED) {
3087
- hasLineBreak = true;
3088
- if (shouldTrackWidth) {
3089
- hasFoldableLine = hasFoldableLine || i - previousLineBreak - 1 > lineWidth && !isMoreIndented(string[previousLineBreak + 1]);
3090
- previousLineBreak = i;
3091
- }
3092
- } else if (!isPrintable(char)) return STYLE_DOUBLE;
3093
- plain = plain && isPlainSafe(char, prevChar, inblock);
3094
- prevChar = char;
3095
- }
3096
- hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && !isMoreIndented(string[previousLineBreak + 1]);
3097
- }
3098
- if (!hasLineBreak && !hasFoldableLine) {
3099
- if (plain && !forceQuote) return STYLE_PLAIN;
3100
- return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
3101
- }
3102
- if (blockIndent > 9 && needIndentIndicator(string)) return STYLE_DOUBLE;
3103
- return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
3104
- }
3105
- function renderScalarStyle(string, style, layout) {
3106
- const { indent, blockIndent, lineWidth } = layout;
3107
- switch (style) {
3108
- case STYLE_PLAIN:
3109
- return encodeFlowBreaks(string, indent);
3110
- case STYLE_SINGLE:
3111
- return `'${encodeFlowBreaks(string, indent).replace(/'/g, "''")}'`;
3112
- case STYLE_LITERAL:
3113
- return "|" + blockHeader(string, blockIndent) + dropEndingNewline(indentString(string, indent));
3114
- case STYLE_FOLDED:
3115
- return ">" + blockHeader(string, blockIndent) + dropEndingNewline(indentString(foldBlockScalar(string, lineWidth), indent));
3116
- case STYLE_DOUBLE:
3117
- return `"${escapeString(string)}"`;
3118
- }
3119
- }
3120
- function resolveScalarStyle(state, node, layout, iskey, inblock) {
3121
- const singleLineOnly = iskey || !inblock;
3122
- if (node.style.singleQuoted) return STYLE_SINGLE;
3123
- if (node.style.doubleQuoted) return STYLE_DOUBLE;
3124
- if (!singleLineOnly) {
3125
- if (node.style.literal) return STYLE_LITERAL;
3126
- if (node.style.folded) return STYLE_FOLDED;
3127
- }
3128
- const string = node.value;
3129
- if (string.length === 0) {
3130
- if (node.style.tagged || state.schema.resolveImplicitScalarTag(string).tag.tagName === node.tag) return STYLE_PLAIN;
3131
- return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
3132
- }
3133
- const style = chooseScalarStyle(state, string, layout, singleLineOnly, state.forceQuotes && !iskey, inblock);
3134
- if (style === STYLE_PLAIN && !node.style.tagged && state.schema.resolveImplicitScalarTag(string).tag.tagName !== node.tag) return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
3135
- return style;
3136
- }
3137
- function blockHeader(string, indentPerLevel) {
3138
- const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
3194
+ function blockHeader(string, shiftOfParent, shiftOfContent) {
3195
+ const indentIndicator = needIndentIndicator(string) ? String(shiftOfContent - shiftOfParent) : "";
3139
3196
  const clip = string[string.length - 1] === "\n";
3140
3197
  return `${indentIndicator}${clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-"}
3141
3198
  `;
3142
3199
  }
3143
- function encodeFlowBreaks(string, indent) {
3144
- let nextLF = string.indexOf("\n");
3145
- if (nextLF === -1) return string;
3146
- const pad = " ".repeat(indent);
3147
- let result = string.slice(0, nextLF);
3148
- const lineRe = /(\n+)([^\n]*)/g;
3149
- lineRe.lastIndex = nextLF;
3150
- let match;
3151
- while (match = lineRe.exec(string)) {
3152
- const breaks = match[1].length;
3153
- const line = match[2];
3154
- result += "\n".repeat(breaks + 1) + pad + line;
3155
- }
3156
- return result;
3157
- }
3158
3200
  function dropEndingNewline(string) {
3159
3201
  return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
3160
3202
  }
3161
3203
  function isMoreIndented(char) {
3162
3204
  return char === " " || char === " ";
3163
3205
  }
3164
- function foldBlockScalar(string, width) {
3165
- const lineRe = /(\n+)([^\n]*)/g;
3166
- let nextLF = string.indexOf("\n");
3167
- if (nextLF === -1) nextLF = string.length;
3168
- lineRe.lastIndex = nextLF;
3169
- let result = foldLine(string.slice(0, nextLF), width);
3170
- let prevMoreIndented = string[0] === "\n" || isMoreIndented(string[0]);
3171
- let moreIndented;
3172
- let match;
3173
- while (match = lineRe.exec(string)) {
3174
- const prefix = match[1];
3175
- const line = match[2];
3176
- moreIndented = line !== "" && isMoreIndented(line[0]);
3177
- result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
3178
- prevMoreIndented = moreIndented;
3179
- }
3180
- return result;
3181
- }
3182
3206
  function foldLine(line, width) {
3183
3207
  if (line === "" || isMoreIndented(line[0])) return line;
3184
3208
  const breakRe = / [^ \t]/g;
@@ -3204,43 +3228,133 @@ ${line.slice(curr + 1)}`;
3204
3228
  else result += line.slice(start);
3205
3229
  return result.slice(1);
3206
3230
  }
3207
- function escapeString(string) {
3208
- let result = "";
3209
- let char = 0;
3210
- for (let i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
3211
- char = codePointAt(string, i);
3212
- const escapeSeq = ESCAPE_SEQUENCES[char];
3213
- if (escapeSeq) {
3214
- result += escapeSeq;
3215
- continue;
3216
- }
3217
- if (isPrintable(char)) {
3218
- result += string[i];
3219
- if (char >= 65536) result += string[i + 1];
3220
- continue;
3221
- }
3222
- result += encodeNonPrintable(char);
3231
+ function foldBlockScalar(string, width) {
3232
+ const lineRe = /(\n+)([^\n]*)/g;
3233
+ let nextLF = string.indexOf("\n");
3234
+ if (nextLF === -1) nextLF = string.length;
3235
+ lineRe.lastIndex = nextLF;
3236
+ let result = foldLine(string.slice(0, nextLF), width);
3237
+ let prevMoreIndented = string[0] === "\n" || isMoreIndented(string[0]);
3238
+ let moreIndented;
3239
+ let match;
3240
+ while (match = lineRe.exec(string)) {
3241
+ const prefix = match[1];
3242
+ const line = match[2];
3243
+ moreIndented = line !== "" && isMoreIndented(line[0]);
3244
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
3245
+ prevMoreIndented = moreIndented;
3223
3246
  }
3224
3247
  return result;
3225
3248
  }
3249
+ var CHARACTERS_TO_ESCAPE = /["\\\x00-\x1F\x7F-\xA0\u2028\u2029\uD800-\uDFFF\uFEFF\uFFFE\uFFFF]/gu;
3250
+ function escapeCharacter(character) {
3251
+ switch (character) {
3252
+ case "\0":
3253
+ return "\\0";
3254
+ case "\x07":
3255
+ return "\\a";
3256
+ case "\b":
3257
+ return "\\b";
3258
+ case " ":
3259
+ return "\\t";
3260
+ case "\n":
3261
+ return "\\n";
3262
+ case "\v":
3263
+ return "\\v";
3264
+ case "\f":
3265
+ return "\\f";
3266
+ case "\r":
3267
+ return "\\r";
3268
+ case "\x1B":
3269
+ return "\\e";
3270
+ case '"':
3271
+ return '\\"';
3272
+ case "\\":
3273
+ return "\\\\";
3274
+ case "\x85":
3275
+ return "\\N";
3276
+ case "\xA0":
3277
+ return "\\_";
3278
+ case "\u2028":
3279
+ return "\\L";
3280
+ case "\u2029":
3281
+ return "\\P";
3282
+ }
3283
+ const code = character.charCodeAt(0);
3284
+ const hex = code.toString(16).toUpperCase();
3285
+ if (code <= 255) return `\\x${"0".repeat(2 - hex.length)}${hex}`;
3286
+ return `\\u${"0".repeat(4 - hex.length)}${hex}`;
3287
+ }
3288
+ function escapeString(string) {
3289
+ return string.replace(CHARACTERS_TO_ESCAPE, escapeCharacter);
3290
+ }
3291
+ var CHAR_LINE_FEED = 10;
3292
+ var DEFAULT_PRESENTER_OPTIONS = {
3293
+ indent: 2,
3294
+ seqNoIndent: false,
3295
+ seqInlineFirst: true,
3296
+ lineWidth: 80,
3297
+ flowBracketPadding: false,
3298
+ flowSkipCommaSpace: false,
3299
+ flowSkipColonSpace: false,
3300
+ quoteFlowKeys: false,
3301
+ quoteStyle: "single",
3302
+ forceQuotes: false,
3303
+ scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
3304
+ tagBeforeAnchor: false
3305
+ };
3306
+ function nodeTagShort(node) {
3307
+ return node.tagged ? node.tag : tagNameShort(node.tag);
3308
+ }
3309
+ function createPresenterState(options) {
3310
+ const opts = {
3311
+ ...DEFAULT_PRESENTER_OPTIONS,
3312
+ ...options
3313
+ };
3314
+ if (opts.flowSkipColonSpace) opts.quoteFlowKeys = true;
3315
+ return {
3316
+ ...opts,
3317
+ defaultScalarTagName: opts.schema.defaultScalarTag.tagName,
3318
+ openEnded: false
3319
+ };
3320
+ }
3321
+ function generateNextLine(state, level) {
3322
+ return `
3323
+ ${" ".repeat(state.indent * level)}`;
3324
+ }
3325
+ function scalarLayout(state, node, parent, level, isKey, flowOnly) {
3326
+ return {
3327
+ node,
3328
+ parent,
3329
+ level,
3330
+ isKey,
3331
+ flowOnly,
3332
+ shiftOfParent: level === 0 ? -1 : state.indent * (level - 1),
3333
+ shiftOfContent: state.indent * Math.max(1, level),
3334
+ shiftOfFirstLine: level === 0 ? 0 : state.indent * level,
3335
+ presenterOptions: state,
3336
+ allowedStylesMask: 0,
3337
+ style: node.style
3338
+ };
3339
+ }
3226
3340
  function writeFlowSequence(state, level, node) {
3227
3341
  let result = "";
3228
3342
  for (let index = 0, length = node.items.length; index < length; index += 1) {
3229
- const item = writeNode(state, level, node.items[index], {});
3230
- if (result !== "") result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3343
+ const item = writeNode(state, level, node.items[index], node, {}).text;
3344
+ if (index > 0) result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3231
3345
  result += item;
3232
3346
  }
3233
- const pad = state.flowBracketPadding && result !== "" ? " " : "";
3347
+ const pad = state.flowBracketPadding && node.items.length > 0 ? " " : "";
3234
3348
  return `[${pad}${result}${pad}]`;
3235
3349
  }
3236
3350
  function writeBlockSequence(state, level, node, compact) {
3237
3351
  let result = "";
3238
3352
  for (let index = 0, length = node.items.length; index < length; index += 1) {
3239
- const item = writeNode(state, level + 1, node.items[index], {
3353
+ const item = writeNode(state, level + 1, node.items[index], node, {
3240
3354
  block: true,
3241
3355
  compact: state.seqInlineFirst,
3242
3356
  isblockseq: true
3243
- });
3357
+ }).text;
3244
3358
  if (!compact || result !== "") result += generateNextLine(state, level);
3245
3359
  if (item === "" || CHAR_LINE_FEED === item.charCodeAt(0)) result += "-";
3246
3360
  else result += "- ";
@@ -3250,70 +3364,51 @@ function writeBlockSequence(state, level, node, compact) {
3250
3364
  }
3251
3365
  function writeFlowMapping(state, level, node) {
3252
3366
  let result = "";
3253
- const items = sortMappingItems(state, node.items);
3254
- for (const { key, value } of items) {
3367
+ for (const { key, value } of node.items) {
3255
3368
  let pairBuffer = "";
3256
3369
  if (result !== "") pairBuffer += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3257
- const keyText = writeNode(state, level, key, { iskey: true });
3258
- const explicitPair = keyText.length > 1024;
3259
- if (explicitPair) pairBuffer += "? ";
3260
- else if (state.quoteFlowKeys) pairBuffer += '"';
3261
- const valueText = writeNode(state, level, value, {});
3370
+ const keyRender = writeNode(state, level, key, node, { iskey: true });
3371
+ const keyText = keyRender.text;
3372
+ const valueText = writeNode(state, level, value, node, {}).text;
3262
3373
  const sep = state.flowSkipColonSpace || valueText === "" ? "" : " ";
3263
- pairBuffer += `${keyText}${state.quoteFlowKeys && !explicitPair ? '"' : ""}:${sep}${valueText}`;
3374
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
3375
+ const keyColonSep = key.kind === "alias" || keyIsBareProps ? " " : "";
3376
+ pairBuffer += `${keyText}${keyColonSep}:${sep}${valueText}`;
3264
3377
  result += pairBuffer;
3265
3378
  }
3266
3379
  const pad = state.flowBracketPadding && result !== "" ? " " : "";
3267
3380
  return `{${pad}${result}${pad}}`;
3268
3381
  }
3269
- function sortKeyValue(key) {
3270
- return key.kind === "scalar" ? key.value : key;
3271
- }
3272
- function sortMappingItems(state, items) {
3273
- if (!state.sortKeys) return items;
3274
- const copy = items.slice();
3275
- if (state.sortKeys === true) copy.sort((a, b) => {
3276
- const x = sortKeyValue(a.key);
3277
- const y = sortKeyValue(b.key);
3278
- if (x < y) return -1;
3279
- if (x > y) return 1;
3280
- return 0;
3281
- });
3282
- else {
3283
- const fn = state.sortKeys;
3284
- copy.sort((a, b) => fn(sortKeyValue(a.key), sortKeyValue(b.key)));
3285
- }
3286
- return copy;
3287
- }
3288
3382
  function writeBlockMapping(state, level, node, compact) {
3289
3383
  let result = "";
3290
- const items = sortMappingItems(state, node.items);
3291
- for (let index = 0, length = items.length; index < length; index += 1) {
3384
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
3292
3385
  let pairBuffer = "";
3293
3386
  if (!compact || result !== "") pairBuffer += generateNextLine(state, level);
3294
- const { key, value } = items[index];
3295
- const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && !key.style.flow && key.items.length !== 0 || key.kind === "scalar" && (key.style.literal || key.style.folded);
3296
- const keyText = keyIsBlock ? writeNode(state, level + 1, key, {
3387
+ const { key, value } = node.items[index];
3388
+ const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && key.style === COLLECTION_STYLE.BLOCK && key.items.length !== 0 || key.kind === "scalar" && (key.style === SCALAR_STYLE.LITERAL_BLOCK || key.style === SCALAR_STYLE.FOLDED_BLOCK);
3389
+ const keyRender = keyIsBlock ? writeNode(state, level + 1, key, node, {
3297
3390
  block: true,
3298
3391
  compact: true,
3299
3392
  isblockseq: !cannotBeCompact(state, key, level + 1)
3300
- }) : writeNode(state, level + 1, key, {
3393
+ }) : writeNode(state, level + 1, key, node, {
3301
3394
  block: true,
3302
3395
  compact: true,
3303
3396
  iskey: true
3304
3397
  });
3398
+ const keyText = keyRender.text;
3305
3399
  const keyHasLineBreak = key.kind === "scalar" && key.value.indexOf("\n") !== -1;
3306
- const explicitPair = keyIsBlock || keyHasLineBreak || keyText.length > 1024;
3400
+ const keyIsTooLong = keyText.length > 1024 && /^[\s\S]{1025}/u.test(keyText);
3401
+ const explicitPair = keyIsBlock || keyHasLineBreak || keyIsTooLong;
3307
3402
  if (explicitPair) if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?";
3308
3403
  else pairBuffer += "? ";
3309
3404
  pairBuffer += keyText;
3310
3405
  if (explicitPair) pairBuffer += generateNextLine(state, level);
3311
- const valueText = writeNode(state, level + 1, value, {
3406
+ const valueText = writeNode(state, level + 1, value, node, {
3312
3407
  block: true,
3313
3408
  compact: explicitPair,
3314
3409
  isblockseq: explicitPair && !cannotBeCompact(state, value, level + 1)
3315
- });
3316
- const keyIsBareProps = key.kind === "scalar" && key.value === "" && keyText !== "" && keyText.charCodeAt(keyText.length - 1) !== CHAR_SINGLE_QUOTE && keyText.charCodeAt(keyText.length - 1) !== CHAR_DOUBLE_QUOTE;
3410
+ }).text;
3411
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
3317
3412
  const keyColonSep = !explicitPair && (key.kind === "alias" || keyIsBareProps) ? " " : "";
3318
3413
  if (valueText === "" || CHAR_LINE_FEED === valueText.charCodeAt(0)) pairBuffer += `${keyColonSep}:`;
3319
3414
  else pairBuffer += `${keyColonSep}: `;
@@ -3323,29 +3418,41 @@ function writeBlockMapping(state, level, node, compact) {
3323
3418
  return result;
3324
3419
  }
3325
3420
  function cannotBeCompact(state, node, level) {
3326
- return node.style.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3421
+ if (node.kind === "alias") return true;
3422
+ return node.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3327
3423
  }
3328
- function writeNode(state, level, node, ctx) {
3329
- if (node.kind === "alias") return `*${node.anchor}`;
3424
+ function writeNode(state, level, node, parent, ctx) {
3425
+ if (node.kind === "alias") {
3426
+ state.openEnded = false;
3427
+ return {
3428
+ text: `*${node.anchor}`,
3429
+ noBody: false
3430
+ };
3431
+ }
3330
3432
  const { block = false, iskey = false, isblockseq = false } = ctx;
3331
3433
  let compact = ctx.compact ?? false;
3332
3434
  const hasAnchor = node.anchor !== void 0;
3333
3435
  if (cannotBeCompact(state, node, level)) compact = false;
3334
3436
  let body;
3335
- let shouldPrintTag = node.style.tagged;
3336
- const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && !node.style.flow && node.items.length !== 0;
3437
+ let shouldPrintTag = node.tagged;
3438
+ const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0;
3337
3439
  if (node.kind === "mapping") if (useBlockCollection) body = writeBlockMapping(state, level, node, compact);
3338
3440
  else body = writeFlowMapping(state, level, node);
3339
3441
  else if (node.kind === "sequence") if (useBlockCollection) if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact);
3340
3442
  else body = writeBlockSequence(state, level, node, compact);
3341
3443
  else body = writeFlowSequence(state, level, node);
3342
3444
  else {
3343
- const layout = scalarLayout(state, level);
3344
- const style = resolveScalarStyle(state, node, layout, iskey, block);
3345
- body = renderScalarStyle(node.value, style, layout);
3346
- shouldPrintTag = node.style.tagged || style !== STYLE_PLAIN && node.tag !== state.defaultScalarTagName;
3347
- }
3445
+ const layout = scalarLayout(state, node, parent, level, iskey, !block);
3446
+ detectAllowedStyles(layout);
3447
+ for (const rule of state.scalarStyleRules) rule(layout);
3448
+ body = renderScalar(layout);
3449
+ state.openEnded = (layout.style === SCALAR_STYLE.LITERAL_BLOCK || layout.style === SCALAR_STYLE.FOLDED_BLOCK) && (node.value === "\n" || node.value.endsWith("\n\n"));
3450
+ shouldPrintTag = node.tagged || body === "" && layout.flowOnly && parent?.kind === "sequence" && !hasAnchor || layout.style !== SCALAR_STYLE.PLAIN && node.tag !== state.defaultScalarTagName;
3451
+ }
3452
+ if ((node.kind === "mapping" || node.kind === "sequence") && !useBlockCollection) state.openEnded = false;
3348
3453
  if (useBlockCollection && compact && level > 0 && state.indent > 2) body = `${" ".repeat(state.indent - 2)}${body}`;
3454
+ const noBody = body === "";
3455
+ let text = body;
3349
3456
  if (shouldPrintTag || hasAnchor) {
3350
3457
  const props = [];
3351
3458
  const tag = shouldPrintTag ? nodeTagShort(node) : null;
@@ -3358,19 +3465,15 @@ function writeNode(state, level, node, ctx) {
3358
3465
  if (tag !== null) props.push(tag);
3359
3466
  }
3360
3467
  const sep = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
3361
- body = `${props.join(" ")}${sep}${body}`;
3468
+ text = `${props.join(" ")}${sep}${body}`;
3362
3469
  }
3363
- return body;
3470
+ return {
3471
+ text,
3472
+ noBody
3473
+ };
3364
3474
  }
3365
3475
  function rootStartsOwnLine(node) {
3366
- return (node.kind === "sequence" || node.kind === "mapping") && !node.style.flow && node.items.length !== 0 && !node.style.tagged && node.anchor === void 0;
3367
- }
3368
- function isOpenEnded(node) {
3369
- let leaf = node;
3370
- while ((leaf.kind === "sequence" || leaf.kind === "mapping") && !leaf.style.flow && leaf.items.length !== 0) leaf = leaf.kind === "sequence" ? leaf.items[leaf.items.length - 1] : leaf.items[leaf.items.length - 1].value;
3371
- if (leaf.kind !== "scalar" || !(leaf.style.literal || leaf.style.folded)) return false;
3372
- const { value } = leaf;
3373
- return value.endsWith("\n\n") || value === "\n";
3476
+ return (node.kind === "sequence" || node.kind === "mapping") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0 && !node.tagged && node.anchor === void 0;
3374
3477
  }
3375
3478
  function writeDocumentDirectives(doc) {
3376
3479
  let result = "";
@@ -3392,6 +3495,7 @@ function present(documents, options) {
3392
3495
  let previousEnded = false;
3393
3496
  for (let index = 0; index < documents.length; index += 1) {
3394
3497
  const doc = documents[index];
3498
+ state.openEnded = false;
3395
3499
  const directives = writeDocumentDirectives(doc);
3396
3500
  const hasDirectives = directives !== "";
3397
3501
  const marker = doc.explicitStart || hasDirectives || index > 0 && !previousEnded;
@@ -3399,18 +3503,18 @@ function present(documents, options) {
3399
3503
  if (doc.contents === null) {
3400
3504
  if (marker) result += "---\n";
3401
3505
  } else if (marker) {
3402
- const body = writeNode(state, 0, doc.contents, {
3506
+ const body = writeNode(state, 0, doc.contents, null, {
3403
3507
  block: true,
3404
3508
  compact: true
3405
- });
3509
+ }).text;
3406
3510
  const sep = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
3407
3511
  result += `---${sep}${body}
3408
3512
  `;
3409
- } else result += writeNode(state, 0, doc.contents, {
3513
+ } else result += writeNode(state, 0, doc.contents, null, {
3410
3514
  block: true,
3411
3515
  compact: true
3412
- }) + "\n";
3413
- previousEnded = doc.explicitEnd || doc.contents !== null && isOpenEnded(doc.contents);
3516
+ }).text + "\n";
3517
+ previousEnded = doc.explicitEnd || state.openEnded;
3414
3518
  if (previousEnded) result += "...\n";
3415
3519
  }
3416
3520
  return result;
@@ -3421,9 +3525,17 @@ var DEFAULT_DUMP_OPTIONS = {
3421
3525
  skipInvalid: false,
3422
3526
  noRefs: false,
3423
3527
  flowLevel: -1,
3528
+ sortKeys: false,
3424
3529
  transform: () => {
3425
3530
  }
3426
3531
  };
3532
+ function defaultCompareFn(a, b) {
3533
+ const x = String(a);
3534
+ const y = String(b);
3535
+ if (x < y) return -1;
3536
+ if (x > y) return 1;
3537
+ return 0;
3538
+ }
3427
3539
  function dump(input, options = {}) {
3428
3540
  const opts = {
3429
3541
  ...DEFAULT_DUMP_OPTIONS,
@@ -3435,9 +3547,16 @@ function dump(input, options = {}) {
3435
3547
  });
3436
3548
  if (opts.flowLevel >= 0) visit(documents, (node, ctx) => {
3437
3549
  if (ctx.depth < opts.flowLevel) return;
3438
- node.style.flow = true;
3550
+ if (node.kind === "sequence" || node.kind === "mapping") node.style = COLLECTION_STYLE.FLOW;
3439
3551
  return VISIT_SKIP;
3440
3552
  });
3553
+ if (opts.sortKeys) {
3554
+ const compareFn = opts.sortKeys === true ? defaultCompareFn : opts.sortKeys;
3555
+ visit(documents, (node) => {
3556
+ if (node.kind !== "mapping") return;
3557
+ node.items.sort((a, b) => compareFn(a.key.kind === "scalar" ? a.key.value : "", b.key.kind === "scalar" ? b.key.value : ""));
3558
+ });
3559
+ }
3441
3560
  opts.transform(documents);
3442
3561
  return present(documents, {
3443
3562
  ...pick(opts, Object.keys(DEFAULT_PRESENTER_OPTIONS)),
@@ -4030,16 +4149,10 @@ function lockedKeysReferencedBy(rawKeys) {
4030
4149
  return [...hit];
4031
4150
  }
4032
4151
  function assertValidParsedKey(rawKey, parsed) {
4033
- if (rawKey.startsWith("~") || parsed.key.includes("~")) {
4034
- throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684 ~ \u64CD\u4F5C\u7B26`, {
4035
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4036
- hint: ["\u6309 name \u5408\u5E76/\u8FFD\u52A0\u6570\u7EC4\u5143\u7D20\u7684 ~ \u4E0E ~? \u5DF2\u79FB\u9664\uFF0C\u6539\u7528 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\u7684\u811A\u672C\u4E00\u8282\uFF09\u3002"]
4037
- });
4038
- }
4039
- if (rawKey.includes("<") || rawKey.includes(">")) {
4040
- throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684\u5C16\u62EC\u53F7\u8F6C\u4E49`, {
4152
+ if (/[~<>]/.test(rawKey)) {
4153
+ throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684\u64CD\u4F5C\u7B26\uFF08~ / ~? / <key>\uFF09`, {
4041
4154
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4042
- hint: ["<key> \u8F6C\u4E49\u5DF2\u968F ~ \u64CD\u4F5C\u7B26\u79FB\u9664\u2014\u2014mihomo-cli \u9876\u5C42\u952E\u4E0D\u542B\u5C16\u62EC\u53F7\uFF0C\u76F4\u63A5\u5199\u952E\u540D\u5373\u53EF\u3002"]
4155
+ hint: ["\u6309 name \u5408\u5E76\u6570\u7EC4\u5143\u7D20\u6539\u7528 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\uFF09\uFF1B<key> \u8F6C\u4E49\u4E0D\u518D\u9700\u8981\uFF0C\u76F4\u63A5\u5199\u952E\u540D\u3002"]
4043
4156
  });
4044
4157
  }
4045
4158
  if (parsed.key === "") {
@@ -4192,12 +4305,6 @@ function normalizeMatch(raw, fileName) {
4192
4305
  throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u5FC5\u987B\u662F\u5BF9\u8C61\uFF08name / url-domain\uFF09`, { label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF" });
4193
4306
  }
4194
4307
  const rawEntries = raw;
4195
- if ("subscription" in rawEntries) {
4196
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u7528\u4E86 subscription \u952E`, {
4197
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4198
- hint: ["subscription \u952E\u5DF2\u6536\u6389\uFF08\u4E0E name \u540C\u4E49\u4F46\u4E24\u5957\u5199\u6CD5\uFF09\uFF0C\u8BF7\u6539\u5199 name\uFF0C\u5339\u914D\u8BED\u4E49\u4E0D\u53D8:", " match:", " name: edu*"]
4199
- });
4200
- }
4201
4308
  const result = {};
4202
4309
  const problems = [];
4203
4310
  for (const [key, value] of Object.entries(rawEntries)) {
@@ -4228,16 +4335,6 @@ function normalizeMatch(raw, fileName) {
4228
4335
  ]
4229
4336
  });
4230
4337
  }
4231
- const impossible = arr.find((v) => !v.includes("*") && !SAFE_NAME_RE.test(v));
4232
- if (impossible !== void 0) {
4233
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 name \u503C\u4E0D\u53EF\u80FD\u5339\u914D\u4EFB\u4F55\u8BA2\u9605: "${impossible}"`, {
4234
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4235
- hint: [
4236
- "\u8BA2\u9605\u540D\u53EA\u80FD\u542B\u5B57\u6BCD\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u8FDE\u5B57\u7B26\u4E0E\u4E2D\u6587\uFF081-64 \u5B57\u7B26\uFF09\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u8BEF\u5E26\u4E86 /\u3001~\u3001\u7A7A\u683C\u3001\u70B9\u53F7\u7B49\u5B57\u7B26\u3002",
4237
- "\u66F4\u590D\u6742\u7684\u5339\u914D\u5199 JS \u8986\u5199\u811A\u672C\uFF08README\u300C\u8986\u5199\u914D\u7F6E\u300D\u7AE0\u8282\uFF09\u3002"
4238
- ]
4239
- });
4240
- }
4241
4338
  }
4242
4339
  result[key] = arr;
4243
4340
  }
@@ -4267,14 +4364,8 @@ function isValidNamePattern(value) {
4267
4364
  return star === 0 || star === value.length - 1;
4268
4365
  }
4269
4366
  function urlDomainValueProblem(value) {
4270
- if (value.includes("*") || value.includes("?")) {
4271
- return `url-domain \u4E0D\u652F\u6301\u901A\u914D\u7B26\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF0C\u53EA\u505A\u5B57\u9762\u540E\u7F00\u6BD4\u5BF9`;
4272
- }
4273
- if (/[:/]/.test(value)) {
4274
- return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF1A\u4E0D\u8981\u5E26\u534F\u8BAE\u3001\u8DEF\u5F84\u6216\u7AEF\u53E3\uFF0C\u8BF7\u53BB\u6389 https://\u3001\u5C3E\u659C\u6760\u4E0E\u7AEF\u53E3`;
4275
- }
4276
- if (/\s/.test(value)) {
4277
- return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF1A\u503C\u4E2D\u4E0D\u80FD\u542B\u7A7A\u683C`;
4367
+ if (/[*?:/\s]/.test(value)) {
4368
+ return `url-domain \u53EA\u8981\u88F8\u57DF\u540D\u3001\u4E0D\u652F\u6301\u901A\u914D\uFF08\u5F53\u524D\u503C "${value}"\uFF09\uFF0C\u53BB\u6389 https://\u3001\u8DEF\u5F84\u3001\u7AEF\u53E3\u3001* \u4E0E\u7A7A\u683C`;
4278
4369
  }
4279
4370
  return void 0;
4280
4371
  }
@@ -4330,24 +4421,11 @@ function selectActiveOverwriteFiles(files, scope) {
4330
4421
  var METADATA_KEYS = /* @__PURE__ */ new Set(["match", "enabled"]);
4331
4422
  function assertNoMetadataKeyLookalikes(config, fileName) {
4332
4423
  for (const rawKey of Object.keys(config)) {
4333
- const parsed = parseOverrideKey(rawKey).key;
4334
- if (parsed !== rawKey && METADATA_KEYS.has(parsed)) {
4335
- throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684\u5143\u6570\u636E\u952E "${rawKey}" \u4E0D\u652F\u6301\u64CD\u4F5C\u7B26`, {
4336
- label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4337
- hint: [
4338
- `match \u4E0E enabled \u662F\u672C CLI \u7684\u5143\u6570\u636E\u952E\uFF0C\u5728\u5408\u5E76\u524D\u5C31\u88AB\u5265\u79BB\uFF0C\u5E26\u64CD\u4F5C\u7B26\u5199\u6CD5\uFF08\u5982 ${rawKey}\uFF09\u4E0D\u4F1A\u751F\u6548\uFF0C\u53CD\u800C\u4F1A\u628A ${parsed} \u5F53\u666E\u901A\u914D\u7F6E\u952E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\u3002`,
4339
- `\u8BF7\u76F4\u63A5\u5199 ${parsed}: <\u503C>\u3002`
4340
- ]
4341
- });
4342
- }
4343
- const normalized = rawKey.trim().toLowerCase();
4424
+ const normalized = parseOverrideKey(rawKey.trim().toLowerCase()).key;
4344
4425
  if (normalized !== rawKey && METADATA_KEYS.has(normalized)) {
4345
4426
  throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 "${rawKey}" \u7591\u4F3C\u60F3\u5199\u5143\u6570\u636E\u952E ${normalized}`, {
4346
4427
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4347
- hint: [
4348
- `YAML \u952E\u533A\u5206\u5927\u5C0F\u5199\u4E0E\u7A7A\u767D\uFF0C"${rawKey}" \u4E0D\u4F1A\u88AB\u8BC6\u522B\u4E3A ${normalized}\u2014\u2014\u6587\u4EF6\u4E0D\u4F1A\u88AB\u505C\u7528/\u9650\u5B9A\u4F5C\u7528\u57DF\uFF0C\u8BE5\u952E\u53CD\u800C\u4F1A\u5F53\u666E\u901A\u914D\u7F6E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\uFF08\u5185\u6838\u5BF9\u672A\u77E5\u9876\u5C42\u952E\u4E0D\u62A5\u9519\uFF0C\u4E0D\u4F1A\u6709\u4EFB\u4F55\u63D0\u793A\uFF09\u3002`,
4349
- `\u8BF7\u5199\u6210 ${normalized}: <\u503C>\u3002`
4350
- ]
4428
+ hint: [`\u5143\u6570\u636E\u952E\u53EA\u8BA4\u7CBE\u786E\u5199\u6CD5\uFF08\u533A\u5206\u5927\u5C0F\u5199\u3001\u4E0D\u5E26\u64CD\u4F5C\u7B26\uFF09\uFF0C"${rawKey}" \u4E0D\u4F1A\u751F\u6548\uFF0C\u53CD\u800C\u4F1A\u5F53\u666E\u901A\u952E\u5199\u8FDB\u8FD0\u884C\u914D\u7F6E\u3002`, `\u8BF7\u5199\u6210 ${normalized}: <\u503C>\u3002`]
4351
4429
  });
4352
4430
  }
4353
4431
  }
@@ -4409,7 +4487,7 @@ function loadOverwriteScript(filePath, fileName) {
4409
4487
  throw new CliError(`\u8986\u5199\u811A\u672C "${fileName}" \u7F3A\u5C11\u53D8\u6362\u51FD\u6570`, {
4410
4488
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4411
4489
  hint: [
4412
- "\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF1Breturn true \u8868\u793A\u547D\u4E2D\u5F53\u524D\u8BA2\u9605\uFF0C\u5176\u4F59\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
4490
+ "\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF0C\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
4413
4491
  " export default function (config, ctx) { ... }",
4414
4492
  "CommonJS \u5199\u6CD5 module.exports = function (config, ctx) { ... } \u540C\u6837\u8BA4\u3002"
4415
4493
  ]
@@ -4493,7 +4571,6 @@ function applyOverwrite(baseConfig, files, opts) {
4493
4571
  let result = { ...baseConfig };
4494
4572
  const scriptWarnings = [];
4495
4573
  const scriptLockedHits = [];
4496
- const scriptMatches = [];
4497
4574
  const host = hostFromSubUrl(opts.scope?.subUrl) ?? "";
4498
4575
  const subscription = { name: opts.scope?.subName ?? "", url: opts.scope?.subUrl ?? "", host };
4499
4576
  for (const file of files) {
@@ -4517,14 +4594,13 @@ function applyOverwrite(baseConfig, files, opts) {
4517
4594
  });
4518
4595
  }
4519
4596
  scriptWarnings.push(...notes.map((message) => `${message}\uFF08\u811A\u672C ${file.name}\uFF09`));
4520
- scriptMatches.push({ file: file.name, matched: returned === true });
4521
4597
  const keys = diffLockedKeys(before, result);
4522
4598
  if (keys.length > 0) scriptLockedHits.push({ file: file.name, keys });
4523
4599
  continue;
4524
4600
  }
4525
4601
  result = mergeConfigLevel(result, file.config ?? {}, true);
4526
4602
  }
4527
- return { config: result, scriptWarnings, scriptLockedHits, scriptMatches };
4603
+ return { config: result, scriptWarnings, scriptLockedHits };
4528
4604
  }
4529
4605
  function listOverwriteFile(scope) {
4530
4606
  const { ok, broken } = readOverwriteFiles();
@@ -4532,23 +4608,21 @@ function listOverwriteFile(scope) {
4532
4608
  return {
4533
4609
  enabled,
4534
4610
  dir: USER_DATA_DIR,
4535
- entries: ok,
4536
4611
  files: ok.map((f) => ({
4537
4612
  name: f.name,
4538
4613
  kind: f.transform ? "script" : "yaml",
4539
4614
  keys: f.transform ? [] : Object.keys(f.config || {}),
4540
4615
  scope: summarizeMatch(f.match),
4541
4616
  enabled: f.enabled !== false,
4542
- ...scope ? { matched: matchesScope(f.match, scope) } : {}
4617
+ ...scope && !f.transform ? { matched: matchesScope(f.match, scope) } : {}
4543
4618
  })),
4544
4619
  broken
4545
4620
  };
4546
4621
  }
4547
4622
 
4548
4623
  // src/config.ts
4549
- var SAFE_YAML_LOAD_OPTIONS = { maxAliases: YAML_MAX_ALIASES };
4550
4624
  function loadYamlSafe(content) {
4551
- return load(content, SAFE_YAML_LOAD_OPTIONS);
4625
+ return load(content, { maxAliases: YAML_MAX_ALIASES });
4552
4626
  }
4553
4627
  function parseConfigContent(content, errorMsg) {
4554
4628
  const label = errorMsg || "\u5185\u5BB9";
@@ -4716,20 +4790,6 @@ function buildConfig(subRawContent, mode, scope) {
4716
4790
  function renderLockedWarning(source, keys) {
4717
4791
  return `${source}\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${keys.join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u3001\u63A7\u5236\u5668\u8BC1\u4E66\u4E0E\u5C40\u57DF\u7F51/\u5165\u7AD9\u9274\u6743\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF0C\u5165\u7AD9\u56FA\u5B9A\u53EA\u76D1\u542C\u56DE\u73AF\uFF0C\u9700\u8981\u5C40\u57DF\u7F51\u5165\u7AD9\u8BF7\u5728\u672C\u673A\u53E6\u8D77\u4E00\u4E2A mihomo-cli \u5B9E\u4F8B\uFF09`;
4718
4792
  }
4719
- function judgeScriptMatches(subRawContent, mode, scope, entries) {
4720
- try {
4721
- const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
4722
- const settings = readSettings();
4723
- const active = settings.overwrite_enabled !== false ? selectActiveOverwriteFiles(entries, scope) : [];
4724
- const { scriptMatches } = applyOverwrite(subscriptionConfig, active, {
4725
- mode,
4726
- scope
4727
- });
4728
- return { matches: scriptMatches };
4729
- } catch {
4730
- return { matches: [] };
4731
- }
4732
- }
4733
4793
  function deriveRuntimeMode(info) {
4734
4794
  return info?.tun ? "tun" : "mixed";
4735
4795
  }
@@ -4756,7 +4816,7 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
4756
4816
  }
4757
4817
  const hint = ["", ...detail.split("\n").map((line) => line.trim() ? `${HINT_INDENT}${line}` : "")];
4758
4818
  if (overwriteSummaries.length > 0) {
4759
- hint.push("", `${HINT_INDENT}\u5F53\u524D\u751F\u6548\u7684\u8986\u5199\u6587\u4EF6:`);
4819
+ hint.push("", `${HINT_INDENT}\u672C\u6B21\u53C2\u4E0E\u6784\u5EFA\u7684\u8986\u5199\u6587\u4EF6:`);
4760
4820
  for (const summary of overwriteSummaries) hint.push(sanitizeTerminal(`${HINT_INDENT.repeat(2)}${summary}`));
4761
4821
  hint.push(`${HINT_INDENT}\u82E5\u62A5\u9519\u7684\u5143\u7D20\u6765\u81EA\u8986\u5199\uFF08YAML \u8FFD\u52A0\u6216 JS \u811A\u672C\u6CE8\u5165\uFF09\uFF0C\u68C0\u67E5\u5BF9\u5E94\u7684\u8986\u5199\u6587\u4EF6\u4E0E\u811A\u672C\u3002`);
4762
4822
  }
@@ -5683,7 +5743,7 @@ function cmdConfig(args = []) {
5683
5743
  return;
5684
5744
  }
5685
5745
  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"));
5746
+ console.log(colors.gray("# \u914D\u7F6E\u9884\u89C8\uFF1A\u672A\u5199\u76D8\u3001\u672A\u6821\u9A8C\u3001\u672A\u5E94\u7528"));
5687
5747
  if (!reveal && redacted.changed) {
5688
5748
  console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
5689
5749
  }
@@ -5967,7 +6027,7 @@ import fs12 from "fs";
5967
6027
  import path7 from "path";
5968
6028
 
5969
6029
  // src/hot-reload.ts
5970
- import fs9 from "fs";
6030
+ import fs8 from "fs";
5971
6031
 
5972
6032
  // src/proxy-probe.ts
5973
6033
  import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
@@ -6025,47 +6085,12 @@ async function probeProxyConnectivity(port) {
6025
6085
  }
6026
6086
  }
6027
6087
 
6028
- // src/stop-epoch.ts
6029
- import fs8 from "fs";
6030
- function readStopEpoch() {
6031
- try {
6032
- const n = Number.parseInt(fs8.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
6033
- return Number.isSafeInteger(n) && n >= 0 ? n : 0;
6034
- } catch {
6035
- return 0;
6036
- }
6037
- }
6038
- var stopEpochBaselineCaptured = null;
6039
- function captureStopEpochBaseline() {
6040
- stopEpochBaselineCaptured = readStopEpoch();
6041
- return stopEpochBaselineCaptured;
6042
- }
6043
- function stopEpochBaseline() {
6044
- return stopEpochBaselineCaptured ?? readStopEpoch();
6045
- }
6046
- function bumpStopEpoch() {
6047
- try {
6048
- ensureDirs();
6049
- atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
6050
- } catch {
6051
- }
6052
- }
6053
- function recordServiceStopped() {
6054
- bumpStopEpoch();
6055
- }
6056
- function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
6057
- return stopEpochNow !== stopEpochBefore;
6058
- }
6059
- function startAbortedByConcurrentStop() {
6060
- return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
6061
- }
6062
-
6063
6088
  // src/hot-reload.ts
6064
6089
  var HOT_RELOAD_TIMEOUT_MS = 5e3;
6065
6090
  var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
6066
6091
  function logOversized() {
6067
6092
  try {
6068
- return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
6093
+ return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
6069
6094
  } catch {
6070
6095
  return false;
6071
6096
  }
@@ -6102,17 +6127,14 @@ async function tryHotReload(prefetched) {
6102
6127
  return false;
6103
6128
  }
6104
6129
  }
6105
- function concludeHotReload(stopEpochBefore, stopEpochNow) {
6106
- return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
6107
- }
6108
6130
 
6109
6131
  // src/process-stop.ts
6110
6132
  import { spawnSync as spawnSync6 } from "child_process";
6111
- import fs11 from "fs";
6133
+ import fs10 from "fs";
6112
6134
 
6113
6135
  // src/sudo.ts
6114
6136
  import { spawnSync as spawnSync5 } from "child_process";
6115
- import fs10 from "fs";
6137
+ import fs9 from "fs";
6116
6138
  import path6 from "path";
6117
6139
  var SUDO_TIMEOUT_MS = 6e4;
6118
6140
  var SudoAuthError = class extends Error {
@@ -6139,8 +6161,8 @@ function runSudoScript(scriptBody, opts) {
6139
6161
  }
6140
6162
  ensureDirs();
6141
6163
  const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
6142
- fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6143
- fs10.chmodSync(scriptPath, 448);
6164
+ fs9.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6165
+ fs9.chmodSync(scriptPath, 448);
6144
6166
  try {
6145
6167
  const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
6146
6168
  if (result.error) {
@@ -6150,7 +6172,7 @@ function runSudoScript(scriptBody, opts) {
6150
6172
  if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
6151
6173
  } finally {
6152
6174
  try {
6153
- fs10.unlinkSync(scriptPath);
6175
+ fs9.unlinkSync(scriptPath);
6154
6176
  } catch {
6155
6177
  }
6156
6178
  }
@@ -6161,26 +6183,19 @@ var PROCESS_WAIT_ATTEMPTS = 50;
6161
6183
  var PROCESS_WAIT_INTERVAL = 100;
6162
6184
  var BATCH_KILL_THRESHOLD = 3;
6163
6185
  function clearRuntime() {
6164
- if (fs11.existsSync(DIRS.runtime)) {
6186
+ if (fs10.existsSync(DIRS.runtime)) {
6165
6187
  rmrf(DIRS.runtime);
6166
6188
  }
6167
6189
  ensureDirs();
6168
6190
  }
6169
- function describePidCleanupFailure(err) {
6170
- return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
6171
- }
6172
6191
  var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
6173
6192
  function printResidueWarning(remaining) {
6174
6193
  console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
6175
6194
  console.log(MANUAL_PKILL_HINT);
6176
6195
  }
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
6196
  function clearPid() {
6182
6197
  try {
6183
- fs11.unlinkSync(PATHS.pidFile);
6198
+ fs10.unlinkSync(PATHS.pidFile);
6184
6199
  return null;
6185
6200
  } catch (e) {
6186
6201
  if (e.code === "ENOENT") return null;
@@ -6224,7 +6239,7 @@ function buildKernelCleanupScript() {
6224
6239
  async function cleanupAll() {
6225
6240
  const pids = getMihomoPids();
6226
6241
  if (pids.length === 0) {
6227
- return { remaining: [], scriptError: null, pidError: clearPid() };
6242
+ return { remaining: [], incomplete: clearPid() };
6228
6243
  }
6229
6244
  let scriptError = null;
6230
6245
  const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
@@ -6251,23 +6266,18 @@ async function cleanupAll() {
6251
6266
  await waitUntilNoMihomo(pids);
6252
6267
  const remaining = getMihomoPids();
6253
6268
  const pidError = remaining.length === 0 ? clearPid() : null;
6254
- return { remaining, scriptError, pidError };
6269
+ return { remaining, incomplete: scriptError ?? pidError };
6255
6270
  }
6256
6271
  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 });
6272
+ const alive = result.remaining.length > 0;
6273
+ const state = alive ? `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${result.remaining.join(", ")}\uFF09` : "\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF0C\u4F46\u6E05\u7406\u672A\u8D70\u5B8C";
6274
+ const manual = alive ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: rm -f ${PATHS.pidFile}`;
6275
+ const hint = [ctx.mainOutcome, state, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`, manual];
6276
+ if (result.incomplete instanceof SudoAuthError) {
6277
+ const message = `${describeSudoFailure(result.incomplete)}\uFF0C${alive ? "\u6B8B\u7559\u672A\u88AB\u6E05\u7406" : "\u6E05\u7406\u672A\u5B8C\u6210"}`;
6278
+ return new CliError(message, { label: "\u5DF2\u53D6\u6D88", hint });
6265
6279
  }
6266
- return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
6267
- }
6268
- function classifyResidueCleanup(result) {
6269
- if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
6270
- return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
6280
+ return new CliError(result.incomplete?.message ?? "\u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
6271
6281
  }
6272
6282
  function warnResidueCleanup(result, ctx) {
6273
6283
  const err = buildRootResidueCleanupError(result, ctx);
@@ -6276,38 +6286,61 @@ function warnResidueCleanup(result, ctx) {
6276
6286
  }
6277
6287
  async function cleanupKernelsOrThrow(ctx) {
6278
6288
  const result = await cleanupAll();
6279
- const verdict = classifyResidueCleanup(result);
6280
- if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
6281
- if (verdict === "warn") warnResidueCleanup(result, ctx);
6289
+ if (result.incomplete !== null) {
6290
+ if (result.remaining.length > 0) throw buildRootResidueCleanupError(result, ctx);
6291
+ warnResidueCleanup(result, ctx);
6292
+ }
6282
6293
  return result;
6283
6294
  }
6284
6295
  async function stop() {
6285
6296
  const allPids = getMihomoPids();
6286
6297
  if (allPids.length === 0) {
6287
- warnPidCleanupFailed(clearPid());
6298
+ const pidError = clearPid();
6299
+ if (pidError) console.warn(colors.yellow(`\u8B66\u544A: pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${pidError.message}\uFF09\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
6288
6300
  clearRuntime();
6289
6301
  return {};
6290
6302
  }
6291
6303
  const result = await cleanupAll();
6292
- if (result.remaining.length === 0) {
6293
- warnPidCleanupFailed(result.pidError);
6294
- if (result.scriptError) {
6295
- console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo-cli stop`));
6296
- }
6297
- }
6298
- const remaining = result.remaining;
6299
- if (remaining.length > 0) {
6300
- console.log("");
6301
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
6302
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
6303
- console.log(MANUAL_PKILL_HINT);
6304
- console.log("");
6305
- return { remaining };
6304
+ if (result.remaining.length === 0 && result.incomplete !== null) {
6305
+ warnResidueCleanup(result, { mainOutcome: "\u5185\u6838\u5DF2\u505C\u6B62", retryCommand: "mihomo-cli stop" });
6306
6306
  }
6307
+ if (result.remaining.length > 0) return { remaining: result.remaining };
6307
6308
  clearRuntime();
6308
6309
  return {};
6309
6310
  }
6310
6311
 
6312
+ // src/stop-epoch.ts
6313
+ import fs11 from "fs";
6314
+ function readStopEpoch() {
6315
+ try {
6316
+ const n = Number.parseInt(fs11.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
6317
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
6318
+ } catch {
6319
+ return 0;
6320
+ }
6321
+ }
6322
+ var stopEpochBaselineCaptured = null;
6323
+ function captureStopEpochBaseline() {
6324
+ stopEpochBaselineCaptured = readStopEpoch();
6325
+ return stopEpochBaselineCaptured;
6326
+ }
6327
+ function stopEpochBaseline() {
6328
+ return stopEpochBaselineCaptured ?? readStopEpoch();
6329
+ }
6330
+ function bumpStopEpoch() {
6331
+ try {
6332
+ ensureDirs();
6333
+ atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
6334
+ } catch {
6335
+ }
6336
+ }
6337
+ function epochChanged(before, now) {
6338
+ return now !== before;
6339
+ }
6340
+ function startAbortedByConcurrentStop() {
6341
+ return epochChanged(stopEpochBaseline(), readStopEpoch());
6342
+ }
6343
+
6311
6344
  // src/service.ts
6312
6345
  var SERVICE_HEALTH_INTERVAL_MS = 100;
6313
6346
  var SERVICE_OBSERVE_MS = 1200;
@@ -6553,7 +6586,7 @@ async function restartService(prefetched) {
6553
6586
  }
6554
6587
  const oversized = logOversized();
6555
6588
  if (!oversized && await tryHotReload(prefetched)) {
6556
- return concludeHotReload(stopEpochBaseline(), readStopEpoch());
6589
+ return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
6557
6590
  }
6558
6591
  if (oversized) {
6559
6592
  const archiveFile = allocateArchivePath();
@@ -6857,31 +6890,33 @@ function detectSystemProxy(mixedPort) {
6857
6890
  if (r.error || r.status !== 0 || typeof r.stdout !== "string" || !r.stdout.includes("<dictionary>")) return null;
6858
6891
  return summarizeSystemProxy(parseScutilProxy(r.stdout), mixedPort);
6859
6892
  }
6860
- function printSystemProxyHint(mixedPort) {
6861
- const summary = detectSystemProxy(mixedPort);
6893
+ function buildSystemProxyHint(summary, mixedPort) {
6894
+ const applicationGuide = `\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`;
6862
6895
  if (summary === null) {
6863
- console.log(colors.gray(`\u63D0\u793A: Mixed \u6A21\u5F0F\u9700\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u914D\u7F6E HTTP/SOCKS \u4EE3\u7406 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
6864
- return;
6896
+ return { text: `\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B${applicationGuide}`, warning: false };
6865
6897
  }
6866
6898
  if (summary.pac) {
6867
6899
  const desc = summary.pac.wpad ? "WPAD \u81EA\u52A8\u53D1\u73B0" : `PAC \u6587\u4EF6${summary.pac.source ? `\uFF08${summary.pac.source}\uFF09` : ""}`;
6868
- console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u662F\u5426\u8D70 mihomo-cli \u7531\u811A\u672C\u51B3\u5B9A\uFF1B\u5982\u9700\u56FA\u5B9A\u5168\u91CF\u8D70\u4EE3\u7406\uFF0C\u53EF\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u6539\u7528\u624B\u52A8\u4EE3\u7406 127.0.0.1:${mixedPort}`));
6869
- return;
6900
+ return { text: `\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`, warning: false };
6870
6901
  }
6871
6902
  if (summary.matched) {
6872
6903
  if (summary.diverged.length > 0) {
6873
- console.log(colors.yellow(`\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\u2014\u2014\u5BF9\u5E94\u6D41\u91CF\u53EF\u80FD\u4E0D\u7ECF mihomo-cli`));
6874
- } else {
6875
- console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}`));
6904
+ return {
6905
+ text: `\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\uFF1B\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u8FD9\u4E9B\u8BBE\u7F6E\uFF0C\u5177\u4F53\u5E94\u7528\u4EE5\u81EA\u8EAB\u4EE3\u7406\u914D\u7F6E\u4E3A\u51C6`,
6906
+ warning: true
6907
+ };
6876
6908
  }
6877
- return;
6909
+ return { text: `\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF08\u53EA\u8BFB\u68C0\u6D4B\uFF09\uFF1B\u5177\u4F53\u5E94\u7528\u4ECD\u4EE5\u81EA\u8EAB\u4EE3\u7406\u914D\u7F6E\u4E3A\u51C6`, warning: false };
6878
6910
  }
6879
6911
  const pointing = summary.active.length > 0 ? `\uFF0C\u5F53\u524D\u6307\u5411 ${summary.active.join("\u3001")}` : "";
6880
- console.log(colors.yellow(`\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF1B\u9700\u8981\u4EE3\u7406\u7684\u5E94\u7528\u8BF7\u914D\u7F6E\u540E\u4F7F\u7528\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
6881
- console.log(colors.gray(" \u8BBE\u7F6E\u547D\u4EE4\uFF08\u628A Wi-Fi \u6362\u6210\u5B9E\u9645\u7F51\u7EDC\u670D\u52A1\uFF0C\u5168\u90E8\u670D\u52A1\u89C1 networksetup -listallnetworkservices\uFF09:"));
6882
- console.log(colors.gray(` networksetup -setwebproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6883
- console.log(colors.gray(` networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6884
- console.log(colors.gray(` networksetup -setsocksfirewallproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6912
+ return {
6913
+ text: `\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`,
6914
+ warning: true
6915
+ };
6916
+ }
6917
+ function printSystemProxyHint(mixedPort) {
6918
+ const hint = buildSystemProxyHint(detectSystemProxy(mixedPort), mixedPort);
6919
+ console.log(hint.warning ? colors.yellow(hint.text) : colors.gray(hint.text));
6885
6920
  }
6886
6921
 
6887
6922
  // src/commands/status.ts
@@ -6932,11 +6967,10 @@ function buildStatusJson(args) {
6932
6967
  } : null,
6933
6968
  overwrite: {
6934
6969
  enabled: args.overwriteEnabled,
6935
- files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
6936
- // 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
6937
- // 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
6970
+ // 全局关闭时 buildConfig 不加载任何覆写,applied 必须为空;只滤文件 enabled/match
6971
+ // 会与同一份 JSON 里的 overwrite.enabled:false 自相矛盾
6938
6972
  applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
6939
- // 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors。
6973
+ // 加载失败的文件不属于 applied(既没合并也无法判 enabled/match),单列 errors。
6940
6974
  // hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
6941
6975
  // 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
6942
6976
  errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message, hint: b.hint }))
@@ -6963,23 +6997,8 @@ async function printStatus(args = []) {
6963
6997
  const {
6964
6998
  enabled: overwriteEnabled,
6965
6999
  files: overwriteFiles,
6966
- entries: overwriteEntries,
6967
7000
  broken: overwriteBroken
6968
7001
  } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
6969
- if (activeSub && overwriteEnabled && overwriteFiles.some((f) => f.kind === "script")) {
6970
- try {
6971
- const rawContent = readSubscriptionRawConfig(activeSub.name);
6972
- if (rawContent) {
6973
- const { matches } = judgeScriptMatches(rawContent, deriveRuntimeMode(info), { subName: activeSub.name, subUrl: activeSub.url }, overwriteEntries);
6974
- const matchedByName = new Map(matches.map((m) => [m.file, m.matched]));
6975
- for (const f of overwriteFiles) {
6976
- if (f.kind === "script" && matchedByName.has(f.name)) f.matched = matchedByName.get(f.name);
6977
- }
6978
- }
6979
- } catch (e) {
6980
- if (!(e instanceof CliError)) throw e;
6981
- }
6982
- }
6983
7002
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6984
7003
  const controllerPort = getPortsOrNull()?.controller ?? null;
6985
7004
  const { running, pid, kind } = state;
@@ -7000,8 +7019,6 @@ async function printStatus(args = []) {
7000
7019
  activeSub,
7001
7020
  cached,
7002
7021
  overwriteEnabled,
7003
- // 两个数组在 buildStatusJson 里分出来:files 仍是旧契约(只滤文件级 enabled,
7004
- // 不按 match、不随全局开关变空),applied 才是本次真正参与合并的
7005
7022
  overwriteFiles,
7006
7023
  overwriteBroken,
7007
7024
  service
@@ -7104,7 +7121,7 @@ function printOverwriteLines(enabled, files, broken) {
7104
7121
  if (active.length > 0) {
7105
7122
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${active.map((f) => shortOverwriteName(f.name)).join(", ")}${suffix})`);
7106
7123
  } else {
7107
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
7124
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u9009\u4E2D\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
7108
7125
  }
7109
7126
  for (const b of broken) {
7110
7127
  console.log(colors.red(` ${b.message}`));
@@ -7157,7 +7174,7 @@ async function cmdStart(args) {
7157
7174
  console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D"));
7158
7175
  console.log("");
7159
7176
  } else {
7160
- recordServiceStopped();
7177
+ bumpStopEpoch();
7161
7178
  }
7162
7179
  captureStopEpochBaseline();
7163
7180
  } else if (!serviceBefore.installed) {
@@ -7338,7 +7355,6 @@ var GITHUB_REPO = "MetaCubeX/mihomo";
7338
7355
  var KERNEL_HTTP_TIMEOUT = 12e4;
7339
7356
  var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
7340
7357
  var GH_DOWNLOAD_TIMEOUT = 1e5;
7341
- var HTTP_CLIENT2 = createHttpClient({ timeout: KERNEL_HTTP_TIMEOUT });
7342
7358
  var execFileAsync2 = promisify3(execFile3);
7343
7359
  function withMirror(url, mirror) {
7344
7360
  if (mirror && url.startsWith("https://github.com/")) {
@@ -7419,8 +7435,7 @@ function pickLatestRelease(releases) {
7419
7435
  function buildReleaseApiCurlArgs(proxy, url) {
7420
7436
  return [
7421
7437
  "-s",
7422
- "-x",
7423
- proxy,
7438
+ ...proxy ? ["-x", proxy] : ["--noproxy", "*"],
7424
7439
  "--proto",
7425
7440
  "=https",
7426
7441
  "--proto-redir",
@@ -7475,7 +7490,6 @@ async function getLatestReleaseViaGh(repo, signal) {
7475
7490
  return pickLatestRelease(JSON.parse(result.stdout));
7476
7491
  }
7477
7492
  async function getLatestRelease(repo, opts) {
7478
- const url = `https://api.github.com/repos/${repo}/releases`;
7479
7493
  if (opts.useGh) {
7480
7494
  try {
7481
7495
  return await getLatestReleaseViaGh(repo, opts.signal);
@@ -7484,35 +7498,33 @@ async function getLatestRelease(repo, opts) {
7484
7498
  opts.onGhFallback?.();
7485
7499
  }
7486
7500
  }
7487
- if (opts.proxy) {
7488
- let stdout;
7489
- try {
7490
- const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(opts.proxy, url), {
7491
- encoding: "utf8",
7492
- maxBuffer: 50 * 1024 * 1024,
7493
- timeout: KERNEL_HTTP_TIMEOUT + 1e4,
7494
- signal: opts.signal,
7495
- // no_proxy 例外表会绕过显式 -x——统一出口置空,保 -x 权威(curl-spawn.ts)
7496
- env: buildCurlSpawnEnv()
7497
- });
7498
- stdout = result.stdout;
7499
- } catch (e) {
7500
- throw translateReleaseApiCurlError(e);
7501
- }
7502
- const { body, statusCode } = parseCurlStatusOutput(stdout);
7503
- if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
7504
- throw createHttpError(statusCode, body);
7505
- }
7506
- let releases;
7507
- try {
7508
- releases = JSON.parse(body);
7509
- } catch {
7510
- throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
7511
- }
7512
- return pickLatestRelease(releases);
7501
+ const url = `https://api.github.com/repos/${repo}/releases`;
7502
+ let stdout;
7503
+ try {
7504
+ const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(opts.proxy, url), {
7505
+ encoding: "utf8",
7506
+ maxBuffer: 50 * 1024 * 1024,
7507
+ timeout: KERNEL_HTTP_TIMEOUT + 1e4,
7508
+ signal: opts.signal,
7509
+ // no_proxy 例外表会绕过显式 -x——统一出口置空,保 -x 权威(curl-spawn.ts)
7510
+ env: buildCurlSpawnEnv()
7511
+ });
7512
+ stdout = result.stdout;
7513
+ } catch (e) {
7514
+ if (opts.signal?.aborted) throw e;
7515
+ throw translateReleaseApiCurlError(e);
7513
7516
  }
7514
- const response = await HTTP_CLIENT2.get(url, { responseType: "json", signal: opts.signal });
7515
- return pickLatestRelease(response.data);
7517
+ const { body, statusCode } = parseCurlStatusOutput(stdout);
7518
+ if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
7519
+ throw createHttpError(statusCode, body);
7520
+ }
7521
+ let releases;
7522
+ try {
7523
+ releases = JSON.parse(body);
7524
+ } catch {
7525
+ throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
7526
+ }
7527
+ return pickLatestRelease(releases);
7516
7528
  }
7517
7529
  async function checkUpdate(opts) {
7518
7530
  const currentVersion = opts.currentVersion !== void 0 ? opts.currentVersion : getKernelVersion();
@@ -8187,6 +8199,9 @@ function parseProxyArg(args) {
8187
8199
  }
8188
8200
 
8189
8201
  // src/commands/kernel.ts
8202
+ function kernelRestartCommand(state) {
8203
+ return `mihomo-cli stop && ${startCommandForCurrentMode(state)}`;
8204
+ }
8190
8205
  function channelLabel(channel, isExplicitProxy) {
8191
8206
  switch (channel.kind) {
8192
8207
  case "gh":
@@ -8293,30 +8308,16 @@ async function cmdKernel(args) {
8293
8308
  if (useGh) {
8294
8309
  hint.push("", "\u672C\u6B21\u5DF2\u5148\u5C1D\u8BD5 gh \u8BA4\u8BC1\u901A\u9053\u3001\u5931\u8D25\u540E\u624D\u56DE\u9000\u76F4\u8FDE\uFF0C\u53EF\u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8295
8310
  }
8296
- } else if (!mirrorInfo.mirror) {
8297
- if (apiProxy) {
8298
- hint.push("", "\u63D0\u793A: \u7ECF\u4EE3\u7406\u67E5\u8BE2 GitHub \u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u662F\u5426\u53EF\u7528\uFF0C\u6216 mihomo-cli kernel --mirror direct \u91CD\u8BD5\u76F4\u8FDE");
8299
- } else {
8300
- hint.push(
8301
- "",
8302
- "\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF\u6216\u4EE3\u7406:",
8303
- " mihomo-cli kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u88F8 --mirror \u56FA\u5B9A\u88F8\u57DF\uFF0C\u53EF\u7528 v6/v4/cdn \u7B49\u522B\u540D\uFF09",
8304
- ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`,
8305
- " mihomo-cli kernel --proxy <\u7AEF\u53E3> # \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u51FA\u7F51"
8306
- );
8307
- }
8308
8311
  } else if (apiProxy) {
8309
8312
  hint.push("", "\u63D0\u793A: \u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09\u7ECF\u4EE3\u7406\u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u662F\u5426\u53EF\u7528\uFF1B\u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4E0B\u8F7D\uFF0C\u4E0E\u67E5\u8BE2\u65E0\u5173");
8310
- } else if (useGh) {
8311
- hint.push("", "\u63D0\u793A: gh \u8BA4\u8BC1\u901A\u9053\u4E0E\u76F4\u8FDE\u90FD\u5931\u8D25\u4E86\uFF0C\u53EF\u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8312
8313
  } else {
8313
- hint.push(
8314
- "",
8315
- "\u63D0\u793A: \u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4E0B\u8F7D\uFF0C\u7248\u672C\u67E5\u8BE2\u4ECD\u9700\u76F4\u8FDE GitHub API\uFF08\u5F53\u524D\u4E0D\u901A\uFF09\u3002\u51FA\u8DEF:",
8316
- " \u5B89\u88C5\u5E76\u767B\u5F55 GitHub CLI\uFF08\u8BA4\u8BC1\u914D\u989D 5000 \u6B21/\u65F6\uFF09:",
8317
- " brew install gh && gh auth login",
8318
- " \u6216\u7ECF\u672C\u673A\u4EE3\u7406\u5DE5\u5177\u67E5\u8BE2: mihomo-cli kernel --proxy <\u7AEF\u53E3>"
8319
- );
8314
+ hint.push("", `\u63D0\u793A: \u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09${useGh ? "gh \u8BA4\u8BC1\u901A\u9053\u4E0E\u76F4\u8FDE\u90FD" : "\u76F4\u8FDE"}\u5931\u8D25\u3002\u51FA\u8DEF:`);
8315
+ if (useGh) hint.push(" \u68C0\u67E5 gh \u767B\u5F55\u72B6\u6001: gh auth status");
8316
+ else hint.push(" \u5B89\u88C5\u5E76\u767B\u5F55 GitHub CLI\uFF08\u8BA4\u8BC1\u914D\u989D 5000 \u6B21/\u65F6\uFF09: brew install gh && gh auth login");
8317
+ hint.push(" \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u67E5\u8BE2: mihomo-cli kernel --proxy <\u7AEF\u53E3>");
8318
+ if (!mirrorInfo.mirror) {
8319
+ hint.push(` \u4E0B\u8F7D\u8FC7\u6162\u53EF\u52A0\u955C\u50CF: mihomo-cli kernel --mirror [\u955C\u50CF]\uFF08\u53EF\u7528: ${AVAILABLE_MIRRORS.join(", ")}\uFF1B\u955C\u50CF\u4E0D\u4F5C\u7528\u4E8E\u7248\u672C\u67E5\u8BE2\uFF09`);
8320
+ }
8320
8321
  }
8321
8322
  throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
8322
8323
  }
@@ -8351,8 +8352,7 @@ async function cmdKernel(args) {
8351
8352
  \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
8352
8353
  const state = getRunningState();
8353
8354
  if (state.running) {
8354
- const restartCommand = startCommandForCurrentMode(state);
8355
- console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${restartCommand} \u91CD\u542F\u540E\u751F\u6548`));
8355
+ console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${kernelRestartCommand(state)} \u540E\u751F\u6548`));
8356
8356
  }
8357
8357
  console.log(colors.gray("\u63D0\u793A: \u82E5\u4F7F\u7528\u5C40\u57DF\u7F51\u8282\u70B9\uFF08192.168/10.x/*.local\uFF09\uFF0C\u9996\u6B21\u542F\u52A8\u53EF\u80FD\u91CD\u65B0\u5F39\u51FA\u300C\u672C\u5730\u7F51\u7EDC\u300D\u6388\u6743"));
8358
8358
  }
@@ -8464,7 +8464,7 @@ function printOverwriteList() {
8464
8464
  console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
8465
8465
  }
8466
8466
  if (f.kind === "script") {
8467
- console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF1B\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605\u65F6\u672B\u5C3E return true\uFF0Cstatus \u636E\u6B64\u533A\u5206\u751F\u6548\u4E0E\u4E0D\u9002\u7528\uFF09`);
8467
+ console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF1B\u4F5C\u7528\u57DF\u7531\u811A\u672C\u81EA\u884C\u5224\u65AD\uFF09`);
8468
8468
  } else if (f.keys.length > 0) {
8469
8469
  console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
8470
8470
  }
@@ -8619,10 +8619,10 @@ async function cmdReset(args) {
8619
8619
  hint: [MANUAL_PKILL_HINT]
8620
8620
  });
8621
8621
  }
8622
- if (!serviceActive && (cleanup.scriptError !== null || cleanup.pidError !== null)) {
8622
+ if (!serviceActive && cleanup.incomplete !== null) {
8623
8623
  warnResidueCleanup(cleanup, { mainOutcome: "\u91CD\u7F6E\u7EE7\u7EED\u6267\u884C", retryCommand: "mihomo-cli stop" });
8624
8624
  }
8625
- recordServiceStopped();
8625
+ bumpStopEpoch();
8626
8626
  }
8627
8627
  if (!needsStop && serviceTargeted && cleanup !== null && cleanup.remaining.length > 0) {
8628
8628
  printResidueWarning(cleanup.remaining);
@@ -8739,7 +8739,7 @@ async function cmdUninstall(args) {
8739
8739
  }
8740
8740
  console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo-cli install"));
8741
8741
  console.log(colors.gray("\u5F7B\u5E95\u79FB\u9664 mihomo-cli:"));
8742
- console.log(colors.gray(" mihomo-cli reset --full # \u5220\u9664\u5168\u90E8\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
8742
+ console.log(colors.gray(" mihomo-cli reset --full # \u5220\u9664\u53D7\u7BA1\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
8743
8743
  console.log(colors.gray(" npm uninstall -g mihomo-cli"));
8744
8744
  console.log("");
8745
8745
  }
@@ -8757,14 +8757,14 @@ async function cmdStop(args) {
8757
8757
  const pids = getMihomoPids();
8758
8758
  const needsServiceWork = status.loaded || status.installed && !status.disabled;
8759
8759
  if (!needsServiceWork && pids.length === 0) {
8760
- recordServiceStopped();
8760
+ bumpStopEpoch();
8761
8761
  console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
8762
8762
  return;
8763
8763
  }
8764
8764
  if (!needsServiceWork) {
8765
8765
  console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
8766
8766
  handleStopResult(await stop());
8767
- recordServiceStopped();
8767
+ bumpStopEpoch();
8768
8768
  console.log(colors.green("\u5DF2\u505C\u6B62"));
8769
8769
  return;
8770
8770
  }
@@ -9154,7 +9154,7 @@ var COMMANDS = [
9154
9154
  aliases: [],
9155
9155
  handler: cmdConfig,
9156
9156
  group: "config",
9157
- usage: [{ signature: "config [-j|--json] [--reveal]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9157
+ usage: [{ signature: "config [-j|--json] [--reveal]", description: "\u9884\u89C8\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u7F13\u5B58\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9158
9158
  },
9159
9159
  {
9160
9160
  name: "overwrite",
@@ -9182,7 +9182,7 @@ var COMMANDS = [
9182
9182
  aliases: [],
9183
9183
  handler: cmdKernel,
9184
9184
  group: "system",
9185
- usage: [{ signature: "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1A\u672C\u673A\u4EE3\u7406 > gh > \u76F4\u8FDE\uFF09" }]
9185
+ usage: [{ signature: "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u6309\u73AF\u5883\u9009\u62E9\u672C\u673A\u4EE3\u7406\u3001gh \u6216\u76F4\u8FDE\uFF09" }]
9186
9186
  },
9187
9187
  {
9188
9188
  name: "update",
@@ -9196,7 +9196,9 @@ var COMMANDS = [
9196
9196
  aliases: [],
9197
9197
  handler: cmdReset,
9198
9198
  group: "system",
9199
- usage: [{ signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199/\u670D\u52A1\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }]
9199
+ usage: [
9200
+ { signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199/\u670D\u52A1\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\u53D7\u7BA1\u76EE\u6807\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }
9201
+ ]
9200
9202
  },
9201
9203
  {
9202
9204
  name: "doctor",
@@ -9304,11 +9306,11 @@ function assertNotRoot(commandName) {
9304
9306
  });
9305
9307
  }
9306
9308
  function assertSupportedNodeVersion(commandName) {
9307
- if (!MIN_NODE_VERSION) return;
9309
+ if (!NODE_ENGINES) return;
9308
9310
  if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
9309
9311
  const current = process.versions.node;
9310
- if (compareVersions(current, MIN_NODE_VERSION) >= 0) return;
9311
- throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 >= ${MIN_NODE_VERSION}\uFF09`, {
9312
+ if (satisfies(current, NODE_ENGINES)) return;
9313
+ throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 ${NODE_ENGINES}\uFF09`, {
9312
9314
  label: "Node \u7248\u672C\u4E0D\u652F\u6301",
9313
9315
  hint: ["\u5347\u7EA7 Node \u540E\u91CD\u8BD5\uFF0C\u4F8B\u5982:", " brew upgrade node", " \u6216\u7528 nvm: nvm install --lts && nvm use --lts", "", `\u5F53\u524D\u89E3\u91CA\u5668: ${process.execPath}`]
9314
9316
  });
@@ -9378,5 +9380,5 @@ main().catch((e) => {
9378
9380
  /*! Bundled license information:
9379
9381
 
9380
9382
  js-yaml/dist/js-yaml.mjs:
9381
- (*! js-yaml 5.3.0 https://github.com/nodeca/js-yaml @license MIT *)
9383
+ (*! js-yaml 5.4.3 https://github.com/nodeca/js-yaml @license MIT *)
9382
9384
  */