MatchMaster/packages/cloud-rise-package/pack.js
2026-09-16 18:19:34 +08:00

46 lines
2.9 KiB
JavaScript

'use strict';
const fs = require('fs'), path = require('path'), vm = require('vm');
const names = ['cloud_rise_matching', 'cloud_rise_stage1', 'cloud_rise_stage2', 'cloud_rise_stage3'];
function pack(destination) {
const root = path.resolve(destination), group = path.join(root, 'subpackages', 'cloud_rise');
const gameFile = path.join(root, 'game.json'), settingsFile = path.join(root, 'src', 'settings.js');
const manifest = JSON.parse(fs.readFileSync(gameFile, 'utf8'));
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');
const sources = names.map(name => {
const source = path.join(root, 'subpackages', name), target = path.join(group, name);
const folder = fs.existsSync(source) ? source : target;
const version = settings.bundleVers[name];
const config = path.join(folder, `config.${version ? version + '.' : ''}json`);
if (!fs.existsSync(config) || !fs.existsSync(path.join(folder, 'game.js'))) throw Error('Missing Cloud Rise bundle: ' + name);
return { source, target, folder };
});
const bootFile = path.join(root, 'game.js');
let boot = fs.readFileSync(bootFile, 'utf8');
const entry = "require('./cloud-rise-package');";
if (!boot.includes(entry)) {
if (!boot.includes('window.boot();')) throw Error('Missing WeChat boot insertion point');
boot = boot.replace('window.boot();', entry + '\nwindow.boot();');
}
fs.mkdirSync(group, { recursive: true });
for (const { source, target, folder } of sources) {
if (folder === target) continue; // Re-running the hook is safe.
// Only replace these generated children inside the checked build output directory.
const relative = path.relative(group, path.resolve(target));
if (relative.startsWith('..') || path.isAbsolute(relative) || !names.includes(relative)) throw Error('Unsafe build destination');
if (fs.existsSync(target)) fs.rmdirSync(target, { recursive: true });
fs.renameSync(source, target);
}
fs.writeFileSync(path.join(group, 'game.js'), names.map(name => `require('./${name}/game.js');`).join('\n') + '\n');
manifest.subpackages = (manifest.subpackages || []).filter(item => !names.includes(item.name) && item.name !== 'cloud_rise');
manifest.subpackages.unshift({ name: 'cloud_rise', root: 'subpackages/cloud_rise' });
settings.subpackages = (settings.subpackages || []).filter(name => !names.includes(name));
fs.writeFileSync(gameFile, JSON.stringify(manifest, null, 2) + '\n');
fs.writeFileSync(settingsFile, 'window._CCSettings=' + JSON.stringify(settings) + ';\n');
fs.copyFileSync(path.join(__dirname, 'runtime.js'), path.join(root, 'cloud-rise-package.js'));
fs.writeFileSync(bootFile, boot);
}
module.exports = { pack, names };