import { parse as parseYAML, stringify as serializeYAML } from 'yaml'; addEventListener('fetch', event => { const { request } = event; // 检查 User-Agent 是否为空 const userAgent = request.headers.get('User-Agent'); if (!userAgent) { event.respondWith( new Response('User-Agent is required', { status: 400 }) ); return; } event.respondWith(handleRequest(request)); }); async function handleRequest(request) { // 获取原始 YAML 和修改器 YAML 的 URL const url = new URL(request.url); const originalYamlUrl = url.searchParams.get('originalYaml'); const modifierYamlUrl = url.searchParams.get('modifierYaml'); // 获取原始 YAML 和修改器 YAML 的文本 const [originalYamlText, modifierYamlText] = await Promise.all([ fetch(originalYamlUrl).then(res => res.text()), fetch(modifierYamlUrl).then(res => res.text()) ]); // 解析 YAML const originalYaml = parseYAML(originalYamlText); const modifierYaml = parseYAML(modifierYamlText); // 应用修改 applyModifications(originalYaml, modifierYaml); // 序列化修改后的 YAML const modifiedYamlText = serializeYAML(originalYaml); // 返回修改后的 YAML return new Response(modifiedYamlText, { headers: { 'Content-Type': 'text/plain' } }); } function applyModifications(originalYaml, modifierYaml) { const keys = [ "append-rules", "prepend-rules", "append-proxies", "prepend-proxies", "append-proxy-groups", "prepend-proxy-groups", "mix-proxy-providers", "mix-rule-providers", "mix-object", "commands", ]; keys.forEach((key) => { if (modifierYaml.hasOwnProperty(key)) { switch (key) { case "append-rules": case "append-proxies": case "append-proxy-groups": originalYaml[key.replace("append-", "")].push(...modifierYaml[key]); break; case "prepend-rules": case "prepend-proxies": case "prepend-proxy-groups": originalYaml[key.replace("prepend-", "")].unshift(...modifierYaml[key]); break; case "mix-proxy-providers": case "mix-rule-providers": case "mix-object": Object.assign(originalYaml[key.replace("mix-", "")], modifierYaml[key]); break; case "commands": applyCommands(originalYaml, modifierYaml[key]); break; } } }); } function applyCommands(originalYaml, commands) { for (let i = 0; i < commands.length; i++) { const parts = commands[i].split('.') let target = originalYaml for (let j = 0; j < parts.length - 1; j++) { const part = parts[j] if (part.match(/^\d+$/)) { target = target[parseInt(part)] } else { target = target[part] } } const lastPart = parts[parts.length - 1] const cmdParts = lastPart.split(/([=+-])/) const cmd = cmdParts[1] const value = cmdParts[2] switch (cmd) { case '=': target[cmdParts[0]] = parseValue(value) break case '+': target[cmdParts[0]].push(parseValue(value)) break case '-': target.splice(cmdParts[0], 1) break } } }