fixed # 更改更新方式

This commit is contained in:
2026-11-24 10:17:49 +08:00
parent 884d694d22
commit 2d7bd0fbdc
11 changed files with 876 additions and 16 deletions
+16
View File
@@ -16,6 +16,7 @@
2. 在 `modules` 中维护可选模块的目录、入口和显示名。
3. 发布工作流为每个模块生成独立清单,并将清单提交到发布标签。
4. 完整 ZIP 安装包仍包含所有模块,供离线或整包安装使用。
5. GitHub 和 Gitea 都从校验通过的标签快照生成 `mengsan-<tag>-part-001.zip` 等分包,随完整 ZIP 上传到同一 Release。分包内使用模块清单的 `mengsan/` 路径,供客户端首次安装使用。
修改 `extension.js` 中的 `shuYingLocalVersion`,提交并推送到 GitHub
默认分支后,工作流会比较推送前后的版本号。版本号变化时自动生成和校验
@@ -31,6 +32,21 @@ Gitea 保持接收同一发布标签后打包的流程;使用 Gitea 更新源
`dist/manifest.json` 和 `dist/modules/*.json` 的同一标签;当前 Gitea 工作流
会生成并上传附件,但不会改写触发它的标签。
## 分包安装试用
在测试客户端中将 `shuYing_mengsan_zip_trial` 设为 `true`,然后从扩展菜单首次安装梦三。在客户端的调试控制台执行以下代码,试用后将 `true` 改为 `false` 再执行一次。默认设置沿用逐文件下载,待手机实测通过后启用分包。
```js
const { game } = await import(new URL("noname.js", document.baseURI).href);
game.saveConfig("shuYing_mengsan_zip_trial", true);
```
每包按 5 MiB 的展开数据量分组,压缩包最大 6 MiB。大于展开上限的单文件继续逐个下载。客户端顺序处理同源同标签的附件,已校验并暂存的文件可供本次安装复用。附件缺失或无法使用时,剩余文件从当前标签的 raw 路径补齐。
Electron 走原生 HTTPS,Cordova 使用 `FileTransfer` 下载一包到当前操作的临时目录,读取前核对大小,处理结束后清理。网页端走 Fetch,附件域不可读时回退。ZIP 解压需要支持 `DecompressionStream("deflate-raw")`,不支持的客户端继续逐文件下载。
实测应记录手机型号、客户端版本、标签、下载源、请求数、总耗时和内存峰值,并分别验证 GitHub 和 Gitea 在游戏内可以下载附件及回退到同源逐文件下载。
发布时生成器会把 `tools/legacy/mengsan-files.json`、上一次完整清单和当前模块
文件合并,随新标签发布迁移路径清单。它用于接管旧安装中的梦三文件并清理
不再属于新版本的文件。该文件由迁移时仓库内的梦三路径生成,作为冻结的旧版
+82
View File
@@ -0,0 +1,82 @@
"""Build bounded ZIP attachments from the verified Mengsan release snapshot."""
import argparse
import hashlib
import json
import re
import zipfile
from pathlib import Path
from generate_manifest import validate_relative_paths
MAX_UNCOMPRESSED_BYTES = 5 * 1024**2
MAX_ARCHIVE_BYTES = 6 * 1024**2
def write_part(root: Path, part: Path, files: list[str], manifest: dict) -> None:
with zipfile.ZipFile(part, "w", zipfile.ZIP_DEFLATED, compresslevel=6, allowZip64=False) as archive:
for name in files:
source = (root / name).resolve()
if not source.is_relative_to(root) or source.stat().st_size != manifest[name]["size"]:
raise ValueError(f"Source size or path differs from manifest: {name}")
archive.write(source, name)
if part.stat().st_size > MAX_ARCHIVE_BYTES:
raise ValueError(f"ZIP size exceeds download limit: {part.name}")
with zipfile.ZipFile(part) as archive:
if archive.namelist() != files:
raise ValueError(f"Unexpected ZIP entries: {part.name}")
for entry in archive.infolist():
info = manifest[entry.filename]
if entry.file_size != info["size"]:
raise ValueError(f"ZIP entry size differs from manifest: {entry.filename}")
if hashlib.sha256(archive.read(entry)).hexdigest() != info["sha256"]:
raise ValueError(f"ZIP entry SHA-256 differs from manifest: {entry.filename}")
def build_archives(root: Path, output: Path, tag: str) -> list[Path]:
root = root.resolve()
manifest = json.loads((root / "dist/modules/mengsan.json").read_text(encoding="utf-8"))
if (not re.fullmatch(r"v\d+\.\d+\.\d+\.\d+(?:-rc\.\d+)?", tag)
or manifest.get("version") != tag[1:] or manifest.get("module_id") != "mengsan"):
raise ValueError("Mengsan manifest and release version do not match")
files = manifest["files"]
validate_relative_paths(list(files), "Mengsan manifest")
groups: list[list[str]] = []
group: list[str] = []
group_bytes = 0
for name, info in sorted(files.items()):
size = info["size"]
if not name.startswith("mengsan/") or "\\" in name or type(size) is not int or size < 0:
raise ValueError(f"Invalid Mengsan manifest entry: {name}")
if size > MAX_UNCOMPRESSED_BYTES:
continue
if group and group_bytes + size > MAX_UNCOMPRESSED_BYTES:
groups.append(group)
group = []
group_bytes = 0
group.append(name)
group_bytes += size
if group:
groups.append(group)
output.mkdir(parents=True)
parts = []
for index, names in enumerate(groups, 1):
part = output / f"mengsan-{tag}-part-{index:03}.zip"
write_part(root, part, names, files)
parts.append(part)
return parts
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--out-dir", required=True, type=Path)
parser.add_argument("--tag", required=True)
args = parser.parse_args()
parts = build_archives(args.root, args.out_dir, args.tag)
print(f"Verified {len(parts)} Mengsan ZIP parts for {args.tag}")
if __name__ == "__main__":
main()
+61
View File
@@ -0,0 +1,61 @@
import hashlib
import json
import tempfile
import unittest
import zipfile
from pathlib import Path
from unittest.mock import patch
from build_mengsan_archives import build_archives
class MengsanArchivesTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / "snapshot"
self.output = Path(self.temp.name) / "archives"
self.manifest = self.root / "dist/modules/mengsan.json"
self.manifest.parent.mkdir(parents=True)
def write_snapshot(self, files):
entries = {}
for name, data in files.items():
file = self.root / name
file.parent.mkdir(parents=True, exist_ok=True)
file.write_bytes(data)
entries[name] = {"size": len(data), "sha256": hashlib.sha256(data).hexdigest()}
self.manifest.write_text(json.dumps({
"version": "2.0.2.3-rc.8", "module_id": "mengsan", "files": entries,
}), encoding="utf-8")
def test_parts_cover_packable_files_once(self):
first = b"a" * (3 * 1024**2)
second = b"b" * (3 * 1024**2)
self.write_snapshot({
"mengsan/b": second,
"mengsan/oversized": b"c" * (5 * 1024**2 + 1),
"mengsan/a": first,
})
parts = build_archives(self.root, self.output, "v2.0.2.3-rc.8")
self.assertEqual([part.name for part in parts], [
"mengsan-v2.0.2.3-rc.8-part-001.zip", "mengsan-v2.0.2.3-rc.8-part-002.zip",
])
for part, name, data in zip(parts, ["mengsan/a", "mengsan/b"], [first, second], strict=True):
with zipfile.ZipFile(part) as archive:
self.assertEqual(archive.namelist(), [name])
self.assertEqual(archive.read(name), data)
def test_reject_inconsistent_release(self):
self.write_snapshot({"mengsan/a": b"a"})
with self.assertRaisesRegex(ValueError, "version"):
build_archives(self.root, self.output, "v2.0.2.3-rc.9")
(self.root / "mengsan/a").write_bytes(b"b")
with self.assertRaisesRegex(ValueError, "SHA-256"):
build_archives(self.root, self.output, "v2.0.2.3-rc.8")
def test_reject_archive_over_download_limit(self):
self.write_snapshot({"mengsan/a": b"a"})
with patch("build_mengsan_archives.MAX_ARCHIVE_BYTES", 50):
with self.assertRaisesRegex(ValueError, "ZIP size"):
build_archives(self.root, self.output, "v2.0.2.3-rc.8")
+352
View File
@@ -0,0 +1,352 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createHash, webcrypto } from "node:crypto";
import { EventEmitter } from "node:events";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { resolve } from "node:path";
import { Readable } from "node:stream";
import { test } from "node:test";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createContext, SourceTextModule, SyntheticModule } from "node:vm";
const engineRoot = process.env.NONAME_ROOT || fileURLToPath(new URL("../../../", import.meta.url));
const { default: JSZip } = await import(pathToFileURL(resolve(engineRoot, "_virtual/index2.js")));
const updaterSource = await readFile(new URL("../update.js", import.meta.url), "utf8");
const version = "2.0.2.3";
const tag = `v${version}`;
const moduleEntry = "mengsan/register.js";
const asset = "mengsan/assets/card.png";
const assets = { [moduleEntry]: "export default 1;", [asset]: "card data" };
const extensionRoot = "extension/术樱包/";
const recordKey = "shuYing_mengsan_installation";
function info(text) {
return { size: Buffer.byteLength(text), sha256: createHash("sha256").update(text).digest("hex") };
}
function zip(files) {
const archive = new JSZip();
for (const [name, data] of Object.entries(files)) archive.file(name, data);
return archive.generate({ type: "uint8array", compression: "DEFLATE" });
}
async function setup({ source = "github", parts = [zip(assets)], releaseTag = tag,
draft = false, failWrite = false, record, trial = true, transport = "browser",
blocksBrowserAssets = false, canInflate = true, localVersion = version } = {}) {
const github = source == "github";
const api = github ? "https://api.github.com/repos/Shu-Ying/noname-shuying"
: "https://gitea.diuse.work/api/v1/repos/Diuse/noname-shuying";
const repository = github ? "https://github.com/Shu-Ying/noname-shuying"
: "https://gitea.diuse.work/Diuse/noname-shuying";
const raw = path => github
? `https://raw.githubusercontent.com/Shu-Ying/noname-shuying/${tag}/${path}`
: `${api}/raw/${path}?ref=${tag}`;
const releaseUrl = `${api}/releases/tags/${tag}`;
const requests = [];
const writes = [];
const alerts = [];
const errors = [];
const files = new Map();
const config = { shuYing_update_source: source, shuYing_local_version: localVersion,
shuYing_mengsan_zip_trial: trial, [recordKey]: record };
const lib = { config, configprefix: "test_", node: {}, status: { reload: 0 } };
const game = {
checkFile(path, done) { done(files.has(path) ? 1 : -1); },
createDir(path, done) { done(); },
readFile(path, done, fail) {
if (files.has(path)) done(files.get(path));
else fail({ code: "ENOENT" });
},
writeFile(bytes, dir, name, done) {
const path = `${dir}/${name}`;
if (failWrite && path.includes("/new/mengsan/")) { done("disk is unwritable"); return; }
writes.push({ path, afterRequests: requests.length });
files.set(path, typeof bytes == "string" ? new TextEncoder().encode(bytes) : new Uint8Array(bytes));
done();
},
removeFile(path, done) { files.delete(path); done(); },
saveConfig(key, value) { config[key] = value; },
reload2() {},
};
const modulePath = "dist/modules/mengsan.json";
const rootManifest = { algorithm: "sha256", update_channels: true, version,
files: { "extension.js": info("main") },
modules: { mengsan: { entry: moduleEntry, manifest: modulePath } } };
const moduleManifest = { algorithm: "sha256", module_id: "mengsan", version,
files: Object.fromEntries(Object.entries(assets).map(([file, content]) => [file, info(content)])) };
const attachments = parts?.map((part, index) => {
const name = `mengsan-${tag}-part-${String(index + 1).padStart(3, "0")}.zip`;
const url = `${repository}/releases/download/${tag}/${name}`;
return { name, browser_download_url: url, size: part.size ?? (part.bytes?.length || part.length) };
});
const archiveAt = url => {
const index = attachments?.findIndex(part => part.browser_download_url == url) ?? -1;
return index < 0 ? null : parts[index].bytes || parts[index];
};
const window = {};
const storage = new Map();
const nativeRequests = [];
if (transport == "node") {
const redirect = "https://release-assets.githubusercontent.com/part.zip";
window.require = name => {
assert.equal(name, "https");
return { get(url, callback) {
const request = new EventEmitter();
request.destroy = error => { if (error) request.emit("error", error); };
queueMicrotask(() => {
nativeRequests.push(String(url));
const redirected = String(url) == redirect;
const stream = Readable.from(redirected ? [archiveAt(attachments[0].browser_download_url)] : []);
stream.statusCode = redirected ? 200 : 302;
stream.headers = redirected ? {} : { location: redirect };
callback(stream);
stream.on("close", () => request.emit("close"));
});
return request;
} };
};
}
class TestFileReader {
readAsArrayBuffer(file) { file.arrayBuffer().then(result => { this.result = result; this.onload(); }); }
}
if (transport == "cordova") {
lib.device = "android";
delete lib.node;
storage.set("noname_inited", "file:///sandbox/");
window.resolveLocalFileSystemURL = (root, done) => done({
getFile(path, options, found, missing) {
if (options.create && !files.has(path)) files.set(path, new Uint8Array());
if (!files.has(path)) { missing({ code: 1 }); return; }
found({ isFile: true, toURL: () => encodeURI(root + path),
file: done => done(Object.assign(new Blob([files.get(path)]), { lastModified: 1 })),
remove: done => { files.delete(path); done(); },
createWriter(done) {
done({ truncate() { this.onwriteend(); }, write(blob) {
blob.arrayBuffer().then(bytes => {
files.set(path, new Uint8Array(bytes));
this.onwriteend();
});
} });
},
});
},
});
window.FileTransfer = class {
download(url, target, done) {
nativeRequests.push(url);
const bytes = archiveAt(url);
files.set(decodeURI(target).slice("file:///sandbox/".length), bytes);
this.onprogress({ loaded: bytes.length });
done();
}
abort() { throw new Error("Unexpected abort"); }
};
}
const fetch = async url => {
requests.push(url);
if (url.startsWith(`${api}/tags?`)) return Response.json([{ name: tag }]);
if (url == raw("dist/manifest.json")) return Response.json(rootManifest);
if (url == raw(modulePath)) return Response.json(moduleManifest);
if (url == releaseUrl) return parts ? Response.json({ tag_name: releaseTag, draft, assets: attachments })
: new Response(null, { status: 404 });
const partIndex = attachments?.findIndex(part => part.browser_download_url == url) ?? -1;
if (partIndex >= 0) {
if (blocksBrowserAssets) throw new TypeError("Failed to fetch");
const part = parts[partIndex];
if (part.retry && requests.filter(request => request == url).length == 1) {
return new Response(null, { status: 503 });
}
return new Response(part.bytes || part);
}
for (const [file, content] of Object.entries({ ...assets, "extension.js": "main" })) {
if (url == raw(file)) return new Response(content);
}
return new Response(null, { status: 404 });
};
const body = {
appendChild(node) { node.parentNode = this; },
removeChild(node) { node.parentNode = null; },
};
const context = createContext({
AbortController, DecompressionStream: canInflate ? DecompressionStream : undefined,
URL, TextDecoder, TextEncoder, Uint8Array, ArrayBuffer, setTimeout, clearTimeout,
fetch, crypto: webcrypto, window, document: { body }, Blob, FileReader: TestFileReader,
TypeError,
localStorage: { getItem: key => storage.get(key), setItem: (key, value) => storage.set(key, value) },
console: { error: error => errors.push(error), warn() {} },
confirm: () => true, alert: message => alerts.push(message),
});
const engine = new SyntheticModule(["lib", "game", "get"], function () {
this.setExport("lib", lib);
this.setExport("game", game);
this.setExport("get", { zip: callback => callback(new JSZip()) });
}, { context });
const module = new SourceTextModule(updaterSource, { context });
await module.link(() => engine);
await module.evaluate();
const shuYing = { text: { style: {}, showPopover() {}, setAttribute() {}, matches: () => false } };
return { updater: module.namespace.default, shuYing, requests, releaseUrl, raw, attachments, nativeRequests,
writes, config, files, alerts, errors };
}
async function install(options) {
const result = await setup(options);
await result.updater.manageMengsanModule(result.shuYing);
return result;
}
function assertInstalled(result) {
assert.deepEqual(result.errors, []);
assert.equal(result.config[recordKey]?.status, "installed", result.alerts.join("\n"));
for (const [file, content] of Object.entries(assets)) {
assert.equal(new TextDecoder().decode(result.files.get(extensionRoot + file)), content);
}
}
for (const source of ["github", "gitea"]) {
test(`fresh install stages both parts from the selected ${source} release`, async () => {
const result = await install({ source, parts: [zip({ [moduleEntry]: assets[moduleEntry] }), zip({ [asset]: assets[asset] })] });
assertInstalled(result);
const first = result.requests.indexOf(result.attachments[0].browser_download_url);
const second = result.requests.indexOf(result.attachments[1].browser_download_url);
assert.ok(first > result.requests.indexOf(result.releaseUrl));
assert.ok(second > first);
assert.ok(result.writes.find(write => write.path.endsWith(`/new/${moduleEntry}`)).afterRequests <= second);
assert.ok(result.writes.find(write => write.path == extensionRoot + moduleEntry).afterRequests > second);
assert.ok(!result.requests.includes(result.raw(moduleEntry)));
assert.ok(!result.requests.includes(result.raw(asset)));
});
}
test("carries staged files through a hash mismatch and falls back within the same tag", async () => {
const result = await install({ parts: [zip({ [moduleEntry]: assets[moduleEntry], [asset]: "bad! data" })] });
assertInstalled(result);
assert.equal(result.requests.filter(url => url == result.attachments[0].browser_download_url).length, 2);
assert.ok(result.requests.includes(result.raw(asset)));
assert.ok(!result.requests.includes(result.raw(moduleEntry)));
});
test("retries a transient ZIP download error before using its contents", async () => {
const result = await install({ parts: [{ bytes: zip(assets), retry: true }] });
assertInstalled(result);
assert.equal(result.requests.filter(url => url == result.attachments[0].browser_download_url).length, 2);
assert.ok(!result.requests.includes(result.raw(asset)));
});
for (const [description, options] of Object.entries({
"missing release": { parts: null },
"wrong release tag": { releaseTag: "v1.0.0.0" },
"draft release": { draft: true },
"invalid ZIP": { parts: [new Uint8Array([1, 2, 3])] },
"ZIP contains unlisted entries": { parts: [zip({ ...assets, "../unexpected.js": "x" })] },
"ZIP above the download budget": { parts: [new Uint8Array(6 * 1024**2 + 1)] },
"response larger than its attachment metadata": { parts: [{ size: 1, bytes: zip(assets) }] },
})) {
test(`uses same-tag raw after ${description}`, async () => {
const result = await install(options);
assertInstalled(result);
assert.ok(result.requests.includes(result.releaseUrl));
assert.ok(result.requests.includes(result.raw(moduleEntry)));
assert.ok(result.requests.includes(result.raw(asset)));
assert.ok(!result.writes.some(write => write.path.includes("unexpected.js")));
});
}
test("a staging storage failure stops the ZIP install without raw retries", async () => {
const result = await install({ failWrite: true });
assert.equal(result.config[recordKey]?.status, "disabled");
assert.match(result.alerts[0], /disk is unwritable/);
assert.ok(result.requests.includes(result.attachments[0].browser_download_url));
assert.ok(!result.requests.includes(result.raw(moduleEntry)));
assert.ok(!result.files.has(extensionRoot + moduleEntry));
});
test("restoring a legacy pending installation stays on raw", async () => {
const result = await install({ record: { status: "repair", version, files: [moduleEntry, asset] } });
assertInstalled(result);
assert.ok(!result.requests.includes(result.releaseUrl));
assert.ok(result.requests.includes(result.raw(asset)));
});
test("restarts a known first installation using a fresh ZIP download", async () => {
const result = await install({ record: { status: "installing", version, files: [moduleEntry, asset], freshInstall: true } });
assertInstalled(result);
assert.ok(result.requests.includes(result.attachments[0].browser_download_url));
assert.ok(!result.requests.includes(result.raw(asset)));
});
test("fresh install uses raw with the trial disabled", async () => {
const result = await install({ trial: false });
assertInstalled(result);
assert.ok(!result.requests.includes(result.releaseUrl));
assert.ok(result.requests.includes(result.raw(asset)));
});
for (const transport of ["node", "cordova"]) {
test(`uses ${transport} transfer for GitHub assets when browser Fetch cannot read them`, async () => {
const result = await install({ transport, blocksBrowserAssets: true });
assertInstalled(result);
assert.equal(result.nativeRequests[0], result.attachments[0].browser_download_url);
if (transport == "node") assert.equal(result.nativeRequests[1], "https://release-assets.githubusercontent.com/part.zip");
assert.ok(!result.requests.includes(result.raw(asset)));
assert.ok(!Array.from(result.files.keys()).some(path => path.endsWith(".zip")));
});
}
test("an unavailable browser attachment origin skips the remaining ZIP requests", async () => {
const result = await install({ blocksBrowserAssets: true, parts: [zip(assets), zip(assets)] });
assertInstalled(result);
assert.ok(result.requests.includes(result.attachments[0].browser_download_url));
assert.ok(!result.requests.includes(result.attachments[1].browser_download_url));
assert.ok(result.requests.includes(result.raw(asset)));
});
test("a WebView without streaming inflate uses raw before requesting ZIPs", async () => {
const result = await install({ canInflate: false });
assertInstalled(result);
assert.ok(!result.requests.includes(result.releaseUrl));
assert.ok(result.requests.includes(result.raw(asset)));
});
test("downloads and extracts a ZIP generated by the release script", async () => {
const temp = await mkdtemp(resolve(tmpdir(), "shuying-archive-test-"));
try {
const root = resolve(temp, "snapshot");
const output = resolve(temp, "parts");
const manifest = resolve(root, "dist/modules/mengsan.json");
await mkdir(resolve(root, "dist/modules"), { recursive: true });
await mkdir(resolve(root, "mengsan/assets"), { recursive: true });
const fileInfo = {};
for (const [file, content] of Object.entries(assets)) {
await writeFile(resolve(root, file), content);
fileInfo[file] = info(content);
}
await writeFile(manifest, JSON.stringify({ version, module_id: "mengsan", files: fileInfo }));
const script = fileURLToPath(new URL("build_mengsan_archives.py", import.meta.url));
execFileSync("python", ["-B", script, "--root", root, "--out-dir", output, "--tag", tag]);
const bytes = await readFile(resolve(output, `mengsan-${tag}-part-001.zip`));
const result = await install({ parts: [bytes] });
assertInstalled(result);
assert.ok(!result.requests.includes(result.raw(asset)));
}
finally { await rm(temp, { recursive: true, force: true }); }
});
test("查漏补缺 of an installed module stays on raw with the trial enabled", async () => {
const result = await setup({ record: { status: "installed", version, source: "github", files: [moduleEntry, asset] } });
await result.updater.repairMissingFiles(result.shuYing);
assertInstalled(result);
assert.ok(result.requests.includes(result.raw(asset)));
assert.ok(!result.requests.includes(result.releaseUrl));
});
test("an installed module version update stays on raw with the trial enabled", async () => {
const localVersion = "2.0.2.2";
const result = await setup({ localVersion,
record: { status: "installed", version: localVersion, source: "github", files: [moduleEntry, asset] } });
await result.updater.checkVersion(result.shuYing);
assertInstalled(result);
assert.ok(result.requests.includes(result.raw(asset)));
assert.ok(!result.requests.includes(result.releaseUrl));
});