diff --git a/backend/package.json b/backend/package.json index bfcdf1db..759f6ebe 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.42.3", + "version": "2.42.4", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "packageManager": "pnpm@11.0.9", diff --git a/backend/src/restful/sync.js b/backend/src/restful/sync.js index d08fc57b..cf5f3b24 100644 --- a/backend/src/restful/sync.js +++ b/backend/src/restful/sync.js @@ -288,6 +288,7 @@ async function produceArtifact({ noCache, noFlow, all, + includeRaw, }) { platform = platform || 'JSON'; @@ -307,10 +308,10 @@ async function produceArtifact({ sub.ignoreFailedRemoteSub, ); const skipFlow = noFlow || sub.noFlow; + let sourceRaw = []; try { let raw; - let sourceRaw; if ( content && !['localFirst', 'remoteFirst'].includes(mergeSources) @@ -443,7 +444,15 @@ async function produceArtifact({ } } if (produceType === 'raw') { - return JSON.stringify((Array.isArray(raw) ? raw : [raw]).flat()); + const result = JSON.stringify( + (Array.isArray(raw) ? raw : [raw]).flat(), + ); + return includeRaw + ? { + result, + raw: Array.isArray(sourceRaw) ? sourceRaw : [sourceRaw], + } + : result; } // parse proxies let proxies = (Array.isArray(raw) ? raw : [raw]) @@ -485,12 +494,18 @@ async function produceArtifact({ exist[proxy.name] = true; } // produce - return ProxyUtils.produce( + const result = ProxyUtils.produce( proxies, platform, produceType, produceOpts, ); + return includeRaw + ? { + result, + raw: Array.isArray(sourceRaw) ? sourceRaw : [sourceRaw], + } + : result; } catch (err) { if (!shouldFallbackIgnoreFailedRemoteSub(subIgnoreFailedRemoteSub)) { throw err; @@ -511,11 +526,17 @@ async function produceArtifact({ `订阅 ${sub.name} 启用兜底后返回空结果: ${err.message ?? err}`, ); - return buildEmptySubscriptionOutput({ + const result = buildEmptySubscriptionOutput({ platform, produceType, produceOpts, }); + return includeRaw + ? { + result, + raw: Array.isArray(sourceRaw) ? sourceRaw : [sourceRaw], + } + : result; } } else if (['collection', 'col'].includes(type)) { const allSubs = $.read(SUBS_KEY); @@ -541,11 +562,11 @@ async function produceArtifact({ collection.ignoreFailedRemoteSub, ); const skipFlow = noFlow || collection.noFlow; + const rawResults = {}; try { const results = {}; const errors = {}; - const rawResults = {}; let processed = 0; await Promise.all( @@ -797,12 +818,13 @@ async function produceArtifact({ } exist[proxy.name] = true; } - return ProxyUtils.produce( + const result = ProxyUtils.produce( proxies, platform, produceType, produceOpts, ); + return includeRaw ? { result, raw: rawResults } : result; } catch (err) { if ( !shouldFallbackIgnoreFailedRemoteSub( @@ -829,11 +851,12 @@ async function produceArtifact({ }`, ); - return buildEmptySubscriptionOutput({ + const result = buildEmptySubscriptionOutput({ platform, produceType, produceOpts, }); + return includeRaw ? { result, raw: rawResults } : result; } } else if (type === 'rule') { const allRules = $.read(RULES_KEY); diff --git a/backend/src/test/restful/sync.spec.js b/backend/src/test/restful/sync.spec.js index e0538fdc..df40337c 100644 --- a/backend/src/test/restful/sync.spec.js +++ b/backend/src/test/restful/sync.spec.js @@ -1,11 +1,21 @@ import { expect } from 'chai'; import { after, before, beforeEach, describe, it } from 'mocha'; -import { ARTIFACTS_KEY, FILES_KEY, SETTINGS_KEY } from '@/constants'; +import { + ARTIFACTS_KEY, + COLLECTIONS_KEY, + FILES_KEY, + SETTINGS_KEY, + SUBS_KEY, +} from '@/constants'; + +const VLESS_WS = + 'vless://11111111-1111-4111-8111-111111111111@1.1.1.1:443?security=tls&type=ws&host=cdn.example.com&path=%2Fws&sni=sni.example.com#VLESS%20WS'; let $; let registerArtifactRoutes; let registerSyncRoutes; +let produceArtifact; let produceSyncArtifactOutput; let originalError; let originalInfo; @@ -104,9 +114,11 @@ describe('sync routes', function () { before(async function () { ({ default: $ } = require('@/core/app')); ({ default: registerArtifactRoutes } = require('@/restful/artifacts')); - ({ default: registerSyncRoutes, produceSyncArtifactOutput } = require( - '@/restful/sync' - )); + ({ + default: registerSyncRoutes, + produceArtifact, + produceSyncArtifactOutput, + } = require('@/restful/sync')); ageUtils = require('@/utils/age'); originalRead = $.read.bind($); @@ -127,6 +139,12 @@ describe('sync routes', function () { beforeEach(function () { state = { [SETTINGS_KEY]: {}, + [SUBS_KEY]: [ + { name: 'raw-sub', source: 'local', content: VLESS_WS }, + ], + [COLLECTIONS_KEY]: [ + { name: 'raw-col', subscriptions: ['raw-sub'] }, + ], [ARTIFACTS_KEY]: [ { name: 'local-artifact', @@ -156,6 +174,245 @@ describe('sync routes', function () { $.error = () => {}; }); + it('returns subscription output and raw only when requested', async function () { + state[SUBS_KEY][0].process = [ + { + type: 'Script Operator', + args: { + mode: 'script', + content: `function operator(proxies, targetPlatform, context) { + return proxies.map(proxy => ({ ...proxy, name: context.raw[0] })); + }`, + }, + }, + ]; + + for (const type of ['subscription', 'sub']) { + for (const produceType of [undefined, 'internal', 'raw']) { + const options = { type, name: 'raw-sub', produceType }; + const original = await produceArtifact(options); + const output = await produceArtifact({ + ...options, + includeRaw: true, + }); + + expect(output).to.deep.equal({ + result: original, + raw: [VLESS_WS], + }); + expect( + await produceArtifact({ ...options, includeRaw: false }), + ).to.deep.equal(original); + if (produceType !== 'raw') { + const proxies = Array.isArray(output.result) + ? output.result + : JSON.parse(output.result); + expect(proxies[0].name).to.equal(output.raw[0]); + } + } + } + }); + + it('keeps processor raw arguments unchanged regardless of includeRaw', async function () { + const { ProxyUtils } = require('@/core/proxy-utils'); + const originalProcess = ProxyUtils.process; + let passedRaw; + ProxyUtils.process = (...args) => { + passedRaw = args[5]; + return originalProcess(...args); + }; + + try { + for (const content of [VLESS_WS, [VLESS_WS]]) { + state[SUBS_KEY][0].content = content; + for (const options of [ + {}, + { includeRaw: false }, + { includeRaw: true }, + ]) { + const output = await produceArtifact({ + type: 'subscription', + name: 'raw-sub', + ...options, + }); + + expect(passedRaw).to.equal(content); + const result = options.includeRaw ? output.result : output; + expect(JSON.parse(result)).to.have.length(1); + } + } + } finally { + ProxyUtils.process = originalProcess; + } + }); + + it('returns collection raw keyed by subscription name including tag matches', async function () { + const taggedContent = VLESS_WS.replace('#VLESS%20WS', '#Tagged'); + state[SUBS_KEY].push({ + name: 'tagged-sub', + source: 'local', + content: taggedContent, + tag: ['raw-tag'], + }); + state[COLLECTIONS_KEY][0].subscriptionTags = ['raw-tag']; + + for (const type of ['collection', 'col']) { + const options = { type, name: 'raw-col', produceType: 'internal' }; + const output = await produceArtifact({ + ...options, + includeRaw: true, + }); + + expect(output.result).to.deep.equal(await produceArtifact(options)); + expect(output.result.map((proxy) => proxy.name)).to.deep.equal([ + 'VLESS WS', + 'Tagged', + ]); + expect(output.raw).to.deep.equal({ + 'raw-sub': [VLESS_WS], + 'tagged-sub': [taggedContent], + }); + } + }); + + it('preserves unpreprocessed remote raw and merged source order', async function () { + const openApi = require('@/vendor/open-api'); + const originalHTTP = openApi.HTTP; + const remoteContent = [ + 'proxies:', + ' - name: Remote', + ' type: ss', + ' server: example.com', + ' port: 443', + ' cipher: aes-128-gcm', + ' password: pass', + '', + ].join('\n'); + const secondContent = VLESS_WS.replace('#VLESS%20WS', '#Second'); + const url = + 'https://example.com/raw-first\nhttps://example.com/raw-second'; + openApi.HTTP = () => ({ + get: async ({ url }) => ({ + body: url.endsWith('raw-first') ? remoteContent : secondContent, + headers: {}, + statusCode: 200, + }), + }); + + try { + for (const mergeSources of ['localFirst', 'remoteFirst']) { + Object.assign(state[SUBS_KEY][0], { + source: 'remote', + url, + mergeSources, + }); + const expectedRaw = [remoteContent, secondContent]; + if (mergeSources === 'localFirst') + expectedRaw.unshift(VLESS_WS); + else expectedRaw.push(VLESS_WS); + + for (const [type, override] of [ + ['subscription', false], + ['subscription', true], + ['collection', false], + ]) { + const output = await produceArtifact({ + type, + name: type === 'collection' ? 'raw-col' : 'raw-sub', + produceType: type === 'collection' ? 'internal' : 'raw', + ...(override + ? { url, content: VLESS_WS, mergeSources } + : {}), + noCache: true, + noFlow: true, + includeRaw: true, + }); + + expect(output.raw).to.deep.equal( + type === 'collection' + ? { 'raw-sub': expectedRaw } + : expectedRaw, + ); + if (type === 'subscription') { + const remoteIndex = + mergeSources === 'localFirst' ? 1 : 0; + expect( + JSON.parse(output.result)[remoteIndex], + ).to.not.equal(remoteContent); + } else { + expect(output.result).to.have.length(3); + } + } + } + } finally { + openApi.HTTP = originalHTTP; + } + }); + + it('returns available raw alongside subscription and collection fallback output', async function () { + const failingProcess = [ + { + type: 'Script Operator', + args: { mode: 'script', content: "throw new Error('boom')" }, + }, + ]; + + for (const type of ['subscription', 'collection']) { + state[SUBS_KEY][0].process = + type === 'subscription' ? failingProcess : []; + state[COLLECTIONS_KEY][0].process = + type === 'collection' ? failingProcess : []; + const output = await produceArtifact({ + type, + name: type === 'subscription' ? 'raw-sub' : 'raw-col', + produceType: 'internal', + ignoreFailedRemoteSub: 'fallbackQuiet', + includeRaw: true, + }); + + expect(output).to.deep.equal({ + result: [], + raw: + type === 'subscription' + ? [VLESS_WS] + : { 'raw-sub': [VLESS_WS] }, + }); + } + }); + + it('preserves ignored and fallback child failures in returned collection raw', async function () { + state[SUBS_KEY].push({ + name: 'broken-sub', + source: 'local', + content: VLESS_WS, + process: [ + { + type: 'Script Operator', + args: { + mode: 'script', + content: "throw new Error('boom')", + }, + }, + ], + }); + state[COLLECTIONS_KEY][0].subscriptions.push('broken-sub'); + + for (const mode of ['quiet', 'fallbackQuiet']) { + const output = await produceArtifact({ + type: 'collection', + name: 'raw-col', + ignoreFailedRemoteSub: mode, + includeRaw: true, + }); + + expect(JSON.parse(output.result)).to.have.length(1); + expect(output.raw).to.deep.equal({ + 'raw-sub': [VLESS_WS], + 'broken-sub': mode === 'quiet' ? undefined : [], + }); + } + }); + it('updates run time without requiring a Gist URL when upload is disabled', async function () { const startedAt = new Date().getTime(); diff --git a/scripts/demo.js b/scripts/demo.js index 48117e93..564a9c34 100644 --- a/scripts/demo.js +++ b/scripts/demo.js @@ -396,6 +396,17 @@ function operator(proxies = [], targetPlatform, context) { // 如果某个子订阅处理失败并启用失败静默/失败通知, 会保留该 key, value 为 undefined // 如果启用静默兜底/通知兜底, 会保留该 key, value 为 [] + // produceArtifact 可通过 includeRaw: true 同时返回处理结果和 context.raw 对应的原始内容 + // includeRaw 只控制返回值, 不改变传给处理器的原始内容 + // 适用于 type: 'subscription' / 'sub' / 'collection' / 'col', 不传时仍直接返回处理结果 + // const { result, raw } = await produceArtifact({ + // type: 'subscription', // 使用 collection 时, raw 为按单条订阅 name 分组的对象 + // name: 'sub', + // platform: 'ClashMeta', + // produceType: 'internal', // result 为节点数组; 不传 produceType 时为输出字符串 + // includeRaw: true, + // }) + // 其中 source 为 订阅和组合订阅的数据, 有三种情况, 按需判断 (若只需要取订阅/组合订阅名称 直接用 `_subName` `_subDisplayName` `_collectionName` `_collectionDisplayName` 即可) // 若存在 `source._collection` 且 `source._collection.subscriptions` 中的 key 在 `source` 上也存在, 说明输出结果为组合订阅, 但是脚本设置在单条订阅上