diff --git a/assets/GameplayIntro/compressed.meta b/assets/GameplayIntro/compressed.meta new file mode 100644 index 00000000..1b20b99c --- /dev/null +++ b/assets/GameplayIntro/compressed.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.3", + "uuid": "ed02622f-2754-4652-93d3-b026960fb8cd", + "importer": "folder", + "isBundle": false, + "bundleName": "", + "priority": 1, + "compressionType": {}, + "optimizeHotUpdate": {}, + "inlineSpriteFrames": {}, + "isRemoteBundle": {}, + "subMetas": {} +} \ No newline at end of file diff --git a/assets/Script/PyramidView.ts b/assets/Script/PyramidView.ts index 69429c44..a69e7506 100644 --- a/assets/Script/PyramidView.ts +++ b/assets/Script/PyramidView.ts @@ -130,12 +130,25 @@ export default class PyramidView extends cc.Component { }); } private async open(reminder?: PyramidDailyReminder): Promise { - if (this.overlay || this.opening || this.settlementQueued) return; this.opening = true; + console.log("openPyramid"); + console.log("open1"); + console.log(this.node); + const alive = () => cc.isValid(this, true) && cc.isValid(this.node, true); + console.log(alive()); + console.log(this.overlay); + console.log(this.opening); + console.log(this.settlementQueued); + if (!alive() || this.overlay || this.opening || this.settlementQueued) return; this.opening = true; // Prepare automatic reminders silently; only an explicit click shows Loading. - const stopLoading = reminder ? () => {} : this.startLoading(); + console.log("openLoading"); + const stopLoading = reminder ? () => { } : this.startLoading(); try { - this.releaseResources = await Service.acquireResources(); + console.log("try"); + const release = await Service.acquireResources(); + if (!alive()) { release(); return; } + this.releaseResources = release; const [synced, prefab] = await Promise.all([Service.sync(), Service.prefab()]); + if (!alive()) return; const state = Service.data(); if (!synced && !reminder && typeof window !== "undefined" && (window as any).wx) (window as any).wx.showToast({ title: Service.error || "活动信息暂时无法获取", icon: "none" }); @@ -145,23 +158,33 @@ export default class PyramidView extends cc.Component { this.node.addChild(this.overlay); this.overlay.zIndex = 2000; const panel: any = this.overlay.getComponent("PyramidPanel"); await panel.initialize(this.closeOverlay); + if (!alive()) return; + if (!cc.isValid(panel, true) || !cc.isValid(this.overlay, true)) { this.closeOverlay(); return; } if (reminder && !this.reminderCurrent(reminder)) { this.closeOverlay(); return; } if (this.overlay && cc.isValid(this.overlay, true)) { this.overlay.active = true; if (reminder) ActivityScheduleService.markPyramidReminderShown(reminder); } } catch (error) { - cc.warn("[Pyramid] 界面加载失败", error); - this.closeOverlay(); + console.log("catch"); + console.log(error); + if (alive()) { + cc.warn("[Pyramid] 界面加载失败", error); + this.closeOverlay(); + } } finally { - stopLoading(); this.opening = false; this.syncPaymentLoading(); - if (!this.overlay && this.releaseResources) { this.releaseResources(); this.releaseResources = null; } - if (!this.overlay && this.finishReminder) this.closeOverlay(); + console.log("finally"); + stopLoading(); + if (alive()) { + this.opening = false; this.syncPaymentLoading(); + if (!this.overlay && this.releaseResources) { this.releaseResources(); this.releaseResources = null; } + if (!this.overlay && this.finishReminder) this.closeOverlay(); + } } } private startLoading(): () => void { const template = this.node.getChildByName("Loading"); - if (!template || !template.parent) return () => {}; + if (!template || !template.parent) return () => { }; const parent = template.parent, size = parent.getContentSize(); const factor = Math.min(1, size.width / 1080, size.height / 1920); const viewport = new cc.Node("PyramidLoading"); diff --git a/assets/Script/module/Config/GameConfig.ts b/assets/Script/module/Config/GameConfig.ts index 748f36bb..035acda6 100644 --- a/assets/Script/module/Config/GameConfig.ts +++ b/assets/Script/module/Config/GameConfig.ts @@ -771,7 +771,7 @@ export class GameConfig { vibrateOpen: true, //震动 coinnum: 0, //每局的金币数 paid_user: false, //是否是付费用户 - version: "1.0.84", //版本号 + version: "1.0.85", //版本号 shushu_DistinctId: "", //数数访客ID shushu_AccountId: "", //数数账号ID uid: "", //用户和后端唯一id diff --git a/assets/gacha_bundle/compressed.meta b/assets/gacha_bundle/compressed.meta new file mode 100644 index 00000000..c58b69ba --- /dev/null +++ b/assets/gacha_bundle/compressed.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.3", + "uuid": "80678d32-cc82-4c0c-9004-af929fa2a1bd", + "importer": "folder", + "isBundle": false, + "bundleName": "", + "priority": 1, + "compressionType": {}, + "optimizeHotUpdate": {}, + "inlineSpriteFrames": {}, + "isRemoteBundle": {}, + "subMetas": {} +} \ No newline at end of file diff --git a/assets/gacha_bundle/img/cat.meta b/assets/gacha_bundle/img/cat.meta new file mode 100644 index 00000000..85ec429f --- /dev/null +++ b/assets/gacha_bundle/img/cat.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.3", + "uuid": "a6fe7c1d-9f4a-41ca-bf25-d16ae4c4f48d", + "importer": "folder", + "isBundle": false, + "bundleName": "", + "priority": 1, + "compressionType": {}, + "optimizeHotUpdate": {}, + "inlineSpriteFrames": {}, + "isRemoteBundle": {}, + "subMetas": {} +} \ No newline at end of file diff --git a/assets/libs/dn-sdk-minigame.meta b/assets/libs/dn-sdk-minigame.meta new file mode 100644 index 00000000..f84ec953 --- /dev/null +++ b/assets/libs/dn-sdk-minigame.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.3", + "uuid": "6cd4858b-849d-49fb-8a08-1cd296c2d768", + "importer": "folder", + "isBundle": false, + "bundleName": "", + "priority": 1, + "compressionType": {}, + "optimizeHotUpdate": {}, + "inlineSpriteFrames": {}, + "isRemoteBundle": {}, + "subMetas": {} +} \ No newline at end of file diff --git a/assets/passCheck/script.meta b/assets/passCheck/script.meta new file mode 100644 index 00000000..98bb30d7 --- /dev/null +++ b/assets/passCheck/script.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.3", + "uuid": "23f1f7f1-3041-436d-9f89-1a35e1a004b4", + "importer": "folder", + "isBundle": false, + "bundleName": "", + "priority": 1, + "compressionType": {}, + "optimizeHotUpdate": {}, + "inlineSpriteFrames": {}, + "isRemoteBundle": {}, + "subMetas": {} +} \ No newline at end of file diff --git a/assets/propWindow/compressed.meta b/assets/propWindow/compressed.meta new file mode 100644 index 00000000..c7887801 --- /dev/null +++ b/assets/propWindow/compressed.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.3", + "uuid": "a15ece85-8805-4499-8297-2601c01d0d42", + "importer": "folder", + "isBundle": false, + "bundleName": "", + "priority": 1, + "compressionType": {}, + "optimizeHotUpdate": {}, + "inlineSpriteFrames": {}, + "isRemoteBundle": {}, + "subMetas": {} +} \ No newline at end of file diff --git a/assets/pyramid/scripts/PyramidPanel.ts b/assets/pyramid/scripts/PyramidPanel.ts index 45b8de70..c2bdbca3 100644 --- a/assets/pyramid/scripts/PyramidPanel.ts +++ b/assets/pyramid/scripts/PyramidPanel.ts @@ -65,7 +65,11 @@ export default class PyramidPanel extends cc.Component { this.debugSession = new PyramidAnimationDebug(source, identity); return this.debugSession.state; } + private isAlive(): boolean { + return cc.isValid(this, true) && cc.isValid(this.node, true); + } async initialize(close: () => void): Promise { + if (!this.isAlive()) return; this.closing = close; this.design = this.node.getChildByName("Design"); this.summitGlow = this.design.getChildByName("SummitGlow"); this.rewardRoot = this.design.getChildByName("Rewards"); this.tip = this.design.getChildByName("Tooltip"); @@ -75,7 +79,9 @@ export default class PyramidPanel extends cc.Component { const graphics = shield.addComponent(cc.Graphics); graphics.fillColor = new cc.Color(0, 0, 0, 165); graphics.rect(-size.width / 2, -size.height / 2, size.width, size.height); graphics.fill(); shield.addComponent(cc.BlockInputEvents); this.node.addComponent(cc.BlockInputEvents); - this.bundle = await Service.bundle(); + const bundle = await Service.bundle().catch(error => { if (this.isAlive()) throw error; return null; }); + if (!this.isAlive()) return; + this.bundle = bundle; if (this.goodsFrames.length !== GOODS_IDS.length || this.movingGoodsFrames.length !== GOODS_IDS.length || !this.hourFrame || !this.minuteFrame) throw new Error("金字塔新版奖励素材配置不完整"); if (this.countdownFrames.length !== 10 || !this.countdownBackgroundFrame) @@ -87,14 +93,15 @@ export default class PyramidPanel extends cc.Component { for (let i = 1; i <= 5; i++) paths.push("row-" + i); for (let i = 0; i < 10; i++) paths.push("digits/" + i); await Promise.all(paths.map(path => new Promise((resolve, reject) => this.bundle.load("art/" + path, cc.SpriteFrame, (err, frame: cc.SpriteFrame) => { + if (!this.isAlive()) { resolve(); return; } if (err) { reject(err); return; } this.frames[path] = frame; resolve(); - })))); - if (!cc.isValid(this.node, true)) return; + })))).catch(error => { if (this.isAlive()) throw error; }); + if (!this.isAlive()) return; for (let i = 0; i < 10; i++) this.digits[i] = this.frames["digits/" + i]; if (!this.countPrefixFrame) throw new Error("金字塔缺少数量前缀 x 图片"); this.digits.x = this.countPrefixFrame; if (this.state() && this.state().canPay) await this.ensurePriceAssets(); - if (!cc.isValid(this.node, true)) return; + if (!this.isAlive()) return; this.design.getChildByName("Free").getComponent(cc.Sprite).spriteFrame = this.frames.free; this.button("Close", () => { if (!Service.deliveryBusy && !this.animation && !this.drawing) this.closing(); }); this.button("Help", () => { void this.help(); }); @@ -166,41 +173,60 @@ export default class PyramidPanel extends cc.Component { return node; } private ensurePriceAssets(): Promise { + if (!this.isAlive()) return Promise.resolve(); if (this.price["0"]) return Promise.resolve(); if (!this.priceTask) { this.priceError = false; this.priceTask = Promise.all(Array.from({ length: 10 }, (_, i) => new Promise((resolve, reject) => { this.bundle.load("art/price/" + i, cc.SpriteFrame, (error, frame: cc.SpriteFrame) => { + if (!this.isAlive()) { resolve(); return; } if (error) { reject(error); return; } this.price[i] = frame; resolve(); }); - }))).then(() => { }).catch(error => { this.priceTask = null; this.priceError = true; throw error; }); + }))).then(() => { }).catch(error => { + if (!this.isAlive()) return; + this.priceTask = null; this.priceError = true; throw error; + }); } return this.priceTask; } private ensureProbabilityAssets(): Promise { + if (!this.isAlive()) return Promise.resolve(); if (this.probabilityDigits["0"] && this.continueFrame && this.continueMaterial) return Promise.resolve(); if (!this.probabilityTask) { const paths = ["probability/background", "probability/title", "probability/point", "probability/percent"]; for (let i = 0; i < 10; i++) paths.push("probability/" + i); const pyramidAssets = Promise.all(paths.map(path => new Promise((resolve, reject) => { this.bundle.load("art/" + path, cc.SpriteFrame, (error, frame: cc.SpriteFrame) => { + if (!this.isAlive()) { resolve(); return; } if (error) { reject(error); return; } this.frames[path] = frame; resolve(); }); }))); const sharedAssets = new Promise((resolve, reject) => { - cc.assetManager.loadBundle("cloud_rise_home", (error, bundle) => error ? reject(error) : resolve(bundle)); - }).then(bundle => Promise.all([ - new Promise((resolve, reject) => bundle.load("images/continue", cc.SpriteFrame, (error, frame: cc.SpriteFrame) => { - if (error) { reject(error); return; } this.continueFrame = frame; resolve(); - })), - new Promise((resolve, reject) => bundle.load("images/continue_outline", cc.Material, (error, material: cc.Material) => { - if (error) { reject(error); return; } this.continueMaterial = material; resolve(); - })) - ])); + cc.assetManager.loadBundle("cloud_rise_home", (error, bundle) => { + if (!this.isAlive()) { resolve(null); return; } + error ? reject(error) : resolve(bundle); + }); + }).then(bundle => { + if (!this.isAlive()) return; + return Promise.all([ + new Promise((resolve, reject) => bundle.load("images/continue", cc.SpriteFrame, (error, frame: cc.SpriteFrame) => { + if (!this.isAlive()) { resolve(); return; } + if (error) { reject(error); return; } this.continueFrame = frame; resolve(); + })), + new Promise((resolve, reject) => bundle.load("images/continue_outline", cc.Material, (error, material: cc.Material) => { + if (!this.isAlive()) { resolve(); return; } + if (error) { reject(error); return; } this.continueMaterial = material; resolve(); + })) + ]); + }); this.probabilityTask = Promise.all([pyramidAssets, sharedAssets]).then(() => { + if (!this.isAlive()) return; for (let i = 0; i < 10; i++) this.probabilityDigits[i] = this.frames["probability/" + i]; this.probabilityDigits["."] = this.frames["probability/point"]; this.probabilityDigits["%"] = this.frames["probability/percent"]; - }).catch(error => { this.probabilityTask = null; throw error; }); + }).catch(error => { + if (!this.isAlive()) return; + this.probabilityTask = null; throw error; + }); } return this.probabilityTask; } @@ -291,7 +317,7 @@ export default class PyramidPanel extends cc.Component { }); } private render(): void { - if (!this.ready || !cc.isValid(this.node, true)) return; + if (!this.ready || !this.isAlive()) return; const s = this.state(); if (!s) return; const signature = JSON.stringify([s.revision, s.periodId, s.currentLevel]); if (signature !== this.signature && !this.drawing) { @@ -399,12 +425,13 @@ export default class PyramidPanel extends cc.Component { this.tip.setSiblingIndex(this.design.childrenCount - 1); } private async help(): Promise { + if (!this.isAlive()) return; const help = this.design.getChildByName("Help"), button = help && help.getComponent(cc.Button); if (button) button.interactable = false; try { await this.ensureProbabilityAssets(); } catch (error) { cc.warn("[Pyramid] 概率资源加载失败", error); return; } - finally { if (button && cc.isValid(button.node, true)) button.interactable = true; } - if (!cc.isValid(this.node, true)) return; + finally { if (this.isAlive() && cc.isValid(button, true) && cc.isValid(button.node, true)) button.interactable = true; } + if (!this.isAlive()) return; const state = this.state(), level = state && state.levels.find(l => l.level === state.currentLevel); if (!level) return; this.tip.active = false; this.closeHelp(); @@ -538,7 +565,7 @@ export default class PyramidPanel extends cc.Component { } /** Presentation only: tuning the reward reveal must never change the player's inventory. */ private async animateRewards(goods: Array<{ id: number; count: number }>): Promise { - if (!goods.length) return; + if (!this.isAlive() || !goods.length) return; const types = { 1001: "coin", 2001: "freeze", 2002: "hammer", 2003: "magic", 2005: "infinite_health" }; const rewards: Array<{ type: string; count: number; spriteFrame: cc.SpriteFrame }> = []; goods.forEach(good => { @@ -547,12 +574,19 @@ export default class PyramidPanel extends cc.Component { else rewards.push({ type, count: good.count, spriteFrame: this.movingGoodsFrames[GOODS_IDS.indexOf(good.id)] }); }); const bundle = cc.assetManager.getBundle("publicUI") || await new Promise((resolve, reject) => { - cc.assetManager.loadBundle("publicUI", (error, loaded) => error ? reject(error) : resolve(loaded)); - }); + cc.assetManager.loadBundle("publicUI", (error, loaded) => { + if (!this.isAlive()) { resolve(null); return; } + error ? reject(error) : resolve(loaded); + }); + }).catch(error => { if (this.isAlive()) throw error; return null; }); + if (!this.isAlive()) return; const prefab = await new Promise((resolve, reject) => { - bundle.load("prefab/RewardWindow", cc.Prefab, (error, loaded: cc.Prefab) => error ? reject(error) : resolve(loaded)); - }); - if (!cc.isValid(this.node, true)) return; + bundle.load("prefab/RewardWindow", cc.Prefab, (error, loaded: cc.Prefab) => { + if (!this.isAlive()) { resolve(null); return; } + error ? reject(error) : resolve(loaded); + }); + }).catch(error => { if (this.isAlive()) throw error; return null; }); + if (!this.isAlive()) return; // Use the battle-pass reward prefab and its own reveal/click-to-close animation. const overlay = cc.instantiate(prefab); this.node.addChild(overlay); overlay.setPosition(0, 0); overlay.zIndex = 1001; this.rewardAnimation = overlay; diff --git a/assets/res/shop.meta b/assets/res/shop.meta new file mode 100644 index 00000000..5dc7ceb0 --- /dev/null +++ b/assets/res/shop.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.3", + "uuid": "3ff1f0a3-8ad2-4b8f-bf5b-649d8bdf1aba", + "importer": "folder", + "isBundle": false, + "bundleName": "", + "priority": 1, + "compressionType": {}, + "optimizeHotUpdate": {}, + "inlineSpriteFrames": {}, + "isRemoteBundle": {}, + "subMetas": {} +} \ No newline at end of file diff --git a/assets/win/compressed.meta b/assets/win/compressed.meta new file mode 100644 index 00000000..65d28b8e --- /dev/null +++ b/assets/win/compressed.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.3", + "uuid": "88e93e58-0939-475f-aca7-a7fe765b9c54", + "importer": "folder", + "isBundle": false, + "bundleName": "", + "priority": 1, + "compressionType": {}, + "optimizeHotUpdate": {}, + "inlineSpriteFrames": {}, + "isRemoteBundle": {}, + "subMetas": {} +} \ No newline at end of file diff --git a/docs/activity-bundles.md b/docs/activity-bundles.md index 652d934d..db449d42 100644 --- a/docs/activity-bundles.md +++ b/docs/activity-bundles.md @@ -48,7 +48,7 @@ Bundle 配置文件名、版本及逐文件校验信息存于 ZIP 内的 `bundle - 登录至首次首页共享一个资源检查周期;之后每次返回首页、切回前台开启新周期。一个周期内,各活动共享一个清单请求,同一 Bundle 共享加载任务。持续停留和倒计时不发起网络请求。 - 缓存按资源服务器地址、Bundle 名、ZIP 哈希隔离。哈希相同且每个文件的大小、SHA-256 和 Bundle 配置都正确时使用本地解压目录;缺失或损坏时重新下载。 - ZIP 先下载到新的暂存目录,核对大小、实际 SHA-256 和归档路径后解压,再验证文件和配置。全部成功才更新该 Bundle 的缓存记录。失败只删除该暂存目录,不覆盖旧记录、不清除其他活动缓存。 -- 清单或 ZIP 失败在当前周期内共享失败结果,防止每次 render 都重试;下次返回首页或切回前台重新检查。不能获取新清单时不自行猜测远端版本,旧磁盘缓存保留。 +- 清单请求、解析或校验失败时,允许使用本地缓存继续加载,但仍校验缓存归属、内部清单哈希及每个文件的完整性;没有有效缓存则失败,不猜测远端版本、不下载或改写缓存记录。同周期共享加载结果,下次返回首页或切回前台重新检查清单。正常清单缺少活动条目或 ZIP 加载失败时仍报错,不回退旧缓存。 - 活动页面与进行中的 Prefab 预加载持有资源引用。新哈希可先下载,但使用中的 Bundle 保持有效,引用释放后下次加载才切换。切换时清理本 Bundle 的旧内存资源,不调用全局清缓存。 - 只有一份本次客户端支持的接入名单;未来接入其他活动时添加 Bundle 名、接入其开放判断和页面引用生命周期,再完整构建。 diff --git a/packages/activity-bundles/pack.js b/packages/activity-bundles/pack.js index faf7f907..6209c576 100644 --- a/packages/activity-bundles/pack.js +++ b/packages/activity-bundles/pack.js @@ -18,7 +18,7 @@ function pack(destination, bundles = names) { for (const name of bundles) { if (!/^[a-z][a-zA-Z0-9_]*$/.test(name) || manifest.bundles[name]) throw Error('Invalid or duplicate bundle name'); if (!(settings.remoteBundles || []).includes(name)) throw Error('Activity must be a remote bundle: ' + name); - const version = settings.bundleVers[name] || '', configFile = 'config.' + (version ? version + '.' : '') + 'json'; + const version = (settings.bundleVers || {})[name] || '', configFile = 'config.' + (version ? version + '.' : '') + 'json'; const folder = path.join(root, 'remote', name), config = JSON.parse(fs.readFileSync(path.join(folder, configFile), 'utf8')); if (config.name !== name || config.isZip) throw Error('Use Merge All JSON for ' + name); if (!fs.existsSync(path.join(root, 'src/scripts', name, 'index.js'))) throw Error('Missing local bundle script: ' + name); diff --git a/packages/activity-bundles/runtime.js b/packages/activity-bundles/runtime.js index 25e3c18c..52ddcdd0 100644 --- a/packages/activity-bundles/runtime.js +++ b/packages/activity-bundles/runtime.js @@ -97,12 +97,15 @@ function checkArchive(bytes) { } async function directory(name, entry) { const previous = cached(name); - if (previous && previous.hash === entry.hash && digest(previous.metadataHash) && owned(previous.dir, name, entry.hash)) { + if (previous && digest(previous.hash) && (!entry || previous.hash === entry.hash) + && digest(previous.metadataHash) && owned(previous.dir, name, previous.hash)) { try { const { metadata } = await readMetadata(previous.dir, name, previous.metadataHash); await complete(previous.dir, name, metadata); return { dir: previous.dir, metadata }; - } catch (_) { /* Repair only this bundle. */ } + } catch (error) { if (!entry) throw error; /* Repair only this bundle when the manifest is available. */ } } + // Without a manifest, only verified disk cache is usable; never guess a download URL. + if (!entry) throw Error('活动资源清单不可用且无有效缓存:' + name); const stage = root + '/' + name + '/' + entry.hash + '/' + Date.now().toString(36) + '-' + (++sequence); const dir = stage + '/' + name, zipFile = stage + '/archive.zip'; try { @@ -112,6 +115,14 @@ async function directory(name, entry) { const { data } = await call('readFile', { filePath: zipFile }); if (data.byteLength !== entry.size || sha256(data) !== entry.hash) throw Error('活动分包 SHA-256 校验失败'); const archivePaths = checkArchive(new Uint8Array(data)); + // Create parents explicitly instead of relying on native unzip to create them. + const directories = new Set(); + for (const file of archivePaths) { + const index = file.lastIndexOf('/'); + if (index > 0) directories.add(file.slice(0, index)); + } + for (const relative of directories) + await call('mkdir', { dirPath: dir + '/' + relative, recursive: true }); await call('unzip', { zipFilePath: zipFile, targetPath: dir }); const { metadata, metadataHash } = await readMetadata(dir, name); if (archivePaths.size !== metadata.files.length + 1 || metadata.files.some(file => !archivePaths.has(file.path))) @@ -141,13 +152,13 @@ async function activate(name, entry, dir) { function ensureBundle(name) { if (!config.bundles.includes(name)) return Promise.reject(Error('活动尚未接入公共分包:' + name)); if (tasks.has(name)) return tasks.get(name); - const selectedCycle = cycle, selectedManifest = manifest(), preceding = serial.get(name); + const selectedCycle = cycle, selectedManifest = manifest().catch(() => null), preceding = serial.get(name); const task = (async () => { // Different lifecycle cycles for the same bundle cannot replace each other's pointer out of order. const [data] = await Promise.all([selectedManifest, preceding && preceding.catch(() => {})]); if (selectedCycle !== cycle) throw Error('活动资源检查周期已更新'); - const entry = data.bundles[name]; - if (!entry) throw Error('公共清单未配置活动资源:' + name); + const entry = data && data.bundles[name]; + if (data && !entry) throw Error('公共清单未配置活动资源:' + name); const { dir, metadata } = await directory(name, entry); if (selectedCycle !== cycle) throw Error('活动资源检查周期已更新'); return activate(name, metadata, dir); diff --git a/packages/cloud-rise-package/pack.js b/packages/cloud-rise-package/pack.js index 6e9b4d6f..e0137202 100644 --- a/packages/cloud-rise-package/pack.js +++ b/packages/cloud-rise-package/pack.js @@ -20,27 +20,28 @@ function pack(destination, versionFile = path.join(__dirname, '../../assets/clou const context = { window: {} }; vm.runInNewContext(fs.readFileSync(settingsFile, 'utf8'), context); const settings = context.window._CCSettings; - if (!settings || !settings.bundleVers) throw Error('Missing Creator bundle settings'); + if (!settings) throw Error('Missing Creator bundle settings'); const server = String(settings.server || '').replace(/\/+$/, ''); if (!/^https:\/\/[^\s?#]+$/.test(server)) throw Error('Configure the WeChat HTTPS resource server before building Cloud Rise'); const entries = []; for (const name of names) { - const folder = path.join(remote, name), version = settings.bundleVers[name]; - if (!version || !fs.existsSync(path.join(folder, 'config.' + version + '.json'))) { - throw Error('Missing remote Cloud Rise bundle (enable MD5 Cache): ' + name); + const folder = path.join(remote, name), version = (settings.bundleVers || {})[name] || ''; + const configFile = 'config.' + (version ? version + '.' : '') + 'json'; + if (!fs.existsSync(path.join(folder, configFile))) { + throw Error('Missing remote Cloud Rise bundle: ' + name + ' (' + configFile + ')'); } if (!(settings.remoteBundles || []).includes(name)) throw Error('Cloud Rise must be a remote bundle: ' + name); - const config = JSON.parse(fs.readFileSync(path.join(folder, 'config.' + version + '.json'), 'utf8')); + const config = JSON.parse(fs.readFileSync(path.join(folder, configFile), 'utf8')); if (config.name !== name || config.isZip) throw Error('Use Merge All JSON for independent remote bundles: ' + name); if (!fs.existsSync(path.join(root, 'src/scripts', name, 'index.js'))) { throw Error('Missing locally shipped Creator bundle script: ' + name); } for (const file of files(folder)) { - if (path.dirname(file) === folder && /^config\..*\.json$/.test(path.basename(file)) - && path.basename(file) !== 'config.' + version + '.json') continue; + if (path.dirname(file) === folder && /^config(?:\..*)?\.json$/.test(path.basename(file)) + && path.basename(file) !== configFile) continue; if (/\.js$/i.test(file)) throw Error('Executable scripts must remain in the client package: ' + file); const relative = path.relative(folder, file).replace(/\\/g, '/'); - const isConfig = relative === 'config.' + version + '.json'; + const isConfig = relative === configFile; // A fixed entry point avoids a separate manifest of Creator's config hashes. const target = isConfig ? 'config.json' : relative; const data = isConfig ? Buffer.from(JSON.stringify(Object.assign({}, config, { cloudRiseVersion: release.version }))) : fs.readFileSync(file); diff --git a/settings/builder.json b/settings/builder.json index 3e5e6f95..bde1e55d 100644 --- a/settings/builder.json +++ b/settings/builder.json @@ -15,7 +15,7 @@ "mainCompressionType": "subpackage", "mainIsRemote": false, "optimizeHotUpdate": false, - "md5Cache": true, + "md5Cache": false, "nativeMd5Cache": true, "encryptJs": true, "xxteaKey": "07ac496c-82b0-4f", diff --git a/tools/test-activity-bundles.cjs b/tools/test-activity-bundles.cjs index 5ee862f9..e885cf7e 100644 --- a/tools/test-activity-bundles.cjs +++ b/tools/test-activity-bundles.cjs @@ -3,18 +3,18 @@ const path = require('node:path'), vm = require('node:vm'), crypto = require('no const { pack } = require('../packages/activity-bundles/pack'), sha256 = require('../packages/activity-bundles/sha256'); const runtime = fs.readFileSync('packages/activity-bundles/runtime.js', 'utf8'); const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); -function fixture(t, names = ['pyramid', 'other']) { +function fixture(t, names = ['pyramid', 'other'], md5Cache = true) { fs.mkdirSync('temp', { recursive: true }); const parent = fs.mkdtempSync(path.resolve('temp/activity-bundles-test-')), root = path.join(parent, 'game'); t.after(() => { assert(parent.startsWith(path.resolve('temp') + path.sep)); fs.rmSync(parent, { recursive: true, force: true }); }); fs.mkdirSync(path.join(root, 'src'), { recursive: true }); - fs.writeFileSync(path.join(root, 'src/settings.js'), 'window._CCSettings=' + JSON.stringify({ server: 'https://cdn.example/game/', remoteBundles: names, bundleVers: Object.fromEntries(names.map(n => [n, 'abc'])) })); + fs.writeFileSync(path.join(root, 'src/settings.js'), 'window._CCSettings=' + JSON.stringify({ server: 'https://cdn.example/game/', remoteBundles: names, bundleVers: md5Cache ? Object.fromEntries(names.map(n => [n, 'abc'])) : undefined })); fs.writeFileSync(path.join(root, 'game.js'), "require('./cloud-rise-package');\nwindow.boot();"); fs.writeFileSync(path.join(root, 'project.config.json'), JSON.stringify({ packOptions: { ignore: [{ type: 'file', value: 'keep' }] } })); for (const name of names) { const folder = path.join(root, 'remote', name); fs.mkdirSync(path.join(folder, 'native'), { recursive: true }); fs.mkdirSync(path.join(folder, 'import'), { recursive: true }); - fs.writeFileSync(path.join(folder, 'config.abc.json'), JSON.stringify({ name, isZip: false, importBase: 'import', nativeBase: 'native', deps: ['main'] })); + fs.writeFileSync(path.join(folder, md5Cache ? 'config.abc.json' : 'config.json'), JSON.stringify({ name, isZip: false, importBase: 'import', nativeBase: 'native', deps: ['main'] })); fs.writeFileSync(path.join(folder, 'native/icon.png'), name + ' art'); fs.writeFileSync(path.join(folder, 'import/pack.json'), '{}'); fs.mkdirSync(path.join(root, 'src/scripts', name), { recursive: true }); fs.writeFileSync(path.join(root, 'src/scripts', name, 'index.js'), '// local code'); } @@ -24,7 +24,7 @@ function fixture(t, names = ['pyramid', 'other']) { publish() { publication = pack(root, names); return publication; } }; } // Read ZIP central directory independently, then inflate the referenced local payloads. -function unzip(bytes, target) { +function unzip(bytes, target, createParents = true) { let pos = bytes.readUInt32LE(bytes.length - 6), count = bytes.readUInt16LE(bytes.length - 12); for (let i = 0; i < count; i++) { const len = bytes.readUInt16LE(pos + 28), name = bytes.toString('utf8', pos + 46, pos + 46 + len); @@ -33,7 +33,8 @@ function unzip(bytes, target) { const data = zlib.inflateRawSync(bytes.subarray(start, start + size)); assert.equal(data.length, bytes.readUInt32LE(pos + 24)); const out = path.resolve(target, name); assert(out.startsWith(path.resolve(target) + path.sep)); - fs.mkdirSync(path.dirname(out), { recursive: true }); fs.writeFileSync(out, data); + if (createParents) fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, data); pos += 46 + len + bytes.readUInt16LE(pos + 30) + bytes.readUInt16LE(pos + 32); } } @@ -42,9 +43,9 @@ function loader(f, options = {}) { const userRoot = path.join(f.parent, 'user').replace(/\\/g, '/'), bundles = new Map(), state = {}; const complete = (o, fn) => queueMicrotask(() => { try { o.success(fn()); } catch (error) { o.fail(error); } }); const wxfs = { - mkdir: o => complete(o, () => fs.mkdirSync(o.dirPath, { recursive: true })), + mkdir: o => complete(o, () => { if (state.mkdirFail && o.dirPath.endsWith('/pyramid/native')) throw Error('mkdir fail'); fs.mkdirSync(o.dirPath, { recursive: true }); }), readFile: o => complete(o, () => { const bytes = fs.readFileSync(o.filePath); return { data: o.encoding ? bytes.toString(o.encoding) : bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) }; }), - unzip: o => complete(o, () => { if (state.unzipFail) throw Error('unzip fail'); unzip(fs.readFileSync(o.zipFilePath), o.targetPath); if (state.missingFile) fs.unlinkSync(o.targetPath + '/native/icon.png'); }), + unzip: o => complete(o, () => { if (state.unzipFail) throw Error('unzip fail'); unzip(fs.readFileSync(o.zipFilePath), o.targetPath, false); if (state.missingFile) fs.unlinkSync(o.targetPath + '/native/icon.png'); }), unlink: o => complete(o, () => fs.unlinkSync(o.filePath)), rmdir: o => complete(o, () => { assert(o.dirPath.startsWith(userRoot + '/activity-bundles/')); removed.push(o.dirPath); fs.rmSync(o.dirPath, { recursive: true, force: true }); }) }; @@ -52,7 +53,7 @@ function loader(f, options = {}) { env: { USER_DATA_PATH: userRoot }, getFileSystemManager: () => wxfs, getStorageSync: key => structuredClone(storage.get(key)), setStorageSync: (key, value) => { if (state.storageFail) throw Error('storage full'); storage.set(key, structuredClone(value)); }, request(o) { requests.push(o.url); const data = structuredClone(state.manifest || f.publication.manifest); - const reply = () => state.manifestFail ? o.fail(Error('offline')) : o.success({ statusCode: 200, data }); + const reply = () => state.manifestFail ? o.fail(Error('offline')) : o.success({ statusCode: state.manifestStatus || 200, data }); if (state.holdManifest) state.reply = reply; else queueMicrotask(reply); }, downloadFile(o) { downloads.push(o.url); complete(o, () => { if (state.downloadFail) throw Error('offline'); @@ -67,7 +68,7 @@ function loader(f, options = {}) { if (!dir.startsWith(userRoot)) { done(null, { name: dir }); return; } activations.push(dir); queueMicrotask(() => { if (state.activationFail) return done(Error('engine fail')); - const data = JSON.parse(fs.readFileSync(dir + '/config.' + opts.version + '.json')); + const data = JSON.parse(fs.readFileSync(dir + '/config.' + (opts.version ? opts.version + '.' : '') + 'json')); const bundle = { name: data.name, dir, releaseAll: () => releases.push(dir) }; bundles.set(bundle.name, bundle); done(null, bundle); }); } }; @@ -103,6 +104,31 @@ test('build emits deterministic ZIPs and one common manifest, retaining local sc f.change('pyramid', 'updated'); assert.notEqual(f.publication.manifest.bundles.pyramid.hash, first.manifest.bundles.pyramid.hash); assert.equal(f.publication.manifest.bundles.other.hash, first.manifest.bundles.other.hash); }); +test('MD5-disabled builds load config.json, reuse cached ZIPs and refresh changed resources', async t => { + const f = fixture(t, ['pyramid'], false), first = f.publication.manifest.bundles.pyramid; + fs.writeFileSync(path.join(f.root, 'remote/pyramid/config.old.json'), '{}'); + assert.deepEqual(f.publish().manifest.bundles.pyramid, first, 'stale hashed configs stay outside the ZIP'); + const l = loader(f), original = await l.api.ensureBundle('pyramid'); + const metadata = JSON.parse(fs.readFileSync(original.dir + '/bundle-manifest.json')); + assert.equal(metadata.version, ''); assert.equal(metadata.config, 'config.json'); + assert(fs.existsSync(original.dir + '/config.json')); + assert(!fs.existsSync(original.dir + '/config.old.json')); + const cached = loader(f, { storage: l.storage }); + await cached.api.ensureBundle('pyramid'); assert.equal(cached.downloads.length, 0); + f.change('pyramid', 'updated without MD5'); l.api.beginCycle(); + const updated = await l.api.ensureBundle('pyramid'); + assert.notEqual(updated, original); assert.equal(l.downloads.length, 2); + assert.notEqual(f.publication.manifest.bundles.pyramid.hash, first.hash); + assert.equal(fs.readFileSync(updated.dir + '/native/icon.png', 'utf8'), 'updated without MD5'); +}); + +test('MD5-disabled builds reject a missing config.json instead of publishing a stale hashed config', t => { + const f = fixture(t, ['pyramid'], false), manifest = fs.readFileSync(path.join(f.publication.publishDir, 'manifest.json')); + fs.renameSync(path.join(f.root, 'remote/pyramid/config.json'), path.join(f.root, 'remote/pyramid/config.old.json')); + assert.throws(() => f.publish(), /ENOENT.*config\.json/); + assert.deepEqual(fs.readFileSync(path.join(f.publication.publishDir, 'manifest.json')), manifest); +}); + test('only requested bundles download, parallel calls share tasks and activities share one manifest per cycle', async t => { const f = fixture(t), l = loader(f); const [a,b] = await Promise.all([l.api.ensureBundle('pyramid'), l.api.ensureBundle('pyramid')]); assert.equal(a,b); assert.equal(l.requests.length,1); assert.equal(l.downloads.length,1); @@ -110,6 +136,17 @@ test('only requested bundles download, parallel calls share tasks and activities l.api.beginCycle(); await Promise.all([l.api.ensureBundle('pyramid'),l.api.ensureBundle('other')]); assert.equal(l.requests.length,2); assert.equal(l.downloads.length,2); assert.equal(l.activations.length,2); }); +test('unzip without automatic directory creation loads nested siblings and root files', async t => { + const f = fixture(t, ['pyramid']), folder = path.join(f.root, 'remote/pyramid/native/icons/deep'); + fs.mkdirSync(folder, { recursive: true }); + for (const name of ['first.png', 'second.png']) fs.writeFileSync(path.join(folder, name), name); + f.publish(); + const l = loader(f), bundle = await l.api.ensureBundle('pyramid'); + for (const name of ['first.png', 'second.png']) + assert.equal(fs.readFileSync(path.join(bundle.dir, 'native/icons/deep', name), 'utf8'), name); + assert.equal(JSON.parse(fs.readFileSync(bundle.dir + '/config.abc.json')).name, 'pyramid'); + assert.equal(JSON.parse(fs.readFileSync(bundle.dir + '/bundle-manifest.json')).name, 'pyramid'); +}); test('cold restart reuses complete disk cache without ZIP downloads and missing/corrupt files repair only that bundle', async t => { const f=fixture(t), l=loader(f); await l.api.ensureBundle('pyramid'); await l.api.ensureBundle('other'); const next=loader(f,{storage:l.storage});await next.api.ensureBundle('pyramid');assert.equal(next.downloads.length,0); @@ -124,11 +161,12 @@ test('new hashes download and activate without clearing another activity', async assert.notEqual(next,old);assert.equal(l.downloads.length,3);assert.equal(l.releases.length,1);assert.deepEqual(l.record('other'),other); assert(fs.existsSync(other.dir+'/native/icon.png'));assert.equal(l.record('pyramid').hash,f.publication.manifest.bundles.pyramid.hash); }); -test('download, digest, unzip, incomplete extraction and storage failure preserve the old cache pointer', async t => { - for(const failure of ['downloadFail','corruptZip','unzipFail','missingFile','storageFail']) { +test('download, digest, mkdir, unzip, incomplete extraction and storage failure preserve the old cache pointer', async t => { + for(const failure of ['downloadFail','corruptZip','mkdirFail','unzipFail','missingFile','storageFail']) { const f=fixture(t),l=loader(f);await l.api.ensureBundle('pyramid');const old=l.record('pyramid'); - f.change('pyramid','new art');l.state[failure]=true;l.api.beginCycle();await assert.rejects(l.api.ensureBundle('pyramid')); + f.change('pyramid','new art');l.state[failure]=true;l.api.beginCycle();await assert.rejects(l.api.ensureBundle('pyramid'), failure === 'mkdirFail' ? /mkdir fail/ : undefined); assert.deepEqual(l.record('pyramid'),old);assert(fs.existsSync(old.dir+'/native/icon.png'));assert.equal(l.releases.length,0); + if (failure === 'mkdirFail') { assert.equal(l.removed.length, 1); assert(!fs.existsSync(l.removed[0])); } await assert.rejects(l.api.ensureBundle('pyramid'));assert.equal(l.downloads.length,2,'no render retry storm'); l.state[failure]=false;l.api.beginCycle();await l.api.ensureBundle('pyramid');assert.notEqual(l.record('pyramid').dir,old.dir); } @@ -147,6 +185,81 @@ test('manifest failure is shared until the next lifecycle; loading resources nev const f=fixture(t),l=loader(f);l.state.manifestFail=true;await assert.rejects(l.api.ensureBundle('pyramid'));await assert.rejects(l.api.ensureBundle('other')); assert.equal(l.requests.length,1);assert.equal(l.downloads.length,0);l.state.manifestFail=false;l.api.beginCycle();await l.api.ensureBundle('pyramid');assert.equal(l.downloads.length,1); }); + +test('unavailable manifest reuses verified MD5-disabled disk caches without downloads or pointer writes, then updates next cycle', async t => { + const f=fixture(t,['pyramid','other'],false),seed=loader(f); + await Promise.all([seed.api.ensureBundle('pyramid'),seed.api.ensureBundle('other')]); + const before=structuredClone([...seed.storage]),l=loader(f,{storage:seed.storage}); + l.state.manifestFail=true;l.state.storageFail=true; + const [first,duplicate,other]=await Promise.all([l.api.ensureBundle('pyramid'),l.api.ensureBundle('pyramid'),l.api.ensureBundle('other')]); + assert.equal(first,duplicate);assert.equal(first.dir,l.record('pyramid').dir);assert.equal(other.dir,l.record('other').dir); + assert.equal(JSON.parse(fs.readFileSync(first.dir+'/bundle-manifest.json')).version,''); + assert.equal(l.requests.length,1);assert.equal(l.downloads.length,0);assert.equal(l.activations.length,2); + assert.deepEqual([...l.storage],before);assert.equal(l.removed.length,0); + f.change('pyramid','updated after offline cache');l.state.manifestFail=false;l.state.storageFail=false; + assert.equal(await l.api.ensureBundle('pyramid'),first);assert.equal(l.requests.length,1); + l.api.beginCycle();const next=await l.api.ensureBundle('pyramid'); + assert.notEqual(next,first);assert.equal(l.requests.length,2);assert.equal(l.downloads.length,1); + assert.equal(l.record('pyramid').hash,f.publication.manifest.bundles.pyramid.hash); + assert.equal(fs.readFileSync(next.dir+'/native/icon.png','utf8'),'updated after offline cache'); + assert.deepEqual(l.record('other'),before.find(([key])=>key.endsWith(':other'))[1]); +}); + +test('HTTP, JSON and invalid manifest failures can all use a verified local cache', async t => { + const f=fixture(t,['pyramid']),seed=loader(f);await seed.api.ensureBundle('pyramid'); + const before=structuredClone([...seed.storage]); + for(const failure of [{manifestStatus:503},{manifest:'{broken'},{manifest:{schemaVersion:2,bundles:{}}}]){ + const l=loader(f,{storage:seed.storage});Object.assign(l.state,failure); + const bundle=await l.api.ensureBundle('pyramid');assert.equal(bundle.dir,l.record('pyramid').dir); + assert.equal(l.requests.length,1);assert.equal(l.downloads.length,0);assert.deepEqual([...l.storage],before); + } +}); + +test('unavailable manifest cannot use absent, corrupt, unverified or foreign disk caches', async t => { + for(const failure of ['absent','missing-file','corrupt-file','invalid-hash','missing-metadata-hash','metadata-hash','foreign-path']){ + const f=fixture(t,['pyramid']),seed=loader(f);await seed.api.ensureBundle('pyramid'); + const record=seed.record('pyramid'),icon=record.dir+'/native/icon.png'; + if(failure==='absent')seed.storage.clear(); + else if(failure==='missing-file')fs.unlinkSync(icon); + else if(failure==='corrupt-file'){const bytes=fs.readFileSync(icon);bytes[0]^=1;fs.writeFileSync(icon,bytes);} + else if(failure==='invalid-hash'){ + const dir=record.dir.replace('/'+record.hash+'/', '/../escape/'); + fs.cpSync(record.dir,dir,{recursive:true});record.hash='../escape';record.dir=dir; + } + else if(failure==='missing-metadata-hash')delete record.metadataHash; + else if(failure==='metadata-hash')record.metadataHash='0'.repeat(64); + else {const dir=path.join(f.parent,'foreign','pyramid').replace(/\\/g,'/');fs.cpSync(record.dir,dir,{recursive:true});record.dir=dir;} + const before=structuredClone([...seed.storage]),l=loader(f,{storage:seed.storage});l.state.manifestFail=true; + await assert.rejects(l.api.ensureBundle('pyramid')); + assert.equal(l.requests.length,1);assert.equal(l.downloads.length,0);assert.equal(l.activations.length,0); + assert.deepEqual([...l.storage],before);assert.equal(l.removed.length,0); + } +}); + +test('a valid manifest missing the bundle or a failed new ZIP cannot fall back to old cache', async t => { + for(const failure of ['missing-bundle','download']){ + const f=fixture(t,['pyramid']),seed=loader(f);await seed.api.ensureBundle('pyramid'); + const before=structuredClone([...seed.storage]),l=loader(f,{storage:seed.storage}); + if(failure==='missing-bundle')l.state.manifest={schemaVersion:1,bundles:{}}; + else {f.change('pyramid','new version');l.state.downloadFail=true;} + await assert.rejects(l.api.ensureBundle('pyramid')); + assert.equal(l.requests.length,1);assert.equal(l.downloads.length,failure==='download'?1:0);assert.equal(l.activations.length,0); + assert.deepEqual([...l.storage],before);assert(fs.existsSync(seed.record('pyramid').dir+'/native/icon.png')); + } +}); + +test('a new lifecycle supersedes a late failed manifest instead of activating its old cache', async t => { + const f=fixture(t,['pyramid']),seed=loader(f);await seed.api.ensureBundle('pyramid'); + const l=loader(f,{storage:seed.storage});l.state.holdManifest=true; + const old=l.api.ensureBundle('pyramid'),oldReply=l.state.reply;old.catch(()=>{}); + f.change('pyramid','latest lifecycle');l.api.beginCycle(); + const next=l.api.ensureBundle('pyramid'),newReply=l.state.reply; + newReply();l.state.manifestFail=true;oldReply();l.state.manifestFail=false; + await assert.rejects(old);const bundle=await next; + assert.equal(l.requests.length,2);assert.equal(l.downloads.length,1);assert.equal(l.activations.length,1); + assert.equal(l.record('pyramid').hash,f.publication.manifest.bundles.pyramid.hash); + assert.equal(fs.readFileSync(bundle.dir+'/native/icon.png','utf8'),'latest lifecycle'); +}); test('legacy loadBundle signature redirects only integrated names and engine failures restore the loaded bundle', async t => { const f=fixture(t),l=loader(f),load=name=>new Promise((resolve,reject)=>l.manager.loadBundle(name,(e,b)=>e?reject(e):resolve(b))); assert.equal((await load('shop')).name,'shop');assert.equal(l.requests.length,0); diff --git a/tools/test-cloud-rise-package.cjs b/tools/test-cloud-rise-package.cjs index 81691816..672d7d4a 100644 --- a/tools/test-cloud-rise-package.cjs +++ b/tools/test-cloud-rise-package.cjs @@ -3,7 +3,7 @@ const fs = require('node:fs'), path = require('node:path'), vm = require('node:v const { pack, names } = require('../packages/cloud-rise-package/pack'); const runtime = fs.readFileSync('packages/cloud-rise-package/runtime.js', 'utf8'); const settle = async () => { for (let i = 0; i < 60; i++) await Promise.resolve(); }; -function buildFixture(t) { +function buildFixture(t, md5Cache = true) { fs.mkdirSync('temp', {recursive:true}); const parent = fs.mkdtempSync(path.resolve('temp/cloud-rise-remote-test-')), root = path.join(parent,'game'); t.after(()=> { @@ -12,13 +12,14 @@ function buildFixture(t) { }); fs.mkdirSync(path.join(root,'src'),{recursive:true}); const settings={server:'https://cdn.example.com/game',remoteBundles:names,subpackages:['shop'],bundleVers:{...Object.fromEntries(names.map(n=>[n,'abc'])),'cloud_rise_home':'home1'}}; + if (!md5Cache) delete settings.bundleVers; fs.writeFileSync(path.join(root,'src/settings.js'),'window._CCSettings='+JSON.stringify(settings)+';'); fs.writeFileSync(path.join(root,'game.json'),JSON.stringify({subpackages:[{name:'shop',root:'subpackages/shop'}]})); fs.writeFileSync(path.join(root,'project.config.json'),JSON.stringify({packOptions:{ignore:[{type:'file',value:'unrelated.txt'}]}})); fs.writeFileSync(path.join(root,'game.js'),"require('./src/settings');\nwindow.boot();"); for(const name of names){ const folder=path.join(root,'remote',name);fs.mkdirSync(path.join(folder,'native'),{recursive:true}); - fs.writeFileSync(path.join(folder,'config.abc.json'),JSON.stringify({name,deps:['cloud_rise_home'],uuids:['unchanged']})); + fs.writeFileSync(path.join(folder,md5Cache?'config.abc.json':'config.json'),JSON.stringify({name,deps:['cloud_rise_home'],uuids:['unchanged']})); fs.writeFileSync(path.join(folder,'native/image.png'),'image-'+name); fs.mkdirSync(path.join(root,'src/scripts',name),{recursive:true}); fs.writeFileSync(path.join(root,'src/scripts',name,'index.js'),'/* '+name+' local code */'); @@ -67,6 +68,37 @@ test('invalid versions and incomplete output fail before changing client boot co assert.throws(()=>f.pack(),/Missing remote Cloud Rise bundle/); assert.equal(fs.readFileSync(path.join(f.root,'cloud-rise-package-config.js'),'utf8'),before); }); + +test('builds without MD5 publish versioned configs and load through the existing cache path',async t=>{ + const build=buildFixture(t,false); + for(const name of names) fs.writeFileSync(path.join(build.root,'remote',name,'config.stale.json'),'{stale'); + const publication=build.pack(); + for(const name of names){ + const folder=path.join(publication.publishDir,name); + assert.deepEqual(fs.readdirSync(folder).sort(),['config.json','native']); + assert.equal(JSON.parse(fs.readFileSync(path.join(folder,'config.json'))).cloudRiseVersion,'1.0.0'); + } + const f=loaderFixture(build); + const bundle=await f.load('art',{version:'stale-client-hash'}); + assert.equal(bundle.cloudRiseVersion,'1.0.0'); + assert.equal(await f.asset('art/native/image.png'),'image-art'); + f.restart();await f.load('art');await f.asset('art/native/image.png');assert.equal(f.downloads.length,2); + build.release('1.0.1');fs.writeFileSync(path.join(build.root,'remote/art/native/image.png'),'new image');build.pack(); + f.state.response={version:'1.0.1'};f.restart(); + assert.equal((await f.load('art')).cloudRiseVersion,'1.0.1'); + assert.equal(await f.asset('art/native/image.png'),'new image');assert.equal(f.downloads.length,4); +}); + +test('the current MD5 setting selects one config and never falls back to stale output',t=>{ + for(const md5Cache of [true,false]){ + const f=buildFixture(t,md5Cache),folder=path.join(f.root,'remote/art'); + fs.writeFileSync(path.join(folder,md5Cache?'config.json':'config.abc.json'),'{stale'); + const published=f.pack(); + assert.equal(JSON.parse(fs.readFileSync(path.join(published.publishDir,'art/config.json'))).cloudRiseVersion,'1.0.0'); + fs.unlinkSync(path.join(folder,md5Cache?'config.abc.json':'config.json')); + assert.throws(()=>f.pack(),/Missing remote Cloud Rise bundle.*art/); + } +}); test('only WeChat GUI and CLI builds publish the independent remote bundles',t=>{ const hooks={},logs=[],module={exports:{}}; vm.runInNewContext(fs.readFileSync('packages/cloud-rise-package/main.js','utf8'),{ diff --git a/tools/test-pyramid-home-reminder.cjs b/tools/test-pyramid-home-reminder.cjs index 001073af..a3a38f6c 100644 --- a/tools/test-pyramid-home-reminder.cjs +++ b/tools/test-pyramid-home-reminder.cjs @@ -1,22 +1,25 @@ const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'),ts=require('typescript'); const code=ts.transpileModule(fs.readFileSync('assets/Script/PyramidView.ts','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2017,experimentalDecorators:true}}).outputText; function fixture(){ - let now=1000,shown=0,done=0,loading=0,reminder={key:'test:alice',day:1,periodId:'p1'},initialize=async()=>{},sync=true; + let now=1000,shown=0,done=0,loading=0,stopped=0,released=0,paymentSyncs=0,panel,reminder={key:'test:alice',day:1,periodId:'p1'},initialize=async()=>{},sync=true; const tasks=[],label={string:''},time={active:false,getComponent:()=>label},bg={active:false}; const state={status:'active',endAt:100000,pendingGrants:[]}; - const service={busy:false,settlements:()=>[],data:()=>state,now:()=>now,sync:async()=>sync,prefab:async()=>({}),acquireResources:async()=>()=>{}}; + const release=()=>released++; + const service={busy:false,settlements:()=>[],data:()=>state,now:()=>now,sync:async()=>sync,prefab:async()=>({}),acquireResources:async()=>release}; const schedule={active:()=>nownow,pyramidReminder:()=>reminder,markPyramidReminderShown:()=>{shown++;reminder=null;}}; const queue={enqueue:(key,priority,run)=>tasks.push({key,priority,run})}; - const cc={Component:class{},_decorator:{ccclass:c=>c},Label:class{},isValid:n=>!!n&&!n.destroyed,warn(){}, - instantiate:()=>({destroy(){this.destroyed=true;},getComponent:()=>({initialize:()=>initialize()})})}; + const cc={Component:class{},_decorator:{ccclass:c=>c},Label:class{},isValid:n=>!!n&&!n.destroyed,warn(){},game:{off(){}}, + instantiate:()=>{const node={destroy(){this.destroyed=true;},getComponent:()=>panel};panel={node,initialize:()=>initialize()};return node;}}; const context={exports:{},cc,Date:{now:()=>now},require:name=>({default:name.includes('PyramidService')?service:name.includes('ActivityScheduleService')?schedule:name.includes('HomePopupQueue')?{get:()=>queue}:{}})}; vm.runInNewContext(code,context); - const view=new context.exports.default();view.entry={active:true,getChildByName:name=>name==='time'?time:bg};view.node={addChild(){}}; - view.startLoading=()=>{loading++;return ()=>{};};view.syncPaymentLoading=()=>{}; + const view=new context.exports.default();view.entry={active:true,getChildByName:name=>name==='time'?time:bg,destroy(){this.destroyed=true;}};view.node={addChild(){}}; + view.unschedule=()=>{};view.startLoading=()=>{loading++;return ()=>stopped++;};view.syncPaymentLoading=()=>{paymentSyncs++;assert(!view.destroyed,'destroyed View must not update payment Loading');}; + const destroyView=(componentOnly=false)=>{view.destroyed=true;if(!componentOnly)view.node.destroyed=true;view.onDestroy();view.entry=null;view.overlay=null;view.releaseResources=null;view.finishReminder=null;view.closeOverlay=null;}; return {view,service,state,tasks,label,time,bg,setNow:n=>now=n,setReminder:r=>reminder=r,setSync:b=>sync=b,setInitialize:fn=>initialize=fn, - run:()=>tasks.shift().run(()=>done++),shown:()=>shown,done:()=>done,loading:()=>loading}; + run:()=>tasks.shift().run(()=>done++),shown:()=>shown,done:()=>done,loading:()=>loading,stopped:()=>stopped,released:()=>released,paymentSyncs:()=>paymentSyncs,panel:()=>panel,release,destroyView}; } const flush=()=>new Promise(resolve=>setImmediate(resolve)); +const deferred=()=>{let resolve,reject;const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});return {promise,resolve,reject};}; test('daily login popup uses shared queue, records only after display and releases on close',async()=>{ const f=fixture();f.view.queueDailyReminder();f.view.queueDailyReminder();assert.equal(f.tasks.length,1);assert.equal(f.tasks[0].priority,11); f.run();assert.equal(f.shown(),0);await flush();assert.equal(f.shown(),1);assert.equal(f.done(),0);assert.equal(f.view.overlay.active,true); @@ -55,3 +58,30 @@ test('entry countdown matches GoldMiner day/hour and clock formatting and hides f.state.endAt=1000+milliseconds;f.view.refreshCountdown();assert.equal(f.label.string,text);assert.equal(f.time.active,milliseconds>0);assert.equal(f.bg.active,milliseconds>0); } }); +test('destroying View while acquiring resources releases the late lease and stops manual Loading',async()=>{ + for(const componentOnly of [false,true]){ + const f=fixture(),wait=deferred();let prefabs=0;f.service.acquireResources=()=>wait.promise;f.service.prefab=async()=>{prefabs++;return {};}; + const opening=f.view.open();f.destroyView(componentOnly);wait.resolve(f.release);await opening; + assert.equal(f.released(),1);assert.equal(prefabs,0);assert.equal(f.stopped(),1);assert.equal(f.paymentSyncs(),0); + } +}); +test('destroying View during prefab or panel initialization settles the reminder without touching destroyed fields',async()=>{ + for(const stage of ['prefab','initialize'])for(const componentOnly of [false,true])for(const fail of [false,true]){ + const f=fixture(),wait=deferred();let opening; + if(stage==='prefab')f.service.prefab=()=>wait.promise;else f.setInitialize(()=>wait.promise); + const open=f.view.open.bind(f.view);f.view.open=(...args)=>opening=open(...args); + f.view.queueDailyReminder();f.run();await flush(); + const overlay=f.view.overlay;f.destroyView(componentOnly); + if(fail)wait.reject(Error('late load failure'));else wait.resolve({});await opening; + assert.equal(f.released(),1,stage);assert.equal(f.done(),1,stage);assert.equal(f.shown(),0,stage);assert.equal(f.paymentSyncs(),0,stage); + if(overlay){assert.equal(overlay.destroyed,true);assert.equal(overlay.active,false);} + } +}); +test('a destroyed panel component is not activated when its initialization finishes',async()=>{ + const f=fixture(),wait=deferred();f.setInitialize(()=>wait.promise);let opening; + const open=f.view.open.bind(f.view);f.view.open=(...args)=>opening=open(...args); + f.view.queueDailyReminder();f.run();await flush();const overlay=f.view.overlay;f.panel().destroyed=true; + wait.resolve();await opening; + assert.equal(overlay.active,false);assert.equal(overlay.destroyed,true);assert.equal(f.view.overlay,null); + assert.equal(f.released(),1);assert.equal(f.done(),1);assert.equal(f.shown(),0); +}); diff --git a/tools/test-pyramid-resource-lifecycle.cjs b/tools/test-pyramid-resource-lifecycle.cjs new file mode 100644 index 00000000..5ef46217 --- /dev/null +++ b/tools/test-pyramid-resource-lifecycle.cjs @@ -0,0 +1,207 @@ +const test = require('node:test'), assert = require('node:assert/strict'); +const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript'); +const source = ts.transpileModule(fs.readFileSync('assets/pyramid/scripts/PyramidPanel.ts', 'utf8'), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2017, experimentalDecorators: true } +}).outputText; +const flush = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); }; +function observe(promise) { + const result = { status: 'pending' }; + promise.then(value => Object.assign(result, { status: 'fulfilled', value }), error => Object.assign(result, { status: 'rejected', error })); + return result; +} +async function fulfilled(result) { await flush(); assert.equal(result.status, 'fulfilled', result.error && result.error.stack); } +function fixture(waitForBundle = false) { + const dead = new WeakSet(), pending = new WeakSet(), requests = [], calls = { render: 0, subscribe: 0, record: 0, instantiate: 0 }; + class Node { + constructor(name) { this.name = name; this.children = []; } + addChild(node) { this.children.push(node); } + insertChild(node, index) { this.children.splice(index, 0, node); } + getChildByName(name) { return this.children.find(node => node.name === name); } + setScale() {} setContentSize() {} setPosition() {} on() {} + addComponent(Type) { return new Type(); } + getComponent() { return {}; } + } + Node.EventType = { TOUCH_START: 'touchstart' }; + class Graphics { rect() {} fill() {} } + const bundle = name => ({ load(path, type, done) { requests.push({ kind: 'asset', bundle: name, path, done, value: { path, bundle: name } }); } }); + const pyramid = bundle('pyramid'), shared = bundle('cloud_rise_home'), publicUI = bundle('publicUI'); + let resolveBundle, rejectBundle; + const bundleTask = new Promise((resolve, reject) => { resolveBundle = resolve; rejectBundle = reject; }); + if (!waitForBundle) resolveBundle(pyramid); + const service = { bundle: () => bundleTask, data: () => null, recordPriceView: async () => { calls.record++; }, subscribe: () => { calls.subscribe++; return () => {}; } }; + const cc = { + Node, Graphics, Color: class {}, BlockInputEvents: class {}, Component: class {}, SpriteFrame: class {}, Material: class {}, Prefab: class {}, Sprite: class {}, Widget: class {}, + _decorator: { ccclass: Type => Type, property: () => () => {} }, + view: { getVisibleSize: () => ({ width: 1080, height: 2000 }) }, + isValid: (object, strict) => !!object && !dead.has(object) && !(strict && pending.has(object)), + assetManager: { getBundle: () => null, loadBundle(name, done) { requests.push({ kind: 'bundle', path: name, done, value: name === 'publicUI' ? publicUI : shared }); } }, + instantiate() { calls.instantiate++; throw Error('Destroyed panel must not instantiate rewards'); } + }; + const context = { exports: {}, cc, require: () => ({ default: service }) }; + vm.runInNewContext(source, context); + const panel = new context.exports.default(), node = new Node('Panel'), design = new Node('Design'); + node.addChild(design); + for (const name of ['SummitGlow', 'Rewards', 'Tooltip', 'Free']) design.addChild(new Node(name)); + panel.node = node; panel.bundle = pyramid; + panel.goodsFrames = Array.from({ length: 5 }, () => ({})); panel.movingGoodsFrames = Array.from({ length: 5 }, () => ({})); + panel.hourFrame = {}; panel.minuteFrame = {}; panel.countPrefixFrame = {}; panel.countdownBackgroundFrame = {}; + panel.countdownFrames = Array.from({ length: 10 }, () => ({})); + panel.button = () => {}; panel.render = () => { calls.render++; }; panel.animationDebug = () => false; + function finish(request, error = null) { + assert(request && !request.finished, 'Expected an outstanding resource callback'); request.finished = true; + assert.doesNotThrow(() => request.done(error, error ? null : request.value), request.path); + } + function destroy(mode) { + if (mode === 'component-pending') pending.add(panel); + else if (mode === 'node-pending') pending.add(node); + else { + dead.add(panel); dead.add(node); + // Cocos 2.4 destructs own object/function fields even for inactive nodes. + for (const key of Object.keys(panel)) if (typeof panel[key] === 'object' || typeof panel[key] === 'function') panel[key] = null; + } + const fields = Object.entries(panel), maps = ['frames', 'digits', 'price', 'probabilityDigits'].filter(key => panel[key]).map(key => [key, Object.entries(panel[key])]); + return () => { + for (const [key, value] of fields) assert.strictEqual(panel[key], value, 'Destroyed panel field changed: ' + key); + for (const [key, entries] of maps) assert.deepEqual(Object.entries(panel[key]), entries, 'Destroyed panel dictionary changed: ' + key); + }; + } + return { panel, requests, calls, finish, destroy, resolveBundle: () => resolveBundle(pyramid), rejectBundle, + assets: name => requests.filter(request => request.kind === 'asset' && request.bundle === name && !request.finished), + bundleRequest: name => requests.find(request => request.kind === 'bundle' && request.path === name && !request.finished) }; +} +const modes = ['component-pending', 'node-pending', 'destructed']; + +for (const mode of modes) { + test('initialization ignores resource callbacks after ' + mode, async () => { + const f = fixture(), result = observe(f.panel.initialize(() => {})); await flush(); + assert.equal(f.assets('pyramid').length, 30); + assert(f.assets('pyramid').some(request => request.path === 'art/check')); + const unchanged = f.destroy(mode); + for (const request of f.assets('pyramid')) f.finish(request); + await fulfilled(result); unchanged(); assert.equal(f.calls.subscribe, 0); + }); + test('initialization stops after a late Service.bundle result for ' + mode, async () => { + const f = fixture(true), result = observe(f.panel.initialize(() => {})); + const unchanged = f.destroy(mode); f.resolveBundle(); + await fulfilled(result); unchanged(); assert.equal(f.requests.length, 0); + }); + test('all ten price callbacks settle without writes after ' + mode, async () => { + const f = fixture(), result = observe(f.panel.ensurePriceAssets()); + assert.equal(f.assets('pyramid').length, 10); const unchanged = f.destroy(mode); + for (const request of f.assets('pyramid')) f.finish(request); + await fulfilled(result); unchanged(); + }); + test('probability and shared image/material callbacks settle without writes after ' + mode, async () => { + const f = fixture(), result = observe(f.panel.ensureProbabilityAssets()); + f.finish(f.bundleRequest('cloud_rise_home')); await flush(); + assert.equal(f.assets('pyramid').length, 14); assert.equal(f.assets('cloud_rise_home').length, 2); + const unchanged = f.destroy(mode); + for (const request of [...f.assets('pyramid'), ...f.assets('cloud_rise_home')]) f.finish(request); + await fulfilled(result); unchanged(); + }); + test('late probability loadBundle result starts no child loads after ' + mode, async () => { + const f = fixture(), result = observe(f.panel.ensureProbabilityAssets()), unchanged = f.destroy(mode); + f.finish(f.bundleRequest('cloud_rise_home')); + for (const request of f.assets('pyramid')) f.finish(request); + await fulfilled(result); unchanged(); assert.equal(f.assets('cloud_rise_home').length, 0); + }); +} + +test('a failed initialization can destroy the panel before other Promise.all callbacks arrive', async () => { + const f = fixture(), error = Error('image missing'), result = observe(f.panel.initialize(() => {})); await flush(); + f.finish(f.assets('pyramid').find(request => request.path === 'art/selection'), error); await flush(); + assert.equal(result.status, 'rejected'); assert.strictEqual(result.error, error); + const unchanged = f.destroy('destructed'); + for (const request of f.assets('pyramid')) f.finish(request); + await flush(); unchanged(); +}); + +test('initialization suppresses an already queued load rejection when destroyed before await resumes', async () => { + const f = fixture(), result = observe(f.panel.initialize(() => {})); await flush(); + f.finish(f.assets('pyramid')[0], Error('failed before destruction')); + const unchanged = f.destroy('destructed'); + for (const request of f.assets('pyramid')) f.finish(request); + await fulfilled(result); unchanged(); +}); + +test('late load errors are ignored without restoring destroyed price/probability state', async () => { + for (const method of ['ensurePriceAssets', 'ensureProbabilityAssets']) { + const f = fixture(), result = observe(f.panel[method]()); + if (method === 'ensureProbabilityAssets') { f.finish(f.bundleRequest('cloud_rise_home')); await flush(); } + const unchanged = f.destroy('destructed'); + for (const request of [...f.assets('pyramid'), ...f.assets('cloud_rise_home')]) f.finish(request, Error('late failure')); + await fulfilled(result); unchanged(); + } +}); + +test('a queued rejection handler cannot write fields after destruction', async () => { + for (const method of ['ensurePriceAssets', 'ensureProbabilityAssets']) { + const f = fixture(), error = Error('failed before destruction'), result = observe(f.panel[method]()); + f.finish(f.assets('pyramid')[0], error); + const unchanged = f.destroy('destructed'); + if (method === 'ensureProbabilityAssets') f.finish(f.bundleRequest('cloud_rise_home')); + for (const request of f.assets('pyramid')) f.finish(request); + await flush(); assert.notEqual(result.status, 'pending'); unchanged(); + if (result.status === 'rejected') assert.strictEqual(result.error, error); + assert.equal(f.assets('cloud_rise_home').length, 0); + } +}); + +test('late bundle failures settle without starting dependent image requests', async () => { + const initialization = fixture(true), initResult = observe(initialization.panel.initialize(() => {})); + const initUnchanged = initialization.destroy('destructed'); initialization.rejectBundle(Error('late bundle failure')); + await flush(); assert.notEqual(initResult.status, 'pending'); initUnchanged(); assert.equal(initialization.requests.length, 0); + for (const method of ['ensureProbabilityAssets', 'animateRewards']) { + const f = fixture(), result = observe(method === 'animateRewards' ? f.panel.animateRewards([{ id: 1001, count: 1 }]) : f.panel[method]()); + const unchanged = f.destroy('destructed'); + f.finish(f.bundleRequest(method === 'animateRewards' ? 'publicUI' : 'cloud_rise_home'), Error('late bundle failure')); + for (const request of f.assets('pyramid')) f.finish(request); + await flush(); assert.notEqual(result.status, 'pending'); unchanged(); + assert.equal(f.assets('cloud_rise_home').length + f.assets('publicUI').length, 0); + } +}); + +test('living panels initialize images and preserve price/probability failures and retries', async () => { + const init = fixture(), initialized = observe(init.panel.initialize(() => {})); await flush(); + for (const request of init.assets('pyramid')) init.finish(request); + await fulfilled(initialized); assert.equal(init.panel.frames.check.path, 'art/check'); assert.equal(init.panel.digits[0].path, 'art/digits/0'); + assert.equal(init.panel.ready, true); assert.equal(init.calls.subscribe, 1); + for (const method of ['ensurePriceAssets', 'ensureProbabilityAssets']) { + const f = fixture(), error = Error('download failed'), failed = observe(f.panel[method]()); + f.finish(f.assets('pyramid')[0], error); + for (const request of f.assets('pyramid')) f.finish(request); + if (method === 'ensureProbabilityAssets') { f.finish(f.bundleRequest('cloud_rise_home')); await flush(); for (const request of f.assets('cloud_rise_home')) f.finish(request); } + await flush(); assert.equal(failed.status, 'rejected'); assert.strictEqual(failed.error, error); + const task = method === 'ensurePriceAssets' ? 'priceTask' : 'probabilityTask'; assert.equal(f.panel[task], null); + if (method === 'ensurePriceAssets') assert.equal(f.panel.priceError, true); + const retry = observe(f.panel[method]()); + for (const request of f.assets('pyramid')) f.finish(request); + if (method === 'ensureProbabilityAssets') { f.finish(f.bundleRequest('cloud_rise_home')); await flush(); for (const request of f.assets('cloud_rise_home')) f.finish(request); } + await fulfilled(retry); + if (method === 'ensurePriceAssets') { assert.equal(f.panel.priceError, false); assert.equal(f.panel.price[0].path, 'art/price/0'); } + else { assert.equal(f.panel.probabilityDigits[0].path, 'art/probability/0'); assert.equal(f.panel.continueFrame.path, 'images/continue'); assert.equal(f.panel.continueMaterial.path, 'images/continue_outline'); } + } +}); + +test('reward resource loading stops after destruction before or after publicUI resolves', async () => { + for (const phase of ['bundle', 'prefab']) { + const f = fixture(), result = observe(f.panel.animateRewards([{ id: 1001, count: 1 }])); + if (phase === 'prefab') { f.finish(f.bundleRequest('publicUI')); await flush(); assert.equal(f.assets('publicUI').length, 1); } + const unchanged = f.destroy('destructed'); + if (phase === 'bundle') f.finish(f.bundleRequest('publicUI')); + else f.finish(f.assets('publicUI')[0]); + await fulfilled(result); unchanged(); assert.equal(f.calls.instantiate, 0); + if (phase === 'bundle') assert.equal(f.assets('publicUI').length, 0); + } +}); + +test('reward bundle and prefab rejections preserve live errors but settle after same-tick destruction', async () => { + for (const phase of ['bundle', 'prefab']) for (const destroy of [false, true]) { + const f = fixture(), error = Error('reward resource failed'), result = observe(f.panel.animateRewards([{ id: 1001, count: 1 }])); + if (phase === 'prefab') { f.finish(f.bundleRequest('publicUI')); await flush(); } + f.finish(phase === 'bundle' ? f.bundleRequest('publicUI') : f.assets('publicUI')[0], error); + if (destroy) { const unchanged = f.destroy('destructed'); await fulfilled(result); unchanged(); } + else { await flush(); assert.equal(result.status, 'rejected'); assert.strictEqual(result.error, error); } + assert.equal(f.assets('publicUI').length, 0); assert.equal(f.calls.instantiate, 0); + } +});