diff --git a/assets/Script/GameManager.ts b/assets/Script/GameManager.ts index 94f002e9..e5b0704c 100644 --- a/assets/Script/GameManager.ts +++ b/assets/Script/GameManager.ts @@ -15,6 +15,7 @@ import { MiniGameManager } from "./Sdk/MiniGameManager"; import { MiniGameSdk } from "./Sdk/MiniGameSdk"; import MiniProgramBenefitsBridge from "./module/MiniProgramBenefitsBridge"; import WucaiEntry from "./module/WucaiEntry"; +import ClientUpdate from "./module/Config/ClientUpdate"; const { ccclass, property } = cc._decorator; @@ -71,6 +72,7 @@ export default class GameManager extends cc.Component { // }); this.startTimeCutDown(); cc.fx.GameConfig.init(true); + ClientUpdate.initialize(cc.fx.GameConfig.CLIENT_UPDATE_PREVIEW); cc.fx.GameConfig.GM_INFO.sceneValue = "loadScene"; cc.fx.GameConfig.GM_INFO.gameState = false; //@ts-ignore @@ -180,6 +182,7 @@ export default class GameManager extends cc.Component { } onShow(options?: any) { + if (ClientUpdate.onShow()) return; if (options) { this.updateWucaiEntry(options); MiniProgramBenefitsBridge.instance.capture(options, "show"); @@ -242,7 +245,7 @@ export default class GameManager extends cc.Component { console.error('加载 publicUI 失败:', publicUIError); return; } - activityReady.then(() => { if (cc.isValid(this.node)) cc.director.loadScene("HomeScene"); }); + activityReady.then(() => { if (!ClientUpdate.blocked && cc.isValid(this.node)) cc.director.loadScene("HomeScene"); }); }); } @@ -299,6 +302,7 @@ export default class GameManager extends cc.Component { // console.log("_________________________abTests:", cc.fx.GameConfig.GM_INFO.abTests); } readUserData(retryCount = 0) { + if (ClientUpdate.blocked) return; const wucaiEntryId = WucaiEntry.loginEntryId; //@ts-ignore if ((typeof wx !== 'undefined' && wx !== null) || (typeof tt !== 'undefined' && tt !== null)) { @@ -316,7 +320,9 @@ export default class GameManager extends cc.Component { ]; const attemptUserInfo = () => { + if (ClientUpdate.blocked) return; Utils.getUserInfo((data) => { + if (ClientUpdate.blocked) return; if (data.code == 1) { // 假设返回数据中有 success 字段表示成功 // console.log("登錄", data); let systemInfo = null; @@ -1083,6 +1089,7 @@ export default class GameManager extends cc.Component { /** 主循环,判断是否各项加载完成进入游戏 */ update(dt) { + if (ClientUpdate.blocked) return; if (this.load1 && this.load2 && this.load3 && this.load4 && this.load5 && this.load6 == true && this.timeNumber <= 0) { this.loginShushuOnce(); if (cc.fx.GameConfig.GM_INFO.wucai_type === 1) { diff --git a/assets/Script/module/Config/ClientUpdate.ts b/assets/Script/module/Config/ClientUpdate.ts new file mode 100644 index 00000000..bb2f868e --- /dev/null +++ b/assets/Script/module/Config/ClientUpdate.ts @@ -0,0 +1,149 @@ +declare const wx: any; + +/** A terminal gate for this process. Only a real package restart clears it. */ +export default class ClientUpdate { + private static initialized = false; + private static manager: any = null; + private static state: "checking" | "downloading" | "ready" | "unavailable" = "checking"; + private static rejection: any = null; + private static dialogOpen = false; + private static waitTimer: any = null; + private static previewPanel: HTMLElement = null; + + static get blocked(): boolean { return this.rejection !== null; } + static get blockedResponse(): any { return this.rejection; } + + static initialize(simulateInPreview = false): void { + if (this.initialized) return; + this.initialized = true; + if (typeof wx !== "undefined" && typeof wx.getUpdateManager === "function") { + try { + this.manager = wx.getUpdateManager(); + this.manager.onCheckForUpdate(result => { + if (this.state === "ready") return; + this.state = result.hasUpdate ? "downloading" : "unavailable"; + if (this.blocked) this.showPrompt(); + }); + this.manager.onUpdateReady(() => { + this.state = "ready"; + if (this.blocked) this.showPrompt(); + }); + this.manager.onUpdateFailed(() => { + this.state = "unavailable"; + if (this.blocked) this.showPrompt(); + }); + } catch (_) { this.state = "unavailable"; } + } else { + this.state = "unavailable"; + } + // Local UI simulation only. Never changes the reported version or bypasses the server gate. + if (typeof CC_PREVIEW !== "undefined" && CC_PREVIEW && simulateInPreview) { + this.handleResponse({ code: 0, errorCode: "CLIENT_UPDATE_REQUIRED", msg: "强更流程预览", data: null }); + } + } + + /** Also converts late successful responses to the same error after another request blocks us. */ + static handleResponse(response: any): any { + if (!this.blocked && response?.errorCode === "CLIENT_UPDATE_REQUIRED") { + this.initialize(); + this.rejection = response; + this.freezeGame(); + this.showPrompt(); + } + return this.rejection || response; + } + + /** GameManager calls this before its normal foreground resume. */ + static onShow(): boolean { + if (!this.blocked) return false; + this.freezeGame(); + this.showPrompt(); + return true; + } + + private static freezeGame(): void { + cc.fx.GameConfig.GM_INFO.gameState = false; + const scene = cc.director.getScene(); + if (scene) scene.pauseSystemEvents(true); + cc.audioEngine.pauseAll(); + cc.game.pause(); + } + + private static clearWait(): void { + if (this.waitTimer !== null) clearTimeout(this.waitTimer); + this.waitTimer = null; + } + + private static showPrompt(): void { + if (typeof wx === "undefined" || typeof wx.showModal !== "function") { + this.showPreviewPanel(); + return; + } + if (this.state === "checking" || this.state === "downloading") { + if (this.dialogOpen) return; + wx.showLoading({ title: "正在准备更新", mask: true }); + if (this.waitTimer === null) { + this.waitTimer = setTimeout(() => { + this.waitTimer = null; + if (this.state !== "ready") { + this.state = "unavailable"; + this.showPrompt(); + } + }, 30000); + } + return; + } + this.clearWait(); + if (this.dialogOpen) return; + wx.hideLoading(); + const promptState = this.state; + const ready = promptState === "ready"; + this.dialogOpen = true; + wx.showModal({ + title: "游戏需要更新", + content: ready ? "新版本已准备好,请重启更新。更新后将自动登录。" + : "当前版本已无法继续游戏,暂未取得可用的新版本。请退出后重新进入;仍有问题请稍后再试。", + showCancel: false, + confirmText: ready ? "重启更新" : "退出游戏", + success: result => { + if (!result.confirm || this.state !== promptState) return; + if (ready) { + try { this.manager.applyUpdate(); } + catch (_) { this.state = "unavailable"; } + } else if (typeof wx.exitMiniProgram === "function") { + wx.exitMiniProgram({ fail: () => { + wx.showToast({ title: "请手动退出后重新进入", icon: "none", duration: 3000 }); + } }); + } + }, + complete: () => { + this.dialogOpen = false; + if (this.state !== promptState) { + setTimeout(() => this.showPrompt(), 0); + } else { + // Keep a visible mask even if the platform refuses to exit/restart or dismisses the modal. + wx.showLoading({ title: ready ? "请重启游戏" : "请重新进入游戏", mask: true }); + } + }, + }); + } + + private static showPreviewPanel(): void { + if (this.previewPanel || typeof document === "undefined" || !document.body) return; + const panel = document.createElement("div"); + panel.style.cssText = "position:fixed;inset:0;z-index:2147483647;background:#182036;color:#fff;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:24px;font:18px sans-serif"; + const title = document.createElement("h2"); + title.textContent = "游戏需要更新"; + const message = document.createElement("p"); + message.textContent = "请加载兼容的新版本后刷新页面。更新后将自动登录。"; + const button = document.createElement("button"); + button.textContent = "刷新页面"; + button.style.cssText = "padding:12px 28px;margin-top:20px;font:18px sans-serif;cursor:pointer"; + button.onclick = () => window.location.reload(); + panel.appendChild(title); + panel.appendChild(message); + panel.appendChild(button); + document.body.appendChild(panel); + this.previewPanel = panel; + } +} diff --git a/assets/Script/module/Config/ClientUpdate.ts.meta b/assets/Script/module/Config/ClientUpdate.ts.meta new file mode 100644 index 00000000..887281e7 --- /dev/null +++ b/assets/Script/module/Config/ClientUpdate.ts.meta @@ -0,0 +1,10 @@ +{ + "ver": "1.1.0", + "uuid": "08fb0068-e901-4e1f-a44e-a8b6068ab61a", + "importer": "typescript", + "isPlugin": false, + "loadPluginInWeb": true, + "loadPluginInNative": true, + "loadPluginInEditor": false, + "subMetas": {} +} diff --git a/assets/Script/module/Config/GameConfig.ts b/assets/Script/module/Config/GameConfig.ts index 771f27ac..03e90d41 100644 --- a/assets/Script/module/Config/GameConfig.ts +++ b/assets/Script/module/Config/GameConfig.ts @@ -15,6 +15,8 @@ interface GameplayEntryPreparation { const { ccclass, property } = cc._decorator; @ccclass('GameConfig') export class GameConfig { + // Cocos browser preview only: show the update gate without changing server policy/version reporting. + static CLIENT_UPDATE_PREVIEW = false; //所有控制信息都通过GameAppStart内控制 private static _instance: GameConfig = null; diff --git a/assets/Script/module/Pay/Utils.ts b/assets/Script/module/Pay/Utils.ts index 72e1731a..4390c8e1 100644 --- a/assets/Script/module/Pay/Utils.ts +++ b/assets/Script/module/Pay/Utils.ts @@ -2,6 +2,7 @@ import { MiniGameSdk } from "../../Sdk/MiniGameSdk"; import { normalizePass, mergePassInfo, legacyPassInfo, legacyExperience, passTier, PASS_PERIOD } from '../Config/BattlePassModel'; import { settlementRewards, settlementClaimFlags } from '../Config/BattlePassSettlementModel'; import BattlePassSettlementCheck from '../Config/BattlePassSettlementCheck'; +import ClientUpdate from '../Config/ClientUpdate'; //#region 测试 /** 测试 */ export default class Utils { @@ -42,6 +43,11 @@ export default class Utils { } private static trackWucaiRequest(path: string, body: any, callback): ((response: any) => void) | null { + if (ClientUpdate.blocked) { + // Do not start another transport or recursively invoke callers' retry handlers. + setTimeout(() => callback(ClientUpdate.blockedResponse), 0); + return null; + } if (this.wucaiRequestsBlocked && path !== "login" && path !== "wucaiTransfer") { callback({ code: 0, data: null, errorCode: "WUCAI_PREPARING", msg: "正在准备选择游戏进度" }); return null; @@ -61,6 +67,7 @@ export default class Utils { const request = new Promise(done => { resolve = done; }); this.pendingRequests.add(request); return response => { + response = ClientUpdate.handleResponse(response); const uncertain = !response || response.networkError || response.errorCode === "NETWORK_UNKNOWN"; if ((save || mayWrite) && response && response.code === 1) { this.wucaiUnconfirmedWrites.delete(writeKey); @@ -116,7 +123,8 @@ export default class Utils { xhr.open('POST', this.serverUrl() + path, true); xhr.timeout = 10000; xhr.setRequestHeader('Content-Type', 'application/json'); - xhr.send(JSON.stringify(authenticated ? { ...body, token: cc.fx.GameConfig.GM_INFO.token } : body)); + const payload = { ...body, version: cc.fx.GameConfig.GM_INFO.version }; + xhr.send(JSON.stringify(authenticated ? { ...payload, token: cc.fx.GameConfig.GM_INFO.token } : payload)); } catch (_) { fail('请求未能发出'); } } static uid: string = ""; @@ -144,7 +152,7 @@ export default class Utils { let isCallBackCalled = false; // 定义轮询函数 const pollLogin = () => { - if (isCallBackCalled) { + if (isCallBackCalled || ClientUpdate.blocked) { console.log("回调已被调用,不再发起请求"); return; } @@ -546,7 +554,7 @@ export default class Utils { xhr.onabort = networkFailure; let dataStr = ''; let isDebug = false; - param = { ...param, token: cc.fx.GameConfig.GM_INFO.token }; + param = { ...param, token: cc.fx.GameConfig.GM_INFO.token, version: cc.fx.GameConfig.GM_INFO.version }; let test = cc.fx.GameTool.getWechatGameVersion(); if (test == "正式版") { isDebug = true; diff --git a/tools/test-activity-schedule.cjs b/tools/test-activity-schedule.cjs index 976e1587..ddc7291e 100644 --- a/tools/test-activity-schedule.cjs +++ b/tools/test-activity-schedule.cjs @@ -161,7 +161,8 @@ test('cache environment resolver exactly matches POST routing in development, tr }; const Utils = load('assets/Script/module/Pay/Utils.ts', cc, { '../../Sdk/MiniGameSdk': { MiniGameSdk: {} }, '../Config/BattlePassModel': {}, - '../Config/BattlePassSettlementModel': {}, '../Config/BattlePassSettlementCheck': { default: {} } + '../Config/BattlePassSettlementModel': {}, '../Config/BattlePassSettlementCheck': { default: {} }, + '../Config/ClientUpdate': { default: { blocked: false, handleResponse: value => value } } }, () => 10000, ts.ScriptTarget.ES5); // Match the project's target for existing Utils identifiers. for (version of ['开发版', '体验版', '正式版', 'web']) { const expected = ['开发版', '体验版'].includes(version) ? Utils.testHttpip : Utils.httpip; diff --git a/tools/test-client-update.cjs b/tools/test-client-update.cjs new file mode 100644 index 00000000..fa49a1df --- /dev/null +++ b/tools/test-client-update.cjs @@ -0,0 +1,242 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const ts = require('typescript'); + +const read = file => fs.readFileSync(file, 'utf8'); +const transpile = source => ts.transpileModule(source, { compilerOptions: { + target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.CommonJS, experimentalDecorators: true, +} }).outputText; +const required = () => ({ code: 0, errorCode: 'CLIENT_UPDATE_REQUIRED', msg: '需要更新', data: { version: '1.0.84', minVersion: '1.0.83' } }); + +function fixture({ native = true, managerAvailable = true, preview = false } = {}) { + const events = {}, requests = [], dialogs = [], timers = new Map(), elements = []; + const state = { initialized: 0, applied: 0, exits: 0, paused: 0, resumed: 0, inputPaused: 0, audioPaused: 0, loading: [], reloaded: 0 }; + let id = 0; + const manager = { + onCheckForUpdate: cb => { events.check = cb; }, + onUpdateReady: cb => { events.ready = cb; }, + onUpdateFailed: cb => { events.failed = cb; }, + applyUpdate: () => { state.applied++; }, + }; + const wx = { + getUpdateManager: managerAvailable ? () => { state.initialized++; return manager; } : undefined, + showLoading: options => state.loading.push(options), hideLoading() {}, + showModal: options => dialogs.push(options), showToast() {}, + exitMiniProgram: () => { state.exits++; }, + login: options => options.success({ code: 'wx-code' }), + }; + const cc = { + game: { pause: () => { state.paused++; }, resume: () => { state.resumed++; } }, + audioEngine: { pauseAll: () => { state.audioPaused++; }, resumeAll() {} }, + director: { getScene: () => ({ pauseSystemEvents: recursive => { assert.equal(recursive, true); state.inputPaused++; } }) }, + fx: { + GameConfig: { GM_INFO: { version: '1.0.82', token: 'token', gameState: true } }, + GameTool: { getWechatGameVersion: () => '正式版', trackErrorToShushu() {} }, + }, + loader: { getXMLHttpRequest: () => ({ + open(method, url) { this.url = url; }, setRequestHeader(name, value) { this.contentType = value; }, + send(body) { this.body = body; requests.push(this); }, + respond(value) { + this.readyState = 4; this.status = 200; this.responseText = JSON.stringify(value); this.onreadystatechange(); + }, + }) }, + }; + const context = vm.createContext({ + cc, CC_PREVIEW: preview, console: { log() {}, error() {} }, exports: {}, + setTimeout: (fn, ms) => { const key = ++id; timers.set(key, { fn, ms }); return key; }, + clearTimeout: key => timers.delete(key), + window: { location: { reload: () => { state.reloaded++; } } }, + document: { body: { appendChild: element => elements.push(element) }, createElement: tag => ({ + tag, style: {}, children: [], appendChild(child) { this.children.push(child); }, + }) }, + }); + if (native) context.wx = wx; + vm.runInContext(transpile(read('assets/Script/module/Config/ClientUpdate.ts')), context); + const ClientUpdate = context.exports.default; + context.exports = {}; + const sdk = { isWechat: () => native, isBytedance: () => false, API: { showToast() {} } }; + context.require = name => name.endsWith('/ClientUpdate') ? { default: ClientUpdate } + : name.includes('MiniGameSdk') ? { MiniGameSdk: sdk } : {}; + // Existing Utils contains an unrelated U+200C method name beyond the request helpers. + const transport = read('assets/Script/module/Pay/Utils.ts').split(' static getGacha')[0] + '\n}'; + vm.runInContext(transpile(transport), context); + const Utils = context.exports.default; + const runTimers = ms => { + for (const [key, timer] of Array.from(timers)) if (ms === undefined || timer.ms === ms) { + timers.delete(key); timer.fn(); + } + }; + const answer = (dialog, confirm = true) => { dialog.success({ confirm }); dialog.complete(); }; + return { ClientUpdate, Utils, cc, wx, manager, events, requests, dialogs, state, timers, elements, context, runTimers, answer }; +} + +test('all form/JSON/authenticated/public/external business requests report the configured version', () => { + const f = fixture(); + const input = { version: 'spoofed', action: 'read' }; + f.Utils.POST('login', input, () => {}); + f.Utils.POST('userData', input, () => {}, { json: true }); + f.Utils.POSTJSON('cloudRise/index', input, () => {}); + f.Utils.POSTJSON('activityConfig/list', input, () => {}, false); + f.Utils.POST('getRank', input, () => {}); + f.Utils.POST('getAddressRankOther', input, () => {}); + assert.equal(f.requests.length, 6); + for (const xhr of f.requests) { + const body = xhr.contentType === 'application/json' ? JSON.parse(xhr.body) : Object.fromEntries(new URLSearchParams(xhr.body)); + assert.equal(body.version, '1.0.82'); + } + assert.equal(input.version, 'spoofed', 'caller object is not mutated'); + assert.equal(JSON.parse(f.requests[3].body).token, undefined); + assert.match(f.requests[4].url, /bx7gi3d4oq/); + assert.match(f.requests[5].url, /laf.nika4games.com/); +}); + +test('ordinary available updates do not interrupt a compatible player', () => { + const f = fixture(); + f.ClientUpdate.initialize(); f.ClientUpdate.initialize(); + f.events.check({ hasUpdate: true }); f.events.ready(); + const response = { code: 1, data: {} }; + assert.equal(f.ClientUpdate.handleResponse(response), response); + assert.equal(f.state.initialized, 1); + assert.equal(f.ClientUpdate.blocked, false); + assert.equal(f.dialogs.length, 0); + assert.equal(f.state.applied, 0); +}); + +test('required update freezes gameplay, waits for readiness, and applies only on restart confirmation', () => { + const f = fixture(); + f.ClientUpdate.initialize(); + f.events.check({ hasUpdate: true }); + f.ClientUpdate.handleResponse(required()); + assert.equal(f.ClientUpdate.blocked, true); + assert.equal(f.cc.fx.GameConfig.GM_INFO.gameState, false); + assert.equal(f.state.paused, 1); assert.equal(f.state.inputPaused, 1); + assert.equal(f.dialogs.length, 0); assert.equal(f.state.applied, 0); + f.events.ready(); + assert.equal(f.dialogs.length, 1); + assert.equal(f.dialogs[0].showCancel, false); + assert.equal(f.dialogs[0].confirmText, '重启更新'); + f.ClientUpdate.handleResponse(required()); f.ClientUpdate.onShow(); + assert.equal(f.dialogs.length, 1, 'parallel responses/foreground events cannot duplicate the modal'); + f.answer(f.dialogs[0]); + assert.equal(f.state.applied, 1); assert.equal(f.ClientUpdate.blocked, true); + assert.equal(f.state.resumed, 0); + assert.equal(f.timers.size, 0); +}); + +test('an already downloaded update is offered immediately after a server rejection', () => { + const f = fixture(); + f.ClientUpdate.initialize(); f.events.ready(); f.ClientUpdate.handleResponse(required()); + assert.equal(f.dialogs[0].confirmText, '重启更新'); + assert.equal(f.state.applied, 0); +}); + +test('late successes are converted to the gate error and further requests never reach the network', () => { + const f = fixture(), callbacks = []; + f.Utils.POST('login', {}, value => callbacks.push(value)); + f.Utils.POSTJSON('userCoin', {}, value => callbacks.push(value)); + f.requests[0].respond(required()); + f.requests[1].respond({ code: 1, data: { coin: 999 } }); + f.Utils.POST('userData', {}, value => callbacks.push(value)); + f.Utils.POSTJSON('cloudRise/index', {}, value => callbacks.push(value)); + f.runTimers(0); + assert.equal(f.requests.length, 2); + assert.equal(callbacks.length, 4); + assert(callbacks.every(value => value.errorCode === 'CLIENT_UPDATE_REQUIRED')); + assert.equal(f.Utils.pendingRequests.size, 0, 'existing request bookkeeping must still settle'); + f.requests[0].onerror(); assert.equal(callbacks.length, 4, 'transport completion remains once-only'); +}); + +test('a JSON upgrade response activates the same global gate', () => { + const f = fixture(); + let response; + f.Utils.POSTJSON('cloudRise/index', {}, value => { response = value; }); + f.requests[0].respond(required()); + assert.equal(response.errorCode, 'CLIENT_UPDATE_REQUIRED'); + assert.equal(f.ClientUpdate.blocked, true); +}); + +test('unavailable, failed, timed-out and unsupported updates never unblock or apply an unready package', () => { + for (const mode of ['unavailable', 'failed', 'timeout', 'unsupported']) { + const f = fixture({ managerAvailable: mode !== 'unsupported' }); + f.ClientUpdate.initialize(); + if (mode === 'unavailable') f.events.check({ hasUpdate: false }); + if (mode === 'failed') f.events.failed(); + f.ClientUpdate.handleResponse(required()); + if (mode === 'timeout') f.runTimers(30000); + assert.equal(f.dialogs.length, 1, mode); + assert.equal(f.dialogs[0].confirmText, '退出游戏', mode); + f.answer(f.dialogs[0]); + assert.equal(f.state.exits, 1); assert.equal(f.state.applied, 0); + assert.equal(f.ClientUpdate.blocked, true); + } +}); + +test('readiness while an unavailable modal is open replaces the prompt before any action', () => { + const f = fixture(); + f.ClientUpdate.initialize(); f.events.failed(); f.ClientUpdate.handleResponse(required()); + f.events.ready(); + assert.equal(f.dialogs.length, 1); + f.answer(f.dialogs[0]); f.runTimers(0); + assert.equal(f.state.exits, 0); assert.equal(f.state.applied, 0); + assert.equal(f.dialogs[1].confirmText, '重启更新'); + f.answer(f.dialogs[1]); assert.equal(f.state.applied, 1); +}); + +test('configuration errors remain ordinary retryable service errors and do not activate update UI', () => { + const f = fixture(); + const response = { code: 0, errorCode: 'CLIENT_UPDATE_CONFIG_UNAVAILABLE', msg: '服务暂不可用' }; + assert.equal(f.ClientUpdate.handleResponse(response), response); + assert.equal(f.ClientUpdate.blocked, false); assert.equal(f.dialogs.length, 0); +}); + +test('a failed applyUpdate remains blocked and offers exit instead of repeatedly applying', () => { + const f = fixture(); + f.ClientUpdate.initialize(); f.events.ready(); f.ClientUpdate.handleResponse(required()); + f.manager.applyUpdate = () => { throw Error('platform restart failed'); }; + f.answer(f.dialogs[0]); f.runTimers(0); + assert.equal(f.ClientUpdate.blocked, true); + assert.equal(f.dialogs[1].confirmText, '退出游戏'); + assert.equal(f.state.resumed, 0); +}); + +test('browser preview has a persistent refresh screen; the simulation switch cannot affect release builds', () => { + const f = fixture({ native: false, preview: true }); + f.ClientUpdate.initialize(true); + assert.equal(f.ClientUpdate.blocked, true); assert.equal(f.elements.length, 1); + f.ClientUpdate.onShow(); assert.equal(f.elements.length, 1); + const button = f.elements[0].children.find(child => child.tag === 'button'); + button.onclick(); assert.equal(f.state.reloaded, 1); + const release = fixture(); release.ClientUpdate.initialize(true); + assert.equal(release.ClientUpdate.blocked, false); +}); + +test('login polling stops after upgrade, and a fresh process can log in normally', () => { + const f = fixture(); let result; + f.Utils.getUserInfo(value => { result = value; }); + assert.equal(f.requests.length, 1); + f.requests[0].respond(required()); f.runTimers(6000); + assert.equal(result.errorCode, 'CLIENT_UPDATE_REQUIRED'); assert.equal(f.requests.length, 1); + const restarted = fixture(); let loggedIn = false; + restarted.Utils.getUserInfo(value => { loggedIn = value.code === 1; }); + restarted.requests[0].respond({ code: 1, data: { _id: 'u', openid: 'o', session_key: 's' } }); + assert.equal(loggedIn, true); assert.equal(restarted.ClientUpdate.blocked, false); +}); + +test('GameManager guards foreground resume, login retry entry, load completion and scene transition', () => { + const f = fixture(); + const source = ts.createSourceFile('GameManager.ts', read('assets/Script/GameManager.ts'), 99, true); + const cls = source.statements.find(ts.isClassDeclaration); + const methods = ['onShow', 'readUserData', 'update'].map(name => cls.members.find(member => member.name?.getText(source) === name).getText(source)).join('\n'); + f.context.ClientUpdate = f.ClientUpdate; + vm.runInContext(transpile(`class Manager { ${methods} }; globalThis.Manager = Manager;`), f.context); + f.ClientUpdate.handleResponse(required()); + const instance = new f.context.Manager(); + instance.onShow(); instance.readUserData(); instance.update(1); + assert.equal(f.state.resumed, 0); + assert.equal(f.requests.length, 0); + const text = read('assets/Script/GameManager.ts'); + assert.match(text, /if \(!ClientUpdate\.blocked && cc\.isValid\(this\.node\)\) cc\.director\.loadScene/); + assert.match(text, /const attemptUserInfo = \(\) => \{\s*if \(ClientUpdate\.blocked\) return;/); +}); diff --git a/tools/test-wucai-request-barrier.cjs b/tools/test-wucai-request-barrier.cjs index 8f911d6f..e74711c5 100644 --- a/tools/test-wucai-request-barrier.cjs +++ b/tools/test-wucai-request-barrier.cjs @@ -39,7 +39,8 @@ function fixture() { const exports = {}; vm.runInNewContext(source, { exports, cc, wx: {}, console, setTimeout, - require: name => name.includes('MiniGameSdk') ? { MiniGameSdk: { API: { showToast() {} } } } : {}, + require: name => name.endsWith('/ClientUpdate') ? { default: { blocked: false, handleResponse: value => value } } + : name.includes('MiniGameSdk') ? { MiniGameSdk: { API: { showToast() {} } } } : {}, }); return { Utils: exports.default, requests, cc, failNextSend: () => { failSend = true; } }; }