贡献功能开发

This commit is contained in:
QLHazyCoder
2026-04-18 23:51:56 +08:00
parent f13b90b7db
commit c994d7ae12
14 changed files with 2658 additions and 19 deletions
+441
View File
@@ -0,0 +1,441 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const backgroundSource = fs.readFileSync('background.js', 'utf8');
function extractFunction(source, name) {
const markers = [`async function ${name}(`, `function ${name}(`];
const start = markers
.map((marker) => source.indexOf(marker))
.find((index) => index >= 0);
if (start < 0) {
throw new Error(`missing function ${name}`);
}
let parenDepth = 0;
let signatureEnded = false;
let braceStart = -1;
for (let i = start; i < source.length; i += 1) {
const ch = source[i];
if (ch === '(') {
parenDepth += 1;
} else if (ch === ')') {
parenDepth -= 1;
if (parenDepth === 0) {
signatureEnded = true;
}
} else if (ch === '{' && signatureEnded) {
braceStart = i;
break;
}
}
let depth = 0;
let end = braceStart;
for (; end < source.length; end += 1) {
const ch = source[end];
if (ch === '{') depth += 1;
if (ch === '}') {
depth -= 1;
if (depth === 0) {
end += 1;
break;
}
}
}
return source.slice(start, end);
}
function createMockResponse(ok, status, payload) {
return {
ok,
status,
async json() {
return payload;
},
};
}
test('background imports contribution oauth module and keeps contribution runtime out of persisted settings', () => {
const persistedStart = backgroundSource.indexOf('const PERSISTED_SETTING_DEFAULTS = {');
const persistedEnd = backgroundSource.indexOf('const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);');
const defaultStateStart = backgroundSource.indexOf('const DEFAULT_STATE = {');
const defaultStateEnd = backgroundSource.indexOf('async function getState()');
const persistedBlock = backgroundSource.slice(persistedStart, persistedEnd);
const defaultStateBlock = backgroundSource.slice(defaultStateStart, defaultStateEnd);
assert.match(backgroundSource, /background\/contribution-oauth\.js/);
assert.doesNotMatch(persistedBlock, /contributionSessionId|contributionAuthUrl|contributionCallbackUrl|contributionStatus/);
assert.match(defaultStateBlock, /contributionMode:\s*false|CONTRIBUTION_RUNTIME_DEFAULTS/);
});
test('contribution oauth module exposes a factory', () => {
const source = fs.readFileSync('background/contribution-oauth.js', 'utf8');
const globalScope = {};
const api = new Function('self', 'fetch', `${source}; return self.MultiPageBackgroundContributionOAuth;`)(
globalScope,
async () => createMockResponse(true, 200, { ok: true })
);
assert.equal(typeof api?.createContributionOAuthManager, 'function');
assert.equal(Array.isArray(api?.RUNTIME_KEYS), true);
});
test('buildContributionModeState preserves active contribution runtime while forcing CPA mode', () => {
const bundle = extractFunction(backgroundSource, 'buildContributionModeState');
const api = new Function(`
const DEFAULT_STATE = { panelMode: 'cpa' };
const CONTRIBUTION_RUNTIME_DEFAULTS = {
contributionMode: false,
contributionSessionId: '',
contributionAuthUrl: '',
contributionAuthState: '',
contributionCallbackUrl: '',
contributionStatus: '',
contributionStatusMessage: '',
contributionLastPollAt: 0,
contributionCallbackStatus: 'idle',
contributionCallbackMessage: '',
contributionAuthOpenedAt: 0,
contributionAuthTabId: 0,
};
const CONTRIBUTION_RUNTIME_KEYS = Object.keys(CONTRIBUTION_RUNTIME_DEFAULTS);
${bundle}
return { buildContributionModeState };
`)();
assert.deepStrictEqual(
api.buildContributionModeState(true, {
panelMode: 'sub2api',
customPassword: 'Secret123!',
accountRunHistoryTextEnabled: true,
}, {
contributionSessionId: 'session-001',
contributionAuthUrl: 'https://auth.example.com',
contributionStatus: 'waiting',
contributionCallbackStatus: 'waiting',
}),
{
contributionMode: true,
contributionSessionId: 'session-001',
contributionAuthUrl: 'https://auth.example.com',
contributionAuthState: '',
contributionCallbackUrl: '',
contributionStatus: 'waiting',
contributionStatusMessage: '',
contributionLastPollAt: 0,
contributionCallbackStatus: 'waiting',
contributionCallbackMessage: '',
contributionAuthOpenedAt: 0,
contributionAuthTabId: 0,
panelMode: 'cpa',
customPassword: '',
accountRunHistoryTextEnabled: false,
}
);
assert.deepStrictEqual(
api.buildContributionModeState(false, {
panelMode: 'sub2api',
customPassword: 'Secret123!',
accountRunHistoryTextEnabled: true,
}, {
contributionSessionId: 'session-001',
contributionAuthUrl: 'https://auth.example.com',
contributionStatus: 'waiting',
}),
{
contributionMode: false,
contributionSessionId: '',
contributionAuthUrl: '',
contributionAuthState: '',
contributionCallbackUrl: '',
contributionStatus: '',
contributionStatusMessage: '',
contributionLastPollAt: 0,
contributionCallbackStatus: 'idle',
contributionCallbackMessage: '',
contributionAuthOpenedAt: 0,
contributionAuthTabId: 0,
panelMode: 'sub2api',
customPassword: 'Secret123!',
accountRunHistoryTextEnabled: true,
}
);
});
test('resetState preserves contribution runtime across reset', () => {
assert.match(backgroundSource, /CONTRIBUTION_RUNTIME_KEYS/);
assert.match(backgroundSource, /const contributionModeState = buildContributionModeState/);
assert.match(backgroundSource, /\.\.\.contributionModeState/);
});
test('message router handles contribution mode, start flow, and status polling messages', async () => {
const source = fs.readFileSync('background/message-router.js', 'utf8');
const globalScope = {};
const api = new Function('self', `${source}; return self.MultiPageBackgroundMessageRouter;`)(globalScope);
const calls = [];
const router = api.createMessageRouter({
ensureManualInteractionAllowed: async () => ({
stepStatuses: { 1: 'pending', 2: 'completed' },
contributionMode: true,
}),
pollContributionStatus: async (options) => {
calls.push({ type: 'poll', options });
return { contributionStatus: 'waiting' };
},
setContributionMode: async (enabled) => {
calls.push({ type: 'toggle', enabled });
return {
contributionMode: Boolean(enabled),
panelMode: 'cpa',
};
},
startContributionFlow: async (options) => {
calls.push({ type: 'start', options });
return {
contributionMode: true,
contributionSessionId: 'session-001',
contributionStatus: 'started',
};
},
});
const enableResponse = await router.handleMessage({
type: 'SET_CONTRIBUTION_MODE',
payload: { enabled: true },
});
const startResponse = await router.handleMessage({
type: 'START_CONTRIBUTION_FLOW',
payload: { nickname: '阿青' },
});
const pollResponse = await router.handleMessage({
type: 'POLL_CONTRIBUTION_STATUS',
payload: { reason: 'test_poll' },
});
assert.equal(enableResponse.ok, true);
assert.equal(startResponse.ok, true);
assert.equal(pollResponse.ok, true);
assert.deepStrictEqual(calls, [
{ type: 'toggle', enabled: true },
{ type: 'start', options: { nickname: '阿青' } },
{ type: 'poll', options: { reason: 'test_poll' } },
]);
});
test('account run history snapshot sync is disabled in contribution mode', () => {
const source = fs.readFileSync('background/account-run-history.js', 'utf8');
const globalScope = {};
const api = new Function('self', `${source}; return self.MultiPageBackgroundAccountRunHistory;`)(globalScope);
const helpers = api.createAccountRunHistoryHelpers({
addLog: async () => {},
buildLocalHelperEndpoint: (baseUrl, path) => `${baseUrl}${path}`,
chrome: {
storage: {
local: {
get: async () => ({}),
set: async () => {},
},
},
},
getErrorMessage: (error) => error?.message || String(error || ''),
getState: async () => ({}),
normalizeAccountRunHistoryHelperBaseUrl: (value) => String(value || '').trim(),
});
assert.equal(
helpers.shouldSyncAccountRunHistorySnapshot({
contributionMode: true,
accountRunHistoryTextEnabled: true,
accountRunHistoryHelperBaseUrl: 'http://127.0.0.1:17373',
}),
false
);
assert.equal(
helpers.shouldSyncAccountRunHistorySnapshot({
contributionMode: false,
accountRunHistoryTextEnabled: true,
accountRunHistoryHelperBaseUrl: 'http://127.0.0.1:17373',
}),
true
);
});
test('contribution oauth manager starts session, opens auth url, polls real statuses, and treats callback submit no-op as success', async () => {
const source = fs.readFileSync('background/contribution-oauth.js', 'utf8');
const globalScope = {};
const fetchCalls = [];
const tabCalls = [];
const closeCallbackCalls = [];
let currentState = {
contributionMode: true,
email: 'user@example.com',
contributionSessionId: '',
contributionStatus: '',
contributionCallbackStatus: 'idle',
};
const broadcasts = [];
const api = new Function('self', 'fetch', `${source}; return self.MultiPageBackgroundContributionOAuth;`)(
globalScope,
async (url, options = {}) => {
fetchCalls.push({ url, options });
if (String(url).endsWith('/start')) {
return createMockResponse(true, 200, {
ok: true,
session_id: 'session-001',
state: 'oauth-state-001',
auth_url: 'https://auth.example.com/oauth?state=oauth-state-001',
message: '登录地址已生成',
});
}
if (String(url).includes('/status?')) {
return createMockResponse(true, 200, {
ok: true,
session_id: 'session-001',
status: 'waiting',
message: '等待 OAuth 回调完成',
});
}
if (String(url).endsWith('/submit-callback')) {
return createMockResponse(false, 400, {
ok: false,
message: '当前已启用自动回调转发,无需手动粘贴回调 URL。',
callback_url_received: true,
});
}
return createMockResponse(true, 200, {
ok: true,
session_id: 'session-001',
status: 'processing',
message: '授权已完成,正在自动审核并导入。',
});
}
);
const manager = api.createContributionOAuthManager({
addLog: async () => {},
broadcastDataUpdate(updates) {
broadcasts.push(updates);
currentState = { ...currentState, ...updates };
},
chrome: {
tabs: {
async create(payload) {
tabCalls.push(payload);
return { id: 88, url: payload.url };
},
async update() {
return null;
},
onUpdated: { addListener() {} },
},
webNavigation: {
onCommitted: { addListener() {} },
onHistoryStateUpdated: { addListener() {} },
},
},
closeLocalhostCallbackTabs: async (callbackUrl) => {
closeCallbackCalls.push(callbackUrl);
},
getState: async () => currentState,
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
});
const startedState = await manager.startContributionFlow();
assert.equal(startedState.contributionSessionId, 'session-001');
assert.equal(startedState.contributionAuthState, 'oauth-state-001');
assert.equal(startedState.contributionStatus, 'waiting');
assert.equal(startedState.contributionAuthTabId, 88);
assert.equal(tabCalls.length, 1);
assert.match(fetchCalls[0].url, /\/start$/);
assert.match(fetchCalls[1].url, /\/status\?/);
const callbackState = await manager.handleCapturedCallback(
'http://localhost:1455/auth/callback?code=abc123&state=oauth-state-001',
{ source: 'test' }
);
assert.equal(callbackState.contributionCallbackUrl, 'http://localhost:1455/auth/callback?code=abc123&state=oauth-state-001');
assert.equal(callbackState.contributionCallbackStatus, 'not_required');
assert.equal(closeCallbackCalls[0], 'http://localhost:1455/auth/callback?code=abc123&state=oauth-state-001');
assert.ok(fetchCalls.some((call) => String(call.url).endsWith('/submit-callback')));
assert.ok(broadcasts.some((item) => item.contributionCallbackStatus === 'captured'));
assert.ok(broadcasts.some((item) => item.contributionCallbackStatus === 'not_required'));
});
test('refreshOAuthUrlBeforeStep6 uses contribution oauth session instead of panel bridge in contribution mode', async () => {
const bundle = extractFunction(backgroundSource, 'refreshOAuthUrlBeforeStep6');
const calls = [];
const api = new Function(`
${bundle}
return { refreshOAuthUrlBeforeStep6 };
`)();
globalThis.addLog = async (message) => {
calls.push({ type: 'log', message });
};
globalThis.contributionOAuthManager = {
async startContributionFlow(options) {
calls.push({ type: 'contribution', options });
return {
contributionAuthUrl: 'https://auth.example.com/oauth?state=oauth-state-001',
};
},
};
globalThis.handleStepData = async (step, payload) => {
calls.push({ type: 'step', step, payload });
};
globalThis.getPanelModeLabel = () => 'CPA';
globalThis.requestOAuthUrlFromPanel = async () => {
calls.push({ type: 'panel' });
return { oauthUrl: 'https://panel.example.com/oauth' };
};
globalThis.LOG_PREFIX = '[test]';
const oauthUrl = await api.refreshOAuthUrlBeforeStep6({
contributionMode: true,
email: 'user@example.com',
});
assert.equal(oauthUrl, 'https://auth.example.com/oauth?state=oauth-state-001');
assert.deepStrictEqual(calls, [
{ type: 'log', message: '步骤 7:贡献模式正在申请贡献登录地址...' },
{
type: 'contribution',
options: {
nickname: 'user@example.com',
openAuthTab: false,
stateOverride: {
contributionMode: true,
email: 'user@example.com',
},
},
},
{
type: 'step',
step: 1,
payload: {
oauthUrl: 'https://auth.example.com/oauth?state=oauth-state-001',
},
},
]);
delete globalThis.addLog;
delete globalThis.contributionOAuthManager;
delete globalThis.handleStepData;
delete globalThis.getPanelModeLabel;
delete globalThis.requestOAuthUrlFromPanel;
delete globalThis.LOG_PREFIX;
});
+20 -1
View File
@@ -406,7 +406,10 @@ return {
});
test('resetState preserves LuckMail session config, used map, and preserve tag cache while clearing runtime purchase state', async () => {
const bundle = extractFunction('resetState');
const bundle = [
extractFunction('buildContributionModeState'),
extractFunction('resetState'),
].join('\n');
const factory = new Function([
'let cleared = false;',
@@ -418,6 +421,7 @@ test('resetState preserves LuckMail session config, used map, and preserve tag c
" luckmailBaseUrl: 'https://mails.luckyous.com',",
" luckmailEmailType: 'ms_graph',",
" luckmailDomain: '',",
" panelMode: 'cpa',",
' luckmailUsedPurchases: {},',
' luckmailPreserveTagId: 0,',
" luckmailPreserveTagName: '保留',",
@@ -425,6 +429,21 @@ test('resetState preserves LuckMail session config, used map, and preserve tag c
" currentLuckmailMailCursor: { messageId: 'stale' },",
' email: null,',
'};',
'const CONTRIBUTION_RUNTIME_DEFAULTS = {',
' contributionMode: false,',
" contributionSessionId: '',",
" contributionAuthUrl: '',",
" contributionAuthState: '',",
" contributionCallbackUrl: '',",
" contributionStatus: '',",
" contributionStatusMessage: '',",
' contributionLastPollAt: 0,',
" contributionCallbackStatus: 'idle',",
" contributionCallbackMessage: '',",
' contributionAuthOpenedAt: 0,',
' contributionAuthTabId: 0,',
'};',
'const CONTRIBUTION_RUNTIME_KEYS = Object.keys(CONTRIBUTION_RUNTIME_DEFAULTS);',
'function normalizeLuckmailBaseUrl(value) {',
" const normalized = String(value || '').trim() || 'https://mails.luckyous.com';",
" return normalized.replace(/\\/$/, '');",
+445
View File
@@ -0,0 +1,445 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const sidepanelSource = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
function extractFunction(name) {
const markers = [`async function ${name}(`, `function ${name}(`];
const start = markers
.map((marker) => sidepanelSource.indexOf(marker))
.find((index) => index >= 0);
if (start < 0) {
throw new Error(`missing function ${name}`);
}
let parenDepth = 0;
let signatureEnded = false;
let braceStart = -1;
for (let i = start; i < sidepanelSource.length; i += 1) {
const ch = sidepanelSource[i];
if (ch === '(') {
parenDepth += 1;
} else if (ch === ')') {
parenDepth -= 1;
if (parenDepth === 0) {
signatureEnded = true;
}
} else if (ch === '{' && signatureEnded) {
braceStart = i;
break;
}
}
let depth = 0;
let end = braceStart;
for (; end < sidepanelSource.length; end += 1) {
const ch = sidepanelSource[end];
if (ch === '{') depth += 1;
if (ch === '}') {
depth -= 1;
if (depth === 0) {
end += 1;
break;
}
}
}
return sidepanelSource.slice(start, end);
}
function createClassList() {
const values = new Set();
return {
add(name) {
values.add(name);
},
remove(name) {
values.delete(name);
},
toggle(name, force) {
if (force === undefined) {
if (values.has(name)) {
values.delete(name);
return false;
}
values.add(name);
return true;
}
if (force) {
values.add(name);
return true;
}
values.delete(name);
return false;
},
contains(name) {
return values.has(name);
},
};
}
function createElement(initial = {}) {
return {
disabled: Boolean(initial.disabled),
hidden: Boolean(initial.hidden),
value: initial.value || '',
title: '',
textContent: initial.textContent || '',
listeners: {},
attributes: {},
classList: createClassList(),
addEventListener(type, handler) {
this.listeners[type] = handler;
},
setAttribute(name, value) {
this.attributes[name] = String(value);
},
};
}
test('sidepanel html contains contribution mode runtime UI and loads the module before sidepanel bootstrap', () => {
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
const moduleIndex = html.indexOf('<script src="contribution-mode.js"></script>');
const sidepanelIndex = html.indexOf('<script src="sidepanel.js"></script>');
assert.match(html, /id="btn-contribution-mode"/);
assert.match(html, /id="contribution-mode-panel"/);
assert.match(html, /id="contribution-oauth-status"/);
assert.match(html, /id="contribution-callback-status"/);
assert.match(html, /id="contribution-mode-summary"/);
assert.match(html, /id="btn-start-contribution"/);
assert.match(html, /id="btn-open-contribution-upload"/);
assert.match(html, /id="btn-exit-contribution-mode"/);
assert.notEqual(moduleIndex, -1);
assert.notEqual(sidepanelIndex, -1);
assert.ok(moduleIndex < sidepanelIndex);
});
test('collectSettingsPayload omits custom password and local sync settings in contribution mode', () => {
const bundle = extractFunction('collectSettingsPayload');
const api = new Function(`
let latestState = { contributionMode: true };
let cloudflareDomainEditMode = false;
let cloudflareTempEmailDomainEditMode = false;
const selectCfDomain = { value: 'example.com' };
const selectTempEmailDomain = { value: 'mail.example.com' };
const selectPanelMode = { value: 'cpa' };
const inputVpsUrl = { value: 'https://panel.example.com' };
const inputVpsPassword = { value: 'panel-secret' };
const inputSub2ApiUrl = { value: 'https://sub.example.com' };
const inputSub2ApiEmail = { value: 'user@example.com' };
const inputSub2ApiPassword = { value: 'sub-secret' };
const inputSub2ApiGroup = { value: ' codex ' };
const inputSub2ApiDefaultProxy = { value: ' proxy-a ' };
const inputPassword = { value: 'Secret123!' };
const selectMailProvider = { value: '163' };
const selectEmailGenerator = { value: 'duck' };
const checkboxAutoDeleteIcloud = { checked: true };
const selectIcloudHostPreference = { value: 'auto' };
const inputAccountRunHistoryTextEnabled = { checked: true };
const inputAccountRunHistoryHelperBaseUrl = { value: 'http://127.0.0.1:17373' };
const inputInbucketHost = { value: 'inbucket.local' };
const inputInbucketMailbox = { value: 'demo' };
const inputHotmailRemoteBaseUrl = { value: 'https://hotmail.example.com' };
const inputHotmailLocalBaseUrl = { value: 'http://127.0.0.1:17373' };
const inputLuckmailApiKey = { value: 'lk-api-key' };
const inputLuckmailBaseUrl = { value: 'https://mails.example.com' };
const selectLuckmailEmailType = { value: 'ms_graph' };
const inputLuckmailDomain = { value: 'luckmail.example.com' };
const inputTempEmailBaseUrl = { value: 'https://temp.example.com' };
const inputTempEmailAdminAuth = { value: 'admin-secret' };
const inputTempEmailCustomAuth = { value: 'custom-secret' };
const inputTempEmailReceiveMailbox = { value: 'relay@example.com' };
const inputAutoSkipFailures = { checked: false };
const inputAutoSkipFailuresThreadIntervalMinutes = { value: '5' };
const inputAutoDelayEnabled = { checked: true };
const inputAutoDelayMinutes = { value: '30' };
const inputAutoStepDelaySeconds = { value: '10' };
const inputVerificationResendCount = { value: '6' };
const DEFAULT_VERIFICATION_RESEND_COUNT = 4;
function getCloudflareDomainsFromState() { return { domains: ['example.com'], activeDomain: 'example.com' }; }
function normalizeCloudflareDomainValue(value) { return String(value || '').trim(); }
function getCloudflareTempEmailDomainsFromState() { return { domains: ['mail.example.com'], activeDomain: 'mail.example.com' }; }
function normalizeCloudflareTempEmailDomainValue(value) { return String(value || '').trim(); }
function getSelectedLocalCpaStep9Mode() { return 'submit'; }
function getSelectedMail2925Mode() { return 'provide'; }
function normalizeAccountRunHistoryHelperBaseUrlValue(value) { return String(value || '').trim(); }
function buildManagedAliasBaseEmailPayload() { return { gmailBaseEmail: '', mail2925BaseEmail: '', emailPrefix: '' }; }
function getSelectedHotmailServiceMode() { return 'local'; }
function normalizeLuckmailBaseUrl(value) { return String(value || '').trim(); }
function normalizeLuckmailEmailType(value) { return String(value || '').trim(); }
function normalizeCloudflareTempEmailBaseUrlValue(value) { return String(value || '').trim(); }
function normalizeCloudflareTempEmailReceiveMailboxValue(value) { return String(value || '').trim(); }
function normalizeAutoRunThreadIntervalMinutes(value) { return Number(value) || 0; }
function normalizeAutoDelayMinutes(value) { return Number(value) || 30; }
function normalizeAutoStepDelaySeconds(value) { return value === '' ? null : Number(value); }
function normalizeVerificationResendCount(value, fallback) { return Number.isFinite(Number(value)) ? Number(value) : fallback; }
${bundle}
return {
collectSettingsPayload,
setLatestState(nextState) { latestState = nextState; },
};
`)();
const contributionPayload = api.collectSettingsPayload();
assert.equal('customPassword' in contributionPayload, false);
assert.equal('accountRunHistoryTextEnabled' in contributionPayload, false);
assert.equal('accountRunHistoryHelperBaseUrl' in contributionPayload, false);
api.setLatestState({ contributionMode: false });
const normalPayload = api.collectSettingsPayload();
assert.equal(normalPayload.customPassword, 'Secret123!');
assert.equal(normalPayload.accountRunHistoryTextEnabled, true);
assert.equal(normalPayload.accountRunHistoryHelperBaseUrl, 'http://127.0.0.1:17373');
});
test('contribution mode manager enters mode, starts main auto flow, polls contribution status, and exits cleanly', async () => {
const source = fs.readFileSync('sidepanel/contribution-mode.js', 'utf8');
const windowObject = {};
const timers = [];
const api = new Function('window', 'setTimeout', 'clearTimeout', `${source}; return window.SidepanelContributionMode;`)(
windowObject,
(handler) => {
timers.push(handler);
return timers.length;
},
(id) => {
if (timers[id - 1]) {
timers[id - 1] = null;
}
}
);
assert.equal(typeof api?.createContributionModeManager, 'function');
let latestState = {
contributionMode: false,
panelMode: 'sub2api',
contributionSessionId: '',
contributionStatus: '',
contributionStatusMessage: '',
contributionCallbackStatus: 'idle',
contributionCallbackMessage: '',
email: 'user@example.com',
};
let blocked = false;
let appliedState = null;
let statusState = null;
let closeConfigMenuCount = 0;
let closeAccountRecordsCount = 0;
let contributionAutoRunStartCount = 0;
let updatePanelModeCount = 0;
let updateSyncUiCount = 0;
let updateConfigMenuCount = 0;
const toasts = [];
const openedUrls = [];
const sentMessages = [];
const dom = {
btnConfigMenu: createElement(),
btnContributionMode: createElement(),
btnExitContributionMode: createElement(),
btnOpenAccountRecords: createElement(),
btnOpenContributionUpload: createElement(),
btnStartContribution: createElement(),
contributionCallbackStatus: createElement(),
contributionModePanel: createElement({ hidden: true }),
contributionModeSummary: createElement(),
contributionModeText: createElement(),
contributionOauthStatus: createElement(),
rowAccountRunHistoryHelperBaseUrl: createElement(),
rowAccountRunHistoryTextEnabled: createElement(),
rowCustomPassword: createElement(),
rowLocalCpaStep9Mode: createElement(),
rowSub2ApiDefaultProxy: createElement(),
rowSub2ApiEmail: createElement(),
rowSub2ApiGroup: createElement(),
rowSub2ApiPassword: createElement(),
rowSub2ApiUrl: createElement(),
rowVpsPassword: createElement(),
rowVpsUrl: createElement(),
selectPanelMode: createElement({ value: 'sub2api' }),
};
const manager = api.createContributionModeManager({
state: {
getLatestState: () => latestState,
},
dom,
helpers: {
applySettingsState(nextState) {
latestState = nextState;
appliedState = nextState;
},
closeAccountRecordsPanel() {
closeAccountRecordsCount += 1;
},
closeConfigMenu() {
closeConfigMenuCount += 1;
},
getContributionNickname() {
return latestState.email;
},
isModeSwitchBlocked() {
return blocked;
},
openConfirmModal: async () => true,
openExternalUrl(url) {
openedUrls.push(url);
},
showToast(message, type) {
toasts.push({ message, type });
},
async startContributionAutoRun() {
contributionAutoRunStartCount += 1;
latestState = {
...latestState,
contributionSessionId: 'session-002',
contributionAuthUrl: 'https://auth.example.com/oauth?state=oauth-state-002',
contributionAuthState: 'oauth-state-002',
contributionStatus: 'started',
contributionStatusMessage: '\u5df2\u751f\u6210\u767b\u5f55\u5730\u5740',
contributionCallbackStatus: 'waiting',
contributionCallbackMessage: '\u7b49\u5f85\u56de\u8c03',
};
return true;
},
updateAccountRunHistorySettingsUI() {
updateSyncUiCount += 1;
},
updateConfigMenuControls() {
updateConfigMenuCount += 1;
},
updatePanelModeUI() {
updatePanelModeCount += 1;
},
updateStatusDisplay(nextState) {
statusState = nextState;
},
},
runtime: {
sendMessage: async (message) => {
sentMessages.push(message);
if (message.type === 'SET_CONTRIBUTION_MODE') {
return {
state: message.payload.enabled
? {
contributionMode: true,
panelMode: 'cpa',
contributionSessionId: '',
contributionAuthUrl: '',
contributionAuthState: '',
contributionStatus: '',
contributionStatusMessage: '',
contributionCallbackStatus: 'idle',
contributionCallbackMessage: '',
email: latestState.email,
}
: {
contributionMode: false,
panelMode: 'cpa',
contributionSessionId: '',
contributionAuthUrl: '',
contributionAuthState: '',
contributionCallbackUrl: '',
contributionStatus: '',
contributionStatusMessage: '',
contributionCallbackStatus: 'idle',
contributionCallbackMessage: '',
email: latestState.email,
},
};
}
if (message.type === 'POLL_CONTRIBUTION_STATUS') {
return {
state: {
...latestState,
contributionStatus: 'processing',
contributionStatusMessage: '已授权,正在自动审核',
contributionCallbackStatus: 'not_required',
contributionCallbackMessage: '当前流程无需手动回调',
},
};
}
return {};
},
},
constants: {
contributionUploadUrl: 'https://apikey.qzz.io/',
pollIntervalMs: 2500,
},
});
manager.render();
assert.equal(dom.contributionModePanel.hidden, true);
assert.equal(dom.btnContributionMode.disabled, false);
manager.bindEvents();
await dom.btnContributionMode.listeners.click();
assert.equal(dom.contributionModePanel.hidden, false);
assert.equal(dom.selectPanelMode.value, 'cpa');
assert.equal(dom.selectPanelMode.disabled, true);
assert.equal(dom.btnOpenAccountRecords.disabled, true);
assert.equal(dom.contributionOauthStatus.textContent, '\u672a\u751f\u6210\u767b\u5f55\u5730\u5740');
assert.equal(dom.contributionCallbackStatus.textContent, '\u7b49\u5f85\u56de\u8c03');
assert.equal(dom.contributionModeSummary.textContent.length > 0, true);
assert.equal(dom.btnContributionMode.classList.contains('is-active'), true);
assert.equal(dom.rowVpsUrl.classList.contains('is-contribution-hidden'), true);
assert.ok(closeConfigMenuCount >= 1);
assert.ok(closeAccountRecordsCount >= 1);
assert.ok(updatePanelModeCount >= 1);
assert.ok(updateSyncUiCount >= 1);
assert.ok(updateConfigMenuCount >= 1);
assert.equal(timers.length, 0);
await dom.btnStartContribution.listeners.click();
assert.equal(contributionAutoRunStartCount, 1);
assert.equal(appliedState.contributionSessionId, '');
assert.equal(latestState.contributionSessionId, 'session-002');
assert.equal(latestState.contributionStatus, 'started');
assert.equal(timers.length > 0, true);
await manager.pollOnce({ reason: 'test_poll' });
assert.equal(statusState.contributionStatus, 'processing');
assert.equal(dom.contributionOauthStatus.textContent, '\u6388\u6743\u5df2\u5b8c\u6210');
assert.equal(dom.contributionCallbackStatus.textContent, '\u5f53\u524d\u6d41\u7a0b\u65e0\u9700\u624b\u52a8\u56de\u8c03');
assert.equal(dom.contributionModeSummary.textContent, '\u5df2\u6388\u6743\uff0c\u6b63\u5728\u81ea\u52a8\u5ba1\u6838');
dom.btnOpenContributionUpload.listeners.click();
assert.deepStrictEqual(openedUrls, ['https://apikey.qzz.io/']);
await dom.btnExitContributionMode.listeners.click();
manager.render();
assert.equal(dom.contributionModePanel.hidden, true);
assert.equal(dom.btnContributionMode.classList.contains('is-active'), false);
assert.equal(dom.selectPanelMode.disabled, false);
assert.equal(dom.rowVpsUrl.classList.contains('is-contribution-hidden'), false);
assert.deepStrictEqual(
sentMessages.map((message) => message.type),
['SET_CONTRIBUTION_MODE', 'POLL_CONTRIBUTION_STATUS', 'SET_CONTRIBUTION_MODE']
);
assert.deepStrictEqual(
toasts.map((item) => item.message),
['\u5df2\u8fdb\u5165\u8d21\u732e\u6a21\u5f0f\u3002', '\u8d21\u732e\u81ea\u52a8\u6d41\u7a0b\u5df2\u542f\u52a8\u3002', '\u5df2\u9000\u51fa\u8d21\u732e\u6a21\u5f0f\u3002']
);
blocked = true;
latestState = {
contributionMode: true,
panelMode: 'cpa',
contributionSessionId: 'session-002',
contributionAuthUrl: 'https://auth.example.com/oauth?state=oauth-state-002',
contributionStatus: 'waiting',
contributionStatusMessage: '\u7b49\u5f85\u6388\u6743\u5b8c\u6210',
contributionCallbackStatus: 'waiting',
contributionCallbackMessage: '\u7b49\u5f85\u56de\u8c03',
};
manager.render();
assert.equal(dom.btnExitContributionMode.disabled, true);
manager.stopPolling();
});