feat: 优化 YAML 相关解析效率

This commit is contained in:
xream committed 2026-11-21 15:23:30 +08:00
1 parent db485ba1a6
commit 48c4a95b76
5 files changed
+107 -53

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.44.20",
"version": "2.44.21",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"packageManager": "pnpm@11.0.9",
+3 -2
View File
@@ -52,9 +52,10 @@ const ageUtils = {
function preprocess(raw) {
for (const processor of PROXY_PREPROCESSORS) {
try {
if (processor.test(raw)) {
const match = processor.test(raw);
if (match) {
$.info(`Pre-processor [${processor.name}] activated`);
return processor.parse(raw);
return processor.parse(raw, false, match);
}
} catch (e) {
$.error(`Parser [${processor.name}] failed\n Reason: ${e}`);
@@ -3,29 +3,24 @@ import { Base64 } from 'js-base64';
import { isAlias, isScalar, isSeq, parseDocument, visit } from 'yaml';
import $ from '@/core/app';
const CLASH_YAML_PARSE_OPTIONS = { merge: true, logLevel: 'error' };
function mayContainShortIds(raw) {
return typeof raw === 'string' && raw.includes('short-id');
}
export function normalizeClashYaml(raw) {
if (typeof raw !== 'string' || !raw.includes('short-id')) {
return raw;
}
if (!mayContainShortIds(raw)) return raw;
let document;
try {
document = parseDocument(raw, {
merge: true,
logLevel: 'error',
});
// legacy !<str> 可由 safeLoad 恢复;AST 仅用于定位原文。
const content =
document.errors.length > 0 ? safeLoad(raw) : document.toJS();
if (
![content.proxies, content.listeners].some(
(items) => Array.isArray(items) && items.length > 0,
)
)
return raw;
const document = parseDocument(raw, CLASH_YAML_PARSE_OPTIONS);
return normalizeClashYamlDocument(raw, document);
} catch (e) {
return raw;
}
}
function normalizeClashYamlDocument(raw, document, content) {
const anchors = new Map();
const aliases = new Map();
visit(document, {
@@ -54,26 +49,21 @@ export function normalizeClashYaml(raw) {
}
},
});
const shortIds = new Set();
// alias 和 merge 引用的节点也属于 REALITY 上下文。
for (const config of realityConfigs) {
visit(config, {
Alias(_, alias) {
realityConfigs.add(resolveAlias(alias));
},
Pair(_, { key, value }) {
if (resolveAlias(key)?.value === 'short-id') {
shortIds.add(value);
}
},
});
}
const shortIds = new Set();
visit(document, {
Pair(_, { key, value }, path) {
if (
resolveAlias(key)?.value === 'short-id' &&
path.some((node) => realityConfigs.has(node))
) {
shortIds.add(value);
}
},
});
const replacements = new Map();
// shortcut: 直接修改 anchor;跨字段共享时若需保留原类型,再隔离引用。
for (const value of shortIds) {
@@ -84,6 +74,18 @@ export function normalizeClashYaml(raw) {
replacements.set(node, JSON.stringify(node.source));
}
}
if (replacements.size === 0) return raw;
// 需要改写时才校验全文,保留旧式 !<str> 的恢复行为。
if (content === undefined) {
content = document.errors.length > 0 ? safeLoad(raw) : document.toJS();
}
if (
![content?.proxies, content?.listeners].some(
(items) => Array.isArray(items) && items.length > 0,
)
)
return raw;
const chunks = [];
let offset = 0;
@@ -167,20 +169,44 @@ function fallbackBase64Encoded() {
function Clash() {
const name = 'Clash Pre-processor';
const test = function (raw) {
if (!/proxies/.test(raw)) return false;
const content = safeLoad(raw);
return (
Array.isArray(content.proxies) ||
Array.isArray(content['proxy-groups'])
);
const prepare = function (raw, detect) {
if (detect && !/proxies/.test(raw)) return false;
let document;
let content;
if (mayContainShortIds(raw)) {
try {
document = parseDocument(raw, CLASH_YAML_PARSE_OPTIONS);
if (document.errors.length === 0) content = document.toJS();
} catch (e) {
document = undefined;
}
}
if (content === undefined) content = safeLoad(raw);
if (
detect &&
!Array.isArray(content.proxies) &&
!Array.isArray(content['proxy-groups'])
)
return false;
if (document) {
const normalized = normalizeClashYamlDocument(
raw,
document,
content,
);
if (normalized !== raw) return { normalized };
}
return { content };
};
const parse = function (raw, includeProxies) {
// Clash YAML format
const afterReplace = normalizeClashYaml(raw);
const { proxies } = safeLoad(afterReplace);
const test = (raw) => prepare(raw, true);
const parse = function (raw, includeProxies, match = prepare(raw)) {
const { proxies } =
match.normalized === undefined
? match.content
: safeLoad(match.normalized);
return (
(includeProxies ? 'proxies:\n' : '') +
(Array.isArray(proxies) ? proxies : [])
@@ -1,7 +1,7 @@
import { expect } from 'chai';
import { Base64 } from 'js-base64';
import { describe, it } from 'mocha';
import { Alias } from 'yaml';
import { Alias, Document } from 'yaml';
import PREPROCESSORS, {
normalizeClashYaml,
@@ -376,9 +376,12 @@ proxies: [{reality-opts: *opts}]
it('keeps non-clash or invalid yaml input untouched', function () {
const invalid = 'proxies:\n - name: broken\n short-id: [';
const unresolved =
'proxies: [{reality-opts: {short-id: 0088}, other: *missing}]';
const unrelated = 'ss://YWVzLTEyOC1nY206c2VjcmV0@example.com:8388';
expect(normalizeClashYaml(invalid)).to.equal(invalid);
expect(normalizeClashYaml(unresolved)).to.equal(unresolved);
expect(normalizeClashYaml(unrelated)).to.equal(unrelated);
});
});
@@ -441,6 +444,28 @@ proxies: [{reality-opts: *opts}]
});
describe('Clash preprocessor', function () {
it('reuses the parsed YAML when REALITY short-ids are already strings', function () {
const processor = getPreprocessor('Clash Pre-processor');
const input = 'proxies: [{reality-opts: {short-id: "0088"}}]';
const toJS = Document.prototype.toJS;
let conversions = 0;
Document.prototype.toJS = function (...args) {
conversions++;
return toJS.apply(this, args);
};
try {
const match = processor.test(input);
const proxy = JSON.parse(processor.parse(input, false, match));
expect(proxy['reality-opts']['short-id']).to.equal('0088');
expect(conversions).to.equal(1);
expect(normalizeClashYaml(input)).to.equal(input);
expect(conversions).to.equal(1);
} finally {
Document.prototype.toJS = toJS;
}
});
it('preserves short-ids when REALITY field names are aliases', function () {
const processor = getPreprocessor('Clash Pre-processor');
const input = `proxies:
@@ -524,7 +549,7 @@ proxies:
short-id: 0088
`;
expect(processor.test(raw)).to.equal(true);
expect(processor.test(raw)).to.be.ok;
expect(normalizeClashYaml(raw)).to.equal(
raw.replace('short-id: 0088', 'short-id: "0088"'),
);
@@ -546,7 +571,7 @@ proxy-groups:
- DIRECT
`;
expect(processor.test(raw)).to.equal(true);
expect(processor.test(raw)).to.be.ok;
expect(processor.parse(raw)).to.equal('');
expect(processor.parse(raw, true)).to.equal('proxies:\n');
});
@@ -558,7 +583,7 @@ proxy-groups:
- test
`;
expect(processor.test(raw)).to.equal(true);
expect(processor.test(raw)).to.be.ok;
expect(processor.parse(raw)).to.equal('');
expect(
processor.test('proxies: invalid\nproxy-groups: {}'),
@@ -586,10 +611,11 @@ proxy-groups:
short-id: 08
`;
expect(processor.test(raw)).to.equal(true);
const match = processor.test(raw);
expect(match).to.be.ok;
const output = processor.parse(raw);
const wrapped = processor.parse(raw, true);
const output = processor.parse(raw, false, match);
const wrapped = processor.parse(raw, true, match);
expect(output).to.include('"name":"Clash SS"');
expect(output).to.include('"name":"Clash VLESS"');
+3 -2
View File
@@ -78,8 +78,9 @@ async function finalizeDownloadedBody(body, { ageSecretKey, preprocess, url }) {
if (preprocess) {
try {
if (clashPreprocessor.test(result)) {
result = clashPreprocessor.parse(result, true);
const match = clashPreprocessor.test(result);
if (match) {
result = clashPreprocessor.parse(result, true, match);
}
} catch (e) {
$.error(`Clash Pre-processor error: ${e}`);