feat: 添加 Plus 模式和贡献模式支持,增强步骤执行延迟和提示逻辑
This commit is contained in:
@@ -45,11 +45,15 @@ const bundle = [
|
||||
'const AUTO_STEP_DELAY_MIN_ALLOWED_SECONDS = 0;',
|
||||
'const AUTO_STEP_DELAY_MAX_ALLOWED_SECONDS = 600;',
|
||||
'const PERSISTED_SETTING_DEFAULTS = { autoStepDelaySeconds: null };',
|
||||
"const AUTO_RUN_PRE_EXECUTION_DELAYS_BY_STEP_KEY = new Map([['plus-checkout-create', 20000]]);",
|
||||
'function getStepDefinitionForState(step, state = {}) { return state.definitions?.[step] || null; }',
|
||||
extractFunction('normalizeAutoStepDelaySeconds'),
|
||||
extractFunction('resolveLegacyAutoStepDelaySeconds'),
|
||||
extractFunction('getStepExecutionKeyForState'),
|
||||
extractFunction('getAutoRunPreExecutionDelayMs'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`${bundle}; return { normalizeAutoStepDelaySeconds, resolveLegacyAutoStepDelaySeconds };`)();
|
||||
const api = new Function(`${bundle}; return { normalizeAutoStepDelaySeconds, resolveLegacyAutoStepDelaySeconds, getAutoRunPreExecutionDelayMs };`)();
|
||||
|
||||
assert.strictEqual(
|
||||
api.normalizeAutoStepDelaySeconds(''),
|
||||
@@ -123,4 +127,24 @@ assert.strictEqual(
|
||||
'empty legacy settings should migrate to no delay'
|
||||
);
|
||||
|
||||
assert.strictEqual(
|
||||
api.getAutoRunPreExecutionDelayMs(6, {
|
||||
definitions: {
|
||||
6: { key: 'plus-checkout-create' },
|
||||
},
|
||||
}),
|
||||
20000,
|
||||
'Plus checkout create should wait before step execution'
|
||||
);
|
||||
|
||||
assert.strictEqual(
|
||||
api.getAutoRunPreExecutionDelayMs(6, {
|
||||
definitions: {
|
||||
6: { key: 'clear-login-cookies' },
|
||||
},
|
||||
}),
|
||||
0,
|
||||
'normal step 6 should not inherit the Plus checkout pre-wait'
|
||||
);
|
||||
|
||||
console.log('auto step delay tests passed');
|
||||
|
||||
@@ -87,6 +87,8 @@ test('account run history helper upgrades old records, keeps stopped items and s
|
||||
totalRuns: 10,
|
||||
attemptRun: 3,
|
||||
},
|
||||
plusModeEnabled: false,
|
||||
contributionMode: false,
|
||||
});
|
||||
|
||||
const appended = await helpers.appendAccountRunRecord('step8_failed', null, '步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
|
||||
@@ -138,6 +140,39 @@ test('account run history helper upgrades old records, keeps stopped items and s
|
||||
assert.equal(normalizedStoppedRecord.failedStep, 7);
|
||||
});
|
||||
|
||||
test('account run history records preserve Plus and contribution mode flags', () => {
|
||||
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({
|
||||
chrome: { storage: { local: { get: async () => ({}), set: async () => {} } } },
|
||||
getState: async () => ({}),
|
||||
normalizeAccountRunHistoryHelperBaseUrl: (value) => String(value || '').trim(),
|
||||
});
|
||||
|
||||
const record = helpers.buildAccountRunHistoryRecord({
|
||||
email: 'plus@example.com',
|
||||
password: 'secret',
|
||||
plusModeEnabled: true,
|
||||
contributionMode: true,
|
||||
}, 'success');
|
||||
|
||||
assert.equal(record.plusModeEnabled, true);
|
||||
assert.equal(record.contributionMode, true);
|
||||
|
||||
const normalized = helpers.normalizeAccountRunHistoryRecord({
|
||||
email: 'plus@example.com',
|
||||
password: 'secret',
|
||||
finalStatus: 'success',
|
||||
plusModeEnabled: true,
|
||||
contributionMode: true,
|
||||
});
|
||||
|
||||
assert.equal(normalized.plusModeEnabled, true);
|
||||
assert.equal(normalized.contributionMode, true);
|
||||
});
|
||||
|
||||
test('account run history helper clears persisted records and syncs full snapshot payload to local helper', async () => {
|
||||
const source = fs.readFileSync('background/account-run-history.js', 'utf8');
|
||||
const globalScope = {};
|
||||
|
||||
@@ -6,7 +6,7 @@ const source = fs.readFileSync('background/steps/create-plus-checkout.js', 'utf8
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundPlusCheckoutCreate;`)(globalScope);
|
||||
|
||||
test('Plus checkout create waits 20 seconds before completing step 6', async () => {
|
||||
test('Plus checkout create does not wait 20 seconds after opening checkout page', async () => {
|
||||
const events = [];
|
||||
const executor = api.createPlusCheckoutCreateExecutor({
|
||||
addLog: async (message, level = 'info') => {
|
||||
@@ -45,11 +45,12 @@ test('Plus checkout create waits 20 seconds before completing step 6', async ()
|
||||
await executor.executePlusCheckoutCreate();
|
||||
|
||||
const sleepEvents = events.filter((event) => event.type === 'sleep');
|
||||
assert.deepStrictEqual(sleepEvents.map((event) => event.ms), [1000, 1000, 20000]);
|
||||
assert.deepStrictEqual(sleepEvents.map((event) => event.ms), [1000, 1000]);
|
||||
|
||||
const fixedWaitIndex = events.findIndex((event) => event.type === 'sleep' && event.ms === 20000);
|
||||
const completeIndex = events.findIndex((event) => event.type === 'complete');
|
||||
assert.ok(fixedWaitIndex > -1);
|
||||
assert.ok(completeIndex > fixedWaitIndex);
|
||||
assert.equal(events.some((event) => event.type === 'log' && /固定等待 20 秒/.test(event.message)), true);
|
||||
const readyLogIndex = events.findIndex((event) => event.type === 'log' && /Plus Checkout 页面已就绪/.test(event.message));
|
||||
assert.ok(readyLogIndex > -1);
|
||||
assert.ok(completeIndex > readyLogIndex);
|
||||
assert.equal(events.some((event) => event.type === 'sleep' && event.ms === 20000), false);
|
||||
assert.equal(events.some((event) => event.type === 'log' && /固定等待 20 秒后继续下一步/.test(event.message)), false);
|
||||
});
|
||||
|
||||
@@ -57,6 +57,7 @@ function createApi({
|
||||
plusRiskEnabled = false,
|
||||
plusRiskConfirmed = true,
|
||||
plusRiskDismissPrompt = false,
|
||||
plusContributionImpl,
|
||||
} = {}) {
|
||||
const bundle = extractFunction('startAutoRunFromCurrentSettings');
|
||||
|
||||
@@ -110,6 +111,9 @@ async function openPlusAutoRunRiskConfirmModal(totalRuns) {
|
||||
function setAutoRunPlusRiskPromptDismissed(dismissed) {
|
||||
events.push({ type: 'plus-risk-dismiss', dismissed });
|
||||
}
|
||||
async function maybeShowPlusContributionPromptBeforeAutoRun(plusModeEnabled) {
|
||||
${plusContributionImpl ? 'return (' + plusContributionImpl + ')(plusModeEnabled, events);' : 'return true;'}
|
||||
}
|
||||
function normalizeAutoDelayMinutes(value) { return Number(value) || 30; }
|
||||
async function refreshContributionContentHint() {
|
||||
events.push({ type: 'refresh' });
|
||||
@@ -216,3 +220,22 @@ test('startAutoRunFromCurrentSettings aborts when Plus risk warning is declined'
|
||||
['refresh', 'confirm-check', 'plus-risk-modal']
|
||||
);
|
||||
});
|
||||
|
||||
test('startAutoRunFromCurrentSettings aborts when Plus contribution prompt opens contribution page', async () => {
|
||||
const api = createApi({
|
||||
plusModeEnabled: true,
|
||||
plusContributionImpl: `async (plusModeEnabled, events) => {
|
||||
events.push({ type: 'plus-contribution-modal', plusModeEnabled });
|
||||
return false;
|
||||
}`,
|
||||
});
|
||||
|
||||
const result = await api.startAutoRunFromCurrentSettings();
|
||||
|
||||
assert.equal(result, false);
|
||||
assert.deepEqual(
|
||||
api.getEvents().map((entry) => entry.type),
|
||||
['refresh', 'confirm-check', 'plus-contribution-modal']
|
||||
);
|
||||
assert.equal(api.getEvents()[2].plusModeEnabled, true);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
|
||||
|
||||
function extractFunction(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;
|
||||
}
|
||||
}
|
||||
if (braceStart < 0) {
|
||||
throw new Error(`missing body for function ${name}`);
|
||||
}
|
||||
|
||||
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 extractBundle(names) {
|
||||
return names.map((name) => extractFunction(name)).join('\n');
|
||||
}
|
||||
|
||||
function createPlusRecords(count, contributionMode = false) {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
recordId: `${contributionMode ? 'contribution' : 'plus'}-${index}@example.com`,
|
||||
email: `${contributionMode ? 'contribution' : 'plus'}-${index}@example.com`,
|
||||
finalStatus: 'success',
|
||||
plusModeEnabled: true,
|
||||
contributionMode,
|
||||
}));
|
||||
}
|
||||
|
||||
test('Plus contribution prompt starts every five normal Plus successes', () => {
|
||||
const bundle = extractBundle([
|
||||
'normalizePlusContributionPromptNumber',
|
||||
'normalizePlusContributionPromptLedger',
|
||||
'isSuccessfulPlusAccountRecord',
|
||||
'getPlusContributionPromptTotals',
|
||||
'getPlusContributionPromptProgress',
|
||||
'shouldShowPlusContributionPrompt',
|
||||
]);
|
||||
|
||||
const api = new Function(`
|
||||
const PLUS_CONTRIBUTION_PROMPT_THRESHOLD = 5;
|
||||
const PLUS_CONTRIBUTION_ACCOUNT_CREDIT = 5;
|
||||
${bundle}
|
||||
return {
|
||||
getPlusContributionPromptProgress,
|
||||
shouldShowPlusContributionPrompt,
|
||||
};
|
||||
`)();
|
||||
|
||||
assert.equal(
|
||||
api.shouldShowPlusContributionPrompt(createPlusRecords(4), true, { promptBaseline: 0, donationCredit: 0 }),
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
api.shouldShowPlusContributionPrompt(createPlusRecords(5), true, { promptBaseline: 0, donationCredit: 0 }),
|
||||
true
|
||||
);
|
||||
assert.equal(
|
||||
api.shouldShowPlusContributionPrompt(createPlusRecords(8), false, { promptBaseline: 0, donationCredit: 0 }),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('Plus contribution success and donated credit delay the next prompt', () => {
|
||||
const bundle = extractBundle([
|
||||
'normalizePlusContributionPromptNumber',
|
||||
'normalizePlusContributionPromptLedger',
|
||||
'isSuccessfulPlusAccountRecord',
|
||||
'getPlusContributionPromptTotals',
|
||||
'getPlusContributionPromptProgress',
|
||||
'shouldShowPlusContributionPrompt',
|
||||
]);
|
||||
|
||||
const api = new Function(`
|
||||
const PLUS_CONTRIBUTION_PROMPT_THRESHOLD = 5;
|
||||
const PLUS_CONTRIBUTION_ACCOUNT_CREDIT = 5;
|
||||
${bundle}
|
||||
return { shouldShowPlusContributionPrompt };
|
||||
`)();
|
||||
|
||||
const afterPromptLedger = { promptBaseline: 5, donationCredit: 0 };
|
||||
assert.equal(
|
||||
api.shouldShowPlusContributionPrompt(
|
||||
[...createPlusRecords(14), ...createPlusRecords(1, true)],
|
||||
true,
|
||||
afterPromptLedger
|
||||
),
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
api.shouldShowPlusContributionPrompt(
|
||||
[...createPlusRecords(15), ...createPlusRecords(1, true)],
|
||||
true,
|
||||
afterPromptLedger
|
||||
),
|
||||
true
|
||||
);
|
||||
|
||||
const donatedLedger = { promptBaseline: 5, donationCredit: 20 };
|
||||
assert.equal(api.shouldShowPlusContributionPrompt(createPlusRecords(29), true, donatedLedger), false);
|
||||
assert.equal(api.shouldShowPlusContributionPrompt(createPlusRecords(30), true, donatedLedger), true);
|
||||
});
|
||||
|
||||
test('Plus contribution support modal includes WeChat image and expected actions', async () => {
|
||||
const bundle = extractBundle([
|
||||
'getPlusContributionSupportImageUrl',
|
||||
'buildPlusContributionSupportPromptHtml',
|
||||
'openPlusContributionSupportModal',
|
||||
]);
|
||||
|
||||
const api = new Function(`
|
||||
let capturedOptions = null;
|
||||
const chrome = { runtime: { getURL: (path) => 'chrome-extension://test/' + path } };
|
||||
function escapeHtml(value) { return String(value || ''); }
|
||||
async function openActionModal(options) {
|
||||
capturedOptions = options;
|
||||
return 'donated';
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
openPlusContributionSupportModal,
|
||||
getCapturedOptions() {
|
||||
return capturedOptions;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const choice = await api.openPlusContributionSupportModal();
|
||||
const options = api.getCapturedOptions();
|
||||
|
||||
assert.equal(choice, 'donated');
|
||||
assert.equal(options.title, 'Plus 功能使用反馈');
|
||||
assert.match(options.messageHtml, /docs\/images\/微信\.png/);
|
||||
assert.deepEqual(options.actions.map((action) => action.label), ['取消', '去贡献账号', '已打赏']);
|
||||
});
|
||||
|
||||
test('Plus contribution prompt marks shown and donated choice adds twenty credits', async () => {
|
||||
const bundle = extractBundle([
|
||||
'normalizePlusContributionPromptNumber',
|
||||
'normalizePlusContributionPromptLedger',
|
||||
'getPlusContributionPromptLedger',
|
||||
'setPlusContributionPromptLedger',
|
||||
'isSuccessfulPlusAccountRecord',
|
||||
'getPlusContributionPromptTotals',
|
||||
'getPlusContributionPromptProgress',
|
||||
'shouldShowPlusContributionPrompt',
|
||||
'markPlusContributionPromptShown',
|
||||
'addPlusContributionPromptCredit',
|
||||
'maybeShowPlusContributionPromptBeforeAutoRun',
|
||||
]);
|
||||
|
||||
const api = new Function('records', `
|
||||
const PLUS_CONTRIBUTION_PROMPT_LEDGER_STORAGE_KEY = 'multipage-plus-contribution-prompt-ledger';
|
||||
const PLUS_CONTRIBUTION_PROMPT_THRESHOLD = 5;
|
||||
const PLUS_CONTRIBUTION_ACCOUNT_CREDIT = 5;
|
||||
const PLUS_CONTRIBUTION_DONATION_CREDIT = 20;
|
||||
const latestState = { accountRunHistory: records };
|
||||
const storage = {};
|
||||
const events = [];
|
||||
const localStorage = {
|
||||
getItem(key) { return Object.prototype.hasOwnProperty.call(storage, key) ? storage[key] : null; },
|
||||
setItem(key, value) { storage[key] = String(value); },
|
||||
};
|
||||
async function openPlusContributionSupportModal() {
|
||||
events.push({ type: 'modal' });
|
||||
return 'donated';
|
||||
}
|
||||
function showToast(message, type) {
|
||||
events.push({ type: 'toast', message, toastType: type });
|
||||
}
|
||||
function openExternalUrl(url) {
|
||||
events.push({ type: 'open', url });
|
||||
}
|
||||
function getContributionPortalUrl() {
|
||||
return 'https://apikey.qzz.io';
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
maybeShowPlusContributionPromptBeforeAutoRun,
|
||||
getLedger() {
|
||||
return JSON.parse(storage[PLUS_CONTRIBUTION_PROMPT_LEDGER_STORAGE_KEY] || '{}');
|
||||
},
|
||||
getEvents() {
|
||||
return events;
|
||||
},
|
||||
};
|
||||
`)(createPlusRecords(5));
|
||||
|
||||
const result = await api.maybeShowPlusContributionPromptBeforeAutoRun(true);
|
||||
|
||||
assert.equal(result, true);
|
||||
assert.deepEqual(api.getEvents().map((event) => event.type), ['modal', 'toast']);
|
||||
assert.deepEqual(api.getLedger(), {
|
||||
promptBaseline: 5,
|
||||
donationCredit: 20,
|
||||
});
|
||||
});
|
||||
|
||||
test('Plus contribution prompt opens portal and aborts normal auto run when contribute is chosen', async () => {
|
||||
const bundle = extractBundle([
|
||||
'normalizePlusContributionPromptNumber',
|
||||
'normalizePlusContributionPromptLedger',
|
||||
'getPlusContributionPromptLedger',
|
||||
'setPlusContributionPromptLedger',
|
||||
'isSuccessfulPlusAccountRecord',
|
||||
'getPlusContributionPromptTotals',
|
||||
'getPlusContributionPromptProgress',
|
||||
'shouldShowPlusContributionPrompt',
|
||||
'markPlusContributionPromptShown',
|
||||
'addPlusContributionPromptCredit',
|
||||
'maybeShowPlusContributionPromptBeforeAutoRun',
|
||||
]);
|
||||
|
||||
const api = new Function('records', `
|
||||
const PLUS_CONTRIBUTION_PROMPT_LEDGER_STORAGE_KEY = 'multipage-plus-contribution-prompt-ledger';
|
||||
const PLUS_CONTRIBUTION_PROMPT_THRESHOLD = 5;
|
||||
const PLUS_CONTRIBUTION_ACCOUNT_CREDIT = 5;
|
||||
const PLUS_CONTRIBUTION_DONATION_CREDIT = 20;
|
||||
const latestState = { accountRunHistory: records };
|
||||
const storage = {};
|
||||
const events = [];
|
||||
const localStorage = {
|
||||
getItem(key) { return Object.prototype.hasOwnProperty.call(storage, key) ? storage[key] : null; },
|
||||
setItem(key, value) { storage[key] = String(value); },
|
||||
};
|
||||
async function openPlusContributionSupportModal() {
|
||||
events.push({ type: 'modal' });
|
||||
return 'contribute';
|
||||
}
|
||||
function showToast(message, type) {
|
||||
events.push({ type: 'toast', message, toastType: type });
|
||||
}
|
||||
function openExternalUrl(url) {
|
||||
events.push({ type: 'open', url });
|
||||
}
|
||||
function getContributionPortalUrl() {
|
||||
return 'https://apikey.qzz.io';
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
maybeShowPlusContributionPromptBeforeAutoRun,
|
||||
getEvents() {
|
||||
return events;
|
||||
},
|
||||
};
|
||||
`)(createPlusRecords(5));
|
||||
|
||||
const result = await api.maybeShowPlusContributionPromptBeforeAutoRun(true);
|
||||
|
||||
assert.equal(result, false);
|
||||
assert.deepEqual(api.getEvents().map((event) => event.type), ['modal', 'open', 'toast']);
|
||||
assert.equal(api.getEvents()[1].url, 'https://apikey.qzz.io');
|
||||
});
|
||||
Reference in New Issue
Block a user