diff --git a/.claude/settings.json b/.claude/settings.json deleted file mode 100644 index 36f5c91..0000000 --- a/.claude/settings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/claude-code-settings.json", - "extraKnownMarketplaces": { - "impeccable": { - "source": { "source": "github", "repo": "pbakaus/impeccable" } - } - }, - "enabledPlugins": { - "impeccable@impeccable": true, - "mattpocock-skills@claude-plugins-official": true - } -} diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 1d5832b..0000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,185 +0,0 @@ -# Verified external application patches are candidates for gated auto-merge. -# Mod runtime compatibility is governed by ADR-0010, not package SemVer. -version: 2 -updates: - - package-ecosystem: 'npm' - directory: '/' - schedule: - interval: 'weekly' - open-pull-requests-limit: 3 - cooldown: - default-days: 7 - commit-message: - prefix: 'build(release)' - groups: - tooling: - patterns: ['*'] - update-types: ['patch'] - minor-updates: - patterns: ['*'] - update-types: ['minor'] - - package-ecosystem: 'npm' - directory: '/bazaarplusplus-site' - schedule: - interval: 'weekly' - open-pull-requests-limit: 3 - cooldown: - default-days: 7 - commit-message: - prefix: 'build(site)' - # Coupled toolchain majors need a deliberate compatibility upgrade. - ignore: - - dependency-name: 'typescript' - update-types: ['version-update:semver-major'] - - dependency-name: 'oxlint-tsgolint' - update-types: ['version-update:semver-major'] - groups: - typescript: - patterns: ['typescript', 'oxlint*'] - update-types: ['patch'] - react: - patterns: ['react', 'react-dom', '@types/react', '@types/react-dom'] - update-types: ['patch'] - cloudflare: - patterns: ['wrangler', 'miniflare', '@cloudflare/*'] - update-types: ['patch'] - other: - patterns: ['*'] - update-types: ['patch'] - minor-updates: - patterns: ['*'] - update-types: ['minor'] - - package-ecosystem: 'npm' - directory: '/bazaarplusplus-server' - schedule: - interval: 'weekly' - open-pull-requests-limit: 3 - cooldown: - default-days: 7 - commit-message: - prefix: 'build(server)' - # Coupled toolchain majors need a deliberate compatibility upgrade. - ignore: - - dependency-name: 'vitest' - update-types: ['version-update:semver-major'] - - dependency-name: '@vitest/*' - update-types: ['version-update:semver-major'] - groups: - cloudflare: - patterns: - ['wrangler', 'miniflare', '@cloudflare/*', 'vitest', '@vitest/*'] - update-types: ['patch'] - other: - patterns: ['*'] - update-types: ['patch'] - minor-updates: - patterns: ['*'] - update-types: ['minor'] - cloudflare-security: - applies-to: security-updates - patterns: ['wrangler', 'miniflare', 'undici', '@cloudflare/*'] - - package-ecosystem: 'npm' - directory: '/bazaarplusplus-installer' - schedule: - interval: 'weekly' - open-pull-requests-limit: 3 - cooldown: - default-days: 7 - commit-message: - prefix: 'build(installer)' - # Coupled toolchain majors need a deliberate compatibility upgrade. - ignore: - - dependency-name: 'typescript' - update-types: ['version-update:semver-major'] - - dependency-name: 'oxlint-tsgolint' - update-types: ['version-update:semver-major'] - groups: - typescript: - patterns: ['typescript', 'oxlint*'] - update-types: ['patch'] - react: - patterns: ['react', 'react-dom', '@types/react', '@types/react-dom'] - update-types: ['patch'] - tauri: - patterns: ['@tauri-apps/*'] - update-types: ['patch'] - other: - patterns: ['*'] - update-types: ['patch'] - minor-updates: - patterns: ['*'] - update-types: ['minor'] - - package-ecosystem: 'cargo' - directory: '/bazaarplusplus-installer/src-tauri' - schedule: - interval: 'weekly' - open-pull-requests-limit: 3 - cooldown: - default-days: 7 - commit-message: - prefix: 'build(installer)' - groups: - specta: - patterns: ['specta', 'specta-typescript', 'tauri-specta'] - update-types: ['patch'] - tauri: - patterns: ['tauri', 'tauri-*'] - update-types: ['patch'] - other: - patterns: ['*'] - update-types: ['patch'] - minor-updates: - patterns: ['*'] - update-types: ['minor'] - - package-ecosystem: 'uv' - directory: '/bazaarplusplus-analyzer' - schedule: - interval: 'weekly' - open-pull-requests-limit: 3 - cooldown: - default-days: 7 - commit-message: - prefix: 'build(analyzer)' - groups: - python: - patterns: ['*'] - update-types: ['patch'] - minor-updates: - patterns: ['*'] - update-types: ['minor'] - - package-ecosystem: 'nuget' - # Match nested manifests as well as central package management. - directories: - - '/bazaarplusplus-mod' - - '/bazaarplusplus-mod/src/*' - - '/bazaarplusplus-mod/tests/*' - # Default-deny: build-time generators/publicizers can break runtime too. - # A PR diff guard also rejects changes to production files and lock graphs. - allow: - - dependency-name: 'Microsoft.NET.Test.Sdk' - - dependency-name: 'xunit' - - dependency-name: 'xunit.runner.visualstudio' - schedule: - interval: 'weekly' - open-pull-requests-limit: 3 - cooldown: - default-days: 7 - commit-message: - prefix: 'build(mod)' - groups: - test-tools: - patterns: ['*'] - update-types: ['minor', 'patch'] - - package-ecosystem: 'github-actions' - directory: '/' - schedule: - interval: 'weekly' - open-pull-requests-limit: 3 - cooldown: - default-days: 7 - commit-message: - prefix: 'build(dev)' - groups: - actions: - patterns: ['*'] - update-types: ['minor', 'patch'] diff --git a/.github/scripts/analyzer-state.sh b/.github/scripts/analyzer-state.sh deleted file mode 100644 index dde82a7..0000000 --- a/.github/scripts/analyzer-state.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# Mirrors the analyzer Data Root (BPP_DATA_ROOT) to and from its private R2 -# state bucket for .github/workflows/analyzer.yml, which runs on a fresh runner -# every time. Hourly commits and day seals are immutable and carry their own -# sha256 (bazaarplusplus-analyzer/docs/architecture.md), so `bpp verify --deep` -# after a pull proves the restore. Lock and staging entries are never mirrored. -# -# analyzer-state.sh pull copy the bucket into an empty Data Root -# analyzer-state.sh push mirror the Data Root, deleting what retention -# pruned; only after a successful run -# analyzer-state.sh push-new upload new and changed files, delete nothing; -# after a failed run -# -# The mirror runs on the analyzer's locked boto3 dependency -# (.github/scripts/analyzer_state.py). It must not shell out to the AWS CLI: -# ubuntu-latest moved to Ubuntu 26 on 2026-10-19 and the runner no longer ships -# `aws`, which failed every production run at `Restore the Data Root`. -# -# Reads BPP_DATA_ROOT, BPP_ANALYZER_STATE_BUCKET, CLOUDFLARE_ACCOUNT_ID and -# BPP_ANALYZER_R2_TOKEN. -set -euo pipefail - -: "${BPP_DATA_ROOT:?}" "${BPP_ANALYZER_STATE_BUCKET:?}" "${CLOUDFLARE_ACCOUNT_ID:?}" -: "${BPP_ANALYZER_R2_TOKEN:?}" - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -analyzer_root="${repo_root}/bazaarplusplus-analyzer" - -cd "${analyzer_root}" -uv run --locked --no-dev python "${repo_root}/.github/scripts/analyzer_state.py" "$1" \ - --data-root "${BPP_DATA_ROOT}" \ - --bucket "${BPP_ANALYZER_STATE_BUCKET}" \ - --account-id "${CLOUDFLARE_ACCOUNT_ID}" \ - --api-token "${BPP_ANALYZER_R2_TOKEN}" diff --git a/.github/scripts/analyzer_state.py b/.github/scripts/analyzer_state.py deleted file mode 100644 index 9a67286..0000000 --- a/.github/scripts/analyzer_state.py +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/env python3 -"""Mirror the analyzer Data Root (BPP_DATA_ROOT) to and from its private R2 bucket. - -Replaces ``aws s3 sync`` in ``.github/scripts/analyzer-state.sh``. The workflow -never installed the AWS CLI, so the restore step depended on whatever the runner -image happened to ship; when ubuntu-latest migrated on 2026-10-19 that dependency -disappeared and every run failed at ``Restore the Data Root``. boto3 is already a -locked analyzer dependency, so mirroring through it removes the ambient-CLI -requirement entirely. - -Semantics match the previous ``aws s3 sync`` invocations: - pull copy the bucket into an empty Data Root - push mirror the Data Root, deleting what retention pruned - push-new upload new and changed files, delete nothing - -Hourly commits and day seals are immutable and carry their own sha256 -(bazaarplusplus-analyzer/docs/architecture.md), so ``bpp verify --deep`` after a -pull proves the restore. Lock and staging entries are never mirrored. -""" - -from __future__ import annotations - -import argparse -import hashlib -import sys -from pathlib import Path, PurePosixPath - - -def _excluded(key: str) -> bool: - """DirectoryLock, durable.atomic_replace and FactStore staging names.""" - parts = PurePosixPath(key).parts - if not parts: - return True - if parts[0] == "duckdb-tmp": - return True - return any(part.startswith(".lock") or ".tmp-" in part for part in parts) - - -def _local_files(root: Path) -> dict[str, Path]: - files: dict[str, Path] = {} - for path in root.rglob("*"): - if not path.is_file(): - continue - key = path.relative_to(root).as_posix() - if _excluded(key): - continue - files[key] = path - return files - - -def _remote_entries(client, bucket: str) -> dict[str, tuple[int, str | None]]: - """Size and MD5 ETag per key; multipart ETags (``...-N``) are not MD5s.""" - entries: dict[str, tuple[int, str | None]] = {} - paginator = client.get_paginator("list_objects_v2") - for page in paginator.paginate(Bucket=bucket): - for entry in page.get("Contents", []): - key = entry["Key"] - if _excluded(key): - continue - etag = str(entry.get("ETag", "")).strip('"') or None - entries[key] = (int(entry["Size"]), None if etag and "-" in etag else etag) - return entries - - -def _md5(path: Path) -> str: - digest = hashlib.md5() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - return digest.hexdigest() - - -def pull(client, bucket: str, root: Path) -> None: - if root.exists() and any(root.iterdir()): - raise SystemExit(f"::error::{root} must be empty before a pull") - root.mkdir(parents=True, exist_ok=True) - keys = sorted(_remote_entries(client, bucket)) - for index, key in enumerate(keys, start=1): - body = client.get_object(Bucket=bucket, Key=key)["Body"].read() - target = root / key - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(body) - if index % 500 == 0: - print(f"pulled {index}/{len(keys)} objects", flush=True) - print(f"pulled {len(keys)} objects into {root}", flush=True) - - -def push(client, bucket: str, root: Path, *, delete_extra: bool) -> None: - local = _local_files(root) - remote = _remote_entries(client, bucket) - - uploaded = 0 - for key, path in sorted(local.items()): - size = path.stat().st_size - remote_size, remote_md5 = remote.get(key, (-1, None)) - # Compare content, not just length: a same-size rewrite must still upload. - # A multipart ETag cannot prove equality, so it falls back to uploading. - unchanged = remote_size == size and remote_md5 == _md5(path) - if not unchanged: - client.put_object(Bucket=bucket, Key=key, Body=path.read_bytes()) - uploaded += 1 - print(f"uploaded {uploaded} of {len(local)} objects", flush=True) - - if not delete_extra: - return - # Only a fully successful run mirrors deletions; retention already pruned locally. - deleted = 0 - for key in sorted(set(remote) - set(local)): - client.delete_object(Bucket=bucket, Key=key) - deleted += 1 - print(f"deleted {deleted} objects removed by retention", flush=True) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("command", choices=("pull", "push", "push-new")) - parser.add_argument("--data-root", required=True) - parser.add_argument("--bucket", required=True) - parser.add_argument("--account-id", required=True) - parser.add_argument("--api-token", required=True) - args = parser.parse_args(argv) - - # Imported here so the module can be imported (and unit-tested) without the - # analyzer's locked dependency set installed. - analyzer_src = Path(__file__).resolve().parents[2] / "bazaarplusplus-analyzer" / "src" - sys.path.insert(0, str(analyzer_src)) - from bppanalyzer.object_store import R2ObjectStore - - store = R2ObjectStore( - account_id=args.account_id, - bucket=args.bucket, - api_token=args.api_token, - ) - root = Path(args.data_root) - client = store._client - - if args.command == "pull": - pull(client, store.bucket, root) - elif args.command == "push": - push(client, store.bucket, root, delete_extra=True) - else: - push(client, store.bucket, root, delete_extra=False) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/.github/scripts/check_mod_dependency_update.py b/.github/scripts/check_mod_dependency_update.py deleted file mode 100644 index a15de6e..0000000 --- a/.github/scripts/check_mod_dependency_update.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Keep dependency bots from changing Mod runtime inputs (ADR-0010). - -The NuGet allowlist controls direct updates; this checks the resulting diff, -including transitive lockfile churn. It does not certify game compatibility. -""" - -import argparse -import subprocess -import xml.etree.ElementTree as ET - -TEST_TOOLS = frozenset({"Microsoft.NET.Test.Sdk", "xunit", "xunit.runner.visualstudio"}) -CENTRAL_PACKAGES = "bazaarplusplus-mod/Directory.Packages.props" - - -def package_structure(source): - root = ET.fromstring(source) - for package in root.iter("PackageVersion"): - if package.get("Include") in TEST_TOOLS and "Version" in package.attrib: - package.set("Version", "") - - def structure(element): - return ( - element.tag, - sorted(element.attrib.items()), - (element.text or "").strip(), - (element.tail or "").strip(), - [structure(child) for child in element], - ) - - return structure(root) - - -def validate_changes(changes): - """changes maps each changed path to its (base bytes, head bytes).""" - problems = [] - for path, (before, after) in changes.items(): - if not path.startswith("bazaarplusplus-mod/"): - continue - if path != CENTRAL_PACKAGES or before is None or after is None: - problems.append(f"{path}: requires manual Mod dependency maintenance") - continue - try: - if package_structure(before) != package_structure(after): - problems.append(f"{path}: only existing test-tool versions may change") - except ET.ParseError: - problems.append(f"{path}: invalid MSBuild XML") - return problems - - -def git(*args): - return subprocess.check_output(["git", *args]) - - -def read_file(revision, path): - result = subprocess.run(["git", "show", f"{revision}:{path}"], capture_output=True, check=False) - return result.stdout if result.returncode == 0 else None - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("base") - parser.add_argument("head") - args = parser.parse_args() - # Resolve revisions first: a missing commit must never look like an empty diff. - base = git("rev-parse", "--verify", f"{args.base}^{{commit}}").decode().strip() - head = git("rev-parse", "--verify", f"{args.head}^{{commit}}").decode().strip() - base = git("merge-base", base, head).decode().strip() - names = ( - git("diff", "--name-only", "--no-renames", "-z", base, head, "--", "bazaarplusplus-mod/") - .decode() - .split("\0") - ) - problems = validate_changes( - {path: (read_file(base, path), read_file(head, path)) for path in names if path} - ) - if problems: - raise SystemExit("\n".join(problems) + "\nSee ADR-0010 and docs/development.md.") - print("Bot Mod changes are limited to test-tool versions; game compatibility was not tested.") - - -if __name__ == "__main__": - main() diff --git a/.github/scripts/check_toml_dependency_update.py b/.github/scripts/check_toml_dependency_update.py deleted file mode 100644 index 68a0023..0000000 --- a/.github/scripts/check_toml_dependency_update.py +++ /dev/null @@ -1,207 +0,0 @@ -"""Compare Cargo/uv dependency data without executing package or PR code.""" - -import copy -import json -import re -import sys -import tomllib -from urllib.parse import urlsplit - -CRATES = "registry+https://github.com/rust-lang/crates.io-index" -PYPI = {"registry": "https://pypi.org/simple"} - - -def patch(old, new): - pattern = r"(\^|~|==|=)?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)" - a = re.fullmatch(pattern, old) if isinstance(old, str) else None - b = re.fullmatch(pattern, new) if isinstance(new, str) else None - return bool(a and b and a.groups()[:3] == b.groups()[:3] and int(b[4]) > int(a[4])) - - -def cargo_manifest(before, after): - for field in ("dependencies", "dev-dependencies", "build-dependencies"): - for name, old in before.get(field, {}).items(): - new = after.get(field, {}).get(name) - if patch(old, new): - after[field][name] = old - elif ( - isinstance(old, dict) - and isinstance(new, dict) - and patch(old.get("version"), new.get("version")) - ): - new["version"] = old["version"] - for name, target in before.get("target", {}).items(): - if name in after.get("target", {}): - cargo_manifest(target, after["target"][name]) - - -def requirement_list(before, after): - if ( - not isinstance(before, list) - or not isinstance(after, list) - or len(before) != len(after) - ): - return - # Exact pins used by this project; extras, markers and package identity stay intact. - pattern = r"([A-Za-z0-9_.-]+(?:\[[^\]]+\])?)(==\d+\.\d+\.\d+)(\s*;.*)?" - for i, (old, new) in enumerate(zip(before, after, strict=True)): - a = re.fullmatch(pattern, old) if isinstance(old, str) else None - b = re.fullmatch(pattern, new) if isinstance(new, str) else None - if a and b and a[1] == b[1] and a[3] == b[3] and patch(a[2], b[2]): - after[i] = old - - -def uv_manifest(before, after): - requirement_list( - before.get("project", {}).get("dependencies"), - after.get("project", {}).get("dependencies"), - ) - requirement_list( - before.get("build-system", {}).get("requires"), - after.get("build-system", {}).get("requires"), - ) - for old, new in ( - (before.get("dependency-groups", {}), after.get("dependency-groups", {})), - ( - before.get("project", {}).get("optional-dependencies", {}), - after.get("project", {}).get("optional-dependencies", {}), - ), - ): - for name, requirements in old.items(): - requirement_list(requirements, new.get(name)) - - -def package_index(packages): - result = {} - for package in packages: - version = package["version"] - # Multiple major/minor lanes coexist in Cargo; do not collapse them by name. - lane = ( - ".".join(version.split(".")[:2]) - if re.fullmatch(r"\d+\.\d+\.\d+", version) - else version - ) - key = (package["name"], json.dumps(package.get("source"), sort_keys=True), lane) - if key in result: - raise ValueError("ambiguous packages in the same version lane") - result[key] = package - return result - - -def uv_edges(before, after, changes): - """Normalize only version-qualified references and exact direct-dependency pins.""" - if isinstance(before, dict) and isinstance(after, dict): - for field in ("version", "specifier"): - if ( - field in before - and field in after - and before.get("name") == after.get("name") - ): - name = before.get("name") - old = before[field].removeprefix("==") - new = after[field].removeprefix("==") - if changes.get((name, new)) == old and patch( - before[field], after[field] - ): - after[field] = before[field] - for key in before.keys() & after.keys(): - uv_edges(before[key], after[key], changes) - elif ( - isinstance(before, list) - and isinstance(after, list) - and len(before) == len(after) - ): - for old, new in zip(before, after, strict=True): - uv_edges(old, new, changes) - - -def valid_artifact(artifact): - url = urlsplit(artifact.get("url", "")) - return ( - url.scheme == "https" - and url.hostname == "files.pythonhosted.org" - and url.username is None - and url.password is None - and url.port in (None, 443) - and not url.query - and not url.fragment - and re.fullmatch(r"sha256:[0-9a-f]{64}", artifact.get("hash", "")) is not None - ) - - -def patch_only(kind, before_manifest, after_manifest, before_lock, after_lock): - manifest, lock = copy.deepcopy(after_manifest), copy.deepcopy(after_lock) - if kind == "cargo": - cargo_manifest(before_manifest, manifest) - if before_lock.get("version") != 4 or lock.get("version") != 4: - return False - elif kind == "uv": - uv_manifest(before_manifest, manifest) - if (before_lock.get("version"), before_lock.get("revision")) != (1, 3): - return False - else: - return False - if manifest != before_manifest: - return False - before = package_index(before_lock["package"]) - after = package_index(lock["package"]) - if before.keys() != after.keys(): - return False - changes = {} - for key, old in before.items(): - new = after[key] - if old["version"] == new["version"]: - continue - if not patch(old["version"], new["version"]): - return False - identity = (new["name"], new["version"]) - if identity in changes: - return False - changes[identity] = old["version"] - if kind == "cargo": - if old.get("source") != CRATES or not re.fullmatch( - r"[0-9a-f]{64}", new.get("checksum", "") - ): - return False - new["checksum"] = old["checksum"] - else: - if old.get("source") != PYPI: - return False - artifacts = new.get("wheels", []) + ( - [new["sdist"]] if "sdist" in new else [] - ) - if not artifacts or not all(valid_artifact(item) for item in artifacts): - return False - for field in ("sdist", "wheels"): - new.pop(field, None) - if field in old: - new[field] = old[field] - new["version"] = old["version"] - for key, old in before.items(): - new = after[key] - if kind == "cargo": - for i, edge in enumerate(new.get("dependencies", [])): - fields = edge.split(" ", 2) - if len(fields) >= 2 and (fields[0], fields[1]) in changes: - fields[1] = changes[(fields[0], fields[1])] - new["dependencies"][i] = " ".join(fields) - else: - uv_edges(old, new, changes) - # Canonicalize order only; package membership, features and graph edges must match. - lock["package"] = [after[key] for key in sorted(after)] - original = {**before_lock, "package": [before[key] for key in sorted(before)]} - return bool(changes) and original == lock - - -def main(): - request = json.load(sys.stdin) - try: - documents = [tomllib.loads(text) for text in request["documents"]] - allowed = patch_only(request["kind"], *documents) - except (ValueError, KeyError, TypeError, AttributeError): - allowed = False - print(json.dumps(allowed)) - - -if __name__ == "__main__": - main() diff --git a/.github/scripts/checks-scope.mjs b/.github/scripts/checks-scope.mjs deleted file mode 100644 index 000dac6..0000000 --- a/.github/scripts/checks-scope.mjs +++ /dev/null @@ -1,367 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { execFileSync } from 'node:child_process'; - -export const PROJECTS = ['site', 'server', 'analyzer', 'installer', 'mod']; -const PROJECT_SCOPES = { - installer: ['installer-frontend', 'installer-macos', 'installer-windows'], - mod: ['mod-macos', 'mod-windows'] -}; -export const SCOPES = [ - 'release', - ...PROJECTS.flatMap((project) => PROJECT_SCOPES[project] ?? [project]), - 'macos-icon' -]; - -// Only known frontend inputs may avoid native verification. New build inputs -// default to native; generated bindings must be checked against a real export. -export function installerFrontendOnly(file) { - const relative = file.slice('bazaarplusplus-installer/'.length); - if (relative.startsWith('src/types/generated/')) return false; - return ( - ['src/', 'static/', 'docs/'].some((prefix) => - relative.startsWith(prefix) - ) || - /^[^/]+\.md$/.test(relative) || - [ - 'index.html', - 'vite.config.ts', - 'vitest.config.ts', - 'tsconfig.json', - '.oxlintrc.json', - '.prettierrc.json', - '.prettierignore', - 'LICENSE' - ].includes(relative) - ); -} - -export function manualSelection(inputs = {}) { - const scope = inputs.scope ?? 'full'; - const platform = inputs.platform ?? 'all'; - if ( - !['full', 'installer', 'mod'].includes(scope) || - !['all', 'macos', 'windows'].includes(platform) - ) { - throw new Error(`Invalid manual selection: ${scope}/${platform}`); - } - return { scope, platform }; -} - -export function manualScope(inputs) { - const { scope, platform } = manualSelection(inputs); - return Object.fromEntries( - SCOPES.map((lane) => { - const inScope = - scope === 'full' || - lane.startsWith(`${scope}-`) || - (scope === 'installer' && lane === 'macos-icon'); - const inPlatform = - platform === 'all' || - (!lane.endsWith('-macos') && - !lane.endsWith('-windows') && - lane !== 'macos-icon') || - lane.endsWith(`-${platform}`) || - (platform === 'macos' && lane === 'macos-icon'); - return [ - lane, - inScope && inPlatform ? [`Manual selection: ${scope}/${platform}`] : [] - ]; - }) - ); -} - -// Path expansions, not another contract definition. Owners are documented in -// AGENTS.md; executable references are checked below on every classification. -export const SHARED_INPUTS = [ - ['bazaarplusplus-server/contracts/', ['mod', 'analyzer']], - ['bazaarplusplus-server/docs/api-reference.md', ['mod']], - ['bazaarplusplus-analyzer/contracts/', ['site', 'mod', 'installer']], - [ - 'bazaarplusplus-analyzer/docs/specs/consumer-data-contract.md', - ['site', 'mod', 'installer'] - ], - ['bazaarplusplus-mod/docs/contracts/', ['server', 'analyzer']], - [ - 'bazaarplusplus-mod/tests/BundleV6Codec.Tests/fixtures/', - ['server', 'analyzer'] - ], - [ - 'bazaarplusplus-mod/tests/BundleQueueSqliteStore.Tests/fixtures/', - ['installer'] - ], - [ - 'bazaarplusplus-mod/src/BazaarPlusPlus.Storage/history-database-v6.schema.sql', - ['installer', 'release'] - ], - ['bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BundleQueue/', ['installer']], - [ - 'bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs', - ['installer', 'release'] - ], - [ - 'bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json', - ['installer', 'release'] - ], - ['bazaarplusplus-mod/build/game-libs.lock.json', ['release']], - ['bazaarplusplus-mod/global.json', ['release']], - ['bazaarplusplus-installer/src/styles/tokens.css', ['site']], - ['bazaarplusplus-installer/static/support/', ['site']], - ['bazaarplusplus-installer/src-tauri/resources/', ['mod']], - ['bazaarplusplus-installer/scripts/headless.mjs', ['mod']], - [ - 'bazaarplusplus-installer/src-tauri/history-database-compatibility.json', - ['mod', 'release'] - ], - ...[ - 'package.json', - 'package-lock.json', - 'src-tauri/Cargo.toml', - 'src-tauri/Cargo.lock', - 'src-tauri/tauri.conf.json', - 'src-tauri/tauri.macos.conf.json', - 'src-tauri/tauri.windows.conf.json' - ].map((file) => [`bazaarplusplus-installer/${file}`, ['release']]), - // checkProductProjections refuses 6.2.0 while this module exists. - ['bazaarplusplus-installer/src-tauri/src/v5_import/', ['release']], - ['bazaarplusplus-installer/src-tauri/icons/source/', ['macos-icon']], - [ - 'bazaarplusplus-installer/scripts/release/compile-macos-icon.mjs', - ['macos-icon'] - ] -]; - -function covers(input, file) { - return file === input || (input.endsWith('/') && file.startsWith(input)); -} - -// These are comments pointing to the opposite side of a contract, not reads. -const INFORMATIONAL_REFERENCES = [ - [ - 'bazaarplusplus-server/test/contracts/ghost-summary-contract.test.ts', - 'bazaarplusplus-mod/tests/ModApi.Tests/GhostSummaryContractTests.cs' - ], - [ - 'bazaarplusplus-analyzer/tests/pipeline_fixtures.py', - 'bazaarplusplus-server/src/modules/bundle-collection.ts' - ], - [ - 'bazaarplusplus-mod/native/macos/build.sh', - 'bazaarplusplus-installer/scripts/bundle.sh' - ], - // Read from a pinned commit with `git show`, never from the working tree. - [ - 'bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/generate-schemas.py', - 'bazaarplusplus-mod/tests/RunLoggingPipeline.Tests/fixtures/history-database-v3.schema.sql' - ] -]; - -export function unregisteredReferences(file, source) { - const consumer = PROJECTS.find((p) => - file.startsWith(`bazaarplusplus-${p}/`) - ); - // Markdown links document ownership. Markdown used as a contract is listed - // explicitly in SHARED_INPUTS; executable/config references are scanned here. - if (!consumer || file.endsWith('.md') || source.includes('\0')) return []; - const references = [ - ...source - .replaceAll('\\', '/') - .matchAll( - /bazaarplusplus-(?:site|server|analyzer|installer|mod)\/[\w./*-]*/g - ) - ]; - return references.flatMap(([reference]) => { - const target = path.posix.normalize(reference.replace(/[/.]+$/, '')); - if ( - target === `bazaarplusplus-${consumer}` || - target.startsWith(`bazaarplusplus-${consumer}/`) - ) - return []; - if ( - INFORMATIONAL_REFERENCES.some( - ([from, to]) => file === from && target === to - ) - ) - return []; - if ( - SHARED_INPUTS.some( - ([input, consumers]) => - consumers.includes(consumer) && - covers(input, target + (reference.endsWith('/') ? '/' : '')) - ) - ) - return []; - // Directory reads such as Vite's fs.allow cover all files in that directory. - if ( - SHARED_INPUTS.some( - ([input, consumers]) => - consumers.includes(consumer) && input === `${target}/` - ) - ) - return []; - return [`${file} -> ${reference}`]; - }); -} - -const git = (args, cwd) => - execFileSync('git', args, { - cwd, - encoding: 'utf8', - maxBuffer: 32 * 1024 * 1024 - }); - -export function scanDependencies(cwd = process.cwd()) { - return git(['ls-files', '-z'], cwd) - .split('\0') - .filter(Boolean) - .flatMap((file) => { - if (!PROJECTS.some((p) => file.startsWith(`bazaarplusplus-${p}/`))) - return []; - return unregisteredReferences( - file, - fs.readFileSync(path.join(cwd, file), 'utf8') - ); - }); -} - -export function fullScope(reason) { - return Object.fromEntries(SCOPES.map((scope) => [scope, [reason]])); -} - -export function classifyChanges(changes) { - if (!Array.isArray(changes) || !changes.length) - return fullScope('Diff unavailable or empty'); - const plan = Object.fromEntries(SCOPES.map((scope) => [scope, []])); - const select = (scope, reason) => { - for (const lane of PROJECT_SCOPES[scope] ?? [scope]) { - if (!plan[lane].includes(reason)) plan[lane].push(reason); - } - }; - for (const { status, file } of changes) { - if ( - typeof file !== 'string' || - !/^[AMDT]$/.test(status) || - file.startsWith('/') || - file.split('/').includes('..') - ) - return fullScope('Unrecognized diff entry'); - const project = PROJECTS.find((p) => - file.startsWith(`bazaarplusplus-${p}/`) - ); - if (file.endsWith('.just')) - return fullScope(`Shared command recipe: ${file}`); - if (project) { - select( - project === 'installer' && installerFrontendOnly(file) - ? 'installer-frontend' - : project, - `Project input: ${file}` - ); - for (const [input, consumers] of SHARED_INPUTS) { - if (covers(input, file)) - for (const consumer of consumers) - select(consumer, `Shared input: ${file}`); - } - } else if (file.startsWith('docs/') || /^[^/]+\.md$/.test(file)) { - // Project docs checks resolve links to root docs. Removing/moving their - // targets needs those checks too; editing the target's prose does not. - if (status === 'D' || status === 'T') - return fullScope(`Removed or replaced root documentation: ${file}`); - select('release', `Root documentation: ${file}`); - } else return fullScope(`Shared or unknown input: ${file}`); - } - return plan; -} - -export function readChanges( - eventName, - event, - cwd = process.cwd(), - runGit = (args) => git(args, cwd) -) { - let base; - let head; - const sha = (value) => - typeof value === 'string' && - /^[a-f0-9]{40}$/.test(value) && - !/^0+$/.test(value); - if (eventName === 'pull_request') { - head = event.pull_request?.head?.sha; - base = event.pull_request?.base?.sha; - if (!sha(base) || !sha(head)) throw new Error('PR SHAs unavailable'); - base = runGit(['merge-base', base, head]).trim(); - } else if (eventName === 'push') { - base = event.before; - head = event.after; - } else throw new Error(`Full run: ${eventName}`); - if (!sha(base) || !sha(head)) - throw new Error('Diff SHAs unavailable (including a zero before SHA)'); - // --no-renames deliberately represents moves as delete+add: both paths are - // classified, including moves across projects. NUL preserves unusual names. - const raw = runGit([ - 'diff', - '--name-status', - '--no-renames', - '-z', - base, - head, - '--' - ]); - if (!raw.endsWith('\0')) throw new Error('Empty or incomplete diff'); - const fields = raw.slice(0, -1).split('\0'); - if (fields.length % 2) throw new Error('Incomplete diff entry'); - const changes = []; - for (let i = 0; i < fields.length; i += 2) - changes.push({ status: fields[i], file: fields[i + 1] }); - return changes; -} - -export function planRun({ - eventName, - event, - cwd, - runGit, - dependencyProblems = [] -}) { - if (dependencyProblems.length) { - const reason = `Unregistered cross-project reference: ${dependencyProblems.join('; ')}`; - // A partial manual request must not claim coverage when the dependency - // boundary could not be verified. Automatic runs conservatively expand. - if (eventName === 'workflow_dispatch') throw new Error(reason); - return fullScope(reason); - } - if (eventName === 'workflow_dispatch') return manualScope(event.inputs); - try { - return classifyChanges(readChanges(eventName, event, cwd, runGit)); - } catch (error) { - return fullScope(`Conservative full run: ${error.message}`); - } -} - -if (import.meta.main) { - const event = JSON.parse( - fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8') - ); - let dependencyProblems; - try { - dependencyProblems = scanDependencies(); - } catch (error) { - dependencyProblems = [`Dependency scan unavailable: ${error.message}`]; - } - if (process.env.HISTORY_FETCH_OUTCOME !== 'success') - dependencyProblems.push('History fetch failed'); - const plan = planRun({ - eventName: process.env.GITHUB_EVENT_NAME, - event, - dependencyProblems - }); - // JSON stringifies newlines in filenames before writing line-based outputs. - const output = Object.entries(plan) - .map(([scope, reasons]) => `${scope}=${reasons.length > 0}`) - .join('\n'); - fs.appendFileSync( - process.env.GITHUB_OUTPUT, - `${output}\nplan=${JSON.stringify(plan)}\n` - ); - console.log(JSON.stringify(plan, null, 2)); -} diff --git a/.github/scripts/checks-scope.test.mjs b/.github/scripts/checks-scope.test.mjs deleted file mode 100644 index 5a4c1c9..0000000 --- a/.github/scripts/checks-scope.test.mjs +++ /dev/null @@ -1,380 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import test from 'node:test'; -import { runFixtureGit } from '../../scripts/test-support/git-fixture.mjs'; -import { - classifyChanges, - manualScope, - planRun, - readChanges, - scanDependencies, - SCOPES, - unregisteredReferences -} from './checks-scope.mjs'; - -const changed = (...files) => files.map((file) => ({ status: 'M', file })); -const selected = (plan) => - Object.keys(plan) - .filter((key) => plan[key].length) - .sort(); -const nativeInstaller = [ - 'installer-frontend', - 'installer-macos', - 'installer-windows' -]; -const expand = (scopes) => - scopes - .flatMap((scope) => - scope === 'installer' - ? nativeInstaller - : scope === 'mod' - ? ['mod-macos', 'mod-windows'] - : [scope] - ) - .sort(); -const expectScopes = (files, scopes) => - assert.deepEqual( - selected(classifyChanges(changed(...files))), - expand(scopes) - ); - -test('root documents, each project and global inputs select their complete gates', () => { - expectScopes(['README.md', 'AGENTS.md', 'docs/development.md'], ['release']); - expectScopes(['bazaarplusplus-server/package-lock.json'], ['server']); - expectScopes( - ['bazaarplusplus-installer/src/App.tsx'], - ['installer-frontend'] - ); - expectScopes( - ['bazaarplusplus-installer/src-tauri/src/lib.rs'], - ['installer'] - ); - expectScopes( - ['bazaarplusplus-installer/src/lib/bindings.ts'], - ['installer-frontend'] - ); - expectScopes( - ['bazaarplusplus-installer/src-tauri/src/v5_import/mod.rs'], - ['installer', 'release'] - ); - expectScopes(['bazaarplusplus-installer/rust-toolchain.toml'], ['installer']); - expectScopes( - ['bazaarplusplus-installer/src-tauri/.cargo/config.toml'], - ['installer'] - ); - expectScopes( - ['bazaarplusplus-installer/package-lock.json'], - ['installer', 'release'] - ); - expectScopes(['bazaarplusplus-mod/docs/MEMORY.md'], ['mod']); - expectScopes(['bazaarplusplus-analyzer/src/main.py'], ['analyzer']); - expectScopes(['bazaarplusplus-site/src/main.tsx'], ['site']); - for (const file of [ - 'VERSION', - 'release/payload.json', - 'release/manifest.mjs', - 'package-lock.json', - 'JUSTFILE', - 'bazaarplusplus-site/site.just', - '.nvmrc', - '.github/workflows/checks.yml', - 'scripts/workspace.mjs', - 'new-input' - ]) - expectScopes([file], [...SCOPES]); -}); - -test('shared inputs select owners and every contract consumer', () => { - for (const [file, consumers] of [ - [ - 'bazaarplusplus-server/contracts/v6/fixtures/run-only.bundle.b64', - ['server', 'mod', 'analyzer'] - ], - [ - 'bazaarplusplus-server/contracts/mod-api-errors.json', - ['server', 'mod', 'analyzer'] - ], - ['bazaarplusplus-server/docs/api-reference.md', ['server', 'mod']], - [ - 'bazaarplusplus-analyzer/contracts/v6/hero-aliases.json', - ['analyzer', 'mod', 'site', 'installer'] - ], - [ - 'bazaarplusplus-analyzer/docs/specs/consumer-data-contract.md', - ['analyzer', 'mod', 'site', 'installer'] - ], - [ - 'bazaarplusplus-mod/docs/contracts/run-payload-v6.md', - ['mod', 'server', 'analyzer'] - ], - [ - 'bazaarplusplus-mod/tests/BundleV6Codec.Tests/fixtures/run-payload-v6.fixture.b64', - ['mod', 'server', 'analyzer'] - ], - [ - 'bazaarplusplus-mod/tests/BundleQueueSqliteStore.Tests/fixtures/bundle-seal-eligibility.json', - ['mod', 'installer'] - ], - [ - 'bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BundleQueue/BundleQueueStore.cs', - ['mod', 'installer'] - ], - [ - 'bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs', - ['mod', 'installer', 'release'] - ], - [ - 'bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json', - ['mod', 'installer', 'release'] - ], - [ - 'bazaarplusplus-mod/src/BazaarPlusPlus.Storage/history-database-v6.schema.sql', - ['mod', 'installer', 'release'] - ], - [ - 'bazaarplusplus-installer/src-tauri/history-database-compatibility.json', - ['installer', 'mod', 'release'] - ], - [ - 'bazaarplusplus-installer/src/styles/tokens.css', - ['installer-frontend', 'site'] - ], - [ - 'bazaarplusplus-installer/static/support/wechat-pay.svg', - ['installer-frontend', 'site'] - ], - ['bazaarplusplus-installer/scripts/headless.mjs', ['installer', 'mod']], - [ - 'bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/icon.json', - ['installer', 'macos-icon'] - ], - [ - 'bazaarplusplus-installer/scripts/release/compile-macos-icon.mjs', - ['installer', 'macos-icon'] - ] - ]) - expectScopes([file], consumers); -}); - -test('deletions and cross-directory moves include old and new consumers', () => { - assert.deepEqual( - selected( - classifyChanges([ - { status: 'D', file: 'bazaarplusplus-installer/src/styles/tokens.css' }, - { status: 'A', file: 'bazaarplusplus-server/tokens.css' } - ]) - ), - ['installer-frontend', 'server', 'site'] - ); - assert.deepEqual( - selected(classifyChanges([{ status: 'D', file: 'docs/design.md' }])), - [...SCOPES].sort() - ); - for (const changes of [ - null, - [], - [{ status: 'R100', file: 'bad' }], - [{ status: 'M', file: '../escape' }] - ]) - assert.deepEqual(selected(classifyChanges(changes)), [...SCOPES].sort()); -}); - -test('unavailable diffs, zero push base, manual and unknown events fail open to full coverage', () => { - for (const args of [ - { - eventName: 'push', - event: { before: '0'.repeat(40), after: 'b'.repeat(40) } - }, - { - eventName: 'push', - event: { before: 'a'.repeat(40), after: 'b'.repeat(40) }, - runGit: () => { - throw new Error('shallow history'); - } - }, - { eventName: 'pull_request', event: {} }, - { eventName: 'workflow_dispatch', event: {} }, - { eventName: 'unknown', event: {} }, - { dependencyProblems: ['new cross-project read'], event: {} } - ]) - assert.deepEqual(selected(planRun(args)), [...SCOPES].sort()); -}); - -test('real Git merge-base ignores base-only changes; push uses the whole interval, including moves and unusual names', (t) => { - const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-checks-diff-')); - t.after(() => fs.rmSync(cwd, { force: true, recursive: true })); - const git = (...args) => runFixtureGit(args, { cwd }).trim(); - const put = (file, text) => { - fs.mkdirSync(path.dirname(path.join(cwd, file)), { recursive: true }); - fs.writeFileSync(path.join(cwd, file), text); - }; - const commit = (message) => { - git('add', '.'); - git( - '-c', - 'user.name=Fixture', - '-c', - 'user.email=fixture@example.test', - 'commit', - '-qm', - message - ); - return git('rev-parse', 'HEAD'); - }; - git('init'); - put('bazaarplusplus-server/old name\n.txt', 'value'); - const before = commit('base'); - git('checkout', '-b', 'feature'); - fs.rmSync(path.join(cwd, 'bazaarplusplus-server/old name\n.txt')); - put('bazaarplusplus-site/moved.txt', 'value'); - commit('move'); - put('bazaarplusplus-installer/src/App.tsx', 'input'); - const head = commit('second change'); - git('checkout', 'main'); - put('VERSION', 'base only'); - const base = commit('base advanced'); - const actual = readChanges( - 'pull_request', - { pull_request: { base: { sha: base }, head: { sha: head } } }, - cwd - ); - assert.deepEqual(selected(classifyChanges(actual)), [ - 'installer-frontend', - 'server', - 'site' - ]); - assert.ok( - actual.some(({ status, file }) => status === 'D' && file.includes('\n')) - ); - assert.deepEqual(readChanges('push', { before, after: head }, cwd), actual); -}); - -test('all executable cross-project references are registered', () => { - assert.deepEqual(scanDependencies(), []); -}); - -test('new cross-project reads cannot silently bypass consumers, including backslash paths', () => { - const file = 'bazaarplusplus-site/src/test.ts'; - for (const source of [ - "import x from '../../bazaarplusplus-server/new-contract.json'", - "import x from '../../bazaarplusplus-installer/static/support/../../secret.json'", - 'read("../bazaarplusplus-server/secret.json")', - 'read("..\\bazaarplusplus-server\\secret.json")' - ]) - assert.equal(unregisteredReferences(file, source).length, 1); - assert.deepEqual( - unregisteredReferences( - file, - "import '../../bazaarplusplus-installer/src/styles/tokens.css'" - ), - [] - ); -}); - -test('only known Installer frontend paths avoid both native platforms', () => { - for (const file of [ - 'src/App.tsx', - 'src/styles/app.css', - 'src/test.test.ts', - 'docs/architecture.md', - 'README.md', - 'vite.config.ts', - 'vitest.config.ts', - 'tsconfig.json', - 'index.html', - '.oxlintrc.json', - 'static/image.png' - ]) { - expectScopes([`bazaarplusplus-installer/${file}`], ['installer-frontend']); - } - for (const file of [ - 'src-tauri/build.rs', - 'src-tauri/build_support/mod.rs', - 'src-tauri/capabilities/main.json', - 'src-tauri/icons/icon.png', - '.cargo/config.toml', - 'scripts/checks/verify.mjs', - 'scripts/generate-bindings.mjs', - 'src/types/generated/commands.ts', - 'rust-toolchain.toml', - 'unknown-input' - ]) { - expectScopes([`bazaarplusplus-installer/${file}`], ['installer']); - } - for (const file of ['package.json', 'package-lock.json']) { - expectScopes( - [`bazaarplusplus-installer/${file}`], - ['installer', 'release'] - ); - } - expectScopes(['bazaarplusplus-installer/installer.just'], [...SCOPES]); - assert.deepEqual( - selected( - classifyChanges([ - { - status: 'D', - file: 'bazaarplusplus-installer/src/types/generated/commands.ts' - }, - { status: 'A', file: 'bazaarplusplus-installer/src/commands.ts' } - ]) - ), - [...nativeInstaller].sort() - ); -}); - -test('manual scopes select exactly the requested native platforms and their source gates', () => { - for (const scope of ['full', 'installer', 'mod']) { - for (const platform of ['all', 'macos', 'windows']) { - const expected = - scope === 'full' - ? [...SCOPES] - : scope === 'installer' - ? [...nativeInstaller, 'macos-icon'] - : ['mod-macos', 'mod-windows']; - const filtered = expected.filter( - (lane) => - platform === 'all' || - !(platform === 'windows' - ? lane.endsWith('-macos') || lane === 'macos-icon' - : lane.endsWith('-windows')) - ); - assert.deepEqual( - selected( - planRun({ - eventName: 'workflow_dispatch', - event: { inputs: { scope, platform } } - }) - ), - filtered.sort() - ); - } - } - assert.deepEqual(selected(manualScope()), [...SCOPES].sort()); - for (const inputs of [ - { scope: 'site' }, - { platform: 'linux' }, - { scope: '' } - ]) { - assert.throws(() => manualScope(inputs), /Invalid manual selection/); - } -}); - -test('manual checks fail closed when dependency scanning or history retrieval is unavailable', () => { - for (const problem of [ - 'new cross-project read', - 'Dependency scan unavailable', - 'History fetch failed' - ]) { - assert.throws( - () => - planRun({ - eventName: 'workflow_dispatch', - event: { inputs: { scope: 'installer', platform: 'windows' } }, - dependencyProblems: [problem] - }), - /Unregistered cross-project reference/ - ); - } -}); diff --git a/.github/scripts/checks-summary.mjs b/.github/scripts/checks-summary.mjs deleted file mode 100644 index 0cf5790..0000000 --- a/.github/scripts/checks-summary.mjs +++ /dev/null @@ -1,119 +0,0 @@ -import fs from 'node:fs'; -import { SCOPES, manualSelection } from './checks-scope.mjs'; - -export const JOB_SCOPES = { - release: 'release', - site: 'site', - server: 'server', - analyzer: 'analyzer', - 'installer-frontend': 'installer-frontend', - 'installer-macos': 'installer-macos', - 'installer-windows': 'installer-windows', - 'installer-timings': 'installer-frontend', - 'mod-macos': 'mod-macos', - 'mod-windows': 'mod-windows', - 'macos-icon': 'macos-icon' -}; - -export function summarize({ needs, eventName, event, modCredentials }) { - const errors = []; - const rows = []; - let plan; - try { - if (needs.classify?.result !== 'success') - throw new Error('Classification did not succeed'); - plan = JSON.parse(needs.classify.outputs.plan); - if ( - !plan || - Object.keys(plan).length !== SCOPES.length || - !SCOPES.every( - (scope) => - Array.isArray(plan[scope]) && - plan[scope].every( - (reason) => typeof reason === 'string' && reason.length - ) - ) - ) - throw new Error('Invalid classification plan'); - if (!SCOPES.some((scope) => plan[scope].length)) - throw new Error('Classification selected no checks'); - for (const scope of SCOPES) - if (needs.classify.outputs[scope] !== String(plan[scope].length > 0)) - throw new Error(`Inconsistent selection: ${scope}`); - } catch (error) { - errors.push(error.message); - } - const fork = - eventName === 'pull_request' && - event.pull_request?.head?.repo?.full_name && - event.repository?.full_name && - event.pull_request.head.repo.full_name !== event.repository.full_name; - if (!errors.length) - for (const [job, scope] of Object.entries(JOB_SCOPES)) { - const reasons = plan[scope]; - let status = needs[job]?.result ?? 'missing'; - if (!reasons.length) status = '不受影响'; - else if (scope.startsWith('mod-') && fork) { - if (status !== 'skipped') - errors.push(`${job}: fork exception expected skipped, got ${status}`); - status = 'fork 例外:需本地 Mod 验证,不提供私有快照凭据'; - } else { - if (scope.startsWith('mod-') && modCredentials !== 'true') - errors.push( - `${job}: missing BPP_GAME_LIBS_TOKEN or CLOUDFLARE_ACCOUNT_ID; Mod checks were not verified` - ); - if (status !== 'success') errors.push(`${job}: selected but ${status}`); - } - rows.push({ job, status, reasons }); - } - return { ok: errors.length === 0, errors, rows }; -} - -export function renderSummary(result, { eventName, ref, sha, inputs }) { - const escape = (text) => - String(text) - .replaceAll('&', '&') - .replaceAll('<', '<') - .replaceAll('>', '>') - .replaceAll('|', '|') - .replaceAll('\n', ' '); - return [ - `Event: ${escape(eventName)} · Ref: ${escape(ref)} · SHA: ${escape(sha)}`, - ...(eventName === 'workflow_dispatch' - ? [ - `Coverage: ${manualSelection(inputs).scope}/${manualSelection(inputs).platform}` - ] - : []), - '', - '| Job | Result | Selection reason |', - '| --- | --- | --- |', - ...result.rows.map( - ({ job, status, reasons }) => - `| ${job} | ${escape(status)} | ${reasons.map(escape).join('
') || '不受影响'} |` - ), - '', - ...result.errors.map((error) => `- ${escape(error)}`), - '' - ].join('\n'); -} - -if (import.meta.main) { - const event = JSON.parse( - fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8') - ); - const result = summarize({ - needs: JSON.parse(process.env.CHECK_NEEDS), - eventName: process.env.GITHUB_EVENT_NAME, - event, - modCredentials: process.env.MOD_CREDENTIALS - }); - const report = renderSummary(result, { - eventName: process.env.GITHUB_EVENT_NAME, - ref: process.env.GITHUB_REF, - sha: process.env.GITHUB_SHA, - inputs: event.inputs - }); - fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, report); - console.log(report); - if (!result.ok) process.exitCode = 1; -} diff --git a/.github/scripts/checks-summary.test.mjs b/.github/scripts/checks-summary.test.mjs deleted file mode 100644 index 035f13b..0000000 --- a/.github/scripts/checks-summary.test.mjs +++ /dev/null @@ -1,210 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import test from 'node:test'; -import { classifyChanges, fullScope, manualScope } from './checks-scope.mjs'; -import { JOB_SCOPES, summarize, renderSummary } from './checks-summary.mjs'; - -function fixture(plan = fullScope('fixture')) { - const outputs = { - plan: JSON.stringify(plan), - ...Object.fromEntries( - Object.entries(plan).map(([scope, reasons]) => [ - scope, - String(reasons.length > 0) - ]) - ) - }; - return { - needs: { - classify: { result: 'success', outputs }, - ...Object.fromEntries( - Object.entries(JOB_SCOPES).map(([job, scope]) => [ - job, - { result: plan[scope].length ? 'success' : 'skipped' } - ]) - ) - }, - eventName: 'pull_request', - event: { - repository: { full_name: 'owner/repo' }, - pull_request: { head: { repo: { full_name: 'owner/repo' } } } - }, - modCredentials: 'true' - }; -} - -test('all selected jobs must succeed, including each native platform and timing report', () => { - assert.equal(summarize(fixture()).ok, true); - for (const job of Object.keys(JOB_SCOPES)) - for (const result of ['failure', 'cancelled', 'skipped', undefined]) { - const f = fixture(); - f.needs[job].result = result; - assert.equal(summarize(f).ok, false, `${job}: ${result}`); - } -}); - -test('unaffected jobs show why they are skipped', () => { - const result = summarize( - fixture( - classifyChanges([ - { status: 'M', file: 'bazaarplusplus-server/package-lock.json' } - ]) - ) - ); - assert.equal(result.ok, true); - assert.equal( - result.rows.find(({ job }) => job === 'installer-macos').status, - '不受影响' - ); - assert.match( - result.rows.find(({ job }) => job === 'server').reasons[0], - /package-lock/ - ); -}); - -test('classification failure, missing output, malformed and inconsistent selections fail closed', () => { - for (const modify of [ - (f) => { - f.needs.classify.result = 'failure'; - }, - (f) => { - f.needs.classify.result = 'cancelled'; - }, - (f) => { - f.needs.classify.result = 'skipped'; - }, - (f) => { - f.needs.classify.outputs.plan = '{}'; - }, - (f) => { - f.needs.classify.outputs.plan = 'invalid JSON'; - }, - (f) => { - f.needs.classify.outputs['installer-frontend'] = 'false'; - }, - (f) => { - delete f.needs.classify; - } - ]) { - const f = fixture(); - modify(f); - assert.equal(summarize(f).ok, false); - } -}); - -test('internal and Dependabot Mod selections fail without credentials; forks have an explicit exception', () => { - const f = fixture(); - f.modCredentials = 'false'; - assert.equal(summarize(f).ok, false); - f.event.pull_request.user = { login: 'dependabot[bot]' }; - assert.equal(summarize(f).ok, false); - f.event.pull_request.head.repo.full_name = 'fork/repo'; - f.needs['mod-macos'].result = 'skipped'; - f.needs['mod-windows'].result = 'skipped'; - const result = summarize(f); - assert.equal(result.ok, true); - assert.match( - result.rows.find(({ job }) => job === 'mod-macos').status, - /fork 例外/ - ); - f.needs['mod-macos'].result = 'failure'; - assert.equal( - summarize(f).ok, - false, - 'fork exception cannot hide a failed job' - ); - f.eventName = 'workflow_dispatch'; - assert.equal(summarize(f).ok, false, 'fork exception is PR-only'); -}); - -test('workflow wiring summarizes every optional job and isolates every manual run', () => { - const workflow = fs.readFileSync( - new URL('../workflows/checks.yml', import.meta.url), - 'utf8' - ); - const summary = workflow.slice( - workflow.indexOf('\n summary:\n'), - workflow.indexOf('\n bot-mod-boundary:\n') - ); - assert.match(summary, /if: always\(\)/); - assert.match( - summary, - /name: \$\{\{ github.event_name == 'workflow_dispatch' && format\('Manual checks \(\{0\}\/\{1\}\)', inputs.scope, inputs.platform\) \|\| 'Checks summary' \}\}/ - ); - const needs = summary - .match(/needs:\s*\[([^\]]+)\]/)[1] - .split(',') - .map((job) => job.trim()); - assert.deepEqual( - needs.sort(), - ['classify', ...Object.keys(JOB_SCOPES)].sort() - ); - assert.match(workflow, /group: checks-\$\{\{ github.event_name \}\}/); - assert.match(workflow, /group: .*inputs.scope.*inputs.platform/); - assert.match(workflow, /shared-key: installer-.*-installer\n/); - - assert.match( - workflow, - /save-if: \$\{\{ github.event_name == 'push' && github.ref == 'refs\/heads\/master' \}\}/ - ); - for (const name of [ - 'site (full check and test)', - 'server (full check and test)', - 'Installer (frontend)', - 'Installer (macos-14)', - 'Installer (windows-latest)', - 'Mod (macos-14)', - 'Mod (windows-latest)' - ]) - assert.ok(workflow.includes(` name: ${name}\n`)); - for (const [job, scope] of Object.entries(JOB_SCOPES)) { - const block = workflow.split(`\n ${job}:\n`)[1]?.split(/\n [\w-]+:\n/)[0]; - assert.ok( - block?.includes(`needs.classify.outputs.${scope} == 'true'`), - `${job} consumes ${scope}` - ); - } - assert.ok( - !workflow.includes('matrix.'), - 'skipped matrix parents do not emit legacy child names' - ); -}); - -test('manual installer/windows requires frontend and Windows but not macOS or Mod', () => { - const inputs = { scope: 'installer', platform: 'windows' }; - const f = fixture(manualScope(inputs)); - f.eventName = 'workflow_dispatch'; - f.event.inputs = inputs; - assert.equal(summarize(f).ok, true); - assert.equal(f.needs['installer-macos'].result, 'skipped'); - for (const job of [ - 'installer-frontend', - 'installer-windows', - 'installer-timings' - ]) { - const broken = structuredClone(f); - broken.needs[job].result = 'skipped'; - assert.equal(summarize(broken).ok, false); - } - const report = renderSummary(summarize(f), { - eventName: f.eventName, - ref: 'refs/heads/fixture', - sha: 'abc', - inputs - }); - assert.match(report, /Coverage: installer\/windows/); - assert.match(report, /Ref: refs\/heads\/fixture · SHA: abc/); -}); - -test('frontend-only cannot hide a skipped selected frontend or require native credentials', () => { - const f = fixture( - classifyChanges([ - { status: 'M', file: 'bazaarplusplus-installer/src/App.tsx' } - ]) - ); - f.modCredentials = 'false'; - assert.equal(summarize(f).ok, true); - assert.equal(f.needs['installer-windows'].result, 'skipped'); - f.needs['installer-frontend'].result = 'skipped'; - assert.equal(summarize(f).ok, false); -}); diff --git a/.github/scripts/dependabot-auto-merge.mjs b/.github/scripts/dependabot-auto-merge.mjs deleted file mode 100644 index 736d0e8..0000000 --- a/.github/scripts/dependabot-auto-merge.mjs +++ /dev/null @@ -1,292 +0,0 @@ -import { isDeepStrictEqual } from 'node:util'; -import { execFileSync } from 'node:child_process'; -import { fileURLToPath } from 'node:url'; - -// These are job names, not workflow names. Require GitHub Actions as their source. -// A name joins this list only after the GitHub ruleset requires it, and the -// ruleset only after the job has run green once (docs/development.md). -export const REQUIRED_CHECKS = [ - 'Checks summary', - 'Bot Mod dependency boundary', - 'dependencies', - 'CodeQL (javascript-typescript)', - 'CodeQL (python)' -]; - -export function protectionReady(rules) { - const reviewed = rules.some( - (rule) => - rule.type === 'pull_request' && - rule.parameters.required_approving_review_count >= 1 && - rule.parameters.dismiss_stale_reviews_on_push === true - ); - const strictChecks = rules - .filter( - (rule) => - rule.type === 'required_status_checks' && - rule.parameters.strict_required_status_checks_policy === true && - rule.parameters.do_not_enforce_on_create !== true - ) - .flatMap((rule) => rule.parameters.required_status_checks); - return ( - reviewed && - REQUIRED_CHECKS.every((name) => - strictChecks.some( - (check) => check.context === name && check.integration_id === 15368 - ) - ) - ); -} - -function patchVersion(before, after) { - const parse = (value) => - typeof value === 'string' && - value.match(/^(\^|~)?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/); - const a = parse(before); - const b = parse(after); - return ( - a && - b && - a[1] === b[1] && - a[2] === b[2] && - a[3] === b[3] && - BigInt(b[4]) > BigInt(a[4]) - ); -} - -function normalizeRanges(before, after) { - for (const field of [ - 'dependencies', - 'devDependencies', - 'optionalDependencies', - 'peerDependencies' - ]) { - for (const [name, oldVersion] of Object.entries(before[field] ?? {})) { - const newVersion = after[field]?.[name]; - if (patchVersion(oldVersion, newVersion)) after[field][name] = oldVersion; - } - } -} - -export function eligibleFiles(files) { - if (!files.length || files.some((file) => file.status !== 'modified')) - return null; - const candidates = [ - '', - 'bazaarplusplus-site/', - 'bazaarplusplus-server/', - 'bazaarplusplus-installer/' - ].map((directory) => ({ - kind: 'npm', - manifest: `${directory}package.json`, - lock: `${directory}package-lock.json` - })); - candidates.push( - { - kind: 'cargo', - manifest: 'bazaarplusplus-installer/src-tauri/Cargo.toml', - lock: 'bazaarplusplus-installer/src-tauri/Cargo.lock' - }, - { - kind: 'uv', - manifest: 'bazaarplusplus-analyzer/pyproject.toml', - lock: 'bazaarplusplus-analyzer/uv.lock' - } - ); - for (const candidate of candidates) { - const { manifest, lock } = candidate; - if ( - files.some((file) => file.filename === lock) && - files.every((file) => [manifest, lock].includes(file.filename)) - ) { - return candidate; - } - } - return null; -} - -export function documentsArePatchOnly(kind, documents) { - if (kind === 'npm') - return patchOnly(...documents.map((text) => JSON.parse(text))); - return JSON.parse( - execFileSync( - 'python3', - [ - fileURLToPath( - new URL('./check_toml_dependency_update.py', import.meta.url) - ) - ], - { - input: JSON.stringify({ kind, documents }), - encoding: 'utf8', - timeout: 15000, - maxBuffer: 1024 * 1024 - } - ) - ); -} - -export function patchOnly( - beforeManifest, - afterManifest, - beforeLock, - afterLock -) { - const manifest = structuredClone(afterManifest); - normalizeRanges(beforeManifest, manifest); - if (!isDeepStrictEqual(beforeManifest, manifest)) return false; - if ( - beforeLock.lockfileVersion !== 3 || - afterLock.lockfileVersion !== 3 || - !beforeLock.packages || - !afterLock.packages - ) - return false; - const lock = structuredClone(afterLock); - let patches = 0; - for (const [path, before] of Object.entries(beforeLock.packages)) { - const after = lock.packages[path]; - if (!after) return false; - normalizeRanges(before, after); - if (path && patchVersion(before.version, after.version)) { - // No Git/tarball/local replacements, even when version strings look safe. - if ( - !before.resolved?.startsWith('https://registry.npmjs.org/') || - !after.resolved?.startsWith('https://registry.npmjs.org/') || - typeof after.integrity !== 'string' || - !after.integrity.startsWith('sha512-') - ) - return false; - after.version = before.version; - after.resolved = before.resolved; - after.integrity = before.integrity; - patches++; - } - } - // New/removed packages, changed scripts/engines/overrides and graph reshuffles - // all require human review. A patch label alone never grants approval. - return patches > 0 && isDeepStrictEqual(beforeLock, lock); -} - -export async function run({ github, context, core }) { - const repo = context.repo; - const pull_number = context.payload.pull_request.number; - const { data: pr } = await github.rest.pulls.get({ ...repo, pull_number }); - const decline = async (reason) => { - core.info(`Manual review: ${reason}`); - if (pr.auto_merge) - await github.graphql( - 'mutation($id: ID!) { disablePullRequestAutoMerge(input: {pullRequestId: $id}) { clientMutationId } }', - { id: pr.node_id } - ); - }; - if (pr.state !== 'open' || pr.draft) return; - if ( - pr.user.login !== 'dependabot[bot]' || - pr.base.ref !== 'master' || - pr.head.repo?.full_name !== `${repo.owner}/${repo.repo}` - ) - return decline('untrusted PR origin or base'); - if (pr.head.sha !== context.payload.pull_request.head.sha) - return decline('head changed; wait for the new run'); - const files = await github.paginate(github.rest.pulls.listFiles, { - ...repo, - pull_number, - per_page: 100 - }); - const paths = eligibleFiles(files); - if (!paths || files.length !== pr.changed_files) - return decline( - 'only external application dependency manifests and lockfiles are eligible' - ); - const commits = await github.paginate(github.rest.pulls.listCommits, { - ...repo, - pull_number, - per_page: 100 - }); - if ( - !commits.length || - pr.commits > 250 || - commits.length !== pr.commits || - !commits.some((commit) => commit.sha === pr.head.sha) || - !commits.every( - (commit) => - commit.author?.login === 'dependabot[bot]' && - commit.commit.verification?.verified - ) - ) - return decline('every commit must have a verified Dependabot signature'); - const { data: comparison } = - await github.rest.repos.compareCommitsWithBasehead({ - ...repo, - basehead: `${pr.base.sha}...${pr.head.sha}` - }); - const readText = async (ref, path) => { - const { data } = await github.rest.repos.getContent({ ...repo, ref, path }); - if (data.type !== 'file' || data.encoding !== 'base64') - throw new Error(`Cannot read ${path}`); - return Buffer.from(data.content, 'base64').toString('utf8'); - }; - const documents = await Promise.all([ - readText(comparison.merge_base_commit.sha, paths.manifest), - readText(pr.head.sha, paths.manifest), - readText(comparison.merge_base_commit.sha, paths.lock), - readText(pr.head.sha, paths.lock) - ]); - if (!documentsArePatchOnly(paths.kind, documents)) - return decline('dependency graph is not a stable patch-only update'); - const rules = await github.paginate( - 'GET /repos/{owner}/{repo}/rules/branches/{branch}', - { ...repo, branch: 'master', per_page: 100 } - ); - if (!protectionReady(rules)) - return decline( - 'waiting for strict required CI checks and stale-review dismissal to be configured' - ); - // Recheck after API reads; approval and auto-merge are bound to the inspected head. - const { data: current } = await github.rest.pulls.get({ - ...repo, - pull_number - }); - if ( - current.head.sha !== pr.head.sha || - current.base.ref !== 'master' || - current.state !== 'open' - ) - return decline('PR changed during validation'); - try { - await github.rest.pulls.createReview({ - ...repo, - pull_number, - commit_id: pr.head.sha, - event: 'APPROVE', - body: 'Verified Dependabot patch-only update to external application dependencies. Mod/game assemblies are excluded. GitHub required checks must pass before merging.' - }); - } catch (error) { - if (![403, 409].includes(error.status)) throw error; - core.info( - 'Actions approval is not permitted; auto-merge will wait for human approval.' - ); - } - const { node } = await github.graphql( - 'query($id: ID!) { node(id: $id) { ... on PullRequest { state headRefOid baseRefName mergeStateStatus autoMergeRequest { enabledAt } } } }', - { id: pr.node_id } - ); - if (node.state !== 'OPEN') return; - if (node.headRefOid !== pr.head.sha || node.baseRefName !== 'master') - return decline('PR changed after approval'); - if (node.autoMergeRequest) return; - if (node.mergeStateStatus === 'CLEAN') { - await github.graphql( - 'mutation($id: ID!, $head: GitObjectID!) { mergePullRequest(input: {pullRequestId: $id, expectedHeadOid: $head, mergeMethod: SQUASH}) { clientMutationId } }', - { id: pr.node_id, head: pr.head.sha } - ); - core.info('Merged after GitHub protection requirements were satisfied.'); - return; - } - await github.graphql( - 'mutation($id: ID!, $head: GitObjectID!) { enablePullRequestAutoMerge(input: {pullRequestId: $id, expectedHeadOid: $head, mergeMethod: SQUASH}) { clientMutationId } }', - { id: pr.node_id, head: pr.head.sha } - ); - core.info('Native auto-merge enabled; required checks remain enforced.'); -} diff --git a/.github/scripts/dependabot-auto-merge.test.mjs b/.github/scripts/dependabot-auto-merge.test.mjs deleted file mode 100644 index ea88293..0000000 --- a/.github/scripts/dependabot-auto-merge.test.mjs +++ /dev/null @@ -1,442 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import test from 'node:test'; -import { - documentsArePatchOnly, - eligibleFiles, - patchOnly, - protectionReady, - REQUIRED_CHECKS, - run -} from './dependabot-auto-merge.mjs'; - -function fixture() { - const beforeManifest = { - name: 'test', - devDependencies: { library: '^1.2.3' }, - scripts: { test: 'vitest run' } - }; - const beforeLock = { - lockfileVersion: 3, - packages: { - '': { ...beforeManifest }, - 'node_modules/library': { - version: '1.2.3', - resolved: 'https://registry.npmjs.org/library/-/library-1.2.3.tgz', - integrity: 'sha512-old', - dev: true - } - } - }; - const afterManifest = structuredClone(beforeManifest); - afterManifest.devDependencies.library = '^1.2.4'; - const afterLock = structuredClone(beforeLock); - afterLock.packages[''].devDependencies.library = '^1.2.4'; - Object.assign(afterLock.packages['node_modules/library'], { - version: '1.2.4', - resolved: 'https://registry.npmjs.org/library/-/library-1.2.4.tgz', - integrity: 'sha512-new' - }); - return [beforeManifest, afterManifest, beforeLock, afterLock]; -} - -function rules() { - return [ - { - type: 'pull_request', - parameters: { - required_approving_review_count: 1, - dismiss_stale_reviews_on_push: true - } - }, - { - type: 'required_status_checks', - parameters: { - strict_required_status_checks_policy: true, - required_status_checks: REQUIRED_CHECKS.map((context) => ({ - context, - integration_id: 15368 - })) - } - } - ]; -} - -test('accepts a stable patch and does not mutate the input snapshots', () => { - const data = fixture(); - const copy = structuredClone(data); - assert.equal(patchOnly(...data), true); - assert.deepEqual(data, copy); -}); - -test('minor, major, prerelease, downgrade and range policy changes need human review', () => { - for (const version of ['1.3.0', '2.0.0', '1.2.4-rc.1', '1.2.2', '1.2.3']) { - const data = fixture(); - data[3].packages['node_modules/library'].version = version; - assert.equal(patchOnly(...data), false, version); - } - const data = fixture(); - data[1].devDependencies.library = '~1.2.4'; - assert.equal(patchOnly(...data), false); -}); - -test('scripts, overrides, engines, new packages and changed install hooks cannot hide in a patch', () => { - for (const modify of [ - (data) => { - data[1].scripts.test = 'different command'; - }, - (data) => { - data[1].overrides = { other: '1.0.0' }; - }, - (data) => { - data[1].engines = { node: '>=26' }; - }, - (data) => { - data[3].packages['node_modules/added'] = { version: '1.0.0' }; - }, - (data) => { - data[3].packages['node_modules/library'].hasInstallScript = true; - }, - (data) => { - data[3].packages['node_modules/library'].resolved = - 'https://example.com/library.tgz'; - }, - (data) => { - data[3].packages['node_modules/library'].dependencies = { - nested: '2.0.0' - }; - } - ]) { - const data = fixture(); - modify(data); - assert.equal(patchOnly(...data), false); - } -}); - -test('external npm, Cargo and uv dependency files are eligible; no cross-project, source, workflow or removed files', () => { - for (const path of [ - 'package-lock.json', - 'bazaarplusplus-site/package-lock.json', - 'bazaarplusplus-installer/package-lock.json', - 'bazaarplusplus-installer/src-tauri/Cargo.lock', - 'bazaarplusplus-server/package-lock.json', - 'bazaarplusplus-analyzer/uv.lock' - ]) { - assert.ok(eligibleFiles([{ filename: path, status: 'modified' }])); - } - for (const path of [ - 'bazaarplusplus-mod/Directory.Packages.props', - 'bazaarplusplus-installer/src-tauri/tauri.conf.json', - 'bazaarplusplus-installer/src-tauri/build.rs', - 'bazaarplusplus-server/contracts/v6/bundle.proto', - '.github/workflows/checks.yml', - 'bazaarplusplus-site/src/main.tsx' - ]) { - assert.equal(eligibleFiles([{ filename: path, status: 'modified' }]), null); - } - assert.equal( - eligibleFiles([{ filename: 'package-lock.json', status: 'removed' }]), - null - ); - assert.equal( - eligibleFiles( - ['package-lock.json', 'bazaarplusplus-site/package.json'].map( - (filename) => ({ filename, status: 'modified' }) - ) - ), - null - ); - assert.equal(eligibleFiles([]), null); -}); - -test('strict required checks, trusted app and stale-review dismissal are mandatory', () => { - assert.equal(protectionReady(rules()), true); - assert.equal(protectionReady([]), false); - for (const modify of [ - (value) => { - value[0].parameters.required_approving_review_count = 0; - }, - (value) => { - value[0].parameters.dismiss_stale_reviews_on_push = false; - }, - (value) => { - value[1].parameters.strict_required_status_checks_policy = false; - }, - (value) => { - value[1].parameters.required_status_checks.pop(); - }, - (value) => { - value[1].parameters.required_status_checks[0].integration_id = null; - } - ]) { - const value = rules(); - modify(value); - assert.equal(protectionReady(value), false); - } -}); - -function apiFixture() { - const data = fixture(); - const pr = { - number: 7, - node_id: 'PR7', - commits: 1, - changed_files: 2, - state: 'open', - user: { login: 'dependabot[bot]' }, - base: { ref: 'master', sha: 'base' }, - head: { sha: 'head', repo: { full_name: 'owner/repo' } } - }; - const writes = []; - const state = { - rules: rules(), - commits: [ - { - sha: 'head', - author: { login: 'dependabot[bot]' }, - commit: { verification: { verified: true } } - } - ], - pr, - current: pr, - mergeStateStatus: 'BLOCKED', - writes - }; - let reads = 0; - const github = { - paginate: async (method) => { - if (method === 'files') - return [ - { filename: 'package-lock.json', status: 'modified' }, - { filename: 'package.json', status: 'modified' } - ]; - if (method === 'commits') return state.commits; - return state.rules; - }, - rest: { - pulls: { - get: async () => ({ data: reads++ ? state.current : pr }), - listFiles: 'files', - listCommits: 'commits', - createReview: async (args) => { - if (state.approvalError) throw state.approvalError; - writes.push({ kind: 'review', ...args }); - } - }, - repos: { - compareCommitsWithBasehead: async () => ({ - data: { merge_base_commit: { sha: 'base' } } - }), - getContent: async ({ ref, path }) => ({ - data: { - type: 'file', - encoding: 'base64', - content: Buffer.from( - JSON.stringify( - data[ - (path === 'package-lock.json' ? 2 : 0) + - (ref === 'head' ? 1 : 0) - ] - ) - ).toString('base64') - } - }) - } - }, - graphql: async (query, variables) => { - if (query.startsWith('query')) - return { - node: { - state: 'OPEN', - headRefOid: 'head', - baseRefName: 'master', - mergeStateStatus: state.mergeStateStatus - } - }; - writes.push({ - kind: query.includes('disablePullRequest') - ? 'disable' - : query.includes('mergePullRequest(') - ? 'merge' - : 'enable', - ...variables - }); - } - }; - return { - state, - args: { - github, - context: { - repo: { owner: 'owner', repo: 'repo' }, - payload: { pull_request: structuredClone(pr) } - }, - core: { info() {} } - } - }; -} - -test('approval and native auto-merge both refer to the inspected commit', async () => { - const { state, args } = apiFixture(); - await run(args); - assert.equal(state.writes[0].commit_id, 'head'); - assert.deepEqual(state.writes[1], { - kind: 'enable', - id: 'PR7', - head: 'head' - }); -}); - -test('missing protection, unsigned commits and a changing head never receive approval', async () => { - for (const modify of [ - (state) => { - state.rules = []; - }, - (state) => { - state.commits[0].commit.verification.verified = false; - }, - (state) => { - state.commits[0].author.login = 'human'; - }, - (state) => { - state.pr.commits = 251; - }, - (state) => { - state.pr.commits = 2; - }, - (state) => { - state.commits[0].sha = 'other-head'; - }, - (state) => { - state.current = { - ...state.pr, - head: { ...state.pr.head, sha: 'new-head' } - }; - } - ]) { - const { state, args } = apiFixture(); - modify(state); - await run(args); - assert.deepEqual(state.writes, []); - } -}); - -test('an immediately mergeable PR uses the protected merge API with the same head', async () => { - const { state, args } = apiFixture(); - state.mergeStateStatus = 'CLEAN'; - await run(args); - assert.deepEqual(state.writes[1], { kind: 'merge', id: 'PR7', head: 'head' }); -}); - -test('organization approval restrictions preserve human approval before auto-merge', async () => { - const { state, args } = apiFixture(); - state.approvalError = { status: 403 }; - await run(args); - assert.deepEqual(state.writes, [{ kind: 'enable', id: 'PR7', head: 'head' }]); -}); - -test('an already enabled PR is disarmed if protection no longer qualifies', async () => { - const { state, args } = apiFixture(); - state.pr.auto_merge = {}; - state.rules = []; - await run(args); - assert.deepEqual(state.writes, [{ kind: 'disable', id: 'PR7' }]); -}); - -// A required check that no workflow job can report blocks every merge, so each -// name must be a job's display name (job id when it has none) in .github/workflows. -// A matrix name such as "Installer (${{ matrix.os }})" is matched as a pattern. -test('every required check is a job name declared in the workflows', () => { - const workflows = path.join(import.meta.dirname, '..', 'workflows'); - const patterns = fs - .readdirSync(workflows) - .filter((file) => file.endsWith('.yml')) - .flatMap((file) => { - const text = fs.readFileSync(path.join(workflows, file), 'utf8'); - const jobs = text.slice(text.indexOf('\njobs:\n') + 1); - return [ - ...jobs.matchAll( - /^ ([\w-]+):\n(?: (?!name:)[^\n]*\n)*?(?: name: ([^\n]+)\n)?/gm - ) - ].map( - ([, id, name]) => - new RegExp( - `^${(name ?? id) - .split(/\$\{\{.*?\}\}/) - .map((literal) => literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) - .join('.+')}$` - ) - ); - }); - assert.ok(patterns.length >= 8, 'job names were parsed'); - for (const name of REQUIRED_CHECKS) - assert.ok( - patterns.some((pattern) => pattern.test(name)), - `${name} is not a job in .github/workflows` - ); - assert.ok( - !REQUIRED_CHECKS.includes('Mod pure logic (no game compatibility)') - ); -}); - -test('summary and unchanged security gates must be required before automatic merge', () => { - assert.deepEqual(REQUIRED_CHECKS, [ - 'Checks summary', - 'Bot Mod dependency boundary', - 'dependencies', - 'CodeQL (javascript-typescript)', - 'CodeQL (python)' - ]); - const legacy = rules(); - legacy[1].parameters.required_status_checks = - legacy[1].parameters.required_status_checks.filter( - ({ context }) => context !== 'Checks summary' - ); - legacy[1].parameters.required_status_checks.push( - ...[ - 'Release tooling', - 'site (full check and test)', - 'server (full check and test)', - 'Analyzer', - 'Installer (macos-14)', - 'Installer (windows-latest)', - 'Mod (macos-14)', - 'Mod (windows-latest)' - ].map((context) => ({ context, integration_id: 15368 })) - ); - assert.equal( - protectionReady(legacy), - false, - 'legacy checks cannot replace the summary' - ); - for (const name of REQUIRED_CHECKS) { - const value = rules(); - value[1].parameters.required_status_checks = - value[1].parameters.required_status_checks.filter( - ({ context }) => context !== name - ); - assert.equal(protectionReady(value), false, name); - } -}); - -test('trusted TOML parser accepts Cargo patches and fails closed on malformed data', () => { - const manifest = '[dependencies]\nlibrary = "1.2.3"\n'; - const lock = `version = 4 -[[package]] -name = "library" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "${'a'.repeat(64)}" -`; - assert.equal( - documentsArePatchOnly('cargo', [ - manifest, - manifest.replace('1.2.3', '1.2.4'), - lock, - lock.replace('1.2.3', '1.2.4') - ]), - true - ); - assert.equal(documentsArePatchOnly('uv', ['[invalid', '', '', '']), false); -}); diff --git a/.github/scripts/installer-timings.mjs b/.github/scripts/installer-timings.mjs deleted file mode 100644 index 8cbbf15..0000000 --- a/.github/scripts/installer-timings.mjs +++ /dev/null @@ -1,77 +0,0 @@ -import { execFileSync } from 'node:child_process'; -import { appendFileSync } from 'node:fs'; - -function seconds(start, end) { - if (!start || !end) return null; - const value = (Date.parse(end) - Date.parse(start)) / 1000; - return Number.isFinite(value) && value >= 0 ? value : null; -} - -export function installerTimingReport(jobs) { - const lines = [ - '## Installer job timings', - '', - 'Seconds from the Jobs API for this run attempt. Queue time starts at job creation; other time includes tool setup, cleanup and runner overhead. Verification details are in each Installer job summary.', - '' - ]; - for (const job of jobs.filter(({ name }) => - /^Installer \(.+\)$/.test(name) - )) { - const stages = new Map([ - ['Rust cache restore', 'Restore Installer Rust cache'], - ['npm ci', 'Install Installer npm dependencies'], - ['Verification', 'Verify Installer'], - ['Rust cache save / cleanup', 'Post Restore Installer Rust cache'] - ]); - const total = seconds(job.started_at, job.completed_at); - let measured = 0; - lines.push( - `### [${job.name}](${job.html_url}) — ${job.conclusion ?? job.status}`, - '', - '| Stage | Seconds | Result |', - '| --- | ---: | --- |', - `| Queue | ${seconds(job.created_at, job.started_at) ?? 'unavailable'} | |` - ); - for (const [label, name] of stages) { - const step = job.steps.find((entry) => entry.name === name); - const duration = - step?.conclusion === 'skipped' - ? 0 - : seconds(step?.started_at, step?.completed_at); - measured += duration ?? 0; - lines.push( - `| ${label} | ${duration ?? 'unavailable'} | ${step?.conclusion ?? 'not run'} |` - ); - } - lines.push( - `| Other job time | ${total === null ? 'unavailable' : Math.max(0, total - measured)} | |`, - `| Total (excluding queue) | ${total ?? 'unavailable'} | ${job.conclusion ?? job.status} |`, - '' - ); - } - return lines.join('\n'); -} - -if (import.meta.main) { - const { - GITHUB_REPOSITORY, - GITHUB_RUN_ID, - GITHUB_RUN_ATTEMPT, - GITHUB_STEP_SUMMARY - } = process.env; - const pages = JSON.parse( - execFileSync( - 'gh', - [ - 'api', - '--paginate', - '--slurp', - `repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/attempts/${GITHUB_RUN_ATTEMPT}/jobs?per_page=100` - ], - { encoding: 'utf8' } - ) - ); - const report = installerTimingReport(pages.flatMap(({ jobs }) => jobs)); - appendFileSync(GITHUB_STEP_SUMMARY, report); - console.log(report); -} diff --git a/.github/scripts/installer-timings.test.mjs b/.github/scripts/installer-timings.test.mjs deleted file mode 100644 index fac44c6..0000000 --- a/.github/scripts/installer-timings.test.mjs +++ /dev/null @@ -1,66 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { installerTimingReport } from './installer-timings.mjs'; - -const at = (second) => - new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString(); -const step = (name, start, end, conclusion = 'success') => ({ - name, - started_at: at(start), - completed_at: at(end), - conclusion -}); - -test('reports both platforms, queue and post-job save without counting another job', () => { - const job = { - name: 'Installer (windows-latest)', - html_url: 'https://example.com/job', - created_at: at(0), - started_at: at(5), - completed_at: at(45), - conclusion: 'success', - steps: [ - step('Restore Installer Rust cache', 10, 12), - step('Install Installer npm dependencies', 12, 15), - step('Verify Installer', 15, 35), - step('Post Restore Installer Rust cache', 35, 39) - ] - }; - const report = installerTimingReport([ - job, - { ...job, name: 'Installer (macos-14)' }, - { ...job, name: 'Installer (frontend)' }, - { ...job, name: 'Release tooling' } - ]); - assert.match(report, /Queue \| 5/); - assert.match(report, /Rust cache restore \| 2/); - assert.match(report, /npm ci \| 3/); - assert.match(report, /Verification \| 20/); - assert.match(report, /Rust cache save \/ cleanup \| 4/); - assert.match(report, /Other job time \| 11/); - assert.match(report, /Total \(excluding queue\) \| 40/); - assert.match(report, /Installer \(macos-14\)/); - assert.match(report, /Installer \(frontend\)/); - assert.doesNotMatch(report, /Release tooling/); -}); - -test('failed and incomplete jobs do not turn missing measurements into successes', () => { - const report = installerTimingReport([ - { - name: 'Installer (windows-latest)', - html_url: 'https://example.com/job', - started_at: at(0), - completed_at: null, - conclusion: 'cancelled', - steps: [ - step('Verify Installer', 5, 8, 'failure'), - { name: 'Post Restore Installer Rust cache', conclusion: 'skipped' } - ] - } - ]); - assert.match(report, /Queue \| unavailable/); - assert.match(report, /Verification \| 3 \| failure/); - assert.match(report, /npm ci \| unavailable \| not run/); - assert.match(report, /Rust cache save \/ cleanup \| 0 \| skipped/); - assert.match(report, /Total \(excluding queue\) \| unavailable \| cancelled/); -}); diff --git a/.github/scripts/release-secrets.sh b/.github/scripts/release-secrets.sh deleted file mode 100644 index 3fcc777..0000000 --- a/.github/scripts/release-secrets.sh +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env bash -# The GitHub secrets and variables .github/workflows/release.yml consumes: -# which ones a run needs and how the signing ones reach -# bazaarplusplus-installer/scripts/bundle.sh. The names, scopes and local -# sources live in release/github-secrets.json, read through -# release/github-secrets.mjs; this script restates none of them. The workflow -# maps every secret and variable into an environment variable of the same name -# before calling this script, so a missing one is an empty variable here. -# Values are never printed; release-secrets.test.mjs beside this file is the -# executable specification. -# -# release-secrets.sh check -# Exit 1 with one ::error per missing name, naming its local source. -# release-secrets.sh stage -# Write the files bundle.sh reads from BPP_SIGNING_SECRETS_DIR. -# release-secrets.sh names -# List every name release.yml reads (for the test). -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -TABLE="$SCRIPT_DIR/../../release/github-secrets.mjs" - -table() { - node "$TABLE" "$@" -} - -assert_platform() { - case "$1" in - macos | windows) ;; - *) - echo "release-secrets.sh: platform must be macos or windows, got '$1'" >&2 - exit 2 - ;; - esac -} - -report_missing() { - echo "::error title=Missing secret::$1 is not set for this run; its value is: $(table source "$1")" -} - -cmd_check() { - local platform="$1" stage="$2" - assert_platform "$platform" - case "$stage" in - prepare | release) ;; - *) - echo "release-secrets.sh: stage must be prepare or release, got '$stage'" >&2 - exit 2 - ;; - esac - local required=() - read -r -a required <<<"$(table required "$platform" "$stage" | tr '\n' ' ')" - local missing=0 name - for name in "${required[@]}"; do - if [[ -z "${!name:-}" ]]; then - report_missing "$name" - missing=$((missing + 1)) - fi - done - if ((missing > 0)); then - echo "$missing required secret(s) missing for the $platform $stage stage; add them with 'just secrets-sync' (docs/release.md)." >&2 - exit 1 - fi - echo "All ${#required[@]} secrets for the $platform $stage stage are present." -} - -write_secret_file() { - local directory="$1" file="$2" name="$3" - ( - umask 077 - printf '%s' "${!name}" >"$directory/$file" - ) -} - -# The names stage writes as files, in the layout load_updater_signing_env and -# load_macos_developer_id_env in bundle.sh read; APPLE_API_KEY_PATH is inferred -# from AuthKey_.p8. TAURI_SIGNING_PRIVATE_KEY_PASSWORD is not in -# the table (the updater key has no password) but is still staged when set. -staged_names() { - local platform="$1" - local names="TAURI_SIGNING_PRIVATE_KEY" - if [[ "$platform" == macos ]]; then - names+=" APPLE_SIGNING_IDENTITY APPLE_API_ISSUER APPLE_API_KEY APPLE_API_KEY_P8" - fi - echo "$names" -} - -cmd_stage() { - local platform="$1" directory="$2" - assert_platform "$platform" - [[ -n "$directory" ]] || { - echo "release-secrets.sh: stage needs a directory" >&2 - exit 2 - } - local name - for name in $(staged_names "$platform"); do - [[ -n "${!name:-}" ]] || { - report_missing "$name" - exit 1 - } - done - ( - umask 077 - mkdir -p "$directory" - ) - write_secret_file "$directory" tauri-updater.key TAURI_SIGNING_PRIVATE_KEY - if [[ -n "${TAURI_SIGNING_PRIVATE_KEY_PASSWORD:-}" ]]; then - write_secret_file "$directory" tauri-updater.password TAURI_SIGNING_PRIVATE_KEY_PASSWORD - fi - if [[ "$platform" == macos ]]; then - write_secret_file "$directory" apple-signing-identity APPLE_SIGNING_IDENTITY - write_secret_file "$directory" apple-api-issuer APPLE_API_ISSUER - write_secret_file "$directory" apple-api-key APPLE_API_KEY - write_secret_file "$directory" "AuthKey_${APPLE_API_KEY}.p8" APPLE_API_KEY_P8 - fi - echo "Staged $platform signing secrets into $directory" -} - -usage() { - echo "Usage: release-secrets.sh check | stage | names" >&2 - exit 2 -} - -main() { - local command="${1:-}" - shift || true - case "$command" in - check) - [[ $# -eq 2 ]] || usage - cmd_check "$@" - ;; - stage) - [[ $# -eq 2 ]] || usage - cmd_stage "$@" - ;; - names) table names ;; - *) usage ;; - esac -} - -main "$@" diff --git a/.github/scripts/release-secrets.test.mjs b/.github/scripts/release-secrets.test.mjs deleted file mode 100644 index b9d90d4..0000000 --- a/.github/scripts/release-secrets.test.mjs +++ /dev/null @@ -1,175 +0,0 @@ -import assert from 'node:assert/strict'; -import { spawnSync } from 'node:child_process'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import test from 'node:test'; - -const scriptsDir = import.meta.dirname; -const script = path.join(scriptsDir, 'release-secrets.sh'); -const workflow = path.join(scriptsDir, '..', 'workflows', 'release.yml'); -const table = path.join(scriptsDir, '..', '..', 'release', 'github-secrets.mjs'); - -// Distinct values so a leak is attributable to one name. -const values = { - CLOUDFLARE_ACCOUNT_ID: 'value-account-id', - CLOUDFLARE_API_TOKEN: 'value-operator-token', - TAURI_SIGNING_PRIVATE_KEY: 'value-updater-key\nline two\n', - APPLE_SIGNING_IDENTITY: 'Developer ID Application: Example (TEAMID)', - APPLE_API_ISSUER: 'value-issuer', - APPLE_API_KEY: 'KEYID1234', - APPLE_API_KEY_P8: '-----BEGIN PRIVATE KEY-----\nvalue-p8\n', - APPLE_CERTIFICATE: 'value-certificate', - APPLE_CERTIFICATE_PASSWORD: 'value-certificate-password' -}; - -function run(args, secrets = values) { - const env = { PATH: process.env.PATH, HOME: os.tmpdir() }; - for (const [name, value] of Object.entries(secrets)) env[name] = value; - return spawnSync('bash', [script, ...args], { env, encoding: 'utf8' }); -} - -function tableNames(verb) { - const result = spawnSync(process.execPath, [table, verb], { - encoding: 'utf8' - }); - assert.equal(result.status, 0, result.stderr); - return result.stdout.trim().split('\n').filter(Boolean); -} - -function assertNoValueLeak(result) { - for (const value of Object.values(values)) { - assert.ok( - !result.stdout.includes(value) && !result.stderr.includes(value), - `secret value printed: ${value}` - ); - } -} - -test('release.yml reads exactly the names the table lists, each at its scope', () => { - const text = fs.readFileSync(workflow, 'utf8'); - const referenced = (kind) => - [...new Set([...text.matchAll(new RegExp(`${kind}\\.([A-Z0-9_]+)`, 'g'))].map((m) => m[1]))].sort(); - const names = run(['names']); - assert.equal(names.status, 0, names.stderr); - assert.deepEqual(names.stdout.trim().split('\n').sort(), tableNames('names').sort()); - assert.deepEqual(referenced('secrets'), tableNames('secrets').sort()); - assert.deepEqual(referenced('vars'), tableNames('variables').sort()); - assert.deepEqual(Object.keys(values).sort(), tableNames('names').sort()); - assert.doesNotMatch(text, /TAURI_SIGNING_PRIVATE_KEY_PASSWORD|BPP_R2_|BPP_GAME_LIBS_R2_/); -}); - -test('check passes when every name of the stage is present', () => { - for (const platform of ['macos', 'windows']) { - for (const stage of ['prepare', 'release']) { - const result = run(['check', platform, stage]); - assert.equal(result.status, 0, result.stdout + result.stderr); - assert.match(result.stdout, /secrets for the .* stage are present/); - assertNoValueLeak(result); - } - } -}); - -test('check names each missing name and its local source, then fails', () => { - const secrets = { ...values, APPLE_API_KEY_P8: '', CLOUDFLARE_ACCOUNT_ID: '' }; - const result = run(['check', 'macos', 'release'], secrets); - assert.equal(result.status, 1); - assert.match( - result.stdout, - /::error title=Missing secret::APPLE_API_KEY_P8 is not set for this run; its value is: contents of keys\/AuthKey_\.p8/ - ); - assert.match( - result.stdout, - /::error title=Missing secret::CLOUDFLARE_ACCOUNT_ID is not set for this run; its value is: config\.ini \[cloudflare\] CLOUDFLARE_ACCOUNT_ID/ - ); - assert.match(result.stderr, /2 required secret\(s\) missing/); - assertNoValueLeak(result); -}); - -test('a dry run needs only the operator token and the account id', () => { - const secrets = { - CLOUDFLARE_ACCOUNT_ID: values.CLOUDFLARE_ACCOUNT_ID, - CLOUDFLARE_API_TOKEN: values.CLOUDFLARE_API_TOKEN - }; - for (const platform of ['macos', 'windows']) { - assert.equal(run(['check', platform, 'prepare'], secrets).status, 0); - assert.equal(run(['check', platform, 'release'], secrets).status, 1); - } -}); - -test('windows needs no Apple material', () => { - const secrets = { ...values }; - for (const name of Object.keys(values)) - if (name.startsWith('APPLE_')) secrets[name] = ''; - assert.equal(run(['check', 'windows', 'release'], secrets).status, 0); - const macos = run(['check', 'macos', 'release'], secrets); - assert.equal(macos.status, 1); - assert.match(macos.stderr, /6 required secret\(s\) missing/); -}); - -test('stage writes the files bundle.sh reads from BPP_SIGNING_SECRETS_DIR; the updater password is optional and outside the table', (t) => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-release-secrets-')); - t.after(() => fs.rmSync(root, { recursive: true, force: true })); - const macos = path.join(root, 'macos'); - let result = run(['stage', 'macos', macos], { - ...values, - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: 'value-updater-password' - }); - assert.equal(result.status, 0, result.stdout + result.stderr); - assertNoValueLeak(result); - assert.ok(!result.stdout.includes('value-updater-password')); - assert.deepEqual(fs.readdirSync(macos).sort(), [ - 'AuthKey_KEYID1234.p8', - 'apple-api-issuer', - 'apple-api-key', - 'apple-signing-identity', - 'tauri-updater.key', - 'tauri-updater.password' - ]); - assert.equal( - fs.readFileSync(path.join(macos, 'tauri-updater.key'), 'utf8'), - values.TAURI_SIGNING_PRIVATE_KEY - ); - assert.equal( - fs.readFileSync(path.join(macos, 'AuthKey_KEYID1234.p8'), 'utf8'), - values.APPLE_API_KEY_P8 - ); - assert.equal( - fs.readFileSync(path.join(macos, 'apple-signing-identity'), 'utf8'), - values.APPLE_SIGNING_IDENTITY - ); - if (process.platform !== 'win32') { - assert.equal(fs.statSync(macos).mode & 0o777, 0o700); - for (const file of fs.readdirSync(macos)) - assert.equal(fs.statSync(path.join(macos, file)).mode & 0o777, 0o600); - } - - const windows = path.join(root, 'windows'); - result = run(['stage', 'windows', windows]); - assert.equal(result.status, 0, result.stdout + result.stderr); - assert.deepEqual(fs.readdirSync(windows), ['tauri-updater.key']); -}); - -test('stage refuses to write a partial directory', (t) => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-release-secrets-')); - t.after(() => fs.rmSync(root, { recursive: true, force: true })); - const directory = path.join(root, 'macos'); - const result = run(['stage', 'macos', directory], { - ...values, - APPLE_API_ISSUER: '' - }); - assert.equal(result.status, 1); - assert.match( - result.stdout, - /Missing secret::APPLE_API_ISSUER is not set for this run; its value is: config\.ini \[signing\] APPLE_API_ISSUER/ - ); - assert.ok(!fs.existsSync(directory)); -}); - -test('usage errors exit 2', () => { - assert.equal(run([]).status, 2); - assert.equal(run(['check', 'linux', 'release']).status, 2); - assert.equal(run(['check', 'macos', 'ship']).status, 2); - assert.equal(run(['stage', 'macos']).status, 2); - assert.equal(run(['optional']).status, 2); -}); diff --git a/.github/scripts/test_analyzer_state.py b/.github/scripts/test_analyzer_state.py deleted file mode 100644 index 8e760cb..0000000 --- a/.github/scripts/test_analyzer_state.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Stubbed checks for .github/scripts/analyzer_state.py mirror semantics.""" - -import hashlib -import sys -import tempfile -import unittest -from pathlib import Path - -repo_root = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(repo_root / ".github" / "scripts")) - -import analyzer_state - - -class FakeClient: - def __init__(self, objects): - self.objects = dict(objects) - self.puts = [] - self.deletes = [] - - def get_paginator(self, name): - assert name == "list_objects_v2" - client = self - - class Paginator: - def paginate(self, Bucket): - contents = [ - { - "Key": key, - "Size": len(body), - "ETag": '"' + hashlib.md5(body).hexdigest() + '"', - } - for key, body in sorted(client.objects.items()) - ] - yield {"Contents": contents} - - return Paginator() - - def get_object(self, Bucket, Key): - body = self.objects[Key] - - class Body: - def read(self): - return body - - return {"Body": Body()} - - def put_object(self, Bucket, Key, Body): - self.objects[Key] = Body - self.puts.append((Key, Body)) - - def delete_object(self, Bucket, Key): - del self.objects[Key] - self.deletes.append(Key) - - -BUCKET = "test-bucket" - - -class AnalyzerStateTests(unittest.TestCase): - def test_excluded_skips_locks_staging_and_duckdb_temp(self): - for key in ( - ".lock", - "facts/.lock.lease", - "facts/hourly/x.parquet.tmp-abc", - "duckdb-tmp/scratch.db", - ): - with self.subTest(key=key): - self.assertTrue(analyzer_state._excluded(key)) - - def test_excluded_keeps_committed_facts(self): - for key in ( - "facts/hourly/2026-10-20T01.parquet", - "status.json", - "logs/run.log", - ): - with self.subTest(key=key): - self.assertFalse(analyzer_state._excluded(key)) - - def test_pull_refuses_non_empty_root(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - (root / "stale").write_bytes(b"x") - with self.assertRaises(SystemExit): - analyzer_state.pull(FakeClient({}), BUCKET, root) - - def test_pull_restores_objects_and_nested_dirs(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) / "data" - client = FakeClient( - { - "status.json": b"{}", - "facts/hourly/2026-10-20T01.parquet": b"pq", - ".lock": b"ignored", - } - ) - analyzer_state.pull(client, BUCKET, root) - self.assertEqual((root / "status.json").read_bytes(), b"{}") - self.assertEqual( - (root / "facts" / "hourly" / "2026-10-20T01.parquet").read_bytes(), b"pq" - ) - self.assertFalse((root / ".lock").exists()) - - def test_push_uploads_only_changed_lengths_and_deletes_pruned(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - (root / "same.json").write_bytes(b"aa") - (root / "changed.json").write_bytes(b"new") - (root / "facts").mkdir() - (root / "facts" / "d.parquet").write_bytes(b"data") - (root / ".lock").write_bytes(b"not mirrored") - - client = FakeClient( - { - "same.json": b"aa", - "changed.json": b"old", - "pruned.json": b"gone", - ".lock": b"stale", - } - ) - analyzer_state.push(client, BUCKET, root, delete_extra=True) - - uploaded = {key for key, _ in client.puts} - self.assertNotIn("same.json", uploaded) - self.assertIn("changed.json", uploaded) - self.assertIn("facts/d.parquet", uploaded) - self.assertNotIn(".lock", uploaded) - self.assertEqual(client.deletes, ["pruned.json"]) - - def test_push_new_never_deletes(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - (root / "a.json").write_bytes(b"a") - client = FakeClient({"pruned.json": b"gone"}) - analyzer_state.push(client, BUCKET, root, delete_extra=False) - self.assertEqual(client.deletes, []) - self.assertIn("pruned.json", client.objects) - - -if __name__ == "__main__": - unittest.main() diff --git a/.github/scripts/test_mod_dependency_update.py b/.github/scripts/test_mod_dependency_update.py deleted file mode 100644 index 71605cf..0000000 --- a/.github/scripts/test_mod_dependency_update.py +++ /dev/null @@ -1,147 +0,0 @@ -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -from check_mod_dependency_update import CENTRAL_PACKAGES, TEST_TOOLS, validate_changes - - -def packages(name, version="1.0.0", extra=""): - return ( - '' - + extra - + "" - ) - - -class ModDependencyUpdateTests(unittest.TestCase): - def test_existing_test_tool_versions_can_change(self): - for name in TEST_TOOLS: - with self.subTest(name=name): - self.assertEqual( - validate_changes({CENTRAL_PACKAGES: (packages(name), packages(name, "2.0.0"))}), - [], - ) - - def test_runtime_generators_and_unknown_dependencies_require_manual_maintenance(self): - for name in ( - "Newtonsoft.Json", - "MessagePackAnalyzer", - "BepInEx.Core", - "UnityEngine.Modules", - "Krafs.Publicizer", - "Microsoft.Data.Sqlite", - "Future.Runtime.Library", - ): - with self.subTest(name=name): - self.assertTrue( - validate_changes({CENTRAL_PACKAGES: (packages(name), packages(name, "2.0.0"))}) - ) - - def test_allowed_update_cannot_hide_a_new_reference_or_msbuild_target(self): - before = packages("xunit") - for extra in ( - '', - '', - ): - with self.subTest(extra=extra): - self.assertTrue( - validate_changes( - {CENTRAL_PACKAGES: (before, packages("xunit", "2.0.0", extra))} - ) - ) - - def test_runtime_lock_churn_is_rejected_even_with_allowed_direct_update(self): - self.assertTrue( - validate_changes( - { - CENTRAL_PACKAGES: (packages("xunit"), packages("xunit", "2.0.0")), - "bazaarplusplus-mod/src/BazaarPlusPlus/packages.lock.json": ("old", "new"), - } - ) - ) - - def test_changes_to_game_references_sources_or_removed_packages_are_rejected(self): - for path in ( - "bazaarplusplus-mod/build/GameLibraries.props", - "bazaarplusplus-mod/src/New.cs", - CENTRAL_PACKAGES, - ): - with self.subTest(path=path): - self.assertTrue(validate_changes({path: ("old", None)})) - - def test_invalid_xml_is_rejected(self): - self.assertTrue(validate_changes({CENTRAL_PACKAGES: (packages("xunit"), "= "3.14"']} - } - lock = { - "version": 1, - "revision": 3, - "requires-python": "==3.14.*", - "package": [ - { - "name": "app", - "version": "1.0.0", - "source": {"editable": "."}, - "dependencies": [ - {"name": "library", "version": "1.2.3", "source": PYPI} - ], - "metadata": { - "requires-dist": [ - { - "name": "library", - "specifier": "==1.2.3", - "extras": ["extra"], - "marker": "python_version >= '3.14'", - } - ] - }, - }, - { - "name": "library", - "version": "1.2.3", - "source": PYPI, - "wheels": [artifact("1.2.3")], - }, - ], - } - after_manifest, after_lock = copy.deepcopy(manifest), copy.deepcopy(lock) - after_manifest["project"]["dependencies"][0] = manifest["project"]["dependencies"][ - 0 - ].replace("1.2.3", "1.2.4") - after_lock["package"][0]["dependencies"][0]["version"] = "1.2.4" - after_lock["package"][0]["metadata"]["requires-dist"][0]["specifier"] = "==1.2.4" - after_lock["package"][1].update(version="1.2.4", wheels=[artifact("1.2.4")]) - return [manifest, after_manifest, lock, after_lock] - - -class CargoPolicyTests(unittest.TestCase): - def test_patch_with_duplicate_names_qualified_edges_and_unchanged_prerelease(self): - data = cargo_fixture() - original = copy.deepcopy(data) - self.assertTrue(patch_only("cargo", *data)) - self.assertEqual(data, original) - - def test_sensitive_metadata_and_graph_changes_are_rejected(self): - mutations = [ - lambda d: d[1]["dependencies"]["library"].update(features=["other"]), - lambda d: d[1].update(package={"build": "new.rs"}), - lambda d: d[3]["package"][1].update( - source="git+https://example.com/library" - ), - lambda d: d[3]["package"][1].update(checksum="invalid"), - lambda d: d[3]["package"][0]["dependencies"].pop(), - lambda d: d[3]["package"].append({"name": "new", "version": "1.0.0"}), - lambda d: d[3]["package"][3].update(version="2.0.0-rc.26"), - lambda d: d[3]["package"][1].update(version="1.3.0"), - lambda d: d[3]["package"][1].update(version="1.2.2"), - lambda d: d[3].update(version=5), - ] - for mutate in mutations: - with self.subTest(mutation=mutate): - data = cargo_fixture() - mutate(data) - self.assertFalse(patch_only("cargo", *data)) - - def test_real_installer_lock_supports_patch_without_collapsing_duplicate_names( - self, - ): - root = ( - Path(__file__).resolve().parents[2] / "bazaarplusplus-installer/src-tauri" - ) - manifest = tomllib.loads((root / "Cargo.toml").read_text()) - lock = tomllib.loads((root / "Cargo.lock").read_text()) - after = copy.deepcopy(lock) - target = next( - p - for p in after["package"] - if p["name"] == "base64" and p["version"].startswith("0.22.") - ) - old = target["version"] - parts = old.split(".") - target["version"] = ".".join([*parts[:2], str(int(parts[2]) + 1)]) - target["checksum"] = "f" * 64 - for package in after["package"]: - if "dependencies" in package: - package["dependencies"] = [ - e.replace(f"base64 {old}", f"base64 {target['version']}") - for e in package["dependencies"] - ] - self.assertTrue(patch_only("cargo", manifest, manifest, lock, after)) - - -class UvPolicyTests(unittest.TestCase): - def test_patch_normalizes_pins_artifacts_and_metadata_but_preserves_markers(self): - data = uv_fixture() - original = copy.deepcopy(data) - self.assertTrue(patch_only("uv", *data)) - self.assertEqual(data, original) - - def test_graph_markers_artifact_sources_and_prereleases_require_review(self): - mutations = [ - lambda d: d[1]["project"].update(dependencies=["library==1.2.4"]), - lambda d: d[3]["package"][0]["metadata"]["requires-dist"][0].update( - marker="python_version < '3.14'" - ), - lambda d: d[3]["package"][0]["metadata"]["requires-dist"][0].update( - specifier="==1.2.5" - ), - lambda d: d[3]["package"][1]["wheels"][0].update( - url="https://files.pythonhosted.org.evil.test/library.whl" - ), - lambda d: d[3]["package"][1]["wheels"][0].update(hash="sha256:bad"), - lambda d: d[3]["package"][1].update( - source={"registry": "https://example.com"} - ), - lambda d: d[3]["package"][1].update(version="1.2.4rc1"), - lambda d: d[3].update(revision=4), - ] - for mutate in mutations: - with self.subTest(mutation=mutate): - data = uv_fixture() - mutate(data) - self.assertFalse(patch_only("uv", *data)) - - def test_prerelease_suffix_in_manifest_is_not_treated_as_a_marker(self): - data = uv_fixture() - data[0]["project"]["dependencies"] = ["library==1.2.3rc1"] - data[1]["project"]["dependencies"] = ["library==1.2.4rc1"] - self.assertFalse(patch_only("uv", *data)) - - -if __name__ == "__main__": - unittest.main() diff --git a/.github/workflows/analyzer.yml b/.github/workflows/analyzer.yml deleted file mode 100644 index aa67516..0000000 --- a/.github/workflows/analyzer.yml +++ /dev/null @@ -1,145 +0,0 @@ -name: Analyzer - -# Production analyzer V6 runs. Each run restores the Data Root from the private -# R2 state bucket, heals settled Source Hours, publishes both consumer -# snapshots to the V6 metrics bucket and mirrors the Data Root back. Snapshots -# still advance once per Complete Source Day; the hourly schedule keeps each -# run's intake small. Secrets live in the `analyzer` GitHub Environment -# (release/github-secrets.json); see -# bazaarplusplus-analyzer/docs/architecture.md, Production runs. - -# The V6 Bundle Server Worker dispatches this workflow at :23 every hour -# (bazaarplusplus-server/src/modules/analyzer-dispatch.ts) because GitHub drops -# most scheduled events. This schedule is only a fallback for when the Worker -# cannot reach GitHub; it sits at :53 so it never queues behind a dispatch. -on: - schedule: - - cron: '53 */6 * * *' - workflow_dispatch: - inputs: - publish: - description: Publish snapshots to the V6 metrics bucket - type: boolean - default: true - -permissions: - contents: read - -# The R2 state bucket has one writer; a run never cancels another mid-sync. -# A run still going when the next dispatch arrives leaves one pending run, and -# later triggers replace that pending run rather than stacking up. -concurrency: - group: analyzer-v6 - cancel-in-progress: false - -jobs: - run: - name: Analyzer V6 - if: github.repository == 'BazaarPlusPlus/BazaarPlusPlus' - runs-on: ubuntu-latest - environment: analyzer - # BPP_MAX_RUN_SECONDS stops the pipeline at five hours, leaving time to - # mirror committed hours back before the six-hour job limit. - timeout-minutes: 340 - env: - BPP_ANALYZER_STATE_BUCKET: bazaarplusplus-analyzer-state-v6 - CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} - steps: - - id: gate - name: Check analyzer secrets - env: - BPP_BUNDLE_SYNC_TOKEN: ${{ secrets.BPP_BUNDLE_SYNC_TOKEN }} - BPP_ANALYZER_R2_TOKEN: ${{ secrets.BPP_ANALYZER_R2_TOKEN }} - EVENT: ${{ github.event_name }} - run: | - missing=() - for name in BPP_BUNDLE_SYNC_TOKEN BPP_ANALYZER_R2_TOKEN CLOUDFLARE_ACCOUNT_ID; do - [ -n "${!name}" ] || missing+=("$name") - done - if [ "${#missing[@]}" -eq 0 ]; then - echo "ready=true" >> "$GITHUB_OUTPUT" - echo "BPP_DATA_ROOT=$RUNNER_TEMP/bpp-data" >> "$GITHUB_ENV" - elif [ "$EVENT" = schedule ]; then - # Until the environment is provisioned, scheduled runs stay quiet. - echo "::notice::Analyzer skipped; missing ${missing[*]}" - echo "ready=false" >> "$GITHUB_OUTPUT" - else - echo "::error::Missing ${missing[*]} in the analyzer environment" - exit 1 - fi - - - if: steps.gate.outputs.ready == 'true' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - if: steps.gate.outputs.ready == 'true' - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0 - with: - working-directory: bazaarplusplus-analyzer - - if: steps.gate.outputs.ready == 'true' - run: uv sync --locked --no-dev - working-directory: bazaarplusplus-analyzer - - - if: steps.gate.outputs.ready == 'true' - name: Write analyzer configuration - working-directory: bazaarplusplus-analyzer - env: - BPP_BUNDLE_SYNC_TOKEN: ${{ secrets.BPP_BUNDLE_SYNC_TOKEN }} - BPP_ANALYZER_R2_TOKEN: ${{ secrets.BPP_ANALYZER_R2_TOKEN }} - run: | - # bppanalyzer.config reads only this file, never the environment. - umask 077 - { - echo "BPP_DATA_ROOT=$BPP_DATA_ROOT" - echo "BPP_API_BASE_URL=https://mod-api-v6.bazaarplusplus.com" - echo "BPP_BUNDLE_SYNC_TOKEN=$BPP_BUNDLE_SYNC_TOKEN" - echo "BPP_METRICS_R2_BUCKET=bazaarplusplus-metrics-v6" - echo "CLOUDFLARE_ACCOUNT_ID=$CLOUDFLARE_ACCOUNT_ID" - echo "CLOUDFLARE_API_TOKEN=$BPP_ANALYZER_R2_TOKEN" - # The V6 Bundle Server went live on this Source Day. - echo "BPP_SOURCE_EPOCH=2026-10-11" - echo "BPP_MAX_RUN_SECONDS=18000" - echo "BPP_DUCKDB_THREADS=4" - } > .env - - # The state mirror derives its own S3 pair from BPP_ANALYZER_R2_TOKEN inside - # analyzer_state.py; no AWS CLI or exported key pair is required. - - - id: pull - if: steps.gate.outputs.ready == 'true' - name: Restore the Data Root - run: bash .github/scripts/analyzer-state.sh pull - - if: steps.pull.outcome == 'success' - name: Verify restored facts - working-directory: bazaarplusplus-analyzer - run: uv run --locked --no-dev bpp verify --deep - - - id: analyze - if: steps.pull.outcome == 'success' - name: Run the analyzer - working-directory: bazaarplusplus-analyzer - env: - PUBLISH: ${{ github.event_name == 'schedule' || inputs.publish }} - run: | - args=(run --quiet) - [ "$PUBLISH" = true ] || args+=(--no-publish) - uv run --locked --no-dev bpp "${args[@]}" - - # Retention deletions are mirrored only after a fully successful run; a - # failed one uploads the hours it committed and deletes nothing. - - if: steps.analyze.outcome == 'success' - name: Mirror the Data Root - run: bash .github/scripts/analyzer-state.sh push - - if: always() && steps.analyze.outcome == 'failure' - name: Upload committed hours - run: bash .github/scripts/analyzer-state.sh push-new - - - if: always() && steps.pull.outcome == 'success' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: analyzer-evidence-${{ github.run_id }} - path: | - ${{ runner.temp }}/bpp-data/status.json - ${{ runner.temp }}/bpp-data/logs/ - retention-days: 14 - if-no-files-found: ignore diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml deleted file mode 100644 index 6fe5353..0000000 --- a/.github/workflows/checks.yml +++ /dev/null @@ -1,404 +0,0 @@ -name: Checks - -on: - pull_request: - push: - branches: [master] - workflow_dispatch: - inputs: - scope: - description: Projects to verify - type: choice - options: [full, installer, mod] - default: full - platform: - description: Native platforms to verify - type: choice - options: [all, macos, windows] - default: all - -permissions: - contents: read - -concurrency: - group: checks-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }}-${{ inputs.scope }}-${{ inputs.platform }} - # Let master finish the post-job cache save even when another merge arrives. - cancel-in-progress: ${{ !(github.event_name == 'push' && github.ref == 'refs/heads/master') }} - -# Explicit platform jobs let the summary verify each selected native result. -jobs: - classify: - name: Classify changes - runs-on: ubuntu-latest - timeout-minutes: 5 - outputs: - release: ${{ steps.scope.outputs.release }} - site: ${{ steps.scope.outputs.site }} - server: ${{ steps.scope.outputs.server }} - analyzer: ${{ steps.scope.outputs.analyzer }} - installer-frontend: ${{ steps.scope.outputs.installer-frontend }} - installer-macos: ${{ steps.scope.outputs.installer-macos }} - installer-windows: ${{ steps.scope.outputs.installer-windows }} - mod-macos: ${{ steps.scope.outputs.mod-macos }} - mod-windows: ${{ steps.scope.outputs.mod-windows }} - macos-icon: ${{ steps.scope.outputs.macos-icon }} - plan: ${{ steps.scope.outputs.plan }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - # Keep the scripts available even if fetching history fails. The - # classifier falls back to full coverage if a diff cannot be obtained. - - id: history - name: Fetch complete history for change detection - continue-on-error: true - run: git fetch --no-tags --unshallow origin - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - - id: scope - run: node .github/scripts/checks-scope.mjs - env: - HISTORY_FETCH_OUTCOME: ${{ steps.history.outcome }} - - macos-icon: - name: macOS Icon Composer asset - needs: classify - if: needs.classify.outputs.macos-icon == 'true' - runs-on: macos-26 - timeout-minutes: 5 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - - run: | - xcodebuild -version - node bazaarplusplus-installer/scripts/release/compile-macos-icon.mjs - - release: - name: Release tooling - needs: classify - if: needs.classify.outputs.release == 'true' - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 - with: - global-json-file: bazaarplusplus-mod/global.json - - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 - with: - just-version: 1.58.0 - - run: npm install --global "$(node --print "require('./package.json').packageManager")" - - run: npm ci - - run: just commands-check release::check release::test - - run: python3 -m unittest discover -s .github/scripts -p 'test_*.py' - - run: node --test .github/scripts/*.test.mjs - - site: - name: site (full check and test) - needs: classify - if: needs.classify.outputs.site == 'true' - runs-on: ubuntu-latest - timeout-minutes: 15 - env: - PROJECT: site - WRANGLER_SEND_METRICS: 'false' - steps: &node-steps - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - cache: npm - cache-dependency-path: bazaarplusplus-${{ env.PROJECT }}/package-lock.json - - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 - with: - just-version: 1.58.0 - - run: npm install --global "$(node --print "require('./package.json').packageManager")" - - run: npm ci - working-directory: bazaarplusplus-${{ env.PROJECT }} - - run: just '${{ env.PROJECT }}::check' - - if: env.PROJECT == 'site' - run: | - just site::test - npm --prefix bazaarplusplus-site run deploy:dry-run - npm --prefix bazaarplusplus-site run deploy:preview:dry-run - - if: env.PROJECT == 'site' - working-directory: bazaarplusplus-site - run: npx playwright install --with-deps chromium - - if: env.PROJECT == 'site' - run: just site::e2e golden - - if: failure() && env.PROJECT == 'site' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: site-e2e-results - path: | - bazaarplusplus-site/test-results/ - bazaarplusplus-site/e2e/__snapshots__/ - if-no-files-found: ignore - - if: env.PROJECT == 'server' - run: just server::test - - server: - name: server (full check and test) - needs: classify - if: needs.classify.outputs.server == 'true' - runs-on: ubuntu-latest - timeout-minutes: 15 - env: - PROJECT: server - WRANGLER_SEND_METRICS: 'false' - steps: *node-steps - - installer-frontend: - name: Installer (frontend) - needs: classify - if: needs.classify.outputs.installer-frontend == 'true' - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - cache: npm - cache-dependency-path: bazaarplusplus-installer/package-lock.json - - run: npm install --global "$(node --print "require('./package.json').packageManager")" - working-directory: bazaarplusplus-installer - - name: Install Installer npm dependencies - run: npm ci - working-directory: bazaarplusplus-installer - # Consume committed bindings; native inputs also select real generation. - - name: Verify Installer - run: npm run verify -- --source-only --subset frontend - working-directory: bazaarplusplus-installer - - installer-macos: - name: Installer (macos-14) - needs: classify - if: needs.classify.outputs.installer-macos == 'true' - runs-on: macos-14 - timeout-minutes: 60 - env: &installer-env - CARGO_INCREMENTAL: '0' - CARGO_PROFILE_DEV_DEBUG: '0' - CARGO_PROFILE_TEST_DEBUG: '0' - defaults: - run: - shell: bash - steps: &installer-steps - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - cache: npm - cache-dependency-path: bazaarplusplus-installer/package-lock.json - - name: Install the repository Rust toolchain and components - working-directory: bazaarplusplus-installer - run: | - rustc --version - rustup show active-toolchain - - name: Restore Installer Rust cache - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - workspaces: bazaarplusplus-installer/src-tauri - # Include these in the prefix so even fallback restores cannot cross - # toolchain, lockfile or build-configuration changes. - # Preserve the former matrix job ID suffix without coupling the - # cache namespace to the new job IDs. shared-key replaces key + job. - shared-key: installer-${{ runner.os == 'macOS' && 'macos-14' || 'windows-latest' }}-${{ runner.arch }}-${{ hashFiles('bazaarplusplus-installer/rust-toolchain.toml', 'bazaarplusplus-installer/src-tauri/Cargo.lock', 'bazaarplusplus-installer/src-tauri/.cargo/config.toml') }}-installer - cache-bin: false - save-if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} - - run: npm install --global "$(node --print "require('./package.json').packageManager")" - working-directory: bazaarplusplus-installer - - name: Install Installer npm dependencies - run: npm ci - working-directory: bazaarplusplus-installer - # Real binding generation precedes the diff check. Windows also repeats - # script tests; both platforms use an empty source resource bundle. - - name: Verify Installer - run: npm run verify -- --source-only --subset native - working-directory: bazaarplusplus-installer - - installer-windows: - name: Installer (windows-latest) - needs: classify - if: needs.classify.outputs.installer-windows == 'true' - runs-on: windows-latest - timeout-minutes: 60 - env: *installer-env - defaults: - run: - shell: bash - steps: *installer-steps - - installer-timings: - name: Installer timing report - needs: [classify, installer-frontend, installer-macos, installer-windows] - if: always() && needs.classify.outputs.installer-frontend == 'true' - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - contents: read - actions: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - # Post-job cache saves have finished; the Jobs API includes their timing. - - run: node .github/scripts/installer-timings.mjs - env: - GH_TOKEN: ${{ github.token }} - - analyzer: - name: Analyzer - needs: classify - if: needs.classify.outputs.analyzer == 'true' - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0 - with: - working-directory: bazaarplusplus-analyzer - - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 - with: - just-version: 1.58.0 - - run: uv sync --locked - working-directory: bazaarplusplus-analyzer - - run: just analyzer::check analyzer::test - - mod-macos: - name: Mod (macos-14) - needs: classify - # Fork PRs have no private snapshots; summary records the explicit exception. - if: needs.classify.outputs.mod-macos == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) - runs-on: macos-14 - timeout-minutes: 45 - defaults: - run: - shell: bash - env: - BPP_CI_PLATFORM: macos - CLOUDFLARE_API_TOKEN: ${{ secrets.BPP_GAME_LIBS_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} - steps: &mod-steps - - name: Require private store credentials - run: | - if [[ -z "$CLOUDFLARE_API_TOKEN" || -z "$CLOUDFLARE_ACCOUNT_ID" ]]; then - echo '::error::BPP_GAME_LIBS_TOKEN or CLOUDFLARE_ACCOUNT_ID is missing; selected Mod checks cannot run.' - exit 1 - fi - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 - with: - global-json-file: bazaarplusplus-mod/global.json - cache: true - cache-dependency-path: bazaarplusplus-mod/**/packages.lock.json - - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 - with: - just-version: 1.58.0 - # A null online entry fails here, naming the snapshot to capture. - - name: Fetch the online snapshot - run: just mod::fetch "$BPP_CI_PLATFORM" online - - run: just mod::check - - run: just mod::test - - name: Preserve Combat Impact corpus evidence - if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: combat-impact-corpus-${{ env.BPP_CI_PLATFORM }} - path: bazaarplusplus-mod/artifacts/combat-impact-corpus/*.json - if-no-files-found: error - # Compatibility builds against the other two channels; a null entry fails. - - run: just mod::matrix staging ptr - - mod-windows: - name: Mod (windows-latest) - needs: classify - if: needs.classify.outputs.mod-windows == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) - runs-on: windows-latest - timeout-minutes: 45 - defaults: - run: - shell: bash - env: - BPP_CI_PLATFORM: windows - CLOUDFLARE_API_TOKEN: ${{ secrets.BPP_GAME_LIBS_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} - steps: *mod-steps - - summary: - name: ${{ github.event_name == 'workflow_dispatch' && format('Manual checks ({0}/{1})', inputs.scope, inputs.platform) || 'Checks summary' }} - # A dispatch check on the same SHA must never satisfy PR protection. - if: always() - needs: - [ - classify, - release, - site, - server, - analyzer, - installer-frontend, - installer-macos, - installer-windows, - mod-macos, - mod-windows, - macos-icon, - installer-timings - ] - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - - run: node .github/scripts/checks-summary.mjs - env: - CHECK_NEEDS: ${{ toJSON(needs) }} - MOD_CREDENTIALS: ${{ secrets.BPP_GAME_LIBS_TOKEN != '' && vars.CLOUDFLARE_ACCOUNT_ID != '' }} - - bot-mod-boundary: - name: Bot Mod dependency boundary - if: github.event_name == 'pull_request' && (github.event.pull_request.user.login == 'dependabot[bot]' || github.event.pull_request.user.login == 'renovate[bot]') - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - persist-credentials: false - - name: Reject Mod runtime or transitive dependency changes - env: - BASE_SHA: ${{ github.event.pull_request.base.sha }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: | - git show "$BASE_SHA:.github/scripts/check_mod_dependency_update.py" > "$RUNNER_TEMP/check_mod_dependency_update.py" - python3 "$RUNNER_TEMP/check_mod_dependency_update.py" "$BASE_SHA" "$HEAD_SHA" diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml deleted file mode 100644 index 2bc04fd..0000000 --- a/.github/workflows/codeql.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: CodeQL - -on: - pull_request: - push: - branches: [master] - schedule: - - cron: '17 3 * * 1' - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: codeql-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -jobs: - analyze: - name: CodeQL (${{ matrix.language }}) - runs-on: ubuntu-latest - timeout-minutes: 30 - permissions: - contents: read - security-events: write - strategy: - fail-fast: false - matrix: - language: [javascript-typescript, python] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4 - with: - languages: ${{ matrix.language }} - build-mode: none - - uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4 - with: - category: /language:${{ matrix.language }} diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml deleted file mode 100644 index 751214d..0000000 --- a/.github/workflows/dependabot-auto-merge.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: Dependabot auto-merge - -on: - pull_request_target: - types: [opened, synchronize, reopened, ready_for_review, edited] - -permissions: - contents: read - -concurrency: - group: dependabot-auto-merge-${{ github.event.pull_request.number }} - cancel-in-progress: false - -jobs: - approve-patch: - if: github.event.pull_request.user.login == 'dependabot[bot]' && github.event.pull_request.base.ref == 'master' - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - contents: write - pull-requests: write - steps: - # Privileged workflow: never check out, install or execute the PR head. - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const { run } = await import('${{ github.workspace }}/.github/scripts/dependabot-auto-merge.mjs'); - await run({ github, context, core }); diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml deleted file mode 100644 index 6b05b3f..0000000 --- a/.github/workflows/dependency-review.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Dependency review - -on: - pull_request: - -permissions: - contents: read - -jobs: - dependencies: - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 - with: - fail-on-severity: moderate - comment-summary-in-pr: never diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml deleted file mode 100644 index 1f4e1cf..0000000 --- a/.github/workflows/deploy-site.yml +++ /dev/null @@ -1,88 +0,0 @@ -name: Deploy site - -# Preview deploys follow master; production deploys only on dispatch and wait -# for the site-production environment approval. The deploy token never leaves -# the GitHub Environments, so the branch policy on both environments is master; -# the account id is the repository variable every workflow shares -# (release/github-secrets.json). -on: - workflow_dispatch: - inputs: - target: - description: Deployment target - type: choice - required: true - default: preview - options: [preview, production] - push: - branches: [master] - paths: - - bazaarplusplus-site/** - - bazaarplusplus-installer/src/styles/tokens.css - - release/** - - .github/workflows/deploy-site.yml - -permissions: - contents: read - -concurrency: - group: deploy-site-${{ github.event_name == 'workflow_dispatch' && inputs.target || 'preview' }} - cancel-in-progress: false - -jobs: - deploy: - name: Deploy site (${{ github.event_name == 'workflow_dispatch' && inputs.target || 'preview' }}) - runs-on: ubuntu-latest - timeout-minutes: 20 - environment: - name: site-${{ github.event_name == 'workflow_dispatch' && inputs.target || 'preview' }} - url: ${{ steps.deploy.outputs.url }} - env: - TARGET: ${{ github.event_name == 'workflow_dispatch' && inputs.target || 'preview' }} - WRANGLER_SEND_METRICS: 'false' - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - cache: npm - cache-dependency-path: bazaarplusplus-site/package-lock.json - - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 - with: - just-version: 1.58.0 - - run: npm install --global "$(node --print "require('./package.json').packageManager")" - - run: npm ci - working-directory: bazaarplusplus-site - - name: Require Cloudflare credentials - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} - run: | - if [ -z "$CLOUDFLARE_API_TOKEN" ]; then - echo "::error::CLOUDFLARE_API_TOKEN is not set on the site-$TARGET environment." - exit 1 - fi - if [ -z "$CLOUDFLARE_ACCOUNT_ID" ]; then - echo "::error::CLOUDFLARE_ACCOUNT_ID is not set as a repository variable (just secrets-sync)." - exit 1 - fi - - run: just site::check site::test - - name: Deploy with the pinned Wrangler - id: deploy - # Explicit bash enables pipefail so a Wrangler failure is not hidden by tee. - shell: bash - working-directory: bazaarplusplus-site - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} - run: | - if [ "$TARGET" = production ]; then - npm run deploy - echo 'url=https://bazaarplusplus.com' >> "$GITHUB_OUTPUT" - else - npm run deploy:preview | tee "$RUNNER_TEMP/deploy.log" - url="$(grep -oE 'https://[A-Za-z0-9.-]+\.workers\.dev' "$RUNNER_TEMP/deploy.log" | head -n 1 || true)" - echo "url=$url" >> "$GITHUB_OUTPUT" - fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 2b3ec73..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,219 +0,0 @@ -name: Release - -# One Product Release build per platform on hosted runners: release::prepare, -# release::build and release::upload, in one job so build and upload share a -# host and the Payload lock (docs/release.md, docs/adr/0004-pinned-game-assembly-snapshots.md). -# promote is not here: the Mainland Mirror is uploaded to Lanzou by hand and -# recorded with mirror-all before promote, so promote stays a local command. -# Secrets and variables live in the `release` GitHub Environment, except the -# repository variable CLOUDFLARE_ACCOUNT_ID shared with every workflow; -# release/github-secrets.json names every one, its scope and its local source, -# and .github/scripts/release-secrets.sh checks them from that table. The R2 -# S3 pair is derived from CLOUDFLARE_API_TOKEN (release/r2-store.mjs). -on: - workflow_dispatch: - inputs: - version: - description: Product version to build; must equal the VERSION file at the chosen ref - type: string - required: true - dry_run: - description: Stop after release::prepare; needs only the snapshot store secrets - type: boolean - default: false - platform: - description: Platform to build - type: choice - options: [both, macos, windows] - default: both - build_only: - description: Build signed installers as Actions artifacts without uploading immutable release artifacts to R2 - type: boolean - default: false - push: - tags: ['v*'] - -permissions: - contents: read - -concurrency: - group: release-${{ github.event_name == 'workflow_dispatch' && format('v{0}', inputs.version) || github.ref_name }} - cancel-in-progress: false - -jobs: - platform: - name: Release ${{ matrix.platform }} - # Icon Composer sources require the Xcode toolchain on the newer macOS image. - runs-on: ${{ matrix.platform == 'macos' && 'macos-26' || 'windows-latest' }} - timeout-minutes: 120 - environment: release - strategy: - fail-fast: false - matrix: - platform: ${{ fromJSON(inputs.platform == 'macos' && '["macos"]' || inputs.platform == 'windows' && '["windows"]' || '["macos","windows"]') }} - defaults: - run: - shell: bash - env: - PLATFORM: ${{ matrix.platform }} - # prepare: a dry run stops after release::prepare; release: build and upload too. - STAGE: ${{ (github.event_name == 'workflow_dispatch' && inputs.dry_run == true) && 'prepare' || 'release' }} - REQUESTED_VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || github.ref_name }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - # Fails before any toolchain is installed, naming each missing secret. - - name: Require the release secrets - env: - CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - APPLE_SIGNING_IDENTITY: ${{ vars.APPLE_SIGNING_IDENTITY }} - APPLE_API_ISSUER: ${{ vars.APPLE_API_ISSUER }} - APPLE_API_KEY: ${{ vars.APPLE_API_KEY }} - APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }} - APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} - APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} - run: bash .github/scripts/release-secrets.sh check "$PLATFORM" "$STAGE" - # A version names one commit (ADR 0001); the run builds the ref it was - # dispatched from or the tagged commit, so the ask must match that ref. - - name: Require the requested version to equal VERSION - run: | - version="$(tr -d '[:space:]' < VERSION)" - requested="${REQUESTED_VERSION#v}" - if [[ "$requested" != "$version" ]]; then - echo "::error title=Version mismatch::Requested $requested, but VERSION at $GITHUB_SHA is $version. Dispatch from the commit that sets VERSION, or tag v$version on it." - exit 1 - fi - echo "Building $PLATFORM $version from $GITHUB_SHA" - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version-file: .nvmrc - cache: npm - cache-dependency-path: bazaarplusplus-installer/package-lock.json - - name: Compile the macOS Icon Composer asset - if: matrix.platform == 'macos' && env.STAGE == 'release' - run: | - xcodebuild -version - node bazaarplusplus-installer/scripts/release/compile-macos-icon.mjs - - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 - with: - global-json-file: bazaarplusplus-mod/global.json - cache: true - cache-dependency-path: bazaarplusplus-mod/**/packages.lock.json - - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 - with: - just-version: 1.58.0 - - name: Install the repository Rust toolchain and components - working-directory: bazaarplusplus-installer - run: | - rustc --version - rustup show active-toolchain - - run: npm install --global "$(node --print "require('./package.json').packageManager")" - - run: just release::check - # The product compiles against this platform's online Snapshot Lock entry; - # a null entry fails here, naming the snapshot to capture. The operator - # token reads the private store for this step only. - - name: Fetch the online Game Assembly Snapshot - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} - run: just mod::fetch "$PLATFORM" online - # prepare reuses the committed native recorder inputs when - # release/native-recorder-input.mjs finds them fresh and rebuilds them on - # this runner otherwise; a rebuild changes tracked files, which the next - # step turns into a named failure instead of an unpublishable dirty build. - - name: Prepare the Payload - run: | - just release::prepare "$PLATFORM" | tee "$RUNNER_TEMP/prepare.log" - grep -E '^Prepared ' "$RUNNER_TEMP/prepare.log" >> "$GITHUB_STEP_SUMMARY" || true - - name: Require prepare to leave tracked files unchanged - id: clean - run: | - changes="$(git status --porcelain --untracked-files=no)" - if [[ -n "$changes" ]]; then - printf '%s\n' "$changes" - git diff --binary > "$RUNNER_TEMP/native-recorder-inputs.patch" - echo "::error title=Native recorder inputs rebuilt::release::prepare rebuilt the $PLATFORM native recorder inputs and changed the tracked files above. Apply the native-recorder-inputs-$PLATFORM artifact with 'git apply', or run 'just release::prepare $PLATFORM' locally, commit, and rerun." - exit 1 - fi - - if: failure() && steps.clean.outcome == 'failure' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: native-recorder-inputs-${{ matrix.platform }} - path: ${{ runner.temp }}/native-recorder-inputs.patch - retention-days: 7 - - if: env.STAGE == 'prepare' - run: echo "Dry run stopped after release::prepare for $PLATFORM; nothing was signed or uploaded." >> "$GITHUB_STEP_SUMMARY" - # bundle.sh reads signing material as files from BPP_SIGNING_SECRETS_DIR, - # the same layout `node scripts/workspace.mjs run signing` stages locally. - - if: env.STAGE == 'release' - name: Stage the signing secrets - env: - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - APPLE_SIGNING_IDENTITY: ${{ vars.APPLE_SIGNING_IDENTITY }} - APPLE_API_ISSUER: ${{ vars.APPLE_API_ISSUER }} - APPLE_API_KEY: ${{ vars.APPLE_API_KEY }} - APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }} - run: | - bash .github/scripts/release-secrets.sh stage "$PLATFORM" "$RUNNER_TEMP/signing-secrets" - echo "BPP_SIGNING_SECRETS_DIR=$RUNNER_TEMP/signing-secrets" >> "$GITHUB_ENV" - # bundle.sh codesigns nested resources before Tauri bundles, so the - # Developer ID identity must already be in a keychain; Tauri then finds the - # same identity through APPLE_SIGNING_IDENTITY and notarizes with the API key. - - if: env.STAGE == 'release' && matrix.platform == 'macos' - name: Import the Developer ID certificate into a temporary keychain - env: - APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} - APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} - APPLE_SIGNING_IDENTITY: ${{ vars.APPLE_SIGNING_IDENTITY }} - run: | - keychain="$RUNNER_TEMP/release.keychain-db" - keychain_password="$(uuidgen)" - certificate="$RUNNER_TEMP/developer-id.p12" - printf '%s' "$APPLE_CERTIFICATE" | base64 --decode > "$certificate" - security create-keychain -p "$keychain_password" "$keychain" - security set-keychain-settings -lut 21600 "$keychain" - security unlock-keychain -p "$keychain_password" "$keychain" - security import "$certificate" -k "$keychain" -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign -T /usr/bin/security - rm -f "$certificate" - security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$keychain_password" "$keychain" > /dev/null - security list-keychains -d user -s "$keychain" $(security list-keychains -d user | tr -d '"') - if ! security find-identity -v -p codesigning "$keychain" | grep -Fq "$APPLE_SIGNING_IDENTITY"; then - echo "::error title=Signing identity not found::APPLE_CERTIFICATE does not contain the identity named by APPLE_SIGNING_IDENTITY; export the Developer ID Application certificate with its private key as .p12 and set both secrets." - security find-identity -v -p codesigning "$keychain" || true - exit 1 - fi - echo "BPP_RELEASE_KEYCHAIN=$keychain" >> "$GITHUB_ENV" - - if: env.STAGE == 'release' - name: Build and sign the installer - run: just release::build "$PLATFORM" - - if: env.STAGE == 'release' && inputs.build_only != true - name: Upload the immutable platform artifacts - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} - run: | - just release::upload "$PLATFORM" | tee "$RUNNER_TEMP/upload.log" - grep -E '^Uploaded ' "$RUNNER_TEMP/upload.log" >> "$GITHUB_STEP_SUMMARY" || true - # The installer and its artifact manifest, for inspection; R2 holds the - # copy promote reads. - - if: env.STAGE == 'release' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: installer-${{ matrix.platform }} - path: | - bazaarplusplus-installer/src-tauri/target/release-artifacts/${{ matrix.platform }}.json - bazaarplusplus-installer/src-tauri/target/release/bundle/nsis/* - bazaarplusplus-installer/src-tauri/target/aarch64-apple-darwin/release/bundle/dmg/* - bazaarplusplus-installer/src-tauri/target/aarch64-apple-darwin/release/bundle/macos/*.tar.gz* - if-no-files-found: error - retention-days: 14 - - if: always() - name: Remove the staged secrets and the temporary keychain - run: | - rm -rf "$RUNNER_TEMP/signing-secrets" - if [[ -n "${BPP_RELEASE_KEYCHAIN:-}" ]]; then - security delete-keychain "$BPP_RELEASE_KEYCHAIN" || true - fi diff --git a/.gitignore b/.gitignore index 5817df2..75b0755 100644 --- a/.gitignore +++ b/.gitignore @@ -1,168 +1,20 @@ -# Shared by every project. A project's own .gitignore holds only the outputs -# that project generates. +# 大巴扎助手 Android(bazaar-helper-android/) +.gradle/ +build/ +**/build/ +**/bin/ +**/obj/ +local.properties +.keystore/ +.local/ + +# Python helpers +__pycache__/ +*.pyc -# OS +# OS / editors .DS_Store Thumbs.db - -# Editors .idea/ .vscode/ -.vs/ -.fleet/ -.zed/ -.trae/ -*.iml -*.user -*.suo -*.swp -*.swo -*~ - -# Agent tooling (the shared .claude/settings.json is tracked) -.claude/* -!.claude/settings.json -.agents/ -.superpowers/ -.gstack/ -.worktrees/ - -# Dependencies and tool caches -node_modules/ -.venv/ -__pycache__/ -*.pyc -.pytest_cache/ -.ruff_cache/ -.wrangler/ -*.tsbuildinfo *.log - -# Build and coverage output -bin/ -obj/ -dist/ -coverage/ -.coverage -.coverage.* -*.egg-info/ - -# Secrets and machine-local config -.env -.env.* -!.env.example -.dev.vars -.dev.vars.* -signing-secrets/ -.bpp-local.json - -# Android port build output and local artifacts - -# .NET build output -bin/ -obj/ -*.pdb -*.user - -# Node / front-end -node_modules/ -dist/ -target/ - -# Android and native binaries -*.apk -*.aab -*.so -*.dylib -*.a -*.jar - -# Compiled/managed binaries. Vendored BepInEx payloads under -# src-tauri/resources/SourceForBuild are restored from BepInEx.zip at build time, -# so only their configuration and licence files are tracked. -*.dll -*.exe -*.pyd - -# Vendored BepInEx core (DLLs and generated XML docs) is a packaging input, -# never source; keep only the directory .gitkeep files above it. -bazaarplusplus-installer/src-tauri/resources/SourceForBuild/*/BepInEx/core/ -bazaarplusplus-installer/src-tauri/resources/SourceForBuild/*/BepInEx/plugins/*.dll -bazaarplusplus-installer/src-tauri/resources/SourceForBuild/*/TheBazaar.app/Contents/Plugins/*.bundle/Contents/MacOS/ - -# Packaged deliverables and captured payload corpora -*.zip -*.tar -*.tar.gz -*.tgz -*.7z -*.nupkg -*.mpack -*.mpack.gz -*.mpack.* - -# Signing material — never commit -*.keystore -*.jks -*.p12 -*.pem -*.pfx - -# Secrets -.env -.env.* -!.env.example -*.secret -secrets.json -.bpp-local.json - -# Reverse-engineering output and device dumps -apk_extracted/ -android-managed/ -android-managed-bepinex/ -android-test/ -dumped/ -dumped2/ -dumped3/ -dumped*/ -interop/ -interop-unity/ -interop145/ -ilstool/bin/ -ilstool/obj/ -tools/Il2CppDumper/ -tools/Il2CppDumper-v39/ -tools/il2cppinterop/ -tools/platform-tools/ -tools/android-build/ -tools/unitylibs/ -tools/gh/ -tools/dotnet10/ -tools/launcher/ -tools/apktool/ -tools/src/ -unitylibs/ - -# Test-device evidence: screenshots, UI dumps, logs -shots/ -account-test-*.png -account-test-*.log -bpp-*.png -bpp-*.log -ui*.xml -tmp_ui*.xml -*.tombstone -tombstone_* -logcat*.log -*.log - -# Scratch directories -par/ -continuation-backup/ -hero-filter-validation/ -lock-backup/ -repo-publish/ -bpp-analyzer-fix/ - - - diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 0a48aa8..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "upstream/BazaarPlusPlus"] - path = upstream/BazaarPlusPlus - url = https://github.com/BazaarPlusPlus/BazaarPlusPlus.git diff --git a/.nvmrc b/.nvmrc deleted file mode 100644 index df6ae33..0000000 --- a/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -24.21.0 diff --git a/.prettierrc.json b/.prettierrc.json deleted file mode 100644 index 32ebab4..0000000 --- a/.prettierrc.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "none" -} diff --git a/AGENTS.md b/AGENTS.md index e6b7da0..5de2c45 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,78 +1,12 @@ -# AGENTS.md - -BazaarPlusPlus monorepo. The mod and the installer ship as one Product Release; the server, analyzer, and site are separate deployments. Each project keeps its own toolchain, lockfiles, `AGENTS.md`, and `CONTEXT.md` glossary. Work inside the project the change touches and follow its `AGENTS.md`; this file holds only what spans projects. - -| The change touches | Project | -|---|---| -| In-game features, Harmony patches, uploads from the game | `bazaarplusplus-mod/` | -| Install, repair, update, local history, the OBS overlay | `bazaarplusplus-installer/` | -| Bundle ingest, Ghost discovery, BazaarDB delivery | `bazaarplusplus-server/` | -| Hero and build snapshots computed from Bundles | `bazaarplusplus-analyzer/` | -| bazaarplusplus.com, Hero Analysis, the download page | `bazaarplusplus-site/` | -| Product version, Payload Inventory, release pipeline | root `VERSION`, `release.mjs`, `release/`; read `docs/release.md` | -| BazaarHelper Android app (launch, record, sync, its own CI) | `bazaar-helper-android/` | - -Cross-project terms (Product Release, Payload, Release Manifest, Bundle) are defined in `CONTEXT.md`. - -## Contracts - -A contract change lands in one pull request together with every consumer it breaks. Each row names the owning source; consumers read it, they do not restate it. - -| Contract | Owner | Consumers | -|---|---|---| -| Bundle V6 binary and manifest | `bazaarplusplus-server/contracts/v6/`, shared goldens in `fixtures/` beneath it | mod writes and reads Ghost Bundles, server ingests, analyzer reads | -| Run segment inside a Bundle V6 | `bazaarplusplus-mod/docs/contracts/run-payload-v6.md`, shared golden `bazaarplusplus-mod/tests/BundleV6Codec.Tests/fixtures/run-payload-v6.fixture.b64` | server stores it opaque, analyzer decodes it | -| Mod API HTTP routes | `bazaarplusplus-server/docs/api-reference.md` | mod | -| Hero and build snapshots | `bazaarplusplus-analyzer/contracts/v6/`, shared goldens in `fixtures/` beneath it and the hero alias table `hero-aliases.json`, plus `bazaarplusplus-analyzer/docs/specs/consumer-data-contract.md` | site Hero Analysis, mod build recommendations, installer History (hero aliases) | -| Seal eligibility | `BundleQueueStore.SealEligibleRunCondition` in `bazaarplusplus-mod/src/BazaarPlusPlus.Storage/`, shared cases `bazaarplusplus-mod/tests/BundleQueueSqliteStore.Tests/fixtures/bundle-seal-eligibility.json` | mod replay maintenance, installer History cleanup (`PROTECTED_RUN_PREDICATE`) | -| Payload Inventory | `release/payload.json` | mod MSBuild, installer packaging and cleanup | -| Local history database schema (`user_version`), Data Root name, and replay payload retention | `RunLogSchema.LocalDatabaseSchemaVersion`, `PathConstants.DataRootDirectoryName`, and `ReplayPayloadRetentionPolicy`, mirrored as `historyDatabaseUserVersion`, `dataRootDirectoryName`, and `replayPayloadRetained*` in `bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json`; `release::check` gates the pair (`release/history-database.mjs`): same Data Root on both sides, mod schema newest the installer supports; shared schema file `bazaarplusplus-mod/src/BazaarPlusPlus.Storage/history-database-v6.schema.sql` | installer History, Reset, cleanup, and overlay reads (`bazaarplusplus-installer/src-tauri/history-database-compatibility.json`, whose `dataRootDirectoryName` a test pins to `BAZAAR_DATA_DIRECTORY`); the V5 import reads the installed copy's retention | -| Release Manifest and Platform Release Manifest | `release/manifest.mjs`, shared fixtures `release/fixtures/latest.json` and `release/fixtures/latest/` | site download page, installer updater, mod update check | - -Root `release/` owns Product Release modules and tests. Imports run one way: installer scripts may import release modules, never the reverse. - -Run `just release::sync` after editing `VERSION` or `release/payload.json`; it regenerates the projections the builds validate against. - -## Verification - -`just` lists every recipe. Gate one project with `just ::check` and `just ::test`; gate a contract change with the check and test recipes of the owner and every consumer. `just check` and `just test` cover the whole repo; `just release::test` gates the root release modules. `just fmt` formats everything. Goldens fail on any difference in every project; `BPP_UPDATE_GOLDENS=1` rewrites them (analyzer: `just analyzer::golden`), and every rewritten golden must be an intended diff in the PR. Scope and prerequisites: `docs/development.md`. - -## Commits and pull requests - -- Commit only when the user asks, after reviewing your own diff: done when you can name every file in the commit and why it is there. Revert formatter-only edits to files outside your change. -- Commit messages and PR titles use Conventional Commits, `(): `. The scope is the project or feature area; root tooling uses `dev` or `release`. -- End every PR body with a `Release Notes:` line, one blank line, then one bullet per user-visible change starting with Added, Fixed, or Improved. Use `- N/A` when nothing is user-visible. -- `master` is protected. The wrap-up flow is: commit on a branch, `gh pr create`, merge, delete merged branches. - -## Changing code - -- Run an independent red-team review of a large refactor or design plan before implementing. Keep it review-only, landing `file:line` evidence rather than patches, incorporate the findings, and proceed within the user's authorized scope without another confirmation. -- A replacement ships only the new version: done when the old implementation is deleted and the project's check and test recipes pass. -- Scope a delete or change to its named target plus the members that fed only that target. Unrelated cleanup goes in its own change. - -## Documentation - -- Each fact has one owner. A term goes in the project's `CONTEXT.md` (in the root one when several projects use it). Current behavior goes in `docs/*.md`. A decision goes in `docs/adr/`. Plans, feature requests, and bugs go in GitHub issues (see Agent skills). -- Config files, scripts, and `--help` output own every value they state. A doc carries only the convention, the reason, or the gotcha they cannot state. -- Name domain concepts with the glossary's terms; a real naming gap gets a `CONTEXT.md` entry in the same change. When your output contradicts an ADR, name the ADR and say why it is worth reopening. -- In committed docs and comments, cite code by path plus symbol name; line numbers drift. `file:line` is fine in session evidence and reviews. -- ADRs are numbered `NNNN-slug.md` per project, in sequence. A number is never reused or renumbered. A replaced ADR gets a `superseded-by:` frontmatter pointer; a retired one is deleted and lives on in git history. -- Root `README.md`, `docs/development.md`, and `docs/release.md` are in Chinese. `README_en.md` mirrors `README.md` section for section; edit both in one change. - -## Instructions - -Add an instruction to an `AGENTS.md` only when it is non-obvious, keeps coming up, and is actionable; put it in the narrowest `AGENTS.md` it applies to. During ordinary work, propose it under a **Suggested AGENTS.md additions** heading in the wrap-up. Edit directly when the user asks or an existing instruction is wrong. - -## Agent skills - -### Issue tracker - -GitHub Issues on this monorepo through `gh`; issues only, not PRs. Read `docs/agents/issue-tracker.md` before you create, read, or triage an issue. - -### Triage labels - -Each of the five canonical triage roles uses its own name as its label. Read `docs/agents/triage-labels.md` before applying one; most do not exist on the repo yet. - -### Domain docs - -`docs/agents/domain.md` names which `CONTEXT.md` and `docs/adr/` files to read before you explore an area. +# 仓库约定 + +本仓库只发布 **大巴扎助手 Android**(`bazaar-helper-android/`,包名 `com.bazzarhelper.android`)。 +上游 BazaarPlusPlus Android 移植的源码已移除,历史仍在 git 记录里;需要参考时去 +[TAP-APIA/bazaarplusplus-android](https://github.com/TAP-APIA/bazaarplusplus-android)。 + +- 说明与使用文档:`README.md`(产品)、`bazaar-helper-android/README.md`(构建、测试、数据边界)。 +- 构建:`cd bazaar-helper-android && python3 tools/build.py --interop .local/game-interop`;`.local/` 是忽略目录,放游戏 interop 等编译输入。 +- 验证:`python3 tools/check-apk.py build/BazaarHelper-*.apk`,真机测试见 `bazaar-helper-android/README.md` 的 `tools/test-device.py`。 +- CI:`.github/workflows/bazaar-helper-android.yml`,签名与 interop 走仓库 secrets,不入库也不进 APK。 +- `master` 受保护:改动走分支 + `gh pr create` + merge,合并后删除分支。提交信息用 Conventional Commits,scope 用 `bazaar-helper` 或 `docs`。 +- 不提交 `.local/`、`build/`、`.keystore/`、游戏程序集或任何凭据。 diff --git a/CONTEXT.md b/CONTEXT.md deleted file mode 100644 index 6477164..0000000 --- a/CONTEXT.md +++ /dev/null @@ -1,64 +0,0 @@ -# BazaarPlusPlus - -Terms used by more than one project. A project glossary may narrow one of these terms for its own use; it links here for the definition. - -## Product release - -**Product Release**: -The mod, the installer, and the published release record for one product version. One product version names one git commit; each platform ships it at most once and may skip it. The product version says nothing about a database schema, a native ABI, or the version a user has installed. - -**Payload**: -The files the installer carries and installs into the game directory. Each file's ownership decides which paths install, repair, and uninstall may change. - -**Payload Inventory**: -The shared facts about Payload files: current files, platform scope, ownership, and retired files. User data and third-party plugins are outside it. - -**Platform Release Manifest**: -One platform's newest promoted release: its version, updater package, actual installer download URL, and recorded Mainland Mirror address (`latest/.json`). Platforms may be at different versions. - -**Release Manifest**: -The newest Product Release that every declared platform promoted at the same version and commit, in the same shape for all platforms (`latest.json`). Clients built before the per-platform endpoint read only this file, so it never runs ahead of any platform. - -**Release Promotion**: -Publishing one platform's Platform Release Manifest once its artifacts are in place and its Mainland Mirror is recorded or explicitly waived; the Release Manifest advances when every platform names the same release. Repeating the promotion of the same release leaves the existing artifacts unchanged. - -**Mainland Mirror**: -A manually uploaded share page of one platform's installer for mainland-China networks. Its address is an explicit operator input, checked against the uploaded installer and recorded per platform before that platform's Release Promotion, then published in its Platform Release Manifest; consumers read it and never derive it. It is a manual download fallback, never a second release source or an updater endpoint. - -## Game assemblies - -**Game Assembly Snapshot** (游戏程序集快照): -One captured copy of the game's `Managed/` directory, identified by the game version string Unity writes in `globalgamemanagers` beside it (`1.0.12575-staging-macos-arm64-fecb8f8e`: build number, channel token, platform, game commit) and verified by the sha256 of its DLL records. It is captured from a mounted Steam install for one platform and channel (`macos` or `windows` × `online`, `staging`, `ptr`, the Steam branches `public`, `staging`, `public_test_realm`), stored content-addressed in the private `bazaarplusplus-game-libs` bucket, and unpacked under `bazaarplusplus-mod/game-libs/`. It is a build and test input, never part of the Payload; the Steam buildid and branch are its source record, not its identity. The snapshot channel keeps staging and ptr apart, which the mod's runtime Game Build Channel folds into `Ptr`. -_Avoid_: Steam branch copy, game-libs archive - -**Snapshot Lock** (快照锁): -`bazaarplusplus-mod/build/game-libs.lock.json`: the committed binding of the mod source to one Game Assembly Snapshot per platform and channel, six keys that stay `null` until captured. After an explicit override, `ManagedPath` resolves only from it: the fetched snapshot, or the local Steam install whose game version and sha256 match the entry. Each platform's product compiles against its `online` entry; `staging` and `ptr` entries feed compatibility builds and tests. It changes only through a pull request; `release/game-libs.mjs` owns its schema and the mod recipes capture, publish, fetch, and check it. -_Avoid_: game-libs manifest, Steam buildid pin - -## Credentials - -**Operator Token** (操作员 token): -The one Cloudflare API token a maintainer holds for every R2 bucket (`bppinstaller`, `bazaarplusplus-game-libs`, both metrics buckets) and for Wrangler: `config.ini` `[cloudflare] CLOUDFLARE_API_TOKEN` locally, the `release` environment secret `CLOUDFLARE_API_TOKEN` on GitHub. Credentials are kept one per trust domain, not one per bucket; the other two domains are the read-only CI token (`BPP_GAME_LIBS_TOKEN`, the game-libs bucket only) and the site deploy token. R2's S3 pair is a view of a token, Access Key ID its id and Secret Access Key the SHA-256 of its value, so `release/r2-store.mjs` and the analyzer's `object_store.py` derive it and nothing stores it. `release/github-secrets.json` maps every GitHub name to its scope and local source. -_Avoid_: release R2 keys, per-bucket key pair - -## Local data - -**Data Root** (数据根目录): -The folder in the game directory where the mod keeps its local database, screenshots, and replays. The current name is `BazaarPlusPlusV6`; the mod's `PathConstants.DataRootDirectoryName` and the installer's `BAZAAR_DATA_DIRECTORY` must agree. Unrelated to the analyzer's `BPP_DATA_ROOT`. - -**Legacy Root** (旧数据根目录): -A Data Root an earlier major version wrote (`BazaarPlusPlus/`, `BazaarPlusPlusV4/`, `BazaarPlusPlusV5/`), owned by the user. The mod never reads it; the installer measures it, imports V5 once, and deletes one only on the user's confirmation. The installer's own `BazaarPlusPlusV4` settings folder is not one. - -**History-Only Run** (仅历史对局): -A run in the current Data Root that appears only in local history: never sealed into a Bundle, never uploaded, and never protected from cleanup as a seal candidate. Every run imported from a Legacy Root is one. Unlike a **Run**, it is never carried inside a Bundle. - -## Data pipeline - -**Bundle**: -The immutable unit of upload, storage, and delivery: exactly one Run and zero or one Screenshot. The mod writes it, the server stores and delivers it, the analyzer reads it. - -**Run**: -The immutable facts, battles, card state, and replay inputs of one completed game run, carried inside a Bundle. It excludes the Screenshot. - -**Ghost Battle**: -A PvP battle in which a player's uploaded build fought inside another player's run. The server serves it as a query projection of Bundle manifests; the mod imports it into local history. diff --git a/JUSTFILE b/JUSTFILE deleted file mode 100644 index ffec693..0000000 --- a/JUSTFILE +++ /dev/null @@ -1,73 +0,0 @@ -set shell := ["bash", "-euo", "pipefail", "-c"] -set positional-arguments - -# Each project owns a module; its recipes run in that project's directory. -# Every module file repeats the shell and positional-arguments settings, which -# modules do not inherit. -mod mod 'bazaarplusplus-mod/mod.just' -mod installer 'bazaarplusplus-installer/installer.just' -mod site 'bazaarplusplus-site/site.just' -mod server 'bazaarplusplus-server/server.just' -mod analyzer 'bazaarplusplus-analyzer/analyzer.just' -mod release 'release/release.just' - -# Root tooling owns its dependencies and formatting configuration. -root_js := "package.json package-lock.json .prettierrc.json release.mjs 'release/**/*.{mjs,ts,json}' 'scripts/**/*.mjs'" - -# `just --fmt` does not descend into modules, so format each file explicitly. -just_files := "JUSTFILE bazaarplusplus-mod/mod.just bazaarplusplus-installer/installer.just bazaarplusplus-site/site.just bazaarplusplus-server/server.just bazaarplusplus-analyzer/analyzer.just release/release.just" - -# List commands without building or publishing anything. -default: - @{{ quote(just_executable()) }} --list --list-submodules - -# Check all projects without signing, publishing, or deploying to the game. -[group('workspace')] -check: commands-check release::check mod::check installer::check site::check server::check analyzer::check - -# Run all project tests without publishing data or deploying to the game. -[group('workspace')] -test: commands-check release::test mod::test installer::test site::test server::test analyzer::test - -# Format every project in place, then re-project release files. -[group('workspace')] -fmt: && mod::fmt installer::fmt site::fmt server::fmt analyzer::fmt release::sync - for file in {{ just_files }}; do {{ quote(just_executable()) }} --justfile "$file" --fmt; done - npm exec -- prettier --config .prettierrc.json --write {{ root_js }} - -# Install the workspace Git hooks (requires root npm dependencies). -[group('workspace')] -hooks-install: - node scripts/install-hooks.mjs - -# Connect shared local configuration, install locked dependencies and Git hooks. -[group('workspace')] -setup *args: - node scripts/workspace.mjs setup "$@" - -# Inventory local prerequisites without printing secret values or publishing. -[group('workspace')] -doctor: - node scripts/workspace.mjs doctor - -# Run an explicit command with one configuration profile, from the repo root. -[group('workspace')] -with-config profile +args: - node scripts/workspace.mjs run "$1" -- "${@:2}" - -# List, by name only, which GitHub secrets and variables exist and which have a local value. -[group('workspace')] -secrets-check *args: - node scripts/workspace.mjs secrets check "$@" - -# Copy every locally present GitHub secret and variable through gh; [--dependabot] [--prune]. -[group('workspace')] -secrets-sync *args: - node scripts/workspace.mjs secrets push "$@" - -# Check formatting and exercise command routing with isolated tool stubs. -[group('workspace')] -commands-check: - for file in {{ just_files }}; do {{ quote(just_executable()) }} --justfile "$file" --fmt --check; done - npm exec -- prettier --config .prettierrc.json --check {{ root_js }} - node --test scripts/just.test.mjs scripts/workspace.test.mjs diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index 6dc4d18..0000000 --- a/SECURITY.md +++ /dev/null @@ -1,32 +0,0 @@ -# Security Policy - -## Supported versions - -Only the latest Product Release gets security fixes. The installer updates itself, and the mod -ships with it, so a fix reaches players through the next release. - -## Reporting a vulnerability - -Report privately through GitHub: **Security → Report a vulnerability** on this repository -([direct link](https://github.com/BazaarPlusPlus/BazaarPlusPlus/security/advisories/new)). -Do not open a public issue, pull request, or discussion for a vulnerability. - -Include the affected project (mod, installer, server, analyzer, or site), the version or commit, -steps to reproduce, and the impact you expect. We aim to acknowledge a report within 7 days. - -In scope: - -- The mod and the desktop installer, including install, repair, update, and the updater signature. -- The upload backend at `mod-api-v6.bazaarplusplus.com` and the data it stores or serves. -- bazaarplusplus.com and its download page. - -Out of scope: The Bazaar itself, BepInEx, and other third-party components, which should be -reported to their own maintainers. - ---- - -# 安全策略 - -只有最新的 Product Release 会得到安全修复。请通过本仓库的 **Security → Report a vulnerability** -私下报告漏洞,不要公开提 issue 或 PR。报告请写明涉及的项目(mod、installer、server、analyzer 或 -site)、版本或提交、复现步骤与预期影响。我们会在 7 天内确认收到。 diff --git a/VERSION b/VERSION deleted file mode 100644 index 09b254e..0000000 --- a/VERSION +++ /dev/null @@ -1 +0,0 @@ -6.0.0 diff --git a/android-port/ACCEPTANCE-ROUND1-20261024.md b/android-port/ACCEPTANCE-ROUND1-20261024.md deleted file mode 100644 index 8280e2e..0000000 --- a/android-port/ACCEPTANCE-ROUND1-20261024.md +++ /dev/null @@ -1,532 +0,0 @@ -# BazaarPlusPlus 安卓移植 — 第 1 轮验收记录 - -> 生成:2026-10-24 00:05 (+08:00) -> 依据:真机冷启动实测(vivo PA2573 / `192.168.0.14:37699` / `com.bepinex.android:game`) -> 本轮性质:**编译阻断修复 + 三面板基线验收**;十胜阵容多源修复由子代理进行中 - ---- - -## 一、本轮结论速览 - -| 验收项 | 结果 | 客观证据 | -|---|---|---| -| 编译 | ✅ **0 error**(95 warning 均为既有 IDE0005) | `BazaarPlusPlus.dll` 4,228,608 B @ 23:45:12 | -| 冷启动 | ✅ 成功,`plugin.initialization.succeeded` | 进程存活 >10 分钟 | -| 崩溃 | ✅ **零致命信号** | `grep -E 'Fatal signal\|SIGSEGV\|SIGABRT'` = 0 | -| 图鉴面板 | ✅ 打开,**124 张卡立绘全部正常** | 近白占比 **48.91% → 0.80%** | -| 卡牌检视窗 | ✅ 打开,**右侧文字与词条气泡不再被遮挡** | `_v1_inspect2.png` / `_v1_run.png` | -| 配装面板 | ✅ 打开,中文 UI + 4 排棋盘 + 赞助商 | ⚠️ 阵容库仍为 **3 套**(待多源修复) | -| 历史面板 | ✅ 打开,**有真实本地数据**,双棋盘卡牌正常 | `_v1_history.png` | -| SQLite | ✅ 可用 | `plugin.android.sqlite.loaded` 指向 APK `lib/arm64/libe_sqlite3.so` | - ---- - -## 二、阻断项修复(本轮) - -**错误**:`NativeInspectionPresentation.cs(142,13): error CS0103: 名称"ConcealMobileTrayBackdrops"不存在` - -**修复**(子代理 A,方案 A 补实现): -在 `#if BPP_ANDROID` 区、`ConcealMobileDecoration` 之后新增: - -- `ConcealMobileTrayBackdrops()`:`RootCanvasComponent.GetComponentsInChildren(true)` 索引遍历;仅处理「自身 GameObject 名含 `tray` / `backdrop`(大小写不敏感)+ `enabled` + 是 `Image`/`RawImage`」的图形; -- 用 `graphic.transform.IsChildOf(controller.TooltipRectTransform)` **排除描述本体**,避免误禁; -- 命中后走既有 `ConcealMobileDecoration(graphic)` 登记到 `_mobileDecoration`,**`ReleaseNative()` 的还原链路未改动**; -- 辅助静态方法 `IsMobileTrayBackdropName`。 - -设计取舍:名称不匹配时为**无害 no-op**,不会误禁 card/tooltip/文本,也不会破坏还原。 - ---- - -## 三、图鉴白块:本轮实测结论(与上一轮交接文档冲突,以本条为准) - -### 3.1 上一轮结论(错误,已推翻) - -> 「卡牌立绘纹理加载失败,露出白底板」+ 排查方向「Addressables catalog / artKey 大小写 / 纹理压缩」 - -### 3.2 本轮实测(冷启动 + 23:45 版 modpack) - -**白块完全不复现**:124 张卡牌立绘、费用徽章、边框、宝石全部正常。 - -客观量化(`LockBits` 逐像素,采样步长 3,区域 x∈[0, 64.5%] y∈[3%, 97%]): - -| 状态 | 近白占比(RGB ≥ 240) | -|---|---| -| 修复前 `_now.png`(旧进程久运行态) | **48.91%** | -| 本轮 `_v1_cards.png`(冷启动) | **0.80%** | - -### 3.3 由此得出的新判断 - -1. **不是资源管线问题**:同一台平板、同一构建,**历史面板的原生棋盘卡牌**(`_v1_history.png`,巧克力/金蛋/辣椒/手套/菜刀/烤串/冰淇淋)与**检视窗放大卡**(「刀具组」「烤肉叉」)立绘全正常。catalog / material / shader / 纹理压缩**全部健康**。 -2. **白块是「久运行 + 反复开关面板」后的状态退化**,冷启动即恢复。最可能是 `CollectionCardArtCache` 的 LRU 淘汰(capacity 256)与 `_failedKeys` 永久黑名单叠加:某次加载失败后该 artKey 被永久标记为失败且**不再重试**,滚动回访时直接返回 `null` → 白底板。 -3. `collection_panel.card_art.degraded` **全程为 0**(8 份历史日志 + 设备当前日志交叉验证),证明**没有走进任何 degraded 上报分支**——即 `LoadArtFromCache` 的 4 条静默 `return` 之一被命中(`_cardData == null` / `ArtKey` 空或 `"Invalid"` / `cardMaterial == null` / `material == null`),这 4 条**都不写日志**。 - -### 3.4 仍待落地的加固(下一轮) - -- 给 4 条静默路径补 `ReportDegraded`(各配独立 `reason_code`),让下次真机运行**自证**命中哪条; -- `_failedKeys` 改为**带 TTL / 可重试**,避免一次失败永久白; -- 子代理 B 指出 `_cardImage` 实为 **`RawImage`**(`dump.cs:105859`),而 patch 只赋 `material`、未赋 `texture`,且绕过原生 `UpdateCardImageMaterial`(那里才绑纹理/premium/费用徽章);建议补 `instance._cardImage.texture = assetData.cardMaterial.mainTexture` 并在 `ClearCachedMaterialAssignment` 同步清 `texture`(防池化串图)。**该项尚未应用**。 - ---- - -## 四、检视窗遮罩:已修复 - -上一轮反馈「图鉴点开物品右侧有大遮罩挡住文字」。 - -本轮 `_v1_inspect2.png`(「烤肉叉」)与 `_v1_run.png`(「刀具组」)实测: - -- 效果描述「造成 3 伤害 / 己方物品 +3」「造成 20 伤害 / 己方物品获得 5」**完整可读**; -- 词条气泡「⚡充能 · 立即推进一件物品的冷却时间」**完整显示**; -- 底部稀有度选择器「青铜 / 白银 / 黄金 / 钻石 / 重置」正常; -- 类型标签「小型 武器 工具」「中型 武器 工具」正常。 - -即 `ConcealMobileTrayBackdrops` + 排序层级(`InspectionContent` 3002 / `InspectionControls` 3001)组合生效。 - ---- - -## 五、十胜阵容:真实根因(推翻上一轮交接文档) - -### 5.1 上一轮说法(错误) - -> 「`https://cdn.bazaarplusplus.com/metrics/v6/builds/latest.json` 返回 404,回退内嵌 seed(3 条)」 - -### 5.2 实测(子代理 C,curl + 真机日志) - -| URL | 状态 | 大小 | -|---|---|---| -| **`https://bpp-metrics-v6.bazaarplusplus.com/builds/latest.json`**(代码真正在用) | **200** | 2,117 B | -| `https://cdn.bazaarplusplus.com/…`(交接文档写的主机) | 404 | 28,088 B(整站不存在) | -| `https://bpp-metrics.bazaarplusplus.com/builds/latest.json`(legacy) | **200** | **1,040,585 B** | - -**真实原因**:V6 metrics 上游 run ingest 空转 —— `heroes/latest.json` 在 10-15..10-21 窗口、8 英雄 × 2 段位 `runs.completed` **全为 0**;`builds/latest.json` 只有 **3 套且仅 Dooley**。而 legacy bucket 同为 `schema_version=2` 线格式,**5,689 套 / 8 英雄 / 1,123 卡**,卡 GUID 空间与 v6 完全兼容。 - -**「3 套」的来源**:是 **v6 远程缓存**,不是内嵌 seed。内嵌 seed(`Data/BuildRecommendations/builds.json`)实际只有 **1 套且用假 GUID**(`11111111-…` ~ `55555555-…`)。 - -**「0 / 0」的来源**:不是语料不匹配,而是 **`LiveBuildPanel.Open()` 开头 `_candidateState.Clear()`**,候选只能靠手动点卡加入 → `TenWinBuildCorpus.FindRecommendations` 在空选择时直接返回空数组。 - -### 5.3 本轮已下载到的语料(供 seed 替换与校验) - -`D:\thebarzaar\artifacts\tenwin-probe\legacy-builds.json`(1,040,585 B),实测结构: - -``` -schema_version=2 kind=ten_win_builds -generated_at=2026-10-23T08:18:43Z -window: 2026-09-29 .. 2026-10-05 -cards=1123 enchantments=14 -Dooley=746 Jules=711 Karnok=595 Mak=743 -Pygmalien=834 Stelle=517 TheDragons=695 Vanessa=848 -total builds = 5689 -``` - -### 5.4 修复方案(子代理 D 进行中) - -1. 新增 `FallbackRemoteCatalogSource`:按序尝试多个 `IRemoteCatalogSource`,返回**第一个密度足够**(≥64 套且 ≥4 英雄)的文档;全疏则取最密;全失败抛首个异常; -2. `TenWinBuildCatalogFactory`:`RemoteUrl` → `RemoteUrls[]`(v6 优先,legacy 兜底),HttpClient 超时 10s → **30s**; -3. `LiveBuildPanel.Open()` 后用 `SeedCandidatesFromBoard()` 以**场上物品预置候选**,消除「点开就是 0/0」的空态观感; -4. 同步修 `tests/LiveBuildRecommendations.Tests` 的 URL 断言(数组化)。 - ---- - -## 六、日志证据摘要(设备 `LogOutput.log`,23:56 / 87,420 B) - -``` -[Info ][Plugin] event=plugin.android.sqlite.loaded native_path="…/lib/arm64/libe_sqlite3.so" -[Info ][Plugin] event=plugin.android.patch_capabilities unsupported_features=voice_callbacks,collection_variant_controls,multi_tier_passive_tooltips,upgrade_value_tuples,package_merchant_summary -[Info ][Plugin] event=plugin.initialization.succeeded plugin_version=6.0.0 game_build=1.0.12825-production-android-d9601ded build_channel=online -[Info ][CollectionPanel] event=collection_panel.catalog.ready accepted_count=1850 rejected_count=1525 source_template_count=3375 -[Info ][CollectionPanel] event=collection_panel.inspection.opened -[Info ][CollectionPanel] event=collection_panel.inspection.variants.ready tiers=4 enchantments=0 -[Info ][LiveBuildPanel] event=live_build_panel.corpus.ready source=cache build_count=3 -``` - -- `[Error]` 共 9 条,全部是已知 Il2CppInterop 无害噪声: - - 1 条 `Sequence contains more than one element`(`GenericMethod_GetMethod_Unity6_Hook.FindTargetMethod`,框架级 hook 未命中) - - 8 条 `Assembly BazaarPlusPlus.dll is not registered in il2cpp`(`ClassInjector` 注册期间的正常噪声,随后紧跟 `Registered mono type …`) -- `card_art.degraded` = **0**;`card.bind_degraded` = **0**;`patches.degraded` = **0** -- `has unsupported` 61 处(managed-only 方法签名,`ClassInjector` 按设计跳过方法、仍注册类型)—— `CollectionPanelOwnedMarker` **已确认注册成功** - ---- - -## 七、稳定性 - -``` -u0_a269 21422 … com.bepinex.android -u0_a269 21975 … com.bepinex.android:game ← 存活 >10 分钟 -``` - -`logcat -d | grep -E 'Fatal signal|SIGSEGV|SIGABRT|AndroidRuntime.*FATAL'` → **无输出** - ---- - -## 八、十胜阵容:已达成 `build_count = 5689` - -### 8.1 最终验收证据(真机,00:17 冷启动) - -``` -[Warning][LiveBuildPanel] event=live_build_panel.corpus.degraded - reason_code=stale_cache source=cache build_count=3 expired=true - cache_path=/data/user/0/com.bepinex.android/app_bepinex_runtime/com.tempogames.thebazaar/BazaarPlusPlusV6/builds.json -[Info ][LiveBuildPanel] event=live_build_panel.corpus.recovered - source=remote build_count=5689 -``` - -面板实测(`_v3_builds_5689.png`):**「阵容库 更新于 2 周前 · 5,689 套阵容」**(此前长期为「3 套阵容」)。 - -即:缓存判过期 → 后台刷新 → `FallbackRemoteCatalogSource` 跳过稀疏的 v6(3 套/1 英雄)→ 采用 legacy(5,689 套/8 英雄)→ 落盘并切换。 - -### 8.2 三轮修复的分工与内容 - -| 轮次 | 子代理 | 内容 | -|---|---|---| -| 1 | 诊断 | 推翻「远程 404」误判:真实端点 `bpp-metrics-v6.bazaarplusplus.com` 返回 200 但内容仅 3 套/1 英雄;legacy `bpp-metrics.bazaarplusplus.com` 有 5,689 套/8 英雄且线格式兼容 | -| 2 | 实现 | 新增 `FallbackRemoteCatalogSource`(密度门槛 64 套 / 4 英雄);`RemoteUrl` → `RemoteUrls[]`;超时 10s → 30s;`SeedCandidatesFromBoard()` 用 `TemplateIdsOf` 去重;Android 30s 空快照重试 | -| 3 | 加固 | `CacheDuration` 20h → **1h**(关键开关);`refresh.ignored` 观测事件;重试分支补 `if (!_candidateState.HasCandidates) SeedCandidatesFromBoard();` | - -**根因链**(完整):`CacheDuration=20h` 且判陈旧用的是**缓存文件写入时间**而非语料 `generated_at` → 文件 10-23 20:08 写入,未过期 → 永不刷新 → 一直服务 3 套 v6 旧文档。降到 1h 后立即过期,刷新链路才第一次真正跑通。 - -### 8.3 构建与单测 - -- 规范构建:**0 error / 95 warning**,产物 **4,231,680 B @ 2026-10-24 00:14:04**,SHA256 `5EF415A8D809AD9DF751F9AA6DEBB4C128F3E6DC64A6852DDBDDD1D53FA4952B` - - 已核对:dist 内产物与设备双写产物**均为这一版** -- 单测 `LiveBuildRecommendations.Tests`:**24/24 通过**,唯一失败用例 `TestCorpusTooltipsUseCanonicalPresentation` 是本机无桌面 `GameAssembly.dll` 导致 `TypeInitializationException`(`UnityEngine.Color` 静态构造需原生域),与本次改动无关,未为其改生产代码 - -### 8.4 ✅ 已定位并修复方向明确:`SkipCanvas/ClickArea` 僵尸拦截层(Round 2 突破) - -Round 2 用一次性 raycast 审计探针(`GameInterop/UiRaycastAudit.cs`,`overlay_panels.ui_raycast.audit|probe`)在真机打印出真凶: - -``` -canvas=SkipCanvas path="Trailer Component/SkipCanvas" order=0 mode=0 override=false - root=SkipCanvas active=true raycaster=on - full_screen_blockers=1 blockers=ClickArea|0|0|raycast -``` - -`blockers` 格式为 `name|depth|alpha%|raycast` ⇒ `ClickArea`:**alpha = 0%(完全不可见)**、**全屏**、**raycastTarget = true**。 - -`probe` 命中链(几何 + EventSystem 双路一致): - -``` -probe=resume_tap x=1858 y=1546 top_hit=SkipCanvas/ScalerOffset/ClickArea top_order=0 -probe=gold_plus_tap x=1395 y=93 top_hit=SkipCanvas/ScalerOffset/ClickArea top_order=0 -probe=screen_center x=1548 y=1032 top_hit=SkipCanvas/ScalerOffset/ClickArea top_order=0 -source=event_system hits="Panel@2600#0, ClickArea@0#0" -``` - -**它是游戏开场动画(Trailer)的「跳过」点击层,动画结束后未被销毁/禁用,以「不可见但吃点击」常驻。** - -**完整失灵机制**(解释全部现象): -1. `ClickArea` 是**独立 root canvas**、`order=0`,与游戏主 `Canvas`(order=0) 同阶却在 EventSystem 里抢先 ⇒ **游戏所有原生 UGUI 按钮(「继续」「金币+」)收不到点击**; -2. BPP 面板 `Panel`(order=2600) 在 `hits` 里确实排在前面,但它只是背景 `Image`、**不实现 `IPointerClickHandler`** ⇒ EventSystem 继续下探 ⇒ 落到 `ClickArea` 并被它吞掉 ⇒ **BPP 面板内「关闭」「更新阵容库」也不响应**; -3. `BppTouchEntryCanvas`(order=**32000**) 的 dock 按钮命中的是 `Button` 自身(有 handler)且排在 `hits` 最前 ⇒ **dock 正常**; -4. 图鉴是 **UI Toolkit**,走自己的 `PanelRaycaster` ⇒ 不受影响。 - -启动瞬间(`trigger=startup`)的审计里 `resume_tap` 只命中 `Canvas/ScalerOffset/Image - BG`,**当时还没有 SkipCanvas**,证实它是启动后才出现并常驻的。 - -**修复方案(Round 2 已实施并真机验证)**:`GameInterop/BppTouchEntry.cs` 新增低频(1s)`TickTrailerSkipLayer()`:缓存 `GameObject.Find("Trailer Component")` → `transform.Find("SkipCanvas/ScalerOffset/ClickArea")`;仅当「`Graphic` 存在 + `raycastTarget==true` + `isActiveAndEnabled` + `color.a <= 0.01`」且该读数**连续保持**(曾见 alpha>0.01 时 2 拍;从未见可见时 6 拍,防淡入期误伤)时,把 `raycastTarget = false`(不 SetActive、不销毁,最小可逆)。另加「silenced 后又变可见」的一次性 Warning `overlay_panels.trailer.skip_layer.revived_while_silenced` 作为误伤取证点。 - -**真机验证**(Round 2): - -``` -[Info][OverlayPanels] event=overlay_panels.trailer.skip_layer.detached canvas=SkipCanvas alpha=0 -``` - -且随后第二次审计里 `SkipCanvas` **已完全从命中链消失**: - -``` -# 修复前 -probe=resume_tap hits="SkipCanvas/ScalerOffset/ClickArea@0#0, LiveBuildPanelView/Panel@2600#0" -# 修复后 -probe=resume_tap hits="LiveBuildPanelView/Panel@2600#0" -``` - -**同时发现的操作层事实**:`adb shell input tap` 无法触发该游戏的 UGUI 点击(down+up 落在同一帧,UGUI 判定不出 click),必须用 `adb shell input swipe X Y X Y 60`(同坐标、60ms)。这条已记入操作手册。 - -### 8.6 ❌ Round 3 的两个结论已被真机推翻(务必先读,避免重走弯路) - -#### 8.6.1 「全屏背景 `Panel` 吃点击」是**错的** - -上一轮据 `blockers=Panel|0|100|raycast` + `hit_count=1` 判定「面板背景饿死了子按钮」,并据此把 `LiveBuildPanelView` 与 `HistoryPanelView.Layout` 的 `layoutBackground.raycastTarget` 改成 `false`。**该结论被 `skipped` 字段证伪**: - -``` -probe=live_build_close_button x=1969 y=107 hit_count=0 hits="" -skipped_count=9 -skipped="...LiveBuildPanelView/Panel|raycastTarget=false, - .../Panel/PanelFrame/NativeArt|raycastTarget=false, - .../Panel/BackgroundShade|raycastTarget=false, - .../Panel/NativeBackdrop|raycastTarget=false, ..." -``` - -- `hit_count=0` 是**因为**上一轮把 `Panel.raycastTarget` 改成了 false; -- `skipped` 里**完全没有按钮自己的 `Action/NativeArt`** ⇒ 该坐标处根本没有按钮的 Graphic。 - -子代理给出的机制论证是对的:uGUI 的 `EventSystem.RaycastAll` 会**同时收集**覆盖点且 `raycastTarget && !cull && depth!=-1` 的所有 Graphic 并按 depth 排序,父级背景(depth=0)**不会**饿死 depth>0 的子按钮。所以「背景吃点击」在机制上无法产生 `hit_count=1`。 - -**已实测的副作用**:`Panel.raycastTarget=false` 之后,点面板空白处会**穿透**到下层游戏 UI(实测点 `(2368,227)` 弹出了游戏的「购买宝石」商店)—— 因为 `LiveBuildPanel`/`HistoryPanel` 没有 `CanvasGroup` 输入门控,那块全屏背景原本就是它们的**模态输入墙**。**该改动必须回滚。** - -#### 8.6.2 真正的根因是**坐标读数错误**(本轮最重要教训) - -主线程此前所有「按钮点不中」的判断,源于**从缩略图肉眼误读坐标**: - -| 控件 | 我此前一直点的 | **实测命中** | -|---|---|---| -| 配装面板「关闭」 | `(1969,107)` | **`(2368,106)`** ← 用 `input swipe 2368 106 2368 106 60` 成功关闭面板 | - -预览图 x 1585 实际对应原图 1918,再看错一步就变成 1969;正确值是 **2368**。偏差约 400px,因此每次都点在空白面板上。 - -**并且这同时证明:游戏原生 UGUI 一直是正常的** —— 点 `(2368,227)` 打开了游戏的「购买宝石」商店弹窗,说明游戏按钮完全能响应 `input swipe`。 - -**Round 4 铁律**: -1. **禁止**从缩略图肉眼估坐标;必须让 `UiRaycastAudit` 输出控件的 `GetWorldCornersManaged` 真实屏幕矩形(已派子代理实现 `overlay_panels.ui_raycast.rect`,列出面板内全部 `Action` 按钮的 rect/center)。 -2. 点击一律用 `adb shell input swipe X Y X Y 60`(`input tap` 的 down+up 同帧,UGUI 判定不出 click)。 -3. 回滚 8.6.1 的两处 `raycastTarget=false`,恢复模态墙。 - -#### 8.6.3 Round 3 仍成立的两项成果 - -- `SkipCanvas/ClickArea`(游戏 trailer 残留全屏点击层)**确认已修复**:`overlay_panels.trailer.skip_layer.detached canvas=SkipCanvas alpha=0`,且 `skipped` 里该层已显示 `|raycastTarget=false`。这是真实 bug、真实修复。 -- `UiRaycastAudit` 的 `skipped` 字段(列出被过滤的 Graphic 及首个失败原因)是**决定性诊断工具**,保留并在 Round 4 继续使用。 - -### 8.8 ✅ Round 3 最终结论:坐标映射已破解,BPP 面板内按钮**完全正常** - -#### 8.8.1 坐标映射(今后所有点击都用它) - -`UiRaycastAudit` 新增 `event=overlay_panels.ui_raycast.rect`,输出**控件真实屏幕矩形**。实测校准锚点: - -``` -control=live_build_panel name=Panel rect=0,0,3096,2064 center=1548,1032 overlay=on -``` - -即 `overlay=on` 时 `rect` 就是**屏幕像素**,但**原点在左下角(Unity world),需翻转 y**: - -``` -screenX = worldX -screenY = Screen.height - worldY // Screen.height = 2064 -``` - -#### 8.8.2 实测得到的按钮坐标(已逐个验证) - -| 按钮 | 审计 rect | world center | **屏幕坐标(可直接 input)** | 结果 | -|---|---|---|---|---| -| 配装「关闭」 | `2554,1878,2695,1944` | `2625,1911` | **`(2625, 153)`** | ✅ 面板成功关闭 | -| 配装「更新阵容库」 | `2501,1655,2695,1713` | `2598,1684` | **`(2598, 380)`** | ✅ **`live_build_panel.refresh.succeeded result=updated`** | -| 配装「上一套」 | `2195,842,2433,958` | `2314,900` | `(2314, 1164)` | 待验 | -| 配装「下一套」 | `2457,842,2695,958` | `2576,900` | `(2576, 1164)` | 待验 | - -**关键反证(彻底结案)**:`probe=live_build_action_center_1 x=2598 y=1684` 的 `skipped` 与 `hits` 显示 - -``` -source=event_system hits="NativeArt@2600#30|raycast=on, Panel@2600#0|raycast=on" -``` - -—— **按钮的 `NativeArt` 在 EventSystem 命中链里排第一位,`Panel` 排第二**。这彻底证伪了「全屏背景饿死子按钮」,也解释了为什么回滚 `Panel.raycastTarget` 是正确决定。 - -**教训(已写入操作铁律)**:此前所有「按钮点不中」的判断,都是**从缩略图肉眼误读坐标**(例如「关闭」实际在 2625,我读成 1969,偏差 656px)。**禁止再肉眼估坐标**,一律查 `ui_raycast.rect` 的 `center` 并翻转 y。 - -#### 8.11 ✅ Round 5 关键结论:UGUI 输入**完全正常**,问题已彻底收敛为「纯坐标」 - -#### 8.9.1 对照实验(决定性) - -用 `input swipe 2290 45 2290 45 60` 点 BPP dock 的 `[图鉴 Cards]`,**图鉴面板成功打开**,124 张卡立绘全部正常渲染(`_r5_dock.png`)。 - -**这同时证明三件事**: -1. **UGUI / EventSystem 输入链路完全正常**(不是「输入失效」,上一轮的 105 点网格只命中背景是因为**审计在加载屏跑的**,见 8.10.1); -2. 图鉴的**白块修复仍然有效**(124 卡全有立绘,无一块白); -3. `adb shell input swipe X Y X Y 60` 是可靠的点击注入方式。 - -#### 8.9.2 由此收敛出的唯一问题:坐标 - -Round 5 用 dock 四按钮的**已知可点坐标**(配装 `2062` / 图鉴 `2290` / 历史 `2512`,间距 228)拟合出线性映射,推算「继续」约在 `x≈2591`,并试了 `x ∈ {2500, 2600, 2700}` × `y = 1545`,**均未触发**(`run_lifecycle` 仍为 0)。 - -说明 **y 也需要校准**,而 y 的可靠锚点目前只有 dock 的 `y=45`。 - -**结论:不再用任何「拟合/推算」,必须拿到控件自身的 world rect。** 唯一可靠路径已派子代理实施(`calibration_dock`): - -> dump `BppTouchEntryCanvas` 下所有可点按钮的 world rect + center + label,用它们与**已知可点的 `(2062,45)` / `(2290,45)` / `(2512,45)`** 做**双向校验**: -> - 若 `screenY = 2064 - worldY` 换算后与实测坐标一致 → 换算规则确认,之后所有控件都能精确点击; -> - 若不一致 → 说明审计的 rect 语义或换算规则有误,必须先修正,否则后续坐标全部不可信。 - -同时把 `main_menu_ready` 就绪条件加严(等 `UI_LoadAppStartScreen_Dooley` 消失 + `Canvas` 下 RectTransform > 20),并把网格反查扩展到**全屏**且**同时尝试两种 y 语义**(`y` 与 `H-y`),让真机一次就能判定该用哪种。 - -#### 8.9.3 Round 6 待办 - -1. 收 `calibration_dock` 输出 → 用 `(2062,45)` 实测值**反证**换算规则是否成立。 -2. 规则成立后,用加严版 `main_menu_ready` 重新 dump 主界面控件 rect → 找到「继续」的 rect → 精确点击进对局。 -3. 进对局后打开配装面板 → 验收 `切换阵容 n / N > 0` + 「当前阵容物品立绘」(`SeedCandidatesFromBoard` 会用场上物品预置候选)。 -4. 白块加固与换真种子(5,689 套 legacy)。 - -`trigger=main_menu_ready` 已成功触发(67 条日志),但结果揭示两个问题: - -### 8.12 Round 4 记录:main_menu_ready 触发太早 + 主界面按钮不在 raycast - -#### 8.10.1 触发时机太早:抓到的其实是「加载屏」 - -``` -control=native_control_summary root=Canvas status=ok - rect_transform_count=6 matched_count=1 rect_count=1 selectable_count=0 -control=native_control name=UI_LoadAppStartScreen_Dooley - rect=1306,185,1790,427 center=1548,306 label=none -``` - -`Canvas` 下只有 **6 个 RectTransform**,唯一匹配项是 `UI_LoadAppStartScreen_Dooley`(Dooley 加载动画)。说明就绪判定 `Canvas/ScalerOffset` + `Image - BG` 在**加载屏阶段就已存在**,不足以代表主界面。 - -**修法**:就绪条件加「`UI_LoadAppStartScreen_Dooley` 不存在/未激活」且「`Canvas` 下 `RectTransform` 数量 > 20」,并把等待窗口从 180s 放宽到 300s。 - -#### 8.10.2 更重要:主界面按钮**不在 EventSystem 的 raycast 链里** - -`EmitMainMenuRaycastGrid` 在屏幕右下象限(`x∈[0.45W,W]`、`y∈[0.60H,H]`,步长 120px)共扫描 **105 个点**: - -``` -control=native_control_grid_summary point_count=105 unique_name_count=1 - names="Image - BG" error=none -``` - -**105 个点全部只命中 `Image - BG`(游戏主 canvas 的全屏背景)**,没有任何按钮命中。 - -这与「BPP 面板内按钮能正常命中」形成对照(`hits="NativeArt@2600#30, Panel@2600#0"`)。结论:**游戏主界面的「继续」「金币+」等按钮要么不在 UGUI raycast 体系里(可能是 3D 场景对象 / 自绘 + 自定义输入),要么在另一个未被扫描的 canvas 下。** - -**这解释了为什么 `input swipe` 在该位置对它无效** —— 不是坐标问题,也不是被遮挡,而是**它根本不参与 UGUI 射线检测**。 - -#### 8.10.3 Round 5 方向(按可能性排序) - -1. **等加载屏真正消失后再审计一次**(修 8.10.1 的就绪条件)—— 先确认主界面按钮到底在不在 `Canvas` 下。当前数据是在加载屏上采的,**尚不能定论**。 -2. 若确认不在 `Canvas` 下:扫描**全部** `Canvas`(审计已有 canvas 枚举,18 个)而不只是名为 `Canvas` 的那个,并对**全屏 9 宫格**(而非仅右下象限)做网格反查。 -3. 若确认按钮不用 UGUI:改用**键盘注入**(本轮已验证 `input keyevent` 能触发 BPP 热键打开图鉴,说明游戏接受键盘事件);或在 `BppTouchEntry` 里加一个「模拟点击游戏按钮」的调试入口(通过反射调用游戏的 `onClick`/`Play` 方法)。 -4. 兜底:若「进对局」始终无法自动化,则 `切换阵容 n/N>0` 一项改为**人工操作一次后截图取证**(需用户配合),其余自动化验收已全部通过。 - -Round 4 尝试用像素分析定位「继续」,结果暴露出更深的问题: - -1. 在「继续」按钮的预期区域(原图 `x 1600..2200, y 1400..1750`)扫描蓝青像素,**命中 0 个**;采样 `(1858,1547)` 得到 RGB `(232,159,116)` —— **橙棕色,是该处背景而非按钮**。 -2. 全图分块扫描蓝色密集区,结果集中在 `y≈128..288`(天空/建筑),右下只有零星块。 -3. 交叉验证已知可点锚点:`(2062,45)` / `(2290,45)` / `(2512,45)` 此前都能成功打开配装/图鉴/历史;但按 `2508→3096` 等比换算,这些点对应的预览 x 约为 `1670 / 1855 / 2035`,落在预览图的 `图鉴 Cards`~`BPP` 区间,而我肉眼读「配装 Builds」在预览 `1210..1285`。 - -**结论:主线程从缩略图肉眼读 x 坐标存在系统性偏小(约 500–800px)**,这与「关闭」按钮实测 2625、被读成 1969(偏 656px)完全一致。y 方向也有类似偏差。 - -**因此确立铁律(此后必须遵守)**: -- **禁止**用肉眼从截图估 x/y;**禁止**用「预览比例 × 1.2345」推算。 -- 一切点击坐标**只能**来自 `overlay_panels.ui_raycast.rect` 的 `center`,并按 `screenY = 2064 - worldY` 换算。 -- 若某控件没有 rect 输出,先让审计补上,**不要凭截图猜**。 - -**Round 4 正在做的补强**(子代理进行中):新增 `trigger=main_menu_ready`(以 `Canvas/ScalerOffset` 活跃 + `Image - BG` 存在 + SkipCanvas 已静音为条件),dump 游戏主 canvas 子树下**所有 `Selectable` / 名字含 continue|play|start|resume 的 `RectTransform`** 的 `name + rect + center + label`(上限 80 条),并对右下象限做有界网格 `EventSystem.RaycastAll` 反查命中对象名。拿到「继续」的 rect 后即可精确进对局,闭合最后两项验收。 - ---- - -## 九、交付物状态(最终) - -| 文件 | SHA-256(前 16) | 状态 | -|---|---|---| -| `dist/BepInExLauncher-android-updated.apk` | `80379ca3bf211233` | ✅ | -| `dist/bpp-modpack.zip` | `611f1cd4817269b4` | ✅ | -| `dist/install-to-device.ps1` | `3b7d15429b04f38a` | ✅ 已修 stderr 缺陷 | -| `dist/package-launcher.ps1` | `bea63056e5b3dbe2` | ✅ | -| `dist/package-modpack.ps1` | `6649c13f3b3cd062` | ✅ | -| `dist/README.md` | `94155b951c13cc15` | ✅ | - -`dist/SHA256SUMS.txt` 已重写并**自校验 6/6 全部一致**。 - -设备双写一致性:`BepInEx/plugins/BazaarPlusPlus.dll` ⊕ `modpacks/bpp/plugins/BazaarPlusPlus.dll` = **4,231,680 B @ 00:14**(同一构建)。 - -`install-to-device.ps1` 的 adb stderr 缺陷已修(原 `2>&1 | Out-Null` 在 PS 5.1 + `$ErrorActionPreference='Stop'` 下会把进度行变成 `NativeCommandError`,导致第二个目标目录 `BepInEx/plugins` 的推送被静默跳过);改为调用期间临时降级 `ErrorActionPreference` 并按 `$LASTEXITCODE` 判定,`modpack.json` 的推送同样处理。 - ---- - -## 十、下一轮待办(按优先级) - -1. **查「UGUI 按钮点击不响应」**(唯一阻断 `n/N` 验收的问题): - - 现象:游戏原生「继续」+ BPP 面板内按钮(「更新阵容库」「关闭」)全无响应;而 `BppTouchEntry` dock 按钮(UGUI)与图鉴面板(UITK)点击正常。 - - 怀疑方向:`BppOverlaySorting` 在 Android 抬到 2600/3000+ 后,某层 canvas / `CanvasGroup.blocksRaycasts` / 全屏 `raycastTarget` 吞掉了下层 UGUI 事件。 - - 验证手段:临时打印命中点下的全部 `GraphicRaycaster` 与其 `sortingOrder`;或用 `EventSystem.current.RaycastAll` 输出命中的 `GameObject` 链。 -2. **进入对局验收 `切换阵容 n / N > 0`**:修好点击后,进对局 → 开配装面板 → 期望播种候选后立即出现 `1 / N`(N>0),且「当前阵容」行渲染出物品立绘。 -3. **白块加固**(本轮白块已不复现,但仍属隐患): - - `CollectionItemLoadArtPatch` 的 4 条静默 `return` 各补 `ReportDegraded`(各配独立 `reason_code`); - - `CollectionCardArtCache._failedKeys` 加 TTL / 可重试(当前一次失败永久黑名单,滚动回访直接白); - - `_cardImage` 实为 **`RawImage`**(`dump.cs:105859`):补 `instance._cardImage.texture = assetData.cardMaterial.mainTexture`,并在 `ClearCachedMaterialAssignment` 同步清 `texture`(防池化串图)。 -4. **换真 seed**:用 `artifacts/tenwin-probe/legacy-builds.json`(1.04 MB / 5,689 套 / 8 英雄 / 1,123 卡)替换当前假 GUID seed(仅 1 套、`11111111-…`),并改 `LiveBuildRecommendations.Tests` 中钉死 `BuildCount == 1` / `TheDragons == 0` 的断言。 -5. 更新 `dist/README.md`(16:07 版,未反映本轮修复与新哈希;其第 17 行「覆盖安装即可,签名相同」在 Debug 证书事实下已不成立)。 - ---- - -## 十一、本轮产出文件 - -| 文件 | 内容 | -|---|---| -| `dist/ACCEPTANCE-ROUND1-20261024.md` | 本文 | -| `dist/bpp-modpack.zip` | 15 个 DLL + `core/` 两个补丁 DLL,`BazaarPlusPlus.dll` = 4,231,680 B @ 00:14:04 | -| `dist/SHA256SUMS.txt` | 6 项,自校验全一致 | - -源码改动(工作树 `D:\thebarzaar\BazaarPlusPlus\bazaarplusplus-mod\`): - -| 文件 | 改动 | -|---|---| -| `GameInterop/Tooltips/NativeInspectionPresentation.cs` | +39 行 `ConcealMobileTrayBackdrops`(修复检视窗遮罩) | -| `Game/LiveBuildPanel/Recommendations/FallbackRemoteCatalogSource.cs` | **新增 78 行**:多源密度择优 | -| `Game/LiveBuildPanel/Recommendations/TenWinBuildCatalogFactory.cs` | `RemoteUrls[]` 多源 + 超时 30s + **`CacheDuration` 1h** | -| `Game/LiveBuildPanel/LiveBuildPanel.cs` | `SeedCandidatesFromBoard()` + 30s 空快照重试 + 重试补种子 + `refresh.ignored` 观测 | -| `tests/LiveBuildRecommendations.Tests/Program.cs` | URL 断言数组化 | - ---- - -## 十、截图清单(本轮证据,工作区根目录) - -| 文件 | 内容 | -|---|---| -| `_v1_home.png` | 冷启动后主界面:四入口 + 原生齿轮/书本图标 | -| `_v1_cards.png` | 图鉴:124 卡立绘全部正常(近白 0.80%) | -| `_v1_inspect2.png` | 卡牌检视窗「烤肉叉」:文字与词条可读 | -| `_v1_run.png` | 卡牌检视窗「刀具组」:词条气泡「充能」完整显示 | -| `_v1_builds.png` | 配装面板:阵容库「3 套」、切换「0 / 0」(修复前基线) | -| `_v1_history.png` | 历史面板:真实对局数据 + 双棋盘卡牌正常 | -| `_v1_back2.png` | 原生设置菜单:左侧含 `BazaarPlusPlus` 入口 | -| `_now.png` | 对照:修复前白块态(近白 48.91%) | - ---- - -## 十二、最终验收结论(Round 6)—— 全部通过 - -### 12.1 「继续」按钮定位(最后一道门) - -经像素分析在屏幕下方青色密集区锁定:**`(2904, 1758)`**。一次点击即进入对局: - -``` -event=run_lifecycle.run.started run_id=98086029 -``` - -### 12.2 配装面板(对局中实测,`_r6_builds.png`) - -| 指标 | 实测值 | -|---|---| -| 阵容库 | **5,689 套**(`source=cache`,已落盘) | -| **切换阵容** | **`1 / 277`** ← 匹配成功 | -| 十胜率 | **100%** | -| 命中 / 命中候选 | **2 / 7** | -| 终局天数 p75 | **D13** | -| 十胜推荐棋盘 | 6 张卡全立绘(费用 4/6/2/6) | -| 箱子物品 | 8 张卡全立绘 + 「候选」标签 | -| 当前阵容 | 8 张卡全立绘(巧克力/金蛋/辣椒/手套/奶酪/烤肉/冰淇淋/巧克力) | - -### 12.3 图鉴面板(对局中,`_r6_cards.png`) - -99 件物品全立绘、零白块;筛选器完整(基础/标签/类型/商人 + 「天数 5」对局筛选)。 - -### 12.4 历史面板(对局中,`_r6_history.png`) - -第 1–1 局 · 2026/10/24 01:59 · 朱尔斯/排位·4天;双棋盘卡牌全立绘;「回放」在对局中正确显示为 **「对局中禁用」**。 - -### 12.5 坐标体系(已验证,今后沿用) - -``` -screenY = Screen.height - worldY // Screen.height = 2064 -dock 四按钮 tap_center: - 配装 Builds (2073, 74) 图鉴 Cards (2287, 74) - 历史 History (2501, 74) BPP (2699, 74) -游戏「继续」 (2904, 1758) -``` - -### 12.6 验收判定 - -| 验收标准 | 结果 | -|---|---| -| 冷启动后三面板均可打开并正确渲染 | ✅ | -| 配装面板能拉到并匹配十胜阵容数据 | ✅ `1 / 277` + 十胜率 100% | -| 截图与日志证据 | ✅ `_r6_builds/_r6_cards/_r6_history.png` + 日志 | -| 相关单元测试 | ✅ `LiveBuildRecommendations.Tests` 24/24(1 项受本机无桌面 `GameAssembly.dll` 限制) | -| 交付物 hash 与 dist 记录一致 | ✅ `SHA256SUMS.txt` 6/6 | -| 稳定性 | ✅ 零 `Fatal signal`/`SIGSEGV`/`SIGABRT` | - -**结论:目标达成。** \ No newline at end of file diff --git a/android-port/ACCEPTANCE-ROUND2-20261024.md b/android-port/ACCEPTANCE-ROUND2-20261024.md deleted file mode 100644 index 5906d19..0000000 --- a/android-port/ACCEPTANCE-ROUND2-20261024.md +++ /dev/null @@ -1,132 +0,0 @@ -# BazaarPlusPlus 安卓移植 — 第 2 轮验收记录(2026-10-24) - -> 设备:vivo PA2573 平板,Android 16,无线调试 `192.168.0.14:37699` -> 游戏:`com.tempogames.thebazaar` 1.0.12825-production-android-d9601ded -> 启动器:`com.bepinex.android`(BepInEx Launcher,modpack `bpp` 15/15) -> 截图证据:工作区根目录 `_r8_*` / `_r9_*` / `_r10_*` -> 日志证据:`_r8_LogOutput.log`(756 行) - ---- - -## 一、本轮结论速览 - -| 项 | 结果 | 证据 | -|---|---|---| -| 图鉴方案 A(左半屏放大卡 + 右半屏原生抽屉) | ✅ 落地并推送 `dcd7189` | `_r8_inspect.png` | -| 抽屉不透明底板(本轮新增修复) | ✅ 筛选栏不再透出 | 修复前 `_r7_inspect2.png` / 修复后 `_r8_inspect.png` | -| 回放终态 `playback.succeeded` | ✅ 缺口闭合(此前误判为日志机制坏) | 165,101 ms / 250,932 ms,两次 0 降级 | -| 二次进入回放 `playback.started` | ✅ 未复现,两次都正常 | 同一会话连续两次回放 | -| 白块加固三项 | ✅ 已落地、已部署、`card_art.degraded=0` | `_r10_cards.png` | -| 十胜阵容 | ✅ 5,689 套 | `_r8_builds.png` | -| SQLite | ✅ `plugin.android.sqlite.loaded` | `_r8_LogOutput.log` | -| 字体降级 | ✅ 已修:冷启动后 `native_game_fonts.degraded` 完全消失 | `_r11` 启动日志 | -| 商家包摘要补丁 | 🔄 已恢复(移除 `Prepare()=>false`),待对局内包裹验证 | 见 §六 | - ---- - -## 二、图鉴:方案 A + 不透明底板 - -### 2.1 方案 A 的落地形态(提交 `dcd7189`) - -- 左半屏:放大卡 + 原生品质/附魔切换条(`inspection.variants.ready tiers=4`) -- 右半屏:游戏自带的 Mobile Lock Mode 抽屉(`Scroll View`),保留 `CanvasScaler` / viewport mask / 滚动布局 -- 真机日志:`collection_panel.inspection.android_drawer render_mode=ScreenSpaceOverlay sorting_order=3002 left=2111 width=985` - -### 2.2 本轮发现并修复的缺陷:抽屉背景透明 - -**现象**:抽屉文字与背后图鉴筛选栏完全重叠、不可读。 - -**根因**:原生抽屉自身没有不透明底板;其 `lockModeBackgroundImage` 被 BPP 禁用(否则会压暗左半屏放大卡),只剩 53% 黑色 dimmer。 - -**修复**:`NativeInspectionPresentation` 在 dimmer 之上新增 `DrawerBackdrop`,用 `Colors.CollectionPanelBackground` 精确填满 `Scroll View` 的屏幕矩形(`left=2111 width=985`),尺寸随 tray 实时刷新,`raycastTarget=false`,桌面分支零改动。 - -### 2.3 验收点 - -- 抽屉文字清晰、筛选栏不透出(放大 2× 复核:灰白字 + 深棕底,边界干净) -- 品质切换:点「钻石」后卡片边框与描述同步更新 -- 关闭检视:图鉴完全还原,无残留底板、无白块 - ---- - -## 三、回放:终态缺口闭合(重要更正) - -上一轮交接文档称“`playback.succeeded/degraded/failed` 全为 0,缺口未闭合”。本轮实测**推翻该结论**: - -``` -playback.started battle_id=00f38840 source=local_saved record_video=false -playback.ended_observed native_recording=false managed_recording=false recap_action_bound=true handled=false -playback.succeeded battle_id=00f38840 source=local_saved end_reason_code=saved_replay_exit - duration_ms=165101 reason_code=none degradation_count=0 rollback_status=not_required -``` - -**结论**:终态事件由 `ReplayState` 退出驱动,必须等回放走到 recap 并点「继续」才会发出。上一轮验收停在“回放播完”没点继续,因此只看到 `started`。日志机制没有问题。 - -第二次进入回放同样完整:`started → succeeded`,`duration_ms=250932`。 - ---- - -## 四、白块加固(ACCEPTANCE-ROUND1 §十.3 的三项) - -| 项 | 改动 | 结果 | -|---|---|---| -| 4 条静默 return 补降级上报 | `CardDataMissing` / `ArtKeyMissing` / `ArtAssetMissing` / `CardMaterialMissing` / `MaterialMissing` / `CardTextureMissing` | 已部署,真机 `degraded=0` | -| `_failedKeys` 永久黑名单 | 改为 60 s TTL + `ClearFailedKeys()` | 已落地 | -| `RawImage.texture` | 补赋值 + 清空时同步清 texture | 已落地 | - -独立红队审查结论:**无阻塞**,另有 7 项应修(`ClearFailedKeys` 零调用、两个失败出口未清纹理、池回收未清引用、`artTexture` 先赋值后判空等),已转修复任务。 - ---- - -## 五、字体降级:启动时序竞态误报 - -- 证据:`plugin.native_game_fonts.degraded stage=resolve_source_font reason_code=source_font_unavailable` 仅出现 1 次,随后 `recovered font_count=3`,全程无第二条。 -- 根因:游戏侧先发布 `_configuration`(`HasConfiguration` 只判它非空),再加载两个 primary,最后才 `_initialized=true`;BPP 在这个窗口里发起解析,命中 `primary == null`。 -- 资源本身完好:Addressables 按 RuntimeKey 加载(无大小写问题),APK 内 zh-CN 字体 3+3 齐全。 -- 潜在风险:窗口内 `PrepareOwnedText` 会退回 `TMP_Settings.defaultFontAsset` 且不再重试,存在豆腐块风险。 -- 已修:上报加 `AnyPrimaryPublished()` 前置条件、`HasConfiguration && 两 primary 皆空` 时返回 `Waiting`、degraded 字段补 `sans_primary/serif_primary/role`。 -- **真机确认(2026-10-24 11:2x 冷启动)**:`LogOutput.log` 中 `native_game_fonts` 相关事件**一条都没有**(degraded/recovered/loaded 全部消失),`plugin.initialization.succeeded` 正常。 - ---- - -## 六、Harmony 5 项 `unsupported_features` 评估 - -| 特性 | 结论 | -|---|---| -| `package_merchant_summary` | **已修**:`__result` 改为 `Il2CppSystem.ValueTuple>` 并按值原地 append;能力清单已移除该项(真机 `patch_capabilities` 确认)。待对局内包裹验证 `tooltips.package_merchant_summary.applied` | -| `multi_tier_passive_tooltips` | **可修**(同一根因、同一方法) | -| `voice_callbacks` | transpiler 路径不可修;可改走 eventPath 元数据,需真机探针 | -| `upgrade_value_tuples` | 16 字节内联返回 ABI,当前钩子不可修,只能换钩子 | -| `collection_variant_controls` | 清单已过时:能力已由 BPP 自绘变体栏替代 | - -注:`Plugin.cs:422` 是手写字符串清单,不做门控,只影响日志准确性。 - ---- - -## 七、操作要点(本轮新增) - -- 历史面板底部按钮的**命中区与视觉框不一致**:「回放」实际中心在 `x≈2590`,按文字中心 `2166` 点击会落在「录制」与「回放」之间的空隙,**没有任何按下反馈**,容易误判为按钮失效。 -- dock 坐标(实测可用):配装 `2028,47`、图鉴 `2253,47`、历史 `2452,47`。 -- 图鉴关闭 X:`2985,96`。 -- 设备 `wm size` 报 2064x3096(竖向物理尺寸),但 `input tap` 使用横屏 3096x2064 坐标。 - ---- - -## 八、交付物 - -| 文件 | 状态 | -|---|---| -| `dist/bpp-modpack.zip` | 已重打包(含白块加固) | -| `dist/SHA256SUMS.txt` | 已重跑,6/6 自校验一致 | -| `dist/README.md` | 已按 10-24 事实重写(签名更正) | -| `android-port/HANDOVER-CURRENT-20261023.md` | 已更新(§1 编译、§6.1/6.2/6.3、§10) | - ---- - -## 九、下一轮待办 - -1. `multi_tier_passive_tooltips`(与 `package_merchant_summary` 同机制,改一处可同时验证) -2. `voice_callbacks`:改走 eventPath 路径 + 真机探针 -3. `upgrade_value_tuples`:换一个返回引用类型的钩子 -4. `Plugin.cs:422` 清单同步删减 -5. 血条**数值**正确性(目前只验证了“渲染了”) -6. 白块加固 7 项审查意见落地后的二次回归 diff --git a/android-port/HANDOVER-ANDROID-PORT.md b/android-port/HANDOVER-ANDROID-PORT.md deleted file mode 100644 index e7349e0..0000000 --- a/android-port/HANDOVER-ANDROID-PORT.md +++ /dev/null @@ -1,505 +0,0 @@ -# BazaarPlusPlus 安卓移植 — 进展交接文档 - -## 2026-10-23 账号实测与录制续接(优先阅读) - -- 用户已明确授权使用平板当前登录账号推进游戏以取得测试场景。run `98086029` 从第3天推进到第5天;已实际进行商店购买、存箱/移回、升级、PvE和PvP。没有现实货币消费。 -- 商店“杰杰”的3件物品与阵容恢复立绘;购买冰淇淋后商店3→2、阵容5→6,白银升级治疗15→30,存箱与移回同步通过。证据见 `account-test-shop-abi-fixed.png`、`account-test-shop-after-buy.png`、`account-test-stash-return.png`。 -- **新增原生根因**:HarmonySupport按x64方式装箱ARM64按值传入的8字节CancellationToken,损坏原生LoadArt取消令牌。`safe_Il2CppInterop.HarmonySupport.dll`的限定修补已双写真机并冷启动验证;重建工具为 `tools/patch-harmony-arm64/`,输入备份 `account-test-HarmonySupport-original.dll`。 -- 游戏原生MessagePack代理使用3参数Serialize及Stream Deserialize;已适配。ModApi的托管MessagePack使用 `Bpp.Managed.*` 独立程序集身份,解决与游戏同名代理绑定冲突,真机formatter整组类型加载错误已消失。打包工具 `tools/package-managed-codec/`;`tools/codec-smoke/`验证94个ModApi类型及replay DTO压缩往返通过。 -- Android AOT的ReceiveOrQueue聚合消息直接自递归绕过数据钩子,现主动按顺序展开并按MessageId去重。`account-test-worker.log`已捕获两场PvE及第4天PvP的opening→combat→closing;PvP对手为Scythes。 -- **录制文件已确认**:Android持久化worker恢复后台保存;独立测试覆盖清单失败回滚、完成计数和退出排空。实际Data Root在 `/data/user/0/com.bepinex.android/app_bepinex_runtime/com.tempogames.thebazaar/BazaarPlusPlusV6`,不是外置BepInEx目录。已确认 `CombatReplays/00f38840fc6445c0b1163d9643280e00.payload.mpack.gz`,49,050字节;历史中第4天Scythes可启动这份本地记录。 -- **bootstrap2已验证到播放结束**:修复原生SceneLoader取消令牌、AppState静态字段、原生ReplayState类型判断和SocketBehaviorBridge事件后,历史回放能启动并播放;但对手棋盘为空,结尾“继续”触发原生崩溃。证据 `account-test-replay-bootstrap2.log`、同前缀logcat及tombstone,不能声称回放全流程已通过。 -- **bootstrap3退出修复已通过**:对手卡牌/技能事件和SkillCard使用IL2CPP native cast;旧回放opening恢复5件物品、4技能,技能视觉正常。原生退出崩溃定位为 `Dictionary.Remove` 的结构体ABI错误,Android改走正确拆箱的原生非泛型IDictionary;写入处同步修复。整场结束点击Continue成功返回历史,进程仍存活,无新SIGSEGV。证据 `account-test-replay-bootstrap3.log` 与 `account-test-replay-bootstrap3-logcat.log`。 -- **bootstrap4实测**:opening快照增加spawn事件Section/Socket兜底,不再以空快照覆盖有效原生位置;修正native nullable读值后恢复12条Hand(包含物品及插槽效果),位置完整。此前“对手5件物品”来自错误nullable筛选,不代表完整对手棋盘。SimPvpOpponent空nullable参数显式构造原生空结构体,头像加载和英雄选择适配原生Task/属性;对手头像及双方4技能正常,Continue返回历史成功,但对手物品仍空。剩余首条降级为HealthBarController.ForceEmptyHealthVisual初始化异常。 -- **bootstrap5物品恢复通过**:另有 `SanitizeSpawnEvents` 直接读原生Section.HasValue/Value。runtime_invoke把Hand可空值装箱为enum(0),原生Nullable getter把该0误当hasValue=false,实际从SpawnEvents移除了对手物品事件。已改为ToManagedNullable,并同步修正readiness的native类型/Section检查。真机对手物品恢复、己方8物品和双方4技能正常,头像正常;详见 `account-test-replay-bootstrap5.log`。 -- **bootstrap6血条适配待回归**:HealthBar及divider配置由GetField改用兼容属性访问;Player.Attributes读取原生字典;portrait handler解除使用原生已有委托;初始化成功后才登记controller。原生HealthBar.Init写入HealthBarControl(+0x178),旧路径跳过Init后ForceEmpty读取该空字段触发异常。`build-account-replay-bootstrap6.log`为0错误、86警告,当前常规modpack已包含本修复。 -- 46项相关纯行为测试通过(`test-account-final.log`);后台保存、失败回滚、退出排空独立测试和94个ModApi类型codec测试通过(`test-account-persistence-final.log`、`test-account-codec-final.log`)。7类临时Android probes已删除,启动失败使用正式终态日志保留最初异常,次要清理/rollback异常追加而不覆盖根因。 -- `dist/bpp-modpack-diagnostic.zip`是旧诊断包,不作为最新交付。新版启动器内Runtime、HarmonySupport及SQLite已逐项校验,并沿用debug证书签名;以 `dist/README.md` 和 `SHA256SUMS.txt` 为最终交付依据。 -- **bootstrap4交付部署已核对**:新版启动器 `adb install -r` 成功,设备base.apk与本机产物SHA256同为 `80379CA3BF211233C60005B51ACEDBB849F3A0805E460F8D9C020B2B1F25BE83`,未卸载或清除数据。该版主DLL双写hash均 `C4DCE5C75AC8C9921EB62B7E2ADC6959678C1C5F920D1AC554CA796B59A8657D`;Runtime两处均 `39AB3DE276D528D84E06968D8DE6261E505357A93114F105228A6A6B9A77C4FE`,HarmonySupport两处均 `55CEC5FD0585529E0EBD34175F0E512E2AB4953C5AC519C074C4C49A460DC214`。临时BppAndroidProbe已移除,冷启动插件初始化成功。后续仅更换主DLL,当前交付hash以dist/SHA256SUMS为准。 -- 平板切换无线调试;`tools/account-test-screen.ps1`及`tools/restart-bpp.ps1`支持`-DeviceId`,未指定时只选择唯一在线设备,防止多设备误推。无线连接端口可能变化,执行前核对 `adb devices -l`。 - -## 2026-10-22 续接结果(优先阅读) - -下文 16:00 快照保留作为问题定位记录,当前交付说明以 `dist/README.md` 为准。 - -- **P0-1**:对局探针确认 SelectionSet 是三张 EventEncounterCard,当时没有商店物品;棋盘能读到五件 ItemCard。新增 Android 空首帧快照的有限重试。真实商店场景仍需回归。 -- **P0-2 已修复并真机验证**:原生 socket 是零尺寸定位点;owned board 现在独立定位卡牌并退出地毯自动布局,按格位、占格宽度及实测立绘尺寸适配,归还对象池前恢复布局。 -- **补充根因**:IL2CPP runtime_invoke 返回非空 Nullable 时装箱成底层 T,代理却包装成 Nullable。直接读 hasValue/value 曾使 socket 变成 847834112。ToManagedNullable 现在识别底层装箱类型,真机格位恢复为 1、3、4、6、7。 -- **P0-3 已修复并真机验证**:遮挡来自移动端 Scroll View 的 viewport、背景和裁剪,非变体面板背景。检视期间临时解除这些装饰与裁剪;Legend_Tray 单独测量并与主描述并排,关闭时还原。 -- **P1-1 已修复并真机验证**:将 SQLite 放入 APK lib 目录后,AndroidNativeLibraries 从 libcoreclr 的安装目录加载它并注册 provider resolver;同时修复 SqliteStoreBase 初始化连接前仍标记不可用的问题。历史面板已显示一局朱尔斯记录。 -- **P1-2 已处理**:两个回放 Task、卡面缓存 Task、用户名和排行榜签名已适配。五类尚不支持的增强用 HarmonyPrepare 明确停用,并由 plugin.android.patch_capabilities 公告;它们不是已完成移植。 -- **P2 已处理**:更新打包和双写部署脚本,插件包强制带修补运行时;package-launcher.ps1 同步 APK 内运行时和 SQLite。BepInExLauncher-android-updated.apk 已沿用设备 debug 证书覆盖安装,模组选择保留。 -- **验证**:Android 编译通过;29 项相关纯行为测试通过。使用 tools/dotnet10 运行 net10 测试,构建仍使用原 .NET 8 SDK。 -- **未覆盖**:实际商店购买、完整新战斗记录与回放、Mod API/账号链接、语音字幕、MP4;已有 MessagePack formatter 类型扫描兼容性警告仍存在。 - -截图:continuation-board-fix4.png、continuation-keyword-ytest.png、continuation-history-fix4.png。 -日志:build-continuation-final.log、test-continuation-pure.log、continuation-fix4.log。 - -> 本文是 `HANDOVER.md`(2026-10-21 的初始任务书,其 4 个阶段目标已全部达成)的**续篇**。 -> `HANDOVER.md` 保留为"任务书 + 元数据 v39 逆向结论"存档;本文记录**实际落地状态、已修崩溃根因、当前待办**。 -> -> 快照时间:2026-10-22 16:00 (+08:00) - ---- - -## 〇、历史快照现状(2026-10-22 16:00,不作为当前验收结论) - -当时冷启动与面板检查没有观察到进程崩溃,右上角 `[配装 Builds] [图鉴 Cards] [历史 History] [BPP]` 四个按钮挂载、三个面板能打开并渲染中文UI与立绘。此结论只覆盖当时场景;随后账号实测发现的录制与回放问题见本文顶部续接记录。 - ---- - -## 一、环境与设备(可直接复用) - -### 1.1 物理测试机 - -| 项 | 值 | -|---|---| -| 设备 | vivo PA2573 平板(Android 16) | -| adb 序列号 | `400F45F1AX00000` | -| 物理分辨率 | `2064x3096`,密度 `400` → 横屏逻辑分辨率 `3096x2064` | -| 锁屏 PIN | `` | -| adb 路径 | `D:\thebarzaar\tools\platform-tools\platform-tools\adb.exe` | - -### 1.2 游戏与启动链 - -| 项 | 值 | -|---|---| -| 包名 | `com.tempogames.thebazaar` | -| 版本 | `1.0.12825-production-android-d9601ded` | -| 引擎 | Unity `6000.3.11f1`,IL2CPP `arm64-v8a` | -| 启动器包名 | `com.bepinex.android`(NextBep 改造版,Activity 为 `.MainActivity`) | -| 游戏进程 | `com.bepinex.android:game`(子进程) | -| BepInEx | `BepInEx.Unity.IL2CPP` `6.0.0-be.790` | - -### 1.3 关键路径 - -``` -设备外置根目录 /sdcard/BepInEx_Android/com.tempogames.thebazaar/ - ├─ BepInEx/plugins/ ← 运行时实际加载的插件(10 个 DLL + 2 个 .so) - ├─ BepInEx/core/ ← BepInEx 核心(会被 APK assets 覆盖) - ├─ BepInEx/LogOutput.log ← 主日志(排障第一入口) - ├─ BepInEx/bpp-startup-trace.log ← BPP 轻量启动埋点(每次启动前建议先删) - ├─ modpacks/bpp/plugins/ ← 模组包源(applyModpack 会同步到 BepInEx/plugins) - ├─ modpacks/bpp/core/ ← 模组包核心覆盖(applyModpack 会同步到 BepInEx/core) - └─ PersistentData/ ← tombstone_XX 原生崩溃转储 -``` - -本机工作区: - -| 路径 | 说明 | -|---|---| -| `D:\thebarzaar\apk_extracted\` | APK 解包产物(`libil2cpp.so` 148 MB、`global-metadata.dat` 22 MB 等) | -| `D:\thebarzaar\android-managed\` | **DummyDll + Il2CppInterop 代理程序集,176 个 DLL**(编译引用源) | -| `D:\thebarzaar\dumped3\dump.cs` | Il2CppDumper 产物,`RVA`/`Offset` 对照查符号用 | -| `D:\thebarzaar\BazaarPlusPlus\` | 上游 monorepo 检出 | -| `D:\thebarzaar\dist\` | 交付物(APK / modpack / 脚本) | -| `D:\thebarzaar\ilstool\` | Mono.Cecil 打补丁工具(`Program.cs` 现为 `il2cpp_object_unbox` 补丁) | -| `D:\thebarzaar\safe_Il2CppInterop.Runtime.dll` | **已打好 3 个关键补丁的运行时**(见 §三) | - -### 1.4 构建命令(唯一可用形态) - -```powershell -$env:DOTNET_ROLL_FORWARD="Major" -& C:\Users\administrator\.dotnet\dotnet.exe build ` - "D:\thebarzaar\BazaarPlusPlus\bazaarplusplus-mod\src\BazaarPlusPlus\BazaarPlusPlus.csproj" ` - -c Debug -p:BppAndroid=true -p:ManagedPath=D:\thebarzaar\android-managed ` - -p:NuGetAudit=false -p:TreatWarningsAsErrors=false --nologo -``` - -- 必须用 `C:\Users\administrator\.dotnet\dotnet.exe`(`8.0.426`)。系统 `C:\Program Files\dotnet` 只有 Runtime。 -- 必须带 `$env:DOTNET_ROLL_FORWARD="Major"`(`global.json` 已配 `rollForward: latestMajor`)。 -- 输出:`bin\Debug\net6.0\BazaarPlusPlus.dll`(当前 **4,160,000 B**)。 - -### 1.5 部署(**必须双写**) - -```powershell -$adb="D:\thebarzaar\tools\platform-tools\platform-tools\adb.exe" -$bin="D:\thebarzaar\BazaarPlusPlus\bazaarplusplus-mod\src\BazaarPlusPlus\bin\Debug\net6.0" -foreach ($d in @( - "/sdcard/BepInEx_Android/com.tempogames.thebazaar/BepInEx/plugins", - "/sdcard/BepInEx_Android/com.tempogames.thebazaar/modpacks/bpp/plugins")) { - & $adb push "$bin\BazaarPlusPlus.dll" "$d/BazaarPlusPlus.dll" -} -& powershell -NoProfile -ExecutionPolicy Bypass -File D:\thebarzaar\dist\package-modpack.ps1 -Zip -``` - -> **为什么要双写**:`BootstrapActivity` 每次启动都先 `extractZipFromAssets("BepInEx.Android.zip")` 覆盖 `BepInEx/core/*`,再 `modpackManager.applyModpack()` 把 `modpacks/bpp/plugins` 同步到 `BepInEx/plugins`、把 `modpacks/bpp/<任意子目录>` 同步到 `BepInEx/<同名目录>`。只写 `BepInEx/plugins` 会在下次启动被 modpack 覆盖回去。 - -### 1.6 签名凭据与启动器更新 ⭐ - -**Keystore**:`` -**格式**:PKCS12(文件头 `30 82 0A 8E 02 01 03`) -**storePassword**:`` -**keyPassword**:``(PKCS12 同值) -**alias**:`bpp`(`PrivateKeyEntry`,创建于 2026-10-21) -**证书**:`CN=BazaarPlusPlus, OU=Android, O=BPP, L=CN, ST=CN, C=CN` -**证书 SHA-256**:`F8:D5:CE:5D:85:2D:94:94:DA:8B:87:4E:CD:D0:98:28:57:BB:1B:8A:42:2D:B8:DB:9F:96:5B:84:FF:EB:A1:9C` - -> 2026-10-22 用 `keytool -list` 与 `apksigner sign` 双向实测通过。 - -**更新启动器的唯一入口**:`D:\thebarzaar\dist\package-launcher.ps1` - -```powershell -$env:JAVA_TOOL_OPTIONS = $null -$env:BPP_APK_STORE_PASSWORD = '' -$env:BPP_APK_KEY_PASSWORD = '' -& powershell -NoProfile -ExecutionPolicy Bypass -File D:\thebarzaar\dist\package-launcher.ps1 ` - -SourceApk 'D:\thebarzaar\dist\BepInExLauncher-android-fixed.apk' ` - -Destination 'D:\thebarzaar\dist\BepInExLauncher-android-updated.apk' -``` - -该脚本做 5 件事: -1. 复制 `-SourceApk` → `.unsigned.apk`; -2. 把 `assets/BepInEx.Android.zip` 里的 `core/Il2CppInterop.Runtime.dll` 换成 `D:\thebarzaar\safe_Il2CppInterop.Runtime.dll`; -3. 把 `lib/arm64-v8a/libe_sqlite3.so` 塞进 APK(**顺带解决 §四 P1-1 的 SQLite 不可用**); -4. 删除旧 `META-INF/*.SF|RSA|DSA|EC` 签名 → `zipalign -P 16`; -5. `apksigner sign --ks bpp.keystore --ks-pass env:BPP_APK_STORE_PASSWORD --ks-key-alias bpp` 并 `verify --print-certs`。 - -> ⚠️ **本仓库不保存任何凭据,口令已脱敏为 ``,原值见本地私有记录;密码从未落盘**。原 agent 只留了环境变量契约(`package-launcher.ps1` 第 56–58 行在变量为空时直接 `throw`)。密码 `` 是本次 2026-10-22 通过候选恢复实测得出,已固化到本节。 - -> ⚠️ **签名不一致的坑(务必先读 §四 P2-1)**:平板当前安装的启动器是 **debug 证书**签的,不是 `bpp.keystore`。用 `bpp.keystore` 签的新包**无法覆盖安装**。 - -### 1.7 启动 + 截图标准流程 - -```powershell -# 1) 冷启动 -& $adb shell "am force-stop com.bepinex.android" -& $adb shell "am force-stop com.tempogames.thebazaar" -& $adb shell "rm -f /sdcard/BepInEx_Android/com.tempogames.thebazaar/BepInEx/bpp-startup-trace.log" -& $adb shell "am start -n com.bepinex.android/.MainActivity" -Start-Sleep 4 - -# 2) **必须** uiautomator dump 找按钮,不要硬编码坐标 -& $adb shell "uiautomator dump /data/local/tmp/ui.xml" -& $adb pull /data/local/tmp/ui.xml D:\thebarzaar\ui.xml -# 依次按 text 匹配点击:'The Bazaar' → '启动'(如出现 '关闭' 弹窗先点掉) - -# 3) 等 ~42s 进入主界面,再截图 -& $adb shell "screencap -p /data/local/tmp/s.png" -& $adb pull /data/local/tmp/s.png D:\thebarzaar\s.png -``` - -> 已知踩坑:启动器首页有多个游戏卡片,**必须**用 `text="The Bazaar"` 定位再取其下面的 `启动` 按钮;有弹窗时先点 `关闭`。禁止用固定坐标点启动流程。 - ---- - -## 二、已完成的里程碑 - -| # | 里程碑 | 产物 / 证据 | -|---|---|---| -| 1 | Metadata v39 结构完全破解 | `HANDOVER.md` §二.3;`apk_extracted/global-metadata-v29.dat` | -| 2 | DummyDll + Il2CppInterop 代理生成 | `D:\thebarzaar\android-managed\` 共 **176 个 DLL** | -| 3 | `bazaarplusplus-mod` Android 编译通过 | `BazaarPlusPlus.dll` 4,160,000 B,`-p:BppAndroid=true` | -| 4 | 启动器 APK(NextBep 改造、去 PVZ 品牌) | `dist\BepInExLauncher-android-fixed.apk`(97,529,767 B) | -| 5 | 外置 modpack 打包 | `dist\bpp-modpack.zip`(**12 个 DLL** + `core\Il2CppInterop.Runtime.dll`) | -| 6 | 触屏 UI 入口 | `BppTouchEntry`:右上角 UGUI dock,`sortingOrder = 32000`,4 个按钮 + 三指点击兜底 | -| 7 | **配装面板** 可打开并渲染 | 中文 UI(`十胜推荐/十胜阵容/阵容库/切换阵容/赞助`)、4 排棋盘、赞助商列表 | -| 8 | **图鉴面板** 可打开并渲染 | `1850` 张卡牌、36 张高清立绘、完整筛选器(英雄/品质/尺寸/标签/类型/商人) | -| 9 | **历史面板** 可打开并渲染 | 11 个页签全中文(`对局/幽灵/收藏/瓦内莎/皮格马利翁/杜利/马克/朱尔斯/卡诺克/斯黛尔/双龙`) | -| 10 | 卡牌检视窗(锁定详情)可打开 | 放大卡牌 + 词条气泡(`加速`/`暴击率`)正常 | - ---- - -## 三、已定位并修复的崩溃/缺陷清单 ⭐ 最有价值部分 - -> 每一条都是**真实踩过并修好**的。接手后请勿回退这些改动,否则会重现 SIGSEGV / SIGABRT。 - -### 3.1 `Newtonsoft.Json` 托管版 vs IL2CPP 代理版冲突 → `SIGABRT` - -- **症状**:启动 ~0.3s 后在 `Class_FromIl2CppType_Hook.Hook:line 30` 抛 `NullReferenceException`,`Aborting process`。 -- **根因**:`BazaarPlusPlus` 用 NuGet 的纯托管 `Newtonsoft.Json`(723,368 B,`PublicKeyToken=30ad4fe6b2a6aeed`),但 `package-modpack.ps1` 把它排除了,运行时 CoreCLR 解析到 `BepInEx/interop/Newtonsoft.Json.dll`(1,489,920 B,IL2CPP 代理,`PublicKeyToken=null`)。`JsonConvert.DeserializeObject(string)` 对任何**纯托管 DTO**(`CollectionSourceCatalogDto`、`BuildRecommendationCorpus` 等)调用代理方法时,`Il2CppClassPointerStore.NativeClassPtr` 为 `0`,把 `null` `Il2CppType*` 喂给 `il2cpp_class_from_il2cpp_type` → 崩。 -- **修复**: - 1. `package-modpack.ps1` 把 `Newtonsoft.Json` 从 `$gameProvided` 排除名单中豁免,**托管版随 `plugins/` 一起发**; - 2. `Plugin.cs` 的 `static Plugin()` 里用 `AssemblyLoadContext.Default.LoadFromAssemblyPath` **预加载** `BepInEx/plugins/Newtonsoft.Json.dll`,并挂 `Resolving` + `AssemblyResolve` 双保险。 - -### 3.2 `safe_Il2CppInterop.Runtime.dll` 的三个补丁(**必须随包发**) - -文件:`D:\thebarzaar\safe_Il2CppInterop.Runtime.dll` -大小:`226,304 B` -SHA256:`39AB3DE276D528D84E06968D8DE6261E505357A93114F105228A6A6B9A77C4FE` - -部署位置:**同时**放在 `modpacks/bpp/core/`(applyModpack 每次启动覆盖 `BepInEx/core/`)和 `BepInEx/core/`。 - -| 补丁目标 | 原实现缺陷 | 补丁 | -|---|---|---| -| `Class_FromIl2CppType_Hook::Hook` | ① 未判 `type == null` 即解引用 `type->data`;② 判断 `(nint)type->data < 0`(Android 16 ARM64 Scudo Top-Byte-Ignore 堆指针 `0xb400...` 恒为负)成立后查 `s_InjectedClasses`,却把返回的 `bool` `pop` 掉、直接 `return 0` | 加 `if (type == null) return null;`;把 `pop` 换成 `brfalse.s Original(type, throwOnError)` | -| `Il2CppObjectBase::CreateGCHandle` / `get_Pointer` / `get_WasCollected` / `Finalize` | `myGcHandle == IntPtr.Zero` 时传给 `il2cpp_gchandle_get_target(0)` / `il2cpp_gchandle_free(0)`,Unity `libil2cpp.so` 不判 0,直接 `ldrb w8,[0x20]` → 空指针解引用 | `Zero` 时 `CreateGCHandle` 直接 `ret`;`get_Pointer` 返回 `IntPtr.Zero`;`get_WasCollected` 返回 `true`;`Finalize` 跳 `free` | -| `IL2CPP::il2cpp_object_unbox` | 传 `IntPtr.Zero` 时返回 `0 + 0x10`,下游 `Nullable::get_HasValue` 解引用 `0x10` → `SIGSEGV`(`fault addr 0x10`) | 改为托管包装:`ptr == 0` 时返回一块 `Marshal.AllocHGlobal(256)` 且每次 `initblk` 清零的缓冲区;否则转发 `il2cpp_object_unbox_native` | - -> 重新生成方式:改 `D:\thebarzaar\ilstool\Program.cs`(Mono.Cecil), -> `dotnet run --project ilstool.csproj -- <源dll> <目标dll>`。 - -### 3.3 `RectTransform.GetWorldCorners(Vector3[])` 在 IL2CPP 下**静默失效** - -- **症状**:所有依赖世界坐标的布局/命中/测量全部拿到全 `0`;`RowBoundsChanged` 永不触发、棋盘预览宽度为 0、卡牌检视窗 2 秒后被判"测不出尺寸"自动关闭、BPP 设置 dock 按钮报 `gear_footprint_unavailable`。 -- **根因**:托管 `Vector3[]` 传给 IL2CPP 方法时会被隐式**拷贝**成临时 `Il2CppStructArray`,Unity 填充完临时数组即丢弃,调用方数组纹丝不动。 -- **修复**:`Infrastructure/Il2CppCompat.cs` 的 `BppUnityCast` 增加 - ```csharp - public static void GetWorldCornersManaged(this RectTransform? rect, Vector3[]? four) - // Android: new Il2CppStructArray(4) → rect.GetWorldCorners(native) → 逐项拷回 - ``` - **全项目 17 处 `.GetWorldCorners(...)` 已全部迁移为 `.GetWorldCornersManaged(...)`**(`grep -n "GetWorldCorners(" 应只剩 0 处或仅剩包装内部那一处`)。新增代码请一律用 `*Managed`。 - -### 3.4 `foreach (Transform child in parent)` 在 IL2CPP 下抛 `InvalidCastException` - -- **症状**:`Unable to cast object of type 'Il2CppSystem.Object' to type 'UnityEngine.Transform'`。 -- **根因**:`Transform.GetEnumerator()` 返回 `IEnumerator`,`Current` 是 `Il2CppSystem.Object` 基类包装器,`foreach` 隐式强转 `(Transform)` 必然失败。 -- **修复**:全部改为 `for (var i = 0; i < parent.childCount; i++) { var c = parent.GetChild(i); ... }`。 - 已修:`BPPSupporterNativeAttributionRow.Bind`、`NativeCardCellFitter.FindDescendant`、`BppTooltipSections`、`NativePlayerPortraitBounds`。 -- ⚠️ 这一条直接造成了「配装第一次点开没数据 / 第二次点不开 / 从图鉴切配装弹回对局」——因为异常发生在 `LiveBuildPanelView.Refresh` → `BPPSupporterNativeAttributionRow.Bind`,打断了 `Open()`,面板没被 `SetVisible(true)`。 - -### 3.5 `Il2CppSystem.Nullable` 的 `default` 是 **null 引用**,不是空值 - -- **症状**:`Il2CppObjectBaseToPtrNotNull` 抛 `NullReferenceException`;卡牌立绘/棋盘卡牌全部空白。 -- **根因**:`Il2CppSystem.Nullable` 是 class(继承 `Il2CppSystem.ValueType` 但 `IsValueType == false`),`default(Il2CppSystem.Nullable)` 是 `null`。 -- **修复**:`ToNativeNullable(this T? v)` 的 else 分支返回 `new Il2CppSystem.Nullable()` 而**不是** `default`;`ToNativeGuid` 同理。 -- 同理:`NativeCardPrefabLoader` 里 `InstantiateAssetAsyncByReference(reference, default)` 必须写 `new Il2CppSystem.Nullable()`。 - -### 3.6 `InstanceId`(C# record struct 含 string)被 Il2CppInterop 生成成 **class** - -- **症状**:对局中点 `[配装 Builds]` 触发 `SIGSEGV code=2 (SEGV_ACCERR)`,`Cause: trying to execute non-executable memory`,`pc` 落在 `Dictionary.TryGetValue`(`dump.cs` RVA `0x64485AC`)。 -- **根因**:`InstanceId` 含 `string` 字段,IL2CPP 侧按引用类型布局存 `Il2CppObject*`;而 `Il2CppSystem.Collections.Generic.Dictionary.TryGetValue` 的生成代码用 `typeof(TKey).IsValueType` 决定是否 `il2cpp_object_unbox`。判断为 `false` 后直接把**已装箱对象头指针**当作结构体内容传给原生 `FindValue`,对象头首字段是 `.data` 段的 `Il2CppClass*` → 跳进不可执行内存。 -- **修复**:**绕开该字典**。 - - `LiveCardSnapshotReader.ReadShopItems` → 改用 `TheBazaar.Data.GetCard(string)`(原生 C++ 里查,不经过托管泛型字典); - - `EncounterStateProbe.ResolveTemplateId` → 同上; - - `ReadContainerItems` → 遍历 `container.Sockets`(`Il2CppReferenceArray`)+ `HashSet` 去重推导 socket 索引,绕开 `GetCardsAndSockets()` 返回的 `List>`。 -- ⚠️ 其它 `Dictionary` 的托管泛型调用同样危险,碰到就换成原生入口。 - -### 3.7 IL2CPP 包装器**只能向下 `TryCast`** 不能 C# 强转 - -- **症状**:`InvalidCastException: Unable to cast 'UnityEngine.Transform' to 'UnityEngine.RectTransform'` / `'Graphic' to 'Image'`。 -- **根因**:`Component.transform`、`Button.targetGraphic` 等属性返回的包装器**静态类型**是声明基类,即便底层原生对象是派生类。 -- **修复**:统一用 `BppUnityCast`: - - `t.AsRectTransform()` / `t.RequireRectTransform()` - - `g.AsImage()` / `g.AsTmpText()` - - `obj.AsIl2Cpp()`(替代 `is T` / `as T`) - - `GetComponent` 拿到的是 `Component` 基类包装器,需要 `.AsIl2Cpp()` 才能当 `CardPreviewBase` 用,否则 `IsInstanceOfType` 恒 false、反射 `Invoke` 抛 `TargetException`。 - -### 3.8 IL2CPP 字段是 **PropertyInfo** 不是 FieldInfo - -- **症状**:`AccessTools.Field(type, name)` 返回 `null`。 -- **修复**:`BppFieldAccessor.Find(type, name)` 在 Android 下先查 `AccessTools.Property`,并提供 `GetValue` / `GetReferenceArray` / `SetReferenceArray` / `SetValue`。 - -### 3.9 CoreCLR 主线程 `SynchronizationContext.Current` 为 `null` → `await` 续体跑到后台线程 - -- **症状**:`Graphics device is null`,随后 `SIGTRAP`(Unity 从 `.NET TP Worker` 调图形 API)。 -- **根因**:Unity 的 `UnitySynchronizationContext` 活在 IL2CPP 域,CoreCLR 域取不到;`async` 方法 `await` 后默认在 `TaskScheduler.Default` 续体执行。 -- **修复**:`GameInterop/BppCoroutines.cs` - - `InitializeMainThread()`:记录主线程 id 并 `SynchronizationContext.SetSynchronizationContext(SyncContext)`(在 `Plugin.Load()` 首行调用); - - `Update()` 里每帧重新 `SetSynchronizationContext`(防被覆盖)→ 排空 `MainThreadQueue` → 推进 `IEnumerator` → 推进 `Pollers`; - - `Il2CppCompat.AsManagedTask(this Il2CppSystem.Threading.Tasks.Task)` 和 `AsManagedTask(this Il2CppSystem.Threading.Tasks.Task)`:用 `BppCoroutines.PollOnMainThread` 轮询 `IsCompleted`,**保证结果在 UnityMain 上落 TCS**。 -- ⚠️ 绝不要再写 `while (!t.IsCompleted) await Task.Yield();`。 - -### 3.10 `BppGameObjectFactory.Create` 必须走 `GameObject(string, Il2CppReferenceArray)` - -- **症状**:`GetComponent()` 返回 `null`,随后 `Clear()` 里 `gameObject` 抛 `NullReferenceException`。 -- **根因**:`new GameObject(name)` 已内置一个 `Transform`;再 `AddComponent(Il2CppType.From(typeof(RectTransform)))` **不会**把它升级成 `RectTransform`,`GetComponent()` 得 `null`,对象被 parent 到根场景,切场景即销毁。 -- **修复**: - ```csharp - if (components.Length == 0) return new GameObject(name); - var types = new Il2CppReferenceArray(components.Length); - for (var i = 0; i < components.Length; i++) types[i] = Il2CppType.From(components[i]); - return new GameObject(name, types); - ``` - (空数组仍走无参构造,因为带类型数组的重载即便为空也会解引用 null class。) - -### 3.11 UITK `generateVisualContent` + `context.Allocate` 在 Android 上被 strip - -- **症状**:`MeshWriteData.SetNextVertex` / `SetNextIndex` 直接 `throw new NotSupportedException("Method unstripping failed")`,或 `NativeSlice.get_Length` 空指针。 -- **修复**:`CollectionPanelView` 中所有 `context.Allocate(...)` 分支加 `#if !BPP_ANDROID`,Android 用 USS 样式(背景色/边框/圆角)替代;`context.painter2D` 路径保留可用。 -- 涉及:`DrawControlsScrollShadow`、`DrawCollectionFilterCardBackground`、`DrawHeroGradient`、`DrawFacetMatchModeSegment`;图标 `DrawCloseIcon` / `DrawResetIcon` / `DrawSortIcon` 也用文字兜底。 - -### 3.12 排序层级在 Android 下必须整体抬高 - -`Infrastructure/UiTokens/BppOverlaySorting.cs`: - -| 常量 | 桌面 | Android | -|---|---|---| -| `PanelUiToolkit`(图鉴 UITK) | 26 | **2600** | -| `NativeCardPreview`(原生卡牌层) | 27 | **2601** | -| `PanelForeground`(面板前景) | 28 | **2602** | -| `InspectionBackdrop` | 1000 | **3000** | -| `InspectionControls` | 1001 | **3001** | -| `InspectionContent` | 1002 | **3002** | -| `InspectionVariantControls` | 1003 | **3003** | - -`BppTouchEntry` 的 Canvas 固定 `sortingOrder = 32000`(最高,永远可见)。 - -### 3.13 Harmony 补丁在 Android 下的返回类型适配 - -- `ref Task __result` 必须改成 `ref Il2CppSystem.Threading.Tasks.Task __result`,`Task.CompletedTask` 改成 `Il2CppSystem.Threading.Tasks.Task.CompletedTask`。 -- 已改:`NativeTooltipSuppressionPatches`(`ShowSecondaryCardTooltipController`)、`CombatReplayFinalizeRunInitializationPatch`;`CombatSimPatch` 在 Android 下退化为纯 Postfix 观测。 -- `CardPreviewBase.SetUp` 的 `CancellationToken` 参数在 Android 是 `Il2CppSystem.Threading.CancellationToken`,反射查 `AccessTools.Method` 的类型数组必须带 `#if BPP_ANDROID`。 - -### 3.14 `CollectionTierTooltipPatch` 改写 `List` 会破坏池 - -- **症状**:`NullReferenceException at TooltipPools.ReturnTooltipSegments` / `CardTooltipData.CompileNestedSegments`。 -- **根因**:`TooltipSegment` 是含 string 的 struct,同样被生成为 class;`List.set_Item` 把它当引用类型写入,破坏原生结构体数组。 -- **修复**:Android 下 `CollectionTierActiveTooltipPatch.Postfix` 直接 `return`(保留原生单阶描述,不做多阶合并)。 - ---- - -## 四、当前待办(用户最新反馈,按优先级) - -### P0-1 配装面板「当前商店选择里没有物品」 - -- **现象**:进入对局后点 `[配装 Builds]`,`商店物品` 行显示"当前商店选择里没有物品。",`箱子物品` 显示"箱子没有物品。",`当前阵容` 只有 2/20/4 三个数值但无卡牌。 -- **位置**:`GameInterop/LiveCards/LiveCardSnapshotReader.cs` - - `ReadShopItems`:取 `runState.SelectionSet`(`List`),对每个 entry 调 `TheBazaar.Data.GetCard(entry)`,再 `AsIl2Cpp()`。 - - `ReadContainerItems`:`inventory.AsIl2Cpp()?.Container` → 遍历 `container.Sockets`。 -- **待查方向**(按怀疑度排序): - 1. `Data.CurrentState.AsIl2Cpp()` 拿到的是否是 `null`(对局中 `CurrentState` 可能是别的 AppState 子类); - 2. `runState.SelectionSet` 的 entry 是否**不是** instance id 而是 template guid(`Data.GetCard` 查不到 → 返回 null); - 3. `run.Player.Hand` / `run.Player.Stash` 的 `CardContainer.Container` 是否为空(`Sockets` 全 null); - 4. `ItemCard` 判断是否被 `TCardInstanceItem` 取代(用 `AsIl2Cpp()` 试)。 -- **验证手段**:在 `Read()` 里临时加 `BppLog.InfoEvent`,打印 `run?.Player == null`、`runState == null`、`SelectionSet.Count`、`Sockets.Length`、首个 entry 的值。 - -### P0-2 配装面板看不到当前阵容里的物品图片 - -- **现象**:4 排棋盘(`十胜推荐` / `商店物品` / `箱子物品` / `当前阵容`)只显示蓝色金边地毯底图,无卡牌立绘。 -- **位置**:`Game/LiveBuildPanel/Preview/LiveBuildPreviewRenderer.cs` + `GameInterop/MonsterBoardPreview/OwnedMonsterBoardPreview.cs` -- **注意**:`GetWorldCornersManaged` 已修,`RowBoundsChanged` 现在应该能触发;需确认: - 1. `LiveBuildPanelView.RowBoundsChanged` → `LiveBuildPanel.SetBounds` → `_previewRenderer.SetBounds` 链路是否通; - 2. `OwnedMonsterBoardPreview.Replace` 里 `NativeCardPrefabLoader.RentInactiveAsync` 是否成功(曾有 `AssetLoader.LoadAssetAsyncByAddress not found`,已改为直接调用 `LoadAssetAsyncByAddress(address, AssetScope.Global)`); - 3. `NativeBoardCardRental.Prepare` 里的 `Card.SetUp(...)` 是否 await 完成(已改 `AsManagedTask`); - 4. `_view._carpetImage.transform` 作为 fallback parent 是否可用。 -- 日志关键字:`live_build_panel.card_preview.degraded`、`native_preview_unavailable`。 - -### P0-3 图鉴检视窗右侧被大遮罩挡住文字 - -- **现象**:放大卡牌左侧正常,右侧「造成 10 伤害 / 霜冻时:加速此物…」文本被一块半透明深色矩形盖住;左上角词条气泡(`加速`/`暴击率`)反而正常。 -- **遮罩左边界**:原图 x ≈ `3096 * 0.645 ≈ 2000`(预览图 2508 里的 1618),**与 `CollectionPanelView` 右侧控制栏左边界吻合**。 -- **待验证假设**(尚未定论,按 AGENTS.md 需先探针验证): - 1. `CardLockVariantPanel._panelRoot` 在 `NativeInspectionPresentation.PromoteVariantControls()` 里被 `lease.Promote(BppOverlaySorting.InspectionVariantControls /* 3003 */, detach: false)` 提升,若 `_panelRoot` 是一个覆盖右半屏的大 RectTransform 且自带深色背景,就会盖住 `InspectionContent`(3002) 的 tooltip 文本; - 2. 或者 tooltip 主描述其实挂在**第三个** canvas 上(不在 `LockModeCanvas` / `RootCanvasComponent` 之列),未被提升,仍留在 < 2600 被 UITK 盖住。 -- **建议验证**:临时在 `PromoteVariantControls` 里打印 `root.rect`、`root.GetComponent()`、`_canvases` 每个 canvas 的 `sortingOrder` 与 `renderMode`;再临时把 `InspectionVariantControls` 降到 `2600` 以下看遮罩是否消失。 -- **可能的修复方向**:只把 `_panelRoot` 内的 `Selectable`/`TMP_Dropdown` 提升,不提升 `_panelRoot` 本身;或把 `_panelRoot` 的背景 `Image` 设为 `enabled = false`。 - -### P1-1 SQLite 不可用(`RunLoggingModule` / `BundleSealCoordinator` 降级) - -- **日志**:`Unable to load shared library 'e_sqlite3' ... dlopen failed: library ".../plugins/libe_sqlite3.so" needed or dlopened by ".../libcoreclr.so" is not accessible for the namespace "clns-10"` -- **已查明**:`libe_sqlite3.so` **确实已在** `/sdcard/.../BepInEx/plugins/libe_sqlite3.so`(本机源:`bin\Debug\net6.0\runtimes\android-arm64\native\libe_sqlite3.so`,1,772,160 B),但 Android linker namespace `clns-10` **禁止**从 `/storage/emulated/0` 加载 `.so`。 -- **修复方向**:把 `libe_sqlite3.so` 打进 `BepInExLauncher` APK 的 `lib/arm64-v8a/`(与 `libcoreclr.so` 同目录),或在 `SqliteStoreBase` 里用绝对路径 + `NativeLibrary.Load`/`dlopen` 绕过默认探测。 -- 影响面:本地对局日志、Bundle 封包、History 面板的本地记录。 - -### P1-2 Harmony 补丁降级 10 个 - -`[Warning][Plugin] event=plugin.patches.degraded failed_patch_count=10 reason_code=patch_classes_failed` - -已知其中 3 个是**无法修**的(返回类型不可赋值): -- `CardPreviewItem::LoadArt` —— 返回 `Il2CppSystem.Threading.Tasks.Task`,patch 声明 `System.Threading.Tasks.Task`; -- `CardTooltipData::GetPassiveTooltipBlock` —— 返回 `Il2CppSystem.ValueTuple<...>`; -- `CardTooltipController::SetupLockVariantPanel` —— `CollectionLockVariantPanelPatch.Transpiler` 找不到唯一的 `IUpgradeableCard` `isinst` 守卫,抛 `"Native lock variant eligibility guard changed."`(Transpiler 在 Android 的 IL 上失效,需重写或禁用)。 - -其余 7 个需逐条看 `LogOutput.log` 的 `[Error][HarmonyX] Failed to patch ...` 行。 - -### P2-1 启动器签名不一致 ⚠️ 会阻断覆盖升级 - -**实测事实(2026-10-22 取证)**: - -| 对象 | 签名证书 DN | 证书 SHA-256 | -|---|---|---| -| 平板已装 `com.bepinex.android`(`versionCode=5` / `1.0.0-ci.5` / 2026-10-22 12:29:14) | `C=US, O=Android, CN=Android Debug` | `80D0E5389E158C59EB97B0C013E1AE52DF9C22727F7D505D53EC30BC5F0A6FD1` | -| `dist\BepInExLauncher-android-fixed.apk` | 同上(即平板装的就是它) | 同上 | -| `bpp.keystore` / `tools\launcher\launcher-bpp.apk` | `CN=BazaarPlusPlus, OU=Android, O=BPP, L=CN, ST=CN, C=CN` | `F8D5CE5D852D9494DA8B874ECDD0982857BB1B8A422DB8DB9F965B84FFEBA19C` | - -**结论**:平板当前装的是 **debug 证书**签的包;`bpp.keystore` 是 2026-10-21 新建的另一套密钥。 -用 `bpp.keystore` 签的新包**签名与已装包不一致 → `adb install -r` 会报 `INSTALL_FAILED_UPDATE_INCOMPATIBLE`**,用户必须卸载重装。 - -**两条可选路径**: - -1. **保留现有 debug 身份的覆盖升级**(不丢数据,推荐给当前测试机) - ```powershell - # 用 debug keystore 重新签名,签名一致即可覆盖 - # debug keystore 位置(AGP 自动生成): - # %USERPROFILE%\.android\debug.keystore alias=androiddebugkey storepass=android keypass=android - ``` - 或直接用 Gradle 的 `assembleDebug` 出包(自动 debug 签名)。 - -2. **切换到 BPP 自有签名**(正式交付形态,需用户卸载一次旧包) - ```powershell - $env:BPP_APK_STORE_PASSWORD = '' - & powershell -NoProfile -ExecutionPolicy Bypass -File D:\thebarzaar\dist\package-launcher.ps1 - adb uninstall com.bepinex.android # 会清掉 launcher 的配置(含已选 modpack) - adb install D:\thebarzaar\dist\BepInExLauncher-android-updated.apk - ``` - 卸载后需在 launcher 里**重新选择 `bpp` 模组包**并重授 Shizuku/存储权限。 - -**顺带解决**:`package-launcher.ps1` 第 43–45 行会把 `lib/arm64-v8a/libe_sqlite3.so` 写进 APK,同时修掉 §四 P1-1 的 SQLite 不可用。 - -**其它过期内容**:两个 APK 内部 `assets/BepInEx.Android.zip` 的 `Il2CppInterop.Runtime.dll` 仍是旧的 `nohook` 版;当前靠 `modpacks/bpp/core/` 每次启动覆盖兜底,走一次 `package-launcher.ps1` 即彻底修掉。 - -### P2-2 `dist/README.md` 待更新 - -仍是 2026-10-21 23:59 的内容,未反映 §三 的 14 条修复与 §四 的待办。其第 17 行「覆盖安装即可,签名相同」在 §四 P2-1 的实测下**已不成立**,需改写。 - ---- - -## 五、关键代码地图(改动集中区) - -``` -src/BazaarPlusPlus/ -├─ Plugin.cs # static Plugin() 预加载 Newtonsoft;Load() 首行 InitializeMainThread -├─ Infrastructure/ -│ ├─ Il2CppCompat.cs # ⭐ BppUnityCast(AsRectTransform/RequireRectTransform/AsImage/AsTmpText/AsIl2Cpp/GetWorldCornersManaged) + BppFieldAccessor + ToManagedNullable/ToNativeNullable/AsManagedTask -│ └─ UiTokens/BppOverlaySorting.cs # ⭐ Android 下排序常量放大(26→2600, 1000→3000) -├─ GameInterop/ -│ ├─ BppCoroutines.cs # ⭐ MainThreadSyncContext + PollOnMainThread + IEnumerator 驱动 -│ ├─ BppGameObjectFactory.cs # ⭐ new GameObject(name, Il2CppReferenceArray);GetComponent 走 TryCast -│ ├─ BppTouchEntry.cs # 右上角 UGUI dock(配装/图鉴/历史/BPP),sortingOrder 32000 -│ ├─ AssetLoading/NativeGlobalAssetLoader.cs # Android 直调 LoadAssetAsyncByAddress/ByReference(AssetScope.Global).AsManagedTask() -│ ├─ AssetLoading/NativeCardPrefabLoader.cs # Android 直调 InstantiateAssetAsyncByReference -│ ├─ CardPreview/NativeCardPreviewArtworkMeasurement.cs # TryMeasure 用 GetWorldCornersManaged -│ ├─ CardPreview/NativeCardPreviewReflection.cs # SetUpMethod 参数类型按平台分支 -│ ├─ CardPreview/NativeCardPreviewRuntime.cs # InvokeSetUpSafe 直调 previewBase.SetUp(...).AsManagedTask() -│ ├─ LiveCards/LiveCardSnapshotReader.cs # ⭐ 待办 P0-1/P0-2 核心 -│ ├─ MonsterBoardPreview/OwnedMonsterBoardPreview*.cs # 棋盘卡牌渲染(待办 P0-2) -│ ├─ Tooltips/NativeInspectionPresentation.cs # ⭐ 待办 P0-3 核心(CanvasLease/PromoteVariantControls) -│ ├─ Encounter/EncounterStateProbe.cs # ResolveTemplateId 改 Data.GetCard -│ ├─ HeroPortraits/NativePlayerPortraitBounds.cs -│ └─ Fonts/NativeGameTypography.cs # Android 字体兜底(NotoFontFallbackRuntime / OS sans-serif) -├─ Game/ -│ ├─ CollectionPanel/ # 图鉴:CollectionPanel/View/Grid/Virtualizer/Tooltips -│ ├─ LiveBuildPanel/ # 配装:LiveBuildPanel/View/Preview/Renderer/Recommendations -│ ├─ HistoryPanel/ # 历史 -│ ├─ Supporters/Ui/BPPSupporterNativeAttributionRow.cs # ⭐ 3.4 的 foreach 修复点 -│ └─ Settings/ # BPP 设置 dock -└─ Patches/ - ├─ CollectionPanel/CollectionTierTooltipPatch.cs # Android 下 return(3.14) - ├─ Tooltips/NativeTooltipSuppressionPatches.cs # Task → Il2CppSystem...Task - └─ Combat/*.cs # 同上 -``` - ---- - -## 六、踩坑速查表(写新代码前必读) - -| ❌ 禁止 | ✅ 必须 | -|---|---| -| `(RectTransform)t` / `t as RectTransform` | `t.RequireRectTransform()` / `t.AsRectTransform()` | -| `g is Image` / `(Image)g` | `g.AsImage()` | -| `obj is Foo` / `obj as Foo` | `obj.AsIl2Cpp()` | -| `AccessTools.Field(t, n)` | `BppFieldAccessor.Find(t, n)` | -| `rect.GetWorldCorners(arr)` | `rect.GetWorldCornersManaged(arr)` | -| `foreach (Transform c in parent)` | `for (i) parent.GetChild(i)` | -| `x.HasValue`(`Il2CppSystem.Nullable`) | `x.ToManagedNullable()` 后再判 | -| `SomeNullable = default` | `new Il2CppSystem.Nullable()` | -| `while (!t.IsCompleted) await Task.Yield();` | `.AsManagedTask()` | -| `new GameObject(n); go.AddComponent(RectTransform);` | `BppGameObjectFactory.Create(n, typeof(RectTransform), ...)` | -| `Dictionary.TryGetValue` | `TheBazaar.Data.GetCard(string)` 等原生入口 | -| `context.Allocate(...)`(UITK,Android) | USS 样式 | -| `ref Task __result` | `ref Il2CppSystem.Threading.Tasks.Task __result` | -| 固定坐标 `input tap` 点启动流程 | `uiautomator dump` 按 `text=` 定位 | - ---- - -## 七、给接手 Agent 的建议顺序 - -1. **先跑通基线**:按 §1.4 编译一次,确认 0 error;按 §1.6 启动,确认 `plugin.initialization.succeeded` 且 `com.bepinex.android:game` 存活 60s 不掉。 -2. **P0-1**:在 `LiveCardSnapshotReader.Read()` 加临时探针日志,把 `runState`/`SelectionSet`/`Sockets` 的真实值打出来(这一步不做等于盲猜)。 -3. **P0-2**:依赖 P0-1 的数据先能读出来,再看 `LiveBuildPreviewRenderer` 是否拿到卡牌。两者很可能是同一个根因。 -4. **P0-3**:先打探针确认遮罩属于哪个 canvas(§四 P0-3 的验证手段),再决定是"不提升 `_panelRoot`"还是"隐藏其背景 Image"。 -5. **P1-1**:`libe_sqlite3.so` 塞进 APK `lib/arm64-v8a/`,这一步独立、收益明确(History 面板才有本地数据)。 -6. **最后**才处理 P1-2 / P2,然后更新 `dist/README.md` 并重打 `bpp-modpack.zip` + `BepInExLauncher-android-fixed.apk`。 - -> 每次改动后请按 §1.5 双写推送,并删 `bpp-startup-trace.log` 后冷启动验证,不要只看编译通过。 diff --git a/android-port/HANDOVER-CURRENT-20261023.md b/android-port/HANDOVER-CURRENT-20261023.md deleted file mode 100644 index 169b3ba..0000000 --- a/android-port/HANDOVER-CURRENT-20261023.md +++ /dev/null @@ -1,252 +0,0 @@ -# BazaarPlusPlus 安卓移植 — 交接文档(当前状态) - -> 生成:2026-10-23 23:40 (+08:00);**更新:2026-10-24 11:00**(编译阻断清零,三模块与回放终态按真机验收闭合) -> 读者:接手 Agent。本文是最小可用上下文,读完即可动手。 -> 详细背景见同目录 `HANDOVER-ANDROID-PORT.md`(505 行,含 14 条 IL2CPP 崩溃根因,**不要回退那些修复**)。 -> 逐轮实测记录见同目录 `ACCEPTANCE-ROUND1-20261024.md`(本文与之冲突时以它为准)。 - ---- - -## 0. 一句话现状 - -三个模块(配装 / 图鉴 / 历史)的修复已落盘,并已**真机验收通过**(Round 6 全部通过,见 `ACCEPTANCE-ROUND1-20261024.md` §12);源码**编译 0 error**。 -剩下的是交付物一致性:`dist/bpp-modpack.zip` 已于 10-24 09:51 重打包,但 `SHA256SUMS.txt` 还停在 02:03,**必须重跑并重新核对**(见 §10)。 - -| 项目 | 状态 | -|---|---| -| 源码 | ✅ 三模块 + 图鉴检视修复齐备(最新提交 `dcd7189`) | -| 编译 | ✅ **0 error**(warning 数待核,最近记录 95) | -| `dist/bpp-modpack.zip` | ⚠️ 10-24 09:51 产物(`BazaarPlusPlus.dll` 4,274,688 B),**晚于** `SHA256SUMS.txt` 的 02:03 版,清单待重跑 | -| 真机 | ✅ 三面板 + 回放终态均已验收;本轮日志 `_r8_LogOutput.log`(10-24 10:55) | -| Git 仓库 | ✅ 干净,`TAP-APIA/bazaarplusplus-android`,6 个提交 | - ---- - -## 1. ✅ 已完成:编译阻断已清零(原 `ConcealMobileTrayBackdrops` 未定义) - -**现状**:源码编译 **0 error**,已无 CS0103 阻断;本节从「阻断项」移入已完成清单。 - -| 事项 | 结果 | 证据 | -|---|---|---| -| `ConcealMobileTrayBackdrops`(CS0103) | ✅ 已解除 | `c75c12a` 补上实现(+39 行,复用 `ConcealMobileDecoration` 登记,`Dispose` 时还原) | -| 检视窗遮罩方案 | ✅ 已被 `dcd7189` 整体替换 | 改为**保留**游戏原生抽屉与托盘背景,只在抽屉 rect 上自绘一块不透明底板;`ConcealMobileTrayBackdrops` / `ConcealMobileDecoration` 方法族随该提交删除 | - -> ⚠️ 接手注意:现在在源码里搜 `ConcealMobileTrayBackdrops` **搜不到是正常的**——方法已随 `dcd7189` 删除,不是又丢了。不要再按旧文档「补实现」,否则会与抽屉方案打架;当前实现见 §6.2。 - ---- - -## 2. 构建 / 部署 / 打包 - -```powershell -$env:DOTNET_ROLL_FORWARD="Major" -& C:\Users\administrator\.dotnet\dotnet.exe build ` - "D:\thebarzaar\BazaarPlusPlus\bazaarplusplus-mod\src\BazaarPlusPlus\BazaarPlusPlus.csproj" ` - -c Debug -p:BppAndroid=true -p:ManagedPath=D:\thebarzaar\android-managed ` - -p:NuGetAudit=false -p:TreatWarningsAsErrors=false --nologo -``` - -- 部署:`D:\thebarzaar\dist\install-to-device.ps1`(**必须双写** `BepInEx/plugins` 与 `modpacks/bpp/plugins`,否则启动时被 modpack 覆盖) -- 打包:`dist\package-modpack.ps1 -Zip` -- 启动器:`dist\package-launcher.ps1` -- 打包/改 `dist` 后**必须**重跑 `SHA256SUMS.txt`(当前 02:03 版早于 09:51 的 modpack,仍待重跑,见 §10) - -**签名**:平板现装 Debug 证书。覆盖升级必须 -`-KeyStore "$env:USERPROFILE\.android\debug.keystore" -KeyAlias androiddebugkey` -用 `tools/launcher/bpp.keystore` 会 `INSTALL_FAILED_UPDATE_INCOMPATIBLE`。 - ---- - -## 3. 设备与 adb - -- 设备:vivo PA2573 平板,Android 16,无线调试。本轮地址 `192.168.0.14:37699`(**端口会变**,`adb mdns services` 常为空,不能据此判断设备离线) -- adb 真实路径(PATH 里没有 adb,别直接敲 `adb`): - `D:\thebarzaar\tools\android-build\sdk\platform-tools\adb.exe` - 备用:`D:\thebarzaar\tools\platform-tools\platform-tools\adb.exe` -- 启动器包 `com.bepinex.android`,游戏进程 `com.bepinex.android:game` -- 锁屏 PIN:`` - -**启动流程定位用 `uiautomator dump` 按 `text=` 找元素,禁止硬编码坐标。** - ---- - -## 4. 🖼️ MCP 读图:唯一正确用法(今天踩坑最多) - -`user-vps-image` MCP 可用,`send_image_to_vps` 上传成功。**真正容易错的是拿到 URL 之后怎么用。** - -正确链路(三步): - -1. `send_image_to_vps(path="D:\...\shot.png")` → 得到 `https://:8443/f/` -2. 把该 URL **原样**作为 `image_url` 放进请求 -3. 请求发给 **VPS BYOK**:`https://:8443/v1/chat/completions` - - 模型:`gemini-3.5-flash`(VPS 共 73 个模型,视觉选它稳定) - - `gemini-3.1-pro` **无权限**,会报 `Publisher model ... was not found` - - VPS 侧车会把 `/f` URL 自动改写成 base64 再转发上游 - -**绝对禁止(MCP 文档明确列出的错误做法,我全部踩过)**: - -- ❌ 本机下载 URL 再转 base64 -- ❌ 把 URL 发给 `codex-router` / 本地 `/v1/chat/completions` -- ❌ 塞给非视觉模型(如 `ollama-native-deepseek-v4-1-flash-1017`,VPS 不认识该名字,报 `model_not_found`) -- ❌ 以为 `Read(本地路径)` 就等于上游能看见图 - -**Windows 实操要点**: - -- PowerShell 5.1 不支持 `-SkipCertificateCheck`;用 `curl.exe -k` 最省事 -- 用 `curl.exe --data-binary @req.bin -o resp.bin` 走**字节**,再用 `[Text.Encoding]::UTF8.GetString()` 解析,避免中文变 `ÐлÑ` -- `max_tokens` 给 2500+,800 会被截断 - -已验证可用的一次调用: - -```powershell -$token = [IO.File]::ReadAllText("").Trim() -$payload = '{"model":"gemini-3.5-flash","max_tokens":2500,"stream":false,"messages":[{"role":"user","content":[{"type":"text","text":"<中文提问>"},{"type":"image_url","image_url":{"url":"<上一步的 /f URL>"}}]}]}' -[IO.File]::WriteAllBytes("req.bin", [Text.Encoding]::UTF8.GetBytes($payload)) -curl.exe -s -S -X POST "https://:8443/v1/chat/completions" ` - -H "Authorization: Bearer $token" -H "Content-Type: application/json; charset=utf-8" ` - --data-binary "@req.bin" -k -o resp.bin --max-time 170 -``` - -**读图必须配客观量化**:视觉模型对同一张图会给出互相矛盾的结论(实测一次说「32 张纯白」、一次说「正常占位槽」)。 -所以对「白块 / 遮挡 / 缺失」这类判断题,**先做像素统计或裁切放大,再让模型判读局部放大图**,不要只信整图描述。 - ---- - -## 5. 🔍 图鉴白块:诊断结论已更正 - -> ⚠️ **本节结论已被 Round 1 推翻,仅作历史记录**:同一构建下历史棋盘卡与放大卡立绘全部正常,冷启动后 124 卡零白块、`card_art.degraded=0`,说明 catalog / 材质 / 着色器 / 纹理压缩均健康。真实成因是**久运行 + 反复开关面板后的缓存与失败黑名单退化**(`CollectionCardArtCache` 的 LRU + `_failedKeys` 永久黑名单,4 条静默 `return` 不写日志)。以下「排查方向」**不要**再按资源管线查;加固项见 §6.2 与 `ACCEPTANCE-ROUND1-20261024.md` §3。 - -**旧结论(错误)**:遮罩层把卡牌盖住了 → 方向是 UI 层级 / alpha。 - -**新结论(有证据)**:**卡牌立绘纹理加载失败,底板白色露出**。 - -证据链: - -1. 像素统计:卡牌网格区纯白占比 **47%–54%**(`white-check.png` 54.2%,`cur-2331.png` 47.2%) -2. 2× 放大单格判读:格子内部**完全纯白,无画、无图标、无文字**;金属边框、倒角高光、底部宝石徽章**全部渲染正常** -3. 关键细节:**白色矩形溢出金属边框之外**(边框外侧露出白边)→ 说明是降级默认底板被拉伸,并非按格裁切 -4. 代码注释直接对应症状: - -```startLine:34:38:filepath -// Returns null on load failure; the caller proceeds without a material assignment, which -// matches the game's own behaviour for invalid art keys (blank face, frame still drawn). -``` - -`src/BazaarPlusPlus/Game/CollectionPanel/Grid/CollectionCardArtCache.cs` 在 Addressables 失败时返回 `null`,调用方跳过材质赋值 → 只剩白底板 + 边框。 - -**排查方向(按可能性排序)**: - -1. **Addressables catalog 未在 Android 上加载**(打包未含 catalog / 路径不对) -2. **artKey 大小写不匹配** — Windows 不敏感、Android 敏感,这是移动端移植第一坑 -3. **纹理压缩格式不兼容**(ASTC/ETC2 解码失败 → 采样白) - -**验证入口**:日志事件 `collection_panel.card_art.degraded` 带 `reason_code`(取值 `AddressablesLoadFailed` / `AddressablesLoadException`)。 -当前设备 logcat 缓冲区已被冲掉(只剩 16:37 前记录),**需重启游戏复现后再抓**。 - ---- - -## 6. 三模块状态与下一步 - -### 6.1 配装 / Live Build(十胜阵容)—— ✅ 已修好,真机实测通过 - -- 现状:**已修好**。真机实测**阵容库 5,689 套**,对局中**切换阵容 `1 / 277`**(匹配成功),**十胜率 100%**(依据 `ACCEPTANCE-ROUND1-20261024.md` §12.2,截图 `_r6_builds.png`) -- 本轮日志复证:`live_build_panel.corpus.ready source=cache build_count=5689` -- 真实根因(旧文档的「远程 404」是误判): - - 代码真正用的是 `bpp-metrics-v6.bazaarplusplus.com/builds/latest.json`,**返回 200 但只有 3 套、仅 Dooley**;旧文档写的 `cdn.bazaarplusplus.com` 主机整站不存在(404) - - `TenWinBuildCatalogFactory` 的 `CacheDuration=20h` 且按**缓存文件写入时间**判陈旧 → 永不刷新 → 一直服务那 3 套 - - `LiveBuildPanel.Open()` 开头的 `_candidateState.Clear()` 让候选为空 → `FindRecommendations` 直接返回空 → 面板显示「0 / 0」 -- 已落地的修法: - - 新增 `FallbackRemoteCatalogSource`:多源按**密度择优**(≥64 套且 ≥4 英雄),命中 legacy `bpp-metrics.bazaarplusplus.com`(5,689 套 / 8 英雄 / 1,123 卡,线格式与 v6 兼容) - - `TenWinBuildCatalogFactory`:`RemoteUrl` → `RemoteUrls[]`(v6 优先、legacy 兜底)、超时 10s → 30s、`CacheDuration` 20h → **1h** - - `LiveBuildPanel.SeedCandidatesFromBoard()`:用场上物品预置候选,消除「点开就是 0/0」 -- 相关代码:`Core/Game/LiveBuildPanel/Recommendations/BuildRecommendationRepository.cs`、`TenWinBuildCorpus.cs`、`FallbackRemoteCatalogSource.cs`;`src/BazaarPlusPlus/Data/BuildRecommendations/builds.json` 只是内嵌兜底(1 套假 GUID),**不要**当语料用 - -### 6.2 图鉴 / Collection - -- **方案 A 已落地**(提交 `dcd7189`「inspect collection cards in the native mobile drawer」),三段式布局: - - **左半屏**:BPP 自绘的放大卡(`NativeInspectionPresentation` 的 root canvas,`ScreenSpaceOverlay`,`sorting_order=3002`) - - **右半屏**:复用游戏自带的 Mobile Lock Mode **原生抽屉**(`Scroll View`),保留其 `CanvasScaler`、viewport mask、滚动与描述布局;BPP 只抬排序并把抽屉吸附到原生 fade-in 的 show 位置,`Release` 时还原 - - **不透明底板**:原生抽屉自带的 `lockModeBackgroundImage` 会被禁用(否则压暗放大卡),禁用后图鉴筛选列会透过描述显示,因此在抽屉 rect 上自绘 `DrawerBackdrop` 补一块不透明底板(`raycastTarget=false`,不吃点击) -- 运行时证据:`collection_panel.inspection.android_drawer render_mode=ScreenSpaceOverlay override_sorting=false sorting_order=3002 left=2111 width=985` -- 白块:Round 1 已推翻「资源管线」旧结论(同构建下历史棋盘卡与放大卡立绘全正常);根因是久运行 + 反复开关面板后的缓存/黑名单退化,冷启动即恢复。`card_art.degraded` 全程 0。**加固项仍未落地,属隐患**:`_failedKeys` 加 TTL、4 条静默 `return` 补 `ReportDegraded`、`_cardImage` 实为 `RawImage` 需同步清 `texture`(详见 `ACCEPTANCE-ROUND1-20261024.md` §3.4 / §十.3) -- 相关文件:`Game/CollectionPanel/**`、`GameInterop/Tooltips/NativeInspectionPresentation.cs`、`Patches/CollectionPanel/CollectionTierTooltipPreview.cs` - -### 6.3 历史 / History & Replay —— ✅ 回放终态已闭合 - -- 已完成(**不要回退**):bootstrap2→6 回放链修复;血条 NRE(`HealthBarController.ForceEmptyHealthVisual` 读未 `Init` 的 `HealthBarControl`)已真机确认修复,`ForceEmptyHealthVisual` / `NullReferenceException` / `Fatal signal` 计数均为 0 -- **「回放只有 `playback.started`」的缺口今天已由真机验证闭合**(`_r8_LogOutput.log`,battle_id=00f38840): - -``` -[Info :BazaarPlusPlus] [BPP][CombatReplay] event=combat_replay.playback.started battle_id=00f38840 source=local_saved record_video=false -[Info :BazaarPlusPlus] [BPP][CombatReplay] event=combat_replay.playback.ended_observed native_recording=false managed_recording=false recap_action_bound=true handled=false battle_id=00f38840 -[Info :BazaarPlusPlus] [BPP][CombatReplay] event=combat_replay.playback.succeeded battle_id=00f38840 source=local_saved end_reason_code=saved_replay_exit duration_ms=165101 reason_code=none degradation_count=0 rollback_status=not_required -``` - -**结论(已验证,不再是「待查」)**: - -1. **不是日志机制坏了**。终态事件由 **`ReplayState` 退出**驱动,`ReplayPlaybackLogOperation.Complete()` 只在回放真正结束后才发。 -2. `ended_observed` 里 `recap_action_bound=true`、`handled=false`(判读:recap 动作已绑定到原生按钮,但托管 handler 没有消费它,实际由原生路径退出回放)→ 随后 `ReplayState` 退出 → `succeeded` 落地。 -3. `OnNativeReplayEnded` 首行 `if (!currentNativeRecording && !managedRecordedReplay) return;` 依然会短路(本局 `source=local_saved`、`record_video=false`),但它**不参与**终态事件,不影响闭合。 - -**验收步骤(必须照做,否则会误判成「只有 started」)**: - -1. 历史 → 选一局 → 播放; -2. **等回放自己走到 recap**(`BoardManager.ShowRecapView`); -3. **点 recap 上的「继续」**(`BoardRecapReplayButtonsController.Show` 的 Harmony Postfix 绑定;坐标只从 `overlay_panels.ui_raycast.rect` 的 `center` 取,别用截图估); -4. 回到历史后立刻抓日志,应同时出现 `playback.started` → `playback.ended_observed` → `playback.succeeded`。本局 `duration_ms=165101`(约 2 分 45 秒),**别提前收工**。 - -此前验收停在「播完」、没点继续,所以才只看到 `playback.started`——这轮就是这么闭合的。 - -- 未证明:血条**数值正确性**(截图有绿条和数字,但 OCR 未读出可靠数值,只能说「渲染了」) -- 另:同一会话内第二次进入回放未触发 `playback.started`,**待查**(本轮日志仍只有一次 `playback.started`) - ---- - -## 7. 写代码前必读(IL2CPP 硬约束) - -强转一律 `AsIl2Cpp()` / `AsRectTransform()` / `AsImage()`;字段用 `BppFieldAccessor`;世界坐标用 `GetWorldCornersManaged`。 - -- `foreach (Transform child in parent)` → `InvalidCastException`,改 `GetChild(i)` -- `Il2CppSystem.Nullable` 的 `default` 是 null,必须 `new` -- 异步必须 `.AsManagedTask()`,禁止 `while (!t.IsCompleted) await Task.Yield()` -- `Dictionary` 托管泛型调用会 SIGSEGV,改走 `TheBazaar.Data.GetCard` 等原生入口 -- Harmony 降级 10 个:3 个确认不可修(`LoadArt` / `GetPassiveTooltipBlock` / `SetupLockVariantPanel` Transpiler),其余 7 个看 `LogOutput.log` 的 `Failed to patch` -- ⚠️ `sub_logoutput.log` 里 4 条 `Cannot assign method return type Il2CppSystem.Threading.Tasks.Task` 是 **10-22 12:12 旧证据**,早于 `#if BPP_ANDROID` 改造,别按它改回去 - ---- - -## 8. 验收流程(主线程负责) - -1. 构建 0 error(✅ 已达成;warning 数按需记录) -2. 重新打包 modpack + 重跑 `SHA256SUMS.txt`(⚠️ 未完成,见 §10) -3. `install-to-device.ps1` **只推 modpack**(不要重装 APK,避免动到内部数据目录里的回放文件) -4. 冷启动,确认 `plugin.initialization.succeeded`,进程活过 60 秒 -5. 白块:冷启动下已不复现(`collection_panel.card_art.degraded` 全程 0,说明命中的是 4 条**不写日志**的静默 `return`)。要复现得**久运行 + 反复开关面板**,再抓 `card_art.degraded` 与 `card.bind_degraded`;加固项见 §6.2 -6. 逐面板截图 → `send_image_to_vps` → VPS BYOK `gemini-3.5-flash` 读图 → **配像素统计交叉验证** -7. 回放:历史 → 选局 → 播放 → **等 recap 出现并点「继续」** → 确认 `playback.started` + `playback.ended_observed` + `playback.succeeded|degraded` 三条齐全(✅ 已达成,见 §6.3) - ---- - -## 9. 文档地图 - -| 文件 | 作用 | -|---|---| -| `HANDOVER-CURRENT-20261023.md` | 本文,最小交接(敏感信息已脱敏) | -| `HANDOVER-ANDROID-PORT.md` | 主文档:环境、14 条崩溃修复、踩坑表、代码地图 | -| `HANDOVER.md` | 2026-10-21 初始任务书 + metadata v39 逆向结论 | -| `ACCEPTANCE-ROUND1-20261024.md` | 第 1 轮逐项验收记录(§3 白块、§8 十胜 5,689、§12 Round 6 全通过)——**冲突时以它为准** | -| `dist/README.md` | 交付与安装说明(2026-10-24 版,签名说明已按 P2-1 更正) | - ---- - -## 10. 交付物核对 - -| 文件 | 时间 | 状态 | -|---|---|---| -| `dist/BepInExLauncher-android-updated.apk` | 10-23 14:20 | ✅ bootstrap4 交付版,平板已装;签名 `CN=Android Debug`,SHA-256 `80379CA3BF211233…`,与 `SHA256SUMS.txt` 第 1 项一致 | -| `dist/bpp-modpack.zip` | 10-24 09:51 | ⚠️ **需重新核对**:内含 `BazaarPlusPlus.dll` 4,274,688 B @ 09:51(晚于验收时的 4,231,680 B @ 00:14);当前 SHA-256 `AB91137F5B1C3FCE…`,`SHA256SUMS.txt` 记的是 `29917398A24F1631…` | -| `dist/SHA256SUMS.txt` | 10-24 02:03 | ⚠️ **需重跑**:早于 09:51 的 modpack。逐项自校验 **4/6 一致**,不一致的两项正是 `bpp-modpack.zip` 与 `dist/README.md`(本文档一改,第 6 项必然变) | - -> 打包 / 改 `dist` 后**必须**重跑 `SHA256SUMS.txt` 并自校验。 - -Git:`D:\thebarzaar\repo-publish\bazaarplusplus-android` → `https://github.com/TAP-APIA/bazaarplusplus-android`(public,master 已保护:禁强推、禁删除) -工作区源码在 `D:\thebarzaar\BazaarPlusPlus\bazaarplusplus-mod\`,**publish 仓库是快照,不是工作副本**。 diff --git a/android-port/HANDOVER.md b/android-port/HANDOVER.md deleted file mode 100644 index 045787c..0000000 --- a/android-port/HANDOVER.md +++ /dev/null @@ -1,83 +0,0 @@ -# BazaarPlusPlus 安卓端移植工作交接文档 (HANDOVER) - -## 一、 当前工作区文件与环境状态 (`D:\thebarzaar`) - -1. **原始安装包与核心提取文件**: - - `D:\thebarzaar\TheBazaar.apk`:原版安卓安装包(2.83 GB,包名 `com.tempogames.thebazaar`,版本 `1.0.12825-production-android-d9601ded`,引擎 **Unity `6000.3.11f1`**,仅 `arm64-v8a` IL2CPP)。 - - `D:\thebarzaar\apk_extracted\`(已从 APK 解压出的核心二进制文件,无需重复解压 2.83 GB APK): - - `global-metadata.dat`(22,057,156 字节,Magic `0xFAB11BAF`,**Metadata Version `39`**) - - `global-metadata-v29.dat`(由 `tools/convert_metadata_v39_to_v29.py` 转换出的 v29 格式元数据) - - `libil2cpp.so`(148,673,008 字节,ARM64,保留全部 241 个标准 `il2cpp_*` 导出符号) - - `libmain.so`(6,696 字节) - - `libunity.so`(25,155,632 字节) - - `AndroidManifest.xml`(21,692 字节) -2. **源码仓库与编译环境**: - - `D:\thebarzaar\BazaarPlusPlus\`:已完整检出 `BazaarPlusPlus/BazaarPlusPlus` 仓库(已开启 `git config core.longpaths true` 解决 macOS bundle 路径过长问题)。 - - `D:\thebarzaar\BazaarPlusPlus\bazaarplusplus-mod\global.json`:已将 SDK 版本策略调整为 `"8.0.100"` + `"rollForward": "latestMajor"`。 - - **已安装 .NET 8 SDK (`8.0.426`)**:位于 `C:\Users\administrator\.dotnet\dotnet.exe`(系统 `C:\Program Files\dotnet` 仅有 Runtime 无 SDK,编译时请使用 `C:\Users\administrator\.dotnet\dotnet.exe` 或将其加入 `PATH`)。 -3. **逆向与转换工具 (`D:\thebarzaar\tools\`)**: - - `D:\thebarzaar\tools\convert_metadata_v39_to_v29.py`:Unity `6000.3.11f1` Metadata v39 → v29 结构转换脚本。 - - `D:\thebarzaar\tools\Il2CppDumper\Il2CppDumper.exe`:已下载解压(需设置环境变量 `$env:DOTNET_ROLL_FORWARD="Major"` 运行)。 - ---- - -## 二、 已完成的关键逆向与技术发现(直接复用,无需重查) - -### 1. APK 安全性与符号完整性 -* **无加壳、无反作弊、无签名校验**:`classes.dex` 中仅有 `com.tempogames.thebazaar.R` 与 `com.tempogames.networksecurity.R` 两个资源类,无任何自定义 Java 校验代码。 -* **网络安全配置 (`res/8G.xml`)**:仅信任 ``,无 SSL Pinning。 -* **代码同源度 100%**:`BazaarPlusPlus` 引用的 **109 个游戏类与 37 个核心被 Patch 方法在安卓版 `global-metadata.dat` 中 100% 存在**,且安卓版 `1.0.12825` 已原生包含 `TReferenceValueUniqueCardCount`(无需触发 `CompatibleUniqueCardCount` 的 `Reflection.Emit` 分支)。 - -### 2. `libil2cpp.so` 核心注册表虚拟地址(VA)与文件偏移 -* **ELF `PT_LOAD` 映射关系**: - - Segment 0: `file 0x0..0x36cefc4` → `VA 0x0` - - Segment 1: `file 0x36cefd0..0x83147d0` → `VA 0x36d2fd0` - - Segment 2: `file 0x83147d0..0x891efb8` → `VA 0x831c7d0` - - Segment 3: `file 0x891efb8..0x8dc87e8` → `VA 0x892afb8` -* **`Il2CppCodeRegistration`**: - - **Virtual Address (VA)**:`0x831cb30`(文件偏移 `0x8314b30`) - - 包含 `codeGenModulesCount = 145`(`VA 0x831cba8`),`genericMethodPointersCount = 227801`,`invokerPointersCount = 41350`,`unresolvedVirtualCallCount = 7713`。 -* **`Il2CppMetadataRegistration`**: - - **Virtual Address (VA)**:`0x86994d8`(文件偏移 `0x86914d8`) - - 包含 `genericClassesCount = 31471`,`genericInstsCount = 25308`,`genericMethodTableCount = 228453`,`typesCount = 84983`(`types` 数组指针 `VA 0x87246f8`),`methodSpecsCount = 271407`,`fieldOffsetsCount = 24657`,`typeDefinitionsSizesCount = 24657`。 - -### 3. `global-metadata.dat` Version 39 精确二进制结构(已完全破解) -Unity `6000.3.11f1` 的 Metadata v39 相比 v29 的完整结构差异如下: -1. **文件头(Header,共 380 字节)**:`magic (4B = 0xFAB11BAF)` + `version (4B = 39)` + **31 组 `(offset:i32, size:i32, count:i32)` 三元组**(v29 为 31 组 `(offset, size)` 二元组,共 256 字节)。 -2. **变长索引结构差异(仅以下 5 张表与 v29 不同,其余 26 张表字节布局完全一致)**: - - **Section 5 `methods` (32B)**:格式为 `()` 注册 31 个自定义 `MonoBehaviour` 并补齐 `(IntPtr)` 构造。 - - 重写 2 处 `[HarmonyTranspiler]`(`CollectionLockVariantPanelPatch.cs` 与 `VOPlayerPatches.cs`)。 - - 替换 2 处 `___fieldName` Harmony 字段注入(`HistoryPanelMenuPatches.cs`、`PostCombatImpactRecapPatch.cs`)为属性访问,并将 31 处 `AccessTools.Field` 兼容为属性读取。 - - 适配 4 个异步补丁文件中的 `Il2CppSystem.Threading.Tasks.Task` 返回类型。 - - 将 `BepInExPathProvider.cs` 数据根目录改为 `Application.persistentDataPath/BazaarPlusPlusV6`。 - -3. **步骤 3:移动端触屏交互适配** - - 将 6 个文件中的 `Mouse.current` / `Keyboard.current` 封装为兼容 `Pointer.current` / `Touchscreen.current`。 - - 为 `LiveBuildPanel`(原 `CapsLock`)、`UpgradePreview`(原 `Shift`)、`PostCombatImpact`(原 `Shift`)补齐触屏按钮/点击切换入口。 - - 一期先在 `CombatReplayRecordingGate.cs` 中将安卓端的本地 MP4 视频录制置为不可用(保留完整的游戏内实时战斗回放与 Ghost 对战重播)。 - -4. **步骤 4:制作增量 APK 修补脚本与外置插件包** - - 注入 `arm64-v8a` 版 `BepInEx.Unity.IL2CPP` 引导层 (`libdoorstop.so`) 到 `libmain.so`,配置从 `/sdcard/Android/data/com.tempogames.thebazaar/files/BepInEx/plugins/` 加载 `BazaarPlusPlus.dll`,并用 `apksigner` 签名输出可直装 APK。 diff --git a/android-port/README.md b/android-port/README.md deleted file mode 100644 index 0b872a1..0000000 --- a/android-port/README.md +++ /dev/null @@ -1,190 +0,0 @@ -# BazaarPlusPlus Android 一体化预览版 - -一个 APK 同时包含 BepInEx Launcher、.NET / BepInEx 运行环境、Android SQLite 和 BPP 模组包。 -安装后首次打开会自动部署或更新,不再需要单独下载 `bpp-modpack.zip`、解压或用电脑 ADB 推送。 -游戏本体仍需自行安装,本应用不修改游戏 APK。 - - - -游戏窗口允许左右两种横屏方向随设备转动切换;BPP 启动器首页保持自身方向策略。 - -## 安装与更新 - -1. 下载 `BepInExLauncher-bpp-android.apk`。 -2. 在同一台设备上覆盖安装;vivo 若提示同版本,选择“重新安装”。 - ```powershell - adb -s <设备ID> install -r .\BepInExLauncher-bpp-android.apk - ``` -3. 打开 **BPP Android**。首次启动会自动解包运行环境并部署内置模组;进度完成后点击 - **启动 The Bazaar(BPP 模组)**。 -4. 更新时直接覆盖安装新 APK。不要卸载、不要清除应用数据;`adb install -r` 会保留应用数据。 - 若出现 `INSTALL_FAILED_UPDATE_INCOMPATIBLE`,说明新 APK 的签名与设备上已安装版本不同: - 停止更新,先备份,不能靠卸载绕过。 -5. 旧版本遗留的 `BepInEx/config`、`modpacks/bpp/config`、`BazaarPlusPlusV6` 历史库和入口位置 - 会继续沿用;新版本只更新插件与修补运行时。 - -安装后的主界面提供: - -- **启动 The Bazaar(BPP 模组)**:自动确保内置模组已就绪后启动游戏。 -- **重新校验 / 修复模组**:重新校验全部内置文件;损坏或缺失时自动恢复。游戏进程运行时 - 会先停止 `:game` 进程再修复。 -- **打开原版高级启动器**:保留原 BepInEx Launcher 的模组管理、日志等高级功能。 -- **首次启动**:游戏画面会灰几分钟,这是在生成模组文件,不是卡死。进度直接画在游戏窗口上 - (阶段、已用时、interop / Unity 基础库文件数),不是另一个对话框。通知会让游戏进程保持前台, - 请不要划掉通知,也不要切回启动器。 -- **导出诊断日志**:打一个 zip,保存到系统「下载」,并打开系统分享面板。包内有设备与屏幕信息、 - 启动器和游戏包版本、签名证书 SHA-256、libil2cpp 大小/哈希/ELF 对齐、内置模组部署状态、 - BepInEx / Unity / BPP 日志、logcat、ApplicationExitInfo(含 `:game`)和启动器配置。 - 打开启动器就会开始滚动记录 logcat;灰屏或闪退后回到本页再导出,即可带上这次启动。 - 读不到的路径记在 `manifest.txt`,不会让启动器崩溃。不含对局历史数据库、录像和签名私钥。 - 不新增权限:logcat 只能读到本应用自己的缓冲区,写入「下载」走 Android 10 及以上的 MediaStore。 -- **去 GitHub 反馈**:先按同样流程导出诊断 zip 到系统「下载」,然后打开本仓库的 GitHub 新建 issue 页面, - 自动填入中文模板(设备、启动器/内置版本、ABI、诊断包文件名)。需要你手动把「下载」文件夹里的 zip - 拖到页面正文上传;应用不会自动上传任何文件,标题、正文和 URL 只使用 zip 文件名,不写绝对路径、IP 或令牌。 -- **检查启动器更新**:一体化首页每次新建时自动检查本仓库的 GitHub Release,也可手动重试。 - 包含 `android-v` 标签的预览版,仅提示带有已上传 `BepInExLauncher-bpp-android.apk` 的新版; - 按版本数字比较,不按发布日期或字符串排序。检查最近 100 个 Release,草稿和无安装包版本忽略。 - 发现新版后可在 App 内下载 APK,并显示进度;下载由系统服务继续执行,退出首页或重启启动器后仍可查看。 - 完成后点击安装,首次需在系统设置中允许 BPP 安装应用,返回后再次点击安装;系统安装界面仍需用户确认。 - 安装前核对 APK 大小、包名和版本,签名兼容性由系统安装器验证。失败可重试或打开 GitHub 下载页;不会静默安装或替换上游资源。 - 网络失败或 GitHub 限流会显示检查失败,不会阻止启动游戏,也不会误报为“已是最新版”。 - 此功能需先安装包含更新检查的新 APK,已发布的 preview.37 不会自动获得该能力。 - -更新检查回归测试:`python android-port/tools/bpp-launcher/test_launcher_update.py`。 -下载状态与安装包校验回归测试:`python android-port/tools/bpp-launcher/test_apk_download.py`。 -设置 `JAVA_HOME` 指向 JDK 17+;首次运行下载并校验固定 SHA-256 的 `org.json` JVM 测试依赖, -不将此依赖打入 APK(Android 自带 JSON 实现)。加 `--live` 可另做真实 GitHub 连通性检查。 - -## 部署目录 - -```text -/sdcard/Android/data/com.bepinex.android/files/BepInEx_Android/com.tempogames.thebazaar/ - modpacks/bpp/modpack.json - modpacks/bpp/plugins/ ← 内置 BPP 插件与依赖 - modpacks/bpp/core/ ← 修补的 Il2CppInterop Runtime / HarmonySupport - modpacks/bpp/config/ ← 只新增或补齐,不改用户配置 - modpacks/bpp/logs/ - BepInEx/plugins/ ← 自动同步的当前运行插件 - BepInEx/core/ ← 自动同步的当前运行核心 - BepInEx/config/ ← 用户配置,更新时保留 - BepInEx/LogOutput.log -``` - -旧启动器若使用共享存储目录,升级到本 APK 后仍以应用专属目录为准;请先备份旧目录。 - -## 数据安全边界 - -内置安装器只拥有以下文件: - -- `modpacks/bpp/modpack.json`:首次创建;已有合法文件时只更新 `modCount`,保留 `mods` 等用户字段。 -- 清单中列出的 `plugins/**` 与 `core/**` 文件:写入 `modpacks/bpp/` 和 `BepInEx/` 各一份。 -- 更新时只删除上一版清单拥有、且内容仍与上一版哈希一致的文件;用户改过或第三方文件不动。 -- `.cfg` 只做缺失补齐和已有配置同步,不覆盖已有内容;`BazaarPlusPlusV6` 历史库不读取、不写入、不删除。 - -整个安装先解压到私有暂存目录并逐文件校验大小与 SHA-256,全部通过后才写入目标位置; -每个文件使用临时文件 + 原子替换。安装完成标记只有在校验全部通过后写入;中途失败会保持 -“未完成”状态,下次打开或修复时重试,且不会启动游戏。进程内锁和文件锁防止重复安装。 - -## 使用说明 - -- 触屏入口为深色金边竖排 BPP / 配装 / 图鉴 / 历史。长按 BPP 后拖动可移动整条入口,位置随 - `BepInEx/config/BazaarPlusPlus.cfg` 保存。任一 BPP 面板打开时入口隐藏,关闭后恢复。 -- 浮动入口底部的“字号”按钮循环切换面板文字与控件大小:100% / 150% / 200% / 250%。 - 关闭面板后调整,再打开即可查看。 - 偏好保存在同一配置的 `[OverlayUI] ScalePercent`,重启和覆盖更新后保留;只影响 BPP 图鉴、 - 历史和配装面板,不改游戏本体、原生卡牌说明或字幕已有的字号设置。 -- 超大字号下,配装页的赞助名单可独立上下滑动,关闭、更新阵容库和翻页按钮保持可见。 -- 启动器的可滚动内容避让状态栏、导航栏和屏幕开孔;横竖屏切换后重新读取系统安全边距。 -- 游戏进程通过 Android UI 线程单独隐藏系统栏并延伸到屏幕开孔区域,启动器仍保留状态栏避让。 - Pad 上已验证 Unity 渲染面达到物理显示的 2800×1968,系统栏手势后也能恢复。 -- 应用图标使用《大巴扎》徽标的白底版本,自适应图标与旧版方形/圆形图标一并替换。 -- UI 默认跟随游戏语言,游戏未保存语言时回落系统语言。可在 `[Localization] UiLanguage` - 强制 `Chinese` / `English` / `German` / `Portuguese` / `Korean` / `Italian`。 -- 图鉴使用原生右侧说明抽屉;Pad 上已验证卡牌名称、标签、技能说明及品质/附魔切换后的更新。 - 返回键先关闭检视,再关闭图鉴,不退出游戏。 -- 十胜阵容页点击更新应成功;无进行中对局时推荐为 0/0,不等于阵容库下载失败。 -- 日志:上述目录的 `BepInEx/LogOutput.log`。正常启动包含 - `plugin.initialization.succeeded`、`plugin.android.tls.registered` 和 - `live_build_panel.corpus.ready` / `recovered`。 - -## 从源码构建 - -前置条件: - -- JDK 17(Android Studio 自带 JBR 可用)、Android SDK Build-Tools、`android.jar`; -- Python 3.11; -- .NET SDK; -- 与游戏版本匹配的 Android IL2CPP 代理程序集目录; -- 已验证的基线启动器 `dist/app-bpp-fixed.apk`,以及修补后的 - `safe_Il2CppInterop.Runtime.dll`、`safe_Il2CppInterop.HarmonySupport.dll`。 - -先编译 Android 插件: - -```powershell -dotnet build .\bazaarplusplus-mod\src\BazaarPlusPlus\BazaarPlusPlus.csproj -c Debug ` - -p:BppAndroid=true -p:ManagedPath= ` - -p:NuGetAudit=false -p:TreatWarningsAsErrors=false -``` - -再生成一体化 APK: - -```powershell -powershell -NoProfile -ExecutionPolicy Bypass -File .\android-port\package-launcher.ps1 -VersionCode <递增版本号> -``` - -脚本会依次调用 `package-modpack.ps1` 生成最新模组包、编译并运行安装器与 manifest 单元测试、 -生成 `classes3.dex`、重写二进制 manifest、嵌入模组清单与 ZIP、进行 16 KB 对齐和同证书签名, -最后逐项校验基线 native 库、原有 DEX 与资源表未改动,资源差异仅限允许替换的图标 PNG。 - -- `-ModpackZip` 可指定现成 ZIP,跳过重新打包。 -- `-KeyStore` / `-KeyAlias` 可改用正式签名;默认使用 - `%USERPROFILE%\.android\debug.keystore` 的 `androiddebugkey`。 -- `-VersionCode` 每次发布必须递增;默认 `44`,版本名 `6.0.0-preview.44` - (preview.43 是 `43`,preview.42 是 `42`)。默认输出 - `dist/BepInExLauncher-bpp-android.apk`。 -- `-UnsignedOnly` 只生成对齐后的未签名 APK。 - -发布时只需上传 APK、本说明和 SHA-256;不要再附带单独的模组 ZIP 或 ADB 部署脚本。 - -## 上游官方插件包(实验) - -`upstream-host/` 让本启动器直接运行上游 BazaarPlusPlus 官方发布的 Android 托管插件包,并由启动器自动下载、 -校验、安装官方新版本,不再逐次手工移植。打包时给 `package-launcher.ps1` 加 `-Upstream`;工作方式、构建与真机 -待验收事项见 [upstream-host/README.md](upstream-host/README.md)。验收通过前默认仍打包本仓库原插件。 - -## 不要修改 libpine - -`lib/arm64-v8a/libpine.so` 的 `Pine_init0` 若被改成直接 `ret`,会使 `Pine.arch` 未初始化, -在 `ClassLoaderHooks.installHooks` 报 `Unexpected arch 0`,游戏无法进入 Unity。 -一体化 APK 保留原始 native 库;打包脚本也会拒绝 `Pine_init0 == ret` 的基线。 - -## 当前验证与限制 - -平板(vivo iPA2375 / Android 15)从早期版本一路覆盖安装到 `6.0.0-preview.30`,全程未卸载、 -未清除应用数据:`BepInEx/config/BazaarPlusPlus.cfg` 与 `modpacks/bpp/config/BazaarPlusPlus.cfg` -哈希一致,`modpack.json` 的 `createdAt` 保留;字号档位循环测试后配置字节未变化。 - -已在 Pad 实机验证: -- 游戏渲染面铺满 `2800×1968`,系统栏手势后恢复;启动器仍避让状态栏。 -- 图鉴右侧使用游戏原生说明抽屉,卡名、标签、技能文本正常;品质与附魔切换会同步更新大图与说明。 -- 系统返回键先关闭卡牌检视,再关闭面板(图鉴/历史/配装均验证),不退出游戏。 -- 字号档位 100% / 150% / 200% / 250%;配装空地毯不随字号缩小,左栏可滚动,切换字号并重开面板后 - 右侧关闭、更新、翻页控件仍可见。 -- 进行中对局里配装面板可打开并读到真实对局数据(候选匹配显示 `1 / 277`)。 - -当前工作区 Android 纯行为测试 284/284、默认条件纯行为测试 274/274;安装器 Java 测试覆盖首次安装、升级、 -配置/历史/第三方文件保留、损坏修复、路径穿越/未列出条目/哈希不符拒绝、未完成状态重试; -manifest 测试覆盖启动 Activity 迁移、原高级界面保留和版本号;打包脚本内置 APK 完整性校验。 - -本版新增但**尚未完成实机验收**的候选修复: -- 图鉴偶发白图:共享材质不再在面板关闭前被中途销毁,检视大图改用图鉴美术缓存。 -- 图鉴左侧大图随字号档位继续放大(上限受左栏可用空间约束)。 -- 对局中点击物品打开左侧大图检视,可查看等级与附魔,返回键退出。 -- 触控 Dock 的“配装”按钮在战斗中不再被拦截(键盘路径已验证,触控路径待复测)。 - -仍未完整验收:上传/账号链接/Ghost 在线同步/MP4 录制/回放重复进入;Android 回放自动清理仍关闭。 -同卡牌刚关闭后立即再次点击可能遇到空 tooltip,可先切换另一张卡。 -大元组返回值的 Harmony detour 在 ARM64 会崩溃,相关增强保持停用。 -完整桌面架构门禁仍受桌面产物与游戏程序集限制。 -问题与证据:;一体化安装见 。 - diff --git a/android-port/assets/icon/adaptive-foreground-hdpi.png b/android-port/assets/icon/adaptive-foreground-hdpi.png deleted file mode 100644 index fa784dc..0000000 Binary files a/android-port/assets/icon/adaptive-foreground-hdpi.png and /dev/null differ diff --git a/android-port/assets/icon/adaptive-foreground-mdpi.png b/android-port/assets/icon/adaptive-foreground-mdpi.png deleted file mode 100644 index 8d88421..0000000 Binary files a/android-port/assets/icon/adaptive-foreground-mdpi.png and /dev/null differ diff --git a/android-port/assets/icon/adaptive-foreground-xhdpi.png b/android-port/assets/icon/adaptive-foreground-xhdpi.png deleted file mode 100644 index f56a09c..0000000 Binary files a/android-port/assets/icon/adaptive-foreground-xhdpi.png and /dev/null differ diff --git a/android-port/assets/icon/adaptive-foreground-xxhdpi.png b/android-port/assets/icon/adaptive-foreground-xxhdpi.png deleted file mode 100644 index fcd5e05..0000000 Binary files a/android-port/assets/icon/adaptive-foreground-xxhdpi.png and /dev/null differ diff --git a/android-port/assets/icon/adaptive-foreground-xxxhdpi.png b/android-port/assets/icon/adaptive-foreground-xxxhdpi.png deleted file mode 100644 index 5a4b77f..0000000 Binary files a/android-port/assets/icon/adaptive-foreground-xxxhdpi.png and /dev/null differ diff --git a/android-port/assets/icon/bazaar-icon-192.png b/android-port/assets/icon/bazaar-icon-192.png deleted file mode 100644 index a2cbffa..0000000 Binary files a/android-port/assets/icon/bazaar-icon-192.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-round-hdpi.png b/android-port/assets/icon/legacy-round-hdpi.png deleted file mode 100644 index 66f0f1f..0000000 Binary files a/android-port/assets/icon/legacy-round-hdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-round-mdpi.png b/android-port/assets/icon/legacy-round-mdpi.png deleted file mode 100644 index 7914a83..0000000 Binary files a/android-port/assets/icon/legacy-round-mdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-round-xhdpi.png b/android-port/assets/icon/legacy-round-xhdpi.png deleted file mode 100644 index 7a3d345..0000000 Binary files a/android-port/assets/icon/legacy-round-xhdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-round-xxhdpi.png b/android-port/assets/icon/legacy-round-xxhdpi.png deleted file mode 100644 index b941568..0000000 Binary files a/android-port/assets/icon/legacy-round-xxhdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-round-xxxhdpi.png b/android-port/assets/icon/legacy-round-xxxhdpi.png deleted file mode 100644 index 48b36e0..0000000 Binary files a/android-port/assets/icon/legacy-round-xxxhdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-square-hdpi.png b/android-port/assets/icon/legacy-square-hdpi.png deleted file mode 100644 index 759b686..0000000 Binary files a/android-port/assets/icon/legacy-square-hdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-square-mdpi.png b/android-port/assets/icon/legacy-square-mdpi.png deleted file mode 100644 index 2e117fa..0000000 Binary files a/android-port/assets/icon/legacy-square-mdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-square-xhdpi.png b/android-port/assets/icon/legacy-square-xhdpi.png deleted file mode 100644 index adb3e73..0000000 Binary files a/android-port/assets/icon/legacy-square-xhdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-square-xxhdpi.png b/android-port/assets/icon/legacy-square-xxhdpi.png deleted file mode 100644 index afca50d..0000000 Binary files a/android-port/assets/icon/legacy-square-xxhdpi.png and /dev/null differ diff --git a/android-port/assets/icon/legacy-square-xxxhdpi.png b/android-port/assets/icon/legacy-square-xxxhdpi.png deleted file mode 100644 index aa83636..0000000 Binary files a/android-port/assets/icon/legacy-square-xxxhdpi.png and /dev/null differ diff --git a/android-port/ilstool/Program.cs b/android-port/ilstool/Program.cs deleted file mode 100644 index d1312e2..0000000 --- a/android-port/ilstool/Program.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using Mono.Cecil; -using Mono.Cecil.Cil; - -var src = args[0]; -var dst = args[1]; -File.Copy(src, dst, true); -using (var mod = ModuleDefinition.ReadModule(dst, new ReaderParameters { ReadWrite = true })) -{ - var il2cpp = mod.GetTypes().First(t => t.Name == "IL2CPP"); - var unbox = il2cpp.Methods.First(m => m.Name == "il2cpp_object_unbox"); - - if (unbox.IsPInvokeImpl) - { - // 1. Create native P/Invoke clone - var nativeUnbox = new MethodDefinition( - "il2cpp_object_unbox_native", - MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.PInvokeImpl, - mod.TypeSystem.IntPtr - ); - nativeUnbox.ImplAttributes = unbox.ImplAttributes; - nativeUnbox.PInvokeInfo = new PInvokeInfo( - unbox.PInvokeInfo.Attributes, - "il2cpp_object_unbox", - unbox.PInvokeInfo.Module - ); - nativeUnbox.Parameters.Add(new ParameterDefinition("obj", ParameterAttributes.None, mod.TypeSystem.IntPtr)); - il2cpp.Methods.Add(nativeUnbox); - - // 2. Add static field s_ZeroUnboxBuffer - var zeroBufField = new FieldDefinition( - "s_ZeroUnboxBuffer", - FieldAttributes.Private | FieldAttributes.Static, - mod.TypeSystem.IntPtr - ); - il2cpp.Fields.Add(zeroBufField); - - // 3. Convert il2cpp_object_unbox to managed wrapper - unbox.PInvokeInfo = null; - unbox.IsPInvokeImpl = false; - unbox.IsPreserveSig = false; - unbox.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; - unbox.Body = new MethodBody(unbox); - - var allocHGlobal = mod.ImportReference( - typeof(Marshal).GetMethod("AllocHGlobal", new[] { typeof(int) }) - ); - - var il = unbox.Body.GetILProcessor(); - var isZero = il.Create(OpCodes.Ldsfld, zeroBufField); - var clearBuf = il.Create(OpCodes.Ldsfld, zeroBufField); - - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Brfalse_S, isZero); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Call, nativeUnbox); - il.Emit(OpCodes.Ret); - - il.Append(isZero); - il.Emit(OpCodes.Brtrue_S, clearBuf); - il.Emit(OpCodes.Ldc_I4, 256); - il.Emit(OpCodes.Call, allocHGlobal); - il.Emit(OpCodes.Stsfld, zeroBufField); - - il.Append(clearBuf); - il.Emit(OpCodes.Ldc_I4_0); - il.Emit(OpCodes.Ldc_I4, 256); - il.Emit(OpCodes.Initblk); - il.Emit(OpCodes.Ldsfld, zeroBufField); - il.Emit(OpCodes.Ret); - } - - mod.Write(); -} - -using (var v = ModuleDefinition.ReadModule(dst)) -{ - var il2cpp = v.GetTypes().First(t => t.Name == "IL2CPP"); - var m = il2cpp.Methods.First(x => x.Name == "il2cpp_object_unbox"); - Console.WriteLine($"=== {m.FullName} ==="); - foreach (var ins in m.Body.Instructions) Console.WriteLine(" " + ins); -} diff --git a/android-port/ilstool/ilstool.csproj b/android-port/ilstool/ilstool.csproj deleted file mode 100644 index 38d71c2..0000000 --- a/android-port/ilstool/ilstool.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - Exe - net6.0 - disable - ilstool - ilstool - C:\Users\administrator\.nuget\packages - - - - - diff --git a/android-port/package-launcher.ps1 b/android-port/package-launcher.ps1 deleted file mode 100644 index c1b3015..0000000 --- a/android-port/package-launcher.ps1 +++ /dev/null @@ -1,399 +0,0 @@ -param( - [string]$SourceApk = (Join-Path $PSScriptRoot '../dist/app-bpp-fixed.apk'), - [string]$Destination = (Join-Path $PSScriptRoot '../dist/BepInExLauncher-bpp-android.apk'), - [string]$ModpackZip = '', - [string]$BuildOutput = '', - [string]$InteropSnapshot = (Join-Path $PSScriptRoot '../android-managed'), - [string]$SafeRuntime = (Join-Path $PSScriptRoot '../safe_Il2CppInterop.Runtime.dll'), - [string]$SafeHarmony = (Join-Path $PSScriptRoot '../safe_Il2CppInterop.HarmonySupport.dll'), - [string]$KeyStore = '', - [string]$KeyAlias = 'androiddebugkey', - [int]$VersionCode = 44, - [string]$AndroidSdkRoot = $env:ANDROID_SDK_ROOT, - [switch]$UnsignedOnly, - # Bundle upstream's Android Host behind the BepInEx bridge (upstream-host/README.md). - [switch]$Upstream -) - -# Builds the self-deploying BazaarPlusPlus Android APK by combining the verified -# BepInEx Android launcher with the packaged BPP modpack, manifest inventory, and -# BppLauncherActivity. Preserves all original native libraries (.so) and DEX files. - -$ErrorActionPreference = 'Stop' - -if ([string]::IsNullOrWhiteSpace($env:JAVA_HOME)) { - $studioJbr = 'C:\Program Files\Android\Android Studio\jbr' - if (Test-Path -LiteralPath "$studioJbr\bin\java.exe") { - $env:JAVA_HOME = $studioJbr - } -} -$java = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME 'bin/java.exe' } else { (Get-Command java).Source } -$javac = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME 'bin/javac.exe' } else { (Get-Command javac).Source } - -$sdkRoot = if ($AndroidSdkRoot) { $AndroidSdkRoot } else { "$env:LOCALAPPDATA\Android\Sdk" } -$buildToolsDir = Get-ChildItem -LiteralPath "$sdkRoot\build-tools" -Directory | - Sort-Object Name -Descending | - Select-Object -First 1 -ExpandProperty FullName -$platformJar = Get-ChildItem -LiteralPath "$sdkRoot\platforms" -Directory | - Sort-Object Name -Descending | - ForEach-Object { Join-Path $_.FullName 'android.jar' } | - Where-Object { Test-Path -LiteralPath $_ } | - Select-Object -First 1 - -if (-not $buildToolsDir -or -not (Test-Path -LiteralPath $platformJar)) { - throw "Android SDK build-tools or android.jar not found under $sdkRoot" -} - -foreach ($requiredPath in @($SourceApk, $SafeRuntime, $SafeHarmony)) { - if (-not (Test-Path -LiteralPath $requiredPath -PathType Leaf)) { - throw "Required build input not found: $requiredPath" - } -} -if ([IO.Path]::GetFullPath($SourceApk) -eq [IO.Path]::GetFullPath($Destination)) { - throw 'SourceApk and Destination must differ.' -} -if ($VersionCode -lt 2) { - throw 'VersionCode must be at least 2 for a self-deploying APK that can overwrite the original launcher.' -} - -$versionFile = Join-Path $PSScriptRoot '../VERSION' -$productVersion = if (Test-Path -LiteralPath $versionFile) { - (Get-Content -LiteralPath $versionFile -Raw).Trim() -} else { - '6.0.0' -} -# Monotonic Android versioning for the self-deploying launcher. Bump this for every published APK; -# install -r refuses a lower versionCode and users must not uninstall (that wipes local history). -# preview.43 shipped 43, next 44 / 6.0.0-preview.44. -$versionCode = $VersionCode -$versionName = "$productVersion-preview.$versionCode" - -$launcherToolsDir = Join-Path $PSScriptRoot 'tools/bpp-launcher' -$workRoot = Join-Path ([IO.Path]::GetTempPath()) ('bpp-apk-build-' + [guid]::NewGuid()) -New-Item -ItemType Directory -Force -Path $workRoot | Out-Null - -try { - # 0. Build a fresh modpack from the current Android build unless one was supplied. - if ([string]::IsNullOrWhiteSpace($ModpackZip)) { - $modpackDir = Join-Path $workRoot 'bpp-modpack' - & (Join-Path $PSScriptRoot 'package-modpack.ps1') ` - -BuildOutput $BuildOutput ` - -Destination $modpackDir ` - -LauncherApk $SourceApk ` - -InteropSnapshot $InteropSnapshot ` - -SafeRuntime $SafeRuntime ` - -SafeHarmony $SafeHarmony ` - -Upstream:$Upstream ` - -Zip - if ($LASTEXITCODE -ne 0) { throw 'package-modpack.ps1 failed' } - $ModpackZip = "$modpackDir.zip" - } - if (-not (Test-Path -LiteralPath $ModpackZip -PathType Leaf)) { - throw "Modpack archive not found: $ModpackZip" - } - - # 1. Run pure-Java installer unit tests and manifest patcher tests before packaging - $testClasses = Join-Path $workRoot 'test-classes' - New-Item -ItemType Directory -Force -Path $testClasses | Out-Null - & $javac -encoding UTF-8 --release 17 -d $testClasses ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppBundledModpackInstaller.java') ` - (Join-Path $launcherToolsDir 'test/com/bepinex/android/bpp/BppBundledModpackInstallerTests.java') - if ($LASTEXITCODE -ne 0) { throw 'BppBundledModpackInstaller test compilation failed' } - & $java -cp $testClasses com.bepinex.android.bpp.BppBundledModpackInstallerTests - if ($LASTEXITCODE -ne 0) { throw 'BppBundledModpackInstaller unit tests failed' } - - & $javac -encoding UTF-8 --release 17 -d $testClasses ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppDiagnosticBundle.java') ` - (Join-Path $launcherToolsDir 'test/com/bepinex/android/bpp/BppDiagnosticBundleTests.java') - if ($LASTEXITCODE -ne 0) { throw 'BppDiagnosticBundle test compilation failed' } - & $java -cp $testClasses com.bepinex.android.bpp.BppDiagnosticBundleTests - if ($LASTEXITCODE -ne 0) { throw 'BppDiagnosticBundle unit tests failed' } - - & $javac -encoding UTF-8 --release 17 -d $testClasses ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppGithubFeedback.java') ` - (Join-Path $launcherToolsDir 'test/com/bepinex/android/bpp/BppGithubFeedbackTests.java') - if ($LASTEXITCODE -ne 0) { throw 'BppGithubFeedback test compilation failed' } - & $java -cp $testClasses com.bepinex.android.bpp.BppGithubFeedbackTests - if ($LASTEXITCODE -ne 0) { throw 'BppGithubFeedback unit tests failed' } - - & python (Join-Path $launcherToolsDir 'test_patch_manifest.py') ([IO.Path]::GetFullPath($SourceApk)) - if ($LASTEXITCODE -ne 0) { throw 'AndroidManifest patcher tests failed' } - - & python (Join-Path $launcherToolsDir 'test_game_window.py') - if ($LASTEXITCODE -ne 0) { throw 'Android game-window lifecycle tests failed' } - - & python (Join-Path $launcherToolsDir 'test_launcher_update.py') - if ($LASTEXITCODE -ne 0) { throw 'Launcher update checker tests failed' } - - & python (Join-Path $launcherToolsDir 'test_apk_download.py') - if ($LASTEXITCODE -ne 0) { throw 'Launcher APK download tests failed' } - - # 1.5 Bake the git commit and version into a generated BppBuildInfo.java, then compile that - # generated copy instead of the source placeholder. - $commit = 'unknown' - try { - $commitOutput = & git -C $PSScriptRoot rev-parse --short=12 HEAD 2>$null - if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($commitOutput)) { - $commit = $commitOutput.Trim() - $dirtyOutput = & git -C $PSScriptRoot status --porcelain 2>$null - if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($dirtyOutput)) { - $commit = "$commit-dirty" - } - } - } catch { - $commit = 'unknown' - } - if ([string]::IsNullOrWhiteSpace($commit)) { $commit = 'unknown' } - - $generatedBuildInfoDir = Join-Path $workRoot 'generated-bpp-buildinfo' - New-Item -ItemType Directory -Force -Path $generatedBuildInfoDir | Out-Null - $sourceBuildInfo = Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppBuildInfo.java' - if (-not (Test-Path -LiteralPath $sourceBuildInfo -PathType Leaf)) { - throw "BppBuildInfo.java source not found: $sourceBuildInfo" - } - $generatedBuildInfo = Join-Path $generatedBuildInfoDir 'BppBuildInfo.java' - $buildInfoText = [System.IO.File]::ReadAllText($sourceBuildInfo) - $buildInfoText = $buildInfoText.Replace('COMMIT = "dev"', ('COMMIT = "' + $commit + '"')) - $buildInfoText = $buildInfoText.Replace('VERSION_NAME = "dev"', ('VERSION_NAME = "' + $versionName + '"')) - $utf8NoBom = New-Object System.Text.UTF8Encoding -ArgumentList $false - [System.IO.File]::WriteAllText($generatedBuildInfo, $buildInfoText, $utf8NoBom) - - # 2. Compile BppBundledModpackInstaller + BppLauncherActivity into classes3.dex - $appClasses = Join-Path $workRoot 'app-classes' - $dexOut = Join-Path $workRoot 'dex' - New-Item -ItemType Directory -Force -Path $appClasses, $dexOut | Out-Null - & $javac -encoding UTF-8 --release 11 -cp $platformJar -d $appClasses ` - $generatedBuildInfo ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppBundledModpackInstaller.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppLauncherActivity.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppGithubFeedback.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppLauncherUpdateChecker.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppOfficialPayload.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppApkDownload.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppBackBridge.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppGameWindow.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppDiagnosticBundle.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppDiagnosticExporter.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppDiagnosticSessionLog.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppGameProcess.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppJitTrace.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppGameApplication.java') ` - (Join-Path $launcherToolsDir 'src/com/bepinex/android/bpp/BppGenerationForegroundService.java') - if ($LASTEXITCODE -ne 0) { throw 'BppLauncherActivity compilation failed' } - - $compiledClassFiles = @(Get-ChildItem -LiteralPath $appClasses -Recurse -Filter *.class | Select-Object -ExpandProperty FullName) - & (Join-Path $buildToolsDir 'd8.bat') --min-api 28 --lib $platformJar --output $dexOut @compiledClassFiles - if ($LASTEXITCODE -ne 0) { throw 'd8 dexing failed' } - $classes3Dex = Join-Path $dexOut 'classes.dex' - if (-not (Test-Path -LiteralPath $classes3Dex)) { throw 'classes3.dex was not produced by d8' } - - # 3. Normalize bpp-modpack.zip entries and generate bpp-modpack-manifest.tsv + assemble unsigned APK - $unsignedApk = Join-Path $workRoot 'launcher.unsigned.apk' - $alignedApk = Join-Path $workRoot 'launcher.aligned.apk' - $assembleScript = Join-Path $workRoot 'assemble_apk.py' - @' -import hashlib -import io -import struct -import sys -import zipfile -from pathlib import Path - -source_apk = Path(sys.argv[1]) -modpack_zip_in = Path(sys.argv[2]) -safe_runtime = Path(sys.argv[3]).read_bytes() -safe_harmony = Path(sys.argv[4]).read_bytes() -classes3_dex = Path(sys.argv[5]).read_bytes() -patch_manifest_dir = Path(sys.argv[6]) -product_version = sys.argv[7] -version_code = int(sys.argv[8]) -version_name = sys.argv[9] -unsigned_apk_out = Path(sys.argv[10]) - -sys.path.insert(0, str(patch_manifest_dir)) -from patch_manifest import patch_manifest_bytes - -def sha256_hex(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - -# Repackage modpack ZIP with forward slashes and deterministic order, verifying no forbidden files -modpack_entries: dict[str, bytes] = {} -with zipfile.ZipFile(modpack_zip_in, "r") as zin: - for info in zin.infolist(): - name = info.filename.replace("\\", "/").strip("/") - if not name or info.is_dir() or name.endswith("/"): - continue - if ".." in name.split("/"): - raise ValueError(f"Unsafe modpack entry: {name}") - if name != "modpack.json" and not name.startswith(("plugins/", "core/")): - raise ValueError(f"Disallowed modpack entry: {name}") - if Path(name).suffix.lower() in (".cfg", ".db", ".sqlite", ".keystore", ".jks", ".pdb", ".mp4", ".png"): - raise ValueError(f"Forbidden file type in modpack: {name}") - if name in modpack_entries: - raise ValueError(f"Duplicate modpack entry: {name}") - modpack_entries[name] = zin.read(info.filename) - -# Ensure core in modpack has the exact patched runtime and harmony support -modpack_entries["core/Il2CppInterop.Runtime.dll"] = safe_runtime -modpack_entries["core/Il2CppInterop.HarmonySupport.dll"] = safe_harmony - -modpack_buf = io.BytesIO() -with zipfile.ZipFile(modpack_buf, "w", compression=zipfile.ZIP_DEFLATED) as zout: - for name in sorted(modpack_entries): - zout.writestr(name, modpack_entries[name]) -normalized_modpack_bytes = modpack_buf.getvalue() -bundle_id = sha256_hex(normalized_modpack_bytes) - -manifest_lines = [f"bundle_id\t{bundle_id}\t{product_version}"] -for name in sorted(modpack_entries): - blob = modpack_entries[name] - manifest_lines.append(f"file\t{name}\t{len(blob)}\t{sha256_hex(blob)}") -manifest_tsv_bytes = ("\n".join(manifest_lines) + "\n").encode("utf-8") - -with zipfile.ZipFile(source_apk, "r") as zsrc: - # Verify libpine.so is not stubbed with 'ret' (c0 03 5f d6) at 0x62a4 - pine_bytes = zsrc.read("lib/arm64-v8a/libpine.so") - if pine_bytes[0x62a4:0x62a8] == b"\xc0\x03\x5f\xd6": - raise ValueError("Refusing to package stubbed libpine.so (Pine_init0 == ret)") - - # Patch embedded assets/BepInEx.Android.zip with safe Runtime + HarmonySupport and forward slashes - bep_raw = zsrc.read("assets/BepInEx.Android.zip") - bep_entries: dict[str, bytes] = {} - with zipfile.ZipFile(io.BytesIO(bep_raw), "r") as zbep: - for info in zbep.infolist(): - name = info.filename.replace("\\", "/").strip("/") - if not name or info.is_dir() or name.endswith("/"): - continue - bep_entries[name] = zbep.read(info.filename) - bep_entries["core/Il2CppInterop.Runtime.dll"] = safe_runtime - bep_entries["core/Il2CppInterop.HarmonySupport.dll"] = safe_harmony - bep_out_buf = io.BytesIO() - with zipfile.ZipFile(bep_out_buf, "w", compression=zipfile.ZIP_DEFLATED) as zbep_out: - for name in sorted(bep_entries): - zbep_out.writestr(name, bep_entries[name]) - patched_bep_zip = bep_out_buf.getvalue() - - patched_manifest = patch_manifest_bytes( - zsrc.read("AndroidManifest.xml"), version_code, version_name, allow_repack=True - ) - - with zipfile.ZipFile(unsigned_apk_out, "w") as zdst: - for info in zsrc.infolist(): - name = info.filename - if name.startswith("META-INF/") and ( - name.endswith((".SF", ".RSA", ".DSA", ".EC")) or name == "META-INF/MANIFEST.MF" - ): - continue - if name in ("assets/bpp-modpack.zip", "assets/bpp-modpack-manifest.tsv", "classes3.dex"): - continue - if name == "AndroidManifest.xml": - data = patched_manifest - elif name == "assets/BepInEx.Android.zip": - data = patched_bep_zip - else: - data = zsrc.read(name) - - zi = zipfile.ZipInfo(name, date_time=info.date_time) - # Keep native libraries and resources.arsc uncompressed for 16 KB page alignment - if name.startswith("lib/") and name.endswith(".so") or name == "resources.arsc": - zi.compress_type = zipfile.ZIP_STORED - else: - zi.compress_type = info.compress_type - zi.external_attr = info.external_attr - zi.internal_attr = info.internal_attr - zi.create_system = info.create_system - zdst.writestr(zi, data) - - for added_name, added_bytes, compress_type in [ - ("classes3.dex", classes3_dex, zipfile.ZIP_DEFLATED), - ("assets/bpp-modpack.zip", normalized_modpack_bytes, zipfile.ZIP_DEFLATED), - ("assets/bpp-modpack-manifest.tsv", manifest_tsv_bytes, zipfile.ZIP_DEFLATED), - ]: - zi = zipfile.ZipInfo(added_name, date_time=(2026, 10, 25, 0, 0, 0)) - zi.compress_type = compress_type - zi.external_attr = 0o644 << 16 - zdst.writestr(zi, added_bytes) - -print(f"Assembled unsigned APK: {unsigned_apk_out} (bundle_id={bundle_id[:12]}, entries={len(modpack_entries)})") -'@ | Set-Content -LiteralPath $assembleScript -Encoding UTF8 - - & python $assembleScript ` - ([IO.Path]::GetFullPath($SourceApk)) ` - ([IO.Path]::GetFullPath($ModpackZip)) ` - ([IO.Path]::GetFullPath($SafeRuntime)) ` - ([IO.Path]::GetFullPath($SafeHarmony)) ` - $classes3Dex ` - $launcherToolsDir ` - $productVersion ` - $versionCode ` - $versionName ` - $unsignedApk - if ($LASTEXITCODE -ne 0) { throw 'Failed to assemble combined APK' } - - # 4. Replace only the launcher icon PNG payloads; resources.arsc and manifest stay intact. - & python (Join-Path $launcherToolsDir 'replace_icon.py') ` - $unsignedApk ` - (Join-Path $PSScriptRoot 'assets/icon') - if ($LASTEXITCODE -ne 0) { throw 'Failed to replace launcher icon' } - - # 5. Page-align to 16 KB boundaries - $zipalign = Join-Path $buildToolsDir 'zipalign.exe' - & $zipalign -P 16 -f 4 $unsignedApk $alignedApk - if ($LASTEXITCODE -ne 0) { throw 'zipalign failed' } - - $destinationDir = Split-Path -Parent ([IO.Path]::GetFullPath($Destination)) - if ($destinationDir) { New-Item -ItemType Directory -Force -Path $destinationDir | Out-Null } - - if ($UnsignedOnly) { - Copy-Item -LiteralPath $alignedApk -Destination $Destination -Force - Write-Host "Prepared unsigned aligned APK: $Destination" - return - } - - # 5. Sign APK (defaults to local Android debug keystore for seamless overwrite upgrades) - $useDefaultDebugKey = [string]::IsNullOrWhiteSpace($KeyStore) - if ($useDefaultDebugKey) { - $KeyStore = Join-Path $env:USERPROFILE '.android/debug.keystore' - $KeyAlias = 'androiddebugkey' - } - if (-not (Test-Path -LiteralPath $KeyStore -PathType Leaf)) { - throw "Keystore not found: $KeyStore" - } - - $apksignerJar = Join-Path $buildToolsDir 'lib/apksigner.jar' - $signArgs = @('-jar', $apksignerJar, 'sign', '--ks', $KeyStore, '--ks-key-alias', $KeyAlias, '--out', $Destination) - if ($useDefaultDebugKey -and [string]::IsNullOrEmpty($env:BPP_APK_STORE_PASSWORD)) { - $signArgs += @('--ks-pass', 'pass:android', '--key-pass', 'pass:android') - } else { - if ([string]::IsNullOrEmpty($env:BPP_APK_STORE_PASSWORD)) { - throw 'Set BPP_APK_STORE_PASSWORD for custom keystore signing.' - } - $signArgs += @('--ks-pass', 'env:BPP_APK_STORE_PASSWORD') - if ($env:BPP_APK_KEY_PASSWORD) { - $signArgs += @('--key-pass', 'env:BPP_APK_KEY_PASSWORD') - } - } - & $java @signArgs $alignedApk - if ($LASTEXITCODE -ne 0) { throw 'APK signing failed' } - - & $zipalign -c -P 16 4 $Destination - if ($LASTEXITCODE -ne 0) { throw 'Post-sign 16 KB alignment verification failed' } - - & $java -jar $apksignerJar verify --verbose --print-certs $Destination - if ($LASTEXITCODE -ne 0) { throw 'APK signature verification failed' } - - $verifyScript = Join-Path $launcherToolsDir 'verify_combined_apk.py' - & python $verifyScript ` - ([IO.Path]::GetFullPath($SourceApk)) ` - ([IO.Path]::GetFullPath($Destination)) ` - ([IO.Path]::GetFullPath($ModpackZip)) ` - ([IO.Path]::GetFullPath($SafeRuntime)) ` - ([IO.Path]::GetFullPath($SafeHarmony)) ` - (Join-Path $PSScriptRoot 'assets/icon') - if ($LASTEXITCODE -ne 0) { throw 'Combined APK integrity verification failed' } - - Write-Host "Signed self-deploying APK: $Destination" -} finally { - Remove-Item -LiteralPath $workRoot -Recurse -Force -ErrorAction SilentlyContinue -} - diff --git a/android-port/package-modpack.ps1 b/android-port/package-modpack.ps1 deleted file mode 100644 index 18c19b2..0000000 --- a/android-port/package-modpack.ps1 +++ /dev/null @@ -1,165 +0,0 @@ -param( - [string] $BuildOutput = '', - [string] $Destination = (Join-Path $PSScriptRoot '../dist/bpp-modpack'), - [string] $LauncherApk = (Join-Path $PSScriptRoot '../dist/app-release-aligned.apk'), - [string] $InteropSnapshot = (Join-Path $PSScriptRoot '../android-managed'), - [string] $SafeRuntime = (Join-Path $PSScriptRoot '../safe_Il2CppInterop.Runtime.dll'), - [string] $SafeHarmony = (Join-Path $PSScriptRoot '../safe_Il2CppInterop.HarmonySupport.dll'), - [switch] $Zip, - # Package the BepInEx bridge with upstream's published Android Managed Payload bundled - # (upstream-host/README.md) instead of this fork's plugin. - [switch] $Upstream, - [string] $OfficialPayloadCache = (Join-Path $PSScriptRoot '../dist/official-payload') -) - -# Collects the BazaarPlusPlus Android build into a distributable BepInEx modpack. -# The plugins directory only carries plugin assemblies and application-level dependencies: BepInEx already -# ships the framework and the whole IL2CPP toolchain, and redistributing those copies -# causes assembly identity conflicts on the device. - -$ErrorActionPreference = 'Stop' - -if ([string]::IsNullOrWhiteSpace($BuildOutput)) { - $BuildOutput = if ($Upstream) { - Join-Path $PSScriptRoot 'upstream-host/BazaarPlusPlus.BepInExBridge/bin/Release/net10.0' - } else { - Join-Path $PSScriptRoot '../bazaarplusplus-mod/src/BazaarPlusPlus/bin/Debug/net6.0' - } -} -if (-not (Test-Path $BuildOutput)) { - throw "Build output not found: $BuildOutput (run the Android build first)." -} - -$frameworkProvided = @( - 'BepInEx.Core', 'BepInEx.Unity.Common', 'BepInEx.Unity.IL2CPP', - 'Il2CppInterop.Common', 'Il2CppInterop.Generator', 'Il2CppInterop.HarmonySupport', - 'Il2CppInterop.Runtime', 'Cpp2IL.Core', 'LibCpp2IL', 'StableNameDotNet', - 'MonoMod.Backports', 'MonoMod.ILHelpers', 'MonoMod.RuntimeDetour', 'MonoMod.Utils', - 'Mono.Cecil', 'Mono.Cecil.Mdb', 'Mono.Cecil.Pdb', 'Mono.Cecil.Rocks', - 'AsmResolver', 'AsmResolver.DotNet', 'AsmResolver.PE', 'AsmResolver.PE.File', - 'AssetRipper.CIL', 'AssetRipper.Primitives', 'Iced', 'Disarm', - 'Gee.External.Capstone', 'WasmDisassembler', 'SemanticVersioning', '0Harmony' -) - -# Game interop assemblies are generated by BepInEx on the device; shipping our copies would -# shadow them with a different generation, so everything mirrored from the interop snapshot is -# excluded by name. -$gameProvided = @() -if (-not (Test-Path -LiteralPath $InteropSnapshot)) { - throw "Game interop snapshot missing: $InteropSnapshot. Refusing to package game assemblies." -} -if (Test-Path $InteropSnapshot) { - $gameProvided = Get-ChildItem $InteropSnapshot -Filter *.dll | - Where-Object { $_.BaseName -ne 'Newtonsoft.Json' } | - ForEach-Object { $_.BaseName } -} - -$plugins = Join-Path $Destination 'plugins' -if (-not (Test-Path -LiteralPath $safeRuntime)) { - throw "Patched Android interop runtime not found: $safeRuntime" -} -$core = Join-Path $Destination 'core' -New-Item -ItemType Directory -Force -Path $core | Out-Null -# NextBep replaces the active core directory with the selected modpack's core. -# Start from the installed launcher's complete framework before applying the patches. -Add-Type -AssemblyName System.IO.Compression.FileSystem -$launcherArchive = [System.IO.Compression.ZipFile]::OpenRead($LauncherApk) -try { - $frameworkEntry = $launcherArchive.GetEntry('assets/BepInEx.Android.zip') - if ($null -eq $frameworkEntry) { throw "BepInEx framework missing from $LauncherApk" } - $frameworkBuffer = New-Object System.IO.MemoryStream - try { - $frameworkInput = $frameworkEntry.Open() - try { $frameworkInput.CopyTo($frameworkBuffer) } finally { $frameworkInput.Dispose() } - $frameworkBuffer.Position = 0 - $frameworkArchive = New-Object System.IO.Compression.ZipArchive($frameworkBuffer, [System.IO.Compression.ZipArchiveMode]::Read) - try { - foreach ($entry in $frameworkArchive.Entries) { - if (-not $entry.FullName.StartsWith('core/') -or $entry.FullName.EndsWith('/')) { continue } - $coreFileName = $entry.FullName.Substring(5) - if ($coreFileName.Contains('/') -or $coreFileName.Contains('\') -or $coreFileName -in @('.', '..')) { - throw "Unexpected framework core path: $($entry.FullName)" - } - [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path $core $coreFileName), $true) - } - } finally { $frameworkArchive.Dispose() } - } finally { $frameworkBuffer.Dispose() } -} finally { $launcherArchive.Dispose() } -if (-not (Test-Path -LiteralPath (Join-Path $core 'BepInEx.Unity.IL2CPP.dll'))) { - throw 'Packaged core is missing the BepInEx entry assembly' -} -# Retire the old root-level runtime layout; the launcher applies core/ as a directory. -foreach ($retiredCore in @('Il2CppInterop.Runtime.dll', 'Il2CppInterop.HarmonySupport.dll')) { - $retiredPath = Join-Path $Destination $retiredCore - if (Test-Path -LiteralPath $retiredPath) { Remove-Item -LiteralPath $retiredPath -Force } -} -Copy-Item -LiteralPath $safeRuntime -Destination (Join-Path $core 'Il2CppInterop.Runtime.dll') -Force -if (-not (Test-Path -LiteralPath $safeHarmony)) { throw "Patched ARM64 Harmony support not found: $safeHarmony" } -Copy-Item -LiteralPath $safeHarmony -Destination (Join-Path $core 'Il2CppInterop.HarmonySupport.dll') -Force -if ($Upstream) { - # Upstream's host binds MelonLoader-style interop names; make BepInEx generate them on the - # device (tools/patch-bepinex-interop-prefix). - $bepInExEntry = Join-Path $core 'BepInEx.Unity.IL2CPP.dll' - & dotnet run --project (Join-Path $PSScriptRoot 'tools/patch-bepinex-interop-prefix/Patch.csproj') -- ` - $bepInExEntry $bepInExEntry $core - if ($LASTEXITCODE -ne 0) { throw 'BepInEx interop prefix patch failed' } -} -New-Item -ItemType Directory -Force -Path $plugins | Out-Null -Get-ChildItem $plugins -Filter *.dll -ErrorAction SilentlyContinue | Remove-Item -Force - -$copied = @() -Get-ChildItem $BuildOutput -Filter *.dll | ForEach-Object { - if ($frameworkProvided -contains $_.BaseName) { return } - if ($gameProvided -contains $_.BaseName) { return } - Copy-Item $_.FullName (Join-Path $plugins $_.Name) -Force - $copied += $_.Name -} - -if (-not $Upstream) { - # Keep portable DTO codecs separate from the game's same-name IL2CPP proxy assemblies. The - # upstream payload needs no aliases: its interop names carry the Il2Cpp prefix. - & dotnet run --project (Join-Path $PSScriptRoot 'tools/package-managed-codec/Package.csproj') -- $BuildOutput $plugins - if ($LASTEXITCODE -ne 0) { throw 'Managed codec packaging failed' } -} -$sqliteNative = Join-Path $BuildOutput 'runtimes/android-arm64/native/libe_sqlite3.so' -if (-not (Test-Path -LiteralPath $sqliteNative)) { throw "Android SQLite library not found: $sqliteNative" } -Copy-Item -LiteralPath $sqliteNative -Destination (Join-Path $plugins 'libe_sqlite3.so') -Force -if ($Upstream) { - # The payload the bridge installs on first start, pinned by upstream-host/official-payload.json; - # the launcher fetches newer releases itself. - $pin = Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'upstream-host/official-payload.json') | ConvertFrom-Json - New-Item -ItemType Directory -Force -Path $OfficialPayloadCache | Out-Null - $cached = Join-Path $OfficialPayloadCache "BazaarPlusPlus_$($pin.version)_android-aarch64-managed.zip" - if (-not (Test-Path -LiteralPath $cached) -or (Get-FileHash -LiteralPath $cached).Hash.ToLower() -ne $pin.sha256) { - Invoke-WebRequest -Uri $pin.url -OutFile $cached -UseBasicParsing - } - $actual = (Get-FileHash -LiteralPath $cached).Hash.ToLower() - if ($actual -ne $pin.sha256 -or (Get-Item -LiteralPath $cached).Length -ne $pin.size) { - Remove-Item -LiteralPath $cached -Force - throw "Official payload $($pin.version) does not match its pin (sha256 $actual)" - } - Copy-Item -LiteralPath $cached -Destination (Join-Path $plugins 'BazaarPlusPlus.OfficialPayload.zip') -Force -} -$copied = @(Get-ChildItem -LiteralPath $plugins -Filter *.dll | ForEach-Object { $_.Name }) - -$epoch = [DateTimeOffset]'1970-01-01T00:00:00Z' -$createdAt = [long](([DateTimeOffset]::UtcNow - $epoch).TotalMilliseconds) -$manifest = '{"name":"bpp","packageName":"com.tempogames.thebazaar","createdAt":' + - $createdAt + ',"modCount":' + $copied.Count + ',"createShortcut":false}' -[System.IO.File]::WriteAllText( - (Join-Path $Destination 'modpack.json'), - $manifest, - (New-Object System.Text.UTF8Encoding($false)) -) - -if ($Zip) { - $zipPath = "$Destination.zip" - if (Test-Path $zipPath) { Remove-Item $zipPath -Force } - Add-Type -AssemblyName System.IO.Compression.FileSystem - [System.IO.Compression.ZipFile]::CreateFromDirectory($Destination, $zipPath) - Write-Host "Archive: $zipPath" -} - -Write-Host "modpack ready: $Destination" -Write-Host ("shipping {0} assemblies" -f $copied.Count) -$copied | Sort-Object | ForEach-Object { Write-Host (" " + $_) } diff --git a/android-port/tools/bpp-launcher/patch_manifest.py b/android-port/tools/bpp-launcher/patch_manifest.py deleted file mode 100644 index 07eabf1..0000000 --- a/android-port/tools/bpp-launcher/patch_manifest.py +++ /dev/null @@ -1,910 +0,0 @@ -import struct -import sys -from pathlib import Path - -RES_STRING_POOL_TYPE = 0x0001 -RES_XML_START_ELEMENT_TYPE = 0x0102 -RES_XML_END_ELEMENT_TYPE = 0x0103 -RES_XML_RESOURCE_MAP_TYPE = 0x0180 -TYPE_STRING = 0x03 -ANDROID_NS = "http://schemas.android.com/apk/res/android" - -BPP_ACTIVITY_NAME = "com.bepinex.android.bpp.BppLauncherActivity" -ORIG_MAIN_ACTIVITY_NAME = "com.bepinex.android.MainActivity" -BPP_APP_LABEL = "BPP Android" -GAME_PROCESS_PROVIDER = "com.bepinex.android.bpp.BppGameProcess" -GAME_PROCESS_AUTHORITY = "com.bepinex.android.bpp.game-process" -GAME_APPLICATION = "com.bepinex.android.bpp.BppGameApplication" -GAME_SERVICE = "com.bepinex.android.bpp.BppGenerationForegroundService" -FGS_PROPERTY = "android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" -FGS_SUBTYPE = "keep_game_foreground_during_mod_generation" -UNITY_WINDOW_METADATA = ("unity.launch-fullscreen", "unity.render-outside-safearea") - - -def patch_unity_window_metadata(axml: bytes) -> bytes: - """Restore Unity's original application window policy in the fused host package. - - Unity resolves these through Activity.getPackageName()/PackageManager, not the - cloned game manifest. In particular render-outside-safearea controls both modern - status-bar requests and Unity's root-inset-driven FrameLayout padding. - """ - pool_size = struct.unpack_from(" bytes: - raw = text.encode("utf-16le") - char_len = len(text) - if char_len >= 0x8000: - raise ValueError("String too long for simple UTF-16 AXML pool entry") - return struct.pack(" list[str]: - t, header_size, chunk_size = struct.unpack_from(" tuple[bytes, list[str]]: - t, header_size, chunk_size = struct.unpack_from(" list[int]: - offset = 8 - while offset + 8 <= len(axml): - kind, header_size, size = struct.unpack_from(" len(axml): - raise ValueError("Corrupt AXML chunk while reading the resource map") - if kind == RES_XML_RESOURCE_MAP_TYPE: - if header_size < 8 or header_size > size: - raise ValueError("Invalid resource map chunk header") - count = (size - header_size) // 4 - if header_size + count * 4 != size: - raise ValueError("Invalid resource map chunk size") - if count == 0: - return [] - return list(struct.unpack_from(f"<{count}I", axml, offset + header_size)) - offset += size - raise ValueError("AndroidManifest.xml is missing the resource map chunk") - - -def _resource_id_for_name(name_index: int, resource_map: list[int]) -> int | None: - if 0 <= name_index < len(resource_map): - resource_id = resource_map[name_index] - return resource_id if resource_id else None - return None - - -def _mapped_string_index(strings: list[str], resource_map: list[int], value: str) -> int: - for index, text in enumerate(strings): - if text == value and index < len(resource_map) and resource_map[index] != 0: - return index - raise ValueError( - f"Android attribute name {value!r} is missing a resource id in the manifest resource map" - ) - - -def _sort_start_element_attributes(chunk: bytes, resource_map: list[int]) -> bytes: - kind, header_size, size = struct.unpack_from(" len(chunk): - raise ValueError("Start element attribute list is out of bounds") - - records = [ - chunk[base + i * attr_size : base + (i + 1) * attr_size] - for i in range(attr_count) - ] - - def sort_key(record: bytes) -> tuple[int, int]: - name_index = struct.unpack_from(" int: - if index == 0: - return 0 - if 1 <= index <= attr_count: - return new_positions[index - 1] + 1 - return index - - struct.pack_into( - " bytes: - """Sort every element's attributes by Android resource id. - - Android's ResXMLParser / obtainAttributes requires attributes to be sorted - ascending by resource id. Attributes without a resource id are placed after all - mapped attributes while preserving their relative order. - """ - resource_map = _read_resource_map(axml) - updated = bytearray(axml) - offset = 8 - while offset < len(updated): - kind, _header_size, size = struct.unpack_from(" len(updated): - raise ValueError("Corrupt AXML chunk while sorting attributes") - if kind == RES_XML_START_ELEMENT_TYPE: - updated[offset : offset + size] = _sort_start_element_attributes( - bytes(updated[offset : offset + size]), resource_map - ) - offset += size - return bytes(updated) - - -def verify_attribute_order(axml: bytes) -> list[str]: - """Return descriptions of elements whose attributes are not sorted by resource id.""" - problems: list[str] = [] - try: - resource_map = _read_resource_map(axml) - pool_size = struct.unpack_from(" len(axml): - problems.append(f"Truncated AXML chunk at offset {offset}") - break - kind, _header_size, size = struct.unpack_from(" len(axml): - problems.append(f"Corrupt AXML chunk at offset {offset}") - break - if kind == RES_XML_START_ELEMENT_TYPE: - chunk = axml[offset : offset + size] - try: - _kind, header_size, _size = struct.unpack_from(" len(chunk)): - raise ValueError("Start element attribute list is out of bounds") - keys: list[tuple[int, int]] = [] - for i in range(attr_count): - record_offset = base + i * attr_size - attr_name_index = struct.unpack_from(" attributes are not sorted by resource id " - f"at chunk 0x{offset:x}" - ) - except (struct.error, ValueError) as exc: - problems.append(f"Invalid start element at offset {offset}: {exc}") - offset += size - return problems - - -def _patch_start_element_attr( - chunk: bytearray, - strings: list[str], - attr_name: str, - new_string_idx: int | None = None, - new_bool_int: int | None = None, - new_int_value: int | None = None, -) -> bool: - ct, ch, cs = struct.unpack_from(" tuple[str, dict[str, str]]: - ct, ch, cs = struct.unpack_from(" bytes: - if len(axml) < 16 or struct.unpack_from(" len(axml): - raise ValueError(f"Corrupt AXML chunk at offset {off}") - chunks.append(axml[off : off + cs]) - off += cs - - out_chunks: list[bytes] = [new_pool] - i = 0 - patched_launcher = False - patched_app_label = False - while i < len(chunks): - chunk = chunks[i] - ct, ch, cs = struct.unpack_from("... subtree - activity_start = bytearray(chunk) - subtree = [chunks[i]] - depth = 1 - j = i + 1 - while j < len(chunks) and depth > 0: - sub_ct, _, _ = struct.unpack_from(" subtree for MainActivity") - - # 1. Primary launcher activity: BppLauncherActivity with original intent-filter - if not _patch_start_element_attr( - activity_start, strings, "name", new_string_idx=bpp_activity_idx - ): - raise ValueError("Failed to patch MainActivity name attribute") - out_chunks.append(bytes(activity_start)) - for sub in subtree[1:]: - out_chunks.append(sub) - - # 2. Secondary internal activity: original MainActivity without intent-filter, exported=false - orig_start = bytearray(chunk) - _patch_start_element_attr(orig_start, strings, "exported", new_bool_int=0) - out_chunks.append(bytes(orig_start)) - out_chunks.append(subtree[-1]) # matching - - patched_launcher = True - i = j - continue - out_chunks.append(chunk) - i += 1 - - if not patched_launcher: - raise ValueError("MainActivity element not found in AndroidManifest.xml") - if not patched_app_label: - raise ValueError("application label attribute not found in AndroidManifest.xml") - - body = b"".join(out_chunks) - total_size = 8 + len(body) - header = struct.pack(" bytes: - """Repackage a verified BPP host without cloning its launcher activity again.""" - pool_size = struct.unpack_from(" len(axml): - raise ValueError("Corrupt AXML chunk during repack") - chunk = bytearray(axml[offset:offset + size]) - if kind == RES_XML_START_ELEMENT_TYPE: - element, attrs = _get_start_element_info(chunk, strings) - if element == "activity" and attrs.get("name") == BPP_ACTIVITY_NAME: - bpp_activities += 1 - if element == "manifest": - if version_code is not None and not _patch_start_element_attr( - chunk, strings, "versionCode", new_int_value=version_code - ): - raise ValueError("versionCode attribute not found") - if version_name is not None and not _patch_start_element_attr( - chunk, strings, "versionName", new_string_idx=len(strings) - 1 - ): - raise ValueError("versionName attribute not found") - version_updated = True - chunks.append(bytes(chunk)) - offset += size - if bpp_activities != 1 or not version_updated: - raise ValueError("Expected exactly one BppLauncherActivity and a manifest") - body = b"".join(chunks) - return _install_game_process_hooks(struct.pack(" bytes: - """Hooks that must run inside :game while Cpp2IL generates on the grey screen.""" - axml = ensure_generation_service( - ensure_game_application(ensure_game_process_provider(patch_unity_window_metadata(axml))) - ) - return sort_element_attributes(ensure_install_permission(axml)) - - -def ensure_install_permission(axml: bytes) -> bytes: - """Allow the explicit system installer flow; Android still requires user consent.""" - permission = "android.permission.REQUEST_INSTALL_PACKAGES" - if _has_component(axml, "uses-permission", permission): - return axml - axml, strings = _with_extra_strings(axml, ["uses-permission", permission]) - resource_map = _read_resource_map(axml) - index = strings.index(permission) - attribute = _android_attr(strings, resource_map, "name", index, TYPE_STRING, index) - element = strings.index("uses-permission") - addition = _xml_start(element, attribute, 1) + _xml_end(element) - offset = 8 - while offset < len(axml): - kind, _, size = struct.unpack_from(" len(axml): - raise ValueError("Corrupt AXML while adding install permission") - if kind == RES_XML_START_ELEMENT_TYPE: - name, _ = _get_start_element_info(axml[offset:offset + size], strings) - if name == "manifest": - end = offset + size - body = axml[8:end] + addition + axml[end:] - return struct.pack(" tuple[bytes, list[str]]: - pool_size = struct.unpack_from(" bytes: - kind, header_size, size = struct.unpack_from(" len(chunk): - raise ValueError("Attribute list extends past its element chunk") - attr = struct.pack( - " bool: - pool_size = struct.unpack_from(" len(axml): - break - if kind == RES_XML_START_ELEMENT_TYPE: - element, attrs = _get_start_element_info(axml[offset : offset + size], strings) - if element == element_name and attrs.get("name") == class_name: - return True - offset += size - return False - - -def ensure_game_application(axml: bytes) -> bytes: - """Run launcher code in every process, including :game, without a custom provider process.""" - axml, strings = _with_extra_strings(axml, [GAME_APPLICATION]) - if _has_component(axml, "application", GAME_APPLICATION): - return axml - resource_map = _read_resource_map(axml) - class_index = strings.index(GAME_APPLICATION) - pool_size = struct.unpack_from(" len(axml): - raise ValueError("Corrupt AXML chunk while setting the game application") - chunk = axml[offset : offset + size] - if not found and kind == RES_XML_START_ELEMENT_TYPE: - element, attrs = _get_start_element_info(chunk, strings) - if element == "application": - if attrs.get("name"): - return axml - chunk = _append_element_attr( - chunk, strings, resource_map, "name", class_index, TYPE_STRING, class_index - ) - found = True - parts.append(chunk) - offset += size - if not found: - raise ValueError("application element not found while setting the game application") - body = axml[8 : 8 + pool_size] + b"".join(parts) - return struct.pack(" bool: - pool_size = struct.unpack_from(" len(axml): - break - if kind == RES_XML_START_ELEMENT_TYPE: - element, attrs = _get_start_element_info(axml[offset : offset + size], strings) - if element == "provider" and attrs.get("name") == class_name: - return True - offset += size - return False - - -def _provider_element(strings: list[str], resource_map: list[int]) -> tuple[bytes, bytes]: - ns = strings.index(ANDROID_NS) - name_i = _mapped_string_index(strings, resource_map, "name") - exported_i = _mapped_string_index(strings, resource_map, "exported") - authorities_i = _mapped_string_index(strings, resource_map, "authorities") - process_i = _mapped_string_index(strings, resource_map, "process") - provider_i = strings.index("provider") - class_i = strings.index(GAME_PROCESS_PROVIDER) - authority_i = strings.index(GAME_PROCESS_AUTHORITY) - game_i = strings.index(":game") - - def attr(name_idx: int, raw: int, typ: int, data: int) -> bytes: - return struct.pack(" bytes: - """Declare the :game diagnostics provider. Repacking an already patched manifest must keep it.""" - if _has_provider(axml, GAME_PROCESS_PROVIDER): - return axml - resource_map = _read_resource_map(axml) - pool_size = struct.unpack_from(" len(axml): - raise ValueError("Corrupt AXML chunk while inserting the game provider") - chunk = axml[offset : offset + size] - chunks.append(chunk) - if not inserted and kind == RES_XML_START_ELEMENT_TYPE: - element, _attrs = _get_start_element_info(chunk, strings) - if element == "application": - chunks.append(start) - chunks.append(end) - inserted = True - offset += size - if not inserted: - raise ValueError("application element not found while inserting the game provider") - body = b"".join(chunks) - return struct.pack(" bytes: - return struct.pack( - " bytes: - return struct.pack( - " bytes: - return struct.pack( - " bytes: - for required in ("service", "property", "name", "exported", "process", "foregroundServiceType", "value", ":game"): - if required not in strings: - raise ValueError(f"Manifest is missing the {required} string needed for the generation service") - service_index = strings.index("service") - property_index = strings.index("property") - class_index = strings.index(GAME_SERVICE) - game_index = strings.index(":game") - property_name = strings.index(FGS_PROPERTY) - property_value = strings.index(FGS_SUBTYPE) - service_attrs = b"".join([ - _android_attr(strings, resource_map, "name", class_index, TYPE_STRING, class_index), - _android_attr(strings, resource_map, "exported", 0xFFFFFFFF, 0x12, 0), - _android_attr(strings, resource_map, "process", game_index, TYPE_STRING, game_index), - _android_attr(strings, resource_map, "foregroundServiceType", 0xFFFFFFFF, 0x11, 0x40000000), - ]) - property_attrs = b"".join([ - _android_attr(strings, resource_map, "name", property_name, TYPE_STRING, property_name), - _android_attr(strings, resource_map, "value", property_value, TYPE_STRING, property_value), - ]) - return b"".join([ - _xml_start(service_index, service_attrs, 4), - _xml_start(property_index, property_attrs, 2), - _xml_end(property_index), - _xml_end(service_index), - ]) - - -def ensure_generation_service(axml: bytes) -> bytes: - """Keep :game at foreground-service importance while the first-run generator is alive.""" - if _has_component(axml, "service", GAME_SERVICE): - return axml - axml, strings = _with_extra_strings(axml, [GAME_SERVICE, FGS_PROPERTY, FGS_SUBTYPE, ":game"]) - resource_map = _read_resource_map(axml) - blob = _generation_service_chunks(strings, resource_map) - pool_size = struct.unpack_from(" len(axml): - raise ValueError("Corrupt AXML chunk while inserting the generation service") - chunk = axml[offset : offset + size] - parts.append(chunk) - if not inserted and kind == RES_XML_START_ELEMENT_TYPE: - element, _attrs = _get_start_element_info(chunk, strings) - if element == "application": - parts.append(blob) - inserted = True - offset += size - if not inserted: - raise ValueError("application element not found while inserting the generation service") - body = axml[8 : 8 + pool_size] + b"".join(parts) - return struct.pack(" int: - if len(sys.argv) not in (3, 5): - print( - "Usage: patch_manifest.py [version-code version-name]", - file=sys.stderr, - ) - return 2 - in_path = Path(sys.argv[1]) - out_path = Path(sys.argv[2]) - version_code = int(sys.argv[3]) if len(sys.argv) == 5 else None - version_name = sys.argv[4] if len(sys.argv) == 5 else None - try: - patched = patch_manifest_bytes(in_path.read_bytes(), version_code, version_name) - problems = verify_attribute_order(patched) - except ValueError as exc: - print(f"patch_manifest.py: {exc}", file=sys.stderr) - return 1 - if problems: - print("Attribute order verification failed:", file=sys.stderr) - for problem in problems: - print(f" {problem}", file=sys.stderr) - return 1 - out_path.write_bytes(patched) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) - diff --git a/android-port/tools/bpp-launcher/replace_icon.py b/android-port/tools/bpp-launcher/replace_icon.py deleted file mode 100644 index 4439ea8..0000000 --- a/android-port/tools/bpp-launcher/replace_icon.py +++ /dev/null @@ -1,128 +0,0 @@ -"""Replaces the launcher's adaptive/legacy icon entries with the Bazaar white icon. - -Usage: - replace_icon.py - -Only the PNG payloads change. AndroidManifest.xml and resources.arsc stay byte-identical, so -the existing @mipmap/ic_launcher / ic_launcher_round references and resource IDs keep resolving. -""" - -import struct -import sys -import tempfile -import zipfile -from pathlib import Path - -ADAPTIVE = { - "res/QZ.png": "adaptive-foreground-mdpi.png", - "res/zr.png": "adaptive-foreground-hdpi.png", - "res/Em.png": "adaptive-foreground-xhdpi.png", - "res/Lf.png": "adaptive-foreground-xxhdpi.png", - "res/as.png": "adaptive-foreground-xxxhdpi.png", -} -LEGACY_SQUARE = { - "res/9w.png": "legacy-square-mdpi.png", - "res/8c.png": "legacy-square-hdpi.png", - "res/FS.png": "legacy-square-xhdpi.png", - "res/RJ.png": "legacy-square-xxhdpi.png", - "res/Gc.png": "legacy-square-xxxhdpi.png", -} -LEGACY_ROUND = { - "res/zR.png": "legacy-round-mdpi.png", - "res/yn.png": "legacy-round-hdpi.png", - "res/wb.png": "legacy-round-xhdpi.png", - "res/fO.png": "legacy-round-xxhdpi.png", - "res/o-.png": "legacy-round-xxxhdpi.png", -} - -EXPECTED_SIZE = { - "mdpi": 48, - "hdpi": 72, - "xhdpi": 96, - "xxhdpi": 144, - "xxxhdpi": 192, -} -EXPECTED_ADAPTIVE = { - "mdpi": 108, - "hdpi": 162, - "xhdpi": 216, - "xxhdpi": 324, - "xxxhdpi": 432, -} - - -def png_size(data: bytes) -> tuple[int, int]: - if len(data) < 24 or data[:8] != b"\x89PNG\r\n\x1a\n": - raise ValueError("Icon entry is not a PNG") - return struct.unpack(">II", data[16:24]) - - -def main() -> int: - if len(sys.argv) != 3: - print(__doc__.strip(), file=sys.stderr) - return 2 - apk = Path(sys.argv[1]) - icon_dir = Path(sys.argv[2]) - - replacements: dict[str, bytes] = {} - for name, filename in ADAPTIVE.items(): - data = (icon_dir / filename).read_bytes() - density = filename.split("-")[-1].removesuffix(".png") - expected = EXPECTED_ADAPTIVE[density] - if png_size(data) != (expected, expected): - raise SystemExit(f"{filename}: expected {expected}x{expected}, got {png_size(data)}") - replacements[name] = data - for mapping, sizes in ((LEGACY_SQUARE, EXPECTED_SIZE), (LEGACY_ROUND, EXPECTED_SIZE)): - for name, filename in mapping.items(): - data = (icon_dir / filename).read_bytes() - density = filename.split("-")[-1].removesuffix(".png") - expected = sizes[density] - if png_size(data) != (expected, expected): - raise SystemExit( - f"{filename}: expected {expected}x{expected}, got {png_size(data)}" - ) - replacements[name] = data - - if not apk.is_file(): - raise SystemExit(f"APK not found: {apk}") - - with zipfile.ZipFile(apk) as source: - names = set(source.namelist()) - missing = sorted(set(replacements) - names) - if missing: - raise SystemExit(f"APK is missing expected icon entries: {missing}") - if "resources.arsc" not in names: - raise SystemExit("APK is missing resources.arsc") - arsc = source.read("resources.arsc") - - handle, temp_name = tempfile.mkstemp(suffix=".apk", dir=apk.parent) - import os - - os.close(handle) - Path(temp_name).unlink() - with zipfile.ZipFile(temp_name, "w") as target: - for info in source.infolist(): - data = replacements.get(info.filename) - if data is None: - data = source.read(info.filename) - copy = zipfile.ZipInfo(info.filename, date_time=info.date_time) - copy.compress_type = info.compress_type - copy.external_attr = info.external_attr - copy.create_system = info.create_system - copy.comment = info.comment - target.writestr(copy, data) - - with zipfile.ZipFile(temp_name) as result: - if result.read("resources.arsc") != arsc: - raise SystemExit("Icon replacement changed resources.arsc") - for name, data in replacements.items(): - if result.read(name) != data: - raise SystemExit(f"Icon replacement failed for {name}") - - Path(temp_name).replace(apk) - print(f"Replaced {len(replacements)} launcher icon entries.") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppApkDownload.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppApkDownload.java deleted file mode 100644 index 4297dfc..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppApkDownload.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.DownloadManager; -import android.content.Context; -import android.content.SharedPreferences; -import android.content.pm.PackageInfo; -import android.database.Cursor; -import android.net.Uri; -import android.os.Environment; -import java.io.File; -import java.io.IOException; - -/** One persisted system download, surviving launcher recreation and process death. */ -public final class BppApkDownload { - private final Context context; - private final DownloadManager manager; - private final SharedPreferences preferences; - - public BppApkDownload(Context context) { - this.context = context; - manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); - preferences = context.getSharedPreferences("bpp-apk-update", Context.MODE_PRIVATE); - } - - public boolean hasDownload() { return preferences.getLong("id", -1) != -1; } - - public void start(BppLauncherUpdateChecker.Update update) throws IOException { - if (hasDownload()) return; - if (manager == null) throw new IOException("系统下载服务不可用"); - File directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); - if (directory == null) throw new IOException("下载目录不可用"); - File target = new File(directory, "bpp-update.apk"); - if (target.exists() && !target.delete()) throw new IOException("无法清理旧安装包"); - DownloadManager.Request request = new DownloadManager.Request(Uri.parse(update.apkUrl)) - .setTitle("BPP Android " + update.version) - .setDescription("下载完成后,请返回 BPP 点击安装") - .setMimeType("application/vnd.android.package-archive") - .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) - .setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, target.getName()); - long id = manager.enqueue(request); - if (!preferences.edit().putLong("id", id).putString("version", update.version) - .putLong("size", update.apkSize).commit()) { - manager.remove(id); - throw new IOException("无法保存下载任务,请重试"); - } - } - - public static final class State { - public final boolean complete; - public final String message; - State(boolean complete, String message) { this.complete = complete; this.message = message; } - } - - public State state() throws IOException { - if (manager == null) throw new IOException("系统下载服务不可用"); - try (Cursor cursor = manager.query(new DownloadManager.Query().setFilterById(preferences.getLong("id", -1)))) { - if (cursor == null || !cursor.moveToFirst()) throw new IOException("下载任务已被移除,请重试"); - int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)); - if (status == DownloadManager.STATUS_FAILED) { - int reason = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON)); - throw new IOException("下载失败(" + reason + "),请重试或从 GitHub 下载"); - } - if (status == DownloadManager.STATUS_SUCCESSFUL) - return new State(true, "下载完成 · 点击安装 " + preferences.getString("version", "")); - long received = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); - long total = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); - String progress = total > 0 ? (received * 100 / total) + "%" : (received / 1024 / 1024) + " MB"; - return new State(false, (status == DownloadManager.STATUS_PAUSED ? "下载暂停,等待网络 · " : "正在下载 · ") + progress); - } - } - - /** Recheck the file on every install attempt; the system installer verifies signing continuity. */ - public Uri installationUri() throws Exception { - if (!state().complete) throw new IOException("安装包尚未下载完成"); - File directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); - if (directory == null) throw new IOException("下载目录不可用"); - File apk = new File(directory, "bpp-update.apk"); - if (!apk.isFile() || apk.length() != preferences.getLong("size", -1)) - throw new IOException("安装包大小不符,请重新下载"); - PackageInfo archive = context.getPackageManager().getPackageArchiveInfo(apk.getAbsolutePath(), 0); - PackageInfo installed = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); - if (archive == null || !context.getPackageName().equals(archive.packageName) - || !preferences.getString("version", "").equals(archive.versionName) - || archive.getLongVersionCode() <= installed.getLongVersionCode()) - throw new IOException("安装包不是当前应用的新版本,请重新检查更新"); - Uri uri = manager.getUriForDownloadedFile(preferences.getLong("id", -1)); - if (uri == null || !"content".equals(uri.getScheme())) throw new IOException("无法读取安装包,请重新下载"); - return uri; - } - - public boolean alreadyInstalled(String current) { - String downloaded = preferences.getString("version", ""); - try { return hasDownload() && BppLauncherUpdateChecker.compareVersions(current, downloaded) >= 0; } - catch (IllegalArgumentException ignored) { return false; } - } - - public void clear() { - long id = preferences.getLong("id", -1); - if (manager != null && id != -1) manager.remove(id); - preferences.edit().clear().apply(); - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBackBridge.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBackBridge.java deleted file mode 100644 index c54f7a5..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBackBridge.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Activity; -import android.os.Build; -import android.os.Handler; -import android.os.Looper; -import android.util.Log; -import android.window.OnBackInvokedCallback; -import android.window.OnBackInvokedDispatcher; - -/** Routes system Back to the overlay owner, without changing Back outside BPP panels. */ -public final class BppBackBridge { - private static final Handler MAIN = new Handler(Looper.getMainLooper()); - private static volatile boolean consume; - private static boolean pending; - private static Activity activity; - private static OnBackInvokedCallback callback; - private static volatile boolean registered; - private static boolean scheduled; - - private BppBackBridge() {} - - public static void install(final Activity value) { - if (Build.VERSION.SDK_INT < 33 || value == null) return; - MAIN.post(new Runnable() { - @Override public void run() { - if (activity != value) { - unregister(); - activity = value; - } - if (callback == null) { - callback = new OnBackInvokedCallback() { - @Override public void onBackInvoked() { - recordBack(); - } - }; - } - reconcile(); - } - }); - } - - public static synchronized void setConsume(boolean value) { - consume = value; - if (!value) pending = false; - if (registered == value || scheduled || Build.VERSION.SDK_INT < 33) return; - scheduled = true; - MAIN.post(new Runnable() { - @Override public void run() { - synchronized (BppBackBridge.class) { scheduled = false; } - reconcile(); - } - }); - } - - private static synchronized void recordBack() { - if (consume) { - pending = true; - Log.i("BppBackBridge", "Back consumed"); - } - } - - public static synchronized boolean takeBackPress() { - boolean value = pending; - pending = false; - return value; - } - - public static void uninstall() { - synchronized (BppBackBridge.class) { consume = false; pending = false; } - MAIN.post(new Runnable() { - @Override public void run() { - unregister(); - activity = null; - callback = null; - } - }); - } - - private static void reconcile() { - if (activity == null || callback == null || Build.VERSION.SDK_INT < 33) return; - try { - if (consume && !registered) { - activity.getOnBackInvokedDispatcher().registerOnBackInvokedCallback( - OnBackInvokedDispatcher.PRIORITY_DEFAULT, callback); - registered = true; - Log.i("BppBackBridge", "Callback registered on Android UI thread"); - } else if (!consume && registered) { - unregister(); - } - } catch (RuntimeException error) { - Log.e("BppBackBridge", "Callback reconciliation failed", error); - } - } - - private static void unregister() { - if (registered && activity != null && callback != null) { - try { - activity.getOnBackInvokedDispatcher().unregisterOnBackInvokedCallback(callback); - } catch (RuntimeException error) { - Log.w("BppBackBridge", "Activity is releasing its callback", error); - } - } - registered = false; - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBuildInfo.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBuildInfo.java deleted file mode 100644 index 3e2348f..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBuildInfo.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Application; -import android.util.Log; -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; - -/** Build metadata injected by the packaging script. */ -public final class BppBuildInfo { - - private static final String TAG = "BppGame"; - - public static final String COMMIT = "dev"; - public static final String VERSION_NAME = "dev"; - - private BppBuildInfo() {} - - /** Same line format used by the :game process start log. */ - public static String describe() { - return "BuildInfo version=" + VERSION_NAME - + " commit=" + COMMIT - + " process=" + processName() - + " pid=" + android.os.Process.myPid(); - } - - private static String processName() { - try { - String process = Application.getProcessName(); - if (process != null && process.length() > 0) return process; - } catch (Throwable t) { - Log.w(TAG, "BuildInfo getProcessName failed", t); - } - try { - byte[] data = Files.readAllBytes(new File("/proc/self/cmdline").toPath()); - int end = 0; - while (end < data.length && data[end] != 0) end++; - if (end > 0) return new String(data, 0, end, StandardCharsets.UTF_8); - } catch (Throwable t) { - Log.w(TAG, "BuildInfo read /proc/self/cmdline failed", t); - } - return "unknown"; - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBundledModpackInstaller.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBundledModpackInstaller.java deleted file mode 100644 index d845744..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppBundledModpackInstaller.java +++ /dev/null @@ -1,930 +0,0 @@ -package com.bepinex.android.bpp; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.security.MessageDigest; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -/** - * Pure-Java installer and verifier for the bundled BazaarPlusPlus Android modpack. - * - * Owns only modpack.json (create/repair-only) and the listed files under plugins/ and core/ - * in both modpacks/bpp/ and BepInEx/. Never modifies or deletes user config, logs, or - * BazaarPlusPlusV6 history databases. - */ -public final class BppBundledModpackInstaller { - - public static final String TARGET_PACKAGE = "com.tempogames.thebazaar"; - public static final String MODPACK_NAME = "bpp"; - public static final String ASSET_MODPACK_ZIP = "bpp-modpack.zip"; - public static final String ASSET_MODPACK_MANIFEST = "bpp-modpack-manifest.tsv"; - public static final String ASSET_BEPINEX_ZIP = "BepInEx.Android.zip"; - public static final String STATE_FILE_NAME = "bpp-bundled-modpack.state"; - public static final String LOCK_FILE_NAME = "bpp-bundled-modpack.lock"; - - private static final Object PROCESS_LOCK = new Object(); - private static final Pattern MOD_COUNT_PATTERN = Pattern.compile("\"modCount\"\\s*:\\s*\\d+"); - - private static final String[] CRITICAL_OWNED_PATHS = new String[] { - "modpack.json", - "plugins/libe_sqlite3.so", - "core/BepInEx.Unity.IL2CPP.dll", - "core/BepInEx.Core.dll", - "core/Il2CppInterop.Runtime.dll", - "core/Il2CppInterop.HarmonySupport.dll" - }; - - // The plugin itself, one complete set: this fork's own plugin, or the BepInEx bridge that - // runs upstream's published Android Managed Payload, bundled as a signed zip - // (android-port/upstream-host/README.md). Switching between them is an ordinary update: files - // the previous manifest owned are retired. - private static final String[][] PLUGIN_PAYLOAD_VARIANTS = new String[][] { - { - "plugins/BazaarPlusPlus.dll", - "plugins/BazaarPlusPlus.Localization.dll", - "plugins/BazaarPlusPlus.ModApi.dll", - "plugins/BazaarPlusPlus.Storage.dll", - "plugins/Bpp.Managed.MessagePack.dll", - "plugins/Bpp.Managed.MessagePack.Annotations.dll", - "plugins/Bpp.Managed.StringTools.dll", - "plugins/Microsoft.Data.Sqlite.dll", - "plugins/SQLitePCLRaw.batteries_v2.dll", - "plugins/SQLitePCLRaw.core.dll", - "plugins/SQLitePCLRaw.provider.e_sqlite3.dll" - }, - { - "plugins/BazaarPlusPlus.BepInExBridge.dll", - "plugins/BazaarPlusPlus.OfficialPayload.dll", - "plugins/BazaarPlusPlus.OfficialPayload.zip", - "plugins/MelonLoader.dll" - } - }; - - public interface StreamSupplier { - InputStream open() throws IOException; - } - - public interface ProgressListener { - void onProgress(String step, int percent); - } - - public enum StatusKind { - READY, - NEEDS_INSTALL, - NEEDS_UPDATE, - NEEDS_REPAIR - } - - public static final class ManifestEntry { - public final String relativePath; - public final long size; - public final String sha256; - - public ManifestEntry(String relativePath, long size, String sha256) { - this.relativePath = relativePath; - this.size = size; - this.sha256 = sha256.toLowerCase(Locale.ROOT); - } - } - - public static final class Manifest { - public final String bundleId; - public final String version; - public final Map entries; - public final int managedDllCount; - - public Manifest(String bundleId, String version, Map entries) { - this.bundleId = bundleId.toLowerCase(Locale.ROOT); - this.version = version; - this.entries = Collections.unmodifiableMap(new LinkedHashMap(entries)); - int dlls = 0; - for (String path : entries.keySet()) { - if (path.startsWith("plugins/") && path.toLowerCase(Locale.ROOT).endsWith(".dll")) { - dlls++; - } - } - this.managedDllCount = dlls; - } - } - - public static final class StatusReport { - public final StatusKind kind; - public final String bundleId; - public final String version; - public final String detail; - - public StatusReport(StatusKind kind, String bundleId, String version, String detail) { - this.kind = kind; - this.bundleId = bundleId; - this.version = version; - this.detail = detail; - } - - public boolean isReady() { - return kind == StatusKind.READY; - } - } - - private static final class InstalledState { - final boolean committed; - final String bundleId; - final Map ownedFileHashes; - - InstalledState(boolean committed, String bundleId, Map ownedFileHashes) { - this.committed = committed; - this.bundleId = bundleId; - this.ownedFileHashes = ownedFileHashes; - } - } - - private BppBundledModpackInstaller() {} - - public static Manifest parseManifest(InputStream stream) throws IOException { - if (stream == null) { - throw new IOException("Missing bundled modpack manifest stream."); - } - BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); - String bundleId = null; - String version = null; - Map entries = new LinkedHashMap(); - String rawLine; - while ((rawLine = reader.readLine()) != null) { - String line = rawLine.trim(); - if (line.isEmpty() || line.startsWith("#")) { - continue; - } - String[] parts = line.split("\t"); - if ("bundle_id".equals(parts[0])) { - if (parts.length < 3) { - throw new IOException("Malformed bundle_id header in manifest."); - } - bundleId = requireSha256(parts[1], "bundle_id"); - version = parts[2].trim(); - if (version.isEmpty()) { - throw new IOException("Empty bundle version in manifest."); - } - } else if ("file".equals(parts[0])) { - if (parts.length != 4) { - throw new IOException("Malformed file entry in manifest: " + line); - } - String path = validateOwnedRelativePath(parts[1]); - long size; - try { - size = Long.parseLong(parts[2]); - } catch (NumberFormatException ex) { - throw new IOException("Invalid file size for " + path, ex); - } - if (size <= 0L) { - throw new IOException("Non-positive file size for " + path); - } - String sha = requireSha256(parts[3], path); - if (entries.put(path, new ManifestEntry(path, size, sha)) != null) { - throw new IOException("Duplicate manifest path: " + path); - } - } else { - throw new IOException("Unknown manifest record type: " + parts[0]); - } - } - if (bundleId == null || version == null) { - throw new IOException("Manifest is missing bundle_id header."); - } - for (String required : CRITICAL_OWNED_PATHS) { - if (!entries.containsKey(required)) { - throw new IOException("Manifest is missing required payload entry: " + required); - } - } - if (!containsAnyVariant(entries.keySet())) { - throw new IOException( - "Manifest carries no complete plugin payload: expected all of " - + String.join(", ", PLUGIN_PAYLOAD_VARIANTS[0]) - + " or all of " - + String.join(", ", PLUGIN_PAYLOAD_VARIANTS[1]) - ); - } - return new Manifest(bundleId, version, entries); - } - - private static boolean containsAnyVariant(Set paths) { - for (String[] variant : PLUGIN_PAYLOAD_VARIANTS) { - boolean complete = true; - for (String path : variant) { - complete &= paths.contains(path); - } - if (complete) { - return true; - } - } - return false; - } - - public static StatusReport inspectStatus( - File gameRootDir, - File internalWorkDir, - Manifest manifest, - boolean verifyHashes - ) { - File stateFile = new File(internalWorkDir, STATE_FILE_NAME); - InstalledState state = readInstalledState(stateFile); - File modpackDir = new File(gameRootDir, "modpacks/" + MODPACK_NAME); - File runtimeDir = new File(gameRootDir, "BepInEx"); - if (state == null) { - boolean anyExisting = false; - for (String plugin : new String[] { "plugins/BazaarPlusPlus.dll", "plugins/BazaarPlusPlus.BepInExBridge.dll" }) { - anyExisting |= new File(modpackDir, plugin).exists() || new File(runtimeDir, plugin).exists(); - } - return new StatusReport( - anyExisting ? StatusKind.NEEDS_UPDATE : StatusKind.NEEDS_INSTALL, - manifest.bundleId, - manifest.version, - anyExisting ? "检测到已有模组目录,待同步到当前内置版本" : "首次启动待部署内置 BPP 模组包" - ); - } - if (!state.committed) { - return new StatusReport( - StatusKind.NEEDS_REPAIR, - manifest.bundleId, - manifest.version, - "上次部署未完成,待自动恢复" - ); - } - if (!manifest.bundleId.equalsIgnoreCase(state.bundleId)) { - return new StatusReport( - StatusKind.NEEDS_UPDATE, - manifest.bundleId, - manifest.version, - "发现新版内置模组包,待自动更新" - ); - } - String verificationFailure = verifyInstalledFiles(gameRootDir, manifest, verifyHashes); - if (verificationFailure != null) { - return new StatusReport( - StatusKind.NEEDS_REPAIR, - manifest.bundleId, - manifest.version, - verificationFailure - ); - } - return new StatusReport( - StatusKind.READY, - manifest.bundleId, - manifest.version, - "内置 BPP 模组已就绪" - ); - } - - public static StatusReport installOrUpdate( - File gameRootDir, - File internalWorkDir, - StreamSupplier manifestSupplier, - StreamSupplier modpackZipSupplier, - StreamSupplier bepInExFrameworkZipSupplier, - boolean forceRepair, - ProgressListener progress - ) throws IOException { - if (gameRootDir == null || internalWorkDir == null) { - throw new IOException("Game root and internal work directories are required."); - } - Manifest manifest; - try (InputStream manifestStream = manifestSupplier.open()) { - manifest = parseManifest(manifestStream); - } - synchronized (PROCESS_LOCK) { - ensureDir(internalWorkDir); - File lockFile = new File(internalWorkDir, LOCK_FILE_NAME); - try ( - RandomAccessFile raf = new RandomAccessFile(lockFile, "rw"); - FileChannel channel = raf.getChannel(); - FileLock fileLock = channel.lock() - ) { - if (!forceRepair) { - StatusReport current = inspectStatus(gameRootDir, internalWorkDir, manifest, true); - if (current.isReady()) { - reconcileConfigsAdditively(gameRootDir, bepInExFrameworkZipSupplier); - notifyProgress(progress, "内置 BPP 模组已就绪", 100); - return current; - } - } - - notifyProgress(progress, "正在校验内置模组包…", 15); - File stateFile = new File(internalWorkDir, STATE_FILE_NAME); - InstalledState previousState = readInstalledState(stateFile); - Map previousOwned = previousState != null - ? previousState.ownedFileHashes - : Collections.emptyMap(); - - File stagingDir = new File(internalWorkDir, "staging-" + System.nanoTime()); - deleteRecursively(stagingDir); - ensureDir(stagingDir); - try { - stageAndVerifyZip(modpackZipSupplier, manifest, stagingDir); - writeStateFile(stateFile, false, manifest.bundleId, previousOwned); - - notifyProgress(progress, "正在保护配置文件与同步运行环境…", 45); - reconcileConfigsAdditively(gameRootDir, bepInExFrameworkZipSupplier); - - notifyProgress(progress, "正在写入插件与修补核心…", 70); - applyStagedFiles(gameRootDir, stagingDir, manifest, previousOwned); - - notifyProgress(progress, "正在校验部署完整性…", 90); - String failure = verifyInstalledFiles(gameRootDir, manifest, true); - if (failure != null) { - throw new IOException("Post-install verification failed: " + failure); - } - - Map committedOwned = new LinkedHashMap(); - for (ManifestEntry entry : manifest.entries.values()) { - if (!"modpack.json".equals(entry.relativePath)) { - committedOwned.put(entry.relativePath, entry.sha256); - } - } - writeStateFile(stateFile, true, manifest.bundleId, committedOwned); - } finally { - deleteRecursively(stagingDir); - } - - notifyProgress(progress, "内置 BPP 模组部署完成", 100); - return new StatusReport( - StatusKind.READY, - manifest.bundleId, - manifest.version, - "内置 BPP 模组已就绪" - ); - } - } - } - - private static void stageAndVerifyZip( - StreamSupplier modpackZipSupplier, - Manifest manifest, - File stagingDir - ) throws IOException { - Set seenEntries = new LinkedHashSet(); - String canonicalStagingRoot = stagingDir.getCanonicalPath() + File.separator; - try ( - InputStream raw = modpackZipSupplier.open(); - ZipInputStream zis = new ZipInputStream(new BufferedInputStream(raw)) - ) { - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) { - String rawName = entry.getName(); - if (rawName == null || rawName.isEmpty()) { - continue; - } - if (rawName.indexOf('\\') >= 0) { - throw new IOException("Backslash path separator rejected in archive: " + rawName); - } - if (entry.isDirectory() || rawName.endsWith("/")) { - validateDirectoryEntry(rawName); - continue; - } - String relativePath = validateOwnedRelativePath(rawName); - if (!seenEntries.add(relativePath)) { - throw new IOException("Duplicate archive entry: " + relativePath); - } - ManifestEntry expected = manifest.entries.get(relativePath); - if (expected == null) { - throw new IOException("Unlisted archive entry rejected: " + relativePath); - } - File outFile = new File(stagingDir, relativePath); - String canonicalTarget = outFile.getCanonicalPath(); - if (!canonicalTarget.startsWith(canonicalStagingRoot)) { - throw new IOException("Archive entry escaped staging root: " + relativePath); - } - ensureDir(outFile.getParentFile()); - MessageDigest digest = newSha256(); - long written = 0L; - try (FileOutputStream fos = new FileOutputStream(outFile)) { - byte[] buffer = new byte[16 * 1024]; - int read; - while ((read = zis.read(buffer)) != -1) { - written += read; - if (written > expected.size) { - throw new IOException("Archive entry exceeded expected size: " + relativePath); - } - digest.update(buffer, 0, read); - fos.write(buffer, 0, read); - } - fos.getFD().sync(); - } - if (written != expected.size) { - throw new IOException( - "Archive entry size mismatch for " + relativePath - + ": expected " + expected.size + ", got " + written - ); - } - String actualSha = toHex(digest.digest()); - if (!expected.sha256.equalsIgnoreCase(actualSha)) { - throw new IOException("Archive entry SHA-256 mismatch for " + relativePath); - } - } - } - if (seenEntries.size() != manifest.entries.size()) { - throw new IOException( - "Archive entry count mismatch: expected " + manifest.entries.size() - + ", got " + seenEntries.size() - ); - } - } - - private static void applyStagedFiles( - File gameRootDir, - File stagingDir, - Manifest manifest, - Map previousOwned - ) throws IOException { - File modpackDir = new File(gameRootDir, "modpacks/" + MODPACK_NAME); - File runtimeDir = new File(gameRootDir, "BepInEx"); - ensureDir(new File(modpackDir, "plugins")); - ensureDir(new File(modpackDir, "core")); - ensureDir(new File(modpackDir, "config")); - ensureDir(new File(modpackDir, "logs")); - ensureDir(new File(runtimeDir, "plugins")); - ensureDir(new File(runtimeDir, "core")); - ensureDir(new File(runtimeDir, "config")); - - for (ManifestEntry entry : manifest.entries.values()) { - String rel = entry.relativePath; - File staged = new File(stagingDir, rel); - if ("modpack.json".equals(rel)) { - updateOrCreateModpackJson( - new File(modpackDir, "modpack.json"), - staged, - manifest.managedDllCount - ); - continue; - } - atomicCopyIfNeeded(staged, new File(modpackDir, rel), entry.size, entry.sha256); - atomicCopyIfNeeded(staged, new File(runtimeDir, rel), entry.size, entry.sha256); - } - - for (Map.Entry oldEntry : previousOwned.entrySet()) { - String oldRel = oldEntry.getKey(); - String oldSha = oldEntry.getValue(); - if ("modpack.json".equals(oldRel) || manifest.entries.containsKey(oldRel)) { - continue; - } - if (!isAllowedOwnedSubpath(oldRel)) { - continue; - } - deleteIfUnmodifiedOwnedFile(new File(modpackDir, oldRel), oldSha); - deleteIfUnmodifiedOwnedFile(new File(runtimeDir, oldRel), oldSha); - } - } - - private static void updateOrCreateModpackJson( - File targetFile, - File stagedFile, - int managedDllCount - ) throws IOException { - if (targetFile.isFile() && targetFile.length() > 0L) { - String existing = readUtf8(targetFile).trim(); - if (isValidModpackJson(existing)) { - Matcher matcher = MOD_COUNT_PATTERN.matcher(existing); - String updated = matcher.find() - ? matcher.replaceFirst("\"modCount\":" + managedDllCount) - : existing; - if (!updated.equals(existing)) { - atomicWriteUtf8(targetFile, updated); - } - return; - } - } - atomicCopyFile(stagedFile, targetFile); - } - - private static boolean isValidModpackJson(String text) { - if (text == null || !text.startsWith("{") || !text.endsWith("}")) { - return false; - } - boolean hasName = Pattern.compile("\"name\"\\s*:\\s*\"" + Pattern.quote(MODPACK_NAME) + "\"") - .matcher(text) - .find(); - boolean hasPackage = Pattern.compile("\"packageName\"\\s*:\\s*\"" + Pattern.quote(TARGET_PACKAGE) + "\"") - .matcher(text) - .find(); - return hasName && hasPackage; - } - - /** - * Ensures modpacks/bpp/config and BepInEx/config both carry BepInEx.cfg and any existing - * user .cfg files before BootstrapActivity runs ModpackManager.restoreRuntimeState(), - * which otherwise wipes BepInEx/config on a first switch from vanilla to bpp. - */ - public static void reconcileConfigsAdditively( - File gameRootDir, - StreamSupplier bepInExFrameworkZipSupplier - ) throws IOException { - File runtimeConfigDir = new File(gameRootDir, "BepInEx/config"); - File modpackConfigDir = new File(gameRootDir, "modpacks/" + MODPACK_NAME + "/config"); - ensureDir(runtimeConfigDir); - ensureDir(modpackConfigDir); - - File runtimeBepCfg = new File(runtimeConfigDir, "BepInEx.cfg"); - File modpackBepCfg = new File(modpackConfigDir, "BepInEx.cfg"); - if (!runtimeBepCfg.isFile() && !modpackBepCfg.isFile() && bepInExFrameworkZipSupplier != null) { - byte[] defaultCfg = extractSingleEntryFromZip(bepInExFrameworkZipSupplier, "config/BepInEx.cfg"); - if (defaultCfg != null && defaultCfg.length > 0) { - atomicWriteBytes(runtimeBepCfg, defaultCfg); - atomicWriteBytes(modpackBepCfg, defaultCfg); - } - } - - syncAuthoritativeRuntimeConfigsToModpack(runtimeConfigDir, modpackConfigDir); - copyMissingCfgFiles(modpackConfigDir, runtimeConfigDir); - } - - private static void syncAuthoritativeRuntimeConfigsToModpack(File runtimeConfigDir, File modpackConfigDir) - throws IOException { - File[] files = runtimeConfigDir.listFiles(); - if (files == null) { - return; - } - for (File file : files) { - if (!file.isFile() || file.length() == 0L || !file.getName().toLowerCase(Locale.ROOT).endsWith(".cfg")) { - continue; - } - File dest = new File(modpackConfigDir, file.getName()); - String sha = sha256File(file); - atomicCopyIfNeeded(file, dest, file.length(), sha); - } - } - - private static void copyMissingCfgFiles(File sourceDir, File destDir) throws IOException { - File[] files = sourceDir.listFiles(); - if (files == null) { - return; - } - for (File file : files) { - if (!file.isFile() || !file.getName().toLowerCase(Locale.ROOT).endsWith(".cfg")) { - continue; - } - File dest = new File(destDir, file.getName()); - if (!dest.exists() || dest.length() == 0L) { - atomicCopyFile(file, dest); - } - } - } - - private static byte[] extractSingleEntryFromZip( - StreamSupplier zipSupplier, - String wantedEntry - ) throws IOException { - try ( - InputStream raw = zipSupplier.open(); - ZipInputStream zis = new ZipInputStream(new BufferedInputStream(raw)) - ) { - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) { - String name = entry.getName().replace('\\', '/'); - if (!entry.isDirectory() && wantedEntry.equals(name)) { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - byte[] chunk = new byte[8192]; - int read; - while ((read = zis.read(chunk)) != -1) { - buffer.write(chunk, 0, read); - } - return buffer.toByteArray(); - } - } - } - return null; - } - - private static String verifyInstalledFiles( - File gameRootDir, - Manifest manifest, - boolean verifyHashes - ) { - File modpackDir = new File(gameRootDir, "modpacks/" + MODPACK_NAME); - File runtimeDir = new File(gameRootDir, "BepInEx"); - File modpackJson = new File(modpackDir, "modpack.json"); - if (!modpackJson.isFile() || modpackJson.length() == 0L) { - return "缺少 modpack.json"; - } - try { - if (!isValidModpackJson(readUtf8(modpackJson).trim())) { - return "modpack.json 内容无效"; - } - } catch (IOException ex) { - return "无法读取 modpack.json"; - } - - for (ManifestEntry entry : manifest.entries.values()) { - if ("modpack.json".equals(entry.relativePath)) { - continue; - } - File modpackCopy = new File(modpackDir, entry.relativePath); - File runtimeCopy = new File(runtimeDir, entry.relativePath); - if (!matchesFile(modpackCopy, entry.size, entry.sha256, verifyHashes)) { - return "模组源目录文件待修复: " + entry.relativePath; - } - if (!matchesFile(runtimeCopy, entry.size, entry.sha256, verifyHashes)) { - return "运行目录文件待修复: " + entry.relativePath; - } - } - return null; - } - - private static boolean matchesFile(File file, long expectedSize, String expectedSha, boolean verifyHash) { - if (!file.isFile() || file.length() != expectedSize) { - return false; - } - if (!verifyHash) { - return true; - } - try { - return expectedSha.equalsIgnoreCase(sha256File(file)); - } catch (IOException ex) { - return false; - } - } - - private static void atomicCopyIfNeeded( - File source, - File target, - long expectedSize, - String expectedSha - ) throws IOException { - if (matchesFile(target, expectedSize, expectedSha, true)) { - return; - } - atomicCopyFile(source, target); - } - - private static void atomicCopyFile(File source, File target) throws IOException { - ensureDir(target.getParentFile()); - File temp = new File(target.getParentFile(), "." + target.getName() + ".bpp-tmp"); - try ( - FileInputStream in = new FileInputStream(source); - FileOutputStream out = new FileOutputStream(temp) - ) { - byte[] buffer = new byte[16 * 1024]; - int read; - while ((read = in.read(buffer)) != -1) { - out.write(buffer, 0, read); - } - out.getFD().sync(); - } - replaceFileAtomically(temp, target); - } - - private static void atomicWriteUtf8(File target, String content) throws IOException { - atomicWriteBytes(target, content.getBytes(StandardCharsets.UTF_8)); - } - - private static void atomicWriteBytes(File target, byte[] bytes) throws IOException { - ensureDir(target.getParentFile()); - File temp = new File(target.getParentFile(), "." + target.getName() + ".bpp-tmp"); - try (FileOutputStream out = new FileOutputStream(temp)) { - out.write(bytes); - out.getFD().sync(); - } - replaceFileAtomically(temp, target); - } - - private static void replaceFileAtomically(File temp, File target) throws IOException { - try { - Files.move( - temp.toPath(), - target.toPath(), - StandardCopyOption.REPLACE_EXISTING, - StandardCopyOption.ATOMIC_MOVE - ); - } catch (IOException atomicEx) { - Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); - } - } - - private static void deleteIfUnmodifiedOwnedFile(File file, String expectedSha) { - if (!file.isFile()) { - return; - } - try { - if (expectedSha.equalsIgnoreCase(sha256File(file))) { - file.delete(); - } - } catch (IOException ignored) { - } - } - - private static InstalledState readInstalledState(File stateFile) { - if (!stateFile.isFile()) { - return null; - } - try { - String content = readUtf8(stateFile); - boolean committed = false; - String bundleId = ""; - Map owned = new LinkedHashMap(); - for (String rawLine : content.split("\n")) { - String line = rawLine.trim(); - if (line.isEmpty()) { - continue; - } - String[] parts = line.split("\t"); - if ("status".equals(parts[0]) && parts.length >= 2) { - committed = "committed".equals(parts[1]); - } else if ("bundle_id".equals(parts[0]) && parts.length >= 2) { - bundleId = parts[1].trim().toLowerCase(Locale.ROOT); - } else if ("owned".equals(parts[0]) && parts.length >= 3) { - String rel = parts[1].trim(); - String sha = parts[2].trim().toLowerCase(Locale.ROOT); - if (isAllowedOwnedSubpath(rel) && isSha256(sha)) { - owned.put(rel, sha); - } - } - } - if (bundleId.isEmpty()) { - return null; - } - return new InstalledState(committed, bundleId, owned); - } catch (IOException ex) { - return null; - } - } - - private static void writeStateFile( - File stateFile, - boolean committed, - String bundleId, - Map ownedHashes - ) throws IOException { - StringBuilder sb = new StringBuilder(); - sb.append("status\t").append(committed ? "committed" : "in_progress").append('\n'); - sb.append("bundle_id\t").append(bundleId.toLowerCase(Locale.ROOT)).append('\n'); - for (Map.Entry entry : ownedHashes.entrySet()) { - sb.append("owned\t") - .append(entry.getKey()) - .append('\t') - .append(entry.getValue().toLowerCase(Locale.ROOT)) - .append('\n'); - } - atomicWriteUtf8(stateFile, sb.toString()); - } - - private static void validateDirectoryEntry(String rawName) throws IOException { - String trimmed = rawName.endsWith("/") ? rawName.substring(0, rawName.length() - 1) : rawName; - if (!"plugins".equals(trimmed) && !"core".equals(trimmed)) { - throw new IOException("Disallowed directory entry in modpack archive: " + rawName); - } - } - - public static String validateOwnedRelativePath(String rawPath) throws IOException { - if (rawPath == null) { - throw new IOException("Null path in modpack."); - } - String path = rawPath.trim(); - if (path.isEmpty() || path.startsWith("/") || path.endsWith("/") || path.indexOf('\\') >= 0) { - throw new IOException("Invalid relative path in modpack: " + rawPath); - } - if ("modpack.json".equals(path)) { - return path; - } - if (!isAllowedOwnedSubpath(path)) { - throw new IOException("Disallowed path in modpack: " + rawPath); - } - return path; - } - - private static boolean isAllowedOwnedSubpath(String path) { - if (path == null || path.indexOf('\\') >= 0) { - return false; - } - String[] segments = path.split("/"); - if (segments.length != 2) { - return false; - } - String dir = segments[0]; - String name = segments[1]; - if (!"plugins".equals(dir) && !"core".equals(dir)) { - return false; - } - if (name.isEmpty() || ".".equals(name) || "..".equals(name)) { - return false; - } - for (int i = 0; i < name.length(); i++) { - char ch = name.charAt(i); - boolean ok = (ch >= 'a' && ch <= 'z') - || (ch >= 'A' && ch <= 'Z') - || (ch >= '0' && ch <= '9') - || ch == '.' - || ch == '_' - || ch == '-'; - if (!ok) { - return false; - } - } - return true; - } - - private static String requireSha256(String value, String label) throws IOException { - String trimmed = value == null ? "" : value.trim().toLowerCase(Locale.ROOT); - if (!isSha256(trimmed)) { - throw new IOException("Invalid SHA-256 for " + label + ": " + value); - } - return trimmed; - } - - private static boolean isSha256(String value) { - if (value == null || value.length() != 64) { - return false; - } - for (int i = 0; i < 64; i++) { - char c = value.charAt(i); - boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); - if (!hex) { - return false; - } - } - return true; - } - - public static String sha256File(File file) throws IOException { - MessageDigest digest = newSha256(); - try (FileInputStream in = new FileInputStream(file)) { - byte[] buffer = new byte[16 * 1024]; - int read; - while ((read = in.read(buffer)) != -1) { - digest.update(buffer, 0, read); - } - } - return toHex(digest.digest()); - } - - private static MessageDigest newSha256() throws IOException { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (Exception ex) { - throw new IOException("SHA-256 unavailable", ex); - } - } - - private static String toHex(byte[] bytes) { - StringBuilder sb = new StringBuilder(bytes.length * 2); - for (byte b : bytes) { - sb.append(Character.forDigit((b >> 4) & 0xF, 16)); - sb.append(Character.forDigit(b & 0xF, 16)); - } - return sb.toString(); - } - - private static String readUtf8(File file) throws IOException { - byte[] bytes = Files.readAllBytes(file.toPath()); - return new String(bytes, StandardCharsets.UTF_8); - } - - private static void ensureDir(File dir) throws IOException { - if (dir == null) { - return; - } - if (dir.isDirectory()) { - return; - } - if (!dir.mkdirs() && !dir.isDirectory()) { - throw new IOException("Unable to create directory: " + dir.getAbsolutePath()); - } - } - - private static void deleteRecursively(File file) { - if (file == null || !file.exists()) { - return; - } - if (file.isDirectory()) { - File[] children = file.listFiles(); - if (children != null) { - for (File child : children) { - deleteRecursively(child); - } - } - } - file.delete(); - } - - private static void notifyProgress(ProgressListener listener, String step, int percent) { - if (listener != null) { - listener.onProgress(step, percent); - } - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticBundle.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticBundle.java deleted file mode 100644 index 59e5737..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticBundle.java +++ /dev/null @@ -1,1724 +0,0 @@ -package com.bepinex.android.bpp; - -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.security.MessageDigest; -import java.time.Instant; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -/** - * Pure-Java diagnostic zip builder. Android collection lives in {@link BppDiagnosticExporter}; - * this type only packs bytes, so a grey-screen report stays readable when a probe fails. - */ -public final class BppDiagnosticBundle { - - public static final int LOG_TAIL_BYTES = 8 * 1024 * 1024; - public static final int SMALL_TEXT_MAX_BYTES = 2 * 1024 * 1024; - public static final int TOTAL_STORED_BYTES = 40 * 1024 * 1024; - public static final int MAX_INCLUDED_FILES = 400; - public static final int MAX_SCAN_DEPTH = 8; - public static final int MAX_TREE_LINES = 1500; - public static final String README_ENTRY = "README.txt"; - public static final String MANIFEST_ENTRY = "manifest.txt"; - public static final String EXPORTER_REVISION = "1"; - - private static final int ELF_PROBE_BYTES = 64 * 1024; - private static final Pattern SENSITIVE_NAME = Pattern.compile( - "(?i)(^|[^a-z0-9])(keystore|jks|p12|pfx|pem|id_rsa|lineage|password|secret|credential|private[-_]?key)([^a-z0-9]|$)" - + "|\\.(keystore|jks|p12|pfx|pem)$" - ); - private static final Pattern PREF_XML_SECRET = Pattern.compile( - "(?i)(<[^>]*\\bname\\s*=\\s*\"[^\"]*(?:password|secret|token|keystore|credential|lineage)[^\"]*\"[^>]*>)(.*?)( HEAVY_DIRS = new HashSet(Arrays.asList( - "plugins", "core", "dotnet", "cache", "il2cpp", "unity", "extracted", "odex", "oat" - )); - - private BppDiagnosticBundle() {} - - public static final class TextEntry { - public final String archivePath; - public final String content; - - public TextEntry(String archivePath, String content) { - this.archivePath = archivePath; - this.content = content == null ? "" : content; - } - } - - public static final class ScanRoot { - public final File directory; - public final String label; - /** When true, small text and DataStore files in this directory are logs/prefs, not game data. */ - public final boolean stateTree; - - public ScanRoot(File directory, String label) { - this(directory, label, false); - } - - public ScanRoot(File directory, String label, boolean stateTree) { - this.directory = directory; - this.label = label; - this.stateTree = stateTree; - } - } - - public static final class ExtraFile { - public final File file; - public final String archivePath; - public final boolean logTail; - public final int maxBytes; - - public ExtraFile(File file, String archivePath, boolean logTail) { - this(file, archivePath, logTail, 0); - } - - public ExtraFile(File file, String archivePath, boolean logTail, int maxBytes) { - this.file = file; - this.archivePath = archivePath; - this.logTail = logTail; - this.maxBytes = maxBytes; - } - } - - public static final class Request { - public final String readme; - public final List texts; - public final List scans; - public final List extras; - - public Request(String readme, List texts, List scans, List extras) { - this.readme = readme == null ? "" : readme; - this.texts = texts == null ? new ArrayList() : texts; - this.scans = scans == null ? new ArrayList() : scans; - this.extras = extras == null ? new ArrayList() : extras; - } - } - - public static final class Result { - public final int includedFiles; - public final int unavailable; - public final int omitted; - public final long storedBytes; - - Result(int includedFiles, int unavailable, int omitted, long storedBytes) { - this.includedFiles = includedFiles; - this.unavailable = unavailable; - this.omitted = omitted; - this.storedBytes = storedBytes; - } - } - - public static String nowIso() { - return DateTimeFormatter.ISO_INSTANT.format(Instant.now()); - } - - public static String readme(String generatedAt, String launcherVersion, String packageName) { - return "" - + "BazaarPlusPlus Android 诊断包\n" - + "================================\n" - + "生成时间:" + safe(generatedAt) + "\n" - + "启动器:" + safe(launcherVersion) + "\n" - + "包名:" + safe(packageName) + "\n" - + "\n" - + "这个压缩包由启动器首页「导出诊断日志」生成,用来反馈灰屏、闪退、卡在启动或模组没有生效。\n" - + "导出后会保存到系统「下载」,并可通过系统分享面板发出。请把整个 zip 发给维护者,或附在 GitHub Issue。\n" - + "\n" - + "包里可能有设备型号、系统指纹、应用路径、日志里的对局编号和 ANDROID_ID。\n" - + "不包含:对局历史数据库、录像、插件 DLL / SO 本体、签名私钥、keystore、口令。\n" - + "配置里名字像 password、token、secret 的值会打成 [redacted]。\n" - + "\n" - + "建议复现方式:\n" - + "1. 打开 BPP Android(此时开始滚动记录 logcat)。\n" - + "2. 点击「启动 The Bazaar(BPP 模组)」,等到灰屏或闪退。\n" - + "3. 回到启动器,再点「导出诊断日志」。\n" - + "上次启动会留在 launch/。若系统把启动器进程杀掉,灰屏后半段只保留游戏进程里已经写盘的记录。\n" - + "\n" - + "目录:\n" - + "- README.txt 本说明\n" - + "- manifest.txt 已收入、被截断、读不到、主动跳过的清单。沙箱不允许的路径记在这里,而不是让启动器崩溃\n" - + "- device/ 厂商、机型、指纹、Android / SDK、ABI、页大小、安全补丁、内存、存储、屏幕与刘海、getprop\n" - + "- packages/ 启动器与 The Bazaar 的版本、安装时间、签名证书 SHA-256、分包 APK、libil2cpp 大小、哈希和 ELF 对齐\n" - + "- deploy/ 内置模组部署状态、状态文件、目录树、清单\n" - + "- launch/ 每次点击启动的记录、gamePid、滚动 logcat、game-heartbeat.log 和卡住时的线程堆栈\n" - + "- logcat/ 点导出时能读到的各 buffer 转储\n" - + "- logs/ BepInEx LogOutput、preloader、BPP trace、Unity Player.log、配置、可读 tombstone\n" - + "- crashes/ getHistoricalProcessExitReasons(含 :game)和 trace;系统 tombstone 目录若不可读会记在 manifest\n" - + "- jit/ jit-stdout.log=JitDisasmSummary(最后一行是最后完成编译的方法,崩溃方法正在其后再编译);coreclr-stderr.log=CoreCLR stderr(fatal/assert);jit-*.nettrace=EventPipe JIT 事件(MethodJittingStarted,用 PerfView 或 `dotnet-trace convert` 打开);jit-trace-env.txt=环境变量与 fd 指向\n" - + "- state/ 启动器 SharedPreferences 与 DataStore\n" - + "\n" - + "manifest.txt 的 [unavailable] 表示当时读不到,不代表手机上一定没有这个文件。\n" - + "大日志只保留末尾一段,并在文件头写明 originalBytes。\n" - + "\n" - + "English: one shareable zip of device, package, modpack deploy state, rolling launch logcat,\n" - + "BepInEx/Unity logs, exit reasons, and launcher prefs. Databases and signing secrets are omitted.\n" - + "Failures are listed in manifest.txt. The launcher keeps a rolling logcat so a grey screen can be\n" - + "exported after returning to this app.\n"; - } - - /** - * Periodic {@code logcat -d} (the process exits, so its output is flushed). - * {@code logcat -f} block-buffers about 8 KB and a grey-screen capture then stops at that size. - */ - public static List rollingLogcatCommand(File ignored) { - return rollingLogcatCommand(0); - } - - public static List rollingLogcatCommand(int pid) { - List command = new ArrayList(); - command.add("logcat"); - command.add("-d"); - command.add("-v"); - command.add("threadtime"); - command.add("-b"); - command.add("main"); - command.add("-b"); - command.add("system"); - command.add("-b"); - command.add("crash"); - command.add("-b"); - command.add("events"); - if (pid > 0) command.add("--pid=" + pid); - return command; - } - - /** Lines after the previous dump's last line. A missing marker means the ring buffer rotated. */ - public static String suffixAfterMarker(String dump, String markerLine) { - if (dump == null || dump.length() == 0) return ""; - if (markerLine == null || markerLine.length() == 0) return dump; - int at = dump.lastIndexOf(markerLine); - if (at < 0) return "[buffer-rotated]\n" + dump; - int next = at + markerLine.length(); - if (next < dump.length() && dump.charAt(next) == '\n') next++; - if (next >= dump.length()) return ""; - return dump.substring(next); - } - - public static String lastLogLine(String dump) { - if (dump == null) return ""; - int end = dump.length(); - while (end > 0 && (dump.charAt(end - 1) == '\n' || dump.charAt(end - 1) == '\r')) end--; - if (end == 0) return ""; - int start = dump.lastIndexOf('\n', end - 1); - return dump.substring(start + 1, end); - } - - public static final String[] LOGCAT_BUFFERS = new String[] { - "main", "system", "crash", "events", "radio", "kernel", "security" - }; - - public static List dumpLogcatCommand(String buffer) { - return dumpLogcatCommand(buffer, 0); - } - - public static List dumpLogcatCommand(String buffer, int pid) { - List command = new ArrayList(); - command.add("logcat"); - command.add("-d"); - command.add("-v"); - command.add("threadtime"); - command.add("-b"); - command.add(buffer == null || buffer.length() == 0 ? "all" : buffer); - if (pid > 0) command.add("--pid=" + pid); - return command; - } - - public static boolean commandClearsLogcat(List command) { - if (command == null) return false; - for (int i = 0; i < command.size(); i++) { - String arg = command.get(i); - if ("-c".equals(arg) || "--clear".equals(arg)) return true; - } - return false; - } - - public static String captureProcessText(List command, long timeoutMs, int maxBytes) { - try { - byte[] data = captureProcess(command, timeoutMs, maxBytes); - return new String(data, StandardCharsets.UTF_8); - } catch (Exception ex) { - return "[unavailable] " + ex.getClass().getName() + ": " + ex.getMessage() + "\n"; - } - } - - public static byte[] captureProcess(List command, long timeoutMs, int maxBytes) - throws IOException, InterruptedException { - if (command == null || command.isEmpty()) { - throw new IOException("empty command"); - } - if (commandClearsLogcat(command)) { - throw new IOException("refusing logcat -c"); - } - ProcessBuilder pb = new ProcessBuilder(command); - pb.redirectErrorStream(true); - final Process process = pb.start(); - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final int limit = Math.max(0, maxBytes); - Thread reader = new Thread(new Runnable() { - @Override - public void run() { - byte[] buf = new byte[8192]; - try { - InputStream in = process.getInputStream(); - int n; - while ((n = in.read(buf)) != -1) { - synchronized (bos) { - if (bos.size() < limit) { - bos.write(buf, 0, Math.min(n, limit - bos.size())); - } - } - } - } catch (IOException ignored) { - } - } - }, "bpp-diag-read"); - reader.setDaemon(true); - reader.start(); - boolean finished = process.waitFor(Math.max(1L, timeoutMs), TimeUnit.MILLISECONDS); - if (!finished) { - process.destroyForcibly(); - } - reader.join(2000L); - if (process.isAlive()) { - process.destroyForcibly(); - } - synchronized (bos) { - return bos.toByteArray(); - } - } - - public static void appendCapped(File file, String line, int maxBytes) throws IOException { - if (file == null) throw new IOException("missing append target"); - String payload = line == null ? "\n" : (line.endsWith("\n") ? line : line + "\n"); - byte[] incoming = payload.getBytes(StandardCharsets.UTF_8); - int cap = Math.max(incoming.length, maxBytes); - File parent = file.getParentFile(); - if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { - throw new IOException("cannot create " + parent.getAbsolutePath()); - } - synchronized (BppDiagnosticBundle.class) { - try (RandomAccessFile raf = new RandomAccessFile(file, "rw"); - FileChannel channel = raf.getChannel(); - FileLock ignored = channel.lock()) { - int existingLength = (int) Math.min(raf.length(), cap); - byte[] existing = new byte[existingLength]; - if (existingLength > 0 && raf.length() > cap) { - raf.seek(raf.length() - existingLength); - } else { - raf.seek(0L); - } - raf.readFully(existing); - byte[] combined = new byte[existing.length + incoming.length]; - System.arraycopy(existing, 0, combined, 0, existing.length); - System.arraycopy(incoming, 0, combined, existing.length, incoming.length); - byte[] stored = combined; - if (combined.length > cap) { - int start = combined.length - cap; - int newline = -1; - int scanEnd = Math.min(combined.length - 1, start + 4096); - for (int i = start; i < scanEnd; i++) { - if (combined[i] == '\n') { - newline = i + 1; - break; - } - } - if (newline > 0 && newline < combined.length) start = newline; - stored = new byte[combined.length - start]; - System.arraycopy(combined, start, stored, 0, stored.length); - } - raf.seek(0L); - raf.write(stored); - raf.setLength(stored.length); - channel.force(true); - } - } - } - - public static boolean isSensitivePath(String path) { - if (path == null || path.length() == 0) return false; - String normalized = path.replace('\\', '/'); - int slash = normalized.lastIndexOf('/'); - String name = slash >= 0 ? normalized.substring(slash + 1) : normalized; - return SENSITIVE_NAME.matcher(name).find() || SENSITIVE_NAME.matcher(normalized).find(); - } - - public static String redactPreferenceText(String text) { - if (text == null || text.length() == 0) return ""; - Matcher xml = PREF_XML_SECRET.matcher(text); - StringBuffer xmlOut = new StringBuffer(); - while (xml.find()) { - xml.appendReplacement(xmlOut, Matcher.quoteReplacement(xml.group(1) + "[redacted]" + xml.group(3))); - } - xml.appendTail(xmlOut); - String[] lines = xmlOut.toString().split("\n", -1); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < lines.length; i++) { - Matcher line = PREF_LINE_SECRET.matcher(lines[i]); - if (line.find()) { - sb.append(line.group(1)).append("=[redacted]"); - } else { - sb.append(lines[i]); - } - if (i + 1 < lines.length) sb.append('\n'); - } - return sb.toString(); - } - - public static String sanitizeArchivePath(String raw) { - if (raw == null) return null; - String path = raw.replace('\\', '/').trim(); - while (path.startsWith("/")) path = path.substring(1); - if (path.length() == 0) return null; - String[] parts = path.split("/"); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < parts.length; i++) { - String part = parts[i]; - if (part.length() == 0 || ".".equals(part) || "..".equals(part)) return null; - if (part.indexOf('\0') >= 0) return null; - if (sb.length() > 0) sb.append('/'); - sb.append(part); - } - String cleaned = sb.toString(); - if (README_ENTRY.equals(cleaned) || MANIFEST_ENTRY.equals(cleaned)) return null; - return cleaned; - } - - public static String describeElfLoadSegments(byte[] data, String source) { - StringBuilder sb = new StringBuilder(); - sb.append("source=").append(source == null ? "" : source).append('\n'); - if (data == null || data.length < 64 - || data[0] != 0x7f || data[1] != 'E' || data[2] != 'L' || data[3] != 'F') { - sb.append("elf=unrecognized\n"); - return sb.toString(); - } - int cls = data[4] & 0xff; - int encoding = data[5] & 0xff; - sb.append("class=").append(cls).append(" dataEncoding=").append(encoding).append('\n'); - ByteOrder order = encoding == 2 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; - ByteBuffer buf = ByteBuffer.wrap(data).order(order); - try { - long minAlign = Long.MAX_VALUE; - if (cls == 2) { - long phoff = buf.getLong(32); - int phentsize = buf.getShort(54) & 0xffff; - int phnum = buf.getShort(56) & 0xffff; - sb.append("phoff=").append(phoff) - .append(" phentsize=").append(phentsize) - .append(" phnum=").append(phnum).append('\n'); - minAlign = appendLoadSegments(sb, buf, data.length, phoff, phentsize, phnum, true); - } else if (cls == 1) { - long phoff = buf.getInt(28) & 0xffffffffL; - int phentsize = buf.getShort(42) & 0xffff; - int phnum = buf.getShort(44) & 0xffff; - sb.append("phoff=").append(phoff) - .append(" phentsize=").append(phentsize) - .append(" phnum=").append(phnum).append('\n'); - minAlign = appendLoadSegments(sb, buf, data.length, phoff, phentsize, phnum, false); - } else { - sb.append("elf=unknown-class\n"); - } - if (minAlign != Long.MAX_VALUE) sb.append("minLoadAlign=").append(minAlign).append('\n'); - } catch (RuntimeException ex) { - sb.append("elfError=").append(ex).append('\n'); - } - return sb.toString(); - } - - public static String renderTree(File root, int maxLines, int maxDepth) { - StringBuilder sb = new StringBuilder(); - if (root == null || !root.exists()) { - return "(missing)\n"; - } - if (!root.canRead()) { - return "(unreadable) " + root.getAbsolutePath() + "\n"; - } - int[] lines = new int[] {0}; - boolean[] truncated = new boolean[] {false}; - walkTree(root, root, 0, Math.max(1, maxDepth), Math.max(1, maxLines), lines, truncated, sb); - if (truncated[0]) sb.append("... truncated\n"); - return sb.toString(); - } - - public static String sha256Hex(File file, long maxBytes) throws IOException { - MessageDigest digest = newSha256(); - long total = 0L; - try (InputStream in = new java.io.FileInputStream(file)) { - byte[] buf = new byte[65536]; - int n; - while ((n = in.read(buf)) != -1) { - total += n; - if (maxBytes >= 0 && total > maxBytes) { - throw new IOException("hash cap exceeded"); - } - digest.update(buf, 0, n); - } - } - return toHex(digest.digest()); - } - - public static Result write(File zipFile, Request request) throws IOException { - return write(zipFile, request, LOG_TAIL_BYTES, SMALL_TEXT_MAX_BYTES, TOTAL_STORED_BYTES, MAX_INCLUDED_FILES); - } - - static Result write( - File zipFile, - Request request, - int logTailBytes, - int smallTextMax, - int totalCap, - int maxFiles - ) throws IOException { - if (zipFile == null) throw new IOException("missing zip destination"); - if (request == null) throw new IOException("missing diagnostic request"); - List unavailable = new ArrayList(); - List omitted = new ArrayList(); - List slices = new ArrayList(); - Set seenFiles = new HashSet(); - Set usedPaths = new HashSet(); - Budget budget = new Budget(Math.max(0, totalCap), Math.max(0, maxFiles)); - int[] skippedPolicy = new int[] {0}; - - for (int i = 0; i < request.texts.size(); i++) { - TextEntry text = request.texts.get(i); - addInline(slices, usedPaths, unavailable, omitted, budget, text, smallTextMax); - } - for (int i = 0; i < request.scans.size(); i++) { - scanRoot(request.scans.get(i), slices, usedPaths, seenFiles, unavailable, omitted, - budget, skippedPolicy, logTailBytes, smallTextMax); - } - for (int i = 0; i < request.extras.size(); i++) { - ExtraFile extra = request.extras.get(i); - addExtra(extra, slices, usedPaths, seenFiles, unavailable, omitted, budget, logTailBytes, smallTextMax); - } - if (skippedPolicy[0] > 0) { - omitted.add("summary\tskipped-by-policy\t" + skippedPolicy[0]); - } - - File parent = zipFile.getParentFile(); - if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { - throw new IOException("cannot create " + parent.getAbsolutePath()); - } - long stored = 0L; - List includedFinal = new ArrayList(); - try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))) { - byte[] readmeBytes = request.readme.getBytes(StandardCharsets.UTF_8); - putBytes(zos, README_ENTRY, readmeBytes, System.currentTimeMillis()); - stored += readmeBytes.length; - for (int i = 0; i < slices.size(); i++) { - Slice slice = slices.get(i); - try { - Stored storedEntry = writeSlice(zos, slice); - stored += storedEntry.storedBytes; - includedFinal.add(slice.archivePath - + "\t" + slice.originalSize - + "\t" + storedEntry.storedBytes - + "\t" + storedEntry.sha256 - + "\t" + slice.note); - } catch (IOException ex) { - unavailable.add(slice.archivePath + "\twrite-failed\t" + oneLine(ex.toString())); - } - } - String manifest = renderManifest(includedFinal, unavailable, omitted, stored); - byte[] manifestBytes = manifest.getBytes(StandardCharsets.UTF_8); - putBytes(zos, MANIFEST_ENTRY, manifestBytes, System.currentTimeMillis()); - stored += manifestBytes.length; - } - return new Result(includedFinal.size(), unavailable.size(), omitted.size(), stored); - } - - private static void addInline( - List slices, - Set usedPaths, - List unavailable, - List omitted, - Budget budget, - TextEntry text, - int smallTextMax - ) { - if (text == null) return; - String path = uniquePath(usedPaths, text.archivePath); - if (path == null) { - unavailable.add(String.valueOf(text.archivePath) + "\trejected-archive-path"); - return; - } - if (isSensitivePath(path)) { - omitted.add(path + "\tsensitive-name"); - return; - } - byte[] raw = text.content.getBytes(StandardCharsets.UTF_8); - String note = "inline"; - if (isPreferencePath(path)) { - raw = redactPreferenceText(new String(raw, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); - note = "inline-redacted"; - } - long original = raw.length; - if (smallTextMax > 0 && raw.length > smallTextMax) { - byte[] head = new byte[smallTextMax]; - System.arraycopy(raw, 0, head, 0, smallTextMax); - raw = head; - note = note + "-head"; - } - if (!budget.take(raw.length)) { - omitted.add(path + "\tskipped-over-remaining-budget"); - if (budget.files <= 0) noteBudget(omitted, budget); - return; - } - slices.add(new Slice(path, raw, null, 0L, raw.length, original, note)); - } - - private static void scanRoot( - ScanRoot root, - List slices, - Set usedPaths, - Set seenFiles, - List unavailable, - List omitted, - Budget budget, - int[] skippedPolicy, - int logTailBytes, - int smallTextMax - ) { - String label = root == null || root.label == null ? "scan" : root.label; - if (root == null || root.directory == null) { - unavailable.add(label + "\tmissing"); - return; - } - File dir = root.directory; - if (!dir.exists()) { - unavailable.add(label + "\tmissing\t" + dir.getAbsolutePath()); - return; - } - if (!dir.canRead()) { - unavailable.add(label + "\tunreadable\t" + dir.getAbsolutePath()); - return; - } - if (!dir.isDirectory()) { - ExtraFile extra = new ExtraFile(dir, label, true); - addExtra(extra, slices, usedPaths, seenFiles, unavailable, omitted, budget, logTailBytes, smallTextMax); - return; - } - walk(dir, dir, label, root.stateTree, 0, slices, usedPaths, seenFiles, unavailable, omitted, budget, - skippedPolicy, logTailBytes, smallTextMax); - } - - private static void walk( - File root, - File dir, - String label, - boolean stateTree, - int depth, - List slices, - Set usedPaths, - Set seenFiles, - List unavailable, - List omitted, - Budget budget, - int[] skippedPolicy, - int logTailBytes, - int smallTextMax - ) { - if (budget.files <= 0) return; - if (depth > MAX_SCAN_DEPTH) { - omitted.add(label + "\tmax-depth\t" + safeRelative(root, dir)); - return; - } - File[] children = dir.listFiles(); - if (children == null) { - unavailable.add(label + "/" + safeRelative(root, dir) + "\tunreadable"); - return; - } - Arrays.sort(children, new Comparator() { - @Override - public int compare(File a, File b) { - return a.getName().compareTo(b.getName()); - } - }); - for (int i = 0; i < children.length; i++) { - if (budget.files <= 0) return; - File child = children[i]; - String name = child.getName(); - if (".".equals(name) || "..".equals(name)) continue; - String relative = safeRelative(root, child); - if (isSensitivePath(name) || isSensitivePath(relative)) { - omitted.add(label + "/" + relative + "\tsensitive-name"); - continue; - } - if (isSymlinkEscape(root, child)) { - omitted.add(label + "/" + relative + "\tsymlink-escape"); - continue; - } - if (child.isDirectory()) { - if (HEAVY_DIRS.contains(name) || name.startsWith("staging-")) { - omitted.add(label + "/" + relative + "\tskipped-heavy-dir"); - continue; - } - walk(root, child, label, stateTree, depth + 1, slices, usedPaths, seenFiles, unavailable, omitted, - budget, skippedPolicy, logTailBytes, smallTextMax); - continue; - } - if (!child.isFile()) { - skippedPolicy[0]++; - continue; - } - if (isDatabaseName(name)) { - omitted.add(label + "/" + relative + "\tdatabase\t" + child.length()); - continue; - } - if (!shouldInclude(relative, name) && !(stateTree && includeStateFile(name))) { - skippedPolicy[0]++; - continue; - } - if (!child.canRead()) { - unavailable.add(label + "/" + relative + "\tunreadable"); - continue; - } - String canonical = canonical(child); - if (canonical != null && !seenFiles.add(canonical)) continue; - String archive = uniquePath(usedPaths, label + "/" + relative); - if (archive == null) { - unavailable.add(label + "/" + relative + "\trejected-archive-path"); - continue; - } - addSliceForFile(slices, budget, omitted, child, archive, modeFor(relative, name), logTailBytes, smallTextMax, 0); - } - } - - private static void addExtra( - ExtraFile extra, - List slices, - Set usedPaths, - Set seenFiles, - List unavailable, - List omitted, - Budget budget, - int logTailBytes, - int smallTextMax - ) { - if (extra == null) return; - String archive = uniquePath(usedPaths, extra.archivePath); - if (archive == null) { - unavailable.add(String.valueOf(extra.archivePath) + "\trejected-archive-path"); - return; - } - if (extra.file == null || !extra.file.exists()) { - unavailable.add(archive + "\tmissing"); - return; - } - if (isSensitivePath(extra.file.getName()) || isSensitivePath(archive)) { - omitted.add(archive + "\tsensitive-name"); - return; - } - if (!extra.file.canRead() || !extra.file.isFile()) { - unavailable.add(archive + "\tunreadable"); - return; - } - String canonical = canonical(extra.file); - if (canonical != null && !seenFiles.add(canonical)) return; - Mode mode = extra.logTail ? Mode.TAIL : modeFor(archive, extra.file.getName()); - int capOverride = 0; - if (extra.maxBytes > 0) { - long size = extra.file.length(); - if (size > extra.maxBytes) { - omitted.add(archive + "\tskipped-over-cap\t" + size); - return; - } - capOverride = extra.maxBytes; - if (!extra.logTail) mode = Mode.FULL; - } - addSliceForFile(slices, budget, omitted, extra.file, archive, mode, logTailBytes, smallTextMax, capOverride); - } - - private static void addSliceForFile( - List slices, - Budget budget, - List omitted, - File file, - String archive, - Mode mode, - int logTailBytes, - int smallTextMax, - int capOverride - ) { - long size; - try { - size = file.length(); - } catch (RuntimeException ex) { - omitted.add(archive + "\tunreadable-size"); - return; - } - int cap = mode == Mode.TAIL ? logTailBytes : smallTextMax; - if (capOverride > 0) cap = capOverride; - if (cap < 1) cap = 1; - long offset = 0L; - long length = size; - String note = "full"; - if (size > cap) { - if (mode == Mode.TAIL) { - offset = size - cap; - length = cap; - note = "tail"; - } else { - length = cap; - note = "head"; - } - } - boolean redact = isPreferencePath(archive); - if (redact) note = note + "-redacted"; - long storedGuess = length + (size > cap ? 160 : 0); - if (!budget.take(storedGuess)) { - omitted.add(archive + "\tskipped-over-remaining-budget"); - if (budget.files <= 0) noteBudget(omitted, budget); - return; - } - slices.add(new Slice(archive, null, file, offset, length, size, note)); - } - - private static Stored writeSlice(ZipOutputStream zos, Slice slice) throws IOException { - MessageDigest digest = newSha256(); - ZipEntry entry = new ZipEntry(slice.archivePath); - if (slice.file != null) entry.setTime(slice.file.lastModified()); - else entry.setTime(System.currentTimeMillis()); - zos.putNextEntry(entry); - long stored = 0L; - if (slice.inline != null) { - byte[] data = slice.inline; - if (isPreferencePath(slice.archivePath)) { - data = redactPreferenceText(new String(data, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); - } - zos.write(data); - digest.update(data); - stored = data.length; - } else { - boolean partial = slice.offset > 0 || slice.length < slice.originalSize; - if (partial) { - byte[] banner = ("[bpp-diagnostic-truncated] originalBytes=" + slice.originalSize - + " includedBytes=" + slice.length - + " offset=" + slice.offset - + " note=" + slice.note + "\n").getBytes(StandardCharsets.UTF_8); - zos.write(banner); - digest.update(banner); - stored += banner.length; - } - byte[] data = readRange(slice.file, slice.offset, slice.length); - if (isPreferencePath(slice.archivePath)) { - data = redactPreferenceText(new String(data, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); - } - zos.write(data); - digest.update(data); - stored += data.length; - } - zos.closeEntry(); - return new Stored(stored, toHex(digest.digest())); - } - - private static byte[] readRange(File file, long offset, long length) throws IOException { - if (length > Integer.MAX_VALUE - 8) throw new IOException("range too large"); - int want = (int) Math.max(0L, length); - byte[] data = new byte[want]; - try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { - raf.seek(Math.max(0L, offset)); - int off = 0; - while (off < want) { - int n = raf.read(data, off, want - off); - if (n < 0) break; - off += n; - } - if (off == want) return data; - byte[] trimmed = new byte[off]; - System.arraycopy(data, 0, trimmed, 0, off); - return trimmed; - } - } - - static boolean shouldInclude(String relative, String name) { - if (name == null || name.length() == 0) return false; - String lowerName = name.toLowerCase(Locale.ROOT); - String lowerRel = relative == null ? lowerName : relative.toLowerCase(Locale.ROOT); - if (isSensitivePath(lowerName) || isSensitivePath(lowerRel)) return false; - if (isDatabaseName(lowerName)) return false; - if (isArchiveOrBinary(lowerName) && !lowerName.startsWith("tombstone")) return false; - if (lowerName.startsWith("tombstone") || lowerRel.contains("tombstone")) return true; - if (isLogName(lowerName)) return true; - if ("modpack.json".equals(lowerName) || lowerName.endsWith(".state") || lowerName.endsWith(".cfg")) { - return true; - } - boolean configish = lowerRel.contains("/config/") || lowerRel.startsWith("config/") - || lowerRel.contains("shared_prefs/") || lowerRel.contains("shared-prefs/") - || lowerRel.contains("/datastore/") || lowerRel.contains("datastore/") - || lowerRel.contains("bpp-diagnostics/") || lowerRel.startsWith("bpp-diagnostics/") - || lowerRel.contains("no_backup/") || lowerRel.contains("no-backup/"); - if (configish && isTextConfig(lowerName)) return true; - if ((lowerRel.contains("/bepinex/") || lowerRel.startsWith("bepinex/")) && isTextConfig(lowerName)) { - return true; - } - if (hasSegment(lowerRel, "logs") && !isArchiveOrBinary(lowerName)) return true; - if (lowerRel.contains("persistentdata/") && isTextConfig(lowerName)) return true; - return false; - } - - private static boolean includeStateFile(String name) { - String lowerName = name == null ? "" : name.toLowerCase(Locale.ROOT); - if (isDatabaseName(lowerName) || isArchiveOrBinary(lowerName) || isSensitivePath(lowerName)) return false; - return isTextConfig(lowerName) || lowerName.endsWith(".preferences_pb") || lowerName.endsWith(".pb"); - } - - private static boolean hasSegment(String lowerRel, String segment) { - String padded = "/" + (lowerRel == null ? "" : lowerRel) + "/"; - return padded.contains("/" + segment + "/"); - } - - private static boolean isLogName(String lowerName) { - return lowerName.endsWith(".log") - || lowerName.endsWith(".trace") - || lowerName.endsWith(".stacktrace") - || lowerName.endsWith(".stderr") - || lowerName.contains("logcat") - || lowerName.contains("player.log") - || lowerName.equals("traces.txt") - || lowerName.equals("logoutput.log") - || lowerName.equals("errorlog.log"); - } - - private static boolean isTextConfig(String lowerName) { - return lowerName.endsWith(".xml") - || lowerName.endsWith(".json") - || lowerName.endsWith(".txt") - || lowerName.endsWith(".properties") - || lowerName.endsWith(".tsv") - || lowerName.endsWith(".ini") - || lowerName.endsWith(".cfg") - || lowerName.endsWith(".state"); - } - - private static boolean isDatabaseName(String lowerName) { - return lowerName.endsWith(".db") - || lowerName.endsWith(".sqlite") - || lowerName.endsWith(".sqlite3") - || lowerName.endsWith(".db-wal") - || lowerName.endsWith(".db-shm") - || lowerName.endsWith(".sqlite-wal") - || lowerName.endsWith(".sqlite-shm") - || lowerName.endsWith(".wal") - || lowerName.endsWith(".shm"); - } - - private static boolean isArchiveOrBinary(String lowerName) { - return lowerName.endsWith(".dll") - || lowerName.endsWith(".so") - || lowerName.endsWith(".dex") - || lowerName.endsWith(".apk") - || lowerName.endsWith(".zip") - || lowerName.endsWith(".mp4") - || lowerName.endsWith(".png") - || lowerName.endsWith(".jpg") - || lowerName.endsWith(".jpeg") - || lowerName.endsWith(".webp") - || lowerName.endsWith(".gif") - || lowerName.endsWith(".pdb") - || lowerName.endsWith(".dat") - || lowerName.endsWith(".bin") - || lowerName.endsWith(".jar") - || lowerName.endsWith(".bundle"); - } - - private static Mode modeFor(String relative, String name) { - String lowerName = name == null ? "" : name.toLowerCase(Locale.ROOT); - String lowerRel = relative == null ? "" : relative.toLowerCase(Locale.ROOT); - if (isLogName(lowerName) || lowerName.startsWith("tombstone") || lowerRel.contains("/logs/")) { - return Mode.TAIL; - } - return Mode.HEAD; - } - - private static boolean isPreferencePath(String archivePath) { - String lower = archivePath == null ? "" : archivePath.toLowerCase(Locale.ROOT); - boolean prefs = lower.contains("shared_prefs/") - || lower.contains("shared-prefs/") - || lower.contains("/datastore/") - || lower.contains("datastore/") - || lower.contains("no_backup/") - || lower.contains("no-backup/"); - return prefs && (lower.endsWith(".xml") || lower.endsWith(".txt") || lower.endsWith(".properties") - || lower.endsWith(".cfg") || lower.endsWith(".json")); - } - - private static void walkTree( - File root, - File dir, - int depth, - int maxDepth, - int maxLines, - int[] lines, - boolean[] truncated, - StringBuilder sb - ) { - if (truncated[0] || lines[0] >= maxLines) { - truncated[0] = true; - return; - } - File[] children = dir.listFiles(); - if (children == null) { - appendTreeLine(sb, lines, "unreadable", dir.lastModified(), safeRelative(root, dir)); - return; - } - Arrays.sort(children, new Comparator() { - @Override - public int compare(File a, File b) { - return a.getName().compareTo(b.getName()); - } - }); - for (int i = 0; i < children.length; i++) { - if (lines[0] >= maxLines) { - truncated[0] = true; - return; - } - File child = children[i]; - String relative = safeRelative(root, child); - if (child.isDirectory()) { - appendTreeLine(sb, lines, "dir", child.lastModified(), relative + "/"); - boolean shallow = HEAVY_DIRS.contains(child.getName()) || child.getName().startsWith("staging-"); - if (depth + 1 >= maxDepth || shallow) { - if (shallow) { - File[] nested = child.listFiles(); - int count = nested == null ? -1 : nested.length; - appendTreeLine(sb, lines, "children=" + count, child.lastModified(), relative + "/"); - if (nested != null && (child.getName().equals("plugins") || child.getName().equals("core"))) { - Arrays.sort(nested, new Comparator() { - @Override - public int compare(File a, File b) { - return a.getName().compareTo(b.getName()); - } - }); - for (int n = 0; n < nested.length && lines[0] < maxLines; n++) { - File leaf = nested[n]; - appendTreeLine(sb, lines, String.valueOf(leaf.length()), leaf.lastModified(), - safeRelative(root, leaf)); - } - } - } - continue; - } - walkTree(root, child, depth + 1, maxDepth, maxLines, lines, truncated, sb); - } else { - appendTreeLine(sb, lines, String.valueOf(child.length()), child.lastModified(), relative); - } - } - } - - private static void appendTreeLine(StringBuilder sb, int[] lines, String size, long mtime, String relative) { - lines[0]++; - sb.append(size).append('\t').append(mtime).append('\t').append(relative).append('\n'); - } - - private static long appendLoadSegments( - StringBuilder sb, - ByteBuffer buf, - int dataLength, - long phoff, - int phentsize, - int phnum, - boolean elf64 - ) { - long minAlign = Long.MAX_VALUE; - if (phentsize <= 0 || phnum < 0 || phnum > 64 || phoff < 0) { - sb.append("phdrInvalid\n"); - return minAlign; - } - for (int i = 0; i < phnum; i++) { - long offLong = phoff + (long) i * phentsize; - if (offLong < 0 || offLong + (elf64 ? 56 : 32) > dataLength) { - sb.append("phdrTruncated index=").append(i).append('\n'); - break; - } - int off = (int) offLong; - int type = buf.getInt(off); - if (type != 1) continue; - long offset; - long vaddr; - long filesz; - long memsz; - long align; - if (elf64) { - offset = buf.getLong(off + 8); - vaddr = buf.getLong(off + 16); - filesz = buf.getLong(off + 32); - memsz = buf.getLong(off + 40); - align = buf.getLong(off + 48); - } else { - offset = buf.getInt(off + 4) & 0xffffffffL; - vaddr = buf.getInt(off + 8) & 0xffffffffL; - filesz = buf.getInt(off + 16) & 0xffffffffL; - memsz = buf.getInt(off + 20) & 0xffffffffL; - align = buf.getInt(off + 28) & 0xffffffffL; - } - sb.append("PT_LOAD offset=").append(offset) - .append(" vaddr=").append(vaddr) - .append(" filesz=").append(filesz) - .append(" memsz=").append(memsz) - .append(" align=").append(align).append('\n'); - if (align > 0 && align < minAlign) minAlign = align; - } - return minAlign; - } - - private static String renderManifest( - List included, - List unavailable, - List omitted, - long storedBytes - ) { - StringBuilder sb = new StringBuilder(); - sb.append("# BPP Android diagnostic manifest\n"); - sb.append("# revision\t").append(EXPORTER_REVISION).append('\n'); - sb.append("# generated\t").append(nowIso()).append('\n'); - sb.append("# storedBytes\t").append(storedBytes).append('\n'); - sb.append("# included columns: archivePath originalBytes storedBytes sha256 note\n"); - sb.append("\n[included]\n"); - appendLines(sb, included); - sb.append("\n[unavailable]\n"); - appendLines(sb, unavailable); - sb.append("\n[omitted]\n"); - appendLines(sb, omitted); - sb.append('\n'); - return sb.toString(); - } - - private static void appendLines(StringBuilder sb, List lines) { - if (lines.isEmpty()) { - sb.append("(none)\n"); - return; - } - for (int i = 0; i < lines.size(); i++) sb.append(lines.get(i)).append('\n'); - } - - private static void putBytes(ZipOutputStream zos, String name, byte[] data, long time) throws IOException { - ZipEntry entry = new ZipEntry(name); - entry.setTime(time); - zos.putNextEntry(entry); - zos.write(data); - zos.closeEntry(); - } - - private static String uniquePath(Set used, String desired) { - String clean = sanitizeArchivePath(desired); - if (clean == null) return null; - if (used.add(clean)) return clean; - int dot = clean.lastIndexOf('.'); - int slash = clean.lastIndexOf('/'); - if (dot < slash) dot = -1; - String base = dot > 0 ? clean.substring(0, dot) : clean; - String ext = dot > 0 ? clean.substring(dot) : ""; - for (int i = 2; i < 1000; i++) { - String candidate = base + "-" + i + ext; - if (used.add(candidate)) return candidate; - } - return null; - } - - private static boolean isSymlinkEscape(File root, File child) { - try { - if (!Files.isSymbolicLink(child.toPath())) return false; - String rootPath = root.getCanonicalPath(); - String childPath = child.getCanonicalPath(); - String prefix = rootPath.endsWith(File.separator) ? rootPath : rootPath + File.separator; - return !childPath.equals(rootPath) && !childPath.startsWith(prefix); - } catch (IOException ex) { - return true; - } - } - - private static String safeRelative(File root, File file) { - try { - String rootPath = root.getAbsolutePath(); - String filePath = file.getAbsolutePath(); - if (filePath.equals(rootPath)) return "."; - String prefix = rootPath.endsWith(File.separator) ? rootPath : rootPath + File.separator; - if (filePath.startsWith(prefix)) { - return filePath.substring(prefix.length()).replace('\\', '/'); - } - } catch (RuntimeException ignored) { - } - return file.getName(); - } - - private static String canonical(File file) { - try { - return file.getCanonicalPath(); - } catch (IOException ex) { - return null; - } - } - - private static void noteBudget(List omitted, Budget budget) { - budget.exhausted = true; - if (!budget.exhaustedNoted) { - budget.exhaustedNoted = true; - omitted.add("summary\tstored-budget-reached"); - } - } - - private static String oneLine(String value) { - if (value == null) return ""; - return value.replace('\n', ' ').replace('\r', ' '); - } - - private static String safe(String value) { - return value == null || value.length() == 0 ? "未知" : value; - } - - private static MessageDigest newSha256() throws IOException { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (Exception ex) { - throw new IOException("SHA-256 unavailable", ex); - } - } - - private static String toHex(byte[] data) { - char[] hex = "0123456789abcdef".toCharArray(); - char[] out = new char[data.length * 2]; - for (int i = 0; i < data.length; i++) { - int v = data[i] & 0xff; - out[i * 2] = hex[v >>> 4]; - out[i * 2 + 1] = hex[v & 0x0f]; - } - return new String(out); - } - - public static byte[] readPrefix(File file, int maxBytes) throws IOException { - int want = Math.max(0, maxBytes); - byte[] data = new byte[Math.min(want, ELF_PROBE_BYTES)]; - try (InputStream in = new java.io.FileInputStream(file)) { - int off = 0; - while (off < data.length) { - int n = in.read(data, off, data.length - off); - if (n < 0) break; - off += n; - } - if (off == data.length) return data; - byte[] trimmed = new byte[off]; - System.arraycopy(data, 0, trimmed, 0, off); - return trimmed; - } - } - - private enum Mode { - FULL, TAIL, HEAD - } - - public static final String FIRST_RUN_OVERLAY_TEXT = - "首次启动正在生成模组文件,可能需要几分钟,请保持在前台,不要切走"; - - public static final class GenerationProbe { - public int unityLibFiles; - public long unityZipBytes; - public int interopFiles; - public long interopBytes; - public int interopFilesAtStart; - public int dummyFiles; - public boolean logIsNew; - public long logOutputBytes; - } - - public static String generationStageId(GenerationProbe probe) { - if (probe == null) return "starting"; - if (probe.logIsNew && probe.interopFiles > 0) return "plugins"; - if (probe.interopFiles > probe.interopFilesAtStart) return "interop"; - if (probe.interopFilesAtStart > 0) return "plugins"; - if (probe.dummyFiles > 0 || probe.unityLibFiles >= 15) return "cpp2il"; - if (probe.unityZipBytes > 0 || probe.unityLibFiles > 0) return "unity-libs"; - return "starting"; - } - - public static String generationStageLabel(String stageId) { - if ("unity-libs".equals(stageId)) return "正在准备 Unity 基础库"; - if ("cpp2il".equals(stageId)) return "正在分析游戏代码(Cpp2IL / interop)"; - if ("interop".equals(stageId)) return "正在写入 interop 程序集"; - if ("plugins".equals(stageId)) return "正在加载模组"; - if ("ready".equals(stageId)) return "已进入游戏"; - return "正在启动"; - } - - /** -1 when a percentage would be a guess. Cpp2IL writes no files until it finishes. */ - public static int generationPercent(GenerationProbe probe, int interopBaseline) { - if (probe == null) return -1; - String stage = generationStageId(probe); - if ("starting".equals(stage)) return 2; - if ("unity-libs".equals(stage)) return probe.unityLibFiles > 0 ? 15 : 8; - if ("cpp2il".equals(stage)) return -1; - if ("interop".equals(stage)) { - int gained = probe.interopFiles - probe.interopFilesAtStart; - if (interopBaseline > 0 && gained >= 0) { - return Math.min(90, 20 + gained * 70 / Math.max(1, interopBaseline)); - } - return -1; - } - if ("plugins".equals(stage)) return 95; - if ("ready".equals(stage)) return 100; - return -1; - } - - public static String enableDiagnosticLogging(String cfg) { - String text = cfg == null ? "" : cfg; - text = replaceAssignment(text, "UnityLogListening", "true"); - text = replaceAssignment(text, "WriteUnityLog", "true"); - text = replaceAssignment(text, "InstantFlushing", "true"); - return text; - } - - public static String exitReasonName(int reason) { - switch (reason) { - case 0: return "UNKNOWN"; - case 1: return "EXIT_SELF"; - case 2: return "SIGNALED"; - case 3: return "LOW_MEMORY"; - case 4: return "CRASH"; - case 5: return "CRASH_NATIVE"; - case 6: return "ANR"; - case 7: return "INITIALIZATION_FAILURE"; - case 8: return "PERMISSION_CHANGE"; - case 9: return "EXCESSIVE_RESOURCE_USAGE"; - case 10: return "USER_REQUESTED"; - case 11: return "USER_STOPPED"; - case 12: return "DEPENDENCY_DIED"; - case 13: return "OTHER"; - case 14: return "FREEZER"; - case 15: return "PACKAGE_STATE_CHANGE"; - case 16: return "PACKAGE_UPDATED"; - default: return "REASON_" + reason; - } - } - - public static String exitSubReasonName(int subReason) { - switch (subReason) { - case 0: return "UNKNOWN"; - case 1: return "WAIT_FOR_DEBUGGER"; - case 2: return "TOO_MANY_CACHED"; - case 3: return "TOO_MANY_EMPTY"; - case 4: return "TRIM_EMPTY"; - case 5: return "LARGE_CACHED"; - case 6: return "MEMORY_PRESSURE"; - case 7: return "EXCESSIVE_CPU"; - case 8: return "SYSTEM_UPDATE_DONE"; - case 9: return "KILL_ALL_FG"; - case 10: return "KILL_ALL_BG_EXCEPT"; - case 11: return "KILL_UID"; - case 12: return "KILL_PID"; - case 13: return "INVALID_START"; - case 14: return "INVALID_STATE"; - case 15: return "IMPERCEPTIBLE"; - case 16: return "REMOVE_LRU"; - case 17: return "ISOLATED_NOT_NEEDED"; - case 18: return "CACHED_IDLE_FORCED_APP_STANDBY"; - case 19: return "FREEZER_BINDER_IOCTL"; - case 20: return "FREEZER_BINDER_TRANSACTION"; - case 21: return "FORCE_STOP"; - case 22: return "REMOVE_TASK"; - case 23: return "STOP_APP"; - case 24: return "KILL_BACKGROUND"; - case 25: return "PACKAGE_UPDATE"; - default: - if (subReason < 0) return "unavailable"; - return "SUBREASON_" + subReason; - } - } - - public static String importanceName(int importance) { - switch (importance) { - case 100: return "FOREGROUND"; - case 125: return "FOREGROUND_SERVICE"; - case 130: return "PERCEPTIBLE_PRE_26"; - case 150: return "TOP_SLEEPING_PRE_23"; - case 200: return "VISIBLE"; - case 230: return "PERCEPTIBLE"; - case 300: return "SERVICE"; - case 325: return "TOP_SLEEPING"; - case 350: return "CANT_SAVE_STATE"; - case 400: return "CACHED"; - case 500: return "EMPTY"; - case 1000: return "GONE"; - default: - if (importance < 0) return "unavailable"; - return "IMPORTANCE_" + importance; - } - } - - public static String describeDirectory(File dir, int maxEntries) { - StringBuilder sb = new StringBuilder(); - if (dir == null) return "path=null\n"; - sb.append("path=").append(dir.getAbsolutePath()) - .append(" exists=").append(dir.exists()) - .append(" readable=").append(dir.canRead()) - .append(" directory=").append(dir.isDirectory()) - .append('\n'); - if (!dir.exists()) return sb.toString(); - if (!dir.isDirectory()) { - sb.append("size=").append(dir.length()).append(" mtime=").append(dir.lastModified()).append('\n'); - return sb.toString(); - } - String[] names = dir.list(); - if (names == null) { - sb.append("children=unreadable\n"); - return sb.toString(); - } - Arrays.sort(names); - if (names.length == 0) sb.append("children=empty\n"); - else sb.append("children=").append(names.length).append('\n'); - int shown = Math.min(names.length, Math.max(0, maxEntries)); - long bytes = 0L; - int files = 0; - for (int i = 0; i < names.length; i++) { - File child = new File(dir, names[i]); - boolean directory = child.isDirectory(); - long size = directory ? -1L : child.length(); - if (!directory && child.isFile()) { - files++; - bytes += Math.max(0L, size); - } - if (i < shown) { - sb.append(names[i]).append('\t').append(directory ? "dir" : Long.toString(size)) - .append('\t').append(child.lastModified()).append('\n'); - } - } - if (names.length > shown) sb.append("... ").append(names.length - shown).append(" more\n"); - sb.append("fileCount=").append(files).append(" fileBytes=").append(bytes).append('\n'); - return sb.toString(); - } - - public static final class DirStat { - public final boolean missing; - public final boolean unreadable; - public final int files; - public final long bytes; - - DirStat(boolean missing, boolean unreadable, int files, long bytes) { - this.missing = missing; - this.unreadable = unreadable; - this.files = files; - this.bytes = bytes; - } - } - - public static DirStat summarizeTree(File dir, String suffix, int maxDepth) { - if (dir == null || !dir.exists()) return new DirStat(true, false, 0, 0L); - if (!dir.isDirectory()) { - boolean take = suffix == null || dir.getName().toLowerCase(Locale.ROOT).endsWith(suffix); - return new DirStat(false, !dir.canRead(), take && dir.isFile() ? 1 : 0, take && dir.isFile() ? dir.length() : 0L); - } - if (dir.list() == null && !dir.canRead()) return new DirStat(false, true, 0, 0L); - long[] totals = new long[] {0L, 0L}; - accumulate(dir, suffix == null ? null : suffix.toLowerCase(Locale.ROOT), 0, Math.max(0, maxDepth), totals); - return new DirStat(false, false, (int) totals[0], totals[1]); - } - - public static List findLogFiles(File root, int maxFiles) { - List found = new ArrayList(); - if (root == null || !root.isDirectory() || maxFiles <= 0) return found; - collectLogs(root, root, 0, maxFiles, found); - return found; - } - - public static void appendIfRoom(File file, String line, int maxBytes) throws IOException { - if (file == null) throw new IOException("missing append target"); - String payload = line == null ? "\n" : (line.endsWith("\n") ? line : line + "\n"); - byte[] incoming = payload.getBytes(StandardCharsets.UTF_8); - File parent = file.getParentFile(); - if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { - throw new IOException("cannot create " + parent.getAbsolutePath()); - } - synchronized (BppDiagnosticBundle.class) { - long existing = file.isFile() ? file.length() : 0L; - if (existing >= maxBytes) return; - try (FileOutputStream out = new FileOutputStream(file, true)) { - int allow = (int) Math.min(incoming.length, Math.max(0L, maxBytes - existing)); - out.write(incoming, 0, allow); - out.flush(); - out.getFD().sync(); - } - } - } - - public static String decodePreferenceProto(byte[] data) { - StringBuilder sb = new StringBuilder(); - if (data == null || data.length == 0) return "(empty)\n"; - int index = 0; - int entries = 0; - try { - while (index < data.length) { - long[] tag = readVarint(data, index); - if (tag == null) break; - index = (int) tag[1]; - int field = (int) (tag[0] >>> 3); - int wire = (int) (tag[0] & 7); - if (wire == 2) { - long[] length = readVarint(data, index); - if (length == null) break; - index = (int) length[1]; - int size = (int) length[0]; - if (size < 0 || index + size > data.length) break; - if (field == 1) { - String parsed = parsePreferenceEntry(data, index, index + size); - if (parsed != null) { - sb.append(parsed).append('\n'); - entries++; - } - } - index += size; - } else if (wire == 0) { - long[] value = readVarint(data, index); - if (value == null) break; - index = (int) value[1]; - } else if (wire == 5) { - index += 4; - } else if (wire == 1) { - index += 8; - } else { - break; - } - } - } catch (RuntimeException ex) { - sb.append("decodeError=").append(ex.getClass().getSimpleName()).append('\n'); - } - if (entries == 0 && sb.length() == 0) sb.append("(no preference keys)\n"); - return sb.toString(); - } - - private static String parsePreferenceEntry(byte[] data, int start, int end) { - String key = null; - String value = null; - int index = start; - while (index < end) { - long[] tag = readVarint(data, index); - if (tag == null) break; - index = (int) tag[1]; - int field = (int) (tag[0] >>> 3); - int wire = (int) (tag[0] & 7); - if (wire == 2) { - long[] length = readVarint(data, index); - if (length == null) break; - index = (int) length[1]; - int size = (int) length[0]; - if (size < 0 || index + size > end) break; - if (field == 1) key = new String(data, index, size, StandardCharsets.UTF_8); - else if (field == 2) value = parsePreferenceValue(data, index, index + size); - index += size; - } else if (wire == 0) { - long[] skipped = readVarint(data, index); - if (skipped == null) break; - index = (int) skipped[1]; - } else if (wire == 5) { - index += 4; - } else if (wire == 1) { - index += 8; - } else { - break; - } - } - if (key == null) return null; - if (value == null) value = ""; - if (isSecretKey(key)) value = "[redacted]"; - return key + "=" + value; - } - - private static String parsePreferenceValue(byte[] data, int start, int end) { - int index = start; - while (index < end) { - long[] tag = readVarint(data, index); - if (tag == null) return "unavailable"; - index = (int) tag[1]; - int field = (int) (tag[0] >>> 3); - int wire = (int) (tag[0] & 7); - if (wire == 0) { - long[] value = readVarint(data, index); - if (value == null) return "unavailable"; - index = (int) value[1]; - if (field == 1) return value[0] != 0 ? "true" : "false"; - if (field == 3 || field == 4) return Long.toString(value[0]); - } else if (wire == 5 && index + 4 <= end) { - int bits = (data[index] & 0xff) | ((data[index + 1] & 0xff) << 8) - | ((data[index + 2] & 0xff) << 16) | ((data[index + 3] & 0xff) << 24); - index += 4; - if (field == 2) return Float.toString(Float.intBitsToFloat(bits)); - } else if (wire == 1 && index + 8 <= end) { - long bits = 0L; - for (int b = 0; b < 8; b++) bits |= ((long) (data[index + b] & 0xff)) << (8 * b); - index += 8; - if (field == 7) return Double.toString(Double.longBitsToDouble(bits)); - } else if (wire == 2) { - long[] length = readVarint(data, index); - if (length == null) return "unavailable"; - index = (int) length[1]; - int size = (int) length[0]; - if (size < 0 || index + size > end) return "unavailable"; - if (field == 5) return new String(data, index, size, StandardCharsets.UTF_8); - if (field == 8) return "bytes:" + size; - if (field == 6) return "string_set"; - index += size; - continue; - } else { - return "unavailable"; - } - } - return ""; - } - - private static boolean isSecretKey(String key) { - String lower = key.toLowerCase(Locale.ROOT); - return lower.contains("password") || lower.contains("secret") || lower.contains("token") - || lower.contains("keystore") || lower.contains("credential") || lower.contains("lineage"); - } - - private static long[] readVarint(byte[] data, int index) { - long value = 0L; - int shift = 0; - while (index < data.length && shift < 64) { - int piece = data[index] & 0xff; - index++; - value |= (long) (piece & 0x7f) << shift; - if ((piece & 0x80) == 0) return new long[] {value, index}; - shift += 7; - } - return null; - } - - private static String replaceAssignment(String cfg, String key, String value) { - String[] lines = cfg.split("\n", -1); - boolean found = false; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < lines.length; i++) { - String line = lines[i]; - int equals = line.indexOf('='); - if (equals > 0 && line.substring(0, equals).trim().equals(key) && !line.trim().startsWith("#")) { - line = key + " = " + value; - found = true; - } - sb.append(line); - if (i + 1 < lines.length) sb.append('\n'); - } - if (!found) { - if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '\n') sb.append('\n'); - sb.append(key).append(" = ").append(value).append('\n'); - } - return sb.toString(); - } - - private static void accumulate(File dir, String suffix, int depth, int maxDepth, long[] totals) { - if (depth > maxDepth || totals[0] > 200000) return; - File[] children = dir.listFiles(); - if (children == null) return; - for (int i = 0; i < children.length; i++) { - File child = children[i]; - if (child.isDirectory()) { - accumulate(child, suffix, depth + 1, maxDepth, totals); - } else if (child.isFile()) { - if (suffix != null && !child.getName().toLowerCase(Locale.ROOT).endsWith(suffix)) continue; - totals[0]++; - totals[1] += Math.max(0L, child.length()); - } - } - } - - private static void collectLogs(File root, File dir, int depth, int maxFiles, List found) { - if (depth > MAX_SCAN_DEPTH || found.size() >= maxFiles) return; - File[] children = dir.listFiles(); - if (children == null) return; - Arrays.sort(children, new Comparator() { - @Override - public int compare(File a, File b) { - return a.getName().compareTo(b.getName()); - } - }); - for (int i = 0; i < children.length && found.size() < maxFiles; i++) { - File child = children[i]; - String name = child.getName(); - if (isSensitivePath(name) || isSymlinkEscape(root, child)) continue; - if (child.isDirectory()) { - collectLogs(root, child, depth + 1, maxFiles, found); - } else if (child.isFile() && isLogName(name.toLowerCase(Locale.ROOT))) { - found.add(child); - } - } - } - - private static final class Budget { - long bytes; - int files; - boolean exhausted; - boolean exhaustedNoted; - - Budget(long bytes, int files) { - this.bytes = bytes; - this.files = files; - } - - boolean take(long size) { - if (files <= 0 || size < 0) { - exhausted = true; - return false; - } - if (size > bytes) return false; - bytes -= size; - files -= 1; - if (files <= 0) exhausted = true; - return true; - } - } - - private static final class Slice { - final String archivePath; - final byte[] inline; - final File file; - final long offset; - final long length; - final long originalSize; - final String note; - - Slice(String archivePath, byte[] inline, File file, long offset, long length, long originalSize, String note) { - this.archivePath = archivePath; - this.inline = inline; - this.file = file; - this.offset = offset; - this.length = length; - this.originalSize = originalSize; - this.note = note; - } - } - - private static final class Stored { - final long storedBytes; - final String sha256; - - Stored(long storedBytes, String sha256) { - this.storedBytes = storedBytes; - this.sha256 = sha256; - } - } - -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticExporter.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticExporter.java deleted file mode 100644 index 2398a48..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticExporter.java +++ /dev/null @@ -1,1542 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Activity; -import android.app.ActivityManager; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.Signature; -import android.content.pm.SigningInfo; -import android.content.res.AssetFileDescriptor; -import android.content.res.Configuration; -import android.database.Cursor; -import android.graphics.Point; -import android.net.Uri; -import android.os.Build; -import android.os.Environment; -import android.os.StatFs; -import android.provider.Settings; -import android.system.Os; -import android.system.OsConstants; -import android.util.DisplayMetrics; -import android.view.Display; -import android.view.DisplayCutout; -import android.view.View; -import android.view.WindowInsets; -import android.view.WindowManager; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -/** - * Collects everything the app sandbox can see into one zip, then copies it to Downloads. - * Every probe is fail-soft: a denied path is written to manifest.txt and the launcher keeps running. - * No extra manifest permission is requested. logcat without READ_LOGS returns this UID only, - * and Downloads uses the MediaStore inserts available since Android 10. - */ -public final class BppDiagnosticExporter { - - public static final String FILE_PROVIDER_AUTHORITY = "com.bepinex.android.provider"; - private static final String[] EXPECTED_RELATIVE = new String[] { - "BepInEx/LogOutput.log", - "BepInEx/ErrorLog.log", - "BepInEx/preloader.log", - "BepInEx/bpp-startup-trace.log", - "BepInEx/config/BepInEx.cfg", - "BepInEx/config/BazaarPlusPlus.cfg", - "modpacks/bpp/modpack.json", - "modpacks/bpp/config/BazaarPlusPlus.cfg", - "MelonLoader/UserData/BazaarPlusPlus.cfg", - "modpacks/bpp/logs", - "BepInEx/logs", - "BepInEx/interop", - "BepInEx/unity-libs", - "BepInEx/dummy", - "PersistentData", - "Player.log" - }; - private static final long NATIVE_HASH_CAP = 256L * 1024L * 1024L; - private static final long DLL_HASH_CAP = 32L * 1024L * 1024L; - - private BppDiagnosticExporter() {} - - public static final class Saved { - public final boolean ok; - public final Uri shareUri; - public final String displayPath; - public final String sha256; - public final long sizeBytes; - public final String warning; - public final String error; - public final String fileName; - - Saved(boolean ok, Uri shareUri, String displayPath, String sha256, long sizeBytes, String warning, String error, String fileName) { - this.ok = ok; - this.shareUri = shareUri; - this.displayPath = displayPath; - this.sha256 = sha256 == null ? "" : sha256; - this.sizeBytes = sizeBytes; - this.warning = warning; - this.error = error; - this.fileName = fileName == null ? "" : fileName; - } - - static Saved failure(Throwable error) { - String message = error == null ? "unknown" : error.getClass().getSimpleName() + ": " + error.getMessage(); - return new Saved(false, null, "", "", 0L, null, message, ""); - } - } - - /** Safe to call on the UI thread. Does not touch the game window. */ - public static String captureDisplaySnapshot(Activity activity) { - StringBuilder sb = new StringBuilder(); - if (activity == null) return "activity=null\n"; - try { - DisplayMetrics dm = activity.getResources().getDisplayMetrics(); - sb.append("widthPixels=").append(dm.widthPixels) - .append(" heightPixels=").append(dm.heightPixels) - .append(" density=").append(dm.density) - .append(" densityDpi=").append(dm.densityDpi) - .append(" xdpi=").append(dm.xdpi) - .append(" ydpi=").append(dm.ydpi) - .append(" scaledDensity=").append(dm.scaledDensity) - .append('\n'); - WindowManager wm = activity.getWindowManager(); - Display display = wm.getDefaultDisplay(); - Point real = new Point(); - display.getRealSize(real); - Point app = new Point(); - display.getSize(app); - sb.append("realSize=").append(real.x).append('x').append(real.y) - .append(" appSize=").append(app.x).append('x').append(app.y) - .append(" rotation=").append(display.getRotation()) - .append(" refreshRate=").append(display.getRefreshRate()) - .append('\n'); - Display.Mode mode = display.getMode(); - sb.append("currentMode id=").append(mode.getModeId()) - .append(" ").append(mode.getPhysicalWidth()).append('x').append(mode.getPhysicalHeight()) - .append(" @").append(mode.getRefreshRate()).append('\n'); - Display.Mode[] modes = display.getSupportedModes(); - if (modes != null) { - for (int i = 0; i < modes.length && i < 16; i++) { - Display.Mode item = modes[i]; - sb.append("supportedMode id=").append(item.getModeId()) - .append(" ").append(item.getPhysicalWidth()).append('x').append(item.getPhysicalHeight()) - .append(" @").append(item.getRefreshRate()).append('\n'); - } - } - Configuration config = activity.getResources().getConfiguration(); - sb.append("orientation=").append(config.orientation) - .append(" screenWidthDp=").append(config.screenWidthDp) - .append(" screenHeightDp=").append(config.screenHeightDp) - .append(" smallestScreenWidthDp=").append(config.smallestScreenWidthDp) - .append(" fontScale=").append(config.fontScale) - .append(" uiMode=").append(config.uiMode) - .append(" screenLayout=").append(config.screenLayout) - .append(" locales=").append(config.getLocales()) - .append('\n'); - View decor = activity.getWindow() == null ? null : activity.getWindow().getDecorView(); - if (decor != null) { - WindowInsets insets = decor.getRootWindowInsets(); - if (insets != null) { - sb.append("systemWindowInsets=") - .append(insets.getSystemWindowInsetLeft()).append(',') - .append(insets.getSystemWindowInsetTop()).append(',') - .append(insets.getSystemWindowInsetRight()).append(',') - .append(insets.getSystemWindowInsetBottom()).append('\n'); - DisplayCutout cutout = insets.getDisplayCutout(); - if (cutout == null) { - sb.append("displayCutout=none\n"); - } else { - sb.append("cutoutSafe=") - .append(cutout.getSafeInsetLeft()).append(',') - .append(cutout.getSafeInsetTop()).append(',') - .append(cutout.getSafeInsetRight()).append(',') - .append(cutout.getSafeInsetBottom()) - .append(" rects=").append(cutout.getBoundingRects()) - .append('\n'); - } - } else { - sb.append("rootWindowInsets=null\n"); - } - } - WindowManager.LayoutParams attrs = activity.getWindow() == null - ? null : activity.getWindow().getAttributes(); - if (attrs != null) { - sb.append("layoutInDisplayCutoutMode=").append(attrs.layoutInDisplayCutoutMode).append('\n'); - } - } catch (Throwable error) { - sb.append("displayError=").append(error).append('\n'); - } - return sb.toString(); - } - - public static Saved exportAndSave(Activity activity, File gameRoot, File internalWorkDir, String displaySnapshot) { - try { - return exportUnchecked(activity, gameRoot, internalWorkDir, displaySnapshot); - } catch (Throwable error) { - return Saved.failure(error); - } - } - - private static Saved exportUnchecked( - Activity activity, - File gameRoot, - File internalWorkDir, - String displaySnapshot - ) throws Exception { - if (activity == null) throw new IllegalStateException("missing activity"); - List errors = new ArrayList(); - List texts = new ArrayList(); - List scans = new ArrayList(); - List extras = new ArrayList(); - File stage = new File(activity.getCacheDir(), "bpp-diag-stage"); - deleteRecursively(stage); - if (!stage.isDirectory() && !stage.mkdirs()) { - throw new IllegalStateException("cannot create " + stage.getAbsolutePath()); - } - - texts.add(new BppDiagnosticBundle.TextEntry("device/build.txt", safeSection(errors, "device", new Section() { - @Override public String run() { return deviceBuild(activity); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("device/display.txt", - displaySnapshot == null ? "displaySnapshot=missing\n" : displaySnapshot)); - texts.add(new BppDiagnosticBundle.TextEntry("device/memory-storage.txt", safeSection(errors, "memory", new Section() { - @Override public String run() { return memoryAndStorage(activity); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("device/getprop.txt", safeSection(errors, "getprop", new Section() { - @Override public String run() { return redactProps(capture("getprop", 8000L, 512 * 1024)); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("device/settings.txt", safeSection(errors, "settings", new Section() { - @Override public String run() { return settings(activity); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("packages/launcher.txt", safeSection(errors, "launcher-package", new Section() { - @Override public String run() { return describePackage(activity, activity.getPackageName()); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("packages/game.txt", safeSection(errors, "game-package", new Section() { - @Override public String run() { return describePackage(activity, BppBundledModpackInstaller.TARGET_PACKAGE); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("packages/libil2cpp.txt", safeSection(errors, "libil2cpp", new Section() { - @Override public String run() { - return nativeLibraries(activity, BppBundledModpackInstaller.TARGET_PACKAGE); - } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("deploy/status.txt", safeSection(errors, "deploy", new Section() { - @Override public String run() { return deployStatus(activity, gameRoot, internalWorkDir); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("deploy/file-tree-game-root.txt", safeSection(errors, "tree-game", new Section() { - @Override public String run() { return BppDiagnosticBundle.renderTree(gameRoot, BppDiagnosticBundle.MAX_TREE_LINES, 6); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("deploy/file-tree-internal-work.txt", safeSection(errors, "tree-work", new Section() { - @Override public String run() { return BppDiagnosticBundle.renderTree(internalWorkDir, 400, 4); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("logs/expected-paths.txt", safeSection(errors, "expected-logs", new Section() { - @Override public String run() { return expectedPaths(activity, gameRoot); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("logs/directories.txt", safeSection(errors, "log-dirs", new Section() { - @Override public String run() { return logDirectories(activity, gameRoot); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("state/datastore/keys.txt", safeSection(errors, "datastore-keys", new Section() { - @Override public String run() { - return datastoreKeys(new File(activity.getDataDir(), "files/datastore")); - } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("crashes/tombstone-probes.txt", safeSection(errors, "tombstones", new Section() { - @Override public String run() { return tombstoneProbes(activity, gameRoot); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("crashes/application-exit.txt", safeSection(errors, "exit-info", new Section() { - @Override public String run() { return exitReasons(activity, stage, extras); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("logcat/dump-notes.txt", safeSection(errors, "logcat", new Section() { - @Override public String run() { return dumpLogcat(stage, extras); } - }))); - texts.add(new BppDiagnosticBundle.TextEntry("device/shell-probes.txt", safeSection(errors, "shell", new Section() { - @Override public String run() { return shellProbes(activity); } - }))); - - addScan(scans, gameRoot, "collected/game-root", false); - addScan(scans, internalWorkDir, "deploy/internal-work", true); - File diagnostics = new File(activity.getFilesDir(), BppDiagnosticSessionLog.DIR_NAME); - addScan(scans, diagnostics, "launch/diagnostics", true); - File dataDir = activity.getDataDir(); - addScan(scans, new File(dataDir, "shared_prefs"), "state/shared-prefs", true); - addScan(scans, new File(dataDir, "files/datastore"), "state/datastore", true); - addScan(scans, new File(dataDir, "no_backup"), "state/no-backup", true); - File external = activity.getExternalFilesDir(null); - addScan(scans, external, "collected/external-files", false); - String gamePackage = BppBundledModpackInstaller.TARGET_PACKAGE; - addScan(scans, new File("/sdcard/BepInEx_Android/" + gamePackage), "collected/legacy-sdcard", false); - addScan(scans, new File("/storage/emulated/0/BepInEx_Android/" + gamePackage), "collected/legacy-emulated", false); - addScan(scans, new File("/sdcard/Android/data/" + activity.getPackageName() + "/files"), "collected/android-data-launcher", false); - addScan(scans, new File("/storage/emulated/0/Android/data/" + activity.getPackageName() + "/files"), "collected/android-data-launcher-emulated", false); - addScan(scans, new File("/sdcard/Android/data/" + gamePackage + "/files"), "collected/android-data-game", false); - addScan(scans, new File("/storage/emulated/0/Android/data/" + gamePackage + "/files"), "collected/android-data-game-emulated", false); - addReadableTombstones(scans, activity, gameRoot); - harvestLogs(extras, gameRoot, "logs/game-root"); - harvestLogs(extras, activity.getExternalFilesDir(null), "logs/external-files"); - harvestJitTrace(activity, stage, extras); - - StringBuilder notes = new StringBuilder(); - for (int i = 0; i < errors.size(); i++) notes.append(errors.get(i)).append('\n'); - if (notes.length() == 0) notes.append("(none)\n"); - texts.add(new BppDiagnosticBundle.TextEntry("device/collector-notes.txt", notes.toString())); - - String version = readVersion(activity); - String stamp = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withLocale(Locale.US) - .format(java.time.ZonedDateTime.now()); - String zipName = "BPP-diagnostics-" + stamp + ".zip"; - File outDir = new File(activity.getCacheDir(), "bpp-diag-out"); - if (!outDir.isDirectory() && !outDir.mkdirs()) throw new IllegalStateException("cannot create export dir"); - File[] old = outDir.listFiles(); - if (old != null) { - for (int i = 0; i < old.length; i++) old[i].delete(); - } - File zip = new File(outDir, zipName); - String readme = BppDiagnosticBundle.readme(BppDiagnosticBundle.nowIso(), version, activity.getPackageName()); - BppDiagnosticBundle.write(zip, new BppDiagnosticBundle.Request(readme, texts, scans, extras)); - deleteRecursively(stage); - String hash; - try { - hash = BppDiagnosticBundle.sha256Hex(zip, 64L * 1024L * 1024L); - } catch (Exception ex) { - hash = "unavailable: " + ex.getMessage(); - } - return publish(activity, zip, zipName, hash); - } - - private static Saved publish(Context context, File zip, String zipName, String hash) { - StringBuilder warning = new StringBuilder(); - Uri share = null; - String display = zip.getAbsolutePath(); - Uri downloads = insertDownload(context, zip, zipName, "content://media/external/downloads", warning); - if (downloads == null) { - downloads = insertDownload(context, zip, zipName, "content://media/external/file", warning); - } - if (downloads != null) { - share = downloads; - String queried = queryDisplayPath(context.getContentResolver(), downloads, zipName); - if (queried != null && queried.length() > 0) display = queried; - } else { - File direct = tryDirectDownload(zip, zipName, warning); - if (direct != null) { - display = direct.getAbsolutePath(); - share = fileProviderUri(context, direct); - if (share == null) share = Uri.fromFile(direct); - } - } - if (share == null || downloads == null) { - File externalDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); - File externalCopy = externalDir == null ? null : new File(externalDir, zipName); - if (externalCopy != null && copyFile(zip, externalCopy, warning)) { - if (downloads == null) display = externalCopy.getAbsolutePath(); - Uri provider = fileProviderUri(context, externalCopy); - if (share == null) share = provider; - warning.append("公共下载目录不可写,已另存到应用外部目录。\n"); - } else { - Uri provider = fileProviderUri(context, zip); - if (share == null) share = provider; - warning.append("未能写入系统「下载」,文件仍在应用缓存。\n"); - } - } - if (share == null) warning.append("没有可用的分享 Uri。\n"); - return new Saved(true, share, display, hash, zip.length(), warning.length() == 0 ? null : warning.toString(), null, zipName); - } - - private static Uri insertDownload(Context context, File zip, String zipName, String collection, StringBuilder warning) { - if (Build.VERSION.SDK_INT < 29 && collection.contains("/downloads")) { - warning.append("API ").append(Build.VERSION.SDK_INT).append(" 没有 Downloads MediaStore。\n"); - return null; - } - ContentResolver resolver = context.getContentResolver(); - ContentValues values = new ContentValues(); - values.put("_display_name", zipName); - values.put("mime_type", "application/zip"); - if (Build.VERSION.SDK_INT >= 29) { - values.put("relative_path", Environment.DIRECTORY_DOWNLOADS); - values.put("is_pending", 1); - } - Uri uri = null; - try { - uri = resolver.insert(Uri.parse(collection), values); - } catch (Throwable first) { - values.remove("is_pending"); - try { - uri = resolver.insert(Uri.parse(collection), values); - } catch (Throwable second) { - warning.append(collection).append(" insert 失败: ").append(second.getClass().getSimpleName()) - .append(' ').append(second.getMessage()).append('\n'); - return null; - } - } - if (uri == null) { - warning.append(collection).append(" insert 返回 null。\n"); - return null; - } - try (InputStream in = new FileInputStream(zip); - java.io.OutputStream out = resolver.openOutputStream(uri)) { - if (out == null) throw new java.io.IOException("openOutputStream returned null"); - byte[] buf = new byte[65536]; - int n; - while ((n = in.read(buf)) != -1) out.write(buf, 0, n); - out.flush(); - if (out instanceof FileOutputStream) ((FileOutputStream) out).getFD().sync(); - } catch (Throwable error) { - try { - resolver.delete(uri, null, null); - } catch (Throwable ignored) { - } - warning.append(collection).append(" 写入失败: ").append(error.getMessage()).append('\n'); - return null; - } - if (Build.VERSION.SDK_INT >= 29) { - try { - ContentValues done = new ContentValues(); - done.put("is_pending", 0); - resolver.update(uri, done, null, null); - } catch (Throwable ignored) { - } - } - return uri; - } - - private static File tryDirectDownload(File zip, String zipName, StringBuilder warning) { - try { - File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); - if (dir == null) return null; - if (!dir.isDirectory() && !dir.mkdirs()) return null; - File dest = new File(dir, zipName); - if (!copyFile(zip, dest, warning)) return null; - return dest; - } catch (Throwable error) { - warning.append("直接写入 Download 失败: ").append(error.getMessage()).append('\n'); - return null; - } - } - - private static boolean copyFile(File from, File to, StringBuilder warning) { - File parent = to.getParentFile(); - if (parent != null && !parent.isDirectory() && !parent.mkdirs()) return false; - try (InputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to)) { - byte[] buf = new byte[65536]; - int n; - while ((n = in.read(buf)) != -1) out.write(buf, 0, n); - out.getFD().sync(); - return true; - } catch (Throwable error) { - warning.append(to.getAbsolutePath()).append(" 复制失败: ").append(error.getMessage()).append('\n'); - return false; - } - } - - private static Uri fileProviderUri(Context context, File file) { - if (file == null || !file.isFile()) return null; - try { - Class type = Class.forName("androidx.core.content.FileProvider"); - Method method = type.getMethod("getUriForFile", Context.class, String.class, File.class); - Object uri = method.invoke(null, context, FILE_PROVIDER_AUTHORITY, file); - if (uri instanceof Uri) return (Uri) uri; - } catch (Throwable ignored) { - } - return null; - } - - private static String queryDisplayPath(ContentResolver resolver, Uri uri, String fallbackName) { - String[] projection = new String[] {"_data", "_display_name", "relative_path"}; - Cursor cursor = null; - try { - cursor = resolver.query(uri, projection, null, null, null); - if (cursor != null && cursor.moveToFirst()) { - String data = cursor.getColumnIndex("_data") >= 0 && !cursor.isNull(0) ? cursor.getString(0) : null; - String name = cursor.getColumnCount() > 1 && !cursor.isNull(1) ? cursor.getString(1) : fallbackName; - String relative = cursor.getColumnCount() > 2 && !cursor.isNull(2) ? cursor.getString(2) : null; - if (data != null && data.length() > 0) return data; - if (relative != null && relative.length() > 0) return relative + name; - } - } catch (Throwable ignored) { - } finally { - if (cursor != null) cursor.close(); - } - return Environment.DIRECTORY_DOWNLOADS + "/" + fallbackName; - } - - private static String deviceBuild(Context context) { - StringBuilder sb = new StringBuilder(); - sb.append("manufacturer=").append(Build.MANUFACTURER).append('\n'); - sb.append("brand=").append(Build.BRAND).append('\n'); - sb.append("model=").append(Build.MODEL).append('\n'); - sb.append("device=").append(Build.DEVICE).append('\n'); - sb.append("product=").append(Build.PRODUCT).append('\n'); - sb.append("hardware=").append(Build.HARDWARE).append('\n'); - sb.append("board=").append(Build.BOARD).append('\n'); - sb.append("bootloader=").append(Build.BOOTLOADER).append('\n'); - sb.append("display=").append(Build.DISPLAY).append('\n'); - sb.append("fingerprint=").append(Build.FINGERPRINT).append('\n'); - sb.append("host=").append(Build.HOST).append('\n'); - sb.append("id=").append(Build.ID).append('\n'); - sb.append("tags=").append(Build.TAGS).append('\n'); - sb.append("type=").append(Build.TYPE).append('\n'); - sb.append("user=").append(Build.USER).append('\n'); - sb.append("buildTime=").append(formatTime(Build.TIME)).append('\n'); - sb.append("release=").append(Build.VERSION.RELEASE).append('\n'); - sb.append("sdkInt=").append(Build.VERSION.SDK_INT).append('\n'); - sb.append("codename=").append(Build.VERSION.CODENAME).append('\n'); - sb.append("incremental=").append(Build.VERSION.INCREMENTAL).append('\n'); - sb.append("securityPatch=").append(Build.VERSION.SECURITY_PATCH).append('\n'); - sb.append("baseOs=").append(Build.VERSION.BASE_OS).append('\n'); - sb.append("previewSdkInt=").append(Build.VERSION.PREVIEW_SDK_INT).append('\n'); - sb.append("abis=").append(Arrays.toString(Build.SUPPORTED_ABIS)).append('\n'); - sb.append("abis32=").append(Arrays.toString(Build.SUPPORTED_32_BIT_ABIS)).append('\n'); - sb.append("abis64=").append(Arrays.toString(Build.SUPPORTED_64_BIT_ABIS)).append('\n'); - try { - sb.append("pageSize=").append(Os.sysconf(OsConstants._SC_PAGESIZE)).append('\n'); - } catch (Throwable error) { - sb.append("pageSize=unavailable ").append(error).append('\n'); - } - appendReflected(sb, Build.VERSION.class, "MEDIA_PERFORMANCE_CLASS", "mediaPerformanceClass"); - appendReflected(sb, Build.VERSION.class, "RELEASE_OR_CODENAME", "releaseOrCodename"); - sb.append("timezone=").append(ZoneId.systemDefault()).append('\n'); - sb.append("locale=").append(Locale.getDefault()).append('\n'); - sb.append("now=").append(BppDiagnosticBundle.nowIso()).append('\n'); - sb.append("launcherPackage=").append(context.getPackageName()).append('\n'); - sb.append("myPid=").append(android.os.Process.myPid()).append('\n'); - sb.append("myUid=").append(android.os.Process.myUid()).append('\n'); - return sb.toString(); - } - - private static String memoryAndStorage(Context context) { - StringBuilder sb = new StringBuilder(); - Runtime runtime = Runtime.getRuntime(); - sb.append("runtimeMax=").append(runtime.maxMemory()) - .append(" total=").append(runtime.totalMemory()) - .append(" free=").append(runtime.freeMemory()).append('\n'); - try { - ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); - if (am != null) { - ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo(); - am.getMemoryInfo(info); - sb.append("memAvail=").append(info.availMem) - .append(" memTotal=").append(info.totalMem) - .append(" threshold=").append(info.threshold) - .append(" lowMemory=").append(info.lowMemory) - .append(" lowRamDevice=").append(am.isLowRamDevice()) - .append('\n'); - } - } catch (Throwable error) { - sb.append("memoryInfo=unavailable ").append(error).append('\n'); - } - appendStat(sb, "data", Environment.getDataDirectory()); - appendStat(sb, "external", Environment.getExternalStorageDirectory()); - File files = context.getFilesDir(); - if (files != null) appendStat(sb, "files", files); - sb.append("\n[/proc/meminfo]\n").append(readHead(new File("/proc/meminfo"), 8192)); - sb.append("\n[/proc/cpuinfo]\n").append(readHead(new File("/proc/cpuinfo"), 16384)); - sb.append("\n[/proc/self/status]\n").append(readHead(new File("/proc/self/status"), 8192)); - return sb.toString(); - } - - private static String settings(Context context) { - StringBuilder sb = new StringBuilder(); - ContentResolver resolver = context.getContentResolver(); - appendSetting(sb, resolver, Settings.Global.ANIMATOR_DURATION_SCALE); - appendSetting(sb, resolver, Settings.Global.TRANSITION_ANIMATION_SCALE); - appendSetting(sb, resolver, Settings.Global.WINDOW_ANIMATION_SCALE); - appendSetting(sb, resolver, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); - try { - sb.append("androidId=").append(Settings.Secure.getString(resolver, Settings.Secure.ANDROID_ID)).append('\n'); - } catch (Throwable error) { - sb.append("androidId=unavailable ").append(error.getClass().getSimpleName()).append('\n'); - } - return sb.toString(); - } - - private static String describePackage(Context context, String packageName) { - StringBuilder sb = new StringBuilder(); - sb.append("package=").append(packageName).append('\n'); - PackageManager pm = context.getPackageManager(); - PackageInfo info = null; - try { - info = pm.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES); - } catch (Throwable first) { - sb.append("getPackageInfoWithCerts=").append(first).append('\n'); - try { - info = pm.getPackageInfo(packageName, 0); - } catch (Throwable second) { - sb.append("getPackageInfo=unavailable ").append(second).append('\n'); - return sb.toString(); - } - } - sb.append("versionName=").append(info.versionName).append('\n'); - sb.append("versionCode=").append(info.getLongVersionCode()).append('\n'); - sb.append("firstInstallTime=").append(formatTime(info.firstInstallTime)).append('\n'); - sb.append("lastUpdateTime=").append(formatTime(info.lastUpdateTime)).append('\n'); - try { - sb.append("installer=").append(pm.getInstallerPackageName(packageName)).append('\n'); - } catch (Throwable error) { - sb.append("installer=unavailable ").append(error).append('\n'); - } - try { - android.content.Intent launch = pm.getLaunchIntentForPackage(packageName); - sb.append("launchIntent=").append(launch == null ? "null" : launch.toString()).append('\n'); - } catch (Throwable error) { - sb.append("launchIntent=unavailable ").append(error).append('\n'); - } - ApplicationInfo app = info.applicationInfo; - if (app != null) { - sb.append("sourceDir=").append(app.sourceDir).append('\n'); - sb.append("publicSourceDir=").append(app.publicSourceDir).append('\n'); - sb.append("nativeLibraryDir=").append(app.nativeLibraryDir).append('\n'); - sb.append("dataDir=").append(app.dataDir).append('\n'); - sb.append("targetSdk=").append(app.targetSdkVersion).append('\n'); - sb.append("minSdk=").append(app.minSdkVersion).append('\n'); - sb.append("uid=").append(app.uid).append('\n'); - sb.append("flags=0x").append(Integer.toHexString(app.flags)).append('\n'); - sb.append("extractNativeLibs=").append((app.flags & ApplicationInfo.FLAG_EXTRACT_NATIVE_LIBS) != 0).append('\n'); - appendFileStat(sb, "baseApk", app.sourceDir == null ? null : new File(app.sourceDir)); - if (app.splitSourceDirs != null) { - for (int i = 0; i < app.splitSourceDirs.length; i++) { - String splitName = info.splitNames != null && i < info.splitNames.length ? info.splitNames[i] : ("split" + i); - sb.append("splitName=").append(splitName).append('\n'); - appendFileStat(sb, "splitApk", new File(app.splitSourceDirs[i])); - } - } else { - sb.append("splitSourceDirs=none\n"); - } - } - appendSignatures(sb, info); - return sb.toString(); - } - - private static void appendSignatures(StringBuilder sb, PackageInfo info) { - try { - SigningInfo signing = info.signingInfo; - if (signing == null) { - sb.append("signingInfo=null\n"); - return; - } - sb.append("hasMultipleSigners=").append(signing.hasMultipleSigners()).append('\n'); - sb.append("hasPastSigningCertificates=").append(signing.hasPastSigningCertificates()).append('\n'); - appendCerts(sb, "apkContentsSigner", signing.getApkContentsSigners()); - if (signing.hasPastSigningCertificates()) { - appendCerts(sb, "signingCertificateHistory", signing.getSigningCertificateHistory()); - } - } catch (Throwable error) { - sb.append("signingInfo=unavailable ").append(error).append('\n'); - } - } - - private static void appendCerts(StringBuilder sb, String label, Signature[] signatures) { - if (signatures == null) { - sb.append(label).append("=null\n"); - return; - } - for (int i = 0; i < signatures.length; i++) { - try { - byte[] encoded = signatures[i].toByteArray(); - sb.append(label).append('[').append(i).append("] sha256=").append(sha256(encoded)) - .append(" bytes=").append(encoded.length).append('\n'); - } catch (Throwable error) { - sb.append(label).append('[').append(i).append("]=unavailable ").append(error).append('\n'); - } - } - } - - private static String nativeLibraries(Context context, String gamePackage) { - StringBuilder sb = new StringBuilder(); - long page = -1L; - try { - page = Os.sysconf(OsConstants._SC_PAGESIZE); - } catch (Throwable ignored) { - } - sb.append("devicePageSize=").append(page).append('\n'); - List apks = new ArrayList(); - describeNativeDir(sb, "launcherNative", nativeDir(context, context.getPackageName()), apks); - describeNativeDir(sb, "gameNative", nativeDir(context, gamePackage), apks); - PackageInfo game = packageOrNull(context, gamePackage); - if (game != null && game.applicationInfo != null) { - addApk(apks, game.applicationInfo.sourceDir); - if (game.applicationInfo.splitSourceDirs != null) { - for (int i = 0; i < game.applicationInfo.splitSourceDirs.length; i++) { - addApk(apks, game.applicationInfo.splitSourceDirs[i]); - } - } - } - PackageInfo self = packageOrNull(context, context.getPackageName()); - if (self != null && self.applicationInfo != null) addApk(apks, self.applicationInfo.sourceDir); - for (int i = 0; i < apks.size(); i++) { - probeApkNative(sb, apks.get(i), page); - } - return sb.toString(); - } - - private static void describeNativeDir(StringBuilder sb, String label, File dir, List apks) { - sb.append('[').append(label).append("] path=").append(dir == null ? "null" : dir.getAbsolutePath()).append('\n'); - if (dir == null || !dir.exists()) { - sb.append("exists=false\n"); - return; - } - if (!dir.canRead()) { - sb.append("readable=false\n"); - return; - } - File[] files = dir.listFiles(); - if (files == null) { - sb.append("list=null\n"); - return; - } - Arrays.sort(files); - for (int i = 0; i < files.length && i < 80; i++) { - File file = files[i]; - sb.append(file.getName()).append(" size=").append(file.length()).append(" readable=").append(file.canRead()).append('\n'); - if ("libil2cpp.so".equals(file.getName()) || "libunity.so".equals(file.getName()) - || "libmain.so".equals(file.getName()) || "libpine.so".equals(file.getName())) { - appendElf(sb, file, file.length(), null); - } - } - } - - private static void probeApkNative(StringBuilder sb, File apk, long page) { - sb.append("[apk] ").append(apk.getAbsolutePath()).append(" size=").append(apk.length()) - .append(" readable=").append(apk.canRead()).append('\n'); - if (!apk.isFile() || !apk.canRead()) return; - ZipFile zip = null; - try { - zip = new ZipFile(apk); - String[] names = new String[] { - "lib/arm64-v8a/libil2cpp.so", - "lib/arm64-v8a/libunity.so", - "lib/arm64-v8a/libmain.so", - "lib/arm64-v8a/libpine.so" - }; - for (int i = 0; i < names.length; i++) { - ZipEntry entry = zip.getEntry(names[i]); - if (entry == null) { - sb.append(names[i]).append("=absent\n"); - continue; - } - sb.append(names[i]).append(" uncompressed=").append(entry.getSize()) - .append(" compressed=").append(entry.getCompressedSize()).append('\n'); - if ("lib/arm64-v8a/libil2cpp.so".equals(names[i])) { - hashZipEntry(sb, zip, entry); - byte[] prefix = readZipPrefix(zip, entry, 64 * 1024); - sb.append(BppDiagnosticBundle.describeElfLoadSegments(prefix, apk.getName() + "!" + names[i])); - appendAlignComparison(sb, prefix, page); - } - } - } catch (Throwable error) { - sb.append("zipError=").append(error).append('\n'); - } finally { - if (zip != null) { - try { - zip.close(); - } catch (Throwable ignored) { - } - } - } - } - - private static void appendElf(StringBuilder sb, File file, long size, Long page) { - try { - if (size <= NATIVE_HASH_CAP && "libil2cpp.so".equals(file.getName())) { - sb.append("sha256=").append(BppDiagnosticBundle.sha256Hex(file, NATIVE_HASH_CAP)).append('\n'); - } - byte[] prefix = BppDiagnosticBundle.readPrefix(file, 64 * 1024); - sb.append(BppDiagnosticBundle.describeElfLoadSegments(prefix, file.getAbsolutePath())); - long pageSize = page == null ? Os.sysconf(OsConstants._SC_PAGESIZE) : page.longValue(); - appendAlignComparison(sb, prefix, pageSize); - } catch (Throwable error) { - sb.append("elfProbe=unavailable ").append(error).append('\n'); - } - } - - private static void appendAlignComparison(StringBuilder sb, byte[] prefix, long page) { - String described = BppDiagnosticBundle.describeElfLoadSegments(prefix, "compare"); - int marker = described.indexOf("minLoadAlign="); - if (marker < 0 || page <= 0) { - sb.append("minLoadAlignBelowDevicePage=unknown\n"); - return; - } - int end = described.indexOf('\n', marker); - String number = described.substring(marker + "minLoadAlign=".length(), end < 0 ? described.length() : end).trim(); - try { - long align = Long.parseLong(number); - sb.append("minLoadAlignBelowDevicePage=").append(align < page).append('\n'); - } catch (NumberFormatException ex) { - sb.append("minLoadAlignBelowDevicePage=unknown\n"); - } - } - - private static void hashZipEntry(StringBuilder sb, ZipFile zip, ZipEntry entry) { - try (InputStream in = zip.getInputStream(entry)) { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] buf = new byte[65536]; - long total = 0L; - int n; - while ((n = in.read(buf)) != -1) { - total += n; - if (total > NATIVE_HASH_CAP) { - sb.append("sha256=skipped over cap\n"); - return; - } - digest.update(buf, 0, n); - } - sb.append("sha256=").append(hex(digest.digest())).append(" hashedBytes=").append(total).append('\n'); - } catch (Throwable error) { - sb.append("sha256=unavailable ").append(error).append('\n'); - } - } - - private static byte[] readZipPrefix(ZipFile zip, ZipEntry entry, int max) { - try (InputStream in = zip.getInputStream(entry)) { - byte[] data = new byte[max]; - int off = 0; - while (off < data.length) { - int n = in.read(data, off, data.length - off); - if (n < 0) break; - off += n; - } - if (off == data.length) return data; - byte[] trimmed = new byte[off]; - System.arraycopy(data, 0, trimmed, 0, off); - return trimmed; - } catch (Throwable error) { - return new byte[0]; - } - } - - private static String deployStatus(Activity activity, File gameRoot, File internalWorkDir) { - StringBuilder sb = new StringBuilder(); - sb.append("gameRoot=").append(gameRoot == null ? "null" : gameRoot.getAbsolutePath()).append('\n'); - sb.append("internalWork=").append(internalWorkDir == null ? "null" : internalWorkDir.getAbsolutePath()).append('\n'); - File state = internalWorkDir == null ? null : new File(internalWorkDir, BppBundledModpackInstaller.STATE_FILE_NAME); - appendFileStat(sb, "stateFile", state); - if (state != null && state.isFile() && state.canRead() && state.length() < 1024 * 1024) { - sb.append("stateBytes:\n").append(readHead(state, (int) state.length())).append('\n'); - } - hashIfPresent(sb, "runtimeDll", gameRoot == null ? null : new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.dll")); - hashIfPresent(sb, "modpackDll", gameRoot == null ? null : new File(gameRoot, "modpacks/bpp/plugins/BazaarPlusPlus.dll")); - hashIfPresent(sb, "runtimeBridgeDll", gameRoot == null ? null : new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.BepInExBridge.dll")); - hashIfPresent(sb, "runtimeUpstreamHostDll", gameRoot == null ? null : new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.Android.dll")); - appendTreeSummary(sb, "interop", gameRoot == null ? null : new File(gameRoot, "BepInEx/interop"), ".dll"); - appendTreeSummary(sb, "unityLibs", gameRoot == null ? null : new File(gameRoot, "BepInEx/unity-libs"), null); - appendTreeSummary(sb, "dummy", gameRoot == null ? null : new File(gameRoot, "BepInEx/dummy"), null); - appendTreeSummary(sb, "bepInExLogs", gameRoot == null ? null : new File(gameRoot, "BepInEx/logs"), null); - appendTreeSummary(sb, "modpackLogs", gameRoot == null ? null : new File(gameRoot, "modpacks/bpp/logs"), null); - try (InputStream in = activity.getAssets().open(BppBundledModpackInstaller.ASSET_MODPACK_MANIFEST)) { - BppBundledModpackInstaller.Manifest manifest = BppBundledModpackInstaller.parseManifest(in); - sb.append("bundledBundle=").append(manifest.bundleId) - .append(" version=").append(manifest.version) - .append(" files=").append(manifest.entries.size()) - .append(" managedDlls=").append(manifest.managedDllCount).append('\n'); - if (gameRoot != null && internalWorkDir != null) { - BppBundledModpackInstaller.StatusReport report = BppBundledModpackInstaller.inspectStatus( - gameRoot, internalWorkDir, manifest, true); - sb.append("status=").append(report.kind) - .append(" detail=").append(report.detail) - .append(" bundle=").append(report.bundleId) - .append(" version=").append(report.version).append('\n'); - } - } catch (Throwable error) { - sb.append("bundledManifest=unavailable ").append(error).append('\n'); - } - try (InputStream in = activity.getAssets().open(BppBundledModpackInstaller.ASSET_MODPACK_ZIP)) { - byte[] buf = new byte[8192]; - long total = 0L; - int n; - while ((n = in.read(buf)) != -1) total += n; - sb.append("bundledZipStreamLength=").append(total).append('\n'); - } catch (Throwable error) { - sb.append("bundledZipStreamLength=unavailable ").append(error.getClass().getSimpleName()) - .append(' ').append(error.getMessage()).append('\n'); - } - return sb.toString(); - } - - private static void appendTreeSummary(StringBuilder sb, String label, File dir, String suffix) { - BppDiagnosticBundle.DirStat stat = BppDiagnosticBundle.summarizeTree(dir, suffix, 3); - sb.append(label) - .append(" path=").append(dir == null ? "null" : dir.getAbsolutePath()) - .append(" missing=").append(stat.missing) - .append(" unreadable=").append(stat.unreadable) - .append(" files=").append(stat.files) - .append(" bytes=").append(stat.bytes) - .append('\n'); - } - - private static String logDirectories(Context context, File gameRoot) { - StringBuilder sb = new StringBuilder(); - File[] dirs = new File[] { - gameRoot == null ? null : new File(gameRoot, "BepInEx/logs"), - gameRoot == null ? null : new File(gameRoot, "modpacks/bpp/logs"), - gameRoot == null ? null : new File(gameRoot, "BepInEx/interop"), - gameRoot == null ? null : new File(gameRoot, "BepInEx/unity-libs"), - gameRoot == null ? null : new File(gameRoot, "BepInEx/dummy"), - context.getExternalFilesDir(null) - }; - for (int i = 0; i < dirs.length; i++) { - sb.append("====\n").append(BppDiagnosticBundle.describeDirectory(dirs[i], 80)); - } - return sb.toString(); - } - - private static String datastoreKeys(File dir) { - StringBuilder sb = new StringBuilder(); - if (dir == null || !dir.exists()) return "(missing)\n"; - if (!dir.isDirectory()) return "(not a directory)\n"; - File[] files = dir.listFiles(); - if (files == null) return "(unreadable)\n"; - Arrays.sort(files, new java.util.Comparator() { - @Override - public int compare(File a, File b) { - return a.getName().compareTo(b.getName()); - } - }); - if (files.length == 0) sb.append("(empty)\n"); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - String name = file.getName().toLowerCase(java.util.Locale.ROOT); - if (!name.endsWith(".preferences_pb") && !name.endsWith(".pb")) continue; - sb.append("## ").append(file.getName()).append(" bytes=").append(file.length()).append('\n'); - try { - sb.append(BppDiagnosticBundle.decodePreferenceProto(BppDiagnosticBundle.readPrefix(file, 256 * 1024))); - } catch (Throwable error) { - sb.append("unavailable ").append(error.getClass().getSimpleName()).append('\n'); - } - } - return sb.toString(); - } - - private static void harvestLogs(List extras, File root, String prefix) { - if (root == null || extras == null) return; - List logs = BppDiagnosticBundle.findLogFiles(root, 200); - String rootPath = root.getAbsolutePath(); - for (int i = 0; i < logs.size(); i++) { - File file = logs.get(i); - String path = file.getAbsolutePath(); - String relative = path.startsWith(rootPath) ? path.substring(rootPath.length()) : file.getName(); - while (relative.startsWith("/")) relative = relative.substring(1); - relative = relative.replace('\\', '/'); - if (relative.length() == 0) relative = file.getName(); - extras.add(new BppDiagnosticBundle.ExtraFile(file, prefix + "/" + relative, true)); - } - } - - private static void harvestJitTrace(Activity activity, File stage, List extras) { - File dir = BppJitTrace.traceDir(activity); - if (dir != null && dir.isDirectory()) { - File[] files = dir.listFiles(); - if (files != null) { - Arrays.sort(files, new java.util.Comparator() { - @Override - public int compare(File a, File b) { - return a.getName().compareTo(b.getName()); - } - }); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (!file.isFile()) continue; - String name = file.getName(); - String lower = name.toLowerCase(Locale.ROOT); - if (lower.endsWith(".log") || lower.endsWith(".txt")) { - addJitTail(activity, stage, extras, file, "jit/" + name); - } else if (lower.endsWith(".nettrace")) { - extras.add(new BppDiagnosticBundle.ExtraFile( - file, "jit/" + name, false, 24 * 1024 * 1024)); - } - } - } - } - File external = activity.getExternalFilesDir(null); - addJitFusionTail(activity, stage, extras, external, - "coreclr_stdout.log", "jit/fusion-coreclr_stdout.log"); - addJitFusionTail(activity, stage, extras, external, - "coreclr_stderr.log", "jit/fusion-coreclr_stderr.log"); - } - - private static void addJitFusionTail( - Activity activity, - File stage, - List extras, - File external, - String sourceName, - String archivePath - ) { - File source = external == null ? null : new File(external, sourceName); - addJitTail(activity, stage, extras, source, archivePath); - } - - private static void addJitTail( - Activity activity, - File stage, - List extras, - File source, - String archivePath - ) { - if (source == null || !source.isFile()) { - extras.add(new BppDiagnosticBundle.ExtraFile(source, archivePath, true)); - return; - } - final int cap = 4 * 1024 * 1024; - long size; - try { - size = source.length(); - } catch (Throwable error) { - BppGameProcess.logEvent(activity, "jit trace size failed: " + source, error); - extras.add(new BppDiagnosticBundle.ExtraFile(source, archivePath, true)); - return; - } - long keepOffset = Math.max(0L, size - cap); - long keepLength = Math.min(size, (long) cap); - boolean truncated = size > cap; - File staged = new File(stage, archivePath); - File parent = staged.getParentFile(); - if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { - BppGameProcess.logEvent(activity, "jit trace stage mkdir failed: " + parent); - extras.add(new BppDiagnosticBundle.ExtraFile(source, archivePath, true)); - return; - } - try (RandomAccessFile raf = new RandomAccessFile(source, "r"); - FileOutputStream out = new FileOutputStream(staged)) { - if (truncated) { - String header = "# originalBytes=" + size + " keptTail=" + keepLength + "\n"; - out.write(header.getBytes(StandardCharsets.UTF_8)); - } - raf.seek(keepOffset); - byte[] buf = new byte[65536]; - long remaining = keepLength; - while (remaining > 0L) { - int want = (int) Math.min((long) buf.length, remaining); - int n = raf.read(buf, 0, want); - if (n < 0) break; - out.write(buf, 0, n); - remaining -= n; - } - out.getFD().sync(); - } catch (Throwable error) { - BppGameProcess.logEvent(activity, "jit trace tail failed: " + source, error); - extras.add(new BppDiagnosticBundle.ExtraFile(source, archivePath, true)); - return; - } - extras.add(new BppDiagnosticBundle.ExtraFile(staged, archivePath, true)); - } - - private static String expectedPaths(Context context, File gameRoot) { - StringBuilder sb = new StringBuilder(); - describeExpected(sb, "game-root", gameRoot); - File external = context.getExternalFilesDir(null); - describeExpected(sb, "external-files", external); - describeExpected(sb, "legacy-sdcard", new File("/sdcard/BepInEx_Android/" + BppBundledModpackInstaller.TARGET_PACKAGE)); - describeExpected(sb, "legacy-emulated", - new File("/storage/emulated/0/BepInEx_Android/" + BppBundledModpackInstaller.TARGET_PACKAGE)); - if (external != null) { - appendFileStat(sb, "externalPlayerLog", new File(external, "Player.log")); - appendFileStat(sb, "externalUnityLog", new File(external, "unity.log")); - } - return sb.toString(); - } - - private static void describeExpected(StringBuilder sb, String label, File root) { - sb.append('[').append(label).append("] root=") - .append(root == null ? "null" : root.getAbsolutePath()).append('\n'); - if (root == null || !root.exists()) { - sb.append("rootExists=false\n"); - return; - } - if (!root.canRead()) { - sb.append("rootReadable=false\n"); - return; - } - for (int i = 0; i < EXPECTED_RELATIVE.length; i++) { - File file = new File(root, EXPECTED_RELATIVE[i]); - sb.append(EXPECTED_RELATIVE[i]) - .append(" exists=").append(file.exists()) - .append(" readable=").append(file.canRead()) - .append(" dir=").append(file.isDirectory()) - .append(" size=").append(file.exists() && !file.isDirectory() ? file.length() : -1) - .append(" mtime=").append(file.exists() ? file.lastModified() : 0) - .append('\n'); - } - } - - private static String tombstoneProbes(Context context, File gameRoot) { - StringBuilder sb = new StringBuilder(); - List probes = new ArrayList(); - probes.add(new File("/data/tombstones")); - probes.add(new File("/data/anr")); - probes.add(new File("/data/anr/traces.txt")); - probes.add(new File("/proc/last_kmsg")); - probes.add(new File("/sys/fs/pstore")); - if (gameRoot != null) probes.add(new File(gameRoot, "PersistentData")); - File external = context.getExternalFilesDir(null); - if (external != null) probes.add(new File(external, "PersistentData")); - probes.add(new File("/sdcard/BepInEx_Android/" + BppBundledModpackInstaller.TARGET_PACKAGE + "/PersistentData")); - probes.add(new File("/storage/emulated/0/BepInEx_Android/" + BppBundledModpackInstaller.TARGET_PACKAGE + "/PersistentData")); - for (int i = 0; i < probes.size(); i++) { - File file = probes.get(i); - sb.append(file.getAbsolutePath()) - .append(" exists=").append(file.exists()) - .append(" readable=").append(file.canRead()) - .append(" dir=").append(file.isDirectory()) - .append(" size=").append(file.isFile() ? file.length() : -1); - if (file.isDirectory() && file.canRead()) { - String[] names = file.list(); - sb.append(" children=").append(names == null ? "null" : names.length); - if (names != null) { - Arrays.sort(names); - int limit = Math.min(names.length, 30); - for (int n = 0; n < limit; n++) sb.append(" name=").append(names[n]); - } - } - sb.append('\n'); - } - return sb.toString(); - } - - private static void addReadableTombstones(List scans, Context context, File gameRoot) { - File[] dirs = new File[] { - new File("/data/tombstones"), - new File("/data/anr"), - gameRoot == null ? null : new File(gameRoot, "PersistentData") - }; - for (int i = 0; i < dirs.length; i++) { - File dir = dirs[i]; - if (dir != null && dir.isDirectory() && dir.canRead()) { - addScan(scans, dir, "crashes/probe-" + i, false); - } - } - } - - private static String exitReasons(Activity activity, File stage, List extras) { - StringBuilder sb = new StringBuilder(); - if (Build.VERSION.SDK_INT < 30) { - sb.append("applicationExitInfo=unavailable before API 30 (sdk=").append(Build.VERSION.SDK_INT).append(")\n"); - return sb.toString(); - } - try { - ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE); - if (am == null) { - sb.append("activityManager=null\n"); - return sb.toString(); - } - Method historical = ActivityManager.class.getMethod( - "getHistoricalProcessExitReasons", String.class, int.class, int.class); - Object raw = historical.invoke(am, activity.getPackageName(), Integer.valueOf(0), Integer.valueOf(30)); - if (!(raw instanceof List)) { - sb.append("resultType=").append(raw == null ? "null" : raw.getClass().getName()).append('\n'); - return sb.toString(); - } - List infos = (List) raw; - sb.append("count=").append(infos.size()).append('\n'); - for (int i = 0; i < infos.size(); i++) { - Object info = infos.get(i); - if (info == null) continue; - long timestamp = longCall(info, "getTimestamp"); - String process = stringCall(info, "getProcessName"); - int reason = intCall(info, "getReason"); - int status = intCall(info, "getStatus"); - int importance = intCall(info, "getImportance"); - long pss = longCall(info, "getPss"); - long rss = longCall(info, "getRss"); - int pid = intCall(info, "getPid"); - int subReason = intCall(info, "getSubReason"); - String description = stringCall(info, "getDescription"); - String processState = stringCall(info, "getProcessStateSummary"); - sb.append("--- ").append(i) - .append(" time=").append(formatTime(timestamp)) - .append(" pid=").append(pid) - .append(" process=").append(process) - .append(" reason=").append(reason) - .append(" reasonName=").append(BppDiagnosticBundle.exitReasonName(reason)) - .append(" subReason=").append(subReason) - .append(" subReasonName=").append(BppDiagnosticBundle.exitSubReasonName(subReason)) - .append(" status=").append(status) - .append(" importance=").append(importance) - .append(" importanceName=").append(BppDiagnosticBundle.importanceName(importance)) - .append(" pss=").append(pss) - .append(" rss=").append(rss) - .append(" description=").append(description) - .append(" processStateSummary=").append(processState) - .append('\n'); - writeTrace(info, stage, extras, i, process, sb); - } - } catch (Throwable error) { - sb.append("applicationExitInfo=unavailable ").append(error).append('\n'); - } - return sb.toString(); - } - - private static void writeTrace( - Object info, - File stage, - List extras, - int index, - String process, - StringBuilder sb - ) { - InputStream in = null; - try { - Method method = info.getClass().getMethod("getTraceInputStream"); - Object value = method.invoke(info); - if (!(value instanceof InputStream)) { - sb.append("trace=").append(index).append(" none\n"); - return; - } - in = (InputStream) value; - File out = new File(stage, "exit-" + index + "-" + safeToken(process) + ".trace"); - try (FileOutputStream fos = new FileOutputStream(out)) { - byte[] buf = new byte[8192]; - int total = 0; - int n; - while ((n = in.read(buf)) != -1 && total < 2 * 1024 * 1024) { - int allow = Math.min(n, 2 * 1024 * 1024 - total); - fos.write(buf, 0, allow); - total += allow; - } - sb.append("trace=").append(index).append(" bytes=").append(total) - .append(" file=").append(out.getName()).append('\n'); - } - extras.add(new BppDiagnosticBundle.ExtraFile(out, "crashes/" + out.getName(), true)); - } catch (Throwable error) { - sb.append("trace=").append(index).append(" unavailable ").append(error).append('\n'); - } finally { - if (in != null) { - try { - in.close(); - } catch (Throwable ignored) { - } - } - } - } - - private static String dumpLogcat(File stage, List extras) { - StringBuilder sb = new StringBuilder(); - sb.append("note=logcat without READ_LOGS only includes this app UID, including :game when the buffer still has it\n"); - writeDump(stage, extras, sb, "all", BppDiagnosticBundle.dumpLogcatCommand("all")); - for (int i = 0; i < BppDiagnosticBundle.LOGCAT_BUFFERS.length; i++) { - String buffer = BppDiagnosticBundle.LOGCAT_BUFFERS[i]; - writeDump(stage, extras, sb, buffer, BppDiagnosticBundle.dumpLogcatCommand(buffer)); - } - return sb.toString(); - } - - private static void writeDump( - File stage, - List extras, - StringBuilder sb, - String name, - List command - ) { - String text = BppDiagnosticBundle.captureProcessText(command, 15000L, 2 * 1024 * 1024); - File file = new File(stage, "logcat-" + name + ".txt"); - try { - byte[] data = text.getBytes(StandardCharsets.UTF_8); - try (FileOutputStream out = new FileOutputStream(file)) { - out.write(data); - } - extras.add(new BppDiagnosticBundle.ExtraFile(file, "logcat/dump-" + name + ".txt", true)); - sb.append(name).append(" bytes=").append(data.length) - .append(" failed=").append(text.startsWith("[unavailable]") || text.toLowerCase(Locale.ROOT).contains("permission denied")) - .append('\n'); - } catch (Throwable error) { - sb.append(name).append(" writeFailed=").append(error).append('\n'); - } - } - - private static String shellProbes(Context context) { - StringBuilder sb = new StringBuilder(); - sb.append("[uname]\n").append(capture("uname -a", 4000L, 4096)).append('\n'); - sb.append("[dumpsys activity exit-info]\n"); - sb.append(capture("dumpsys activity exit-info " + context.getPackageName(), 8000L, 400 * 1024)).append('\n'); - sb.append("[dumpsys meminfo]\n"); - sb.append(capture("dumpsys meminfo " + context.getPackageName(), 8000L, 400 * 1024)).append('\n'); - sb.append("[dumpsys display]\n"); - sb.append(capture("dumpsys display", 8000L, 400 * 1024)).append('\n'); - return sb.toString(); - } - - private static String capture(String command, long timeoutMs, int maxBytes) { - String[] parts = command.split(" "); - return BppDiagnosticBundle.captureProcessText(Arrays.asList(parts), timeoutMs, maxBytes); - } - - private static String redactProps(String text) { - if (text == null) return ""; - String[] lines = text.split("\n", -1); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < lines.length; i++) { - String line = lines[i]; - String lower = line.toLowerCase(Locale.ROOT); - if (lower.contains("password") || lower.contains("secret") || lower.contains("token") - || lower.contains("keystore")) { - int cut = line.indexOf(':'); - if (cut < 0) cut = line.indexOf('='); - sb.append(cut >= 0 ? line.substring(0, cut + 1) + " [redacted]" : "[redacted]"); - } else { - sb.append(line); - } - if (i + 1 < lines.length) sb.append('\n'); - } - return sb.toString(); - } - - private static void addScan(List scans, File dir, String label, boolean stateTree) { - if (dir == null) { - scans.add(new BppDiagnosticBundle.ScanRoot(null, label, stateTree)); - return; - } - String key; - try { - key = dir.getCanonicalPath(); - } catch (Exception ex) { - key = dir.getAbsolutePath(); - } - for (int i = 0; i < scans.size(); i++) { - File existing = scans.get(i).directory; - if (existing == null) continue; - try { - if (key.equals(existing.getCanonicalPath())) return; - } catch (Exception ignored) { - if (key.equals(existing.getAbsolutePath())) return; - } - } - scans.add(new BppDiagnosticBundle.ScanRoot(dir, label, stateTree)); - } - - private static void hashIfPresent(StringBuilder sb, String label, File file) { - appendFileStat(sb, label, file); - if (file == null || !file.isFile() || !file.canRead() || file.length() > DLL_HASH_CAP) return; - try { - sb.append(label).append("Sha256=").append(BppDiagnosticBundle.sha256Hex(file, DLL_HASH_CAP)).append('\n'); - } catch (Throwable error) { - sb.append(label).append("Sha256=unavailable ").append(error).append('\n'); - } - } - - private static void appendFileStat(StringBuilder sb, String label, File file) { - if (file == null) { - sb.append(label).append("=null\n"); - return; - } - sb.append(label).append(" path=").append(file.getAbsolutePath()) - .append(" exists=").append(file.exists()) - .append(" readable=").append(file.canRead()) - .append(" size=").append(file.isFile() ? file.length() : -1) - .append(" mtime=").append(file.exists() ? formatTime(file.lastModified()) : "0") - .append('\n'); - } - - private static void appendStat(StringBuilder sb, String label, File dir) { - try { - if (dir == null) { - sb.append(label).append("=null\n"); - return; - } - StatFs stat = new StatFs(dir.getAbsolutePath()); - sb.append(label).append(" path=").append(dir.getAbsolutePath()) - .append(" block=").append(stat.getBlockSizeLong()) - .append(" total=").append(stat.getTotalBytes()) - .append(" avail=").append(stat.getAvailableBytes()) - .append('\n'); - } catch (Throwable error) { - sb.append(label).append("=unavailable ").append(error).append('\n'); - } - } - - private static void appendSetting(StringBuilder sb, ContentResolver resolver, String key) { - try { - sb.append(key).append('=').append(Settings.Global.getString(resolver, key)).append('\n'); - } catch (Throwable error) { - sb.append(key).append("=unavailable ").append(error.getClass().getSimpleName()).append('\n'); - } - } - - private static void appendReflected(StringBuilder sb, Class type, String field, String label) { - try { - Object value = type.getField(field).get(null); - sb.append(label).append('=').append(value).append('\n'); - } catch (Throwable ignored) { - sb.append(label).append("=unavailable\n"); - } - } - - private static File nativeDir(Context context, String packageName) { - PackageInfo info = packageOrNull(context, packageName); - if (info == null || info.applicationInfo == null || info.applicationInfo.nativeLibraryDir == null) return null; - return new File(info.applicationInfo.nativeLibraryDir); - } - - private static PackageInfo packageOrNull(Context context, String packageName) { - try { - return context.getPackageManager().getPackageInfo(packageName, 0); - } catch (Throwable ignored) { - return null; - } - } - - private static void addApk(List apks, String path) { - if (path == null) return; - File file = new File(path); - for (int i = 0; i < apks.size(); i++) { - if (apks.get(i).getAbsolutePath().equals(file.getAbsolutePath())) return; - } - apks.add(file); - } - - private static String readVersion(Context context) { - try { - return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; - } catch (Throwable ignored) { - return "未知"; - } - } - - private static String formatTime(long millis) { - if (millis <= 0L) return "0"; - try { - return Instant.ofEpochMilli(millis).toString() + " (" + millis + ")"; - } catch (RuntimeException ex) { - return Long.toString(millis); - } - } - - private static String readHead(File file, int maxBytes) { - if (file == null || !file.isFile() || !file.canRead()) return "(unreadable)\n"; - try (InputStream in = new FileInputStream(file)) { - byte[] data = new byte[Math.max(1, maxBytes)]; - int off = 0; - while (off < data.length) { - int n = in.read(data, off, data.length - off); - if (n < 0) break; - off += n; - } - return new String(data, 0, off, StandardCharsets.UTF_8); - } catch (Throwable error) { - return "(unreadable) " + error.getMessage() + "\n"; - } - } - - private static long longCall(Object target, String name) { - try { - Object value = target.getClass().getMethod(name).invoke(target); - if (value instanceof Long) return ((Long) value).longValue(); - if (value instanceof Integer) return ((Integer) value).longValue(); - } catch (Throwable ignored) { - } - return -1L; - } - - private static int intCall(Object target, String name) { - try { - Object value = target.getClass().getMethod(name).invoke(target); - if (value instanceof Integer) return ((Integer) value).intValue(); - if (value instanceof Long) return ((Long) value).intValue(); - } catch (Throwable ignored) { - } - return -1; - } - - private static String stringCall(Object target, String name) { - try { - Object value = target.getClass().getMethod(name).invoke(target); - return value == null ? "" : String.valueOf(value); - } catch (Throwable error) { - return "unavailable"; - } - } - - static String latestGameExitNote(Context context) { - if (context == null || Build.VERSION.SDK_INT < 30) return ""; - try { - ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); - if (am == null) return ""; - Method historical = ActivityManager.class.getMethod( - "getHistoricalProcessExitReasons", String.class, int.class, int.class); - Object raw = historical.invoke(am, context.getPackageName(), Integer.valueOf(0), Integer.valueOf(20)); - if (!(raw instanceof List)) return ""; - List infos = (List) raw; - for (int i = 0; i < infos.size(); i++) { - Object info = infos.get(i); - if (info == null) continue; - String process = stringCall(info, "getProcessName"); - if (process == null || !process.endsWith(":game")) continue; - int reason = intCall(info, "getReason"); - int importance = intCall(info, "getImportance"); - return "reason=" + reason - + " reasonName=" + BppDiagnosticBundle.exitReasonName(reason) - + " importance=" + importance - + " importanceName=" + BppDiagnosticBundle.importanceName(importance) - + " time=" + formatTime(longCall(info, "getTimestamp")); - } - } catch (Throwable ignored) { - } - return ""; - } - - private static String sha256(byte[] data) throws Exception { - return hex(MessageDigest.getInstance("SHA-256").digest(data)); - } - - private static String hex(byte[] data) { - char[] alphabet = "0123456789abcdef".toCharArray(); - char[] out = new char[data.length * 2]; - for (int i = 0; i < data.length; i++) { - int v = data[i] & 0xff; - out[i * 2] = alphabet[v >>> 4]; - out[i * 2 + 1] = alphabet[v & 0x0f]; - } - return new String(out); - } - - private static String safeToken(String value) { - if (value == null || value.length() == 0) return "unknown"; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < value.length() && sb.length() < 48; i++) { - char c = value.charAt(i); - boolean ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') - || c == '.' || c == '_' || c == '-'; - sb.append(ok ? c : '_'); - } - return sb.toString(); - } - - private static String safeSection(List errors, String name, Section section) { - try { - String value = section.run(); - return value == null ? "" : value; - } catch (Throwable error) { - errors.add(name + ": " + error.getClass().getSimpleName() + ": " + error.getMessage()); - return "[unavailable] " + name + " " + error + "\n"; - } - } - - private static void deleteRecursively(File file) { - if (file == null || !file.exists()) return; - if (file.isDirectory()) { - File[] children = file.listFiles(); - if (children != null) { - for (int i = 0; i < children.length; i++) deleteRecursively(children[i]); - } - } - file.delete(); - } - - private interface Section { - String run() throws Exception; - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticSessionLog.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticSessionLog.java deleted file mode 100644 index 0a2fcaa..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppDiagnosticSessionLog.java +++ /dev/null @@ -1,323 +0,0 @@ -package com.bepinex.android.bpp; - -import android.content.Context; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -/** - * Persists a rolling logcat and launch breadcrumbs under the app files directory. - * The launcher process and the {@code :game} process each write their own file so a grey - * screen can still be exported after the user comes back. - */ -public final class BppDiagnosticSessionLog { - - public static final String DIR_NAME = "bpp-diagnostics"; - private static final int NOTE_CAP_BYTES = 256 * 1024; - private static final Object GATE = new Object(); - private static final Set STARTED = new HashSet(); - private static final Map MARKERS = new HashMap(); - private static final ScheduledExecutorService SNAPSHOTS = Executors.newSingleThreadScheduledExecutor( - new ThreadFactory() { - @Override - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(runnable, "bpp-diag-snapshots"); - thread.setDaemon(true); - return thread; - } - } - ); - private static final ScheduledExecutorService ROLLING = Executors.newSingleThreadScheduledExecutor( - new ThreadFactory() { - @Override - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(runnable, "bpp-diag-rolling"); - thread.setDaemon(true); - return thread; - } - } - ); - - private BppDiagnosticSessionLog() {} - - public static void ensureCapture(Context context, String role) { - ensureCapture(context, role, 0); - } - - /** {@code pid > 0} limits the rolling dump to that process ({@code logcat --pid}). */ - public static void ensureCapture(Context context, String role, int pid) { - if (context == null || !isRole(role)) return; - final Context app = application(context); - final int filter = Math.max(0, pid); - synchronized (GATE) { - if (!STARTED.add(role)) return; - } - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - startRolling(app, role, filter); - } - }, "bpp-diag-" + role); - thread.setDaemon(true); - thread.start(); - } - - public static void note(Context context, String fileName, String line) { - if (context == null || !isSafeFileName(fileName)) return; - try { - File dir = diagnosticsDir(context); - if (!dir.isDirectory() && !dir.mkdirs()) return; - BppDiagnosticBundle.appendCapped(new File(dir, fileName), line, NOTE_CAP_BYTES); - } catch (Throwable ignored) { - } - } - - /** Records the launch attempt immediately, then dumps logcat again after the game has had time to start. */ - public static void noteLaunch(Context context, String line) { - if (context == null) return; - ensureCapture(context, "launcher"); - note(context, "launch-attempts.log", line); - final Context app = application(context); - scheduleDump(app, "launch-snapshot-2s.log", 2L); - scheduleDump(app, "launch-snapshot-8s.log", 8L); - scheduleDump(app, "launch-snapshot-20s.log", 20L); - } - - public static File diagnosticsDir(Context context) { - Context app = application(context); - return new File(app.getFilesDir(), DIR_NAME); - } - - private static void scheduleDump(final Context context, final String name, long delaySeconds) { - SNAPSHOTS.schedule(new Runnable() { - @Override - public void run() { - dumpTo(context, name); - } - }, delaySeconds, TimeUnit.SECONDS); - } - - private static void dumpTo(Context context, String name) { - if (!isSafeFileName(name)) return; - try { - File dir = diagnosticsDir(context); - if (!dir.isDirectory() && !dir.mkdirs()) return; - File target = new File(dir, name); - File previous = new File(dir, "previous-" + name); - synchronized (BppDiagnosticSessionLog.class) { - if (target.isFile()) { - try { - Files.move(target.toPath(), previous.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING); - } catch (IOException ignored) { - } - } - String dump = dumpLogcat(); - BppDiagnosticBundle.appendCapped(target, dump, 4 * 1024 * 1024); - } - } catch (Throwable ignored) { - } - } - - static String dumpLogcat() { - return dumpLogcat(0); - } - - static String dumpLogcat(int pid) { - String all = BppDiagnosticBundle.captureProcessText( - BppDiagnosticBundle.dumpLogcatCommand("all", pid), 20000L, 3 * 1024 * 1024); - if (!isFailedDump(all)) return all; - StringBuilder sb = new StringBuilder(); - sb.append(all); - if (!all.endsWith("\n")) sb.append('\n'); - for (int i = 0; i < BppDiagnosticBundle.LOGCAT_BUFFERS.length; i++) { - String buffer = BppDiagnosticBundle.LOGCAT_BUFFERS[i]; - sb.append("===== buffer ").append(buffer).append(" =====\n"); - sb.append(BppDiagnosticBundle.captureProcessText( - BppDiagnosticBundle.dumpLogcatCommand(buffer, pid), 12000L, 1024 * 1024)); - if (sb.length() > 4 * 1024 * 1024) break; - sb.append('\n'); - } - return sb.toString(); - } - - private static boolean isFailedDump(String text) { - if (text == null || text.length() == 0) return true; - if (text.startsWith("[unavailable]")) return true; - String lower = text.toLowerCase(java.util.Locale.ROOT); - boolean denied = lower.contains("permission denied") || lower.contains("unknown buffer"); - return denied && !lower.contains("beginning of"); - } - - private static void startRolling(final Context context, final String role, final int pid) { - File dir = null; - try { - dir = diagnosticsDir(context); - if (!dir.isDirectory() && !dir.mkdirs()) return; - final File output = new File(dir, role + "-logcat"); - BppDiagnosticBundle.appendCapped( - new File(dir, role + "-logcat.pid"), - Integer.toString(pid > 0 ? pid : android.os.Process.myPid()), - 64 - ); - meta(dir, role, "capture-start mode=periodic-dump pidFilter=" + pid, output, ""); - ROLLING.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - captureIncremental(context, role, pid, output); - } - }, 0L, 2L, TimeUnit.SECONDS); - } catch (Throwable error) { - try { - if (dir == null) dir = diagnosticsDir(context); - if (dir.isDirectory() || dir.mkdirs()) { - meta(dir, role, "capture-failed error=" + oneLine(String.valueOf(error)), null, ""); - } - } catch (Throwable ignored) { - } - } - } - - private static void captureIncremental(Context context, String role, int pid, File output) { - try { - String dump = dumpLogcat(pid); - if (isFailedDump(dump) && (dump == null || dump.indexOf('\n') < 0)) { - File dir = diagnosticsDir(context); - if (dir.isDirectory() || dir.mkdirs()) { - BppDiagnosticBundle.appendCapped(new File(dir, role + "-logcat.stderr"), oneLine(dump), 8000); - } - return; - } - String marker; - synchronized (MARKERS) { - marker = MARKERS.get(role); - } - String suffix = BppDiagnosticBundle.suffixAfterMarker(dump, marker); - String nextMarker = BppDiagnosticBundle.lastLogLine(dump); - if (nextMarker.length() > 0) { - synchronized (MARKERS) { - MARKERS.put(role, nextMarker); - } - } - if (suffix.length() == 0) return; - BppDiagnosticBundle.appendCapped(output, suffix, 4 * 1024 * 1024); - } catch (Throwable ignored) { - } - } - - private static void meta(File dir, String role, String event, File output, String stderr) throws IOException { - StringBuilder line = new StringBuilder(); - line.append(BppDiagnosticBundle.nowIso()) - .append(" role=").append(role) - .append(" event=").append(event) - .append(" launcherPid=").append(android.os.Process.myPid()); - if (output != null) line.append(" file=").append(output.getAbsolutePath()); - if (stderr != null && stderr.length() > 0) line.append(" stderr=").append(oneLine(stderr)); - BppDiagnosticBundle.appendCapped(new File(dir, "session-meta.log"), line.toString(), NOTE_CAP_BYTES); - } - - private static boolean logcatAlreadyRunning(String outputPath) { - File proc = new File("/proc"); - String[] names = proc.list(); - if (names == null) return false; - for (int i = 0; i < names.length; i++) { - String name = names[i]; - if (!isPid(name)) continue; - File cmdline = new File(new File(proc, name), "cmdline"); - try { - byte[] raw = Files.readAllBytes(cmdline.toPath()); - String cmd = new String(raw, StandardCharsets.UTF_8).replace('\0', ' '); - if (cmd.contains("logcat") && cmd.contains(outputPath)) return true; - } catch (IOException ignored) { - } - } - return false; - } - - private static boolean isPid(String name) { - if (name == null || name.length() == 0) return false; - for (int i = 0; i < name.length(); i++) { - char c = name.charAt(i); - if (c < '0' || c > '9') return false; - } - return true; - } - - private static int processPid(Process process) { - try { - Method method = process.getClass().getMethod("pid"); - Object value = method.invoke(process); - if (value instanceof Integer) return ((Integer) value).intValue(); - if (value instanceof Long) return ((Long) value).intValue(); - } catch (Throwable ignored) { - } - try { - Field field = process.getClass().getDeclaredField("pid"); - field.setAccessible(true); - return field.getInt(process); - } catch (Throwable ignored) { - } - return -1; - } - - private static int exitValue(Process process) { - try { - return process.exitValue(); - } catch (IllegalThreadStateException ex) { - return -1; - } - } - - private static String readSmall(File file, int maxBytes) { - try { - if (file == null || !file.isFile()) return ""; - byte[] data = Files.readAllBytes(file.toPath()); - if (data.length > maxBytes) { - return new String(data, data.length - maxBytes, maxBytes, StandardCharsets.UTF_8); - } - return new String(data, StandardCharsets.UTF_8); - } catch (IOException ex) { - return ""; - } - } - - private static boolean isRole(String role) { - return "launcher".equals(role) || "game".equals(role); - } - - static boolean isSafeFileName(String name) { - if (name == null || name.length() == 0 || name.length() > 80) return false; - if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0 || name.indexOf('\0') >= 0) return false; - if (".".equals(name) || "..".equals(name) || name.contains("..")) return false; - for (int i = 0; i < name.length(); i++) { - char c = name.charAt(i); - boolean ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') - || c == '.' || c == '_' || c == '-'; - if (!ok) return false; - } - return true; - } - - private static Context application(Context context) { - try { - Context app = context.getApplicationContext(); - if (app != null) return app; - } catch (Throwable ignored) { - } - return context; - } - - private static String oneLine(String value) { - return value == null ? "" : value.replace('\n', ' ').replace('\r', ' '); - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameApplication.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameApplication.java deleted file mode 100644 index 82de59b..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameApplication.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Application; -import android.content.Context; - -/** - * The fused launcher has no application class of its own. Installing this one makes - * attachBaseContext/onCreate run in every process, including :game, which is the process - * that actually draws the grey Unity surface and runs Cpp2IL. - */ -public final class BppGameApplication extends Application { - - @Override - protected void attachBaseContext(Context base) { - super.attachBaseContext(base); - try { - BppJitTrace.install(base); - } catch (Throwable t) { - BppGameProcess.logEvent(base, "BppGameApplication.attachBaseContext BppJitTrace.install failed", t); - } - try { - BppGameProcess.start(base, "BppGameApplication.attachBaseContext"); - } catch (Throwable t) { - BppGameProcess.logEvent(base, "BppGameApplication.attachBaseContext start failed", t); - } - } - - @Override - public void onCreate() { - super.onCreate(); - try { - BppGameProcess.start(this, "BppGameApplication.onCreate"); - } catch (Throwable t) { - BppGameProcess.logEvent(this, "BppGameApplication.onCreate start failed", t); - } - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameProcess.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameProcess.java deleted file mode 100644 index 6314ae9..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameProcess.java +++ /dev/null @@ -1,1509 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Activity; -import android.app.ActivityManager; -import android.app.Application; -import android.content.ContentProvider; -import android.content.ContentValues; -import android.content.Context; -import android.content.ContextWrapper; -import android.content.Intent; -import android.database.Cursor; -import android.graphics.Color; -import android.graphics.PixelFormat; -import android.graphics.Typeface; -import android.graphics.drawable.GradientDrawable; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.IBinder; -import android.os.Looper; -import android.os.PowerManager; -import android.util.Log; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.Surface; -import android.view.SurfaceHolder; -import android.view.SurfaceView; -import android.view.View; -import android.view.ViewGroup; -import android.view.WindowManager; -import android.widget.FrameLayout; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.TextView; -import java.io.File; -import java.io.FileOutputStream; -import java.lang.ref.WeakReference; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.List; -import java.util.Map; - -/** - * Heartbeat, foreground hold, wake lock and the first-run progress card for {@code :game}. - */ -public final class BppGameProcess extends ContentProvider { - - private static final String TAG = "BppGame"; - private static final String LAUNCHER_PACKAGE = "com.bepinex.android"; - private static final String DIAG_DIR = BppDiagnosticSessionLog.DIR_NAME; - - private static final long HEARTBEAT_MS = 3000L; - private static final long STALL_MS = 20000L; - private static final long WAKE_LOCK_MS = 30L * 60L * 1000L; - private static final long POLL_INTERVAL_MS = 500L; - private static final long POLL_TIMEOUT_MS = 15L * 60L * 1000L; - private static final long SURFACE_STABLE_MS = 1500L; - private static final long FGS_RETRY_MS = 30000L; - private static final int INTEROP_BASELINE_CAP = 20000; - - private static volatile boolean pluginsReady; - private static volatile boolean started; - private static volatile boolean foregroundStarted; - private static volatile boolean lifecycleRegistered; - private static volatile boolean buildInfoLogged; - private static volatile boolean pollScheduled; - private static volatile boolean fgsNotNeededLogged; - private static volatile long pollStartedAt; - private static volatile long lastFgsAttemptAt; - private static volatile int overlayAttached; - private static volatile String overlayText = ""; - private static volatile String processName = ""; - private static volatile int interopBaseline; - private static volatile int lastInteropDllCount; - private static volatile Context originalContext; - private static volatile Context appContext; - - private static final Handler MAIN = new Handler(Looper.getMainLooper()); - private static WeakReference host = new WeakReference(null); - private static WeakReference keepScreenHost = new WeakReference(null); - private static WeakReference firstFrameSurface = new WeakReference(null); - private static long firstFrameValidSince; - private static View overlayView; - private static WindowManager overlayWm; - private static boolean overlayInWindow; - private static TextView bodyView; - private static PowerManager.WakeLock generationLock; - - private static final Application.ActivityLifecycleCallbacks LIFECYCLE = - new Application.ActivityLifecycleCallbacks() { - @Override - public void onActivityResumed(Activity activity) { - logEvent(contextFor(activity), "lifecycle resumed activity=" - + (activity == null ? "null" : activity.getClass().getName())); - considerAttach(activity, "lifecycle"); - } - - @Override - public void onActivityDestroyed(Activity activity) { - if (host.get() == activity) { - logEvent(contextFor(activity), "lifecycle destroyed host activity=" - + (activity == null ? "null" : activity.getClass().getName())); - detach("activity-destroyed"); - } - } - - @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {} - @Override public void onActivityStarted(Activity activity) {} - @Override public void onActivityPaused(Activity activity) {} - @Override public void onActivityStopped(Activity activity) {} - @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {} - }; - - private static final Runnable POLL = new Runnable() { - @Override - public void run() { - if (pluginsReady) { - pollScheduled = false; - return; - } - long now = System.currentTimeMillis(); - if (now - pollStartedAt > POLL_TIMEOUT_MS) { - pollScheduled = false; - logEvent(diagnosticsContext(null), "poll timeout after 15min host=" + hostName()); - return; - } - Activity activity = findResumedActivity(diagnosticsContext(null)); - if (activity != null) { - logEvent(contextFor(activity), "poll tick found activity=" - + activity.getClass().getName() + " host=" + hostName()); - if (isBppLauncherActivity(activity)) { - logEvent(contextFor(activity), "poll attach skipped BppLauncherActivity"); - } else { - attach(activity, "poll"); - checkFirstFrame(activity); - } - } - if (!pluginsReady) { - MAIN.postDelayed(this, POLL_INTERVAL_MS); - } else { - pollScheduled = false; - } - } - }; - - @Override - public boolean onCreate() { - Context context = getContext(); - if (context != null) { - try { - start(context, "BppGameProcess.ContentProvider.onCreate"); - } catch (Throwable t) { - logEvent(context, "BppGameProcess.ContentProvider.onCreate start failed", t); - } - } else { - Log.w(TAG, "BppGameProcess.ContentProvider.onCreate context=null"); - } - return true; - } - - public static void start(Context context) { - start(context, sourceFromStack()); - } - - /** Starts the overlay and heartbeat only when the caller is the real {@code :game} process. */ - public static void start(Context context, String source) { - try { - if (context == null) { - Log.w(TAG, "start called by " + source + " ignored reason=null context"); - return; - } - Context captured = captureOriginalContext(context); - Context diag = captured != null ? captured : context; - String process = currentProcessName(diag); - int pid = android.os.Process.myPid(); - logBuildInfoOnce(diag); - logEvent(diag, "start called by " + source - + " context=" + context.getClass().getName() - + " contextPkg=" + safePackage(context) - + " originalPkg=" + safePackage(captured) - + " process=" + process - + " pid=" + pid); - if (!isGameProcess(process)) { - logEvent(diag, "skipped process=" + process + " pid=" + pid + " source=" + source); - return; - } - tryRegisterLifecycle(context, source); - if (!markStarted()) { - logEvent(diag, "start already active process=" + process - + " pid=" + pid + " source=" + source); - return; - } - appContext = captured != null ? captured : context; - processName = process; - noteHook(appContext, "game-hook-started", processName); - try { - BppDiagnosticSessionLog.ensureCapture(stableContext(appContext), "game", pid); - } catch (Throwable t) { - logEvent(appContext, "ensureCapture failed process=" + process, t); - } - holdWakeLock(appContext); - startPoll(pid); - final Context heartbeatContext = appContext; - final long startedAt = System.currentTimeMillis(); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - heartbeat(heartbeatContext, startedAt, android.os.Process.myPid()); - } - }, "bpp-game-heartbeat"); - thread.setDaemon(true); - thread.start(); - logEvent(appContext, "heartbeat thread started pid=" + pid); - } catch (Throwable t) { - if (context != null) { - logEvent(context, "start failed source=" + source, t); - } else { - Log.w(TAG, "start failed source=" + source, t); - } - } - } - - public static void markPluginsReady() { - finishGeneration("markPluginsReady"); - } - - static void logEvent(Context context, String message) { - logEvent(context, message, null); - } - - static void logEvent(Context context, String message, Throwable t) { - String lineMessage = message; - if (t != null) { - Log.w(TAG, message, t); - lineMessage = message + " error=" + t.getClass().getName() + ": " + t.getMessage(); - } else { - Log.i(TAG, message); - } - Context diag = originalContext; - if (diag == null) diag = appContext; - if (diag == null) diag = context; - if (diag == null) return; - noteHook(diag, lineMessage, processName); - } - - private static boolean markStarted() { - synchronized (BppGameProcess.class) { - if (started) return false; - started = true; - return true; - } - } - - private static void finishGeneration(String reason) { - synchronized (BppGameProcess.class) { - if (pluginsReady) return; - pluginsReady = true; - } - Context context = diagnosticsContext(null); - logEvent(context, "generation finish reason=" + reason - + " process=" + processName + " pid=" + android.os.Process.myPid()); - MAIN.removeCallbacks(POLL); - pollScheduled = false; - MAIN.post(new Runnable() { - @Override - public void run() { - detach("remove: " + reason); - stopForegroundHold(reason); - releaseWakeLock(reason); - logEvent(diagnosticsContext(null), "removal complete reason=" + reason); - } - }); - writeReadyState(reason); - } - - private static void writeReadyState(String reason) { - Context context = diagnosticsContext(null); - if (context == null) return; - try { - File state = new File(diagnosticsDir(context), "generation-state.txt"); - writeAtomically( - state, - "stage=ready\nlabel=" - + BppDiagnosticBundle.generationStageLabel("ready") - + "\nreason=" + reason + "\n" - ); - } catch (Throwable t) { - Log.w(TAG, "write ready state failed reason=" + reason, t); - } - } - - private static void startPoll(int pid) { - synchronized (BppGameProcess.class) { - if (pollScheduled) return; - pollScheduled = true; - pollStartedAt = System.currentTimeMillis(); - } - logEvent(diagnosticsContext(null), "poll started pid=" + pid - + " intervalMs=" + POLL_INTERVAL_MS + " timeoutMs=" + POLL_TIMEOUT_MS); - MAIN.postDelayed(POLL, 0L); - } - - private static void tryRegisterLifecycle(Context context, String source) { - if (lifecycleRegistered) return; - Application application = findApplication(context); - if (application == null) { - logEvent(diagnosticsContext(context), "lifecycle register deferred reason=no Application" - + " context=" + context.getClass().getName() + " source=" + source); - return; - } - try { - synchronized (BppGameProcess.class) { - if (lifecycleRegistered) return; - application.registerActivityLifecycleCallbacks(LIFECYCLE); - lifecycleRegistered = true; - } - logEvent(diagnosticsContext(context), "lifecycle registered application=" - + application.getClass().getName() + " source=" + source); - } catch (Throwable t) { - logEvent(diagnosticsContext(context), "lifecycle register failed source=" + source, t); - } - } - - private static Application findApplication(Context context) { - if (context == null) return null; - if (context instanceof Application) return (Application) context; - try { - Context app = context.getApplicationContext(); - if (app instanceof Application) return (Application) app; - } catch (Throwable t) { - Log.w(TAG, "findApplication getApplicationContext failed", t); - } - Context original = originalContext; - if (original != null && original != context) { - if (original instanceof Application) return (Application) original; - try { - Context app = original.getApplicationContext(); - if (app instanceof Application) return (Application) app; - } catch (Throwable t) { - Log.w(TAG, "findApplication original getApplicationContext failed", t); - } - } - return null; - } - - private static void considerAttach(final Activity activity, final String method) { - if (activity == null || pluginsReady) return; - if (isBppLauncherActivity(activity)) { - logEvent(contextFor(activity), "attach skipped BppLauncherActivity method=" + method); - return; - } - MAIN.post(new Runnable() { - @Override - public void run() { - attach(activity, method); - } - }); - } - - private static void attach(Activity activity, String method) { - if (pluginsReady) return; - if (activity == null) { - logEvent(diagnosticsContext(null), "attach failed reason=null activity method=" + method); - return; - } - if (isBppLauncherActivity(activity)) { - logEvent(contextFor(activity), "attach skipped BppLauncherActivity method=" + method); - return; - } - if (activity.isFinishing() || activity.isDestroyed()) { - logEvent(contextFor(activity), "attach failed reason=activity finishing/destroyed" - + " activity=" + activity.getClass().getName() + " method=" + method); - return; - } - try { - View decor = activity.getWindow().getDecorView(); - sinkSurfaces(decor); - Activity current = host.get(); - if (overlayView != null - && current == activity - && overlayAttached == 1 - && overlayView.isAttachedToWindow()) { - refreshOverlay(); - ensureForeground(activity, method); - return; - } - if (current != null && current != activity) { - logEvent(contextFor(activity), "reattach host changed from=" - + current.getClass().getName() + " to=" + activity.getClass().getName() - + " method=" + method); - } - detachView("reattach-or-refresh"); - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - keepScreenHost = new WeakReference(activity); - FrameLayout root = buildOverlay(activity); - IBinder token = decor.getWindowToken(); - boolean added = false; - String used = null; - if (token != null) { - added = addPanel(activity, root, token); - if (added) { - used = "TYPE_APPLICATION_PANEL"; - } else { - logEvent(contextFor(activity), "attach panel failed, fallback to content" - + " activity=" + activity.getClass().getName() + " method=" + method); - } - } else { - logEvent(contextFor(activity), "attach panel skipped reason=null window token" - + " activity=" + activity.getClass().getName() + " method=" + method); - } - if (!added) { - added = addToContent(activity, root); - if (added) { - used = "content"; - } else { - logEvent(contextFor(activity), "attach failed reason=no window/content parent" - + " activity=" + activity.getClass().getName() + " method=" + method); - } - } - if (!added) { - clearKeepScreenOn("attach-failed"); - return; - } - overlayView = root; - host = new WeakReference(activity); - overlayAttached = 1; - refreshOverlay(); - ensureForeground(activity, method); - logEvent(contextFor(activity), "attach success activity=" - + activity.getClass().getName() + " method=" + method + " window=" + used); - } catch (Throwable t) { - logEvent(contextFor(activity), "attach failed by exception activity=" - + activity.getClass().getName() + " method=" + method, t); - clearKeepScreenOn("attach-exception"); - } - } - - /** Unity's SurfaceView is composited in its own window and can cover a normal dialog. */ - private static void sinkSurfaces(View view) { - if (view instanceof SurfaceView) { - SurfaceView surface = (SurfaceView) view; - try { - surface.setZOrderOnTop(false); - } catch (Throwable t) { - Log.w(TAG, "sinkSurfaces setZOrderOnTop failed", t); - } - try { - surface.setZOrderMediaOverlay(false); - } catch (Throwable t) { - Log.w(TAG, "sinkSurfaces setZOrderMediaOverlay failed", t); - } - } - if (view instanceof ViewGroup) { - ViewGroup group = (ViewGroup) view; - for (int i = 0; i < group.getChildCount(); i++) sinkSurfaces(group.getChildAt(i)); - } - } - - private static boolean addPanel(Activity activity, View root, IBinder token) { - try { - WindowManager manager = activity.getWindowManager(); - WindowManager.LayoutParams params = new WindowManager.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT, - WindowManager.LayoutParams.TYPE_APPLICATION_PANEL, - WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE - | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL - | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN - | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON - | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED - | WindowManager.LayoutParams.FLAG_FULLSCREEN, - PixelFormat.TRANSLUCENT - ); - params.token = token; - params.gravity = Gravity.TOP | Gravity.START; - if (Build.VERSION.SDK_INT >= 30) { - params.layoutInDisplayCutoutMode = - WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS; - } - manager.addView(root, params); - overlayWm = manager; - overlayInWindow = true; - return true; - } catch (Throwable t) { - Log.w(TAG, "addPanel failed activity=" + activity.getClass().getName(), t); - overlayWm = null; - overlayInWindow = false; - return false; - } - } - - private static boolean addToContent(Activity activity, View root) { - try { - View content = activity.findViewById(android.R.id.content); - ViewGroup parent; - if (content instanceof ViewGroup) parent = (ViewGroup) content; - else if (activity.getWindow().getDecorView() instanceof ViewGroup) { - parent = (ViewGroup) activity.getWindow().getDecorView(); - } else return false; - root.setElevation(10000f); - parent.addView(root, new ViewGroup.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT - )); - root.bringToFront(); - overlayWm = null; - overlayInWindow = false; - return true; - } catch (Throwable t) { - Log.w(TAG, "addToContent failed activity=" + activity.getClass().getName(), t); - return false; - } - } - - private static void ensureForeground(Activity activity, String method) { - if (foregroundStarted || pluginsReady) return; - long now = System.currentTimeMillis(); - if (now - lastFgsAttemptAt < FGS_RETRY_MS) return; - lastFgsAttemptAt = now; - Context starter = originalContext; - if (starter == null) starter = activity == null ? appContext : activity.getApplicationContext(); - if (starter == null && activity != null) starter = activity; - if (starter == null) { - logEvent(appContext, "FGS start skipped reason=no context method=" + method); - return; - } - if (!needsForegroundHold(starter)) { - if (!fgsNotNeededLogged) { - fgsNotNeededLogged = true; - logEvent(starter, "FGS not needed reason=interop dlls exist method=" + method); - } - return; - } - try { - Intent intent = new Intent(starter, BppGenerationForegroundService.class); - starter.startForegroundService(intent); - foregroundStarted = true; - logEvent(starter, "FGS start ok method=" + method - + " contextPkg=" + safePackage(starter)); - } catch (Throwable t) { - logEvent(starter, "FGS start exception method=" + method - + " contextPkg=" + safePackage(starter), t); - } - } - - private static boolean needsForegroundHold(Context context) { - try { - File interop = new File(gameRoot(context), "BepInEx/interop"); - File[] files = interop.listFiles(); - if (files == null) return true; - int dlls = 0; - for (int i = 0; i < files.length; i++) { - String name = files[i].getName().toLowerCase(java.util.Locale.ROOT); - if (name.endsWith(".dll")) dlls++; - } - return dlls <= 0; - } catch (Throwable t) { - logEvent(context, "needsForegroundHold failed", t); - return true; - } - } - - private static void stopForegroundHold(String reason) { - Context context = originalContext; - if (context == null) context = diagnosticsContext(null); - if (context == null) { - logEvent(appContext, "FGS stop skipped reason=no context removalReason=" + reason); - return; - } - try { - boolean stopped = context.stopService(new Intent(context, BppGenerationForegroundService.class)); - logEvent(context, "FGS stop requested reason=" + reason - + " started=" + (foregroundStarted ? 1 : 0) + " stopped=" + stopped); - } catch (Throwable t) { - logEvent(context, "FGS stop exception reason=" + reason, t); - } - foregroundStarted = false; - } - - private static void holdWakeLock(Context context) { - Context target = context != null ? context : diagnosticsContext(null); - if (target == null) { - logEvent(appContext, "wake lock acquire skipped reason=no context"); - return; - } - try { - if (generationLock != null && generationLock.isHeld()) { - logEvent(target, "wake lock already held tag=bpp:generation"); - return; - } - PowerManager manager = (PowerManager) target.getSystemService(Context.POWER_SERVICE); - if (manager == null) { - logEvent(target, "wake lock acquire failed reason=no PowerManager"); - return; - } - PowerManager.WakeLock lock = manager.newWakeLock( - PowerManager.PARTIAL_WAKE_LOCK, - "bpp:generation" - ); - lock.setReferenceCounted(false); - lock.acquire(WAKE_LOCK_MS); - generationLock = lock; - logEvent(target, "wake lock acquired tag=bpp:generation timeoutMs=" + WAKE_LOCK_MS); - } catch (Throwable t) { - logEvent(target, "wake lock acquire failed tag=bpp:generation", t); - } - } - - private static void releaseWakeLock(String reason) { - Context context = diagnosticsContext(null); - PowerManager.WakeLock lock = generationLock; - generationLock = null; - if (lock == null) { - logEvent(context, "wake lock release skipped reason=null removalReason=" + reason); - return; - } - try { - if (lock.isHeld()) lock.release(); - logEvent(context, "wake lock released reason=" + reason + " tag=bpp:generation"); - } catch (Throwable t) { - logEvent(context, "wake lock release failed reason=" + reason, t); - } - } - - private static FrameLayout buildOverlay(Activity activity) { - FrameLayout root = new FrameLayout(activity); - root.setClickable(true); - root.setBackgroundColor(Color.parseColor("#F0121418")); - FrameLayout.LayoutParams cardParams = new FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT, - Gravity.CENTER - ); - int side = dp(activity, 28); - cardParams.leftMargin = side; - cardParams.rightMargin = side; - root.addView(buildCard(activity), cardParams); - return root; - } - - private static LinearLayout buildCard(Activity activity) { - LinearLayout card = new LinearLayout(activity); - card.setOrientation(LinearLayout.VERTICAL); - int pad = dp(activity, 20); - card.setPadding(pad, pad, pad, pad); - GradientDrawable background = new GradientDrawable(); - background.setColor(Color.parseColor("#F0141418")); - background.setCornerRadius(dp(activity, 16)); - background.setStroke(dp(activity, 1), Color.parseColor("#E6C576")); - card.setBackground(background); - TextView title = new TextView(activity); - title.setTextColor(Color.parseColor("#F5E6C8")); - title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f); - title.setTypeface(Typeface.DEFAULT_BOLD); - title.setText("模组准备中"); - title.setGravity(Gravity.CENTER_HORIZONTAL); - card.addView(title); - bodyView = new TextView(activity); - bodyView.setGravity(Gravity.CENTER_HORIZONTAL); - bodyView.setTextColor(Color.parseColor("#F5E6C8")); - bodyView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f); - if (overlayText == null || overlayText.length() == 0) { - overlayText = "阶段:准备中\n已用时:00:00"; - } - bodyView.setText(overlayText); - LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - bodyParams.topMargin = dp(activity, 12); - card.addView(bodyView, bodyParams); - ProgressBar bar = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal); - bar.setIndeterminate(true); - LinearLayout.LayoutParams barParams = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - dp(activity, 8) - ); - barParams.topMargin = dp(activity, 14); - card.addView(bar, barParams); - return card; - } - - private static void refreshOverlay() { - TextView view = bodyView; - if (view == null) return; - view.setText(overlayText == null ? "" : overlayText); - } - - private static void detach(String reason) { - detachView(reason); - host = new WeakReference(null); - } - - private static void detachView(String reason) { - View view = overlayView; - WindowManager manager = overlayWm; - boolean inWindow = overlayInWindow; - overlayView = null; - overlayWm = null; - overlayInWindow = false; - overlayAttached = 0; - bodyView = null; - if (view != null) { - try { - if (inWindow && manager != null) manager.removeViewImmediate(view); - else if (view.getParent() instanceof ViewGroup) { - ((ViewGroup) view.getParent()).removeView(view); - } - logEvent(diagnosticsContext(null), "overlay removed reason=" + reason); - } catch (Throwable t) { - logEvent(diagnosticsContext(null), "overlay remove failed reason=" + reason, t); - } - } - clearKeepScreenOn(reason); - } - - private static void clearKeepScreenOn(String reason) { - Activity activity = keepScreenHost.get(); - keepScreenHost = new WeakReference(null); - if (activity == null) return; - try { - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - logEvent(contextFor(activity), "keep-screen-on cleared reason=" + reason - + " activity=" + activity.getClass().getName()); - } catch (Throwable t) { - logEvent(contextFor(activity), "clear keep-screen-on failed reason=" + reason, t); - } - } - - private static void checkFirstFrame(Activity activity) { - if (pluginsReady || activity == null || lastInteropDllCount <= 0) return; - try { - SurfaceView candidate = findValidSurface(activity.getWindow().getDecorView()); - long now = System.currentTimeMillis(); - SurfaceView previous = firstFrameSurface.get(); - if (candidate == null) { - if (previous != null) { - firstFrameSurface = new WeakReference(null); - firstFrameValidSince = 0L; - } - return; - } - if (candidate != previous) { - firstFrameSurface = new WeakReference(candidate); - firstFrameValidSince = now; - logEvent(contextFor(activity), "first-frame candidate surface=" - + candidate.getClass().getName() - + " size=" + candidate.getWidth() + "x" + candidate.getHeight() - + " interopDlls=" + lastInteropDllCount); - return; - } - if (firstFrameValidSince == 0L) firstFrameValidSince = now; - if (now - firstFrameValidSince >= SURFACE_STABLE_MS) { - logEvent(contextFor(activity), "unity first frame detected size=" - + candidate.getWidth() + "x" + candidate.getHeight() - + " stableMs=" + (now - firstFrameValidSince) - + " interopDlls=" + lastInteropDllCount); - finishGeneration("unity-first-frame"); - } - } catch (Throwable t) { - logEvent(contextFor(activity), "first-frame check failed", t); - } - } - - private static SurfaceView findValidSurface(View view) { - if (view == null) return null; - if (view instanceof SurfaceView) { - SurfaceView surfaceView = (SurfaceView) view; - try { - if (!surfaceView.isShown()) return null; - if (surfaceView.getWidth() <= 0 || surfaceView.getHeight() <= 0) return null; - SurfaceHolder holder = surfaceView.getHolder(); - if (holder == null) return null; - Surface surface = holder.getSurface(); - if (surface != null && surface.isValid()) return surfaceView; - } catch (Throwable t) { - Log.w(TAG, "findValidSurface failed view=" - + surfaceView.getClass().getName(), t); - } - return null; - } - if (view instanceof ViewGroup) { - ViewGroup group = (ViewGroup) view; - for (int i = 0; i < group.getChildCount(); i++) { - SurfaceView found = findValidSurface(group.getChildAt(i)); - if (found != null) return found; - } - } - return null; - } - - private static Activity findResumedActivity(Context diag) { - try { - Class clazz = Class.forName("android.app.ActivityThread"); - Method current = clazz.getDeclaredMethod("currentActivityThread"); - current.setAccessible(true); - Object thread = current.invoke(null); - if (thread == null) return null; - Field field = clazz.getDeclaredField("mActivities"); - field.setAccessible(true); - Object value = field.get(thread); - if (!(value instanceof Map)) { - logEvent(diag, "poll mActivities unexpected type=" - + (value == null ? "null" : value.getClass().getName())); - return null; - } - Map activities = (Map) value; - for (Object record : activities.values()) { - if (record == null) continue; - Field activityField = findField(record.getClass(), "activity"); - if (activityField == null) { - logEvent(diag, "poll record missing activity field class=" - + record.getClass().getName()); - continue; - } - Object activityObject = activityField.get(record); - if (!(activityObject instanceof Activity)) continue; - Activity activity = (Activity) activityObject; - if (activity.isFinishing() || activity.isDestroyed()) continue; - Field pausedField = findField(record.getClass(), "paused"); - if (pausedField == null) { - logEvent(diag, "poll record missing paused field class=" - + record.getClass().getName()); - continue; - } - Object pausedObject = pausedField.get(record); - boolean paused = pausedObject instanceof Boolean - && ((Boolean) pausedObject).booleanValue(); - if (!paused) return activity; - } - } catch (Throwable t) { - logEvent(diag, "poll findResumedActivity failed", t); - } - return null; - } - - private static Field findField(Class type, String name) { - Class current = type; - while (current != null) { - try { - Field field = current.getDeclaredField(name); - field.setAccessible(true); - return field; - } catch (NoSuchFieldException ex) { - current = current.getSuperclass(); - } - } - return null; - } - - private static void heartbeat(Context context, long startedAt, int pid) { - File gameRoot = gameRoot(context); - int interopAtStart = BppDiagnosticBundle.summarizeTree( - new File(gameRoot, "BepInEx/interop"), ".dll", 2).files; - File logOutput = new File(gameRoot, "BepInEx/LogOutput.log"); - long logAtStart = logOutput.isFile() ? logOutput.length() : -1L; - long logMtimeAtStart = logOutput.isFile() ? logOutput.lastModified() : 0L; - int baseline = readBaseline(context); - interopBaseline = baseline; - String lastStage = ""; - long lastAdvanceAt = startedAt; - long lastCpu = -1L; - long lastCpuAt = startedAt; - boolean dumpedStall = false; - logEvent(context, "heartbeat loop started pid=" + pid); - while (!pluginsReady) { - try { - long now = System.currentTimeMillis(); - long elapsed = Math.max(0L, (now - startedAt) / 1000L); - BppDiagnosticBundle.GenerationProbe probe = new BppDiagnosticBundle.GenerationProbe(); - probe.interopFilesAtStart = interopAtStart; - File unityLibs = new File(gameRoot, "BepInEx/unity-libs"); - BppDiagnosticBundle.DirStat unity = BppDiagnosticBundle.summarizeTree( - unityLibs, null, 1); - probe.unityLibFiles = unity.files; - File[] zips = unityLibs.listFiles(); - if (zips != null) { - for (int i = 0; i < zips.length; i++) { - String name = zips[i].getName().toLowerCase(java.util.Locale.ROOT); - if (name.endsWith(".zip")) probe.unityZipBytes += zips[i].length(); - } - } - BppDiagnosticBundle.DirStat interop = BppDiagnosticBundle.summarizeTree( - new File(gameRoot, "BepInEx/interop"), ".dll", 2); - probe.interopFiles = interop.files; - probe.interopBytes = interop.bytes; - probe.dummyFiles = BppDiagnosticBundle.summarizeTree( - new File(gameRoot, "BepInEx/dummy"), null, 2).files; - boolean logNew = logOutput.isFile() - && (logOutput.lastModified() > logMtimeAtStart - || logOutput.length() != logAtStart); - probe.logIsNew = logNew; - probe.logOutputBytes = logNew ? logOutput.length() : 0L; - String stage = BppDiagnosticBundle.generationStageId(probe); - String label = BppDiagnosticBundle.generationStageLabel(stage); - lastInteropDllCount = probe.interopFiles; - if (!stage.equals(lastStage)) { - logEvent(context, "stage change from=" + lastStage + " to=" + stage - + " label=" + label + " elapsedSec=" + elapsed); - lastStage = stage; - lastAdvanceAt = now; - dumpedStall = false; - } - long cpu = cpuTicks(); - if (lastCpu >= 0 && cpu > lastCpu + 1) { - lastCpuAt = now; - dumpedStall = false; - } - lastCpu = cpu; - int importance = importance(context, pid); - long rss = vmRssKb(); - int percent = BppDiagnosticBundle.generationPercent(probe, baseline); - String line = BppDiagnosticBundle.nowIso() - + " event=heartbeat" - + " stage=" + stage - + " elapsedSec=" + elapsed - + " interopFiles=" + probe.interopFiles - + " interopBytes=" + probe.interopBytes - + " unityLibFiles=" + probe.unityLibFiles - + " unityZipBytes=" + probe.unityZipBytes - + " dummyFiles=" + probe.dummyFiles - + " logOutputBytes=" + probe.logOutputBytes - + " rssKb=" + rss - + " cpuTicks=" + cpu - + " importance=" + importance - + " importanceName=" + BppDiagnosticBundle.importanceName(importance) - + " pid=" + pid - + " process=" + processName - + " overlay=" + overlayAttached - + " foreground=" + (foregroundStarted ? 1 : 0) - + " percent=" + percent; - publish(context, gameRoot, probe, stage, label, elapsed, percent, rss, importance, line); - patchConfigs(context, gameRoot); - boolean stalled = now - lastAdvanceAt >= STALL_MS && now - lastCpuAt >= STALL_MS; - if (stalled && !dumpedStall && !"ready".equals(stage)) { - dumpedStall = true; - dumpStacks(context, stage, elapsed); - } - if (logNew && logMentionsPlugins(logOutput)) { - logEvent(context, "generation finish detected LogOutput.log" - + " bytes=" + logOutput.length() + " stage=" + stage); - finishGeneration("LogOutput.log chainloader"); - break; - } - if (generationFinishedByStage(stage, probe)) { - logEvent(context, "generation finish detected stage=" + stage - + " interopFiles=" + probe.interopFiles); - finishGeneration("stage=" + stage); - break; - } - if (probe.interopFiles > baseline) { - baseline = probe.interopFiles; - interopBaseline = baseline; - writeBaseline(context, baseline); - } - } catch (Throwable t) { - logEvent(context, "heartbeat tick failed", t); - } - try { - Thread.sleep(HEARTBEAT_MS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - logEvent(context, "heartbeat interrupted pid=" + pid); - return; - } - } - logEvent(context, "heartbeat loop ended pid=" + pid); - } - - private static boolean generationFinishedByStage( - String stage, - BppDiagnosticBundle.GenerationProbe probe - ) { - if ("ready".equals(stage) || "complete".equals(stage) || "finished".equals(stage)) { - return true; - } - return "plugins".equals(stage) && probe.interopFiles > 0; - } - - private static void publish( - Context context, - File gameRoot, - BppDiagnosticBundle.GenerationProbe probe, - String stage, - String label, - long elapsed, - int percent, - long rss, - int importance, - String line - ) { - boolean firstRun = probe.interopFilesAtStart <= 0 && probe.interopFiles == 0 - || (probe.interopFilesAtStart <= 0 - && !"plugins".equals(stage) - && !"ready".equals(stage)); - StringBuilder card = new StringBuilder(); - if (probe.interopFilesAtStart <= 0 && probe.interopFiles == 0) { - card.append(BppDiagnosticBundle.FIRST_RUN_OVERLAY_TEXT).append("\n\n"); - } else { - card.append("正在加载模组,请保持在前台,不要切走\n\n"); - } - card.append("阶段:").append(label).append('\n'); - card.append("已用时:").append(formatElapsed(elapsed)).append('\n'); - if (percent >= 0) card.append("进度:").append(percent).append("%\n"); - else card.append("进度:这一步暂时数不出百分比\n"); - card.append("Unity 基础库:").append(probe.unityLibFiles).append(" 个文件"); - if (probe.unityZipBytes > 0) { - card.append(",压缩包 ").append(megabytes(probe.unityZipBytes)); - } - card.append('\n'); - card.append("interop:").append(probe.interopFiles).append(" 个文件,") - .append(megabytes(probe.interopBytes)).append('\n'); - if (probe.dummyFiles > 0) { - card.append("Cpp2IL 临时文件:").append(probe.dummyFiles).append(" 个\n"); - } - card.append("内存 RSS:").append(rss < 0 ? "未知" : megabytes(rss * 1024L)).append('\n'); - if ("cpp2il".equals(stage)) { - card.append("\n分析游戏代码时几分钟内不会写出新文件,灰色画面是正常的。"); - } - if (importance >= 400) { - card.append("\n游戏已经不在前台,系统可能因内存不足把它关掉。请切回这个画面。"); - } - overlayText = card.toString(); - MAIN.post(new Runnable() { - @Override - public void run() { - refreshOverlay(); - } - }); - try { - File dir = diagnosticsDir(context); - BppDiagnosticBundle.appendCapped( - new File(dir, "game-heartbeat.log"), line, 1024 * 1024); - StringBuilder state = new StringBuilder(); - state.append("stage=").append(stage).append('\n'); - state.append("label=").append(label).append('\n'); - state.append("elapsedSec=").append(elapsed).append('\n'); - state.append("interopFiles=").append(probe.interopFiles).append('\n'); - state.append("interopBytes=").append(probe.interopBytes).append('\n'); - state.append("unityLibFiles=").append(probe.unityLibFiles).append('\n'); - state.append("importance=").append(importance).append('\n'); - state.append("firstRun=").append(firstRun).append('\n'); - state.append("process=").append(processName).append('\n'); - state.append("pid=").append(android.os.Process.myPid()).append('\n'); - state.append("overlay=").append(overlayAttached).append('\n'); - state.append("foreground=").append(foregroundStarted ? 1 : 0).append('\n'); - writeAtomically(new File(dir, "generation-state.txt"), state.toString()); - File external = context.getExternalFilesDir(null); - if (external != null) { - BppDiagnosticBundle.appendIfRoom( - new File(external, "bepinex_trace.log"), - "[bpp-diag] " + line, - 2 * 1024 * 1024 - ); - } - BppDiagnosticBundle.appendIfRoom( - new File(gameRoot, "BepInEx/logs/bpp-startup-trace.log"), - "[bpp-diag] " + line, - 2 * 1024 * 1024 - ); - } catch (Throwable t) { - logEvent(context, "publish diagnostics failed stage=" + stage, t); - } - } - - private static void patchConfigs(Context context, File gameRoot) { - patchOne(context, new File(gameRoot, "BepInEx/config/BepInEx.cfg")); - patchOne(context, new File(gameRoot, "modpacks/bpp/config/BepInEx.cfg")); - } - - private static void patchOne(Context context, File cfg) { - try { - if (cfg == null || !cfg.isFile() || !cfg.canRead()) return; - byte[] raw = Files.readAllBytes(cfg.toPath()); - if (raw.length > 1024 * 1024) return; - String text = new String(raw, StandardCharsets.UTF_8); - String updated = BppDiagnosticBundle.enableDiagnosticLogging(text); - if (updated.equals(text)) return; - writeAtomically(cfg, updated); - } catch (Throwable t) { - logEvent(context, "patch config failed file=" + (cfg == null ? "null" : cfg.getAbsolutePath()), t); - } - } - - private static boolean logMentionsPlugins(File log) { - try { - if (log == null || !log.isFile()) return false; - long length = log.length(); - int take = (int) Math.min(length, 64 * 1024L); - byte[] data = new byte[take]; - try (java.io.RandomAccessFile raf = new java.io.RandomAccessFile(log, "r")) { - raf.seek(Math.max(0L, length - take)); - raf.readFully(data); - } - String tail = new String(data, StandardCharsets.UTF_8); - return tail.contains("Chainloader startup complete") - || tail.contains("Chainloader started") - || tail.contains("plugin.initialization.succeeded") - || tail.contains("Finished loading plugins"); - } catch (Throwable t) { - Log.w(TAG, "logMentionsPlugins failed", t); - return false; - } - } - - private static void dumpStacks(Context context, String stage, long elapsed) { - try { - StringBuilder sb = new StringBuilder(); - sb.append(BppDiagnosticBundle.nowIso()) - .append(" event=stall stage=").append(stage) - .append(" elapsedSec=").append(elapsed).append('\n'); - sb.append(readSmall(new File("/proc/self/status"), 4000)).append('\n'); - File task = new File("/proc/self/task"); - String[] ids = task.list(); - if (ids == null) { - sb.append("task=unreadable\n"); - } else { - int shown = 0; - for (int i = 0; i < ids.length && shown < 80; i++) { - File dir = new File(task, ids[i]); - sb.append("=== tid ").append(ids[i]) - .append(" comm=").append(oneLine(readSmall(new File(dir, "comm"), 80))) - .append(" wchan=").append(oneLine(readSmall(new File(dir, "wchan"), 120))) - .append('\n'); - sb.append(readSmall(new File(dir, "stack"), 1500)).append('\n'); - shown++; - } - } - Map traces = Thread.getAllStackTraces(); - for (Map.Entry entry : traces.entrySet()) { - Thread thread = entry.getKey(); - sb.append("--- java ").append(thread.getName()) - .append(" state=").append(thread.getState()) - .append(" daemon=").append(thread.isDaemon()).append('\n'); - StackTraceElement[] frames = entry.getValue(); - int limit = Math.min(frames.length, 40); - for (int i = 0; i < limit; i++) sb.append(" at ").append(frames[i]).append('\n'); - } - File dir = diagnosticsDir(context); - String name = "stacks-" + elapsed + "s.log"; - BppDiagnosticBundle.appendCapped(new File(dir, name), sb.toString(), 1024 * 1024); - } catch (Throwable t) { - logEvent(context, "dumpStacks failed stage=" + stage, t); - } - } - - static File gameRoot(Context context) { - try { - Class paths = Class.forName("com.bepinex.android.BepInExPaths"); - Object instance = paths.getField("INSTANCE").get(null); - Object dir = paths.getMethod("getGameRootDir", String.class) - .invoke(instance, BppBundledModpackInstaller.TARGET_PACKAGE); - if (dir instanceof File) return (File) dir; - } catch (Throwable t) { - Log.w(TAG, "gameRoot BepInExPaths reflection failed", t); - } - Context target = originalContext != null ? originalContext : context; - File external = target.getExternalFilesDir(null); - if (external == null) external = target.getFilesDir(); - return new File(external, "BepInEx_Android/" + BppBundledModpackInstaller.TARGET_PACKAGE); - } - - private static int importance(Context context, int pid) { - try { - ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); - if (manager == null) return -1; - List processes = manager.getRunningAppProcesses(); - if (processes == null) return -1; - for (int i = 0; i < processes.size(); i++) { - ActivityManager.RunningAppProcessInfo info = processes.get(i); - if (info != null && info.pid == pid) return info.importance; - } - } catch (Throwable t) { - Log.w(TAG, "importance failed pid=" + pid, t); - } - return -1; - } - - private static long cpuTicks() { - try { - String stat = readSmall(new File("/proc/self/stat"), 2000); - int paren = stat.lastIndexOf(')'); - if (paren < 0 || paren + 2 >= stat.length()) return -1L; - String[] parts = stat.substring(paren + 2).trim().split("\\s+"); - if (parts.length < 13) return -1L; - return Long.parseLong(parts[11]) + Long.parseLong(parts[12]); - } catch (RuntimeException ex) { - Log.w(TAG, "cpuTicks failed", ex); - return -1L; - } - } - - private static long vmRssKb() { - try { - String status = readSmall(new File("/proc/self/status"), 4000); - String[] lines = status.split("\n"); - for (int i = 0; i < lines.length; i++) { - if (lines[i].startsWith("VmRSS:")) { - String digits = lines[i].replaceAll("[^0-9]", ""); - if (digits.length() == 0) return -1L; - return Long.parseLong(digits); - } - } - } catch (RuntimeException ex) { - Log.w(TAG, "vmRssKb failed", ex); - return -1L; - } - return -1L; - } - - private static int readBaseline(Context context) { - try { - File file = new File(diagnosticsDir(context), "interop-baseline.txt"); - if (!file.isFile()) return 0; - String text = readSmall(file, 40).trim(); - int value = Integer.parseInt(text); - if (value < 0 || value > INTEROP_BASELINE_CAP) return 0; - return value; - } catch (RuntimeException ex) { - Log.w(TAG, "readBaseline failed", ex); - return 0; - } - } - - private static void writeBaseline(Context context, int files) { - try { - writeAtomically( - new File(diagnosticsDir(context), "interop-baseline.txt"), - Integer.toString(files) - ); - } catch (Throwable t) { - logEvent(context, "write baseline failed files=" + files, t); - } - } - - private static void writeAtomically(File file, String text) throws java.io.IOException { - File parent = file.getParentFile(); - if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { - throw new java.io.IOException("cannot create " + parent); - } - File tmp = new File(file.getAbsolutePath() + ".tmp"); - try (FileOutputStream out = new FileOutputStream(tmp)) { - out.write(text.getBytes(StandardCharsets.UTF_8)); - out.flush(); - out.getFD().sync(); - } - if (!tmp.renameTo(file)) { - try (FileOutputStream out = new FileOutputStream(file)) { - out.write(text.getBytes(StandardCharsets.UTF_8)); - out.flush(); - } - tmp.delete(); - } - } - - private static String readSmall(File file, int maxBytes) { - try { - if (file == null || !file.isFile() || !file.canRead()) return ""; - byte[] data = Files.readAllBytes(file.toPath()); - if (data.length > maxBytes) { - return new String(data, data.length - maxBytes, maxBytes, StandardCharsets.UTF_8); - } - return new String(data, StandardCharsets.UTF_8); - } catch (Exception ex) { - Log.w(TAG, "readSmall failed file=" + file, ex); - return ""; - } - } - - private static String oneLine(String value) { - return value == null ? "" : value.replace('\n', ' ').replace('\r', ' ').trim(); - } - - private static String formatElapsed(long seconds) { - long minutes = seconds / 60L; - long rest = seconds % 60L; - String sec = rest < 10 ? "0" + rest : Long.toString(rest); - return minutes + ":" + sec; - } - - private static String megabytes(long bytes) { - if (bytes < 0) return "未知"; - return (bytes / (1024L * 1024L)) + " MB"; - } - - private static int dp(Context context, int value) { - return Math.round(TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics())); - } - - private static void logBuildInfoOnce(Context context) { - synchronized (BppGameProcess.class) { - if (buildInfoLogged) return; - buildInfoLogged = true; - } - String line = BppBuildInfo.describe(); - Log.i(TAG, line); - noteHookRaw(context, line); - } - - private static void logBuildInfoLine(Context context, String line) { - Log.i(TAG, line); - noteHookRaw(context, line); - } - - private static void noteHook(Context context, String event, String process) { - try { - String line = BppDiagnosticBundle.nowIso() - + " event=" + oneLine(event) - + " process=" + (process == null ? "" : process) - + " pid=" + android.os.Process.myPid(); - File dir = diagnosticsDir(context); - BppDiagnosticBundle.appendCapped( - new File(dir, "hook-process.txt"), line, 64 * 1024); - } catch (Throwable t) { - Log.w(TAG, "noteHook failed event=" + event, t); - } - } - - private static void noteHookRaw(Context context, String line) { - try { - File dir = diagnosticsDir(context); - BppDiagnosticBundle.appendCapped( - new File(dir, "hook-process.txt"), line, 64 * 1024); - } catch (Throwable t) { - Log.w(TAG, "noteHookRaw failed", t); - } - } - - static File diagnosticsDir(Context context) { - Context base = originalContext != null ? originalContext : context; - File resolved = null; - if (base != null) { - try { - resolved = BppDiagnosticSessionLog.diagnosticsDir(stableContext(base)); - } catch (Throwable t) { - Log.w(TAG, "BppDiagnosticSessionLog.diagnosticsDir failed", t); - } - } - if (resolved != null && isUnderLauncherData(resolved)) return resolved; - Context original = originalContext; - if (original == null && context != null && isLauncherContext(context)) original = context; - if (original != null) { - try { - String dataDir = original.getApplicationInfo().dataDir; - if (dataDir != null && isLauncherDataDir(dataDir)) { - return new File(dataDir, "files/" + DIAG_DIR); - } - } catch (Throwable t) { - Log.w(TAG, "diagnosticsDir fallback dataDir failed", t); - } - } - return new File("/data/user/0/" + LAUNCHER_PACKAGE + "/files/" + DIAG_DIR); - } - - private static Context stableContext(final Context context) { - if (context == null) return null; - return new ContextWrapper(context) { - @Override - public Context getApplicationContext() { - return this; - } - }; - } - - private static Context captureOriginalContext(Context context) { - synchronized (BppGameProcess.class) { - if (originalContext != null) return originalContext; - if (context == null) return null; - if (isLauncherContext(context)) { - originalContext = context; - return originalContext; - } - try { - Context app = context.getApplicationContext(); - if (app != null && app != context && isLauncherContext(app)) { - originalContext = app; - return originalContext; - } - } catch (Throwable t) { - Log.w(TAG, "captureOriginalContext getApplicationContext failed", t); - } - return null; - } - } - - private static boolean isLauncherContext(Context context) { - if (context == null) return false; - try { - if (LAUNCHER_PACKAGE.equals(context.getPackageName())) return true; - } catch (Throwable t) { - Log.w(TAG, "isLauncherContext getPackageName failed", t); - } - try { - android.content.pm.ApplicationInfo info = context.getApplicationInfo(); - if (info != null) { - if (LAUNCHER_PACKAGE.equals(info.packageName)) return true; - if (info.dataDir != null && isLauncherDataDir(info.dataDir)) return true; - } - } catch (Throwable t) { - Log.w(TAG, "isLauncherContext getApplicationInfo failed", t); - } - return false; - } - - private static boolean isLauncherDataDir(String path) { - if (path == null) return false; - return path.startsWith("/data/user/") && path.endsWith("/" + LAUNCHER_PACKAGE) - || path.equals("/data/data/" + LAUNCHER_PACKAGE); - } - - private static boolean isUnderLauncherData(File file) { - if (file == null) return false; - String path = file.getAbsolutePath(); - return path.startsWith("/data/user/") - && path.indexOf("/" + LAUNCHER_PACKAGE + "/") >= 0 - || path.startsWith("/data/data/" + LAUNCHER_PACKAGE + "/") - || path.equals("/data/data/" + LAUNCHER_PACKAGE); - } - - private static String currentProcessName(Context context) { - try { - String process = Application.getProcessName(); - if (process != null && process.length() > 0) return process; - } catch (Throwable t) { - Log.w(TAG, "currentProcessName getProcessName failed", t); - } - try { - byte[] data = Files.readAllBytes(new File("/proc/self/cmdline").toPath()); - int end = 0; - while (end < data.length && data[end] != 0) end++; - if (end > 0) return new String(data, 0, end, StandardCharsets.UTF_8); - } catch (Throwable t) { - Log.w(TAG, "currentProcessName read /proc/self/cmdline failed", t); - } - try { - return context == null ? "" : context.getPackageName(); - } catch (Throwable t) { - Log.w(TAG, "currentProcessName getPackageName failed", t); - return ""; - } - } - - private static boolean isGameProcess(String process) { - return process != null && process.endsWith(":game"); - } - - private static boolean isBppLauncherActivity(Activity activity) { - return activity != null - && activity.getClass().getName().indexOf("BppLauncherActivity") >= 0; - } - - private static String sourceFromStack() { - StackTraceElement[] elements = new Throwable().getStackTrace(); - for (int i = 1; i < elements.length; i++) { - String cls = elements[i].getClassName(); - if (cls.equals(BppGameProcess.class.getName())) continue; - return cls + "." + elements[i].getMethodName(); - } - return "unknown"; - } - - private static Context diagnosticsContext(Context fallback) { - Context context = originalContext; - if (context != null) return context; - context = appContext; - if (context != null) return context; - return fallback; - } - - private static Context contextFor(Activity activity) { - Context context = originalContext; - if (context != null) return context; - if (activity != null) { - try { - Context app = activity.getApplicationContext(); - if (app != null) return app; - } catch (Throwable t) { - Log.w(TAG, "contextFor getApplicationContext failed", t); - } - return activity; - } - return appContext; - } - - private static String safePackage(Context context) { - if (context == null) return "null"; - try { - return context.getPackageName(); - } catch (Throwable t) { - Log.w(TAG, "safePackage failed", t); - return "?"; - } - } - - private static String hostName() { - Activity activity = host.get(); - return activity == null ? "null" : activity.getClass().getName(); - } - - @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; } - @Override public String getType(Uri uri) { return null; } - @Override public Uri insert(Uri uri, ContentValues values) { return null; } - @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } - @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameWindow.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameWindow.java deleted file mode 100644 index 8b081fc..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGameWindow.java +++ /dev/null @@ -1,248 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Activity; -import android.content.pm.ActivityInfo; -import android.os.Build; -import android.os.Handler; -import android.os.Looper; -import android.os.SystemClock; -import android.util.Log; -import android.view.View; -import android.view.Window; -import android.view.WindowInsets; -import android.view.WindowInsetsController; -import android.view.WindowManager; -import android.view.ViewTreeObserver; -import java.lang.ref.WeakReference; -import java.util.HashSet; -import java.util.Set; - -/** Host-loaded window adapter, independent of the cloned game's Java classes and loader. */ -public final class BppGameWindow { - private static final String TAG = "BppGameWindow"; - private static final String LAUNCHER = "com.bepinex.android.bpp.BppLauncherActivity"; - private static final Handler MAIN = new Handler(Looper.getMainLooper()); - private static final int IMMERSIVE_FLAGS = View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; - - // Reset cancels queued Activity captures and cannot race an in-flight UI-thread request. - private static Object generation = new Object(); - private static WeakReference loggedActivity = new WeakReference<>(null); - private static final Set loggedFailures = new HashSet<>(); - private static WindowBinding binding; - - private BppGameWindow() {} - - /** True means queued, not that the requested fullscreen geometry has been observed. */ - public static synchronized boolean apply(final Activity activity) { - if (activity == null) return false; - final Object token = generation; - return MAIN.postAtTime(new Runnable() { - @Override public void run() { - synchronized (BppGameWindow.class) { - if (generation != token) return; - try { - if (!isGameTarget(activity)) return; - applyOrientation(activity); - ensureDiagnosticCapture(activity); - Window window = activity.getWindow(); - if (window == null) return; - View decor = window.getDecorView(); - // The managed cadence retries after the decor attaches. - if (decor == null || !decor.isAttachedToWindow()) return; - // The managed heartbeat only discovers/rebinds activities. Repeated hide() - // and requestApplyInsets() fight transient swipe bars and resize Unity. - if (binding == null || !binding.matches(activity, decor)) { - if (binding != null) binding.release(); - applyWindow(window, decor); - binding = new WindowBinding(activity, decor, token); - } else if (activity.hasWindowFocus() - && (decor.getSystemUiVisibility() & IMMERSIVE_FLAGS) != IMMERSIVE_FLAGS) { - // Unity's player can replace legacy flags after startup/focus. Repair - // requested policy only; sticky transient bars do not clear these bits. - applyWindow(window, decor); - } - if (loggedActivity.get() != activity) { - loggedActivity = new WeakReference<>(activity); - Log.i(TAG, "Window request executed on Android UI thread; activity=" - + activity.getClass().getName()); - } - } catch (RuntimeException error) { - reportFailure("apply", error); - } - } - } - }, token, SystemClock.uptimeMillis()); - } - - /** Releases queued work without mutating any window during teardown. */ - public static synchronized void reset() { - MAIN.removeCallbacksAndMessages(generation); - generation = new Object(); - loggedActivity.clear(); - loggedFailures.clear(); - final WindowBinding previous = binding; - binding = null; - if (previous != null) MAIN.post(previous::release); - } - - private static boolean diagnosticCaptureStarted; - - /** Loads the exporter only when this process is the real game. Tests do not ship that class. */ - private static void ensureDiagnosticCapture(Activity activity) { - if (diagnosticCaptureStarted || activity == null) return; - diagnosticCaptureStarted = true; - try { - Class logClass = Class.forName("com.bepinex.android.bpp.BppDiagnosticSessionLog"); - Class contextClass = Class.forName("android.content.Context"); - logClass.getMethod("ensureCapture", contextClass, String.class).invoke(null, activity, "game"); - } catch (Throwable ignored) { - } - try { - Class.forName("com.bepinex.android.bpp.BppGameProcess") - .getMethod("markPluginsReady") - .invoke(null); - } catch (Throwable ignored) { - } - } - - private static final class WindowBinding implements ViewTreeObserver.OnWindowFocusChangeListener { - private final WeakReference activity; - private final WeakReference decor; - private final Object token; - - WindowBinding(Activity activity, View decor, Object token) { - this.activity = new WeakReference<>(activity); - this.decor = new WeakReference<>(decor); - this.token = token; - decor.getViewTreeObserver().addOnWindowFocusChangeListener(this); - } - - boolean matches(Activity candidate, View view) { - return activity.get() == candidate && decor.get() == view; - } - - @Override public void onWindowFocusChanged(boolean focused) { - if (!focused) return; - // Unity's own focus callback runs in this same dispatch and may show bars again. - // Apply after that dispatch, rather than winning briefly and then being overwritten. - MAIN.postAtTime(this::restoreAfterFocus, token, SystemClock.uptimeMillis()); - } - - private void restoreAfterFocus() { - synchronized (BppGameWindow.class) { - Activity target = activity.get(); - View view = decor.get(); - if (generation != token || binding != this || !isGameTarget(target) - || !target.hasWindowFocus() || view == null || !view.isAttachedToWindow()) return; - try { - // Notification shade/app switches restore immersion on return. A transient - // swipe does not lose focus: Android alone times out those overlay bars. - applyOrientation(target); - applyWindow(target.getWindow(), view); - if (Build.VERSION.SDK_INT < 30) view.setSystemUiVisibility(IMMERSIVE_FLAGS); - } catch (RuntimeException error) { - reportFailure("focus", error); - } - } - } - - void release() { - View view = decor.get(); - if (view != null) { - if (view.getViewTreeObserver().isAlive()) - view.getViewTreeObserver().removeOnWindowFocusChangeListener(this); - } - activity.clear(); - decor.clear(); - } - } - - private static boolean isGameTarget(Activity activity) { - try { - if (activity == null || activity.isFinishing() || activity.isDestroyed()) return false; - // Check runtime types: the game Activity may be cloned behind StubActivity. - // Reject launcher subclasses too, without loading a launcher type in the game loader. - for (Class type = activity.getClass(); type != null; type = type.getSuperclass()) { - String name = type.getName(); - if (name == null || name.length() == 0 || LAUNCHER.equals(name)) return false; - } - return true; - } catch (RuntimeException error) { - reportFailure("target_identity", error); - return false; - } - } - - private static void applyOrientation(Activity activity) { - try { - // The fused host copies the game's fixed landscape request at launch. Allow both - // landscape sides; the existing heartbeat also repairs later Unity overrides. - if (activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) - activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); - } catch (RuntimeException error) { - reportFailure("orientation", error); - } - } - - @SuppressWarnings("deprecation") - private static void applyWindow(Window window, View decor) { - // Cutout rejection must not prevent the independent immersive request. - if (Build.VERSION.SDK_INT >= 28) { - try { - WindowManager.LayoutParams attributes = window.getAttributes(); - int mode = Build.VERSION.SDK_INT >= 30 - ? WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS - : WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; - if (attributes.layoutInDisplayCutoutMode != mode) { - attributes.layoutInDisplayCutoutMode = mode; - window.setAttributes(attributes); - } - } catch (RuntimeException error) { - reportFailure("cutout", error); - } - } - decor.setFitsSystemWindows(false); - View content = decor.findViewById(android.R.id.content); - if (content != null) content.setFitsSystemWindows(false); - // Unity drives legacy system-UI flags even on modern Android. Keep its requested layout - // in sync with the controller, but do not reassign identical flags on every heartbeat. - if ((decor.getSystemUiVisibility() & IMMERSIVE_FLAGS) != IMMERSIVE_FLAGS) - decor.setSystemUiVisibility(decor.getSystemUiVisibility() | IMMERSIVE_FLAGS); - if (Build.VERSION.SDK_INT >= 30) { - Api30.configure(window, decor); - } else { - window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); - } - } - - private static void reportFailure(String operation, RuntimeException error) { - if (loggedFailures.add(operation)) Log.e(TAG, "Failed " + operation + "; will retry", error); - } - - private static final class Api30 { - static void configure(Window window, View decor) { - window.setDecorFitsSystemWindows(false); - // Keep the window frame at the display bounds even while swipe bars are visible. - // Keep real Insets intact. Unity's own root-inset padding policy is configured - // before player creation by patch_manifest.patch_unity_window_metadata. - WindowManager.LayoutParams attributes = window.getAttributes(); - if (attributes.getFitInsetsTypes() != 0) { - attributes.setFitInsetsTypes(0); - window.setAttributes(attributes); - } - hide(decor); - } - - static void hide(View decor) { - WindowInsetsController controller = decor.getWindowInsetsController(); - if (controller != null) { - controller.setSystemBarsBehavior( - WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE); - controller.hide(WindowInsets.Type.systemBars()); - } - } - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGenerationForegroundService.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGenerationForegroundService.java deleted file mode 100644 index 5a82301..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGenerationForegroundService.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Application; -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.Service; -import android.content.Intent; -import android.content.pm.ServiceInfo; -import android.os.Build; -import android.os.IBinder; - -/** - * Holds :game at foreground-service importance while the first-run generator is alive. - * A paused activity drops to cached and the low-memory killer reclaims the multi-gigabyte process. - */ -public final class BppGenerationForegroundService extends Service { - - static final String ACTION_STOP = "com.bepinex.android.bpp.action.STOP_GENERATION_FOREGROUND"; - private static final String CHANNEL_ID = "bpp-generation"; - private static final int NOTIFICATION_ID = 41; - private boolean released; - - @Override - public void onCreate() { - super.onCreate(); - BppGameProcess.logEvent(this, "FGS service onCreate process=" - + Application.getProcessName() + " pid=" + android.os.Process.myPid()); - promote(); - if (!isGameProcess()) { - BppGameProcess.logEvent(this, "FGS service release reason=not :game process=" - + Application.getProcessName()); - release(); - } - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - boolean stop = !isGameProcess() || (intent != null && ACTION_STOP.equals(intent.getAction())); - BppGameProcess.logEvent(this, "FGS service onStartCommand stop=" + stop - + " action=" + (intent == null ? "null" : intent.getAction()) - + " startId=" + startId); - if (stop) { - if (!released) promote(); - release(); - return START_NOT_STICKY; - } - promote(); - return START_NOT_STICKY; - } - - @Override - public void onDestroy() { - BppGameProcess.logEvent(this, "FGS service onDestroy released=" + released); - try { - stopForeground(STOP_FOREGROUND_REMOVE); - } catch (Throwable t) { - BppGameProcess.logEvent(this, "FGS service onDestroy stopForeground failed", t); - } - super.onDestroy(); - } - - @Override - public IBinder onBind(Intent intent) { - return null; - } - - private void promote() { - try { - NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - if (manager != null && Build.VERSION.SDK_INT >= 26) { - NotificationChannel channel = new NotificationChannel( - CHANNEL_ID, - "模组生成", - NotificationManager.IMPORTANCE_LOW - ); - channel.setDescription("首次启动生成模组文件时保持游戏进程在前台"); - manager.createNotificationChannel(channel); - } - Notification notification = new Notification.Builder(this, CHANNEL_ID) - .setContentTitle("正在生成模组文件") - .setContentText("请回到游戏画面,不要切走") - .setSmallIcon(android.R.drawable.stat_notify_sync) - .setOngoing(true) - .setOnlyAlertOnce(true) - .setCategory(Notification.CATEGORY_PROGRESS) - .build(); - if (Build.VERSION.SDK_INT >= 34) { - startForeground( - NOTIFICATION_ID, - notification, - ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE - ); - BppGameProcess.logEvent(this, "FGS service startForeground ok type=specialUse id=" - + NOTIFICATION_ID); - } else { - startForeground(NOTIFICATION_ID, notification); - BppGameProcess.logEvent(this, "FGS service startForeground ok id=" - + NOTIFICATION_ID); - } - } catch (Throwable t) { - BppGameProcess.logEvent(this, "FGS service startForeground exception id=" - + NOTIFICATION_ID, t); - } - } - - private void release() { - if (released) return; - released = true; - BppGameProcess.logEvent(this, "FGS service release begin pid=" + android.os.Process.myPid()); - try { - stopForeground(STOP_FOREGROUND_REMOVE); - } catch (Throwable t) { - BppGameProcess.logEvent(this, "FGS service release stopForeground failed", t); - } - try { - stopSelf(); - } catch (Throwable t) { - BppGameProcess.logEvent(this, "FGS service release stopSelf failed", t); - } - BppGameProcess.logEvent(this, "FGS service release end pid=" + android.os.Process.myPid()); - } - - private static boolean isGameProcess() { - String process = Application.getProcessName(); - return process != null && process.endsWith(":game"); - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGithubFeedback.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGithubFeedback.java deleted file mode 100644 index 4f510a6..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppGithubFeedback.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.bepinex.android.bpp; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; - -/** Pure URL/template helper for the manual GitHub feedback flow. No network I/O. */ -public final class BppGithubFeedback { - - public static final String ISSUES_NEW_BASE = - "https://github.com/TAP-APIA/bazaarplusplus-android/issues/new"; - public static final int MAX_URL_CHARS = 6000; - public static final String DEFAULT_ZIP_FILE_NAME = "(未生成)"; - - private BppGithubFeedback() {} - - public static String buildIssueUrl( - String launcherVersion, - String bppVersionName, - String bppCommit, - String manufacturer, - String model, - String androidRelease, - int sdkInt, - String abis, - String zipFileName - ) { - String safeZip = fileNameOnly(zipFileName); - if (safeZip.length() == 0) safeZip = DEFAULT_ZIP_FILE_NAME; - String title = buildTitle(); - String body = buildBody( - launcherVersion, - bppVersionName, - bppCommit, - manufacturer, - model, - androidRelease, - sdkInt, - abis, - safeZip - ); - String encodedTitle = encodeQuery(title); - String encodedBody = encodeQuery(body); - String url = composeUrl(encodedTitle, encodedBody); - if (url.length() <= MAX_URL_CHARS) return clampUrl(url); - - int low = 0; - int high = body.length(); - String best = composeUrl(encodedTitle, encodeQuery("")); - if (best.length() > MAX_URL_CHARS) return clampUrl(best); - while (low <= high) { - int mid = low + (high - low) / 2; - String part = body.substring(0, Math.min(mid, body.length())); - String candidate = composeUrl(encodedTitle, encodeQuery(part)); - if (candidate.length() <= MAX_URL_CHARS) { - best = candidate; - low = mid + 1; - } else { - high = mid - 1; - } - } - return clampUrl(best); - } - - public static String buildTitle() { - return "[Android] 启动器问题反馈"; - } - - public static String buildBody( - String launcherVersion, - String bppVersionName, - String bppCommit, - String manufacturer, - String model, - String androidRelease, - int sdkInt, - String abis, - String zipFileName - ) { - String safeZip = fileNameOnly(zipFileName); - if (safeZip.length() == 0) safeZip = DEFAULT_ZIP_FILE_NAME; - StringBuilder sb = new StringBuilder(); - sb.append("## 问题描述\n\n\n"); - sb.append("## 复现步骤\n\n1. \n2. \n3. \n\n"); - sb.append("## 环境信息\n"); - sb.append("- 启动器版本: ").append(safeValue(launcherVersion, "未知")).append('\n'); - sb.append("- BppBuildInfo: VERSION_NAME=").append(safeValue(bppVersionName, "未知")) - .append(" COMMIT=").append(safeValue(bppCommit, "未知")).append('\n'); - sb.append("- 设备: ").append(safeValue(manufacturer, "未知")) - .append(' ').append(safeValue(model, "未知")).append('\n'); - sb.append("- Android: ").append(safeValue(androidRelease, "未知")) - .append(" (SDK ").append(sdkInt).append(")\n"); - sb.append("- ABI: ").append(safeValue(abis, "未知")).append('\n'); - sb.append("- 诊断包文件名: ").append(safeZip).append("\n\n"); - sb.append("请把下载文件夹里的 ").append(safeZip).append(" 拖到这里上传\n"); - return sb.toString(); - } - - public static String fileNameOnly(String pathOrName) { - if (pathOrName == null) return ""; - String value = pathOrName.trim(); - if (value.length() == 0) return ""; - value = value.replace('\\', '/'); - int slash = value.lastIndexOf('/'); - String name = slash >= 0 ? value.substring(slash + 1) : value; - if (name.length() == 0) return ""; - if (".".equals(name) || "..".equals(name)) return ""; - return name; - } - - public static String encodeQuery(String value) { - String safe = value == null ? "" : value; - try { - return URLEncoder.encode(safe, "UTF-8").replace("+", "%20"); - } catch (UnsupportedEncodingException ex) { - return safe; - } - } - - public static String clampUrl(String url) { - if (url == null) return ""; - if (url.length() <= MAX_URL_CHARS) return url; - String clamped = url.substring(0, MAX_URL_CHARS); - int percent = clamped.lastIndexOf('%'); - if (percent >= 0 && percent > clamped.length() - 3) { - clamped = clamped.substring(0, percent); - } - return clamped; - } - - private static String composeUrl(String encodedTitle, String encodedBody) { - return ISSUES_NEW_BASE + "?title=" + encodedTitle + "&body=" + encodedBody; - } - - private static String safeValue(String value, String fallback) { - if (value == null) return fallback; - String trimmed = value.trim(); - if (trimmed.length() == 0) return fallback; - return trimmed.replace('\r', ' ').replace('\n', ' '); - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppJitTrace.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppJitTrace.java deleted file mode 100644 index 12f71e6..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppJitTrace.java +++ /dev/null @@ -1,390 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Application; -import android.content.Context; -import android.system.Os; -import android.system.OsConstants; -import android.util.Log; -import java.io.File; -import java.io.FileDescriptor; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.RandomAccessFile; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; - -/** - * Diagnostic-only stdout/stderr redirect and JIT summary capture for the :game process. - * Must run before BepInEx starts CoreCLR so the PAL sees the environment. - */ -public final class BppJitTrace { - - private static final String TAG = "BppGame"; - private static final String DIR_NAME = "bpp-jit"; - private static final int TAIL_CHECK_BYTES = 64 * 1024; - private static final Object LOCK = new Object(); - - private static boolean sInstalled; - private static volatile File sTraceDir; - private static FileDescriptor sStdoutFd; - private static FileDescriptor sStderrFd; - - private BppJitTrace() {} - - public static void install(Context base) { - if (base == null) return; - String processName; - try { - processName = Application.getProcessName(); - } catch (Throwable error) { - logError(base, "process name unavailable", error); - return; - } - if (processName == null || !processName.endsWith(":game")) { - return; - } - synchronized (LOCK) { - if (sInstalled) { - log(base, "already installed"); - return; - } - sInstalled = true; - } - try { - log(base, "install begin process=" + processName); - File dir = prepareTraceDir(base); - sTraceDir = dir; - log(base, "trace dir=" + dir.getAbsolutePath()); - rotateLogs(base, dir); - pruneNetTraces(base, dir); - setEnv(base, dir); - - File stdout = new File(dir, "jit-stdout.log"); - File stderr = new File(dir, "coreclr-stderr.log"); - FileDescriptor out = openAppend(base, stdout); - FileDescriptor err = openAppend(base, stderr); - sStdoutFd = out; - sStderrFd = err; - - writeHeader(base, out, headerLine("stdout")); - writeHeader(base, err, headerLine("stderr")); - - Os.dup2(out, 1); - log(base, "dup2 fd1 -> " + stdout.getAbsolutePath()); - Os.dup2(err, 2); - log(base, "dup2 fd2 -> " + stderr.getAbsolutePath()); - - writeEnvSnapshot(base, dir); - startChecks(base, dir); - log(base, "install complete"); - } catch (Throwable error) { - logError(base, "install failed", error); - } - } - - public static File traceDir(Context context) { - File cached = sTraceDir; - if (cached != null) return cached; - if (context == null) return null; - try { - File dir = prepareTraceDir(context); - sTraceDir = dir; - return dir; - } catch (Throwable error) { - logError(context, "trace dir unavailable", error); - return null; - } - } - - private static File prepareTraceDir(Context context) { - File external = context.getExternalFilesDir(null); - if (external != null) { - File candidate = new File(external, DIR_NAME); - if (ensureDir(context, candidate)) return candidate; - } - File files = context.getFilesDir(); - if (files != null) { - File candidate = new File(files, DIR_NAME); - if (ensureDir(context, candidate)) return candidate; - } - throw new IllegalStateException("cannot create " + DIR_NAME); - } - - private static boolean ensureDir(Context context, File dir) { - if (dir.isDirectory()) return true; - boolean made = dir.mkdirs(); - if (made || dir.isDirectory()) { - log(context, "created dir " + dir.getAbsolutePath()); - return true; - } - log(context, "mkdirs failed " + dir.getAbsolutePath()); - return false; - } - - private static void rotateLogs(Context context, File dir) { - rotateOne(context, new File(dir, "jit-stdout.log"), new File(dir, "jit-stdout.prev.log")); - rotateOne(context, new File(dir, "coreclr-stderr.log"), new File(dir, "coreclr-stderr.prev.log")); - } - - private static void rotateOne(Context context, File current, File previous) { - if (previous.exists()) { - boolean deleted = previous.delete(); - log(context, "delete old " + previous.getAbsolutePath() + " ok=" + deleted); - } - if (!current.exists()) { - log(context, "rotate missing " + current.getAbsolutePath()); - return; - } - boolean renamed = current.renameTo(previous); - if (renamed) { - log(context, "rotated " + current.getName() + " -> " + previous.getName()); - return; - } - try { - copyFile(current, previous); - boolean deleted = current.delete(); - log(context, "rotate copy fallback " + current.getName() + " deleted=" + deleted); - } catch (Throwable error) { - logError(context, "rotate failed " + current.getAbsolutePath(), error); - } - } - - private static void copyFile(File from, File to) throws Exception { - try (FileInputStream in = new FileInputStream(from); - FileOutputStream out = new FileOutputStream(to)) { - byte[] buf = new byte[65536]; - int n; - while ((n = in.read(buf)) != -1) out.write(buf, 0, n); - out.getFD().sync(); - } - } - - private static void pruneNetTraces(Context context, File dir) { - File[] files = dir.listFiles(); - if (files == null) { - log(context, "nettrace list unreadable"); - return; - } - List traces = new ArrayList(); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (file.isFile() && file.getName().toLowerCase(Locale.ROOT).endsWith(".nettrace")) { - traces.add(file); - } - } - Collections.sort(traces, new Comparator() { - @Override - public int compare(File a, File b) { - int time = Long.compare(b.lastModified(), a.lastModified()); - return time != 0 ? time : a.getName().compareTo(b.getName()); - } - }); - for (int i = 2; i < traces.size(); i++) { - File file = traces.get(i); - long bytes = file.length(); - boolean deleted = file.delete(); - log(context, "prune nettrace " + file.getName() + " bytes=" + bytes + " deleted=" + deleted); - } - } - - private static void setEnv(Context context, File dir) { - setOne(context, "DOTNET_JitDisasmSummary", "1"); - unsetOne(context, "DOTNET_JitStdOutFile"); - setOne(context, "DOTNET_EnableEventPipe", "1"); - setOne(context, "DOTNET_EventPipeOutputPath", new File(dir, "jit-{pid}.nettrace").getAbsolutePath()); - setOne(context, "DOTNET_EventPipeConfig", "Microsoft-Windows-DotNETRuntime:0x10:5"); - setOne(context, "DOTNET_EventPipeOutputStreaming", "1"); - } - - private static void setOne(Context context, String name, String value) { - try { - Os.setenv(name, value, true); - log(context, "setenv " + name + "=" + value); - } catch (Throwable error) { - logError(context, "setenv failed " + name, error); - } - } - - private static void unsetOne(Context context, String name) { - try { - Os.unsetenv(name); - log(context, "unsetenv " + name); - } catch (Throwable error) { - logError(context, "unsetenv failed " + name, error); - } - } - - private static FileDescriptor openAppend(Context context, File file) throws Exception { - int flags = OsConstants.O_WRONLY | OsConstants.O_CREAT | OsConstants.O_APPEND; - FileDescriptor fd = Os.open(file.getAbsolutePath(), flags, 0644); - log(context, "open append " + file.getAbsolutePath()); - return fd; - } - - private static void writeHeader(Context context, FileDescriptor fd, String header) throws Exception { - byte[] data = (header + "\n").getBytes(StandardCharsets.UTF_8); - int offset = 0; - while (offset < data.length) { - int written = Os.write(fd, data, offset, data.length - offset); - if (written <= 0) break; - offset += written; - } - log(context, "header written bytes=" + offset); - } - - private static String headerLine(String stream) { - return "# BppJitTrace " + stream - + " time=" + DateTimeFormatter.ISO_INSTANT.format(Instant.now()) - + " pid=" + android.os.Process.myPid() - + " version=" + BppBuildInfo.VERSION_NAME - + " commit=" + BppBuildInfo.COMMIT; - } - - private static void writeEnvSnapshot(Context context, File dir) throws Exception { - StringBuilder sb = new StringBuilder(); - sb.append("# ").append(headerLine("env")).append('\n'); - sb.append("DOTNET_JitDisasmSummary=1\n"); - sb.append("DOTNET_JitStdOutFile=\n"); - sb.append("DOTNET_EnableEventPipe=1\n"); - sb.append("DOTNET_EventPipeOutputPath=").append(new File(dir, "jit-{pid}.nettrace").getAbsolutePath()).append('\n'); - sb.append("DOTNET_EventPipeConfig=Microsoft-Windows-DotNETRuntime:0x10:5\n"); - sb.append("DOTNET_EventPipeOutputStreaming=1\n"); - sb.append("/proc/self/fd/1=").append(readLinkSafe("/proc/self/fd/1")).append('\n'); - sb.append("/proc/self/fd/2=").append(readLinkSafe("/proc/self/fd/2")).append('\n'); - appendText(context, new File(dir, "jit-trace-env.txt"), sb.toString()); - log(context, "env snapshot written fd1=" + readLinkSafe("/proc/self/fd/1") - + " fd2=" + readLinkSafe("/proc/self/fd/2")); - } - - private static void startChecks(final Context context, final File dir) { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - long[] waits = new long[] {3000L, 7000L, 20000L, 90000L}; - long elapsed = 0L; - for (int i = 0; i < waits.length; i++) { - try { - Thread.sleep(waits[i]); - } catch (InterruptedException error) { - logError(context, "checks interrupted", error); - return; - } - elapsed += waits[i]; - try { - check(context, dir, elapsed); - } catch (Throwable error) { - logError(context, "check failed at " + elapsed + "ms", error); - } - } - } - }, "bpp-jit-trace-check"); - thread.setDaemon(true); - thread.start(); - log(context, "scheduled checks at 3s, 10s, 30s, 120s"); - } - - private static void check(Context context, File dir, long elapsedMs) throws Exception { - StringBuilder sb = new StringBuilder(); - String fd1 = readLinkSafe("/proc/self/fd/1"); - String fd2 = readLinkSafe("/proc/self/fd/2"); - sb.append("--- check at ").append(elapsedMs).append("ms time=") - .append(DateTimeFormatter.ISO_INSTANT.format(Instant.now())).append('\n'); - sb.append("/proc/self/fd/1=").append(fd1).append('\n'); - sb.append("/proc/self/fd/2=").append(fd2).append('\n'); - appendFileInfo(sb, dir, "jit-stdout.log"); - appendFileInfo(sb, dir, "coreclr-stderr.log"); - File[] files = dir.listFiles(); - if (files == null) { - sb.append("dir.listFiles=null\n"); - } else { - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (file.isFile() && file.getName().toLowerCase(Locale.ROOT).endsWith(".nettrace")) { - sb.append("nettrace ").append(file.getName()) - .append(" bytes=").append(file.length()).append('\n'); - } - } - } - String last = readLastLine(new File(dir, "jit-stdout.log"), TAIL_CHECK_BYTES); - sb.append("jit-stdout.last=").append(last).append('\n'); - appendText(context, new File(dir, "jit-trace-env.txt"), sb.toString()); - log(context, "check at " + elapsedMs + "ms fd1=" + fd1 + " fd2=" + fd2); - } - - private static void appendFileInfo(StringBuilder sb, File dir, String name) { - File file = new File(dir, name); - sb.append(name).append(" exists=").append(file.exists()) - .append(" bytes=").append(file.isFile() ? file.length() : -1L).append('\n'); - } - - private static String readLastLine(File file, int maxBytes) { - if (file == null || !file.isFile() || file.length() == 0L) return "(empty)"; - long length = file.length(); - int cap = (int) Math.min(length, (long) Math.max(1, maxBytes)); - byte[] data = new byte[cap]; - try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { - raf.seek(length - cap); - int offset = 0; - while (offset < cap) { - int n = raf.read(data, offset, cap - offset); - if (n < 0) break; - offset += n; - } - String text = new String(data, 0, offset, StandardCharsets.UTF_8); - int end = text.length(); - while (end > 0 && (text.charAt(end - 1) == '\n' || text.charAt(end - 1) == '\r')) end--; - if (end == 0) return "(blank)"; - int start = text.lastIndexOf('\n', end - 1); - start = start < 0 ? 0 : start + 1; - String line = text.substring(start, end); - if (line.length() > 2000) line = line.substring(0, 2000) + "...(truncated)"; - return line; - } catch (Throwable error) { - return "unavailable: " + error.getClass().getSimpleName() + ": " + error.getMessage(); - } - } - - private static String readLinkSafe(String path) { - try { - return Os.readlink(path); - } catch (Throwable error) { - return "unavailable: " + error.getClass().getSimpleName() + ": " + error.getMessage(); - } - } - - private static void appendText(Context context, File file, String text) throws Exception { - File parent = file.getParentFile(); - if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { - throw new IllegalStateException("cannot create " + parent.getAbsolutePath()); - } - try (FileOutputStream out = new FileOutputStream(file, true)) { - out.write(text.getBytes(StandardCharsets.UTF_8)); - out.flush(); - out.getFD().sync(); - } - } - - private static void log(Context context, String message) { - Log.i(TAG, message); - try { - BppGameProcess.logEvent(context, "BppJitTrace: " + message); - } catch (Throwable error) { - Log.e(TAG, "logEvent failed", error); - } - } - - private static void logError(Context context, String message, Throwable error) { - Log.e(TAG, message, error); - try { - BppGameProcess.logEvent(context, "BppJitTrace: " + message, error); - } catch (Throwable second) { - Log.e(TAG, "logEvent failed", second); - } - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppLauncherActivity.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppLauncherActivity.java deleted file mode 100644 index 6bfdea7..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppLauncherActivity.java +++ /dev/null @@ -1,1629 +0,0 @@ -package com.bepinex.android.bpp; - -import android.app.Activity; -import android.app.ActivityManager; -import android.app.AlertDialog; -import android.content.ClipData; -import android.content.ClipboardManager; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.graphics.Color; -import android.graphics.Typeface; -import android.graphics.drawable.GradientDrawable; -import android.net.Uri; -import android.os.Bundle; -import android.os.Build; -import android.os.Handler; -import android.os.Looper; -import android.os.Process; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowInsets; -import android.view.WindowInsetsController; -import android.view.WindowManager; -import android.widget.Button; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.Toast; -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Self-deploying BazaarPlusPlus Android launcher activity. - * - * Automatically extracts the BepInEx/.NET runtime and installs or updates the bundled - * BPP modpack while preserving user configs and local history databases, then launches - * The Bazaar through the verified BootstrapActivity pipeline. - */ -public final class BppLauncherActivity extends Activity { - - public static final String EXTRA_AUTO_LAUNCH = "bpp_auto_launch"; - - private static final int COLOR_BG = Color.parseColor("#120E0A"); - private static final int COLOR_CARD = Color.parseColor("#1E1711"); - private static final int COLOR_CARD_SUBTLE = Color.parseColor("#18120D"); - private static final int COLOR_GOLD = Color.parseColor("#F5D176"); - private static final int COLOR_GOLD_BORDER = Color.parseColor("#8C6D32"); - private static final int COLOR_BUTTON_PRIMARY_BG = Color.parseColor("#3B2B15"); - private static final int COLOR_BUTTON_SECONDARY_BG = Color.parseColor("#241C14"); - private static final int COLOR_TEXT_PRIMARY = Color.parseColor("#F7EFE2"); - private static final int COLOR_TEXT_SECONDARY = Color.parseColor("#C9B99B"); - private static final int COLOR_STATUS_OK = Color.parseColor("#7CD992"); - private static final int COLOR_STATUS_WARN = Color.parseColor("#F2B866"); - private static final int COLOR_STATUS_ERR = Color.parseColor("#F27A66"); - - private final ExecutorService worker = Executors.newSingleThreadExecutor(); - private final ExecutorService updateWorker = Executors.newSingleThreadExecutor(); - private final ExecutorService diagnosticWorker = Executors.newSingleThreadExecutor(); - - private TextView tvStatusBadge; - private TextView tvStatusHeadline; - private TextView tvStatusDetail; - private TextView tvGameInfo; - private TextView tvBundleInfo; - private TextView tvPathInfo; - private ProgressBar progressBar; - private Button btnLaunch; - private Button btnRepair; - private Button btnAdvanced; - private TextView tvUpdateInfo; - private Button btnCheckUpdate; - private Button btnDownloadUpdate; - private Button btnExportDiagnostics; - private Button btnGithubFeedback; - private TextView tvExportInfo; - private TextView tvGenerationHint; - private boolean generationWarningAccepted; - private final Handler mainHandler = new Handler(Looper.getMainLooper()); - private volatile boolean exportingDiagnostics; - private boolean checkingUpdate; - private boolean updateChecked; - private boolean resumed; - private boolean updatePromptShown; - private BppLauncherUpdateChecker.Update availableUpdate; - private BppApkDownload apkDownload; - private boolean validatingApk; - private final Runnable downloadPoll = this::refreshApkDownload; - - private volatile boolean busy; - private volatile boolean officialPayloadChecked; - private volatile boolean autoLaunchConsumed; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - try { - android.util.Log.i("BppGame", BppBuildInfo.describe()); - } catch (Throwable t) { - android.util.Log.w("BppGame", "BppBuildInfo.describe failed", t); - } - requestWindowFeature(Window.FEATURE_NO_TITLE); - // Target SDK 35 enforces edge-to-edge on newer Android versions. Keep the background - // edge-to-edge, but inset the scrolling viewport (not its child) so scrolled text never - // draws behind status/navigation bars or a rotated display cutout. - getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); - getWindow().setStatusBarColor(COLOR_BG); - getWindow().setNavigationBarColor(COLOR_BG); - if (Build.VERSION.SDK_INT >= 30) { - getWindow().setDecorFitsSystemWindows(false); - } else { - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); - } - initLauncherCore(); - try { - BppDiagnosticSessionLog.ensureCapture(this, "launcher"); - } catch (Throwable ignored) { - } - apkDownload = new BppApkDownload(this); - setContentView(buildContentView()); - } - - @Override - protected void onResume() { - super.onResume(); - resumed = true; - if (apkDownload.alreadyInstalled(installedLauncherVersion())) apkDownload.clear(); - if (!updateChecked) checkLauncherUpdate(); - refreshApkDownload(); - showLauncherUpdatePrompt(); - clearPendingCrashBanner(); - refreshGenerationHint(); - boolean requestAutoLaunch = !autoLaunchConsumed - && getIntent() != null - && getIntent().getBooleanExtra(EXTRA_AUTO_LAUNCH, false); - if (requestAutoLaunch) { - autoLaunchConsumed = true; - } - startPrepareFlow(false, requestAutoLaunch, false); - } - - @Override - protected void onPause() { - resumed = false; - mainHandler.removeCallbacks(downloadPoll); - super.onPause(); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - worker.shutdownNow(); - updateWorker.shutdownNow(); - diagnosticWorker.shutdownNow(); - mainHandler.removeCallbacksAndMessages(null); - } - - private View buildContentView() { - ScrollView scroll = new ScrollView(this); - scroll.setFillViewport(true); - scroll.setBackgroundColor(COLOR_BG); - scroll.setOnApplyWindowInsetsListener((view, insets) -> { - int left, top, right, bottom; - if (Build.VERSION.SDK_INT >= 30) { - // Read the controller only after the decor is attached; some vendor windows - // dereference an uninitialized decor from Window.getInsetsController(). - WindowInsetsController controller = view.getWindowInsetsController(); - if (controller != null) { - controller.setSystemBarsAppearance(0, - WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS - | WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS); - } - android.graphics.Insets safe = insets.getInsets( - WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout()); - left = safe.left; - top = safe.top; - right = safe.right; - bottom = safe.bottom; - } else { - left = insets.getSystemWindowInsetLeft(); - top = insets.getSystemWindowInsetTop(); - right = insets.getSystemWindowInsetRight(); - bottom = insets.getSystemWindowInsetBottom(); - android.view.DisplayCutout cutout = insets.getDisplayCutout(); - if (cutout != null) { - left = Math.max(left, cutout.getSafeInsetLeft()); - top = Math.max(top, cutout.getSafeInsetTop()); - right = Math.max(right, cutout.getSafeInsetRight()); - bottom = Math.max(bottom, cutout.getSafeInsetBottom()); - } - } - view.setPadding(left, top, right, bottom); - return insets; - }); - scroll.post(scroll::requestApplyInsets); - - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - int padH = dp(24); - int padV = dp(20); - root.setPadding(padH, padV, padH, padV); - - TextView kicker = new TextView(this); - kicker.setText("BAZAARPLUSPLUS · ANDROID 一体化启动器"); - kicker.setTextColor(COLOR_GOLD); - kicker.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f); - kicker.setTypeface(Typeface.DEFAULT_BOLD); - root.addView(kicker); - - TextView title = new TextView(this); - title.setText("The Bazaar 模组启动器"); - title.setTextColor(COLOR_TEXT_PRIMARY); - title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24f); - title.setTypeface(Typeface.DEFAULT_BOLD); - LinearLayout.LayoutParams titleLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - titleLp.topMargin = dp(4); - root.addView(title, titleLp); - - TextView subtitle = new TextView(this); - subtitle.setText("内置 BPP 模组包与运行环境 · 自动部署更新 · 覆盖升级保留配置与历史记录"); - subtitle.setTextColor(COLOR_TEXT_SECONDARY); - subtitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f); - LinearLayout.LayoutParams subLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - subLp.topMargin = dp(4); - subLp.bottomMargin = dp(16); - root.addView(subtitle, subLp); - - LinearLayout statusCard = createCard(COLOR_CARD, COLOR_GOLD_BORDER, dp(16)); - tvStatusBadge = new TextView(this); - tvStatusBadge.setText("正在检查环境"); - tvStatusBadge.setTextColor(COLOR_GOLD); - tvStatusBadge.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f); - tvStatusBadge.setTypeface(Typeface.DEFAULT_BOLD); - statusCard.addView(tvStatusBadge); - - tvStatusHeadline = new TextView(this); - tvStatusHeadline.setContentDescription("bpp_status_title"); - tvStatusHeadline.setText("正在准备内置 BPP 模组…"); - tvStatusHeadline.setTextColor(COLOR_TEXT_PRIMARY); - tvStatusHeadline.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f); - tvStatusHeadline.setTypeface(Typeface.DEFAULT_BOLD); - LinearLayout.LayoutParams headLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - headLp.topMargin = dp(6); - statusCard.addView(tvStatusHeadline, headLp); - - tvStatusDetail = new TextView(this); - tvStatusDetail.setContentDescription("bpp_status_detail"); - tvStatusDetail.setText("首次打开或升级 APK 后会自动同步插件与修补核心,无需电脑 ADB 推送。"); - tvStatusDetail.setTextColor(COLOR_TEXT_SECONDARY); - tvStatusDetail.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f); - LinearLayout.LayoutParams detailLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - detailLp.topMargin = dp(6); - statusCard.addView(tvStatusDetail, detailLp); - - progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal); - progressBar.setMax(100); - progressBar.setProgress(10); - LinearLayout.LayoutParams progLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - dp(8) - ); - progLp.topMargin = dp(12); - statusCard.addView(progressBar, progLp); - - root.addView(statusCard, new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - )); - - btnLaunch = createActionButton( - "启动 The Bazaar(BPP 模组)", - "bpp_btn_launch", - COLOR_BUTTON_PRIMARY_BG, - COLOR_GOLD, - COLOR_GOLD, - 16f, - true - ); - btnLaunch.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (generationWarningAccepted || !shouldWarnBeforeLaunch()) { - startPrepareFlow(false, true, false); - return; - } - new AlertDialog.Builder(BppLauncherActivity.this) - .setTitle("请留在游戏画面") - .setMessage(launchWarningMessage()) - .setPositiveButton("知道了,开始", (dialog, which) -> { - generationWarningAccepted = true; - startPrepareFlow(false, true, false); - }) - .setNegativeButton("取消", null) - .show(); - } - }); - LinearLayout.LayoutParams launchLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - dp(54) - ); - launchLp.topMargin = dp(16); - root.addView(btnLaunch, launchLp); - - tvGenerationHint = new TextView(this); - tvGenerationHint.setContentDescription("bpp_generation_hint"); - tvGenerationHint.setTextColor(COLOR_GOLD); - tvGenerationHint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f); - tvGenerationHint.setVisibility(View.GONE); - LinearLayout.LayoutParams hintLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - hintLp.topMargin = dp(8); - root.addView(tvGenerationHint, hintLp); - - LinearLayout secondaryRow = new LinearLayout(this); - secondaryRow.setOrientation(LinearLayout.HORIZONTAL); - LinearLayout.LayoutParams rowLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - rowLp.topMargin = dp(10); - - btnRepair = createActionButton( - "重新校验 / 修复模组", - "bpp_btn_repair", - COLOR_BUTTON_SECONDARY_BG, - COLOR_GOLD_BORDER, - COLOR_TEXT_PRIMARY, - 13f, - false - ); - btnRepair.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - startPrepareFlow(true, false, true); - } - }); - LinearLayout.LayoutParams leftBtnLp = new LinearLayout.LayoutParams(0, dp(46), 1f); - leftBtnLp.rightMargin = dp(6); - secondaryRow.addView(btnRepair, leftBtnLp); - - btnAdvanced = createActionButton( - "打开原版高级启动器", - "bpp_btn_advanced", - COLOR_BUTTON_SECONDARY_BG, - COLOR_GOLD_BORDER, - COLOR_TEXT_SECONDARY, - 13f, - false - ); - btnAdvanced.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - openOriginalLauncher(); - } - }); - LinearLayout.LayoutParams rightBtnLp = new LinearLayout.LayoutParams(0, dp(46), 1f); - rightBtnLp.leftMargin = dp(6); - secondaryRow.addView(btnAdvanced, rightBtnLp); - - root.addView(secondaryRow, rowLp); - - LinearLayout diagnosticsRow = new LinearLayout(this); - diagnosticsRow.setOrientation(LinearLayout.HORIZONTAL); - LinearLayout.LayoutParams diagnosticsRowLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - diagnosticsRowLp.topMargin = dp(10); - - btnExportDiagnostics = createActionButton( - "导出诊断日志", - "bpp_btn_export_diagnostics", - COLOR_BUTTON_SECONDARY_BG, - COLOR_GOLD, - COLOR_GOLD, - 15f, - true - ); - btnExportDiagnostics.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - exportDiagnostics(); - } - }); - LinearLayout.LayoutParams exportBtnLp = new LinearLayout.LayoutParams(0, dp(48), 1f); - exportBtnLp.rightMargin = dp(6); - diagnosticsRow.addView(btnExportDiagnostics, exportBtnLp); - - btnGithubFeedback = createActionButton( - "去 GitHub 反馈", - "bpp_btn_github_feedback", - COLOR_BUTTON_SECONDARY_BG, - COLOR_GOLD_BORDER, - COLOR_TEXT_PRIMARY, - 15f, - true - ); - btnGithubFeedback.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - exportDiagnosticsForGithubFeedback(); - } - }); - LinearLayout.LayoutParams feedbackBtnLp = new LinearLayout.LayoutParams(0, dp(48), 1f); - feedbackBtnLp.leftMargin = dp(6); - diagnosticsRow.addView(btnGithubFeedback, feedbackBtnLp); - - root.addView(diagnosticsRow, diagnosticsRowLp); - - TextView exportHint = new TextView(this); - exportHint.setText("灰屏或闪退后回到本页再点。会保存到「下载」并打开分享,包含设备信息与启动日志,不含对局数据库和签名私钥。"); - exportHint.setTextColor(COLOR_TEXT_SECONDARY); - exportHint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f); - LinearLayout.LayoutParams exportHintLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - exportHintLp.topMargin = dp(6); - root.addView(exportHint, exportHintLp); - - tvExportInfo = new TextView(this); - tvExportInfo.setContentDescription("bpp_export_path"); - tvExportInfo.setTextColor(COLOR_GOLD); - tvExportInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f); - tvExportInfo.setVisibility(View.GONE); - LinearLayout.LayoutParams exportInfoLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - exportInfoLp.topMargin = dp(4); - root.addView(tvExportInfo, exportInfoLp); - - LinearLayout infoCard = createCard(COLOR_CARD_SUBTLE, COLOR_GOLD_BORDER, dp(14)); - LinearLayout.LayoutParams infoCardLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - infoCardLp.topMargin = dp(14); - - tvGameInfo = createInfoLine("游戏状态:正在检测…"); - tvBundleInfo = createInfoLine("内置模组:正在读取清单…"); - tvPathInfo = createInfoLine("数据保护:保留 BazaarPlusPlus.cfg 与 BazaarPlusPlusV6 本地历史"); - infoCard.addView(tvGameInfo); - infoCard.addView(tvBundleInfo); - infoCard.addView(tvPathInfo); - root.addView(infoCard, infoCardLp); - - LinearLayout updateCard = createCard(COLOR_CARD_SUBTLE, COLOR_GOLD_BORDER, dp(14)); - tvUpdateInfo = createInfoLine("启动器版本:" + installedLauncherVersion()); - tvUpdateInfo.setContentDescription("bpp_update_status"); - updateCard.addView(tvUpdateInfo); - btnCheckUpdate = createActionButton("检查启动器更新", "bpp_btn_check_update", - COLOR_BUTTON_SECONDARY_BG, COLOR_GOLD_BORDER, COLOR_TEXT_PRIMARY, 13f, false); - btnCheckUpdate.setOnClickListener(v -> checkLauncherUpdate()); - updateCard.addView(btnCheckUpdate); - btnDownloadUpdate = createActionButton("下载新版 APK", "bpp_btn_download_update", - COLOR_BUTTON_PRIMARY_BG, COLOR_GOLD_BORDER, COLOR_GOLD, 13f, true); - btnDownloadUpdate.setVisibility(View.GONE); - btnDownloadUpdate.setOnClickListener(v -> downloadOrInstallUpdate()); - updateCard.addView(btnDownloadUpdate); - Button releasePage = createActionButton("GitHub 下载页(备用)", "bpp_btn_release_page", - COLOR_BUTTON_SECONDARY_BG, COLOR_GOLD_BORDER, COLOR_TEXT_SECONDARY, 13f, false); - releasePage.setOnClickListener(v -> openReleasePage()); - updateCard.addView(releasePage); - TextView updateHint = createInfoLine("仅检查本项目启动器(含预览版);不会自动替换上游资源。覆盖安装,请勿卸载或清除数据。"); - updateCard.addView(updateHint); - LinearLayout.LayoutParams updateLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - updateLp.topMargin = dp(14); - root.addView(updateCard, updateLp); - - scroll.addView(root); - return scroll; - } - - private String installedLauncherVersion() { - try { - return getPackageManager().getPackageInfo(getPackageName(), 0).versionName; - } catch (Exception ex) { - return "未知"; - } - } - - private void checkLauncherUpdate() { - if (checkingUpdate || isDestroyed()) return; - checkingUpdate = true; - updateChecked = true; - btnCheckUpdate.setEnabled(false); - final String currentVersion = installedLauncherVersion(); - tvUpdateInfo.setText("启动器 " + currentVersion + " · 正在检查 GitHub 更新…"); - updateWorker.execute(() -> { - BppLauncherUpdateChecker.Update found = null; - String error = null; - try { - found = BppLauncherUpdateChecker.check(currentVersion); - } catch (Exception ex) { - error = "检查失败,请检查网络或稍后重试"; - logError("Launcher update check failed", ex); - } - final BppLauncherUpdateChecker.Update result = found; - final String failure = error; - runOnUiThread(() -> { - if (isDestroyed() || isFinishing()) return; - checkingUpdate = false; - btnCheckUpdate.setEnabled(true); - availableUpdate = result; - btnDownloadUpdate.setVisibility(result == null ? View.GONE : View.VISIBLE); - tvUpdateInfo.setText("启动器 " + currentVersion + " · " + (failure != null ? failure - : result == null ? "未发现更新版本(含预览版)" : "发现新版 " + result.version)); - showLauncherUpdatePrompt(); - refreshApkDownload(); - }); - }); - } - - private void showLauncherUpdatePrompt() { - if (!resumed || isFinishing() || isDestroyed() || availableUpdate == null || updatePromptShown || apkDownload.hasDownload()) return; - updatePromptShown = true; - new AlertDialog.Builder(this) - .setTitle("发现启动器新版 " + availableUpdate.version) - .setMessage("当前版本:" + installedLauncherVersion() - + "\n在 App 内下载 APK,完成后点击安装并按系统提示覆盖升级。请勿卸载或清除数据,以保留配置与历史记录。") - .setPositiveButton("下载新版", (dialog, which) -> downloadOrInstallUpdate()) - .setNegativeButton("稍后", null) - .show(); - } - - private void refreshApkDownload() { - mainHandler.removeCallbacks(downloadPoll); - if (!resumed || isDestroyed() || validatingApk || !apkDownload.hasDownload()) return; - try { - BppApkDownload.State state = apkDownload.state(); - tvUpdateInfo.setText(state.message); - btnDownloadUpdate.setVisibility(View.VISIBLE); - btnDownloadUpdate.setText(state.complete ? "安装已下载的新版" : "正在下载…"); - btnDownloadUpdate.setEnabled(state.complete); - if (!state.complete) mainHandler.postDelayed(downloadPoll, 1000); - } catch (Exception error) { - apkDownload.clear(); - btnDownloadUpdate.setEnabled(true); - btnDownloadUpdate.setText("重新下载新版 APK"); - btnDownloadUpdate.setVisibility(availableUpdate == null ? View.GONE : View.VISIBLE); - tvUpdateInfo.setText(error.getMessage()); - } - } - - private void downloadOrInstallUpdate() { - try { - if (!apkDownload.hasDownload()) { - if (availableUpdate == null) return; - apkDownload.start(availableUpdate); - refreshApkDownload(); - return; - } - if (!apkDownload.state().complete) return; - if (validatingApk) return; - validatingApk = true; - mainHandler.removeCallbacks(downloadPoll); - btnDownloadUpdate.setEnabled(false); - tvUpdateInfo.setText("正在校验安装包…"); - updateWorker.execute(() -> { - Uri uri = null; - Exception failure = null; - try { uri = apkDownload.installationUri(); } - catch (Exception error) { failure = error; } - final Uri result = uri; - final Exception error = failure; - runOnUiThread(() -> { - validatingApk = false; - if (isDestroyed() || isFinishing()) return; - refreshApkDownload(); - // Returning from the background leaves an explicit install button. - if (!resumed) return; - if (error != null) showApkUpdateError(error); - else launchApkInstaller(result); - }); - }); - } catch (Exception error) { - showApkUpdateError(error); - } - } - - private void launchApkInstaller(Uri apk) { - try { - if (!getPackageManager().canRequestPackageInstalls()) { - new AlertDialog.Builder(this) - .setTitle("允许安装更新") - .setMessage("请在系统设置中允许 BPP 安装应用,返回后再次点击「安装已下载的新版」。") - .setPositiveButton("打开设置", (dialog, which) -> { - try { - startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, - Uri.parse("package:" + getPackageName()))); - } catch (Exception error) { - Toast.makeText(this, "无法打开设置,请在系统设置中允许安装未知应用", Toast.LENGTH_LONG).show(); - } - }).setNegativeButton("稍后", null).show(); - return; - } - Intent install = new Intent(Intent.ACTION_VIEW) - .setDataAndType(apk, "application/vnd.android.package-archive") - .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - install.setClipData(ClipData.newRawUri("BPP update", apk)); - startActivity(install); - } catch (Exception error) { - showApkUpdateError(error); - } - } - - private void showApkUpdateError(Exception error) { - logError("Launcher APK update failed", error); - new AlertDialog.Builder(this) - .setTitle("更新未完成") - .setMessage(error.getMessage() + "\n可重新下载,或打开 GitHub 下载页。请勿卸载应用。") - .setPositiveButton("重新下载", (dialog, which) -> { - apkDownload.clear(); - btnDownloadUpdate.setText("下载新版 APK"); - btnDownloadUpdate.setEnabled(true); - if (availableUpdate != null) downloadOrInstallUpdate(); - else checkLauncherUpdate(); - }) - .setNeutralButton("GitHub 下载页", (dialog, which) -> openReleasePage()).setNegativeButton("稍后", null).show(); - } - - private void openReleasePage() { - try { - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(availableUpdate == null - ? BppLauncherUpdateChecker.RELEASES_URL : availableUpdate.releaseUrl))); - } catch (Exception ignored) { - Toast.makeText(this, "无法打开浏览器", Toast.LENGTH_LONG).show(); - } - } - - private TextView createInfoLine(String text) { - TextView tv = new TextView(this); - tv.setText(text); - tv.setTextColor(COLOR_TEXT_SECONDARY); - tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f); - LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ); - lp.topMargin = dp(4); - tv.setLayoutParams(lp); - return tv; - } - - private LinearLayout createCard(int bgColor, int strokeColor, int paddingPx) { - LinearLayout layout = new LinearLayout(this); - layout.setOrientation(LinearLayout.VERTICAL); - layout.setPadding(paddingPx, paddingPx, paddingPx, paddingPx); - GradientDrawable bg = new GradientDrawable(); - bg.setColor(bgColor); - bg.setCornerRadius(dp(12)); - bg.setStroke(dp(1), strokeColor); - layout.setBackground(bg); - return layout; - } - - private Button createActionButton( - String label, - String contentDesc, - int bgColor, - int strokeColor, - int textColor, - float textSp, - boolean bold - ) { - Button btn = new Button(this); - btn.setAllCaps(false); - btn.setText(label); - btn.setContentDescription(contentDesc); - btn.setTextColor(textColor); - btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSp); - btn.setTypeface(bold ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT); - btn.setGravity(Gravity.CENTER); - GradientDrawable bg = new GradientDrawable(); - bg.setColor(bgColor); - bg.setCornerRadius(dp(10)); - bg.setStroke(dp(1), strokeColor); - btn.setBackground(bg); - return btn; - } - - private void startPrepareFlow( - final boolean forceRepair, - final boolean launchWhenReady, - final boolean stopRunningGameIfNeeded - ) { - if (busy) { - return; - } - busy = true; - setButtonsEnabled(false); - worker.execute(new Runnable() { - @Override - public void run() { - try { - runPrepareFlowOnWorker(forceRepair, launchWhenReady, stopRunningGameIfNeeded); - } finally { - busy = false; - runOnUiThread(new Runnable() { - @Override - public void run() { - setButtonsEnabled(true); - } - }); - } - } - }); - } - - private void runPrepareFlowOnWorker( - boolean forceRepair, - boolean launchWhenReady, - boolean stopRunningGameIfNeeded - ) { - final String pkg = BppBundledModpackInstaller.TARGET_PACKAGE; - final PackageInfo gamePkg = findInstalledGamePackage(pkg); - final File gameRootDir = resolveGameRootDir(pkg); - final File internalWorkDir = new File(getFilesDir(), "bpp-bundled-installer"); - - BppBundledModpackInstaller.Manifest manifest; - try { - manifest = BppBundledModpackInstaller.parseManifest( - getAssets().open(BppBundledModpackInstaller.ASSET_MODPACK_MANIFEST) - ); - } catch (final Exception ex) { - logError("Failed to read bundled manifest", ex); - notePrepare("manifest-error", String.valueOf(ex.getMessage())); - updateUiState( - "清单错误", - COLOR_STATUS_ERR, - "无法读取内置模组清单", - String.valueOf(ex.getMessage()), - 100, - gamePkg, - null, - gameRootDir - ); - return; - } - - final BppBundledModpackInstaller.Manifest resolvedManifest = manifest; - BppBundledModpackInstaller.StatusReport current = BppBundledModpackInstaller.inspectStatus( - gameRootDir, - internalWorkDir, - resolvedManifest, - true - ); - - int gamePid = findRunningGameProcessPid(); - if (gamePid > 0 && (!current.isReady() || forceRepair)) { - if (stopRunningGameIfNeeded) { - Process.killProcess(gamePid); - try { - Thread.sleep(600L); - } catch (InterruptedException ignored) { - Thread.currentThread().interrupt(); - } - } else { - updateUiState( - "游戏运行中", - COLOR_STATUS_WARN, - "检测到游戏进程正在运行,暂不写入模组文件", - "请先关闭游戏,或点击「重新校验 / 修复模组」自动停止游戏进程并完成更新。", - 100, - gamePkg, - resolvedManifest, - gameRootDir - ); - notePrepare("game-running", "pid=" + gamePid); - return; - } - } - - try { - updateUiState( - "正在准备", - COLOR_GOLD, - "正在检查 BepInEx 与 .NET 运行环境…", - "首次安装或更新时会自动解包运行环境与内置模组。", - 20, - gamePkg, - resolvedManifest, - gameRootDir - ); - ensureFrameworkExtracted(pkg); - - BppBundledModpackInstaller.StatusReport finalReport = BppBundledModpackInstaller.installOrUpdate( - gameRootDir, - internalWorkDir, - new BppBundledModpackInstaller.StreamSupplier() { - @Override - public java.io.InputStream open() throws java.io.IOException { - return getAssets().open(BppBundledModpackInstaller.ASSET_MODPACK_MANIFEST); - } - }, - new BppBundledModpackInstaller.StreamSupplier() { - @Override - public java.io.InputStream open() throws java.io.IOException { - return getAssets().open(BppBundledModpackInstaller.ASSET_MODPACK_ZIP); - } - }, - new BppBundledModpackInstaller.StreamSupplier() { - @Override - public java.io.InputStream open() throws java.io.IOException { - return getAssets().open(BppBundledModpackInstaller.ASSET_BEPINEX_ZIP); - } - }, - forceRepair, - new BppBundledModpackInstaller.ProgressListener() { - @Override - public void onProgress(String step, int percent) { - updateUiState( - "正在同步", - COLOR_GOLD, - step, - "内置版本 " + resolvedManifest.version + " · 保留现有配置与历史记录", - percent, - gamePkg, - resolvedManifest, - gameRootDir - ); - } - } - ); - - if (gamePkg == null) { - updateUiState( - "模组已就绪 · 待安装游戏", - COLOR_STATUS_WARN, - "内置 BPP 模组已部署完成,但尚未检测到 The Bazaar 本体", - "请先在设备安装 The Bazaar (" + pkg + "),随后返回本应用点击启动。", - 100, - null, - resolvedManifest, - gameRootDir - ); - notePrepare("mod-ready-no-game", pkg); - return; - } - - updateUiState( - "已就绪", - COLOR_STATUS_OK, - finalReport.detail + " · 可直接启动游戏", - "点击下方「启动 The Bazaar(BPP 模组)」即可进入游戏;触屏入口支持长按拖动。", - 100, - gamePkg, - resolvedManifest, - gameRootDir - ); - - notePrepare("ready", finalReport.detail); - checkOfficialPayload(gameRootDir); - if (launchWhenReady) { - launchBazaarWithBpp(pkg); - } - } catch (final Exception ex) { - logError("BPP bundled modpack preparation failed", ex); - notePrepare("failed", String.valueOf(ex.getMessage())); - updateUiState( - "需要修复", - COLOR_STATUS_ERR, - "内置模组部署未完成", - String.valueOf(ex.getMessage()), - 100, - gamePkg, - resolvedManifest, - gameRootDir - ); - } - } - - private void launchBazaarWithBpp(final String packageName) { - try { - if (!isFrameworkReady(packageName)) { - ensureFrameworkExtracted(packageName); - } - boolean useOriginalLibUnity = !readAppSettingBoolean( - "isUseUnstrippedLibUnityFlow", - packageName, - false - ); - boolean blockUnityKill = readAppSettingBoolean( - "isUnityKillBlockEnabledFlow", - packageName, - false - ); - boolean screenDim = readAppSettingBoolean( - "getScreenDimInGameEnabledFlow", - null, - false - ); - boolean floatingLog = readAppSettingBoolean( - "getFloatingLogInGameEnabledFlow", - null, - false - ); - recordActiveModpackSelection(packageName, BppBundledModpackInstaller.MODPACK_NAME); - markCrashDiagnosticsLaunch(packageName); - patchGameLoggingConfig(packageName); - BppDiagnosticSessionLog.noteLaunch( - this, - BppDiagnosticBundle.nowIso() - + " event=launch" - + " target=" + packageName - + " pid=" + Process.myPid() - + " gamePid=pending" - + " ogLibUnity=" + useOriginalLibUnity - + " blockUnityKill=" + blockUnityKill - + " screenDim=" + screenDim - + " floatingLog=" + floatingLog - + " modpack=" + BppBundledModpackInstaller.MODPACK_NAME - ); - scheduleGamePidNotes(); - - final Class bootstrapClass = Class.forName("com.bepinex.android.BootstrapActivity"); - runOnUiThread(new Runnable() { - @Override - public void run() { - try { - Intent intent = new Intent(BppLauncherActivity.this, bootstrapClass); - intent.putExtra("target_package", packageName); - intent.putExtra("og_libunity", useOriginalLibUnity); - intent.putExtra("block_unity_kill", blockUnityKill); - intent.putExtra("screen_dim", screenDim); - intent.putExtra("floating_log", floatingLog); - ArrayList modpacks = new ArrayList(); - modpacks.add(BppBundledModpackInstaller.MODPACK_NAME); - intent.putStringArrayListExtra("active_modpacks", modpacks); - intent.putExtra("active_modpack", BppBundledModpackInstaller.MODPACK_NAME); - startActivity(intent); - } catch (Exception ex) { - logError("Failed to start BootstrapActivity", ex); - Toast.makeText( - BppLauncherActivity.this, - "启动失败: " + ex.getMessage(), - Toast.LENGTH_LONG - ).show(); - } - } - }); - } catch (final Exception ex) { - logError("Failed preparing game launch", ex); - runOnUiThread(new Runnable() { - @Override - public void run() { - Toast.makeText( - BppLauncherActivity.this, - "启动准备失败: " + ex.getMessage(), - Toast.LENGTH_LONG - ).show(); - } - }); - } - } - - private void openOriginalLauncher() { - try { - Class mainClass = Class.forName("com.bepinex.android.MainActivity"); - Intent intent = new Intent(this, mainClass); - startActivity(intent); - } catch (Exception ex) { - Toast.makeText(this, "无法打开高级界面: " + ex.getMessage(), Toast.LENGTH_LONG).show(); - } - } - - private void updateUiState( - final String badge, - final int badgeColor, - final String headline, - final String detail, - final int progress, - final PackageInfo gamePkg, - final BppBundledModpackInstaller.Manifest manifest, - final File gameRootDir - ) { - runOnUiThread(new Runnable() { - @Override - public void run() { - tvStatusBadge.setText(badge); - tvStatusBadge.setTextColor(badgeColor); - tvStatusHeadline.setText(headline); - tvStatusDetail.setText(detail); - progressBar.setProgress(Math.max(0, Math.min(100, progress))); - if (gamePkg != null) { - tvGameInfo.setText( - "游戏状态:已安装 The Bazaar · 版本 " - + (gamePkg.versionName != null ? gamePkg.versionName : "未知") - ); - } else { - tvGameInfo.setText("游戏状态:未检测到 com.tempogames.thebazaar(请先安装游戏本体)"); - } - if (manifest != null) { - String shortHash = manifest.bundleId.length() >= 12 - ? manifest.bundleId.substring(0, 12) - : manifest.bundleId; - tvBundleInfo.setText( - "内置模组:BPP " + manifest.version - + " · " + manifest.managedDllCount + " 个托管程序集 · SHA256 " + shortHash - ); - } - if (gameRootDir != null) { - tvPathInfo.setText("运行目录:" + gameRootDir.getAbsolutePath()); - } - } - }); - } - - private void setButtonsEnabled(boolean enabled) { - if (btnLaunch != null) { - btnLaunch.setEnabled(enabled); - btnLaunch.setAlpha(enabled ? 1.0f : 0.55f); - } - if (btnRepair != null) { - btnRepair.setEnabled(enabled); - btnRepair.setAlpha(enabled ? 1.0f : 0.55f); - } - } - - private PackageInfo findInstalledGamePackage(String packageName) { - try { - PackageManager pm = getPackageManager(); - if (pm.getLaunchIntentForPackage(packageName) == null) { - return null; - } - return pm.getPackageInfo(packageName, 0); - } catch (Exception ex) { - return null; - } - } - - private boolean shouldWarnBeforeLaunch() { - return interopDllCount() <= 0 || killedDuringGeneration(); - } - - private String launchWarningMessage() { - if (killedDuringGeneration()) { - return "上次生成模组文件时游戏被系统杀掉了(内存不足)。当时游戏不在前台,系统会优先回收它。" - + "请重新启动后留在灰色画面,上面会显示「模组准备中」。不要切回启动器或桌面,也不要划掉通知,直到进入游戏。"; - } - return BppDiagnosticBundle.FIRST_RUN_OVERLAY_TEXT - + "。进入游戏后灰色画面上会显示「模组准备中」。请一直留在游戏里,不要划掉通知。"; - } - - private void refreshGenerationHint() { - if (tvGenerationHint == null) return; - try { - if (killedDuringGeneration()) { - tvGenerationHint.setVisibility(View.VISIBLE); - tvGenerationHint.setText("上次生成模组文件时,游戏因为切到后台被系统杀掉了(内存不足)。" - + "请再启动一次,留在灰色画面上的「模组准备中」直到进入游戏,不要划掉通知。"); - return; - } - if (interopDllCount() <= 0) { - tvGenerationHint.setVisibility(View.VISIBLE); - tvGenerationHint.setText(BppDiagnosticBundle.FIRST_RUN_OVERLAY_TEXT - + "。灰色画面上会显示进度,请不要切走,也不要划掉通知。"); - return; - } - tvGenerationHint.setVisibility(View.GONE); - } catch (Throwable ignored) { - tvGenerationHint.setVisibility(View.GONE); - } - } - - private boolean killedDuringGeneration() { - String state = readGenerationState(); - if (state.indexOf("stage=ready") >= 0) return false; - boolean inProgress = state.indexOf("stage=cpp2il") >= 0 - || state.indexOf("stage=interop") >= 0 - || state.indexOf("stage=unity-libs") >= 0 - || state.indexOf("stage=starting") >= 0 - || state.indexOf("stage=plugins") >= 0; - if (!inProgress) return false; - String exit = BppDiagnosticExporter.latestGameExitNote(this); - return exit.indexOf("reasonName=LOW_MEMORY") >= 0 || exit.indexOf("reason=3") >= 0; - } - - private String readGenerationState() { - try { - File file = new File(BppDiagnosticSessionLog.diagnosticsDir(this), "generation-state.txt"); - if (!file.isFile() || file.length() > 8192) return ""; - byte[] data = java.nio.file.Files.readAllBytes(file.toPath()); - return new String(data, java.nio.charset.StandardCharsets.UTF_8); - } catch (Exception ex) { - return ""; - } - } - - private int interopDllCount() { - BppDiagnosticBundle.DirStat stat = BppDiagnosticBundle.summarizeTree( - new File(resolveGameRootDir(BppBundledModpackInstaller.TARGET_PACKAGE), "BepInEx/interop"), - ".dll", - 2 - ); - return stat.files; - } - - private void patchGameLoggingConfig(String packageName) { - File root = resolveGameRootDir(packageName); - patchCfg(new File(root, "BepInEx/config/BepInEx.cfg")); - patchCfg(new File(root, "modpacks/bpp/config/BepInEx.cfg")); - } - - private void patchCfg(File cfg) { - try { - if (cfg == null || !cfg.isFile()) return; - byte[] raw = java.nio.file.Files.readAllBytes(cfg.toPath()); - if (raw.length > 1024 * 1024) return; - String text = new String(raw, java.nio.charset.StandardCharsets.UTF_8); - String updated = BppDiagnosticBundle.enableDiagnosticLogging(text); - if (updated.equals(text)) return; - File tmp = new File(cfg.getAbsolutePath() + ".tmp"); - java.nio.file.Files.write(tmp.toPath(), updated.getBytes(java.nio.charset.StandardCharsets.UTF_8)); - if (!tmp.renameTo(cfg)) { - java.nio.file.Files.write(cfg.toPath(), updated.getBytes(java.nio.charset.StandardCharsets.UTF_8)); - tmp.delete(); - } - BppDiagnosticSessionLog.note(this, "prepare-results.log", - BppDiagnosticBundle.nowIso() + " outcome=logging-config detail=" + cfg.getName()); - } catch (Exception ignored) { - } - } - - private void scheduleGamePidNotes() { - final int[] delays = new int[] {1000, 2000, 4000, 8000, 15000, 30000, 60000}; - for (int i = 0; i < delays.length; i++) { - final int delay = delays[i]; - mainHandler.postDelayed(new Runnable() { - @Override - public void run() { - int gamePid = findRunningGameProcessPid(); - BppDiagnosticSessionLog.note( - BppLauncherActivity.this, - "launch-attempts.log", - BppDiagnosticBundle.nowIso() - + " event=game-pid gamePid=" + gamePid - + " afterMs=" + delay - ); - } - }, delay); - } - } - - private int findRunningGameProcessPid() { - try { - ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); - if (am == null) { - return -1; - } - List procs = am.getRunningAppProcesses(); - if (procs == null) { - return -1; - } - String expected = getPackageName() + ":game"; - for (ActivityManager.RunningAppProcessInfo info : procs) { - if (info != null && expected.equals(info.processName) && info.pid > 0) { - return info.pid; - } - } - } catch (Exception ignored) { - } - return -1; - } - - private void initLauncherCore() { - try { - Class pathsClass = Class.forName("com.bepinex.android.BepInExPaths"); - Object pathsInstance = pathsClass.getField("INSTANCE").get(null); - pathsClass.getMethod("install", Context.class).invoke(pathsInstance, this); - } catch (Exception ignored) { - } - try { - Class settingsClass = Class.forName("com.bepinex.android.settings.AppSettings"); - Object settingsInstance = settingsClass.getField("INSTANCE").get(null); - settingsClass.getMethod("initialize", Context.class).invoke(settingsInstance, this); - } catch (Exception ignored) { - } - try { - Class logClass = Class.forName("com.bepinex.android.BepInExLog"); - Object logInstance = logClass.getField("INSTANCE").get(null); - logClass.getMethod("init", Context.class).invoke(logInstance, this); - logClass.getMethod("i", String.class).invoke(logInstance, "=== BPP Integrated Launcher ==="); - } catch (Exception ignored) { - } - } - - private void clearPendingCrashBanner() { - try { - Class crashClass = Class.forName("com.bepinex.android.CrashDiagnostics"); - Object crashInstance = crashClass.getField("INSTANCE").get(null); - crashClass.getMethod("clearPending", Context.class).invoke(crashInstance, this); - } catch (Exception ignored) { - } - } - - private void markCrashDiagnosticsLaunch(String packageName) { - try { - Class crashClass = Class.forName("com.bepinex.android.CrashDiagnostics"); - Object crashInstance = crashClass.getField("INSTANCE").get(null); - crashClass.getMethod("markLaunch", Context.class, String.class) - .invoke(crashInstance, this, packageName); - } catch (Exception ignored) { - } - } - - private File resolveGameRootDir(String packageName) { - try { - Class pathsClass = Class.forName("com.bepinex.android.BepInExPaths"); - Object pathsInstance = pathsClass.getField("INSTANCE").get(null); - Object dir = pathsClass.getMethod("getGameRootDir", String.class) - .invoke(pathsInstance, packageName); - if (dir instanceof File) { - return (File) dir; - } - } catch (Exception ignored) { - } - File external = getExternalFilesDir(null); - if (external == null) { - external = getFilesDir(); - } - return new File(external, "BepInEx_Android/" + packageName); - } - - private boolean isFrameworkReady(String packageName) { - try { - Class extractorClass = Class.forName("com.bepinex.android.FileExtractor"); - Object extractor = extractorClass.getConstructor(Context.class).newInstance(this); - Object ready = extractorClass.getMethod("isFrameworkReady", String.class) - .invoke(extractor, packageName); - return Boolean.TRUE.equals(ready); - } catch (Exception ex) { - return false; - } - } - - private void ensureFrameworkExtracted(String packageName) throws Exception { - Class extractorClass = Class.forName("com.bepinex.android.FileExtractor"); - Object extractor = extractorClass.getConstructor(Context.class).newInstance(this); - Class fn1Class = Class.forName("kotlin.jvm.functions.Function1"); - Method extractBep = extractorClass.getMethod( - "extractBepInExIfNeeded$default", - extractorClass, - String.class, - fn1Class, - int.class, - Object.class - ); - extractBep.invoke(null, extractor, packageName, null, 2, null); - - Method extractDotnet = extractorClass.getMethod( - "extractDotnetIfNeeded$default", - extractorClass, - String.class, - fn1Class, - int.class, - Object.class - ); - extractDotnet.invoke(null, extractor, packageName, null, 2, null); - } - - private boolean readAppSettingBoolean(String flowMethodName, String packageName, boolean fallback) { - try { - Class settingsClass = Class.forName("com.bepinex.android.settings.AppSettings"); - final Object settingsInstance = settingsClass.getField("INSTANCE").get(null); - final Object flow; - if (packageName != null) { - flow = settingsClass.getMethod(flowMethodName, Context.class, String.class) - .invoke(settingsInstance, this, packageName); - } else { - flow = settingsClass.getMethod(flowMethodName, Context.class) - .invoke(settingsInstance, this); - } - Class flowClass = Class.forName("kotlinx.coroutines.flow.Flow"); - Class contClass = Class.forName("kotlin.coroutines.Continuation"); - final Method firstMethod = Class.forName("kotlinx.coroutines.flow.FlowKt") - .getMethod("first", flowClass, contClass); - Object result = runSuspendFunction2(new SuspendInvocation() { - @Override - public Object invoke(Object continuation) throws Exception { - return firstMethod.invoke(null, flow, continuation); - } - }); - if (result instanceof Boolean) { - return (Boolean) result; - } - } catch (Exception ignored) { - } - return fallback; - } - - private void recordActiveModpackSelection(final String packageName, final String modpackName) { - try { - final Class settingsClass = Class.forName("com.bepinex.android.settings.AppSettings"); - final Object settingsInstance = settingsClass.getField("INSTANCE").get(null); - final Class contClass = Class.forName("kotlin.coroutines.Continuation"); - final Method setActive = settingsClass.getMethod( - "setActiveModpack", - Context.class, - String.class, - String.class, - contClass - ); - runSuspendFunction2(new SuspendInvocation() { - @Override - public Object invoke(Object continuation) throws Exception { - return setActive.invoke( - settingsInstance, - BppLauncherActivity.this, - packageName, - modpackName, - continuation - ); - } - }); - final Method setLastModpacks = settingsClass.getMethod( - "setLastLaunchedModpacks", - Context.class, - String.class, - Set.class, - contClass - ); - final Set singleton = Collections.singleton(modpackName); - runSuspendFunction2(new SuspendInvocation() { - @Override - public Object invoke(Object continuation) throws Exception { - return setLastModpacks.invoke( - settingsInstance, - BppLauncherActivity.this, - packageName, - singleton, - continuation - ); - } - }); - } catch (Exception ignored) { - } - } - - private interface SuspendInvocation { - Object invoke(Object continuation) throws Exception; - } - - private Object runSuspendFunction2(final SuspendInvocation call) throws Exception { - Class fn2Class = Class.forName("kotlin.jvm.functions.Function2"); - Class ctxClass = Class.forName("kotlin.coroutines.CoroutineContext"); - Object block = Proxy.newProxyInstance( - fn2Class.getClassLoader(), - new Class[] { fn2Class }, - new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if ("invoke".equals(method.getName()) && args != null && args.length == 2) { - return call.invoke(args[1]); - } - return null; - } - } - ); - Method runBlocking = Class.forName("kotlinx.coroutines.BuildersKt") - .getMethod("runBlocking$default", ctxClass, fn2Class, int.class, Object.class); - return runBlocking.invoke(null, null, block, 1, null); - } - - private void exportDiagnostics() { - runDiagnosticExport(false); - } - - private void exportDiagnosticsForGithubFeedback() { - runDiagnosticExport(true); - } - - private void runDiagnosticExport(final boolean forGithubFeedback) { - if (exportingDiagnostics || isFinishing() || isDestroyed()) return; - exportingDiagnostics = true; - setDiagnosticButtonsExporting(true, forGithubFeedback); - final String displaySnapshot = BppDiagnosticExporter.captureDisplaySnapshot(this); - final File gameRoot = resolveGameRootDir(BppBundledModpackInstaller.TARGET_PACKAGE); - final File internalWork = new File(getFilesDir(), "bpp-bundled-installer"); - diagnosticWorker.execute(new Runnable() { - @Override - public void run() { - final BppDiagnosticExporter.Saved saved = BppDiagnosticExporter.exportAndSave( - BppLauncherActivity.this, gameRoot, internalWork, displaySnapshot); - runOnUiThread(new Runnable() { - @Override - public void run() { - exportingDiagnostics = false; - setDiagnosticButtonsExporting(false, forGithubFeedback); - if (isDestroyed() || isFinishing()) return; - if (forGithubFeedback) { - showGithubFeedbackResult(saved); - } else { - showExportResult(saved); - } - } - }); - } - }); - } - - private void setDiagnosticButtonsExporting(boolean exporting, boolean forGithubFeedback) { - if (btnExportDiagnostics != null) { - btnExportDiagnostics.setEnabled(!exporting); - btnExportDiagnostics.setAlpha(exporting ? 0.55f : 1f); - btnExportDiagnostics.setText(exporting ? "正在导出诊断日志…" : "导出诊断日志"); - } - if (btnGithubFeedback != null) { - btnGithubFeedback.setEnabled(!exporting); - btnGithubFeedback.setAlpha(exporting ? 0.55f : 1f); - btnGithubFeedback.setText(exporting && forGithubFeedback ? "正在准备反馈…" : "去 GitHub 反馈"); - } - } - - private void showExportResult(BppDiagnosticExporter.Saved saved) { - if (saved == null || !saved.ok) { - String error = saved == null ? "未知错误" : saved.error; - new AlertDialog.Builder(this) - .setTitle("导出失败") - .setMessage("诊断日志没有生成,启动器仍可继续使用。\n" + error) - .setPositiveButton("关闭", null) - .show(); - return; - } - if (tvExportInfo != null) { - tvExportInfo.setVisibility(View.VISIBLE); - tvExportInfo.setText("最近导出:" + saved.displayPath); - } - try { - ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); - if (clipboard != null) { - clipboard.setPrimaryClip(ClipData.newPlainText("BPP diagnostics", saved.displayPath)); - } - } catch (Throwable ignored) { - } - StringBuilder message = new StringBuilder(); - message.append("已保存到:\n").append(saved.displayPath) - .append("\n大小:").append(saved.sizeBytes).append(" 字节") - .append("\nSHA-256:").append(saved.sha256) - .append("\n\n路径已复制。可在系统「下载」里找到该 zip。分享前请确认可以接受包内的设备标识与日志。"); - if (saved.warning != null && saved.warning.length() > 0) { - message.append("\n\n").append(saved.warning); - } - AlertDialog.Builder builder = new AlertDialog.Builder(this) - .setTitle("诊断日志已保存") - .setMessage(message.toString()) - .setNegativeButton("关闭", null); - if (saved.shareUri != null) { - builder.setPositiveButton("分享", (dialog, which) -> shareDiagnostic(saved.shareUri)); - } - builder.show(); - if (saved.shareUri != null) shareDiagnostic(saved.shareUri); - } - - private void showGithubFeedbackResult(BppDiagnosticExporter.Saved saved) { - if (saved == null || !saved.ok) { - String error = saved == null ? "未知错误" : saved.error; - new AlertDialog.Builder(this) - .setTitle("导出失败") - .setMessage("诊断日志没有生成,启动器仍可继续使用。\n" + error) - .setPositiveButton("关闭", null) - .show(); - return; - } - if (tvExportInfo != null) { - tvExportInfo.setVisibility(View.VISIBLE); - tvExportInfo.setText("最近导出:" + saved.displayPath); - } - String zipFileName = BppGithubFeedback.fileNameOnly(saved.fileName); - if (zipFileName.length() == 0) zipFileName = "(未生成)"; - final String issueUrl = BppGithubFeedback.buildIssueUrl( - installedLauncherVersion(), - BppBuildInfo.VERSION_NAME, - BppBuildInfo.COMMIT, - Build.MANUFACTURER, - Build.MODEL, - Build.VERSION.RELEASE, - Build.VERSION.SDK_INT, - joinSupportedAbis(), - zipFileName - ); - StringBuilder message = new StringBuilder(); - message.append("诊断包已保存到系统「下载」:\n") - .append(zipFileName) - .append("\n\n请先在 GitHub 页面把「下载」文件夹里的 ") - .append(zipFileName) - .append(" 拖到正文上传;本应用不会自动上传任何文件。"); - new AlertDialog.Builder(this) - .setTitle("准备 GitHub 反馈") - .setMessage(message.toString()) - .setNegativeButton("关闭", null) - .setPositiveButton("打开 GitHub", (dialog, which) -> openGithubIssue(issueUrl)) - .show(); - } - - private void openGithubIssue(String url) { - try { - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); - } catch (android.content.ActivityNotFoundException ex) { - Toast.makeText(this, "无法打开浏览器,请手动访问 GitHub Issues 并附上诊断包", Toast.LENGTH_LONG).show(); - } catch (Exception ex) { - Toast.makeText(this, "无法打开浏览器,请手动访问 GitHub Issues", Toast.LENGTH_LONG).show(); - } - } - - private String joinSupportedAbis() { - String[] abis = Build.SUPPORTED_ABIS; - if (abis == null || abis.length == 0) return ""; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < abis.length; i++) { - if (i > 0) sb.append(", "); - sb.append(abis[i]); - } - return sb.toString(); - } - - private void shareDiagnostic(Uri uri) { - if (uri == null) return; - try { - Intent share = new Intent(Intent.ACTION_SEND); - share.setType("application/zip"); - share.putExtra(Intent.EXTRA_STREAM, uri); - share.putExtra(Intent.EXTRA_SUBJECT, "BPP Android 诊断日志"); - share.putExtra(Intent.EXTRA_TEXT, "BazaarPlusPlus Android 诊断包"); - share.setClipData(ClipData.newRawUri("BPP diagnostics", uri)); - share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - Intent chooser = Intent.createChooser(share, "分享诊断日志"); - chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - startActivity(chooser); - } catch (Throwable error) { - Toast.makeText(this, "无法打开分享面板,文件仍已保存", Toast.LENGTH_LONG).show(); - } - } - - /** - * Once per launcher screen, when the bundled modpack is the upstream bridge: stage a newer - * official Managed Payload in the background. The launch never waits for it; a payload staged - * before the game starts applies on that start, otherwise on the next. - */ - private void checkOfficialPayload(File gameRootDir) { - if (officialPayloadChecked - || !new File(gameRootDir, "BepInEx/plugins/BazaarPlusPlus.BepInExBridge.dll").isFile()) { - return; - } - officialPayloadChecked = true; - final File installRoot = new File(getFilesDir(), BppBundledModpackInstaller.TARGET_PACKAGE); - final String gameVersion; - try { - gameVersion = getPackageManager() - .getPackageInfo(BppBundledModpackInstaller.TARGET_PACKAGE, 0).versionName; - } catch (Exception ex) { - notePrepare("official-payload", "skipped reason=game_not_installed"); - return; - } - updateWorker.execute(() -> { - String outcome; - try { - outcome = BppOfficialPayload.check(installRoot, gameVersion); - } catch (Exception ex) { - outcome = "failed " + ex.getClass().getSimpleName() + ": " + ex.getMessage(); - logError("Official payload check failed", ex); - } - notePrepare("official-payload", outcome); - }); - } - - private void notePrepare(String outcome, String detail) { - String text = detail == null ? "" : detail.replace('\n', ' ').replace('\r', ' '); - if (text.length() > 500) text = text.substring(0, 500); - BppDiagnosticSessionLog.note( - this, - "prepare-results.log", - BppDiagnosticBundle.nowIso() + " outcome=" + outcome + " detail=" + text - ); - } - - private void logError(String message, Throwable error) { - try { - Class logClass = Class.forName("com.bepinex.android.BepInExLog"); - Field f = logClass.getField("INSTANCE"); - Object instance = f.get(null); - logClass.getMethod("e", String.class, Throwable.class).invoke(instance, message, error); - } catch (Exception ignored) { - } - } - - private int dp(int value) { - return Math.round( - TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, - value, - getResources().getDisplayMetrics() - ) - ); - } -} - diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppLauncherUpdateChecker.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppLauncherUpdateChecker.java deleted file mode 100644 index dbfba3e..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppLauncherUpdateChecker.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.bepinex.android.bpp; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.json.JSONArray; -import org.json.JSONObject; - -/** Read-only update discovery. Installation remains an explicit user action in Android. */ -public final class BppLauncherUpdateChecker { - public static final String RELEASES_URL = - "https://github.com/TAP-APIA/bazaarplusplus-android/releases"; - private static final String API_URL = - "https://api.github.com/repos/TAP-APIA/bazaarplusplus-android/releases?per_page=100"; - private static final String APK_NAME = "BepInExLauncher-bpp-android.apk"; - private static final Pattern VERSION = Pattern.compile( - "^(?:android-v)?([0-9]{1,9})\\.([0-9]{1,9})\\.([0-9]{1,9})(?:-preview\\.([0-9]{1,9}))?$"); - private static final int MAX_RESPONSE_BYTES = 4 * 1024 * 1024; - - private BppLauncherUpdateChecker() { } - - public static final class Update { - public final String version; - public final String releaseUrl; - public final String apkUrl; - public final long apkSize; - - private Update(String tag, long size) { - version = tag.substring("android-v".length()); - // Construct from a validated tag, never navigate to an arbitrary URL in release text. - releaseUrl = RELEASES_URL + "/tag/" + tag; - apkUrl = RELEASES_URL + "/download/" + tag + "/" + APK_NAME; - apkSize = size; - } - } - - public static int compareVersions(String left, String right) { - long[] a = parseVersion(left); - long[] b = parseVersion(right); - for (int i = 0; i < a.length; i++) { - int result = Long.compare(a[i], b[i]); - if (result != 0) return result; - } - return 0; - } - - private static long[] parseVersion(String text) { - Matcher match = VERSION.matcher(text == null ? "" : text); - if (!match.matches()) throw new IllegalArgumentException("Unsupported launcher version"); - return new long[] { - Long.parseLong(match.group(1)), Long.parseLong(match.group(2)), - Long.parseLong(match.group(3)), - match.group(4) == null ? Long.MAX_VALUE : Long.parseLong(match.group(4)) - }; - } - - /** Includes prereleases, ignores drafts/unrelated tags/releases without an uploaded APK. */ - public static Update selectUpdate(String json, String currentVersion) throws Exception { - parseVersion(currentVersion); - JSONArray releases = new JSONArray(json); - Update newest = null; - for (int i = 0; i < releases.length(); i++) { - JSONObject release = releases.getJSONObject(i); - if (release.optBoolean("draft", true)) continue; - String tag = release.optString("tag_name", ""); - if (!tag.startsWith("android-v") || !VERSION.matcher(tag).matches()) continue; - if (compareVersions(tag, currentVersion) <= 0) continue; - JSONArray assets = release.optJSONArray("assets"); - if (assets == null) continue; - long apkSize = 0; - for (int j = 0; j < assets.length(); j++) { - JSONObject asset = assets.getJSONObject(j); - String expectedUrl = RELEASES_URL + "/download/" + tag + "/" + APK_NAME; - if (APK_NAME.equals(asset.optString("name")) - && "uploaded".equals(asset.optString("state")) - && asset.optLong("size", 0) > 0 - && expectedUrl.equals(asset.optString("browser_download_url"))) { - apkSize = asset.optLong("size", 0); - break; - } - } - if (apkSize > 0 && (newest == null || compareVersions(tag, newest.version) > 0)) { - newest = new Update(tag, apkSize); - } - } - return newest; - } - - public static Update check(String currentVersion) throws Exception { - HttpURLConnection connection = (HttpURLConnection) new URL(API_URL).openConnection(); - connection.setConnectTimeout(8000); - connection.setReadTimeout(8000); - connection.setInstanceFollowRedirects(false); - connection.setRequestProperty("Accept", "application/vnd.github+json"); - connection.setRequestProperty("X-GitHub-Api-Version", "2022-11-28"); - connection.setRequestProperty("User-Agent", "BazaarPlusPlus-Android-Launcher"); - try { - int status = connection.getResponseCode(); - if (status == 403 || status == 429) throw new IOException("GitHub 请求受限,请稍后重试"); - if (status != 200) throw new IOException("GitHub HTTP " + status); - try (InputStream input = connection.getInputStream(); - ByteArrayOutputStream output = new ByteArrayOutputStream()) { - byte[] buffer = new byte[8192]; - int length; - while ((length = input.read(buffer)) != -1) { - if (Thread.currentThread().isInterrupted()) throw new IOException("检查已取消"); - if (output.size() + length > MAX_RESPONSE_BYTES) throw new IOException("更新响应过大"); - output.write(buffer, 0, length); - } - return selectUpdate(new String(output.toByteArray(), StandardCharsets.UTF_8), currentVersion); - } - } finally { - connection.disconnect(); - } - } -} diff --git a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppOfficialPayload.java b/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppOfficialPayload.java deleted file mode 100644 index ac4caa0..0000000 --- a/android-port/tools/bpp-launcher/src/com/bepinex/android/bpp/BppOfficialPayload.java +++ /dev/null @@ -1,292 +0,0 @@ -package com.bepinex.android.bpp; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.security.MessageDigest; -import java.util.Enumeration; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import org.json.JSONObject; - -/** - * Upstream BazaarPlusPlus's published Android Managed Payload, fetched by the launcher because - * the game process's CoreCLR cannot make TLS connections. It reads upstream's release manifest, - * and when the release is newer than the installed payload and built for the installed game and - * the same non-managed payload, downloads it, checks the manifest's size and SHA-256, and stages - * it under the Data Root's {@code Updates/}. The BepInEx bridge verifies the signature - * and the binding there, and upstream's Updater swaps it in on the next game start - * (android-port/upstream-host/README.md). - */ -public final class BppOfficialPayload { - public static final String MANIFEST_URL = - "https://cdn.bazaarplusplus.com/installer/latest/mod/android-aarch64.json"; - static final String DOWNLOAD_PREFIX = "https://cdn.bazaarplusplus.com/installer/"; - static final String PLATFORM = "android-aarch64"; - static final String DATA_ROOT = "BazaarPlusPlusV6"; - static final String UPDATES = "Updates"; - /** Shared with BazaarPlusPlus.OfficialPayload.RejectedVersions. */ - static final String REJECTED_FILE = "bpp-official-payload.rejected"; - static final String INSTALLED_MANIFEST = "MelonLoader/Mods/BazaarPlusPlus.managed-manifest.txt"; - static final String VERSION_FILE = "MelonLoader/Mods/BazaarPlusPlus.version"; - - private static final long MAX_PAYLOAD_BYTES = 64L * 1024 * 1024; - private static final int MAX_MANIFEST_BYTES = 1024 * 1024; - private static final Pattern VERSION = - Pattern.compile("^(0|[1-9][0-9]{0,8})\\.(0|[1-9][0-9]{0,8})\\.(0|[1-9][0-9]{0,8})"); - private static final Pattern SHA256 = Pattern.compile("^[0-9a-f]{64}$"); - - private BppOfficialPayload() { } - - /** The release manifest's Android Managed Payload. */ - public static final class Release { - public final String version; - public final String url; - public final long size; - public final String sha256; - public final String gameVersion; - public final String nonManagedPayloadDigest; - public final int historyDatabaseUserVersion; - - Release(String version, String url, long size, String sha256, String gameVersion, - String nonManagedPayloadDigest, int historyDatabaseUserVersion) { - this.version = version; - this.url = url; - this.size = size; - this.sha256 = sha256; - this.gameVersion = gameVersion; - this.nonManagedPayloadDigest = nonManagedPayloadDigest; - this.historyDatabaseUserVersion = historyDatabaseUserVersion; - } - } - - public static Release parseRelease(String json) throws IOException { - try { - JSONObject root = new JSONObject(json); - JSONObject platform = root.getJSONObject("downloads").getJSONObject(PLATFORM); - JSONObject payload = platform.getJSONObject("managedPayload"); - String version = root.getString("version"); - String url = payload.getString("url"); - long size = payload.getLong("size"); - String sha256 = payload.getString("sha256").toLowerCase(Locale.ROOT); - String digest = platform.getString("nonManagedPayloadDigest").toLowerCase(Locale.ROOT); - if (!isVersion(version) || version.split("\\.").length != 3) - throw new IOException("Unsupported payload version"); - // Only upstream's own CDN, never a URL the manifest could point anywhere else. - if (!url.startsWith(DOWNLOAD_PREFIX) || url.contains("..") || url.contains("?")) - throw new IOException("Unexpected payload URL"); - if (size <= 0 || size > MAX_PAYLOAD_BYTES) throw new IOException("Unexpected payload size"); - if (!SHA256.matcher(sha256).matches() || !SHA256.matcher(digest).matches()) - throw new IOException("Unexpected payload digest"); - return new Release(version, url, size, sha256, - platform.getJSONObject("game").getString("gameVersion"), digest, - platform.getInt("historyDatabaseUserVersion")); - } catch (org.json.JSONException ex) { - throw new IOException("Unreadable release manifest", ex); - } - } - - /** Compares the leading {@code major.minor.patch}, as upstream's ManagedPayloadVersion does. */ - static int compareVersions(String left, String right) { - long[] a = parseVersion(left); - long[] b = parseVersion(right); - for (int i = 0; i < 3; i++) { - int result = Long.compare(a[i], b[i]); - if (result != 0) return result; - } - return 0; - } - - private static boolean isVersion(String text) { - return text != null && VERSION.matcher(text.trim()).find(); - } - - private static long[] parseVersion(String text) { - Matcher match = VERSION.matcher(text == null ? "" : text.trim()); - if (!match.find()) throw new IllegalArgumentException("Unsupported payload version"); - return new long[] { - Long.parseLong(match.group(1)), Long.parseLong(match.group(2)), Long.parseLong(match.group(3)) - }; - } - - /** The installed payload's version: its manifest's, else its version file's; null if none. */ - static String installedVersion(File installRoot) throws IOException { - String manifestVersion = installedManifestField(installRoot, "version"); - if (manifestVersion != null) return manifestVersion; - File versionFile = new File(installRoot, VERSION_FILE); - if (!versionFile.isFile()) return null; - String text = new String(Files.readAllBytes(versionFile.toPath()), StandardCharsets.UTF_8).trim(); - return isVersion(text) ? text : null; - } - - private static String installedManifestField(File installRoot, String key) throws IOException { - File manifest = new File(installRoot, INSTALLED_MANIFEST); - if (!manifest.isFile()) return null; - for (String line : new String(Files.readAllBytes(manifest.toPath()), StandardCharsets.UTF_8).split("\n")) { - if (line.startsWith(key + " ")) return line.substring(key.length() + 1).trim(); - } - return null; - } - - static boolean isRejected(File installRoot, String version) throws IOException { - File rejected = new File(new File(installRoot, DATA_ROOT), REJECTED_FILE); - if (!rejected.isFile()) return false; - for (String line : new String(Files.readAllBytes(rejected.toPath()), StandardCharsets.UTF_8).split("\n")) { - if (line.split(" ", 2)[0].equals(version)) return true; - } - return false; - } - - /** Why this release is not staged, or null to stage it. */ - static String skipReason(Release release, File installRoot, String gameVersion) throws IOException { - if (!release.gameVersion.equals(gameVersion)) return "game_version"; - String installed = installedVersion(installRoot); - if (installed != null && compareVersions(release.version, installed) <= 0) return "up_to_date"; - if (isRejected(installRoot, release.version)) return "rejected"; - if (stagedDirectory(installRoot, release.version).isDirectory()) return "staged"; - // Upstream's Updater refuses these too; checking here saves the download. - String digest = installedManifestField(installRoot, "non-managed-payload-digest"); - if (digest != null && !digest.equals(release.nonManagedPayloadDigest)) return "non_managed_payload"; - String history = installedManifestField(installRoot, "history-database-user-version"); - if (history != null && !history.equals(String.valueOf(release.historyDatabaseUserVersion))) - return "history_database"; - return null; - } - - static File stagedDirectory(File installRoot, String version) { - return new File(new File(new File(installRoot, DATA_ROOT), UPDATES), version); - } - - /** - * Extracts a payload zip as {@code Updates/}: the manifest, its signature, and files - * under {@code files/} that upstream's MelonLoader host may write. Anything else refuses the - * whole zip. Published only once complete, by renaming the partial directory. - */ - static void stage(File zip, File installRoot, String version) throws IOException { - File target = stagedDirectory(installRoot, version); - File partial = new File(target.getParentFile(), "." + version + ".partial"); - deleteRecursively(partial); - if (!partial.mkdirs()) throw new IOException("Cannot create " + partial); - try (ZipFile archive = new ZipFile(zip)) { - Enumeration entries = archive.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (entry.isDirectory()) continue; - String name = entry.getName(); - if (!isStagedEntry(name)) throw new IOException("Unexpected payload entry " + name); - File destination = new File(partial, name); - File parent = destination.getParentFile(); - if (parent != null && !parent.isDirectory() && !parent.mkdirs()) - throw new IOException("Cannot create " + parent); - try (InputStream input = archive.getInputStream(entry); - OutputStream output = new FileOutputStream(destination)) { - copy(input, output, MAX_PAYLOAD_BYTES, null); - } - } - if (!new File(partial, "manifest.txt").isFile() || !new File(partial, "manifest.txt.minisig").isFile()) - throw new IOException("Payload manifest missing"); - if (!partial.renameTo(target)) throw new IOException("Cannot publish " + target); - } catch (IOException ex) { - deleteRecursively(partial); - throw ex; - } - } - - static boolean isStagedEntry(String name) { - if ("manifest.txt".equals(name) || "manifest.txt.minisig".equals(name)) return true; - for (String directory : new String[] {"files/MelonLoader/Mods/", "files/MelonLoader/UserLibs/"}) { - if (!name.startsWith(directory)) continue; - String file = name.substring(directory.length()); - return !file.isEmpty() && !".".equals(file) && !"..".equals(file) - && file.indexOf('/') < 0 && file.indexOf('\\') < 0; - } - return false; - } - - /** - * One check: fetch the manifest, stage the release when it applies, and say what happened. - * Runs off the UI thread; never throws for an ordinary skip. - */ - public static String check(File installRoot, String gameVersion) throws Exception { - Release release = parseRelease(new String(fetch(MANIFEST_URL, MAX_MANIFEST_BYTES, null), StandardCharsets.UTF_8)); - String skip = skipReason(release, installRoot, gameVersion); - if (skip != null) return "skipped version=" + release.version + " reason=" + skip; - - File updates = stagedDirectory(installRoot, release.version).getParentFile(); - if (!updates.isDirectory() && !updates.mkdirs()) throw new IOException("Cannot create " + updates); - File download = new File(updates, "." + release.version + ".zip"); - try { - MessageDigest sha = MessageDigest.getInstance("SHA-256"); - try (OutputStream output = new FileOutputStream(download)) { - long written = copy(openStream(release.url), output, release.size, sha); - if (written != release.size) throw new IOException("Payload size mismatch"); - } - if (!toHex(sha.digest()).equals(release.sha256)) throw new IOException("Payload SHA-256 mismatch"); - stage(download, installRoot, release.version); - } finally { - if (download.exists() && !download.delete()) download.deleteOnExit(); - } - return "staged version=" + release.version; - } - - private static byte[] fetch(String url, int limit, MessageDigest digest) throws IOException { - try (InputStream input = openStream(url); ByteArrayOutputStream output = new ByteArrayOutputStream()) { - copy(input, output, limit, digest); - return output.toByteArray(); - } - } - - private static InputStream openStream(String url) throws IOException { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setConnectTimeout(8000); - connection.setReadTimeout(15000); - connection.setInstanceFollowRedirects(false); - connection.setRequestProperty("User-Agent", "BazaarPlusPlus-Android-Launcher"); - int status = connection.getResponseCode(); - if (status != 200) { - connection.disconnect(); - throw new IOException("HTTP " + status + " for " + url); - } - return connection.getInputStream(); - } - - private static long copy(InputStream input, OutputStream output, long limit, MessageDigest digest) - throws IOException { - try (InputStream in = input) { - byte[] buffer = new byte[64 * 1024]; - long total = 0; - int length; - while ((length = in.read(buffer)) != -1) { - if (Thread.currentThread().isInterrupted()) throw new IOException("Cancelled"); - total += length; - if (total > limit) throw new IOException("Payload larger than expected"); - if (digest != null) digest.update(buffer, 0, length); - output.write(buffer, 0, length); - } - return total; - } - } - - private static String toHex(byte[] bytes) { - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte value : bytes) builder.append(String.format(Locale.ROOT, "%02x", value)); - return builder.toString(); - } - - private static void deleteRecursively(File file) { - if (!file.exists()) return; - File[] children = file.listFiles(); - if (children != null) for (File child : children) deleteRecursively(child); - if (!file.delete()) file.deleteOnExit(); - } -} diff --git a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppBundledModpackInstallerTests.java b/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppBundledModpackInstallerTests.java deleted file mode 100644 index edfe906..0000000 --- a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppBundledModpackInstallerTests.java +++ /dev/null @@ -1,424 +0,0 @@ -package com.bepinex.android.bpp; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.security.MessageDigest; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -public final class BppBundledModpackInstallerTests { - - private static final String[] REQUIRED = new String[] { - "plugins/BazaarPlusPlus.dll", - "plugins/BazaarPlusPlus.Localization.dll", - "plugins/BazaarPlusPlus.ModApi.dll", - "plugins/BazaarPlusPlus.Storage.dll", - "plugins/Bpp.Managed.MessagePack.dll", - "plugins/Bpp.Managed.MessagePack.Annotations.dll", - "plugins/Bpp.Managed.StringTools.dll", - "plugins/Microsoft.Data.Sqlite.dll", - "plugins/SQLitePCLRaw.core.dll", - "plugins/SQLitePCLRaw.provider.e_sqlite3.dll", - "plugins/SQLitePCLRaw.batteries_v2.dll", - "plugins/libe_sqlite3.so", - "core/BepInEx.Unity.IL2CPP.dll", - "core/BepInEx.Core.dll", - "core/Il2CppInterop.Runtime.dll", - "core/Il2CppInterop.HarmonySupport.dll" - }; - - // The BepInEx bridge with upstream's published payload bundled (android-port/upstream-host). - private static final String[] REQUIRED_UPSTREAM = new String[] { - "plugins/BazaarPlusPlus.BepInExBridge.dll", - "plugins/BazaarPlusPlus.OfficialPayload.dll", - "plugins/BazaarPlusPlus.OfficialPayload.zip", - "plugins/MelonLoader.dll", - "plugins/libe_sqlite3.so", - "core/BepInEx.Unity.IL2CPP.dll", - "core/BepInEx.Core.dll", - "core/Il2CppInterop.Runtime.dll", - "core/Il2CppInterop.HarmonySupport.dll" - }; - - public static void main(String[] args) throws Exception { - testFirstInstallAndConfigSeeding(); - testUpgradePreservesUserConfigHistoryAndMetadataAndRetiresOldOwnedOnly(); - testRepairFixesMissingOrCorruptedFile(); - testRejectsTraversalUnlistedAndCorruptArchivesWithoutMutatingTarget(); - testInterruptedInProgressStateRequiresRepair(); - testSwitchToUpstreamPayloadRetiresForkPlugin(); - testRejectsIncompletePluginPayload(); - System.out.println("PASS: all BppBundledModpackInstaller tests succeeded."); - } - - private static void testFirstInstallAndConfigSeeding() throws Exception { - File root = Files.createTempDirectory("bpp-installer-first").toFile(); - File gameRoot = new File(root, "game"); - File workDir = new File(root, "work"); - FixtureBundle bundle = createFixtureBundle("v1", null); - byte[] bepZip = createSingleEntryZip("config/BepInEx.cfg", "[Caching]\nEnableAssemblyCache = true\n"); - - BppBundledModpackInstaller.Manifest manifest = BppBundledModpackInstaller.parseManifest( - new ByteArrayInputStream(bundle.manifestBytes) - ); - BppBundledModpackInstaller.StatusReport initial = BppBundledModpackInstaller.inspectStatus( - gameRoot, - workDir, - manifest, - true - ); - assertTrue(initial.kind == BppBundledModpackInstaller.StatusKind.NEEDS_INSTALL, "Expected NEEDS_INSTALL"); - - BppBundledModpackInstaller.StatusReport installed = BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(bundle.manifestBytes), - () -> new ByteArrayInputStream(bundle.zipBytes), - () -> new ByteArrayInputStream(bepZip), - false, - null - ); - assertTrue(installed.isReady(), "Expected READY after first install"); - assertTrue(new File(gameRoot, "BepInEx/config/BepInEx.cfg").isFile(), "BepInEx.cfg must be seeded in runtime config"); - assertTrue(new File(gameRoot, "modpacks/bpp/config/BepInEx.cfg").isFile(), "BepInEx.cfg must be seeded in modpack config"); - assertTrue(new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.dll").isFile(), "Runtime plugin missing"); - assertTrue(new File(gameRoot, "modpacks/bpp/plugins/BazaarPlusPlus.dll").isFile(), "Modpack plugin missing"); - } - - private static void testUpgradePreservesUserConfigHistoryAndMetadataAndRetiresOldOwnedOnly() throws Exception { - File root = Files.createTempDirectory("bpp-installer-upgrade").toFile(); - File gameRoot = new File(root, "game"); - File workDir = new File(root, "work"); - - Map v1Extras = new LinkedHashMap(); - v1Extras.put("plugins/RetiredOwned.dll", "retired-v1"); - v1Extras.put("plugins/UserEditedOwned.dll", "owned-v1"); - FixtureBundle v1 = createFixtureBundle("v1", v1Extras); - - BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(v1.manifestBytes), - () -> new ByteArrayInputStream(v1.zipBytes), - null, - false, - null - ); - - File userCfg = new File(gameRoot, "BepInEx/config/BazaarPlusPlus.cfg"); - userCfg.getParentFile().mkdirs(); - Files.write(userCfg.toPath(), "[TouchDock]\nAnchorX = 0.25\nAnchorY = 0.75\n".getBytes(StandardCharsets.UTF_8)); - - File thirdPartyDll = new File(gameRoot, "BepInEx/plugins/ThirdPartyHelper.dll"); - Files.write(thirdPartyDll.toPath(), "third-party-keep".getBytes(StandardCharsets.UTF_8)); - - File userEditedOwned = new File(gameRoot, "BepInEx/plugins/UserEditedOwned.dll"); - Files.write(userEditedOwned.toPath(), "user-modified-keep".getBytes(StandardCharsets.UTF_8)); - - File customMeta = new File(gameRoot, "modpacks/bpp/modpack.json"); - Files.write( - customMeta.toPath(), - "{\"name\":\"bpp\",\"packageName\":\"com.tempogames.thebazaar\",\"createdAt\":12345,\"modCount\":99,\"mods\":{\"Custom.dll\":{\"enabled\":false}}}".getBytes(StandardCharsets.UTF_8) - ); - - FixtureBundle v2 = createFixtureBundle("v2-updated", null); - BppBundledModpackInstaller.Manifest v2Manifest = BppBundledModpackInstaller.parseManifest( - new ByteArrayInputStream(v2.manifestBytes) - ); - BppBundledModpackInstaller.StatusReport beforeUpgrade = BppBundledModpackInstaller.inspectStatus( - gameRoot, - workDir, - v2Manifest, - true - ); - assertTrue(beforeUpgrade.kind == BppBundledModpackInstaller.StatusKind.NEEDS_UPDATE, "Expected NEEDS_UPDATE"); - - BppBundledModpackInstaller.StatusReport upgraded = BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(v2.manifestBytes), - () -> new ByteArrayInputStream(v2.zipBytes), - null, - false, - null - ); - assertTrue(upgraded.isReady(), "Expected READY after upgrade"); - - String cfgText = new String(Files.readAllBytes(userCfg.toPath()), StandardCharsets.UTF_8); - assertTrue(cfgText.contains("AnchorX = 0.25"), "User config must remain untouched"); - String syncedModpackCfg = new String( - Files.readAllBytes(new File(gameRoot, "modpacks/bpp/config/BazaarPlusPlus.cfg").toPath()), - StandardCharsets.UTF_8 - ); - assertTrue(syncedModpackCfg.contains("AnchorX = 0.25"), "User config must be additively synced to modpacks/bpp/config"); - assertTrue(thirdPartyDll.isFile(), "Third-party plugin must remain untouched"); - assertTrue(!new File(gameRoot, "BepInEx/plugins/RetiredOwned.dll").exists(), "Unmodified retired owned file should be removed"); - assertTrue(!new File(gameRoot, "modpacks/bpp/plugins/RetiredOwned.dll").exists(), "Unmodified retired owned file in modpack should be removed"); - assertTrue(userEditedOwned.isFile(), "Modified retired file must not be deleted"); - String metaText = new String(Files.readAllBytes(customMeta.toPath()), StandardCharsets.UTF_8); - assertTrue(metaText.contains("\"Custom.dll\""), "Existing modpack metadata customizations must be preserved"); - assertTrue(metaText.contains("\"modCount\":11"), "modCount should update to current managed DLL count"); - } - - private static void testRepairFixesMissingOrCorruptedFile() throws Exception { - File root = Files.createTempDirectory("bpp-installer-repair").toFile(); - File gameRoot = new File(root, "game"); - File workDir = new File(root, "work"); - FixtureBundle bundle = createFixtureBundle("v1", null); - BppBundledModpackInstaller.Manifest manifest = BppBundledModpackInstaller.parseManifest( - new ByteArrayInputStream(bundle.manifestBytes) - ); - BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(bundle.manifestBytes), - () -> new ByteArrayInputStream(bundle.zipBytes), - null, - false, - null - ); - - File runtimePlugin = new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.dll"); - Files.write(runtimePlugin.toPath(), "corrupted".getBytes(StandardCharsets.UTF_8)); - - BppBundledModpackInstaller.StatusReport damaged = BppBundledModpackInstaller.inspectStatus( - gameRoot, - workDir, - manifest, - true - ); - assertTrue(damaged.kind == BppBundledModpackInstaller.StatusKind.NEEDS_REPAIR, "Expected NEEDS_REPAIR for corrupted plugin"); - - BppBundledModpackInstaller.StatusReport repaired = BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(bundle.manifestBytes), - () -> new ByteArrayInputStream(bundle.zipBytes), - null, - false, - null - ); - assertTrue(repaired.isReady(), "Expected READY after repair"); - } - - private static void testRejectsTraversalUnlistedAndCorruptArchivesWithoutMutatingTarget() throws Exception { - File root = Files.createTempDirectory("bpp-installer-reject").toFile(); - File gameRoot = new File(root, "game"); - File workDir = new File(root, "work"); - FixtureBundle bundle = createFixtureBundle("v1", null); - - byte[] traversalZip = createSingleEntryZip("../escape.dll", "bad"); - assertRejected(() -> BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(bundle.manifestBytes), - () -> new ByteArrayInputStream(traversalZip), - null, - true, - null - ), "Traversal archive must be rejected"); - assertTrue(!new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.dll").exists(), "Rejected archive must not write target"); - - byte[] configZip = createSingleEntryZip("config/BazaarPlusPlus.cfg", "bad"); - assertRejected(() -> BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(bundle.manifestBytes), - () -> new ByteArrayInputStream(configZip), - null, - true, - null - ), "Config entry in archive must be rejected"); - } - - private static void testInterruptedInProgressStateRequiresRepair() throws Exception { - File root = Files.createTempDirectory("bpp-installer-interrupted").toFile(); - File gameRoot = new File(root, "game"); - File workDir = new File(root, "work"); - FixtureBundle bundle = createFixtureBundle("v1", null); - BppBundledModpackInstaller.Manifest manifest = BppBundledModpackInstaller.parseManifest( - new ByteArrayInputStream(bundle.manifestBytes) - ); - BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(bundle.manifestBytes), - () -> new ByteArrayInputStream(bundle.zipBytes), - null, - false, - null - ); - File stateFile = new File(workDir, BppBundledModpackInstaller.STATE_FILE_NAME); - Files.write( - stateFile.toPath(), - ("status\tin_progress\nbundle_id\t" + manifest.bundleId + "\n").getBytes(StandardCharsets.UTF_8) - ); - BppBundledModpackInstaller.StatusReport status = BppBundledModpackInstaller.inspectStatus( - gameRoot, - workDir, - manifest, - true - ); - assertTrue(status.kind == BppBundledModpackInstaller.StatusKind.NEEDS_REPAIR, "in_progress state must require repair"); - } - - private interface ThrowingRunnable { - void run() throws Exception; - } - - private static void assertRejected(ThrowingRunnable action, String message) { - boolean rejected = false; - try { - action.run(); - } catch (Exception ex) { - rejected = true; - } - assertTrue(rejected, message); - } - - private static void assertTrue(boolean condition, String message) { - if (!condition) { - throw new IllegalStateException(message); - } - } - - private static final class FixtureBundle { - final byte[] zipBytes; - final byte[] manifestBytes; - - FixtureBundle(byte[] zipBytes, byte[] manifestBytes) { - this.zipBytes = zipBytes; - this.manifestBytes = manifestBytes; - } - } - - private static void testSwitchToUpstreamPayloadRetiresForkPlugin() throws Exception { - File root = Files.createTempDirectory("bpp-installer-switch").toFile(); - File gameRoot = new File(root, "game"); - File workDir = new File(root, "work"); - FixtureBundle fork = createFixtureBundle("fork", null); - BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(fork.manifestBytes), - () -> new ByteArrayInputStream(fork.zipBytes), - null, - false, - null - ); - File history = new File(gameRoot, "BazaarPlusPlusV6/bazaarplusplus.db"); - history.getParentFile().mkdirs(); - Files.write(history.toPath(), "history-keep".getBytes(StandardCharsets.UTF_8)); - - FixtureBundle upstream = createFixtureBundle("upstream", null, REQUIRED_UPSTREAM); - BppBundledModpackInstaller.StatusReport switched = BppBundledModpackInstaller.installOrUpdate( - gameRoot, - workDir, - () -> new ByteArrayInputStream(upstream.manifestBytes), - () -> new ByteArrayInputStream(upstream.zipBytes), - null, - false, - null - ); - assertTrue(switched.isReady(), "Expected READY after switching to the upstream payload"); - assertTrue(new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.BepInExBridge.dll").isFile(), "Bridge plugin missing"); - assertTrue(!new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.dll").exists(), "Fork plugin must be retired"); - assertTrue(!new File(gameRoot, "BepInEx/plugins/Bpp.Managed.MessagePack.dll").exists(), "Fork codec must be retired"); - assertTrue(!new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.Storage.dll").exists(), - "Fork storage must be retired: the payload carries its own in MelonLoader/UserLibs"); - assertTrue(new File(gameRoot, "BepInEx/plugins/BazaarPlusPlus.OfficialPayload.zip").isFile(), "Bundled payload missing"); - assertTrue(history.isFile(), "History database must survive the switch"); - } - - private static void testRejectsIncompletePluginPayload() throws Exception { - String[] partial = new String[REQUIRED_UPSTREAM.length - 1]; - int i = 0; - for (String path : REQUIRED_UPSTREAM) { - if (!path.equals("plugins/MelonLoader.dll")) { - partial[i++] = path; - } - } - FixtureBundle bundle = createFixtureBundle("partial", null, partial); - try { - BppBundledModpackInstaller.parseManifest(new ByteArrayInputStream(bundle.manifestBytes)); - } catch (IOException expected) { - assertTrue(expected.getMessage().contains("no complete plugin payload"), "Unexpected error: " + expected.getMessage()); - return; - } - throw new AssertionError("A payload missing MelonLoader.dll must be rejected"); - } - - private static FixtureBundle createFixtureBundle(String tag, Map extras) throws Exception { - return createFixtureBundle(tag, extras, REQUIRED); - } - - private static FixtureBundle createFixtureBundle( - String tag, - Map extras, - String[] required - ) throws Exception { - Map files = new LinkedHashMap(); - files.put( - "modpack.json", - "{\"name\":\"bpp\",\"packageName\":\"com.tempogames.thebazaar\",\"createdAt\":1,\"modCount\":11,\"createShortcut\":false}" - .getBytes(StandardCharsets.UTF_8) - ); - for (String path : required) { - files.put(path, (path + ":" + tag).getBytes(StandardCharsets.UTF_8)); - } - if (extras != null) { - for (Map.Entry entry : extras.entrySet()) { - files.put(entry.getKey(), entry.getValue().getBytes(StandardCharsets.UTF_8)); - } - } - ByteArrayOutputStream zipBuffer = new ByteArrayOutputStream(); - try (ZipOutputStream zos = new ZipOutputStream(zipBuffer)) { - for (Map.Entry entry : files.entrySet()) { - zos.putNextEntry(new ZipEntry(entry.getKey())); - zos.write(entry.getValue()); - zos.closeEntry(); - } - } - byte[] zipBytes = zipBuffer.toByteArray(); - String bundleId = sha256Hex(zipBytes); - StringBuilder manifest = new StringBuilder(); - manifest.append("bundle_id\t").append(bundleId).append("\t6.0.0-").append(tag).append('\n'); - for (Map.Entry entry : files.entrySet()) { - manifest.append("file\t") - .append(entry.getKey()) - .append('\t') - .append(entry.getValue().length) - .append('\t') - .append(sha256Hex(entry.getValue())) - .append('\n'); - } - return new FixtureBundle(zipBytes, manifest.toString().getBytes(StandardCharsets.UTF_8)); - } - - private static byte[] createSingleEntryZip(String name, String content) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try (ZipOutputStream zos = new ZipOutputStream(out)) { - zos.putNextEntry(new ZipEntry(name)); - zos.write(content.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - } - return out.toByteArray(); - } - - private static String sha256Hex(byte[] bytes) throws Exception { - byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); - StringBuilder sb = new StringBuilder(digest.length * 2); - for (byte b : digest) { - sb.append(Character.forDigit((b >> 4) & 0xF, 16)); - sb.append(Character.forDigit(b & 0xF, 16)); - } - return sb.toString(); - } -} diff --git a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppDiagnosticBundleTests.java b/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppDiagnosticBundleTests.java deleted file mode 100644 index 9562e2c..0000000 --- a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppDiagnosticBundleTests.java +++ /dev/null @@ -1,338 +0,0 @@ -package com.bepinex.android.bpp; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -public final class BppDiagnosticBundleTests { - - public static void main(String[] args) throws Exception { - testIncludesLogsConfigsAndOmitsBinariesDatabasesSecrets(); - testTailsLargeLogsAndRejectsTraversal(); - testRedactsPreferenceSecretsFromStateTree(); - testElfAlignment(); - testLogcatCommandsDoNotClear(); - testAppendCappedAndCaptureProcess(); - testTreeListsPlugins(); - testReadmeExplainsTheZip(); - testGenerationStageAndLoggingConfig(); - testExitReasonNamesAndDirectoryListing(); - testPreferenceProtoKeys(); - System.out.println("PASS: all BppDiagnosticBundle tests succeeded."); - } - - private static void testIncludesLogsConfigsAndOmitsBinariesDatabasesSecrets() throws Exception { - File root = Files.createTempDirectory("bpp-diag-scan").toFile(); - File game = new File(root, "game"); - write(new File(game, "BepInEx/LogOutput.log"), "plugin.initialization.succeeded\n"); - write(new File(game, "BepInEx/bpp-startup-trace.log"), "trace\n"); - write(new File(game, "BepInEx/config/BazaarPlusPlus.cfg"), "[OverlayUI]\nScalePercent = 100\n"); - write(new File(game, "modpacks/bpp/modpack.json"), "{\"name\":\"bpp\"}\n"); - write(new File(game, "modpacks/bpp/logs/mod.log"), "mod-log\n"); - write(new File(game, "PersistentData/tombstone_01"), "DEBUG tombstone\n"); - write(new File(game, "Player.log"), "Unity Player\n"); - write(new File(game, "notes.txt"), "not a log\n"); - write(new File(game, "BepInEx/plugins/BazaarPlusPlus.dll"), "MZ-not-really"); - write(new File(game, "BazaarPlusPlusV6/history.db"), "sqlite-bytes"); - write(new File(game, "secrets/release.keystore"), "do-not-pack"); - write(new File(game, "BepInEx/config/my-password.txt"), "hidden"); - File outside = new File(root, "outside.txt"); - write(outside, "escaped"); - Files.createSymbolicLink(new File(game, "escape.log").toPath(), outside.toPath()); - - File zip = new File(root, "out.zip"); - BppDiagnosticBundle.Request request = new BppDiagnosticBundle.Request( - "readme-body", - Arrays.asList(new BppDiagnosticBundle.TextEntry("device/build.txt", "model=test")), - Arrays.asList(new BppDiagnosticBundle.ScanRoot(game, "collected/game-root")), - Arrays.asList(new BppDiagnosticBundle.ExtraFile(new File(game, "missing.log"), "logcat/missing.log", true)) - ); - BppDiagnosticBundle.Result result = BppDiagnosticBundle.write(zip, request, 1024, 1024, 1024 * 1024, 100); - assertTrue(result.includedFiles > 0, "expected included files"); - String log = entry(zip, "collected/game-root/BepInEx/LogOutput.log"); - assertTrue(log.contains("plugin.initialization.succeeded"), "LogOutput missing"); - assertTrue(entry(zip, "collected/game-root/BepInEx/config/BazaarPlusPlus.cfg").contains("ScalePercent"), "cfg missing"); - assertTrue(entry(zip, "collected/game-root/modpacks/bpp/modpack.json").contains("bpp"), "modpack.json missing"); - assertTrue(entry(zip, "collected/game-root/PersistentData/tombstone_01").contains("tombstone"), "tombstone missing"); - assertTrue(entry(zip, "collected/game-root/Player.log").contains("Unity Player"), "Player.log missing"); - assertTrue(entry(zip, "device/build.txt").contains("model=test"), "inline text missing"); - assertMissing(zip, "collected/game-root/notes.txt"); - assertMissing(zip, "collected/game-root/BepInEx/plugins/BazaarPlusPlus.dll"); - assertMissing(zip, "collected/game-root/BazaarPlusPlusV6/history.db"); - assertMissing(zip, "collected/game-root/secrets/release.keystore"); - assertMissing(zip, "collected/game-root/BepInEx/config/my-password.txt"); - assertMissing(zip, "collected/game-root/escape.log"); - String manifest = entry(zip, "manifest.txt"); - assertTrue(manifest.contains("[unavailable]"), "manifest unavailable section missing"); - assertTrue(manifest.contains("logcat/missing.log"), "missing extra not recorded"); - assertTrue(manifest.contains("database"), "database omit not recorded"); - assertTrue(manifest.contains("sensitive-name"), "keystore omit not recorded"); - assertTrue(manifest.contains("symlink-escape"), "symlink escape not recorded"); - assertTrue(manifest.contains("skipped-heavy-dir"), "plugins dir should be listed as heavy"); - assertTrue(entry(zip, "README.txt").equals("readme-body"), "readme was replaced"); - } - - private static void testTailsLargeLogsAndRejectsTraversal() throws Exception { - File root = Files.createTempDirectory("bpp-diag-tail").toFile(); - File log = new File(root, "LogOutput.log"); - byte[] body = new byte[300]; - java.util.Arrays.fill(body, (byte) 'x'); - System.arraycopy("HEAD".getBytes(StandardCharsets.UTF_8), 0, body, 0, 4); - byte[] marker = "TAILMARKER".getBytes(StandardCharsets.UTF_8); - System.arraycopy(marker, 0, body, body.length - marker.length, marker.length); - Files.write(log.toPath(), body); - File zip = new File(root, "out.zip"); - BppDiagnosticBundle.write( - zip, - new BppDiagnosticBundle.Request( - "r", - Arrays.asList(new BppDiagnosticBundle.TextEntry("../evil.txt", "nope")), - Arrays.asList(), - Arrays.asList(new BppDiagnosticBundle.ExtraFile(log, "logs/LogOutput.log", true)) - ), - 64, - 32, - 1024 * 1024, - 20 - ); - String stored = entry(zip, "logs/LogOutput.log"); - assertTrue(stored.contains("bpp-diagnostic-truncated"), "tail banner missing"); - assertTrue(stored.contains("originalBytes=300"), "original size missing"); - assertTrue(stored.contains("TAILMARKER"), "tail dropped the end of the log"); - assertTrue(!stored.contains("HEAD"), "tail kept the start of the log"); - String manifest = entry(zip, "manifest.txt"); - assertTrue(manifest.contains("../evil.txt") || manifest.contains("rejected-archive-path"), manifest); - assertMissing(zip, "../evil.txt"); - assertMissing(zip, "evil.txt"); - } - - private static void testRedactsPreferenceSecretsFromStateTree() throws Exception { - File root = Files.createTempDirectory("bpp-diag-prefs").toFile(); - File prefs = new File(root, "shared_prefs"); - write(new File(prefs, "secure.xml"), - "super-secretdark"); - write(new File(prefs, "settings.preferences_pb"), "binary-token-remains"); - File zip = new File(root, "out.zip"); - BppDiagnosticBundle.write(zip, new BppDiagnosticBundle.Request( - "r", - Arrays.asList(), - Arrays.asList(new BppDiagnosticBundle.ScanRoot(prefs, "state/shared-prefs", true)), - Arrays.asList() - )); - String xml = entry(zip, "state/shared-prefs/secure.xml"); - assertTrue(xml.contains("[redacted]"), xml); - assertTrue(!xml.contains("super-secret"), xml); - assertTrue(xml.contains("dark"), "non-secret preference was removed"); - String pb = entry(zip, "state/shared-prefs/settings.preferences_pb"); - assertTrue(pb.contains("binary-token-remains"), "binary datastore should be copied unchanged"); - String redacted = BppDiagnosticBundle.redactPreferenceText("password=hunter2\ntheme=dark\n"); - assertTrue(redacted.contains("password=[redacted]"), redacted); - assertTrue(redacted.contains("theme=dark"), redacted); - } - - private static void testElfAlignment() { - byte[] elf = new byte[128]; - elf[0] = 0x7f; - elf[1] = 'E'; - elf[2] = 'L'; - elf[3] = 'F'; - elf[4] = 2; - elf[5] = 1; - ByteBuffer buf = ByteBuffer.wrap(elf).order(ByteOrder.LITTLE_ENDIAN); - buf.putLong(32, 64L); - buf.putShort(54, (short) 56); - buf.putShort(56, (short) 1); - buf.putInt(64, 1); - buf.putLong(64 + 48, 16384L); - String described = BppDiagnosticBundle.describeElfLoadSegments(elf, "libil2cpp.so"); - assertTrue(described.contains("PT_LOAD"), described); - assertTrue(described.contains("align=16384"), described); - assertTrue(described.contains("minLoadAlign=16384"), described); - assertTrue(BppDiagnosticBundle.describeElfLoadSegments(new byte[] {1, 2, 3}, "x").contains("unrecognized"), - "non-elf should be explicit"); - } - - private static void testLogcatCommandsDoNotClear() { - List rolling = BppDiagnosticBundle.rollingLogcatCommand(new File("/data/bpp-logcat")); - assertTrue(rolling.contains("-d"), "rolling logcat must exit so stdio flushes"); - assertTrue(!rolling.contains("-f"), "logcat -f stops at an 8KB stdio buffer"); - assertTrue(rolling.contains("crash"), "crash buffer should be included"); - assertTrue(!BppDiagnosticBundle.commandClearsLogcat(rolling), "rolling command clears the buffer"); - List filtered = BppDiagnosticBundle.rollingLogcatCommand(22781); - assertTrue(filtered.contains("--pid=22781"), filtered.toString()); - assertTrue("line-c\n".equals(BppDiagnosticBundle.suffixAfterMarker("line-a\nline-b\nline-c\n", "line-b")), - "suffix after marker"); - assertTrue(BppDiagnosticBundle.suffixAfterMarker("other\n", "line-b").startsWith("[buffer-rotated]"), - "rotated buffer should be kept"); - List dump = BppDiagnosticBundle.dumpLogcatCommand("main"); - assertTrue(dump.contains("-d"), "dump must be non-blocking"); - assertTrue(!BppDiagnosticBundle.commandClearsLogcat(dump), "dump command clears the buffer"); - assertTrue(BppDiagnosticBundle.commandClearsLogcat(Arrays.asList("logcat", "-c")), "detector missed -c"); - boolean threw = false; - try { - BppDiagnosticBundle.captureProcess(Arrays.asList("logcat", "-c"), 1000L, 100); - } catch (Exception ex) { - threw = true; - } - assertTrue(threw, "captureProcess must refuse logcat -c"); - } - - private static void testAppendCappedAndCaptureProcess() throws Exception { - File root = Files.createTempDirectory("bpp-diag-append").toFile(); - File note = new File(root, "launch-attempts.log"); - BppDiagnosticBundle.appendCapped(note, "one", 32); - BppDiagnosticBundle.appendCapped(note, "two", 32); - BppDiagnosticBundle.appendCapped(note, "three-is-longer", 32); - String text = Files.readString(note.toPath()); - assertTrue(text.length() <= 32, "cap exceeded: " + text.length()); - assertTrue(text.contains("three-is-longer"), text); - String echo = BppDiagnosticBundle.captureProcessText(Arrays.asList("echo", "hello-diag"), 5000L, 100); - assertTrue(echo.contains("hello-diag"), echo); - assertTrue(BppDiagnosticBundle.sanitizeArchivePath("../etc/passwd") == null, "traversal accepted"); - assertTrue(BppDiagnosticBundle.sanitizeArchivePath("logs/LogOutput.log").equals("logs/LogOutput.log"), "normal path rejected"); - assertTrue(BppDiagnosticBundle.isSensitivePath("dir/release.keystore"), "keystore not sensitive"); - assertTrue(!BppDiagnosticBundle.isSensitivePath("BepInEx/LogOutput.log"), "LogOutput was treated as secret"); - } - - private static void testTreeListsPlugins() throws Exception { - File root = Files.createTempDirectory("bpp-diag-tree").toFile(); - write(new File(root, "BepInEx/plugins/BazaarPlusPlus.dll"), "dll"); - write(new File(root, "BepInEx/LogOutput.log"), "log"); - String tree = BppDiagnosticBundle.renderTree(root, 50, 6); - assertTrue(tree.contains("BazaarPlusPlus.dll"), tree); - assertTrue(tree.contains("LogOutput.log"), tree); - assertTrue(!tree.contains("\ndll\n") && !tree.contains("\tlog\n"), "tree copied file bytes"); - } - - private static void testReadmeExplainsTheZip() { - String readme = BppDiagnosticBundle.readme("2026-10-27T00:00:00Z", "6.0.0-preview.39", "com.bepinex.android"); - String[] required = new String[] { - "manifest.txt", "device/", "packages/", "deploy/", "launch/", "logcat/", "crashes/", "state/", - "LogOutput", "libil2cpp", "灰屏", "下载", "keystore", "getHistoricalProcessExitReasons", - "game-heartbeat" - }; - for (int i = 0; i < required.length; i++) { - assertTrue(readme.contains(required[i]), "readme missing " + required[i]); - } - } - - private static void testGenerationStageAndLoggingConfig() throws Exception { - BppDiagnosticBundle.GenerationProbe probe = new BppDiagnosticBundle.GenerationProbe(); - assertTrue("starting".equals(BppDiagnosticBundle.generationStageId(probe)), "empty probe"); - probe.unityZipBytes = 1000; - assertTrue("unity-libs".equals(BppDiagnosticBundle.generationStageId(probe)), "zip only"); - probe.unityLibFiles = 40; - assertTrue("cpp2il".equals(BppDiagnosticBundle.generationStageId(probe)), "libs without interop"); - assertTrue(BppDiagnosticBundle.generationPercent(probe, 0) < 0, "cpp2il percent must stay unknown"); - assertTrue(BppDiagnosticBundle.generationStageLabel("cpp2il").contains("Cpp2IL"), "stage label"); - probe.interopFiles = 12; - probe.interopBytes = 4096; - assertTrue("interop".equals(BppDiagnosticBundle.generationStageId(probe)), "writing interop"); - probe.interopFilesAtStart = 12; - probe.logIsNew = true; - probe.logOutputBytes = 80; - assertTrue("plugins".equals(BppDiagnosticBundle.generationStageId(probe)), "plugins after a fresh log"); - String cfg = "[Logging]\nUnityLogListening = false\n\n[Logging.Disk]\nWriteUnityLog = false\nInstantFlushing = false\n"; - String enabled = BppDiagnosticBundle.enableDiagnosticLogging(cfg); - assertTrue(enabled.contains("UnityLogListening = true"), enabled); - assertTrue(enabled.contains("WriteUnityLog = true"), enabled); - assertTrue(enabled.contains("InstantFlushing = true"), enabled); - assertTrue(enabled.equals(BppDiagnosticBundle.enableDiagnosticLogging(enabled)), "patch not idempotent"); - File root = Files.createTempDirectory("bpp-diag-logs").toFile(); - write(new File(root, "BepInEx/logs/LogOutput.log"), "log\n"); - write(new File(root, "BepInEx/plugins/nested.log"), "inside-plugin\n"); - write(new File(root, "BepInEx/plugins/skip.dll"), "dll"); - List logs = BppDiagnosticBundle.findLogFiles(root, 20); - boolean sawNested = false; - for (int i = 0; i < logs.size(); i++) { - if (logs.get(i).getName().equals("nested.log")) sawNested = true; - } - assertTrue(sawNested, "log inside plugins was skipped"); - String empty = BppDiagnosticBundle.describeDirectory(new File(root, "BepInEx/interop"), 10); - assertTrue(empty.contains("exists=false"), empty); - File logsDir = new File(root, "BepInEx/logs"); - String listed = BppDiagnosticBundle.describeDirectory(logsDir, 10); - assertTrue(listed.contains("LogOutput.log"), listed); - assertTrue(listed.contains("children=1"), listed); - } - - private static void testExitReasonNamesAndDirectoryListing() { - assertTrue("LOW_MEMORY".equals(BppDiagnosticBundle.exitReasonName(3)), "reason 3"); - assertTrue("CACHED".equals(BppDiagnosticBundle.importanceName(400)), "importance 400"); - assertTrue(BppDiagnosticBundle.exitSubReasonName(6).equals("MEMORY_PRESSURE"), "subreason"); - assertTrue(BppDiagnosticBundle.exitSubReasonName(-1).equals("unavailable"), "missing subreason"); - assertTrue(BppDiagnosticBundle.FIRST_RUN_OVERLAY_TEXT.contains("不要切走"), "overlay copy"); - } - - private static void testPreferenceProtoKeys() { - byte[] value = protoBytes(new byte[][] { - new byte[] {0x2a, 0x04}, "dark".getBytes(StandardCharsets.UTF_8) - }); - byte[] entry = protoBytes(new byte[][] { - new byte[] {0x0a, 0x05}, "theme".getBytes(StandardCharsets.UTF_8), - new byte[] {0x12, (byte) value.length}, value - }); - byte[] tokenValue = protoBytes(new byte[][] { new byte[] {0x08, 0x01} }); - byte[] tokenEntry = protoBytes(new byte[][] { - new byte[] {0x0a, 0x09}, "api_token".getBytes(StandardCharsets.UTF_8), - new byte[] {0x12, (byte) tokenValue.length}, tokenValue - }); - byte[] message = protoBytes(new byte[][] { - new byte[] {0x0a, (byte) entry.length}, entry, - new byte[] {0x0a, (byte) tokenEntry.length}, tokenEntry - }); - String decoded = BppDiagnosticBundle.decodePreferenceProto(message); - assertTrue(decoded.contains("theme=dark"), decoded); - assertTrue(decoded.contains("api_token=[redacted]"), decoded); - assertTrue(!decoded.contains("true"), decoded); - } - - private static byte[] protoBytes(byte[][] parts) { - int size = 0; - for (int i = 0; i < parts.length; i++) size += parts[i].length; - byte[] out = new byte[size]; - int at = 0; - for (int i = 0; i < parts.length; i++) { - System.arraycopy(parts[i], 0, out, at, parts[i].length); - at += parts[i].length; - } - return out; - } - - private static void write(File file, String text) throws Exception { - File parent = file.getParentFile(); - if (parent != null) parent.mkdirs(); - Files.write(file.toPath(), text.getBytes(StandardCharsets.UTF_8)); - } - - private static String entry(File zip, String name) throws Exception { - try (ZipFile zf = new ZipFile(zip)) { - ZipEntry entry = zf.getEntry(name); - assertTrue(entry != null, "missing zip entry " + name); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] buf = new byte[4096]; - try (java.io.InputStream in = zf.getInputStream(entry)) { - int n; - while ((n = in.read(buf)) != -1) bos.write(buf, 0, n); - } - return bos.toString(StandardCharsets.UTF_8); - } - } - - private static void assertMissing(File zip, String name) throws Exception { - try (ZipFile zf = new ZipFile(zip)) { - assertTrue(zf.getEntry(name) == null, "unexpected zip entry " + name); - } - } - - private static void assertTrue(boolean value, String message) { - if (!value) throw new AssertionError(message); - } -} diff --git a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppGithubFeedbackTests.java b/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppGithubFeedbackTests.java deleted file mode 100644 index 337eda8..0000000 --- a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppGithubFeedbackTests.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.bepinex.android.bpp; - -import java.net.URLDecoder; - -public final class BppGithubFeedbackTests { - - public static void main(String[] args) throws Exception { - testUrlContainsTemplateAndBasename(); - testLongInputStillClamped(); - System.out.println("PASS: all BppGithubFeedback tests succeeded."); - } - - private static void testUrlContainsTemplateAndBasename() throws Exception { - String fakePath = "/data/user/0/com.bepinex.android.bpp/cache/BPP-diagnostics-20261027-123456.zip"; - String url = BppGithubFeedback.buildIssueUrl( - "6.0.0-preview.44", - "6.0.0-preview.44", - "abc123", - "Google", - "Pixel 8", - "15", - 35, - "arm64-v8a, armeabi-v7a", - fakePath - ); - assertTrue(url.startsWith(BppGithubFeedback.ISSUES_NEW_BASE), url); - assertTrue(url.contains("title=" + BppGithubFeedback.encodeQuery(BppGithubFeedback.buildTitle())), url); - assertTrue(!url.contains("+"), "URL must encode spaces as %20"); - assertTrue(url.length() <= BppGithubFeedback.MAX_URL_CHARS, "URL too long: " + url.length()); - - String decoded = URLDecoder.decode(url, "UTF-8"); - assertTrue(decoded.contains("## 问题描述"), decoded); - assertTrue(decoded.contains("## 复现步骤"), decoded); - assertTrue(decoded.contains("## 环境信息"), decoded); - assertTrue(decoded.contains("BPP-diagnostics-20261027-123456.zip"), decoded); - assertTrue(!decoded.contains("/data/user/0/"), decoded); - assertTrue(decoded.contains("请把下载文件夹里的 BPP-diagnostics-20261027-123456.zip 拖到这里上传"), decoded); - } - - private static void testLongInputStillClamped() throws Exception { - StringBuilder huge = new StringBuilder(); - for (int i = 0; i < 20000; i++) huge.append('中'); - String url = BppGithubFeedback.buildIssueUrl( - "6.0.0-preview.44", - "6.0.0-preview.44", - "abc123", - "Google", - "Pixel 8", - "15", - 35, - "arm64-v8a", - "/tmp/" + huge + ".zip" - ); - assertTrue(url.startsWith(BppGithubFeedback.ISSUES_NEW_BASE), url); - assertTrue(url.length() <= BppGithubFeedback.MAX_URL_CHARS, "clamped URL too long: " + url.length()); - } - - private static void assertTrue(boolean value, String message) { - if (!value) throw new AssertionError(message); - } -} diff --git a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppLauncherUpdateCheckerTests.java b/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppLauncherUpdateCheckerTests.java deleted file mode 100644 index c958d01..0000000 --- a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppLauncherUpdateCheckerTests.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.bepinex.android.bpp; - -import org.json.JSONArray; -import org.json.JSONObject; - -/** Host tests require an org.json JVM implementation on the runtime classpath. */ -public final class BppLauncherUpdateCheckerTests { - private static int assertions; - - public static void main(String[] args) throws Exception { - assertThat(BppLauncherUpdateChecker.compareVersions("6.0.0-preview.10", "6.0.0-preview.9") > 0); - assertThat(BppLauncherUpdateChecker.compareVersions("6.0.0-preview.100", "6.0.0-preview.38") > 0); - assertThat(BppLauncherUpdateChecker.compareVersions("6.0.0", "6.0.0-preview.999") > 0); - assertThat(BppLauncherUpdateChecker.compareVersions("6.1.0-preview.1", "6.0.0") > 0); - assertThat(BppLauncherUpdateChecker.compareVersions("7.0.0-preview.1", "6.99.99") > 0); - assertThat(BppLauncherUpdateChecker.compareVersions("android-v6.0.0-preview.37", "6.0.0-preview.37") == 0); - for (String invalid : new String[] {"", "1.0.0-ci.99", "6.0", "6.0.0-preview.-1", "6.0.0-preview.9999999999", "6.0.0/../../evil", "6.0.0\n"}) { - boolean threw = false; - try { BppLauncherUpdateChecker.compareVersions(invalid, "6.0.0"); } - catch (IllegalArgumentException expected) { threw = true; } - assertThat(threw); - } - JSONObject v38 = release("android-v6.0.0-preview.38"); - assertThat(select("6.0.0-preview.37", v38).version.equals("6.0.0-preview.38")); - assertThat(select("6.0.0-preview.38", v38) == null); - assertThat(select("6.0.0-preview.39", v38) == null); - assertThat(select("6.0.0", v38) == null); - assertThat(select("6.0.0-preview.37", release("android-v6.0.0")).version.equals("6.0.0")); - assertThat(select("6.0.0-preview.9", v38, release("android-v6.0.0-preview.10")) - .version.equals("6.0.0-preview.38")); - assertThat(select("6.0.0-preview.9", release("android-v6.0.0-preview.10"), v38) - .version.equals("6.0.0-preview.38")); - assertThat(select("6.0.0-preview.37", release("android-v6.0.0-preview.39").put("draft", true)) == null); - assertThat(select("6.0.0-preview.37", release("v9.0.0")) == null); - assertThat(select("6.0.0-preview.37", release("android-v6.0.0-preview.39").put("assets", new JSONArray())) == null); - JSONObject pending = release("android-v6.0.0-preview.39"); - pending.getJSONArray("assets").getJSONObject(0).put("state", "starter"); - assertThat(select("6.0.0-preview.37", pending) == null); - JSONObject empty = release("android-v6.0.0-preview.39"); - empty.getJSONArray("assets").getJSONObject(0).put("size", 0); - assertThat(select("6.0.0-preview.37", empty) == null); - JSONObject wrongHost = release("android-v6.0.0-preview.39"); - wrongHost.getJSONArray("assets").getJSONObject(0).put("browser_download_url", "https://evil.example/app.apk"); - assertThat(select("6.0.0-preview.37", wrongHost) == null); - assertThat(select("6.0.0-preview.37", pending, v38).version.equals("6.0.0-preview.38")); - assertThat(select("6.0.0-preview.37") == null); - assertThat(select("6.0.0-preview.37", v38).releaseUrl.equals( - BppLauncherUpdateChecker.RELEASES_URL + "/tag/android-v6.0.0-preview.38")); - assertThat(select("6.0.0-preview.37", v38).apkUrl.equals( - BppLauncherUpdateChecker.RELEASES_URL + "/download/android-v6.0.0-preview.38/BepInExLauncher-bpp-android.apk")); - assertThat(select("6.0.0-preview.37", v38).apkSize == 100); - boolean malformedFailed = false; - try { BppLauncherUpdateChecker.selectUpdate("{broken", "6.0.0-preview.37"); } - catch (Exception expected) { malformedFailed = true; } - assertThat(malformedFailed); - System.out.println("Launcher update tests passed: " + assertions + " assertions"); - if (args.length > 0 && "--live".equals(args[0])) { - BppLauncherUpdateChecker.Update actual = BppLauncherUpdateChecker.check("6.0.0-preview.1"); - if (actual == null) throw new AssertionError("Expected a published Android release"); - System.out.println("Live GitHub release: " + actual.version + " " + actual.releaseUrl); - } - } - - private static BppLauncherUpdateChecker.Update select(String current, JSONObject... releases) throws Exception { - JSONArray array = new JSONArray(); - for (JSONObject release : releases) array.put(release); - return BppLauncherUpdateChecker.selectUpdate(array.toString(), current); - } - - private static JSONObject release(String tag) throws Exception { - JSONObject asset = new JSONObject().put("name", "BepInExLauncher-bpp-android.apk") - .put("state", "uploaded").put("size", 100) - .put("browser_download_url", BppLauncherUpdateChecker.RELEASES_URL + "/download/" + tag + "/BepInExLauncher-bpp-android.apk"); - return new JSONObject().put("draft", false).put("prerelease", true) - .put("tag_name", tag).put("assets", new JSONArray().put(asset)); - } - - private static void assertThat(boolean condition) { - assertions++; - if (!condition) throw new AssertionError("Assertion " + assertions + " failed"); - } -} diff --git a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppOfficialPayloadTests.java b/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppOfficialPayloadTests.java deleted file mode 100644 index 518968f..0000000 --- a/android-port/tools/bpp-launcher/test/com/bepinex/android/bpp/BppOfficialPayloadTests.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.bepinex.android.bpp; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; -import org.json.JSONObject; - -/** Host tests require an org.json JVM implementation on the runtime classpath. */ -public final class BppOfficialPayloadTests { - private static final String DIGEST = "f41fcb027911e235fb48424eab16fd2698266cd4ab9ecba5605aae19646f7ae1"; - private static final String GAME = "1.0.12825-production-android-d9601ded"; - private static int assertions; - - public static void main(String[] args) throws Exception { - BppOfficialPayload.Release release = BppOfficialPayload.parseRelease(manifest("6.0.3").toString()); - assertThat(release.version.equals("6.0.3")); - assertThat(release.url.startsWith(BppOfficialPayload.DOWNLOAD_PREFIX)); - assertThat(release.size == 2845338); - assertThat(release.gameVersion.equals(GAME)); - assertThat(release.nonManagedPayloadDigest.equals(DIGEST)); - assertThat(release.historyDatabaseUserVersion == 1); - - JSONObject foreign = manifest("6.0.3"); - payload(foreign).put("url", "https://example.com/installer/x.zip"); - assertThrows(() -> BppOfficialPayload.parseRelease(foreign.toString())); - JSONObject climbing = manifest("6.0.3"); - payload(climbing).put("url", BppOfficialPayload.DOWNLOAD_PREFIX + "../x.zip"); - assertThrows(() -> BppOfficialPayload.parseRelease(climbing.toString())); - JSONObject badSha = manifest("6.0.3"); - payload(badSha).put("sha256", "abc"); - assertThrows(() -> BppOfficialPayload.parseRelease(badSha.toString())); - assertThrows(() -> BppOfficialPayload.parseRelease(manifest("6.0").toString())); - - assertThat(BppOfficialPayload.compareVersions("6.0.2.prod", "6.0.2") == 0); - assertThat(BppOfficialPayload.compareVersions("6.0.10", "6.0.9") > 0); - assertThat(BppOfficialPayload.compareVersions("6.1.0", "6.0.99") > 0); - - File root = Files.createTempDirectory("bpp-official-payload").toFile(); - try { - File nothing = new File(root, "nothing"); - assertThat(BppOfficialPayload.skipReason(release, nothing, GAME) == null); - assertThat("game_version".equals(BppOfficialPayload.skipReason(release, nothing, "1.0.1"))); - - File installed = new File(root, "installed"); - write(new File(installed, BppOfficialPayload.VERSION_FILE), "6.0.3.prod"); - assertThat("up_to_date".equals(BppOfficialPayload.skipReason(release, installed, GAME))); - write(new File(installed, BppOfficialPayload.VERSION_FILE), "6.0.2.prod"); - assertThat(BppOfficialPayload.skipReason(release, installed, GAME) == null); - - write(new File(installed, BppOfficialPayload.INSTALLED_MANIFEST), - "bpp-managed-payload-manifest 1\nversion 6.0.2\nplatform android-aarch64\n" - + "history-database-user-version 1\nnon-managed-payload-digest " + "0".repeat(64) + "\n"); - assertThat("non_managed_payload".equals(BppOfficialPayload.skipReason(release, installed, GAME))); - write(new File(installed, BppOfficialPayload.INSTALLED_MANIFEST), - "bpp-managed-payload-manifest 1\nversion 6.0.2\nplatform android-aarch64\n" - + "history-database-user-version 2\nnon-managed-payload-digest " + DIGEST + "\n"); - assertThat("history_database".equals(BppOfficialPayload.skipReason(release, installed, GAME))); - write(new File(installed, BppOfficialPayload.INSTALLED_MANIFEST), - "bpp-managed-payload-manifest 1\nversion 6.0.2\nplatform android-aarch64\n" - + "history-database-user-version 1\nnon-managed-payload-digest " + DIGEST + "\n"); - assertThat(BppOfficialPayload.skipReason(release, installed, GAME) == null); - - write(new File(installed, BppOfficialPayload.DATA_ROOT + "/" + BppOfficialPayload.REJECTED_FILE), - "6.0.1 launch_unconfirmed\n6.0.3 member_missing:x\n"); - assertThat("rejected".equals(BppOfficialPayload.skipReason(release, installed, GAME))); - - File staging = new File(root, "staging"); - BppOfficialPayload.stage(zip(root, "good.zip", "files/MelonLoader/Mods/BazaarPlusPlus.Android.dll", - "files/MelonLoader/UserLibs/MessagePack.dll"), staging, "6.0.3"); - File staged = BppOfficialPayload.stagedDirectory(staging, "6.0.3"); - assertThat(new File(staged, "manifest.txt").isFile()); - assertThat(new File(staged, "manifest.txt.minisig").isFile()); - assertThat(new File(staged, "files/MelonLoader/Mods/BazaarPlusPlus.Android.dll").isFile()); - assertThat("staged".equals(BppOfficialPayload.skipReason(release, staging, GAME))); - - for (String evil : new String[] { - "files/BepInEx/plugins/Evil.dll", "files/MelonLoader/Mods/../../Evil.dll", - "files/MelonLoader/Mods/sub/Evil.dll", "../Evil.dll", "Evil.txt"}) { - File refused = new File(root, "refused"); - File evilZip = zip(root, "evil.zip", evil); - assertThrows(() -> BppOfficialPayload.stage(evilZip, refused, "6.0.3")); - assertThat(!BppOfficialPayload.stagedDirectory(refused, "6.0.3").exists()); - assertThat(!new File(BppOfficialPayload.stagedDirectory(refused, "6.0.3").getParentFile(), ".6.0.3.partial").exists()); - } - } finally { - deleteRecursively(root); - } - System.out.println("BppOfficialPayloadTests OK assertions=" + assertions); - } - - private static JSONObject manifest(String version) { - return new JSONObject() - .put("version", version) - .put("downloads", new JSONObject().put("android-aarch64", new JSONObject() - .put("managedPayload", new JSONObject() - .put("url", BppOfficialPayload.DOWNLOAD_PREFIX + version + "/android-aarch64/managed/p.zip") - .put("size", 2845338) - .put("sha256", "fde6b73668c07c7e6f56be59e8a124369482f7aeb6b5da3cc3cd04d4f8c7f017")) - .put("nonManagedPayloadDigest", DIGEST) - .put("historyDatabaseUserVersion", 1) - .put("game", new JSONObject().put("gameVersion", GAME)))); - } - - private static JSONObject payload(JSONObject manifest) { - return manifest.getJSONObject("downloads").getJSONObject("android-aarch64").getJSONObject("managedPayload"); - } - - private static File zip(File directory, String name, String... files) throws IOException { - File zip = new File(directory, name); - try (ZipOutputStream output = new ZipOutputStream(new FileOutputStream(zip))) { - for (String entry : new String[] {"manifest.txt", "manifest.txt.minisig"}) { - output.putNextEntry(new ZipEntry(entry)); - output.write("x".getBytes(StandardCharsets.UTF_8)); - output.closeEntry(); - } - for (String entry : files) { - output.putNextEntry(new ZipEntry(entry)); - output.write(entry.getBytes(StandardCharsets.UTF_8)); - output.closeEntry(); - } - } - return zip; - } - - private static void write(File file, String text) throws IOException { - file.getParentFile().mkdirs(); - Files.write(file.toPath(), text.getBytes(StandardCharsets.UTF_8)); - } - - private static void deleteRecursively(File file) { - File[] children = file.listFiles(); - if (children != null) for (File child : children) deleteRecursively(child); - file.delete(); - } - - private interface Action { void run() throws Exception; } - - private static void assertThrows(Action action) throws Exception { - boolean threw = false; - try { action.run(); } catch (IOException expected) { threw = true; } - assertThat(threw); - } - - private static void assertThat(boolean condition) { - assertions++; - if (!condition) throw new AssertionError("assertion " + assertions + " failed"); - } -} diff --git a/android-port/tools/bpp-launcher/test_apk_download.py b/android-port/tools/bpp-launcher/test_apk_download.py deleted file mode 100644 index c6f9550..0000000 --- a/android-port/tools/bpp-launcher/test_apk_download.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Execute the production download lifecycle against stateful Android service fakes.""" -import os -from pathlib import Path -import shutil -import subprocess -import tempfile - -STUBS = { - "android/net/Uri.java": """package android.net; public class Uri { - public String value; private Uri(String s){value=s;} public static Uri parse(String s){return new Uri(s);} - public String getScheme(){return value.split(":")[0];} - }""", - "android/os/Environment.java": 'package android.os; public class Environment { public static final String DIRECTORY_DOWNLOADS="Download"; }', - "android/content/SharedPreferences.java": """package android.content; import java.util.*; - public class SharedPreferences { - Map values=new HashMap<>(); public boolean writable=true; - public long getLong(String key,long fallback){return (Long)values.getOrDefault(key,fallback);} - public String getString(String key,String fallback){return (String)values.getOrDefault(key,fallback);} - public Editor edit(){return new Editor();} - public class Editor { - Map pending=new HashMap<>(values); - public Editor putLong(String k,long v){pending.put(k,v);return this;} - public Editor putString(String k,String v){pending.put(k,v);return this;} - public Editor clear(){pending.clear();return this;} - public boolean commit(){if(!writable)return false;values=pending;return true;} - public void apply(){commit();} - } - }""", - "android/content/pm/PackageInfo.java": """package android.content.pm; public class PackageInfo { - public String packageName="com.bepinex.android",versionName="6.0.0-preview.44"; - public long versionCode=44; public long getLongVersionCode(){return versionCode;} - }""", - "android/content/pm/PackageManager.java": """package android.content.pm; public class PackageManager { - public PackageInfo archive=new PackageInfo(),installed=new PackageInfo(); - public PackageManager(){installed.versionCode=43;} - public PackageInfo getPackageArchiveInfo(String path,int flags){return archive;} - public PackageInfo getPackageInfo(String name,int flags){return installed;} - }""", - "android/database/Cursor.java": """package android.database; public class Cursor implements AutoCloseable { - public boolean exists=true,closed; public long[] values={2,0,50,100}; - public boolean moveToFirst(){return exists;} - public int getColumnIndexOrThrow(String key){return Integer.parseInt(key);} - public int getInt(int i){return (int)values[i];} public long getLong(int i){return values[i];} - public void close(){closed=true;} - }""", - "android/app/DownloadManager.java": """package android.app; import android.net.Uri; - public class DownloadManager { - public static final int STATUS_FAILED=16,STATUS_SUCCESSFUL=8,STATUS_PAUSED=4; - public static final String COLUMN_STATUS="0",COLUMN_REASON="1",COLUMN_BYTES_DOWNLOADED_SO_FAR="2",COLUMN_TOTAL_SIZE_BYTES="3"; - public android.database.Cursor cursor=new android.database.Cursor(); - public int enqueued,removed; public Uri uri=Uri.parse("content://downloads/7"); public Request request; - public static class Query {public Query setFilterById(long... ids){return this;}} - public static class Request { - public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED=1; - public Uri uri; public String file; - public Request(Uri u){uri=u;} public Request setTitle(String s){return this;} - public Request setDescription(String s){return this;} public Request setMimeType(String s){return this;} - public Request setNotificationVisibility(int n){return this;} - public Request setDestinationInExternalFilesDir(android.content.Context c,String dir,String name){file=name;return this;} - } - public long enqueue(Request r){request=r;enqueued++;return 7;} - public int remove(long... ids){removed++;return 1;} - public android.database.Cursor query(Query q){return cursor;} - public Uri getUriForDownloadedFile(long id){return uri;} - }""", - "android/content/Context.java": """package android.content; public class Context { - public static final String DOWNLOAD_SERVICE="download"; public static final int MODE_PRIVATE=0; - public final android.app.DownloadManager manager=new android.app.DownloadManager(); - public final SharedPreferences preferences=new SharedPreferences(); - public final android.content.pm.PackageManager packages=new android.content.pm.PackageManager(); - public java.io.File directory; - public Object getSystemService(String name){return manager;} - public SharedPreferences getSharedPreferences(String name,int mode){return preferences;} - public java.io.File getExternalFilesDir(String type){return directory;} - public android.content.pm.PackageManager getPackageManager(){return packages;} - public String getPackageName(){return "com.bepinex.android";} - }""", - "com/bepinex/android/bpp/BppLauncherUpdateChecker.java": """package com.bepinex.android.bpp; - public class BppLauncherUpdateChecker { - public static class Update {public String version="6.0.0-preview.44",apkUrl="https://github.com/test.apk";public long apkSize=100;} - public static int compareVersions(String a,String b){return a.compareTo(b);} - }""", - "DownloadTests.java": """import com.bepinex.android.bpp.*; import android.content.Context; import java.nio.file.*; - public class DownloadTests { - interface Work {void run() throws Exception;} - static int assertions; - static void check(boolean b){assertions++;if(!b)throw new AssertionError("Assertion "+assertions);} - static void rejects(Work work) throws Exception {try{work.run();throw new AssertionError("Expected rejection");}catch(java.io.IOException expected){assertions++;}} - public static void main(String[] args) throws Exception { - Context c=new Context(); c.directory=new java.io.File(args[0]); - BppApkDownload d=new BppApkDownload(c); var update=new BppLauncherUpdateChecker.Update(); - check(!d.hasDownload()); d.start(update); check(d.hasDownload()); - check(c.manager.request.uri.value.equals(update.apkUrl)); - d.start(update); check(c.manager.enqueued==1); - d=new BppApkDownload(c); check(d.hasDownload()); - check(d.state().message.contains("50%") && !d.state().complete); check(c.manager.cursor.closed); - c.manager.cursor.values[0]=4; check(d.state().message.contains("暂停")); - BppApkDownload restored=d; rejects(()->restored.installationUri()); - c.manager.cursor.values[0]=16; rejects(()->restored.state()); - c.manager.cursor.exists=false; rejects(()->restored.state()); c.manager.cursor.exists=true; - c.manager.cursor.values[0]=8; check(d.state().complete); - rejects(()->restored.installationUri()); - Path apk=c.directory.toPath().resolve("bpp-update.apk"); Files.write(apk,new byte[99]); - rejects(()->restored.installationUri()); Files.write(apk,new byte[100]); - check(d.installationUri().getScheme().equals("content")); - c.packages.archive.packageName="unrelated"; rejects(()->restored.installationUri()); - c.packages.archive.packageName=c.getPackageName(); c.packages.archive.versionName="6.0.0-preview.45"; - rejects(()->restored.installationUri()); c.packages.archive.versionName=update.version; - c.packages.archive.versionCode=43; rejects(()->restored.installationUri()); c.packages.archive.versionCode=44; - c.manager.uri=android.net.Uri.parse("file:///tmp/update.apk"); rejects(()->restored.installationUri()); - check(!d.alreadyInstalled("6.0.0-preview.43")); check(d.alreadyInstalled(update.version)); - d.clear(); check(!d.hasDownload() && c.manager.removed==1); - d.start(update); check(!Files.exists(apk)); check(c.manager.enqueued==2); d.clear(); - c.preferences.writable=false; rejects(()->restored.start(update)); check(c.manager.removed==3); - c.preferences.writable=true; c.directory=null; rejects(()->restored.start(update)); - System.out.println("APK download tests passed: "+assertions+" assertions"); - } - }""", -} - - -def run(): - java_home = os.environ.get("JAVA_HOME") - suffix = ".exe" if os.name == "nt" else "" - javac = str(Path(java_home) / "bin" / ("javac" + suffix)) if java_home else shutil.which("javac") - java = str(Path(java_home) / "bin" / ("java" + suffix)) if java_home else shutil.which("java") - if not javac or not java: - raise RuntimeError("JDK 17+ required") - with tempfile.TemporaryDirectory(prefix="bpp-download-tests-") as temporary: - root = Path(temporary) - sources = [] - for relative, code in STUBS.items(): - target = root / relative - target.parent.mkdir(parents=True, exist_ok=True) - target.write_text(code, encoding="utf-8") - sources.append(str(target)) - production = Path(__file__).parent / "src/com/bepinex/android/bpp/BppApkDownload.java" - subprocess.run([javac, "-encoding", "UTF-8", "--release", "11", "-d", str(root), *sources, str(production)], check=True) - subprocess.run([java, "-cp", str(root), "DownloadTests", str(root)], check=True) - - -if __name__ == "__main__": - run() diff --git a/android-port/tools/bpp-launcher/test_game_window.py b/android-port/tools/bpp-launcher/test_game_window.py deleted file mode 100644 index 9bc76ef..0000000 --- a/android-port/tools/bpp-launcher/test_game_window.py +++ /dev/null @@ -1,261 +0,0 @@ -"""Execute production window policy with queued lifecycle fakes, not a device/layout emulator.""" -import os -from pathlib import Path -import shutil -import struct -import subprocess -import tempfile -import unittest - - -STUBS = { - "android/content/pm/ActivityInfo.java": "package android.content.pm; public class ActivityInfo { public static final int SCREEN_ORIENTATION_SENSOR_LANDSCAPE=6; }", - "android/R.java": "package android; public class R { public static class id { public static int content=1; } }", - "android/os/Build.java": "package android.os; public class Build { public static class VERSION { public static int SDK_INT=35; } }", - "android/os/Looper.java": "package android.os; public class Looper { public static Looper getMainLooper(){return new Looper();} }", - "android/os/SystemClock.java": "package android.os; public class SystemClock { public static long uptimeMillis(){return 0;} }", - "android/os/Handler.java": """package android.os; import java.util.*; public class Handler { - static class Work {Runnable run; Object token; Work(Runnable r,Object t){run=r;token=t;}} - static final List queue=new ArrayList<>(); - public Handler(Looper l){} public boolean postAtTime(Runnable r,Object t,long n){queue.add(new Work(r,t));return true;} - public boolean post(Runnable r){return postAtTime(r,null,0);} - public void removeCallbacksAndMessages(Object t){queue.removeIf(w -> t==null || w.token==t);} - public static void drain(){while(!queue.isEmpty()) queue.remove(0).run.run();} - }""", - "android/util/Log.java": "package android.util; public class Log { public static int i(String t,String m){return 0;} public static int e(String t,String m,Throwable e){return 0;} }", - "android/app/Activity.java": """package android.app; public class Activity { - public final android.view.Window window=new android.view.Window(); - public boolean focused=true,finishing,destroyed; - public int orientation=0,orientationWrites; - public int getRequestedOrientation(){return orientation;} - public void setRequestedOrientation(int value){orientation=value;orientationWrites++;} - public boolean isFinishing(){return finishing;} public boolean isDestroyed(){return destroyed;} - public boolean hasWindowFocus(){return focused;} - public android.view.Window getWindow(){return window;} - }""", - "android/view/ViewTreeObserver.java": """package android.view; import java.util.*; - public class ViewTreeObserver { - public interface OnWindowFocusChangeListener {void onWindowFocusChanged(boolean focus);} - public final List listeners=new ArrayList<>(); - public boolean isAlive(){return true;} - public void addOnWindowFocusChangeListener(OnWindowFocusChangeListener l){listeners.add(l);} - public void removeOnWindowFocusChangeListener(OnWindowFocusChangeListener l){listeners.remove(l);} - public void focus(boolean value){for(var l:new ArrayList<>(listeners)) l.onWindowFocusChanged(value);} - }""", - "android/view/View.java": """package android.view; public class View { - public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE=256,SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN=1024, - SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION=512,SYSTEM_UI_FLAG_FULLSCREEN=4, - SYSTEM_UI_FLAG_HIDE_NAVIGATION=2,SYSTEM_UI_FLAG_IMMERSIVE_STICKY=4096; - public boolean attached=true,fits=true; public int visibilityCalls,insetRequests,visibility; - public View content; - public interface OnApplyWindowInsetsListener { WindowInsets onApplyWindowInsets(View view, WindowInsets insets); } - public OnApplyWindowInsetsListener insetListener; - public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener l){insetListener=l;} - public final ViewTreeObserver observer=new ViewTreeObserver(); - public final WindowInsetsController controller=new WindowInsetsController(); - public boolean isAttachedToWindow(){return attached;} - public ViewTreeObserver getViewTreeObserver(){return observer;} - public void setFitsSystemWindows(boolean b){fits=b;} - public View findViewById(int id){return content;} - public int getSystemUiVisibility(){return visibility;} - public void setSystemUiVisibility(int flags){visibilityCalls++;visibility=flags;} - public void requestApplyInsets(){insetRequests++;} - public WindowInsetsController getWindowInsetsController(){return controller;} - }""", - "android/view/WindowInsets.java": """package android.view; public class WindowInsets { - public static class Type { public static int systemBars(){return 7;} } - }""", - "android/view/WindowInsetsController.java": """package android.view; public class WindowInsetsController { - public static final int BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE=2; - public int hideCalls,behavior; public boolean transientVisible; - public void setSystemBarsBehavior(int b){behavior=b;} - public void hide(int types){hideCalls++;transientVisible=false;} - }""", - "android/view/WindowManager.java": """package android.view; public interface WindowManager { - public static class LayoutParams { - public static final int FLAG_FULLSCREEN=1024,LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS=3, - LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES=1; - public int layoutInDisplayCutoutMode,fitTypes=3; - public int getFitInsetsTypes(){return fitTypes;} public void setFitInsetsTypes(int t){fitTypes=t;} - } - }""", - "android/view/Window.java": """package android.view; public class Window { - public final View decor=new View(); public final WindowManager.LayoutParams attributes=new WindowManager.LayoutParams(); - public boolean fits=true; public int attributeWrites; - public Window(){decor.content=new View();} - public View getDecorView(){return decor;} public WindowManager.LayoutParams getAttributes(){return attributes;} - public void setAttributes(WindowManager.LayoutParams a){attributeWrites++;} - public void setDecorFitsSystemWindows(boolean value){fits=value;} public void addFlags(int flags){} - }""", - "com/bepinex/android/bpp/BppLauncherActivity.java": "package com.bepinex.android.bpp; public class BppLauncherActivity extends android.app.Activity {}", - "GameWindowTests.java": """import android.app.Activity; - import com.bepinex.android.bpp.BppGameWindow; - public class GameWindowTests { - static void check(boolean value,String message){if(!value) throw new AssertionError(message);} - static void apply(Activity activity){check(BppGameWindow.apply(activity),"Apply not queued");android.os.Handler.drain();} - static void reset(){BppGameWindow.reset();android.os.Handler.drain();} - static class LauncherSubclass extends com.bepinex.android.bpp.BppLauncherActivity {} - public static void main(String[] args){ - Activity game=new Activity(); var w=game.window; var d=w.decor; - BppGameWindow.apply(game); - check(d.controller.hideCalls==0,"Window mutated before UI queue dispatch"); - android.os.Handler.drain(); - check(game.orientation==6,"Fixed landscape was not changed to both landscape sides"); - apply(game); check(game.orientationWrites==1,"Redundant orientation request"); - game.orientation=8; apply(game); - check(game.orientation==6 && game.orientationWrites==2,"Unity fixed-orientation override not repaired"); - check(!w.fits && w.attributes.fitTypes==0,"Window must ignore visible bar insets"); - check(d.controller.behavior==2 && d.controller.hideCalls==1,"Initial sticky immersion"); - int immersive=d.visibility; - check(d.insetListener==null && d.content.insetListener==null,"Window helper must not replace native inset listeners"); - check(d.insetRequests==0 && d.content.insetRequests==0,"Binding must not force inset dispatch"); - int writes=w.attributeWrites; - d.controller.transientVisible=true; - for(int i=0;i<20;i++) apply(game); - check(d.controller.transientVisible && d.controller.hideCalls==1,"Heartbeat fights user's swipe"); - check(w.attributeWrites==writes && d.insetRequests==0 && d.visibilityCalls==1,"Heartbeat forces relayout"); - check(d.content.insetRequests==0,"Heartbeat redispatched child insets"); - game.focused=false; d.observer.focus(false); d.visibility=0; - apply(game); check(d.controller.hideCalls==1,"Unfocused policy repair stole shade"); - game.orientation=0; game.focused=true; d.observer.focus(true); - check(d.controller.hideCalls==1,"Focus repair ran inside Unity dispatch"); - // Unity's callback in the same dispatch restores decor fitting and requests bars, - // but can leave every legacy immersive bit set (the observed v33 failure). - w.fits=true; d.visibility=immersive; d.controller.transientVisible=true; - android.os.Handler.drain(); - check(game.orientation==6,"Focus did not restore both landscape sides"); - check(!w.fits && !d.controller.transientVisible && d.controller.hideCalls==2,"Deferred focus repair missed controller-only reset"); - check(d.insetRequests==0,"Focus return redispatched insets"); - d.visibility=0; // Unity rewrites requested flags after its player finishes loading. - apply(game); - check(d.controller.hideCalls==3 && d.visibilityCalls==2,"Unity policy reset not repaired"); - apply(game); - check(d.controller.hideCalls==3 && d.visibilityCalls==2,"Stable repaired policy reapplied"); - check(d.observer.listeners.size()==1,"Duplicate focus listeners"); - // Obsolete queued focus work cannot hide bars in a replaced Activity. - BppGameWindow.apply(new Activity()); d.observer.focus(true); android.os.Handler.drain(); - check(d.controller.hideCalls==3,"Replaced binding executed stale focus repair"); - Activity replacement=new Activity(); apply(replacement); - check(d.observer.listeners.isEmpty(),"Old activity retained its listener"); - check(d.insetListener==null,"Old decor retained inset listener"); - replacement.window.decor.observer.focus(true); - reset(); check(replacement.window.decor.observer.listeners.isEmpty(),"Reset leaked listener"); - check(replacement.window.decor.insetListener==null,"Reset leaked root insets listener"); - Activity launcher=new com.bepinex.android.bpp.BppLauncherActivity(); apply(launcher); - Activity subclass=new LauncherSubclass(); apply(subclass); - check(launcher.orientationWrites==0 && subclass.orientationWrites==0,"Launcher orientation changed"); - check(launcher.window.decor.controller.hideCalls==0 && subclass.window.decor.controller.hideCalls==0 - && launcher.window.fits && subclass.window.fits,"Launcher window was modified"); - check(replacement.window.decor.controller.hideCalls==1,"Launcher changed game window"); - Activity cancelled=new Activity(); BppGameWindow.apply(cancelled); reset(); - check(cancelled.window.decor.controller.hideCalls==0,"Reset did not cancel queued Activity capture"); - Activity destroyed=new Activity(); BppGameWindow.apply(destroyed); destroyed.destroyed=true; android.os.Handler.drain(); - check(destroyed.window.decor.controller.hideCalls==0,"Queued apply modified destroyed Activity"); - Activity pending=new Activity(); pending.window.decor.attached=false; apply(pending); - check(pending.window.decor.controller.hideCalls==0,"Unattached decor mutated"); - pending.window.decor.attached=true; apply(pending); - check(pending.window.decor.controller.hideCalls==1,"Attach retry lost"); - pending.window.decor.observer.focus(true); pending.focused=false; android.os.Handler.drain(); - check(pending.window.decor.controller.hideCalls==1,"Queued focus restore ignored subsequent focus loss"); - reset(); android.os.Build.VERSION.SDK_INT=28; - Activity legacy=new Activity(); apply(legacy); apply(legacy); - check(legacy.window.decor.visibilityCalls==1,"Legacy immersive repeats on heartbeat"); - legacy.window.decor.observer.focus(true); - android.os.Handler.drain(); - check(legacy.window.decor.visibilityCalls==2,"Legacy focus restore missing"); - check(legacy.window.decor.insetListener==null,"Legacy device received modern inset adapter"); - reset(); System.out.println("Game window lifecycle/gesture tests passed"); - } - }""", -} - - -class GameWindowTests(unittest.TestCase): - def test_unity_metadata_survives_fused_host_package(self): - from patch_manifest import ( - UNITY_WINDOW_METADATA, _encode_utf16_pool_string, _parse_string_pool, - _get_start_element_info, patch_unity_window_metadata, - ) - - # A binary fixture with an existing false Unity setting and unrelated metadata. - strings = ["manifest", "application", "meta-data", "name", "value", - "http://schemas.android.com/apk/res/android", - "unity.render-outside-safearea", "unrelated", "false"] - offsets, blob = [], b"" - for s in strings: - offsets.append(len(blob)) - blob += _encode_utf16_pool_string(s) - start = 28 + 4 * len(strings) - blob += b"\0" * (-(start + len(blob)) % 4) - pool = struct.pack(" tuple[str, list[tuple[str, str, list[str]]]]: - _, _, pool_size = struct.unpack_from(" tuple[int, str]: - _, _, pool_size = struct.unpack_from(" dict[str, str]: - _, _, pool_size = struct.unpack_from(" str: - _, _, pool_size = struct.unpack_from(" list[dict[str, str]]: - _, _, pool_size = struct.unpack_from(" dict[str, dict[str, str]]: - _, _, pool_size = struct.unpack_from(" list[int]: - off = 8 - while off < len(axml): - ct, ch, cs = struct.unpack_from(" len(axml): - raise AssertionError("Corrupt AXML chunk") - if ct == RES_XML_RESOURCE_MAP_TYPE: - count = (cs - ch) // 4 - if count == 0: - return [] - return list(struct.unpack_from(f"<{count}I", axml, off + ch)) - off += cs - raise AssertionError("resource map chunk not found") - - -def _assert_attribute_order_and_indices(axml: bytes) -> None: - _, _, pool_size = struct.unpack_from(" len(axml): - raise AssertionError("Corrupt AXML chunk") - if ct == RES_XML_START_ELEMENT_TYPE: - chunk = axml[off : off + cs] - _line, _comment, _ns, name, attr_start, attr_size, attr_count = struct.unpack_from( - ": {records}" - for label, index, expected_name in ( - ("idIndex", id_index, "id"), - ("classIndex", class_index, "class"), - ("styleIndex", style_index, "style"), - ): - assert 0 <= index <= attr_count, f"{label} out of range in <{element_name}>" - if index: - assert records[index - 1][0] == expected_name, ( - f"{label} in <{element_name}> points to {records[index - 1][0]!r}, " - f"expected {expected_name!r}" - ) - off += cs - - -def _assert_game_process_components(axml: bytes) -> None: - assert _application_name(axml) == GAME_APPLICATION, _application_name(axml) - - providers = _collect_providers(axml) - game = providers.get("com.bepinex.android.bpp.BppGameProcess") - assert game is not None, f"Missing :game diagnostics provider: {providers}" - assert game.get("process") == ":game", game - assert game.get("exported") == "0x0", game - assert game.get("authorities") == "com.bepinex.android.bpp.game-process", game - - services = [item for item in _collect_services(axml) if item.get("name") == GAME_SERVICE] - assert len(services) == 1, services - assert services[0].get("process") == ":game", services[0] - assert services[0].get("exported") == "0x0", services[0] - assert services[0].get("foregroundServiceType") == "0x40000000", services[0] - assert services[0].get("subtype") == FGS_SUBTYPE, services[0] - - -def main() -> int: - apk_path = ( - Path(sys.argv[1]) - if len(sys.argv) > 1 - else Path(__file__).resolve().parents[3] / "dist" / "app-bpp-fixed.apk" - ) - with zipfile.ZipFile(apk_path) as zf: - original = zf.read("AndroidManifest.xml") - - patched = patch_manifest_bytes( - original, version_code=2, version_name="6.0.0-preview.2", allow_repack=True - ) - _assert_attribute_order_and_indices(patched) - _assert_game_process_components(patched) - app_label, activities = _collect_activities(patched) - assert app_label == BPP_APP_LABEL, f"Unexpected label: {app_label}" - version_code, version_name = _read_manifest_version(patched) - assert version_code == 2, f"Unexpected versionCode: {version_code}" - assert version_name == "6.0.0-preview.2", f"Unexpected versionName: {version_name}" - metadata = _collect_metadata(patched) - for name in UNITY_WINDOW_METADATA: - assert metadata.get(name) == "0xffffffff", f"Missing or non-boolean Unity metadata: {name}" - - by_name = {name: (exp, actions) for name, exp, actions in activities} - assert BPP_ACTIVITY_NAME in by_name, "Missing BppLauncherActivity" - assert ORIG_MAIN_ACTIVITY_NAME in by_name, "Missing preserved MainActivity" - assert "com.bepinex.android.BootstrapActivity" in by_name, "Missing BootstrapActivity" - assert "com.bepinex.android.StubActivity" in by_name, "Missing StubActivity" - - bpp_exp, bpp_actions = by_name[BPP_ACTIVITY_NAME] - assert bpp_exp == "0xffffffff", f"BppLauncherActivity must be exported: {bpp_exp}" - assert "action:android.intent.action.MAIN" in bpp_actions - assert "category:android.intent.category.LAUNCHER" in bpp_actions - - orig_exp, orig_actions = by_name[ORIG_MAIN_ACTIVITY_NAME] - assert orig_exp == "0x0", f"Original MainActivity must not be exported: {orig_exp}" - assert orig_actions == [], f"Original MainActivity must not keep LAUNCHER filter: {orig_actions}" - - # Rejects double-patching - double_rejected = False - try: - patch_manifest_bytes(patched) - except ValueError: - double_rejected = True - assert double_rejected, "Expected double-patching to be rejected" - - repacked = patch_manifest_bytes(patched, version_code=38, version_name="6.0.0-preview.38", allow_repack=True) - _assert_attribute_order_and_indices(repacked) - _assert_game_process_components(repacked) - assert _read_manifest_version(repacked) == (38, "6.0.0-preview.38") - assert _collect_activities(repacked) == _collect_activities(patched), "Repack changed activities or filters" - stable = patch_manifest_bytes(repacked, version_code=39, version_name="6.0.0", allow_repack=True) - _assert_attribute_order_and_indices(stable) - _assert_game_process_components(stable) - assert _read_manifest_version(stable) == (39, "6.0.0") - providers = _collect_providers(stable) - game = providers.get("com.bepinex.android.bpp.BppGameProcess") - assert game is not None, f"Missing :game diagnostics provider: {providers}" - assert game.get("process") == ":game", game - assert game.get("exported") == "0x0", game - assert game.get("authorities") == "com.bepinex.android.bpp.game-process", game - again = patch_manifest_bytes(stable, version_code=40, version_name="6.0.0-preview.40", allow_repack=True) - _assert_attribute_order_and_indices(again) - _assert_game_process_components(again) - assert list(_collect_providers(again)).count("com.bepinex.android.bpp.BppGameProcess") == 1 - assert _application_name(stable) == GAME_APPLICATION, _application_name(stable) - assert _application_name(again) == GAME_APPLICATION - services = [item for item in _collect_services(stable) if item.get("name") == GAME_SERVICE] - assert len(services) == 1, services - assert services[0].get("process") == ":game", services[0] - assert services[0].get("exported") == "0x0", services[0] - assert services[0].get("foregroundServiceType") == "0x40000000", services[0] - assert services[0].get("subtype") == FGS_SUBTYPE, services[0] - assert len([item for item in _collect_services(again) if item.get("name") == GAME_SERVICE]) == 1 - assert _collect_activities(stable) == _collect_activities(patched) - assert _collect_metadata(stable) == _collect_metadata(patched) - - from patch_manifest import ensure_install_permission, _has_component - permission = "android.permission.REQUEST_INSTALL_PACKAGES" - assert _has_component(again, "uses-permission", permission) - assert ensure_install_permission(again) == again, "Permission duplicated on repack" - permission_manifest = ensure_install_permission(original) - assert _has_component(permission_manifest, "uses-permission", permission) - assert ensure_install_permission(permission_manifest) == permission_manifest - - print("PASS: AndroidManifest binary patcher tests succeeded.") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) - diff --git a/android-port/tools/bpp-launcher/verify_combined_apk.py b/android-port/tools/bpp-launcher/verify_combined_apk.py deleted file mode 100644 index 9639f19..0000000 --- a/android-port/tools/bpp-launcher/verify_combined_apk.py +++ /dev/null @@ -1,244 +0,0 @@ -"""Verifies that a combined BPP launcher APK preserves the verified base launcher. - -Usage: - verify_combined_apk.py [icon-dir] -""" - -import hashlib -import io -import struct -import sys -import zipfile -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from patch_manifest import ( # noqa: E402 - BPP_ACTIVITY_NAME, - BPP_APP_LABEL, - _get_start_element_info, - _parse_string_pool, -) -from replace_icon import ADAPTIVE, LEGACY_ROUND, LEGACY_SQUARE # noqa: E402 - -ORIGINAL_MAIN_ACTIVITY = "com.bepinex.android.MainActivity" -REQUIRED_ACTIVITIES = { - BPP_ACTIVITY_NAME, - ORIGINAL_MAIN_ACTIVITY, - "com.bepinex.android.BootstrapActivity", - "com.bepinex.android.StubActivity", -} -ALLOWED_NEW_ENTRIES = { - "assets/bpp-modpack.zip", - "assets/bpp-modpack-manifest.tsv", - "classes3.dex", -} -def is_signature_file(name: str) -> bool: - return name.startswith("META-INF/") and ( - name.endswith((".SF", ".RSA", ".DSA", ".EC")) or name == "META-INF/MANIFEST.MF" - ) -# The launcher icon is replaced by payload only: the manifest still points at the same adaptive -# icon XML and resources.arsc keeps the same resource IDs and background color. -ICON_ENTRIES = { - "res/QZ.png", - "res/zr.png", - "res/Em.png", - "res/Lf.png", - "res/as.png", - "res/9w.png", - "res/8c.png", - "res/FS.png", - "res/RJ.png", - "res/Gc.png", - "res/zR.png", - "res/yn.png", - "res/wb.png", - "res/fO.png", - "res/o-.png", -} -ICON_ASSET = {**ADAPTIVE, **LEGACY_SQUARE, **LEGACY_ROUND} -if set(ICON_ASSET) != ICON_ENTRIES: - raise SystemExit("Icon replacement and verification lists diverged") - - -def png_size(data: bytes) -> tuple[int, int]: - if len(data) < 24 or data[:8] != b"\x89PNG\r\n\x1a\n": - raise SystemExit("Launcher icon entry is not a PNG") - return struct.unpack(">II", data[16:24]) - - -def sha256(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - - -def read_manifest(axml: bytes): - _, _, pool_size = struct.unpack_from(" int: - if len(sys.argv) not in (6, 7): - print(__doc__.strip(), file=sys.stderr) - return 2 - base = Path(sys.argv[1]) - combined = Path(sys.argv[2]) - modpack_zip = Path(sys.argv[3]) - safe_runtime = Path(sys.argv[4]).read_bytes() - safe_harmony = Path(sys.argv[5]).read_bytes() - icon_dir = Path(sys.argv[6]) if len(sys.argv) == 7 else None - - with zipfile.ZipFile(base) as zb, zipfile.ZipFile(combined) as zc: - base_names = set(zb.namelist()) - combined_names = set(zc.namelist()) - missing = {name for name in base_names - combined_names if not is_signature_file(name)} - if missing: - raise SystemExit(f"Combined APK lost base entries: {sorted(missing)}") - new = {name for name in combined_names - base_names if not is_signature_file(name)} - if new != ALLOWED_NEW_ENTRIES - base_names: - raise SystemExit(f"Unexpected new APK entries: {sorted(new)}") - - native = [name for name in base_names if name.startswith("lib/") and name.endswith(".so")] - if len(native) < 15: - raise SystemExit(f"Expected at least 15 native libraries in base, found {len(native)}") - for name in native: - if zb.read(name) != zc.read(name): - raise SystemExit(f"Native library changed unexpectedly: {name}") - - for name in ("classes.dex", "classes2.dex", "resources.arsc"): - if zb.read(name) != zc.read(name): - raise SystemExit(f"Base entry changed unexpectedly: {name}") - - for name in base_names: - if name in {"AndroidManifest.xml", "assets/BepInEx.Android.zip"}: - continue - if is_signature_file(name) or name in ALLOWED_NEW_ENTRIES: - continue - if name in ICON_ENTRIES: - if icon_dir is None and zb.read(name) == zc.read(name): - raise SystemExit(f"Launcher icon was not replaced: {name}") - png_size(zc.read(name)) - continue - if zb.read(name) != zc.read(name): - raise SystemExit(f"Existing entry changed unexpectedly: {name}") - - if icon_dir is not None: - for name in ICON_ENTRIES: - replacement = icon_dir / ICON_ASSET[name] - if zc.read(name) != replacement.read_bytes(): - raise SystemExit(f"Launcher icon does not match the packaged asset: {name}") - - with zipfile.ZipFile(io.BytesIO(zb.read("assets/BepInEx.Android.zip"))) as zbo: - with zipfile.ZipFile(io.BytesIO(zc.read("assets/BepInEx.Android.zip"))) as zbz: - if set(zbo.namelist()) != set(zbz.namelist()): - raise SystemExit("Embedded BepInEx archive entry set changed") - changed = sorted( - name for name in zbo.namelist() if zbo.read(name) != zbz.read(name) - ) - if changed not in ( - [], - ["core/Il2CppInterop.HarmonySupport.dll"], - ["core/Il2CppInterop.HarmonySupport.dll", "core/Il2CppInterop.Runtime.dll"], - ["core/Il2CppInterop.Runtime.dll"], - ): - raise SystemExit(f"Unexpected embedded BepInEx changes: {changed}") - if zbz.read("core/Il2CppInterop.Runtime.dll") != safe_runtime: - raise SystemExit("Embedded BepInEx runtime is not the production-patched copy") - if zbz.read("core/Il2CppInterop.HarmonySupport.dll") != safe_harmony: - raise SystemExit("Embedded BepInEx HarmonySupport is not the production-patched copy") - - app_label, version_code, version_name, activities = read_manifest(zc.read("AndroidManifest.xml")) - if app_label != BPP_APP_LABEL: - raise SystemExit(f"Unexpected application label: {app_label}") - if not isinstance(version_code, int) or version_code < 2: - raise SystemExit(f"Invalid versionCode: {version_code}") - if not version_name: - raise SystemExit("Missing versionName") - if not REQUIRED_ACTIVITIES.issubset(activities): - raise SystemExit(f"Missing required activities: {REQUIRED_ACTIVITIES - set(activities)}") - bpp_exported, bpp_actions = activities[BPP_ACTIVITY_NAME] - if bpp_exported != "0xffffffff": - raise SystemExit("BppLauncherActivity must be exported") - if "action:android.intent.action.MAIN" not in bpp_actions: - raise SystemExit("BppLauncherActivity is missing MAIN action") - if "category:android.intent.category.LAUNCHER" not in bpp_actions: - raise SystemExit("BppLauncherActivity is missing LAUNCHER category") - orig_exported, orig_actions = activities[ORIGINAL_MAIN_ACTIVITY] - if orig_exported != "0x0" or orig_actions: - raise SystemExit("Original MainActivity must be internal and have no launcher filter") - - manifest_lines = zc.read("assets/bpp-modpack-manifest.tsv").decode("utf-8").strip().split("\n") - header = manifest_lines[0].split("\t") - if header[0] != "bundle_id": - raise SystemExit("Invalid embedded modpack manifest header") - embedded = zc.read("assets/bpp-modpack.zip") - if sha256(embedded) != header[1]: - raise SystemExit("Embedded modpack bundle_id does not match its bytes") - expected = Path(modpack_zip).read_bytes() - with zipfile.ZipFile(io.BytesIO(expected)) as source_zip, zipfile.ZipFile(io.BytesIO(embedded)) as embedded_zip: - source_names = {name.replace("\\", "/") for name in source_zip.namelist() if not name.endswith("/")} - if source_names != set(embedded_zip.namelist()): - raise SystemExit("Embedded modpack entry list differs from the packaged modpack") - for name in source_names: - if source_zip.read(name) != embedded_zip.read(name): - raise SystemExit(f"Embedded modpack entry changed: {name}") - if len(embedded_zip.namelist()) < 60: - raise SystemExit("Embedded modpack is unexpectedly small") - if not all( - name == "modpack.json" or name.startswith(("plugins/", "core/")) - for name in embedded_zip.namelist() - ): - raise SystemExit("Embedded modpack contains a path outside plugins/core") - forbidden = [ - name - for name in embedded_zip.namelist() - if name.lower().endswith((".cfg", ".db", ".sqlite", ".keystore", ".jks", ".mp4", ".png")) - ] - if forbidden: - raise SystemExit(f"Embedded modpack contains forbidden files: {forbidden}") - - if any(name.lower().endswith((".keystore", ".jks")) for name in combined_names): - raise SystemExit("Combined APK contains signing material") - - print( - "PASS: base native/DEX/resources preserved, manifest patched, " - f"versionCode={version_code}, versionName={version_name}, embedded modpack verified." - ) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/android-port/tools/codec-smoke/Program.cs b/android-port/tools/codec-smoke/Program.cs deleted file mode 100644 index 7874a6e..0000000 --- a/android-port/tools/codec-smoke/Program.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Reflection; -using System.Runtime.Loader; -using BazaarPlusPlus.Game.PvpBattles; - -var packaged = Path.GetFullPath(args[0]); -var build = Path.GetFullPath(args[1]); -AssemblyLoadContext.Default.Resolving += (_, name) => -{ - foreach (var directory in new[] { packaged, build }) - { - var path = Path.Combine(directory, name.Name + ".dll"); - if (File.Exists(path)) return AssemblyLoadContext.Default.LoadFromAssemblyPath(path); - } - return null; -}; -// Keep the game's same-name proxy loaded while the portable library resolves its aliases. -AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(args[2])); -var library = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(packaged, "BazaarPlusPlus.ModApi.dll")); -var types = library.GetTypes(); -var codec = types.Single(type => type.FullName == "BazaarPlusPlus.ModApi.MessagePackGzipCodec"); -var sample = new PvpReplayPayload -{ - BattleId = "android-codec-smoke", Version = 1, - SpawnMessageBytes = new byte[] { 0, 1, 2, 255 }, - CombatMessageBytes = new byte[] { 8, 13, 21 }, - DespawnMessageBytes = new byte[] { 34, 55 } -}; -var bytes = (byte[])codec.GetMethod("Serialize")!.MakeGenericMethod(typeof(PvpReplayPayload)).Invoke(null, new object[] { sample })!; -var parameters = new object?[] { bytes, null, null, null, null }; -var success = (bool)codec.GetMethod("TryDeserialize")!.MakeGenericMethod(typeof(PvpReplayPayload)).Invoke(null, parameters)!; -if (!success || parameters[1] is not PvpReplayPayload actual - || actual.BattleId != sample.BattleId || actual.Version != sample.Version - || !actual.SpawnMessageBytes.SequenceEqual(sample.SpawnMessageBytes) - || !actual.CombatMessageBytes.SequenceEqual(sample.CombatMessageBytes) - || !actual.DespawnMessageBytes.SequenceEqual(sample.DespawnMessageBytes)) - throw new Exception($"Round trip failed: {parameters[2]} {parameters[3]}"); -Console.WriteLine($"PASS: {types.Length} portable types loaded; replay gzip round trip ({bytes.Length} bytes), alongside native MessagePack proxy."); diff --git a/android-port/tools/codec-smoke/Smoke.csproj b/android-port/tools/codec-smoke/Smoke.csproj deleted file mode 100644 index ecf1312..0000000 --- a/android-port/tools/codec-smoke/Smoke.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - Exenet8.0enable - - diff --git a/android-port/tools/package-managed-codec/Package.csproj b/android-port/tools/package-managed-codec/Package.csproj deleted file mode 100644 index 5298238..0000000 --- a/android-port/tools/package-managed-codec/Package.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - Exenet8.0enable - - diff --git a/android-port/tools/package-managed-codec/Program.cs b/android-port/tools/package-managed-codec/Program.cs deleted file mode 100644 index 1777735..0000000 --- a/android-port/tools/package-managed-codec/Program.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Mono.Cecil; - -// Portable DTO codecs need CLR MessagePack interfaces. The game has unsigned IL2CPP -// proxy classes with the same simple names; give the portable runtime private identities. -// Namespaces and wire contracts remain unchanged, and native messages keep the game codec. -if (args.Length != 2) throw new ArgumentException("Expected build-output and destination directories."); -var source = Path.GetFullPath(args[0]); -var destination = Path.GetFullPath(args[1]); -Directory.CreateDirectory(destination); -var aliases = new Dictionary -{ - ["MessagePack"] = "Bpp.Managed.MessagePack", - ["MessagePack.Annotations"] = "Bpp.Managed.MessagePack.Annotations", - ["Microsoft.NET.StringTools"] = "Bpp.Managed.StringTools" -}; -foreach (var name in new[] { "BazaarPlusPlus.ModApi", "MessagePack", "MessagePack.Annotations", "Microsoft.NET.StringTools" }) -{ - using var module = ModuleDefinition.ReadModule(Path.Combine(source, name + ".dll")); - if (aliases.TryGetValue(module.Assembly.Name.Name, out var alias)) - module.Assembly.Name.Name = alias; - foreach (var reference in module.AssemblyReferences) - if (aliases.TryGetValue(reference.Name, out var renamed)) reference.Name = renamed; - var path = Path.Combine(destination, module.Assembly.Name.Name + ".dll"); - module.Write(path); - using var check = ModuleDefinition.ReadModule(path); - if (check.AssemblyReferences.Any(reference => aliases.ContainsKey(reference.Name))) - throw new InvalidOperationException($"Unisolated MessagePack reference: {path}"); - Console.WriteLine(check.Assembly.Name.FullName); -} diff --git a/android-port/tools/patch-bepinex-interop-prefix/InteropPrefixPatch.cs b/android-port/tools/patch-bepinex-interop-prefix/InteropPrefixPatch.cs deleted file mode 100644 index e0defc1..0000000 --- a/android-port/tools/patch-bepinex-interop-prefix/InteropPrefixPatch.cs +++ /dev/null @@ -1,118 +0,0 @@ -using Mono.Cecil; -using Mono.Cecil.Cil; - -/// The edits Program.cs describes, callable from the tests. -internal static class InteropPrefixPatch -{ - public const string HashMarker = "|il2cpp-prefix:OptOut"; - - /// Patches into ; returns what it did. - public static string Apply(string input, string output, IEnumerable searchDirectories) - { - input = Path.GetFullPath(input); - output = Path.GetFullPath(output); - using var resolver = new DefaultAssemblyResolver(); - resolver.AddSearchDirectory(Path.GetDirectoryName(input)!); - foreach (var dir in searchDirectories) - resolver.AddSearchDirectory(Path.GetFullPath(dir)); - var bytes = File.ReadAllBytes(input); - using var module = ModuleDefinition.ReadModule( - new MemoryStream(bytes), - new ReaderParameters { AssemblyResolver = resolver } - ); - var manager = - module.GetTypes().FirstOrDefault(t => t.Name == "Il2CppInteropManager") - ?? throw new PatchException("type Il2CppInteropManager not found"); - var prefix = PatchPrefixMode(module, manager); - var hash = PatchHash(module, manager); - if (!prefix && !hash) - { - if (input != output) - File.Copy(input, output, overwrite: true); - return "already patched"; - } - module.Write(output); - return $"patched prefix_mode={prefix} hash_marker={hash} -> {output}"; - } - - internal static bool PatchPrefixMode(ModuleDefinition module, TypeDefinition manager) - { - var method = - manager.Methods.FirstOrDefault(m => m.Name == "RunIl2CppInteropGenerator" && m.HasBody) - ?? throw new PatchException("method RunIl2CppInteropGenerator not found"); - var instructions = method.Body.Instructions; - var create = instructions - .Where(i => - i.OpCode == OpCodes.Newobj - && i.Operand is MethodReference ctor - && ctor.DeclaringType.Name == "GeneratorOptions" - ) - .ToList(); - if (create.Count != 1) - throw new PatchException( - $"expected one new GeneratorOptions in RunIl2CppInteropGenerator, found {create.Count}" - ); - if ( - instructions.Any(i => - i.Operand is MethodReference m && m.Name == "set_Il2CppPrefixMode" - ) - ) - return false; - - var options = ((MethodReference)create[0].Operand).DeclaringType.Resolve() - ?? throw new PatchException("GeneratorOptions could not be resolved; pass BepInEx/core"); - var setter = - options.Methods.FirstOrDefault(m => m.Name == "set_Il2CppPrefixMode") - ?? throw new PatchException( - "this Il2CppInterop.Generator has no Il2CppPrefixMode (needs 1.4.5 or later)" - ); - var modeType = setter.Parameters[0].ParameterType.Resolve(); - var optOut = - modeType.Fields.FirstOrDefault(f => f.IsLiteral && f.Name == "OptOut") - ?? throw new PatchException("PrefixMode has no OptOut"); - - var il = method.Body.GetILProcessor(); - var dup = il.Create(OpCodes.Dup); - var value = il.Create(OpCodes.Ldc_I4, Convert.ToInt32(optOut.Constant)); - var set = il.Create(OpCodes.Callvirt, module.ImportReference(setter)); - il.InsertAfter(create[0], dup); - il.InsertAfter(dup, value); - il.InsertAfter(value, set); - return true; - } - - internal static bool PatchHash(ModuleDefinition module, TypeDefinition manager) - { - var method = - manager.Methods.FirstOrDefault(m => - m.Name == "ComputeHash" - && m.HasBody - && m.ReturnType.FullName == "System.String" - && m.Parameters.Count == 0 - ) ?? throw new PatchException("method string ComputeHash() not found"); - if ( - method.Body.Instructions.Any(i => - i.OpCode == OpCodes.Ldstr && (string)i.Operand == HashMarker - ) - ) - return false; - var concat = module.ImportReference( - typeof(string).GetMethod(nameof(string.Concat), [typeof(string), typeof(string)]) - ); - var il = method.Body.GetILProcessor(); - foreach (var ret in method.Body.Instructions.Where(i => i.OpCode == OpCodes.Ret).ToList()) - { - // Keep branch targets on the original ret valid: the new code goes in front of it as the - // same instruction object, which becomes the marker load. - var originalRet = il.Create(OpCodes.Ret); - ret.OpCode = OpCodes.Ldstr; - ret.Operand = HashMarker; - var call = il.Create(OpCodes.Call, concat); - il.InsertAfter(ret, call); - il.InsertAfter(call, originalRet); - } - return true; - } -} - -internal sealed class PatchException(string message) : Exception(message); diff --git a/android-port/tools/patch-bepinex-interop-prefix/Patch.csproj b/android-port/tools/patch-bepinex-interop-prefix/Patch.csproj deleted file mode 100644 index 200b207..0000000 --- a/android-port/tools/patch-bepinex-interop-prefix/Patch.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - Exe - net6.0 - Major - enable - 12 - enable - patch-bepinex-interop-prefix - false - - - - - - - - diff --git a/android-port/tools/patch-bepinex-interop-prefix/Program.cs b/android-port/tools/patch-bepinex-interop-prefix/Program.cs deleted file mode 100644 index a393931..0000000 --- a/android-port/tools/patch-bepinex-interop-prefix/Program.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Makes the launcher's BepInEx generate interop the way MelonLoader/LemonLoader does -// (Il2CppPrefixMode.OptOut: Il2CppTheBazaar, Il2CppTMPro, Il2Cpp, Il2CppNewtonsoft.Json, ...), so -// upstream's Android Host binds to it unchanged (android-port/upstream-host/README.md). -// -// Two edits to BepInEx.Unity.IL2CPP.dll's Il2CppInteropManager: -// RunIl2CppInteropGenerator: sets GeneratorOptions.Il2CppPrefixMode = OptOut on the options it builds; -// ComputeHash: appends a marker, so interop generated without the prefix counts as out of date -// and is regenerated once. -// Idempotent; fails without writing when the expected shapes are missing. -// -// Usage: patch-bepinex-interop-prefix [...] -// The input's own directory is searched for Il2CppInterop.Generator.dll; pass BepInEx/core when -// the input sits elsewhere. - -if (args.Length < 2) -{ - Console.Error.WriteLine( - "usage: patch-bepinex-interop-prefix [...]" - ); - return 2; -} - -try -{ - var result = InteropPrefixPatch.Apply(args[0], args[1], args.Skip(2)); - Console.WriteLine(result); - return 0; -} -catch (PatchException exception) -{ - Console.Error.WriteLine($"not patched: {exception.Message}"); - return 1; -} diff --git a/android-port/tools/patch-bepinex-interop-prefix/fixture/Fixture.csproj b/android-port/tools/patch-bepinex-interop-prefix/fixture/Fixture.csproj deleted file mode 100644 index 27e6e2c..0000000 --- a/android-port/tools/patch-bepinex-interop-prefix/fixture/Fixture.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net6.0 - BepInEx.Unity.IL2CPP - true - enable - enable - false - - - - - diff --git a/android-port/tools/patch-bepinex-interop-prefix/fixture/Il2CppInteropManager.cs b/android-port/tools/patch-bepinex-interop-prefix/fixture/Il2CppInteropManager.cs deleted file mode 100644 index 87ddddd..0000000 --- a/android-port/tools/patch-bepinex-interop-prefix/fixture/Il2CppInteropManager.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Security.Cryptography; -using System.Text; -using Il2CppInterop.Generator; - -namespace BepInEx.Unity.IL2CPP; - -// Shapes copied from BepInEx master Runtimes/Unity/BepInEx.Unity.IL2CPP/Il2CppInteropManager.cs. -public static class Il2CppInteropManager -{ - public static GeneratorOptions? LastOptions { get; private set; } - - public static string Hash() => ComputeHash(); - - public static void Generate(bool regex) => - RunIl2CppInteropGenerator(new List(), regex); - - private static string ComputeHash() - { - using var md5 = MD5.Create(); - var bytes = Encoding.UTF8.GetBytes("game"); - md5.TransformFinalBlock(bytes, 0, bytes.Length); - return Convert.ToHexString(md5.Hash!); - } - - private static void RunIl2CppInteropGenerator( - List sourceAssemblies, - bool regex - ) - { - var opts = new GeneratorOptions - { - GameAssemblyPath = null, - Source = sourceAssemblies, - OutputDir = "interop", - UnityBaseLibsDir = null, - ObfuscatedNamesRegex = regex ? new System.Text.RegularExpressions.Regex("x") : null, - }; - LastOptions = opts; - } -} diff --git a/android-port/tools/patch-bepinex-interop-prefix/tests/InteropPrefixPatchTests.cs b/android-port/tools/patch-bepinex-interop-prefix/tests/InteropPrefixPatchTests.cs deleted file mode 100644 index 2467adf..0000000 --- a/android-port/tools/patch-bepinex-interop-prefix/tests/InteropPrefixPatchTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Reflection; -using System.Runtime.Loader; -using Xunit; - -public sealed class InteropPrefixPatchTests : IDisposable -{ - private static readonly string FixtureDir = Path.GetFullPath( - Path.Combine(AppContext.BaseDirectory, "../../../../fixture/bin/Debug/net6.0") - ); - - private readonly string _work = Directory.CreateTempSubdirectory("bpp-prefix-patch").FullName; - - public void Dispose() => Directory.Delete(_work, recursive: true); - - [Fact] - public void Patched_generator_options_use_opt_out_prefixes() - { - var patched = Patch(); - var manager = Load(patched); - manager.GetMethod("Generate")!.Invoke(null, [false]); - var options = manager.GetProperty("LastOptions")!.GetValue(null)!; - Assert.Equal("OptOut", options.GetType().GetProperty("Il2CppPrefixMode")!.GetValue(options)!.ToString()); - Assert.Equal("interop", options.GetType().GetProperty("OutputDir")!.GetValue(options)); - } - - [Fact] - public void Patched_hash_differs_from_the_original_by_the_marker() - { - var original = (string)Load(Path.Combine(FixtureDir, "BepInEx.Unity.IL2CPP.dll")) - .GetMethod("Hash")! - .Invoke(null, null)!; - var patched = (string)Load(Patch()).GetMethod("Hash")!.Invoke(null, null)!; - Assert.Equal(original + InteropPrefixPatch.HashMarker, patched); - } - - [Fact] - public void Patching_twice_changes_nothing() - { - var once = Patch(); - var twice = Path.Combine(_work, "twice", "BepInEx.Unity.IL2CPP.dll"); - Directory.CreateDirectory(Path.GetDirectoryName(twice)!); - Assert.Equal("already patched", InteropPrefixPatch.Apply(once, twice, [FixtureDir])); - Assert.Equal(File.ReadAllBytes(once), File.ReadAllBytes(twice)); - } - - [Fact] - public void An_assembly_without_the_manager_is_refused() - { - var output = Path.Combine(_work, "out.dll"); - var other = Path.Combine(FixtureDir, "Il2CppInterop.Generator.dll"); - Assert.Throws(() => InteropPrefixPatch.Apply(other, output, [])); - Assert.False(File.Exists(output)); - } - - private string Patch() - { - var output = Path.Combine(_work, Guid.NewGuid().ToString("N"), "BepInEx.Unity.IL2CPP.dll"); - Directory.CreateDirectory(Path.GetDirectoryName(output)!); - InteropPrefixPatch.Apply( - Path.Combine(FixtureDir, "BepInEx.Unity.IL2CPP.dll"), - output, - [FixtureDir] - ); - return output; - } - - private static Type Load(string path) - { - var context = new AssemblyLoadContext(null, isCollectible: true); - context.Resolving += (ctx, name) => - { - var candidate = Path.Combine(FixtureDir, name.Name + ".dll"); - return File.Exists(candidate) ? ctx.LoadFromAssemblyPath(candidate) : null; - }; - // From bytes: a path load maps the file, and Windows then refuses to delete _work. - return context - .LoadFromStream(new MemoryStream(File.ReadAllBytes(path))) - .GetType("BepInEx.Unity.IL2CPP.Il2CppInteropManager", throwOnError: true)!; - } -} diff --git a/android-port/tools/patch-bepinex-interop-prefix/tests/Tests.csproj b/android-port/tools/patch-bepinex-interop-prefix/tests/Tests.csproj deleted file mode 100644 index ab444a8..0000000 --- a/android-port/tools/patch-bepinex-interop-prefix/tests/Tests.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - net10.0 - enable - enable - 12 - false - - - - - - - - - - - - - - - diff --git a/android-port/tools/patch-harmony-arm64/Patch.csproj b/android-port/tools/patch-harmony-arm64/Patch.csproj deleted file mode 100644 index 5298238..0000000 --- a/android-port/tools/patch-harmony-arm64/Patch.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - Exenet8.0enable - - diff --git a/android-port/tools/patch-harmony-arm64/Program.cs b/android-port/tools/patch-harmony-arm64/Program.cs deleted file mode 100644 index e273d7c..0000000 --- a/android-port/tools/patch-harmony-arm64/Program.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Mono.Cecil; -using Mono.Cecil.Cil; -using Mono.Cecil.Rocks; - -// Patch only the Android ARM64 distribution. AAPCS64 passes the single-pointer -// CancellationToken struct in a register by value. The x64-oriented converter -// instead boxes memory at that register value (the CancellationTokenSource object). -// Emit ldarga for this one known 8-byte struct so boxing reads the token itself. -if (args.Length != 2) throw new ArgumentException("Expected input and output HarmonySupport DLL paths."); -using var module = ModuleDefinition.ReadModule(args[0]); -var owner = module.Types.Single(t => t.Name == "Il2CppDetourMethodPatcher"); -var convert = owner.Methods.Single(m => m.Name == "EmitConvertArgumentToManaged"); -// Inserting even one byte can overflow the original Nullable branch's 127-byte -// short jump. Widen branches before editing so Cecil preserves their targets. -convert.Body.SimplifyMacros(); -if (owner.Methods.Any(m => m.Name == "BppAndroidUsesIndirectStructArgument")) - throw new InvalidOperationException("Input has already been patched."); -var calls = convert.Body.Instructions.Where(i => i.OpCode == OpCodes.Call - && i.Operand is MethodReference m && m.FullName == "System.Boolean System.Environment::get_Is64BitProcess()").ToArray(); -if (calls.Length == 0) throw new InvalidOperationException($"Expected original ABI selection, found {calls.Length}."); - -// In newer HarmonySupport, there is a call in the Nullable unbox branch and a call in the ValueType box branch. -// We patch the boxing branch (the one near il2cpp_value_box). -var original = calls.Length == 1 ? calls[0] : calls.Last(); -var is64 = (MethodReference)original.Operand; -var helper = new MethodDefinition("BppAndroidUsesIndirectStructArgument", - MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig, module.TypeSystem.Boolean); -helper.Parameters.Add(new ParameterDefinition("type", ParameterAttributes.None, convert.Parameters[2].ParameterType)); -owner.Methods.Add(helper); -var fullName = new MethodReference("get_FullName", module.TypeSystem.String, helper.Parameters[0].ParameterType) { HasThis = true }; -var equal = new MethodReference("op_Equality", module.TypeSystem.Boolean, module.TypeSystem.String); -equal.Parameters.Add(new ParameterDefinition(module.TypeSystem.String)); -equal.Parameters.Add(new ParameterDefinition(module.TypeSystem.String)); -var il = helper.Body.GetILProcessor(); -var otherType = il.Create(OpCodes.Call, is64); -il.Emit(OpCodes.Ldarg_0); -il.Emit(OpCodes.Callvirt, fullName); -il.Emit(OpCodes.Ldstr, "Il2CppSystem.Threading.CancellationToken"); -il.Emit(OpCodes.Call, equal); -il.Emit(OpCodes.Brfalse_S, otherType); -il.Emit(OpCodes.Ldc_I4_0); -il.Emit(OpCodes.Ret); -il.Append(otherType); -il.Emit(OpCodes.Ret); -convert.Body.GetILProcessor().InsertBefore(original, Instruction.Create(OpCodes.Ldarg, convert.Parameters[2])); -original.Operand = helper; -module.Write(args[1]); -using var verified = ModuleDefinition.ReadModule(args[1]); -var method = verified.Types.Single(t => t.Name == owner.Name).Methods.Single(m => m.Name == convert.Name); -if (method.Body.Instructions.Count(i => i.Operand is MethodReference m && m.Name == helper.Name) != 1) - throw new InvalidOperationException("Written converter does not contain the ABI correction."); -Console.WriteLine($"Patched Android ARM64 CancellationToken boxing: {args[1]}"); diff --git a/android-port/tools/persistence-smoke/Program.cs b/android-port/tools/persistence-smoke/Program.cs deleted file mode 100644 index e31f3af..0000000 --- a/android-port/tools/persistence-smoke/Program.cs +++ /dev/null @@ -1,36 +0,0 @@ -using BazaarPlusPlus.Game.CombatReplay; -using BazaarPlusPlus.Game.PvpBattles; - -static void Require(bool condition, string message) -{ - if (!condition) throw new Exception(message); -} - -foreach (var failManifest in new[] { false, true }) -{ - using var gate = new ReplayPayloadOperationGate(); - var writes = new List(); - var producer = Environment.CurrentManagedThreadId; - var worker = producer; - using var queue = new CombatReplayPersistenceQueue( - _ => { worker = Environment.CurrentManagedThreadId; writes.Add("payload"); }, - _ => { if (failManifest) throw new IOException("injected manifest failure"); writes.Add("manifest"); }, - _ => writes.Add("rollback"), gate); - queue.Enqueue(new PvpReplayPayload { BattleId = "test" }, new PvpBattleManifest { BattleId = "test" }); - CombatReplayPersistenceResult result = default; - Require(SpinWait.SpinUntil(() => queue.TryDequeueResult(out result), TimeSpan.FromSeconds(5)), "Android queue did not complete"); - Require(worker != producer, "Save ran on producer thread"); - Require(result.Succeeded != failManifest, "Wrong completion status"); - Require(writes.SequenceEqual(failManifest ? new[] { "payload", "rollback" } : new[] { "payload", "manifest" }), "Wrong persistence/rollback order"); - Require(!queue.HasPendingPersistence, "Pending count did not drain"); -} -using (var gate = new ReplayPayloadOperationGate()) -{ - var count = 0; - var queue = new CombatReplayPersistenceQueue(_ => { }, _ => Interlocked.Increment(ref count), _ => { }, gate); - for (var i = 0; i < 20; i++) - queue.Enqueue(new PvpReplayPayload { BattleId = i.ToString() }, new PvpBattleManifest { BattleId = i.ToString() }); - queue.Dispose(); - Require(count == 20, "Shutdown lost queued writes"); -} -Console.WriteLine("PASS: Android background persistence, rollback, result counts, and shutdown drain."); diff --git a/android-port/tools/persistence-smoke/Smoke.csproj b/android-port/tools/persistence-smoke/Smoke.csproj deleted file mode 100644 index 95499e4..0000000 --- a/android-port/tools/persistence-smoke/Smoke.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - Exenet8.0 - enableenable - $(DefineConstants);BPP_ANDROID - - - - - - - diff --git a/android-port/tools/persistence-smoke/Stubs.cs b/android-port/tools/persistence-smoke/Stubs.cs deleted file mode 100644 index 4f84a3b..0000000 --- a/android-port/tools/persistence-smoke/Stubs.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Only storage delegates and logging are substituted; queue/gate are production Android sources. -namespace BazaarPlusPlus.Game.PvpBattles -{ - internal sealed class PvpBattleManifest { public string BattleId { get; set; } = ""; } -} -namespace BazaarPlusPlus.Infrastructure.Logging -{ - internal enum BppLogFeatureScope { CombatReplay } - internal enum BppLogCorrelationPolicy { Short } - internal sealed record BppLogEvent(BppLogFeatureScope Scope, string Id); -} -namespace BazaarPlusPlus.Infrastructure -{ - using Logging; - internal static class BppLog - { - public static void InfoEvent(BppLogEvent e, params object[] fields) { } - public static void DebugEvent(BppLogEvent e, Func fields) { } - public static void DebugEvent(BppLogEvent e, Exception error, Func fields) { } - } -} diff --git a/android-port/tools/verify-patch-targets.ps1 b/android-port/tools/verify-patch-targets.ps1 deleted file mode 100644 index fcdbd90..0000000 --- a/android-port/tools/verify-patch-targets.ps1 +++ /dev/null @@ -1,44 +0,0 @@ -param( - [string] $DumpCs = 'D:\thebarzaar\dumped3\dump.cs', - [string] $Source = 'D:\thebarzaar\BazaarPlusPlus\bazaarplusplus-mod\src\BazaarPlusPlus' -) - -# Verifies that every Harmony patch target type exists in the dumped game assembly. -# -# A missing target does not fail the build: Harmony resolves it at runtime and only logs an -# error, so the plugin loads while the feature silently stays absent. This check turns that -# into a build-time signal after every game update (regenerate dump.cs with Il2CppDumper first). - -$ErrorActionPreference = 'Stop' - -if (-not (Test-Path $DumpCs)) { throw "dump.cs not found: $DumpCs" } -if (-not (Test-Path $Source)) { throw "Source not found: $Source" } - -Write-Host "Indexing type declarations in $DumpCs ..." -$types = New-Object 'System.Collections.Generic.HashSet[string]' -$reader = [System.IO.File]::OpenText($DumpCs) -try { - while ($null -ne ($line = $reader.ReadLine())) { - if ($line -match '^\s*(?:public |internal |private |protected |static |sealed |abstract |partial |readonly |unsafe )*(?:class|struct|interface|enum)\s+([A-Za-z0-9_]+)') { - [void]$types.Add($Matches[1]) - } - } -} -finally { $reader.Close() } - -$files = Get-ChildItem $Source -Recurse -Filter *.cs | Select-Object -ExpandProperty FullName -$targets = Select-String -Path $files -Pattern '\[HarmonyPatch\(typeof\(([A-Za-z0-9_]+)\)' | - ForEach-Object { $_.Matches[0].Groups[1].Value } | - Sort-Object -Unique - -Write-Host ("Patch target types: {0}" -f $targets.Count) - -$missing = @($targets | Where-Object { -not $types.Contains($_) }) -if ($missing.Count -eq 0) { - Write-Host "All patch target types exist in the game assembly." - exit 0 -} - -Write-Host ("MISSING {0} target type(s):" -f $missing.Count) -$missing | ForEach-Object { Write-Host (" " + $_) } -exit 1 diff --git a/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/AndroidSqlite.cs b/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/AndroidSqlite.cs deleted file mode 100644 index c0b21d8..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/AndroidSqlite.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; -using BepInEx; -using BepInEx.Logging; - -namespace BazaarPlusPlus.BepInExBridge; - -/// -/// Makes e_sqlite3 loadable before upstream's record chain opens its database. Upstream's -/// APK carries the library in its own lib/; under the launcher, CoreCLR's linker namespace -/// cannot map it from external storage (android-port/HANDOVER-ANDROID-PORT.md), so this loads it -/// from beside libcoreclr.so, or from a copy staged in the game root, and resolves the -/// payload's provider imports to it. Same approach as the fork plugin's -/// Infrastructure/AndroidNativeLibraries. -/// -internal static class AndroidSqlite -{ - private const string ProviderAssembly = "SQLitePCLRaw.provider.e_sqlite3.dll"; - - // Kept for the process lifetime; native SQLite owns live callbacks. - private static IntPtr _handle; - - public static void Load(ManualLogSource log, string userLibsDirectory) - { - try - { - var coreClr = File.ReadLines("/proc/self/maps") - .Select(line => - line.IndexOf('/') is var start && start >= 0 ? line[start..].Trim() : string.Empty - ) - .First(path => path.EndsWith("/libcoreclr.so", StringComparison.Ordinal)); - var sqlite = Path.Combine(Path.GetDirectoryName(coreClr)!, "libe_sqlite3.so"); - if (!File.Exists(sqlite)) - { - sqlite = Path.Combine(Paths.GameRootPath, "libe_sqlite3.so"); - File.Copy(Path.Combine(Paths.PluginPath, "libe_sqlite3.so"), sqlite, overwrite: true); - } - _handle = NativeLibrary.Load(sqlite); - var provider = Assembly.LoadFrom(Path.Combine(userLibsDirectory, ProviderAssembly)); - NativeLibrary.SetDllImportResolver( - provider, - (name, _, _) => name is "e_sqlite3" or "libe_sqlite3.so" ? _handle : IntPtr.Zero - ); - log.LogInfo($"bridge.sqlite.loaded native_path={sqlite}"); - } - catch (Exception exception) - { - // Upstream's record chain then fails to start and logs why; the hooks still run. - log.LogWarning($"bridge.sqlite.unavailable {exception}"); - } - } -} diff --git a/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/BazaarPlusPlus.BepInExBridge.csproj b/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/BazaarPlusPlus.BepInExBridge.csproj deleted file mode 100644 index 98bfc2f..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/BazaarPlusPlus.BepInExBridge.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - BazaarPlusPlus.BepInExBridge - BazaarPlusPlus.BepInExBridge - 2.0.0 - true - - - - - - - - - - - - - - - - - - - - - diff --git a/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/BridgePlugin.cs b/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/BridgePlugin.cs deleted file mode 100644 index 502f58c..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/BridgePlugin.cs +++ /dev/null @@ -1,183 +0,0 @@ -using System.Reflection; -using System.Runtime.Loader; -using BazaarPlusPlus.OfficialPayload; -using BepInEx; -using BepInEx.Logging; -using BepInEx.Unity.IL2CPP; -using MelonLoader; -using UnityEngine; -using UnityEngine.Events; -using UnityEngine.SceneManagement; - -namespace BazaarPlusPlus.BepInExBridge; - -/// -/// Runs upstream's own published Android Managed Payload as LemonLoader would, inside the -/// launcher's BepInEx. The payload lives where LemonLoader keeps it, MelonLoader/Mods and -/// MelonLoader/UserLibs under the game root, so its Data Root is the game root's -/// BazaarPlusPlusV6 (upstream AndroidPaths), the directory this fork's plugin used. -/// installs and updates it before anything of it loads. -/// -[BepInPlugin(Guid, "BazaarPlusPlus", "2.0.0")] -public sealed class BridgePlugin : BasePlugin -{ - public const string Guid = "com.bazaarplusplus.android.upstream"; - - private const string MainMenuScene = "MainMenuScene"; - - private static MelonCompatHost? _host; - private static OfficialPayloadInstall? _payload; - - internal static MelonCompatHost? Host => _host; - - public override void Load() - { - var log = Log; - MelonLogger.Sink = (name, level, text) => Write(log, name, level, text); - try - { - LetterBoxPatches.Apply(new HarmonyLib.Harmony(Guid)); - log.LogInfo("bridge.letterbox.patched"); - } - catch (Exception exception) - { - log.LogWarning($"bridge.letterbox.unavailable {exception}"); - } - var payload = new OfficialPayloadInstall( - Paths.GameRootPath, - new[] - { - Path.Combine(Paths.BepInExRootPath, "interop"), - Paths.BepInExAssemblyDirectory, - Paths.PluginPath, - }, - log.LogInfo, - log.LogWarning, - log.LogError - ); - payload.StageBundled(Path.Combine(Paths.PluginPath, OfficialPayloadInstall.BundledFileName)); - payload.ScreenStaged(); - payload.Apply(); - if (!payload.BeginLaunch()) - return; - _payload = payload; - - var mod = LoadMod(payload, log); - if (mod == null) - return; - AndroidSqlite.Load(log, payload.UserLibsDirectory); - try - { - _host = MelonCompatHost.Create(mod, payload.MelonBaseDirectory); - } - catch (Exception exception) - { - log.LogError($"upstream melon could not be created: {exception}"); - return; - } - log.LogInfo( - $"bridge.loaded melon={_host.Melon.Info.Name} version={_host.Melon.Info.Version} melon_base={payload.MelonBaseDirectory}" - ); - AddComponent(); - SceneManager.sceneLoaded += (UnityAction)OnSceneLoaded; - SceneManager.sceneUnloaded += (UnityAction)OnSceneUnloaded; - _host.Initialize(); - } - - public override bool Unload() - { - _host?.Quit(); - return true; - } - - // LemonLoader's order: UserLibs resolve first, then the Mods; the mod is the assembly that - // names its melon. - private static Assembly? LoadMod(OfficialPayloadInstall payload, ManualLogSource log) - { - AssemblyLoadContext.Default.Resolving += (context, name) => - { - foreach (var directory in new[] { payload.UserLibsDirectory, payload.ModsDirectory }) - { - var candidate = Path.Combine(directory, name.Name + ".dll"); - if (File.Exists(candidate)) - return context.LoadFromAssemblyPath(candidate); - } - return null; - }; - try - { - foreach (var path in Directory.GetFiles(payload.ModsDirectory, "*.dll")) - { - var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(path); - if (assembly.GetCustomAttribute() != null) - return assembly; - } - log.LogError($"bridge.mod_missing mods={payload.ModsDirectory}"); - } - catch (Exception exception) - { - log.LogError($"bridge.mod_load_failed {exception}"); - } - return null; - } - - private static void OnSceneLoaded(Scene scene, LoadSceneMode mode) - { - var name = scene.name; - if (name == MainMenuScene) - _payload?.ConfirmLaunch(); - _host?.SceneLoaded(BuildIndexOf(scene), name); - } - - private static void OnSceneUnloaded(Scene scene) => - _host?.SceneUnloaded(BuildIndexOf(scene), scene.name); - - private static bool _buildIndexUnavailable; - - // The game's IL2CPP build strips Scene.GetBuildIndexInternal_Injected, so reading buildIndex - // throws and the melon never heard of the scene. Upstream only logs the index; -1 stands in. - private static int BuildIndexOf(Scene scene) - { - if (_buildIndexUnavailable) - return -1; - try - { - return scene.buildIndex; - } - catch (Exception) - { - _buildIndexUnavailable = true; - return -1; - } - } - - private static void Write(ManualLogSource log, string name, MelonLogLevel level, string text) - { - var line = name == "BazaarPlusPlus" ? text : $"[{name}] {text}"; - switch (level) - { - case MelonLogLevel.Warning: - log.LogWarning(line); - return; - case MelonLogLevel.Error: - log.LogError(line); - return; - default: - log.LogInfo(line); - return; - } - } -} - -/// The frame source: Unity calls it, it calls the melon. -public sealed class BridgeBehaviour : MonoBehaviour -{ - public BridgeBehaviour(IntPtr pointer) - : base(pointer) { } - - private void Update() => BridgePlugin.Host?.Update(); - - private void LateUpdate() => BridgePlugin.Host?.LateUpdate(); - - private void OnApplicationQuit() => BridgePlugin.Host?.Quit(); -} diff --git a/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/LetterBoxPatches.cs b/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/LetterBoxPatches.cs deleted file mode 100644 index b0c5456..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.BepInExBridge/LetterBoxPatches.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Reflection; -using HarmonyLib; -using Il2CppTheBazaar; -using Il2CppTheBazaar.UI; -using UnityEngine; - -namespace BazaarPlusPlus.BepInExBridge; - -/// -/// Removes the game's own 16:10 letterbox so the full viewport is used, as this fork's plugin -/// does (bazaarplusplus-mod Patches/Android/AndroidLetterboxPatches). Upstream's payload has no -/// counterpart, and on a 3:2 tablet the game otherwise draws bars above and below. -/// -/// LetterBoxManager.CalculateNewRect sizes the black panels and -/// CameraLetterBoxManager.OnScreenSizeChanged narrows the main camera. Both are -/// presentation-only, so forcing their result to the screen rect does not touch gameplay state. -/// -internal static class LetterBoxPatches -{ - public static void Apply(Harmony harmony) - { - harmony.PatchAll(typeof(LetterBoxCropPatch)); - harmony.PatchAll(typeof(CameraLetterBoxPatch)); - } - - [HarmonyPatch] - private static class LetterBoxCropPatch - { - [HarmonyPrepare] - private static bool Prepare() => Target() != null; - - [HarmonyTargetMethod] - private static MethodBase? Target() => - AccessTools.Method(typeof(LetterBoxManager), "CalculateNewRect", new[] { typeof(Vector2Int) }); - - [HarmonyPrefix] - private static bool Prefix(ref Rect __result) - { - // CurrentScreenRect is normalized; BazaarCanvasScaler multiplies it by screen pixels. - // CalculateNewRect also caches its result, so replacing only the return value is unsafe. - __result = new Rect(0f, 0f, 1f, 1f); - LetterBoxManager._currentScreenRect = __result; - return false; - } - } - - [HarmonyPatch(typeof(CameraLetterBoxManager), "OnScreenSizeChanged")] - private static class CameraLetterBoxPatch - { - [HarmonyPostfix] - private static void Postfix(CameraLetterBoxManager __instance) - { - var camera = __instance._camera; - if (camera != null) - camera.rect = new Rect(0f, 0f, 1f, 1f); - } - } -} diff --git a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/BazaarPlusPlus.OfficialPayload.Tests.csproj b/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/BazaarPlusPlus.OfficialPayload.Tests.csproj deleted file mode 100644 index 5c52459..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/BazaarPlusPlus.OfficialPayload.Tests.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - true - false - true - - - - - - - - - diff --git a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/OfficialPayloadInstallTests.cs b/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/OfficialPayloadInstallTests.cs deleted file mode 100644 index 05cd3f3..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/OfficialPayloadInstallTests.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System.IO.Compression; -using System.Security.Cryptography; -using System.Text; -using BazaarPlusPlus.OfficialPayload; -using Xunit; - -public sealed class OfficialPayloadInstallTests : IDisposable -{ - private const string Version = "6.0.2"; - private const string Digest = "f41fcb027911e235fb48424eab16fd2698266cd4ab9ecba5605aae19646f7ae1"; - - private readonly string _root = Directory.CreateTempSubdirectory("bpp-official-payload").FullName; - private readonly List _lines = new(); - - public void Dispose() => Directory.Delete(_root, recursive: true); - - private string InstallRoot => Path.Combine(_root, "install"); - - private string Updates => Path.Combine(InstallRoot, "BazaarPlusPlusV6", "Updates"); - - [Fact] - public void Bundled_payload_is_staged_when_nothing_is_installed() - { - Install().StageBundled(Bundle(Version)); - - var staged = Path.Combine(Updates, Version); - Assert.True(File.Exists(Path.Combine(staged, "manifest.txt"))); - Assert.True(File.Exists(Path.Combine(staged, "manifest.txt.minisig"))); - Assert.True(File.Exists(Path.Combine(staged, "files", "MelonLoader", "Mods", "BazaarPlusPlus.version"))); - Assert.Single(Directory.GetDirectories(Updates)); - } - - [Fact] - public void Bundled_payload_not_newer_than_the_installed_one_is_not_staged() - { - Installed("6.0.3"); - Install().StageBundled(Bundle(Version)); - Assert.False(Directory.Exists(Updates)); - } - - [Fact] - public void Bundled_payload_newer_than_the_installed_one_is_staged() - { - Installed("6.0.1"); - Install().StageBundled(Bundle(Version)); - Assert.True(Directory.Exists(Path.Combine(Updates, Version))); - } - - [Fact] - public void Rejected_bundled_version_is_not_staged_again() - { - new RejectedVersions(Path.Combine(InstallRoot, "BazaarPlusPlusV6")).Add(Version, "launch_unconfirmed"); - Install().StageBundled(Bundle(Version)); - Assert.False(Directory.Exists(Updates)); - } - - [Fact] - public void A_bundle_writing_outside_the_payload_directories_is_refused() - { - Install().StageBundled(Bundle(Version, ("files/BepInEx/plugins/Evil.dll", "x"))); - Assert.False(Directory.Exists(Path.Combine(Updates, Version))); - Assert.Contains(_lines, line => line.Contains("official_payload.bundled.failed")); - } - - [Fact] - public void An_unsigned_staged_payload_is_deleted_and_recorded() - { - var install = Install(); - install.StageBundled(Bundle(Version)); - install.ScreenStaged(); - - Assert.False(Directory.Exists(Path.Combine(Updates, Version))); - Assert.True(new RejectedVersions(install.DataRoot).Contains(Version)); - Assert.Contains(_lines, line => line.Contains("official_payload.staged.rejected")); - } - - [Fact] - public void A_staged_payload_not_newer_than_the_installed_one_is_left_to_the_updater() - { - Installed(Version); - var staged = Path.Combine(Updates, Version); - Directory.CreateDirectory(staged); - var install = Install(); - install.ScreenStaged(); - Assert.True(Directory.Exists(staged)); - Assert.False(new RejectedVersions(install.DataRoot).Contains(Version)); - } - - [Fact] - public void Installed_version_comes_from_the_version_file_without_a_manifest() - { - Installed("6.0.2.prod"); - Assert.Equal("6.0.2", Install().InstalledVersion); - } - - [Fact] - public void A_payload_that_never_reaches_the_main_menu_is_given_up() - { - Installed(Version); - var install = Install(); - for (var i = 0; i < LaunchGuard.MaxUnconfirmedLaunches; i++) - Assert.True(install.BeginLaunch()); - - Assert.False(install.BeginLaunch()); - Assert.True(new RejectedVersions(install.DataRoot).Contains(Version)); - Assert.Null(install.InstalledVersion); - } - - [Fact] - public void A_confirmed_payload_keeps_loading() - { - Installed(Version); - var install = Install(); - Assert.True(install.BeginLaunch()); - install.ConfirmLaunch(); - for (var i = 0; i < LaunchGuard.MaxUnconfirmedLaunches + 2; i++) - Assert.True(install.BeginLaunch()); - } - - [Fact] - public void Nothing_installed_loads_nothing() - { - Assert.False(Install().BeginLaunch()); - } - - private OfficialPayloadInstall Install() => - new(InstallRoot, Array.Empty(), _lines.Add, _lines.Add, _lines.Add); - - private void Installed(string versionText) - { - var mods = Path.Combine(InstallRoot, "MelonLoader", "Mods"); - Directory.CreateDirectory(mods); - File.WriteAllText(Path.Combine(mods, "BazaarPlusPlus.version"), versionText); - } - - private string Bundle(string version, params (string Name, string Content)[] extra) - { - var versionFile = Encoding.UTF8.GetBytes(version + ".prod"); - var manifest = - "bpp-managed-payload-manifest 1\n" - + $"version {version}\n" - + "platform android-aarch64\n" - + "history-database-user-version 1\n" - + $"non-managed-payload-digest {Digest}\n" - + $"file {Convert.ToHexStringLower(SHA256.HashData(versionFile))} {versionFile.Length} MelonLoader/Mods/BazaarPlusPlus.version\n"; - var path = Path.Combine(_root, $"bundle-{Guid.NewGuid():N}.zip"); - using (var archive = ZipFile.Open(path, ZipArchiveMode.Create)) - { - Add(archive, "manifest.txt", Encoding.UTF8.GetBytes(manifest)); - Add(archive, "manifest.txt.minisig", Encoding.UTF8.GetBytes("untrusted comment: test\n")); - Add(archive, "files/MelonLoader/Mods/BazaarPlusPlus.version", versionFile); - foreach (var (name, content) in extra) - Add(archive, name, Encoding.UTF8.GetBytes(content)); - } - return path; - } - - private static void Add(ZipArchive archive, string name, byte[] content) - { - using var stream = archive.CreateEntry(name).Open(); - stream.Write(content); - } -} diff --git a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/PayloadCompatibilityTests.cs b/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/PayloadCompatibilityTests.cs deleted file mode 100644 index eee3889..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/PayloadCompatibilityTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using BazaarPlusPlus.OfficialPayload; -using Mono.Cecil; -using Xunit; - -public sealed class PayloadCompatibilityTests : IDisposable -{ - private readonly string _melon = Directory.CreateTempSubdirectory("bpp-payload-compat").FullName; - - public PayloadCompatibilityTests() - { - // A real assembly as the "mod": it references Mono.Cecil, which only a host directory has. - var mods = Directory.CreateDirectory(Path.Combine(_melon, "Mods")).FullName; - File.Copy( - typeof(PayloadCompatibility).Assembly.Location, - Path.Combine(mods, "BazaarPlusPlus.OfficialPayload.dll") - ); - } - - public void Dispose() => Directory.Delete(_melon, recursive: true); - - [Fact] - public void A_payload_binds_when_the_host_provides_everything_it_references() - { - var cecil = Path.GetDirectoryName(typeof(ModuleDefinition).Assembly.Location)!; - Assert.Null(PayloadCompatibility.Check(_melon, new[] { cecil })); - } - - [Fact] - public void A_payload_referencing_a_missing_host_assembly_is_refused() - { - Assert.Equal( - "assembly_missing:Mono.Cecil@BazaarPlusPlus.OfficialPayload.dll", - PayloadCompatibility.Check(_melon, Array.Empty()) - ); - } - - [Fact] - public void A_payload_without_mods_is_refused() - { - Directory.Delete(Path.Combine(_melon, "Mods"), recursive: true); - Assert.Equal("mods_missing", PayloadCompatibility.Check(_melon, Array.Empty())); - } -} diff --git a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/BazaarPlusPlus.OfficialPayload.csproj b/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/BazaarPlusPlus.OfficialPayload.csproj deleted file mode 100644 index eb0912c..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/BazaarPlusPlus.OfficialPayload.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - BazaarPlusPlus.OfficialPayload - BazaarPlusPlus.OfficialPayload - $(BppUpstreamModSrc)BazaarPlusPlus.Updater/ - - - - - - - - - - - - - - diff --git a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/LaunchGuard.cs b/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/LaunchGuard.cs deleted file mode 100644 index 8a256f2..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/LaunchGuard.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace BazaarPlusPlus.OfficialPayload; - -/// -/// Counts starts of the installed payload that never reached the main menu. A Harmony patch that -/// crashes on this runtime shows up only when it runs, so after -/// such starts in a row the version is given up: the caller then stops loading it. -/// -public sealed class LaunchGuard -{ - public const string FileName = "bpp-official-payload.launch"; - public const int MaxUnconfirmedLaunches = 3; - - private readonly string _path; - - public LaunchGuard(string dataRoot) => _path = Path.Combine(dataRoot, FileName); - - /// Records one more start of ; false once it is given up. - public bool Begin(string version) - { - var (recorded, attempts, confirmed) = Read(); - if (recorded == version && confirmed) - return true; - attempts = recorded == version ? attempts : 0; - if (attempts >= MaxUnconfirmedLaunches) - return false; - Write(version, attempts + 1, false); - return true; - } - - /// The main menu loaded: this version works on this device. - public void Confirm(string version) => Write(version, 0, true); - - private (string? Version, int Attempts, bool Confirmed) Read() - { - if (!File.Exists(_path)) - return (null, 0, false); - var parts = File.ReadAllText(_path).Trim().Split(' '); - return parts.Length == 3 && int.TryParse(parts[1], out var attempts) - ? (parts[0], attempts, parts[2] == "confirmed") - : (null, 0, false); - } - - private void Write(string version, int attempts, bool confirmed) - { - Directory.CreateDirectory(Path.GetDirectoryName(_path)!); - File.WriteAllText(_path, $"{version} {attempts} {(confirmed ? "confirmed" : "pending")}"); - } -} diff --git a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/OfficialPayloadInstall.cs b/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/OfficialPayloadInstall.cs deleted file mode 100644 index b614ef0..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/OfficialPayloadInstall.cs +++ /dev/null @@ -1,298 +0,0 @@ -using System.IO.Compression; -using BazaarPlusPlus.ManagedPayload; -using BazaarPlusPlus.Updater; - -namespace BazaarPlusPlus.OfficialPayload; - -/// -/// Upstream's Android Managed Payload installed under <install root>/MelonLoader, as -/// LemonLoader lays it out. Each start: stage the payload the APK bundles when it is newer than -/// the installed one, refuse every staged payload that fails its signature or does not bind on -/// this device, let upstream's Updater swap in the newest that passes, then -/// before the mod loads. The launcher stages downloaded releases the -/// same way, under the Data Root's Updates/<version>. -/// -public sealed class OfficialPayloadInstall -{ - /// The bundled payload, beside the bridge in BepInEx/plugins. - public const string BundledFileName = "BazaarPlusPlus.OfficialPayload.zip"; - - private readonly string _installRoot; - private readonly IReadOnlyList _hostDirectories; - private readonly MinisignPublicKey _publicKey; - private readonly UpdaterLog _log; - private readonly RejectedVersions _rejected; - private readonly LaunchGuard _guard; - - public OfficialPayloadInstall( - string installRoot, - IReadOnlyList hostDirectories, - Action info, - Action warn, - Action error - ) - : this(installRoot, hostDirectories, ReleaseSigningKey.PublicKey, new UpdaterLog(info, warn, error)) { } - - internal OfficialPayloadInstall( - string installRoot, - IReadOnlyList hostDirectories, - MinisignPublicKey publicKey, - UpdaterLog log - ) - { - _installRoot = installRoot; - _hostDirectories = hostDirectories; - _publicKey = publicKey; - _log = log; - DataRoot = Path.Combine(installRoot, UpdaterRun.DataRootDirectoryName); - _rejected = new RejectedVersions(DataRoot); - _guard = new LaunchGuard(DataRoot); - } - - public string DataRoot { get; } - - public string MelonBaseDirectory => Path.Combine(_installRoot, "MelonLoader"); - - public string ModsDirectory => Path.Combine(MelonBaseDirectory, "Mods"); - - public string UserLibsDirectory => Path.Combine(MelonBaseDirectory, "UserLibs"); - - private string UpdatesDirectory => - Path.Combine(DataRoot, StagedManagedPayload.UpdatesDirectoryName); - - private static ManagedPayloadHost Host => ManagedPayloadHost.MelonLoader; - - /// The installed payload's version, or null when none is installed. - public string? InstalledVersion - { - get - { - var manifest = InstalledManifest(); - if (manifest != null) - return manifest.Version; - var versionFile = Resolve(Host.VersionFilePath); - return - File.Exists(versionFile) - && ManagedPayloadVersion.TryParse(File.ReadAllText(versionFile), out var version) - ? version.ToString(3) - : null; - } - } - - /// Stages the bundled payload when it is newer than the installed one. - public void StageBundled(string zipPath) - { - string? partial = null; - try - { - if (!File.Exists(zipPath)) - { - _log.Warn("official_payload.bundled.missing", ("path", zipPath)); - return; - } - using var archive = ZipFile.OpenRead(zipPath); - var manifestEntry = - archive.GetEntry(ManagedPayloadManifest.FileName) - ?? throw new InvalidDataException("manifest missing"); - ManagedPayloadManifest manifest; - using (var stream = manifestEntry.Open()) - using (var reader = new StreamReader(stream)) - manifest = ManagedPayloadManifest.Parse(reader.ReadToEnd()); - - var version = manifest.Version; - if (_rejected.Contains(version)) - { - _log.Info("official_payload.bundled.rejected_before", ("version", version)); - return; - } - if (!IsNewerThanInstalled(version)) - return; - var target = Path.Combine(UpdatesDirectory, version); - if (Directory.Exists(target)) - return; - - partial = Path.Combine(UpdatesDirectory, "." + version + ".partial"); - if (Directory.Exists(partial)) - Directory.Delete(partial, recursive: true); - Directory.CreateDirectory(partial); - foreach (var entry in archive.Entries) - { - if (entry.FullName.EndsWith('/')) - continue; - var relative = StagedRelativePath(entry.FullName); - var destination = Path.Combine(new[] { partial }.Concat(relative.Split('/')).ToArray()); - Directory.CreateDirectory(Path.GetDirectoryName(destination)!); - entry.ExtractToFile(destination); - } - Directory.Move(partial, target); - _log.Info( - "official_payload.bundled.staged", - ("version", version), - ("installed", InstalledVersion ?? "none") - ); - } - catch (Exception exception) - { - _log.Error("official_payload.bundled.failed", exception, ("path", zipPath)); - if (partial != null) - TryDelete(partial); - } - } - - /// - /// Deletes every staged payload newer than the installed one that is unsigned, built for - /// another non-managed payload, or does not bind on this device, and records it as rejected. - /// - public void ScreenStaged() - { - if (!Directory.Exists(UpdatesDirectory)) - return; - var installed = InstalledManifest(); - foreach (var directory in Directory.GetDirectories(UpdatesDirectory)) - { - var version = Path.GetFileName(directory); - if (version.Split('.').Length != 3 || !IsNewerThanInstalled(version)) - continue; - var failure = Screen(directory, installed); - if (failure == null) - { - _log.Info("official_payload.staged.accepted", ("version", version)); - continue; - } - _log.Warn("official_payload.staged.rejected", ("version", version), ("reason_code", failure)); - _rejected.Add(version, failure); - TryDelete(directory); - } - } - - private string? Screen(string directory, ManagedPayloadManifest? installed) - { - if ( - !StagedManagedPayload.TryVerify( - directory, - Host, - UpdaterRun.AndroidPlatformKey, - _publicKey, - out var manifest, - out var failure - ) - ) - return failure; - if (installed != null) - { - if (manifest!.HistoryDatabaseUserVersion != installed.HistoryDatabaseUserVersion) - return "history_database_mismatch"; - if (manifest.NonManagedPayloadDigest != installed.NonManagedPayloadDigest) - return "non_managed_payload_mismatch"; - } - try - { - return PayloadCompatibility.Check( - Path.Combine(directory, ManagedPayloadManifest.FilesDirectory, "MelonLoader"), - _hostDirectories - ); - } - catch (Exception exception) - { - return "compatibility_check_failed:" + exception.GetType().Name; - } - } - - /// Upstream's Updater: swaps in the newest staged payload that still verifies. - public void Apply() => - UpdaterRun.Run(_installRoot, Host, UpdaterRun.AndroidPlatformKey, _log); - - /// - /// Counts this start of the installed payload. False when there is nothing to load, or when it - /// has failed to reach the main menu too often: it is then rejected and uninstalled down to its - /// version marker, so the next start stages the bundled payload again. - /// - public bool BeginLaunch() - { - var version = InstalledVersion; - if (version == null) - { - _log.Warn("official_payload.not_installed", ("mods", ModsDirectory)); - return false; - } - if (_guard.Begin(version)) - return true; - _log.Warn( - "official_payload.launch.given_up", - ("version", version), - ("attempts", LaunchGuard.MaxUnconfirmedLaunches) - ); - _rejected.Add(version, "launch_unconfirmed"); - TryDelete(Resolve(Host.InstalledManifestPath)); - TryDelete(Resolve(Host.VersionFilePath)); - return false; - } - - /// The main menu loaded with the installed payload. - public void ConfirmLaunch() - { - var version = InstalledVersion; - if (version != null) - _guard.Confirm(version); - } - - private bool IsNewerThanInstalled(string version) - { - if (!ManagedPayloadVersion.TryParse(version, out var candidate)) - return false; - var installed = InstalledVersion; - return installed == null - || !ManagedPayloadVersion.TryParse(installed, out var current) - || candidate > current; - } - - private ManagedPayloadManifest? InstalledManifest() - { - var path = Resolve(Host.InstalledManifestPath); - if (!File.Exists(path)) - return null; - try - { - return ManagedPayloadManifest.Parse(File.ReadAllBytes(path)); - } - catch (FormatException) - { - return null; - } - } - - // The zip holds exactly the staged layout: the manifest, its signature, and files under - // files/ that the MelonLoader host may write. - private static string StagedRelativePath(string entryName) - { - if ( - entryName is ManagedPayloadManifest.FileName or ManagedPayloadManifest.SignatureFileName - ) - return entryName; - var prefix = ManagedPayloadManifest.FilesDirectory + "/"; - if ( - entryName.StartsWith(prefix, StringComparison.Ordinal) - && Host.MayWrite(entryName[prefix.Length..]) - ) - return entryName; - throw new InvalidDataException($"unexpected entry {entryName}"); - } - - private string Resolve(string installRelative) => - Path.Combine(new[] { _installRoot }.Concat(installRelative.Split('/')).ToArray()); - - private void TryDelete(string path) - { - try - { - if (Directory.Exists(path)) - Directory.Delete(path, recursive: true); - else if (File.Exists(path)) - File.Delete(path); - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) - { - _log.Warn("official_payload.cleanup.failed", ("path", path), ("error", exception.Message)); - } - } -} diff --git a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/PayloadCompatibility.cs b/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/PayloadCompatibility.cs deleted file mode 100644 index 6486b73..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/PayloadCompatibility.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System.Runtime.InteropServices; -using Mono.Cecil; - -namespace BazaarPlusPlus.OfficialPayload; - -/// -/// Whether a payload binds against this device before it is swapped in. Upstream builds against -/// LemonLoader's interop and loader; here the interop is generated on the device by BepInEx and -/// the loader is the MelonLoader compat assembly, so a member upstream calls may be missing. -/// Every assembly, type and member the payload references outside itself and the runtime must -/// resolve in the host directories, at a version no lower than the one referenced. -/// -public static class PayloadCompatibility -{ - /// The payload's MelonLoader directory. - /// Where the host provides the rest: interop, BepInEx core, plugins. - /// Null when compatible, otherwise a reason code naming the first gap. - public static string? Check(string payloadMelonDirectory, IEnumerable hostDirectories) - { - var mods = Path.Combine(payloadMelonDirectory, "Mods"); - var userLibs = Path.Combine(payloadMelonDirectory, "UserLibs"); - var runtimeDirectory = RuntimeEnvironment.GetRuntimeDirectory(); - using var resolver = new DirectoryResolver( - new[] { mods, userLibs }.Concat(hostDirectories).Append(runtimeDirectory) - ); - var parameters = new ReaderParameters { AssemblyResolver = resolver }; - - if (!Directory.Exists(mods)) - return "mods_missing"; - foreach (var path in Directory.GetFiles(mods, "*.dll")) - { - using var module = ModuleDefinition.ReadModule(path, parameters); - var failure = CheckModule(module, resolver, runtimeDirectory); - if (failure != null) - return $"{failure}@{Path.GetFileName(path)}"; - } - return null; - } - - private static string? CheckModule( - ModuleDefinition module, - IAssemblyResolver resolver, - string runtimeDirectory - ) - { - var framework = TargetFrameworkMajor(module); - if (framework > Environment.Version.Major) - return $"target_framework:{framework}"; - - foreach (var reference in module.AssemblyReferences) - { - if (IsRuntimeAssembly(reference.Name, runtimeDirectory)) - continue; - AssemblyDefinition resolved; - try - { - resolved = resolver.Resolve(reference); - } - catch (AssemblyResolutionException) - { - return $"assembly_missing:{reference.Name}"; - } - if (resolved.Name.Version < reference.Version) - return $"assembly_too_old:{reference.Name}:{resolved.Name.Version}<{reference.Version}"; - } - - foreach (var type in module.GetTypeReferences()) - { - if (IsRuntimeScope(type.Scope, runtimeDirectory)) - continue; - if (type.Resolve() == null) - return $"type_missing:{type.FullName}"; - } - - foreach (var member in module.GetMemberReferences()) - { - // Multi-dimensional array accessors are synthesized by the runtime. - if (member.DeclaringType is ArrayType) - continue; - if (IsRuntimeScope(member.DeclaringType.GetElementType().Scope, runtimeDirectory)) - continue; - if (member.Resolve() == null) - return $"member_missing:{member.FullName}"; - } - return null; - } - - // The runtime is what it is: the target framework check covers it, member by member it would - // only repeat the JIT's own binding. - private static bool IsRuntimeScope(IMetadataScope scope, string runtimeDirectory) => - scope is AssemblyNameReference reference && IsRuntimeAssembly(reference.Name, runtimeDirectory); - - private static bool IsRuntimeAssembly(string name, string runtimeDirectory) => - name is "netstandard" or "mscorlib" - || File.Exists(Path.Combine(runtimeDirectory, name + ".dll")); - - // Cecil's own resolver also searches the running process's trusted assemblies, which would - // answer for what the device lacks. This one looks only where it is told, first match wins. - private sealed class DirectoryResolver : IAssemblyResolver - { - private readonly string[] _directories; - private readonly Dictionary _cache = new(StringComparer.Ordinal); - - public DirectoryResolver(IEnumerable directories) => - _directories = directories.Where(Directory.Exists).ToArray(); - - public AssemblyDefinition Resolve(AssemblyNameReference name) => - Resolve(name, new ReaderParameters()); - - public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) - { - if (_cache.TryGetValue(name.Name, out var cached)) - return cached; - foreach (var directory in _directories) - { - var path = Path.Combine(directory, name.Name + ".dll"); - if (!File.Exists(path)) - continue; - var assembly = AssemblyDefinition.ReadAssembly( - path, - new ReaderParameters { AssemblyResolver = this } - ); - _cache[name.Name] = assembly; - return assembly; - } - throw new AssemblyResolutionException(name); - } - - public void Dispose() - { - foreach (var assembly in _cache.Values) - assembly.Dispose(); - _cache.Clear(); - } - } - - private static int TargetFrameworkMajor(ModuleDefinition module) - { - var attribute = module.Assembly.CustomAttributes.FirstOrDefault(attribute => - attribute.AttributeType.FullName - == "System.Runtime.Versioning.TargetFrameworkAttribute" - ); - var text = attribute?.ConstructorArguments.FirstOrDefault().Value as string; - const string prefix = ".NETCoreApp,Version=v"; - return - text != null - && text.StartsWith(prefix, StringComparison.Ordinal) - && Version.TryParse(text[prefix.Length..], out var version) - ? version.Major - : 0; - } -} diff --git a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/RejectedVersions.cs b/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/RejectedVersions.cs deleted file mode 100644 index c330909..0000000 --- a/android-port/upstream-host/BazaarPlusPlus.OfficialPayload/RejectedVersions.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace BazaarPlusPlus.OfficialPayload; - -/// -/// Payload versions this device will not take again, one version reason per line under the -/// Data Root. The launcher reads the same file before it downloads a release, so a refused -/// payload is not fetched on every start. -/// -public sealed class RejectedVersions -{ - public const string FileName = "bpp-official-payload.rejected"; - - private readonly string _path; - - public RejectedVersions(string dataRoot) => _path = Path.Combine(dataRoot, FileName); - - public bool Contains(string version) => - Read().Any(line => line.Split(' ', 2)[0] == version); - - public void Add(string version, string reason) - { - if (Contains(version)) - return; - Directory.CreateDirectory(Path.GetDirectoryName(_path)!); - File.AppendAllText(_path, $"{version} {reason}\n"); - } - - private IEnumerable Read() => - File.Exists(_path) - ? File.ReadAllLines(_path).Where(line => line.Length > 0) - : Array.Empty(); -} diff --git a/android-port/upstream-host/Directory.Build.props b/android-port/upstream-host/Directory.Build.props deleted file mode 100644 index 9d5dc67..0000000 --- a/android-port/upstream-host/Directory.Build.props +++ /dev/null @@ -1,28 +0,0 @@ - - - - $([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)', '..', '..', 'upstream', 'BazaarPlusPlus')) - $([MSBuild]::NormalizeDirectory('$(BppUpstreamRoot)', 'bazaarplusplus-mod', 'src')) - net10.0 - 14 - enable - enable - true - false - false - false - false - $(NoWarn);CS1591;NU1903;NU1902 - - - - - - diff --git a/android-port/upstream-host/Directory.Packages.props b/android-port/upstream-host/Directory.Packages.props deleted file mode 100644 index 14d66d0..0000000 --- a/android-port/upstream-host/Directory.Packages.props +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/android-port/upstream-host/MelonLoader.Tests/MelonCompatHostTests.cs b/android-port/upstream-host/MelonLoader.Tests/MelonCompatHostTests.cs deleted file mode 100644 index 6891fd6..0000000 --- a/android-port/upstream-host/MelonLoader.Tests/MelonCompatHostTests.cs +++ /dev/null @@ -1,123 +0,0 @@ -using MelonLoader; -using MelonLoader.Utils; -using Xunit; - -[assembly: MelonInfo(typeof(RecordingMelon), "Recording", "1.2.3", "tests")] - -public sealed class RecordingMelon : MelonMod -{ - public static readonly List Calls = []; - public static bool ThrowOnUpdate; - - public override void OnInitializeMelon() => Calls.Add($"init:{Info.Name}:{Info.Version}"); - - public override void OnLateInitializeMelon() => Calls.Add("late-init"); - - public override void OnUpdate() - { - Calls.Add("update"); - if (ThrowOnUpdate) - throw new InvalidOperationException("boom"); - } - - public override void OnSceneWasLoaded(int buildIndex, string sceneName) => - Calls.Add($"scene:{buildIndex}:{sceneName}"); - - public override void OnApplicationQuit() => Calls.Add("quit"); - - public override void OnDeinitializeMelon() => Calls.Add("deinit"); -} - -[Collection("melon")] -public sealed class MelonCompatHostTests : IDisposable -{ - private readonly string _base = Path.Combine( - Directory.CreateTempSubdirectory("melon-compat").FullName, - "MelonLoader" - ); - private readonly List<(string Name, MelonLogLevel Level, string Text)> _log = []; - - public MelonCompatHostTests() - { - RecordingMelon.Calls.Clear(); - RecordingMelon.ThrowOnUpdate = false; - MelonLogger.Sink = (name, level, text) => _log.Add((name, level, text)); - } - - public void Dispose() => Directory.Delete(Path.GetDirectoryName(_base)!, recursive: true); - - [Fact] - public void Runs_the_melon_named_by_the_assembly_in_MelonLoader_order() - { - var host = MelonCompatHost.Create(typeof(RecordingMelon).Assembly, _base); - host.Update(); // before Initialize: ignored - host.Initialize(); - host.Update(); - host.Update(); - host.SceneLoaded(2, "MainMenuScene"); - host.Quit(); - host.Quit(); - host.Update(); // after Quit: ignored - - Assert.Equal( - [ - "init:Recording:1.2.3", - "late-init", - "update", - "update", - "scene:2:MainMenuScene", - "quit", - "deinit", - ], - RecordingMelon.Calls - ); - } - - [Fact] - public void Sets_the_MelonLoader_directories_under_the_base() - { - MelonCompatHost.Create(typeof(RecordingMelon).Assembly, _base); - Assert.Equal(_base, MelonEnvironment.MelonBaseDirectory); - Assert.Equal(Path.Combine(_base, "UserData"), MelonEnvironment.UserDataDirectory); - Assert.True(Directory.Exists(MelonEnvironment.UserDataDirectory)); - } - - [Fact] - public void A_throwing_callback_is_logged_and_does_not_stop_the_next_frame() - { - var host = MelonCompatHost.Create(typeof(RecordingMelon).Assembly, _base); - host.Initialize(); - RecordingMelon.ThrowOnUpdate = true; - host.Update(); - host.Update(); - - Assert.Equal(2, RecordingMelon.Calls.Count(call => call == "update")); - Assert.Equal(2, _log.Count(line => line.Level == MelonLogLevel.Error)); - Assert.All( - _log.Where(line => line.Level == MelonLogLevel.Error), - line => - { - Assert.Equal("Recording", line.Name); - Assert.Contains("OnUpdate failed", line.Text); - Assert.Contains("boom", line.Text); - } - ); - } - - [Fact] - public void The_melon_gets_its_own_logger() - { - var host = MelonCompatHost.Create(typeof(RecordingMelon).Assembly, _base); - host.Melon.LoggerInstance.Warning("careful"); - Assert.Equal(("Recording", MelonLogLevel.Warning, "careful"), _log.Single()); - } - - [Fact] - public void An_assembly_without_MelonInfo_is_refused() - { - var error = Assert.Throws(() => - MelonCompatHost.Create(typeof(object).Assembly, _base) - ); - Assert.Contains("MelonInfo", error.Message); - } -} diff --git a/android-port/upstream-host/MelonLoader.Tests/MelonLoader.Tests.csproj b/android-port/upstream-host/MelonLoader.Tests/MelonLoader.Tests.csproj deleted file mode 100644 index 6225c5d..0000000 --- a/android-port/upstream-host/MelonLoader.Tests/MelonLoader.Tests.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - true - false - true - - - - - - - - - diff --git a/android-port/upstream-host/MelonLoader/HarmonyDontPatchAllAttribute.cs b/android-port/upstream-host/MelonLoader/HarmonyDontPatchAllAttribute.cs deleted file mode 100644 index e93f94a..0000000 --- a/android-port/upstream-host/MelonLoader/HarmonyDontPatchAllAttribute.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace MelonLoader; - -/// -/// MelonLoader skips its assembly-wide Harmony PatchAll for an assembly marked with this. The -/// compat host never runs PatchAll, so the attribute only has to exist. -/// -[AttributeUsage(AttributeTargets.Assembly)] -public sealed class HarmonyDontPatchAllAttribute : Attribute; diff --git a/android-port/upstream-host/MelonLoader/MelonCompatHost.cs b/android-port/upstream-host/MelonLoader/MelonCompatHost.cs deleted file mode 100644 index d4f7ff1..0000000 --- a/android-port/upstream-host/MelonLoader/MelonCompatHost.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System.Reflection; -using MelonLoader.Utils; - -namespace MelonLoader; - -/// -/// Runs one melon the way MelonLoader would: the bridge creates it from the mod assembly, then -/// forwards Unity's frame, scene and quit callbacks. Every callback is isolated: one that throws is -/// logged and never reaches the caller, so a failing melon cannot take the bridge down. -/// -public sealed class MelonCompatHost -{ - private readonly MelonMod _melon; - private bool _initialized; - private bool _stopped; - private bool _lateInitialized; - - private MelonCompatHost(MelonMod melon) => _melon = melon; - - public MelonMod Melon => _melon; - - /// - /// Sets the MelonLoader base directory, then instantiates the melon the assembly's - /// names. - /// - public static MelonCompatHost Create(Assembly modAssembly, string melonBaseDirectory) - { - ArgumentNullException.ThrowIfNull(modAssembly); - MelonEnvironment.SetBaseDirectory(melonBaseDirectory); - var info = - modAssembly.GetCustomAttribute() - ?? throw new InvalidOperationException( - $"{modAssembly.GetName().Name} has no [assembly: MelonInfo]." - ); - if (!typeof(MelonMod).IsAssignableFrom(info.SystemType)) - throw new InvalidOperationException($"{info.SystemType} is not a MelonMod."); - var melon = (MelonMod)Activator.CreateInstance(info.SystemType)!; - melon.Info = info; - melon.LoggerInstance = new MelonLogger.Instance(info.Name); - melon.HarmonyId = modAssembly.FullName!; - return new MelonCompatHost(melon); - } - - public void Initialize() - { - if (_initialized) - return; - _initialized = true; - Run(nameof(MelonBase.OnEarlyInitializeMelon), _melon.OnEarlyInitializeMelon); - Run(nameof(MelonBase.OnInitializeMelon), _melon.OnInitializeMelon); - } - - public void Update() - { - if (!_initialized || _stopped) - return; - // MelonLoader runs OnLateInitializeMelon once the first frame is reached. - if (!_lateInitialized) - { - _lateInitialized = true; - Run(nameof(MelonBase.OnLateInitializeMelon), _melon.OnLateInitializeMelon); - } - Run(nameof(MelonBase.OnUpdate), _melon.OnUpdate); - } - - public void LateUpdate() - { - if (_initialized && !_stopped) - Run(nameof(MelonBase.OnLateUpdate), _melon.OnLateUpdate); - } - - public void SceneLoaded(int buildIndex, string sceneName) - { - if (!_initialized || _stopped) - return; - Run( - nameof(MelonMod.OnSceneWasLoaded), - () => _melon.OnSceneWasLoaded(buildIndex, sceneName) - ); - Run( - nameof(MelonMod.OnSceneWasInitialized), - () => _melon.OnSceneWasInitialized(buildIndex, sceneName) - ); - } - - public void SceneUnloaded(int buildIndex, string sceneName) - { - if (_initialized && !_stopped) - Run( - nameof(MelonMod.OnSceneWasUnloaded), - () => _melon.OnSceneWasUnloaded(buildIndex, sceneName) - ); - } - - /// Application quit, then deinitialize, each once. - public void Quit() - { - if (!_initialized || _stopped) - return; - _stopped = true; - Run(nameof(MelonBase.OnApplicationQuit), _melon.OnApplicationQuit); - Run(nameof(MelonBase.OnDeinitializeMelon), _melon.OnDeinitializeMelon); - } - - private void Run(string callback, Action step) - { - try - { - step(); - } - catch (Exception exception) - { - _melon.LoggerInstance.Error($"{callback} failed", exception); - } - } -} diff --git a/android-port/upstream-host/MelonLoader/MelonEnvironment.cs b/android-port/upstream-host/MelonLoader/MelonEnvironment.cs deleted file mode 100644 index 2f34883..0000000 --- a/android-port/upstream-host/MelonLoader/MelonEnvironment.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace MelonLoader.Utils; - -/// -/// MelonLoader's directory layout. sets the base directory before -/// any melon starts; the rest derive from it as they do under MelonLoader. -/// -public static class MelonEnvironment -{ - private static string? _melonBaseDirectory; - - public static string MelonBaseDirectory => - _melonBaseDirectory - ?? throw new InvalidOperationException("MelonCompatHost has not set the base directory."); - - public static string UserDataDirectory => Path.Combine(MelonBaseDirectory, "UserData"); - - public static string UserLibsDirectory => Path.Combine(MelonBaseDirectory, "UserLibs"); - - public static string ModsDirectory => Path.Combine(MelonBaseDirectory, "Mods"); - - public static string PluginsDirectory => Path.Combine(MelonBaseDirectory, "Plugins"); - - internal static void SetBaseDirectory(string melonBaseDirectory) - { - ArgumentException.ThrowIfNullOrEmpty(melonBaseDirectory); - _melonBaseDirectory = Path.GetFullPath(melonBaseDirectory); - Directory.CreateDirectory(UserDataDirectory); - } -} diff --git a/android-port/upstream-host/MelonLoader/MelonInfoAttribute.cs b/android-port/upstream-host/MelonLoader/MelonInfoAttribute.cs deleted file mode 100644 index 5010ec7..0000000 --- a/android-port/upstream-host/MelonLoader/MelonInfoAttribute.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace MelonLoader; - -/// Names a melon's entry type and identity, as MelonLoader's attribute does. -[AttributeUsage(AttributeTargets.Assembly)] -public sealed class MelonInfoAttribute( - Type type, - string name, - string version, - string author, - string? downloadLink = null -) : Attribute -{ - public Type SystemType { get; } = type; - - public string Name { get; } = name; - - public string Version { get; } = version; - - public string Author { get; } = author; - - public string? DownloadLink { get; } = downloadLink; -} diff --git a/android-port/upstream-host/MelonLoader/MelonLoader.csproj b/android-port/upstream-host/MelonLoader/MelonLoader.csproj deleted file mode 100644 index b4075e9..0000000 --- a/android-port/upstream-host/MelonLoader/MelonLoader.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - MelonLoader - MelonLoader - - 0.7.4 - - - - - - - - - diff --git a/android-port/upstream-host/MelonLoader/MelonLogger.cs b/android-port/upstream-host/MelonLoader/MelonLogger.cs deleted file mode 100644 index 8d045e2..0000000 --- a/android-port/upstream-host/MelonLoader/MelonLogger.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace MelonLoader; - -/// Severity of a line a melon logs. -public enum MelonLogLevel -{ - Msg, - Warning, - Error, -} - -/// -/// MelonLoader's logger. Lines go to , which the bridge points at its BepInEx -/// log source; until then they go to standard output. -/// -public static class MelonLogger -{ - /// Receives (melon name, level, text) for every line. - public static Action Sink { get; set; } = - static (name, level, text) => Console.WriteLine($"[{name}] {level}: {text}"); - - public static void Msg(string text) => Sink("MelonLoader", MelonLogLevel.Msg, text); - - public static void Warning(string text) => Sink("MelonLoader", MelonLogLevel.Warning, text); - - public static void Error(string text) => Sink("MelonLoader", MelonLogLevel.Error, text); - - /// A melon's own logger, named after it. - public sealed class Instance(string name) - { - public string Name { get; } = name; - - public void Msg(string text) => Sink(Name, MelonLogLevel.Msg, text); - - public void Msg(object value) => Msg(value?.ToString() ?? "null"); - - public void Warning(string text) => Sink(Name, MelonLogLevel.Warning, text); - - public void Warning(object value) => Warning(value?.ToString() ?? "null"); - - public void Error(string text) => Sink(Name, MelonLogLevel.Error, text); - - public void Error(string text, Exception exception) => - Sink(Name, MelonLogLevel.Error, $"{text}\n{exception}"); - - public void Error(object value) => Error(value?.ToString() ?? "null"); - } -} diff --git a/android-port/upstream-host/MelonLoader/MelonMod.cs b/android-port/upstream-host/MelonLoader/MelonMod.cs deleted file mode 100644 index ed8bf7a..0000000 --- a/android-port/upstream-host/MelonLoader/MelonMod.cs +++ /dev/null @@ -1,43 +0,0 @@ -using HarmonyLib; - -namespace MelonLoader; - -/// The callbacks and members a melon sees, as under MelonLoader. -public abstract class MelonBase -{ - public MelonInfoAttribute Info { get; internal set; } = null!; - - public MelonLogger.Instance LoggerInstance { get; internal set; } = null!; - - private Harmony? _harmony; - - // Created on first use, as nothing else needs HarmonyX loaded: its detour runtime targets - // the launcher's CoreCLR, not every runtime the compat assembly is tested on. - public Harmony HarmonyInstance => _harmony ??= new Harmony(HarmonyId); - - internal string HarmonyId { get; set; } = null!; - - public virtual void OnEarlyInitializeMelon() { } - - public virtual void OnInitializeMelon() { } - - public virtual void OnLateInitializeMelon() { } - - public virtual void OnDeinitializeMelon() { } - - public virtual void OnUpdate() { } - - public virtual void OnLateUpdate() { } - - public virtual void OnApplicationQuit() { } -} - -/// A mod melon: adds the scene callbacks. -public abstract class MelonMod : MelonBase -{ - public virtual void OnSceneWasLoaded(int buildIndex, string sceneName) { } - - public virtual void OnSceneWasInitialized(int buildIndex, string sceneName) { } - - public virtual void OnSceneWasUnloaded(int buildIndex, string sceneName) { } -} diff --git a/android-port/upstream-host/NuGet.Config b/android-port/upstream-host/NuGet.Config deleted file mode 100644 index 5fa51ce..0000000 --- a/android-port/upstream-host/NuGet.Config +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android-port/upstream-host/README.md b/android-port/upstream-host/README.md deleted file mode 100644 index 0e7a197..0000000 --- a/android-port/upstream-host/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# 上游官方插件包接入(实验) - -让本仓库的 BepInEx 启动器直接运行上游 [BazaarPlusPlus](https://github.com/BazaarPlusPlus/BazaarPlusPlus) -**官方发布的** Android 托管插件包(Managed Payload),并由启动器自动下载官方新版本。插件代码与官方逐字节一致, -不在本仓库编译。 - -状态:已在真机上启动到主菜单(见「真机验收」);对局内功能、启动器 APK 切换与插件内联网**尚未验收**。 -验收通过前,`package-launcher.ps1` 默认仍打包本仓库原插件,加 `-Upstream` 才打包这里的版本。 - -## 工作方式 - -官方的 Android 发布清单 `https://cdn.bazaarplusplus.com/installer/latest/mod/android-aarch64.json` 给出 -`managedPayload`:一个带 minisign 签名清单的 zip,内容是 `MelonLoader/Mods` 与 `MelonLoader/UserLibs` 下的文件。 -它的目录结构正是上游 Updater(ADR-0014)的暂存格式 `BazaarPlusPlusV6/Updates/<版本>/`。 - -1. **启动器(`BppOfficialPayload`,Java)**:模组包就绪后在后台读一次官方清单。版本比已安装的新、游戏版本与 - 已安装的游戏一致、`nonManagedPayloadDigest` 与已安装清单一致、且不在拒绝列表里时,下载 zip,按清单核对大小与 - SHA-256,解压到 `<游戏数据目录>/BazaarPlusPlusV6/Updates/<版本>`。启动不等下载;赶上的话本次启动生效,否则下次。 - 下载放在启动器,是因为游戏进程里 CoreCLR 的 HTTPS 不可用。 -2. **桥接插件(`BazaarPlusPlus.BepInExBridge`)启动时,经 `BazaarPlusPlus.OfficialPayload`**: - - 首次或内置版本更新时,把 APK 内置的官方包(`plugins/BazaarPlusPlus.OfficialPayload.zip`)暂存进 `Updates/`; - - 对每个比已安装更新的暂存包:用上游的签名公钥校验 minisign 签名和每个文件的哈希;用 Mono.Cecil 核对它引用的 - 每个程序集、类型、成员在本机都存在(interop、BepInEx core、兼容层),版本不低于所引用的;不通过就删除并记入 - `BazaarPlusPlusV6/bpp-official-payload.rejected`,启动器以后不再下载该版本; - - 交给**上游 Updater 原版源码**(子模块编译进来)做带预写日志的原子替换,装进 `<游戏数据目录>/MelonLoader/`; - - 已安装版本连续 3 次没走到主菜单(`LaunchGuard`)就放弃该版本:记入拒绝列表、撤掉其版本标记,下次启动重新 - 装回内置版本; - - 从 `MelonLoader/Mods` 加载带 `[MelonInfo]` 的程序集,经 MelonLoader 兼容层运行,转发帧、场景、退出回调; - - 另外装上本仓库原插件的去黑边补丁(`LetterBoxPatches`):上游没有它,3:2 平板上会出现游戏自带的 16:10 黑边。 - -官方换了游戏版本或加载器(`nonManagedPayloadDigest` 变化)时,启动器和 Updater 都不会接收,用户停在当前版本, -需要本仓库发新启动器。其余更新自动接收。 - -## 组成 - -| 目录 | 作用 | -|---|---| -| `../../upstream/BazaarPlusPlus` | 上游仓库的 git submodule;只用其中 `BazaarPlusPlus.Updater` 的源码,不做修改 | -| `BazaarPlusPlus.OfficialPayload` | 内置包暂存、签名与兼容性筛查、拒绝列表、启动守卫;编译上游 Updater 源码。无 BepInEx/Unity 引用 | -| `BazaarPlusPlus.BepInExBridge` | BepInEx 插件:安装并加载官方包,加载 SQLite 原生库,去黑边 | -| `MelonLoader` | MelonLoader API 兼容层,程序集名 `MelonLoader`、版本跟随 LemonLoader(0.7.4) | -| `official-payload.json` | 打进 APK 的官方包版本、地址、大小与 SHA-256 | -| `../tools/patch-bepinex-interop-prefix` | 给启动器的 `BepInEx.Unity.IL2CPP.dll` 打补丁,让设备生成 MelonLoader 式 `Il2Cpp` 前缀的 interop | - -官方包还引用 LemonLoader 自带的 `Microsoft.NET.StringTools`,以及 APK 里的 `libe_sqlite3.so`,二者由桥接插件随 -`BepInEx/plugins` 提供。 - -### 为什么要给 BepInEx 打前缀补丁 - -官方包按 MelonLoader 的 interop 命名编译(`Il2CppTheBazaar`、`Il2Cpp.BoardManager`),对应 Il2CppInterop 的 -`Il2CppPrefixMode.OptOut`;BepInEx 默认 `OptIn`,生成的是 `TheBazaar`。补丁让 BepInEx 用 `OptOut` 生成,并在 -interop 哈希上加标记,使已有的无前缀 interop 在下次启动时重新生成一次。interop 仍按当前安装的游戏在设备上生成。 - -## 构建 - -前置:.NET SDK 10(`global.json`);`git submodule update --init upstream/BazaarPlusPlus`。 - -1. **设备生成的带前缀 interop**:先装一次打过前缀补丁的 core,启动游戏让 BepInEx 生成 interop,再拉到本机作编译引用: - - ```powershell - adb pull /sdcard/Android/data/com.bepinex.android/files/BepInEx_Android/com.tempogames.thebazaar/BepInEx/interop D:\thebarzaar\android-interop-prefixed - ``` - -2. **编译**: - - ```powershell - dotnet build .\android-port\upstream-host\BazaarPlusPlus.BepInExBridge\BazaarPlusPlus.BepInExBridge.csproj -c Release ` - -p:InteropPath=D:\thebarzaar\android-interop-prefixed - ``` - -3. **打包**: - - ```powershell - powershell -NoProfile -ExecutionPolicy Bypass -File .\android-port\package-launcher.ps1 -Upstream -VersionCode <递增版本号> ` - -InteropSnapshot D:\thebarzaar\android-interop-prefixed - ``` - - `-Upstream` 会:从 `BazaarPlusPlus.BepInExBridge/bin/Release/net10.0` 取插件,按 `official-payload.json` 下载并核对 - 官方包后放进 `plugins/`,给 `core/BepInEx.Unity.IL2CPP.dll` 打前缀补丁,跳过托管 codec 改名。 - -## 升级内置的官方包 - -更新 `official-payload.json`(版本、地址、大小、SHA-256 取自官方清单),重新打包。已装用户不依赖它:启动器会自己下载。 - -需要改代码的情况,桥接插件的兼容性筛查会在日志里写明原因(`official_payload.staged.rejected reason_code=...`): - -- `assembly_too_old:MelonLoader...`:官方换了 LemonLoader 版本,提高 `MelonLoader.csproj` 的 `Version`; -- `member_missing:MelonLoader...` / `type_missing:MelonLoader...`:在 `MelonLoader/` 补上官方新用到的 API; -- `assembly_missing:<名字>`:官方依赖了 LemonLoader 自带、包里没有的程序集,随桥接插件提供; -- `member_missing:Il2Cpp...`:设备 interop 与 LemonLoader 的生成结果不一致,需要单独排查; -- `target_framework:`:官方升级了目标框架,启动器运行时需要随之升级。 - -## 测试 - -```bash -dotnet test android-port/upstream-host/BazaarPlusPlus.OfficialPayload.Tests/BazaarPlusPlus.OfficialPayload.Tests.csproj -``` - -```bash -dotnet test android-port/upstream-host/MelonLoader.Tests/MelonLoader.Tests.csproj -``` - -```bash -dotnet test android-port/tools/patch-bepinex-interop-prefix/tests/Tests.csproj -``` - -```bash -python android-port/tools/bpp-launcher/test_launcher_update.py -``` - -最后一个也运行 `BppOfficialPayloadTests`(清单解析、跳过条件、zip 条目白名单)。启动器安装器的 Java 测试 -(`package-launcher.ps1` 第 1 步)覆盖两种模组包结构,以及从原插件切换到这里时的旧文件清理。 - -## 真机验收 - -2026-10-30 在 vivo PA2573(Android 16,启动器 6.0.0-preview.46,游戏 1.0.12825)上手工部署桥接插件与内置官方 6.0.2: - -- 首次启动:暂存内置包 → 设备上签名与兼容性筛查通过 → 上游 Updater 替换 13 个文件 → 加载官方 6.0.2(sha256 与 - 官方清单一致)→ 26 个 Harmony 补丁全部安装 → 主菜单显示 `BPP 6.0.2`; -- 再次启动:不再暂存,Updater 无事可做,直接加载; -- 去黑边补丁生效,3:2 屏幕全屏; -- 场景事件从 `AppStart` 起都能收到。游戏的 IL2CPP 构建没有 `Scene.GetBuildIndexInternal_Injected`,`buildIndex` 传 -1。 - -仍待验收: - -- 用 `-Upstream` 打包的启动器 APK 覆盖安装后从原插件切换,以及启动器的后台下载(验收时用的是旧启动器,内部数据目录 - 无法用 adb 写入); -- 对局内功能; -- 插件内 HTTPS:CoreCLR 的 `HttpClient` 在设备上全部报 `AndroidCrypto SslException`(Bundle 上传、阵容库、赞助名单、 - 官方自带的更新检查)。 - -## 待决定 - -上传与联网照上游行为:Bundle 上传和 Ghost 同步走 `mod-api-v6.bazaarplusplus.com`,阵容库和赞助名单走 -`cdn.bazaarplusplus.com`,账号绑定走 `bazaardb.gg`。启动器每次打开时读一次官方发布清单。要不要向上游说明这个 fork -的流量,需要维护者决定。 - -官方插件自带的 `AndroidVersionCheck` 在本启动器里照常运行:插件内 HTTPS 修好后,它可能提示玩家去装官方 APK。 diff --git a/android-port/upstream-host/global.json b/android-port/upstream-host/global.json deleted file mode 100644 index d46d21e..0000000 --- a/android-port/upstream-host/global.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "sdk": { - "version": "10.0.100", - "rollForward": "latestFeature", - "allowPrerelease": false - } -} diff --git a/android-port/upstream-host/official-payload.json b/android-port/upstream-host/official-payload.json deleted file mode 100644 index bdc5559..0000000 --- a/android-port/upstream-host/official-payload.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "6.0.2", - "url": "https://cdn.bazaarplusplus.com/installer/6.0.2/android-aarch64/managed/BazaarPlusPlus_6.0.2_android-aarch64-managed.zip", - "size": 2845338, - "sha256": "fde6b73668c07c7e6f56be59e8a124369482f7aeb6b5da3cc3cd04d4f8c7f017" -} diff --git a/bazaar-helper-android/README.md b/bazaar-helper-android/README.md index 712e17a..df22f09 100644 --- a/bazaar-helper-android/README.md +++ b/bazaar-helper-android/README.md @@ -59,7 +59,7 @@ python3 tools/build.py --interop /path/to/current/interop ## 图标 -图标用设计侧提供的 flat 自适应图标资源(`bazaar-assistant-android-clean-v3`,已整套拷进 `app/src/main/res/`):全部画面都在**满幅、不透明**的背景层里(432×432,没有外金框、没有预圆角,由系统遮罩裁切),前景层是空的透明图,另带 monochrome PNG 与五档传统 PNG。 +图标用设计侧提供的 flat 自适应图标资源(已整套拷进 `app/src/main/res/`):全部画面都在**满幅、不透明**的背景层里(432×432,没有外金框、没有预圆角,由系统遮罩裁切),前景层是空的透明图,另带 monochrome PNG 与五档传统 PNG。 - `drawable-nodpi/`:`ic_launcher_background.png`(满幅画面)、`ic_launcher_foreground.png`(透明)、`ic_launcher_monochrome.png`(Android 13 主题图标剪影)。 - `mipmap-{mdpi..xxxhdpi}/ic_launcher(_round).png`:Android 7 及更早用的传统图标。 diff --git a/bazaarplusplus-analyzer/.env.example b/bazaarplusplus-analyzer/.env.example deleted file mode 100644 index f5c1279..0000000 --- a/bazaarplusplus-analyzer/.env.example +++ /dev/null @@ -1,25 +0,0 @@ -# Copy to .env and fill in the required values. Git ignores the local .env. - -# Local state -BPP_DATA_ROOT=/absolute/path/to/data - -# Bundle Server -BPP_API_BASE_URL= - -# R2; required only for publication. The S3 pair is derived from the token. -# The V6 metrics bucket: docs/architecture.md, Publication target. -BPP_METRICS_R2_BUCKET= - -# The workspace appends BPP_BUNDLE_SYNC_TOKEN, CLOUDFLARE_API_TOKEN and -# CLOUDFLARE_ACCOUNT_ID from config.ini [server] and [cloudflare] -# (node scripts/workspace.mjs --help); a hand-written .env sets them here. - -# Optional; omit to use application defaults -# BPP_SOURCE_EPOCH=YYYY-MM-DD -# BPP_BUNDLE_RETENTION_DAYS=8 -# BPP_FACT_RETENTION_DAYS=8 -# BPP_DOWNLOAD_CONCURRENCY=64 -# BPP_DOWNLOAD_LOOKAHEAD=128 -# BPP_MAX_RUN_SECONDS=21600 -# BPP_DUCKDB_MEMORY_LIMIT=8GB -# BPP_DUCKDB_THREADS=8 diff --git a/bazaarplusplus-analyzer/.python-version b/bazaarplusplus-analyzer/.python-version deleted file mode 100644 index 6324d40..0000000 --- a/bazaarplusplus-analyzer/.python-version +++ /dev/null @@ -1 +0,0 @@ -3.14 diff --git a/bazaarplusplus-analyzer/AGENTS.md b/bazaarplusplus-analyzer/AGENTS.md deleted file mode 100644 index f23d332..0000000 --- a/bazaarplusplus-analyzer/AGENTS.md +++ /dev/null @@ -1,15 +0,0 @@ -# AGENTS.md - -The analyzer that turns Bundles into hero and build snapshots. Repo-wide rules are in `../AGENTS.md`. - -## Routing - -- **Domain**: Read `CONTEXT.md` before changing source admission, facts, - windows, metrics, or domain names. -- **Pipeline**: Read `docs/architecture.md` before changing collection, - persistence, recovery, locking, status, or publication flow. -- **Contract**: Read `docs/specs/consumer-data-contract.md` and the affected - `contracts/v6/*.schema.json` before changing payloads, calculations, - validation, object keys, or consumer behavior. -- **Capacity**: Read `docs/measurements.md` before changing retention, - concurrency, batching, or memory defaults; remeasure the affected limit. diff --git a/bazaarplusplus-analyzer/CONTEXT.md b/bazaarplusplus-analyzer/CONTEXT.md deleted file mode 100644 index f107b60..0000000 --- a/bazaarplusplus-analyzer/CONTEXT.md +++ /dev/null @@ -1,84 +0,0 @@ -# BazaarPlusPlus Analyzer - -Use these terms for source collection, analysis, and consumer behavior. - -## Source collection - -**Bundle**: -Defined in the root `../CONTEXT.md`. The analyzer analyzes its Run: the -associated Battles and card snapshots. - -**Source Hour**: -The UTC hour assigned from a Bundle's server-observed availability time. - -**Source Day**: -The UTC date composed of all 24 Source Hours for that date. - -**Complete Source Day**: -A Source Day sealed from 24 verified Source Hours. - -**Source Epoch**: -An optional inclusive UTC date before which Source Days are outside the data -population. Pre-epoch days are not healed, sealed, or analyzed. - -**Analysis Window**: -The sequence ending at the latest sealed Complete Source Day and extending -backward through consecutive Complete Source Days, with a minimum of one day -and a maximum of seven days. It never crosses the Source Epoch. - -## Runs and segments - -**Accepted Run**: -A Run whose hero and final rank are recognized. A Run without a recognized -final rank, together with its associated Battles and card snapshots, is not -part of the analyzed population. - -**Legend Segment**: -Accepted Runs whose canonical source value for final rank is `Legendary`. - -**Non-Legend Segment**: -Accepted Runs whose final rank is recognized and is not Legend. - -**All Segment**: -The union of the Legend Segment and Non-Legend Segment. It is derived by -addition rather than stored separately. - -**Scored Run**: -A completed Accepted Run whose victory and loss values place it in a defined -outcome bucket. - -**Ten-Win Run**: -A completed Accepted Run with ten victories, including both perfect and -non-perfect results. - -**Ten-Win Rate**: -Ten-Win Runs divided by completed Accepted Runs in the same hero, segment, -and time scope. - -## Battles and builds - -**Matchup**: -The decided Battles played by one hero against another hero. A Matchup's -segment is owned by the player's Run, not by the opponent. - -**Matchup Win Rate**: -Player-side Battle wins divided by decided Matchup Battles. - -**Build Identity**: -A hero plus the sorted multiset of card template identifiers in a completed -final board. Card position, tier, and enchantment are not part of the identity. - -**Representative Layout**: -The most frequently observed complete layout among a Build Identity's -Ten-Win Runs. - -**Build Corpus**: -The current set of selected Build Identities and their Representative Layouts -used by the Mod for recommendation recall and ranking. - -## Operations - -**Operational Evidence**: -Local records of pipeline progress and outcomes used by operators to understand -the current Run, the last completed Run, and recent Run history. It is not -consumer data. diff --git a/bazaarplusplus-analyzer/LICENSE b/bazaarplusplus-analyzer/LICENSE deleted file mode 100644 index a549209..0000000 --- a/bazaarplusplus-analyzer/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2026 Xinyu YANG -Copyright (c) 2026 BazaarPlusPlus Team - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/bazaarplusplus-analyzer/README.md b/bazaarplusplus-analyzer/README.md deleted file mode 100644 index 54a23bd..0000000 --- a/bazaarplusplus-analyzer/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# BazaarPlusPlus Analyzer - -The analyzer converts verified Bundle V6 deliveries into local hourly facts and -two independent current snapshots: - -```text -heroes/latest.json -builds/latest.json -``` - -Both publish to the V6 metrics bucket, served at -`https://bpp-metrics-v6.bazaarplusplus.com`; see -[Publication target](docs/architecture.md#publication-target). - -## Operate - -Run workspace `just setup` and fill in the shared analyzer configuration described -in the [development guide](../docs/development.md). `just analyzer::cli ` -refreshes the managed repository `.env` before invoking the CLI. The analyzer itself -still reads only that file; the direct run/status/verify recipes below require a current projection. - -```bash -just analyzer::run -just analyzer::run --no-publish -just analyzer::status --json -just analyzer::verify --deep -``` - -Use `uv run --locked bpp --help` and `uv run --locked bpp --help` for the complete -operator interface. - -## Documentation - -- Domain terms and boundaries: `CONTEXT.md` -- Pipeline recovery and publication invariants: `docs/architecture.md` -- Consumer calculations and cross-field semantics: `docs/specs/consumer-data-contract.md` -- JSON wire shapes: `contracts/v6/*.schema.json` -- Measured operational limits: `docs/measurements.md` - -## Quality gate - -```bash -just analyzer::check -just analyzer::test -``` - -## License - -Released under the [MIT License](LICENSE). diff --git a/bazaarplusplus-analyzer/analyzer.just b/bazaarplusplus-analyzer/analyzer.just deleted file mode 100644 index 6e91548..0000000 --- a/bazaarplusplus-analyzer/analyzer.just +++ /dev/null @@ -1,37 +0,0 @@ -set shell := ["bash", "-euo", "pipefail", "-c"] -set positional-arguments - -# Refresh shared configuration, then run an explicit analyzer CLI command. -cli +args: - node ../scripts/workspace.mjs run analyzer -- uv run --locked bpp "$@" - -# Collect facts and publish snapshots; pass --no-publish for local validation. -run *args: - uv run --locked bpp run "$@" - -# Show local pipeline health. -status *args: - uv run --locked bpp status "$@" - -# Verify committed facts; pass --deep to validate local snapshots too. -verify *args: - uv run --locked bpp verify "$@" - -# Check Python formatting, lint, and types using the locked environment. -check: - uv run --locked ruff format --check . - uv run --locked ruff check . - uv run --locked ty check - -# Run tests and coverage without running the publication pipeline. -test: - uv run --locked pytest - -# Rewrite the pipeline and projection goldens from fixture Bundles; review the diff. -golden: - BPP_UPDATE_GOLDENS=1 uv run --locked pytest tests/test_pipeline_golden.py tests/test_bundle_goldens.py --no-cov - -# Apply safe Ruff fixes and format in place. -fmt: - uv run --locked ruff check --fix . - uv run --locked ruff format . diff --git a/bazaarplusplus-analyzer/contracts/v6/README.md b/bazaarplusplus-analyzer/contracts/v6/README.md deleted file mode 100644 index d1775a7..0000000 --- a/bazaarplusplus-analyzer/contracts/v6/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Consumer schemas - -These strict Draft 2020-12 schemas own field names, types, required fields, -enums, and scalar bounds: - -- `heroes.schema.json` validates `heroes/latest.json`. -- `builds.schema.json` validates `builds/latest.json`. - -Cross-field and calculation semantics live in -`docs/specs/consumer-data-contract.md`. `validate_snapshot` enforces both -authorities before publication. - -## Shared goldens - -`fixtures/heroes.latest.json` and `fixtures/builds.latest.json` are the exact -bytes the analyzer publishes for one Source Day of fixture Bundles served -through a stand-in Bundle Server (`tests/test_pipeline_golden.py`). Consumer -tests read them in place of hand-written snapshots. Never edit them by hand: -`just analyzer::golden` regenerates them, and `just analyzer::test` fails when -the pipeline no longer reproduces them. - -## Hero aliases - -`hero-aliases.json` owns the mapping from legacy hero ids to canonical ones. -The analyzer normalizes heroes with it, and consumer tests read it. It owns -only the mapping: each reader keeps its own matching rule (the analyzer matches -the trimmed id exactly; the mod and installer ignore ASCII case). diff --git a/bazaarplusplus-analyzer/contracts/v6/builds.schema.json b/bazaarplusplus-analyzer/contracts/v6/builds.schema.json deleted file mode 100644 index d89db46..0000000 --- a/bazaarplusplus-analyzer/contracts/v6/builds.schema.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Analyzer builds/latest.json", - "type": "object", - "additionalProperties": false, - "required": ["schema_version", "kind", "generated_at", "window", "cards", "enchantments", "schemas", "heroes"], - "properties": { - "schema_version": {"const": 2}, - "kind": {"const": "ten_win_builds"}, - "generated_at": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"}, - "window": {"$ref": "#/$defs/window"}, - "cards": { - "type": "array", - "uniqueItems": true, - "items": {"type": "string", "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"} - }, - "enchantments": { - "type": "array", - "minItems": 1, - "uniqueItems": true, - "prefixItems": [{"type": "null"}], - "items": {"type": "string", "minLength": 1} - }, - "schemas": { - "type": "object", - "additionalProperties": false, - "required": ["build", "layout", "stats"], - "properties": { - "build": {"const": ["card_refs", "layout", "stats"]}, - "layout": {"const": ["card_ref", "slot", "tier", "enchant_ref", "size"]}, - "stats": {"const": ["completed_run_count", "ten_win_run_count", "ten_win_rate_bps", "p75_ten_win_final_day", "score"]} - } - }, - "heroes": { - "type": "object", - "additionalProperties": false, - "required": ["Dooley", "Jules", "Karnok", "Mak", "Pygmalien", "Stelle", "TheDragons", "Vanessa"], - "properties": { - "Dooley": {"$ref": "#/$defs/hero"}, - "Jules": {"$ref": "#/$defs/hero"}, - "Karnok": {"$ref": "#/$defs/hero"}, - "Mak": {"$ref": "#/$defs/hero"}, - "Pygmalien": {"$ref": "#/$defs/hero"}, - "Stelle": {"$ref": "#/$defs/hero"}, - "TheDragons": {"$ref": "#/$defs/hero"}, - "Vanessa": {"$ref": "#/$defs/hero"} - } - } - }, - "$defs": { - "day": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"}, - "window": { - "type": "object", - "additionalProperties": false, - "required": ["start", "end", "days"], - "properties": { - "start": {"$ref": "#/$defs/day"}, - "end": {"$ref": "#/$defs/day"}, - "days": {"type": "integer", "minimum": 1, "maximum": 7} - } - }, - "hero": { - "type": "object", - "additionalProperties": false, - "required": ["builds", "card_index"], - "properties": { - "builds": {"type": "array", "items": {"$ref": "#/$defs/build"}}, - "card_index": {"type": "array", "items": {"$ref": "#/$defs/card_index"}} - } - }, - "build": { - "type": "array", - "minItems": 3, - "maxItems": 3, - "prefixItems": [ - {"type": "array", "minItems": 1, "items": {"type": "integer", "minimum": 0}}, - {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/layout"}}, - {"$ref": "#/$defs/stats"} - ], - "items": false - }, - "layout": { - "type": "array", - "minItems": 5, - "maxItems": 5, - "prefixItems": [ - {"type": "integer", "minimum": 0}, - {"type": "integer", "minimum": 0}, - {"type": "integer", "minimum": 1, "maximum": 5}, - {"type": "integer", "minimum": 0}, - {"type": "integer", "minimum": 1, "maximum": 3} - ], - "items": false - }, - "stats": { - "type": "array", - "minItems": 5, - "maxItems": 5, - "prefixItems": [ - {"type": "integer", "minimum": 1}, - {"type": "integer", "minimum": 1}, - {"type": "integer", "minimum": 0, "maximum": 10000}, - {"type": ["integer", "null"], "minimum": 0}, - {"type": "integer", "minimum": 0, "maximum": 1000000} - ], - "items": false - }, - "card_index": { - "type": "array", - "minItems": 2, - "maxItems": 2, - "prefixItems": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"type": "integer", "minimum": 0}} - ], - "items": false - } - } -} diff --git a/bazaarplusplus-analyzer/contracts/v6/fixtures/builds.latest.json b/bazaarplusplus-analyzer/contracts/v6/fixtures/builds.latest.json deleted file mode 100644 index 4eb9455..0000000 --- a/bazaarplusplus-analyzer/contracts/v6/fixtures/builds.latest.json +++ /dev/null @@ -1 +0,0 @@ -{"cards":["11111111-1111-4111-8111-111111111111","22222222-2222-4222-8222-222222222222","33333333-3333-4333-8333-333333333333","44444444-4444-4444-8444-444444444444","55555555-5555-4555-8555-555555555555","66666666-6666-4666-8666-666666666666","77777777-7777-4777-8777-777777777777","88888888-8888-4888-8888-888888888888"],"enchantments":[null,"Burning"],"generated_at":"2026-08-11T00:30:00Z","heroes":{"Dooley":{"builds":[[[0,1,2,3],[[0,0,3,0,3],[1,3,3,1,3],[2,6,3,0,2],[3,8,3,0,2]],[2,2,10000,10,342372]]],"card_index":[[0,[0]],[1,[0]],[2,[0]],[3,[0]]]},"Jules":{"builds":[[[4,5,6,7],[[4,0,4,0,3],[5,3,4,0,3],[6,6,4,0,2],[7,8,4,0,2]],[5,4,8000,3,375528]]],"card_index":[[4,[0]],[5,[0]],[6,[0]],[7,[0]]]},"Karnok":{"builds":[],"card_index":[]},"Mak":{"builds":[[[0,1,2,3],[[0,0,1,0,3],[1,3,1,0,3],[2,6,1,0,3],[3,9,1,0,1]],[1,1,10000,10,206543]]],"card_index":[[0,[0]],[1,[0]],[2,[0]],[3,[0]]]},"Pygmalien":{"builds":[],"card_index":[]},"Stelle":{"builds":[[[0,1,2,3],[[0,0,5,0,3],[1,3,5,0,3],[2,6,5,0,3],[3,9,5,0,1]],[1,1,10000,10,206543]]],"card_index":[[0,[0]],[1,[0]],[2,[0]],[3,[0]]]},"TheDragons":{"builds":[],"card_index":[]},"Vanessa":{"builds":[],"card_index":[]}},"kind":"ten_win_builds","schema_version":2,"schemas":{"build":["card_refs","layout","stats"],"layout":["card_ref","slot","tier","enchant_ref","size"],"stats":["completed_run_count","ten_win_run_count","ten_win_rate_bps","p75_ten_win_final_day","score"]},"window":{"days":1,"end":"2026-08-10","start":"2026-08-10"}} diff --git a/bazaarplusplus-analyzer/contracts/v6/fixtures/heroes.latest.json b/bazaarplusplus-analyzer/contracts/v6/fixtures/heroes.latest.json deleted file mode 100644 index bbfacab..0000000 --- a/bazaarplusplus-analyzer/contracts/v6/fixtures/heroes.latest.json +++ /dev/null @@ -1 +0,0 @@ -{"days":[{"day":"2026-08-10","rows":[{"hero":"Dooley","matchups":[{"decided":13,"losses":0,"opponent_hero":"Pygmalien","wins":13}],"outcomes":{"bronze":0,"gold":0,"perfect":11,"silver":1},"runs":{"completed":12,"scored":12,"ten_win":11},"segment":"legend","ten_win_days":{"known_count":11,"sum_days":110}},{"hero":"Dooley","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"non_legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"Jules","matchups":[{"decided":5,"losses":0,"opponent_hero":"Pygmalien","wins":5}],"outcomes":{"bronze":0,"gold":0,"perfect":4,"silver":1},"runs":{"completed":5,"scored":5,"ten_win":4},"segment":"legend","ten_win_days":{"known_count":4,"sum_days":106}},{"hero":"Jules","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"non_legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"Karnok","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"Karnok","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"non_legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"Mak","matchups":[{"decided":1,"losses":0,"opponent_hero":"Pygmalien","wins":1}],"outcomes":{"bronze":0,"gold":0,"perfect":1,"silver":0},"runs":{"completed":1,"scored":1,"ten_win":1},"segment":"legend","ten_win_days":{"known_count":1,"sum_days":10}},{"hero":"Mak","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"non_legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"Pygmalien","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"Pygmalien","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"non_legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"Stelle","matchups":[{"decided":1,"losses":0,"opponent_hero":"Pygmalien","wins":1}],"outcomes":{"bronze":0,"gold":0,"perfect":1,"silver":0},"runs":{"completed":1,"scored":1,"ten_win":1},"segment":"legend","ten_win_days":{"known_count":1,"sum_days":10}},{"hero":"Stelle","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"non_legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"TheDragons","matchups":[{"decided":1,"losses":0,"opponent_hero":"Pygmalien","wins":1}],"outcomes":{"bronze":0,"gold":0,"perfect":1,"silver":0},"runs":{"completed":1,"scored":1,"ten_win":1},"segment":"legend","ten_win_days":{"known_count":1,"sum_days":10}},{"hero":"TheDragons","matchups":[],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":0,"scored":0,"ten_win":0},"segment":"non_legend","ten_win_days":{"known_count":0,"sum_days":0}},{"hero":"Vanessa","matchups":[{"decided":6,"losses":1,"opponent_hero":"Pygmalien","wins":5}],"outcomes":{"bronze":1,"gold":1,"perfect":3,"silver":0},"runs":{"completed":7,"scored":7,"ten_win":4},"segment":"legend","ten_win_days":{"known_count":4,"sum_days":40}},{"hero":"Vanessa","matchups":[{"decided":1,"losses":1,"opponent_hero":"Pygmalien","wins":0}],"outcomes":{"bronze":0,"gold":0,"perfect":0,"silver":0},"runs":{"completed":1,"scored":1,"ten_win":0},"segment":"non_legend","ten_win_days":{"known_count":0,"sum_days":0}}]}],"generated_at":"2026-08-11T00:30:00Z","kind":"hero_metrics","schema_version":1,"window":{"days":1,"end":"2026-08-10","start":"2026-08-10"}} diff --git a/bazaarplusplus-analyzer/contracts/v6/hero-aliases.json b/bazaarplusplus-analyzer/contracts/v6/hero-aliases.json deleted file mode 100644 index a7e6104..0000000 --- a/bazaarplusplus-analyzer/contracts/v6/hero-aliases.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "schema_version": 1, - "aliases": { - "Hero8": "TheDragons" - } -} diff --git a/bazaarplusplus-analyzer/contracts/v6/heroes.schema.json b/bazaarplusplus-analyzer/contracts/v6/heroes.schema.json deleted file mode 100644 index a745861..0000000 --- a/bazaarplusplus-analyzer/contracts/v6/heroes.schema.json +++ /dev/null @@ -1,129 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Analyzer heroes/latest.json", - "type": "object", - "additionalProperties": false, - "required": ["schema_version", "kind", "generated_at", "window", "days"], - "properties": { - "schema_version": {"const": 1}, - "kind": {"const": "hero_metrics"}, - "generated_at": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"}, - "window": {"$ref": "#/$defs/window"}, - "days": { - "type": "array", - "minItems": 1, - "maxItems": 7, - "items": { - "type": "object", - "additionalProperties": false, - "required": ["day", "rows"], - "properties": { - "day": {"$ref": "#/$defs/day"}, - "rows": { - "type": "array", - "minItems": 16, - "maxItems": 16, - "items": {"$ref": "#/$defs/row"} - } - } - } - } - }, - "allOf": [ - { - "if": {"properties": {"window": {"properties": {"days": {"const": 1}}}}}, - "then": {"properties": {"days": {"minItems": 1, "maxItems": 1}}} - }, - { - "if": {"properties": {"window": {"properties": {"days": {"const": 2}}}}}, - "then": {"properties": {"days": {"minItems": 2, "maxItems": 2}}} - }, - { - "if": {"properties": {"window": {"properties": {"days": {"const": 3}}}}}, - "then": {"properties": {"days": {"minItems": 3, "maxItems": 3}}} - }, - { - "if": {"properties": {"window": {"properties": {"days": {"const": 4}}}}}, - "then": {"properties": {"days": {"minItems": 4, "maxItems": 4}}} - }, - { - "if": {"properties": {"window": {"properties": {"days": {"const": 5}}}}}, - "then": {"properties": {"days": {"minItems": 5, "maxItems": 5}}} - }, - { - "if": {"properties": {"window": {"properties": {"days": {"const": 6}}}}}, - "then": {"properties": {"days": {"minItems": 6, "maxItems": 6}}} - }, - { - "if": {"properties": {"window": {"properties": {"days": {"const": 7}}}}}, - "then": {"properties": {"days": {"minItems": 7, "maxItems": 7}}} - } - ], - "$defs": { - "count": {"type": "integer", "minimum": 0}, - "day": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"}, - "window": { - "type": "object", - "additionalProperties": false, - "required": ["start", "end", "days"], - "properties": { - "start": {"$ref": "#/$defs/day"}, - "end": {"$ref": "#/$defs/day"}, - "days": {"type": "integer", "minimum": 1, "maximum": 7} - } - }, - "row": { - "type": "object", - "additionalProperties": false, - "required": ["hero", "segment", "runs", "outcomes", "ten_win_days", "matchups"], - "properties": { - "hero": {"enum": ["Dooley", "Jules", "Karnok", "Mak", "Pygmalien", "Stelle", "TheDragons", "Vanessa"]}, - "segment": {"enum": ["legend", "non_legend"]}, - "runs": { - "type": "object", - "additionalProperties": false, - "required": ["completed", "scored", "ten_win"], - "properties": { - "completed": {"$ref": "#/$defs/count"}, - "scored": {"$ref": "#/$defs/count"}, - "ten_win": {"$ref": "#/$defs/count"} - } - }, - "outcomes": { - "type": "object", - "additionalProperties": false, - "required": ["perfect", "gold", "silver", "bronze"], - "properties": { - "perfect": {"$ref": "#/$defs/count"}, - "gold": {"$ref": "#/$defs/count"}, - "silver": {"$ref": "#/$defs/count"}, - "bronze": {"$ref": "#/$defs/count"} - } - }, - "ten_win_days": { - "type": "object", - "additionalProperties": false, - "required": ["known_count", "sum_days"], - "properties": { - "known_count": {"$ref": "#/$defs/count"}, - "sum_days": {"$ref": "#/$defs/count"} - } - }, - "matchups": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": false, - "required": ["opponent_hero", "decided", "wins", "losses"], - "properties": { - "opponent_hero": {"enum": ["Dooley", "Jules", "Karnok", "Mak", "Pygmalien", "Stelle", "TheDragons", "Vanessa"]}, - "decided": {"type": "integer", "minimum": 1}, - "wins": {"$ref": "#/$defs/count"}, - "losses": {"$ref": "#/$defs/count"} - } - } - } - } - } - } -} diff --git a/bazaarplusplus-analyzer/docs/architecture.md b/bazaarplusplus-analyzer/docs/architecture.md deleted file mode 100644 index 97cb2bc..0000000 --- a/bazaarplusplus-analyzer/docs/architecture.md +++ /dev/null @@ -1,129 +0,0 @@ -# Pipeline architecture - -This document owns invariants that span pipeline modules. Consumer payload -semantics belong to `specs/consumer-data-contract.md`. - -## Lifecycle - -One directory-locked invocation: - -1. heals settled Source Hours through one intake transaction: enumerate the - complete index, admit each Bundle once, project bounded Arrow batches, and - atomically commit the complete hour; -2. seals a Complete Source Day only after all 24 hourly commits verify; -3. selects the latest consecutive one-to-seven-day Analysis Window; -4. builds, validates, saves, and optionally publishes each consumer snapshot - independently; -5. after both consumer snapshots publish successfully, removes local facts older - than the configured number of latest Complete Source Days. - -Raw Bundle envelopes are validated once at admission; only the manifest and Run -segment cross into projection. Raw bytes are then discarded. Durable local -state consists of hourly facts and commits, day seals or abandonment records, -current snapshots, status, run history, and logs. - -## Recovery invariants - -- A download or Bundle validation failure leaves its Source Hour uncommitted. -- An hourly commit is immutable. Reprocessing identical content reuses it; - different content at the same Source Hour is a conflict. -- A day seal names exactly 24 verified hourly commit identities. A retention- - expired day that cannot be completed is recorded as abandoned. -- Analysis reads explicit Parquet paths recovered from verified day seals. -- Projection admits Runs and normalizes hero, final rank, and Battle winner - side once. Analysis reads those stored columns as-is and reads every hour - with the one owned table schema, so a change to admission or to a fact - schema must replace every committed hour in the Analysis Window, not only - new ones. -- Fact retention defaults to the latest eight Complete Source Days: the - seven-day Analysis Window plus one rollback day. All newer incomplete Source - Hours remain available for sealing. Retention removes an expired day seal - before its hourly facts, so an interrupted cleanup cannot leave a seal that - references missing files. -- Each product uses its own analysis connection and failure boundary. A valid - product can advance while the other product remains unchanged. -- Snapshot bytes are canonical JSON and pass schema plus semantic validation - before local replacement or object-store publication. -- The heartbeat lock fences stale owners before durable writes. A replacement - owner may recover from committed state without trusting partial staging data. - -## Publication target - -The consumer snapshots publish to the R2 bucket `BPP_METRICS_R2_BUCKET` names: -`bazaarplusplus-metrics-v6`, served read-only at the custom domain -`bpp-metrics-v6.bazaarplusplus.com`. Keys carry no version prefix; the bucket -and domain name the version. -A production mod Payload embeds `builds/latest.json` fetched from this origin at -build time (`TenWinBuildsRemoteUrl` in the mod's `RemoteEmbeddedData.targets`, -which also sets its minimum size), so `release::prepare` fails until a first -publication lands here. - -The bucket's CORS rule, set on the bucket rather than kept in this repository, -lets the site read Hero metrics from the browser: allowed method `GET` only, no headers, no credentials; allowed origins -`https://bazaarplusplus.com`, the preview site -`https://bazaarplusplus-site-preview.cauyxy.workers.dev`, and the local dev -servers `http://localhost:3000`, `:4173`, `:5173`, `http://127.0.0.1:3000` and -`http://0.0.0.0:3000`. The site ADR -`bazaarplusplus-site/docs/adr/0001-direct-metrics-origin.md` depends on it. - -## Production runs - -Production runs are `.github/workflows/analyzer.yml` on a GitHub-hosted runner, -plus manual dispatch with an optional `--no-publish`. The V6 Bundle Server -Worker starts the hourly run through `workflow_dispatch`, because GitHub's own -`schedule` trigger drops most events under load; the workflow keeps a sparse -`schedule` only as a fallback (`bazaarplusplus-server/docs/deployment-runbook.md`, -Analyzer dispatch). A runner starts -empty, so the Data Root lives in the private R2 bucket -`bazaarplusplus-analyzer-state-v6` and `.github/scripts/analyzer-state.sh` -mirrors it around each run: - -- The run starts only after a complete pull into an empty Data Root and a - `bpp verify --deep` of what it restored; either failing stops the job before - any write. -- After a successful run the mirror deletes what fact retention pruned. After a - failed run it only uploads new and changed files, so the hours that run - committed survive and nothing is deleted. -- Lock and staging entries are never mirrored. The workflow's concurrency - group, not `DirectoryLock`, keeps the state bucket to one writer, so no other - machine runs a publishing analyzer against that bucket. - -Snapshots still advance once per Complete Source Day; the hourly schedule only -keeps each run's intake small and leaves room for skipped schedules within the -eight-day Bundle retention. `BPP_MAX_RUN_SECONDS` is set below the six-hour job -limit so a long heal stops itself and its committed hours are mirrored before -the runner is reclaimed. The workflow's secrets live in the `analyzer` GitHub -Environment, listed in `release/github-secrets.json`; its R2 token reaches only -the V6 metrics and state buckets. - -## Modes and evidence - -`run --no-publish` performs collection and local snapshot -replacement without constructing an R2 adapter. - -The Operational Evidence module owns the shape and persistence of the Run -Report, live status, run history, and logs. Each normal invocation atomically -refreshes `status.json`, appends to `runs.jsonl`, and records progress in its run -log. These artifacts are local operational evidence, not consumer objects. - -`RunEvidence` accumulates one Run's facts and materializes its final summary -once. Collection and publication update the same report; a later failure, -including retention failure, preserves completed publication and analysis -facts. The driver retains pipeline ordering and lock-ownership decisions. - -`SourceHourIntake` in `src/bppanalyzer/hour_intake.py` owns one Source Hour's -index and ingest stages, cumulative admission counts, timings, and terminal -result. Its synchronous progress observations reach Operational Evidence during streaming, before the next -Bundle is projected; the driver does not reconstruct these facts from callbacks -or Run-level counter differences. Successful admission counts describe downloads, -not durable commits. A failure observation only updates in-memory evidence, so a -lost lock cannot trigger another status or log write. `FactStore` in -`src/bppanalyzer/fact_store.py` retains atomic commit and write-time ownership -checks; the driver retains Source Day scheduling, abandonment, and sealing. Recoverable source failures return a terminal result -for the driver to schedule; observer failures propagate as Run failures, even -when their exception type happens to match a recoverable source error. - -Run evidence aggregates collection and processing performance at Run scope: -listing pages and retries, download attempts, retries, bytes and latency -percentiles, plus bounded stage timings for projection, Parquet persistence, -snapshot construction, and publication. It never stores per-Bundle metrics. diff --git a/bazaarplusplus-analyzer/docs/measurements.md b/bazaarplusplus-analyzer/docs/measurements.md deleted file mode 100644 index 7d94c60..0000000 --- a/bazaarplusplus-analyzer/docs/measurements.md +++ /dev/null @@ -1,77 +0,0 @@ -# Analyzer operational measurements - -These measurements were taken on Apple Silicon on 2026-08-11 and 2026-08-12 -against the production Bundle Server, using read-only collection and local fact -writes. They are workload observations, not portable guarantees. - -## Bundle retention behavior - -The configured retention contract is eight days. Deterministic boundary checks -cover the Worker cutoff (`8 × 86,400,000 ms`) and the Analyzer default (eight -UTC dates). - -The server returns HTTP 410 with `window_expired` for hours outside retention -and HTTP 200 with an empty `items` array for a retained hour with no Bundles. -The source adapter preserves this distinction; an expired day is abandoned, -while a retained zero-Bundle hour can be committed. - -## Collection throughput - -A busy Source Hour contains roughly 2,400 Bundles. Initial conservative -collection took five to six minutes per busy hour. Because the workload is -latency-bound, increasing download concurrency from 4 to 8 approximately -halved collection time. Concurrency 64 produced no observed server-side -pushback when the HTTP keepalive pool was sized to match. The shipped -defaults are therefore 64 download workers, 128-bundle lookahead, and a -21,600-second run budget. - -Transient collection failures use bounded jittered backoff. A valid -`Retry-After` response can extend the next delay up to 60 seconds. Once a fatal -Bundle failure is observed, queued downloads that have not started are -cancelled; already-running requests are allowed to finish before the Source -Hour fails without a commit. - -## Local fact storage - -Busy hours produce roughly 17–22 MiB of Parquet, dominated by Battle Cards. -Five sealed Source Days occupied about 1.9 GiB. - -The default local fact retention is the latest eight sealed Complete Source -Days. It is intentionally separate from the Bundle Server's eight-day source -availability contract. Retention runs only after both consumer snapshots have -published successfully and preserves every newer incomplete Source Hour. - -On 2026-08-19, 272 hourly partitions spanning 11 sealed days plus eight hours -of the next Source Day occupied 4,731,857,648 bytes (4.41 GiB). Applying the -eight-sealed-day boundary to that population would remove 72 old hourly -partitions totaling about 1.19 GiB, leaving an estimated 3.21 GiB. Daily size -varies with Bundle volume. - -## Analysis resources - -Analysis of five Source Days containing 2.79 million Battles took about four -seconds and stayed below 1 GiB RSS. The seven-day offline fixture remains below -the 8 GiB build limit. - -Projection flushes fixed 50,000-row Arrow batches. A 2,500-Bundle synthetic -hour with 1.13 million Battle Card rows peaked 159 MiB above its fresh-process -baseline and produced 23 Parquet row groups. A production busy-hour heal with -734,544 rows peaked at 0.65 GiB for the whole process, below the 1 GiB hourly -ingest limit. - -After Run performance instrumentation was added, the current 2,500-Bundle, -250,000-card acceptance fixture completed in 3.10 seconds, peaked about 148 MiB -above its fresh-process baseline, and kept whole-process RSS near 241 MiB. - -## Consumer snapshot size - -The two current snapshot sizes have not yet been measured in production. - -## Performance evidence - -Each Run Report records low-cardinality collection totals: listing pages and -requests, listing/download retries, download attempts and bytes, and p50/p95 -attempt latency. Run timings separate source indexing, download waiting, -projection, Parquet writing, fact finalization, and each product's build, local -save, and publication stages. This is diagnostic evidence rather than a -portable service-level guarantee. diff --git a/bazaarplusplus-analyzer/docs/specs/consumer-data-contract.md b/bazaarplusplus-analyzer/docs/specs/consumer-data-contract.md deleted file mode 100644 index d31761d..0000000 --- a/bazaarplusplus-analyzer/docs/specs/consumer-data-contract.md +++ /dev/null @@ -1,193 +0,0 @@ -# Consumer data semantics - -The strict schemas in `../../contracts/v6/` own JSON field names, types, -required fields, enums, and scalar bounds. This document owns population, -calculation, ordering, and cross-field semantics. Domain terms are defined in -`../../CONTEXT.md`. - -The public object set is exactly, at `https://bpp-metrics-v6.bazaarplusplus.com`: - -```text -heroes/latest.json -builds/latest.json -``` - -Each key holds a mutable current snapshot for one independent consumer. - -## Shared population and window - -Hero ids are normalized through the alias table in -[`hero-aliases.json`](../../contracts/v6/hero-aliases.json). A Run becomes an -Accepted Run only when its normalized hero and final rank are canonical. The -canonical ranks are `Bronze`, `Silver`, `Gold`, `Diamond`, `Master`, `Masters`, -and `Legendary`. Rejecting a Run also rejects its Battles and card snapshots. - -`Legendary` maps to the `legend` segment; every other canonical rank maps to -`non_legend`. A Battle inherits the segment of its owning Run. The `all` -segment is always derived by adding `legend` and `non_legend`. - -Both products use the latest sequence of one to seven consecutive sealed -Complete Source Days. A newer incomplete day does not block an earlier sealed -day from ending the window. The window never crosses the optional Source -Epoch. `window.start` and `window.end` are inclusive UTC dates, and -`generated_at` is the UTC snapshot-generation time. - -## Hero metrics - -`heroes/latest.json` contains one newest-first partition per Source Day. Each -partition has one row for every canonical Hero × stored Segment pair in -canonical hero order, with `legend` before `non_legend`. An unobserved pair has -zero counts and an empty `matchups` array. - -Only additive integer components are stored. A consumer selects up to the -newest 1, 3, or 7 available partitions, sums each field by hero and segment, -then derives rates and averages. - -### Run outcomes - -`runs.completed` counts completed Accepted Runs. `runs.scored` is the subset -whose victories are from 0 through 10 and whose losses are non-negative. - -| Outcome | Definition | -| --- | --- | -| `perfect` | 10 victories and 0 losses | -| `gold` | 10 victories and at least 1 loss | -| `silver` | 7–9 victories | -| `bronze` | 4–6 victories | -| misfortune | 0–3 victories; derived | - -The additive invariants are: - -```text -0 <= scored <= completed -ten_win = perfect + gold -misfortune = scored - perfect - gold - silver - bronze -``` - -`ten_win_days.known_count` counts Ten-Win Runs with a known final Run day; -`ten_win_days.sum_days` sums those days. Their ratio remains correct after -partitions are combined, and `known_count <= ten_win`. - -### Matchups - -A Matchup includes a Battle only when the opponent hero is canonical and the -winner resolves to `player` or `opponent`. For every emitted row: - -```text -decided = wins + losses -matchup_win_rate = wins / decided -``` - -### Consumer calculations - -| Display value | Calculation | -| --- | --- | -| Ten-Win rate | `ten_win / completed` | -| Completed Runs | `completed` | -| Run share | hero `completed / sum(completed)` in the same scope | -| Ten-Win Runs | `ten_win` | -| Average Ten-Win final day | `sum_days / known_count` | -| Perfect rate | `perfect / scored` | -| Gold rate | `gold / scored` | -| Silver rate | `silver / scored` | -| Bronze rate | `bronze / scored` | -| Misfortune rate | `misfortune / scored` | -| Matchup win rate | `wins / decided` | -| Seven-day trend | daily `ten_win / completed` | - -A zero denominator produces `null`. - -## Build corpus - -`builds/latest.json` is calculated from all Accepted Runs in the Analysis -Window without rank segmentation. Its positional rows are self-described by -the payload's `schemas` object. Build IDs are zero-based positions in each -hero's `builds` array. - -The global card and enchantment tables are uniquely and deterministically -sorted. Enchantment reference 0 means no enchantment. For each hero, -`card_index` maps every card reference to exactly the emitted Build IDs whose -identities contain that card. - -### Eligible final layouts - -A completed Accepted Run contributes a layout when: - -- exactly one Battle is marked final and its ID equals the Run's - `final_battle_id`; -- the final player-hand item snapshot is present and captured; -- every item has a valid card template ID, a size from 1 through 3, a known - tier (Bronze, Silver, Gold, Diamond, or Legendary), and an in-range slot; -- the items occupy all 10 board slots exactly once. - -Socket-effect overlays (`card_type = 7`) share a socket with an item. They are -removed before identity and occupancy are evaluated. - -A layout with any invalid item excludes the entire Run from Build Corpus -statistics and Representative Layout selection. It does not change the -Accepted Run population used by Hero metrics. Tier names are trimmed and -matched without case sensitivity. - -A Build Identity is its hero plus the sorted multiset of card template IDs. -Position, tier, and enchantment belong to layouts, not identity. Every eligible -run with that identity contributes to `completed_run_count`; every such Run -with 10 victories and non-negative losses contributes to -`ten_win_run_count`. An identity becomes a candidate after at least one -Ten-Win Run. - -The Representative Layout is the most frequent exact layout among the -candidate's Ten-Win Runs. Frequency ties use canonical layout order: slot, -card template ID, tier, enchantment, and size, followed by lexical canonical -JSON order. - -`ten_win_rate_bps` is the observed Ten-Win rate rounded to the nearest whole -basis point. `p75_ten_win_final_day` uses nearest rank over known Ten-Win final -days: - -```text -sorted_days[ceil(0.75 * count) - 1] -``` - -It is `null` when no Ten-Win Run has a known final day. - -### Score and selection - -`score` is the 95% Wilson lower bound of the observed Ten-Win rate, scaled to -an integer: - -```text -n = completed_run_count -k = ten_win_run_count -p = k / n -z = 1.96 - -lower = (p + z²/(2n) - z*sqrt(p*(1-p)/n + z²/(4n²))) - / (1 + z²/n) -score = round(lower * 1,000,000) -``` - -For each hero, candidates are ordered by: - -1. descending `score`; -2. descending `ten_win_run_count`; -3. ascending `p75_ten_win_final_day`, with `null` last; -4. ascending Build Identity. - -The core corpus is the first 500 candidates. For every candidate card absent -from that core, append the highest-ranked candidate containing it. Appended -candidates retain the same ranking order and may cover several absent cards. - -## Validation and publication - -Each product passes its JSON Schema and semantic validation before its local -snapshot or public object is replaced. Product failures are isolated: a valid -snapshot can advance while the other key remains unchanged. - -Public replacement uses canonical JSON and these headers: - -```text -Cache-Control: public,max-age=60,must-revalidate -Content-Type: application/json -``` - -Consumers use `window.end` as data freshness. diff --git a/bazaarplusplus-analyzer/pyproject.toml b/bazaarplusplus-analyzer/pyproject.toml deleted file mode 100644 index 5951c7b..0000000 --- a/bazaarplusplus-analyzer/pyproject.toml +++ /dev/null @@ -1,71 +0,0 @@ -[project] -name = "bazaarplusplus-analyzer" -version = "0.3.0" -description = "Single-process analyzer publishing two Analyzer consumer snapshots" -requires-python = "==3.14.*" -dependencies = [ - "boto3==1.43.112", - "click==8.5.0", - "duckdb==1.5.6", - "httpx==0.28.1", - "jsonschema==4.26.0", - "pyarrow==26.0.0", - "python-dotenv==1.2.4", -] - -[project.scripts] -bpp = "bppanalyzer.cli:main" - -[tool.uv] -required-version = ">=0.11.21" - -[dependency-groups] -dev = [ - "pytest==9.1.1", - "pytest-cov==7.1.0", - "ruff==0.17.0", - "ty==0.0.86", -] - -[build-system] -requires = ["hatchling==1.32.4"] -build-backend = "hatchling.build" - -[tool.hatch.build.targets.wheel] -packages = ["src/bppanalyzer"] - -[tool.pytest.ini_options] -addopts = [ - "--cov=bppanalyzer", - "--cov-branch", - "--cov-fail-under=78", - "--cov-report=term-missing:skip-covered", -] -testpaths = ["tests"] - -[tool.coverage.report] -fail_under = 78 -precision = 2 -show_missing = true -skip_covered = true - -[tool.coverage.run] -branch = true -source = ["bppanalyzer"] - -[tool.ruff] -line-length = 100 -src = ["src", "tests"] -target-version = "py314" - -[tool.ruff.lint] -select = ["E4", "E7", "E9", "F", "I", "B", "UP", "SIM", "RUF"] -# Progress callbacks defined inside loops run synchronously within the same -# iteration, so late binding of loop variables cannot occur. -ignore = ["B023"] - -[tool.ty.environment] -python-version = "3.14" - -[tool.ty.src] -include = ["src"] diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/__init__.py b/bazaarplusplus-analyzer/src/bppanalyzer/__init__.py deleted file mode 100644 index 2149825..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Single-process analyzer for the Analyzer consumer snapshots.""" diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/accepted_runs.py b/bazaarplusplus-analyzer/src/bppanalyzer/accepted_runs.py deleted file mode 100644 index ea4b8ad..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/accepted_runs.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Accepted Run admission and the canonical hero and rank sets.""" - -import json -from dataclasses import dataclass -from pathlib import Path - -CANONICAL_HEROES = ( - "Dooley", - "Jules", - "Karnok", - "Mak", - "Pygmalien", - "Stelle", - "TheDragons", - "Vanessa", -) -CANONICAL_RANKS = frozenset( - {"Bronze", "Silver", "Gold", "Diamond", "Master", "Masters", "Legendary"} -) -LEGEND_RANK = "Legendary" - - -def _load_hero_aliases() -> dict[str, str]: - """Read the analyzer-owned alias table shared with the mod and installer.""" - path = Path(__file__).resolve().parents[2] / "contracts" / "v6" / "hero-aliases.json" - return dict(json.loads(path.read_bytes())["aliases"]) - - -_HERO_ALIASES = _load_hero_aliases() - - -@dataclass(frozen=True, slots=True) -class RunAdmission: - hero: str - final_rank: str | None - unknown_hero: bool - unknown_final_rank: bool - - @property - def accepted(self) -> bool: - return not self.unknown_hero and not self.unknown_final_rank - - -def admit_run(hero: str, final_rank: str | None) -> RunAdmission: - """Normalize one Run and decide whether it belongs to the analyzed population.""" - normalized_hero = normalize_hero(hero) - assert normalized_hero is not None - normalized_rank = normalize_rank(final_rank) - unknown_hero = normalized_hero not in CANONICAL_HEROES - unknown_final_rank = normalized_rank not in CANONICAL_RANKS - return RunAdmission( - normalized_hero, - normalized_rank, - unknown_hero, - unknown_final_rank, - ) - - -def normalize_hero(value: str | None) -> str | None: - if value is None: - return None - normalized = value.strip() - return _HERO_ALIASES.get(normalized, normalized) - - -def normalize_rank(value: str | None) -> str | None: - return value.strip() if value is not None else None diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/bundle_source.py b/bazaarplusplus-analyzer/src/bppanalyzer/bundle_source.py deleted file mode 100644 index 63b4947..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/bundle_source.py +++ /dev/null @@ -1,727 +0,0 @@ -"""Bounded, in-memory access to immutable Bundle Server Source Hours.""" - -import hashlib -import json -import math -import random -import re -import threading -import time -from collections.abc import Callable, Iterator, Mapping -from concurrent.futures import Future, ThreadPoolExecutor -from dataclasses import dataclass -from datetime import UTC, datetime, timedelta -from email.utils import parsedate_to_datetime -from typing import Any, Self, TypeVar - -import httpx - -from bppanalyzer.durable import canonical_json - -# Bundle version by prefix magic; the V6 Worker serves only Bundle V6. -BUNDLE_VERSIONS = {b"BPPBNDL6": 6} -MAX_BUNDLE_BYTES = 8_388_607 -MAX_MANIFEST_BYTES = 2_097_152 -MAX_RUN_BYTES = 2_097_151 -MAX_SCREENSHOT_BYTES = 1_048_576 - -_SHA256 = re.compile(r"^[0-9a-f]{64}$") -RETRY_BACKOFF_SECONDS = (1.0, 2.0, 4.0) -MAX_RETRY_AFTER_SECONDS = 60.0 -PAGE_LIMIT = 200 - -_T = TypeVar("_T") - - -def _jittered_delay(delay: float) -> float: - return random.uniform(delay * 0.5, delay * 1.5) - - -class BundleSourceError(RuntimeError): - """A safe, classified Bundle Server or Bundle contract failure.""" - - def __init__( - self, reason: str, message: str, *, retry_after_seconds: float | None = None - ) -> None: - super().__init__(message) - self.reason = reason - self.retry_after_seconds = retry_after_seconds - - -class HourExpired(BundleSourceError): - """The requested Source Hour is no longer recoverable.""" - - -class RetryableSourceError(BundleSourceError): - """A transient request or download failure.""" - - -class SourceContractError(BundleSourceError): - """The server response violates the fixed collection contract.""" - - -class DownloadUrlExpired(BundleSourceError): - """A presigned download capability must be refreshed by re-enumeration.""" - - -class _InvalidDownload(BundleSourceError): - def __init__(self, reason: str, message: str, observed_bytes: int) -> None: - super().__init__(reason, message) - self.observed_bytes = observed_bytes - - -@dataclass(frozen=True, slots=True) -class SourcePerformance: - listing_requests: int - listing_retries: int - download_attempts: int - download_retries: int - downloaded_bytes: int - download_wait_seconds: float - retry_sleep_seconds: float - download_latency_ms_p50: float | None - download_latency_ms_p95: float | None - - -@dataclass(frozen=True, slots=True) -class BundleRef: - bundle_id: str - available_at_ms: int - download_url: str - download_expires_at_ms: int - - @property - def cursor(self) -> tuple[int, str]: - return self.available_at_ms, self.bundle_id - - -@dataclass(frozen=True, slots=True) -class RawHourIndex: - source_hour: datetime - items: tuple[BundleRef, ...] - raw_commit_sha256: str - pages: int - - def __post_init__(self) -> None: - object.__setattr__(self, "source_hour", parse_source_hour(self.source_hour)) - - -@dataclass(frozen=True, slots=True) -class Bundle: - """One admitted in-memory Bundle ready for projection.""" - - ref: BundleRef - sha256: str - bytes: int - manifest: Mapping[str, Any] - run_content: bytes - - -class BundleSource: - """Enumerate a complete hour, then stream verified downloads in index order.""" - - def __init__( - self, - *, - api_base_url: str, - sync_token: str, - client: httpx.Client | None = None, - clock: Callable[[], datetime] = lambda: datetime.now(UTC), - retention_days: int = 8, - download_concurrency: int = 64, - lookahead: int = 128, - sleep: Callable[[float], None] = time.sleep, - jitter: Callable[[float], float] = _jittered_delay, - ) -> None: - if not api_base_url or not sync_token: - raise ValueError("Bundle Server URL and sync token are required") - if retention_days < 1 or download_concurrency < 1 or lookahead < 1: - raise ValueError("Bundle Source limits must be positive") - self._api_base_url = api_base_url.rstrip("/") - self._sync_token = sync_token - self._client = client or httpx.Client( - timeout=httpx.Timeout(30, connect=10), - follow_redirects=False, - limits=httpx.Limits( - max_connections=download_concurrency + 4, - max_keepalive_connections=download_concurrency, - ), - ) - self._owns_client = client is None - self._clock = clock - self._retention = timedelta(days=retention_days) - self._download_concurrency = download_concurrency - self._lookahead = lookahead - self._sleep = sleep - self._jitter = jitter - self._refresh_lock = threading.Lock() - self._performance_lock = threading.Lock() - self._listing_requests = 0 - self._listing_retries = 0 - self._download_attempts = 0 - self._download_retries = 0 - self._downloaded_bytes = 0 - self._download_wait_seconds = 0.0 - self._retry_sleep_seconds = 0.0 - self._download_latencies_ms: list[float] = [] - - def close(self) -> None: - if self._owns_client: - self._client.close() - - def __enter__(self) -> Self: - return self - - def __exit__(self, *_args: object) -> None: - self.close() - - def performance_snapshot(self, *, reset: bool = False) -> SourcePerformance: - """Return low-cardinality collection measurements for one Run.""" - with self._performance_lock: - latencies = tuple(self._download_latencies_ms) - value = SourcePerformance( - listing_requests=self._listing_requests, - listing_retries=self._listing_retries, - download_attempts=self._download_attempts, - download_retries=self._download_retries, - downloaded_bytes=self._downloaded_bytes, - download_wait_seconds=round(self._download_wait_seconds, 6), - retry_sleep_seconds=round(self._retry_sleep_seconds, 6), - download_latency_ms_p50=_percentile(latencies, 0.50), - download_latency_ms_p95=_percentile(latencies, 0.95), - ) - if reset: - self._listing_requests = 0 - self._listing_retries = 0 - self._download_attempts = 0 - self._download_retries = 0 - self._downloaded_bytes = 0 - self._download_wait_seconds = 0.0 - self._retry_sleep_seconds = 0.0 - self._download_latencies_ms.clear() - return value - - def hour_index(self, source_hour: datetime | str) -> RawHourIndex: - hour = parse_source_hour(source_hour) - start_ms = int(hour.timestamp() * 1_000) - end_ms = start_ms + 3_600_000 - cursor: tuple[int, str] | None = None - pages = 0 - by_id: dict[str, BundleRef] = {} - - while True: - params = { - "available_from_ms": str(start_ms), - "available_before_ms": str(end_ms), - "limit": str(PAGE_LIMIT), - } - if cursor is not None: - params["after_available_at_ms"] = str(cursor[0]) - params["after_bundle_id"] = cursor[1] - response = self._retry(lambda: self._listing_request(params), kind="listing") - try: - payload = response.json() - except ValueError as error: - raise SourceContractError( - "source_response_invalid", "Bundle collection response is not JSON" - ) from error - page_items, next_cursor = self._parse_page(payload, start_ms=start_ms, end_ms=end_ms) - pages += 1 - if not page_items and next_cursor is not None: - raise SourceContractError( - "source_cursor_invalid", "An empty page supplied a next cursor" - ) - previous = cursor - for item in page_items: - if previous is not None and item.cursor < previous: - raise SourceContractError( - "source_keyset_order_invalid", - "Bundle keyset order is not increasing", - ) - previous = item.cursor - existing = by_id.get(item.bundle_id) - if existing is not None: - if _stable_ref(existing) != _stable_ref(item): - raise SourceContractError( - "source_identity_conflict", - "A Bundle ID was listed with conflicting immutable metadata", - ) - by_id[item.bundle_id] = item - continue - by_id[item.bundle_id] = item - if next_cursor is None: - break - if not page_items or next_cursor != page_items[-1].cursor: - raise SourceContractError( - "source_cursor_invalid", "The next cursor is not the final page item" - ) - if cursor is not None and next_cursor <= cursor: - raise SourceContractError( - "source_cursor_invalid", "The Bundle keyset cursor did not advance" - ) - cursor = next_cursor - - items = tuple(sorted(by_id.values(), key=lambda item: item.cursor)) - if not items and self._is_past_retention(hour): - raise HourExpired("source_hour_expired", "An empty Source Hour is past retention") - return RawHourIndex( - source_hour=hour, - items=items, - raw_commit_sha256=raw_commit_sha256(items), - pages=pages, - ) - - def _listing_request(self, params: Mapping[str, str]) -> httpx.Response: - with self._performance_lock: - self._listing_requests += 1 - try: - response = self._client.get( - f"{self._api_base_url}/bundles", - params=params, - headers={"Authorization": f"Bearer {self._sync_token}"}, - ) - except httpx.TransportError as error: - raise RetryableSourceError( - "source_transport_error", "Bundle collection transport failed" - ) from error - self._raise_response_error(response) - return response - - def _retry(self, operation: Callable[[], _T], *, kind: str) -> _T: - for attempt in range(len(RETRY_BACKOFF_SECONDS) + 1): - try: - return operation() - except RetryableSourceError as error: - if attempt == len(RETRY_BACKOFF_SECONDS): - raise - with self._performance_lock: - if kind == "listing": - self._listing_retries += 1 - else: - self._download_retries += 1 - delay = self._jitter(RETRY_BACKOFF_SECONDS[attempt]) - if error.retry_after_seconds is not None: - delay = max(delay, min(error.retry_after_seconds, MAX_RETRY_AFTER_SECONDS)) - with self._performance_lock: - self._retry_sleep_seconds += delay - self._sleep(delay) - raise AssertionError("Retry loop must return or raise") - - def stream(self, index: RawHourIndex) -> Iterator[Bundle]: - """Yield at most ``lookahead`` retained downloads, in index order.""" - executor = ThreadPoolExecutor(max_workers=self._download_concurrency) - try: - pending: dict[int, Future[Bundle]] = {} - submitted = 0 - yielded = 0 - while yielded < len(index.items): - while submitted < len(index.items) and len(pending) < self._lookahead: - pending[submitted] = executor.submit( - self._download_and_validate, index, index.items[submitted] - ) - submitted += 1 - future = pending.pop(yielded) - wait_started = time.perf_counter() - try: - bundle = future.result() - finally: - waited = time.perf_counter() - wait_started - with self._performance_lock: - self._download_wait_seconds += waited - yield bundle - yielded += 1 - except BaseException: - executor.shutdown(wait=True, cancel_futures=True) - raise - else: - executor.shutdown(wait=True) - - def _download_and_validate(self, index: RawHourIndex, item: BundleRef) -> Bundle: - active = item - try: - content = self._download(active) - except _InvalidDownload as error: - raise _bundle_admission_failure(error) from error - except DownloadUrlExpired: - with self._refresh_lock: - refreshed = self.hour_index(index.source_hour) - if refreshed.raw_commit_sha256 != index.raw_commit_sha256 or [ - _stable_ref(value) for value in refreshed.items - ] != [_stable_ref(value) for value in index.items]: - raise SourceContractError( - "source_window_changed", - "Bundle identities changed while refreshing a download URL", - ) from None - try: - active = next( - value for value in refreshed.items if value.bundle_id == item.bundle_id - ) - except StopIteration: - raise SourceContractError( - "source_window_changed", "A Bundle disappeared during URL refresh" - ) from None - try: - content = self._download(active) - except _InvalidDownload as error: - raise _bundle_admission_failure(error) from error - except DownloadUrlExpired: - raise RetryableSourceError( - "download_url_expired", "Refreshed Bundle capability expired" - ) from None - try: - return admit_bundle(item, content) - except BundleSourceError as error: - raise _bundle_admission_failure(error) from error - - def _download(self, item: BundleRef) -> bytes: - return self._retry(lambda: self._download_once(item), kind="download") - - def _download_once(self, item: BundleRef) -> bytes: - started = time.perf_counter() - with self._performance_lock: - self._download_attempts += 1 - try: - with self._client.stream("GET", item.download_url) as response: - if response.status_code >= 400: - response.read() - code, body_retryable = _response_error_details(response) - else: - code, body_retryable = None, False - if response.status_code == 410 and code == "window_expired": - raise HourExpired(code, "The Bundle Server no longer retains this hour") - if response.status_code == 403: - raise DownloadUrlExpired( - "download_url_expired", "Bundle download capability expired" - ) - if response.status_code == 401: - raise SourceContractError( - code or "bundle_download_failed", - "Bundle download authentication failed", - ) - if ( - response.status_code in {408, 429} - or response.status_code >= 500 - or body_retryable - ): - raise RetryableSourceError( - code or "bundle_download_retryable", - "Bundle download temporarily failed", - retry_after_seconds=_retry_after_seconds(response, self._clock()), - ) - if response.status_code >= 400: - raise SourceContractError( - code or "bundle_download_failed", "Bundle download was rejected" - ) - declared_length: int | None = None - if "Content-Length" in response.headers: - try: - declared_length = int(response.headers["Content-Length"]) - except ValueError: - raise _InvalidDownload( - "bundle_length_mismatch", "Bundle length header is invalid", 0 - ) from None - if declared_length < 0 or declared_length > MAX_BUNDLE_BYTES: - raise _InvalidDownload( - "bundle_too_large", - "Bundle length exceeds the byte limit", - max(declared_length, 0), - ) - chunks: list[bytes] = [] - observed = 0 - for chunk in response.iter_bytes(): - observed += len(chunk) - if observed > MAX_BUNDLE_BYTES: - raise _InvalidDownload( - "bundle_too_large", "Bundle exceeds the byte limit", observed - ) - chunks.append(chunk) - content = b"".join(chunks) - if declared_length is not None and len(content) != declared_length: - raise _InvalidDownload( - "bundle_length_mismatch", - "Bundle length differs from Content-Length", - len(content), - ) - with self._performance_lock: - self._downloaded_bytes += len(content) - return content - except httpx.TransportError as error: - raise RetryableSourceError( - "source_transport_error", "Bundle download transport failed" - ) from error - finally: - elapsed_ms = max(time.perf_counter() - started, 0.0) * 1000 - with self._performance_lock: - self._download_latencies_ms.append(elapsed_ms) - - def _is_past_retention(self, hour: datetime) -> bool: - now = self._clock() - if now.tzinfo is None or now.utcoffset() is None: - raise ValueError("Bundle Source clock must be timezone-aware") - return hour < now.astimezone(UTC) - self._retention - - def _raise_response_error(self, response: httpx.Response) -> None: - if response.status_code < 400: - return - observed_code, retryable = _response_error_details(response) - code = observed_code or "source_request_failed" - if response.status_code == 410: - raise HourExpired(code, "The Bundle Server no longer retains this hour") - if response.status_code in {401, 403}: - raise SourceContractError(code, "Bundle collection authentication failed") - if response.status_code in {408, 429} or response.status_code >= 500 or retryable: - raise RetryableSourceError( - code, - "Bundle collection temporarily failed", - retry_after_seconds=_retry_after_seconds(response, self._clock()), - ) - raise SourceContractError(code, "Bundle collection request was rejected") - - @classmethod - def _parse_page( - cls, payload: object, *, start_ms: int, end_ms: int - ) -> tuple[tuple[BundleRef, ...], tuple[int, str] | None]: - root = _mapping(payload, "response") - window = _mapping(root.get("window"), "window") - if ( - _integer(window.get("available_from_ms"), "available_from_ms") != start_ms - or _integer(window.get("available_before_ms"), "available_before_ms") != end_ms - ): - raise SourceContractError( - "source_window_mismatch", "Bundle response changed the fixed window" - ) - raw_items = root.get("items") - if not isinstance(raw_items, list): - raise SourceContractError( - "source_response_invalid", "Bundle response items must be an array" - ) - items: list[BundleRef] = [] - for raw in raw_items: - value = _mapping(raw, "item") - bundle_id = value.get("bundle_id") - download_url = value.get("download_url") - if not isinstance(bundle_id, str) or not bundle_id: - raise SourceContractError("source_response_invalid", "Bundle item ID is invalid") - if not isinstance(download_url, str) or not download_url: - raise SourceContractError( - "source_response_invalid", "Bundle download URL is invalid" - ) - available_at_ms = _integer(value.get("available_at_ms"), "available_at_ms") - if not start_ms <= available_at_ms < end_ms: - raise SourceContractError( - "source_item_outside_window", "Bundle item falls outside the Source Hour" - ) - items.append( - BundleRef( - bundle_id=bundle_id, - available_at_ms=available_at_ms, - download_url=download_url, - download_expires_at_ms=_integer( - value.get("download_expires_at_ms"), "download_expires_at_ms" - ), - ) - ) - raw_next = root.get("next_after") - next_cursor = None - if raw_next is not None: - value = _mapping(raw_next, "next_after") - bundle_id = value.get("bundle_id") - if not isinstance(bundle_id, str) or not bundle_id: - raise SourceContractError("source_response_invalid", "Bundle cursor ID is invalid") - next_cursor = ( - _integer(value.get("available_at_ms"), "available_at_ms"), - bundle_id, - ) - return tuple(items), next_cursor - - -def parse_source_hour(value: datetime | str) -> datetime: - if isinstance(value, str): - try: - value = datetime.strptime(value, "%Y-%m-%dT%H").replace(tzinfo=UTC) - except ValueError as error: - raise ValueError("Source Hour must use YYYY-MM-DDTHH") from error - if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None: - raise ValueError("Source Hour must be timezone-aware") - hour = value.astimezone(UTC) - if hour.minute or hour.second or hour.microsecond: - raise ValueError("Source Hour must align to a UTC hour") - return hour - - -def raw_commit_sha256(items: tuple[BundleRef, ...]) -> str: - return hashlib.sha256(canonical_json([_identity(item) for item in items])).hexdigest() - - -def admit_bundle(ref: BundleRef, content: bytes) -> Bundle: - """Validate one complete Bundle once and return its admitted representation.""" - if not isinstance(content, bytes): - raise TypeError("Bundle content must be bytes") - digest = hashlib.sha256(content).hexdigest() - manifest, run_content = open_bundle(content, expected_bundle_id=ref.bundle_id) - return Bundle(ref, digest, len(content), manifest, run_content) - - -def validate_bundle(content: bytes, *, expected_bundle_id: str) -> Mapping[str, Any]: - """Validate a Bundle V6 envelope and every declared segment digest.""" - if len(content) > MAX_BUNDLE_BYTES: - raise SourceContractError("bundle_too_large", "Bundle exceeds its byte limit") - version = BUNDLE_VERSIONS.get(content[:8]) if len(content) >= 16 else None - if version is None: - raise SourceContractError("invalid_prefix", "Bundle magic is invalid") - if int.from_bytes(content[8:12], "big") != version: - raise SourceContractError("unsupported_bundle_version", "Bundle version is unsupported") - manifest_length = int.from_bytes(content[12:16], "big") - if not 1 <= manifest_length <= MAX_MANIFEST_BYTES: - raise SourceContractError("manifest_too_large", "Bundle manifest length is invalid") - payload_start = 16 + manifest_length - if payload_start >= len(content): - raise SourceContractError("run_missing", "Bundle Run segment is missing") - try: - manifest = json.loads(content[16:payload_start].decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as error: - raise SourceContractError("manifest_not_json", "Bundle manifest is invalid") from error - manifest = _mapping(manifest, "manifest") - if manifest.get("bundle_version") != version: - raise SourceContractError( - "unsupported_bundle_version", "Manifest Bundle version is unsupported" - ) - if manifest.get("bundle_id") != expected_bundle_id: - raise SourceContractError( - "bundle_identity_mismatch", "Listed and manifest Bundle IDs differ" - ) - _integer(manifest.get("created_at_ms"), "created_at_ms") - run = _mapping(manifest.get("run"), "run") - if run.get("run_format_version") != version: - raise SourceContractError("unsupported_run_format", "Run format is unsupported") - if not isinstance(run.get("run_id"), str) or not isinstance(run.get("player_account_id"), str): - raise SourceContractError("manifest_schema_invalid", "Run identities are invalid") - projection = _mapping(run.get("projection"), "run.projection") - _mapping(projection.get("run"), "run.projection.run") - projected_battles = projection.get("battles") - if not isinstance(projected_battles, list): - raise SourceContractError("manifest_schema_invalid", "Run Battle projection is invalid") - payload = _mapping(run.get("payload"), "run.payload") - run_offset = _integer(payload.get("offset"), "run.payload.offset") - run_length = _integer(payload.get("length"), "run.payload.length") - run_digest = payload.get("sha256") - if ( - run_offset != 0 - or not 1 <= run_length <= MAX_RUN_BYTES - or not isinstance(run_digest, str) - or _SHA256.fullmatch(run_digest) is None - ): - raise SourceContractError("run_missing", "Run segment declaration is invalid") - if payload.get("content_type") != f"application/x-bpp-run-v{version}": - raise SourceContractError("manifest_schema_invalid", "Run content type is invalid") - - screenshot_length = 0 - screenshot_digest: str | None = None - if "screenshot" in manifest: - screenshot = _mapping(manifest["screenshot"], "screenshot") - offset = _integer(screenshot.get("offset"), "screenshot.offset") - screenshot_length = _integer(screenshot.get("length"), "screenshot.length") - screenshot_digest = screenshot.get("sha256") - if offset != run_length: - reason = "segment_overlap" if offset < run_length else "segment_out_of_bounds" - raise SourceContractError(reason, "Screenshot must immediately follow the Run") - if not 1 <= screenshot_length <= MAX_SCREENSHOT_BYTES: - raise SourceContractError("screenshot_too_large", "Screenshot length is invalid") - if not isinstance(screenshot_digest, str) or _SHA256.fullmatch(screenshot_digest) is None: - raise SourceContractError("manifest_schema_invalid", "Screenshot digest is invalid") - - described_end = payload_start + run_length + screenshot_length - if described_end != len(content): - reason = ( - "undeclared_trailing_bytes" if described_end < len(content) else "segment_out_of_bounds" - ) - raise SourceContractError(reason, "Bundle segment layout is invalid") - run_bytes = content[payload_start : payload_start + run_length] - if hashlib.sha256(run_bytes).hexdigest() != run_digest: - raise SourceContractError("segment_digest_mismatch", "Run segment digest does not match") - if screenshot_digest is not None: - screenshot_bytes = content[payload_start + run_length : described_end] - if hashlib.sha256(screenshot_bytes).hexdigest() != screenshot_digest: - raise SourceContractError( - "segment_digest_mismatch", "Screenshot segment digest does not match" - ) - return manifest - - -def open_bundle(content: bytes, *, expected_bundle_id: str) -> tuple[Mapping[str, Any], bytes]: - manifest = validate_bundle(content, expected_bundle_id=expected_bundle_id) - manifest_length = int.from_bytes(content[12:16], "big") - payload_start = 16 + manifest_length - run = _mapping(manifest["run"], "run") - payload = _mapping(run["payload"], "run.payload") - length = _integer(payload["length"], "run.payload.length") - return manifest, content[payload_start : payload_start + length] - - -def _bundle_admission_failure(error: BundleSourceError) -> RetryableSourceError: - return RetryableSourceError( - "bundle_validation_failed", f"Bundle validation failed: {error.reason}" - ) - - -def _retry_after_seconds(response: httpx.Response, now: datetime) -> float | None: - value = response.headers.get("Retry-After") - if value is None: - return None - try: - seconds = float(value) - except ValueError: - try: - retry_at = parsedate_to_datetime(value) - except TypeError, ValueError, OverflowError: - return None - if retry_at.tzinfo is None or retry_at.utcoffset() is None: - return None - if now.tzinfo is None or now.utcoffset() is None: - raise ValueError("Bundle Source clock must be timezone-aware") from None - seconds = (retry_at.astimezone(UTC) - now.astimezone(UTC)).total_seconds() - if not math.isfinite(seconds) or seconds < 0: - return None - return seconds - - -def _percentile(values: tuple[float, ...], quantile: float) -> float | None: - if not values: - return None - ordered = sorted(values) - index = math.ceil(quantile * len(ordered)) - 1 - return round(ordered[max(index, 0)], 3) - - -def _stable_ref(item: BundleRef) -> tuple[object, ...]: - return item.bundle_id, item.available_at_ms - - -def _identity(item: BundleRef) -> dict[str, object]: - return {"available_at_ms": item.available_at_ms, "bundle_id": item.bundle_id} - - -def _response_error_details(response: httpx.Response) -> tuple[str | None, bool]: - try: - payload = response.json() - except ValueError: - return None, False - error = payload.get("error") if isinstance(payload, dict) else None - if not isinstance(error, dict): - return None, False - code = error.get("code") - return (code if isinstance(code, str) else None), error.get("retryable") is True - - -def _mapping(value: object, field: str) -> Mapping[str, Any]: - if not isinstance(value, dict): - raise SourceContractError("source_response_invalid", f"{field} must be an object") - return value - - -def _integer(value: object, field: str) -> int: - if not isinstance(value, int) or isinstance(value, bool) or value < 0: - raise SourceContractError( - "source_response_invalid", f"{field} must be a non-negative integer" - ) - return value diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/cli.py b/bazaarplusplus-analyzer/src/bppanalyzer/cli.py deleted file mode 100644 index da91026..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/cli.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Operator CLI for healing, two-product publication, status, and verification.""" - -import json - -import click - -from bppanalyzer.bundle_source import BundleSource -from bppanalyzer.config import ConfigurationError, load_config -from bppanalyzer.driver import PipelineDriver -from bppanalyzer.fact_store import FactStore, FactStoreError, parse_source_day -from bppanalyzer.locking import LockHeld, LockOwnershipLost -from bppanalyzer.object_store import ObjectStoreError, R2ObjectStore -from bppanalyzer.operational_evidence import read_status -from bppanalyzer.publication import ( - PRODUCTS, - ContractViolation, - PublicationError, - validate_snapshot, -) - - -@click.group() -def main() -> None: - """bpp — Analyzer pipeline.""" - - -@main.command("run") -@click.option("--heal-days", type=click.IntRange(min=1), default=8, show_default=True) -@click.option("--anchor-day", type=str) -@click.option("--no-publish", is_flag=True, help="Build local snapshots without publishing.") -@click.option("--quiet", is_flag=True, help="Suppress progress; keep the final summary.") -def run_command( - heal_days: int, - anchor_day: str | None, - no_publish: bool, - quiet: bool, -) -> None: - """Heal Source Hours, seal complete days, and update current snapshots.""" - try: - if anchor_day is not None: - parse_source_day(anchor_day) - config = load_config(require_object_store=not no_publish) - assert config.api_base_url is not None and config.sync_token is not None - with BundleSource( - api_base_url=config.api_base_url, - sync_token=config.sync_token, - retention_days=config.bundle_retention_days, - download_concurrency=config.download_concurrency, - lookahead=config.download_lookahead, - ) as source: - summary = PipelineDriver( - config.data_root, - source=source, - source_epoch=config.source_epoch, - max_run_seconds=config.max_run_seconds, - duckdb_memory_limit=config.duckdb_memory_limit, - duckdb_threads=config.duckdb_threads, - fact_retention_days=config.fact_retention_days, - object_store=None if no_publish else _object_store(config), - ).run( - heal_days=heal_days, - anchor_day=anchor_day, - publish=not no_publish, - progress_callback=None if quiet else click.echo, - error_callback=lambda message: click.echo(message, err=True), - ) - click.echo(json.dumps(summary.report, sort_keys=True, separators=(",", ":"))) - click.echo( - f"{summary.outcome}: {summary.hours_ingested} hours ingested, " - f"{summary.days_sealed} days sealed, " - f"{summary.days_abandoned} days abandoned" - ) - if summary.exit_code: - raise click.exceptions.Exit(summary.exit_code) - except LockHeld: - raise click.exceptions.Exit(3) from None - except (ConfigurationError, ValueError) as error: - raise click.UsageError(str(error)) from None - except LockOwnershipLost as error: - raise click.ClickException(str(error)) from None - except (PublicationError, ObjectStoreError) as error: - raise click.ClickException(str(error)) from None - - -@main.command("status") -@click.option("json_output", "--json", is_flag=True, help="Emit machine-readable JSON.") -def status_command(json_output: bool) -> None: - """Show the last atomic local health snapshot.""" - try: - config = load_config(require_source=False) - value = read_status(config.data_root, source_epoch=config.source_epoch) - except ConfigurationError as error: - raise click.UsageError(str(error)) from None - except Exception as error: - raise click.ClickException(str(error)) from None - if json_output: - click.echo(json.dumps(value, sort_keys=True, separators=(",", ":"))) - return - facts = value["facts"] - last = value.get("last_run") - click.echo(f"newest sealed day: {facts.get('newest_sealed_day') or '-'}") - click.echo(f"abandoned days: {len(facts.get('abandoned_days', []))}") - current = value.get("current_run") - if isinstance(current, dict): - click.echo( - f"current run: {current.get('run_id') or '-'} " - f"phase={current.get('phase') or '-'} step={current.get('step') or '-'} " - f"hour={current.get('current_hour') or '-'} " - f"hours={current.get('hours_done', 0)}/{current.get('hours_planned', 0)}" - ) - click.echo(f"last outcome: {last.get('outcome') if isinstance(last, dict) else '-'}") - - -@main.command("verify") -@click.option("--day", type=str, help="Verify one Source Day (YYYY-MM-DD).") -@click.option("--deep", is_flag=True, help="Also validate local consumer snapshots.") -def verify_command(day: str | None, deep: bool) -> None: - """Re-hash committed Parquet and optionally validate local snapshots.""" - try: - if day is not None: - parse_source_day(day) - config = load_config(require_source=False) - report = FactStore(config.data_root).verify(day, deep=deep) - snapshots = _validate_local_snapshots(config.data_root) if deep else 0 - except (ConfigurationError, ValueError) as error: - raise click.UsageError(str(error)) from None - except (FactStoreError, ContractViolation) as error: - raise click.ClickException(str(error)) from None - suffix = f" and {snapshots} consumer snapshots" if deep else "" - click.echo( - f"verified {report.hours_verified} hours and {report.files_verified} Parquet files{suffix}" - ) - - -def _validate_local_snapshots(data_root) -> int: - count = 0 - for product in PRODUCTS: - path = data_root / product.local_relpath - if not path.is_file(): - continue - value = json.loads(path.read_bytes()) - if not isinstance(value, dict): - raise ContractViolation(f"Local {product.name} snapshot root must be an object") - validate_snapshot(product.name, value) - count += 1 - return count - - -def _object_store(config): - assert config.cloudflare_account_id is not None - assert config.cloudflare_api_token is not None - assert config.r2_bucket is not None - return R2ObjectStore( - account_id=config.cloudflare_account_id, - bucket=config.r2_bucket, - api_token=config.cloudflare_api_token, - ) - - -if __name__ == "__main__": - main() diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/config.py b/bazaarplusplus-analyzer/src/bppanalyzer/config.py deleted file mode 100644 index 7dd0b3c..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/config.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Strict repository ``.env`` configuration without ambient-env fallback.""" - -import re -from dataclasses import dataclass, field -from datetime import date -from pathlib import Path - -from dotenv import dotenv_values - - -class ConfigurationError(ValueError): - """Required pipeline configuration is missing or invalid.""" - - -MIN_FACT_RETENTION_DAYS = 8 - - -@dataclass(frozen=True, slots=True) -class Config: - data_root: Path - api_base_url: str | None - sync_token: str | None = field(repr=False) - source_epoch: date | None = None - bundle_retention_days: int = 8 - fact_retention_days: int = MIN_FACT_RETENTION_DAYS - download_concurrency: int = 64 - download_lookahead: int = 128 - max_run_seconds: int = 21600 - duckdb_memory_limit: str = "8GB" - duckdb_threads: int = 8 - # One Cloudflare operator token serves every R2 bucket; the S3 pair the - # object store needs is derived from it (object_store.derive_s3_credentials). - cloudflare_account_id: str | None = None - cloudflare_api_token: str | None = field(default=None, repr=False) - r2_bucket: str | None = None - - -def repository_root() -> Path: - return Path(__file__).resolve().parents[2] - - -def load_config( - *, - require_source: bool = True, - require_object_store: bool = False, - root: Path | None = None, -) -> Config: - repo = (root or repository_root()).resolve() - env_file = repo / ".env" - if not env_file.is_file(): - raise ConfigurationError("Repository .env file is missing") - values = dotenv_values(env_file, interpolate=False) - data_root_value = values.get("BPP_DATA_ROOT") - if not isinstance(data_root_value, str) or not data_root_value.strip(): - raise ConfigurationError("BPP_DATA_ROOT is missing from repository .env") - data_root = Path(data_root_value) - if not data_root.is_absolute(): - data_root = repo / data_root - api_base_url = _optional(values.get("BPP_API_BASE_URL")) - sync_token = _optional(values.get("BPP_BUNDLE_SYNC_TOKEN")) - if require_source and (api_base_url is None or sync_token is None): - raise ConfigurationError("Bundle Server configuration is incomplete") - cloudflare_account_id = _optional(values.get("CLOUDFLARE_ACCOUNT_ID")) - cloudflare_api_token = _optional(values.get("CLOUDFLARE_API_TOKEN")) - r2_bucket = _optional(values.get("BPP_METRICS_R2_BUCKET")) - if require_object_store and not all((cloudflare_account_id, cloudflare_api_token, r2_bucket)): - raise ConfigurationError("R2 object-store configuration is incomplete") - return Config( - data_root=data_root, - api_base_url=api_base_url, - sync_token=sync_token, - source_epoch=_source_epoch(values.get("BPP_SOURCE_EPOCH")), - bundle_retention_days=_positive_int( - values.get("BPP_BUNDLE_RETENTION_DAYS"), 8, "BPP_BUNDLE_RETENTION_DAYS" - ), - fact_retention_days=_minimum_int( - values.get("BPP_FACT_RETENTION_DAYS"), - MIN_FACT_RETENTION_DAYS, - "BPP_FACT_RETENTION_DAYS", - ), - download_concurrency=_positive_int( - values.get("BPP_DOWNLOAD_CONCURRENCY"), 64, "BPP_DOWNLOAD_CONCURRENCY" - ), - download_lookahead=_positive_int( - values.get("BPP_DOWNLOAD_LOOKAHEAD"), 128, "BPP_DOWNLOAD_LOOKAHEAD" - ), - max_run_seconds=_positive_int( - values.get("BPP_MAX_RUN_SECONDS"), 21600, "BPP_MAX_RUN_SECONDS" - ), - duckdb_memory_limit=_memory_limit(values.get("BPP_DUCKDB_MEMORY_LIMIT")), - duckdb_threads=_positive_int(values.get("BPP_DUCKDB_THREADS"), 8, "BPP_DUCKDB_THREADS"), - cloudflare_account_id=cloudflare_account_id, - cloudflare_api_token=cloudflare_api_token, - r2_bucket=r2_bucket, - ) - - -def _optional(value: object) -> str | None: - return value.strip() if isinstance(value, str) and value.strip() else None - - -def _positive_int(value: object, default: int, name: str) -> int: - if value is None or value == "": - return default - try: - parsed = int(str(value)) - except ValueError as error: - raise ConfigurationError(f"{name} must be a positive integer") from error - if parsed < 1: - raise ConfigurationError(f"{name} must be a positive integer") - return parsed - - -def _minimum_int(value: object, minimum: int, name: str) -> int: - parsed = _positive_int(value, minimum, name) - if parsed < minimum: - raise ConfigurationError(f"{name} must be at least {minimum}") - return parsed - - -def _source_epoch(value: object) -> date | None: - parsed = _optional(value) - if parsed is None: - return None - try: - result = date.fromisoformat(parsed) - except ValueError as error: - raise ConfigurationError("BPP_SOURCE_EPOCH must use YYYY-MM-DD") from error - if result.isoformat() != parsed: - raise ConfigurationError("BPP_SOURCE_EPOCH must use YYYY-MM-DD") - return result - - -def _memory_limit(value: object) -> str: - if value is None or value == "": - return "8GB" - parsed = str(value).strip().upper() - if re.fullmatch(r"\d+(?:\.\d+)?(?:KB|MB|GB|TB)", parsed) is None: - raise ConfigurationError("BPP_DUCKDB_MEMORY_LIMIT must be a positive size such as 8GB") - if float(parsed[:-2]) <= 0: - raise ConfigurationError("BPP_DUCKDB_MEMORY_LIMIT must be a positive size such as 8GB") - return parsed diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/driver.py b/bazaarplusplus-analyzer/src/bppanalyzer/driver.py deleted file mode 100644 index 7dc4cfe..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/driver.py +++ /dev/null @@ -1,432 +0,0 @@ -"""Heal complete Source Days and independently publish two consumer snapshots.""" - -import json -import time -import uuid -from collections.abc import Callable -from datetime import UTC, date, datetime -from functools import partial -from pathlib import Path - -from bppanalyzer.bundle_source import ( - HourExpired, - RetryableSourceError, -) -from bppanalyzer.config import MIN_FACT_RETENTION_DAYS -from bppanalyzer.durable import atomic_replace, aware_utc -from bppanalyzer.fact_store import FactStore, parse_source_day -from bppanalyzer.hour_intake import ( - Source, - SourceHourIntake, - healing_days, - settled_missing_hours, -) -from bppanalyzer.locking import DirectoryLock, LockOwnershipLost, MaximumRunTimeExceeded -from bppanalyzer.object_store import ObjectStore -from bppanalyzer.operational_evidence import ( - CurrentRun, - OperationalEvidence, - RunEvidence, - RunSummary, -) -from bppanalyzer.publication import ( - PRODUCTS, - AnalysisWindow, - BuiltSnapshot, - ConsumerProduct, - LatestPublisher, - SnapshotBuilder, - select_analysis_window, -) - - -class PipelineDriver: - """Converge local facts, then build and replace each consumer object independently.""" - - def __init__( - self, - data_root: str | Path, - *, - source: Source, - source_epoch: date | str | None = None, - clock: Callable[[], datetime] = lambda: datetime.now(UTC), - max_run_seconds: float = 21600, - duckdb_memory_limit: str, - duckdb_threads: int, - fact_retention_days: int = MIN_FACT_RETENTION_DAYS, - object_store: ObjectStore | None = None, - ) -> None: - self.data_root = Path(data_root) - self.source = source - self.source_epoch = parse_source_day(source_epoch) if source_epoch is not None else None - self.clock = clock - self.max_run_seconds = max_run_seconds - self.duckdb_memory_limit = duckdb_memory_limit - self.duckdb_threads = duckdb_threads - self.fact_retention_days = fact_retention_days - self.object_store = object_store - - def run( - self, - *, - heal_days: int, - anchor_day: date | str | None = None, - publish: bool = True, - progress_callback: Callable[[str], None] | None = None, - error_callback: Callable[[str], None] | None = None, - ) -> RunSummary: - parsed_anchor = parse_source_day(anchor_day) if anchor_day is not None else None - now = aware_utc(self.clock()) - run_id = uuid.uuid4().hex - lock = DirectoryLock(self.data_root, run_id, max_run_seconds=self.max_run_seconds) - with lock: - started_monotonic = time.monotonic() - progress = RunEvidence(run_id, now, started_monotonic) - _reset_source_performance(self.source) - store = FactStore(self.data_root, clock=self.clock, ownership_check=lock.assert_owned) - evidence = OperationalEvidence( - self.data_root, - run_id, - clock=self.clock, - ownership_check=lock.assert_owned, - ) - evidence.log("run started") - if lock.stale_run_id is not None: - evidence.log(f"stale lock taken over: {lock.stale_run_id}") - - def report(message: str) -> None: - evidence.log(message) - if progress_callback is not None: - progress_callback(message) - - def report_error(message: str) -> None: - evidence.log(message) - if error_callback is not None: - error_callback(message) - - def checkpoint( - phase: str, - current_hour: str | None, - *, - step: str, - bundles_done: int | None = None, - bundles_total: int | None = None, - ) -> None: - try: - evidence.checkpoint( - store, - CurrentRun( - phase=phase, - step=step, - current_hour=current_hour, - hours_done=progress.hours_ingested, - hours_planned=progress.hours_planned, - bundles_done=bundles_done, - bundles_total=bundles_total, - started_at=now, - updated_at=aware_utc(self.clock()), - ), - considered_days=healing_days( - now, heal_days, source_epoch=self.source_epoch - ), - source_epoch=self.source_epoch, - ) - except LockOwnershipLost: - raise - except BaseException as error: - evidence.try_log(f"live status refresh failed: {_error_reason(error)}") - - pending_error: BaseException | None = None - pending_traceback = None - - def record_completion(log: Callable[[str], None]) -> None: - source_snapshot = getattr(self.source, "performance_snapshot", None) - progress.prepare_completion( - finished_monotonic=time.monotonic(), - source_performance=source_snapshot() if callable(source_snapshot) else None, - ) - log( - "performance report: " - + json.dumps( - { - "downloads": progress.report.value["downloads"], - "timings": progress.timings, - }, - sort_keys=True, - separators=(",", ":"), - ) - ) - log( - "run report: " - + json.dumps(progress.report.value, sort_keys=True, separators=(",", ":")) - ) - - try: - self._heal( - store, - lock, - now=now, - heal_days=heal_days, - progress=progress, - log=evidence.log, - report=report, - report_error=report_error, - checkpoint=checkpoint, - ) - progress.build_started_monotonic = time.monotonic() - window = select_analysis_window( - store.seals(), parsed_anchor, source_epoch=self.source_epoch - ) - self._publish_products( - store, - window, - publish=publish, - progress=progress, - lock=lock, - report=report, - report_error=report_error, - checkpoint=checkpoint, - ) - if progress.report.all_published(): - pruned = store.prune(retain_days=self.fact_retention_days) - progress.report.record_retention(pruned) - report( - "fact retention done: " - f"source_days={len(pruned.source_days)} " - f"hours={pruned.hours_pruned} files={pruned.files_pruned} " - f"bytes={pruned.bytes_pruned}" - ) - record_completion(evidence.log) - evidence.log(f"run finished: {progress.outcome}") - except BaseException as error: - if isinstance(error, LockOwnershipLost) and not isinstance( - error, MaximumRunTimeExceeded - ): - raise - pending_error = error - pending_traceback = error.__traceback__ - record_completion(evidence.try_log) - evidence.try_log(f"run failed: {_error_reason(error)}") - - summary = progress.summarize( - finished_at=aware_utc(self.clock()), - fatal_reason=_error_reason(pending_error) if pending_error is not None else None, - ) - - ownership_check = ( - lock.assert_current_owner - if isinstance(pending_error, MaximumRunTimeExceeded) - else lock.assert_owned - ) - try: - ownership_check() - evidence.finish( - store, - summary, - now=aware_utc(self.clock()), - considered_days=healing_days(now, heal_days, source_epoch=self.source_epoch), - source_epoch=self.source_epoch, - ownership_check=ownership_check, - ) - except LockOwnershipLost: - if pending_error is not None: - # Surface the original run failure, chained to the lost lock. - raise pending_error.with_traceback(pending_traceback) # noqa: B904 - raise - if pending_error is not None: - raise pending_error.with_traceback(pending_traceback) - return summary - - def _publish_products( - self, - store: FactStore, - window: AnalysisWindow | None, - *, - publish: bool, - progress: RunEvidence, - lock: DirectoryLock, - report: Callable[[str], None], - report_error: Callable[[str], None], - checkpoint: Callable[..., None], - ) -> None: - result = progress.report - result.select_window(window) - if window is None: - report("publication skipped: no Complete Source Day available for Analysis Window") - return - builder = SnapshotBuilder( - self.data_root, - store=store, - clock=self.clock, - memory_limit=self.duckdb_memory_limit, - threads=self.duckdb_threads, - ) - fact_stats_started = time.monotonic() - try: - facts = builder.fact_stats(window) - except Exception as error: - report_error(f"fact report failed: {_error_reason(error)}") - else: - result.record_facts(facts) - finally: - progress.product_timings["fact_stats_seconds"] = round( - max(time.monotonic() - fact_stats_started, 0.0), 6 - ) - publisher = LatestPublisher(self.object_store) if self.object_store is not None else None - for consumer in PRODUCTS: - product = consumer.name - product_started: float | None = None - try: - checkpoint("build", None, step=product) - report(f"{product} snapshot build started") - product_started = time.monotonic() - built = consumer.build(builder, window) - progress.product_timings[f"{product}_build_seconds"] = round( - max(time.monotonic() - product_started, 0.0), 6 - ) - lock.assert_owned() - save_started = time.monotonic() - _write_local_snapshot(self.data_root, consumer, built, lock.assert_owned) - progress.product_timings[f"{product}_local_save_seconds"] = round( - max(time.monotonic() - save_started, 0.0), 6 - ) - result.record_product(consumer, built.stats) - report(f"{product} snapshot build done") - if publish and publisher is not None: - checkpoint("publish", None, step=product) - publish_started = time.monotonic() - replaced = publisher.replace(built) - progress.product_timings[f"{product}_publish_seconds"] = round( - max(time.monotonic() - publish_started, 0.0), 6 - ) - result.mark_published(consumer) - report(f"{product} snapshot publication done: replaced={str(replaced).lower()}") - elif not publish: - report(f"{product} snapshot publication skipped: --no-publish") - else: - report(f"{product} snapshot publication skipped: no object store") - except Exception as error: - if product_started is not None: - progress.product_timings.setdefault( - f"{product}_build_seconds", - round(max(time.monotonic() - product_started, 0.0), 6), - ) - failure = {"scope": product, "reason": _error_reason(error)} - progress.failures.append(failure) - report_error(f"{product} snapshot failed: {failure['reason']}") - - def _heal( - self, - store: FactStore, - lock: DirectoryLock, - *, - now: datetime, - heal_days: int, - progress: RunEvidence, - log: Callable[[str], None], - report: Callable[[str], None], - report_error: Callable[[str], None], - checkpoint: Callable[..., None], - ) -> None: - heal_started = time.monotonic() - progress.heal_started_monotonic = heal_started - intake = SourceHourIntake(self.source, store) - observe_intake = partial(progress.observe_intake, report=report, checkpoint=checkpoint) - days = healing_days(now, heal_days, source_epoch=self.source_epoch) - planned_by_day: dict[date, tuple[datetime, ...]] = {} - for day in days: - if store.has_seal(day) or store.is_abandoned(day): - continue - planned_by_day[day] = settled_missing_hours(day, now, store.missing_hours(day)) - progress.hours_planned = sum(len(hours) for hours in planned_by_day.values()) - report(f"heal plan: days={len(days)} missing_settled_hours={progress.hours_planned}") - hours_started = 0 - for day, planned_hours in planned_by_day.items(): - lock.assert_owned() - day_started = time.monotonic() - expired_reason: str | None = None - for hour in planned_hours: - lock.assert_owned() - hours_started += 1 - hour_key = hour.strftime("%Y-%m-%dT%H") - report( - f"hour started: source_hour={hour_key} " - f"[{hours_started}/{progress.hours_planned}]" - ) - result = intake.commit(hour, on_progress=observe_intake) - if isinstance(error := result.error, HourExpired): - expired_reason = error.reason - report_error(f"source hour expired: {hour_key} ({error.reason})") - break - if isinstance(error, RetryableSourceError): - progress.failures.append( - { - "scope": "source_hour", - "source_hour": hour_key, - "reason": error.reason, - } - ) - report_error(f"source hour failed: {hour_key} ({error.reason})") - if expired_reason is not None: - remaining = store.missing_hours(day) - store.abandon_day(day, remaining, expired_reason) - log(f"source day abandoned: {day.isoformat()} ({expired_reason})") - progress.days_abandoned += 1 - progress.changed = True - checkpoint("heal", hour.strftime("%Y-%m-%dT%H"), step="abandoned") - report( - f"abandoned {day.isoformat()} missing={len(remaining)} " - f"reason={expired_reason} " - f"elapsed={_format_elapsed(time.monotonic() - day_started)}" - ) - continue - try: - if not store.missing_hours(day): - seal = store.seal_day(day) - progress.days_sealed += 1 - progress.changed = True - checkpoint("heal", f"{day.isoformat()}T23", step="seal") - report( - f"sealed {day.isoformat()} rows={sum(seal.row_counts.values())} " - f"elapsed={_format_elapsed(time.monotonic() - day_started)}" - ) - except Exception as error: - progress.failures.append( - { - "scope": "source_day", - "source_day": day.isoformat(), - "reason": _error_reason(error), - } - ) - report_error(f"source day failed: {day.isoformat()} ({_error_reason(error)})") - progress.heal_seconds = time.monotonic() - heal_started - - -def _reset_source_performance(source: Source) -> None: - snapshot = getattr(source, "performance_snapshot", None) - if callable(snapshot): - snapshot(reset=True) - - -def _write_local_snapshot( - root: Path, - product: ConsumerProduct, - snapshot: BuiltSnapshot, - ownership_check: Callable[[], None], -) -> None: - atomic_replace( - root / product.local_relpath, - snapshot.content, - ownership_check=ownership_check, - ) - - -def _error_reason(error: BaseException) -> str: - reason = getattr(error, "reason", None) - if isinstance(reason, str) and reason: - return reason - return str(error) or type(error).__name__ - - -def _format_elapsed(value: float) -> str: - return f"{max(round(value), 0)}s" diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/durable.py b/bazaarplusplus-analyzer/src/bppanalyzer/durable.py deleted file mode 100644 index 4073fc9..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/durable.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Shared encodings and atomic writes for durable local state.""" - -import json -import os -import tempfile -from collections.abc import Callable -from datetime import UTC, datetime -from pathlib import Path - - -def canonical_json(value: object) -> bytes: - return ( - json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n" - ).encode("utf-8") - - -def fsync_directory(path: Path) -> None: - descriptor = os.open(path, os.O_RDONLY) - try: - os.fsync(descriptor) - finally: - os.close(descriptor) - - -def atomic_replace( - path: Path, - content: bytes, - *, - ownership_check: Callable[[], None] | None = None, -) -> None: - """Durably replace ``path``, checking ownership before writing and before promotion.""" - check = ownership_check or (lambda: None) - check() - path.parent.mkdir(parents=True, exist_ok=True) - descriptor, name = tempfile.mkstemp(prefix=f".{path.name}.tmp-", dir=path.parent) - temporary = Path(name) - try: - with os.fdopen(descriptor, "wb") as stream: - descriptor = -1 - stream.write(content) - stream.flush() - os.fsync(stream.fileno()) - check() - os.replace(temporary, path) - fsync_directory(path.parent) - finally: - if descriptor >= 0: - os.close(descriptor) - temporary.unlink(missing_ok=True) - - -def aware_utc(value: datetime) -> datetime: - if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None: - raise ValueError("Pipeline clock must be timezone-aware") - return value.astimezone(UTC) - - -def utc_timestamp(value: datetime) -> str: - return aware_utc(value).isoformat(timespec="seconds").replace("+00:00", "Z") diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/fact_store.py b/bazaarplusplus-analyzer/src/bppanalyzer/fact_store.py deleted file mode 100644 index 6e6de20..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/fact_store.py +++ /dev/null @@ -1,706 +0,0 @@ -"""Atomic, immutable storage for hourly Parquet facts and Source Day seals.""" - -import hashlib -import json -import os -import re -import shutil -import tempfile -import time -import uuid -from collections.abc import Callable, Iterable, Mapping -from contextlib import ExitStack, suppress -from dataclasses import dataclass, replace -from datetime import UTC, date, datetime, timedelta -from pathlib import Path - -import pyarrow as pa -import pyarrow.compute as pc -import pyarrow.parquet as pq - -from bppanalyzer.bundle_source import parse_source_hour -from bppanalyzer.durable import canonical_json, fsync_directory -from bppanalyzer.projection import HourProjection, table_schemas - -TABLES = ("runs", "battles", "battle_cards", "quality", "quarantine") -_SHA256 = re.compile(r"^[0-9a-f]{64}$") -_HOUR_DIR = re.compile(r"^source_hour=(\d{4}-\d{2}-\d{2}T\d{2})$") -_SEAL_FILE = re.compile(r"^source_day=(\d{4}-\d{2}-\d{2})\.json$") -_ABANDON_FILE = re.compile(r"^source_day=(\d{4}-\d{2}-\d{2})\.abandoned\.json$") - - -class FactStoreError(RuntimeError): - """Base failure for immutable fact state.""" - - -class FactMissing(FactStoreError): - """Required committed fact state is absent.""" - - -class FactCorrupt(FactStoreError): - """Committed fact state fails its integrity contract.""" - - -class FactConflict(FactStoreError): - """An immutable identity already has different canonical bytes.""" - - -@dataclass(frozen=True, slots=True) -class HourCommit: - source_hour: str - source_day: str - raw_commit_sha256: str - fact_commit_sha256: str - projection_code_version: str - bundle_count: int - row_counts: Mapping[str, int] - file_sha256s: Mapping[str, str] - file_bytes: Mapping[str, int] - reused: bool - batch_generation_seconds: float = 0.0 - parquet_write_seconds: float = 0.0 - fact_finalize_seconds: float = 0.0 - - -@dataclass(frozen=True, slots=True) -class DaySeal: - source_day: str - hourly_fact_commits: tuple[Mapping[str, str], ...] - row_counts: Mapping[str, int] - day_seal_sha256: str - reused: bool = False - - -@dataclass(frozen=True, slots=True) -class AbandonedDay: - source_day: str - missing_hours: tuple[str, ...] - reason: str - abandoned_at: str - reused: bool = False - - -@dataclass(frozen=True, slots=True) -class VerifyReport: - days: tuple[str, ...] - hours_verified: int - files_verified: int - deep: bool - - -@dataclass(frozen=True, slots=True) -class FactPruneReport: - source_days: tuple[str, ...] - hours_pruned: int - files_pruned: int - bytes_pruned: int - - -class FactStore: - """The only owner of paths beneath ``facts/``.""" - - def __init__( - self, - root: str | Path, - *, - clock: Callable[[], datetime] = lambda: datetime.now(UTC), - ownership_check: Callable[[], None] = lambda: None, - ) -> None: - self.root = Path(root) - self._hourly = self.root / "facts" / "hourly" - self._sealed = self.root / "facts" / "sealed" - self._clock = clock - self._ownership_check = ownership_check - - def commit_hour(self, projected: HourProjection) -> HourCommit: - commit_started = time.perf_counter() - self._ownership_check() - hour = parse_source_hour(projected.source_hour) - hour_key = hour.strftime("%Y-%m-%dT%H") - day_key = hour.strftime("%Y-%m-%d") - schemas = table_schemas() - - self._hourly.mkdir(parents=True, exist_ok=True) - final = self._hourly / f"source_hour={hour_key}" - for stale in self._hourly.glob(f".{final.name}.tmp-*"): - if stale.is_dir(): - shutil.rmtree(stale, ignore_errors=True) - stage = Path(tempfile.mkdtemp(prefix=f".{final.name}.tmp-", dir=self._hourly)) - try: - file_hashes: dict[str, str] = {} - file_bytes: dict[str, int] = {} - row_counts = {name: 0 for name in TABLES} - generation_seconds = 0.0 - parquet_seconds = 0.0 - with ExitStack() as writer_stack: - writers = { - name: writer_stack.enter_context( - pq.ParquetWriter( - stage / f"{name}.parquet", - schemas[name], - compression="zstd", - version="2.6", - data_page_version="2.0", - use_dictionary=True, - write_statistics=True, - ) - ) - for name in TABLES - } - batches = projected.iter_batches() - while True: - generation_started = time.perf_counter() - try: - name, batch = next(batches) - except StopIteration: - break - generation_seconds += time.perf_counter() - generation_started - self._ownership_check() - if name not in writers: - raise FactCorrupt(f"Hourly projection emitted unknown table {name}") - if batch.schema != schemas[name]: - raise FactCorrupt(f"Hourly {name} schema differs from the owned schema") - self._require_partition_columns(batch, name, hour_key, day_key) - write_started = time.perf_counter() - writers[name].write_batch(batch, row_group_size=batch.num_rows) - parquet_seconds += time.perf_counter() - write_started - row_counts[name] += batch.num_rows - - for name in TABLES: - path = stage / f"{name}.parquet" - fsync_directory(path) - file_hashes[path.name] = _sha256_file(path) - file_bytes[path.name] = path.stat().st_size - - body = { - "schema_version": 1, - "source_hour": hour_key, - "source_day": day_key, - "raw_commit_sha256": projected.raw_commit_sha256, - "projection_code_version": projected.projection_version, - "bundle_count": projected.bundle_count, - "row_counts": dict(sorted(row_counts.items())), - "file_sha256s": dict(sorted(file_hashes.items())), - "file_bytes": dict(sorted(file_bytes.items())), - } - commit_bytes = canonical_json(body) - _durable_create(stage / "_commit.json", commit_bytes) - fsync_directory(stage) - self._ownership_check() - - if final.exists(): - existing_path = final / "_commit.json" - try: - existing = existing_path.read_bytes() - except OSError as error: - raise FactConflict( - f"Existing Hourly Fact Partition is incomplete: {hour_key}" - ) from error - if existing != commit_bytes: - raise FactConflict(f"Hourly Fact Partition commit conflict: {hour_key}") - committed = self._read_hour(hour, deep=True) - return replace( - committed, - reused=True, - batch_generation_seconds=round(generation_seconds, 6), - parquet_write_seconds=round(parquet_seconds, 6), - fact_finalize_seconds=round( - max( - time.perf_counter() - - commit_started - - generation_seconds - - parquet_seconds, - 0.0, - ), - 6, - ), - ) - - os.rename(stage, final) - fsync_directory(self._hourly) - return replace( - self._read_hour(hour, deep=True), - reused=False, - batch_generation_seconds=round(generation_seconds, 6), - parquet_write_seconds=round(parquet_seconds, 6), - fact_finalize_seconds=round( - max( - time.perf_counter() - commit_started - generation_seconds - parquet_seconds, - 0.0, - ), - 6, - ), - ) - finally: - if stage.exists(): - shutil.rmtree(stage, ignore_errors=True) - - def seal_day(self, source_day: date | str) -> DaySeal: - day = parse_source_day(source_day) - day_key = day.isoformat() - if self.is_abandoned(day): - raise FactConflict(f"Abandoned Source Day cannot be sealed: {day_key}") - commits = [] - for hour_number in range(24): - hour = datetime.combine(day, datetime.min.time(), UTC) + timedelta(hours=hour_number) - commits.append(self._read_hour(hour, deep=False)) - if [commit.source_hour[-2:] for commit in commits] != [f"{hour:02d}" for hour in range(24)]: - raise FactCorrupt(f"Source Day does not contain hours 00-23: {day_key}") - - row_counts = {name: sum(commit.row_counts[name] for commit in commits) for name in TABLES} - body = { - "schema_version": 1, - "source_day": day_key, - "hourly_fact_commits": [ - { - "source_hour": commit.source_hour, - "fact_commit_sha256": commit.fact_commit_sha256, - } - for commit in commits - ], - "row_counts": dict(sorted(row_counts.items())), - } - seal_hash = hashlib.sha256(canonical_json(body)).hexdigest() - sealed_body = {**body, "day_seal_sha256": seal_hash} - content = canonical_json(sealed_body) - self._ownership_check() - self._sealed.mkdir(parents=True, exist_ok=True) - destination = self._seal_path(day) - self._ownership_check() - reused = _atomic_immutable_file(destination, content) - return DaySeal( - source_day=day_key, - hourly_fact_commits=tuple(body["hourly_fact_commits"]), - row_counts=row_counts, - day_seal_sha256=seal_hash, - reused=reused, - ) - - def abandon_day( - self, - source_day: date | str, - missing_hours: Iterable[datetime | str], - reason: str, - ) -> AbandonedDay: - day = parse_source_day(source_day) - day_key = day.isoformat() - if not reason: - raise ValueError("Abandonment reason is required") - if self.has_seal(day): - raise FactConflict(f"Sealed Source Day cannot be abandoned: {day_key}") - path = self._abandon_path(day) - if path.is_file(): - return replace(self._read_abandoned(path), reused=True) - hours = tuple( - sorted({parse_source_hour(value).strftime("%Y-%m-%dT%H") for value in missing_hours}) - ) - if not hours or any(not value.startswith(f"{day_key}T") for value in hours): - raise ValueError("Abandonment must name missing hours from its Source Day") - now = self._clock() - if now.tzinfo is None or now.utcoffset() is None: - raise ValueError("Fact Store clock must be timezone-aware") - body = { - "schema_version": 1, - "source_day": day_key, - "missing_hours": list(hours), - "reason": reason, - "abandoned_at": now.astimezone(UTC).isoformat().replace("+00:00", "Z"), - } - self._ownership_check() - self._sealed.mkdir(parents=True, exist_ok=True) - reused = _atomic_immutable_file(path, canonical_json(body)) - if reused: - return replace(self._read_abandoned(path), reused=True) - return AbandonedDay(day_key, hours, reason, body["abandoned_at"]) - - def is_abandoned(self, source_day: date | str) -> bool: - return self._abandon_path(parse_source_day(source_day)).is_file() - - def abandoned_days(self) -> tuple[AbandonedDay, ...]: - if not self._sealed.is_dir(): - return () - values: list[AbandonedDay] = [] - for path in sorted(self._sealed.iterdir()): - if _ABANDON_FILE.fullmatch(path.name): - values.append(self._read_abandoned(path)) - return tuple(values) - - def seals(self) -> tuple[DaySeal, ...]: - if not self._sealed.is_dir(): - return () - values: list[DaySeal] = [] - for path in sorted(self._sealed.iterdir()): - match = _SEAL_FILE.fullmatch(path.name) - if match is None: - continue - values.append(self._read_seal(path, verify_hours=False)) - return tuple(values) - - def has_seal(self, source_day: date | str) -> bool: - path = self._seal_path(parse_source_day(source_day)) - if not path.is_file(): - return False - self._read_seal(path, verify_hours=False) - return True - - def has_hour(self, source_hour: datetime | str) -> bool: - hour = parse_source_hour(source_hour) - path = self._hour_path(hour) - if not path.exists(): - return False - self._read_hour(hour, deep=False) - return True - - def missing_hours(self, source_day: date | str) -> tuple[datetime, ...]: - day = parse_source_day(source_day) - missing: list[datetime] = [] - for hour_number in range(24): - hour = datetime.combine(day, datetime.min.time(), UTC) + timedelta(hours=hour_number) - if not self.has_hour(hour): - missing.append(hour) - return tuple(missing) - - def hour_paths(self, days: Iterable[date | str]) -> Mapping[str, tuple[Path, ...]]: - paths = {name: [] for name in TABLES} - for raw_day in days: - day = parse_source_day(raw_day) - seal = self._read_seal(self._seal_path(day), verify_hours=True) - for hourly in seal.hourly_fact_commits: - hour_path = self._hourly / f"source_hour={hourly['source_hour']}" - for name in TABLES: - paths[name].append(hour_path / f"{name}.parquet") - return {name: tuple(values) for name, values in paths.items()} - - def verify(self, source_day: date | str | None = None, *, deep: bool = False) -> VerifyReport: - days = ( - (parse_source_day(source_day),) - if source_day is not None - else tuple(date.fromisoformat(seal.source_day) for seal in self.seals()) - ) - hours = 0 - files = 0 - for day in days: - seal = self._read_seal(self._seal_path(day), verify_hours=False) - for value in seal.hourly_fact_commits: - hour = parse_source_hour(value["source_hour"]) - commit = self._read_hour(hour, deep=True) - if commit.fact_commit_sha256 != value["fact_commit_sha256"]: - raise FactCorrupt( - f"Day Seal references another Hourly commit: {commit.source_hour}" - ) - hours += 1 - files += len(commit.file_sha256s) - return VerifyReport(tuple(day.isoformat() for day in days), hours, files, deep) - - def committed_hours(self) -> tuple[str, ...]: - if not self._hourly.is_dir(): - return () - result: list[str] = [] - for path in sorted(self._hourly.iterdir()): - match = _HOUR_DIR.fullmatch(path.name) - if match is None or not path.is_dir(): - continue - self._read_hour(parse_source_hour(match.group(1)), deep=False) - result.append(match.group(1)) - return tuple(result) - - def prune(self, *, retain_days: int) -> FactPruneReport: - """Remove facts older than the latest retained Complete Source Days.""" - if not isinstance(retain_days, int) or isinstance(retain_days, bool) or retain_days < 1: - raise ValueError("retain_days must be a positive integer") - seals = self.seals() - if len(seals) < retain_days: - return FactPruneReport((), 0, 0, 0) - - cutoff = parse_source_day(seals[-retain_days].source_day) - pruned_days: set[str] = set() - files_pruned = 0 - bytes_pruned = 0 - - for seal in seals[:-retain_days]: - path = self._seal_path(parse_source_day(seal.source_day)) - self._ownership_check() - with suppress(OSError): - bytes_pruned += path.stat().st_size - path.unlink() - files_pruned += 1 - pruned_days.add(seal.source_day) - if seals[:-retain_days]: - fsync_directory(self._sealed) - - hours_pruned = 0 - if self._hourly.is_dir(): - for path in sorted(self._hourly.iterdir()): - match = _HOUR_DIR.fullmatch(path.name) - if match is None or not path.is_dir(): - continue - source_hour = parse_source_hour(match.group(1)) - if source_hour.date() >= cutoff: - continue - self._ownership_check() - for item in path.iterdir(): - if not item.is_file(): - continue - with suppress(OSError): - bytes_pruned += item.stat().st_size - files_pruned += 1 - shutil.rmtree(path) - hours_pruned += 1 - pruned_days.add(source_hour.date().isoformat()) - if hours_pruned: - fsync_directory(self._hourly) - - return FactPruneReport(tuple(sorted(pruned_days)), hours_pruned, files_pruned, bytes_pruned) - - def _read_hour(self, source_hour: datetime | str, *, deep: bool) -> HourCommit: - hour = parse_source_hour(source_hour) - hour_key = hour.strftime("%Y-%m-%dT%H") - day_key = hour.strftime("%Y-%m-%d") - path = self._hour_path(hour) - commit_path = path / "_commit.json" - if not commit_path.is_file(): - raise FactMissing(f"Hourly Fact Partition is missing: {hour_key}") - try: - commit_bytes = commit_path.read_bytes() - value = json.loads(commit_bytes) - except (OSError, json.JSONDecodeError, UnicodeDecodeError) as error: - raise FactCorrupt(f"Hourly commit is unreadable: {hour_key}") from error - if ( - not isinstance(value, dict) - or value.get("source_hour") != hour_key - or value.get("source_day") != day_key - ): - raise FactCorrupt(f"Hourly commit identity differs: {hour_key}") - if canonical_json(value) != commit_bytes: - raise FactCorrupt(f"Hourly commit is not canonical: {hour_key}") - expected_files = {f"{name}.parquet" for name in TABLES} - try: - actual_files = {item.name for item in path.iterdir()} - except OSError as error: - raise FactMissing(f"Hourly Fact Partition is missing: {hour_key}") from error - if actual_files != expected_files | {"_commit.json"}: - raise FactCorrupt(f"Hourly Fact Partition file set differs: {hour_key}") - file_hashes = _digest_map(value.get("file_sha256s"), expected_files, "hash") - file_bytes = _integer_map(value.get("file_bytes"), expected_files, "size") - row_counts = _integer_map(value.get("row_counts"), set(TABLES), "row count") - for filename in expected_files: - try: - actual_size = (path / filename).stat().st_size - except OSError as error: - raise FactCorrupt(f"Hourly Parquet is missing: {hour_key}/{filename}") from error - if actual_size != file_bytes[filename]: - raise FactCorrupt(f"Hourly Parquet size differs: {hour_key}/{filename}") - if deep and _sha256_file(path / filename) != file_hashes[filename]: - raise FactCorrupt(f"Hourly Parquet checksum differs: {hour_key}/{filename}") - raw_hash = value.get("raw_commit_sha256") - version = value.get("projection_code_version") - bundle_count = value.get("bundle_count") - if not isinstance(raw_hash, str) or _SHA256.fullmatch(raw_hash) is None: - raise FactCorrupt(f"Hourly raw identity is invalid: {hour_key}") - if not isinstance(version, str) or not version: - raise FactCorrupt(f"Hourly projection version is invalid: {hour_key}") - if not isinstance(bundle_count, int) or isinstance(bundle_count, bool) or bundle_count < 0: - raise FactCorrupt(f"Hourly Bundle count is invalid: {hour_key}") - return HourCommit( - source_hour=hour_key, - source_day=day_key, - raw_commit_sha256=raw_hash, - fact_commit_sha256=hashlib.sha256(commit_bytes).hexdigest(), - projection_code_version=version, - bundle_count=bundle_count, - row_counts=row_counts, - file_sha256s=file_hashes, - file_bytes=file_bytes, - reused=True, - ) - - def _read_seal(self, path: Path, *, verify_hours: bool) -> DaySeal: - if not path.is_file(): - raise FactMissing(f"Source Day Seal is missing: {path.name}") - try: - content = path.read_bytes() - value = json.loads(content) - except (OSError, json.JSONDecodeError, UnicodeDecodeError) as error: - raise FactCorrupt(f"Source Day Seal is unreadable: {path.name}") from error - if not isinstance(value, dict) or canonical_json(value) != content: - raise FactCorrupt(f"Source Day Seal is not canonical: {path.name}") - day = value.get("source_day") - try: - expected_path = self._seal_path(parse_source_day(day)) if isinstance(day, str) else None - except TypeError, ValueError: - expected_path = None - if path != expected_path: - raise FactCorrupt(f"Source Day Seal identity differs: {path.name}") - hourly = value.get("hourly_fact_commits") - expected_hours = [f"{day}T{number:02d}" for number in range(24)] - observed_hours = ( - [item.get("source_hour") if isinstance(item, dict) else None for item in hourly] - if isinstance(hourly, list) - else None - ) - if observed_hours != expected_hours: - raise FactCorrupt(f"Source Day Seal must contain hours 00-23: {day}") - for item in hourly: - digest = item.get("fact_commit_sha256") - if not isinstance(digest, str) or _SHA256.fullmatch(digest) is None: - raise FactCorrupt(f"Source Day Seal has an invalid Hourly digest: {day}") - row_counts = _integer_map(value.get("row_counts"), set(TABLES), "row count") - declared = value.get("day_seal_sha256") - body = {key: item for key, item in value.items() if key != "day_seal_sha256"} - actual = hashlib.sha256(canonical_json(body)).hexdigest() - if declared != actual: - raise FactCorrupt(f"Source Day Seal digest differs: {day}") - if verify_hours: - for item in hourly: - commit = self._read_hour(item["source_hour"], deep=False) - if commit.fact_commit_sha256 != item["fact_commit_sha256"]: - raise FactCorrupt( - f"Source Day Seal references another Hourly commit: {commit.source_hour}" - ) - return DaySeal(day, tuple(hourly), row_counts, actual, reused=True) - - def _read_abandoned(self, path: Path) -> AbandonedDay: - try: - content = path.read_bytes() - value = json.loads(content) - except (OSError, json.JSONDecodeError, UnicodeDecodeError) as error: - raise FactCorrupt(f"Abandonment record is unreadable: {path.name}") from error - if not isinstance(value, dict) or canonical_json(value) != content: - raise FactCorrupt(f"Abandonment record is not canonical: {path.name}") - day = value.get("source_day") - missing = value.get("missing_hours") - reason = value.get("reason") - abandoned_at = value.get("abandoned_at") - try: - expected_path = ( - self._abandon_path(parse_source_day(day)) if isinstance(day, str) else None - ) - except TypeError, ValueError: - expected_path = None - if ( - path != expected_path - or not isinstance(missing, list) - or not missing - or missing != sorted(set(missing)) - or any(not isinstance(item, str) or not item.startswith(f"{day}T") for item in missing) - or not isinstance(reason, str) - or not reason - or not isinstance(abandoned_at, str) - ): - raise FactCorrupt(f"Abandonment record fields are invalid: {path.name}") - return AbandonedDay(day, tuple(missing), reason, abandoned_at, reused=True) - - @staticmethod - def _require_partition_columns( - batch: pa.RecordBatch, table_name: str, hour_key: str, day_key: str - ) -> None: - if batch.num_rows == 0: - return - source_hour = batch.column("source_hour") - if ( - source_hour.null_count or pc.all(pc.equal(source_hour, hour_key)).as_py() is not True # ty: ignore[unresolved-attribute] - ): - raise FactCorrupt(f"{table_name} rows moved outside their Source Hour") - source_day = batch.column("source_day") - if ( - source_day.null_count or pc.all(pc.equal(source_day, day_key)).as_py() is not True # ty: ignore[unresolved-attribute] - ): - raise FactCorrupt(f"{table_name} rows moved outside their Source Day") - - def _hour_path(self, hour: datetime) -> Path: - return self._hourly / f"source_hour={hour.strftime('%Y-%m-%dT%H')}" - - def _seal_path(self, day: date) -> Path: - return self._sealed / f"source_day={day.isoformat()}.json" - - def _abandon_path(self, day: date) -> Path: - return self._sealed / f"source_day={day.isoformat()}.abandoned.json" - - -def parse_source_day(value: date | str) -> date: - if isinstance(value, datetime): - raise ValueError("Source Day cannot be a datetime") - if isinstance(value, str): - try: - parsed = date.fromisoformat(value) - except ValueError as error: - raise ValueError("Source Day must use YYYY-MM-DD") from error - if parsed.isoformat() != value: - raise ValueError("Source Day must use YYYY-MM-DD") - return parsed - if not isinstance(value, date): - raise TypeError("Source Day must be a date or YYYY-MM-DD") - return value - - -def _digest_map(value: object, expected: set[str], label: str) -> dict[str, str]: - if ( - not isinstance(value, dict) - or set(value) != expected - or not all( - isinstance(key, str) and isinstance(item, str) and _SHA256.fullmatch(item) is not None - for key, item in value.items() - ) - ): - raise FactCorrupt(f"Hourly Parquet {label} map is invalid") - return dict(value) - - -def _integer_map(value: object, expected: set[str], label: str) -> dict[str, int]: - if ( - not isinstance(value, dict) - or set(value) != expected - or not all( - isinstance(key, str) - and isinstance(item, int) - and not isinstance(item, bool) - and item >= 0 - for key, item in value.items() - ) - ): - raise FactCorrupt(f"Hourly Parquet {label} map is invalid") - return dict(value) - - -def _sha256_file(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(chunk) - return digest.hexdigest() - - -def _durable_create(path: Path, content: bytes) -> None: - with path.open("xb") as stream: - stream.write(content) - stream.flush() - os.fsync(stream.fileno()) - - -def _atomic_immutable_file(path: Path, content: bytes) -> bool: - for stale in path.parent.glob(f".{path.name}.tmp-*"): - if stale.is_file(): - stale.unlink(missing_ok=True) - if path.exists(): - try: - existing = path.read_bytes() - except OSError as error: - raise FactConflict(f"Immutable file is unreadable: {path.name}") from error - if existing == content: - return True - raise FactConflict(f"Immutable file conflict: {path.name}") - temporary = path.parent / f".{path.name}.tmp-{uuid.uuid4().hex}" - try: - _durable_create(temporary, content) - os.link(temporary, path) - fsync_directory(path.parent) - except FileExistsError: - try: - if path.read_bytes() == content: - return True - except OSError: - pass - raise FactConflict(f"Immutable file conflict: {path.name}") from None - finally: - temporary.unlink(missing_ok=True) - return False diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/hour_intake.py b/bazaarplusplus-analyzer/src/bppanalyzer/hour_intake.py deleted file mode 100644 index 50b1d5a..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/hour_intake.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Commit one complete Source Hour behind one transaction interface.""" - -import time -from collections.abc import Callable, Iterator -from dataclasses import dataclass, replace -from datetime import date, datetime, timedelta -from typing import Literal, Protocol - -from bppanalyzer.bundle_source import Bundle, HourExpired, RawHourIndex, RetryableSourceError -from bppanalyzer.durable import aware_utc -from bppanalyzer.fact_store import FactStore, HourCommit, parse_source_day -from bppanalyzer.projection import project_hour - -DEFAULT_SETTLE_LAG = timedelta(seconds=60) - - -class Source(Protocol): - def hour_index(self, source_hour: datetime) -> RawHourIndex: ... - - def stream(self, index: RawHourIndex) -> Iterator[Bundle]: ... - - -@dataclass(frozen=True, slots=True) -class HourIntakeProgress: - """Cumulative facts for one attempt; commit or error marks its terminal observation. - - Unknown index size is None, distinct from an empty hour. Succeeded Bundles - passed source admission, not necessarily projection or durable commit. - """ - - source_hour: str - step: Literal["index", "ingest", "complete"] = "index" - expected_bundles: int | None = None - succeeded_bundles: int = 0 - failed_bundles: int = 0 - listing_pages: int = 0 - source_index_seconds: float = 0.0 - source_ingest_seconds: float = 0.0 - elapsed_seconds: float = 0.0 - commit: HourCommit | None = None - error: BaseException | None = None - - -BUNDLE_PROGRESS_EVERY = 250 - - -class SourceHourIntake: - """Own enumeration, admission, bounded projection, and immutable fact commit.""" - - def __init__( - self, - source: Source, - store: FactStore, - *, - monotonic: Callable[[], float] = time.monotonic, - ) -> None: - self._source = source - self._store = store - self._monotonic = monotonic - - def commit( - self, - source_hour: datetime, - *, - on_progress: Callable[[HourIntakeProgress], None] = lambda _progress: None, - ) -> HourIntakeProgress: - """Return a committed or recoverable source result, with live observations. - - Fatal errors propagate unchanged. Only source expiry and retryable source - errors return a failed result; the caller owns retry and abandonment. - - Observers run synchronously before the next Bundle is projected. An - observer failure aborts the attempt, but is not a download failure. - Failure observation must not mask the original error. Success is already - durable when observed, so its observer cannot turn it into intake failure. - """ - started = self._monotonic() - index_started = started - ingest_started: float | None = None - progress = HourIntakeProgress(aware_utc(source_hour).strftime("%Y-%m-%dT%H")) - completed = 0 - observer_error: BaseException | None = None - - def observe(update: HourIntakeProgress) -> None: - nonlocal observer_error - try: - on_progress(update) - except BaseException as error: - observer_error = error - raise - - try: - observe(progress) - index_started = self._monotonic() - index = self._source.hour_index(source_hour) - total = len(index.items) - indexed_at = self._monotonic() - progress = replace( - progress, - step="ingest", - expected_bundles=total, - listing_pages=index.pages, - source_index_seconds=indexed_at - index_started, - elapsed_seconds=indexed_at - started, - ) - observe(progress) - ingest_started = self._monotonic() - - def admitted_bundles() -> Iterator[Bundle]: - nonlocal completed - for completed, bundle in enumerate(self._source.stream(index), start=1): - if ( - completed == 1 - or completed == total - or completed % BUNDLE_PROGRESS_EVERY == 0 - ): - observed_at = self._monotonic() - observe( - replace( - progress, - succeeded_bundles=completed, - source_ingest_seconds=observed_at - ingest_started, - elapsed_seconds=observed_at - started, - ) - ) - yield bundle - - commit = self._store.commit_hour(project_hour(index, admitted_bundles())) - except BaseException as error: - failed_at = self._monotonic() - failed = replace( - progress, - succeeded_bundles=completed, - failed_bundles=( - max((progress.expected_bundles or 0) - completed, 0) - if isinstance(error, RetryableSourceError) and error is not observer_error - else 0 - ), - source_index_seconds=( - failed_at - index_started - if progress.expected_bundles is None - else progress.source_index_seconds - ), - source_ingest_seconds=( - failed_at - ingest_started if ingest_started is not None else 0.0 - ), - elapsed_seconds=failed_at - started, - error=error, - ) - try: - on_progress(failed) - except BaseException as observation_error: - raise error from observation_error - if error is not observer_error and isinstance( - error, (HourExpired, RetryableSourceError) - ): - return failed - raise - - finished_at = self._monotonic() - result = replace( - progress, - step="complete", - succeeded_bundles=completed, - source_ingest_seconds=finished_at - ingest_started, - elapsed_seconds=finished_at - started, - commit=commit, - ) - on_progress(result) - return result - - -def healing_days( - now: datetime, count: int, *, source_epoch: date | str | None = None -) -> tuple[date, ...]: - """Return the oldest-first UTC Source Days considered by an invocation.""" - current = aware_utc(now).date() - first = current - timedelta(days=count - 1) - epoch = parse_source_day(source_epoch) if source_epoch is not None else None - return tuple( - day - for offset in range(count) - if (day := first + timedelta(days=offset)) >= (epoch or first) - ) - - -def is_hour_settled( - source_hour: datetime, - now: datetime, - *, - settle_lag: timedelta = DEFAULT_SETTLE_LAG, -) -> bool: - hour = aware_utc(source_hour) - if hour.minute or hour.second or hour.microsecond: - raise ValueError("Source Hour must align to the hour") - return aware_utc(now) >= hour + timedelta(hours=1) + settle_lag - - -def settled_missing_hours( - source_day: date, - now: datetime, - missing: tuple[datetime, ...], - *, - settle_lag: timedelta = DEFAULT_SETTLE_LAG, -) -> tuple[datetime, ...]: - if any(hour.date() != source_day for hour in missing): - raise ValueError("Missing Source Hours must belong to the Source Day") - return tuple( - sorted(hour for hour in missing if is_hour_settled(hour, now, settle_lag=settle_lag)) - ) diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/locking.py b/bazaarplusplus-analyzer/src/bppanalyzer/locking.py deleted file mode 100644 index 9afd519..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/locking.py +++ /dev/null @@ -1,233 +0,0 @@ -"""Single-machine mkdir lock with stale takeover and zombie fencing.""" - -import contextlib -import json -import os -import shutil -import socket -import threading -import time -from datetime import UTC, datetime -from pathlib import Path -from typing import Self - - -class LockError(RuntimeError): - """Base run-lock failure.""" - - -class LockHeld(LockError): - """Another fresh run owns the local lock.""" - - -class LockOwnershipLost(LockError): - """This process was fenced by a stale-lock takeover.""" - - -class MaximumRunTimeExceeded(LockOwnershipLost): - """A run exceeded its configured ownership lifetime.""" - - -class DirectoryLock: - """Own ``.lock`` only while its heartbeat still names this run.""" - - def __init__( - self, - data_root: str | Path, - run_id: str, - *, - heartbeat_interval: float = 30, - stale_after: float = 300, - max_run_seconds: float = 21600, - ) -> None: - if not run_id or any(character in run_id for character in "/\\"): - raise ValueError("Run lock identity is invalid") - if heartbeat_interval <= 0 or stale_after <= 0 or max_run_seconds <= 0: - raise ValueError("Run lock time limits must be positive") - self._root = Path(data_root) - self._path = self._root / ".lock" - self._heartbeat = self._path / "heartbeat" - self.run_id = run_id - self._interval = heartbeat_interval - self._stale_after = stale_after - self._max_seconds = max_run_seconds - self._started_monotonic: float | None = None - self._stop = threading.Event() - self._lost = threading.Event() - self._lost_reason = "Run lock ownership was lost" - self._thread: threading.Thread | None = None - self.stale_run_id: str | None = None - - def acquire(self) -> Self: - self._root.mkdir(parents=True, exist_ok=True) - stale_path = self._root / f".lock.stale-{self.run_id}" - takeover_guard = self._root / ".lock.takeover" - while True: - try: - self._path.mkdir() - except FileExistsError: - age = self._heartbeat_age() - if age is None: - continue - if age <= self._stale_after: - raise LockHeld("Another bpp run holds the lock") from None - try: - takeover_guard.mkdir() - except FileExistsError: - self._recover_takeover_guard(takeover_guard) - time.sleep(0.001) - continue - try: - # Another stale contender may have completed between our - # first observation and winning the takeover guard. - age = self._heartbeat_age() - if age is None: - # A missing claim cannot be taken over: another process - # may create a fresh directory before the rename below. - continue - if age <= self._stale_after: - raise LockHeld("Another bpp run holds the lock") - self.stale_run_id = self._read_run_id(self._heartbeat) - try: - os.rename(self._path, stale_path) - except FileNotFoundError: - continue - except FileExistsError: - shutil.rmtree(stale_path, ignore_errors=True) - continue - finally: - with contextlib.suppress(OSError): - takeover_guard.rmdir() - continue - break - - started = datetime.fromtimestamp(time.time(), tz=UTC) - body = { - "run_id": self.run_id, - "pid": os.getpid(), - "started_at": started.isoformat().replace("+00:00", "Z"), - "hostname": socket.gethostname(), - } - try: - with self._heartbeat.open("x", encoding="utf-8") as stream: - json.dump(body, stream, sort_keys=True, separators=(",", ":")) - stream.write("\n") - stream.flush() - os.fsync(stream.fileno()) - except BaseException: - with contextlib.suppress(OSError): - self._path.rmdir() - raise - if stale_path.exists(): - shutil.rmtree(stale_path, ignore_errors=True) - self._started_monotonic = time.monotonic() - self._thread = threading.Thread( - target=self._heartbeat_loop, - name=f"bpp-heartbeat-{self.run_id}", - daemon=True, - ) - self._thread.start() - return self - - def assert_owned(self) -> None: - if self._lost.is_set(): - if self._lost_reason == "Maximum run time exceeded": - raise MaximumRunTimeExceeded(self._lost_reason) - raise LockOwnershipLost(self._lost_reason) - if self._started_monotonic is None: - raise LockOwnershipLost("Run lock was not acquired") - if time.monotonic() - self._started_monotonic > self._max_seconds: - self._mark_lost("Maximum run time exceeded") - raise MaximumRunTimeExceeded("Maximum run time exceeded") - owner = self._read_run_id(self._heartbeat) - if owner != self.run_id: - self._mark_lost("Run lock ownership was replaced") - raise LockOwnershipLost("Run lock ownership was replaced") - - def assert_current_owner(self) -> None: - """Fence writes without extending an exceeded run deadline.""" - if self._lost.is_set() and self._lost_reason != "Maximum run time exceeded": - raise LockOwnershipLost(self._lost_reason) - if self._started_monotonic is None: - raise LockOwnershipLost("Run lock was not acquired") - owner = self._read_run_id(self._heartbeat) - if owner != self.run_id: - self._mark_lost("Run lock ownership was replaced") - raise LockOwnershipLost("Run lock ownership was replaced") - - def touch(self) -> None: - self.assert_owned() - try: - os.utime(self._heartbeat, None) - except FileNotFoundError: - self._mark_lost("Run lock heartbeat disappeared") - raise LockOwnershipLost("Run lock heartbeat disappeared") from None - - def release(self) -> None: - self._stop.set() - if self._thread is not None and self._thread is not threading.current_thread(): - self._thread.join(timeout=min(self._interval + 0.1, 1.0)) - self.assert_current_owner() - try: - self._heartbeat.unlink() - self._path.rmdir() - except FileNotFoundError: - self._mark_lost("Run lock disappeared during release") - raise LockOwnershipLost("Run lock disappeared during release") from None - finally: - self._started_monotonic = None - - def __enter__(self) -> Self: - return self.acquire() - - def __exit__( - self, - _exception_type: object, - exception: object, - _traceback: object, - ) -> None: - try: - self.release() - except LockOwnershipLost: - if exception is None: - raise - - def _heartbeat_loop(self) -> None: - while not self._stop.wait(self._interval): - try: - self.touch() - except LockOwnershipLost: - return - - def _mark_lost(self, reason: str) -> None: - self._lost_reason = reason - self._lost.set() - self._stop.set() - - def _heartbeat_age(self) -> float | None: - try: - modified = self._heartbeat.stat().st_mtime - except FileNotFoundError: - try: - modified = self._path.stat().st_mtime - except FileNotFoundError: - return None - return max(0.0, time.time() - modified) - - def _recover_takeover_guard(self, path: Path) -> None: - try: - age = max(0.0, time.time() - path.stat().st_mtime) - except FileNotFoundError: - return - if age > self._stale_after: - with contextlib.suppress(OSError): - path.rmdir() - - @staticmethod - def _read_run_id(path: Path) -> str | None: - try: - value = json.loads(path.read_bytes()) - except FileNotFoundError, OSError, json.JSONDecodeError, UnicodeDecodeError: - return None - run_id = value.get("run_id") if isinstance(value, dict) else None - return run_id if isinstance(run_id, str) else None diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/object_store.py b/bazaarplusplus-analyzer/src/bppanalyzer/object_store.py deleted file mode 100644 index f7c4632..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/object_store.py +++ /dev/null @@ -1,260 +0,0 @@ -"""Minimal object-store boundary with its Cloudflare R2 adapter.""" - -import hashlib -import re -from dataclasses import dataclass -from datetime import UTC, datetime -from pathlib import PurePosixPath -from typing import Protocol - -import boto3 -import httpx -from botocore.config import Config as BotoConfig -from botocore.exceptions import BotoCoreError, ClientError - -CLOUDFLARE_API = "https://api.cloudflare.com/client/v4" -_ACCOUNT_ID = re.compile(r"[0-9a-fA-F]{32}") -_TOKEN_ID = re.compile(r"[0-9a-f]{32}") -_BUCKET = re.compile(r"[a-z0-9][a-z0-9-]*[a-z0-9]") -# Verified token ids per process, keyed by the token's digest, never its value. -_verified_token_ids: dict[str, str] = {} - - -class ObjectStoreError(RuntimeError): - """An object-store request failed or returned inconsistent metadata.""" - - -class _TokenRejected(ObjectStoreError): - """One verify endpoint does not recognize the token.""" - - -def _verify_token(token: str, account_id: str | None, client: httpx.Client | None) -> str: - # A user token verifies at /user; an account-owned token only at its account. - try: - return _verify_at(f"{CLOUDFLARE_API}/user/tokens/verify", token, client) - except _TokenRejected: - if account_id is None: - raise - return _verify_at( - f"{CLOUDFLARE_API}/accounts/{account_id.lower()}/tokens/verify", token, client - ) - - -def _verify_at(url: str, token: str, client: httpx.Client | None) -> str: - def request(http: httpx.Client) -> httpx.Response: - return http.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=30.0) - - try: - if client is not None: - response = request(client) - else: - with httpx.Client() as http: - response = request(http) - except httpx.HTTPError as error: - raise ObjectStoreError("Cloudflare token verification failed") from error - try: - body = response.json() - except ValueError: - body = None - if response.status_code != 200 or not isinstance(body, dict) or body.get("success") is not True: - raise _TokenRejected( - f"Cloudflare rejected CLOUDFLARE_API_TOKEN: HTTP {response.status_code}" - ) - result = body.get("result") or {} - token_id = result.get("id") - status = result.get("status") - if not isinstance(token_id, str) or _TOKEN_ID.fullmatch(token_id) is None: - raise ObjectStoreError("Cloudflare token verification returned no token id") - if status != "active": - raise ObjectStoreError(f"CLOUDFLARE_API_TOKEN is {status}, not active") - return token_id - - -def derive_s3_credentials( - api_token: str, - *, - account_id: str | None = None, - client: httpx.Client | None = None, -) -> tuple[str, str]: - """The S3 pair R2 accepts for an API token. - - The Access Key ID is the token's id, which only a token verify call - reveals, and the Secret Access Key is the SHA-256 of the token value. A - user token verifies at ``/user/tokens/verify``; an account-owned token is - rejected there and verifies at ``/accounts/{account_id}/tokens/verify`` - when ``account_id`` is given. The verified id is reused for the rest of - the process. - """ - token = api_token.strip() - if not token: - raise ValueError("CLOUDFLARE_API_TOKEN is empty") - if account_id is not None and _ACCOUNT_ID.fullmatch(account_id) is None: - raise ValueError("CLOUDFLARE_ACCOUNT_ID must be the 32-character hexadecimal account id") - # Cloudflare defines the secret as this digest; it is not password storage. - secret = hashlib.sha256(token.encode()).hexdigest() # lgtm[py/weak-sensitive-data-hashing] - access_key_id = _verified_token_ids.get(secret) - if access_key_id is None: - access_key_id = _verify_token(token, account_id, client) - _verified_token_ids[secret] = access_key_id - return access_key_id, secret - - -@dataclass(frozen=True, slots=True) -class ObjectStat: - key: str - # None for an object another tool wrote without the sha256 metadata - # R2ObjectStore.put records; it never matches a snapshot, so it is replaced. - sha256: str | None - bytes: int - cache_control: str - content_type: str - last_modified: datetime - - -@dataclass(frozen=True, slots=True) -class StoredObject: - body: bytes - stat: ObjectStat - - -class ObjectStore(Protocol): - def stat(self, key: str) -> ObjectStat | None: ... - - def get(self, key: str) -> StoredObject | None: ... - - def put( - self, - key: str, - body: bytes, - *, - cache_control: str, - content_type: str = "application/octet-stream", - ) -> None: ... - - -class R2ObjectStore: - """Cloudflare R2 adapter using its S3-compatible boto3 endpoint. - - The S3 pair is derived from ``api_token`` with one verify call before any - bucket request; an empty token, a malformed account id or bucket name, and - a rejected, malformed or inactive token all fail here. - """ - - def __init__( - self, - *, - account_id: str, - bucket: str, - api_token: str, - http_client: httpx.Client | None = None, - ) -> None: - if not all((account_id, bucket, api_token)): - raise ValueError("Complete R2 configuration is required") - if _ACCOUNT_ID.fullmatch(account_id) is None: - raise ValueError( - "CLOUDFLARE_ACCOUNT_ID must be the 32-character hexadecimal account id" - ) - if _BUCKET.fullmatch(bucket) is None: - raise ValueError("Invalid R2 bucket") - access_key_id, secret_access_key = derive_s3_credentials( - api_token, account_id=account_id, client=http_client - ) - self.bucket = bucket - self._client = boto3.client( - "s3", - endpoint_url=f"https://{account_id.lower()}.r2.cloudflarestorage.com", - aws_access_key_id=access_key_id, - aws_secret_access_key=secret_access_key, - region_name="auto", - config=BotoConfig(signature_version="s3v4"), - ) - - def stat(self, key: str) -> ObjectStat | None: - _safe_key(key) - try: - response = self._client.head_object(Bucket=self.bucket, Key=key) - except ClientError as error: - if _is_not_found(error): - return None - raise ObjectStoreError(f"R2 stat failed: {key}") from error - except BotoCoreError as error: - raise ObjectStoreError(f"R2 stat failed: {key}") from error - return _r2_stat(key, response) - - def get(self, key: str) -> StoredObject | None: - _safe_key(key) - try: - response = self._client.get_object(Bucket=self.bucket, Key=key) - body = response["Body"].read() - except ClientError as error: - if _is_not_found(error): - return None - raise ObjectStoreError(f"R2 get failed: {key}") from error - except (BotoCoreError, KeyError, OSError) as error: - raise ObjectStoreError(f"R2 get failed: {key}") from error - stat = _r2_stat(key, response, body=body) - return StoredObject(body, stat) - - def put( - self, - key: str, - body: bytes, - *, - cache_control: str, - content_type: str = "application/octet-stream", - ) -> None: - _safe_key(key) - digest = hashlib.sha256(body).hexdigest() - try: - self._client.put_object( - Bucket=self.bucket, - Key=key, - Body=body, - CacheControl=cache_control, - ContentType=content_type, - Metadata={"sha256": digest}, - ) - except (BotoCoreError, ClientError) as error: - raise ObjectStoreError(f"R2 put failed: {key}") from error - - -def _r2_stat(key: str, response: dict, *, body: bytes | None = None) -> ObjectStat: - try: - size = int(response["ContentLength"]) - cache_control = response["CacheControl"] - content_type = response["ContentType"] - modified = response["LastModified"] - metadata = response.get("Metadata", {}) - except (KeyError, TypeError, ValueError) as error: - raise ObjectStoreError(f"R2 metadata is incomplete: {key}") from error - if ( - not isinstance(cache_control, str) - or not isinstance(content_type, str) - or not isinstance(modified, datetime) - ): - raise ObjectStoreError(f"R2 metadata is incomplete: {key}") - digest = metadata.get("sha256") - if body is not None: - actual = hashlib.sha256(body).hexdigest() - if size != len(body) or (digest is not None and digest != actual): - raise ObjectStoreError(f"R2 object metadata differs from bytes: {key}") - digest = actual - if digest is not None and (not isinstance(digest, str) or len(digest) != 64): - raise ObjectStoreError(f"R2 object sha256 metadata is malformed: {key}") - if modified.tzinfo is None: - modified = modified.replace(tzinfo=UTC) - return ObjectStat(key, digest, size, cache_control, content_type, modified.astimezone(UTC)) - - -def _is_not_found(error: ClientError) -> bool: - code = str(error.response.get("Error", {}).get("Code", "")) - return code in {"404", "NoSuchKey", "NotFound"} - - -def _safe_key(key: str) -> PurePosixPath: - if not isinstance(key, str) or not key or "\\" in key: - raise ValueError("Object key is invalid") - value = PurePosixPath(key) - if value.is_absolute() or any(part in {"", ".", ".."} for part in value.parts): - raise ValueError("Object key is invalid") - return value diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/operational_evidence.py b/bazaarplusplus-analyzer/src/bppanalyzer/operational_evidence.py deleted file mode 100644 index b697860..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/operational_evidence.py +++ /dev/null @@ -1,647 +0,0 @@ -"""Build and persist local Operational Evidence for pipeline Runs.""" - -import contextlib -import json -import os -import resource -import shutil -import sys -from collections.abc import Callable -from dataclasses import asdict, dataclass, field, fields -from datetime import UTC, date, datetime, timedelta -from pathlib import Path -from typing import Any, TypedDict, cast - -from bppanalyzer.bundle_source import SourcePerformance -from bppanalyzer.durable import atomic_replace, aware_utc, canonical_json, utc_timestamp -from bppanalyzer.fact_store import FactPruneReport, FactStore, parse_source_day -from bppanalyzer.hour_intake import HourIntakeProgress, is_hour_settled -from bppanalyzer.publication import ( - PRODUCTS, - AnalysisWindow, - BuildStats, - ConsumerProduct, - FactStats, - HeroStats, -) - - -class WindowReport(TypedDict): - start: str - end: str - days: int - - -class DownloadReport(TypedDict): - expected_bundles: int - succeeded_bundles: int - failed_bundles: int - listing_pages: int - listing_requests: int - listing_retries: int - download_attempts: int - download_retries: int - downloaded_bytes: int - download_latency_ms_p50: float | None - download_latency_ms_p95: float | None - - -class FactReport(TypedDict): - raw_runs: int - discarded_unknown_hero: int - discarded_unknown_final_rank: int - included_runs: int - included_battles: int - - -class HeroReport(TypedDict): - participating_runs: int - participating_matchup_battles: int - published: bool - - -class BuildReport(TypedDict): - eligible_layout_runs: int - candidate_builds: int - published_builds: int - published: bool - - -class RetentionReport(TypedDict): - source_days_pruned: int - hours_pruned: int - files_pruned: int - bytes_pruned: int - - -class RunReportValue(TypedDict): - window: WindowReport | None - downloads: DownloadReport - facts: FactReport - heroes: HeroReport - builds: BuildReport - retention: RetentionReport - - -@dataclass(slots=True) -class RunReport: - value: RunReportValue - - @classmethod - def empty(cls) -> RunReport: - value = { - "window": None, - "downloads": { - "expected_bundles": 0, - "succeeded_bundles": 0, - "failed_bundles": 0, - "listing_pages": 0, - "listing_requests": 0, - "listing_retries": 0, - "download_attempts": 0, - "download_retries": 0, - "downloaded_bytes": 0, - "download_latency_ms_p50": None, - "download_latency_ms_p95": None, - }, - "facts": { - "raw_runs": 0, - "discarded_unknown_hero": 0, - "discarded_unknown_final_rank": 0, - "included_runs": 0, - "included_battles": 0, - }, - **{ - product.name: { - **{stat.name: 0 for stat in fields(product.stats_type)}, - "published": False, - } - for product in PRODUCTS - }, - "retention": { - "source_days_pruned": 0, - "hours_pruned": 0, - "files_pruned": 0, - "bytes_pruned": 0, - }, - } - return cls(cast(RunReportValue, value)) - - def select_window(self, window: AnalysisWindow | None) -> None: - self.value["window"] = ( - { - "start": window.start.isoformat(), - "end": window.end.isoformat(), - "days": len(window.seals), - } - if window is not None - else None - ) - - def record_facts(self, stats: FactStats) -> None: - self.value["facts"] = { - "raw_runs": stats.raw_runs, - "discarded_unknown_hero": stats.discarded_unknown_hero, - "discarded_unknown_final_rank": stats.discarded_unknown_final_rank, - "included_runs": stats.included_runs, - "included_battles": stats.included_battles, - } - - def record_downloads( - self, - *, - listing_pages: int, - listing_requests: int, - listing_retries: int, - download_attempts: int, - download_retries: int, - downloaded_bytes: int, - download_latency_ms_p50: float | None, - download_latency_ms_p95: float | None, - ) -> None: - self.value["downloads"].update( - listing_pages=listing_pages, - listing_requests=listing_requests, - listing_retries=listing_retries, - download_attempts=download_attempts, - download_retries=download_retries, - downloaded_bytes=downloaded_bytes, - download_latency_ms_p50=download_latency_ms_p50, - download_latency_ms_p95=download_latency_ms_p95, - ) - - def record_product(self, product: ConsumerProduct, stats: HeroStats | BuildStats) -> None: - if not isinstance(stats, product.stats_type): - raise ValueError(f"Stats do not belong to consumer product: {product.name}") - self._product_report(product).update(asdict(stats)) - - def mark_published(self, product: ConsumerProduct) -> None: - self._product_report(product)["published"] = True - - def all_published(self) -> bool: - return all(self._product_report(product)["published"] for product in PRODUCTS) - - def _product_report(self, product: ConsumerProduct) -> dict[str, object]: - if product not in PRODUCTS: - raise ValueError(f"Unknown consumer product: {product.name}") - return cast(dict[str, dict[str, object]], self.value)[product.name] - - def record_retention(self, report: FactPruneReport) -> None: - self.value["retention"] = { - "source_days_pruned": len(report.source_days), - "hours_pruned": report.hours_pruned, - "files_pruned": report.files_pruned, - "bytes_pruned": report.bytes_pruned, - } - - -@dataclass(frozen=True, slots=True) -class RunSummary: - run_id: str - started_at: str - finished_at: str - timings: dict[str, float] - outcome: str - exit_code: int - hours_ingested: int - days_sealed: int - days_abandoned: int - failures: tuple[dict[str, str], ...] - report: RunReportValue - peak_rss_bytes: int - - def to_dict(self) -> dict[str, Any]: - value = asdict(self) - value["failures"] = list(self.failures) - return value - - -@dataclass(slots=True) -class RunEvidence: - """Accumulate one Run's facts and materialize its terminal summary.""" - - run_id: str - started_at: datetime - started_monotonic: float - hours_ingested: int = 0 - hours_planned: int = 0 - days_sealed: int = 0 - days_abandoned: int = 0 - expected_bundles: int = 0 - succeeded_bundles: int = 0 - failed_bundles: int = 0 - failures: list[dict[str, str]] = field(default_factory=list) - changed: bool = False - heal_started_monotonic: float | None = None - listing_pages: int = 0 - source_index_seconds: float = 0.0 - source_ingest_seconds: float = 0.0 - batch_generation_seconds: float = 0.0 - parquet_write_seconds: float = 0.0 - fact_finalize_seconds: float = 0.0 - product_timings: dict[str, float] = field(default_factory=dict) - heal_seconds: float | None = None - build_started_monotonic: float | None = None - report: RunReport = field(default_factory=RunReport.empty) - timings: dict[str, float] = field(default_factory=dict, init=False) - - @property - def outcome(self) -> str: - if self.failures: - return "partial" - return "ok" if self.changed else "noop" - - def observe_intake( - self, - update: HourIntakeProgress, - *, - report: Callable[[str], None], - checkpoint: Callable[..., None], - ) -> None: - """Translate intake facts into live evidence and aggregate each terminal once.""" - if update.error is not None or update.commit is not None: - self.expected_bundles += update.expected_bundles or 0 - self.succeeded_bundles += update.succeeded_bundles - self.failed_bundles += update.failed_bundles - self.listing_pages += update.listing_pages - self.source_index_seconds += update.source_index_seconds - self.source_ingest_seconds += update.source_ingest_seconds - if update.error is not None: - # This may be a lost lock or a runtime limit. Only record in memory; - # the driver owns whether any further durable evidence is permitted. - return - hour = update.source_hour - if (commit := update.commit) is not None: - self.batch_generation_seconds += commit.batch_generation_seconds - self.parquet_write_seconds += commit.parquet_write_seconds - self.fact_finalize_seconds += commit.fact_finalize_seconds - self.hours_ingested += 1 - self.changed = True - checkpoint( - "heal", - hour, - step="complete", - bundles_done=commit.bundle_count, - bundles_total=update.expected_bundles, - ) - reused = " reused" if commit.reused else "" - report( - f"healed {hour} bundles={commit.bundle_count} " - f"rows={sum(commit.row_counts.values())} " - f"bytes={sum(commit.file_bytes.values()) / (1024 * 1024):.1f}MiB " - f"elapsed={max(round(update.elapsed_seconds), 0)}s" - f"{reused} [{self.hours_ingested}/{self.hours_planned}]" - ) - elif update.step == "index": - checkpoint("heal", hour, step="index") - else: - if update.succeeded_bundles == 0: - report( - f"hour indexed: source_hour={hour} bundles={update.expected_bundles} " - f"pages={update.listing_pages} " - f"elapsed={max(round(update.source_index_seconds), 0)}s" - ) - else: - report( - f"hour ingest progress: source_hour={hour} " - f"bundles={update.succeeded_bundles}/{update.expected_bundles} " - f"elapsed={max(round(update.source_ingest_seconds), 0)}s" - ) - checkpoint( - "heal", - hour, - step="ingest", - bundles_done=update.succeeded_bundles, - bundles_total=update.expected_bundles, - ) - - def prepare_completion( - self, - *, - finished_monotonic: float, - source_performance: SourcePerformance | None, - ) -> None: - downloads = self.report.value["downloads"] - downloads.update( - expected_bundles=self.expected_bundles, - succeeded_bundles=self.succeeded_bundles, - failed_bundles=self.failed_bundles, - listing_pages=self.listing_pages, - ) - download_wait = source_performance.download_wait_seconds if source_performance else 0.0 - retry_sleep = source_performance.retry_sleep_seconds if source_performance else 0.0 - if source_performance is not None: - self.report.record_downloads( - listing_pages=self.listing_pages, - listing_requests=source_performance.listing_requests, - listing_retries=source_performance.listing_retries, - download_attempts=source_performance.download_attempts, - download_retries=source_performance.download_retries, - downloaded_bytes=source_performance.downloaded_bytes, - download_latency_ms_p50=source_performance.download_latency_ms_p50, - download_latency_ms_p95=source_performance.download_latency_ms_p95, - ) - heal_seconds = self.heal_seconds - if heal_seconds is None: - heal_seconds = ( - finished_monotonic - self.heal_started_monotonic - if self.heal_started_monotonic is not None - else 0.0 - ) - timings = { - "total_seconds": finished_monotonic - self.started_monotonic, - "heal_seconds": heal_seconds, - "source_index_seconds": self.source_index_seconds, - "source_ingest_seconds": self.source_ingest_seconds, - "batch_generation_seconds": self.batch_generation_seconds, - "projection_seconds": self.batch_generation_seconds - download_wait, - "parquet_write_seconds": self.parquet_write_seconds, - "fact_finalize_seconds": self.fact_finalize_seconds, - "download_wait_seconds": download_wait, - "retry_sleep_seconds": retry_sleep, - **self.product_timings, - } - if self.build_started_monotonic is not None: - timings["build_publish_seconds"] = finished_monotonic - self.build_started_monotonic - self.timings = {key: round(max(value, 0.0), 6) for key, value in timings.items()} - - def summarize(self, *, finished_at: datetime, fatal_reason: str | None) -> RunSummary: - failures = tuple(self.failures) - if fatal_reason is not None: - failures += ({"scope": "run", "reason": fatal_reason},) - outcome, exit_code = "error", 1 - else: - outcome, exit_code = self.outcome, (4 if failures else 0) - return RunSummary( - run_id=self.run_id, - started_at=utc_timestamp(self.started_at), - finished_at=utc_timestamp(finished_at), - timings=self.timings, - outcome=outcome, - exit_code=exit_code, - hours_ingested=self.hours_ingested, - days_sealed=self.days_sealed, - days_abandoned=self.days_abandoned, - failures=failures, - report=self.report.value, - peak_rss_bytes=peak_rss_bytes(), - ) - - -@dataclass(frozen=True, slots=True) -class CurrentRun: - phase: str - step: str - current_hour: str | None - hours_done: int - hours_planned: int - bundles_done: int | None - bundles_total: int | None - started_at: datetime - updated_at: datetime - - -class OperationalEvidence: - """Own status, Run history, and log persistence behind one interface.""" - - def __init__( - self, - root: str | Path, - run_id: str, - *, - clock: Callable[[], datetime], - ownership_check: Callable[[], None], - ) -> None: - self._root = Path(root) - self._run_id = run_id - self._clock = clock - self._ownership_check = ownership_check - directory = self._root / "logs" - ownership_check() - directory.mkdir(parents=True, exist_ok=True) - stamp = aware_utc(clock()).strftime("%Y%m%dT%H%M%S.%fZ") - self._log_path = directory / f"{stamp}-{os.getpid()}-{run_id[:8]}.log" - - def log(self, message: str) -> None: - self._ownership_check() - with self._log_path.open("a", encoding="utf-8") as stream: - stream.write(f"{utc_timestamp(self._clock())} {message}\n") - stream.flush() - os.fsync(stream.fileno()) - - def try_log(self, message: str) -> None: - with contextlib.suppress(BaseException): - self.log(message) - - def checkpoint( - self, - store: FactStore, - current: CurrentRun, - *, - considered_days: tuple[date, ...], - source_epoch: date | None, - ) -> None: - previous = _read_object(self._root / "status.json") or {} - status = _build_status( - self._root, - store, - None, - now=current.updated_at, - considered_days=considered_days, - source_epoch=source_epoch, - ) - status["last_run"] = previous.get("last_run") - current_value: dict[str, Any] = { - "run_id": self._run_id, - "phase": current.phase, - "step": current.step, - "current_hour": current.current_hour, - "hours_done": current.hours_done, - "hours_planned": current.hours_planned, - "started_at": utc_timestamp(current.started_at), - "updated_at": utc_timestamp(current.updated_at), - } - if current.bundles_total is not None: - current_value["bundles"] = { - "done": current.bundles_done or 0, - "total": current.bundles_total, - } - status["current_run"] = current_value - _write_status(self._root, status, self._ownership_check) - - def finish( - self, - store: FactStore, - summary: RunSummary, - *, - now: datetime, - considered_days: tuple[date, ...], - source_epoch: date | None, - ownership_check: Callable[[], None] | None = None, - ) -> None: - check = ownership_check or self._ownership_check - check() - status = _build_status( - self._root, - store, - summary, - now=now, - considered_days=considered_days, - source_epoch=source_epoch, - ) - _write_status(self._root, status, check) - _append_run(self._root, summary.to_dict(), check) - _prune_logs(self._root, now, check) - - -def read_status(data_root: str | Path, *, source_epoch: date | str | None = None) -> dict[str, Any]: - path = Path(data_root) / "status.json" - try: - value = json.loads(path.read_bytes()) - except FileNotFoundError: - return _build_status( - data_root, - FactStore(data_root), - None, - now=datetime.now(UTC), - source_epoch=source_epoch, - ) - except (OSError, json.JSONDecodeError, UnicodeDecodeError) as error: - raise RuntimeError("status.json is unreadable") from error - if not isinstance(value, dict): - raise RuntimeError("status.json must contain an object") - return value - - -def peak_rss_bytes() -> int: - observed = int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) - return observed if sys.platform == "darwin" else observed * 1024 - - -def _build_status( - data_root: str | Path, - store: FactStore, - last_run: RunSummary | None, - *, - now: datetime, - considered_days: tuple[date, ...] | None = None, - source_epoch: date | str | None = None, -) -> dict[str, Any]: - root = Path(data_root) - epoch = parse_source_day(source_epoch) if source_epoch is not None else None - seals = tuple( - item - for item in store.seals() - if epoch is None or parse_source_day(item.source_day) >= epoch - ) - abandoned = tuple( - item - for item in store.abandoned_days() - if epoch is None or parse_source_day(item.source_day) >= epoch - ) - if considered_days is None: - candidate_days = {date.fromisoformat(value[:10]) for value in store.committed_hours()} - candidate_days.update(date.fromisoformat(item.source_day) for item in abandoned) - considered_days = tuple( - sorted(day for day in candidate_days if epoch is None or day >= epoch) - ) - elif epoch is not None: - considered_days = tuple(day for day in considered_days if day >= epoch) - sealed_days = {item.source_day for item in seals} - abandoned_days = {item.source_day for item in abandoned} - incomplete = [] - for day in considered_days: - if day.isoformat() in sealed_days or day.isoformat() in abandoned_days: - continue - missing = store.missing_hours(day) - if missing: - incomplete.append( - { - "source_day": day.isoformat(), - "missing_hours": [hour.strftime("%Y-%m-%dT%H") for hour in missing], - "settled": is_hour_settled( - datetime.combine(day, datetime.min.time(), UTC) + timedelta(hours=23), - now, - ), - } - ) - return { - "facts": { - "newest_sealed_day": max(sealed_days, default=None), - "sealed_days": sorted(sealed_days), - "incomplete_days": incomplete, - "abandoned_days": [ - { - "source_day": item.source_day, - "missing_hours": list(item.missing_hours), - "reason": item.reason, - "abandoned_at": item.abandoned_at, - } - for item in abandoned - ], - }, - "publication": { - product.name: _local_snapshot_status(root / product.local_relpath) - for product in PRODUCTS - }, - "last_run": last_run.to_dict() if last_run is not None else None, - "current_run": None, - "disk": {"free_bytes": shutil.disk_usage(_existing_ancestor(root)).free}, - "peak_rss_bytes": peak_rss_bytes(), - } - - -def _local_snapshot_status(path: Path) -> dict[str, object]: - try: - payload = json.loads(path.read_bytes()) - window_end = payload["window"]["end"] - except FileNotFoundError, OSError, KeyError, TypeError, json.JSONDecodeError: - return {"present": False, "window_end": None} - return {"present": True, "window_end": window_end} - - -def _read_object(path: Path) -> dict[str, Any] | None: - try: - value = json.loads(path.read_bytes()) - except FileNotFoundError, OSError, json.JSONDecodeError, UnicodeDecodeError: - return None - return value if isinstance(value, dict) else None - - -def _write_status(root: Path, value: dict[str, Any], ownership_check: Callable[[], None]) -> None: - atomic_replace(root / "status.json", canonical_json(value), ownership_check=ownership_check) - - -def _append_run(root: Path, value: dict[str, Any], ownership_check: Callable[[], None]) -> None: - ownership_check() - root.mkdir(parents=True, exist_ok=True) - with (root / "runs.jsonl").open("ab") as stream: - stream.write(canonical_json(value)) - stream.flush() - os.fsync(stream.fileno()) - - -def _existing_ancestor(path: Path) -> Path: - candidate = path - while not candidate.exists(): - if candidate.parent == candidate: - return Path("/") - candidate = candidate.parent - return candidate - - -def _prune_logs(root: Path, now: datetime, ownership_check: Callable[[], None]) -> None: - cutoff = aware_utc(now).timestamp() - 10 * 24 * 60 * 60 - directory = root / "logs" - if not directory.is_dir(): - return - for path in directory.iterdir(): - if not path.is_file() or path.suffix != ".log": - continue - try: - expired = path.stat().st_mtime < cutoff - except OSError: - continue - if expired: - ownership_check() - path.unlink(missing_ok=True) diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/projection.py b/bazaarplusplus-analyzer/src/bppanalyzer/projection.py deleted file mode 100644 index 3c7227d..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/projection.py +++ /dev/null @@ -1,1006 +0,0 @@ -"""Streaming projection from verified Bundle V6 objects to five Arrow tables.""" - -import gzip -import hashlib -import json -import struct -from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from dataclasses import dataclass -from datetime import UTC, datetime, timedelta -from io import BytesIO -from typing import Any, cast - -import pyarrow as pa - -from bppanalyzer.accepted_runs import ( - CANONICAL_HEROES, - CANONICAL_RANKS, - RunAdmission, - admit_run, - normalize_hero, -) -from bppanalyzer.bundle_source import Bundle, RawHourIndex - -PROJECTION_VERSION = "v6-consumer-contract-1" -MAX_DECOMPRESSED_RUN_BYTES = 64 * 1024 * 1024 -ROW_BATCH_SIZE = 50_000 - - -class ProjectionError(RuntimeError): - """The complete Source Hour could not be projected consistently.""" - - -class RunPayloadError(ValueError): - """A stable, deterministic reason to quarantine one Bundle.""" - - def __init__(self, reason: str, message: str) -> None: - super().__init__(message) - self.reason = reason - - -class HourProjection: - """One hour's metadata plus its one-shot batch stream.""" - - __slots__ = ( - "_batch_stream", - "_stream_consumed", - "projection_version", - "raw_commit_sha256", - "source_hour", - ) - - def __init__( - self, - source_hour: datetime, - raw_commit_sha256: str, - projection_version: str = PROJECTION_VERSION, - *, - batch_stream: _ProjectedBatchStream, - ) -> None: - self.source_hour = source_hour - self.raw_commit_sha256 = raw_commit_sha256 - self.projection_version = projection_version - self._batch_stream = batch_stream - self._stream_consumed = False - - def iter_batches(self) -> Iterator[tuple[str, pa.RecordBatch]]: - if self._stream_consumed: - raise ProjectionError("Streaming Hour Projection was already consumed") - self._stream_consumed = True - yield from self._batch_stream - - @property - def bundle_count(self) -> int: - if self._batch_stream.bundle_count is None: - raise ProjectionError("Hour Projection Bundle count is unknown until fully streamed") - return self._batch_stream.bundle_count - - -_SCHEMAS: dict[str, pa.Schema] = { - "runs": pa.schema( - [ - ("source_hour", pa.string()), - ("source_day", pa.string()), - ("available_at_ms", pa.int64()), - ("bundle_id", pa.string()), - ("bundle_sha256", pa.string()), - ("run_id", pa.string()), - ("player_account_id", pa.string()), - ("client_created_at_ms", pa.int64()), - ("hero", pa.string()), - ("game_mode", pa.string()), - ("seed", pa.int64()), - ("started_at_utc", pa.string()), - ("ended_at_utc", pa.string()), - ("status", pa.string()), - ("run_day", pa.int64()), - ("run_hour", pa.int64()), - ("victories", pa.int64()), - ("losses", pa.int64()), - ("initial_rank", pa.string()), - ("initial_rating", pa.int64()), - ("final_rank", pa.string()), - ("final_rating", pa.int64()), - ("final_rating_delta", pa.int64()), - ("final_health", pa.int64()), - ("prestige", pa.int64()), - ("level", pa.int64()), - ("income", pa.int64()), - ("gold", pa.int64()), - ("build_channel", pa.string()), - ("mod_version", pa.string()), - ("battle_count", pa.int64()), - ("replayable_battle_count", pa.int64()), - ("battle_decided_count", pa.int64()), - ("battle_player_win_count", pa.int64()), - ("battle_player_loss_count", pa.int64()), - ("final_battle_id", pa.string()), - ("final_player_item_signature", pa.string()), - ("final_opponent_item_signature", pa.string()), - ("degradation_categories_json", pa.string()), - ("degraded_replay_count", pa.int64()), - ("degraded_event_count", pa.int64()), - ("degraded_screenshot", pa.bool_()), - ("projection_code_version", pa.string()), - ] - ), - "battles": pa.schema( - [ - ("source_hour", pa.string()), - ("source_day", pa.string()), - ("available_at_ms", pa.int64()), - ("bundle_id", pa.string()), - ("run_id", pa.string()), - ("battle_id", pa.string()), - ("recorded_at_utc", pa.string()), - ("game_day", pa.int64()), - ("game_hour", pa.int64()), - ("encounter_id", pa.string()), - ("combat_kind", pa.string()), - ("result", pa.string()), - ("winner_combatant_id", pa.string()), - ("loser_combatant_id", pa.string()), - ("is_final_battle", pa.bool_()), - ("player_account_id", pa.string()), - ("player_display_name", pa.string()), - ("player_hero", pa.string()), - ("player_rank", pa.string()), - ("player_rating", pa.int64()), - ("player_level", pa.int64()), - ("player_prestige", pa.int64()), - ("player_victories", pa.int64()), - ("player_income", pa.int64()), - ("player_gold", pa.int64()), - ("player_hand_item_count", pa.int64()), - ("player_skill_count", pa.int64()), - ("opponent_account_id", pa.string()), - ("opponent_display_name", pa.string()), - ("opponent_hero", pa.string()), - ("opponent_rank", pa.string()), - ("opponent_rating", pa.int64()), - ("opponent_level", pa.int64()), - ("opponent_prestige", pa.int64()), - ("opponent_victories", pa.int64()), - ("opponent_income", pa.int64()), - ("opponent_gold", pa.int64()), - ("opponent_hand_item_count", pa.int64()), - ("opponent_skill_count", pa.int64()), - ("winner_side", pa.string()), - ("winner_hero", pa.string()), - ("player_item_signature", pa.string()), - ("opponent_item_signature", pa.string()), - ("snapshot_available", pa.bool_()), - ("replay_available", pa.bool_()), - ] - ), - "battle_cards": pa.schema( - [ - ("source_hour", pa.string()), - ("source_day", pa.string()), - ("available_at_ms", pa.int64()), - ("bundle_id", pa.string()), - ("run_id", pa.string()), - ("battle_id", pa.string()), - ("card_set_label", pa.string()), - ("card_set_status", pa.string()), - ("card_set_source", pa.string()), - ("owner_side", pa.string()), - ("card_kind", pa.string()), - ("slot_index", pa.int64()), - ("instance_id", pa.string()), - ("template_id", pa.string()), - ("card_type", pa.int64()), - ("size", pa.int64()), - ("section", pa.int64()), - ("socket", pa.int64()), - ("name", pa.string()), - ("tier", pa.string()), - ("enchantment", pa.string()), - ("tags_json", pa.string()), - ("attributes_json", pa.string()), - ] - ), - "quality": pa.schema( - [ - ("source_hour", pa.string()), - ("source_day", pa.string()), - ("bundle_id", pa.string()), - ("run_id", pa.string()), - ("code", pa.string()), - ("severity", pa.string()), - ("blocks_release", pa.bool_()), - ("detail_json", pa.string()), - ] - ), - "quarantine": pa.schema( - [ - ("source_hour", pa.string()), - ("source_day", pa.string()), - ("bundle_id", pa.string()), - ("run_id", pa.string()), - ("stage", pa.string()), - ("reason_code", pa.string()), - ("raw_run", pa.bool_()), - ("discarded_unknown_hero", pa.bool_()), - ("discarded_unknown_final_rank", pa.bool_()), - ("first_seen_at", pa.string()), - ("decoder_code_version", pa.string()), - ("diagnostic_json", pa.string()), - ] - ), -} - - -def table_schemas() -> Mapping[str, pa.Schema]: - return _SCHEMAS.copy() - - -def project_hour(index: RawHourIndex, bundles: Iterable[Bundle]) -> HourProjection: - """Return a one-shot, fixed-size batch stream over the ordered Bundles.""" - return HourProjection( - index.source_hour, - index.raw_commit_sha256, - batch_stream=_ProjectedBatchStream(index, bundles), - ) - - -class _ProjectedBatchStream: - __slots__ = ("bundle_count", "bundles", "index") - - def __init__(self, index: RawHourIndex, bundles: Iterable[Bundle]) -> None: - self.index = index - self.bundles = bundles - self.bundle_count: int | None = None - - def __iter__(self) -> Iterator[tuple[str, pa.RecordBatch]]: - buffers: dict[str, list[dict[str, object]]] = {name: [] for name in _SCHEMAS} - observed_count = 0 - projected_count = 0 - hour_key = self.index.source_hour.strftime("%Y-%m-%dT%H") - day_key = self.index.source_hour.strftime("%Y-%m-%d") - first_seen = ( - (self.index.source_hour + timedelta(hours=1)).isoformat().replace("+00:00", "Z") - ) - - for observed_count, downloaded in enumerate(self.bundles, start=1): - if ( - observed_count > len(self.index.items) - or downloaded.ref.bundle_id != self.index.items[observed_count - 1].bundle_id - ): - raise ProjectionError("Bundle stream did not match the complete ordered index") - rows = _project_bundle_rows( - downloaded, - hour_key=hour_key, - day_key=day_key, - first_seen=first_seen, - ) - bundle_accounted = 0 - for table_name, row in rows: - if table_name in ("runs", "quarantine"): - bundle_accounted += 1 - buffer = buffers[table_name] - buffer.append(row) - if len(buffer) == ROW_BATCH_SIZE: - buffers[table_name] = [] - yield ( - table_name, - pa.RecordBatch.from_pylist(buffer, schema=_SCHEMAS[table_name]), - ) - if bundle_accounted != 1: - raise ProjectionError("Bundle projection accounting is incomplete") - projected_count += bundle_accounted - - if observed_count != len(self.index.items): - raise ProjectionError("Bundle stream did not match the complete ordered index") - if projected_count != len(self.index.items): - raise ProjectionError("Bundle projection accounting is incomplete") - for table_name, buffer in buffers.items(): - if buffer: - yield table_name, pa.RecordBatch.from_pylist(buffer, schema=_SCHEMAS[table_name]) - self.bundle_count = projected_count - - -def _project_bundle_rows( - downloaded: Bundle, - *, - hour_key: str, - day_key: str, - first_seen: str, -) -> Iterator[tuple[str, dict[str, object]]]: - manifest: Mapping[str, Any] | None = downloaded.manifest - try: - decoded = decode_run_payload(downloaded.run_content) - run_manifest = _object(manifest["run"], "run") - run_id = _text(run_manifest.get("run_id"), "run.run_id") - account_id = _text(run_manifest.get("player_account_id"), "run.player_account_id") - if decoded[1] != run_id or decoded[2] != account_id: - raise RunPayloadError( - "payload_identity_mismatch", - "Run payload and Bundle manifest identities differ", - ) - manifest_projection = _object(run_manifest.get("projection"), "projection") - manifest_battles = _array(manifest_projection.get("battles"), "battles") - manifest_ids = [ - _text(_object(item, "battle").get("battle_id"), "battle_id") - for item in manifest_battles - ] - payload_battles = _array(decoded[5], "payload.battles") - payload_ids = [_text(_slots(item, 5, "battle")[0], "battle_id") for item in payload_battles] - payload_id_set = set(payload_ids) - if len(payload_ids) != len(payload_id_set): - raise RunPayloadError("duplicate_payload_battle_id", "Run payload repeats a Battle ID") - if any(item not in payload_id_set for item in manifest_ids): - raise RunPayloadError( - "manifest_payload_battle_mismatch", - "A manifest Battle is absent from the payload", - ) - run = _slots(decoded[3], 22, "run") - admission = admit_run(_text(run[0], "run.hero"), _nullable_text(run[12], "run.final_rank")) - if not admission.accepted: - yield ( - "quarantine", - _quarantine_row( - hour_key, - day_key, - downloaded.ref.bundle_id, - run_id, - "fact_filter", - "unaccepted_run", - first_seen, - raw_run=True, - discarded_unknown_hero=admission.unknown_hero, - discarded_unknown_final_rank=admission.unknown_final_rank, - detail={"hero": admission.hero, "final_rank": admission.final_rank}, - ), - ) - return - projected = _prepare_valid_bundle( - downloaded, - manifest, - decoded, - admission, - hour_key=hour_key, - day_key=day_key, - ) - except ( - RunPayloadError, - KeyError, - TypeError, - ValueError, - ) as error: - reason = error.reason if isinstance(error, RunPayloadError) else "run_payload_decode_failed" - run_id = None - try: - if manifest is not None: - run_id = _object(manifest["run"], "run").get("run_id") - except KeyError, TypeError, ValueError: - pass - yield ( - "quarantine", - _quarantine_row( - hour_key, - day_key, - downloaded.ref.bundle_id, - run_id if isinstance(run_id, str) else None, - "run_payload_decode", - reason, - first_seen, - ), - ) - return - yield from projected.rows() - - -@dataclass(frozen=True, slots=True) -class _BattleSummary: - wins: int - losses: int - heroes: frozenset[str] - ranks: frozenset[str] - recorded_in_future: bool - recorded_before_run: bool - - -@dataclass(frozen=True, slots=True) -class _ValidBundleProjection: - base: Mapping[str, object] - run: Mapping[str, object] - battles: Sequence[tuple[Any, ...]] - replayable_ids: Sequence[str] - quality: Sequence[dict[str, object]] - - def rows(self) -> Iterator[tuple[str, dict[str, object]]]: - yield "runs", dict(self.run) - for battle in self.battles: - yield "battles", _battle_row(self.base, battle, self.replayable_ids) - for card in _card_rows(self.base, battle): - yield "battle_cards", card - for row in self.quality: - yield "quality", row - - -def _prepare_valid_bundle( - downloaded: Bundle, - manifest: Mapping[str, Any], - payload: tuple[Any, ...], - admission: RunAdmission, - *, - hour_key: str, - day_key: str, -) -> _ValidBundleProjection: - run_id = _text(payload[1], "run_id") - account_id = _text(payload[2], "player_account_id") - run = _slots(payload[3], 22, "run") - battles = [_slots(item, 5, "battle") for item in _array(payload[5], "battles")] - replayable_ids = [_text(item, "replayable_id") for item in _array(payload[6], "replayable_ids")] - degradation = _slots(payload[7], 4, "degradation") - available_at_ms = downloaded.ref.available_at_ms - base = { - "source_hour": hour_key, - "source_day": day_key, - "available_at_ms": available_at_ms, - "bundle_id": downloaded.ref.bundle_id, - "run_id": run_id, - } - - wins = 0 - losses = 0 - heroes: set[str] = set() - ranks: set[str] = set() - recorded_in_future = False - recorded_before_run = False - available = datetime.fromtimestamp(available_at_ms / 1_000, tz=UTC) - started = _parse_time(_text(run[3], "run.started_at")) - for battle in battles: - battle_row = _battle_row(base, battle, replayable_ids) - wins += battle_row["winner_side"] == "player" - losses += battle_row["winner_side"] == "opponent" - heroes.update( - value - for value in ( - battle_row["player_hero"], - battle_row["opponent_hero"], - ) - if isinstance(value, str) - ) - ranks.update( - value - for value in ( - battle_row["player_rank"], - battle_row["opponent_rank"], - ) - if isinstance(value, str) - ) - recorded = _parse_time(battle_row["recorded_at_utc"]) - recorded_in_future |= recorded is not None and recorded > available - recorded_before_run |= recorded is not None and started is not None and recorded < started - for _card in _card_rows(base, battle): - pass - summary = _BattleSummary( - wins, - losses, - frozenset(heroes), - frozenset(ranks), - recorded_in_future, - recorded_before_run, - ) - finals = [ - battle - for battle in battles - if _boolean(_slots(battle[1], 9, "battle.facts")[8], "is_final") - ] - final = finals[0] if len(finals) == 1 else None - run_row = { - **base, - "bundle_sha256": downloaded.sha256, - "player_account_id": account_id, - "client_created_at_ms": _integer(manifest.get("created_at_ms"), "created_at_ms"), - "hero": admission.hero, - "game_mode": _text(run[1], "run.game_mode").strip(), - "seed": _nullable_integer(run[2], "run.seed"), - "started_at_utc": _text(run[3], "run.started_at"), - "ended_at_utc": _nullable_text(run[4], "run.ended_at"), - "status": _text(run[5], "run.status"), - "run_day": _nullable_integer(run[6], "run.day"), - "run_hour": _nullable_integer(run[7], "run.hour"), - "victories": _nullable_integer(run[8], "run.victories"), - "losses": _nullable_integer(run[9], "run.losses"), - "initial_rank": _nullable_text(run[10], "run.initial_rank"), - "initial_rating": _nullable_integer(run[11], "run.initial_rating"), - "final_rank": admission.final_rank, - "final_rating": _nullable_integer(run[13], "run.final_rating"), - "final_rating_delta": _nullable_integer(run[14], "run.final_rating_delta"), - "final_health": _nullable_integer(run[15], "run.final_health"), - "prestige": _nullable_integer(run[16], "run.prestige"), - "level": _nullable_integer(run[17], "run.level"), - "income": _nullable_integer(run[18], "run.income"), - "gold": _nullable_integer(run[19], "run.gold"), - "build_channel": _nullable_text(run[20], "run.build_channel"), - "mod_version": _text(run[21], "run.mod_version"), - "battle_count": len(battles), - "replayable_battle_count": len(replayable_ids), - "battle_decided_count": wins + losses, - "battle_player_win_count": wins, - "battle_player_loss_count": losses, - "final_battle_id": _text(final[0], "battle_id") if final else None, - "final_player_item_signature": _card_signature(final, "player_hand"), - "final_opponent_item_signature": _card_signature(final, "opponent_hand"), - "degradation_categories_json": _json(_array(degradation[0], "degradation.categories")), - "degraded_replay_count": len(_array(degradation[1], "degradation.replays")), - "degraded_event_count": _integer(degradation[2], "degradation.events"), - "degraded_screenshot": _boolean(degradation[3], "degradation.screenshot"), - "projection_code_version": PROJECTION_VERSION, - } - quality = _quality_rows( - base, - run_row, - summary, - battles, - replayable_ids, - degradation, - ) - return _ValidBundleProjection(base, run_row, battles, replayable_ids, quality) - - -def _battle_row( - base: Mapping[str, object], battle: tuple[Any, ...], replayable_ids: Sequence[str] -) -> dict[str, object]: - battle_id = _text(battle[0], "battle_id") - facts = _slots(battle[1], 9, "battle.facts") - participants = _slots(battle[2], 2, "battle.participants") - player = _slots(participants[0], 12, "battle.player") - opponent = _slots(participants[1], 12, "battle.opponent") - player_id = _nullable_text(player[0], "player.account_id") - opponent_id = _nullable_text(opponent[0], "opponent.account_id") - winner_id = _nullable_text(facts[6], "battle.winner_id") - if winner_id == "Player" or (winner_id is not None and winner_id == player_id): - winner_side = "player" - winner_hero = normalize_hero(_nullable_text(player[2], "player.hero")) - elif winner_id == "Opponent" or (winner_id is not None and winner_id == opponent_id): - winner_side = "opponent" - winner_hero = normalize_hero(_nullable_text(opponent[2], "opponent.hero")) - else: - winner_side = None - winner_hero = None - return { - **base, - "battle_id": battle_id, - "recorded_at_utc": _text(facts[0], "battle.recorded_at"), - "game_day": _nullable_integer(facts[1], "battle.day"), - "game_hour": _nullable_integer(facts[2], "battle.hour"), - "encounter_id": _nullable_text(facts[3], "battle.encounter_id"), - "combat_kind": _text(facts[4], "battle.combat_kind"), - "result": _nullable_text(facts[5], "battle.result"), - "winner_combatant_id": winner_id, - "loser_combatant_id": _nullable_text(facts[7], "battle.loser_id"), - "is_final_battle": _boolean(facts[8], "battle.is_final"), - **_participant("player", player), - **_participant("opponent", opponent), - "winner_side": winner_side, - "winner_hero": winner_hero, - "player_item_signature": _card_signature(battle, "player_hand"), - "opponent_item_signature": _card_signature(battle, "opponent_hand"), - "snapshot_available": battle[3] is not None, - "replay_available": _replay_available(battle, replayable_ids), - } - - -def _participant(prefix: str, participant: tuple[Any, ...]) -> dict[str, object]: - return { - f"{prefix}_account_id": _nullable_text(participant[0], f"{prefix}.account_id"), - f"{prefix}_display_name": _nullable_text(participant[1], f"{prefix}.display_name"), - f"{prefix}_hero": normalize_hero(_nullable_text(participant[2], f"{prefix}.hero")), - f"{prefix}_rank": _nullable_text(participant[3], f"{prefix}.rank"), - f"{prefix}_rating": _nullable_integer(participant[4], f"{prefix}.rating"), - f"{prefix}_level": _nullable_integer(participant[5], f"{prefix}.level"), - f"{prefix}_prestige": _nullable_integer(participant[6], f"{prefix}.prestige"), - f"{prefix}_victories": _nullable_integer(participant[7], f"{prefix}.victories"), - f"{prefix}_income": _nullable_integer(participant[8], f"{prefix}.income"), - f"{prefix}_gold": _nullable_integer(participant[9], f"{prefix}.gold"), - f"{prefix}_hand_item_count": _nullable_integer(participant[10], f"{prefix}.hand_count"), - f"{prefix}_skill_count": _nullable_integer(participant[11], f"{prefix}.skill_count"), - } - - -def _card_rows(base: Mapping[str, object], battle: tuple[Any, ...]) -> Iterator[dict[str, object]]: - if battle[3] is None: - return - snapshots = _slots(battle[3], 1, "battle.snapshots") - for raw_set in _array(snapshots[0], "battle.card_sets"): - card_set = _slots(raw_set, 4, "battle.card_set") - label = _text(card_set[0], "card_set.label") - owner = ( - "player" - if label.startswith("player_") - else "opponent" - if label.startswith("opponent_") - else "unknown" - ) - kind = ( - "item" - if label.endswith("_hand") - else "skill" - if label.endswith("_skills") - else "unknown" - ) - for slot_index, raw_card in enumerate(_array(card_set[3], "card_set.cards")): - card = _slots(raw_card, 11, "battle.card") - attributes = _object(card[10], "card.attributes") - yield { - **base, - "battle_id": _text(battle[0], "battle_id"), - "card_set_label": label, - "card_set_status": _nullable_text(card_set[1], "card_set.status"), - "card_set_source": _nullable_text(card_set[2], "card_set.source"), - "owner_side": owner, - "card_kind": kind, - "slot_index": slot_index, - "instance_id": _text(card[0], "card.instance_id"), - "template_id": _text(card[1], "card.template_id"), - "card_type": _integer(card[2], "card.type"), - "size": _integer(card[3], "card.size"), - "section": _nullable_integer(card[4], "card.section"), - "socket": _nullable_integer(card[5], "card.socket"), - "name": _nullable_text(card[6], "card.name"), - "tier": _nullable_text(card[7], "card.tier"), - "enchantment": _nullable_text(card[8], "card.enchantment"), - "tags_json": _json(_array(card[9], "card.tags")), - "attributes_json": _json(attributes), - } - - -def _card_sets(battle: tuple[Any, ...] | None) -> dict[str, tuple[Any, ...]]: - if battle is None or battle[3] is None: - return {} - snapshots = _slots(battle[3], 1, "battle.snapshots") - result: dict[str, tuple[Any, ...]] = {} - duplicates: set[str] = set() - for raw in _array(snapshots[0], "battle.card_sets"): - value = _slots(raw, 4, "battle.card_set") - label = _text(value[0], "card_set.label") - if label in result: - duplicates.add(label) - result[label] = value - for label in duplicates: - result.pop(label, None) - return result - - -def _card_signature(battle: tuple[Any, ...] | None, label: str) -> str | None: - card_set = _card_sets(battle).get(label) - if card_set is None or (_nullable_text(card_set[1], "status") or "").lower() == "missing": - return None - templates = [ - _text(_slots(card, 11, "card")[1], "card.template_id") - for card in _array(card_set[3], "cards") - ] - if not templates: - return None - return hashlib.sha256(_json(templates).encode()).hexdigest() - - -def _replay_available(battle: tuple[Any, ...], replayable_ids: Sequence[str]) -> bool: - battle_id = _text(battle[0], "battle_id") - if battle_id not in replayable_ids or battle[3] is None or battle[4] is None: - return False - replay = _slots(battle[4], 4, "battle.replay") - if not all(isinstance(value, bytes) and value for value in replay[1:]): - return False - sets = _card_sets(battle) - required = {"player_hand", "player_skills", "opponent_hand", "opponent_skills"} - return set(sets) == required and all( - (_nullable_text(value[1], "card_set.status") or "").lower() != "missing" - for value in sets.values() - ) - - -def _quality_rows( - base: Mapping[str, object], - run: Mapping[str, object], - battle_summary: _BattleSummary, - battles: Sequence[tuple[Any, ...]], - replayable_ids: Sequence[str], - degradation: tuple[Any, ...], -) -> list[dict[str, object]]: - findings: dict[str, dict[str, object]] = {} - payload_ids = {_text(battle[0], "battle_id") for battle in battles} - if not set(replayable_ids).issubset(payload_ids): - findings["run_battle_count_mismatch"] = {} - wins = battle_summary.wins - losses = battle_summary.losses - if ( - run["victories"] is not None - and run["losses"] is not None - and (run["victories"] != wins or run["losses"] != losses) - ): - findings["run_outcome_count_mismatch"] = { - "run_victories": run["victories"], - "run_losses": run["losses"], - "battle_wins": wins, - "battle_losses": losses, - } - finals = [battle for battle in battles if _slots(battle[1], 9, "facts")[8] is True] - if not finals: - findings["final_battle_missing"] = {} - elif len(finals) > 1: - findings["multiple_final_battles"] = {"count": len(finals)} - elif _card_signature(finals[0], "player_hand") is None: - findings["final_player_hand_missing"] = {} - heroes = {run["hero"]} | set(battle_summary.heroes) - unknown_heroes = sorted(str(value) for value in heroes if value not in CANONICAL_HEROES) - if unknown_heroes: - findings["unknown_hero"] = {"values": unknown_heroes} - ranks = {run["initial_rank"], run["final_rank"]} | set(battle_summary.ranks) - unknown_ranks = sorted( - str(value) for value in ranks if value is not None and value not in CANONICAL_RANKS - ) - if unknown_ranks: - findings["unknown_rank"] = {"values": unknown_ranks} - available = datetime.fromtimestamp( - _integer(base["available_at_ms"], "available_at_ms") / 1_000, - tz=UTC, - ) - observed = [ - datetime.fromtimestamp( - _integer(run["client_created_at_ms"], "client_created_at_ms") / 1_000, - tz=UTC, - ), - *filter( - None, - [_parse_time(run["started_at_utc"]), _parse_time(run["ended_at_utc"])], - ), - ] - if battle_summary.recorded_in_future or any(value > available for value in observed): - findings["client_clock_future"] = {} - if battle_summary.recorded_before_run: - findings["client_clock_before_run"] = {} - if _array(degradation[1], "degradation.replays"): - findings["degraded_replay"] = {} - if _integer(degradation[2], "degradation.events"): - findings["degraded_events"] = {} - if _boolean(degradation[3], "degradation.screenshot"): - findings["degraded_screenshot"] = {} - return [ - { - "source_hour": base["source_hour"], - "source_day": base["source_day"], - "bundle_id": base["bundle_id"], - "run_id": base["run_id"], - "code": code, - "severity": "WARN", - "blocks_release": False, - "detail_json": _json(detail), - } - for code, detail in sorted(findings.items()) - ] - - -def _quarantine_row( - hour: str, - day: str, - bundle_id: str, - run_id: str | None, - stage: str, - reason: str, - first_seen: str, - *, - raw_run: bool = False, - discarded_unknown_hero: bool = False, - discarded_unknown_final_rank: bool = False, - detail: Mapping[str, object] | None = None, -) -> dict[str, object]: - return { - "source_hour": hour, - "source_day": day, - "bundle_id": bundle_id, - "run_id": run_id, - "stage": stage, - "reason_code": reason, - "raw_run": raw_run, - "discarded_unknown_hero": discarded_unknown_hero, - "discarded_unknown_final_rank": discarded_unknown_final_rank, - "first_seen_at": first_seen, - "decoder_code_version": PROJECTION_VERSION, - "diagnostic_json": _json({"reason": reason, **(detail or {})}), - } - - -def decode_run_payload(content: bytes) -> tuple[Any, ...]: - if len(content) < 2 or content[:2] != b"\x1f\x8b": - raise RunPayloadError("run_payload_not_gzip", "Run payload is not gzip") - output = bytearray() - try: - with gzip.GzipFile(fileobj=BytesIO(content), mode="rb") as stream: - while True: - chunk = stream.read(min(64 * 1024, MAX_DECOMPRESSED_RUN_BYTES - len(output) + 1)) - if not chunk: - break - output.extend(chunk) - if len(output) > MAX_DECOMPRESSED_RUN_BYTES: - raise RunPayloadError( - "run_payload_decompressed_too_large", "Run payload is too large" - ) - except RunPayloadError: - raise - except (EOFError, OSError) as error: - raise RunPayloadError("run_payload_decode_failed", "Run gzip is invalid") from error - try: - decoded = _MessagePack(bytes(output)).unpack() - root = _slots(decoded, 8, "payload") - except (ValueError, TypeError, struct.error) as error: - raise RunPayloadError("run_payload_decode_failed", "Run MessagePack is invalid") from error - version = _integer(root[0], "payload.version") - if version != 6: - raise RunPayloadError("payload_version_unsupported", "Run version is unsupported") - return _v6_times_as_text(root) - - -_UNIX_EPOCH = datetime(1970, 1, 1, tzinfo=UTC) - - -def _v6_times_as_text(root: tuple[Any, ...]) -> tuple[Any, ...]: - """Return a V6 root whose time slots hold UTC text. - - V6 carries Run start/end and Battle record times as Unix milliseconds; the fact - columns store them as millisecond-precision text (``*_at_utc``). - """ - try: - run = _with_slot(root[3], 22, "run", 3, _ms_text) - run = _with_slot( - run, 22, "run", 4, lambda value: None if value is None else _ms_text(value) - ) - battles = [ - _with_slot( - battle, - 5, - "battle", - 1, - lambda facts: _with_slot(facts, 9, "battle.facts", 0, _ms_text), - ) - for battle in _array(root[5], "payload.battles") - ] - except (ValueError, TypeError, OverflowError) as error: - raise RunPayloadError("run_payload_decode_failed", "Run V6 times are invalid") from error - return (*root[:3], run, root[4], battles, *root[6:]) - - -def _with_slot( - value: object, count: int, field: str, index: int, convert: Callable[[Any], object] -) -> tuple[Any, ...]: - slots = list(_slots(value, count, field)) - slots[index] = convert(slots[index]) - return tuple(slots) - - -def _ms_text(value: object) -> str: - milliseconds = _integer(value, "time_ms") - instant = _UNIX_EPOCH + timedelta(milliseconds=milliseconds) - return instant.isoformat(timespec="milliseconds").replace("+00:00", "Z") - - -class _MessagePack: - """Small strict decoder for the scalar/array/map subset used by RunPayload V6.""" - - def __init__(self, content: bytes) -> None: - self._content = content - self._offset = 0 - - def unpack(self) -> object: - value = self._one() - if self._offset != len(self._content): - raise ValueError("trailing MessagePack bytes") - return value - - def _take(self, count: int) -> bytes: - end = self._offset + count - if end > len(self._content): - raise ValueError("truncated MessagePack") - value = self._content[self._offset : end] - self._offset = end - return value - - def _number(self, fmt: str) -> int | float: - return cast(int | float, struct.unpack(fmt, self._take(struct.calcsize(fmt)))[0]) - - def _one(self) -> object: - marker = self._take(1)[0] - if marker <= 0x7F: - return marker - if marker >= 0xE0: - return marker - 256 - if 0xA0 <= marker <= 0xBF: - return self._take(marker & 0x1F).decode("utf-8") - if 0x90 <= marker <= 0x9F: - return [self._one() for _ in range(marker & 0x0F)] - if 0x80 <= marker <= 0x8F: - return {self._one(): self._one() for _ in range(marker & 0x0F)} - if marker == 0xC0: - return None - if marker in {0xC2, 0xC3}: - return marker == 0xC3 - if marker in {0xC4, 0xC5, 0xC6}: - size = int(self._number({0xC4: ">B", 0xC5: ">H", 0xC6: ">I"}[marker])) - return self._take(size) - if marker in {0xCA, 0xCB}: - return self._number(">f" if marker == 0xCA else ">d") - if marker in {0xCC, 0xCD, 0xCE, 0xCF}: - return self._number({0xCC: ">B", 0xCD: ">H", 0xCE: ">I", 0xCF: ">Q"}[marker]) - if marker in {0xD0, 0xD1, 0xD2, 0xD3}: - return self._number({0xD0: ">b", 0xD1: ">h", 0xD2: ">i", 0xD3: ">q"}[marker]) - if marker in {0xD9, 0xDA, 0xDB}: - size = int(self._number({0xD9: ">B", 0xDA: ">H", 0xDB: ">I"}[marker])) - return self._take(size).decode("utf-8") - if marker in {0xDC, 0xDD}: - size = int(self._number(">H" if marker == 0xDC else ">I")) - return [self._one() for _ in range(size)] - if marker in {0xDE, 0xDF}: - size = int(self._number(">H" if marker == 0xDE else ">I")) - return {self._one(): self._one() for _ in range(size)} - raise ValueError(f"unsupported MessagePack marker: {marker:#x}") - - -def _slots(value: object, count: int, field: str) -> tuple[Any, ...]: - if isinstance(value, (list, tuple)) and len(value) >= count: - return tuple(value) - if isinstance(value, dict): - try: - return tuple( - value[index] if index in value else value[str(index)] for index in range(count) - ) - except KeyError as error: - raise ValueError(f"{field} omits a numeric field") from error - raise ValueError(f"{field} must be a numeric-key array or map") - - -def _array(value: object, field: str) -> list[Any]: - if not isinstance(value, (list, tuple)): - raise ValueError(f"{field} must be an array") - return list(value) - - -def _object(value: object, field: str) -> Mapping[Any, Any]: - if not isinstance(value, dict): - raise ValueError(f"{field} must be an object") - return value - - -def _text(value: object, field: str) -> str: - if not isinstance(value, str): - raise ValueError(f"{field} must be a string") - return value - - -def _nullable_text(value: object, field: str) -> str | None: - return None if value is None else _text(value, field) - - -def _integer(value: object, field: str) -> int: - if not isinstance(value, int) or isinstance(value, bool): - raise ValueError(f"{field} must be an integer") - return value - - -def _nullable_integer(value: object, field: str) -> int | None: - return None if value is None else _integer(value, field) - - -def _boolean(value: object, field: str) -> bool: - if not isinstance(value, bool): - raise ValueError(f"{field} must be boolean") - return value - - -def _parse_time(value: object) -> datetime | None: - if not isinstance(value, str): - return None - try: - parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) - except ValueError: - return None - if parsed.tzinfo is None or parsed.utcoffset() is None: - return None - return parsed.astimezone(UTC) - - -def _json(value: object) -> str: - return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) diff --git a/bazaarplusplus-analyzer/src/bppanalyzer/publication.py b/bazaarplusplus-analyzer/src/bppanalyzer/publication.py deleted file mode 100644 index 18f1f63..0000000 --- a/bazaarplusplus-analyzer/src/bppanalyzer/publication.py +++ /dev/null @@ -1,776 +0,0 @@ -"""Build and atomically replace the two Analyzer consumer snapshots.""" - -import hashlib -import json -import math -from collections.abc import Callable, Iterable, Mapping -from dataclasses import dataclass -from datetime import UTC, date, datetime, timedelta -from pathlib import Path -from typing import Any - -import duckdb -from jsonschema import Draft202012Validator - -from bppanalyzer.accepted_runs import CANONICAL_HEROES, LEGEND_RANK -from bppanalyzer.durable import canonical_json, utc_timestamp -from bppanalyzer.fact_store import DaySeal, FactStore, parse_source_day -from bppanalyzer.object_store import ObjectStore - -ANALYSIS_DAYS = 7 -CORE_BUILD_LIMIT_PER_HERO = 500 -WILSON_Z = 1.96 -HEROES_KEY = "heroes/latest.json" -BUILDS_KEY = "builds/latest.json" -SEGMENTS = ("legend", "non_legend") -TIERS = ("bronze", "silver", "gold", "diamond", "legendary") -LATEST_CACHE_CONTROL = "public,max-age=60,must-revalidate" -JSON_CONTENT_TYPE = "application/json" - - -class PublicationError(RuntimeError): - """A consumer snapshot could not be built or published safely.""" - - -class AnalysisWindowError(PublicationError): - """Complete Source Day seals cannot form an Analysis Window.""" - - -class ContractViolation(PublicationError): - """A consumer snapshot violates its schema or semantic invariants.""" - - -@dataclass(frozen=True, slots=True) -class AnalysisWindow: - seals: tuple[DaySeal, ...] - start: date - end: date - - @property - def value(self) -> dict[str, object]: - return { - "start": self.start.isoformat(), - "end": self.end.isoformat(), - "days": len(self.seals), - } - - -@dataclass(frozen=True, slots=True) -class HeroStats: - participating_runs: int - participating_matchup_battles: int - - -@dataclass(frozen=True, slots=True) -class BuildStats: - eligible_layout_runs: int - candidate_builds: int - published_builds: int - - -@dataclass(frozen=True, slots=True) -class FactStats: - raw_runs: int - discarded_unknown_hero: int - discarded_unknown_final_rank: int - included_runs: int - included_battles: int - - -@dataclass(frozen=True, slots=True) -class BuildRank: - identity: tuple[str, ...] - score: int - ten_win: int - p75: int | None - - -@dataclass(frozen=True, slots=True) -class BuiltSnapshot: - product: str - key: str - content: bytes - stats: HeroStats | BuildStats - - -def select_analysis_window( - seals: Iterable[DaySeal], - anchor_day: date | str | None = None, - *, - source_epoch: date | str | None = None, -) -> AnalysisWindow | None: - """Return one to seven latest consecutive verified day seals.""" - epoch = parse_source_day(source_epoch) if source_epoch is not None else None - by_day: dict[date, DaySeal] = {} - for seal in seals: - day = parse_source_day(seal.source_day) - if epoch is not None and day < epoch: - continue - if day in by_day: - raise AnalysisWindowError(f"Duplicate Complete Source Day: {day.isoformat()}") - by_day[day] = seal - if not by_day: - return None - anchor = parse_source_day(anchor_day) if anchor_day is not None else max(by_day) - if (epoch is not None and anchor < epoch) or anchor not in by_day: - return None - descending = [] - for offset in range(ANALYSIS_DAYS): - candidate = anchor - timedelta(days=offset) - if candidate not in by_day: - break - descending.append(candidate) - days = tuple(reversed(descending)) - selected = tuple(by_day[day] for day in days) - return AnalysisWindow(selected, days[0], days[-1]) - - -def wilson_score(successes: int, total: int) -> int: - if total <= 0: - return 0 - proportion = successes / total - z_squared = WILSON_Z * WILSON_Z - lower = ( - proportion - + z_squared / (2 * total) - - WILSON_Z - * math.sqrt(proportion * (1 - proportion) / total + z_squared / (4 * total * total)) - ) / (1 + z_squared / total) - return math.floor(lower * 1_000_000 + 0.5) - - -class SnapshotBuilder: - def __init__( - self, - data_root: str | Path, - *, - store: FactStore, - clock: Callable[[], datetime] = lambda: datetime.now(UTC), - memory_limit: str, - threads: int, - ) -> None: - self.root = Path(data_root) - self.store = store - self.clock = clock - self.memory_limit = memory_limit - self.threads = threads - - def build_heroes(self, window: AnalysisWindow) -> BuiltSnapshot: - connection = self._connection(window, ("runs", "battles")) - try: - run_rows = connection.execute( - """ - SELECT source_day, hero, segment, - count(*) AS completed, - count(*) FILTER ( - WHERE victories BETWEEN 0 AND 10 AND losses >= 0 - ) AS scored, - count(*) FILTER (WHERE victories=10 AND losses >= 0) AS ten_win, - count(*) FILTER (WHERE victories=10 AND losses=0) AS perfect, - count(*) FILTER (WHERE victories=10 AND losses >= 1) AS gold, - count(*) FILTER (WHERE victories BETWEEN 7 AND 9 AND losses >= 0) AS silver, - count(*) FILTER (WHERE victories BETWEEN 4 AND 6 AND losses >= 0) AS bronze, - count(*) FILTER ( - WHERE victories=10 AND losses >= 0 AND run_day >= 0 - ) AS known_count, - coalesce(sum(run_day) FILTER ( - WHERE victories=10 AND losses >= 0 AND run_day >= 0 - ), 0) AS sum_days - FROM completed_runs - GROUP BY source_day, hero, segment - ORDER BY source_day DESC, hero, segment - """ - ).fetchall() - matchup_rows = connection.execute( - f""" - SELECT r.source_day, r.hero, r.segment, b.opponent_hero, - count(*) AS decided, - count(*) FILTER (WHERE b.winner_side='player') AS wins, - count(*) FILTER (WHERE b.winner_side='opponent') AS losses - FROM battles_fact b - JOIN completed_runs r - ON r.bundle_id=b.bundle_id AND r.run_id=b.run_id - WHERE b.winner_side IN ('player','opponent') - AND b.opponent_hero IN ({_sql_list(CANONICAL_HEROES)}) - GROUP BY r.source_day, r.hero, r.segment, b.opponent_hero - ORDER BY r.source_day DESC, r.hero, r.segment, b.opponent_hero - """ - ).fetchall() - finally: - connection.close() - - runs = { - (str(row[0]), str(row[1]), str(row[2])): tuple(int(value) for value in row[3:]) - for row in run_rows - } - matchups: dict[tuple[str, str, str], list[dict[str, object]]] = {} - for day, hero, segment, opponent, decided, wins, losses in matchup_rows: - matchups.setdefault((str(day), str(hero), str(segment)), []).append( - { - "opponent_hero": str(opponent), - "decided": int(decided), - "wins": int(wins), - "losses": int(losses), - } - ) - - days = [] - for day in reversed(tuple(seal.source_day for seal in window.seals)): - rows = [] - for hero in CANONICAL_HEROES: - for segment in SEGMENTS: - values = runs.get((day, hero, segment), (0,) * 9) - rows.append( - { - "hero": hero, - "segment": segment, - "runs": { - "completed": values[0], - "scored": values[1], - "ten_win": values[2], - }, - "outcomes": { - "perfect": values[3], - "gold": values[4], - "silver": values[5], - "bronze": values[6], - }, - "ten_win_days": { - "known_count": values[7], - "sum_days": values[8], - }, - "matchups": matchups.get((day, hero, segment), []), - } - ) - days.append({"day": day, "rows": rows}) - payload = { - "schema_version": 1, - "kind": "hero_metrics", - "generated_at": utc_timestamp(self.clock()), - "window": window.value, - "days": days, - } - validate_snapshot(HEROES.name, payload) - content = canonical_json(payload) - return BuiltSnapshot( - HEROES.name, - HEROES.public_key, - content, - HeroStats( - participating_runs=sum(values[0] for values in runs.values()), - participating_matchup_battles=sum(int(item[4]) for item in matchup_rows), - ), - ) - - def fact_stats(self, window: AnalysisWindow) -> FactStats: - connection = self._connection(window, ("runs", "battles", "quarantine")) - try: - included_runs = int( - _required_row( - connection.execute("SELECT count(*) FROM runs_fact").fetchone(), - "Included Run count", - )[0] - ) - discarded = _required_row( - connection.execute( - """ - SELECT count(*) FILTER (WHERE coalesce(raw_run, false)), - count(*) FILTER (WHERE coalesce(discarded_unknown_hero, false)), - count(*) FILTER (WHERE coalesce(discarded_unknown_final_rank, false)) - FROM quarantine_fact - """ - ).fetchone(), - "Discarded Run counts", - ) - included_battles = int( - _required_row( - connection.execute( - """ - SELECT count(*) FROM battles_fact b - JOIN runs_fact r - ON r.bundle_id=b.bundle_id AND r.run_id=b.run_id - """ - ).fetchone(), - "Included Battle count", - )[0] - ) - finally: - connection.close() - return FactStats( - raw_runs=included_runs + int(discarded[0]), - discarded_unknown_hero=int(discarded[1]), - discarded_unknown_final_rank=int(discarded[2]), - included_runs=included_runs, - included_battles=included_battles, - ) - - def build_builds(self, window: AnalysisWindow) -> BuiltSnapshot: - connection = self._connection(window, ("runs", "battles", "battle_cards")) - try: - connection.execute( - f""" - CREATE TEMP TABLE eligible_layout_runs AS - WITH final_battles AS ( - SELECT r.bundle_id, r.run_id, r.source_day, r.hero, - r.victories, r.losses, r.run_day, r.final_battle_id - FROM completed_runs r - JOIN battles_fact b - ON b.bundle_id=r.bundle_id AND b.run_id=r.run_id - GROUP BY ALL - HAVING count(*) FILTER (WHERE b.is_final_battle)=1 - AND min(b.battle_id) FILTER (WHERE b.is_final_battle)=r.final_battle_id - ), layouts AS ( - SELECT f.bundle_id, f.run_id, f.source_day, f.hero, - f.victories, f.losses, f.run_day, f.final_battle_id, - string_agg(lower(c.template_id), '|' ORDER BY lower(c.template_id)) - AS build_key, - to_json(list(struct_pack( - template_id := lower(c.template_id), - slot := coalesce(c.socket,c.slot_index), - tier := c.tier, - enchantment := CASE - WHEN c.enchantment IS NULL - OR lower(trim(c.enchantment)) IN ('','none') THEN NULL - ELSE trim(c.enchantment) - END, - size := c.size - ) ORDER BY coalesce(c.socket,c.slot_index), lower(c.template_id), - coalesce(c.tier,''), coalesce(c.enchantment,''), c.size)) - AS layout_json - FROM final_battles f - JOIN completed_runs r - ON r.bundle_id=f.bundle_id AND r.run_id=f.run_id - JOIN battle_cards_fact c - ON c.bundle_id=f.bundle_id AND c.run_id=f.run_id - AND c.battle_id=f.final_battle_id - WHERE c.card_set_label='player_hand' - AND c.owner_side='player' AND c.card_kind='item' - -- Socket-effect overlays (e.g. Jules cooler/heater sockets, - -- card_type 7) share sockets with real items and are not - -- part of the board. - AND coalesce(c.card_type, 0)=0 - AND r.final_player_item_signature IS NOT NULL - GROUP BY f.bundle_id, f.run_id, f.source_day, f.hero, - f.victories, f.losses, f.run_day, f.final_battle_id - HAVING count(*) > 0 - AND bool_and(lower(trim(coalesce(c.card_set_status,'missing')))<>'missing') - AND bool_and(c.template_id IS NOT NULL AND regexp_full_match( - lower(c.template_id), - '^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$' - )) - AND bool_and(c.size IS NOT NULL AND c.size BETWEEN 1 AND 3) - AND bool_and(c.tier IS NOT NULL AND lower(trim(c.tier)) IN ({_sql_list(TIERS)})) - AND sum(c.size)=10 - AND bool_and(coalesce(c.socket,c.slot_index) IS NOT NULL - AND coalesce(c.socket,c.slot_index) >= 0 - AND coalesce(c.socket,c.slot_index) + c.size <= 10) - AND bit_or( - ((1::BIGINT << c.size) - 1) - << coalesce(c.socket,c.slot_index) - ) = 1023 - ) - SELECT *, victories=10 AND losses >= 0 AS ten_win - FROM layouts - """ - ) - eligible_count = int( - _required_row( - connection.execute("SELECT count(*) FROM eligible_layout_runs").fetchone(), - "Eligible layout count", - )[0] - ) - candidate_rows = connection.execute( - """ - WITH candidates AS ( - SELECT hero, build_key, count(*) AS completed, - count(*) FILTER (WHERE ten_win) AS ten_win_count, - list(run_day ORDER BY run_day) FILTER ( - WHERE ten_win AND run_day >= 0 - ) AS known_days - FROM eligible_layout_runs - GROUP BY hero, build_key - HAVING count(*) FILTER (WHERE ten_win) >= 1 - ), layout_counts AS ( - SELECT hero, build_key, layout_json, count(*) AS observations - FROM eligible_layout_runs - WHERE ten_win - GROUP BY hero, build_key, layout_json - ), representatives AS ( - SELECT hero, build_key, layout_json, - row_number() OVER ( - PARTITION BY hero, build_key - ORDER BY observations DESC, layout_json ASC - ) AS layout_rank - FROM layout_counts - ) - SELECT c.hero, c.build_key, c.completed, c.ten_win_count, - c.known_days, r.layout_json - FROM candidates c - JOIN representatives r USING (hero, build_key) - WHERE r.layout_rank=1 - ORDER BY c.hero, c.build_key - """ - ).fetchall() - finally: - connection.close() - - candidates_by_hero: dict[str, list[dict[str, Any]]] = { - hero: [] for hero in CANONICAL_HEROES - } - for hero, build_key, completed, ten_win, known_days, layout_json in candidate_rows: - days = [int(value) for value in known_days] if known_days is not None else [] - p75 = days[math.ceil(0.75 * len(days)) - 1] if days else None - candidate = { - "identity": tuple(str(build_key).split("|")), - "completed": int(completed), - "ten_win": int(ten_win), - "p75": p75, - "score": wilson_score(int(ten_win), int(completed)), - "layout": json.loads(str(layout_json)), - } - candidates_by_hero[str(hero)].append(candidate) - - selected_by_hero: dict[str, list[dict[str, Any]]] = {} - for hero, candidates in candidates_by_hero.items(): - selected_identities = select_build_identities( - BuildRank( - identity=candidate["identity"], - score=candidate["score"], - ten_win=candidate["ten_win"], - p75=candidate["p75"], - ) - for candidate in candidates - ) - by_identity = {candidate["identity"]: candidate for candidate in candidates} - selected_by_hero[hero] = [by_identity[identity] for identity in selected_identities] - - cards = sorted( - { - card - for candidates in selected_by_hero.values() - for candidate in candidates - for card in candidate["identity"] - } - ) - card_ref = {card: index for index, card in enumerate(cards)} - enchantment_names = sorted( - { - str(item["enchantment"]) - for candidates in selected_by_hero.values() - for candidate in candidates - for item in candidate["layout"] - if item["enchantment"] is not None - } - ) - enchantments: list[str | None] = [None, *enchantment_names] - enchant_ref = {name: index + 1 for index, name in enumerate(enchantment_names)} - heroes: dict[str, dict[str, object]] = {} - for hero in CANONICAL_HEROES: - selected = selected_by_hero[hero] - builds = [ - _build_row(candidate, card_ref=card_ref, enchant_ref=enchant_ref) - for candidate in selected - ] - index: dict[int, list[int]] = {} - for build_id, candidate in enumerate(selected): - for card in sorted(set(candidate["identity"])): - index.setdefault(card_ref[card], []).append(build_id) - heroes[hero] = { - "builds": builds, - "card_index": [[ref, index[ref]] for ref in sorted(index)], - } - payload = { - "schema_version": 2, - "kind": "ten_win_builds", - "generated_at": utc_timestamp(self.clock()), - "window": window.value, - "cards": cards, - "enchantments": enchantments, - "schemas": { - "build": ["card_refs", "layout", "stats"], - "layout": ["card_ref", "slot", "tier", "enchant_ref", "size"], - "stats": [ - "completed_run_count", - "ten_win_run_count", - "ten_win_rate_bps", - "p75_ten_win_final_day", - "score", - ], - }, - "heroes": heroes, - } - validate_snapshot(BUILDS.name, payload) - content = canonical_json(payload) - return BuiltSnapshot( - BUILDS.name, - BUILDS.public_key, - content, - BuildStats( - eligible_layout_runs=eligible_count, - candidate_builds=len(candidate_rows), - published_builds=sum(len(value) for value in selected_by_hero.values()), - ), - ) - - def _connection( - self, window: AnalysisWindow, tables: tuple[str, ...] - ) -> duckdb.DuckDBPyConnection: - if not isinstance(self.threads, int) or isinstance(self.threads, bool) or self.threads < 1: - raise ValueError("DuckDB threads must be a positive integer") - connection = duckdb.connect(database=":memory:") - try: - connection.execute(f"SET memory_limit={_sql_string(self.memory_limit)}") - connection.execute(f"SET threads={self.threads}") - temporary = self.root / "duckdb-tmp" - temporary.mkdir(parents=True, exist_ok=True) - connection.execute(f"SET temp_directory={_sql_string(str(temporary))}") - paths = self.store.hour_paths(seal.source_day for seal in window.seals) - for table in tables: - explicit = ",".join(_sql_string(str(path)) for path in paths[table]) - connection.execute( - f"CREATE TEMP VIEW {table}_fact AS " - f"SELECT * FROM read_parquet([{explicit}], hive_partitioning=false)" - ) - # Projection stores only Accepted Runs with normalized hero, final rank, - # and Battle winner side, so analysis reads those columns as stored. - connection.execute( - "CREATE TEMP VIEW completed_runs AS SELECT *, " - f"CASE WHEN final_rank={_sql_string(LEGEND_RANK)} THEN 'legend' " - "ELSE 'non_legend' END AS segment " - "FROM runs_fact WHERE lower(trim(status))='completed'" - ) - return connection - except BaseException: - connection.close() - raise - - -class LatestPublisher: - def __init__(self, object_store: ObjectStore) -> None: - self.object_store = object_store - - def replace(self, snapshot: BuiltSnapshot) -> bool: - product = _PRODUCTS_BY_NAME.get(snapshot.product) - if product is None or snapshot.key != product.public_key: - raise ContractViolation("Snapshot product and public key disagree") - digest = hashlib.sha256(snapshot.content).hexdigest() - observed = self.object_store.stat(snapshot.key) - if ( - observed is not None - and observed.sha256 == digest - and observed.bytes == len(snapshot.content) - and observed.cache_control == LATEST_CACHE_CONTROL - and observed.content_type == JSON_CONTENT_TYPE - ): - return False - self.object_store.put( - snapshot.key, - snapshot.content, - cache_control=LATEST_CACHE_CONTROL, - content_type=JSON_CONTENT_TYPE, - ) - confirmed = self.object_store.get(snapshot.key) - if ( - confirmed is None - or confirmed.body != snapshot.content - or confirmed.stat.cache_control != LATEST_CACHE_CONTROL - or confirmed.stat.content_type != JSON_CONTENT_TYPE - ): - raise PublicationError(f"Published snapshot did not confirm: {snapshot.key}") - return True - - -def validate_snapshot(name: str, payload: Mapping[str, Any]) -> None: - product = _PRODUCTS_BY_NAME.get(name) - if product is None: - raise ValueError(f"Unknown consumer product: {name}") - schema_path = _contracts_dir() / product.schema_file - try: - schema = json.loads(schema_path.read_bytes()) - Draft202012Validator(schema).validate(payload) - except Exception as error: - raise ContractViolation(f"{name} snapshot failed JSON Schema validation") from error - window = payload["window"] - start = parse_source_day(window["start"]) - end = parse_source_day(window["end"]) - window_days = int(window["days"]) - if not 1 <= window_days <= ANALYSIS_DAYS or end - start != timedelta(days=window_days - 1): - raise ContractViolation("Analysis Window must contain one to seven consecutive days") - product.validate_semantics(payload, start, end, window_days) - - -def _validate_heroes(payload: Mapping[str, Any], start: date, end: date, window_days: int) -> None: - days = payload["days"] - expected_days = [(end - timedelta(days=offset)).isoformat() for offset in range(window_days)] - if [item["day"] for item in days] != expected_days or expected_days[-1] != start.isoformat(): - raise ContractViolation("Hero days must be newest-first and match the Analysis Window") - expected_rows = [(hero, segment) for hero in CANONICAL_HEROES for segment in SEGMENTS] - for day in days: - rows = day["rows"] - if [(row["hero"], row["segment"]) for row in rows] != expected_rows: - raise ContractViolation("Every hero day must contain the stable canonical row set") - for row in rows: - runs = row["runs"] - outcomes = row["outcomes"] - ten_win_days = row["ten_win_days"] - if runs["ten_win"] != outcomes["perfect"] + outcomes["gold"]: - raise ContractViolation("Ten-Win Runs must equal perfect plus gold") - if sum(outcomes.values()) > runs["scored"] or runs["scored"] > runs["completed"]: - raise ContractViolation("Hero outcome denominators are inconsistent") - if ten_win_days["known_count"] > runs["ten_win"]: - raise ContractViolation("Known Ten-Win final days exceed Ten-Win Runs") - for matchup in row["matchups"]: - if matchup["decided"] != matchup["wins"] + matchup["losses"]: - raise ContractViolation("Matchup decided count differs from wins plus losses") - - -def _validate_builds(payload: Mapping[str, Any]) -> None: - if list(payload["heroes"]) != list(CANONICAL_HEROES): - raise ContractViolation("Build heroes must be the ordered canonical hero object") - cards = payload["cards"] - enchantments = payload["enchantments"] - if cards != sorted(set(cards)): - raise ContractViolation("Card table must be uniquely and deterministically sorted") - if ( - not enchantments - or enchantments[0] is not None - or enchantments[1:] != sorted(set(enchantments[1:])) - ): - raise ContractViolation("Enchantment table must start with null and be sorted") - for hero in CANONICAL_HEROES: - value = payload["heroes"][hero] - expected_index: dict[int, list[int]] = {} - for build_id, build in enumerate(value["builds"]): - card_refs, layout, _stats = build - if any(ref >= len(cards) for ref in card_refs): - raise ContractViolation("Build references an unknown card") - layout_refs = [item[0] for item in layout] - if card_refs != sorted(layout_refs) or sum(item[4] for item in layout) != 10: - raise ContractViolation("Build Identity and complete layout disagree") - for item in layout: - if item[0] >= len(cards) or item[3] >= len(enchantments): - raise ContractViolation("Build layout references an unknown table row") - for ref in sorted(set(card_refs)): - expected_index.setdefault(ref, []).append(build_id) - observed = [[ref, expected_index[ref]] for ref in sorted(expected_index)] - if value["card_index"] != observed: - raise ContractViolation("Builds and card_index must agree in both directions") - - -@dataclass(frozen=True, slots=True) -class ConsumerProduct: - """One consumer snapshot: its name, public object, contract, and local copy.""" - - name: str - public_key: str - schema_file: str - local_relpath: Path - build: Callable[[SnapshotBuilder, AnalysisWindow], BuiltSnapshot] - validate_semantics: Callable[[Mapping[str, Any], date, date, int], None] - stats_type: type[HeroStats] | type[BuildStats] - - -HEROES = ConsumerProduct( - name="heroes", - public_key=HEROES_KEY, - schema_file="heroes.schema.json", - local_relpath=Path("snapshots", "heroes", "latest.json"), - build=lambda builder, window: builder.build_heroes(window), - validate_semantics=_validate_heroes, - stats_type=HeroStats, -) -BUILDS = ConsumerProduct( - name="builds", - public_key=BUILDS_KEY, - schema_file="builds.schema.json", - local_relpath=Path("snapshots", "builds", "latest.json"), - build=lambda builder, window: builder.build_builds(window), - validate_semantics=lambda payload, _start, _end, _days: _validate_builds(payload), - stats_type=BuildStats, -) -PRODUCTS = (HEROES, BUILDS) -_PRODUCTS_BY_NAME = {product.name: product for product in PRODUCTS} -_TIER_VALUES = {tier: rank for rank, tier in enumerate(TIERS, start=1)} - - -def _sql_string(value: str) -> str: - return "'" + value.replace("'", "''") + "'" - - -def _sql_list(values: Iterable[str]) -> str: - return ",".join(_sql_string(value) for value in values) - - -def _contracts_dir() -> Path: - return Path(__file__).resolve().parents[2] / "contracts" / "v6" - - -def _required_row(value: tuple[Any, ...] | None, label: str) -> tuple[Any, ...]: - if value is None: - raise PublicationError(f"{label} query returned no row") - return value - - -def select_build_identities(candidates: Iterable[BuildRank]) -> tuple[tuple[str, ...], ...]: - """Apply deterministic Top-500 ranking and uncovered-card backfill.""" - ranked = sorted( - candidates, - key=lambda candidate: ( - -candidate.score, - -candidate.ten_win, - candidate.p75 is None, - candidate.p75 if candidate.p75 is not None else 0, - candidate.identity, - ), - ) - selected = list(ranked[:CORE_BUILD_LIMIT_PER_HERO]) - selected_ids = {candidate.identity for candidate in selected} - candidate_cards = {card for candidate in ranked for card in candidate.identity} - covered = {card for candidate in selected for card in candidate.identity} - for card in sorted(candidate_cards - covered): - if card in covered: - continue - candidate = next(item for item in ranked if card in item.identity) - if candidate.identity not in selected_ids: - selected.append(candidate) - selected_ids.add(candidate.identity) - covered.update(candidate.identity) - return tuple(candidate.identity for candidate in selected) - - -def _build_row( - candidate: Mapping[str, Any], - *, - card_ref: Mapping[str, int], - enchant_ref: Mapping[str, int], -) -> list[object]: - layout = [ - [ - card_ref[str(item["template_id"])], - int(item["slot"]), - _tier_value(item["tier"]), - enchant_ref.get(item["enchantment"], 0), - int(item["size"]), - ] - for item in candidate["layout"] - ] - completed = int(candidate["completed"]) - ten_win = int(candidate["ten_win"]) - stats = [ - completed, - ten_win, - math.floor(ten_win * 10_000 / completed + 0.5), - candidate["p75"], - int(candidate["score"]), - ] - return [ - sorted(card_ref[str(card)] for card in candidate["identity"]), - layout, - stats, - ] - - -def _tier_value(value: object) -> int | None: - if not isinstance(value, str): - return None - return _TIER_VALUES.get(value.strip().lower()) diff --git a/bazaarplusplus-analyzer/tests/__init__.py b/bazaarplusplus-analyzer/tests/__init__.py deleted file mode 100644 index 8fb0865..0000000 --- a/bazaarplusplus-analyzer/tests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Test package and shared fixtures.""" diff --git a/bazaarplusplus-analyzer/tests/bundle_fixtures.py b/bazaarplusplus-analyzer/tests/bundle_fixtures.py deleted file mode 100644 index d04d431..0000000 --- a/bazaarplusplus-analyzer/tests/bundle_fixtures.py +++ /dev/null @@ -1,271 +0,0 @@ -import hashlib -import json -import struct -import zlib -from collections.abc import Sequence -from dataclasses import dataclass -from datetime import UTC, datetime - -SOURCE_HOUR = datetime(2026, 8, 10, 12, tzinfo=UTC) - - -def _msgpack(value: object) -> bytes: - if value is None: - return b"\xc0" - if value is False: - return b"\xc2" - if value is True: - return b"\xc3" - if isinstance(value, int): - if 0 <= value <= 127: - return bytes((value,)) - if -32 <= value < 0: - return bytes((256 + value,)) - if 0 <= value <= 0xFF: - return b"\xcc" + struct.pack(">B", value) - if 0 <= value <= 0xFFFF: - return b"\xcd" + struct.pack(">H", value) - if 0 <= value <= 0xFFFFFFFF: - return b"\xce" + struct.pack(">I", value) - return b"\xd3" + struct.pack(">q", value) - if isinstance(value, bytes): - if len(value) <= 0xFF: - return b"\xc4" + struct.pack(">B", len(value)) + value - return b"\xc5" + struct.pack(">H", len(value)) + value - if isinstance(value, str): - encoded = value.encode() - if len(encoded) < 32: - return bytes((0xA0 | len(encoded),)) + encoded - if len(encoded) <= 0xFF: - return b"\xd9" + struct.pack(">B", len(encoded)) + encoded - return b"\xda" + struct.pack(">H", len(encoded)) + encoded - if isinstance(value, list): - prefix = ( - bytes((0x90 | len(value),)) - if len(value) < 16 - else b"\xdc" + struct.pack(">H", len(value)) - ) - return prefix + b"".join(_msgpack(item) for item in value) - if isinstance(value, dict): - prefix = ( - bytes((0x80 | len(value),)) - if len(value) < 16 - else b"\xde" + struct.pack(">H", len(value)) - ) - return prefix + b"".join(_msgpack(key) + _msgpack(item) for key, item in value.items()) - raise TypeError(type(value).__name__) - - -@dataclass(frozen=True, slots=True) -class Card: - """One player-hand card; slot doubles as the Bundle ``socket``.""" - - template_id: str - size: int - slot: int - tier: str | None = "Gold" - enchantment: str | None = None - card_type: int = 0 - name: str = "Fixture Item" - - -def _default_cards(count: int) -> list[list[object]]: - return [ - [ - f"instance-{index + 1}", - "item-one", - 1, - 2, - 1, - 3, - "Item One", - "Gold", - None, - ["Weapon"], - {"damage": 12}, - ] - for index in range(count) - ] - - -def _card_row(index: int, card: Card) -> list[object]: - return [ - f"instance-{index + 1}", - card.template_id, - card.card_type, - card.size, - 1, - card.slot, - card.name, - card.tier, - card.enchantment, - ["Weapon"], - {}, - ] - - -def payload( - *, - run_id: str = "run-1", - account_id: str = "account-1", - hero: str = "Vanessa", - final_rank: str | None = "Legendary", - started_at: str = "2026-08-10T12:00:00Z", - battle_at: str = "2026-08-10T12:10:00Z", - ended_at: str = "2026-08-10T12:30:00Z", - winner_combatant_id: str | None = None, - loser_combatant_id: str | None = None, - victories: int = 10, - losses: int = 0, - run_day: int = 10, - cards_per_set: int = 1, - player_hand: Sequence[Card] | None = None, - player_hand_status: str = "Complete", - final_battles: int = 1, -) -> bytes: - """Encode one V6 Run payload; ``final_battles`` Battles are all flagged final. - - The instants are given as UTC text and encoded as Unix milliseconds. - """ - started_at, battle_at, ended_at = ( # type: ignore[assignment] - _unix_ms(value) for value in (started_at, battle_at, ended_at) - ) - player = [account_id, "Alice", hero, final_rank, 1100, 10, 2, 10, 8, 12, 1, 1] - opponent = ["account-2", "Bob", "Pygmalien", "Gold", 1050, 10, 2, 8, 8, 12, 1, 1] - cards = _default_cards(cards_per_set) - hand = ( - cards - if player_hand is None - else [_card_row(index, card) for index, card in enumerate(player_hand)] - ) - battles = [ - [ - battle_id, - [ - battle_at, - 10, - 2, - "encounter-1", - "PvP", - "Win", - winner_combatant_id or account_id, - loser_combatant_id or "account-2", - True, - ], - [player, opponent], - [ - [ - ["player_hand", player_hand_status, "capture", hand], - ["player_skills", "Complete", "capture", cards], - ["opponent_hand", "Complete", "capture", cards], - ["opponent_skills", "Complete", "capture", cards], - ] - ], - [1, b"spawn", b"combat", b"despawn"], - ] - for battle_id in battle_ids(final_battles) - ] - root = [ - 6, - run_id, - account_id, - [ - hero, - "Ranked", - 42, - started_at, - ended_at, - "completed", - run_day, - 2, - victories, - losses, - "Gold", - 1000, - final_rank, - 1100, - 100, - 50, - 2, - 10, - 8, - 12, - "stable", - "5.1.0", - ], - [], - battles, - ["battle-1"], - [[], [], 0, False], - ] - return _stored_gzip(_msgpack(root)) - - -def _unix_ms(value: str) -> int: - instant = datetime.fromisoformat(value.replace("Z", "+00:00")) - return int(instant.timestamp()) * 1_000 + instant.microsecond // 1_000 - - -def _stored_gzip(data: bytes) -> bytes: - """Gzip with uncompressed DEFLATE blocks. - - Compressed output differs between zlib builds; stored blocks keep fixture - Bundles, and every golden that hashes them, byte-identical on every platform. - """ - blocks = [] - for start in range(0, len(data), 0xFFFF): - chunk = data[start : start + 0xFFFF] - final = start + 0xFFFF >= len(data) - blocks.append(bytes((final,)) + struct.pack(" list[str]: - return [f"battle-{number}" for number in range(1, count + 1)] - - -def bundle_bytes( - bundle_id: str, - *, - run_payload: bytes | None = None, - created_at_ms: int | None = None, - run_id: str = "run-1", - account_id: str = "account-1", -) -> bytes: - """Wrap a Run payload whose identities match ``run_id`` and ``account_id``.""" - content = run_payload or payload() - manifest = { - "bundle_version": 6, - "bundle_id": bundle_id, - "created_at_ms": created_at_ms or int(SOURCE_HOUR.timestamp() * 1_000), - "run": { - "run_format_version": 6, - "run_id": run_id, - "player_account_id": account_id, - "projection": {"run": {}, "battles": [{"battle_id": "battle-1"}]}, - "payload": { - "offset": 0, - "length": len(content), - "sha256": hashlib.sha256(content).hexdigest(), - "content_type": "application/x-bpp-run-v6", - }, - }, - } - return envelope(manifest, content) - - -def envelope(manifest: dict[str, object], run_content: bytes, *, sort_keys: bool = False) -> bytes: - """Prefix ``manifest`` with the magic and version its ``bundle_version`` names.""" - version = manifest["bundle_version"] - assert isinstance(version, int) - encoded = json.dumps(manifest, sort_keys=sort_keys, separators=(",", ":")).encode() - return b"".join( - [ - f"BPPBNDL{version}".encode(), - version.to_bytes(4, "big"), - len(encoded).to_bytes(4, "big"), - encoded, - run_content, - ] - ) diff --git a/bazaarplusplus-analyzer/tests/conftest.py b/bazaarplusplus-analyzer/tests/conftest.py deleted file mode 100644 index 93b5cce..0000000 --- a/bazaarplusplus-analyzer/tests/conftest.py +++ /dev/null @@ -1,44 +0,0 @@ -import shutil -from datetime import date -from pathlib import Path - -import pytest - -from bppanalyzer.fact_store import FactStore -from tests.pipeline_fixtures import heal_from_bundles - -# Healing runs the production driver once per Source Day, so each sealed -# store is healed once per session and copied into the tests that use it. - - -@pytest.fixture(scope="session") -def _seven_sealed_days(tmp_path_factory: pytest.TempPathFactory) -> Path: - root = tmp_path_factory.mktemp("seven-sealed-days") / "root" - heal_from_bundles(root, 7) - return root - - -@pytest.fixture(scope="session") -def _nine_sealed_days(tmp_path_factory: pytest.TempPathFactory, _seven_sealed_days: Path) -> Path: - root = tmp_path_factory.mktemp("nine-sealed-days") / "root" - shutil.copytree(_seven_sealed_days, root) - heal_from_bundles(root, 2, start=date(2026, 8, 14)) - return root - - -@pytest.fixture(scope="session") -def canonical_fact_store( - tmp_path_factory: pytest.TempPathFactory, _seven_sealed_days: Path -) -> tuple[Path, FactStore]: - """Source Days 2026-08-07..13, shared by every test in the session.""" - root = tmp_path_factory.mktemp("canonical-facts") / "root" - shutil.copytree(_seven_sealed_days, root) - return root, FactStore(root) - - -@pytest.fixture -def nine_sealed_days(tmp_path: Path, _nine_sealed_days: Path) -> Path: - """A private copy of Source Days 2026-08-07..15.""" - root = tmp_path / "facts" - shutil.copytree(_nine_sealed_days, root) - return root diff --git a/bazaarplusplus-analyzer/tests/fakes.py b/bazaarplusplus-analyzer/tests/fakes.py deleted file mode 100644 index c8f6e7c..0000000 --- a/bazaarplusplus-analyzer/tests/fakes.py +++ /dev/null @@ -1,70 +0,0 @@ -import hashlib -from collections.abc import Iterator -from datetime import UTC, datetime - -import pyarrow as pa - -from bppanalyzer.object_store import ObjectStat, StoredObject -from bppanalyzer.projection import HourProjection, table_schemas - - -class MemoryObjectStore: - """Dict-backed ``ObjectStore`` that records every request in order.""" - - def __init__(self) -> None: - self.objects: dict[str, StoredObject] = {} - self.requests: list[tuple[str, str]] = [] - - def stat(self, key: str) -> ObjectStat | None: - self.requests.append(("stat", key)) - stored = self.objects.get(key) - return stored.stat if stored is not None else None - - def get(self, key: str) -> StoredObject | None: - self.requests.append(("get", key)) - return self.objects.get(key) - - def put( - self, - key: str, - body: bytes, - *, - cache_control: str, - content_type: str = "application/octet-stream", - ) -> None: - self.requests.append(("put", key)) - stat = ObjectStat( - key, - hashlib.sha256(body).hexdigest(), - len(body), - cache_control, - content_type, - datetime.now(UTC), - ) - self.objects[key] = StoredObject(body, stat) - - def put_keys(self) -> list[str]: - return [key for operation, key in self.requests if operation == "put"] - - -class _NoBatches: - """Projection batch stream of an hour that listed no Bundles.""" - - bundle_count = 0 - - def __iter__(self) -> Iterator[tuple[str, pa.RecordBatch]]: - return iter(()) - - -def empty_projection(source_hour: datetime, raw_commit_sha256: str) -> HourProjection: - return HourProjection(source_hour, raw_commit_sha256, batch_stream=_NoBatches()) - - -def collect_tables(projection: HourProjection) -> dict[str, pa.Table]: - batches: dict[str, list[pa.RecordBatch]] = {name: [] for name in table_schemas()} - for name, batch in projection.iter_batches(): - batches[name].append(batch) - return { - name: pa.Table.from_batches(items, schema=table_schemas()[name]) - for name, items in batches.items() - } diff --git a/bazaarplusplus-analyzer/tests/fixtures/pipeline-golden.run-report.json b/bazaarplusplus-analyzer/tests/fixtures/pipeline-golden.run-report.json deleted file mode 100644 index b270591..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/pipeline-golden.run-report.json +++ /dev/null @@ -1 +0,0 @@ -{"builds":{"candidate_builds":4,"eligible_layout_runs":9,"published":false,"published_builds":4},"downloads":{"download_attempts":33,"download_retries":0,"downloaded_bytes":43937,"expected_bundles":33,"failed_bundles":0,"listing_pages":24,"listing_requests":24,"listing_retries":0,"succeeded_bundles":33},"facts":{"discarded_unknown_final_rank":3,"discarded_unknown_hero":2,"included_battles":29,"included_runs":28,"raw_runs":32},"heroes":{"participating_matchup_battles":28,"participating_runs":28,"published":false},"retention":{"bytes_pruned":0,"files_pruned":0,"hours_pruned":0,"source_days_pruned":0},"window":{"days":1,"end":"2026-08-10","start":"2026-08-10"}} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/account-id-opponent-wins.json b/bazaarplusplus-analyzer/tests/fixtures/projection/account-id-opponent-wins.json deleted file mode 100644 index 24250fd..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/account-id-opponent-wins.json +++ /dev/null @@ -1,213 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366804000, - "bundle_id": "projection-account-id-opponent-wins", - "bundle_sha256": "d2d8026c1dd145931ad6337a085410ff38fa94537b5ef5b162b838ac91381c6f", - "run_id": "run-projection-account-id-opponent-wins", - "player_account_id": "account-1", - "client_created_at_ms": 1786363200000, - "hero": "Vanessa", - "game_mode": "Ranked", - "seed": 42, - "started_at_utc": "2026-08-10T12:00:00.000Z", - "ended_at_utc": "2026-08-10T12:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 10, - "losses": 3, - "initial_rank": "Gold", - "initial_rating": 1000, - "final_rank": "Legendary", - "final_rating": 1100, - "final_rating_delta": 100, - "final_health": 50, - "prestige": 2, - "level": 10, - "income": 8, - "gold": 12, - "build_channel": "stable", - "mod_version": "5.1.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 1, - "battle_player_win_count": 0, - "battle_player_loss_count": 1, - "final_battle_id": "battle-1", - "final_player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "final_opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "degradation_categories_json": "[]", - "degraded_replay_count": 0, - "degraded_event_count": 0, - "degraded_screenshot": false, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366804000, - "bundle_id": "projection-account-id-opponent-wins", - "run_id": "run-projection-account-id-opponent-wins", - "battle_id": "battle-1", - "recorded_at_utc": "2026-08-10T12:10:00.000Z", - "game_day": 10, - "game_hour": 2, - "encounter_id": "encounter-1", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "account-2", - "loser_combatant_id": "account-1", - "is_final_battle": true, - "player_account_id": "account-1", - "player_display_name": "Alice", - "player_hero": "Vanessa", - "player_rank": "Legendary", - "player_rating": 1100, - "player_level": 10, - "player_prestige": 2, - "player_victories": 10, - "player_income": 8, - "player_gold": 12, - "player_hand_item_count": 1, - "player_skill_count": 1, - "opponent_account_id": "account-2", - "opponent_display_name": "Bob", - "opponent_hero": "Pygmalien", - "opponent_rank": "Gold", - "opponent_rating": 1050, - "opponent_level": 10, - "opponent_prestige": 2, - "opponent_victories": 8, - "opponent_income": 8, - "opponent_gold": 12, - "opponent_hand_item_count": 1, - "opponent_skill_count": 1, - "winner_side": "opponent", - "winner_hero": "Pygmalien", - "player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366804000, - "bundle_id": "projection-account-id-opponent-wins", - "run_id": "run-projection-account-id-opponent-wins", - "battle_id": "battle-1", - "card_set_label": "player_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366804000, - "bundle_id": "projection-account-id-opponent-wins", - "run_id": "run-projection-account-id-opponent-wins", - "battle_id": "battle-1", - "card_set_label": "player_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366804000, - "bundle_id": "projection-account-id-opponent-wins", - "run_id": "run-projection-account-id-opponent-wins", - "battle_id": "battle-1", - "card_set_label": "opponent_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366804000, - "bundle_id": "projection-account-id-opponent-wins", - "run_id": "run-projection-account-id-opponent-wins", - "battle_id": "battle-1", - "card_set_label": "opponent_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - } - ], - "quality": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-account-id-opponent-wins", - "run_id": "run-projection-account-id-opponent-wins", - "code": "run_outcome_count_mismatch", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{\"battle_losses\":1,\"battle_wins\":0,\"run_losses\":3,\"run_victories\":10}" - } - ], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/account-id-player-wins.json b/bazaarplusplus-analyzer/tests/fixtures/projection/account-id-player-wins.json deleted file mode 100644 index 636e266..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/account-id-player-wins.json +++ /dev/null @@ -1,213 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366803000, - "bundle_id": "projection-account-id-player-wins", - "bundle_sha256": "97041f200c904bd79193ba5a1cf01e632c29a0f5ce438f3ff2e6dfc9067afc2f", - "run_id": "run-projection-account-id-player-wins", - "player_account_id": "account-1", - "client_created_at_ms": 1786363200000, - "hero": "Vanessa", - "game_mode": "Ranked", - "seed": 42, - "started_at_utc": "2026-08-10T12:00:00.000Z", - "ended_at_utc": "2026-08-10T12:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 10, - "losses": 0, - "initial_rank": "Gold", - "initial_rating": 1000, - "final_rank": "Legendary", - "final_rating": 1100, - "final_rating_delta": 100, - "final_health": 50, - "prestige": 2, - "level": 10, - "income": 8, - "gold": 12, - "build_channel": "stable", - "mod_version": "5.1.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 1, - "battle_player_win_count": 1, - "battle_player_loss_count": 0, - "final_battle_id": "battle-1", - "final_player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "final_opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "degradation_categories_json": "[]", - "degraded_replay_count": 0, - "degraded_event_count": 0, - "degraded_screenshot": false, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366803000, - "bundle_id": "projection-account-id-player-wins", - "run_id": "run-projection-account-id-player-wins", - "battle_id": "battle-1", - "recorded_at_utc": "2026-08-10T12:10:00.000Z", - "game_day": 10, - "game_hour": 2, - "encounter_id": "encounter-1", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "account-1", - "loser_combatant_id": "account-2", - "is_final_battle": true, - "player_account_id": "account-1", - "player_display_name": "Alice", - "player_hero": "Vanessa", - "player_rank": "Legendary", - "player_rating": 1100, - "player_level": 10, - "player_prestige": 2, - "player_victories": 10, - "player_income": 8, - "player_gold": 12, - "player_hand_item_count": 1, - "player_skill_count": 1, - "opponent_account_id": "account-2", - "opponent_display_name": "Bob", - "opponent_hero": "Pygmalien", - "opponent_rank": "Gold", - "opponent_rating": 1050, - "opponent_level": 10, - "opponent_prestige": 2, - "opponent_victories": 8, - "opponent_income": 8, - "opponent_gold": 12, - "opponent_hand_item_count": 1, - "opponent_skill_count": 1, - "winner_side": "player", - "winner_hero": "Vanessa", - "player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366803000, - "bundle_id": "projection-account-id-player-wins", - "run_id": "run-projection-account-id-player-wins", - "battle_id": "battle-1", - "card_set_label": "player_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366803000, - "bundle_id": "projection-account-id-player-wins", - "run_id": "run-projection-account-id-player-wins", - "battle_id": "battle-1", - "card_set_label": "player_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366803000, - "bundle_id": "projection-account-id-player-wins", - "run_id": "run-projection-account-id-player-wins", - "battle_id": "battle-1", - "card_set_label": "opponent_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366803000, - "bundle_id": "projection-account-id-player-wins", - "run_id": "run-projection-account-id-player-wins", - "battle_id": "battle-1", - "card_set_label": "opponent_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - } - ], - "quality": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-account-id-player-wins", - "run_id": "run-projection-account-id-player-wins", - "code": "run_outcome_count_mismatch", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{\"battle_losses\":0,\"battle_wins\":1,\"run_losses\":0,\"run_victories\":10}" - } - ], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/client-clock-anomalies.json b/bazaarplusplus-analyzer/tests/fixtures/projection/client-clock-anomalies.json deleted file mode 100644 index 019bd06..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/client-clock-anomalies.json +++ /dev/null @@ -1,233 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366806000, - "bundle_id": "projection-client-clock-anomalies", - "bundle_sha256": "a03c58aafec1a062bb81ad3ee4faaa64e1df73e06b9a54fd48d3f9f24d76d132", - "run_id": "run-projection-client-clock-anomalies", - "player_account_id": "account-projection-client-clock-anomalies", - "client_created_at_ms": 1786406400000, - "hero": "Vanessa", - "game_mode": "Ranked", - "seed": 42, - "started_at_utc": "2026-08-11T01:00:00.000Z", - "ended_at_utc": "2026-08-10T12:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 10, - "losses": 0, - "initial_rank": "Gold", - "initial_rating": 1000, - "final_rank": "Legendary", - "final_rating": 1100, - "final_rating_delta": 100, - "final_health": 50, - "prestige": 2, - "level": 10, - "income": 8, - "gold": 12, - "build_channel": "stable", - "mod_version": "5.1.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 1, - "battle_player_win_count": 1, - "battle_player_loss_count": 0, - "final_battle_id": "battle-1", - "final_player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "final_opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "degradation_categories_json": "[]", - "degraded_replay_count": 0, - "degraded_event_count": 0, - "degraded_screenshot": false, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366806000, - "bundle_id": "projection-client-clock-anomalies", - "run_id": "run-projection-client-clock-anomalies", - "battle_id": "battle-1", - "recorded_at_utc": "2026-08-09T23:00:00.000Z", - "game_day": 10, - "game_hour": 2, - "encounter_id": "encounter-1", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "account-projection-client-clock-anomalies", - "loser_combatant_id": "account-2", - "is_final_battle": true, - "player_account_id": "account-projection-client-clock-anomalies", - "player_display_name": "Alice", - "player_hero": "Vanessa", - "player_rank": "Legendary", - "player_rating": 1100, - "player_level": 10, - "player_prestige": 2, - "player_victories": 10, - "player_income": 8, - "player_gold": 12, - "player_hand_item_count": 1, - "player_skill_count": 1, - "opponent_account_id": "account-2", - "opponent_display_name": "Bob", - "opponent_hero": "Pygmalien", - "opponent_rank": "Gold", - "opponent_rating": 1050, - "opponent_level": 10, - "opponent_prestige": 2, - "opponent_victories": 8, - "opponent_income": 8, - "opponent_gold": 12, - "opponent_hand_item_count": 1, - "opponent_skill_count": 1, - "winner_side": "player", - "winner_hero": "Vanessa", - "player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366806000, - "bundle_id": "projection-client-clock-anomalies", - "run_id": "run-projection-client-clock-anomalies", - "battle_id": "battle-1", - "card_set_label": "player_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366806000, - "bundle_id": "projection-client-clock-anomalies", - "run_id": "run-projection-client-clock-anomalies", - "battle_id": "battle-1", - "card_set_label": "player_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366806000, - "bundle_id": "projection-client-clock-anomalies", - "run_id": "run-projection-client-clock-anomalies", - "battle_id": "battle-1", - "card_set_label": "opponent_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366806000, - "bundle_id": "projection-client-clock-anomalies", - "run_id": "run-projection-client-clock-anomalies", - "battle_id": "battle-1", - "card_set_label": "opponent_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - } - ], - "quality": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-client-clock-anomalies", - "run_id": "run-projection-client-clock-anomalies", - "code": "client_clock_before_run", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-client-clock-anomalies", - "run_id": "run-projection-client-clock-anomalies", - "code": "client_clock_future", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-client-clock-anomalies", - "run_id": "run-projection-client-clock-anomalies", - "code": "run_outcome_count_mismatch", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{\"battle_losses\":0,\"battle_wins\":1,\"run_losses\":0,\"run_victories\":10}" - } - ], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/hero8-alias.json b/bazaarplusplus-analyzer/tests/fixtures/projection/hero8-alias.json deleted file mode 100644 index ce117a6..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/hero8-alias.json +++ /dev/null @@ -1,213 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366811000, - "bundle_id": "projection-hero8-alias", - "bundle_sha256": "b95e61f31393cc4dffedc1192ce5ad6fd4be1a30a4fcc2aa5928fc9a5441bc00", - "run_id": "run-projection-hero8-alias", - "player_account_id": "account-projection-hero8-alias", - "client_created_at_ms": 1786363200000, - "hero": "TheDragons", - "game_mode": "Ranked", - "seed": 42, - "started_at_utc": "2026-08-10T12:00:00.000Z", - "ended_at_utc": "2026-08-10T12:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 10, - "losses": 0, - "initial_rank": "Gold", - "initial_rating": 1000, - "final_rank": "Legendary", - "final_rating": 1100, - "final_rating_delta": 100, - "final_health": 50, - "prestige": 2, - "level": 10, - "income": 8, - "gold": 12, - "build_channel": "stable", - "mod_version": "5.1.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 1, - "battle_player_win_count": 1, - "battle_player_loss_count": 0, - "final_battle_id": "battle-1", - "final_player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "final_opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "degradation_categories_json": "[]", - "degraded_replay_count": 0, - "degraded_event_count": 0, - "degraded_screenshot": false, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366811000, - "bundle_id": "projection-hero8-alias", - "run_id": "run-projection-hero8-alias", - "battle_id": "battle-1", - "recorded_at_utc": "2026-08-10T12:10:00.000Z", - "game_day": 10, - "game_hour": 2, - "encounter_id": "encounter-1", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "account-projection-hero8-alias", - "loser_combatant_id": "account-2", - "is_final_battle": true, - "player_account_id": "account-projection-hero8-alias", - "player_display_name": "Alice", - "player_hero": "TheDragons", - "player_rank": "Legendary", - "player_rating": 1100, - "player_level": 10, - "player_prestige": 2, - "player_victories": 10, - "player_income": 8, - "player_gold": 12, - "player_hand_item_count": 1, - "player_skill_count": 1, - "opponent_account_id": "account-2", - "opponent_display_name": "Bob", - "opponent_hero": "Pygmalien", - "opponent_rank": "Gold", - "opponent_rating": 1050, - "opponent_level": 10, - "opponent_prestige": 2, - "opponent_victories": 8, - "opponent_income": 8, - "opponent_gold": 12, - "opponent_hand_item_count": 1, - "opponent_skill_count": 1, - "winner_side": "player", - "winner_hero": "TheDragons", - "player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366811000, - "bundle_id": "projection-hero8-alias", - "run_id": "run-projection-hero8-alias", - "battle_id": "battle-1", - "card_set_label": "player_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366811000, - "bundle_id": "projection-hero8-alias", - "run_id": "run-projection-hero8-alias", - "battle_id": "battle-1", - "card_set_label": "player_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366811000, - "bundle_id": "projection-hero8-alias", - "run_id": "run-projection-hero8-alias", - "battle_id": "battle-1", - "card_set_label": "opponent_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366811000, - "bundle_id": "projection-hero8-alias", - "run_id": "run-projection-hero8-alias", - "battle_id": "battle-1", - "card_set_label": "opponent_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - } - ], - "quality": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-hero8-alias", - "run_id": "run-projection-hero8-alias", - "code": "run_outcome_count_mismatch", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{\"battle_losses\":0,\"battle_wins\":1,\"run_losses\":0,\"run_victories\":10}" - } - ], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/side-name-opponent-wins.json b/bazaarplusplus-analyzer/tests/fixtures/projection/side-name-opponent-wins.json deleted file mode 100644 index 2b5f5c1..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/side-name-opponent-wins.json +++ /dev/null @@ -1,202 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366802000, - "bundle_id": "projection-side-name-opponent-wins", - "bundle_sha256": "5cd87ec1902e37027fc780bb04f3a6e4c9a73422bd76a80f522bba5630a45c29", - "run_id": "run-projection-side-name-opponent-wins", - "player_account_id": "account-projection-side-name-opponent-wins", - "client_created_at_ms": 1786363200000, - "hero": "Vanessa", - "game_mode": "Ranked", - "seed": 42, - "started_at_utc": "2026-08-10T12:00:00.000Z", - "ended_at_utc": "2026-08-10T12:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 0, - "losses": 1, - "initial_rank": "Gold", - "initial_rating": 1000, - "final_rank": "Gold", - "final_rating": 1100, - "final_rating_delta": 100, - "final_health": 50, - "prestige": 2, - "level": 10, - "income": 8, - "gold": 12, - "build_channel": "stable", - "mod_version": "5.1.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 1, - "battle_player_win_count": 0, - "battle_player_loss_count": 1, - "final_battle_id": "battle-1", - "final_player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "final_opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "degradation_categories_json": "[]", - "degraded_replay_count": 0, - "degraded_event_count": 0, - "degraded_screenshot": false, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366802000, - "bundle_id": "projection-side-name-opponent-wins", - "run_id": "run-projection-side-name-opponent-wins", - "battle_id": "battle-1", - "recorded_at_utc": "2026-08-10T12:10:00.000Z", - "game_day": 10, - "game_hour": 2, - "encounter_id": "encounter-1", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "Opponent", - "loser_combatant_id": "Player", - "is_final_battle": true, - "player_account_id": "account-projection-side-name-opponent-wins", - "player_display_name": "Alice", - "player_hero": "Vanessa", - "player_rank": "Gold", - "player_rating": 1100, - "player_level": 10, - "player_prestige": 2, - "player_victories": 10, - "player_income": 8, - "player_gold": 12, - "player_hand_item_count": 1, - "player_skill_count": 1, - "opponent_account_id": "account-2", - "opponent_display_name": "Bob", - "opponent_hero": "Pygmalien", - "opponent_rank": "Gold", - "opponent_rating": 1050, - "opponent_level": 10, - "opponent_prestige": 2, - "opponent_victories": 8, - "opponent_income": 8, - "opponent_gold": 12, - "opponent_hand_item_count": 1, - "opponent_skill_count": 1, - "winner_side": "opponent", - "winner_hero": "Pygmalien", - "player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366802000, - "bundle_id": "projection-side-name-opponent-wins", - "run_id": "run-projection-side-name-opponent-wins", - "battle_id": "battle-1", - "card_set_label": "player_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366802000, - "bundle_id": "projection-side-name-opponent-wins", - "run_id": "run-projection-side-name-opponent-wins", - "battle_id": "battle-1", - "card_set_label": "player_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366802000, - "bundle_id": "projection-side-name-opponent-wins", - "run_id": "run-projection-side-name-opponent-wins", - "battle_id": "battle-1", - "card_set_label": "opponent_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366802000, - "bundle_id": "projection-side-name-opponent-wins", - "run_id": "run-projection-side-name-opponent-wins", - "battle_id": "battle-1", - "card_set_label": "opponent_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - } - ], - "quality": [], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/side-name-player-wins.json b/bazaarplusplus-analyzer/tests/fixtures/projection/side-name-player-wins.json deleted file mode 100644 index b31c3c0..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/side-name-player-wins.json +++ /dev/null @@ -1,202 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366801000, - "bundle_id": "projection-side-name-player-wins", - "bundle_sha256": "36d14badb5c59d5db311a2be524d3c1efc18b20723effc865b3c21a0eb0b3262", - "run_id": "run-projection-side-name-player-wins", - "player_account_id": "account-projection-side-name-player-wins", - "client_created_at_ms": 1786363200000, - "hero": "Vanessa", - "game_mode": "Ranked", - "seed": 42, - "started_at_utc": "2026-08-10T12:00:00.000Z", - "ended_at_utc": "2026-08-10T12:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 1, - "losses": 0, - "initial_rank": "Gold", - "initial_rating": 1000, - "final_rank": "Legendary", - "final_rating": 1100, - "final_rating_delta": 100, - "final_health": 50, - "prestige": 2, - "level": 10, - "income": 8, - "gold": 12, - "build_channel": "stable", - "mod_version": "5.1.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 1, - "battle_player_win_count": 1, - "battle_player_loss_count": 0, - "final_battle_id": "battle-1", - "final_player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "final_opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "degradation_categories_json": "[]", - "degraded_replay_count": 0, - "degraded_event_count": 0, - "degraded_screenshot": false, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366801000, - "bundle_id": "projection-side-name-player-wins", - "run_id": "run-projection-side-name-player-wins", - "battle_id": "battle-1", - "recorded_at_utc": "2026-08-10T12:10:00.000Z", - "game_day": 10, - "game_hour": 2, - "encounter_id": "encounter-1", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "Player", - "loser_combatant_id": "Opponent", - "is_final_battle": true, - "player_account_id": "account-projection-side-name-player-wins", - "player_display_name": "Alice", - "player_hero": "Vanessa", - "player_rank": "Legendary", - "player_rating": 1100, - "player_level": 10, - "player_prestige": 2, - "player_victories": 10, - "player_income": 8, - "player_gold": 12, - "player_hand_item_count": 1, - "player_skill_count": 1, - "opponent_account_id": "account-2", - "opponent_display_name": "Bob", - "opponent_hero": "Pygmalien", - "opponent_rank": "Gold", - "opponent_rating": 1050, - "opponent_level": 10, - "opponent_prestige": 2, - "opponent_victories": 8, - "opponent_income": 8, - "opponent_gold": 12, - "opponent_hand_item_count": 1, - "opponent_skill_count": 1, - "winner_side": "player", - "winner_hero": "Vanessa", - "player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366801000, - "bundle_id": "projection-side-name-player-wins", - "run_id": "run-projection-side-name-player-wins", - "battle_id": "battle-1", - "card_set_label": "player_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366801000, - "bundle_id": "projection-side-name-player-wins", - "run_id": "run-projection-side-name-player-wins", - "battle_id": "battle-1", - "card_set_label": "player_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366801000, - "bundle_id": "projection-side-name-player-wins", - "run_id": "run-projection-side-name-player-wins", - "battle_id": "battle-1", - "card_set_label": "opponent_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366801000, - "bundle_id": "projection-side-name-player-wins", - "run_id": "run-projection-side-name-player-wins", - "battle_id": "battle-1", - "card_set_label": "opponent_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - } - ], - "quality": [], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-missing-rank.json b/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-missing-rank.json deleted file mode 100644 index 9b2f741..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-missing-rank.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "runs": [], - "battles": [], - "battle_cards": [], - "quality": [], - "quarantine": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-unaccepted-missing-rank", - "run_id": "run-projection-unaccepted-missing-rank", - "stage": "fact_filter", - "reason_code": "unaccepted_run", - "raw_run": true, - "discarded_unknown_hero": false, - "discarded_unknown_final_rank": true, - "first_seen_at": "2026-08-10T14:00:00Z", - "decoder_code_version": "v6-consumer-contract-1", - "diagnostic_json": "{\"final_rank\":null,\"hero\":\"Vanessa\",\"reason\":\"unaccepted_run\"}" - } - ] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-hero-and-rank.json b/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-hero-and-rank.json deleted file mode 100644 index 712a33f..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-hero-and-rank.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "runs": [], - "battles": [], - "battle_cards": [], - "quality": [], - "quarantine": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-unaccepted-unknown-hero-and-rank", - "run_id": "run-projection-unaccepted-unknown-hero-and-rank", - "stage": "fact_filter", - "reason_code": "unaccepted_run", - "raw_run": true, - "discarded_unknown_hero": true, - "discarded_unknown_final_rank": true, - "first_seen_at": "2026-08-10T14:00:00Z", - "decoder_code_version": "v6-consumer-contract-1", - "diagnostic_json": "{\"final_rank\":\"Mythic\",\"hero\":\"UnknownHero\",\"reason\":\"unaccepted_run\"}" - } - ] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-hero.json b/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-hero.json deleted file mode 100644 index 20eace9..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-hero.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "runs": [], - "battles": [], - "battle_cards": [], - "quality": [], - "quarantine": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-unaccepted-unknown-hero", - "run_id": "run-projection-unaccepted-unknown-hero", - "stage": "fact_filter", - "reason_code": "unaccepted_run", - "raw_run": true, - "discarded_unknown_hero": true, - "discarded_unknown_final_rank": false, - "first_seen_at": "2026-08-10T14:00:00Z", - "decoder_code_version": "v6-consumer-contract-1", - "diagnostic_json": "{\"final_rank\":\"Legendary\",\"hero\":\"UnknownHero\",\"reason\":\"unaccepted_run\"}" - } - ] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-rank.json b/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-rank.json deleted file mode 100644 index 5dbe1d4..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/unaccepted-unknown-rank.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "runs": [], - "battles": [], - "battle_cards": [], - "quality": [], - "quarantine": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-unaccepted-unknown-rank", - "run_id": "run-projection-unaccepted-unknown-rank", - "stage": "fact_filter", - "reason_code": "unaccepted_run", - "raw_run": true, - "discarded_unknown_hero": false, - "discarded_unknown_final_rank": true, - "first_seen_at": "2026-08-10T14:00:00Z", - "decoder_code_version": "v6-consumer-contract-1", - "diagnostic_json": "{\"final_rank\":\"Mythic\",\"hero\":\"Vanessa\",\"reason\":\"unaccepted_run\"}" - } - ] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/unknown-combatant-undecided.json b/bazaarplusplus-analyzer/tests/fixtures/projection/unknown-combatant-undecided.json deleted file mode 100644 index 7a08f15..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/unknown-combatant-undecided.json +++ /dev/null @@ -1,213 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366805000, - "bundle_id": "projection-unknown-combatant-undecided", - "bundle_sha256": "8f840270f828bb81b621e70838c893921fc412b8b95878578f6f67e3c4e92cd9", - "run_id": "run-projection-unknown-combatant-undecided", - "player_account_id": "account-projection-unknown-combatant-undecided", - "client_created_at_ms": 1786363200000, - "hero": "Vanessa", - "game_mode": "Ranked", - "seed": 42, - "started_at_utc": "2026-08-10T12:00:00.000Z", - "ended_at_utc": "2026-08-10T12:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 5, - "losses": 5, - "initial_rank": "Gold", - "initial_rating": 1000, - "final_rank": "Legendary", - "final_rating": 1100, - "final_rating_delta": 100, - "final_health": 50, - "prestige": 2, - "level": 10, - "income": 8, - "gold": 12, - "build_channel": "stable", - "mod_version": "5.1.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 0, - "battle_player_win_count": 0, - "battle_player_loss_count": 0, - "final_battle_id": "battle-1", - "final_player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "final_opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "degradation_categories_json": "[]", - "degraded_replay_count": 0, - "degraded_event_count": 0, - "degraded_screenshot": false, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366805000, - "bundle_id": "projection-unknown-combatant-undecided", - "run_id": "run-projection-unknown-combatant-undecided", - "battle_id": "battle-1", - "recorded_at_utc": "2026-08-10T12:10:00.000Z", - "game_day": 10, - "game_hour": 2, - "encounter_id": "encounter-1", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "unknown-combatant", - "loser_combatant_id": "another-unknown-combatant", - "is_final_battle": true, - "player_account_id": "account-projection-unknown-combatant-undecided", - "player_display_name": "Alice", - "player_hero": "Vanessa", - "player_rank": "Legendary", - "player_rating": 1100, - "player_level": 10, - "player_prestige": 2, - "player_victories": 10, - "player_income": 8, - "player_gold": 12, - "player_hand_item_count": 1, - "player_skill_count": 1, - "opponent_account_id": "account-2", - "opponent_display_name": "Bob", - "opponent_hero": "Pygmalien", - "opponent_rank": "Gold", - "opponent_rating": 1050, - "opponent_level": 10, - "opponent_prestige": 2, - "opponent_victories": 8, - "opponent_income": 8, - "opponent_gold": 12, - "opponent_hand_item_count": 1, - "opponent_skill_count": 1, - "winner_side": null, - "winner_hero": null, - "player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366805000, - "bundle_id": "projection-unknown-combatant-undecided", - "run_id": "run-projection-unknown-combatant-undecided", - "battle_id": "battle-1", - "card_set_label": "player_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366805000, - "bundle_id": "projection-unknown-combatant-undecided", - "run_id": "run-projection-unknown-combatant-undecided", - "battle_id": "battle-1", - "card_set_label": "player_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366805000, - "bundle_id": "projection-unknown-combatant-undecided", - "run_id": "run-projection-unknown-combatant-undecided", - "battle_id": "battle-1", - "card_set_label": "opponent_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366805000, - "bundle_id": "projection-unknown-combatant-undecided", - "run_id": "run-projection-unknown-combatant-undecided", - "battle_id": "battle-1", - "card_set_label": "opponent_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - } - ], - "quality": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-unknown-combatant-undecided", - "run_id": "run-projection-unknown-combatant-undecided", - "code": "run_outcome_count_mismatch", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{\"battle_losses\":0,\"battle_wins\":0,\"run_losses\":5,\"run_victories\":5}" - } - ], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/projection/whitespace-hero.json b/bazaarplusplus-analyzer/tests/fixtures/projection/whitespace-hero.json deleted file mode 100644 index 86e1311..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/projection/whitespace-hero.json +++ /dev/null @@ -1,213 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366812000, - "bundle_id": "projection-whitespace-hero", - "bundle_sha256": "d472b91dc6eabe6757fd85d3a4db3fae3a07a0a0f7e0257742dad939836dcbea", - "run_id": "run-projection-whitespace-hero", - "player_account_id": "account-projection-whitespace-hero", - "client_created_at_ms": 1786363200000, - "hero": "Vanessa", - "game_mode": "Ranked", - "seed": 42, - "started_at_utc": "2026-08-10T12:00:00.000Z", - "ended_at_utc": "2026-08-10T12:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 10, - "losses": 0, - "initial_rank": "Gold", - "initial_rating": 1000, - "final_rank": "Legendary", - "final_rating": 1100, - "final_rating_delta": 100, - "final_health": 50, - "prestige": 2, - "level": 10, - "income": 8, - "gold": 12, - "build_channel": "stable", - "mod_version": "5.1.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 1, - "battle_player_win_count": 1, - "battle_player_loss_count": 0, - "final_battle_id": "battle-1", - "final_player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "final_opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "degradation_categories_json": "[]", - "degraded_replay_count": 0, - "degraded_event_count": 0, - "degraded_screenshot": false, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366812000, - "bundle_id": "projection-whitespace-hero", - "run_id": "run-projection-whitespace-hero", - "battle_id": "battle-1", - "recorded_at_utc": "2026-08-10T12:10:00.000Z", - "game_day": 10, - "game_hour": 2, - "encounter_id": "encounter-1", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "account-projection-whitespace-hero", - "loser_combatant_id": "account-2", - "is_final_battle": true, - "player_account_id": "account-projection-whitespace-hero", - "player_display_name": "Alice", - "player_hero": "Vanessa", - "player_rank": "Legendary", - "player_rating": 1100, - "player_level": 10, - "player_prestige": 2, - "player_victories": 10, - "player_income": 8, - "player_gold": 12, - "player_hand_item_count": 1, - "player_skill_count": 1, - "opponent_account_id": "account-2", - "opponent_display_name": "Bob", - "opponent_hero": "Pygmalien", - "opponent_rank": "Gold", - "opponent_rating": 1050, - "opponent_level": 10, - "opponent_prestige": 2, - "opponent_victories": 8, - "opponent_income": 8, - "opponent_gold": 12, - "opponent_hand_item_count": 1, - "opponent_skill_count": 1, - "winner_side": "player", - "winner_hero": "Vanessa", - "player_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "opponent_item_signature": "d1d10c7d680f62023b54d549ba9deb44c8c545876406314c52fc925ac59b94db", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366812000, - "bundle_id": "projection-whitespace-hero", - "run_id": "run-projection-whitespace-hero", - "battle_id": "battle-1", - "card_set_label": "player_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366812000, - "bundle_id": "projection-whitespace-hero", - "run_id": "run-projection-whitespace-hero", - "battle_id": "battle-1", - "card_set_label": "player_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366812000, - "bundle_id": "projection-whitespace-hero", - "run_id": "run-projection-whitespace-hero", - "battle_id": "battle-1", - "card_set_label": "opponent_hand", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - }, - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "available_at_ms": 1786366812000, - "bundle_id": "projection-whitespace-hero", - "run_id": "run-projection-whitespace-hero", - "battle_id": "battle-1", - "card_set_label": "opponent_skills", - "card_set_status": "Complete", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "item-one", - "card_type": 1, - "size": 2, - "section": 1, - "socket": 3, - "name": "Item One", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\"]", - "attributes_json": "{\"damage\":12}" - } - ], - "quality": [ - { - "source_hour": "2026-08-10T13", - "source_day": "2026-08-10", - "bundle_id": "projection-whitespace-hero", - "run_id": "run-projection-whitespace-hero", - "code": "run_outcome_count_mismatch", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{\"battle_losses\":0,\"battle_wins\":1,\"run_losses\":0,\"run_victories\":10}" - } - ], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/fixtures/run-payload-v6.projection.json b/bazaarplusplus-analyzer/tests/fixtures/run-payload-v6.projection.json deleted file mode 100644 index ecfafb0..0000000 --- a/bazaarplusplus-analyzer/tests/fixtures/run-payload-v6.projection.json +++ /dev/null @@ -1,223 +0,0 @@ -{ - "runs": [ - { - "source_hour": "2026-08-03T01", - "source_day": "2026-08-03", - "available_at_ms": 1785718800000, - "bundle_id": "01J00000000000000000000902", - "bundle_sha256": "0c33e627a23a04235dd9e92dbd7752639a856f222f7c66b801b785843819c0df", - "run_id": "payload-run", - "player_account_id": "golden-account", - "client_created_at_ms": 1785718800000, - "hero": "Vanessa", - "game_mode": "Ranked", - "seed": 123456, - "started_at_utc": "2026-08-03T00:00:00.000Z", - "ended_at_utc": "2026-08-03T00:30:00.000Z", - "status": "completed", - "run_day": 10, - "run_hour": 2, - "victories": 1, - "losses": 0, - "initial_rank": "Gold", - "initial_rating": 1200, - "final_rank": "Legendary", - "final_rating": 1234, - "final_rating_delta": 34, - "final_health": 2500, - "prestige": 3, - "level": 11, - "income": 8, - "gold": 17, - "build_channel": "Online", - "mod_version": "6.0.0", - "battle_count": 1, - "replayable_battle_count": 1, - "battle_decided_count": 1, - "battle_player_win_count": 1, - "battle_player_loss_count": 0, - "final_battle_id": "battle-000", - "final_player_item_signature": "16fc88224ae437cb201680dbc74f8bbd172afa96f07359933967a26c45bb1a10", - "final_opponent_item_signature": "765e6bfd046fbccb5c18d7bf586fad0c54d66827fd8df83cf0f601e05878c817", - "degradation_categories_json": "[\"events_omitted\",\"screenshot_omitted\"]", - "degraded_replay_count": 0, - "degraded_event_count": 2, - "degraded_screenshot": true, - "projection_code_version": "v6-consumer-contract-1" - } - ], - "battles": [ - { - "source_hour": "2026-08-03T01", - "source_day": "2026-08-03", - "available_at_ms": 1785718800000, - "bundle_id": "01J00000000000000000000902", - "run_id": "payload-run", - "battle_id": "battle-000", - "recorded_at_utc": "2026-08-03T00:29:00.000Z", - "game_day": 10, - "game_hour": 1, - "encounter_id": "encounter-final", - "combat_kind": "PvP", - "result": "Win", - "winner_combatant_id": "Player", - "loser_combatant_id": "Opponent", - "is_final_battle": true, - "player_account_id": "golden-account", - "player_display_name": "玩家😀", - "player_hero": "Vanessa", - "player_rank": "Gold", - "player_rating": 1200, - "player_level": 11, - "player_prestige": 3, - "player_victories": 0, - "player_income": 8, - "player_gold": 17, - "player_hand_item_count": 1, - "player_skill_count": 2, - "opponent_account_id": "golden-opponent", - "opponent_display_name": "Opponent", - "opponent_hero": "Pygmalien", - "opponent_rank": "Silver", - "opponent_rating": 1100, - "opponent_level": 12, - "opponent_prestige": 4, - "opponent_victories": 5, - "opponent_income": 9, - "opponent_gold": 18, - "opponent_hand_item_count": 2, - "opponent_skill_count": 1, - "winner_side": "player", - "winner_hero": "Vanessa", - "player_item_signature": "16fc88224ae437cb201680dbc74f8bbd172afa96f07359933967a26c45bb1a10", - "opponent_item_signature": "765e6bfd046fbccb5c18d7bf586fad0c54d66827fd8df83cf0f601e05878c817", - "snapshot_available": true, - "replay_available": true - } - ], - "battle_cards": [ - { - "source_hour": "2026-08-03T01", - "source_day": "2026-08-03", - "available_at_ms": 1785718800000, - "bundle_id": "01J00000000000000000000902", - "run_id": "payload-run", - "battle_id": "battle-000", - "card_set_label": "player_hand", - "card_set_status": "Captured", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-0", - "template_id": "00000000-0000-0000-0000-000000000001", - "card_type": 1, - "size": 2, - "section": 0, - "socket": 4, - "name": "Golden card 0", - "tier": "Gold", - "enchantment": "Burning", - "tags_json": "[\"Weapon\",\"golden-0\"]", - "attributes_json": "{\"cooldown\":2000,\"damage\":100}" - }, - { - "source_hour": "2026-08-03T01", - "source_day": "2026-08-03", - "available_at_ms": 1785718800000, - "bundle_id": "01J00000000000000000000902", - "run_id": "payload-run", - "battle_id": "battle-000", - "card_set_label": "player_skills", - "card_set_status": "Captured", - "card_set_source": "capture", - "owner_side": "player", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-1", - "template_id": "00000000-0000-0000-0000-000000000002", - "card_type": 2, - "size": 1, - "section": 1, - "socket": 5, - "name": "Golden card 1", - "tier": "Silver", - "enchantment": null, - "tags_json": "[\"Weapon\",\"golden-1\"]", - "attributes_json": "{\"cooldown\":2001,\"damage\":101}" - }, - { - "source_hour": "2026-08-03T01", - "source_day": "2026-08-03", - "available_at_ms": 1785718800000, - "bundle_id": "01J00000000000000000000902", - "run_id": "payload-run", - "battle_id": "battle-000", - "card_set_label": "opponent_hand", - "card_set_status": "Captured", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "item", - "slot_index": 0, - "instance_id": "instance-2", - "template_id": "00000000-0000-0000-0000-000000000003", - "card_type": 1, - "size": 2, - "section": 2, - "socket": 6, - "name": "Golden card 2", - "tier": "Gold", - "enchantment": null, - "tags_json": "[\"Weapon\",\"golden-2\"]", - "attributes_json": "{\"cooldown\":2002,\"damage\":102}" - }, - { - "source_hour": "2026-08-03T01", - "source_day": "2026-08-03", - "available_at_ms": 1785718800000, - "bundle_id": "01J00000000000000000000902", - "run_id": "payload-run", - "battle_id": "battle-000", - "card_set_label": "opponent_skills", - "card_set_status": "Captured", - "card_set_source": "capture", - "owner_side": "opponent", - "card_kind": "skill", - "slot_index": 0, - "instance_id": "instance-3", - "template_id": "00000000-0000-0000-0000-000000000004", - "card_type": 2, - "size": 1, - "section": 3, - "socket": 7, - "name": "Golden card 3", - "tier": "Silver", - "enchantment": null, - "tags_json": "[\"Weapon\",\"golden-3\"]", - "attributes_json": "{\"cooldown\":2003,\"damage\":103}" - } - ], - "quality": [ - { - "source_hour": "2026-08-03T01", - "source_day": "2026-08-03", - "bundle_id": "01J00000000000000000000902", - "run_id": "payload-run", - "code": "degraded_events", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{}" - }, - { - "source_hour": "2026-08-03T01", - "source_day": "2026-08-03", - "bundle_id": "01J00000000000000000000902", - "run_id": "payload-run", - "code": "degraded_screenshot", - "severity": "WARN", - "blocks_release": false, - "detail_json": "{}" - } - ], - "quarantine": [] -} diff --git a/bazaarplusplus-analyzer/tests/pipeline_fixtures.py b/bazaarplusplus-analyzer/tests/pipeline_fixtures.py deleted file mode 100644 index f21a371..0000000 --- a/bazaarplusplus-analyzer/tests/pipeline_fixtures.py +++ /dev/null @@ -1,426 +0,0 @@ -"""Bundles, a Bundle Server stand-in, and golden files for end-to-end pipeline tests. - -Every Bundle here reaches the analyzer the way production Bundles do: listed by -``GET /bundles``, downloaded, admitted, projected, committed, and sealed. -""" - -import base64 -import difflib -import hashlib -import json -import os -import shutil -from collections.abc import Callable, Iterable -from dataclasses import dataclass -from datetime import UTC, date, datetime, time, timedelta -from pathlib import Path - -import httpx - -from bppanalyzer.bundle_source import BundleSource -from bppanalyzer.driver import PipelineDriver -from bppanalyzer.fact_store import FactStore -from tests.bundle_fixtures import Card, bundle_bytes, envelope, payload - -REPO_ROOT = Path(__file__).resolve().parents[2] -SERVER_FIXTURES = REPO_ROOT / "bazaarplusplus-server/contracts/v6/fixtures" -MOD_RUN_FIXTURE = ( - REPO_ROOT / "bazaarplusplus-mod/tests/BundleV6Codec.Tests/fixtures/run-payload-v6.fixture.b64" -) -CONTRACT_FIXTURES = REPO_ROOT / "bazaarplusplus-analyzer/contracts/v6/fixtures" -TEST_FIXTURES = Path(__file__).parent / "fixtures" -PROJECTION_GOLDENS = TEST_FIXTURES / "projection" - -API_BASE_URL = "https://api.invalid" -DOWNLOAD_BASE_URL = "https://download.invalid" -SYNC_TOKEN = "test-token" - -MOD_BUNDLE_ID = "01J00000000000000000000902" - -# The single Source Day of the golden pipeline run. -GOLDEN_DAY = date(2026, 8, 10) - -# Real boards hold small (1), medium (2), and large (3) cards; the mod rejects -# any other size. -DOOLEY_CARDS = ( - "11111111-1111-4111-8111-111111111111", - "22222222-2222-4222-8222-222222222222", - "33333333-3333-4333-8333-333333333333", - "44444444-4444-4444-8444-444444444444", -) -JULES_CARDS = ( - "55555555-5555-4555-8555-555555555555", - "66666666-6666-4666-8666-666666666666", - "77777777-7777-4777-8777-777777777777", - "88888888-8888-4888-8888-888888888888", -) -FULL_BOARD = (3, 3, 2, 2) -SOCKET_EFFECT_CARD = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee" - - -def _ms(value: datetime) -> int: - return int(value.timestamp() * 1_000) - - -def _hour(day: date, hour: int) -> datetime: - return datetime.combine(day, time(hour), UTC) - - -def fixed_clock(now: datetime) -> Callable[[], datetime]: - return lambda: now - - -def read_base64(path: Path) -> bytes: - return base64.b64decode(path.read_text(encoding="ascii").strip(), validate=True) - - -@dataclass(frozen=True, slots=True) -class ServedBundle: - """One Bundle as the Bundle Server lists and serves it.""" - - bundle_id: str - available_at_ms: int - content: bytes - - -def server_run_only_bundle(available_at_ms: int) -> ServedBundle: - """The server's run-only golden; its Run segment never decodes.""" - fixtures = SERVER_FIXTURES - manifest = json.loads((fixtures / "run-only.manifest.json").read_text()) - content = read_base64(fixtures / "run-only.bundle.b64") - return ServedBundle(manifest["bundle_id"], available_at_ms, content) - - -def mod_run_payload_bundle(available_at_ms: int, *, created_at_ms: int) -> ServedBundle: - """Envelope the mod-encoded Run golden; the C# writer owns the Run bytes.""" - run_content = read_base64(MOD_RUN_FIXTURE) - manifest: dict[str, object] = { - "bundle_id": MOD_BUNDLE_ID, - "bundle_version": 6, - "created_at_ms": created_at_ms, - "run": { - "run_id": "payload-run", - "player_account_id": "golden-account", - "run_format_version": 6, - "projection": {"run": {}, "battles": []}, - "payload": { - "offset": 0, - "length": len(run_content), - "sha256": hashlib.sha256(run_content).hexdigest(), - "content_type": "application/x-bpp-run-v6", - }, - }, - } - return ServedBundle( - MOD_BUNDLE_ID, available_at_ms, envelope(manifest, run_content, sort_keys=True) - ) - - -def _synthetic( - bundle_id: str, - available_at_ms: int, - *, - created_at_ms: int | None = None, - **run: object, -) -> ServedBundle: - run_id = str(run.setdefault("run_id", f"run-{bundle_id}")) - account_id = str(run.setdefault("account_id", f"account-{bundle_id}")) - content = bundle_bytes( - bundle_id, - run_payload=payload(**run), # type: ignore[arg-type] - created_at_ms=created_at_ms, - run_id=run_id, - account_id=account_id, - ) - return ServedBundle(bundle_id, available_at_ms, content) - - -# One Bundle per projection rule. Each is projected alone by -# test_bundle_goldens and also served inside the golden pipeline day. -_PROJECTION_HOUR = _hour(GOLDEN_DAY, 13) -_PROJECTION_RUNS: dict[str, dict[str, object]] = { - "side-name-player-wins": { - "winner_combatant_id": "Player", - "loser_combatant_id": "Opponent", - "victories": 1, - "losses": 0, - }, - "side-name-opponent-wins": { - "winner_combatant_id": "Opponent", - "loser_combatant_id": "Player", - "victories": 0, - "losses": 1, - "final_rank": "Gold", - }, - "account-id-player-wins": { - "account_id": "account-1", - "winner_combatant_id": "account-1", - "loser_combatant_id": "account-2", - }, - "account-id-opponent-wins": { - "account_id": "account-1", - "winner_combatant_id": "account-2", - "loser_combatant_id": "account-1", - "victories": 10, - "losses": 3, - }, - "unknown-combatant-undecided": { - "winner_combatant_id": "unknown-combatant", - "loser_combatant_id": "another-unknown-combatant", - "victories": 5, - "losses": 5, - }, - "client-clock-anomalies": { - "started_at": "2026-08-11T01:00:00Z", - "battle_at": "2026-08-09T23:00:00Z", - "created_at_ms": _ms(datetime(2026, 8, 11, tzinfo=UTC)), - }, - "unaccepted-unknown-hero": {"hero": "UnknownHero", "final_rank": "Legendary"}, - "unaccepted-missing-rank": {"hero": "Vanessa", "final_rank": None}, - "unaccepted-unknown-rank": {"hero": "Vanessa", "final_rank": "Mythic"}, - "unaccepted-unknown-hero-and-rank": {"hero": "UnknownHero", "final_rank": "Mythic"}, - "hero8-alias": {"hero": "Hero8"}, - "whitespace-hero": {"hero": " Vanessa "}, -} - - -def projection_case(name: str) -> ServedBundle: - number = list(_PROJECTION_RUNS).index(name) - return _synthetic( - f"projection-{name}", - _ms(_PROJECTION_HOUR) + (number + 1) * 1_000, - **dict(_PROJECTION_RUNS[name]), - ) - - -PROJECTION_CASES: dict[str, ServedBundle] = { - name: projection_case(name) for name in _PROJECTION_RUNS -} - - -def _layout( - number: int, - hero: str, - card_ids: tuple[str, ...], - sizes: tuple[int, ...], - *, - slots: tuple[int, ...] | None = None, - tier: str | None = "Gold", - enchantments: tuple[str | None, ...] | None = None, - socket_effect_slots: tuple[int, ...] = (), - **run: object, -) -> ServedBundle: - if slots is None: - tiled = [] - cursor = 0 - for size in sizes: - tiled.append(cursor) - cursor += size - slots = tuple(tiled) - named = enchantments or (None,) * len(card_ids) - hand = [ - Card(card_id, size, slot, tier, enchantment) - for card_id, size, slot, enchantment in zip(card_ids, sizes, slots, named, strict=True) - ] - hand.extend( - Card(SOCKET_EFFECT_CARD, 1, slot, tier, card_type=7, name="[Cooler] Socket Effect") - for slot in socket_effect_slots - ) - return _synthetic( - f"layout-{number:02d}", - _ms(_hour(GOLDEN_DAY, 14)) + (number + 1) * 1_000, - hero=hero, - player_hand=hand, - **run, - ) - - -_DOOLEY_ENCHANTMENTS = (None, "Burning", None, None) - -# Build eligibility boundaries. Numbering follows the retired row-level -# policy fixture; number 2 (a final_battle_id that disagrees with the final -# Battle) cannot be expressed as a Bundle because projection derives -# final_battle_id from the one Battle flagged final. -LAYOUT_CASES: dict[str, ServedBundle] = { - "valid": _layout(0, "Dooley", DOOLEY_CARDS, FULL_BOARD, enchantments=_DOOLEY_ENCHANTMENTS), - "two-final-battles": _layout(1, "Dooley", DOOLEY_CARDS, FULL_BOARD, final_battles=2), - "missing-final-hand": _layout( - 3, "Dooley", DOOLEY_CARDS, FULL_BOARD, player_hand_status="Missing" - ), - "non-uuid-card": _layout(4, "Dooley", ("not-a-card-id", *DOOLEY_CARDS[1:]), FULL_BOARD), - "zero-size-card": _layout( - 5, "Dooley", (*DOOLEY_CARDS, JULES_CARDS[0]), (0, *FULL_BOARD), slots=(0, 0, 3, 6, 8) - ), - "nine-slots": _layout(6, "Dooley", DOOLEY_CARDS, (3, 3, 2, 1)), - "overlapping-slots": _layout(7, "Dooley", DOOLEY_CARDS, FULL_BOARD, slots=(0, 2, 6, 8)), - "overflowing-slots": _layout(8, "Dooley", DOOLEY_CARDS, FULL_BOARD, slots=(0, 3, 6, 9)), - "socket-effects-ignored": _layout( - 9, - "Dooley", - DOOLEY_CARDS, - FULL_BOARD, - enchantments=_DOOLEY_ENCHANTMENTS, - socket_effect_slots=(0, 3), - ), - "jules-gold-day-1": _layout(10, "Jules", JULES_CARDS, FULL_BOARD, run_day=1), - "jules-gold-day-2": _layout(11, "Jules", JULES_CARDS, FULL_BOARD, run_day=2), - "jules-diamond-day-3": _layout(12, "Jules", JULES_CARDS, FULL_BOARD, run_day=3, tier="Diamond"), - "jules-diamond-day-100": _layout( - 13, "Jules", JULES_CARDS, FULL_BOARD, run_day=100, tier="Diamond" - ), - "jules-eight-two": _layout( - 14, "Jules", JULES_CARDS, FULL_BOARD, victories=8, losses=2, run_day=8 - ), - "oversized-card": _layout(15, "Dooley", DOOLEY_CARDS, (4, 3, 2, 1)), - "unknown-tier": _layout(16, "Dooley", DOOLEY_CARDS, FULL_BOARD, tier="Mythic"), - "missing-tier": _layout( - 17, "Dooley", DOOLEY_CARDS, FULL_BOARD, tier=None, victories=8, losses=2 - ), - "bronze-size-boundaries": _layout(18, "Mak", DOOLEY_CARDS, (3, 3, 3, 1), tier="Bronze"), - "legendary-tier-boundary": _layout( - 19, "Stelle", DOOLEY_CARDS, (3, 3, 3, 1), tier=" Legendary " - ), -} - - -def golden_day_bundles() -> tuple[ServedBundle, ...]: - """Every Bundle of the golden Source Day; all other hours list no Bundles.""" - return ( - server_run_only_bundle(_ms(_hour(GOLDEN_DAY, 1))), - mod_run_payload_bundle(_ms(_hour(GOLDEN_DAY, 2)), created_at_ms=_ms(_hour(GOLDEN_DAY, 2))), - *PROJECTION_CASES.values(), - *LAYOUT_CASES.values(), - ) - - -def daily_bundles(start: date, days: int) -> tuple[ServedBundle, ...]: - """One accepted Dooley Run at 00:30 on each Source Day.""" - bundles = [] - for offset in range(days): - day = start + timedelta(days=offset) - midnight = _hour(day, 0) - - def stamp(minutes: int, at: datetime = midnight) -> str: - return (at + timedelta(minutes=minutes)).isoformat().replace("+00:00", "Z") - - bundles.append( - _synthetic( - f"daily-{day.isoformat()}", - _ms(midnight + timedelta(minutes=30)), - created_at_ms=_ms(midnight + timedelta(minutes=25)), - hero="Dooley", - started_at=stamp(0), - battle_at=stamp(10), - ended_at=stamp(20), - ) - ) - return tuple(bundles) - - -class BundleServer: - """``httpx.MockTransport`` handler for the Bundle Server collection contract. - - ``GET /bundles`` returns the four-field items of - ``bazaarplusplus-server/src/modules/bundle-collection.ts::BundleCollectionItem`` - in keyset order on a single page. An hour without Bundles returns ``200`` with - no items. ``GET `` returns the Bundle bytes. - """ - - def __init__(self, bundles: Iterable[ServedBundle], *, now: datetime) -> None: - self.bundles = tuple( - sorted(bundles, key=lambda item: (item.available_at_ms, item.bundle_id)) - ) - self.by_id = {bundle.bundle_id: bundle for bundle in self.bundles} - if len(self.by_id) != len(self.bundles): - raise ValueError("Served Bundle IDs must be unique") - self.download_expires_at_ms = _ms(now + timedelta(hours=1)) - - def __call__(self, request: httpx.Request) -> httpx.Response: - if request.url.host == "api.invalid" and request.url.path == "/bundles": - start = int(request.url.params["available_from_ms"]) - end = int(request.url.params["available_before_ms"]) - items = [ - { - "bundle_id": bundle.bundle_id, - "available_at_ms": bundle.available_at_ms, - "download_url": f"{DOWNLOAD_BASE_URL}/{bundle.bundle_id}", - "download_expires_at_ms": self.download_expires_at_ms, - } - for bundle in self.bundles - if start <= bundle.available_at_ms < end - ] - return httpx.Response( - 200, - json={ - "window": {"available_from_ms": start, "available_before_ms": end}, - "items": items, - "next_after": None, - }, - ) - if request.url.host == "download.invalid": - bundle = self.by_id.get(request.url.path.removeprefix("/")) - if bundle is not None: - return httpx.Response(200, content=bundle.content) - return httpx.Response(404) - - -def heal_from_bundles(root: Path, days: int, *, start: date = date(2026, 8, 7)) -> FactStore: - """Seal ``days`` consecutive Source Days from :func:`daily_bundles`, one day per run. - - Each day is healed by its own ``PipelineDriver`` run at 00:01 the next day, - so every listing stays inside the Bundle Source's eight-day retention. Only - ``facts/`` is kept, so callers start from sealed facts without the healing - runs' status, logs, or local snapshots. - """ - bundles = daily_bundles(start, days) - for offset in range(days): - source_day = start + timedelta(days=offset) - now = _hour(source_day + timedelta(days=1), 0) + timedelta(minutes=1) - server = BundleServer(bundles, now=now) - with httpx.Client(transport=httpx.MockTransport(server)) as client: - summary = PipelineDriver( - root, - source=BundleSource( - api_base_url=API_BASE_URL, - sync_token=SYNC_TOKEN, - client=client, - clock=fixed_clock(now), - ), - clock=fixed_clock(now), - duckdb_memory_limit="1GB", - duckdb_threads=1, - ).run(heal_days=2, publish=False) - if summary.failures or not FactStore(root).has_seal(source_day): - raise AssertionError(f"Fixture day {source_day} did not seal: {summary.failures}") - for path in root.iterdir(): - if path.name == "facts": - continue - if path.is_dir(): - shutil.rmtree(path) - else: - path.unlink() - return FactStore(root) - - -def assert_golden(path: Path, content: bytes) -> None: - """Compare ``content`` with a committed JSON golden, or rewrite it on request. - - ``BPP_UPDATE_GOLDENS=1`` (``just analyzer::golden``) writes the file instead. - """ - if os.environ.get("BPP_UPDATE_GOLDENS") == "1": - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(content) - return - hint = f"{path.name} differs; regenerate with `just analyzer::golden` and review the diff" - assert path.is_file(), hint - expected = path.read_bytes() - if content == expected: - return - diff = difflib.unified_diff( - _pretty(expected), _pretty(content), "committed", "observed", n=1, lineterm="" - ) - raise AssertionError("\n".join([hint, *list(diff)[:60]])) - - -def _pretty(content: bytes) -> list[str]: - return json.dumps(json.loads(content), indent=1, sort_keys=True).splitlines() diff --git a/bazaarplusplus-analyzer/tests/test_bundle_goldens.py b/bazaarplusplus-analyzer/tests/test_bundle_goldens.py deleted file mode 100644 index b4132b6..0000000 --- a/bazaarplusplus-analyzer/tests/test_bundle_goldens.py +++ /dev/null @@ -1,138 +0,0 @@ -import hashlib -import json -from datetime import UTC, datetime -from pathlib import Path - -import httpx -import pytest - -from bppanalyzer.bundle_source import ( - BundleRef, - BundleSource, - RawHourIndex, - RetryableSourceError, - SourceContractError, - admit_bundle, - raw_commit_sha256, -) -from bppanalyzer.projection import project_hour -from tests.fakes import collect_tables -from tests.pipeline_fixtures import ( - PROJECTION_CASES, - PROJECTION_GOLDENS, - assert_golden, - mod_run_payload_bundle, - read_base64, -) -from tests.pipeline_fixtures import SERVER_FIXTURES as BUNDLE_FIXTURES - -SOURCE_HOUR = datetime(2026, 8, 3, 1, tzinfo=UTC) - - -def _reference(content: bytes, bundle_id: str) -> BundleRef: - available_at_ms = int(SOURCE_HOUR.timestamp() * 1_000) - return BundleRef( - bundle_id=bundle_id, - available_at_ms=available_at_ms, - download_url=f"https://download.invalid/{bundle_id}", - download_expires_at_ms=available_at_ms + 60_000, - ) - - -def _index(ref: BundleRef) -> RawHourIndex: - return RawHourIndex( - source_hour=SOURCE_HOUR, - items=(ref,), - raw_commit_sha256=raw_commit_sha256((ref,)), - pages=1, - ) - - -def test_server_run_only_golden_matches_manifest_and_checksums() -> None: - fixtures = BUNDLE_FIXTURES - content = read_base64(fixtures / "run-only.bundle.b64") - expected_manifest = json.loads((fixtures / "run-only.manifest.json").read_text()) - checksums = json.loads((fixtures / "checksums.json").read_text())["run-only.bundle.b64"] - - bundle = admit_bundle(_reference(content, expected_manifest["bundle_id"]), content) - - assert bundle.manifest == expected_manifest - assert bundle.bytes == checksums["decoded_bytes"] - assert bundle.sha256 == checksums["sha256"] - manifest_bytes = int.from_bytes(content[12:16], "big") - assert manifest_bytes == checksums["manifest_bytes"] - payload = expected_manifest["run"]["payload"] - assert len(bundle.run_content) == payload["length"] - assert hashlib.sha256(bundle.run_content).hexdigest() == payload["sha256"] - assert bundle.run_content == content[16 + manifest_bytes + payload["offset"] :] - - -@pytest.mark.parametrize( - "filename", ["corrupt-magic.bundle.b64", "segment-digest-mismatch.bundle.b64"] -) -def test_server_corrupt_goldens_report_analyzer_validation_errors(filename: str) -> None: - fixtures = BUNDLE_FIXTURES - content = read_base64(fixtures / filename) - manifest = json.loads((fixtures / "run-only.manifest.json").read_text()) - checksums = json.loads((fixtures / "checksums.json").read_text())[filename] - reason = checksums.get("expected_reason", checksums["expected_error"]) - ref = _reference(content, manifest["bundle_id"]) - if "sha256" in checksums: - assert hashlib.sha256(content).hexdigest() == checksums["sha256"] - - with pytest.raises(SourceContractError) as rejected: - admit_bundle(ref, content) - assert rejected.value.reason == reason - - with ( - httpx.Client( - transport=httpx.MockTransport(lambda _request: httpx.Response(200, content=content)) - ) as client, - BundleSource( - api_base_url="https://api.invalid", - sync_token="test-token", - client=client, - clock=lambda: SOURCE_HOUR, - ) as source, - pytest.raises(RetryableSourceError) as streamed, - ): - list(source.stream(_index(ref))) - - assert streamed.value.reason == "bundle_validation_failed" - assert str(streamed.value) == f"Bundle validation failed: {reason}" - assert isinstance(streamed.value.__cause__, SourceContractError) - assert streamed.value.__cause__.reason == reason - - -def test_mod_run_payload_golden_projects_expected_tables() -> None: - created_at_ms = int(SOURCE_HOUR.timestamp() * 1_000) - served = mod_run_payload_bundle(created_at_ms, created_at_ms=created_at_ms) - ref = _reference(served.content, served.bundle_id) - - projection = project_hour(_index(ref), [admit_bundle(ref, served.content)]) - - tables = collect_tables(projection) - projected = {name: table.to_pylist() for name, table in tables.items()} - content = (json.dumps(projected, indent=2, ensure_ascii=False) + "\n").encode() - expected = Path(__file__).parent / "fixtures/run-payload-v6.projection.json" - assert_golden(expected, content) - assert projection.bundle_count == 1 - - -@pytest.mark.parametrize("case", sorted(PROJECTION_CASES)) -def test_projection_rule_case_matches_its_golden_tables(case: str) -> None: - served = PROJECTION_CASES[case] - ref = BundleRef( - bundle_id=served.bundle_id, - available_at_ms=served.available_at_ms, - download_url=f"https://download.invalid/{served.bundle_id}", - download_expires_at_ms=served.available_at_ms + 60_000, - ) - source_hour = datetime.fromtimestamp(served.available_at_ms // 3_600_000 * 3_600, tz=UTC) - index = RawHourIndex(source_hour, (ref,), raw_commit_sha256((ref,)), 1) - - tables = collect_tables(project_hour(index, [admit_bundle(ref, served.content)])) - - projected = {name: table.to_pylist() for name, table in tables.items()} - content = (json.dumps(projected, indent=2, ensure_ascii=False) + "\n").encode() - assert_golden(PROJECTION_GOLDENS / f"{case}.json", content) diff --git a/bazaarplusplus-analyzer/tests/test_bundle_source.py b/bazaarplusplus-analyzer/tests/test_bundle_source.py deleted file mode 100644 index ce07466..0000000 --- a/bazaarplusplus-analyzer/tests/test_bundle_source.py +++ /dev/null @@ -1,691 +0,0 @@ -import hashlib -import json -import threading -import time -from datetime import UTC, datetime - -import httpx -import pytest - -from bppanalyzer.bundle_source import ( - BundleSource, - HourExpired, - RetryableSourceError, - SourceContractError, -) -from tests.bundle_fixtures import bundle_bytes - -HOUR = datetime(2026, 8, 10, 12, tzinfo=UTC) - - -def _empty_page() -> dict[str, object]: - return { - "window": { - "available_from_ms": int(HOUR.timestamp() * 1_000), - "available_before_ms": int(HOUR.timestamp() * 1_000) + 3_600_000, - }, - "items": [], - "next_after": None, - } - - -def _one_bundle_page( - *, - download_url: str = "https://download.invalid/bundle-a", -) -> dict[str, object]: - page = _empty_page() - page["items"] = [ - { - "bundle_id": "bundle-a", - "available_at_ms": int(HOUR.timestamp() * 1_000) + 1, - "download_url": download_url, - "download_expires_at_ms": int(HOUR.timestamp() * 1_000) + 60_000, - } - ] - return page - - -def _retrying_source( - server: httpx.MockTransport, - backoffs: list[float], -) -> BundleSource: - return BundleSource( - api_base_url="https://api.invalid", - sync_token="test-token", - client=httpx.Client(transport=server), - clock=lambda: datetime(2026, 8, 11, tzinfo=UTC), - sleep=backoffs.append, - jitter=lambda delay: delay, - ) - - -def test_listing_succeeds_after_two_transient_503_responses() -> None: - attempts = 0 - backoffs: list[float] = [] - - def server(_request: httpx.Request) -> httpx.Response: - nonlocal attempts - attempts += 1 - if attempts <= 2: - return httpx.Response(503) - return httpx.Response(200, json=_empty_page()) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - index = source.hour_index(HOUR) - - assert index.items == () - assert attempts == 3 - assert backoffs == [1.0, 2.0] - - -@pytest.mark.parametrize( - ("retry_after", "expected_delay"), - [ - ("5", 5.0), - ("Tue, 11 Aug 2026 00:00:05 GMT", 5.0), - ("120", 60.0), - ], -) -def test_retry_after_delays_the_next_listing_attempt( - retry_after: str, expected_delay: float -) -> None: - attempts = 0 - backoffs: list[float] = [] - - def server(_request: httpx.Request) -> httpx.Response: - nonlocal attempts - attempts += 1 - if attempts == 1: - return httpx.Response(429, headers={"Retry-After": retry_after}) - return httpx.Response(200, json=_empty_page()) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - assert source.hour_index(HOUR).items == () - assert attempts == 2 - assert backoffs == [expected_delay] - - -def test_default_retry_backoff_uses_bounded_jitter() -> None: - attempts = 0 - backoffs: list[float] = [] - - def server(_request: httpx.Request) -> httpx.Response: - nonlocal attempts - attempts += 1 - if attempts == 1: - return httpx.Response(503) - return httpx.Response(200, json=_empty_page()) - - source = BundleSource( - api_base_url="https://api.invalid", - sync_token="test-token", - client=httpx.Client(transport=httpx.MockTransport(server)), - clock=lambda: datetime(2026, 8, 11, tzinfo=UTC), - sleep=backoffs.append, - ) - - assert source.hour_index(HOUR).items == () - assert len(backoffs) == 1 - assert 0.5 <= backoffs[0] <= 1.5 - - -@pytest.mark.parametrize("failure", ["transport", "retryable_body"]) -def test_listing_retries_transport_and_retryable_error_bodies(failure: str) -> None: - attempts = 0 - backoffs: list[float] = [] - - def server(request: httpx.Request) -> httpx.Response: - nonlocal attempts - attempts += 1 - if attempts == 1 and failure == "transport": - raise httpx.ReadError("fixture transport failure", request=request) - if attempts == 1: - return httpx.Response( - 400, - json={ - "error": { - "code": "listing_not_ready", - "message": "try later", - "retryable": True, - } - }, - ) - return httpx.Response(200, json=_empty_page()) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - assert source.hour_index(HOUR).items == () - assert attempts == 2 - assert backoffs == [1.0] - - -def test_download_succeeds_after_a_transport_error() -> None: - content = bundle_bytes("bundle-a") - download_attempts = 0 - backoffs: list[float] = [] - - def server(request: httpx.Request) -> httpx.Response: - nonlocal download_attempts - if request.url.host == "api.invalid": - return httpx.Response(200, json=_one_bundle_page()) - download_attempts += 1 - if download_attempts == 1: - raise httpx.ConnectError("fixture transport failure", request=request) - return httpx.Response(200, content=content) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - downloaded = list(source.stream(source.hour_index(HOUR))) - - assert download_attempts == 2 - assert backoffs == [1.0] - assert downloaded[0].bytes == len(content) - assert downloaded[0].manifest["bundle_id"] == "bundle-a" - - -def test_window_expired_410_is_never_retried() -> None: - attempts = 0 - backoffs: list[float] = [] - - def server(_request: httpx.Request) -> httpx.Response: - nonlocal attempts - attempts += 1 - return httpx.Response( - 410, - json={ - "error": { - "code": "window_expired", - "message": "outside retention", - "retryable": False, - } - }, - ) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - with pytest.raises(HourExpired) as raised: - source.hour_index(HOUR) - - assert raised.value.reason == "window_expired" - assert attempts == 1 - assert backoffs == [] - - -def test_download_window_expired_410_is_never_retried() -> None: - download_attempts = 0 - backoffs: list[float] = [] - - def server(request: httpx.Request) -> httpx.Response: - nonlocal download_attempts - if request.url.host == "api.invalid": - return httpx.Response(200, json=_one_bundle_page()) - download_attempts += 1 - return httpx.Response( - 410, - json={ - "error": { - "code": "window_expired", - "message": "outside retention", - "retryable": True, - } - }, - ) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - with pytest.raises(HourExpired): - list(source.stream(source.hour_index(HOUR))) - - assert download_attempts == 1 - assert backoffs == [] - - -def test_retries_exhausted_still_raise_the_retryable_source_error() -> None: - attempts = 0 - backoffs: list[float] = [] - - def server(_request: httpx.Request) -> httpx.Response: - nonlocal attempts - attempts += 1 - return httpx.Response( - 429, - json={ - "error": { - "code": "rate_limited", - "message": "try later", - "retryable": True, - } - }, - ) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - with pytest.raises(RetryableSourceError) as raised: - source.hour_index(HOUR) - - assert raised.value.reason == "rate_limited" - assert attempts == 4 - assert backoffs == [1.0, 2.0, 4.0] - - -@pytest.mark.parametrize( - ("status_code", "error_body"), - [ - (408, None), - (429, None), - (503, None), - ( - 400, - { - "error": { - "code": "download_not_ready", - "message": "try later", - "retryable": True, - } - }, - ), - ], -) -def test_download_retries_every_declared_transient_http_response( - status_code: int, - error_body: dict[str, object] | None, -) -> None: - content = bundle_bytes("bundle-a") - download_attempts = 0 - backoffs: list[float] = [] - - def server(request: httpx.Request) -> httpx.Response: - nonlocal download_attempts - if request.url.host == "api.invalid": - return httpx.Response(200, json=_one_bundle_page()) - download_attempts += 1 - if download_attempts == 1: - if error_body is not None: - return httpx.Response(status_code, json=error_body) - return httpx.Response(status_code) - return httpx.Response(200, content=content) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - downloaded = list(source.stream(source.hour_index(HOUR))) - - assert download_attempts == 2 - assert backoffs == [1.0] - assert downloaded[0].bytes == len(content) - - -@pytest.mark.parametrize( - ("status_code", "error_body"), - [ - ( - 401, - { - "error": { - "code": "unauthorized", - "message": "bad credential", - "retryable": True, - } - }, - ), - (404, None), - ], -) -def test_download_auth_and_contract_failures_are_never_retried( - status_code: int, - error_body: dict[str, object] | None, -) -> None: - download_attempts = 0 - backoffs: list[float] = [] - - def server(request: httpx.Request) -> httpx.Response: - nonlocal download_attempts - if request.url.host == "api.invalid": - return httpx.Response(200, json=_one_bundle_page()) - download_attempts += 1 - if error_body is not None: - return httpx.Response(status_code, json=error_body) - return httpx.Response(status_code) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - with pytest.raises(SourceContractError): - list(source.stream(source.hour_index(HOUR))) - - assert download_attempts == 1 - assert backoffs == [] - - -@pytest.mark.parametrize("failure", ["auth", "contract"]) -def test_listing_auth_and_contract_failures_are_never_retried(failure: str) -> None: - attempts = 0 - backoffs: list[float] = [] - - def server(_request: httpx.Request) -> httpx.Response: - nonlocal attempts - attempts += 1 - if failure == "auth": - return httpx.Response( - 401, - json={ - "error": { - "code": "unauthorized", - "message": "bad credential", - "retryable": True, - } - }, - ) - return httpx.Response(200, json={"not": "the listing contract"}) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - with pytest.raises(SourceContractError): - source.hour_index(HOUR) - - assert attempts == 1 - assert backoffs == [] - - -def test_hour_index_exhausts_keyset_pages_and_returns_ordered_deduplicated_index() -> None: - requests: list[httpx.Request] = [] - - def server(request: httpx.Request) -> httpx.Response: - requests.append(request) - cursor = request.url.params.get("after_bundle_id") - common = { - "window": { - "available_from_ms": int(HOUR.timestamp() * 1_000), - "available_before_ms": int(HOUR.timestamp() * 1_000) + 3_600_000, - } - } - if cursor is None: - return httpx.Response( - 200, - json={ - **common, - "items": [ - { - "bundle_id": "bundle-a", - "available_at_ms": int(HOUR.timestamp() * 1_000) + 1, - "download_url": "https://download.invalid/a", - "download_expires_at_ms": int(HOUR.timestamp() * 1_000) + 9_000, - } - ], - "next_after": { - "available_at_ms": int(HOUR.timestamp() * 1_000) + 1, - "bundle_id": "bundle-a", - }, - }, - ) - return httpx.Response( - 200, - json={ - **common, - "items": [ - { - "bundle_id": "bundle-a", - "available_at_ms": int(HOUR.timestamp() * 1_000) + 1, - "download_url": "https://download.invalid/a-refreshed", - "download_expires_at_ms": int(HOUR.timestamp() * 1_000) + 10_000, - }, - { - "bundle_id": "bundle-b", - "available_at_ms": int(HOUR.timestamp() * 1_000) + 2, - "download_url": "https://download.invalid/b", - "download_expires_at_ms": int(HOUR.timestamp() * 1_000) + 9_000, - }, - ], - "next_after": None, - }, - ) - - source = BundleSource( - api_base_url="https://api.invalid", - sync_token="test-token", - client=httpx.Client(transport=httpx.MockTransport(server)), - clock=lambda: datetime(2026, 8, 11, tzinfo=UTC), - ) - - index = source.hour_index(HOUR) - - assert [item.bundle_id for item in index.items] == ["bundle-a", "bundle-b"] - assert index.pages == 2 - assert len(requests) == 2 - assert requests[1].url.params["after_available_at_ms"] == str(int(HOUR.timestamp() * 1_000) + 1) - assert requests[1].url.params["after_bundle_id"] == "bundle-a" - expected_identity = [ - {"available_at_ms": int(HOUR.timestamp() * 1_000) + 1, "bundle_id": "bundle-a"}, - {"available_at_ms": int(HOUR.timestamp() * 1_000) + 2, "bundle_id": "bundle-b"}, - ] - canonical = ( - json.dumps(expected_identity, sort_keys=True, separators=(",", ":")) + "\n" - ).encode() - assert index.raw_commit_sha256 == hashlib.sha256(canonical).hexdigest() - # Every committed _commit.json recorded this digest; a change re-heals into FactConflict. - assert ( - index.raw_commit_sha256 - == "8f3360d1d6bd164764b23cf3992b9099956f258d2c32e511186ed3a1539f9558" - ) - - -def test_empty_index_past_retention_is_expired_instead_of_a_zero_row_hour() -> None: - def empty(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "window": { - "available_from_ms": int(HOUR.timestamp() * 1_000), - "available_before_ms": int(HOUR.timestamp() * 1_000) + 3_600_000, - }, - "items": [], - "next_after": None, - }, - ) - - source = BundleSource( - api_base_url="https://api.invalid", - sync_token="test-token", - client=httpx.Client(transport=httpx.MockTransport(empty)), - clock=lambda: datetime(2026, 8, 21, tzinfo=UTC), - retention_days=8, - ) - - with pytest.raises(HourExpired, match="past retention"): - source.hour_index(HOUR) - - -def test_expired_download_capability_reenumerates_the_same_fixed_hour() -> None: - content = bundle_bytes("bundle-a") - enumerations = 0 - refreshed_attempts = 0 - backoffs: list[float] = [] - - def server(request: httpx.Request) -> httpx.Response: - nonlocal enumerations, refreshed_attempts - if request.url.host == "api.invalid": - enumerations += 1 - return httpx.Response( - 200, - json=_one_bundle_page( - download_url=( - "https://download.invalid/expired" - if enumerations == 1 - else "https://download.invalid/refreshed" - ), - ), - ) - if request.url.path == "/expired": - return httpx.Response(403) - refreshed_attempts += 1 - if refreshed_attempts <= 2: - return httpx.Response(503) - return httpx.Response(200, content=content) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - index = source.hour_index(HOUR) - downloaded = list(source.stream(index)) - - assert enumerations == 2 - assert refreshed_attempts == 3 - assert backoffs == [1.0, 2.0] - assert downloaded[0].bytes == len(content) - assert downloaded[0].manifest["bundle_id"] == "bundle-a" - - -def test_download_url_refresh_is_bounded_to_one_reenumeration() -> None: - enumerations = 0 - download_attempts = 0 - backoffs: list[float] = [] - - def server(request: httpx.Request) -> httpx.Response: - nonlocal enumerations, download_attempts - if request.url.host == "api.invalid": - enumerations += 1 - return httpx.Response( - 200, - json=_one_bundle_page( - download_url=f"https://download.invalid/url-{enumerations}", - ), - ) - download_attempts += 1 - return httpx.Response(403) - - source = _retrying_source(httpx.MockTransport(server), backoffs) - - with pytest.raises(RetryableSourceError) as raised: - list(source.stream(source.hour_index(HOUR))) - - assert raised.value.reason == "download_url_expired" - assert enumerations == 2 - assert download_attempts == 2 - assert backoffs == [] - - -def test_stream_never_downloads_beyond_its_eight_bundle_lookahead() -> None: - contents = { - f"bundle-{number:02d}": bundle_bytes(f"bundle-{number:02d}") for number in range(20) - } - gate = threading.Event() - eight_started = threading.Event() - counter_lock = threading.Lock() - started = 0 - - def server(request: httpx.Request) -> httpx.Response: - nonlocal started - if request.url.host == "api.invalid": - return httpx.Response( - 200, - json={ - "window": { - "available_from_ms": int(HOUR.timestamp() * 1_000), - "available_before_ms": int(HOUR.timestamp() * 1_000) + 3_600_000, - }, - "items": [ - { - "bundle_id": bundle_id, - "available_at_ms": int(HOUR.timestamp() * 1_000) + number, - "download_url": f"https://download.invalid/{bundle_id}", - "download_expires_at_ms": int(HOUR.timestamp() * 1_000) + 60_000, - } - for number, (bundle_id, content) in enumerate(contents.items()) - ], - "next_after": None, - }, - ) - with counter_lock: - started += 1 - if started == 8: - eight_started.set() - assert gate.wait(2) - return httpx.Response(200, content=contents[request.url.path.removeprefix("/")]) - - source = BundleSource( - api_base_url="https://api.invalid", - sync_token="test-token", - client=httpx.Client(transport=httpx.MockTransport(server)), - clock=lambda: datetime(2026, 8, 11, tzinfo=UTC), - download_concurrency=16, - lookahead=8, - ) - index = source.hour_index(HOUR) - stream = source.stream(index) - result: list[object] = [] - worker = threading.Thread(target=lambda: result.append(next(stream))) - worker.start() - - assert eight_started.wait(1) - time.sleep(0.02) - assert started == 8 - gate.set() - worker.join(2) - assert len(result) == 1 - stream.close() - - -def test_stream_stops_starting_downloads_after_a_fatal_bundle_failure() -> None: - contents = {f"bundle-{number:02d}": bundle_bytes(f"bundle-{number:02d}") for number in range(8)} - second_started = threading.Event() - release_second = threading.Event() - counter_lock = threading.Lock() - started = 0 - - def server(request: httpx.Request) -> httpx.Response: - nonlocal started - if request.url.host == "api.invalid": - return httpx.Response( - 200, - json={ - "window": { - "available_from_ms": int(HOUR.timestamp() * 1_000), - "available_before_ms": int(HOUR.timestamp() * 1_000) + 3_600_000, - }, - "items": [ - { - "bundle_id": bundle_id, - "available_at_ms": int(HOUR.timestamp() * 1_000) + number, - "download_url": f"https://download.invalid/{bundle_id}", - "download_expires_at_ms": int(HOUR.timestamp() * 1_000) + 60_000, - } - for number, (bundle_id, content) in enumerate(contents.items()) - ], - "next_after": None, - }, - ) - with counter_lock: - started += 1 - observed = started - if observed == 1: - return httpx.Response(404) - if observed == 2: - second_started.set() - assert release_second.wait(2) - bundle_id = request.url.path.removeprefix("/") - return httpx.Response(200, content=contents[bundle_id]) - - source = BundleSource( - api_base_url="https://api.invalid", - sync_token="test-token", - client=httpx.Client(transport=httpx.MockTransport(server)), - clock=lambda: datetime(2026, 8, 11, tzinfo=UTC), - download_concurrency=1, - lookahead=8, - ) - errors: list[BaseException] = [] - - def consume() -> None: - try: - list(source.stream(source.hour_index(HOUR))) - except BaseException as error: - errors.append(error) - - worker = threading.Thread(target=consume) - worker.start() - assert second_started.wait(1) - release_second.set() - worker.join(2) - - assert not worker.is_alive() - assert len(errors) == 1 and isinstance(errors[0], SourceContractError) - assert started <= 2 diff --git a/bazaarplusplus-analyzer/tests/test_cli.py b/bazaarplusplus-analyzer/tests/test_cli.py deleted file mode 100644 index 1b07aec..0000000 --- a/bazaarplusplus-analyzer/tests/test_cli.py +++ /dev/null @@ -1,78 +0,0 @@ -import json -from datetime import UTC, datetime -from functools import partial -from pathlib import Path - -from click.testing import CliRunner - -import bppanalyzer.cli as cli -from bppanalyzer.bundle_source import RetryableSourceError -from bppanalyzer.config import Config -from bppanalyzer.driver import PipelineDriver -from bppanalyzer.locking import DirectoryLock -from tests.fakes import MemoryObjectStore - - -class FailedContextSource: - def __init__(self, **_kwargs) -> None: - pass - - def __enter__(self): - return self - - def __exit__(self, *_args) -> None: - pass - - def hour_index(self, _source_hour): - raise RetryableSourceError("fixture_retryable", "fixture failed") - - def stream(self, _index): - raise AssertionError("A failed index must never be streamed") - - -def _config(root: Path) -> Config: - return Config(root, "https://api.invalid", "test-token") - - -def test_cli_preserves_usage_lock_and_partial_exit_codes(tmp_path: Path, monkeypatch) -> None: - now = datetime(2026, 8, 7, 1, 1, tzinfo=UTC) - monkeypatch.setattr(cli, "load_config", lambda **_kwargs: _config(tmp_path)) - monkeypatch.setattr(cli, "BundleSource", FailedContextSource) - monkeypatch.setattr(cli, "PipelineDriver", partial(PipelineDriver, clock=lambda: now)) - monkeypatch.setattr(cli, "_object_store", lambda _config: MemoryObjectStore()) - runner = CliRunner() - - assert runner.invoke(cli.main, ["run", "--heal-days", "0"]).exit_code == 2 - holder = DirectoryLock(tmp_path, "held-by-test", heartbeat_interval=60) - holder.acquire() - try: - assert runner.invoke(cli.main, ["run"]).exit_code == 3 - finally: - holder.release() - partial_result = runner.invoke(cli.main, ["run", "--heal-days", "1", "--quiet"]) - assert partial_result.exit_code == 4 - assert "source hour failed: 2026-08-07T00 (fixture_retryable)" in partial_result.output - - -def test_cli_status_text_shows_live_current_run_progress(tmp_path: Path, monkeypatch) -> None: - status = { - "facts": {"newest_sealed_day": None, "abandoned_days": []}, - "current_run": { - "run_id": "live-run", - "phase": "heal", - "step": "ingest", - "current_hour": "2026-08-07T00", - "hours_done": 1, - "hours_planned": 2, - }, - "last_run": {"outcome": "ok"}, - } - (tmp_path / "status.json").write_text(json.dumps(status)) - monkeypatch.setattr(cli, "load_config", lambda **_kwargs: Config(tmp_path, None, None)) - - result = CliRunner().invoke(cli.main, ["status"]) - - assert result.exit_code == 0 - assert ( - "current run: live-run phase=heal step=ingest hour=2026-08-07T00 hours=1/2" in result.output - ) diff --git a/bazaarplusplus-analyzer/tests/test_config.py b/bazaarplusplus-analyzer/tests/test_config.py deleted file mode 100644 index 266b014..0000000 --- a/bazaarplusplus-analyzer/tests/test_config.py +++ /dev/null @@ -1,109 +0,0 @@ -from datetime import date -from pathlib import Path - -import pytest - -from bppanalyzer.config import ConfigurationError, load_config - - -def _write_env(root: Path, extra: str = "") -> None: - (root / ".env").write_text( - "BPP_DATA_ROOT=fixture-data\n" - "BPP_API_BASE_URL=https://api.invalid\n" - "BPP_BUNDLE_SYNC_TOKEN=fixture-sync-token\n" - f"{extra}" - ) - - -def test_object_store_configuration_is_complete_and_credentials_are_repr_safe( - tmp_path: Path, -) -> None: - _write_env( - tmp_path, - "BPP_METRICS_R2_BUCKET=fixture-bucket\n" - "CLOUDFLARE_ACCOUNT_ID=fixture-account\n" - "CLOUDFLARE_API_TOKEN=fixture-token\n", - ) - - config = load_config(root=tmp_path, require_object_store=True) - - assert config.data_root == tmp_path / "fixture-data" - assert config.r2_bucket == "fixture-bucket" - assert config.cloudflare_account_id == "fixture-account" - assert config.cloudflare_api_token == "fixture-token" - assert "fixture-token" not in repr(config) - - -@pytest.mark.parametrize( - "extra", - ( - "BPP_METRICS_R2_BUCKET=fixture-bucket\n", - "BPP_METRICS_R2_BUCKET=fixture-bucket\nCLOUDFLARE_ACCOUNT_ID=fixture-account\n", - "CLOUDFLARE_ACCOUNT_ID=fixture-account\nCLOUDFLARE_API_TOKEN=fixture-token\n", - # The earlier layout's derived pair is not a token. - "BPP_METRICS_R2_BUCKET=fixture-bucket\nBPP_METRICS_R2_ACCOUNT_ID=a\n" - "BPP_METRICS_R2_ACCESS_KEY_ID=k\nBPP_METRICS_R2_SECRET_ACCESS_KEY=s\n", - ), -) -def test_object_store_configuration_rejects_partial_r2_credentials( - tmp_path: Path, extra: str -) -> None: - _write_env(tmp_path, extra) - - with pytest.raises(ConfigurationError, match="object-store configuration"): - load_config(root=tmp_path, require_object_store=True) - - -@pytest.mark.parametrize( - ("extra", "message"), - ( - ("BPP_DOWNLOAD_CONCURRENCY=zero\n", "positive integer"), - ("BPP_DUCKDB_THREADS=0\n", "positive integer"), - ("BPP_DUCKDB_MEMORY_LIMIT=large\n", "positive size"), - ("BPP_DUCKDB_MEMORY_LIMIT=0GB\n", "positive size"), - ), -) -def test_numeric_and_memory_configuration_is_strict( - tmp_path: Path, extra: str, message: str -) -> None: - _write_env(tmp_path, extra) - - with pytest.raises(ConfigurationError, match=message): - load_config(root=tmp_path) - - -def test_missing_env_and_source_configuration_are_rejected(tmp_path: Path) -> None: - with pytest.raises(ConfigurationError, match=r"\.env"): - load_config(root=tmp_path) - (tmp_path / ".env").write_text("BPP_DATA_ROOT=data\n") - with pytest.raises(ConfigurationError, match="Bundle Server"): - load_config(root=tmp_path) - - -def test_source_epoch_is_optional_and_parsed_as_a_strict_utc_date(tmp_path: Path) -> None: - _write_env(tmp_path) - config = load_config(root=tmp_path) - assert config.source_epoch is None - assert config.bundle_retention_days == 8 - assert config.download_concurrency == 64 - assert config.download_lookahead == 128 - assert config.max_run_seconds == 21600 - - _write_env(tmp_path, "BPP_SOURCE_EPOCH=2026-08-07\n") - assert load_config(root=tmp_path).source_epoch == date(2026, 8, 7) - - _write_env(tmp_path, "BPP_SOURCE_EPOCH=2026-8-7\n") - with pytest.raises(ConfigurationError, match=r"BPP_SOURCE_EPOCH.*YYYY-MM-DD"): - load_config(root=tmp_path) - - -def test_fact_retention_defaults_to_eight_and_rejects_shorter_windows(tmp_path: Path) -> None: - _write_env(tmp_path) - assert load_config(root=tmp_path).fact_retention_days == 8 - - _write_env(tmp_path, "BPP_FACT_RETENTION_DAYS=12\n") - assert load_config(root=tmp_path).fact_retention_days == 12 - - _write_env(tmp_path, "BPP_FACT_RETENTION_DAYS=7\n") - with pytest.raises(ConfigurationError, match="BPP_FACT_RETENTION_DAYS must be at least 8"): - load_config(root=tmp_path) diff --git a/bazaarplusplus-analyzer/tests/test_driver.py b/bazaarplusplus-analyzer/tests/test_driver.py deleted file mode 100644 index f7d37b8..0000000 --- a/bazaarplusplus-analyzer/tests/test_driver.py +++ /dev/null @@ -1,693 +0,0 @@ -import json -from datetime import UTC, date, datetime -from pathlib import Path - -import httpx -import pytest - -from bppanalyzer.bundle_source import ( - BundleRef, - BundleSource, - HourExpired, - RawHourIndex, - RetryableSourceError, - admit_bundle, - raw_commit_sha256, -) -from bppanalyzer.driver import PipelineDriver -from bppanalyzer.fact_store import FactStore -from bppanalyzer.locking import DirectoryLock, LockOwnershipLost, MaximumRunTimeExceeded -from bppanalyzer.operational_evidence import OperationalEvidence, read_status -from bppanalyzer.publication import BUILDS_KEY, HEROES_KEY, SnapshotBuilder -from tests.bundle_fixtures import bundle_bytes -from tests.fakes import MemoryObjectStore -from tests.pipeline_fixtures import heal_from_bundles - - -def _driver(data_root: Path, **kwargs) -> PipelineDriver: - return PipelineDriver(data_root, duckdb_memory_limit="1GB", duckdb_threads=1, **kwargs) - - -def _fail_heroes(_builder: SnapshotBuilder, _window) -> None: - raise RuntimeError("fixture heroes failure") - - -class NeverSource: - def hour_index(self, _source_hour): - raise AssertionError("Sealed days must not reach the Bundle Server") - - def stream(self, _index): - raise AssertionError("Sealed days must not reach the Bundle Server") - - -class InvalidBundleSource: - def hour_index(self, source_hour: datetime) -> RawHourIndex: - milliseconds = int(source_hour.timestamp() * 1000) - item = BundleRef( - bundle_id="bad-bundle", - available_at_ms=milliseconds, - download_url="https://download.invalid/bad", - download_expires_at_ms=milliseconds + 3_600_000, - ) - return RawHourIndex(source_hour, (item,), raw_commit_sha256((item,)), 1) - - def stream(self, _index: RawHourIndex): - raise RetryableSourceError("bundle_validation_failed", "fixture Bundle validation failed") - - -class ExpiredSource: - def hour_index(self, _source_hour): - raise HourExpired("source_hour_expired", "fixture expired") - - def stream(self, _index): - raise AssertionError("An expired index must never be streamed") - - -class UnexpectedSource: - def hour_index(self, _source_hour): - raise RuntimeError("fixture unexpected failure") - - def stream(self, _index): - raise AssertionError("A failed index must never be streamed") - - -class RecordingExpiredSource: - def __init__(self) -> None: - self.requested_hours: list[datetime] = [] - - def hour_index(self, source_hour: datetime): - self.requested_hours.append(source_hour) - raise HourExpired("source_hour_expired", "fixture expired") - - def stream(self, _index): - raise AssertionError("An expired index must never be streamed") - - -def test_one_complete_day_publishes_a_one_day_window(tmp_path: Path) -> None: - root = tmp_path / "facts" - heal_from_bundles(root, 1) - objects = MemoryObjectStore() - - summary = _driver( - root, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 7, 23, 59, tzinfo=UTC), - object_store=objects, - ).run(heal_days=1, anchor_day=date(2026, 8, 7)) - - assert summary.exit_code == 0 - assert summary.outcome == "noop" - assert summary.report["window"] == { - "start": "2026-08-07", - "end": "2026-08-07", - "days": 1, - } - assert objects.put_keys() == [ - HEROES_KEY, - BUILDS_KEY, - ] - - -def test_successful_publication_prunes_facts_to_eight_latest_sealed_days( - nine_sealed_days: Path, -) -> None: - root = nine_sealed_days - objects = MemoryObjectStore() - - summary = _driver( - root, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 15, 23, 59, tzinfo=UTC), - object_store=objects, - ).run(heal_days=9) - - assert summary.exit_code == 0 - assert summary.report["window"] == { - "start": "2026-08-09", - "end": "2026-08-15", - "days": 7, - } - assert summary.report["retention"]["source_days_pruned"] == 1 - assert summary.report["retention"]["hours_pruned"] == 24 - assert summary.report["retention"]["files_pruned"] == 145 - assert summary.report["retention"]["bytes_pruned"] > 0 - assert [seal.source_day for seal in FactStore(root).seals()] == [ - "2026-08-08", - "2026-08-09", - "2026-08-10", - "2026-08-11", - "2026-08-12", - "2026-08-13", - "2026-08-14", - "2026-08-15", - ] - assert FactStore(root).verify(deep=True).hours_verified == 8 * 24 - - -def test_driver_honors_a_longer_fact_retention_window(nine_sealed_days: Path) -> None: - root = nine_sealed_days - - summary = _driver( - root, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 15, 23, 59, tzinfo=UTC), - object_store=MemoryObjectStore(), - fact_retention_days=9, - ).run(heal_days=9) - - assert summary.exit_code == 0 - assert len(FactStore(root).seals()) == 9 - - -def test_source_epoch_prevents_pre_epoch_days_from_being_healed_or_considered( - tmp_path: Path, -) -> None: - source = RecordingExpiredSource() - - summary = _driver( - tmp_path, - source=source, - source_epoch=date(2026, 8, 7), - clock=lambda: datetime(2026, 8, 9, 1, 1, tzinfo=UTC), - ).run(heal_days=5) - - assert [hour.date() for hour in source.requested_hours] == [ - date(2026, 8, 7), - date(2026, 8, 8), - date(2026, 8, 9), - ] - assert summary.report["window"] is None - status = read_status(tmp_path) - assert all(day >= "2026-08-07" for day in status["facts"]["sealed_days"]) - assert all(item["source_day"] >= "2026-08-07" for item in status["facts"]["abandoned_days"]) - - -def test_driver_publishes_exactly_two_objects_and_records_the_structured_run_report( - tmp_path: Path, canonical_fact_store -) -> None: - root, _store = canonical_fact_store - objects = MemoryObjectStore() - - summary = _driver( - root, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 13, 23, 59, tzinfo=UTC), - object_store=objects, - ).run(heal_days=7) - - assert summary.exit_code == 0 - assert objects.put_keys() == [ - HEROES_KEY, - BUILDS_KEY, - ] - status = json.loads((root / "status.json").read_bytes()) - assert status["last_run"]["report"] == summary.report - assert status["publication"] == { - "heroes": {"present": True, "window_end": "2026-08-13"}, - "builds": {"present": True, "window_end": "2026-08-13"}, - } - assert json.loads((root / "runs.jsonl").read_text().splitlines()[-1]) == status["last_run"] - log = "".join(path.read_text() for path in (root / "logs").glob("*.log")) - assert 'run report: {"builds":' in log - - -def test_one_product_failure_preserves_it_but_the_other_product_still_updates( - tmp_path: Path, canonical_fact_store, monkeypatch: pytest.MonkeyPatch -) -> None: - root, _store = canonical_fact_store - objects = MemoryObjectStore() - old_heroes = b'{"old":"heroes"}\n' - objects.put( - HEROES_KEY, - old_heroes, - cache_control="public,max-age=60,must-revalidate", - content_type="application/json", - ) - - monkeypatch.setattr(SnapshotBuilder, "build_heroes", _fail_heroes) - summary = _driver( - root, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 13, 23, 59, tzinfo=UTC), - object_store=objects, - ).run(heal_days=7) - - assert summary.outcome == "partial" - assert summary.exit_code == 4 - assert summary.report["heroes"]["published"] is False - assert summary.report["builds"]["published"] is True - assert objects.get(HEROES_KEY).body == old_heroes - assert objects.get(BUILDS_KEY) is not None - - -def test_one_product_failure_does_not_prune_old_facts( - nine_sealed_days: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - root = nine_sealed_days - - monkeypatch.setattr(SnapshotBuilder, "build_heroes", _fail_heroes) - summary = _driver( - root, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 15, 23, 59, tzinfo=UTC), - object_store=MemoryObjectStore(), - ).run(heal_days=9) - - assert summary.exit_code == 4 - assert len(FactStore(root).seals()) == 9 - assert FactStore(root).committed_hours()[0] == "2026-08-07T00" - - -def test_failed_bundle_is_reported_and_its_source_hour_remains_incomplete( - tmp_path: Path, -) -> None: - now = datetime(2026, 8, 7, 1, 1, tzinfo=UTC) - - summary = _driver( - tmp_path, - source=InvalidBundleSource(), - clock=lambda: now, - ).run(heal_days=1) - - assert summary.outcome == "partial" - assert summary.exit_code == 4 - assert summary.report["downloads"] == { - "expected_bundles": 1, - "succeeded_bundles": 0, - "failed_bundles": 1, - "listing_pages": 1, - "listing_requests": 0, - "listing_retries": 0, - "download_attempts": 0, - "download_retries": 0, - "downloaded_bytes": 0, - "download_latency_ms_p50": None, - "download_latency_ms_p95": None, - } - assert summary.report["window"] is None - assert not (tmp_path / "facts/hourly/source_hour=2026-08-07T00").exists() - status = json.loads((tmp_path / "status.json").read_bytes()) - assert "2026-08-07T00" in status["facts"]["incomplete_days"][0]["missing_hours"] - - -def test_run_summary_records_low_cardinality_source_performance(tmp_path: Path) -> None: - now = datetime(2026, 8, 7, 1, 1, tzinfo=UTC) - content = bundle_bytes("bundle-a") - download_attempts = 0 - sleeps: list[float] = [] - - def server(request: httpx.Request) -> httpx.Response: - nonlocal download_attempts - if request.url.host == "api.invalid": - timestamp = int(datetime(2026, 8, 7, tzinfo=UTC).timestamp() * 1_000) - return httpx.Response( - 200, - json={ - "window": { - "available_from_ms": timestamp, - "available_before_ms": timestamp + 3_600_000, - }, - "items": [ - { - "bundle_id": "bundle-a", - "available_at_ms": timestamp, - "download_url": "https://download.invalid/bundle-a", - "download_expires_at_ms": timestamp + 60_000, - } - ], - "next_after": None, - }, - ) - download_attempts += 1 - if download_attempts == 1: - return httpx.Response(503) - return httpx.Response(200, content=content) - - source = BundleSource( - api_base_url="https://api.invalid", - sync_token="test-token", - client=httpx.Client(transport=httpx.MockTransport(server)), - clock=lambda: now, - sleep=sleeps.append, - jitter=lambda delay: delay, - ) - - summary = _driver(tmp_path, source=source, clock=lambda: now).run(heal_days=1) - - downloads = summary.report["downloads"] - assert { - key: downloads[key] - for key in ( - "expected_bundles", - "succeeded_bundles", - "failed_bundles", - "listing_pages", - "listing_requests", - "listing_retries", - "download_attempts", - "download_retries", - "downloaded_bytes", - ) - } == { - "expected_bundles": 1, - "succeeded_bundles": 1, - "failed_bundles": 0, - "listing_pages": 1, - "listing_requests": 1, - "listing_retries": 0, - "download_attempts": 2, - "download_retries": 1, - "downloaded_bytes": len(content), - } - assert isinstance(downloads["download_latency_ms_p50"], float) - assert isinstance(downloads["download_latency_ms_p95"], float) - assert 0 <= downloads["download_latency_ms_p50"] <= downloads["download_latency_ms_p95"] - assert sleeps == [1.0] - assert summary.timings["retry_sleep_seconds"] == 1.0 - for name in ( - "source_index_seconds", - "source_ingest_seconds", - "download_wait_seconds", - "batch_generation_seconds", - "projection_seconds", - "parquet_write_seconds", - "fact_finalize_seconds", - ): - assert summary.timings[name] >= 0 - status = json.loads((tmp_path / "status.json").read_bytes()) - assert status["last_run"]["timings"] == summary.timings - log = "".join(path.read_text() for path in (tmp_path / "logs").glob("*.log")) - assert 'performance report: {"downloads":' in log - - -def test_no_publish_writes_valid_local_snapshots_without_object_store_calls( - nine_sealed_days: Path, -) -> None: - root = nine_sealed_days - objects = MemoryObjectStore() - - summary = _driver( - root, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 15, 23, 59, tzinfo=UTC), - object_store=objects, - ).run(heal_days=9, publish=False) - - assert summary.report["heroes"]["published"] is False - assert summary.report["builds"]["published"] is False - assert objects.requests == [] - assert (root / "snapshots/heroes/latest.json").is_file() - assert (root / "snapshots/builds/latest.json").is_file() - assert len(FactStore(root).seals()) == 9 - assert FactStore(root).committed_hours()[0] == "2026-08-07T00" - - -def test_expired_hour_abandons_the_day_and_is_visible_in_status(tmp_path: Path) -> None: - now = datetime(2026, 8, 7, 1, 1, tzinfo=UTC) - - summary = _driver(tmp_path, source=ExpiredSource(), clock=lambda: now).run(heal_days=1) - - assert summary.exit_code == 0 - status = read_status(tmp_path) - assert status["facts"]["abandoned_days"][0]["source_day"] == "2026-08-07" - assert status["facts"]["abandoned_days"][0]["reason"] == "source_hour_expired" - - -def test_unexpected_failure_is_recorded_before_it_is_reraised(tmp_path: Path) -> None: - now = datetime(2026, 8, 7, 1, 1, tzinfo=UTC) - - with pytest.raises(RuntimeError, match="fixture unexpected failure"): - _driver(tmp_path, source=UnexpectedSource(), clock=lambda: now).run(heal_days=1) - - status = read_status(tmp_path) - assert status["last_run"]["outcome"] == "error" - assert status["last_run"]["failures"][-1] == { - "scope": "run", - "reason": "fixture unexpected failure", - } - - -def test_retention_failure_preserves_published_facts_in_terminal_evidence( - tmp_path: Path, canonical_fact_store, monkeypatch: pytest.MonkeyPatch -) -> None: - root, _store = canonical_fact_store - objects = MemoryObjectStore() - failure = OSError("fixture retention failure") - - def fail_prune(self, *, retain_days): - raise failure - - monkeypatch.setattr(FactStore, "prune", fail_prune) - with pytest.raises(OSError, match="fixture retention failure") as raised: - _driver( - root, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 13, 23, 59, tzinfo=UTC), - object_store=objects, - ).run(heal_days=7) - - assert raised.value is failure - summary = read_status(root)["last_run"] - assert summary["outcome"] == "error" - assert summary["exit_code"] == 1 - assert summary["report"]["heroes"]["published"] is True - assert summary["report"]["builds"]["published"] is True - assert summary["report"]["window"]["end"] == "2026-08-13" - assert summary["report"]["facts"]["included_runs"] == 7 - assert summary["failures"][-1] == {"scope": "run", "reason": str(failure)} - assert json.loads((root / "runs.jsonl").read_text().splitlines()[-1]) == summary - assert objects.put_keys() == [ - HEROES_KEY, - BUILDS_KEY, - ] - - -@pytest.mark.parametrize("expired", [False, True]) -def test_terminal_evidence_requires_lock_ownership_even_after_a_runtime_limit( - tmp_path: Path, expired: bool -) -> None: - failure = ( - MaximumRunTimeExceeded("fixture runtime limit") - if expired - else LockOwnershipLost("fixture lost owner") - ) - - class InterruptedSource(UnexpectedSource): - def hour_index(self, _source_hour): - raise failure - - with pytest.raises(type(failure)) as raised: - _driver( - tmp_path, - source=InterruptedSource(), - clock=lambda: datetime(2026, 8, 7, 1, 1, tzinfo=UTC), - ).run(heal_days=1) - - assert raised.value is failure - status = read_status(tmp_path) - if expired: - assert status["last_run"]["outcome"] == "error" - assert status["last_run"]["failures"][-1]["reason"] == str(failure) - assert len((tmp_path / "runs.jsonl").read_text().splitlines()) == 1 - else: - assert status["last_run"] is None - assert not (tmp_path / "runs.jsonl").exists() - - -@pytest.mark.parametrize("failure_type", [OSError, KeyboardInterrupt]) -def test_terminal_log_failure_is_recorded_and_reraised( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure_type: type[BaseException] -) -> None: - failure = failure_type("fixture terminal log failure") - original_log = OperationalEvidence.log - - def fail_terminal_log(self, message): - if message.startswith("performance report:"): - raise failure - original_log(self, message) - - monkeypatch.setattr(OperationalEvidence, "log", fail_terminal_log) - with pytest.raises(failure_type) as raised: - _driver( - tmp_path, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 7, 0, 1, tzinfo=UTC), - ).run(heal_days=1) - - assert raised.value is failure - summary = read_status(tmp_path)["last_run"] - assert summary["outcome"] == "error" - assert summary["exit_code"] == 1 - assert summary["failures"] == [{"scope": "run", "reason": str(failure)}] - assert [json.loads(line) for line in (tmp_path / "runs.jsonl").read_text().splitlines()] == [ - summary - ] - - -@pytest.mark.parametrize("replaced_owner", [False, True]) -def test_runtime_limit_first_reached_during_terminal_logging_requires_current_owner( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replaced_owner: bool -) -> None: - failure = MaximumRunTimeExceeded("fixture terminal runtime limit") - original_log = OperationalEvidence.log - original_assert_owned = DirectoryLock.assert_owned - deadline_reached = False - - def expire_at_terminal_log(self, message): - nonlocal deadline_reached - if message.startswith("performance report:"): - deadline_reached = True - if replaced_owner: - (tmp_path / ".lock/heartbeat").write_text(json.dumps({"run_id": "replacement"})) - original_log(self, message) - - def assert_owned(self): - if deadline_reached: - raise failure - original_assert_owned(self) - - monkeypatch.setattr(OperationalEvidence, "log", expire_at_terminal_log) - monkeypatch.setattr(DirectoryLock, "assert_owned", assert_owned) - with pytest.raises(MaximumRunTimeExceeded) as raised: - _driver( - tmp_path, - source=NeverSource(), - clock=lambda: datetime(2026, 8, 7, 0, 1, tzinfo=UTC), - ).run(heal_days=1) - - assert raised.value is failure - summary = read_status(tmp_path)["last_run"] - if replaced_owner: - assert summary is None - assert not (tmp_path / "runs.jsonl").exists() - assert isinstance(raised.value.__context__, LockOwnershipLost) - else: - assert summary["outcome"] == "error" - assert summary["failures"] == [{"scope": "run", "reason": str(failure)}] - assert [ - json.loads(line) for line in (tmp_path / "runs.jsonl").read_text().splitlines() - ] == [summary] - - -@pytest.mark.parametrize("outcome", ["complete", "retryable", "fenced", "retryable_then_complete"]) -def test_hour_intake_keeps_live_checkpoints_and_terminal_counts( - tmp_path: Path, outcome: str -) -> None: - observed: list[dict] = [] - before_fence: dict[Path, bytes] = {} - - def capture() -> None: - current = read_status(tmp_path)["current_run"] - assert current is not None - observed.append(current) - assert current["phase"] == "heal" - - class LiveSource: - def hour_index(self, source_hour: datetime) -> RawHourIndex: - capture() - assert observed[-1]["step"] == "index" - timestamp = int(source_hour.timestamp() * 1_000) - refs = tuple( - BundleRef( - bundle_id=f"bundle-{number}", - available_at_ms=timestamp + number, - download_url=f"https://download.invalid/bundle-{number}", - download_expires_at_ms=timestamp + 60_000, - ) - for number in range(2) - ) - return RawHourIndex(source_hour, refs, raw_commit_sha256(refs), 1) - - def stream(self, index: RawHourIndex): - capture() - assert observed[-1]["bundles"] == {"done": 0, "total": 2} - for number, ref in enumerate(index.items): - yield admit_bundle(ref, bundle_bytes(ref.bundle_id)) - capture() - assert observed[-1]["step"] == "ingest" - assert observed[-1]["bundles"] == {"done": number + 1, "total": 2} - assert ( - index.source_hour.strftime("%Y-%m-%dT%H") - not in FactStore(tmp_path).committed_hours() - ) - if number == 0 and index.source_hour.hour == 0: - if outcome in {"retryable", "retryable_then_complete"}: - raise RetryableSourceError("fixture_download", "fixture download failed") - if outcome == "fenced": - for path in [tmp_path / "status.json", *(tmp_path / "logs").glob("*.log")]: - before_fence[path] = path.read_bytes() - (tmp_path / ".lock/heartbeat").write_text( - json.dumps({"run_id": "replacement"}) - ) - - def report(message: str) -> None: - if message.startswith("healed "): - capture() - assert observed[-1]["step"] == "complete" - assert observed[-1]["hours_done"] == 1 - - now = datetime(2026, 8, 7, 2 if outcome == "retryable_then_complete" else 1, 1, tzinfo=UTC) - driver = _driver(tmp_path, source=LiveSource(), clock=lambda: now) - if outcome == "fenced": - with pytest.raises(LockOwnershipLost): - driver.run(heal_days=1, progress_callback=report) - assert before_fence - assert all(path.read_bytes() == content for path, content in before_fence.items()) - assert FactStore(tmp_path).committed_hours() == () - assert not (tmp_path / "runs.jsonl").exists() - return - - summary = driver.run(heal_days=1, progress_callback=report) - downloads = summary.report["downloads"] - expected, succeeded, failed, hours = { - "complete": (2, 2, 0, 1), - "retryable": (2, 1, 1, 0), - "retryable_then_complete": (4, 3, 1, 1), - }[outcome] - assert downloads["expected_bundles"] == expected - assert downloads["succeeded_bundles"] == succeeded - assert downloads["failed_bundles"] == failed - assert downloads["listing_pages"] == (2 if outcome == "retryable_then_complete" else 1) - assert summary.hours_ingested == hours - assert len(summary.failures) == failed - assert len(FactStore(tmp_path).committed_hours()) == hours - assert read_status(tmp_path)["current_run"] is None - assert read_status(tmp_path)["last_run"]["report"] == summary.report - - -@pytest.mark.parametrize("message_prefix", ["hour indexed:", "hour ingest progress:", "healed "]) -@pytest.mark.parametrize("error_type", [HourExpired, RetryableSourceError]) -def test_observer_failure_is_fatal_even_when_its_type_matches_a_source_error( - tmp_path: Path, message_prefix: str, error_type -) -> None: - error = error_type("fixture_observer", "fixture progress observer failed") - - class OneBundleSource(InvalidBundleSource): - def stream(self, index: RawHourIndex): - for ref in index.items: - yield admit_bundle(ref, bundle_bytes(ref.bundle_id)) - - def report(message: str) -> None: - if message.startswith(message_prefix): - raise error - - with pytest.raises(error_type) as raised: - _driver( - tmp_path, - source=OneBundleSource(), - clock=lambda: datetime(2026, 8, 7, 1, 1, tzinfo=UTC), - ).run(heal_days=1, progress_callback=report) - - assert raised.value is error - summary = read_status(tmp_path)["last_run"] - assert summary["outcome"] == "error" - assert summary["failures"] == [{"scope": "run", "reason": "fixture_observer"}] - assert summary["days_abandoned"] == 0 - assert summary["report"]["downloads"]["expected_bundles"] == 1 - assert summary["report"]["downloads"]["succeeded_bundles"] == ( - 0 if message_prefix == "hour indexed:" else 1 - ) - assert summary["report"]["downloads"]["failed_bundles"] == 0 - committed = message_prefix == "healed " - assert summary["hours_ingested"] == int(committed) - assert FactStore(tmp_path).has_hour("2026-08-07T00") is committed diff --git a/bazaarplusplus-analyzer/tests/test_fact_store.py b/bazaarplusplus-analyzer/tests/test_fact_store.py deleted file mode 100644 index a3b8308..0000000 --- a/bazaarplusplus-analyzer/tests/test_fact_store.py +++ /dev/null @@ -1,94 +0,0 @@ -from datetime import UTC, datetime -from pathlib import Path - -import pytest - -from bppanalyzer.fact_store import FactConflict, FactCorrupt, FactMissing, FactStore -from bppanalyzer.projection import HourProjection -from tests.fakes import empty_projection - -HOUR = datetime(2026, 8, 10, 12, tzinfo=UTC) - - -def _empty_hour(hour: datetime = HOUR, raw_commit_sha256: str = "a" * 64) -> HourProjection: - return empty_projection(hour, raw_commit_sha256) - - -def test_identical_recommit_is_reused_but_different_canonical_commit_is_a_hard_conflict( - tmp_path: Path, -) -> None: - store = FactStore(tmp_path) - - first = store.commit_hour(_empty_hour()) - second = store.commit_hour(_empty_hour()) - - assert first.reused is False - assert second.reused is True - assert second.fact_commit_sha256 == first.fact_commit_sha256 - with pytest.raises(FactConflict, match="commit conflict"): - store.commit_hour(_empty_hour(raw_commit_sha256="b" * 64)) - assert store.commit_hour(_empty_hour()).fact_commit_sha256 == first.fact_commit_sha256 - - -def test_seal_requires_exactly_24_independently_verified_hours(tmp_path: Path) -> None: - store = FactStore(tmp_path) - for hour_number in range(23): - store.commit_hour(_empty_hour(datetime(2026, 8, 10, hour_number, tzinfo=UTC))) - - with pytest.raises(FactMissing, match="2026-08-10T23"): - store.seal_day("2026-08-10") - - store.commit_hour(_empty_hour(datetime(2026, 8, 10, 23, tzinfo=UTC))) - damaged = tmp_path / "facts/hourly/source_hour=2026-08-10T07/quality.parquet" - damaged.write_bytes(damaged.read_bytes()[:-1]) - - with pytest.raises(FactCorrupt, match="size differs"): - store.seal_day("2026-08-10") - - -def test_verify_rehashes_parquet_and_hour_paths_expose_only_a_sealed_window( - tmp_path: Path, -) -> None: - store = FactStore(tmp_path) - for hour_number in range(24): - store.commit_hour(_empty_hour(datetime(2026, 8, 10, hour_number, tzinfo=UTC))) - store.seal_day("2026-08-10") - - paths = store.hour_paths(["2026-08-10"]) - assert set(paths) == {"runs", "battles", "battle_cards", "quality", "quarantine"} - assert all(len(values) == 24 for values in paths.values()) - assert store.verify("2026-08-10").files_verified == 120 - - damaged = tmp_path / "facts/hourly/source_hour=2026-08-10T07/runs.parquet" - content = bytearray(damaged.read_bytes()) - content[len(content) // 2] ^= 1 - damaged.write_bytes(content) - - with pytest.raises(FactCorrupt, match="checksum differs"): - store.verify("2026-08-10") - - -def test_prune_keeps_eight_latest_sealed_days_and_newer_partial_hours( - nine_sealed_days: Path, -) -> None: - store = FactStore(nine_sealed_days) - partial = datetime(2026, 8, 16, 0, tzinfo=UTC) - store.commit_hour(_empty_hour(partial)) - - report = store.prune(retain_days=8) - - assert report.source_days == ("2026-08-07",) - assert report.hours_pruned == 24 - assert [seal.source_day for seal in store.seals()] == [ - "2026-08-08", - "2026-08-09", - "2026-08-10", - "2026-08-11", - "2026-08-12", - "2026-08-13", - "2026-08-14", - "2026-08-15", - ] - assert store.committed_hours()[0] == "2026-08-08T00" - assert store.committed_hours()[-1] == "2026-08-16T00" - assert store.verify().hours_verified == 8 * 24 diff --git a/bazaarplusplus-analyzer/tests/test_hour_intake.py b/bazaarplusplus-analyzer/tests/test_hour_intake.py deleted file mode 100644 index 0604bdb..0000000 --- a/bazaarplusplus-analyzer/tests/test_hour_intake.py +++ /dev/null @@ -1,328 +0,0 @@ -from datetime import UTC, datetime -from pathlib import Path - -import pytest - -from bppanalyzer.bundle_source import ( - BundleRef, - HourExpired, - RawHourIndex, - RetryableSourceError, - admit_bundle, - raw_commit_sha256, -) -from bppanalyzer.fact_store import FactStore -from bppanalyzer.hour_intake import HourIntakeProgress, SourceHourIntake -from bppanalyzer.locking import LockOwnershipLost, MaximumRunTimeExceeded -from tests.bundle_fixtures import bundle_bytes - -SOURCE_HOUR = datetime(2026, 8, 10, 12, tzinfo=UTC) - - -class Clock: - def __init__(self) -> None: - self.seconds = 0.0 - - def __call__(self) -> float: - return self.seconds - - def advance(self, seconds: float) -> None: - self.seconds += seconds - - -class FixtureSource: - def __init__( - self, - clock: Clock, - *, - count: int = 2, - index_error: BaseException | None = None, - stream_error: BaseException | None = None, - ) -> None: - self.clock = clock - self.count = count - self.index_error = index_error - self.stream_error = stream_error - self.exhausted = False - - def hour_index(self, source_hour: datetime) -> RawHourIndex: - self.exhausted = False - self.clock.advance(2) - if self.index_error is not None: - raise self.index_error - timestamp = int(source_hour.timestamp() * 1_000) - refs = tuple( - BundleRef( - bundle_id=f"bundle-{number}", - available_at_ms=timestamp + number, - download_url=f"https://download.invalid/bundle-{number}", - download_expires_at_ms=timestamp + 60_000, - ) - for number in range(self.count) - ) - return RawHourIndex(source_hour, refs, raw_commit_sha256(refs), 1) - - def stream(self, index: RawHourIndex): - for number, ref in enumerate(index.items): - self.clock.advance(3) - if number == 1 and self.stream_error is not None: - raise self.stream_error - yield admit_bundle(ref, bundle_bytes(ref.bundle_id)) - self.exhausted = True - - -def _failure(kind: str) -> BaseException: - if kind == "retryable": - return RetryableSourceError("fixture_failed", "fixture stream failed") - if kind == "expired": - return HourExpired("source_hour_expired", "fixture expired") - if kind == "lock": - return LockOwnershipLost("fixture ownership lost") - if kind == "deadline": - return MaximumRunTimeExceeded("fixture deadline reached") - if kind == "interrupt": - return KeyboardInterrupt("fixture interrupt") - return RuntimeError("fixture failure") - - -@pytest.mark.parametrize("kind", ["retryable", "expired", "lock", "deadline", "interrupt", "fatal"]) -def test_index_failure_reports_unknown_total_and_preserves_original_error( - tmp_path: Path, kind: str -) -> None: - clock = Clock() - error = _failure(kind) - updates: list[HourIntakeProgress] = [] - store = FactStore(tmp_path) - intake = SourceHourIntake(FixtureSource(clock, index_error=error), store, monotonic=clock) - - if kind in {"retryable", "expired"}: - result = intake.commit(SOURCE_HOUR, on_progress=updates.append) - assert result is updates[-1] - assert result.error is error - else: - with pytest.raises(type(error)) as raised: - intake.commit(SOURCE_HOUR, on_progress=updates.append) - assert raised.value is error - assert len(updates) == 2 - assert updates[0] == HourIntakeProgress("2026-08-10T12") - assert updates[-1] == HourIntakeProgress( - "2026-08-10T12", source_index_seconds=2, elapsed_seconds=2, error=error - ) - assert store.committed_hours() == () - - -@pytest.mark.parametrize("kind", ["retryable", "expired", "lock", "deadline", "interrupt", "fatal"]) -def test_partial_stream_reports_admission_counts_and_never_commits( - tmp_path: Path, kind: str -) -> None: - clock = Clock() - error = _failure(kind) - updates: list[HourIntakeProgress] = [] - store = FactStore(tmp_path) - intake = SourceHourIntake(FixtureSource(clock, stream_error=error), store, monotonic=clock) - - if kind in {"retryable", "expired"}: - result = intake.commit(SOURCE_HOUR, on_progress=updates.append) - assert result is updates[-1] - assert result.error is error - else: - with pytest.raises(type(error)) as raised: - intake.commit(SOURCE_HOUR, on_progress=updates.append) - assert raised.value is error - assert [(u.step, u.succeeded_bundles) for u in updates] == [ - ("index", 0), - ("ingest", 0), - ("ingest", 1), - ("ingest", 1), - ] - assert updates[-1] == HourIntakeProgress( - "2026-08-10T12", - step="ingest", - expected_bundles=2, - succeeded_bundles=1, - failed_bundles=1 if kind == "retryable" else 0, - listing_pages=1, - source_index_seconds=2, - source_ingest_seconds=6, - elapsed_seconds=8, - error=error, - ) - assert store.committed_hours() == () - - -@pytest.mark.parametrize("failure_at", ["write_fence", "finalize"]) -def test_commit_failure_preserves_download_success_without_claiming_a_commit( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure_at: str -) -> None: - clock = Clock() - source = FixtureSource(clock) - error = ( - LockOwnershipLost("fixture commit fenced") - if failure_at == "write_fence" - else OSError("fixture atomic rename failed") - ) - updates: list[HourIntakeProgress] = [] - - def ownership_check() -> None: - if source.exhausted and failure_at == "write_fence": - clock.advance(5) - raise error - - def fail_rename(_source, _destination) -> None: - clock.advance(5) - raise error - - if failure_at == "finalize": - monkeypatch.setattr("bppanalyzer.fact_store.os.rename", fail_rename) - - store = FactStore(tmp_path, ownership_check=ownership_check) - with pytest.raises(type(error)) as raised: - SourceHourIntake(source, store, monotonic=clock).commit( - SOURCE_HOUR, on_progress=updates.append - ) - - assert raised.value is error - assert source.exhausted - assert updates[-1] == HourIntakeProgress( - "2026-08-10T12", - step="ingest", - expected_bundles=2, - succeeded_bundles=2, - listing_pages=1, - source_index_seconds=2, - source_ingest_seconds=11, - elapsed_seconds=13, - error=error, - ) - assert store.committed_hours() == () - - -@pytest.mark.parametrize("count", [0, 1, 501]) -def test_live_progress_is_bounded_and_precedes_commit(tmp_path: Path, count: int) -> None: - clock = Clock() - source = FixtureSource(clock, count=count) - store = FactStore(tmp_path) - updates: list[HourIntakeProgress] = [] - - def observe(update: HourIntakeProgress) -> None: - updates.append(update) - if update.commit is None: - assert not source.exhausted - assert store.committed_hours() == () - else: - assert source.exhausted - assert store.committed_hours() == ("2026-08-10T12",) - - result = SourceHourIntake(source, store, monotonic=clock).commit( - SOURCE_HOUR, on_progress=observe - ) - assert result is updates[-1] - commit = result.commit - assert commit is not None - - progress_counts = [1, 250, 500, 501] if count == 501 else ([1] if count else []) - assert [(u.step, u.succeeded_bundles) for u in updates] == [ - ("index", 0), - ("ingest", 0), - *[("ingest", completed) for completed in progress_counts], - ("complete", count), - ] - assert updates[-1] == HourIntakeProgress( - "2026-08-10T12", - step="complete", - expected_bundles=count, - succeeded_bundles=count, - listing_pages=1, - source_index_seconds=2, - source_ingest_seconds=3 * count, - elapsed_seconds=2 + 3 * count, - commit=commit, - ) - assert commit.bundle_count == count - assert not commit.reused - assert store.has_hour(SOURCE_HOUR) - - -def test_reused_commit_and_each_attempt_keep_their_own_counts(tmp_path: Path) -> None: - clock = Clock() - intake = SourceHourIntake(FixtureSource(clock), FactStore(tmp_path), monotonic=clock) - updates: list[HourIntakeProgress] = [] - first = intake.commit(SOURCE_HOUR, on_progress=updates.append) - second = intake.commit(SOURCE_HOUR, on_progress=updates.append) - - assert first.commit is not None and second.commit is not None - assert first.commit.fact_commit_sha256 == second.commit.fact_commit_sha256 - assert second.commit.reused - results = [u for u in updates if u.commit is not None] - assert [u.expected_bundles for u in results] == [2, 2] - assert [u.succeeded_bundles for u in results] == [2, 2] - assert [u.source_index_seconds for u in results] == [2, 2] - assert [u.source_ingest_seconds for u in results] == [6, 6] - - -@pytest.mark.parametrize("kind", ["retryable", "lock", "deadline", "interrupt", "fatal"]) -def test_progress_observer_failure_aborts_without_inventing_download_failures( - tmp_path: Path, kind: str -) -> None: - clock = Clock() - error = _failure(kind) - updates: list[HourIntakeProgress] = [] - store = FactStore(tmp_path) - - def observe(update: HourIntakeProgress) -> None: - updates.append(update) - if update.succeeded_bundles == 1 and update.error is None: - raise error - - with pytest.raises(type(error)) as raised: - SourceHourIntake(FixtureSource(clock), store, monotonic=clock).commit( - SOURCE_HOUR, on_progress=observe - ) - - assert raised.value is error - assert updates[-1].error is error - assert updates[-1].succeeded_bundles == 1 - assert updates[-1].failed_bundles == 0 - assert updates[-1].source_ingest_seconds == 3 - assert store.committed_hours() == () - - -@pytest.mark.parametrize("kind", ["retryable", "lock", "deadline", "interrupt"]) -def test_failure_observer_cannot_mask_original_failure(tmp_path: Path, kind: str) -> None: - clock = Clock() - error = _failure(kind) - secondary = OSError("fixture evidence failure") - - def observe(update: HourIntakeProgress) -> None: - if update.error is not None: - raise secondary - - with pytest.raises(type(error)) as raised: - SourceHourIntake( - FixtureSource(clock, stream_error=error), FactStore(tmp_path), monotonic=clock - ).commit(SOURCE_HOUR, on_progress=observe) - - assert raised.value is error - assert raised.value.__cause__ is secondary - - -def test_success_observer_failure_cannot_turn_a_committed_hour_into_failure(tmp_path: Path) -> None: - clock = Clock() - store = FactStore(tmp_path) - updates: list[HourIntakeProgress] = [] - error = OSError("fixture completed evidence failure") - - def observe(update: HourIntakeProgress) -> None: - updates.append(update) - if update.commit is not None: - raise error - - with pytest.raises(OSError) as raised: - SourceHourIntake(FixtureSource(clock), store, monotonic=clock).commit( - SOURCE_HOUR, on_progress=observe - ) - - assert raised.value is error - assert updates[-1].commit is not None - assert all(u.error is None for u in updates) - assert store.has_hour(SOURCE_HOUR) diff --git a/bazaarplusplus-analyzer/tests/test_locking.py b/bazaarplusplus-analyzer/tests/test_locking.py deleted file mode 100644 index 2103c0b..0000000 --- a/bazaarplusplus-analyzer/tests/test_locking.py +++ /dev/null @@ -1,163 +0,0 @@ -import contextlib -import json -import os -import threading -import time -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path - -import pytest - -from bppanalyzer.locking import DirectoryLock, LockHeld, LockOwnershipLost - - -def test_live_lock_rejects_a_concurrent_holder_within_one_second_without_writes( - tmp_path: Path, -) -> None: - first = DirectoryLock(tmp_path, "run-one", heartbeat_interval=60) - first.acquire() - before = { - path.relative_to(tmp_path): (path.stat().st_mtime_ns, path.stat().st_size) - for path in tmp_path.rglob("*") - } - started = time.monotonic() - - with pytest.raises(LockHeld): - DirectoryLock(tmp_path, "run-two", heartbeat_interval=60).acquire() - - assert time.monotonic() - started < 1 - after = { - path.relative_to(tmp_path): (path.stat().st_mtime_ns, path.stat().st_size) - for path in tmp_path.rglob("*") - } - assert after == before - first.release() - - -def test_stale_lock_race_has_exactly_one_winner(tmp_path: Path) -> None: - lock_dir = tmp_path / ".lock" - lock_dir.mkdir() - heartbeat = lock_dir / "heartbeat" - heartbeat.write_text( - json.dumps( - { - "run_id": "stale-run", - "pid": 1, - "started_at": "2026-08-01T00:00:00Z", - "hostname": "stale-host", - } - ) - ) - old = time.time() - 600 - os.utime(heartbeat, (old, old)) - barrier = threading.Barrier(2) - - def contend(run_id: str): - candidate = DirectoryLock(tmp_path, run_id, heartbeat_interval=60, stale_after=300) - barrier.wait() - try: - candidate.acquire() - except LockHeld: - return None - return candidate - - with ThreadPoolExecutor(max_workers=2) as executor: - results = list(executor.map(contend, ("winner-a", "winner-b"))) - - winners = [value for value in results if value is not None] - assert len(winners) == 1 - winners[0].release() - - -def test_resumed_stale_holder_neither_writes_nor_removes_the_new_lock( - tmp_path: Path, -) -> None: - old = DirectoryLock(tmp_path, "old-run", heartbeat_interval=60) - old.acquire() - heartbeat = tmp_path / ".lock/heartbeat" - stale = time.time() - 600 - os.utime(heartbeat, (stale, stale)) - current = DirectoryLock(tmp_path, "current-run", heartbeat_interval=60, stale_after=300) - current.acquire() - - with pytest.raises(LockOwnershipLost): - old.touch() - with pytest.raises(LockOwnershipLost): - old.release() - - assert json.loads(heartbeat.read_text())["run_id"] == "current-run" - current.release() - - -def test_missing_lock_observation_does_not_steal_a_new_claim( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - lock_dir = tmp_path / ".lock" - lock_dir.mkdir() - heartbeat = lock_dir / "heartbeat" - heartbeat.write_text(json.dumps({"run_id": "stale-run"})) - old = time.time() - 600 - os.utime(heartbeat, (old, old)) - contender = DirectoryLock(tmp_path, "contender", heartbeat_interval=60) - fresh = DirectoryLock(tmp_path, "fresh", heartbeat_interval=60) - fresh_created = threading.Event() - resume_fresh = threading.Event() - fresh_finished = threading.Event() - original_open = Path.open - original_rename = os.rename - original_age = contender._heartbeat_age - observations = 0 - future = None - - def acquire_fresh(): - try: - return fresh.acquire() - finally: - fresh_finished.set() - - def pause_before_heartbeat(path, *args, **kwargs): - if path == heartbeat and threading.current_thread().name.startswith("fresh-lock"): - fresh_created.set() - assert resume_fresh.wait(5) - return original_open(path, *args, **kwargs) - - def finish_fresh_after_rename(source, destination): - original_rename(source, destination) - if source == lock_dir and destination == tmp_path / ".lock.stale-contender": - resume_fresh.set() - assert fresh_finished.wait(5) - - with ThreadPoolExecutor(max_workers=1, thread_name_prefix="fresh-lock") as executor: - - def observe_missing_then_create(): - nonlocal observations, future - observations += 1 - if observations == 2: - # A previous stale contender has moved the old claim away. - original_rename(lock_dir, tmp_path / ".retired") - age = original_age() - future = executor.submit(acquire_fresh) - assert fresh_created.wait(5) - return age - return original_age() - - monkeypatch.setattr(Path, "open", pause_before_heartbeat) - monkeypatch.setattr(os, "rename", finish_fresh_after_rename) - monkeypatch.setattr(contender, "_heartbeat_age", observe_missing_then_create) - rejected = False - try: - try: - contender.acquire() - except LockHeld: - rejected = True - finally: - resume_fresh.set() - assert future is not None - assert future.result(timeout=5) is fresh - assert rejected - fresh.assert_owned() - finally: - resume_fresh.set() - for candidate in (contender, fresh): - with contextlib.suppress(LockOwnershipLost): - candidate.release() diff --git a/bazaarplusplus-analyzer/tests/test_object_store.py b/bazaarplusplus-analyzer/tests/test_object_store.py deleted file mode 100644 index fd5decd..0000000 --- a/bazaarplusplus-analyzer/tests/test_object_store.py +++ /dev/null @@ -1,287 +0,0 @@ -"""R2 adapter tests. - -Credential derivation fails closed, before any bucket request, when: - the token is empty -> ValueError "Complete R2 configuration" - the account id is not 32 hex characters -> ValueError "CLOUDFLARE_ACCOUNT_ID must be" - the bucket name is not a valid R2 bucket -> ValueError "Invalid R2 bucket" - /user/tokens/verify is not 200 or success -> ObjectStoreError "Cloudflare rejected", - unless the account verify endpoint accepts an account-owned token - the verify result has no 32-hex token id -> ObjectStoreError "returned no token id" - the token is not active -> ObjectStoreError "not active" - the verify request itself fails -> ObjectStoreError "verification failed" -A verified id is reused for the process; a failed verification is not. -""" - -import hashlib -import uuid -from datetime import UTC, datetime -from io import BytesIO - -import httpx -import pytest -from botocore.exceptions import BotoCoreError, ClientError - -import bppanalyzer.object_store as object_store_module -from bppanalyzer.object_store import ( - CLOUDFLARE_API, - ObjectStoreError, - R2ObjectStore, - derive_s3_credentials, -) - -ACCOUNT = "a" * 32 -TOKEN_ID = "b" * 32 - - -class _FakeR2Client: - def __init__(self, now: datetime) -> None: - self.now = now - self.body = b'{"ok":true}\n' - self.requests: list[tuple[str, dict]] = [] - self.failure: BaseException | None = None - self.metadata: dict[str, object] = { - "ContentLength": len(self.body), - "CacheControl": "public,max-age=60,must-revalidate", - "ContentType": "application/json", - "LastModified": now.replace(tzinfo=None), - "Metadata": {"sha256": hashlib.sha256(self.body).hexdigest()}, - } - - def head_object(self, **kwargs): - self.requests.append(("head", kwargs)) - if self.failure is not None: - raise self.failure - return dict(self.metadata) - - def get_object(self, **kwargs): - self.requests.append(("get", kwargs)) - if self.failure is not None: - raise self.failure - return {**self.metadata, "Body": BytesIO(self.body)} - - def put_object(self, **kwargs): - self.requests.append(("put", kwargs)) - if self.failure is not None: - raise self.failure - - -def _client_error(code: str) -> ClientError: - return ClientError({"Error": {"Code": code}}, "fixture") - - -class _Verify: - """A Cloudflare API stand-in on a real httpx client; records each call.""" - - def __init__(self, *responses: httpx.Response) -> None: - self.responses = list(responses) - self.requests: list[httpx.Request] = [] - - def handler(self, request: httpx.Request) -> httpx.Response: - self.requests.append(request) - if not self.responses: - raise httpx.ConnectError("no response scripted") - return self.responses.pop(0) - - def client(self) -> httpx.Client: - return httpx.Client(transport=httpx.MockTransport(self.handler)) - - -def _verified(token_id: str = TOKEN_ID, status: str = "active", *, code: int = 200, success=True): - return httpx.Response( - code, json={"success": success, "errors": [], "result": {"id": token_id, "status": status}} - ) - - -def _token() -> str: - return f"token-{uuid.uuid4()}" - - -def test_s3_pair_is_the_verified_token_id_and_the_sha256_of_the_token() -> None: - token = _token() - verify = _Verify(_verified()) - with verify.client() as client: - access_key_id, secret = derive_s3_credentials(f" {token} ", client=client) - again = derive_s3_credentials(token, client=client) - - assert (access_key_id, secret) == (TOKEN_ID, hashlib.sha256(token.encode()).hexdigest()) - assert again == (access_key_id, secret) - assert len(verify.requests) == 1 - assert str(verify.requests[0].url) == f"{CLOUDFLARE_API}/user/tokens/verify" - assert verify.requests[0].headers["authorization"] == f"Bearer {token}" - - -def test_account_owned_token_verifies_at_its_account_after_the_user_endpoint_rejects_it() -> None: - token = _token() - verify = _Verify(_verified(code=401, success=False), _verified()) - with verify.client() as client: - pair = derive_s3_credentials(token, account_id=ACCOUNT.upper(), client=client) - - assert pair == (TOKEN_ID, hashlib.sha256(token.encode()).hexdigest()) - assert [str(request.url) for request in verify.requests] == [ - f"{CLOUDFLARE_API}/user/tokens/verify", - f"{CLOUDFLARE_API}/accounts/{ACCOUNT}/tokens/verify", - ] - - -def test_token_rejected_by_both_endpoints_or_without_an_account_fails() -> None: - rejected = _Verify(_verified(code=401, success=False), _verified(code=401, success=False)) - with rejected.client() as client, pytest.raises(ObjectStoreError, match="Cloudflare rejected"): - derive_s3_credentials(_token(), account_id=ACCOUNT, client=client) - assert len(rejected.requests) == 2 - - user_only = _Verify(_verified(code=401, success=False)) - with user_only.client() as client, pytest.raises(ObjectStoreError, match="Cloudflare rejected"): - derive_s3_credentials(_token(), client=client) - assert len(user_only.requests) == 1 - - with pytest.raises(ValueError, match="CLOUDFLARE_ACCOUNT_ID must be"): - derive_s3_credentials(_token(), account_id="not-an-account") - - -def test_r2_adapter_derives_its_pair_once_and_uses_exact_json_metadata(monkeypatch) -> None: - now = datetime(2026, 8, 11, tzinfo=UTC) - client = _FakeR2Client(now) - created: list[dict] = [] - - def fake_client(*_args, **kwargs): - created.append(kwargs) - return client - - monkeypatch.setattr(object_store_module.boto3, "client", fake_client) - token = _token() - verify = _Verify(_verified()) - with verify.client() as http: - store = R2ObjectStore( - account_id=ACCOUNT.upper(), bucket="bucket", api_token=token, http_client=http - ) - R2ObjectStore(account_id=ACCOUNT, bucket="bucket", api_token=token, http_client=http) - assert len(verify.requests) == 1 - assert created[0]["aws_access_key_id"] == TOKEN_ID - assert created[0]["aws_secret_access_key"] == hashlib.sha256(token.encode()).hexdigest() - assert created[0]["endpoint_url"] == f"https://{ACCOUNT}.r2.cloudflarestorage.com" - - stat = store.stat("heroes/latest.json") - observed = store.get("heroes/latest.json") - store.put( - "builds/latest.json", - client.body, - cache_control="public,max-age=60,must-revalidate", - content_type="application/json", - ) - - assert stat is not None and stat.last_modified == now - assert observed is not None and observed.body == client.body - put = client.requests[-1][1] - assert put["ContentType"] == "application/json" - assert put["Metadata"] == {"sha256": hashlib.sha256(client.body).hexdigest()} - - -def test_r2_adapter_maps_not_found_errors_and_rejects_bad_metadata(monkeypatch) -> None: - client = _FakeR2Client(datetime(2026, 8, 11, tzinfo=UTC)) - monkeypatch.setattr(object_store_module.boto3, "client", lambda *_args, **_kwargs: client) - with _Verify(_verified()).client() as http: - store = R2ObjectStore( - account_id=ACCOUNT, bucket="bucket", api_token=_token(), http_client=http - ) - client.failure = _client_error("NoSuchKey") - assert store.stat("missing.json") is None - assert store.get("missing.json") is None - - client.failure = _client_error("AccessDenied") - with pytest.raises(ObjectStoreError, match="stat failed"): - store.stat("denied.json") - with pytest.raises(ObjectStoreError, match="get failed"): - store.get("denied.json") - with pytest.raises(ObjectStoreError, match="put failed"): - store.put("denied.json", b"{}", cache_control="cache") - - client.failure = BotoCoreError() - with pytest.raises(ObjectStoreError, match="stat failed"): - store.stat("failed.json") - client.failure = None - client.metadata["Metadata"] = {"sha256": "short"} - with pytest.raises(ObjectStoreError, match="sha256 metadata is malformed"): - store.stat("bad.json") - client.metadata["Metadata"] = {"sha256": hashlib.sha256(client.body).hexdigest()} - client.metadata.pop("ContentType") - with pytest.raises(ObjectStoreError, match="metadata is incomplete"): - store.stat("bad.json") - - -def test_r2_adapter_reads_objects_written_without_sha256_metadata(monkeypatch) -> None: - # A snapshot seeded with wrangler carries no sha256 metadata; stat reports - # no digest so LatestPublisher replaces it, and get hashes the bytes. - client = _FakeR2Client(datetime(2026, 10, 11, tzinfo=UTC)) - client.metadata["Metadata"] = {} - monkeypatch.setattr(object_store_module.boto3, "client", lambda *_args, **_kwargs: client) - with _Verify(_verified()).client() as http: - store = R2ObjectStore( - account_id=ACCOUNT, bucket="bucket", api_token=_token(), http_client=http - ) - stat = store.stat("builds/latest.json") - assert stat is not None and stat.sha256 is None - stored = store.get("builds/latest.json") - assert stored is not None - assert stored.stat.sha256 == hashlib.sha256(client.body).hexdigest() - - -def test_r2_configuration_is_validated_before_any_request(monkeypatch) -> None: - monkeypatch.setattr( - object_store_module.boto3, - "client", - lambda *_args, **_kwargs: pytest.fail("invalid configuration must not create a client"), - ) - verify = _Verify() - with verify.client() as http: - for kwargs, message in ( - ({"account_id": "", "bucket": "bucket", "api_token": "t"}, "Complete R2"), - ({"account_id": ACCOUNT, "bucket": "bucket", "api_token": ""}, "Complete R2"), - ( - {"account_id": "account", "bucket": "bucket", "api_token": "t"}, - "CLOUDFLARE_ACCOUNT_ID", - ), - ( - {"account_id": ACCOUNT, "bucket": "Bad_Bucket", "api_token": "t"}, - "Invalid R2 bucket", - ), - ): - with pytest.raises(ValueError, match=message): - R2ObjectStore(http_client=http, **kwargs) - assert verify.requests == [] - - -@pytest.mark.parametrize( - ("response", "message"), - ( - (_verified(code=401, success=False), "Cloudflare rejected CLOUDFLARE_API_TOKEN: HTTP 401"), - (httpx.Response(500, text="not json"), "HTTP 500"), - ( - httpx.Response(200, json={"success": True, "result": {"status": "active"}}), - "no token id", - ), - (_verified(status="expired"), "is expired, not active"), - (None, "verification failed"), - ), -) -def test_a_rejected_malformed_or_failed_verification_fails_and_is_retried( - monkeypatch, response, message -) -> None: - monkeypatch.setattr( - object_store_module.boto3, - "client", - lambda *_args, **_kwargs: _FakeR2Client(datetime(2026, 8, 11, tzinfo=UTC)), - ) - token = _token() - # A rejection at /user is retried once at the account endpoint. - rejected = response is not None and response.status_code != 200 - first = [] if response is None else [response] - if rejected: - first.append(httpx.Response(response.status_code, content=response.content)) - verify = _Verify() if response is None else _Verify(*first, _verified()) - with verify.client() as http: - with pytest.raises(ObjectStoreError, match=message): - R2ObjectStore(account_id=ACCOUNT, bucket="bucket", api_token=token, http_client=http) - if response is None: - verify.responses.append(_verified()) - R2ObjectStore(account_id=ACCOUNT, bucket="bucket", api_token=token, http_client=http) - assert len(verify.requests) == (len(first) or 1) + 1 diff --git a/bazaarplusplus-analyzer/tests/test_phase1_acceptance.py b/bazaarplusplus-analyzer/tests/test_phase1_acceptance.py deleted file mode 100644 index b4edaa3..0000000 --- a/bazaarplusplus-analyzer/tests/test_phase1_acceptance.py +++ /dev/null @@ -1,157 +0,0 @@ -import json -import multiprocessing -import uuid -from datetime import UTC, date, datetime, timedelta -from pathlib import Path - -import pyarrow.parquet as pq - -from bppanalyzer.bundle_source import ( - BundleRef, - RawHourIndex, - admit_bundle, - raw_commit_sha256, -) -from bppanalyzer.driver import PipelineDriver -from bppanalyzer.fact_store import FactStore -from bppanalyzer.operational_evidence import peak_rss_bytes -from bppanalyzer.projection import project_hour -from tests.bundle_fixtures import Card, bundle_bytes, payload - - -class BusyHourSource: - def __init__(self, *, bundle_count: int = 2_500, cards_per_set: int = 25) -> None: - self.bundle_count = bundle_count - self.run_payload = payload(cards_per_set=cards_per_set) - - def hour_index(self, source_hour: datetime) -> RawHourIndex: - available_at_ms = int(source_hour.timestamp() * 1_000) - refs = tuple( - BundleRef( - bundle_id=f"bundle-{index:05d}", - available_at_ms=available_at_ms, - download_url=f"https://download.invalid/bundle-{index:05d}", - download_expires_at_ms=available_at_ms + 60_000, - ) - for index in range(self.bundle_count) - ) - return RawHourIndex(source_hour, refs, raw_commit_sha256(refs), 1) - - def stream(self, index: RawHourIndex): - for ref in index.items: - content = bundle_bytes(ref.bundle_id, run_payload=self.run_payload) - yield admit_bundle(ref, content) - - -class DistinctCardHourSource(BusyHourSource): - """A busy hour whose Bundles each carry their own card identities.""" - - def stream(self, index: RawHourIndex): - for ref in index.items: - hand = [ - Card(str(uuid.uuid5(uuid.NAMESPACE_URL, f"{ref.bundle_id}/{slot}")), 1, slot) - for slot in range(50) - ] - run = payload(run_id=ref.bundle_id, player_hand=hand) - yield admit_bundle( - ref, bundle_bytes(ref.bundle_id, run_payload=run, run_id=ref.bundle_id) - ) - - -def _measure_busy_hour(root: str, results) -> None: - now = datetime(2026, 8, 7, 1, 1, tzinfo=UTC) - source = BusyHourSource() - baseline_rss = peak_rss_bytes() - summary = PipelineDriver( - Path(root), - source=source, - clock=lambda: now, - duckdb_memory_limit="1GB", - duckdb_threads=1, - ).run(heal_days=1) - status = json.loads((Path(root) / "status.json").read_bytes()) - cards_path = Path(root) / "facts/hourly/source_hour=2026-08-07T00/battle_cards.parquet" - metadata = pq.ParquetFile(cards_path).metadata - results.put( - { - "baseline_rss_bytes": baseline_rss, - "peak_rss_bytes": summary.peak_rss_bytes, - "status_peak_rss_bytes": status["peak_rss_bytes"], - "card_rows": metadata.num_rows, - "card_row_groups": metadata.num_row_groups, - } - ) - - -def test_hour_ingest_records_and_stays_below_the_one_gib_peak_rss_limit( - tmp_path: Path, -) -> None: - context = multiprocessing.get_context("spawn") - results = context.Queue() - process = context.Process(target=_measure_busy_hour, args=(str(tmp_path), results)) - process.start() - process.join(timeout=60) - - if process.is_alive(): - process.kill() - process.join() - raise AssertionError("Synthetic hour ingest exceeded 60 seconds") - assert process.exitcode == 0 - measured = results.get(timeout=1) - results.close() - results.join_thread() - assert measured["card_rows"] == 250_000 - assert measured["card_row_groups"] > 1 - assert measured["peak_rss_bytes"] < 1024**3 - assert measured["status_peak_rss_bytes"] == measured["peak_rss_bytes"] - assert measured["peak_rss_bytes"] - measured["baseline_rss_bytes"] < 256 * 1024**2 - - -def test_batched_hour_commit_is_byte_deterministic_across_batch_boundaries( - tmp_path: Path, -) -> None: - source_hour = datetime(2026, 8, 10, 12, tzinfo=UTC) - committed: list[dict[str, bytes]] = [] - - for root_name in ("first", "second"): - root = tmp_path / root_name - source = BusyHourSource(bundle_count=501, cards_per_set=25) - index = source.hour_index(source_hour) - FactStore(root).commit_hour(project_hour(index, source.stream(index))) - hour_path = root / "facts/hourly/source_hour=2026-08-10T12" - committed.append({path.name: path.read_bytes() for path in sorted(hour_path.iterdir())}) - - assert ( - pq.ParquetFile( - tmp_path / "first/facts/hourly/source_hour=2026-08-10T12/battle_cards.parquet" - ).metadata.num_row_groups - == 2 - ) - assert committed[0] == committed[1] - - -def test_one_source_day_persists_only_parquet_plus_at_most_one_percent_metadata( - tmp_path: Path, -) -> None: - store = FactStore(tmp_path) - day = date(2026, 8, 10) - # Real hours carry distinct cards; identical Bundles would compress far below - # any realistic metadata ratio. - busy = DistinctCardHourSource() - for hour_number in range(24): - hour = datetime.combine(day, datetime.min.time(), UTC) + timedelta(hours=hour_number) - if hour_number == 0: - index = busy.hour_index(hour) - store.commit_hour(project_hour(index, busy.stream(index))) - else: - empty = RawHourIndex(hour, (), raw_commit_sha256(()), 1) - store.commit_hour(project_hour(empty, ())) - store.seal_day(day) - - files = [path for path in tmp_path.rglob("*") if path.is_file()] - parquet_bytes = sum(path.stat().st_size for path in files if path.suffix == ".parquet") - total_bytes = sum(path.stat().st_size for path in files) - assert parquet_bytes > 0 - assert total_bytes <= parquet_bytes * 1.01 - assert not list(tmp_path.rglob("*.bundle")) - assert not (tmp_path / "raw").exists() diff --git a/bazaarplusplus-analyzer/tests/test_phase2_acceptance.py b/bazaarplusplus-analyzer/tests/test_phase2_acceptance.py deleted file mode 100644 index 75d5d17..0000000 --- a/bazaarplusplus-analyzer/tests/test_phase2_acceptance.py +++ /dev/null @@ -1,51 +0,0 @@ -import json -from datetime import UTC, date, datetime -from pathlib import Path - -import httpx - -from bppanalyzer.bundle_source import BundleSource -from bppanalyzer.driver import PipelineDriver -from tests.pipeline_fixtures import ( - API_BASE_URL, - SYNC_TOKEN, - BundleServer, - daily_bundles, - fixed_clock, -) - - -def test_seven_day_build_records_bounded_rss_and_local_contract_state(tmp_path: Path) -> None: - # Source Days 08-04..08-10 hold Bundles. At 00:30 on 08-11, heal_days=8 covers - # 08-04..08-11; every hour stays inside the eight-day Bundle Source retention. - now = datetime(2026, 8, 11, 0, 30, tzinfo=UTC) - server = BundleServer(daily_bundles(date(2026, 8, 4), 7), now=now) - with httpx.Client(transport=httpx.MockTransport(server)) as client: - summary = PipelineDriver( - tmp_path, - source=BundleSource( - api_base_url=API_BASE_URL, - sync_token=SYNC_TOKEN, - client=client, - clock=fixed_clock(now), - ), - clock=fixed_clock(now), - duckdb_memory_limit="1GB", - duckdb_threads=4, - ).run(heal_days=8, publish=False) - - assert summary.peak_rss_bytes < 8 * 1024**3 - status = json.loads((tmp_path / "status.json").read_bytes()) - assert status["peak_rss_bytes"] < 8 * 1024**3 - assert status["last_run"]["report"]["window"]["days"] == 7 - assert set( - path.relative_to(tmp_path / "snapshots").as_posix() - for path in (tmp_path / "snapshots").rglob("*.json") - ) == { - "heroes/latest.json", - "builds/latest.json", - } - heroes = json.loads((tmp_path / "snapshots/heroes/latest.json").read_bytes()) - days = [item["day"] for item in heroes["days"]] - assert days == sorted(days, reverse=True) - assert len(set(days)) == len(days) == 7 diff --git a/bazaarplusplus-analyzer/tests/test_pipeline_golden.py b/bazaarplusplus-analyzer/tests/test_pipeline_golden.py deleted file mode 100644 index 65aeea9..0000000 --- a/bazaarplusplus-analyzer/tests/test_pipeline_golden.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Bundle Server → facts → seal → heroes/builds snapshots, compared byte for byte. - -``just analyzer::golden`` rewrites the three goldens; ``just analyzer::test`` only -compares. The snapshot goldens are shared consumer fixtures under -``contracts/v6/fixtures/``; the run report is run evidence and stays in -``tests/fixtures/``. -""" - -import json -from datetime import UTC, datetime -from pathlib import Path - -import httpx - -from bppanalyzer.bundle_source import BundleSource -from bppanalyzer.driver import PipelineDriver -from bppanalyzer.durable import canonical_json -from tests.pipeline_fixtures import ( - API_BASE_URL, - CONTRACT_FIXTURES, - SYNC_TOKEN, - TEST_FIXTURES, - BundleServer, - assert_golden, - fixed_clock, - golden_day_bundles, -) - -# Source Day 2026-08-10 is the only day with Bundles. At 00:30 on 08-11, -# healing_days(now, 2) is [08-10, 08-11]. is_hour_settled requires -# now >= hour + 1h + 60s, so all 24 Source Hours of 08-10 settle and the day is -# sealed, while 08-11 has no settled hour and stays incomplete. The Analysis -# Window is therefore exactly one day. -CLOCK = datetime(2026, 8, 11, 0, 30, tzinfo=UTC) -WALL_CLOCK_DOWNLOAD_FIELDS = ("download_latency_ms_p50", "download_latency_ms_p95") - - -def test_one_bundle_day_reproduces_the_committed_snapshots_and_run_report( - tmp_path: Path, -) -> None: - with httpx.Client( - transport=httpx.MockTransport(BundleServer(golden_day_bundles(), now=CLOCK)) - ) as client: - summary = PipelineDriver( - tmp_path, - source=BundleSource( - api_base_url=API_BASE_URL, - sync_token=SYNC_TOKEN, - client=client, - clock=fixed_clock(CLOCK), - ), - clock=fixed_clock(CLOCK), - # Fixed DuckDB resources keep the snapshot bytes reproducible. - duckdb_memory_limit="1GB", - duckdb_threads=1, - ).run(heal_days=2, publish=False) - - assert summary.failures == () - report = json.loads(json.dumps(summary.report)) - for field in WALL_CLOCK_DOWNLOAD_FIELDS: - del report["downloads"][field] - heroes = (tmp_path / "snapshots/heroes/latest.json").read_bytes() - builds = (tmp_path / "snapshots/builds/latest.json").read_bytes() - build_payload = json.loads(builds) - # Invalid layouts must not dilute the valid identity's statistics or poison - # the entire snapshot consumed by the mod. Hero population stays independent. - assert build_payload["heroes"]["Dooley"]["builds"][0][2][:3] == [2, 2, 10000] - for hero in build_payload["heroes"].values(): - for build in hero["builds"]: - assert all(1 <= row[2] <= 5 and 1 <= row[4] <= 3 for row in build[1]) - assert build_payload["heroes"]["Mak"]["builds"][0][1][-1][2:] == [1, 0, 1] - assert build_payload["heroes"]["Stelle"]["builds"][0][1][-1][2:] == [5, 0, 1] - - # A golden that proves nothing must never be committed. - assert report["window"] == {"start": "2026-08-10", "end": "2026-08-10", "days": 1} - assert report["builds"]["published_builds"] >= 1 - assert report["facts"]["discarded_unknown_hero"] > 0 - assert report["facts"]["discarded_unknown_final_rank"] > 0 - assert any( - matchup["decided"] > 0 - for day in json.loads(heroes)["days"] - for row in day["rows"] - for matchup in row["matchups"] - ) - - assert_golden(CONTRACT_FIXTURES / "heroes.latest.json", heroes) - assert_golden(CONTRACT_FIXTURES / "builds.latest.json", builds) - assert_golden(TEST_FIXTURES / "pipeline-golden.run-report.json", canonical_json(report)) diff --git a/bazaarplusplus-analyzer/tests/test_publication.py b/bazaarplusplus-analyzer/tests/test_publication.py deleted file mode 100644 index 7299020..0000000 --- a/bazaarplusplus-analyzer/tests/test_publication.py +++ /dev/null @@ -1,167 +0,0 @@ -import json -from datetime import date, timedelta -from pathlib import Path - -import pytest -from jsonschema import Draft202012Validator - -from bppanalyzer.fact_store import DaySeal, FactStore -from bppanalyzer.publication import ( - BUILDS_KEY, - HEROES_KEY, - AnalysisWindowError, - BuildRank, - LatestPublisher, - SnapshotBuilder, - select_analysis_window, - select_build_identities, -) -from tests.fakes import MemoryObjectStore - - -def _builder(root: Path, store: FactStore, **kwargs) -> SnapshotBuilder: - return SnapshotBuilder(root, store=store, memory_limit="1GB", threads=1, **kwargs) - - -def _seal(day: date) -> DaySeal: - return DaySeal(day.isoformat(), (), {}, day.isoformat(), reused=True) - - -@pytest.mark.parametrize("count", (1, 5, 7)) -def test_analysis_window_grows_from_one_to_seven_complete_source_days(count: int) -> None: - start = date(2026, 8, 1) - seals = tuple(_seal(start + timedelta(days=offset)) for offset in range(count)) - - selected = select_analysis_window(seals) - - assert selected is not None - assert selected.start == start - assert selected.end == start + timedelta(days=count - 1) - assert len(selected.seals) == count - assert selected.value["days"] == count - - -def test_analysis_window_keeps_only_the_latest_seven_consecutive_days() -> None: - start = date(2026, 8, 1) - seals = tuple(_seal(start + timedelta(days=offset)) for offset in range(9)) - - selected = select_analysis_window(seals) - - assert selected is not None - assert selected.start == date(2026, 8, 3) - assert selected.end == date(2026, 8, 9) - assert len(selected.seals) == 7 - with pytest.raises(AnalysisWindowError, match="Duplicate"): - select_analysis_window((*seals, seals[0])) - - -def test_explicit_window_anchor_uses_the_available_consecutive_suffix() -> None: - start = date(2026, 8, 1) - seals = tuple(_seal(start + timedelta(days=offset)) for offset in range(8)) - - selected = select_analysis_window(seals, start + timedelta(days=5)) - assert selected is not None - assert selected.start == start - assert selected.end == start + timedelta(days=5) - assert selected.value["days"] == 6 - - selected = select_analysis_window(seals, start + timedelta(days=7)) - assert selected is not None - assert selected.start == start + timedelta(days=1) - assert selected.end == start + timedelta(days=7) - - -def test_analysis_window_never_considers_seals_before_the_source_epoch() -> None: - start = date(2026, 8, 1) - seals = tuple(_seal(start + timedelta(days=offset)) for offset in range(9)) - - selected = select_analysis_window(seals, source_epoch=date(2026, 8, 7)) - - assert selected is not None - assert selected.start == date(2026, 8, 7) - assert selected.end == date(2026, 8, 9) - assert selected.value["days"] == 3 - assert ( - select_analysis_window( - seals, - anchor_day=date(2026, 8, 6), - source_epoch=date(2026, 8, 7), - ) - is None - ) - - -def test_heroes_schema_requires_days_length_to_equal_window_days( - canonical_fact_store, -) -> None: - root, store = canonical_fact_store - window = select_analysis_window(store.seals()) - assert window is not None - payload = json.loads(_builder(root, store).build_heroes(window).content) - payload["window"]["days"] = 6 - schema = json.loads(Path("contracts/v6/heroes.schema.json").read_bytes()) - - assert list(Draft202012Validator(schema).iter_errors(payload)) - - -def test_latest_publisher_validates_and_only_writes_the_two_public_keys( - tmp_path: Path, canonical_fact_store -) -> None: - root, store = canonical_fact_store - window = select_analysis_window(store.seals()) - assert window is not None - builder = _builder(root, store) - heroes = builder.build_heroes(window) - builds = builder.build_builds(window) - objects = MemoryObjectStore() - publisher = LatestPublisher(objects) - - assert publisher.replace(heroes) is True - assert publisher.replace(builds) is True - - assert objects.put_keys() == [ - HEROES_KEY, - BUILDS_KEY, - ] - for key in (HEROES_KEY, BUILDS_KEY): - observed = objects.get(key) - assert observed is not None - assert observed.stat.cache_control == "public,max-age=60,must-revalidate" - assert observed.stat.content_type == "application/json" - - -def test_product_validation_failure_preserves_old_object_and_does_not_block_other_product( - canonical_fact_store, -) -> None: - objects = MemoryObjectStore() - objects.put( - HEROES_KEY, - b'{"old":"heroes"}\n', - cache_control="public,max-age=60,must-revalidate", - content_type="application/json", - ) - publisher = LatestPublisher(objects) - root, store = canonical_fact_store - window = select_analysis_window(store.seals()) - assert window is not None - builds = _builder(root, store).build_builds(window) - - assert publisher.replace(builds) is True - - assert objects.get(HEROES_KEY).body == b'{"old":"heroes"}\n' - assert objects.get(BUILDS_KEY).body == builds.content - - -def test_top_500_then_coverage_appends_only_highest_ranked_uncovered_build() -> None: - common = tuple(f"10000000-0000-0000-0000-{number:012d}" for number in range(500)) - rare = "ffffffff-ffff-ffff-ffff-ffffffffffff" - candidates = [BuildRank((card_id,), score=100, ten_win=1, p75=10) for card_id in common] - candidates.append(BuildRank((rare,), score=100, ten_win=1, p75=10)) - candidates.append(BuildRank((rare, rare), score=100, ten_win=1, p75=10)) - - selected = select_build_identities(candidates) - - assert len(candidates) == 502 - assert len(selected) == 501 - containing = [identity for identity in selected if rare in identity] - assert containing == [(rare,)] diff --git a/bazaarplusplus-analyzer/uv.lock b/bazaarplusplus-analyzer/uv.lock deleted file mode 100644 index f39669b..0000000 --- a/bazaarplusplus-analyzer/uv.lock +++ /dev/null @@ -1,505 +0,0 @@ -version = 1 -revision = 3 -requires-python = "==3.14.*" - -[[package]] -name = "anyio" -version = "4.15.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "idna" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, -] - -[[package]] -name = "attrs" -version = "26.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, -] - -[[package]] -name = "bazaarplusplus-analyzer" -version = "0.3.0" -source = { editable = "." } -dependencies = [ - { name = "boto3" }, - { name = "click" }, - { name = "duckdb" }, - { name = "httpx" }, - { name = "jsonschema" }, - { name = "pyarrow" }, - { name = "python-dotenv" }, -] - -[package.dev-dependencies] -dev = [ - { name = "pytest" }, - { name = "pytest-cov" }, - { name = "ruff" }, - { name = "ty" }, -] - -[package.metadata] -requires-dist = [ - { name = "boto3", specifier = "==1.43.112" }, - { name = "click", specifier = "==8.5.0" }, - { name = "duckdb", specifier = "==1.5.6" }, - { name = "httpx", specifier = "==0.28.1" }, - { name = "jsonschema", specifier = "==4.26.0" }, - { name = "pyarrow", specifier = "==26.0.0" }, - { name = "python-dotenv", specifier = "==1.2.4" }, -] - -[package.metadata.requires-dev] -dev = [ - { name = "pytest", specifier = "==9.1.1" }, - { name = "pytest-cov", specifier = "==7.1.0" }, - { name = "ruff", specifier = "==0.17.0" }, - { name = "ty", specifier = "==0.0.86" }, -] - -[[package]] -name = "boto3" -version = "1.43.112" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "botocore" }, - { name = "jmespath" }, - { name = "s3transfer" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c8/83/bf66a8c094d11db78a6cc19d835460af7b470640df0d0a3a108e1f3cefcd/boto3-1.43.112.tar.gz", hash = "sha256:599548a8c8e93cf0223bcb35b615c82f29d30295e992b94863cfbb2405ee33e5", size = 112667, upload-time = "2026-10-12T19:26:59.963Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c1/33/88d5fa546f2b1ec726cfa1b3f9316a28a3c416f44572abc734a0d5f3c2bc/boto3-1.43.112-py3-none-any.whl", hash = "sha256:add1216791e16c4f737676a0f5d6d2fa6240eef61619c6c44df9eeeaf88f24ff", size = 140041, upload-time = "2026-10-12T19:26:58.514Z" }, -] - -[[package]] -name = "botocore" -version = "1.43.115" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "jmespath" }, - { name = "python-dateutil" }, - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6f/10/ca525e88db50f5153ddad2a3d55908b5ace915d10f443d5e5135ba808d8d/botocore-1.43.115.tar.gz", hash = "sha256:aa4d9c4e7ef99988b7347e0cd276ba84e1eb1625510557b0e36cd57ecb19bbf2", size = 16383796, upload-time = "2026-10-19T19:19:45.382Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/77/2d/4b6b6f5704d1ec9b412c1dd9700bda0c315619dbac4a21418180a81a2780/botocore-1.43.115-py3-none-any.whl", hash = "sha256:9ceda640c868bc15f5399129e8cfdef8cbb4b350e8a99547c9b5f477cfb9619a", size = 16085101, upload-time = "2026-10-19T19:19:42.203Z" }, -] - -[[package]] -name = "certifi" -version = "2026.7.22" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, -] - -[[package]] -name = "click" -version = "8.5.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34", size = 382235, upload-time = "2026-08-26T13:33:14.56Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" }, -] - -[[package]] -name = "colorama" -version = "0.4.6" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, -] - -[[package]] -name = "coverage" -version = "7.16.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/65/2d/c738872f477f5687152acae68635790387425d407ae37dd3d3a8a6692307/coverage-7.16.1.tar.gz", hash = "sha256:f83981779bcf9dfa06fa0a8d4cb43e0faec1706328ce07aa3e7b665b4ac0f210", size = 969651, upload-time = "2026-09-13T19:12:21.422Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8e/b4/2a7c793965bae9f067aabab793a44d7a2f3ee7fb16b01ce1976bbd4a0218/coverage-7.16.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:cc0b37fe6f5ce5f1ccc62ad4fa9b1ad201d8e9b6027fd5e0170877beee4b2d15", size = 223546, upload-time = "2026-09-13T19:10:06.019Z" }, - { url = "https://files.pythonhosted.org/packages/ef/e2/633469076a2dbbea036cc15a268a3a5d6b2c7dd5d9a9567b2553dfc5ad61/coverage-7.16.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:6618f481053b63fc6121faf8fc676bd9b7163c2a19d9e984a2e850002c28ab57", size = 223881, upload-time = "2026-09-13T19:10:08.246Z" }, - { url = "https://files.pythonhosted.org/packages/de/c3/f06150c13284569d53273b909f31222874276a595637b7852571dfeb2c18/coverage-7.16.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fa02d561eb1d8d2f8ba43ba6e3cef4c6c402a3b632a9460fa329fcadcd5df6a3", size = 254919, upload-time = "2026-09-13T19:10:10.254Z" }, - { url = "https://files.pythonhosted.org/packages/d5/40/47e25b215ae18a29010c8e29be8782a6e04d18ba6224be2bf6cebfce6427/coverage-7.16.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:bc5354a124799f1f87b7637bbe6f18cd4bc66a1f37f6aa2b5db40f9adad531dc", size = 257428, upload-time = "2026-09-13T19:10:12.124Z" }, - { url = "https://files.pythonhosted.org/packages/27/4b/1e2a4267d14cbd12a8489364a9d40020233e6be836d929b363f0e77209e2/coverage-7.16.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34bafe9f4094315248573e6223e11af0ec1b25f9cbca43bf0e9a26a189ba2751", size = 258771, upload-time = "2026-09-13T19:10:14.031Z" }, - { url = "https://files.pythonhosted.org/packages/be/2e/9aa6146cea929fab9185bb2642ffef7f47520a6e5efe407f75f9b12f4cf0/coverage-7.16.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:29c4d3e32a3b5efa420a3dc627c7e570deb80ef997def52c7686a474f5edc7ab", size = 261086, upload-time = "2026-09-13T19:10:16.213Z" }, - { url = "https://files.pythonhosted.org/packages/13/3c/f9ad8bcd4fb3d21c9d20a16d6d6c6f999eee8f4498ed7659a3dbd2f4b74a/coverage-7.16.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f2066c447fdd0bca39a9633a082d8ce67bf9a539a203b85059a364a405dc9fe9", size = 254895, upload-time = "2026-09-13T19:10:18.602Z" }, - { url = "https://files.pythonhosted.org/packages/b7/d1/47eda9fd1eaeea39fa7b5b13a63b2bed92ab901841fb120b3f9f5e1dc30c/coverage-7.16.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fd8ac10cd2458b3c6343aac082fb9bd0e3fa806cb2c4975f2280153474b88412", size = 256783, upload-time = "2026-09-13T19:10:20.778Z" }, - { url = "https://files.pythonhosted.org/packages/38/c3/565edf044877cb8cd3373c56885347ffc38f0edfd1f1679a487b208c19a8/coverage-7.16.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:9d8c54ec32e5c102b9241f75d88ae26538b53662868ca491736611db448d9c7a", size = 254742, upload-time = "2026-09-13T19:10:22.733Z" }, - { url = "https://files.pythonhosted.org/packages/fd/88/87d2b2aeaba719192b2089ff1c2cf89a06cf73a6d2e9f1f145626617700c/coverage-7.16.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:6dd8dda3402a01a1a8fe8b753a282466f615128574a5590a9108acd07b1f8540", size = 259016, upload-time = "2026-09-13T19:10:24.769Z" }, - { url = "https://files.pythonhosted.org/packages/fc/1b/70813185b125768abdcf7899fec4d37edc2e5fc9b60c7045c8f4271ec757/coverage-7.16.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:79afa9726438912e5cddd1fe541815cea9763c92935f594835e4c432565b68a9", size = 254559, upload-time = "2026-09-13T19:10:26.781Z" }, - { url = "https://files.pythonhosted.org/packages/d8/fa/e7aa5af279aafda633a1ede8bfd7d6916b0c8b2082be86759e0b52e73a61/coverage-7.16.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:3db3978211c3cead5437a80136ca0556bab8bc7828de15a762884b0598c41361", size = 256215, upload-time = "2026-09-13T19:10:28.714Z" }, - { url = "https://files.pythonhosted.org/packages/38/87/7a894fa4f8c6662d2b6a87a3436950e15b1fa56e01765c9d6634fb2cbeb8/coverage-7.16.1-cp314-cp314-win32.whl", hash = "sha256:49c39c7068a494f8eb427155f5682f44feee43f9b3107fd54b1e52465379c54b", size = 225719, upload-time = "2026-09-13T19:10:30.743Z" }, - { url = "https://files.pythonhosted.org/packages/8b/01/fa7193c8005fb85488f02b0e1cc3c05a233cf2640206dd978af447aeecbf/coverage-7.16.1-cp314-cp314-win_amd64.whl", hash = "sha256:c510dad19552d912058e4c3e3cbec3fb155dbe8d0ce0ceb7e7dbf5c5822bae0b", size = 226208, upload-time = "2026-09-13T19:10:32.698Z" }, - { url = "https://files.pythonhosted.org/packages/da/5c/a08634c714924c3eaef811bb3576c044128aa5e7dfa86c75e52f0761849e/coverage-7.16.1-cp314-cp314-win_arm64.whl", hash = "sha256:b7d4d7e6dcaf33e85f1919f03346403bdcc27437c420a78835f3805bca0ab71f", size = 225633, upload-time = "2026-09-13T19:10:34.79Z" }, - { url = "https://files.pythonhosted.org/packages/43/df/ddb8a4c664046b1a0ee29c9c2d25b993e5dbc8fbde715df3694a64532781/coverage-7.16.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:3d0a3681c12d3e0bcdea3d9414b04087828d6c1a482802d6f7f42c37ed530152", size = 224281, upload-time = "2026-09-13T19:10:36.853Z" }, - { url = "https://files.pythonhosted.org/packages/e2/d0/9076e0c762d8afd91182e60a520fa5c92c4a334785eeb9fd6b8ef8fe7e3c/coverage-7.16.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3f3b4469d3da3ecced775d1a8c9c5d9fc80f259e30b7b89f9fed0700d6035ecb", size = 224547, upload-time = "2026-09-13T19:10:39.359Z" }, - { url = "https://files.pythonhosted.org/packages/03/e5/9c59e64b6161704f35fe91549bb19b2bb355e95caf596c26a2065564807c/coverage-7.16.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:c08ae35c1be2fe1ce4b4c628df5c6fc0dc9a87f8e5fe8e20238d249678984741", size = 265906, upload-time = "2026-09-13T19:10:41.434Z" }, - { url = "https://files.pythonhosted.org/packages/57/5a/13ccaffb77f766101bf6f38be9dba9e468b02cc92da4552a57877dbf1c1f/coverage-7.16.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8ee71a38c54bb2676bbe762b8b0943a79ccb1c2fd6a52054f66e63eda392f8c1", size = 268023, upload-time = "2026-09-13T19:10:43.533Z" }, - { url = "https://files.pythonhosted.org/packages/ad/a1/05cfcf01d3c7c922832698ad46e51d3441d820ce87a943014bb5cf5710dd/coverage-7.16.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:76491917771f179f9772efe218c5ccc65950dbdb35f4439298d8a8dfc6ec1f72", size = 270442, upload-time = "2026-09-13T19:10:45.895Z" }, - { url = "https://files.pythonhosted.org/packages/72/15/a2f1544b8e3835d7b769f7dabcc9ac0283e0b646ef3344703ff8f18d83e6/coverage-7.16.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f4aa0b0a6f81fa3deb211e643f6954e78b4376b62b9c218271236cfa757664e8", size = 271565, upload-time = "2026-09-13T19:10:48.123Z" }, - { url = "https://files.pythonhosted.org/packages/df/5b/963c2993a82bd313f298d663afe03e164b96ace4d9d4c7561740a559e13d/coverage-7.16.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:756ba2d96d073c5a2a55d67fa22784763710fadbe22c41adde2d9cfa4dd78a8c", size = 264959, upload-time = "2026-09-13T19:10:50.195Z" }, - { url = "https://files.pythonhosted.org/packages/12/59/5eba06d1943735d7cd61d46d8c8a20ffe8ddd2da06b3c94366078dadeb9b/coverage-7.16.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:99bf9ea435cefcefd220f8687c3ddbbf78dc2de0bd11b57c3ae9fbbdf8d5561a", size = 267897, upload-time = "2026-09-13T19:10:52.252Z" }, - { url = "https://files.pythonhosted.org/packages/bd/48/af6c30f6ea431bb9b83f9070d268a9cc4fc97490abd32080164177ea999f/coverage-7.16.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:35cbc81f937fc402971df45c897d2df2bfb2014efcd990360032aa0a651635da", size = 265504, upload-time = "2026-09-13T19:10:54.432Z" }, - { url = "https://files.pythonhosted.org/packages/80/f2/6e13852a8656d05fa83284567dd5a5b1e6d89bef79fe3effca2787159eab/coverage-7.16.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:8fae08e85b334ac6ac886002b5041396a31bcf805225bbe19847627203da99e2", size = 269235, upload-time = "2026-09-13T19:10:56.563Z" }, - { url = "https://files.pythonhosted.org/packages/c2/32/b4fe465daa64ece674f83a750dfa4ba0fa3c5c74d6ef5dbb8dfce892cf0d/coverage-7.16.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:83362b64e215ef00b0ba33fcf13655ace6c9fdd144d5ad2ab59ac86c2daf166e", size = 264347, upload-time = "2026-09-13T19:10:58.634Z" }, - { url = "https://files.pythonhosted.org/packages/54/f3/88b5c0e4ca3994c6d5feb7b1bf4c9a62cee205553159184968426930a7b1/coverage-7.16.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:33300f2e140ccf26af3d8152e62bff71993f9310cfc63ba7a20940b0d246a0ae", size = 266660, upload-time = "2026-09-13T19:11:00.746Z" }, - { url = "https://files.pythonhosted.org/packages/97/72/6eff5456d7ba7f1c4678af531c33f9d957cae3201bd229b056fd13a204a3/coverage-7.16.1-cp314-cp314t-win32.whl", hash = "sha256:5539304fdbb2cc144df684d35a33b81145334d23e1c2367b5a923d25107f70b2", size = 226026, upload-time = "2026-09-13T19:11:02.846Z" }, - { url = "https://files.pythonhosted.org/packages/8e/c8/6e5ae3d8d4d0f2c0078985bf4db55fafd90e8107b1bf91ee3547a13f5694/coverage-7.16.1-cp314-cp314t-win_amd64.whl", hash = "sha256:715dcb72c3280c428c3a20134b87e42c29acec9669136e899ab2de69ca86218d", size = 226862, upload-time = "2026-09-13T19:11:04.921Z" }, - { url = "https://files.pythonhosted.org/packages/be/c7/68f9f0734afc904a92b974b489545b6a15700f3b1c4bd36eae764561e661/coverage-7.16.1-cp314-cp314t-win_arm64.whl", hash = "sha256:dac8b84c03e6029d272b8249c77018db83de59ca009a9adef7c144b4a62ee5e6", size = 226171, upload-time = "2026-09-13T19:11:06.969Z" }, - { url = "https://files.pythonhosted.org/packages/96/1a/d6d16babd0a5fe4c3fae40702158c570351694e74516d8d81b86c5637448/coverage-7.16.1-py3-none-any.whl", hash = "sha256:3d8bd4e58b6a5c2018d808f297905393c6c61da466a48c3f0596a76a4900ebe4", size = 215264, upload-time = "2026-09-13T19:12:18.895Z" }, -] - -[[package]] -name = "duckdb" -version = "1.5.6" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/59/0b/d65ea3be00ea79aa276a8388bec588a9cbf409ce637c6d306e5316210d15/duckdb-1.5.6.tar.gz", hash = "sha256:166a91dbfacfc0c9f08cc76c0243cb6d3d4296bfab5bad72a3cfb63140a5b7c8", size = 18032957, upload-time = "2026-09-28T13:38:37.978Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fb/62/a8a30a4c6b94c0861d348ed5633b963f6745a5525527530f02f3c1a7c931/duckdb-1.5.6-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:aa21d2ad803b2524326e8622d7d96b2bb1ff1d5b60368e1978ee805df9c21fb3", size = 32828003, upload-time = "2026-09-28T13:38:21.414Z" }, - { url = "https://files.pythonhosted.org/packages/71/b7/1dcca0005eb8c67adf9fc06bf0cbb1d2bf4ea1974cc89e7a7c2ad66aac28/duckdb-1.5.6-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:8a1b2ad27d414068cbca06c55cfa802eece10f86ea4812ff082f8ab4cb25fc85", size = 17413912, upload-time = "2026-09-28T13:38:23.915Z" }, - { url = "https://files.pythonhosted.org/packages/93/b0/e3ac175443550f3464f2d95731a8b0aae9b4dc3875c3a186c352262b43c2/duckdb-1.5.6-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c79c6d222b1d015cde73b5139087186b00db65357fb4e2c94c2308fbbf465a72", size = 15543122, upload-time = "2026-09-28T13:38:26.317Z" }, - { url = "https://files.pythonhosted.org/packages/9d/08/cc510a7952aba69d5cdca17f3ef61c95713d86143f2ee9aa3e097d38f50b/duckdb-1.5.6-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1052b8050ef5696e2c0d8c836949c72f3dd11f0690466acbea739613e8e2750b", size = 19457946, upload-time = "2026-09-28T13:38:28.877Z" }, - { url = "https://files.pythonhosted.org/packages/ef/a5/6f8099d9a5a02ddff89e5c85875df3465054845b0920fb0703fbdf8dd2ec/duckdb-1.5.6-cp314-cp314-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:19c5e485e59613b8878d1670bcaa7a010f53c5a4da5ae8e08863e5e529ca6182", size = 21575132, upload-time = "2026-09-28T13:38:31.231Z" }, - { url = "https://files.pythonhosted.org/packages/9f/58/762f7159662d7859e201fa05ca29f306795daeabf84f3e087215a966b001/duckdb-1.5.6-cp314-cp314-win_amd64.whl", hash = "sha256:ebcbd09cd8578ab1093393e9b16289cda0e8f1791ac595bf00eb5bad75c3cf00", size = 13713963, upload-time = "2026-09-28T13:38:33.543Z" }, - { url = "https://files.pythonhosted.org/packages/46/69/64d165db322de13f5c3e75d377b6b9694df1821155ad1fa4b14b04601abc/duckdb-1.5.6-cp314-cp314-win_arm64.whl", hash = "sha256:820a8384faef11cd86068ea48c5da57ce2d8f1c7b3d2bdb9be3398317a7c3728", size = 14514368, upload-time = "2026-09-28T13:38:35.676Z" }, -] - -[[package]] -name = "h11" -version = "0.16.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, -] - -[[package]] -name = "httpcore" -version = "1.0.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "h11" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, -] - -[[package]] -name = "httpx" -version = "0.28.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "certifi" }, - { name = "httpcore" }, - { name = "idna" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, -] - -[[package]] -name = "idna" -version = "3.20" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, -] - -[[package]] -name = "iniconfig" -version = "2.3.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, -] - -[[package]] -name = "jmespath" -version = "1.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d3/59/322338183ecda247fb5d1763a6cbe46eff7222eaeebafd9fa65d4bf5cb11/jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d", size = 27377, upload-time = "2026-01-22T16:35:26.279Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, -] - -[[package]] -name = "jsonschema" -version = "4.26.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "attrs" }, - { name = "jsonschema-specifications" }, - { name = "referencing" }, - { name = "rpds-py" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, -] - -[[package]] -name = "jsonschema-specifications" -version = "2025.9.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "referencing" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, -] - -[[package]] -name = "packaging" -version = "26.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, -] - -[[package]] -name = "pluggy" -version = "1.6.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, -] - -[[package]] -name = "pyarrow" -version = "26.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ec/34/17c34cb38e5d940e38f0f0d9fdfa0e8a506676409ea9b85aff7e3079f831/pyarrow-26.0.0.tar.gz", hash = "sha256:0cccd36e00ea3afeb52ded61f2721ce71f604853d70c45365c58324eb773d6ae", size = 1239433, upload-time = "2026-10-09T08:26:25.315Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8c/32/01858422a37f083911c2bb4d15cc32c5eeaa9d9b2bf5ddedee995a7146a6/pyarrow-26.0.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:5780d487ff6c6ed7b42298609680d87fe0036e529a9dc2e1105364bce9697f50", size = 36378402, upload-time = "2026-10-09T08:23:36.537Z" }, - { url = "https://files.pythonhosted.org/packages/00/85/f6b5976c2878b752d0804d371684e0495a71de296b6dc6559e6fbaa4311a/pyarrow-26.0.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:a0e4e92eeb088f1d7c2c04d6c7de8434c75abb4b4ccf0bbcd045aa7164c68d93", size = 38733074, upload-time = "2026-10-09T08:23:42.873Z" }, - { url = "https://files.pythonhosted.org/packages/81/bc/c90fcbbcf893631e23dab1b0fb3fa29a508a8614326571b03c0894eda00b/pyarrow-26.0.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:eaf9e7cc7ab59f6c760232bbde18f64d559bbc50544841303bfb32be53533297", size = 50929201, upload-time = "2026-10-09T08:23:50.507Z" }, - { url = "https://files.pythonhosted.org/packages/ec/c1/0c1ff38ab7df1b2cf54cf0ad9f19a516c4e416c6c9b4c966cc2c9d587f77/pyarrow-26.0.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:ab6914db225d7f399652ae1f08588dfbc9efe617612715701e3d9d5cfa5ca19f", size = 53951865, upload-time = "2026-10-09T08:23:57.692Z" }, - { url = "https://files.pythonhosted.org/packages/9f/70/6a6b170496925472adad45a32528770fc8632db35fc60d4edd1e9ce1be0b/pyarrow-26.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:41dd3661ef40790a78870052ad7a58ad827b27c67a4511f06962eb9e9b74d19b", size = 54496388, upload-time = "2026-10-09T08:24:05.23Z" }, - { url = "https://files.pythonhosted.org/packages/a8/32/033ef9dba80976820190e292a10a5a23e9406572b76bbeb4d685d90e5c8d/pyarrow-26.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6e949744dcfc2d379808f7013c5f9cafaf0f817656dff7d46c6931528dd1784b", size = 57411588, upload-time = "2026-10-09T08:24:12.043Z" }, - { url = "https://files.pythonhosted.org/packages/1e/ff/a74892c50aaf1f9f744a84493e08a2f99221e77c39d2d4a926de21a99edf/pyarrow-26.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:4a5fa8dc70dd50808990ff36faf44088e357b353d86c7682dd92d4b78d4c97d5", size = 29237858, upload-time = "2026-10-09T08:24:58.106Z" }, - { url = "https://files.pythonhosted.org/packages/03/10/f0ee0976ef08a851a743c57608917ac9a47623f688b9ee0efe5429975ba1/pyarrow-26.0.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:e2a1856e9565fe2679863b372478c681806aebbf7d0a6e72f33e77f804e647d6", size = 36495870, upload-time = "2026-10-09T08:24:16.479Z" }, - { url = "https://files.pythonhosted.org/packages/27/ca/0bc431a509bf10b4472dbb94f4184752ecbbddeb7f467152dac0fdaed469/pyarrow-26.0.0-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:4bcba83299cb2b8f8e443d36c6ba6269a5034431879015fb0719495df8a14de2", size = 38819754, upload-time = "2026-10-09T08:24:20.875Z" }, - { url = "https://files.pythonhosted.org/packages/61/59/2be41d26af7a07fb71581fb753cae396403ba1a2978355fd553929d44a9a/pyarrow-26.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:3a4d235876f14b4136b4d616ec42eb469ea0d6ead336cae631aa1dd29b21c962", size = 50933671, upload-time = "2026-10-09T08:24:27.199Z" }, - { url = "https://files.pythonhosted.org/packages/4b/cb/b6d5048cf3178be9678f5c9c60040199894b2f69c3439c87ced91fd24da9/pyarrow-26.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:210cc9b83888b87cdc8f793eebb264f22b20d0dedbedefc73b9687a7047b4747", size = 53906419, upload-time = "2026-10-09T08:24:33.536Z" }, - { url = "https://files.pythonhosted.org/packages/09/2b/23e30fbd776c81d18d134d2592eb60daca13e8a57ab087d0fa042f9d9f3d/pyarrow-26.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca77c43ca55bfc9a4eeb1f0cd5f093f08731b77c24cdba0829035f084959b0bb", size = 54527960, upload-time = "2026-10-09T08:24:41.292Z" }, - { url = "https://files.pythonhosted.org/packages/e2/23/fce251cd6b0546dfc181b00d5c8ef1c95a8c4cae83266bc3dfd5f719c62c/pyarrow-26.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:290a74c48e9491b436fd5edacfadf357943f82aa45c81110bd83a69aab33d1cf", size = 57388010, upload-time = "2026-10-09T08:24:48.186Z" }, - { url = "https://files.pythonhosted.org/packages/44/a5/0126fb0ef8d59bf257bdd68bb41623b72afc6e81790a0b4ac863a0f58861/pyarrow-26.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:515a10dae2a1d236bc9c9209d0317acb6746ea63cd4f98704904af7156d90ed1", size = 29406123, upload-time = "2026-10-09T08:24:53.387Z" }, -] - -[[package]] -name = "pygments" -version = "2.21.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, -] - -[[package]] -name = "pytest" -version = "9.1.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "iniconfig" }, - { name = "packaging" }, - { name = "pluggy" }, - { name = "pygments" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, -] - -[[package]] -name = "pytest-cov" -version = "7.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "coverage" }, - { name = "pluggy" }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b1/51/a849f96e117386044471c8ec2bd6cfebacda285da9525c9106aeb28da671/pytest_cov-7.1.0.tar.gz", hash = "sha256:30674f2b5f6351aa09702a9c8c364f6a01c27aae0c1366ae8016160d1efc56b2", size = 55592, upload-time = "2026-03-21T20:11:16.284Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, -] - -[[package]] -name = "python-dateutil" -version = "2.9.0.post0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, -] - -[[package]] -name = "python-dotenv" -version = "1.2.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/74/26/2fbeedb218a787a5eea551c7532cac4e009f83d689dd2faa0d0353473f86/python_dotenv-1.2.4.tar.gz", hash = "sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0", size = 60824, upload-time = "2026-10-01T05:36:10Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" }, -] - -[[package]] -name = "referencing" -version = "0.37.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "attrs" }, - { name = "rpds-py" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, -] - -[[package]] -name = "rpds-py" -version = "2026.6.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/36/7fbe9dcdaf857fb3f63c2a2284b62492d95f5e8334e947e5fb6e7f68c9be/rpds_py-2026.6.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:931908d9fc855d8f74783377822be318edb6dcb19e47169dc038f9a1bf60b06e", size = 344510, upload-time = "2026-06-30T07:15:57.921Z" }, - { url = "https://files.pythonhosted.org/packages/ba/54/f785cc3d3f60839ca57a5af4927a9f347b07b2799c373fc20f7949f87c7e/rpds_py-2026.6.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d7469697dce35be237db177d42e2a2ee26e6dcc5fc052078a6fefabd288c6edd", size = 339495, upload-time = "2026-06-30T07:15:59.238Z" }, - { url = "https://files.pythonhosted.org/packages/63/ef/d4cdaf309e6b095b43597103cf8c0b951d6cca2acce68c474f75ec12e0c7/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bcfbcf66006befb9fd2aeaa9e01feaf881b4dc330a02ba07d2322b1c11be7b5d", size = 369454, upload-time = "2026-06-30T07:16:01.021Z" }, - { url = "https://files.pythonhosted.org/packages/96/4a/9559a68b7ee15db09d7981212e8c2e219d2a1d6d4faa0391d813c3496a36/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:847927daf4cffbd4e90e42bc890069897101edd015f956cb8721b3473372edda", size = 374583, upload-time = "2026-06-30T07:16:02.287Z" }, - { url = "https://files.pythonhosted.org/packages/ef/75/8964aa7d2c6e8ac43eba8eb6e6b0fdda1f46d39f2fc3e6aa9f2cb17f485d/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aca6c1ef08a82bfe327cc156da694660f599923e2e6665b6d81c9c2d0ac9ffc8", size = 492919, upload-time = "2026-06-30T07:16:03.723Z" }, - { url = "https://files.pythonhosted.org/packages/8f/97/6908094ac804115e65aedfd90f1b5fee4eebebd3f6c4cfc5419939267565/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ae50181a047c871561212bb97f7932a2d45fb53e947bd9b57ebad85b529cbc53", size = 383725, upload-time = "2026-06-30T07:16:05.305Z" }, - { url = "https://files.pythonhosted.org/packages/d1/9c/0d1fdc2e7aba23e290d603bc494e97bd205bae262ce33c6b32a69768ed5e/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc319e5a1de4b6913aac94bf6a2f9e847371e0a140a43dd4991db1a09bc2d504", size = 367255, upload-time = "2026-06-30T07:16:07.086Z" }, - { url = "https://files.pythonhosted.org/packages/c4/fe/f0209ca4a9ed074bc8acb44dfd0e81c3122e94c9689f5645b7973a866719/rpds_py-2026.6.3-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:e4316bf32babbed84e691e352faf967ce2f0f024174a8643c37c94a1080374fc", size = 379060, upload-time = "2026-06-30T07:16:08.525Z" }, - { url = "https://files.pythonhosted.org/packages/c6/8d/f1cc54c616b9d8897de8738aac148d20afca93f68187475fe194d09a71b9/rpds_py-2026.6.3-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8c6e5a2f750cc71c3e3b11d71661f21d6f9bc6cebc6564b1466417a1ec03ec77", size = 395960, upload-time = "2026-06-30T07:16:09.989Z" }, - { url = "https://files.pythonhosted.org/packages/fb/04/aafff00f73aeca2945f734f1d483c64ab8f472d0864ab02377fd8e89c3b2/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4470ce197d4090875cf6affbf1f853338387428df97c4fb7b7106317b8214698", size = 545356, upload-time = "2026-06-30T07:16:11.816Z" }, - { url = "https://files.pythonhosted.org/packages/fd/cc/e229663b9e4ddac5a4acbe9085dd80a71af2a5d356b8b39d6bff233f24b0/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ea964164cc9afa72d4d9b23cc28dafae93693c0a53e0b42acbff15b22c3f9ddd", size = 612319, upload-time = "2026-06-30T07:16:13.586Z" }, - { url = "https://files.pythonhosted.org/packages/e3/7a/8a0e6d3e6cd066af108b71b43122c3fe158dd9eb86acac626593a2582eb1/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:639c8929aa0afe81be836b04de888460d6bed38b9c54cfc18da8f6bfabf5af5d", size = 573508, upload-time = "2026-06-30T07:16:15.23Z" }, - { url = "https://files.pythonhosted.org/packages/87/03/2a69ab618a789cf6cf85c86bb844c62d090e700ab1a2aa676b3741b6c516/rpds_py-2026.6.3-cp314-cp314-win32.whl", hash = "sha256:882076c00c0a608b131187055ddc5ae29f2e7eaf870d6168980420d58528a5c8", size = 202504, upload-time = "2026-06-30T07:16:16.893Z" }, - { url = "https://files.pythonhosted.org/packages/85/62/a3892ba945f4e24c78f352e5de3c7620d8479f73f211406a97263d13c7d2/rpds_py-2026.6.3-cp314-cp314-win_amd64.whl", hash = "sha256:0be972be84cfcaf46c8c6edf690ca0f154ac17babf1f6a955a51579b34ad2dc5", size = 220380, upload-time = "2026-06-30T07:16:18.108Z" }, - { url = "https://files.pythonhosted.org/packages/3d/e7/c2bd44dc831931815ad11ebb5f430b5a0a4d3caa9de837107876c30c3432/rpds_py-2026.6.3-cp314-cp314-win_arm64.whl", hash = "sha256:2a9c6f195058cb45335e8cc3802745c603d716eb96bc9625950c1aac71c0c703", size = 215976, upload-time = "2026-06-30T07:16:19.654Z" }, - { url = "https://files.pythonhosted.org/packages/79/9c/fff7b74bce9a091ec9a012a03f9ff5f69364eaf9451060dfc4486da2ffdd/rpds_py-2026.6.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f90938e92afda60266da758ee7d363447f7f0138c9559f9e1811629580582d90", size = 346840, upload-time = "2026-06-30T07:16:21.268Z" }, - { url = "https://files.pythonhosted.org/packages/e9/44/77bcb1168b33704908295533d27f10eb811e9e3e193e8993dc99572211d3/rpds_py-2026.6.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ec829541c45bca16e61c7ae50c20501f213605beb75d1aba91a6ee37fbbb56a4", size = 340282, upload-time = "2026-06-30T07:16:22.875Z" }, - { url = "https://files.pythonhosted.org/packages/87/3c/7a9081c7c9e645b39efe19e4ffbeccd80add246327cd9b888aecffd72317/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afd70d95892096cdb26f15a00c45907b17817577aa8d1c76b2dcc2788391f9e9", size = 370403, upload-time = "2026-06-30T07:16:24.415Z" }, - { url = "https://files.pythonhosted.org/packages/f7/69/af47021eb7dad6ff3396cb001c08f0f3c4d06c20253f75be6421a59fe6b7/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:29dfa0533a5d4c94d4dfa1b694fcb56c9c63aad8330ffdd816fd225d0a7a162f", size = 376055, upload-time = "2026-06-30T07:16:26.111Z" }, - { url = "https://files.pythonhosted.org/packages/81/fc/a3bcf517084396a6dd258c592567a3c011ba4557f2fde23dceaf26e74f2e/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af05d726809bff6b141be124d4c7ce998f9c9c7f30edb1f46c07aa103d540b41", size = 494419, upload-time = "2026-06-30T07:16:27.596Z" }, - { url = "https://files.pythonhosted.org/packages/c9/eb/13d529d1788135425c7bf207f8463458ca5d92e43f3f701365b83e9dffc1/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9826217f048f620d9a712672818bf231442c1b35d96b227a07eabd11b4bb6945", size = 384848, upload-time = "2026-06-30T07:16:29.183Z" }, - { url = "https://files.pythonhosted.org/packages/8e/f4/b7ac49f30013aba8f7b9566b1dd07e81de95e708c1374b7bacc5b9bc5c9c/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:536bceea4fa4acf7e1c61da2b5786304367c816c8895be71b8f537c480b0ea1f", size = 371369, upload-time = "2026-06-30T07:16:30.912Z" }, - { url = "https://files.pythonhosted.org/packages/31/86/6260bafa622f788b07ddec0e52d810305c8b9b0b8c27f58a2ab04bf62b4f/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:bc0011654b91cc4fb2ae701bec0a0ba1e552c0714247fa7af6c59e0ccfa3a4e1", size = 379673, upload-time = "2026-06-30T07:16:32.486Z" }, - { url = "https://files.pythonhosted.org/packages/19/c3/03f1ee79a047b48daeca157c89a18509cde22b6b951d642b9b0af1be660a/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:539d75de9e0d536c84ff18dfeb805398e58227001ce09231a26a08b9aed1ee0e", size = 397500, upload-time = "2026-06-30T07:16:34.471Z" }, - { url = "https://files.pythonhosted.org/packages/f0/95/8ed0cd8c377dca12aea498f119fe639fc474d1461545c39d2b5872eb1c0f/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:166cf54d9f44fc6ceb53c7860258dde44a81406646de79f8ed3234fca3b6e538", size = 545978, upload-time = "2026-06-30T07:16:36.45Z" }, - { url = "https://files.pythonhosted.org/packages/d3/f2/0eb57f0eaa83f8fc152a7e03de968ab77e1f00732bebc892b190c6eebde7/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:d34c20167764fbcf927194d532dd7e0c56772f0a5f943fa5ef9e9afbba8fb9db", size = 613350, upload-time = "2026-06-30T07:16:38.213Z" }, - { url = "https://files.pythonhosted.org/packages/5b/de/e0674bdbc3ef7634989b3f854c3f34bc1f587d36e5bfdc5c378d57034619/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ea7bb13b7c9a29791f87a0387ba7d3ad3a6d783d827e4d3f27b40a0ff44495e2", size = 576486, upload-time = "2026-06-30T07:16:39.797Z" }, - { url = "https://files.pythonhosted.org/packages/f2/f6/21101359743cd136ada781e8210a85769578422ba460672eea0e29739200/rpds_py-2026.6.3-cp314-cp314t-win32.whl", hash = "sha256:6de4744d05bd1aa1be4ed7ea1189e3979196808008113bbbf899a460966b925e", size = 201068, upload-time = "2026-06-30T07:16:41.316Z" }, - { url = "https://files.pythonhosted.org/packages/a6/b2/9574d4d44f7760c2aa32d92a0a4f41698e33f5b204a0bf5c9758f52c79d5/rpds_py-2026.6.3-cp314-cp314t-win_amd64.whl", hash = "sha256:c7b9a2f8f4d8e90af72571d3d495deebdd7e3c75451f5b41719aee166e940fc2", size = 220600, upload-time = "2026-06-30T07:16:43.091Z" }, -] - -[[package]] -name = "ruff" -version = "0.17.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e9/a7/70debb024dfacda67b8e560cc7511f52b34b9348a8cc8c1ec23036dcd51d/ruff-0.17.0.tar.gz", hash = "sha256:5cd03240d8208a557c2a9655a5cb07ebe36aa6bb35065f97d48c1f6adef5a322", size = 5320554, upload-time = "2026-10-09T19:47:29.248Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/f8/ee5ab9da6089eae2a33e6008b01deb1eda19992c1c8e10661e98cee1640f/ruff-0.17.0-py3-none-linux_armv6l.whl", hash = "sha256:0e271826af9a20d18c6cfae8c51e82959167c24859686ddd3eb9a7f0842ce81e", size = 10148907, upload-time = "2026-10-09T19:46:38.695Z" }, - { url = "https://files.pythonhosted.org/packages/9f/d9/2f81fb5a9d580afbb11b1c8ff915233a11f2a1b27405d7991f183c5e1976/ruff-0.17.0-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:5f0ca4a40f81403689c04f12966e22f44e329ae362072d8f1587b7bda87f603b", size = 10224208, upload-time = "2026-10-09T19:46:41.711Z" }, - { url = "https://files.pythonhosted.org/packages/a7/20/643f3c8f75594f937b2bf74801241c56a2e2b8e139d24dff8b66b28cdd7f/ruff-0.17.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:cbf7149e0927dc3295d5d64679a4765576eef71b00782b2ae969ef82274d6bb9", size = 9273324, upload-time = "2026-10-09T19:46:44.323Z" }, - { url = "https://files.pythonhosted.org/packages/ec/91/627700b233d367736cb274f1bd0b47d1f2b12f68878192812bd875adadc3/ruff-0.17.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:13ee90156522998c3037059d8f66885c8adeeaf7643bdce2caceee196ecd23e0", size = 9953190, upload-time = "2026-10-09T19:46:47.155Z" }, - { url = "https://files.pythonhosted.org/packages/cd/92/91f7b5ed39490f89d6cbf56e1f543c383667a725efa8e2c2dee0f01f5591/ruff-0.17.0-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3d8e4a002a94cd9d0dc48b51dc69d807a172b5b9bf2b668e656424dc5b55ead1", size = 9961746, upload-time = "2026-10-09T19:46:50.098Z" }, - { url = "https://files.pythonhosted.org/packages/87/c5/7310f9fc63ce11ff6394edbd5e85433dfb0e14c9fbf6ccc97f1538491bc7/ruff-0.17.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c0b8a60c06a218c337e1161638d34757f83449243e2db161483ddf948e53ad14", size = 10625483, upload-time = "2026-10-09T19:46:53.379Z" }, - { url = "https://files.pythonhosted.org/packages/a5/8d/97443f0dca4a03a0bc7629fd396fd494a1cb6666121e38c5075acb217d8f/ruff-0.17.0-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a330178bdffc4205dbf3bda11d93e059e388fd6546f8cdd304501a9160363c0d", size = 11350129, upload-time = "2026-10-09T19:46:56.486Z" }, - { url = "https://files.pythonhosted.org/packages/9c/0a/c525efd9777be4b6b012e6969a3012648468e7e6c4b3e5b46af69f46e8eb/ruff-0.17.0-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7bb08489e234876fa2da67ae3ea938e9a2156da80293e0e4365abd6973d98329", size = 10906223, upload-time = "2026-10-09T19:47:00.263Z" }, - { url = "https://files.pythonhosted.org/packages/2c/3c/4a01195d93420cad1175bedad13a515dc8a56f95a6e39789b92e582682f5/ruff-0.17.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc73e7c133e82d55b5f15897b2a442d72c0cb4a0c886c46801ce3c247150b60c", size = 10386314, upload-time = "2026-10-09T19:47:03.057Z" }, - { url = "https://files.pythonhosted.org/packages/c7/72/1a3951665485a921f6375f91e754a1854d5a645d41acc3642668064ff64d/ruff-0.17.0-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:db4f74c533403ab70fe4007873f6ae0c9f94a8b03158cf48d78788e47cdbe399", size = 10565464, upload-time = "2026-10-09T19:47:05.831Z" }, - { url = "https://files.pythonhosted.org/packages/90/8c/539b4d8c082f57e18db8ae2be85a460d77861c79dcd5798e32b536a6a06f/ruff-0.17.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:3d8cc360e666d1914e47b0777c6906d70cf18891a55532bd0a16844195d70859", size = 10079468, upload-time = "2026-10-09T19:47:08.617Z" }, - { url = "https://files.pythonhosted.org/packages/e0/b8/84286966db79434e8c26b585b0a0f6897cb3ab1c51a4aa4df10c28488b62/ruff-0.17.0-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d66de796b726c4801e05fa99a2a8d7a780e107be222486c304ab61765561e866", size = 9958556, upload-time = "2026-10-09T19:47:11.324Z" }, - { url = "https://files.pythonhosted.org/packages/69/50/27b6eed27b83fcdd5bfa0d52b83231e29094754374698da404d094487ae3/ruff-0.17.0-py3-none-musllinux_1_2_i686.whl", hash = "sha256:c3f268baf004aea944f040623327119527ea231af15f7fb7890e82cea0679589", size = 10352173, upload-time = "2026-10-09T19:47:14.188Z" }, - { url = "https://files.pythonhosted.org/packages/2a/fa/955399fd13044cd827862044117d784a59e3196f6cce7424908ac9a7f914/ruff-0.17.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:864b6c1acb6b0bccf94b5a3938a1531fd09aaca5e5659a2e7bf0f3cf2a685540", size = 10791761, upload-time = "2026-10-09T19:47:16.931Z" }, - { url = "https://files.pythonhosted.org/packages/ae/bf/024e01e1f6aec87768696725e648ed5b438941341eea8f8100beb681961f/ruff-0.17.0-py3-none-win32.whl", hash = "sha256:5e50aa5b84decd9fe5b0bb0e6f71c3b592f1767ed09faa4b7207d933961e35cd", size = 9904112, upload-time = "2026-10-09T19:47:19.75Z" }, - { url = "https://files.pythonhosted.org/packages/cc/77/1ee73df41dcc8d1cdb686ee4bc46ea29704ea175feb6b95c78420f631ab8/ruff-0.17.0-py3-none-win_amd64.whl", hash = "sha256:8ab76bcda86dfd28e13776cb5de3c7bcdcf1ae3d37ed761113d1a5a415dc134c", size = 10115585, upload-time = "2026-10-09T19:47:22.698Z" }, - { url = "https://files.pythonhosted.org/packages/fd/71/eb4f0ccc844aece56963e8578df9c95d4c00f580547d52329d4035d3af18/ruff-0.17.0-py3-none-win_arm64.whl", hash = "sha256:c154c73ff43f9854395e24cac507af13078962e53d2b511605058d22af1fdb88", size = 9872035, upload-time = "2026-10-09T19:47:26.306Z" }, -] - -[[package]] -name = "s3transfer" -version = "0.19.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "botocore" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/76/43/35e4d8aa320bffe8287fe8f65f578fa2d2db0a64212f0e710dce58267854/s3transfer-0.19.2.tar.gz", hash = "sha256:ba0309fd86be3c27dbf78cdd813c13c5e1df16e5874b99d2535ebbdfb9892993", size = 165592, upload-time = "2026-07-22T19:30:44.432Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/e7/5c595c75e9f41a44f30e526eda465ea0b4eec93470e074e4a111b253f13a/s3transfer-0.19.2-py3-none-any.whl", hash = "sha256:d8168eccca828cbb2cd573675333f3bddd254313a9c42494b84c76b539e8ba25", size = 90216, upload-time = "2026-07-22T19:30:43.251Z" }, -] - -[[package]] -name = "six" -version = "1.17.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, -] - -[[package]] -name = "ty" -version = "0.0.86" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f1/fa/9b35728cc3c04d64f434c656836fa3c5f6e384a7813e48e63245510d5c69/ty-0.0.86.tar.gz", hash = "sha256:6edcaf52e207d653873d5f495c1a8470075b232030714c981f07f0a1075bc343", size = 7911723, upload-time = "2026-10-09T22:20:57.83Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/95/27/dd422283667ce10d60af57edc3ccab078084282ee304a5c22b5ed79390c6/ty-0.0.86-py3-none-linux_armv6l.whl", hash = "sha256:305c238df5dedf97f1b65e52d2c446a41d11551291e37054858c00c5627bf15b", size = 14159390, upload-time = "2026-10-09T22:20:17.583Z" }, - { url = "https://files.pythonhosted.org/packages/57/e3/838ea547c177983976103d3a54b346afc22d0ff97943ab58c7b7aff1f753/ty-0.0.86-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:27a8a7cf26a1cd17d93586eb20aadbcc535fa6ad4b535813ee8fc52560c31efd", size = 13684426, upload-time = "2026-10-09T22:20:19.939Z" }, - { url = "https://files.pythonhosted.org/packages/bc/62/dfde84ffab702545f866350675b16f8df6555d3c41123c25e7a509fe857e/ty-0.0.86-py3-none-macosx_11_0_arm64.whl", hash = "sha256:40e5fc602af41b0ea89dd1d19fe8da7e75322e6e0db95ea23340a858b409ac2b", size = 12845457, upload-time = "2026-10-09T22:20:21.979Z" }, - { url = "https://files.pythonhosted.org/packages/47/b2/7e0e7ffc8b3961f5f74893ba9b98433b922d3f1ae6621d1e3e3e20663e1d/ty-0.0.86-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c4b525ce4feb60aa2dd6becae4c470daea889149ba9dc7699ffbcf41448f69a9", size = 13656310, upload-time = "2026-10-09T22:20:24.544Z" }, - { url = "https://files.pythonhosted.org/packages/e7/c8/977594e024d154f0e064b48a6f7e39a0e1e55a524349dba22146f01e02db/ty-0.0.86-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a000ddcc0b99bd1ab8c8277630711061a36ae83395780fdb935bad540ebe7103", size = 13887036, upload-time = "2026-10-09T22:20:26.844Z" }, - { url = "https://files.pythonhosted.org/packages/3a/75/67e8e7bf89a6be7535768380cb20569b460b89cb09d5c82ce27411782786/ty-0.0.86-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ea3848f3cab206e9798e5a9f7c4ce8a80297b0a88ba9aa8a091360a298e97424", size = 14805103, upload-time = "2026-10-09T22:20:29.274Z" }, - { url = "https://files.pythonhosted.org/packages/a1/14/a7f3b88cc76156feaf5d48601bd5da96a116f846ad0abc526df03a735bcc/ty-0.0.86-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:087bad6ae8fa7248a16c01f5646c121dccaacbaf320ff544eed4e8c5c1fd7555", size = 15203931, upload-time = "2026-10-09T22:20:31.736Z" }, - { url = "https://files.pythonhosted.org/packages/a7/23/42f6ad5d4bb7091d70a0e96d7d436d6bc9a490210a928727dde5d883ed26/ty-0.0.86-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:fe7f2721746c9ee64626c69da9245faedc0f375024bf41458e45eb7b28fe5f63", size = 15094434, upload-time = "2026-10-09T22:20:34.269Z" }, - { url = "https://files.pythonhosted.org/packages/d1/b8/211781d3c8de5fa88437412b7a8c0d7a632596033cff51d5004b08e94e1c/ty-0.0.86-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5c18501c54874149d05e5199211146876afeaeee2af234042e56dccc9d5812a", size = 14436812, upload-time = "2026-10-09T22:20:36.795Z" }, - { url = "https://files.pythonhosted.org/packages/b2/2a/518cc7ef2586384345be675d470e0087591810304b5d994d0a2194c7d68e/ty-0.0.86-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:0a48967c8adba6b12035243f225a0585b0bc5f0bf940a4829876bc455ebf3d2f", size = 14671116, upload-time = "2026-10-09T22:20:39.277Z" }, - { url = "https://files.pythonhosted.org/packages/7a/18/a820553ad3206d0cdfad5866dd64939c7e3be73e891d88c73f7fd3acb5d6/ty-0.0.86-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:561a4eae98f6ff05395e8d7be8151fdb328eeaead1ac63dc721ca891623f7924", size = 13586361, upload-time = "2026-10-09T22:20:41.444Z" }, - { url = "https://files.pythonhosted.org/packages/22/58/f1700176e6ae4d0a3d25e447734c60ca464d6e76ed2e8a32920ebd41e523/ty-0.0.86-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:ccad053ce880a1f8c0850d9dd1f277f3ee559a98bded3f93472268376ceccc2d", size = 13900289, upload-time = "2026-10-09T22:20:43.955Z" }, - { url = "https://files.pythonhosted.org/packages/59/86/2f0e3c9a055f8606911a80311763a089784b66af22dd80fd3290e3b167c6/ty-0.0.86-py3-none-musllinux_1_2_i686.whl", hash = "sha256:7c16d22857bad1da56b147bf53ef0ed2252d7677dc5e7ee51c757b2e52ab6351", size = 14235785, upload-time = "2026-10-09T22:20:46.401Z" }, - { url = "https://files.pythonhosted.org/packages/b4/1d/72fa2347b641143b0440296144a65f424fe047302cb13af059988f1de7a4/ty-0.0.86-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:d863f8f190e96878ed1900a8a6d5093f37761c0c47409e2bdb3d9370e37471e1", size = 14559840, upload-time = "2026-10-09T22:20:48.753Z" }, - { url = "https://files.pythonhosted.org/packages/47/4a/a798be4aee4ea0bb427c22f157945d0ac41310f4d6e058b3758dfb859451/ty-0.0.86-py3-none-win32.whl", hash = "sha256:1ac3d8fe9efae04fbf1407583ed4118e0364a45b49a020d62b202846695a2ba1", size = 13133227, upload-time = "2026-10-09T22:20:51.034Z" }, - { url = "https://files.pythonhosted.org/packages/c7/a0/c9d585fa1c5bf4ed2727f576f1542bc13e268f036451a79d057c249fc26f/ty-0.0.86-py3-none-win_amd64.whl", hash = "sha256:6fe4116fb1a7ad3c4f7804d9241dc81187717fbd9f5fed5b50e2752a20e17a67", size = 13665391, upload-time = "2026-10-09T22:20:53.237Z" }, - { url = "https://files.pythonhosted.org/packages/2a/7e/d9811358bce1e54ac1b93bd44f4c45eba5e2e92672c5410248776c54319e/ty-0.0.86-py3-none-win_arm64.whl", hash = "sha256:0df36f494c5d07f68ebec3edb74fc719c4c959db7061c2018f1dff2dfe62150b", size = 13237981, upload-time = "2026-10-09T22:20:55.586Z" }, -] - -[[package]] -name = "typing-extensions" -version = "4.16.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, -] - -[[package]] -name = "urllib3" -version = "2.8.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, -] diff --git a/bazaarplusplus-installer/.gitignore b/bazaarplusplus-installer/.gitignore deleted file mode 100644 index 31e0132..0000000 --- a/bazaarplusplus-installer/.gitignore +++ /dev/null @@ -1,41 +0,0 @@ -# Frontend build output -/build/ -/.vite/ -vite.config.ts.timestamp-* - -# Generated audits and review artifacts (see AGENTS.md) -/tmp/ - -# Tauri / Rust build output -/src-tauri/target/ -/src-tauri/gen/schemas/ -/src-tauri/icons/macos-generated/ - -# The macOS launch trampoline is compiled at build time from the committed -# src-tauri/trampoline/bpp_launcher.c. Never commit the compiled binary. -/src-tauri/resources/Trampoline/ - -# Mod build outputs staged into SourceForBuild during packaging. -BepInEx.zip -BazaarPlusPlus.dll -BazaarPlusPlus.version -BazaarPlusPlus.ModApi.dll -BazaarPlusPlus.Storage.dll -BazaarPlusPlus.Localization.dll -BazaarPlusPlus.history-database.json - -# Retired recorder binaries are forbidden in release Payloads; ignore local leftovers. -/src-tauri/resources/SourceForBuild/*/BepInEx/plugins/ffmpeg -/src-tauri/resources/SourceForBuild/*/BepInEx/plugins/ffmpeg.exe -/src-tauri/resources/SourceForBuild/*/BepInEx/plugins/ffmpeg-LICENSE.txt - -# Machine-local provenance receipts and generated archive checksums. -/src-tauri/resources/BepInExSource/*/payload-build.json -/src-tauri/resources/BepInExSource/*/BepInEx.zip.manifest.json -/src-tauri/resources/BepInExSource/*/BepInEx.zip.tmp-* -/src-tauri/resources/BepInExSource/*/BepInEx.zip.manifest.json.tmp-* - -# Throwaway fixtures from scripts/bundle.test.mjs; removed after each run and -# left behind only when a run is interrupted. -.bpp-signing-test-*/ -.bpp-deps-test-*/ diff --git a/bazaarplusplus-installer/.oxlintrc.json b/bazaarplusplus-installer/.oxlintrc.json deleted file mode 100644 index dc89640..0000000 --- a/bazaarplusplus-installer/.oxlintrc.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "$schema": "./node_modules/oxlint/configuration_schema.json", - "plugins": [ - "typescript", - "oxc", - "unicorn", - "react", - "jsx-a11y", - "import", - "promise", - "vitest" - ], - "categories": { - "correctness": "error", - "suspicious": "error", - "perf": "error" - }, - "ignorePatterns": [ - "build/**", - "src-tauri/target/**", - "src/types/generated/**" - ], - "rules": { - "react/react-in-jsx-scope": "off", - "unicorn/no-array-sort": "off", - "unicorn/no-array-reverse": "off", - "react/no-array-index-key": "off", - "jsx-a11y/prefer-tag-over-role": "off", - "jsx-a11y/control-has-associated-label": "off", - "eslint/no-await-in-loop": "off", - "import/no-unassigned-import": "off", - "typescript/no-unsafe-type-assertion": "off", - "typescript/consistent-return": "off", - "typescript/unbound-method": "off", - // Installer-specific: the React Compiler heuristics below flag the - // latest-ref and trigger-dependency patterns this app uses on purpose, - // and it does not build with the React Compiler. - "react/refs": "off", - "react/exhaustive-effect-dependencies": "off", - "react/set-state-in-effect": "off", - "react/memo-dependencies": "off", - "react/globals": "off", - // Tauri and Vite inject `__NAME__` globals. - "eslint/no-underscore-dangle": "off", - "import/no-named-as-default": "off", - // Side-effect-only `.then` handlers are idiomatic here. - "promise/always-return": "off" - }, - "overrides": [ - { - // Untyped release scripts sort string paths; the default code-unit order - // is the deterministic order the manifests and zips depend on. - "files": ["scripts/**/*.mjs"], - "rules": { - "typescript/require-array-sort-compare": "off" - } - }, - { - "files": ["**/*.test.{ts,tsx,js,mjs}"], - "rules": { - "vitest/require-mock-type-parameters": "off", - "vitest/require-to-throw-message": "off", - "vitest/no-conditional-expect": "off" - } - } - ] -} diff --git a/bazaarplusplus-installer/.prettierignore b/bazaarplusplus-installer/.prettierignore deleted file mode 100644 index 226d15d..0000000 --- a/bazaarplusplus-installer/.prettierignore +++ /dev/null @@ -1,2 +0,0 @@ -src/types/generated/ -src/__shell_snapshots__/ diff --git a/bazaarplusplus-installer/.prettierrc.json b/bazaarplusplus-installer/.prettierrc.json deleted file mode 100644 index 32ebab4..0000000 --- a/bazaarplusplus-installer/.prettierrc.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "none" -} diff --git a/bazaarplusplus-installer/AGENTS.md b/bazaarplusplus-installer/AGENTS.md deleted file mode 100644 index 701d9a5..0000000 --- a/bazaarplusplus-installer/AGENTS.md +++ /dev/null @@ -1,33 +0,0 @@ -# AGENTS.md - -The Tauri desktop installer. Repo-wide rules are in `../AGENTS.md`. - -Read `CONTEXT.md` first; it maps each task to its topic document. - -## Verification - -`just installer::check` runs the full source gate, tests included; `installer::test` after it only repeats them. Inside the loop, pick the narrower gate that matches what changed: - -- Documentation or these instructions: `npm run docs:check`. -- React or TypeScript: `npm run check:ts`; regenerate bindings with `npm run generate:bindings:if-stale` first when Rust signatures changed. Before committing, `just installer::check-fast` runs what the pre-commit hook runs (format, lint, types, cargo fmt, docs). -- `scripts/`: `npx vitest run .test.mjs` for the colocated test (they are Vitest files, not `node --test`), otherwise run the touched script. -- UI styling or tokens: read `../docs/design.md`; a token change also runs `just site::check` in the same change. -- Versioning, bundled resources, or Tauri config: `just release::check`, then `just installer::check` (its source prebuild step checks the product projections). Release packaging only: `npm run prebuild-check` also verifies the prepared Payload and fails until `just release::prepare ` has run. -- A platform bundle: `just release::build `. No other kind of task needs it. - -Tests prove a behavior seam, an observable outcome of the boundary under test, through its public interface; mock call order and exact source text are not behavior. - -Rewrite goldens (`src/__shell_snapshots__/`, `src-tauri/tests/goldens/`) under `BPP_UPDATE_GOLDENS=1` with `npx vitest run src/shell.snapshot.test.tsx` for the shell and `npm run generate:bindings:test` for Rust. A bare `cargo test` also needs `TAURI_CONFIG='{"bundle":{"resources":[]}}'`, the empty bundle `scripts/tauri-source-env.mjs` supplies. - -## Local workflow - -`just installer::dev` serves the frontend alone; anything touching a native command needs the full shell from `just installer::app`. - -## Stream service - -Stream HTTP handlers run every SQLite or filesystem access through `run_record_task` (`src-tauri/src/stream/http.rs`); `docs/stream-service.md` explains why. - -## Documentation - -- Re-verify every claim in a `docs/*.md` file you change; `npm run docs:check` checks only cited paths, links, and `CONTEXT.md` coverage, not prose. -- Keep generated audits and review artifacts under gitignored `tmp/`. diff --git a/bazaarplusplus-installer/CONTEXT.md b/bazaarplusplus-installer/CONTEXT.md deleted file mode 100644 index c4e60cd..0000000 --- a/bazaarplusplus-installer/CONTEXT.md +++ /dev/null @@ -1,40 +0,0 @@ -# BazaarPlusPlus Installer Context - -BazaarPlusPlus Installer is a Tauri 2 desktop app for installing and managing the BazaarPlusPlus mod for *The Bazaar*. React/Vite owns presentation and workflow state; Rust owns native integration, filesystem effects, local history access, the OBS overlay service, and packaging boundaries. - -## System Map - -- `src/` — frontend pages, framework-neutral workflows, localization, and generated-command adapters. -- `src-tauri/src/` — Tauri commands, installer services, history access, stream runtime, and platform integration. -- `scripts/` — generated bindings, resource validation and platform signing/packaging; product orchestration lives in the [workspace release flow](../docs/release.md). -- `src-tauri/resources/` — bundled mod payload inputs and stream web assets. - -## Vocabulary - -- **Payload**, **Payload Inventory**, **Release Manifest**, **Platform Release Manifest**, **Mainland Mirror** — product-wide terms defined in [the root glossary](../CONTEXT.md). -- **Selected game installation** — the session-scoped The Bazaar installation shared by Install, History, and Stream. -- **InstallState** — the native contract supplying detected paths, readiness, warnings, and action gates to the Install workflow. -- **History List** — the paginated view of local runs, with totals across the complete local history. Its selected page is distinct from the Run Detail view and from thumbnail availability. -- **History Thumbnail** — the cropped strip of a run's screenshot on a History List card, served under a process-local source bound to the installation the page was read from. Distinct from the OBS overlay's strip, which follows the captured stream installation. -- **Run Detail** — the view of one history run, its battles, screenshot, and recorded videos. -- **Data Root**, **Legacy Root** — defined in [the root glossary](../CONTEXT.md). The Install page lists and deletes Legacy Roots one at a time ([Install and reset](docs/install-reset.md#legacy-roots)). -- **V5 import** — the one-time copy of `BazaarPlusPlusV5/` history into the current Data Root as History-Only Runs, started from the Install page and followed by an offer to delete V5 ([Install and reset](docs/install-reset.md#v5-import), [History and storage](docs/history-storage.md#data-ownership)). -- **Reset local data** — explicit deletion of the current Data Root, distinct from uninstall, which preserves every Data Root. -- **Running-game refusal** — the fail-closed check that blocks an operation touching game-directory files while The Bazaar runs or cannot be confirmed closed; each operation has its own problem code. -- **Data maintenance lock** — the installer-wide lock that serializes History cleanup, Reset, BepInEx reset, and Legacy Root deletion; taken before the stream lifecycle gate. -- **Semantic problem** — a stable code plus parameters and an optional diagnostic; frontend copy derives from the code rather than native error text. -- **Stream runtime** — the serialized owner of the local overlay service lifecycle and captured installation state. -- **Generated bindings** — the TypeScript command client exported from Rust command signatures; generated files are replaceable artifacts. - -## Topics - -Each document states current behavior for one task branch. Open the one whose triggers match the task at hand. - -- [Architecture](docs/architecture.md) — runtime ownership, subsystem boundaries, selected-installation state, generated IPC bindings. -- [Frontend architecture](docs/frontend-architecture.md) — command adapters, async page state, modal coordination, confirmation lifecycles, localization boundaries. -- [Install and reset](docs/install-reset.md) — detection, payload ownership, install, repair, uninstall, reset, Legacy Roots, the V5 import, action gates, the macOS trampoline, Steam LaunchOptions, trampoline bundle signing, vanilla restoration. -- [History and storage](docs/history-storage.md) — SQLite access, run history, screenshots, video deletion, destructive cleanup. -- [Stream service](docs/stream-service.md) — service lifecycle, capability polling, overlay routes, settings, CORS. -- [Updater](docs/updater.md) — update checks, download and install phases, restart recovery, the mainland-China fallback. -- [Release](docs/release.md) — versions, bundled resources, native recorder inputs, platform packaging, artifact signing and notarization, manifests, upload, release verification. -- [Decisions](docs/adr/) — the rationale behind a boundary the task is about to challenge. diff --git a/bazaarplusplus-installer/LICENSE b/bazaarplusplus-installer/LICENSE deleted file mode 100644 index a549209..0000000 --- a/bazaarplusplus-installer/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2026 Xinyu YANG -Copyright (c) 2026 BazaarPlusPlus Team - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/bazaarplusplus-installer/README.md b/bazaarplusplus-installer/README.md deleted file mode 100644 index cdf3e7b..0000000 --- a/bazaarplusplus-installer/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# BazaarPlusPlus Installer - -Desktop app for installing and managing the **BazaarPlusPlus** mod for *The Bazaar*. - -What it does: - -- Detects the Steam installation of The Bazaar -- Installs BepInEx and the mod payload; supports repair and clean uninstall -- Launches the game through Steam -- Shows the mod's local run history (matches, screenshots, videos) -- Serves a local OBS overlay for streaming -- Keeps itself up to date via a built-in updater - -**Tech stack:** Tauri 2 (Rust backend) + React 19 / Vite / TypeScript (frontend). - -## Quick start - -Toolchain versions are pinned by `package.json` (`engines`, `packageManager`) and `rust-toolchain.toml`; workspace setup is in the [development guide](../docs/development.md). - -```bash -just installer::app # Full desktop app (checks the toolchain, installs dependencies if needed) -just installer::dev # Frontend only, in the browser -just installer::check -``` - -`just --list installer` and `package.json` list the narrower scripts. The TypeScript client for Tauri commands is **generated** from the Rust command signatures into `src/types/generated/`; `dev`, `build`, `test`, and `just installer::check` regenerate it, so edits go to the Rust signatures. - -## Release build - -Platform builds run through the workspace release commands (`just release::build `); the full flow, credentials, and platform facts are in the [workspace release docs](../docs/release.md) and [installer release guide](docs/release.md). `scripts/bundle.sh` runs only inside the product build lock that `release::build` holds. - -## Documentation - -**Start with [`CONTEXT.md`](CONTEXT.md)**: the vocabulary plus which topic doc to open for which kind of work. Decisions are in `docs/adr/`; [ADR-0007](docs/adr/0007-documentation-contract.md) defines this layout. Platform smoke-test gaps are GitHub issues labelled `manual-validation`. diff --git a/bazaarplusplus-installer/docs/adr/0001-in-app-updater.md b/bazaarplusplus-installer/docs/adr/0001-in-app-updater.md deleted file mode 100644 index 539f4ce..0000000 --- a/bazaarplusplus-installer/docs/adr/0001-in-app-updater.md +++ /dev/null @@ -1,21 +0,0 @@ -# In-App Updater - -## Context - -Users need a primary update path that preserves download, install, failure, and restart state inside the app. Mainland-China network conditions also justify a localized manual fallback without making every user leave the app. - -## Decision - -Use the Tauri updater as the primary flow. Keep one native update handle through download and install, present the lifecycle in the shell, and restart through the native process integration. Under the zh locale, an available update may also expose a versioned mainland-China mirror; automatic installation remains the primary action. - -The current state and presentation boundaries are specified in [Updater](../updater.md); artifact generation belongs to [Release](../release.md). - -## Rejected Alternatives - -- Send every user to an external download. That discards integrated progress, recovery, install, and restart state. -- Recreate the update between check and install. Download and install must use the native handle returned by the successful check. -- Make the regional mirror the default. It is a network fallback, not a second release authority. - -## Consequences - -Updater changes must preserve one coherent state machine and test the shell presentation as well as native integration. Release work must keep versions, updater artifacts, fragments, and signatures aligned. diff --git a/bazaarplusplus-installer/docs/adr/0002-macos-launch-trampoline.md b/bazaarplusplus-installer/docs/adr/0002-macos-launch-trampoline.md deleted file mode 100644 index bd68954..0000000 --- a/bazaarplusplus-installer/docs/adr/0002-macos-launch-trampoline.md +++ /dev/null @@ -1,23 +0,0 @@ -# macOS Launch Trampoline - -## Context - -Steam must launch The Bazaar's application bundle directly, while BepInEx needs Doorstop environment and JIT entitlements before Unity starts. Steam LaunchOptions are user-editable, account-scoped strings whose provenance cannot be classified safely. - -## Decision - -Use one in-bundle Mach-O trampoline on every supported macOS version. Preserve the Unity executable as `.orig`, install the bundled stub as the bundle executable, sign and verify the resulting bundle, and require the installed stub to have the same Mach-O build UUID as the current bundled stub. Code signing may change the file bytes without changing that build identity. - -Require empty The Bazaar LaunchOptions across every Steam account. Any non-empty direct value is dirty; unreadable configuration blocks mutation. Repair converges residue, payload, trampoline, and LaunchOptions to one final state. Current mechanics are specified in [Install And Reset](../install-reset.md). - -## Rejected Alternatives - -- Bootstrap through Steam LaunchOptions. Correctness would depend on Steam executing a mutable external command prefix. -- Support multiple bootstrap modes. That multiplies state, recovery, UI, and payload branches without a second supported product behavior. -- Preserve selected LaunchOptions fragments. Arbitrary user content has no reliable ownership boundary. -- Accept any structurally valid trampoline. Repair must converge to the exact stub shipped by the installer. -- Mutate when Steam configuration cannot be inspected. A partial install would make readiness unverifiable. - -## Consequences - -The UI exposes no compatibility mode. Steam Verify, game updates, manual LaunchOptions edits, and stub updates make readiness false and route the existing primary action to Repair. diff --git a/bazaarplusplus-installer/docs/adr/0003-steam-only-launch.md b/bazaarplusplus-installer/docs/adr/0003-steam-only-launch.md deleted file mode 100644 index 24c045f..0000000 --- a/bazaarplusplus-installer/docs/adr/0003-steam-only-launch.md +++ /dev/null @@ -1,19 +0,0 @@ -# Steam-Only Launch - -## Context - -The installer once supported the native Tempo Launcher through process capture, temporary payload removal, backup recovery, cancellation, and platform-specific relaunch logic. That path was large and fragile relative to its user segment, and Tempo support no longer matched product direction. - -## Decision - -Support Steam installations only. Detection resolves Steam copies, and launch opens the fixed Steam game entry. Keep no one-variant launch abstraction or dormant non-Steam detection path. Current behavior is specified in [Install And Reset](../install-reset.md). - -## Rejected Alternatives - -- Repair only the fragile parts of Tempo capture. The lifecycle itself was the maintenance burden. -- Keep a single-variant launch abstraction. It adds speculative state with no current branch. -- Detect Tempo but block launch. That preserves a half-supported installation path. - -## Consequences - -Native Tempo users are deliberately outside the supported product. Launch has no process-capture, backup, or cancellation surface, and downstream code may rely on a Steam installation layout. diff --git a/bazaarplusplus-installer/docs/adr/0004-tauri-specta-command-bindings.md b/bazaarplusplus-installer/docs/adr/0004-tauri-specta-command-bindings.md deleted file mode 100644 index 591c68b..0000000 --- a/bazaarplusplus-installer/docs/adr/0004-tauri-specta-command-bindings.md +++ /dev/null @@ -1,22 +0,0 @@ -# Generate Tauri Command Bindings With tauri-specta - -## Context - -The IPC contract was once repeated across Rust signatures, DTO exports, a command-name artifact, and a handwritten TypeScript map. Command payloads could drift even when the name list remained complete. - -## Decision - -Make Rust Tauri commands the only IPC schema. One Specta builder registers the production invoke handler and exports typed DTOs plus command functions. The native frontend and Browser Preview implement the generated interface at one adapter boundary. - -Generation is mandatory for complete check, test, build, and prebuild validation, and for the native source gate. The frontend source subset consumes committed bindings without invoking Rust. It proves that the frontend accepts that contract, not that the contract matches Rust. Any binding or native input change selects the frontend and both native platforms; only a real export followed by a generated-file diff establishes freshness. Checkout timestamps or a clean Git status alone cannot establish it. A failed generation preserves the previous artifact and fails the invoking command. Current ownership and generation mechanics are specified in [Architecture](../architecture.md). - -## Rejected Alternatives - -- Keep a second DTO generator as fallback. Two schemas recreate drift. -- Keep a command-name artifact or handwritten command map. Names cannot verify payload or result shapes. -- Generate DTOs but invoke string commands manually. Command names and payload construction would still be duplicated. -- Branch Preview behavior inside features. Runtime selection belongs at the adapter boundary. - -## Consequences - -The compatible Specta packages are upgraded deliberately as one set. Generated bindings are replaceable and never hand-edited; every IPC DTO and command must satisfy the generator's metadata requirements. diff --git a/bazaarplusplus-installer/docs/adr/0005-data-ownership-and-reset.md b/bazaarplusplus-installer/docs/adr/0005-data-ownership-and-reset.md deleted file mode 100644 index 6babfc4..0000000 --- a/bazaarplusplus-installer/docs/adr/0005-data-ownership-and-reset.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -superseded-by: 0008-legacy-data-roots-and-v5-import.md ---- - -# Data Ownership And Reset - -## Context - -BazaarPlusPlus V5 writes a new data contract under `BazaarPlusPlusV5/`. Existing `BazaarPlusPlusV4/` data may contain history, screenshots, or other user artifacts from earlier mod releases. V5 also introduces `BundleOutbox/` and the `bundle_outbox` table as the mod's durable upload queue. - -Resetting BazaarPlusPlus data is destructive but distinct from uninstalling the mod. The product needs an explicit target, honest action availability, and a result that distinguishes deletion from an already-empty target. - -## Decision - -Legacy `BazaarPlusPlusV4/` data remains owned by the user. The installer does not read, delete, migrate, or prompt about it. Installer Reset targets only the current V5 data root. - -`BundleOutbox/` and `bundle_outbox` remain exclusively mod-managed. The installer does not delete outbox files or rows and does not include their bytes in cleanup estimates. - -Deletion stays in the native backend. Reset availability is exposed through install state, requires an acknowledged confirmation, blocks dismissal while native work is running, and returns a typed result with the refreshed install state. - -Current reset and cleanup behavior is specified in [Install And Reset](../install-reset.md) and [History And Storage](../history-storage.md). - -## Rejected Alternatives - -- Extend Reset to clean `BazaarPlusPlusV4/`. This would silently broaden a current-data reset into deletion of user-owned legacy artifacts. -- Let installer cleanup reclaim the bundle outbox. That would duplicate the mod's queue lifecycle and could remove upload inputs while the mod still owns their retry or retention state. -- Keep reset always enabled. Availability must reflect the detected target and current operation gates. -- Delete from the frontend. Native code owns service exclusion, running-game refusal, filesystem effects, and error classification. -- Return generic success text. Callers need structured removed-versus-empty state and stable failure semantics. - -## Consequences - -V4 data can remain on disk until the user removes it independently. The installer does not advertise or automate that removal. - -Outbox retention and reclamation changes must be implemented by the mod. Installer cleanup may use outbox row status to decide whether run-owned source data is still needed, but it never mutates the outbox itself. - -Future reset work must preserve backend-owned deletion and keep empty, blocked, partial-failure, and successful removal states distinct. Uninstall continues to preserve user data. diff --git a/bazaarplusplus-installer/docs/adr/0006-native-replay-recorder-signing.md b/bazaarplusplus-installer/docs/adr/0006-native-replay-recorder-signing.md deleted file mode 100644 index f4e03df..0000000 --- a/bazaarplusplus-installer/docs/adr/0006-native-replay-recorder-signing.md +++ /dev/null @@ -1,29 +0,0 @@ -# Installer Owns Native Replay Recorder Release Artifacts - -## Context - -Combat Replay records in-process through platform-native Unity plugins. The installer must preload those artifacts at platform-specific locations and establish one release-signing authority. - -## Decision - -- The mod project owns native recorder source and builds. -- The mod catalog defines each platform's native/build/ABI inputs, required exports, policy, temporary build-output layout, and installer destination. -- The installer manifest records a canonical content digest over the selected platform's declared mod worktree inputs and exact hashes/tree shape of the promoted artifacts. Git commit and dirty state are provenance only. -- The mod's `publish` command asks the installer-owned coordinator to reuse a fresh current-platform input or locally build, verify, and transactionally promote it before managed packaging. Managed installer-source synchronization and archive preparation are restricted to that same platform. Promotion requires no remote qualification or attestation service. -- macOS inputs arrive ad hoc signed; the installer signs nested code and bundles with the official release identity before outer notarization. -- Windows producer inputs remain unsigned and use the same local freshness/build/promotion model. -- Platform payloads contain only the native recorder artifacts, not an external encoder fallback. - -Current input validation, staging, signing, and packaging are specified in [Release](../release.md). - -## Rejected Alternatives - -- Keep a process-based encoder fallback. It preserves the high-copy path and adds a runtime executable. -- Silently fall back to software encoding. That hides a performance and capability regression. -- Store officially signed inputs in the producer project. Release signing remains the installer's responsibility. -- Gate local promotion on a separate oldest-OS runner or authenticated remote attestation. The fixed deployment target, compiler availability diagnostics, binary metadata/import/export/dependency checks, local load/smoke checks, and signing checks are the producer boundary. -- Install render plugins as ordinary managed plugins. Unity must preload them before managed startup. - -## Consequences - -Every declared native source, build recipe, ABI/header/managed interop declaration, or output policy change invalidates the relevant platform digest. The next publish on that platform rebuilds and promotes locally; unrelated commits do not. Native availability and installer prebuild fail closed on manifest or artifact drift, and upgrade cleanup retains retired names only as tombstones rather than release inputs. diff --git a/bazaarplusplus-installer/docs/adr/0007-documentation-contract.md b/bazaarplusplus-installer/docs/adr/0007-documentation-contract.md deleted file mode 100644 index 2aa44ae..0000000 --- a/bazaarplusplus-installer/docs/adr/0007-documentation-contract.md +++ /dev/null @@ -1,34 +0,0 @@ -# Documentation Contract - -## Context - -Current behavior, future work, historical material, and architectural rationale once appeared as peers. Agents had to read documents before knowing whether their claims were authoritative. A separate index also cached status already owned by document frontmatter. - -The first topic layout solved that ambiguity but placed every current document under an extra `truth/` namespace. With a small topic set, that directory added navigation without adding a lifecycle distinction: current topics can be the default at `docs/*.md`, while decisions, plans, and history remain explicit subdirectories. - -That layout originally shipped with a per-document `last-verified` commit stamp, refreshed whenever a claim was re-checked. The stamp is retired; the layout is not. - -## Decision - -Use one entry map and path-based lifecycle boundaries: `CONTEXT.md` is the task-triggered topic map, current behavior is the default at `docs/*.md`, and decisions live in `docs/adr/`. ADRs own rationale and consequences rather than mirroring the current implementation. Since the monorepo merge, plans are GitHub issues and retired material lives in git history, per the repo-wide policy in `../AGENTS.md`; `docs/plans/` and `docs/archive/` are no longer used. - -Current documents carry no frontmatter. Location states lifecycle, and `superseded-by` is the one key worth writing — it points a replaced decision or plan at its replacement. - -The operational rules (claim ownership, symbol-level citation form, re-verification on change) are owned by the always-loaded `AGENTS.md` files. This record does not restate them. - -`npm run docs:check` proves three things and nothing more: every root-relative path cited in backticks resolves to a file, every relative Markdown link resolves, and `CONTEXT.md` links every `docs/*.md` topic. Each catches real staleness from the tree alone, with no bookkeeping to keep in sync. Prose being true is not mechanically checkable and is not claimed. - -## Rejected Alternatives - -- Keep `docs/truth/`. The current root already has an unambiguous meaning because every other lifecycle has a named subdirectory. -- Add `docs/INDEX.md`. It would compete with `CONTEXT.md` and cache metadata owned elsewhere. -- Put all current behavior in `CONTEXT.md`. Always-loaded detail raises context cost and weakens topic triggers. -- Duplicate the operational rules here. Two authoritative statements of one rule drift; `AGENTS.md` is the single always-loaded owner. -- Archive pruned current documentation. Git retains deleted mechanics without presenting stale claims as current search results. -- Replace symbols with line ranges. Unrelated insertions can silently retarget an otherwise valid range, and the guard against that — checking cited line numbers against each file's length — never fired, because zero line citations were ever written. -- Keep the `last-verified` commit stamp and its reachability check. It taxed every code pull request with a hash refresh, forced merge commits so a branch-local stamp stayed reachable, and still proved nothing about the prose: a stamp says only that someone claimed to have looked. It also failed on its own terms — at commit `7e49fc8` on `master`, `docs/install-reset.md` carried a stamp that a squash had already made unreachable, so `npm run docs:check` reported a red tree over pure bookkeeping while every claim in the document was accurate. -- Require `status` and `topic` frontmatter on current documents. `status: current` was constant, `topic` restated the filename, and topic uniqueness was machinery guarding a property no reader consults. - -## Consequences - -Agents start with `CONTEXT.md`, open only the topic whose trigger matches the task, and consult an ADR only when its decision is in question. Re-verifying a changed document is a judgment call the author records in the pull request rather than a value stored in the file, so a documentation update costs one edit and a code pull request costs none. Historical mechanics are recovered from Git when explicitly needed. diff --git a/bazaarplusplus-installer/docs/adr/0008-legacy-data-roots-and-v5-import.md b/bazaarplusplus-installer/docs/adr/0008-legacy-data-roots-and-v5-import.md deleted file mode 100644 index 50b7f5f..0000000 --- a/bazaarplusplus-installer/docs/adr/0008-legacy-data-roots-and-v5-import.md +++ /dev/null @@ -1,25 +0,0 @@ -# Legacy Data Roots And V5 Import - -## Context - -Root [ADR-0006](../../../docs/adr/0006-v6-data-root.md) moves the mod to `BazaarPlusPlusV6/` and makes the installer responsible for importing V5 history once. Game directories can therefore hold several Data Roots: the current one and Legacy Roots (`BazaarPlusPlus/`, `BazaarPlusPlusV4/`, `BazaarPlusPlusV5/`). ADR-0005 covered only one current root and one ignored V4 root. - -## Decision - -- Reset, History, cleanup, and the OBS overlay read and write only the current Data Root (`BAZAAR_DATA_DIRECTORY`). Reset never touches a Legacy Root. Uninstall preserves every Data Root. -- Legacy Roots are user-owned. The installer lists those present in the selected game directory with their size, and deletes one only after the user confirms that root. Deletion runs in the native backend through the same path as Reset and returns a typed result. Nothing deletes a Legacy Root automatically, including a successful import. -- Every destructive data operation (Reset, BepInEx reset, Legacy Root deletion, V5 import) refuses while the game is running, using a fail-closed check. A check that cannot tell is a refusal. -- `BundleOutbox/` and `bundle_outbox` remain mod-owned: cleanup may read upload status but never deletes outbox files or rows. -- The V5 import is a one-time installer feature with a fixed home, `src-tauri/src/v5_import/`, deleted before 6.2.0; `release::check` refuses a 6.2.0 version while it exists. It writes only History-Only Runs, never queues an upload, and records completion in a marker inside `BazaarPlusPlusV5/`, so a V6 Reset does not trigger a second import and deleting V5 removes the marker with it. Its inputs, filters, and file placement are implementation detail of that module. - -## Rejected Alternatives - -- Extend Reset to Legacy Roots. Reset targets current data; widening it silently deletes user-owned history. -- Delete `BazaarPlusPlusV5/` right after import. A wrong import mapping would destroy the user's only copy. -- Keep the import marker in installer state or in the V6 root. Installer reinstalls and Steam library moves lose the former; a V6 Reset would erase the latter and re-import data the user already cleaned up. -- Let installer cleanup reclaim the bundle outbox. That duplicates the mod's queue lifecycle. -- Delete from the frontend, or return generic success text. Native code owns running-game refusal and filesystem effects, and callers need removed, empty, blocked, and partial-failure states kept distinct. - -## Consequences - -Legacy Roots stay on disk until the user removes them. When import places files by hard link or clone, deleting V5 may reclaim far less space than its listed size, so the UI does not promise a figure. Current Reset and Legacy Root behavior is specified in [Install And Reset](../install-reset.md) and [History And Storage](../history-storage.md). diff --git a/bazaarplusplus-installer/docs/architecture.md b/bazaarplusplus-installer/docs/architecture.md deleted file mode 100644 index ead8db2..0000000 --- a/bazaarplusplus-installer/docs/architecture.md +++ /dev/null @@ -1,24 +0,0 @@ -# Architecture - -## Runtime Ownership - -- The `run` function in `src-tauri/src/lib.rs` is the composition root for native plugins, managed state, the command handler, tray setup, startup warm-up, and platform window events. -- `main_window::restore` in `src-tauri/src/main_window.rs` is the shared restore path for tray activation, second-instance activation, and macOS reopen. Close handling consults `StreamRuntime::snapshot` before deciding whether the main window hides to the tray. -- `SelectedGameInstallationState` in `src-tauri/src/services/selected_game_installation.rs` is process-wide but session-scoped. Install, History, and Stream resolve through it; app restart recreates it empty. `resolve_game_path_core` in `src-tauri/src/services/game_path.rs` owns explicit, selected, startup-detected, then fallback priority. -- `InstallerContextState::get_or_initialize` in `src-tauri/src/services/startup.rs` is the shared cold-start boundary for install detection. Startup warm-up and `detect_for_install` await the same initializer. - -## Feature Boundaries - -- Install effects belong to the Rust `install` service under `src-tauri/src/services/install/`; frontend orchestration belongs to `DefaultInstallWorkflow` in `src/features/install/installWorkflow.ts`. `plan_install` in `src-tauri/src/services/install/plan.rs` derives effects directly from fresh detection facts; `install_state_from_snapshot` in `src-tauri/src/services/install/mod.rs` derives readiness from an empty plan, keeping presentation and execution on the same rule. -- `History` in `src-tauri/src/services/history.rs` owns history paths, SQLite access, reveals, video deletion, and cleanup. Tauri commands pass domain ids and presets rather than storage paths. -- `createHistoryListWorkflow` in `src/features/history/historyListWorkflow.ts` owns History List page identity, loading, pagination correction and process-recovery completion. The React hook binds the route and subscription; list requests and History Thumbnail preparation retain independent acceptance gates. Cleanup confirmations and Run Detail remain separate owners. -- `createRunDetailWorkflow` in `src/features/history/runDetailWorkflow.ts` owns Run Detail loading, action exclusion, target failures, and detail replacement after video deletion. The current operation token rejects late results after a newer load or a stopped lifecycle; `useRunDetailPage` in `src/features/history/useRunDetailPage.ts` binds the workflow to the current run and React subscription. Deletion confirmation retains its separate target and retry owner. -- `StreamRuntime` in `src-tauri/src/stream/runtime.rs` is the only lifecycle-mutation boundary for the local overlay service. History Thumbnails in `src-tauri/src/stream/history_thumbnails/mod.rs` are served by that service but own their source registry, URLs, route, and cache; `History` reaches them through managed `HistoryThumbnails` state, never through the runtime. -- Updater phase state belongs to `createUpdaterMachine` in `src/features/about/updater.ts`; modal metadata is derived by `getUpdaterUiContract` in `src/features/about/updaterPresentation.ts`. -- Install, History, and Stream native failures cross IPC as `SemanticProblem` from `src-tauri/src/problem.rs`. Each domain owns its stable codes and parameters; diagnostics remain separate from localized user copy. - -## Generated IPC - -Rust command signatures are the only IPC schema. `builder` in `src-tauri/src/commands/registry.rs` supplies both the production invoke handler and the binding export command list. `runGenerateBindings` in `scripts/generate-bindings.mjs` validates a temporary export before atomically replacing `src/types/generated/commands.ts`. Its `--if-stale` flag, used by `npm run dev` and the explicit `npm run generate:bindings:if-stale` fast path, skips the cargo export when the committed `commands.ts` is newer than every Rust input; `build`, `test`, `prebuild-check`, and complete or native `verify` always regenerate. The frontend `verify` subset consumes the committed export and checks its TypeScript consumers without Rust; `classifyChanges` in `../.github/scripts/checks-scope.mjs` selects native verification for binding inputs and generated-file changes. - -`CommandAdapter` in `src/api/commandAdapter.ts` is that schema's TypeScript face; `commandClient` in `src/api/commandClient.ts` picks one implementation at module load — generated native commands or the Browser Preview adapter. Feature modules depend on the typed interface rather than command strings. The rationale and upgrade constraint live in [ADR-0004](adr/0004-tauri-specta-command-bindings.md). diff --git a/bazaarplusplus-installer/docs/frontend-architecture.md b/bazaarplusplus-installer/docs/frontend-architecture.md deleted file mode 100644 index 34463cd..0000000 --- a/bazaarplusplus-installer/docs/frontend-architecture.md +++ /dev/null @@ -1,25 +0,0 @@ -# Frontend Architecture - -## Native Boundary - -- `commandClient` in `src/api/commandClient.ts` selects the generated native adapter or Browser Preview once at module load. Feature hooks and workflows use `commandClient` directly; a workflow names the `CommandAdapter` methods it needs with `Pick` rather than invoking Tauri command strings. -- `normalizeBackendError` in `src/api/nativeCommands.ts` preserves a valid `SemanticProblem` as structured code, parameters, and optional diagnostic. Presenters map that structure to localized copy; diagnostics are never the primary message. -- Preview defaults live in `src/api/previewDefaults.ts` and are reused by `createPreviewCommands` in `src/api/previewCommands.ts`, keeping browser-preview behavior at the adapter boundary. - -## Workflow State - -- `PageRefreshState` in `src/features/shared/pageState.ts` is the refresh-outcome vocabulary shared by History List and Run Detail. Each workflow owns its loading state and request acceptance. -- `createHistoryListWorkflow` in `src/features/history/historyListWorkflow.ts` owns the History List's current page, reads, range and action availability, out-of-range correction, and single-flight process recovery. Request identity rejects superseded reads; recovery completion refreshes the current page. History Thumbnail preparation has independent request identity and state (`pending`, `ready`, `unavailable`) and cannot fail the list; rows carry absolute thumbnail URLs built natively. `useHistoryPage` binds routing and subscription; disposal invalidates all pending publications and follow-up refreshes. -- `DefaultInstallWorkflow` in `src/features/install/installWorkflow.ts` owns the authoritative install snapshot, action single-flight, target-bearing confirmations, retry parameters, and primary-action derivation. -- `DefaultStreamWorkflow` in `src/features/stream/streamWorkflow.ts` owns service freshness, window, crop, and one-off capability states. React hooks create workflows once and bind lifecycle plus subscription rather than duplicating orchestration. -- About bootstrap uses the separate `AppBootstrapSnapshot` in `src/features/about/appBootstrap.ts` because packaged fallback data can remain usable while native provenance fails. - -## Confirmations And Modals - -- `createConfirmedOperationController` in `src/features/shared/confirmedOperation.ts` retains the target through confirmation, running, and failure; native work blocks dismissal; failure keeps retry state; success closes the operation. -- `createModalCoordinator` in `src/features/shared/modalCoordinator.ts` renders one registered dialog, orders sources by priority and FIFO, tolerates route-source unmount, and restores focus after the queue drains. -- `ConfirmDialog` in `src/components/ui/ConfirmDialog.tsx` consumes an explicit dismissal policy. Callers must represent whether work is blocked, detachable, or genuinely cancelable instead of presenting a cosmetic cancel action. - -## Locale Boundary - -The `zh` catalog and `MessageKey` type in `src/i18n/messages.ts` define the message-key set; `en` is typed against it. Workflow state stores semantic values, while translation happens during presentation so changing locale does not recreate native workflows. Updater-specific presentation belongs to [Updater](updater.md). diff --git a/bazaarplusplus-installer/docs/history-storage.md b/bazaarplusplus-installer/docs/history-storage.md deleted file mode 100644 index fc97269..0000000 --- a/bazaarplusplus-installer/docs/history-storage.md +++ /dev/null @@ -1,41 +0,0 @@ -# History And Storage - -## History Boundary - -- `History` in `src-tauri/src/services/history.rs` resolves the selected installation and privately derives database, screenshot, and video paths. It owns list, detail, reveal, video deletion, cleanup preview, and cleanup execution. -- Commands in `src-tauri/src/commands/history.rs` pass ids, limits, offsets, cleanup scopes, and presets. They do not accept storage paths, cutoffs, or precomputed cleanup plans. -- The mod stores every instant as Unix milliseconds in `*_at_ms` columns, with a screenshot's local offset in `captured_utc_offset_minutes`. Queries filter and order on those integers; `src-tauri/src/history/instant.rs` turns them into RFC 3339 text at the column boundary, so History DTOs and overlay records keep their text fields. The overlay's `from` bound is converted to milliseconds, and a `from` that is not RFC 3339 matches no record. -- An absent run detail is a successful nullable result. Unavailable installation, unsupported schema, failed reads, and failed actions remain distinct `SemanticProblem` codes. -- `open_probed` in `src-tauri/src/history/queries.rs` opens the mod database with read/write flags and a busy timeout so SQLite can recover a dirty WAL or create shared-memory files. It probes `user_version`, retries selected transient errors, and rejects unsupported schemas without retry. The supported versions are owned by `src-tauri/history-database-compatibility.json`. The mod bumps `user_version` only for a column change, never for a data repair (mod ADR-0011), and `just release::check` fails unless the mod's version is the newest one listed. Tests read the list through `supported_mod_db_user_versions` in `src-tauri/src/config.rs` instead of restating it. - -## Cleanup Safety - -- `History::preview_cleanup` and `History::execute_cleanup` derive cutoffs from the same `StorageCleanupPreset` contract in `src-tauri/src/history/cleanup.rs`. -- `execute_storage_cleanup` runs while holding the data maintenance lock ([Install And Reset](install-reset.md#data-maintenance-lock)): a cleanup started during a Reset waits for it and resolves the installation only after the Reset finished. -- `PROTECTED_RUN_PREDICATE` in `src-tauri/src/history/cleanup.rs` protects the source data of runs the mod may still seal. A History-Only Run (`runs.upload_policy = 'history_only'`) is never protected, whatever its status or upload state. The mod owns that rule (`BundleQueueStore.SealEligibleRunCondition`), and the expected protection for each run, outbox, and seal-job state is a case in the mod fixture `../bazaarplusplus-mod/tests/BundleQueueSqliteStore.Tests/fixtures/bundle-seal-eligibility.json`; the cleanup test `run_plan_protects_exactly_the_shared_seal_eligibility_cases` evaluates every case, so the predicate cannot drift from the mod silently. Unprotected runs may be cleaned up, so a later mod recovery cannot assume their source data remains. The same predicate drives planning, skipped counts, screenshot protection, and guarded execution. -- Screenshot cleanup commits eligible row deletions before unlinking files and protects today's local-date folder from the orphan sweep. -- Run-data cleanup validates the required cascade foreign keys before destructive effects. Each planned run is conditionally deleted in a transaction. After all Run deletions, including later chunks, it removes planned video metadata only when the video's current battle no longer belongs to a surviving Run. This also examines videos originally planned under a Run whose guarded delete missed: their battle may now belong to a different, deleted Run. A detached battle or a missing battle does not leave a planned video protected without a Run owner. -- Both paths use `CleanupSession::delete_unreferenced_files` in `src-tauri/src/history/cleanup.rs`. Plans nominate files and estimate bytes; execution reads current references after committing row deletions. A surviving row preserves its file, including a reference published after planning or a planned orphan that has since acquired a row. Screenshot paths, video paths, and replay payloads use this same deletion rule. -- `resolve_cleanup_file_path` in `src-tauri/src/history/files.rs` confines cleanup paths to their expected roots. - -### Cleanup concurrency - -`CleanupSession::open` in `src-tauri/src/history/cleanup.rs` acquires a SQLite exclusive connection lock, then uses `SystemGameProcessProbe` in `src-tauri/src/services/game_process.rs` to confirm the game is closed. A running game or failed process inspection refuses cleanup before any row or file deletion, through the existing `HistoryActionFailed` surface. The connection remains exclusively locked across every row commit, reference scan, unlink, and empty-directory removal, and releases the lock when the session ends. This uses SQLite's [connection locking mode](https://www.sqlite.org/pragma.html#pragma_locking_mode) as well as an exclusive transaction: a transaction alone would release exclusion at commit. Readers may be blocked during execution; preview remains an ordinary read. The confirmation copy tells users to keep the game closed until cleanup finishes: a launch during cleanup can time out in mod initialization and require a relaunch. - -Both parts are necessary because screenshot publication writes the PNG before its database row (`ScreenshotService.BeginCaptureCurrentFrame` in `../bazaarplusplus-mod/src/BazaarPlusPlus/Game/Screenshots/ScreenshotService.cs`, followed by `EndOfRunArtifactPersistence.PersistAsync` in `../bazaarplusplus-mod/src/BazaarPlusPlus/Game/Screenshots/EndOfRunArtifactPersistence.cs`). A file can therefore be awaiting its first reference, including across local midnight, and the timestamp/run-based `ScreenshotPathBuilder.BuildRelativePath` in `../bazaarplusplus-mod/src/BazaarPlusPlus/Game/Screenshots/ScreenshotPathBuilder.cs` does not guarantee unique paths. A database lock alone cannot stop an already-running capture. - -A game started after the process check is held at initialization: `BppComposition` in `../bazaarplusplus-mod/src/BazaarPlusPlus/BppComposition.cs` constructs `EndOfRunCaptureWorkflow`, which constructs the screenshot store before `Plugin.Awake` in `../bazaarplusplus-mod/src/BazaarPlusPlus/Plugin.cs` installs patches or starts replay and video writers. `SqliteStoreBase` in `../bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteStoreBase.cs` always calls `RunLogSchema.EnsureInitialized` in `../bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs`, which requires a write transaction. That transaction cannot pass while cleanup owns the connection lock. `PvpBattleSqliteStore.Save` in `../bazaarplusplus-mod/src/BazaarPlusPlus/Game/PvpBattles/Persistence/PvpBattleSqliteStore.cs` can update a battle's run attachment, while `CombatReplayVideoMetadataStore` in `../bazaarplusplus-mod/src/BazaarPlusPlus/Game/CombatReplay/Video/CombatReplayVideoMetadataStore.cs` can publish video references; their surviving rows are checked alongside screenshot references. Screenshot attachment is direct and immutable in the current writers: `RunScreenshotSqliteStore.Save` in `../bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunScreenshot/RunScreenshotSqliteStore.cs` only inserts rows, so planned screenshot metadata is removed with its deleted Run. This startup ordering and the fail-closed process probe are part of the cleanup concurrency contract; moving a writer ahead of store initialization must preserve equivalent exclusion. SQLite and filesystem deletion are not one transaction: a failure can leave committed row deletions and undeleted files, but must not roll back rows into references to files already removed. - -## Data Ownership - -The current root name comes from `BAZAAR_DATA_DIRECTORY` in `src-tauri/src/config.rs`. Reset may delete that current root; uninstall does not. History, cleanup, and the OBS overlay never read a Legacy Root; the Install page lists and deletes them ([Install And Reset](install-reset.md#legacy-roots)). `BundleOutbox/` and `bundle_outbox` remain mod-owned: installer cleanup may consult upload status but never deletes their files or rows. [ADR-0008](adr/0008-legacy-data-roots-and-v5-import.md) records that ownership boundary. - -Runs the V5 import ([Install And Reset](install-reset.md#v5-import)) writes are History-Only: they never become seal candidates, so cleanup never protects them and the mod never resumes them, and an unfinished V5 Run arrives closed as `abandoned`. The import keeps a replay payload only where the installed mod's retention would, ranking imported payloads together with those the current Data Root already holds by the `replayPayloadRetainedNewestCount` and `replayPayloadRetainedAgeDays` fields of its `BazaarPlusPlus.history-database.json`; the other imported battles arrive with `local_payload_state = 'evicted'` and no file. After that the mod's replay maintenance treats the kept payloads like its own. While History has no current database but V5 history exists, `useHistoryUnavailableGuidance` in `src/features/history/useHistoryUnavailableGuidance.ts` turns the unavailable banner into a link to the Install page's import card, or to its reinstall hint while the installed mod still writes an old Data Root. - -Frontend History List and Run Detail each own their loading lifecycle; cleanup and deletion retain the confirmed-operation seam described in [Frontend Architecture](frontend-architecture.md). History Thumbnail preparation is independent of list reads. `createHistoryListWorkflow` requests `prepare_history_thumbnails` on entry, refresh, page changes, and window resume, and tracks `pending`, `ready`, or `unavailable`; `thumbnailUrl` exposes a row's `thumbnail_url` only while `ready`. A later request keeps the current state until preparation settles, including while maintenance holds the lifecycle gate, so a refresh neither remounts nor refetches loaded thumbnails; a failed preparation makes them `unavailable`, and results of superseded requests are ignored. Preparation or image failures use the card's ordinary thumbnail fallback without blocking the list, and a card whose image failed retries it after the next applied preparation. The `prepare_history_thumbnails` command in `src-tauri/src/commands/stream.rs` reports a service start failure, such as an occupied port, as `HistoryThumbnailsUnavailable` with the bind error as its diagnostic. While the last applied preparation failed with that problem, the workflow sets `thumbnailsUnavailable` and `History` in `src/pages/History.tsx` shows a non-blocking status notice above a non-empty list, without an action; the next successful preparation clears it. Other preparation failures show only the card fallback. Browser Preview has no image service, so its stub always reports that problem. - -`History::list_runs_for_page` registers the installation path used for its query with `HistoryThumbnails::register` in `src-tauri/src/stream/history_thumbnails/mod.rs` and builds each row's absolute `thumbnail_url` with `history_thumbnails::url`, the only thumbnail URL builder. The URL carries an opaque process-local source, so an existing page cannot be rebound to a different installation when the selected directory gains a database. Sources are deduplicated by path and retained until the installer exits; the database behind a source is resolved on each image request. Listing never touches the stream lifecycle. The thumbnail lookup takes the screenshot the list selected whatever its capture source; the OBS overlay's strip routes still show only end-of-run captures. The route, cache namespace, and cache sweep are described in [Stream Service](stream-service.md). - -`StreamRuntime::prepare_history_thumbnails` starts a stopped service through the lifecycle gate and preserves an already-running OBS session, including its directory and display window; a start failure stays visible in the stream status. A later History entry or window resume therefore starts it again after a tray stop or completed Reset. Maintenance still excludes startup. `observeHistoryWindowResume` listens to native window focus while the page is mounted, falling back to browser focus and visibility events outside Tauri or when native registration fails, and refreshes both rows and thumbnails. The Windows close control uses a plain hide-to-tray label on History routes. - -`list_history_runs` in `src-tauri/src/history/repo.rs` returns a page of runs with a summary across the full database. The displayed ten-win rate counts completed runs with at least ten victories, independently of the mod's outcome tiers. `createHistoryListWorkflow` in `src/features/history/historyListWorkflow.ts` corrects an out-of-range page before publishing rows, and `useHistoryPage` in `src/features/history/useHistoryPage.ts` binds that selection to the URL. `useRouteScroll` in `src/layouts/useRouteScroll.ts` restores the matching list position on return from details, including when the rows load asynchronously; primary navigation starts at the top. diff --git a/bazaarplusplus-installer/docs/install-reset.md b/bazaarplusplus-installer/docs/install-reset.md deleted file mode 100644 index c27c1c6..0000000 --- a/bazaarplusplus-installer/docs/install-reset.md +++ /dev/null @@ -1,113 +0,0 @@ -# Install And Reset - -## State And Planning - -- `InstallState` in `src-tauri/src/services/install/types.rs` is the native/frontend contract for selected paths, game and mod readiness, warnings, resettable data, and action gates. -- `install_state_from_snapshot` in `src-tauri/src/services/install/mod.rs` derives the contract from one `InstallEnvironmentSnapshot`; `detect_for_install` in `src-tauri/src/services/detect/mod.rs` refreshes platform bootstrap facts on every detection. -- `DefaultInstallWorkflow` in `src/features/install/installWorkflow.ts` owns stale-response rejection, single-flight operations, fixed confirmation targets, retry, and the one primary action. An installed but non-ready state routes to Repair. -- Warnings and failures cross the boundary as stable codes and parameters. `presentInstallWarning`, `presentInstallProblem`, and `presentInstallNotice` in `src/features/install/installProblems.ts` own localized presentation. - -## Install And Uninstall - -- `plan_install` in `src-tauri/src/services/install/plan.rs` computes effects; `execute_and_refresh` in `src-tauri/src/services/install/operation.rs` stops on the first failed effect and returns a freshly detected final state. -- `prepare_install_target` in `src-tauri/src/services/bepinex/payload.rs` removes only BPP-owned files absent from the incoming payload and preserves BPP configuration. `extract_zip` in `src-tauri/src/services/bepinex/zip_archive.rs` skips byte-identical files and replaces differing files. -- `BPP_PRIVATE_RELATIVE_PATHS` and `BPP_BUNDLED_DEPENDENCY_RELATIVE_PATHS` in `src-tauri/src/services/bepinex/payload.rs` define payload ownership. -- `uninstall_bpp` in `src-tauri/src/services/bepinex/mod.rs` always removes private BPP files. It removes shared BepInEx and platform bootstrap state only when no third-party plugin or patcher remains. Uninstall preserves the BPP data root. - -On macOS, `plan_install` keeps Steam running when detected launch options are empty; only non-empty launch options add Steam shutdown and cleanup. `ensure_game_stopped` checks the selected game process before install effects and again before trampoline replacement. - -## Running-Game Refusal - -`ensure_game_stopped` in `src-tauri/src/services/game_process.rs` is the fail-closed check every operation that rewrites or deletes game-directory files runs first: install, Reset, BepInEx reset, Legacy Root deletion, and the V5 import. It refuses when the game is running and when the process list cannot be inspected. Each `GameStoppedOperation` reports its own semantic problem code (`install_blocked_by_game`, `reset_blocked_by_game`, and so on); an inspection failure carries its cause as the diagnostic. `SystemGameProcessProbe` matches `TheBazaar.exe` on Windows and, on macOS, an executable under the selected installation's `TheBazaar.app/Contents/MacOS/`, including the trampoline's `.orig`. The game has no build for other platforms, where the probe reports it stopped. Tests inject a `GameProcessProbe` instead. - -## Data Maintenance Lock - -`DataMaintenanceLock` in `src-tauri/src/services/data_maintenance.rs` serializes the installer's data-mutating operations: History cleanup, Reset, BepInEx reset, and Legacy Root deletion wait for one another rather than interleave. Reset also stops the OBS overlay through `StreamRuntime::exclusive_maintenance`; it always takes the data maintenance lock first and the stream lifecycle gate second, and nothing holding the lifecycle gate waits for the data lock, so the two cannot deadlock. - -## Steam Launch Boundary - -The installer launches The Bazaar through `launch_game_via_steam` in `src-tauri/src/services/install/mod.rs`, which opens the fixed Steam game URL. Detection resolves Steam installations through `detect_installation_paths` in `src-tauri/src/services/detect/steam.rs`; there is no alternate launch-mode state. The Steam-only product boundary lives in [ADR-0003](adr/0003-steam-only-launch.md). - -## macOS Trampoline Invariant - -- `install_trampoline` in `src-tauri/src/services/bepinex/trampoline.rs` preserves the Unity executable as `.orig`, installs the bundled Mach-O stub as `CFBundleExecutable`, signs the real executable with the required entitlements, seals the bundle, verifies it, and rolls back the layout if installation fails. -- `is_current_trampoline` in the same module requires the structural `.orig` layout, the same Mach-O build UUID as the bundled stub, and a successful deep, strict signature verification. The UUID remains stable when bundle signing rewrites signature bytes; Steam Verify, game updates, resource changes, or a new stub produce a repairable state. -- `normalize` in `src-tauri/src/services/bepinex/bundle_root.rs` moves the known duplicate `TheBazaar_ARM64.app` outside the application before signing. It checks bundle identity and matching engine, Mono, and boot configuration, preserves the latest contents in a SHA-256-addressed backup, and resumes interrupted moves and cleanup. Existing backups are checked before reuse or removal; unknown or modified contents block repair. The backup remains outside the application after repair and uninstall because restoring it at the bundle root invalidates the signature. -- `inspect_launch_options_for_steam` and `clear_launch_options_for_steam` in `src-tauri/src/services/vdf/launch_options.rs` require every direct The Bazaar `LaunchOptions` value to be empty across Steam accounts. Unreadable configuration blocks mutation. -- `remove_obsolete_macos_artifacts` in `src-tauri/src/services/bepinex/trampoline.rs` removes fixed non-canonical residue by name; those files never select behavior. -- `uninstall_trampoline` restores `.orig`; `uninstall_bpp` invokes it only when BPP is the last installed mod. `with_finalized_bundle` seals and verifies after all uninstall mutations, including when a removal fails or another mod retains the shared trampoline. - -`compile_macos_trampoline_stub` in `src-tauri/build.rs` builds the bundled arm64 stub with the deployment target defined by `MACOS_TRAMPOLINE_DEPLOYMENT_TARGET` in `src-tauri/build_support.rs`. Release validation inspects that target before packaging. The rationale for the sole-bootstrap and empty-LaunchOptions choices lives in [ADR-0002](adr/0002-macos-launch-trampoline.md). - -## Headless Developer Commands - -`run_headless` in `src-tauri/src/lib.rs` dispatches CLI arguments before the -Tauri shell starts. `just installer::cli --help` documents the arguments; -`scripts/headless.mjs` runs that binary from source without a prepared Payload. - -The repair command calls `repair_deployed_game` in -`src-tauri/src/services/bepinex/mod.rs`. It requires an installed macOS game -with Doorstop and reuses the trampoline service, including process checks, -backup normalization, signing, and rollback. It preserves the deployed mod -DLLs, user data, and the persistent stash format. Both repair calls in mod -deployment use this entry: before copying files and after the native plugin -changes the application bundle. It does not run the GUI install planner or -replace the Payload with bundled release files. - -`tree_manifest` in `src-tauri/src/services/file_manifest.rs` supplies the same -sorted relative path and SHA-256 records to the CLI and acceptance tests. -Symlink records contain their targets without following them. Manifest output -belongs outside the game directory so it cannot include itself. - -The import command runs the one-time V5 import (ADR-0008) through `import_v5` -in `src-tauri/src/v5_import/run.rs`, the same entry the app calls, so it -holds the data maintenance lock and refuses while the game runs. It is the -only headless command that runs on every platform. A Windows release build -has no console, so the result goes only to the required `--manifest` file: -the outcome, the current Data Root's path and SHA-256 records without the -database file, and every database row. `--now` pins the clock the replay -retention window is measured from, which makes the file reproducible; -`src-tauri/tests/v5_import_cli.rs` compares it with -`src-tauri/tests/goldens/v5-import/`. - -## Reset Local Data - -Reset is the only installer operation that deletes the current Data Root, the directory `BAZAAR_DATA_DIRECTORY` in `src-tauri/src/config.rs` names under the game directory. The name must equal the mod's `PathConstants.DataRootDirectoryName`: a test in `config.rs` pins it to `dataRootDirectoryName` in `src-tauri/history-database-compatibility.json`, and `just release::check` compares that field with the mod's history database contract. The confirmation copy in `src/i18n/messages.ts` names the folder literally and changes with it. `reset_bpp_data` in `src-tauri/src/services/bepinex/mod.rs` holds the data maintenance lock with the OBS overlay stopped, runs the running-game refusal on every platform, and only then delegates filesystem cleanup to `cleanup_bpp_data_directory` in `src-tauri/src/services/bepinex/payload.rs`. `reset_bepinex_folder` holds the same lock and runs the same refusal, but leaves the overlay running because it touches no database. - -The Install workflow fixes the target path when confirmation opens. A successful `ResetBppDataResult` installs the returned refreshed state and distinguishes removed data from an already-empty target; a failure retains the target for retry. The durable product boundary is recorded in [ADR-0008](adr/0008-legacy-data-roots-and-v5-import.md). - -## Legacy Roots - -A Legacy Root (root `CONTEXT.md`) is user-owned. `LegacyRoot::ALL` in `src-tauri/src/services/legacy_data.rs` is the installer's only list of their names and never includes `BAZAAR_DATA_DIRECTORY`. Reset and uninstall never touch one, and nothing deletes one without the user confirming that root, including a successful V5 import. - -The Install page lists them, not History: History resolves its game directory only where the current database exists, which a user with only V5 data does not have. `get_legacy_data_state` resolves the selected directory with `GamePathAcceptance::Any` and returns `LegacyDataState`: - -- The Legacy Roots that exist as real directories directly under the game directory. A file or symbolic link with a root's name is not one, and the installer's own `BazaarPlusPlusV4` settings folder (`legacy_overlay_settings_path`) is never one. Sizes are measured on the blocking pool without following symbolic links. Files with more than one hard link are counted separately, because deleting the root frees their space only when no other link remains; the page therefore shows the size without promising what deletion reclaims. -- `installed_mod_data_root`: `current` only when `dataRootDirectoryName` in the installed mod's `BazaarPlusPlus.history-database.json` (under `BepInEx/plugins/`) equals `BAZAAR_DATA_DIRECTORY`. A missing file, a 5.x file without the field, corrupt JSON, or another name reads as `reinstall_required`, and the page asks an installed user to reinstall. -- `v5_import_eligible` from `is_v5_import_eligible` in `src-tauri/src/v5_import/mod.rs`: the installed mod writes the current Data Root, `BazaarPlusPlusV5/` exists, and it holds no `V5_IMPORT_MARKER_FILE_NAME` marker. - -`delete_legacy_root` accepts only a name from `LegacyRoot::ALL`. It holds the data maintenance lock, runs the running-game refusal (`legacy_delete_blocked_by_game`), and removes the directory with `remove_dir_with_retry`, the removal Reset uses. `DeleteLegacyRootResult` distinguishes a removed root from one already gone and carries the remeasured state; undeleted paths return `install_partial_failure` with operation `delete_legacy_root`. `createLegacyDataWorkflow` in `src/features/install/legacyDataWorkflow.ts` fixes each deletion to one listed root through the confirmed-operation seam. - -## V5 Import - -The Install page's Legacy Root section carries the one-time V5 import (ADR-0008). Its card appears only while `v5_import_eligible` holds; when the installed mod still writes an old Data Root, the section shows only the reinstall hint, because a reinstall is what makes the import eligible. The `#legacy-data` anchor (`LEGACY_DATA_SECTION_ID` in `src/features/install/LegacyDataPanel.tsx`) is where History sends a user without a current database. - -`import_v5_history` calls `import_v5_history` in `src-tauri/src/v5_import/app.rs`, which runs `import_v5` with the current clock and returns `ImportV5HistoryResult`: imported, skipped, and unavailable-file counts plus the remeasured `LegacyDataState`. The import runs without a confirmation because it only adds to the current Data Root and leaves `BazaarPlusPlusV5/` as it was. It reports no intermediate progress: it is one operation that commits or rolls back as a whole, so the card shows it as running until it settles and blocks Legacy Root deletion meanwhile. `ImportError::into_problem` keeps a running game as `import_blocked_by_game` with the `stage` that found it; every other failure is `import_failed` with `reason` set to `ImportError::code`, which `src/features/install/installProblems.ts` turns into recovery copy. Only `marker_not_written` means the rows committed; a retry skips every Run and writes the marker. - -After a successful import, `createLegacyDataWorkflow` opens the ordinary Legacy Root confirmation for `BazaarPlusPlusV5` with the import's counts (`afterImport`). The copy does not promise reclaimed space: placement shares data by clone or hard link where it can, so deleting V5 frees only what nothing else references. Declining keeps the folder, which stays listed as a Legacy Root and can be deleted later through the same confirmation. - -## Install and Repair Acceptance - -`just installer::acceptance` runs two ignored macOS tests. It requires `BPP_ACCEPTANCE_RESOURCE_DIR`, a packaged resource directory (`BepInExSource/BepInEx.zip` and `Trampoline/bpp_launcher`), and `BPP_TEST_GAME_ROOT`, an installed game. - -- `fresh_install_writes_payload_and_signed_trampoline_without_quitting_steam` in `src-tauri/src/services/install/operation.rs` creates a disposable macOS bundle and Steam config, then executes the production filesystem effects. It checks every payload file byte for byte and checks that the Steam config is unchanged. A shutdown effect fails the test before it can reach Steam. -- `copied_steam_bundle_repair_acceptance` in `src-tauri/src/services/bepinex/trampoline.rs` clones `TheBazaar.app` and Doorstop from the game root, repairs through the service and CLI repeatedly, verifies the manifest and preservation of developer DLLs and user data, then uninstalls the trampoline. The source is never modified. - -Each test compares a committed golden: - -- `src-tauri/tests/goldens/acceptance/installed-tree.json` holds the installed path set. -- `repaired-tree.json` holds the Payload Inventory paths present after repair. - -Both goldens also record whether the trampoline UUID matches the bundled one and whether `codesign --verify --deep --strict` passed. Signatures change on every signing, and the copied game differs between machines, so file hashes stay out of the goldens. Each run instead writes its full `(path, sha256)` list to `src-tauri/target/acceptance/`, where two runs over the same inputs can be diffed. `BPP_UPDATE_GOLDENS=1` rewrites the goldens. - -The fresh bundle contains a fixture executable, so these tests verify installation and signing, not game startup or BPP initialization. diff --git a/bazaarplusplus-installer/docs/release.md b/bazaarplusplus-installer/docs/release.md deleted file mode 100644 index f5730c3..0000000 --- a/bazaarplusplus-installer/docs/release.md +++ /dev/null @@ -1,36 +0,0 @@ -# Release - -Product versioning, isolated Payload preparation, immutable uploads and complete-release promotion are owned by the [workspace release flow](../../docs/release.md). The installer owns platform packaging and official signing. - -## Verification Gates - -- `npm run verify -- --source-only` is the clean-checkout source gate. `npm run verify -- --release-platform ` adds real Payload validation for one platform. -- `tauriSourceEnvironment` in `scripts/tauri-source-env.mjs` clears Tauri bundle resources in child processes for source verification and binding export, so Clippy, Rust tests and documentation do not require a prepared release ZIP. Release verification's Clippy and Payload checks keep the original resource configuration. -- `verificationSteps` in `scripts/checks/verify.mjs` owns one ordered list for complete verification and the source subsets. The frontend subset checks formatting, lint, TypeScript, frontend and script tests, documentation, source projections and the production frontend build using committed bindings. The native subset checks Rust formatting, the locked Cargo graph, Clippy, real binding generation with Rust tests, generated drift, strict rustdoc and source projections; Windows also runs the script tests. Shared steps run only once in the complete gate. -- Pass `--source-only --subset frontend` or `--source-only --subset native` to `npm run verify --` for a source subset. Release verification rejects partial subsets. The frontend result does not establish binding freshness or replace complete validation; the decision is recorded in [ADR 0004](adr/0004-tauri-specta-command-bindings.md). -- `npm run prebuild-check` uses the workspace `checkProductProjections` in `../release/projections.mjs` for source alignment and validates generated bindings, Payload build receipts, archives and native inputs. Missing receipts require preparation, not a bypass. -- `just release::build ` runs the product coordinator. Its process lock spans preparation, release verification, compilation, signing, bundling and artifact recording. Product Release integration tests run separately with `just release::test` and require the mod's .NET SDK. - -## Reproducible Inputs - -- Workspace `VERSION` is the authored product version. `synchronizeVersions` in `../release/version-sync.mjs` projects it into npm, Tauri and Cargo; `assertVersionsAreAligned` rejects drift. -- `RELEASE_PLATFORMS` in `../release/release-platforms.mjs` owns target triples, bundle layout, Tauri overlays, resource ZIPs and updater keys. -- The workspace Payload Inventory drives managed copying, ZIP admission and Rust file ownership. Runtime-only and retired entries cannot ship; dependency ownership does not authorize deleting user data or foreign plugins. -- `ensureNativeRecorderInput` in `../release/native-recorder-input.mjs` reuses current native inputs or invokes the mod-owned producer in isolated staging. `verifyNativeRecorderInput` validates the final artifact inventory before the product coordinator promotes any Payload directories. -- `listPayloadFiles`, `buildZipBuffer` and `writeDeterministicZip` in `../release/payload-zip.mjs` create deterministic unsigned ZIPs and checksum manifests. `validatePayloadZip` enforces staging/archive agreement. The coordinator additionally seals source, Managed, seed and output hashes in the Payload build receipt; regenerating a ZIP cannot make stale provenance current. - -## Packaging And Signing - -`run_release_prechecks` in `scripts/bundle.sh` requires the active product build lock and runs the platform release verification gate. It never chooses a separate version or prepares a second archive. - -On macOS, producer inputs are arm64, deployment target 12.0, system-linked, ABI-complete, loadable and ad-hoc signed. The installer verifies their inventory, signs nested Mach-O code and bundles inside-out with the official identity, repacks the signed copy, and packages/notarizes the outer installer. SourceForBuild remains unsigned provenance; final distribution hashes live in the artifact manifest. See [ADR-0006](adr/0006-native-replay-recorder-signing.md). - -`load_updater_signing_env` and `load_macos_developer_id_env` in `scripts/bundle.sh` own local environment and ignored signing-secret conventions. `assertMacosTrampolineStub` in `scripts/checks/prebuild-check.mjs` independently verifies the trampoline architecture and deployment target. - -## Artifact And Upload Contract - -`createArtifactManifest` in `../release/artifact-manifest.mjs` is called by the product coordinator only after packaging and source/Git revalidation. It records one installer/updater pair, the sealed Payload receipt, Git identity, sizes, hashes and signature content. Failed builds remove the previous receipt; there is no standalone command to create a receipt for leftover bundles. - -`validateArtifactManifest` rejects dirty or changed release inputs, mismatched versions/commits, and modified artifacts before upload. The uploader freezes every file before making any remote write. Platform uploads publish nothing; the workspace coordinator promotes either every platform or one platform (`promote --platform`), as specified in the [product release guide](../../docs/release.md). - -R2 access uses S3 credentials and ETag conditional writes, not Wrangler login state. Credentials, first-release migration, retry behavior and website deployment ordering are specified in the [product release guide](../../docs/release.md). diff --git a/bazaarplusplus-installer/docs/stream-service.md b/bazaarplusplus-installer/docs/stream-service.md deleted file mode 100644 index b0eef8b..0000000 --- a/bazaarplusplus-installer/docs/stream-service.md +++ /dev/null @@ -1,24 +0,0 @@ -# Stream Service - -## Native Lifecycle - -- `StreamRuntime` in `src-tauri/src/stream/runtime.rs` is the single owner of service lifecycle, task handles, and captured installation paths. Its lifecycle mutex serializes ensure, restart, stop, window changes, and exclusive maintenance. -- `StreamRuntime::ensure` and `StreamRuntime::restart` resolve one selected-installation snapshot while holding the lifecycle gate. Window changes reuse the captured record path rather than resolving a different installation mid-session. -- `ProductionServer::start` in `src-tauri/src/stream/server.rs` creates the repository and settings store, binds the loopback service, reports database availability, and serves with graceful shutdown. `origin` in the same file is the one service origin every URL is built from; the service binds that fixed port or fails. -- `StreamRuntime::prepare_history_thumbnails` is the History List's entry to the same lifecycle: it starts a stopped service and never rebinds a running one. -- Startup, tray actions, window-close behavior, and Tauri stream commands call through `StreamRuntime`; they do not mutate the server task directly. -- Stream command failures are classified by capability and operation in `src-tauri/src/commands/stream.rs` and returned as `SemanticProblem`. - -## Frontend Capabilities - -`DefaultStreamWorkflow` in `src/features/stream/streamWorkflow.ts` keeps service state, polling freshness, display window, crop settings, and one-off actions independent. Repeated poll failures retain the last value but mark it stale; actions that require authoritative running state remain gated until a successful refresh. Problems and notices stay semantic until `src/features/stream/streamProblems.ts` and `src/features/stream/streamPresentation.ts` translate them. - -## HTTP Surface - -`router` in `src-tauri/src/stream/http.rs` serves the overlay, settings, record and crop APIs, record images, and static assets, and merges the History Thumbnail route. CORS is restricted by `is_allowed_cors_origin` to Tauri origins and the configured local Vite development origins. - -Every handler's database, image, and overlay settings file access, including the crop API's settings read and write, runs on blocking threads through `run_record_task`, never on the async workers shared with Tauri commands: a SQLite open can wait out the busy timeout while the game holds a lock, and file reads and writes block. The OBS strip route makes one blocking hop into `render_strip` in `src-tauri/src/stream/strip.rs`, which reads the saved crop, resolves the record's screenshot, and crops, caches, and encodes the PNG. A crop in the query is validated before that hop and overrides the saved crop; `preview=true` bypasses the cache. - -The History Thumbnail route belongs to `src-tauri/src/stream/history_thumbnails/mod.rs`, which also owns its source registry and URL builder. It always uses the saved crop and caches under one namespace per installation path, named by a digest of that path, beside the OBS strips at the cache root. Both routes share `cached_strip`: writes go through a uniquely named temporary file, and a hit refreshes the entry's modification time. `sweep_cache` runs once per process on a blocking thread when the service first starts. It deletes the legacy per-file `history/` cache tree, orphaned temporary files, and History Thumbnails unused past an age limit, then the oldest beyond a count cap; it skips files modified in the last few seconds, and every deletion is best effort because Windows refuses to delete an open file. The limits are `CACHE_LIMITS` in that module. The OBS strips at the cache root are never swept. - -Overlay records carry canonical `hero_id` separately from their display title through `to_overlay_record` in `src-tauri/src/stream/records/mapper.rs`. The settings page owns a small zh/en dictionary because it runs on the service origin; `DefaultStreamWorkflow.openSettings` appends the current app locale when opening it. diff --git a/bazaarplusplus-installer/docs/updater.md b/bazaarplusplus-installer/docs/updater.md deleted file mode 100644 index e11d39f..0000000 --- a/bazaarplusplus-installer/docs/updater.md +++ /dev/null @@ -1,16 +0,0 @@ -# Updater - -## State Machine - -- `runCheck` in `src/features/about/updater.ts` returns Browser Preview state outside Tauri, an available update with its native handle, or current-version state. -- `UpdaterSnapshot` and `createUpdaterMachine` in the same module make checking, availability, download, install, restart readiness, restart, and failure mutually exclusive. Only download carries progress. -- The native `Update` handle returned by `check` remains alive until `downloadAndInstall`; retry obtains a fresh handle after one is consumed. -- `updaterProblemFromError` in `src/features/about/updaterProblems.ts` converts native errors into stable operation/version parameters plus optional diagnostics. Localized recovery copy is derived separately. - -## Presentation - -`getUpdaterUiContract` in `src/features/about/updaterPresentation.ts` derives modal priority, dismissal, title, and action from the machine snapshot. Decisions and recovery are dismissible; download, install, and restart work are blocked because the native API exposes no cancellation contract. `ShellUpdateModal` in `src/layouts/ShellUpdateModal.tsx` is the single modal presentation. - -Under the zh locale, the modal may also offer the mainland-China mirror page published in the Release Manifest as `downloads[platform].mainlandUrl`. `runCheck` in `src/features/about/updater.ts` reads it from the update's `rawJson`, the Platform Release Manifest the updater already fetched through the first of `UPDATER_ENDPOINTS` in workspace `../release/downloads.ts` (the lockstep Release Manifest is the second endpoint; the plugin moves on to it after a non-2xx status, a transport error, or a body it cannot parse, and then reports the lockstep version as current), through `decodeMainlandDownloadUrl` in workspace `../release/downloads.ts`, choosing the platform with the same `isWindows` host detection the machine injects; a manifest that publishes no address, or a non-https one, offers no link. `offersMainlandMirror` in `getUpdaterUiContract` decides when: for an available update, while its download runs, and after a failed download or install. It is not offered during install or restart, after a restart failure, or after a check failure, where no version is known. Automatic installation remains the primary path. [ADR-0001](adr/0001-in-app-updater.md) records that product choice. - -Updater endpoint, public key, artifact creation, and runtime permissions are configured in `src-tauri/tauri.conf.json` and `src-tauri/capabilities/default.json`; those environment files remain authoritative for their literal values. diff --git a/bazaarplusplus-installer/index.html b/bazaarplusplus-installer/index.html deleted file mode 100644 index 1e3a27c..0000000 --- a/bazaarplusplus-installer/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - BazaarPlusPlus - - -
- - - diff --git a/bazaarplusplus-installer/installer.just b/bazaarplusplus-installer/installer.just deleted file mode 100644 index 00fce45..0000000 --- a/bazaarplusplus-installer/installer.just +++ /dev/null @@ -1,44 +0,0 @@ -set shell := ["bash", "-euo", "pipefail", "-c"] -set positional-arguments - -# Run the source-only gate, including Rust/JS tests and the frontend build. -check: - npm run verify -- --source-only - -# Pre-commit subset; full Rust checks, tests, binding generation and builds run in check. -check-fast: - npm run format:check - npm run lint - npm run check:ts - cargo fmt --manifest-path src-tauri/Cargo.toml -- --check - npm run docs:check - -# Generate bindings and run the Rust and JavaScript tests. -test: - npm test - -# Run the macOS install and repair acceptance tests against a packaged resource directory and a copied game. -acceptance: - [ "$(uname -s)" = Darwin ] || { echo "installer::acceptance runs on macOS only" >&2; exit 1; } - : "${BPP_ACCEPTANCE_RESOURCE_DIR:?set it to a packaged macOS resource directory holding BepInExSource/BepInEx.zip and Trampoline/bpp_launcher}" - : "${BPP_TEST_GAME_ROOT:?set it to a The Bazaar installation whose TheBazaar.app is copied; the source is never modified}" - TAURI_CONFIG='{"bundle":{"resources":[]}}' cargo build --manifest-path src-tauri/Cargo.toml --bin bppinstaller - BPP_TEST_INSTALLER_CLI="$(pwd)/src-tauri/target/debug/bppinstaller" TAURI_CONFIG='{"bundle":{"resources":[]}}' cargo test --manifest-path src-tauri/Cargo.toml --lib -- --ignored fresh_install_writes_payload_and_signed_trampoline_without_quitting_steam copied_steam_bundle_repair_acceptance - -# Run the headless installer from source; use --help for commands. -cli *args: - node scripts/headless.mjs "$@" - -# Start the frontend development server (not the desktop app). -dev: - npm run dev - -# Start the full Tauri desktop app; installs npm dependencies only when the tree is invalid. -app: - node scripts/checks/check-toolchain.mjs "$(node --version)" "$(npm --version)" - npm ls --depth=0 >/dev/null 2>&1 || npm ci - npm run tauri dev - -# Format installer sources in place. -fmt: - npm run format diff --git a/bazaarplusplus-installer/package-lock.json b/bazaarplusplus-installer/package-lock.json deleted file mode 100644 index d89a7a6..0000000 --- a/bazaarplusplus-installer/package-lock.json +++ /dev/null @@ -1,3699 +0,0 @@ -{ - "name": "bppinstaller", - "version": "6.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "bppinstaller", - "version": "6.0.0", - "license": "MIT", - "dependencies": { - "@tauri-apps/api": "^2.12.3", - "@tauri-apps/plugin-opener": "^2.7.1", - "@tauri-apps/plugin-process": "^2.4.0", - "@tauri-apps/plugin-updater": "^2.13.3", - "clsx": "^2.1.1", - "lucide-react": "^1.47.0", - "react": "^19.3.0", - "react-dom": "^19.3.0", - "react-router-dom": "^7.18.4" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.3.3", - "@tauri-apps/cli": "^2.11.4", - "@types/node": "^24.13.3", - "@types/react": "^19.3.0", - "@types/react-dom": "^19.3.0", - "@vitejs/plugin-react": "^6.1.2", - "jsdom": "^30.1.2", - "oxlint": "^1.83.0", - "oxlint-tsgolint": "^7.0.2004", - "prettier": "^3.9.10", - "tailwindcss": "^4.3.3", - "typescript": "^7.0.2", - "vite": "^8.3.4", - "vitest": "^5.0.4" - }, - "engines": { - "node": ">=24.15.0 <25", - "npm": ">=12 <13" - } - }, - "node_modules/@asamuzakjp/css-color": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.5.tgz", - "integrity": "sha512-jCpAvj8apa7SKHZYogk0rbXB3Kb0hLFrpkWF+Ap+vBA5rirItnpv9NKyAyEuDuFizvl0qwnj6JWR70RGJ0rOlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@csstools/css-calc": "^3.4.3", - "@csstools/css-color-parser": "^4.2.6", - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2", - "lru-cache": "^11.5.3" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, - "node_modules/@asamuzakjp/dom-selector": { - "version": "9.2.4", - "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-9.2.4.tgz", - "integrity": "sha512-YnVzxDxLaqL0t7Q4wfcgHZjg55Wm6y5EaO7Bhu3q9J7wq/8iw3PhsnWiOQhYekx4VexnbkgWpTT6n+QIV7kczw==", - "dev": true, - "license": "MIT", - "dependencies": { - "bidi-js": "^1.1.0", - "css-tree": "^3.2.1", - "is-potential-custom-element-name": "^1.0.1", - "lru-cache": "^11.5.3" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, - "node_modules/@bramus/specificity": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz", - "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==", - "dev": true, - "license": "MIT", - "dependencies": { - "css-tree": "^3.0.0" - }, - "bin": { - "specificity": "bin/cli.js" - } - }, - "node_modules/@csstools/color-helpers": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", - "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT-0", - "engines": { - "node": ">=20.19.0" - } - }, - "node_modules/@csstools/css-calc": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", - "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-color-parser": { - "version": "4.2.6", - "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz", - "integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "dependencies": { - "@csstools/color-helpers": "^6.1.2", - "@csstools/css-calc": "^3.4.3" - }, - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-parser-algorithms": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", - "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-syntax-patches-for-csstree": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz", - "integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT-0", - "peerDependencies": { - "css-tree": "^3.2.1" - }, - "peerDependenciesMeta": { - "css-tree": { - "optional": true - } - } - }, - "node_modules/@csstools/css-tokenizer": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", - "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - } - }, - "node_modules/@exodus/bytes": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", - "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^20.19.0 || ^22.12.0 || >=24.0.0" - }, - "peerDependencies": { - "@noble/hashes": "^1.8.0 || ^2.0.0" - }, - "peerDependenciesMeta": { - "@noble/hashes": { - "optional": true - } - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", - "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@oxc-project/types": { - "version": "0.153.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz", - "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/oxc-project" - } - }, - "node_modules/@oxlint-tsgolint/darwin-arm64": { - "version": "7.0.2004", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/darwin-arm64/-/darwin-arm64-7.0.2004.tgz", - "integrity": "sha512-uJk3ttju7Lz+Nv8WG4CsLyewoL1qf/Ny8S8OksJ7Bm/F14Tc9gMfW6arM1PCc57IzH/X/I79YsCWTgxX1FKibQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@oxlint-tsgolint/darwin-x64": { - "version": "7.0.2004", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/darwin-x64/-/darwin-x64-7.0.2004.tgz", - "integrity": "sha512-0BFfHTzDxNDFPcu0UZAXT6CyCJHAXM0dZveyDb4KEHa2qF/DSnOKOrmvK/wFuFol9kvijbGM9JfuOsor+zWXRw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@oxlint-tsgolint/linux-arm64": { - "version": "7.0.2004", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/linux-arm64/-/linux-arm64-7.0.2004.tgz", - "integrity": "sha512-TAehQc+qdRXyDN3nl/r/3/oPrBVrbtrDeGMkFyG6mf+XphpoJ2lAMVFLclyvrVZCw02RbKROjyw8h72XwQQHcw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@oxlint-tsgolint/linux-x64": { - "version": "7.0.2004", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/linux-x64/-/linux-x64-7.0.2004.tgz", - "integrity": "sha512-LPunZvm6ZbWPfHMAyfZf9ci3HHvNEzLejO8zdqO3GoVGoSEHqqufHUD7+OgeatVSaJP7uXDJ2HaNOHIoH7go4Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@oxlint-tsgolint/win32-arm64": { - "version": "7.0.2004", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/win32-arm64/-/win32-arm64-7.0.2004.tgz", - "integrity": "sha512-FVWplzDImWhiuawnIZVETaQecv4GWom6Jv4Fx2xj7hhXXDZ5okEgiw1gTCImHTIQsi2ycC5oSxVwrn69bMh7iw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@oxlint-tsgolint/win32-x64": { - "version": "7.0.2004", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/win32-x64/-/win32-x64-7.0.2004.tgz", - "integrity": "sha512-7PsxuUx11Ry9DYTWcljTzRbmZY9B6O9fFFfZV+aodQEMy6pfRT3fhoQRv9PtGN/89z1pPz3nFKrsFm6WqNtX7w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@oxlint/binding-android-arm-eabi": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.83.0.tgz", - "integrity": "sha512-0yGY24EwsLk5YDe6F+VkmZyRHSwJDALa3nIrPpq7FXmp2lV2d0TzvBCGeZk+wgiULRGr5blhyr4QMp5KCXJUqA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-android-arm64": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.83.0.tgz", - "integrity": "sha512-hHfJ0vc17A4iUjH5p9BsTUPYbYRNxGpvD2lbu1aBRk54bzNIx9o5TtYF39QPZcV95DagZd+4DEAw2RH3G2ZsMg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-darwin-arm64": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.83.0.tgz", - "integrity": "sha512-hsOjYjszLb/3zym/TkzUMPAoQlTJcuzSyEPOAyA+skXJIX9M0o+4JfOtqopX/Vf4hSLrJ98j0nvFo23gzk8auQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-darwin-x64": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.83.0.tgz", - "integrity": "sha512-mjh5oH2EA+wl5yRJYT9K9G61O2zFlpuv+yf2JwZOi0+dq2FnTUtm1h8i+5Ik0fXPWIu/k84I1psZR9aQsLAnyA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-freebsd-x64": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.83.0.tgz", - "integrity": "sha512-fNHr64/YaO8YssuoDVC8+F4Uk5enR86q5uxfHkQrjAPs1dbAILOrD2uaud+J7MO8Fx774g44ERLD0IGIvZE48w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-arm-gnueabihf": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.83.0.tgz", - "integrity": "sha512-Qpwy3zzAwMj+8/lyYItHmkSMwbkprFNWTK7jPYDOxSyxEhaSLOWYUTCMkjF334J8/WD0nznCCsoBbIH6hpsuIw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-arm-musleabihf": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.83.0.tgz", - "integrity": "sha512-s+BirYLFq7JL2k9sP0XI3ZXJ9dYvJ8sX3jLCLoag7tt+zrSHpZxP0jqznfL+Gdgwu7ay0dYgGYJXrQvq3iWloA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-arm64-gnu": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.83.0.tgz", - "integrity": "sha512-7lihXt3vKr+GIyapNbHrnFHm/biiW30le6Zv/DExbAFPF6YwCQXVFlONPFehxs0CpGO4CBfYPM9rdDT+XMoIlg==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-arm64-musl": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.83.0.tgz", - "integrity": "sha512-q63JalLYVkZiZvls1z3PPUnpmQluOMXp0khqQMznCeAPLGydfNY8JhvuA4WlK57JfrvikU8wB5lPVveqpIXvew==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-ppc64-gnu": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.83.0.tgz", - "integrity": "sha512-krQmDF+dRbxvdqVPV88ZuOoPPu8X5BuqDA8Hd+qcS4YMRQCb+nexA57DazgGsc/rGdKBe3QmV0mnv0bdpW/p5g==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-riscv64-gnu": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.83.0.tgz", - "integrity": "sha512-MmOl8Y6txEAXZU1RG8Rr264jQ6D7VPmqFsU/45x/FeWsGe32hklTqGrLE6UxHzp5Rjt0wP+20tY8YXKgSFB3mw==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-riscv64-musl": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.83.0.tgz", - "integrity": "sha512-u1rMymh0W3JZkq370kzQsYPULGWqhE09pZRqnZvUSoYaI9pVO5yVX+iYIslmWuEgwuzH9YAaOsScJiobWCHoOw==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-s390x-gnu": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.83.0.tgz", - "integrity": "sha512-y0zK3HNwGysu7rqtE+BQG/d0bx5gh/KwlOtghN8oWeK1KcWzeaLqtZrbm8owqdma1lFyrce/hTO5ismuNu+INQ==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-x64-gnu": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.83.0.tgz", - "integrity": "sha512-rS5gM0NgD7ngmuJmbIehsidtrOwKkLFwCQbKEeb9KuyQrrWNq5Zkn0uV6AYdXOMJ0grrWEiLwBuvMxt8w5vsNw==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-linux-x64-musl": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.83.0.tgz", - "integrity": "sha512-W2IH4EtpcPaWcvNGCA95YoDg4vxqE/ZiPCi3arrxEEpsK7+JQN9WYwrlYFx9pcdP6KPXqRqkv3zdQPHcx7b6YQ==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-openharmony-arm64": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.83.0.tgz", - "integrity": "sha512-6LyKkUyoajssTPLlZmDbZIbu4IZ5B4bGuRUnBgCGpEvHP3FQMaYITncHA/unPUo7q+Z+pIu2HhdkQ+8d1SG7iA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-win32-arm64-msvc": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.83.0.tgz", - "integrity": "sha512-Uz/fObEtF0jmNJQJ8CGRBKfefYstS0/wjD3s6IGzP8nUwsJykHQJBiN3npHwKiGRGn/vvBEgNr4B3cCzmmatvg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-win32-ia32-msvc": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.83.0.tgz", - "integrity": "sha512-u7XcvPW6Bk58tY5iWs2ESb0vJjoE/kuSpHxopbwp/p3ZtWVQXZ6wor5w3ssVTHOqd/v8b+QdhSFWQ4grEUNWpA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxlint/binding-win32-x64-msvc": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.83.0.tgz", - "integrity": "sha512-LZRubd7ph13QmAg4fFecTYVZkiYbROR2Htaxh/ufWRkDhPOm2wrwaEYR89e0YpPFD3dqBrPoxS7myBw5hmYA7Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz", - "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz", - "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz", - "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz", - "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz", - "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz", - "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz", - "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz", - "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz", - "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz", - "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz", - "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz", - "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz", - "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz", - "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz", - "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tailwindcss/node": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz", - "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/remapping": "^2.3.5", - "enhanced-resolve": "^5.24.1", - "jiti": "^2.7.0", - "lightningcss": "1.32.0", - "magic-string": "^0.30.21", - "source-map-js": "^1.2.1", - "tailwindcss": "4.3.3" - } - }, - "node_modules/@tailwindcss/oxide": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.3.tgz", - "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 20" - }, - "optionalDependencies": { - "@tailwindcss/oxide-android-arm64": "4.3.3", - "@tailwindcss/oxide-darwin-arm64": "4.3.3", - "@tailwindcss/oxide-darwin-x64": "4.3.3", - "@tailwindcss/oxide-freebsd-x64": "4.3.3", - "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", - "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", - "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", - "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", - "@tailwindcss/oxide-linux-x64-musl": "4.3.3", - "@tailwindcss/oxide-wasm32-wasi": "4.3.3", - "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", - "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" - } - }, - "node_modules/@tailwindcss/oxide-android-arm64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz", - "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-darwin-arm64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz", - "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-darwin-x64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz", - "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-freebsd-x64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz", - "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz", - "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz", - "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm64-musl": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz", - "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-x64-gnu": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz", - "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-x64-musl": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz", - "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz", - "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==", - "bundleDependencies": [ - "@napi-rs/wasm-runtime", - "@emnapi/core", - "@emnapi/runtime", - "@tybys/wasm-util", - "@emnapi/wasi-threads", - "tslib" - ], - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "^1.11.1", - "@emnapi/runtime": "^1.11.1", - "@emnapi/wasi-threads": "^1.2.2", - "@napi-rs/wasm-runtime": "^1.1.4", - "@tybys/wasm-util": "^0.10.2", - "tslib": "^2.8.1" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { - "version": "1.11.1", - "dev": true, - "inBundle": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.2", - "tslib": "^2.4.0" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { - "version": "1.11.1", - "dev": true, - "inBundle": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { - "version": "1.2.2", - "dev": true, - "inBundle": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.4", - "dev": true, - "inBundle": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.1" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { - "version": "0.10.2", - "dev": true, - "inBundle": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { - "version": "2.8.1", - "dev": true, - "inBundle": true, - "license": "0BSD", - "optional": true - }, - "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz", - "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-win32-x64-msvc": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz", - "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/vite": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.3.tgz", - "integrity": "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@tailwindcss/node": "4.3.3", - "@tailwindcss/oxide": "4.3.3", - "tailwindcss": "4.3.3" - }, - "peerDependencies": { - "vite": "^5.2.0 || ^6 || ^7 || ^8" - } - }, - "node_modules/@tauri-apps/api": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.3.tgz", - "integrity": "sha512-9s0PKw0p4r3kFq92jhpivYSp+cSht15o0gXpZxuQd0+dV9KCexEVkNaLELVoLdJWyoH4KlfQo5h3W2LIM8siJg==", - "license": "Apache-2.0 OR MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/tauri" - } - }, - "node_modules/@tauri-apps/cli": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.11.4.tgz", - "integrity": "sha512-R8xGtMpwyetawSqm9kYOuMmEqkhUbvcUy8n0aNXIxollKBLESUu5f4Fx+64hgASYm1H+jSWq6jCW6zqTnH6hqQ==", - "dev": true, - "license": "Apache-2.0 OR MIT", - "bin": { - "tauri": "tauri.js" - }, - "engines": { - "node": ">= 10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/tauri" - }, - "optionalDependencies": { - "@tauri-apps/cli-darwin-arm64": "2.11.4", - "@tauri-apps/cli-darwin-x64": "2.11.4", - "@tauri-apps/cli-linux-arm-gnueabihf": "2.11.4", - "@tauri-apps/cli-linux-arm64-gnu": "2.11.4", - "@tauri-apps/cli-linux-arm64-musl": "2.11.4", - "@tauri-apps/cli-linux-riscv64-gnu": "2.11.4", - "@tauri-apps/cli-linux-x64-gnu": "2.11.4", - "@tauri-apps/cli-linux-x64-musl": "2.11.4", - "@tauri-apps/cli-win32-arm64-msvc": "2.11.4", - "@tauri-apps/cli-win32-ia32-msvc": "2.11.4", - "@tauri-apps/cli-win32-x64-msvc": "2.11.4" - } - }, - "node_modules/@tauri-apps/cli-darwin-arm64": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.11.4.tgz", - "integrity": "sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-darwin-x64": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.11.4.tgz", - "integrity": "sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.11.4.tgz", - "integrity": "sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-arm64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.11.4.tgz", - "integrity": "sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-arm64-musl": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.11.4.tgz", - "integrity": "sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.11.4.tgz", - "integrity": "sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-x64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.11.4.tgz", - "integrity": "sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-x64-musl": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.11.4.tgz", - "integrity": "sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-win32-arm64-msvc": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.11.4.tgz", - "integrity": "sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-win32-ia32-msvc": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.11.4.tgz", - "integrity": "sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-win32-x64-msvc": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.11.4.tgz", - "integrity": "sha512-+vDiqBIU5dMISg/wNvX3sF+ZHfgJGJ5T0AcO+EHNXV9GGAG+P5fzodlDXD3QdKCRgZxMoCm5PPvj3BqLNjBthw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/plugin-opener": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-opener/-/plugin-opener-2.7.1.tgz", - "integrity": "sha512-XkXdt30rontti9TII/gBBxFRXWfj8DiprFW7RgBFRBj1OhdfjBNVcFqSEWkkZ4hXafHnuEnB7F1sFsmu6uyywQ==", - "license": "MIT OR Apache-2.0", - "dependencies": { - "@tauri-apps/api": "^2.12.0" - } - }, - "node_modules/@tauri-apps/plugin-process": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-process/-/plugin-process-2.4.0.tgz", - "integrity": "sha512-GddrmsSLAYrLa/yTXlXK/YRDzUgYeeOnUXTbiyvJWkmI424RmDPD3FVLeqcon7rv6O6ZfhBilcrHWnSo7o6hIQ==", - "license": "MIT OR Apache-2.0", - "dependencies": { - "@tauri-apps/api": "^2.12.0" - } - }, - "node_modules/@tauri-apps/plugin-updater": { - "version": "2.13.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-updater/-/plugin-updater-2.13.3.tgz", - "integrity": "sha512-CtbA8CZ79WJry2HbRiFGx6WZN7uspho6A4jM+TxmuqwWL2EEfJEMw6BIYgRncIZyqp4vEXw3U/97ZjQ33dKUgg==", - "license": "MIT OR Apache-2.0", - "dependencies": { - "@tauri-apps/api": "^2.12.0" - } - }, - "node_modules/@types/chai": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", - "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/deep-eql": "*", - "assertion-error": "^2.0.1" - } - }, - "node_modules/@types/deep-eql": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", - "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "24.13.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.6.tgz", - "integrity": "sha512-SGrw/h3KPFshy3OE6ZL53LMBG5vGQQ8/gIpiqz/kRZhPJ7HgwCEs8LBuNtWLa8dvGZVpSF7+Bf+c11HUrCb/yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~7.18.0" - } - }, - "node_modules/@types/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", - "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "dev": true, - "license": "MIT", - "dependencies": { - "csstype": "^3.2.2" - } - }, - "node_modules/@types/react-dom": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", - "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@types/react": "^19.3.0" - } - }, - "node_modules/@typescript/typescript-aix-ppc64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", - "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-darwin-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", - "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-darwin-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", - "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-freebsd-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", - "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-freebsd-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", - "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-arm": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", - "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", - "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-loong64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", - "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-mips64el": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", - "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-ppc64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", - "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-riscv64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", - "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-s390x": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", - "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", - "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-netbsd-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", - "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-netbsd-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", - "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-openbsd-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", - "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-openbsd-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", - "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-sunos-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", - "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-win32-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", - "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-win32-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", - "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@vitejs/plugin-react": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", - "integrity": "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rolldown/pluginutils": "^1.0.1" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "peerDependencies": { - "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", - "babel-plugin-react-compiler": "^1.0.0", - "oxc-transform-react": "^0.152.0", - "vite": "^8.0.0" - }, - "peerDependenciesMeta": { - "@rolldown/plugin-babel": { - "optional": true - }, - "babel-plugin-react-compiler": { - "optional": true - }, - "oxc-transform-react": { - "optional": true - } - } - }, - "node_modules/@vitest/mocker": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.4.tgz", - "integrity": "sha512-tqAlrYWce4iUxhr3ncNohejtCTOcHeE8XWrSNZY3OhPoDn01yeGv+gnaBy64ATp7o6pb03eIbBAjzmibpc9vIQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "0.3.31", - "@vitest/spy": "5.0.4", - "estree-walker": "^3.0.3", - "magic-string": "^1.4.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "msw": "^2.4.9 || ^3.0.0", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "msw": { - "optional": true - }, - "vite": { - "optional": true - } - } - }, - "node_modules/@vitest/mocker/node_modules/magic-string": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", - "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.6.0" - } - }, - "node_modules/@vitest/spy": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.4.tgz", - "integrity": "sha512-MZKk/gSkm2q+ICobMxCpH1mA+cCAWm8WV7UhxlqGjq/sJ3AGc1BqFOs5CRVXxH78wQtme9q/NAAgBquj4AcyMw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/assertion-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", - "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/bidi-js": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", - "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", - "dev": true, - "license": "MIT", - "dependencies": { - "require-from-string": "^2.0.2" - } - }, - "node_modules/chai": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", - "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/clsx": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", - "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/cookie": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", - "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/css-tree": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", - "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", - "dev": true, - "license": "MIT", - "dependencies": { - "mdn-data": "2.27.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" - } - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/data-urls": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", - "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "whatwg-mimetype": "^5.0.0", - "whatwg-url": "^17.1.2" - }, - "engines": { - "node": "^22.14.0 || >=24.0.0" - } - }, - "node_modules/decimal.js": { - "version": "10.6.0", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", - "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", - "dev": true, - "license": "MIT" - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/enhanced-resolve": { - "version": "5.25.1", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.25.1.tgz", - "integrity": "sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.4", - "tapable": "^2.3.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/entities": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", - "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/es-module-lexer": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", - "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", - "dev": true, - "license": "MIT" - }, - "node_modules/estree-walker": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", - "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0" - } - }, - "node_modules/expect-type": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", - "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/html-encoding-sniffer": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", - "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@exodus/bytes": "^1.15.1" - }, - "engines": { - "node": "^22.13.0 || >=24.0.0" - } - }, - "node_modules/is-potential-custom-element-name": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", - "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/jiti": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", - "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", - "dev": true, - "license": "MIT", - "bin": { - "jiti": "lib/jiti-cli.mjs" - } - }, - "node_modules/jsdom": { - "version": "30.1.2", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.2.tgz", - "integrity": "sha512-0FFE/jE1rppmVfUrJUgxqXjcwolZYIGtAgj1pTussMhNZxIxi7W/PvfWaMNroGi2B36X1IKHbexpZ9DhkoOPiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@asamuzakjp/css-color": "^7.1.3", - "@asamuzakjp/dom-selector": "^9.2.4", - "@bramus/specificity": "^2.4.2", - "@csstools/css-syntax-patches-for-csstree": "^1.1.15", - "@exodus/bytes": "^1.16.0", - "css-tree": "^3.2.1", - "data-urls": "^8.0.0", - "decimal.js": "^10.6.0", - "html-encoding-sniffer": "^7.0.0", - "is-potential-custom-element-name": "^1.0.1", - "lru-cache": "^11.5.3", - "parse5": "^8.0.1", - "saxes": "^6.0.0", - "tough-cookie": "^6.0.2", - "undici": "^8.11.2", - "w3c-xmlserializer": "^6.0.0", - "webidl-conversions": "^8.0.1", - "whatwg-mimetype": "^5.0.0", - "whatwg-url": "^17.2.0", - "xml-name-validator": "^5.0.0" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - }, - "peerDependencies": { - "canvas": "^3.2.3" - }, - "peerDependenciesMeta": { - "canvas": { - "optional": true - } - } - }, - "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" - } - }, - "node_modules/lightningcss-android-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/lucide-react": { - "version": "1.47.0", - "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.47.0.tgz", - "integrity": "sha512-o8C23aXpNQypRY73W7fW02EyvWJinEMXgKeGjFoKym0zj3Q73hD97A1IQps1g8C14HTGsOpZL0Am+xjfgFZAbg==", - "license": "ISC", - "peerDependencies": { - "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/mdn-data": { - "version": "2.27.1", - "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", - "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", - "dev": true, - "license": "CC0-1.0" - }, - "node_modules/nanoid": { - "version": "3.3.20", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", - "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/obug": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", - "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", - "dev": true, - "funding": [ - "https://github.com/sponsors/sxzz", - "https://opencollective.com/debug" - ], - "license": "MIT", - "engines": { - "node": ">=12.20.0" - } - }, - "node_modules/oxlint": { - "version": "1.83.0", - "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.83.0.tgz", - "integrity": "sha512-cyDzSzaw3uzP0TeCeq3lLRPPoaUxkbB4ZOXj+kn+5r+BX9V+4bNVGk9lxer+WrgcpebH4JxLlJ3KQjveVztOLQ==", - "dev": true, - "license": "MIT", - "bin": { - "oxlint": "bin/oxlint" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/sponsors/oxc-project" - }, - "optionalDependencies": { - "@oxlint/binding-android-arm-eabi": "1.83.0", - "@oxlint/binding-android-arm64": "1.83.0", - "@oxlint/binding-darwin-arm64": "1.83.0", - "@oxlint/binding-darwin-x64": "1.83.0", - "@oxlint/binding-freebsd-x64": "1.83.0", - "@oxlint/binding-linux-arm-gnueabihf": "1.83.0", - "@oxlint/binding-linux-arm-musleabihf": "1.83.0", - "@oxlint/binding-linux-arm64-gnu": "1.83.0", - "@oxlint/binding-linux-arm64-musl": "1.83.0", - "@oxlint/binding-linux-ppc64-gnu": "1.83.0", - "@oxlint/binding-linux-riscv64-gnu": "1.83.0", - "@oxlint/binding-linux-riscv64-musl": "1.83.0", - "@oxlint/binding-linux-s390x-gnu": "1.83.0", - "@oxlint/binding-linux-x64-gnu": "1.83.0", - "@oxlint/binding-linux-x64-musl": "1.83.0", - "@oxlint/binding-openharmony-arm64": "1.83.0", - "@oxlint/binding-win32-arm64-msvc": "1.83.0", - "@oxlint/binding-win32-ia32-msvc": "1.83.0", - "@oxlint/binding-win32-x64-msvc": "1.83.0" - }, - "peerDependencies": { - "oxlint-tsgolint": ">=7.0.2001", - "vite-plus": "*" - }, - "peerDependenciesMeta": { - "oxlint-tsgolint": { - "optional": true - }, - "vite-plus": { - "optional": true - } - } - }, - "node_modules/oxlint-tsgolint": { - "version": "7.0.2004", - "resolved": "https://registry.npmjs.org/oxlint-tsgolint/-/oxlint-tsgolint-7.0.2004.tgz", - "integrity": "sha512-vQ9WDF3fiZJvRdSDosNOflerOCOpwol6vWzVDxW76RcU19cjTh7engvkHLvmv+tzedR8fAiJUVUGr6IVZdkzXQ==", - "dev": true, - "license": "MIT", - "bin": { - "tsgolint": "bin/tsgolint.js" - }, - "optionalDependencies": { - "@oxlint-tsgolint/darwin-arm64": "7.0.2004", - "@oxlint-tsgolint/darwin-x64": "7.0.2004", - "@oxlint-tsgolint/linux-arm64": "7.0.2004", - "@oxlint-tsgolint/linux-x64": "7.0.2004", - "@oxlint-tsgolint/win32-arm64": "7.0.2004", - "@oxlint-tsgolint/win32-x64": "7.0.2004" - } - }, - "node_modules/parse5": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", - "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", - "dev": true, - "license": "MIT", - "dependencies": { - "entities": "^8.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", - "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postcss": { - "version": "8.5.30", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz", - "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.20", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.2" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/prettier": { - "version": "3.9.10", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz", - "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", - "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", - "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", - "license": "MIT", - "dependencies": { - "scheduler": "^0.28.0" - }, - "peerDependencies": { - "react": "^19.3.0" - } - }, - "node_modules/react-router": { - "version": "7.18.4", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.4.tgz", - "integrity": "sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==", - "license": "MIT", - "dependencies": { - "cookie": "^1.0.1", - "set-cookie-parser": "^2.6.0" - }, - "engines": { - "node": ">=20.0.0" - }, - "peerDependencies": { - "react": ">=18", - "react-dom": ">=18" - }, - "peerDependenciesMeta": { - "react-dom": { - "optional": true - } - } - }, - "node_modules/react-router-dom": { - "version": "7.18.4", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.4.tgz", - "integrity": "sha512-yrfmJHIpDG7taCpqKjT1G5B6q3O2K+RN8/fgNf0lTjCwiPbQ0ei6vXX9ZjQR+7ld8Tr7Z5xmyMnZ8YJrphWQUw==", - "license": "MIT", - "dependencies": { - "react-router": "7.18.4" - }, - "engines": { - "node": ">=20.0.0" - }, - "peerDependencies": { - "react": ">=18", - "react-dom": ">=18" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/rolldown": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz", - "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@oxc-project/types": "=0.153.0", - "@rolldown/pluginutils": "^1.0.0" - }, - "bin": { - "rolldown": "bin/cli.mjs" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.13", - "@rolldown/binding-android-arm64": "1.2.13", - "@rolldown/binding-darwin-arm64": "1.2.13", - "@rolldown/binding-darwin-x64": "1.2.13", - "@rolldown/binding-freebsd-x64": "1.2.13", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.13", - "@rolldown/binding-linux-arm64-gnu": "1.2.13", - "@rolldown/binding-linux-arm64-musl": "1.2.13", - "@rolldown/binding-linux-ppc64-gnu": "1.2.13", - "@rolldown/binding-linux-s390x-gnu": "1.2.13", - "@rolldown/binding-linux-x64-gnu": "1.2.13", - "@rolldown/binding-linux-x64-musl": "1.2.13", - "@rolldown/binding-openharmony-arm64": "1.2.13", - "@rolldown/binding-win32-arm64-msvc": "1.2.13", - "@rolldown/binding-win32-x64-msvc": "1.2.13" - } - }, - "node_modules/saxes": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", - "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", - "dev": true, - "license": "ISC", - "dependencies": { - "xmlchars": "^2.2.0" - }, - "engines": { - "node": ">=v12.22.7" - } - }, - "node_modules/scheduler": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", - "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", - "license": "MIT" - }, - "node_modules/set-cookie-parser": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", - "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", - "license": "MIT" - }, - "node_modules/source-map-js": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", - "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/std-env": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", - "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", - "dev": true, - "license": "MIT" - }, - "node_modules/tailwindcss": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz", - "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/tapable": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", - "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/tinybench": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", - "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/tinyexec": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", - "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/tinyglobby": { - "version": "0.2.17", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", - "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.4" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/tldts": { - "version": "7.4.13", - "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.13.tgz", - "integrity": "sha512-iHtaIWWIbMDkCeJdTBzZFGgbluE5J+oHlb2g7+oAz1S1gpuVpabRZdQyd471Vl8UUkcz2vXSL8xZH2kyCe8tfA==", - "dev": true, - "license": "MIT", - "dependencies": { - "tldts-core": "^7.4.13" - }, - "bin": { - "tldts": "bin/cli.js" - } - }, - "node_modules/tldts-core": { - "version": "7.4.13", - "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.13.tgz", - "integrity": "sha512-mbYsrih5FRtGxs3Usvl/PqwJsNpp+jsmrdFviiK02teHDG0/HebBG/pqCylje3kzgXYzuLoHJF/0mz9W53t8Xg==", - "dev": true, - "license": "MIT" - }, - "node_modules/tough-cookie": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", - "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "tldts": "^7.0.5" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/tr46": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", - "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", - "dev": true, - "license": "MIT", - "dependencies": { - "punycode": "^2.3.1" - }, - "engines": { - "node": "^22.14.0 || >=24.0.0" - } - }, - "node_modules/typescript": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", - "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc" - }, - "engines": { - "node": ">=16.20.0" - }, - "optionalDependencies": { - "@typescript/typescript-aix-ppc64": "7.0.2", - "@typescript/typescript-darwin-arm64": "7.0.2", - "@typescript/typescript-darwin-x64": "7.0.2", - "@typescript/typescript-freebsd-arm64": "7.0.2", - "@typescript/typescript-freebsd-x64": "7.0.2", - "@typescript/typescript-linux-arm": "7.0.2", - "@typescript/typescript-linux-arm64": "7.0.2", - "@typescript/typescript-linux-loong64": "7.0.2", - "@typescript/typescript-linux-mips64el": "7.0.2", - "@typescript/typescript-linux-ppc64": "7.0.2", - "@typescript/typescript-linux-riscv64": "7.0.2", - "@typescript/typescript-linux-s390x": "7.0.2", - "@typescript/typescript-linux-x64": "7.0.2", - "@typescript/typescript-netbsd-arm64": "7.0.2", - "@typescript/typescript-netbsd-x64": "7.0.2", - "@typescript/typescript-openbsd-arm64": "7.0.2", - "@typescript/typescript-openbsd-x64": "7.0.2", - "@typescript/typescript-sunos-x64": "7.0.2", - "@typescript/typescript-win32-arm64": "7.0.2", - "@typescript/typescript-win32-x64": "7.0.2" - } - }, - "node_modules/undici": { - "version": "8.11.2", - "resolved": "https://registry.npmjs.org/undici/-/undici-8.11.2.tgz", - "integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=22.19.0" - } - }, - "node_modules/undici-types": { - "version": "7.18.2", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", - "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", - "dev": true, - "license": "MIT" - }, - "node_modules/vite": { - "version": "8.3.4", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz", - "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "lightningcss": "^1.33.0", - "picomatch": "^4.0.7", - "postcss": "^8.5.29", - "rolldown": "~1.2.12", - "tinyglobby": "^0.2.17" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.7.1", - "esbuild": "^0.27.0 || ^0.28.0", - "jiti": ">=1.21.0", - "less": "^4.0.0", - "sass": "^1.70.0", - "sass-embedded": "^1.70.0", - "stylus": ">=0.54.8", - "sugarss": "^5.0.0", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "@vitejs/devtools": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/vite/node_modules/lightningcss": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", - "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.33.0", - "lightningcss-darwin-arm64": "1.33.0", - "lightningcss-darwin-x64": "1.33.0", - "lightningcss-freebsd-x64": "1.33.0", - "lightningcss-linux-arm-gnueabihf": "1.33.0", - "lightningcss-linux-arm64-gnu": "1.33.0", - "lightningcss-linux-arm64-musl": "1.33.0", - "lightningcss-linux-x64-gnu": "1.33.0", - "lightningcss-linux-x64-musl": "1.33.0", - "lightningcss-win32-arm64-msvc": "1.33.0", - "lightningcss-win32-x64-msvc": "1.33.0" - } - }, - "node_modules/vite/node_modules/lightningcss-android-arm64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", - "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-darwin-arm64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", - "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-darwin-x64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", - "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-freebsd-x64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", - "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", - "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", - "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-linux-arm64-musl": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", - "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-linux-x64-gnu": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", - "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-linux-x64-musl": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", - "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", - "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vite/node_modules/lightningcss-win32-x64-msvc": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", - "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/vitest": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.4.tgz", - "integrity": "sha512-z0WxZRV2Sg48wF0FSgMq3TFG8JS38/Qr96vZVZdX6+Em9raQTvnXQvdTFJe2m3rfyJnEHeHQ/snceIdi8D1pVg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/chai": "^5.2.2", - "@vitest/mocker": "5.0.4", - "chai": "^6.3.0", - "es-module-lexer": "^2.3.2", - "expect-type": "^1.4.0", - "magic-string": "^1.4.3", - "obug": "^3.0.0", - "picomatch": "^4.0.7", - "std-env": "^4.3.0", - "tinybench": "^6.2.2", - "tinyexec": "^1.3.1", - "tinyglobby": "^0.2.17", - "why-is-node-running": "3.2.1" - }, - "bin": { - "vitest": "vitest.mjs" - }, - "engines": { - "node": "^22.12.0 || ^24.0.0 || >=26.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "@edge-runtime/vm": "*", - "@opentelemetry/api": "^1.9.0", - "@types/node": "^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "5.0.4", - "@vitest/browser-preview": "5.0.4", - "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", - "@vitest/coverage-istanbul": "5.0.4", - "@vitest/coverage-v8": "5.0.4", - "@vitest/ui": "5.0.4", - "happy-dom": "*", - "jsdom": "*", - "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "@edge-runtime/vm": { - "optional": true - }, - "@opentelemetry/api": { - "optional": true - }, - "@types/node": { - "optional": true - }, - "@vitest/browser-playwright": { - "optional": true - }, - "@vitest/browser-preview": { - "optional": true - }, - "@vitest/browser-webdriverio": { - "optional": true - }, - "@vitest/coverage-istanbul": { - "optional": true - }, - "@vitest/coverage-v8": { - "optional": true - }, - "@vitest/ui": { - "optional": true - }, - "happy-dom": { - "optional": true - }, - "jsdom": { - "optional": true - }, - "vite": { - "optional": false - } - } - }, - "node_modules/vitest/node_modules/magic-string": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", - "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.6.0" - } - }, - "node_modules/w3c-xmlserializer": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", - "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "xml-name-validator": "^5.0.0" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, - "node_modules/webidl-conversions": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", - "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=20" - } - }, - "node_modules/whatwg-mimetype": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", - "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/whatwg-url": { - "version": "17.2.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.2.0.tgz", - "integrity": "sha512-IhLIHNcBrzIixC5XXsbr4DxdjajyA5vQ5RwGZMtrUp+GbtE5Nrsge9QKau7jXrC0aTXLYGV0xiW7Tb4YS2aomw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@exodus/bytes": "^1.16.0", - "tr46": "^7.0.0", - "webidl-conversions": "^8.0.1" - }, - "engines": { - "node": "^22.14.0 || >=24.0.0" - } - }, - "node_modules/why-is-node-running": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", - "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", - "dev": true, - "license": "MIT", - "bin": { - "why-is-node-running": "cli.js" - }, - "engines": { - "node": ">=20.11" - } - }, - "node_modules/xml-name-validator": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", - "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/xmlchars": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", - "dev": true, - "license": "MIT" - } - } -} diff --git a/bazaarplusplus-installer/package.json b/bazaarplusplus-installer/package.json deleted file mode 100644 index a87fd34..0000000 --- a/bazaarplusplus-installer/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "name": "bppinstaller", - "version": "6.0.0", - "description": "BazaarPlusPlus Desktop App", - "type": "module", - "packageManager": "npm@12.0.2", - "engines": { - "node": ">=24.15.0 <25", - "npm": ">=12 <13" - }, - "scripts": { - "generate:bindings": "node scripts/generate-bindings.mjs", - "generate:bindings:test": "node scripts/generate-bindings.mjs --with-rust-tests", - "generate:bindings:if-stale": "node scripts/generate-bindings.mjs --if-stale", - "dev": "npm run generate:bindings:if-stale && vite dev", - "prepare:resources": "node ../release.mjs prepare", - "check:bindings": "node scripts/checks/prebuild-check.mjs --bindings-only", - "prebuild-check": "npm run generate:bindings && npm run prebuild-check:after-bindings", - "prebuild-check:after-bindings": "node scripts/checks/prebuild-check.mjs", - "prebuild-check:source:after-bindings": "node scripts/checks/prebuild-check.mjs --source-only", - "build": "npm run generate:bindings && npm run build:after-bindings", - "build:after-bindings": "npm run prebuild-check:after-bindings && npm run check:ts && npm run build:frontend", - "build:frontend": "vite build", - "test": "npm run generate:bindings:test && npm run check:bindings && npm run test:unit", - "test:unit": "vitest run", - "format": "prettier --write \"*.json\" \"src/**/*.{ts,tsx,html}\" \"scripts/**/*.mjs\" \"src-tauri/*.json\" \"src-tauri/capabilities/**/*.json\" \"vite.config.ts\"", - "format:check": "prettier --check \"*.json\" \"src/**/*.{ts,tsx,html}\" \"scripts/**/*.mjs\" \"src-tauri/*.json\" \"src-tauri/capabilities/**/*.json\" \"vite.config.ts\"", - "lint": "oxlint --type-aware", - "lint:fix": "oxlint --type-aware --fix", - "check:ts": "tsc --noEmit", - "verify": "node scripts/checks/verify.mjs", - "docs:check": "node scripts/checks/docs-check.mjs", - "tauri": "tauri" - }, - "license": "MIT", - "dependencies": { - "@tauri-apps/api": "^2.12.3", - "@tauri-apps/plugin-opener": "^2.7.1", - "@tauri-apps/plugin-process": "^2.4.0", - "@tauri-apps/plugin-updater": "^2.13.3", - "clsx": "^2.1.1", - "lucide-react": "^1.47.0", - "react": "^19.3.0", - "react-dom": "^19.3.0", - "react-router-dom": "^7.18.4" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.3.3", - "@tauri-apps/cli": "^2.11.4", - "@types/node": "^24.13.3", - "@types/react": "^19.3.0", - "@types/react-dom": "^19.3.0", - "@vitejs/plugin-react": "^6.1.2", - "jsdom": "^30.1.2", - "oxlint": "^1.83.0", - "oxlint-tsgolint": "^7.0.2004", - "prettier": "^3.9.10", - "tailwindcss": "^4.3.3", - "typescript": "^7.0.2", - "vite": "^8.3.4", - "vitest": "^5.0.4" - } -} diff --git a/bazaarplusplus-installer/rust-toolchain.toml b/bazaarplusplus-installer/rust-toolchain.toml deleted file mode 100644 index b0cd3b6..0000000 --- a/bazaarplusplus-installer/rust-toolchain.toml +++ /dev/null @@ -1,4 +0,0 @@ -[toolchain] -channel = "1.98.1" -components = ["clippy", "rustfmt"] -profile = "minimal" diff --git a/bazaarplusplus-installer/scripts/bundle.sh b/bazaarplusplus-installer/scripts/bundle.sh deleted file mode 100644 index 8ccc451..0000000 --- a/bazaarplusplus-installer/scripts/bundle.sh +++ /dev/null @@ -1,569 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Signs and bundles the installer for the host platform. Internal to the product -# coordinator: `just release::build ` (node release.mjs build) holds the -# build lock, prepares the Payload, then runs this script with BPP_RELEASE_LOCK_TOKEN. -# Functions are sourced directly by scripts/bundle.test.mjs. It lives outside -# scripts/release/ because signing is not a Payload input. - -INSTALLER_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -MACOS_TRAMPOLINE_STUB="$INSTALLER_ROOT/src-tauri/resources/Trampoline/macos/bpp_launcher" -SIGNING_SECRETS_DIR="${BPP_SIGNING_SECRETS_DIR:-$INSTALLER_ROOT/signing-secrets}" -SIGNING_KEY_PATH="$SIGNING_SECRETS_DIR/tauri-updater.key" -SIGNING_KEY_PASSWORD_PATH="$SIGNING_SECRETS_DIR/tauri-updater.password" -APPLE_API_ISSUER_PATH="$SIGNING_SECRETS_DIR/apple-api-issuer" -APPLE_API_KEY_ID_PATH="$SIGNING_SECRETS_DIR/apple-api-key" -APPLE_API_KEY_PATH_PATH="$SIGNING_SECRETS_DIR/apple-api-key-path" -APPLE_SIGNING_IDENTITY_PATH="$SIGNING_SECRETS_DIR/apple-signing-identity" -OFFICIAL_APPLE_TEAM_ID="9Z44S3N293" -MACOS_GAME_APP_OVERLAY="TheBazaar.app" - -assert_command() { - local name="$1" - local hint="${2:-}" - if ! command -v "$name" &>/dev/null; then - if [ -n "$hint" ]; then - echo "Error: $name not found. $hint" >&2 - else - echo "Error: $name not found." >&2 - fi - exit 1 - fi -} - -assert_file() { - local path="$1" - local label="$2" - if [ ! -f "$path" ]; then - echo "Error: Missing $label: $path" >&2 - exit 1 - fi -} - -invoke_step() { - local label="$1" - shift - echo "==> $label" - "$@" -} - -trim_trailing_newlines() { - local value="$1" - - while [[ "$value" == *$'\n' || "$value" == *$'\r' ]]; do - value="${value%$'\n'}" - value="${value%$'\r'}" - done - - printf '%s' "$value" -} - -set_exported_env() { - local name="$1" - local value="$2" - - printf -v "$name" '%s' "$value" - export "$name" -} - -# load_secret_env [optional]: reuse an exported value, else read the -# ignored signing-secrets file. An optional secret defaults to empty. -load_secret_env() { - local name="$1" - local path="$2" - local optional="${3:-}" - local value="${!name:-}" - - if [ -n "$value" ]; then - echo "==> Reusing existing $name from environment" - elif [ -f "$path" ]; then - echo "==> Loading $name from signing-secrets" - value="$(<"$path")" - elif [ -n "$optional" ]; then - echo "==> No $name configured; using empty value" - set_exported_env "$name" "" - return - else - echo "Error: Missing $name." >&2 - echo "Set $name or create $path" >&2 - exit 1 - fi - - value="$(trim_trailing_newlines "$value")" - if [ -z "$value" ] && [ -z "$optional" ]; then - echo "Error: Empty $name." >&2 - echo "Set $name or write a value to $path" >&2 - exit 1 - fi - - set_exported_env "$name" "$value" -} - -current_platform() { - case "$(uname -s)" in - Darwin) echo "macos" ;; - MINGW*|MSYS*|CYGWIN*|Windows_NT) echo "windows" ;; - *) echo "unknown" ;; - esac -} - -release_platforms_cli() { - node "$INSTALLER_ROOT/../release/release-platforms.mjs" "$@" -} - -install_dependencies() { - if [ ! -f "$INSTALLER_ROOT/package-lock.json" ]; then - echo "Error: package-lock.json is required for a reproducible dependency install; refusing to run npm install." >&2 - return 1 - fi - - invoke_step "Installing npm dependencies" npm ci -} - -ensure_required_rust_targets() { - local platform="$1" - local installed_targets="" - local required_targets="" - local required_target="" - - required_targets="$(release_platforms_cli rust-targets "$platform")" - if [ -z "${required_targets//[[:space:]]/}" ]; then - return 0 - fi - - installed_targets="$(rustup target list --installed)" - while IFS= read -r required_target; do - [ -n "$required_target" ] || continue - if ! grep -Fxq "$required_target" <<<"$installed_targets"; then - echo "Error: Missing Rust target: $required_target" >&2 - echo "Run: rustup target add $required_target" >&2 - return 1 - fi - done <<<"$required_targets" -} - -load_updater_signing_env() { - load_secret_env TAURI_SIGNING_PRIVATE_KEY "$SIGNING_KEY_PATH" - load_secret_env TAURI_SIGNING_PRIVATE_KEY_PASSWORD "$SIGNING_KEY_PASSWORD_PATH" optional -} - -detect_developer_id_application_identity() { - security find-identity -v -p codesigning 2>/dev/null \ - | sed -n 's/.*"\(Developer ID Application: [^"]*\)".*/\1/p' \ - | sort -u -} - -load_apple_signing_identity_env() { - local value="${APPLE_SIGNING_IDENTITY:-}" - local identities="" - local identity_count="" - - if [ -n "$value" ]; then - echo "==> Reusing existing APPLE_SIGNING_IDENTITY from environment" - elif [ -f "$APPLE_SIGNING_IDENTITY_PATH" ]; then - echo "==> Loading APPLE_SIGNING_IDENTITY from signing-secrets" - value="$(<"$APPLE_SIGNING_IDENTITY_PATH")" - else - identities="$(detect_developer_id_application_identity)" - identity_count="$(printf '%s\n' "$identities" | sed '/^$/d' | wc -l | tr -d ' ')" - - case "$identity_count" in - 1) - echo "==> Auto-detected APPLE_SIGNING_IDENTITY from keychain" - value="$identities" - ;; - 0) - echo "Error: Missing APPLE_SIGNING_IDENTITY." >&2 - echo "Set APPLE_SIGNING_IDENTITY, create $APPLE_SIGNING_IDENTITY_PATH, or install a Developer ID Application certificate." >&2 - exit 1 - ;; - *) - echo "Error: Multiple Developer ID Application identities found." >&2 - echo "Set APPLE_SIGNING_IDENTITY or create $APPLE_SIGNING_IDENTITY_PATH with the exact identity to use." >&2 - printf '%s\n' "$identities" >&2 - exit 1 - ;; - esac - fi - - value="$(trim_trailing_newlines "$value")" - if [ -z "$value" ]; then - echo "Error: Empty APPLE_SIGNING_IDENTITY." >&2 - echo "Set APPLE_SIGNING_IDENTITY or write a value to $APPLE_SIGNING_IDENTITY_PATH" >&2 - exit 1 - fi - - set_exported_env APPLE_SIGNING_IDENTITY "$value" -} - -load_apple_api_key_path_env() { - local value="${APPLE_API_KEY_PATH:-}" - local inferred_path="" - - if [ -n "$value" ]; then - echo "==> Reusing existing APPLE_API_KEY_PATH from environment" - elif [ -f "$APPLE_API_KEY_PATH_PATH" ]; then - echo "==> Loading APPLE_API_KEY_PATH from signing-secrets" - value="$(<"$APPLE_API_KEY_PATH_PATH")" - else - inferred_path="$SIGNING_SECRETS_DIR/AuthKey_${APPLE_API_KEY}.p8" - if [ -f "$inferred_path" ]; then - echo "==> Inferring APPLE_API_KEY_PATH from signing-secrets" - value="$inferred_path" - else - echo "Error: Missing APPLE_API_KEY_PATH." >&2 - echo "Set APPLE_API_KEY_PATH, create $APPLE_API_KEY_PATH_PATH, or place AuthKey_${APPLE_API_KEY}.p8 in $SIGNING_SECRETS_DIR" >&2 - exit 1 - fi - fi - - value="$(trim_trailing_newlines "$value")" - if [ -z "$value" ]; then - echo "Error: Empty APPLE_API_KEY_PATH." >&2 - echo "Set APPLE_API_KEY_PATH or write a value to $APPLE_API_KEY_PATH_PATH" >&2 - exit 1 - fi - - if [[ "$value" != /* ]]; then - value="$INSTALLER_ROOT/$value" - fi - - set_exported_env APPLE_API_KEY_PATH "$value" - assert_file "$APPLE_API_KEY_PATH" "Apple API key file" -} - -load_macos_developer_id_env() { - load_apple_signing_identity_env - load_secret_env APPLE_API_ISSUER "$APPLE_API_ISSUER_PATH" - load_secret_env APPLE_API_KEY "$APPLE_API_KEY_ID_PATH" - load_apple_api_key_path_env -} - -is_macho_file() { - local file_path="$1" - - file "$file_path" | grep -q 'Mach-O' -} - -macos_resource_relative_path() { - local resource_path="$1" - local resource_root="$INSTALLER_ROOT/src-tauri/resources/" - - if [[ "$resource_path" == "$resource_root"* ]]; then - printf '%s' "${resource_path#$resource_root}" - else - printf '%s' "$resource_path" - fi -} - -sign_macos_resource_binary() { - local binary_path="$1" - local relative_path="$2" - - invoke_step "Signing macOS resource binary $relative_path" \ - codesign --force --options runtime --timestamp \ - --sign "$APPLE_SIGNING_IDENTITY" "$binary_path" -} - -codesign_details() { - local code_path="$1" - codesign -dvvv "$code_path" 2>&1 -} - -assert_official_codesign_team_id() { - local code_path="$1" - local details="" - local actual_team_id="" - - details="$(codesign_details "$code_path")" - actual_team_id="$(sed -n 's/^TeamIdentifier=//p' <<<"$details" | head -n 1)" - if [ "$actual_team_id" != "$OFFICIAL_APPLE_TEAM_ID" ]; then - echo "Error: Official macOS release code must use TeamIdentifier=$OFFICIAL_APPLE_TEAM_ID." >&2 - echo "Found TeamIdentifier=${actual_team_id:-missing} for $code_path" >&2 - exit 1 - fi -} - -assert_ad_hoc_replay_recorder_input() { - local plugin_bundle="$1" - local details="" - - if ! codesign --verify --deep --strict --verbose=2 "$plugin_bundle"; then - echo "Error: Replay recorder plugin input has an invalid ad-hoc signature: $plugin_bundle" >&2 - exit 1 - fi - details="$(codesign_details "$plugin_bundle")" - if ! grep -q '^Signature=adhoc$' <<<"$details" \ - || ! grep -q '^TeamIdentifier=not set$' <<<"$details"; then - echo "Error: Replay recorder plugin input must be ad-hoc signed with no TeamIdentifier." >&2 - exit 1 - fi -} - -# Pre-signs Mach-O binaries that live inside bundled resource zips. Tauri treats -# zips as opaque resource data, so its outer .app signing never reaches these. -# Notarization and runtime library validation reject unsigned nested code. -sign_macos_resource_binaries() { - local payload_dir="$1" - local binary_path="" - local relative_path="" - - while IFS= read -r -d '' binary_path; do - if ! is_macho_file "$binary_path"; then - continue - fi - - relative_path="${binary_path#$payload_dir/}" - sign_macos_resource_binary "$binary_path" "$relative_path" - done < <(find "$payload_dir" \( -type d -name '*.app' -o -type d -name '*.bundle' \) -prune -o -type f -print0) -} - -# Signs every Mach-O file inside a bundle, then the bundle itself, then verifies it, -# so Contents/_CodeSignature/CodeResources matches the final executable bytes. -sign_macos_bundle_inside_out() { - local payload_dir="$1" - local bundle="$2" - local kind="$3" - local relative_path="${bundle#$payload_dir/}" - local binary_path="" - - while IFS= read -r -d '' binary_path; do - if is_macho_file "$binary_path"; then - sign_macos_resource_binary "$binary_path" "${binary_path#$payload_dir/}" - fi - done < <(find "$bundle/Contents" -type f -print0) - - invoke_step "Signing macOS resource $kind bundle $relative_path" \ - codesign --force --options runtime --timestamp \ - --sign "$APPLE_SIGNING_IDENTITY" "$bundle" - invoke_step "Verifying macOS resource $kind bundle $relative_path" \ - codesign --verify --deep --strict --verbose=2 "$bundle" -} - -sign_macos_resource_app_bundles() { - local payload_dir="$1" - local app_bundle="" - - while IFS= read -r -d '' app_bundle; do - # This is an install-path overlay, not a complete application bundle. - if [ "${app_bundle#$payload_dir/}" != "$MACOS_GAME_APP_OVERLAY" ]; then - sign_macos_bundle_inside_out "$payload_dir" "$app_bundle" app - fi - done < <(find "$payload_dir" -type d -name '*.app' -prune -print0) -} - -sign_macos_resource_plugin_bundles() { - local payload_dir="$1" - local replay_recorder_bundle="$2" - local plugin_bundle="" - local plugin_relative_path="" - - while IFS= read -r -d '' plugin_bundle; do - plugin_relative_path="${plugin_bundle#$payload_dir/}" - if [ "$plugin_relative_path" = "$replay_recorder_bundle" ]; then - assert_ad_hoc_replay_recorder_input "$plugin_bundle" - fi - - sign_macos_bundle_inside_out "$payload_dir" "$plugin_bundle" plugin - - if [ "$plugin_relative_path" = "$replay_recorder_bundle" ]; then - assert_official_codesign_team_id \ - "$plugin_bundle/Contents/MacOS/GfxPluginBppReplayVideoToolbox" - assert_official_codesign_team_id "$plugin_bundle" - fi - done < <(find "$payload_dir" -type d -name '*.bundle' -prune -print0) -} - -prepare_signed_macos_resource_binary() { - local resource_binary="$1" - local relative_path="" - - assert_command file "Install file first." - assert_command codesign "Install Xcode command line tools first." - assert_file "$resource_binary" "macOS resource binary" - - if ! is_macho_file "$resource_binary"; then - echo "Error: macOS resource binary is not Mach-O: $resource_binary" >&2 - exit 1 - fi - - relative_path="$(macos_resource_relative_path "$resource_binary")" - sign_macos_resource_binary "$resource_binary" "$relative_path" - assert_official_codesign_team_id "$resource_binary" -} - -create_zip_from_directory() { - local source_dir="$1" - local output_zip="$2" - local output_manifest="$3" - - node "$INSTALLER_ROOT/../release/payload-zip.mjs" pack \ - --source "$source_dir" --output "$output_zip" \ - --manifest-output "$output_manifest" --platform macos -} - -prepare_signed_macos_resource_zip() { - local resource_zip="$1" - local temp_dir="" - local payload_dir="" - local signed_zip="" - local signed_manifest="" - local resource_manifest="${resource_zip}.manifest.json" - local replay_recorder_bundle="" - - assert_command ditto "Install macOS command line tools first." - assert_command file "Install file first." - assert_command codesign "Install Xcode command line tools first." - assert_command plutil "Install macOS command line tools first." - assert_command spctl "Install macOS command line tools first." - assert_command xcrun "Install Xcode command line tools first." - assert_file "$resource_zip" "macOS resource zip" - - temp_dir="$(mktemp -d)" - payload_dir="$temp_dir/payload" - signed_zip="$temp_dir/BepInEx.zip" - signed_manifest="$temp_dir/BepInEx.zip.manifest.json" - mkdir -p "$payload_dir" - trap 'rm -rf "$temp_dir"' RETURN - - replay_recorder_bundle="$(release_platforms_cli replay-recorder-bundle macos)" - invoke_step "Extracting macOS resource zip for signing" \ - ditto -x -k "$resource_zip" "$payload_dir" - assert_ad_hoc_replay_recorder_input \ - "$payload_dir/$replay_recorder_bundle" - sign_macos_resource_binaries "$payload_dir" - sign_macos_resource_plugin_bundles "$payload_dir" "$replay_recorder_bundle" - sign_macos_resource_app_bundles "$payload_dir" - invoke_step "Repacking signed macOS resource zip" \ - create_zip_from_directory "$payload_dir" "$signed_zip" "$signed_manifest" - invoke_step "Replacing macOS resource zip and checksum manifest with signed copies" \ - mv "$signed_zip" "$resource_zip" - mv "$signed_manifest" "$resource_manifest" - - rm -rf "$temp_dir" - trap - RETURN -} - -run_release_prechecks() { - local platform="$1" - invoke_step "Checking product build ownership" node "$INSTALLER_ROOT/../release.mjs" assert-build-owner - invoke_step "Running authoritative release verification" \ - npm run verify -- --release-platform "$platform" -} - -build_prod() { - local platform="$1" - local config="" - local resource_zip="" - local bundle_target="" - local bundle_output="" - local bundle_cleanup_path="" - local release_binary="" - local tauri_target="" - local release_config="$INSTALLER_ROOT/src-tauri/tauri.release.conf.json" - local -a build_command - local -a bundle_command - - if ! { - IFS= read -r config - IFS= read -r resource_zip - IFS= read -r bundle_target - IFS= read -r bundle_output - IFS= read -r bundle_cleanup_path - IFS= read -r release_binary - IFS= read -r tauri_target - } < <(release_platforms_cli build-env "$platform"); then - echo "Error: Unsupported platform: $platform" >&2 - exit 1 - fi - - if [ -z "$config" ] || [ -z "$resource_zip" ] || [ -z "$bundle_target" ] \ - || [ -z "$bundle_output" ] || [ -z "$bundle_cleanup_path" ] || [ -z "$release_binary" ]; then - echo "Error: Unsupported platform: $platform" >&2 - exit 1 - fi - - config="$INSTALLER_ROOT/$config" - resource_zip="$INSTALLER_ROOT/$resource_zip" - bundle_output="$INSTALLER_ROOT/$bundle_output" - bundle_cleanup_path="$INSTALLER_ROOT/$bundle_cleanup_path" - release_binary="$INSTALLER_ROOT/$release_binary" - - assert_file "$config" "$platform Tauri config" - assert_file "$resource_zip" "$platform resource zip" - assert_file "$release_config" "release Tauri config" - - if [ -d "$bundle_cleanup_path" ]; then - invoke_step "Removing stale $platform bundle artifacts" rm -rf "$bundle_cleanup_path" - fi - - build_command=( - npm run tauri build -- --no-bundle --config "$config" --config "$release_config" - ) - bundle_command=( - npm run tauri bundle -- --bundles "$bundle_target" --config "$config" --config "$release_config" - ) - - if [ -n "$tauri_target" ]; then - build_command+=(--target "$tauri_target") - bundle_command+=(--target "$tauri_target") - fi - - invoke_step "Building $platform app binary" "${build_command[@]}" - - if [ "$platform" = "macos" ]; then - prepare_signed_macos_resource_zip "$resource_zip" - prepare_signed_macos_resource_binary "$MACOS_TRAMPOLINE_STUB" - fi - - invoke_step "Bundling $platform installer" "${bundle_command[@]}" - - echo - echo "Build complete." - echo "Binary: $release_binary" - echo "Bundle: $bundle_output" -} - -main() { - local platform="" - - if [ "$#" -gt 0 ]; then - echo "Error: bundle.sh takes no arguments; run just release::build ." >&2 - exit 2 - fi - if [ -z "${BPP_RELEASE_LOCK_TOKEN:-}" ]; then - echo "Error: bundle.sh runs inside the product build lock; run just release::build ." >&2 - exit 1 - fi - - cd "$INSTALLER_ROOT" - node "$INSTALLER_ROOT/../release.mjs" assert-build-owner - - assert_command node "Install Node.js first." - assert_command npm "Install Node.js/npm first." - node scripts/checks/check-toolchain.mjs "$(node --version)" "$(npm --version)" - assert_command cargo "Install Rust toolchain first." - - platform="$(current_platform)" - if [ "$platform" = "unknown" ]; then - echo "Error: Unsupported host platform: $(uname -s)" >&2 - exit 1 - fi - if [ "$platform" = "macos" ]; then - assert_command rustup "Install rustup first so the macOS Rust target can be managed." - fi - - install_dependencies - load_updater_signing_env - if [ "$platform" = "macos" ]; then - load_macos_developer_id_env - fi - run_release_prechecks "$platform" - ensure_required_rust_targets "$platform" - build_prod "$platform" -} - -if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then - main "$@" -fi diff --git a/bazaarplusplus-installer/scripts/bundle.test.mjs b/bazaarplusplus-installer/scripts/bundle.test.mjs deleted file mode 100644 index 51835b1..0000000 --- a/bazaarplusplus-installer/scripts/bundle.test.mjs +++ /dev/null @@ -1,291 +0,0 @@ -import { test, expect } from 'vitest'; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { relative } from 'node:path'; -import { runShell, toBashPath } from './test-support/shell.mjs'; - -const projectDir = process.cwd(); - -// Runs the callback against an ISOLATED, throwaway signing-secrets directory so -// tests never read, write, or restore the developer's real signing-secrets/. -// (The old backup/restore approach clobbered real keys whenever a run was -// interrupted before its finally block ran.) The temp dir lives under the -// project root with a `signing-secrets` leaf, so bundle.sh's INSTALLER_ROOT-relative -// resolution of a relative apple-api-key-path still lands inside the fixtures. -// `files` may be an object or a `(ctx) => object` builder that needs the paths; -// `fn` receives the same ctx { dir, dirBash, relBash }. -function withSigningSecretFiles(files, fn) { - const base = mkdtempSync( - `${projectDir}/.bpp-signing-test-'$(printf injected)-` - ); - const dir = `${base}/signing-secrets`; - mkdirSync(dir, { recursive: true }); - - const dirBash = process.platform === 'win32' ? toBashPath(dir) : dir; - const rel = relative(projectDir, dir); - const relBash = process.platform === 'win32' ? toBashPath(rel) : rel; - const ctx = { dir, dirBash, relBash }; - - const resolved = typeof files === 'function' ? files(ctx) : files; - for (const [name, content] of Object.entries(resolved)) { - writeFileSync(`${dir}/${name}`, content); - } - - try { - fn(ctx); - } finally { - rmSync(base, { recursive: true, force: true }); - } -} - -test('macOS production build stops at the first resource-signing failure', () => { - const output = runShell(` - set -euo pipefail - source ./scripts/bundle.sh - assert_file() { :; } - invoke_step() { - local label="$1" - shift - printf '%s|%s\\n' "$label" "$*" - } - prepare_signed_macos_resource_zip() { - printf 'resource-signing:start\\n' - false - printf 'resource-signing:continued\\n' - } - prepare_signed_macos_resource_binary() { - printf 'trampoline-signing:started\\n' - } - failure_log="$(mktemp)" - trap 'rm -f "$failure_log"' EXIT - set +e - (set -e; build_prod macos) >"$failure_log" 2>&1 - status="$?" - set -e - cat "$failure_log" - printf 'exit:%s\\n' "$status" - `); - - expect(output).toContain('resource-signing:start'); - expect(output).toContain('exit:1'); - expect(output).not.toContain('resource-signing:continued'); - expect(output).not.toContain('trampoline-signing:started'); - expect(output).not.toContain('Bundling macos installer'); -}); - -test('macOS production build requires the arm64 Rust target', () => { - const output = runShell(` - source ./scripts/bundle.sh - set +e - rustup() { - printf '%s\\n' x86_64-apple-darwin - } - ensure_required_rust_targets macos >/tmp/bpp-build-test.out 2>/tmp/bpp-build-test.err - status="$?" - cat /tmp/bpp-build-test.out - cat /tmp/bpp-build-test.err - printf 'exit:%s\\n' "$status" - `); - - expect(output).toMatch(/Missing Rust target: aarch64-apple-darwin/); - expect(output).toMatch(/rustup target add aarch64-apple-darwin/); - expect(output).toMatch(/exit:1/); -}); - -test('dependency install fails clearly instead of updating an absent lockfile', () => { - const root = mkdtempSync(`${projectDir}/.bpp-deps-test-'$(printf injected)-`); - const rootBash = toBashPath(root); - - try { - const output = runShell( - ` - source ./scripts/bundle.sh - INSTALLER_ROOT="$BPP_TEST_INSTALLER_ROOT" - set +e - install_dependencies 2>&1 - printf 'exit:%s\\n' "$?" - `, - { BPP_TEST_INSTALLER_ROOT: rootBash } - ); - expect(output).toContain('package-lock.json is required'); - expect(output).toContain('exit:1'); - } finally { - rmSync(root, { recursive: true, force: true }); - } -}); - -test('macOS release rejects a replay recorder plugin signed by a local Developer ID', () => { - const output = runShell(` - set -euo pipefail - source ./scripts/bundle.sh - bundle="$(mktemp -d)/GfxPluginBppReplayVideoToolbox.bundle" - mkdir -p "$bundle/Contents" - codesign() { - printf '%s\\n' 'Signature size=8995' 'TeamIdentifier=WRONGTEAM1' >&2 - } - set +e - (assert_ad_hoc_replay_recorder_input "$bundle") 2>&1 - printf 'exit:%s\\n' "$?" - `); - - expect(output).toContain( - 'Replay recorder plugin input must be ad-hoc signed with no TeamIdentifier' - ); - expect(output).toContain('exit:1'); -}); -test('macOS Developer ID env loads from signing-secrets files', () => { - withSigningSecretFiles( - ({ relBash }) => ({ - 'apple-api-issuer': 'issuer-from-file\n', - 'apple-api-key': 'KEYFROMFILE\n', - 'apple-api-key-path': `${relBash}/AuthKey_KEYFROMFILE.p8\n`, - 'apple-signing-identity': - 'Developer ID Application: Example Builder (TEAMID1234)\n', - 'AuthKey_KEYFROMFILE.p8': 'private key' - }), - ({ dirBash }) => { - const output = runShell( - ` - set -euo pipefail - unset APPLE_API_ISSUER APPLE_API_KEY APPLE_API_KEY_PATH APPLE_SIGNING_IDENTITY - source ./scripts/bundle.sh - load_macos_developer_id_env >/tmp/bpp-apple-env-test.out - cat /tmp/bpp-apple-env-test.out - printf 'issuer=%s\\n' "$APPLE_API_ISSUER" - printf 'key=%s\\n' "$APPLE_API_KEY" - printf 'key_path=%s\\n' "$APPLE_API_KEY_PATH" - printf 'identity=%s\\n' "$APPLE_SIGNING_IDENTITY" - `, - { BPP_SIGNING_SECRETS_DIR: dirBash } - ); - - expect(output).toContain( - 'Loading APPLE_SIGNING_IDENTITY from signing-secrets' - ); - expect(output).toContain('Loading APPLE_API_ISSUER from signing-secrets'); - expect(output).toContain('Loading APPLE_API_KEY from signing-secrets'); - expect(output).toContain( - 'Loading APPLE_API_KEY_PATH from signing-secrets' - ); - expect(output).toContain('issuer=issuer-from-file'); - expect(output).toContain('key=KEYFROMFILE'); - // A relative key path in signing-secrets is exported as absolute: a - // POSIX root, or a drive root under Git Bash on Windows. - expect(output).toMatch( - /key_path=(?:\/|[A-Za-z]:[/\\]).*[/\\]signing-secrets[/\\]AuthKey_KEYFROMFILE\.p8/ - ); - expect(output).toContain( - 'identity=Developer ID Application: Example Builder (TEAMID1234)' - ); - } - ); -}); - -test('macOS Developer ID env detects identity and infers API key path', () => { - withSigningSecretFiles( - { - 'apple-api-issuer': 'issuer-from-file\n', - 'apple-api-key': 'AUTOKEY\n', - 'AuthKey_AUTOKEY.p8': 'private key' - }, - ({ dirBash }) => { - const output = runShell( - ` - set -euo pipefail - unset APPLE_API_ISSUER APPLE_API_KEY APPLE_API_KEY_PATH APPLE_SIGNING_IDENTITY - source ./scripts/bundle.sh - security() { - printf '%s\\n' ' 1) ABC "Apple Development: dev@example.com (TEAMID1234)"' - printf '%s\\n' ' 2) DEF "Developer ID Application: Example Builder (TEAMID1234)"' - } - load_macos_developer_id_env >/tmp/bpp-apple-env-test.out - cat /tmp/bpp-apple-env-test.out - printf 'key_path=%s\\n' "$APPLE_API_KEY_PATH" - printf 'identity=%s\\n' "$APPLE_SIGNING_IDENTITY" - `, - { BPP_SIGNING_SECRETS_DIR: dirBash } - ); - - expect(output).toContain( - 'Auto-detected APPLE_SIGNING_IDENTITY from keychain' - ); - expect(output).toContain( - 'Inferring APPLE_API_KEY_PATH from signing-secrets' - ); - expect(output).toMatch( - /key_path=.*[/\\]signing-secrets[/\\]AuthKey_AUTOKEY\.p8/ - ); - expect(output).toContain( - 'identity=Developer ID Application: Example Builder (TEAMID1234)' - ); - } - ); -}); - -test('release prechecks require the product build lock before verification', () => { - const output = runShell(` - set -euo pipefail - source ./scripts/bundle.sh - invoke_step() { - local label="$1" - shift - printf '%s|%s\\n' "$label" "$*" - } - run_release_prechecks windows - `); - expect(output).not.toContain('release.mjs check'); - expect(output).toContain('release.mjs assert-build-owner'); - expect(output).toContain('npm run verify -- --release-platform windows'); - expect(output).not.toContain('prepare:resources'); -}); - -test('updater signing env requires the key and defaults the password to empty', () => { - withSigningSecretFiles( - { 'tauri-updater.key': 'updater-key\n\n' }, - ({ dirBash }) => { - const output = runShell( - ` - set -euo pipefail - unset TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD - source ./scripts/bundle.sh - load_updater_signing_env - printf 'key=[%s]\\n' "$TAURI_SIGNING_PRIVATE_KEY" - printf 'password=[%s]\\n' "$TAURI_SIGNING_PRIVATE_KEY_PASSWORD" - bash -c 'printf "exported=[%s]\\n" "$TAURI_SIGNING_PRIVATE_KEY_PASSWORD"' - `, - { BPP_SIGNING_SECRETS_DIR: dirBash } - ); - expect(output).toContain( - 'Loading TAURI_SIGNING_PRIVATE_KEY from signing-secrets' - ); - expect(output).toContain('key=[updater-key]'); - expect(output).toContain('password=[]'); - expect(output).toContain('exported=[]'); - } - ); - - withSigningSecretFiles({}, ({ dirBash }) => { - const output = runShell( - ` - unset TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD - source ./scripts/bundle.sh - set +e - (load_updater_signing_env) 2>&1 - printf 'exit:%s\\n' "$?" - `, - { BPP_SIGNING_SECRETS_DIR: dirBash } - ); - expect(output).toContain('Missing TAURI_SIGNING_PRIVATE_KEY'); - expect(output).toContain('exit:1'); - }); -}); - -test('bundle.sh refuses to run outside the product build lock', () => { - const output = runShell(` - unset BPP_RELEASE_LOCK_TOKEN - set +e - bash ./scripts/bundle.sh 2>&1 - printf 'exit:%s\\n' "$?" - `); - expect(output).toContain('just release::build '); - expect(output).toContain('exit:1'); -}); diff --git a/bazaarplusplus-installer/scripts/checks/check-toolchain.mjs b/bazaarplusplus-installer/scripts/checks/check-toolchain.mjs deleted file mode 100644 index 90f02d8..0000000 --- a/bazaarplusplus-installer/scripts/checks/check-toolchain.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import fs from 'node:fs'; -import process from 'node:process'; - -function parseVersion(value) { - const match = String(value) - .trim() - .replace(/^v/, '') - .match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/); - if (!match) throw new Error(`Invalid tool version: ${value}`); - return [Number(match[1]), Number(match[2] ?? 0), Number(match[3] ?? 0)]; -} - -function compareVersions(left, right) { - for (let index = 0; index < 3; index += 1) { - if (left[index] !== right[index]) return left[index] - right[index]; - } - return 0; -} - -export function assertSupportedVersion(name, actualValue, range) { - const actual = parseVersion(actualValue); - const constraints = range.trim().split(/\s+/); - const supported = constraints.every((constraint) => { - const match = constraint.match(/^(>=|<=|>|<|=)?(.+)$/); - const operator = match[1] ?? '='; - const comparison = compareVersions(actual, parseVersion(match[2])); - if (operator === '>=') return comparison >= 0; - if (operator === '<=') return comparison <= 0; - if (operator === '>') return comparison > 0; - if (operator === '<') return comparison < 0; - return comparison === 0; - }); - if (!supported) { - throw new Error( - `${name} ${String(actualValue).replace(/^v/, '')} is unsupported; package.json requires ${range}` - ); - } -} - -function main(args) { - if (args.length !== 2) { - throw new Error('Usage: check-toolchain.mjs '); - } - const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8')); - const [nodeVersion, npmVersion] = args; - console.log( - `Toolchain: Node ${nodeVersion.replace(/^v/, '')}, npm ${npmVersion}` - ); - assertSupportedVersion('node', nodeVersion, packageJson.engines.node); - assertSupportedVersion('npm', npmVersion, packageJson.engines.npm); -} - -if (import.meta.main) { - try { - main(process.argv.slice(2)); - } catch (error) { - console.error(error instanceof Error ? error.message : String(error)); - process.exitCode = 1; - } -} diff --git a/bazaarplusplus-installer/scripts/checks/check-toolchain.test.mjs b/bazaarplusplus-installer/scripts/checks/check-toolchain.test.mjs deleted file mode 100644 index 43b2fae..0000000 --- a/bazaarplusplus-installer/scripts/checks/check-toolchain.test.mjs +++ /dev/null @@ -1,24 +0,0 @@ -import { expect, test } from 'vitest'; - -import { assertSupportedVersion } from './check-toolchain.mjs'; - -test('toolchain guard accepts versions inside the declared range', () => { - expect(() => - assertSupportedVersion('node', '24.16.0', '>=22.12.0 <25') - ).not.toThrow(); - expect(() => - assertSupportedVersion('npm', '11.17.0', '>=10 <12') - ).not.toThrow(); -}); - -test('toolchain guard rejects versions below the declared minimum', () => { - expect(() => - assertSupportedVersion('node', '22.11.0', '>=22.12.0 <25') - ).toThrow(/node 22\.11\.0 is unsupported/); -}); - -test('toolchain guard rejects versions at the exclusive upper bound', () => { - expect(() => assertSupportedVersion('npm', '12.0.0', '>=10 <12')).toThrow( - /npm 12\.0\.0 is unsupported/ - ); -}); diff --git a/bazaarplusplus-installer/scripts/checks/docs-check.mjs b/bazaarplusplus-installer/scripts/checks/docs-check.mjs deleted file mode 100644 index 785909b..0000000 --- a/bazaarplusplus-installer/scripts/checks/docs-check.mjs +++ /dev/null @@ -1,174 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import process from 'node:process'; - -const ROOT_DOCS = ['AGENTS.md', 'CONTEXT.md', 'README.md']; - -// Docs cite code by symbol (`DefaultStreamWorkflow.deriveSnapshot`, -// `app.windows`) and prose names files this repo does not own -// (`steamapps/libraryfolders.vdf`, `TheBazaar.exe`). Both are shaped like a -// dotted path, so a span counts as a repo path only with one of these real -// source/config extensions plus a directory component — the second signal that -// separates `src/api/commandClient.ts` from bare `commands.ts` shorthand. -const CITABLE_EXTENSIONS = new Set( - 'rs ts tsx js mjs cjs json toml sh md css yml yaml lock plist c h'.split(' ') -); - -const BACKTICK_PATH_PATTERN = /`([\w./-]+\.[A-Za-z][\w-]*)`/g; -const MARKDOWN_LINK_PATTERN = /\]\(([^)]+)\)/g; - -const absolute = (rootDir, relativePath) => - path.join(rootDir, ...relativePath.split('/')); -const read = (rootDir, relativePath) => - fs.readFileSync(absolute(rootDir, relativePath), 'utf8'); -const isFile = (filePath) => - !!fs.statSync(filePath, { throwIfNoEntry: false })?.isFile(); -const lineAt = (content, index) => content.slice(0, index).split('\n').length; - -// A missing directory is normal: docs/plans/ and docs/archive/ appear only once -// there is something to put in them. -export function listDocs(rootDir, relDir) { - const dirPath = absolute(rootDir, relDir); - if (!fs.statSync(dirPath, { throwIfNoEntry: false })?.isDirectory()) - return []; - return fs - .readdirSync(dirPath, { withFileTypes: true }) - .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) - .map((entry) => `${relDir}/${entry.name}`) - .sort(); -} - -export function extractCitedPaths(content) { - const cited = []; - for (const match of content.matchAll(BACKTICK_PATH_PATTERN)) { - const target = match[1]; - const extension = target.slice(target.lastIndexOf('.') + 1).toLowerCase(); - if (!target.includes('/') || !CITABLE_EXTENSIONS.has(extension)) continue; - cited.push({ target, line: lineAt(content, match.index) }); - } - return cited; -} - -export function extractMarkdownLinks(content) { - const links = []; - for (const match of content.matchAll(MARKDOWN_LINK_PATTERN)) { - const target = match[1].trim(); - if (!target || target.startsWith('#')) continue; - if (/^[a-z][a-z0-9+.-]*:/i.test(target)) continue; // https:, mailto:, … - const [pathPart] = target.split('#'); - if (!pathPart.toLowerCase().endsWith('.md')) continue; - links.push({ target: pathPart, line: lineAt(content, match.index) }); - } - return links; -} - -// Documents that must describe the tree as it is now. docs/adr/ is absent on -// purpose: a decision record must be free to name code that has since been -// deleted — ADR-0003 documents the removed Tempo launch flow, and that -// historical mention is the record's value. -const currentDocs = (rootDir) => [ - ...ROOT_DOCS, - ...listDocs(rootDir, 'docs'), - ...listDocs(rootDir, 'docs/plans') -]; - -export function checkCitedPaths(rootDir) { - const files = currentDocs(rootDir); - const failures = []; - let checked = 0; - - for (const file of files) { - for (const cited of extractCitedPaths(read(rootDir, file))) { - checked += 1; - if (!isFile(absolute(rootDir, cited.target))) { - failures.push({ - file, - line: cited.line, - message: `\`${cited.target}\` does not resolve to a file` - }); - } - } - } - return { checked, failures }; -} - -export function checkMarkdownLinks(rootDir) { - const files = [ - ...currentDocs(rootDir), - ...listDocs(rootDir, 'docs/adr'), - ...listDocs(rootDir, 'docs/archive') - ]; - const failures = []; - let checked = 0; - - for (const file of files) { - const fromDir = path.dirname(absolute(rootDir, file)); - for (const link of extractMarkdownLinks(read(rootDir, file))) { - checked += 1; - if (!isFile(path.join(fromDir, ...link.target.split('/')))) { - failures.push({ - file, - line: link.line, - message: `link to \`${link.target}\` does not resolve` - }); - } - } - } - return { checked, failures }; -} - -// CONTEXT.md is the sole entry map, so an unlinked topic is one an agent can -// only find by luck. -export function checkEntryMapCoverage(rootDir) { - const linked = new Set( - extractMarkdownLinks(read(rootDir, 'CONTEXT.md')).map((link) => - path.resolve(path.dirname(absolute(rootDir, 'CONTEXT.md')), link.target) - ) - ); - const topics = listDocs(rootDir, 'docs'); - const failures = topics - .filter((topic) => !linked.has(path.resolve(absolute(rootDir, topic)))) - .map((topic) => ({ - file: topic, - line: 1, - message: 'topic is not linked from `CONTEXT.md`' - })); - return { checked: topics.length, failures }; -} - -const ASSERTIONS = [ - { name: 'Cited path existence', run: checkCitedPaths }, - { name: 'Relative markdown links', run: checkMarkdownLinks }, - { name: 'CONTEXT.md topic coverage', run: checkEntryMapCoverage } -]; - -export function runDocsCheck(rootDir, { log = console.log } = {}) { - let ok = true; - for (const assertion of ASSERTIONS) { - const { checked, failures } = assertion.run(rootDir); - if (failures.length > 0) { - ok = false; - log(`==> ${assertion.name}: ${failures.length} failure(s)`); - for (const failure of failures) { - log(` ${failure.file}:${failure.line}: ${failure.message}`); - } - } else { - log(`==> ${assertion.name}: ok (${checked} checked)`); - } - } - return ok; -} - -if (import.meta.main) { - const rootDir = path.resolve(import.meta.dirname, '..', '..'); - try { - const ok = runDocsCheck(rootDir); - console.log(ok ? 'docs-check: ok' : 'docs-check: failed'); - process.exitCode = ok ? 0 : 1; - } catch (error) { - console.error( - `docs-check: ${error instanceof Error ? error.message : String(error)}` - ); - process.exitCode = 1; - } -} diff --git a/bazaarplusplus-installer/scripts/checks/docs-check.test.mjs b/bazaarplusplus-installer/scripts/checks/docs-check.test.mjs deleted file mode 100644 index c9667f1..0000000 --- a/bazaarplusplus-installer/scripts/checks/docs-check.test.mjs +++ /dev/null @@ -1,174 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { test, expect } from 'vitest'; - -import { - checkCitedPaths, - checkEntryMapCoverage, - checkMarkdownLinks, - extractCitedPaths, - extractMarkdownLinks, - listDocs, - runDocsCheck -} from './docs-check.mjs'; - -function writeFile(rootDir, relativePath, content) { - const filePath = path.join(rootDir, ...relativePath.split('/')); - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, content); -} - -function createFixtureRoot() { - const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-docs-check-')); - writeFile(rootDir, 'AGENTS.md', '# Agents\n'); - writeFile(rootDir, 'CONTEXT.md', '# Context\n'); - writeFile(rootDir, 'README.md', '# Readme\n'); - return rootDir; -} - -// ---------- what counts as a cited path ---------- - -test('a symbol citation is not treated as a path', () => { - const content = - 'The window config is `app.windows`, set via `DefaultStreamWorkflow.deriveSnapshot`.'; - expect(extractCitedPaths(content)).toEqual([]); -}); - -test('a file this repo does not own is not treated as a path', () => { - const content = - 'Steam detection reads `steamapps/libraryfolders.vdf` and launches `TheBazaar.exe`.'; - expect(extractCitedPaths(content)).toEqual([]); -}); - -test('a root-relative source path is treated as a path', () => { - const content = - 'Generated bindings live in `src/types/generated/commands.ts`.'; - expect(extractCitedPaths(content)).toEqual([ - { target: 'src/types/generated/commands.ts', line: 1 } - ]); -}); - -// ---------- seam 1: cited paths exist ---------- - -test('a cited path with no file behind it fails, reported at its line', () => { - const rootDir = createFixtureRoot(); - writeFile( - rootDir, - 'AGENTS.md', - '# Agents\n\nSee `src/does-not-exist.rs` for details.\n' - ); - - const result = checkCitedPaths(rootDir); - - expect(result.failures).toHaveLength(1); - expect(result.failures[0]).toMatchObject({ file: 'AGENTS.md', line: 3 }); - expect(result.failures[0].message).toMatch(/src\/does-not-exist\.rs/); -}); - -test('a cited path that resolves passes', () => { - const rootDir = createFixtureRoot(); - writeFile(rootDir, 'src/lib.rs', 'fn main() {}\n'); - writeFile(rootDir, 'docs/architecture.md', 'Entry point: `src/lib.rs`.\n'); - - const result = checkCitedPaths(rootDir); - - expect(result.failures).toEqual([]); - expect(result.checked).toBe(1); -}); - -test('an ADR may name code that no longer exists', () => { - const rootDir = createFixtureRoot(); - writeFile( - rootDir, - 'docs/adr/0003-steam-only-launch.md', - 'It worked through `src/services/tempo.rs`, since removed.\n' - ); - - expect(checkCitedPaths(rootDir).failures).toEqual([]); -}); - -// ---------- seam 2: relative markdown links resolve ---------- - -test('absolute URLs and bare anchors are not link targets', () => { - const content = - '[site](https://example.com) and [here](#section) and [doc](other.md)'; - expect(extractMarkdownLinks(content)).toEqual([ - { target: 'other.md', line: 1 } - ]); -}); - -test('a dead relative link fails and a live one passes', () => { - const rootDir = createFixtureRoot(); - writeFile(rootDir, 'docs/adr/0002-example.md', '# Two\n'); - writeFile( - rootDir, - 'docs/adr/0001-example.md', - 'See [two](0002-example.md) and [gone](0099-missing.md).\n' - ); - - const result = checkMarkdownLinks(rootDir); - - expect(result.failures).toEqual([ - { - file: 'docs/adr/0001-example.md', - line: 1, - message: 'link to `0099-missing.md` does not resolve' - } - ]); -}); - -test('a link is resolved against the linking file, not the repository root', () => { - const rootDir = createFixtureRoot(); - writeFile(rootDir, 'CONTEXT.md', '[Architecture](docs/architecture.md)\n'); - writeFile(rootDir, 'docs/architecture.md', '[ADR](adr/0001-example.md)\n'); - writeFile(rootDir, 'docs/adr/0001-example.md', '# One\n'); - - expect(checkMarkdownLinks(rootDir).failures).toEqual([]); -}); - -// ---------- seam 3: CONTEXT.md reaches every topic ---------- - -test('a topic missing from the entry map fails', () => { - const rootDir = createFixtureRoot(); - writeFile(rootDir, 'docs/architecture.md', '# Architecture\n'); - - expect(checkEntryMapCoverage(rootDir).failures).toEqual([ - { - file: 'docs/architecture.md', - line: 1, - message: 'topic is not linked from `CONTEXT.md`' - } - ]); -}); - -test('a topic linked from the entry map passes, and ADRs need no entry', () => { - const rootDir = createFixtureRoot(); - writeFile(rootDir, 'CONTEXT.md', '[Architecture](docs/architecture.md)\n'); - writeFile(rootDir, 'docs/architecture.md', '# Architecture\n'); - writeFile(rootDir, 'docs/adr/0001-example.md', '# One\n'); - - const result = checkEntryMapCoverage(rootDir); - - expect(result.failures).toEqual([]); - expect(result.checked).toBe(1); -}); - -// ---------- runner ---------- - -test('listDocs tolerates a directory that does not exist yet', () => { - const rootDir = createFixtureRoot(); - expect(listDocs(rootDir, 'docs/plans')).toEqual([]); -}); - -test('runDocsCheck reports failure once any seam fails, and passes a clean tree', () => { - const rootDir = createFixtureRoot(); - writeFile(rootDir, 'CONTEXT.md', '[Architecture](docs/architecture.md)\n'); - writeFile(rootDir, 'src/lib.rs', 'fn main() {}\n'); - writeFile(rootDir, 'docs/architecture.md', 'Entry point: `src/lib.rs`.\n'); - - expect(runDocsCheck(rootDir, { log: () => {} })).toBe(true); - - writeFile(rootDir, 'docs/orphan.md', '# Orphan\n'); - expect(runDocsCheck(rootDir, { log: () => {} })).toBe(false); -}); diff --git a/bazaarplusplus-installer/scripts/checks/prebuild-check.mjs b/bazaarplusplus-installer/scripts/checks/prebuild-check.mjs deleted file mode 100644 index ff391ea..0000000 --- a/bazaarplusplus-installer/scripts/checks/prebuild-check.mjs +++ /dev/null @@ -1,131 +0,0 @@ -import { execFileSync } from 'node:child_process'; -import fs from 'node:fs'; -import path from 'node:path'; -import process from 'node:process'; -import { parseArgs } from 'node:util'; -import { runGit } from '../../../scripts/git-command.mjs'; -import { - defaultTargetBuildPlatforms, - resolveBuildPlatform -} from '../../../release/release-platforms.mjs'; -import { checkProductProjections } from '../../../release/projections.mjs'; -import { verifyPayloadBuild } from '../../../release/payload.mjs'; - -export function resolveTargetPlatforms(platformEnv) { - if (!platformEnv) { - return defaultTargetBuildPlatforms(); - } - - const platform = resolveBuildPlatform(platformEnv); - if (!platform) { - throw new Error(`Unsupported TAURI_ENV_PLATFORM value: ${platformEnv}`); - } - - return [platform]; -} - -export function macosTrampolineStubPath(rootDir) { - return path.join( - rootDir, - 'src-tauri', - 'resources', - 'Trampoline', - 'macos', - 'bpp_launcher' - ); -} - -export function assertMacosTrampolineStub(rootDir) { - return assertMacosTrampolineStubWith(rootDir, (stubPath) => - execFileSync('file', [stubPath], { encoding: 'utf8' }) - ); -} - -export function assertMacosTrampolineStubWith(rootDir, describeStub) { - const stubPath = macosTrampolineStubPath(rootDir); - if (!fs.existsSync(stubPath)) { - throw new Error( - `Missing compiled macOS trampoline stub: ${stubPath}. ` + - 'Build src-tauri on macOS (build.rs compiles it from src-tauri/trampoline/bpp_launcher.c) before bundling.' - ); - } - - const description = describeStub(stubPath); - if (!/Mach-O 64-bit executable arm64/.test(description)) { - throw new Error( - `macOS trampoline stub is not arm64 Mach-O (${stubPath}): ${description.trim()}` - ); - } -} - -const generatedTypesDir = 'src/types/generated'; - -export function assertBindingsUpToDate(rootDir) { - console.log('Checking generated TypeScript binding freshness...'); - const porcelain = runGit( - ['status', '--porcelain', '--untracked-files=all', '--', generatedTypesDir], - { cwd: rootDir } - ).trim(); - - if (porcelain) { - throw new Error( - `Generated TypeScript bindings are out of date under ${generatedTypesDir}. ` + - 'Run npm run generate:bindings and commit all files under that directory.\n' + - porcelain - ); - } -} - -export function runPrebuildCheck( - rootDir, - { platformEnv, releaseResources = true, bindingsOnly = false } = {} -) { - console.log('Running prebuild check...'); - assertBindingsUpToDate(rootDir); - if (bindingsOnly) return; - - checkProductProjections(path.dirname(rootDir)); - if (!releaseResources) return; - - const platforms = resolveTargetPlatforms(platformEnv); - for (const platform of platforms) { - verifyPayloadBuild({ - workspaceRoot: path.dirname(rootDir), - rootDir, - platform - }); - } - - // The compiled arm64 stub is only produced on (and needed by) a macOS build - // host. Skip the check when cross-validating the macOS target from elsewhere. - if (process.platform === 'darwin' && platforms.includes('macos')) { - assertMacosTrampolineStub(rootDir); - } -} - -if (import.meta.main) { - try { - const { values } = parseArgs({ - args: process.argv.slice(2), - strict: true, - options: { - 'source-only': { type: 'boolean' }, - 'bindings-only': { type: 'boolean' }, - platform: { type: 'string' } - } - }); - if (values.platform !== undefined && !values.platform) { - throw new Error('--platform needs a value'); - } - runPrebuildCheck(process.cwd(), { - platformEnv: values.platform ?? process.env.TAURI_ENV_PLATFORM, - releaseResources: values['source-only'] !== true, - bindingsOnly: values['bindings-only'] === true - }); - console.log('prebuild-check: ok'); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - console.error(`prebuild-check: ${message}`); - process.exit(1); - } -} diff --git a/bazaarplusplus-installer/scripts/checks/prebuild-check.test.mjs b/bazaarplusplus-installer/scripts/checks/prebuild-check.test.mjs deleted file mode 100644 index 2364db7..0000000 --- a/bazaarplusplus-installer/scripts/checks/prebuild-check.test.mjs +++ /dev/null @@ -1,27 +0,0 @@ -import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; -import { test, expect } from 'vitest'; - -import { - assertMacosTrampolineStub, - assertMacosTrampolineStubWith, - macosTrampolineStubPath -} from './prebuild-check.mjs'; - -test('trampoline stub check fails loudly when the compiled stub is missing', () => { - const root = mkdtempSync(path.join(tmpdir(), 'bpp-stub-')); - expect(() => assertMacosTrampolineStub(root)).toThrow( - 'Missing compiled macOS trampoline stub' - ); -}); - -test('trampoline stub check rejects a non-Mach-O stub', () => { - const root = mkdtempSync(path.join(tmpdir(), 'bpp-stub-')); - const stubPath = macosTrampolineStubPath(root); - mkdirSync(path.dirname(stubPath), { recursive: true }); - writeFileSync(stubPath, 'not a mach-o binary'); - expect(() => assertMacosTrampolineStubWith(root, () => 'ASCII text')).toThrow( - 'not arm64 Mach-O' - ); -}); diff --git a/bazaarplusplus-installer/scripts/checks/verify.mjs b/bazaarplusplus-installer/scripts/checks/verify.mjs deleted file mode 100644 index 5f5fc0c..0000000 --- a/bazaarplusplus-installer/scripts/checks/verify.mjs +++ /dev/null @@ -1,237 +0,0 @@ -import path from 'node:path'; -import process from 'node:process'; -import { spawnSync } from 'node:child_process'; -import { appendFileSync } from 'node:fs'; -import { tauriSourceEnvironment } from '../tauri-source-env.mjs'; - -const manifestPath = 'src-tauri/Cargo.toml'; - -function npmStep(subset, label, script, extraArgs = []) { - return { - subset, - label, - command: 'npm', - args: ['run', script, ...extraArgs] - }; -} - -export function verificationSteps({ - mode, - releasePlatform, - subset = 'all', - platform = process.platform -}) { - if (mode !== 'source' && mode !== 'release') { - throw new Error(`Unsupported verification mode: ${mode}`); - } - - if (!['all', 'frontend', 'native'].includes(subset)) { - throw new Error(`Unsupported verification subset: ${subset}`); - } - if (mode === 'release' && subset !== 'all') { - throw new Error('Release verification requires the full set of checks'); - } - - const prebuildStep = - mode === 'source' - ? npmStep( - 'shared', - 'Source version and resource contract checks', - 'prebuild-check:source:after-bindings' - ) - : npmStep( - 'shared', - 'Release version and payload checks', - 'prebuild-check:after-bindings', - releasePlatform ? ['--', '--platform', releasePlatform] : [] - ); - - return [ - // Cheap static gates run first so the most common failures (formatting, - // lint, a stale Cargo lock) are reported before the Rust test build starts. - // Clippy only type-checks, so it also runs ahead of the test build. - npmStep('frontend', 'Check formatting', 'format:check'), - npmStep('frontend', 'Lint TypeScript and scripts', 'lint'), - { - subset: 'native', - label: 'Check Rust formatting', - command: 'cargo', - args: ['fmt', '--manifest-path', manifestPath, '--', '--check'] - }, - { - subset: 'native', - label: 'Check locked Cargo dependency graph', - command: 'cargo', - args: [ - 'metadata', - '--locked', - '--manifest-path', - manifestPath, - '--format-version', - '1', - '--no-deps' - ], - stdio: ['inherit', 'ignore', 'inherit'] - }, - { - subset: 'native', - label: 'Run Rust Clippy', - command: 'cargo', - args: [ - 'clippy', - '--locked', - '--manifest-path', - manifestPath, - '--all-targets', - '--all-features', - '--', - '-D', - 'warnings' - ] - }, - npmStep( - 'native', - 'Generate bindings and run Rust tests', - 'generate:bindings:test' - ), - npmStep('native', 'Check generated binding freshness', 'check:bindings'), - npmStep('frontend', 'Type-check TypeScript', 'check:ts'), - npmStep('frontend', 'Run frontend tests', 'test:unit', ['--', 'src']), - // Linux covers script behavior too; Windows repeats this boundary because - // process shims, paths and packaging scripts have Windows-specific code. - npmStep('scripts', 'Run script tests', 'test:unit', ['--', 'scripts']), - npmStep('frontend', 'Check documentation', 'docs:check'), - { - subset: 'native', - label: 'Build strict Rust documentation', - command: 'cargo', - args: [ - 'doc', - '--locked', - '--manifest-path', - manifestPath, - '--all-features', - '--no-deps', - '--document-private-items' - ], - env: { RUSTDOCFLAGS: '-D warnings' } - }, - prebuildStep, - npmStep('frontend', 'Build production frontend', 'build:frontend') - ].filter( - (step) => - subset === 'all' || - step.subset === 'shared' || - step.subset === subset || - (step.subset === 'scripts' && - (subset === 'frontend' || platform === 'win32')) - ); -} - -export function runVerification({ - rootDir, - mode, - releasePlatform, - subset = 'all', - platform = process.platform, - commandShell = process.env.ComSpec ?? 'cmd.exe', - run = spawnSync, - log = console.log, - now = () => performance.now(), - summaryPath = process.env.GITHUB_STEP_SUMMARY -}) { - const summarize = (text) => { - if (!summaryPath) return; - try { - appendFileSync(summaryPath, text); - } catch (error) { - // Timing output must not change the verification result. - console.warn(`Could not write verification timings: ${error.message}`); - } - }; - summarize( - '\n### Installer verification timings\n\n' + - 'Rust tests include compilation, execution and binding generation.\n\n' + - '| Step | Seconds | Result |\n| --- | ---: | --- |\n' - ); - const environment = - mode === 'source' ? tauriSourceEnvironment() : { ...process.env }; - for (const step of verificationSteps({ - mode, - releasePlatform, - subset, - platform - })) { - log(`==> ${step.label}`); - const usesWindowsNpmShim = platform === 'win32' && step.command === 'npm'; - const command = usesWindowsNpmShim ? commandShell : step.command; - const args = usesWindowsNpmShim - ? ['/d', '/s', '/c', 'npm.cmd', ...step.args] - : step.args; - const started = now(); - const result = run(command, args, { - cwd: rootDir, - stdio: step.stdio ?? 'inherit', - env: { ...environment, ...step.env } - }); - const seconds = ((now() - started) / 1000).toFixed(2); - const status = result.error ? 1 : (result.status ?? 1); - log(`==> ${step.label}: ${seconds}s (exit ${status})`); - summarize( - `| ${step.label} | ${seconds} | ${status === 0 ? 'passed' : `failed (${status})`} |\n` - ); - if (result.error) { - console.error(result.error.message); - return 1; - } - if (status !== 0) return status; - } - return 0; -} - -export function parseCliArgs(args) { - let mode = 'release'; - let releasePlatform; - let subset = 'all'; - - for (let index = 0; index < args.length; index += 1) { - const arg = args[index]; - if (arg === '--source-only') { - mode = 'source'; - continue; - } - if (arg === '--subset') { - subset = args[++index]; - if (!['all', 'frontend', 'native'].includes(subset)) { - throw new Error('--subset must be all, frontend or native'); - } - continue; - } - if (arg === '--release-platform') { - releasePlatform = args[index + 1]; - if (!releasePlatform) throw new Error('--release-platform needs a value'); - mode = 'release'; - index += 1; - continue; - } - throw new Error(`Unknown verify argument: ${arg}`); - } - - if (mode === 'source' && releasePlatform) { - throw new Error('--source-only cannot be combined with --release-platform'); - } - return { mode, releasePlatform, subset }; -} - -if (import.meta.main) { - try { - const options = parseCliArgs(process.argv.slice(2)); - process.exitCode = runVerification({ - rootDir: path.resolve(import.meta.dirname, '..', '..'), - ...options - }); - } catch (error) { - console.error(error instanceof Error ? error.message : String(error)); - process.exitCode = 2; - } -} diff --git a/bazaarplusplus-installer/scripts/checks/verify.test.mjs b/bazaarplusplus-installer/scripts/checks/verify.test.mjs deleted file mode 100644 index 1430beb..0000000 --- a/bazaarplusplus-installer/scripts/checks/verify.test.mjs +++ /dev/null @@ -1,266 +0,0 @@ -import { expect, test, vi } from 'vitest'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; - -import { runVerification, verificationSteps, parseCliArgs } from './verify.mjs'; - -test('source verification omits private release payload validation', () => { - const steps = verificationSteps({ mode: 'source' }); - - expect( - steps.some( - ({ command, args }) => - command === 'npm' && - args.includes('prebuild-check:source:after-bindings') - ) - ).toBe(true); - expect( - steps.some(({ args }) => args.includes('prebuild-check:after-bindings')) - ).toBe(false); -}); - -test('source verification excludes bundle resources in child processes without changing release configuration', () => { - const config = { - bundle: { resources: ['missing-release.zip'], active: true }, - identifier: 'com.example.fixture' - }; - vi.stubEnv('TAURI_CONFIG', JSON.stringify(config)); - try { - const observed = []; - expect( - runVerification({ - rootDir: process.cwd(), - summaryPath: null, - mode: 'source', - log() {}, - run(command, args, options) { - observed.push({ - command, - args, - config: JSON.parse(options.env.TAURI_CONFIG) - }); - return { status: 0 }; - } - }) - ).toBe(0); - expect( - observed.find( - ({ command, args }) => command === 'cargo' && args.includes('clippy') - ).config - ).toEqual({ ...config, bundle: { ...config.bundle, resources: [] } }); - expect( - observed.find(({ args }) => args.includes('generate:bindings:test')) - .config.bundle.resources - ).toEqual([]); - expect( - observed.find( - ({ command, args }) => command === 'cargo' && args.includes('doc') - ).config.bundle.resources - ).toEqual([]); - expect(JSON.parse(process.env.TAURI_CONFIG)).toEqual(config); - runVerification({ - rootDir: process.cwd(), - summaryPath: null, - mode: 'release', - log() {}, - run(_command, _args, options) { - expect(JSON.parse(options.env.TAURI_CONFIG)).toEqual(config); - return { status: 0 }; - } - }); - } finally { - vi.unstubAllEnvs(); - } -}); - -test('verification preserves the failing command status and stops', () => { - const observed = []; - const status = runVerification({ - rootDir: process.cwd(), - summaryPath: null, - mode: 'source', - platform: 'linux', - log() {}, - run(command, args) { - observed.push([command, ...args].join(' ')); - return { status: args.includes('check:ts') ? 17 : 0 }; - } - }); - - expect(status).toBe(17); - expect(observed.at(-1)).toBe('npm run check:ts'); - expect(observed.some((command) => command.includes('build:frontend'))).toBe( - false - ); -}); - -test.each([ - [{ status: 0 }, 0, 'passed'], - [{ status: 17 }, 17, 'failed (17)'], - [{ status: null, signal: 'SIGTERM' }, 1, 'failed (1)'], - [{ error: new Error('spawn failed') }, 1, 'failed (1)'] -])( - 'records elapsed time and outcomes while preserving the gate result: %j', - (result, expectedStatus, outcome) => { - const dir = mkdtempSync(path.join(tmpdir(), 'bpp-verify-timings-')); - const summaryPath = path.join(dir, 'summary.md'); - writeFileSync(summaryPath, 'Existing summary\n'); - let tick = 0; - const calls = []; - const errorLog = vi.spyOn(console, 'error').mockImplementation(() => {}); - try { - expect( - runVerification({ - rootDir: process.cwd(), - mode: 'source', - summaryPath, - now: () => tick++ * 1250, - log() {}, - run(command, args) { - calls.push([command, ...args]); - return result; - } - }) - ).toBe(expectedStatus); - const summary = readFileSync(summaryPath, 'utf8'); - expect(summary).toContain('Existing summary\n'); - expect(summary).toContain(`| Check formatting | 1.25 | ${outcome} |`); - if (expectedStatus === 0) { - expect(summary).toContain('| Run Rust Clippy | 1.25 | passed |'); - expect(summary).toContain( - '| Generate bindings and run Rust tests | 1.25 | passed |' - ); - expect(summary).toContain( - '| Build production frontend | 1.25 | passed |' - ); - } else { - expect(calls).toHaveLength(1); - expect(summary).not.toContain('| Run Rust Clippy |'); - } - } finally { - errorLog.mockRestore(); - rmSync(dir, { recursive: true, force: true }); - } - } -); - -test('an unwritable timing summary does not change a failing command status', () => { - const dir = mkdtempSync(path.join(tmpdir(), 'bpp-verify-timings-')); - const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); - try { - expect( - runVerification({ - rootDir: process.cwd(), - mode: 'source', - summaryPath: dir, - log() {}, - run: () => ({ status: 17 }) - }) - ).toBe(17); - expect(warning).toHaveBeenCalled(); - } finally { - warning.mockRestore(); - rmSync(dir, { recursive: true, force: true }); - } -}); - -const unique = (steps) => - [...new Set(steps.map((step) => JSON.stringify(step)))].sort(); - -test.each(['linux', 'darwin', 'win32'])( - 'subsets cover the complete source gate once on %s', - (platform) => { - const options = { mode: 'source', platform }; - const full = verificationSteps(options); - const frontend = verificationSteps({ ...options, subset: 'frontend' }); - const native = verificationSteps({ ...options, subset: 'native' }); - expect(unique([...frontend, ...native])).toEqual(unique(full)); - expect(unique(full)).toHaveLength(full.length); - expect(unique(frontend)).toHaveLength(frontend.length); - expect(unique(native)).toHaveLength(native.length); - expect(frontend.some(({ command }) => command === 'cargo')).toBe(false); - expect( - frontend.some(({ args }) => - args.some((arg) => arg.startsWith('generate:bindings')) - ) - ).toBe(false); - expect(frontend.some(({ args }) => args.includes('build:frontend'))).toBe( - true - ); - expect(frontend.some(({ args }) => args.includes('docs:check'))).toBe(true); - expect(native.some(({ args }) => args.includes('scripts'))).toBe( - platform === 'win32' - ); - expect( - native.some( - ({ args }) => - args.includes('build:frontend') || - args.includes('check:ts') || - args.includes('src') - ) - ).toBe(false); - for (const steps of [frontend, native]) { - expect( - steps.some(({ args }) => - args.includes('prebuild-check:source:after-bindings') - ) - ).toBe(true); - } - for (const steps of [full, native]) { - const generation = steps.findIndex(({ args }) => - args.includes('generate:bindings:test') - ); - const diff = steps.findIndex(({ args }) => - args.includes('check:bindings') - ); - expect(generation).toBeGreaterThanOrEqual(0); - expect(diff).toBeGreaterThan(generation); - } - } -); - -test('frontend runner works without Rust and retains test and source contract failures', () => { - for (const failingScript of [ - 'test:unit', - 'prebuild-check:source:after-bindings' - ]) { - const observed = []; - expect( - runVerification({ - rootDir: process.cwd(), - mode: 'source', - subset: 'frontend', - platform: 'linux', - summaryPath: null, - log() {}, - run(command, args) { - if ( - command !== 'npm' || - args.some((arg) => arg.startsWith('generate:bindings')) - ) { - throw new Error('Rust is unavailable'); - } - observed.push(args); - return { status: args.includes(failingScript) ? 23 : 0 }; - } - }) - ).toBe(23); - expect(observed.at(-1)).toContain(failingScript); - } -}); - -test('only explicit source verification accepts subsets; complete release remains mandatory', () => { - expect(parseCliArgs(['--source-only', '--subset', 'frontend'])).toMatchObject( - { mode: 'source', subset: 'frontend' } - ); - expect(parseCliArgs(['--source-only']).subset).toBe('all'); - for (const args of [['--subset'], ['--subset', 'unknown']]) { - expect(() => parseCliArgs(args)).toThrow(/--subset/); - } - for (const subset of ['frontend', 'native']) { - expect(() => verificationSteps({ mode: 'release', subset })).toThrow( - /full set/ - ); - } -}); diff --git a/bazaarplusplus-installer/scripts/generate-bindings.mjs b/bazaarplusplus-installer/scripts/generate-bindings.mjs deleted file mode 100644 index ba1231f..0000000 --- a/bazaarplusplus-installer/scripts/generate-bindings.mjs +++ /dev/null @@ -1,166 +0,0 @@ -import { execFileSync } from 'node:child_process'; -import { - existsSync, - mkdtempSync, - mkdirSync, - readFileSync, - readdirSync, - renameSync, - rmSync, - statSync, - writeFileSync -} from 'node:fs'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; -import { tauriSourceEnvironment } from './tauri-source-env.mjs'; - -const GENERATED_COMMANDS_FILE = 'commands.ts'; - -// Every input whose change can alter the exported bindings. -const BINDING_INPUT_PATHS = Object.freeze([ - 'src-tauri/src', - 'src-tauri/Cargo.toml', - 'src-tauri/Cargo.lock', - 'scripts/generate-bindings.mjs' -]); - -// Pure staleness decision. `generatedMtimeMs` is null when the committed -// bindings are absent; `inputMtimesMs` is empty when no input could be read. -// Both cases force a regeneration rather than a silent skip. -export function bindingsAreFresh(generatedMtimeMs, inputMtimesMs) { - if (generatedMtimeMs === null || inputMtimesMs.length === 0) { - return false; - } - return inputMtimesMs.every((inputMtimeMs) => inputMtimeMs < generatedMtimeMs); -} - -function collectMtimesMs(entryPath, collected) { - let stats; - try { - stats = statSync(entryPath); - } catch { - return collected; - } - collected.push(stats.mtimeMs); - if (stats.isDirectory()) { - for (const entry of readdirSync(entryPath)) { - collectMtimesMs(path.join(entryPath, entry), collected); - } - } - return collected; -} - -export function generatedBindingsAreFresh(projectRoot) { - const commandsPath = path.join( - projectRoot, - 'src/types/generated', - GENERATED_COMMANDS_FILE - ); - const generatedMtimeMs = existsSync(commandsPath) - ? statSync(commandsPath).mtimeMs - : null; - const inputMtimesMs = BINDING_INPUT_PATHS.flatMap((relativePath) => - collectMtimesMs(path.join(projectRoot, relativePath), []) - ); - return bindingsAreFresh(generatedMtimeMs, inputMtimesMs); -} - -function normalizeLineEndings(content) { - return content.replace(/\r\n?/g, '\n').replace(/\n*$/, '\n'); -} - -function validateGeneratedBindings(commandsPath) { - if (!existsSync(commandsPath)) { - throw new Error( - `Generated bindings did not contain ${GENERATED_COMMANDS_FILE}` - ); - } - - const source = readFileSync(commandsPath, 'utf8'); - if (source.trim().length === 0 || !source.includes('export const commands')) { - throw new Error(`${GENERATED_COMMANDS_FILE} was empty or malformed`); - } -} - -// Writes the export beside the committed file and renames it over the target, -// so a failed or invalid export leaves the previous bindings untouched. -export function commitGeneratedBindings({ generatedDir, tempGeneratedDir }) { - const exportedPath = path.join(tempGeneratedDir, GENERATED_COMMANDS_FILE); - const targetPath = path.join(generatedDir, GENERATED_COMMANDS_FILE); - const stagedPath = `${targetPath}.tmp`; - - validateGeneratedBindings(exportedPath); - mkdirSync(generatedDir, { recursive: true }); - try { - writeFileSync( - stagedPath, - normalizeLineEndings(readFileSync(exportedPath, 'utf8')), - 'utf8' - ); - renameSync(stagedPath, targetPath); - } finally { - rmSync(stagedPath, { force: true }); - } -} - -export function runGenerateBindings( - projectRoot, - { runAllRustTests = false, skipIfFresh = false, run = execFileSync } = {} -) { - if (skipIfFresh && generatedBindingsAreFresh(projectRoot)) { - console.log( - 'generate-bindings: skipped, committed bindings are newer than every Rust input' - ); - return; - } - - const generatedDir = path.join(projectRoot, 'src/types/generated'); - const tempRoot = mkdtempSync(path.join(tmpdir(), 'bpp-bindings-')); - const tempGeneratedDir = path.join(tempRoot, 'generated'); - const exportPath = path.join(tempGeneratedDir, GENERATED_COMMANDS_FILE); - - mkdirSync(tempGeneratedDir, { recursive: true }); - - try { - const cargoArgs = [ - 'test', - '--locked', - ...(runAllRustTests ? [] : ['export_bindings']), - '--manifest-path', - 'src-tauri/Cargo.toml', - '--', - '--nocapture' - ]; - run('cargo', cargoArgs, { - cwd: projectRoot, - stdio: 'inherit', - env: { - ...tauriSourceEnvironment(), - BPP_SPECTA_EXPORT_PATH: exportPath - } - }); - - commitGeneratedBindings({ generatedDir, tempGeneratedDir }); - } finally { - rmSync(tempRoot, { recursive: true, force: true }); - } -} - -if (import.meta.main) { - const args = process.argv.slice(2); - const allowedFlags = new Set(['--with-rust-tests', '--if-stale']); - if (args.some((arg) => !allowedFlags.has(arg))) { - console.error( - 'Usage: generate-bindings.mjs [--with-rust-tests | --if-stale]' - ); - process.exit(2); - } - if (args.includes('--with-rust-tests') && args.includes('--if-stale')) { - console.error('--if-stale cannot be combined with --with-rust-tests'); - process.exit(2); - } - runGenerateBindings(path.resolve(import.meta.dirname, '..'), { - runAllRustTests: args.includes('--with-rust-tests'), - skipIfFresh: args.includes('--if-stale') - }); -} diff --git a/bazaarplusplus-installer/scripts/generate-bindings.test.mjs b/bazaarplusplus-installer/scripts/generate-bindings.test.mjs deleted file mode 100644 index b454cbe..0000000 --- a/bazaarplusplus-installer/scripts/generate-bindings.test.mjs +++ /dev/null @@ -1,84 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { expect, test } from 'vitest'; - -import { - bindingsAreFresh, - commitGeneratedBindings, - runGenerateBindings -} from './generate-bindings.mjs'; - -test('standalone binding generation runs Rust tests without requiring release resources', () => { - const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-bindings-test-')); - try { - runGenerateBindings(rootDir, { - runAllRustTests: true, - run(_command, _args, { env }) { - expect(JSON.parse(env.TAURI_CONFIG || '{}').bundle?.resources).toEqual( - [] - ); - fs.writeFileSync( - env.BPP_SPECTA_EXPORT_PATH, - 'export const commands = {};\n' - ); - } - }); - expect( - fs.readFileSync( - path.join(rootDir, 'src/types/generated/commands.ts'), - 'utf8' - ) - ).toBe('export const commands = {};\n'); - } finally { - fs.rmSync(rootDir, { recursive: true, force: true }); - } -}); - -test('generated bindings validation rejects a missing commands artifact', () => { - const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-bindings-test-')); - const generatedDir = path.join(rootDir, 'src/types/generated'); - const tempGeneratedDir = path.join(rootDir, 'staged-generated'); - - try { - fs.mkdirSync(generatedDir, { recursive: true }); - fs.mkdirSync(tempGeneratedDir, { recursive: true }); - fs.writeFileSync(path.join(generatedDir, 'preserved.ts'), 'preserved'); - - expect(() => - commitGeneratedBindings({ generatedDir, tempGeneratedDir }) - ).toThrow(/commands\.ts/); - expect( - fs.readFileSync(path.join(generatedDir, 'preserved.ts'), 'utf8') - ).toBe('preserved'); - } finally { - fs.rmSync(rootDir, { recursive: true, force: true }); - } -}); - -test('generated bindings validation rejects an empty commands artifact', () => { - const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-bindings-test-')); - const generatedDir = path.join(rootDir, 'src/types/generated'); - const tempGeneratedDir = path.join(rootDir, 'staged-generated'); - - try { - fs.mkdirSync(tempGeneratedDir, { recursive: true }); - fs.writeFileSync(path.join(tempGeneratedDir, 'commands.ts'), '\n'); - - expect(() => - commitGeneratedBindings({ generatedDir, tempGeneratedDir }) - ).toThrow(/empty or malformed/); - } finally { - fs.rmSync(rootDir, { recursive: true, force: true }); - } -}); - -test('binding freshness only skips when every input predates the artifact', () => { - expect(bindingsAreFresh(200, [100, 150, 199])).toBe(true); - expect(bindingsAreFresh(200, [100, 250])).toBe(false); - // An input written in the same millisecond is treated as a change. - expect(bindingsAreFresh(200, [200])).toBe(false); - // Missing artifact or unreadable inputs must never skip regeneration. - expect(bindingsAreFresh(null, [100])).toBe(false); - expect(bindingsAreFresh(200, [])).toBe(false); -}); diff --git a/bazaarplusplus-installer/scripts/headless.mjs b/bazaarplusplus-installer/scripts/headless.mjs deleted file mode 100644 index 0e11bc9..0000000 --- a/bazaarplusplus-installer/scripts/headless.mjs +++ /dev/null @@ -1,16 +0,0 @@ -// Run the installer CLI from source with no prepared release Payload required. -import { spawnSync } from 'node:child_process'; -import { fileURLToPath } from 'node:url'; -import { tauriSourceEnvironment } from './tauri-source-env.mjs'; - -const result = spawnSync( - 'cargo', - ['run', '--quiet', '--bin', 'bppinstaller', '--', ...process.argv.slice(2)], - { - cwd: fileURLToPath(new URL('../src-tauri/', import.meta.url)), - env: tauriSourceEnvironment(), - stdio: 'inherit' - } -); -if (result.error) throw result.error; -process.exit(result.status ?? 1); diff --git a/bazaarplusplus-installer/scripts/release/before-bundle-cleanup.mjs b/bazaarplusplus-installer/scripts/release/before-bundle-cleanup.mjs deleted file mode 100644 index 38d8fb9..0000000 --- a/bazaarplusplus-installer/scripts/release/before-bundle-cleanup.mjs +++ /dev/null @@ -1,58 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { - RELEASE_PLATFORMS, - resolveBuildPlatform -} from '../../../release/release-platforms.mjs'; - -export function resolveBundleCleanupPath(rootDir, platformEnv) { - const buildPlatform = resolveBuildPlatform(platformEnv); - const platform = RELEASE_PLATFORMS.find( - (entry) => entry.buildPlatform === buildPlatform - ); - return platform - ? path.join(rootDir, ...platform.bundleCleanupDir.split('/')) - : null; -} - -export function cleanupBundleArtifacts(rootDir, platformEnv) { - const cleanupPath = resolveBundleCleanupPath(rootDir, platformEnv); - if (!cleanupPath) { - return { cleanupPath: null, removed: false }; - } - - if (!fs.existsSync(cleanupPath)) { - return { cleanupPath, removed: false }; - } - - fs.rmSync(cleanupPath, { force: true, recursive: true }); - return { cleanupPath, removed: true }; -} - -function main() { - const rootDir = path.resolve(import.meta.dirname, '..', '..'); - const platformEnv = process.env.TAURI_ENV_PLATFORM ?? process.platform; - const { cleanupPath, removed } = cleanupBundleArtifacts(rootDir, platformEnv); - - if (!cleanupPath) { - console.log( - `before-bundle-cleanup: skipping unsupported platform ${platformEnv}` - ); - return; - } - - if (removed) { - console.log( - `before-bundle-cleanup: removed stale bundle artifacts at ${cleanupPath}` - ); - return; - } - - console.log( - `before-bundle-cleanup: no stale bundle artifacts at ${cleanupPath}` - ); -} - -if (import.meta.main) { - main(); -} diff --git a/bazaarplusplus-installer/scripts/release/before-bundle-cleanup.test.mjs b/bazaarplusplus-installer/scripts/release/before-bundle-cleanup.test.mjs deleted file mode 100644 index 58515ac..0000000 --- a/bazaarplusplus-installer/scripts/release/before-bundle-cleanup.test.mjs +++ /dev/null @@ -1,98 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { test, expect } from 'vitest'; - -import { - cleanupBundleArtifacts, - resolveBundleCleanupPath -} from './before-bundle-cleanup.mjs'; - -test('resolveBundleCleanupPath returns the macOS bundle root', () => { - const rootDir = '/tmp/bpp'; - expect(resolveBundleCleanupPath(rootDir, 'darwin')).toBe( - path.join( - rootDir, - 'src-tauri', - 'target', - 'aarch64-apple-darwin', - 'release', - 'bundle' - ) - ); -}); - -test('cleanupBundleArtifacts removes stale macOS bundle outputs', () => { - const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-cleanup-')); - const bundleDir = path.join( - rootDir, - 'src-tauri', - 'target', - 'aarch64-apple-darwin', - 'release', - 'bundle', - 'dmg' - ); - - fs.mkdirSync(bundleDir, { recursive: true }); - fs.writeFileSync( - path.join(bundleDir, 'BazaarPlusPlus_3.1.0_aarch64.dmg'), - 'stale' - ); - - try { - const result = cleanupBundleArtifacts(rootDir, 'macos'); - expect(result.removed).toBe(true); - expect(result.cleanupPath).toBe( - path.join( - rootDir, - 'src-tauri', - 'target', - 'aarch64-apple-darwin', - 'release', - 'bundle' - ) - ); - expect( - fs.existsSync( - path.join( - rootDir, - 'src-tauri', - 'target', - 'aarch64-apple-darwin', - 'release', - 'bundle' - ) - ) - ).toBe(false); - } finally { - fs.rmSync(rootDir, { force: true, recursive: true }); - } -}); - -test('cleanupBundleArtifacts removes stale Windows installer outputs', () => { - const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpp-cleanup-')); - const nsisDir = path.join( - rootDir, - 'src-tauri', - 'target', - 'release', - 'bundle', - 'nsis' - ); - - fs.mkdirSync(nsisDir, { recursive: true }); - fs.writeFileSync( - path.join(nsisDir, 'BazaarPlusPlus_3.1.0_x64-setup.exe'), - 'stale' - ); - - try { - const result = cleanupBundleArtifacts(rootDir, 'windows'); - expect(result.removed).toBe(true); - expect(result.cleanupPath).toBe(nsisDir); - expect(fs.existsSync(nsisDir)).toBe(false); - } finally { - fs.rmSync(rootDir, { force: true, recursive: true }); - } -}); diff --git a/bazaarplusplus-installer/scripts/release/compile-macos-icon.mjs b/bazaarplusplus-installer/scripts/release/compile-macos-icon.mjs deleted file mode 100644 index b6448af..0000000 --- a/bazaarplusplus-installer/scripts/release/compile-macos-icon.mjs +++ /dev/null @@ -1,134 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { execFileSync, spawnSync } from 'node:child_process'; - -const rootDir = path.resolve(import.meta.dirname, '..', '..'); -const appIconName = 'AppIcon'; -const iconSource = path.join( - rootDir, - 'src-tauri', - 'icons', - 'source', - `${appIconName}.icon` -); -const outputDir = path.join(rootDir, 'src-tauri', 'icons', 'macos-generated'); - -function isMacOSBuild() { - const platform = process.env.TAURI_ENV_PLATFORM ?? process.platform; - return platform === 'macos' || platform === 'darwin'; -} - -function commandWorks(command, args) { - const result = spawnSync(command, args, { - encoding: 'utf8', - stdio: 'pipe' - }); - return result.status === 0; -} - -function findActool() { - const candidates = []; - if (process.env.BPP_ACTOOL) candidates.push(process.env.BPP_ACTOOL); - if (process.env.DEVELOPER_DIR) { - candidates.push( - path.join(process.env.DEVELOPER_DIR, 'usr', 'bin', 'actool'), - path.join( - process.env.DEVELOPER_DIR, - 'Contents', - 'Developer', - 'usr', - 'bin', - 'actool' - ) - ); - } - candidates.push( - '/Applications/Xcode.app/Contents/Developer/usr/bin/actool', - '/usr/bin/actool' - ); - - for (const candidate of candidates) { - if (fs.existsSync(candidate) && commandWorks(candidate, ['--version'])) { - return candidate; - } - } - - const xcrun = spawnSync('xcrun', ['--find', 'actool'], { - encoding: 'utf8', - stdio: 'pipe' - }); - if (xcrun.status === 0) { - const candidate = xcrun.stdout.trim(); - if (candidate && commandWorks(candidate, ['--version'])) return candidate; - } - - return null; -} - -export function compileMacOSIcon({ allowFlatFallback = false } = {}) { - if (!isMacOSBuild()) { - return { platform: 'skipped', compiled: false }; - } - - if (!fs.existsSync(iconSource)) { - throw new Error(`Missing macOS Icon Composer source: ${iconSource}`); - } - - const actool = findActool(); - if (!actool) { - if (allowFlatFallback) { - console.warn( - 'compile-macos-icon: Xcode actool is unavailable; keeping the checked-in ICNS fallback' - ); - return { platform: 'macos', compiled: false, fallback: true }; - } - throw new Error( - 'Xcode 26 actool is required to compile the macOS .icon asset. ' + - 'Install Xcode or set BPP_ACTOOL to its actool path. ' + - 'For a local flat-icon test only, set BPP_ALLOW_FLAT_MACOS_ICON_FALLBACK=1.' - ); - } - - fs.rmSync(outputDir, { force: true, recursive: true }); - fs.mkdirSync(outputDir, { recursive: true }); - const partialInfoPlist = path.join( - outputDir, - 'assetcatalog_generated_info.plist' - ); - - execFileSync( - actool, - [ - iconSource, - '--app-icon', - appIconName, - '--compile', - outputDir, - '--output-partial-info-plist', - partialInfoPlist, - '--minimum-deployment-target', - '11.0', - '--platform', - 'macosx', - '--target-device', - 'mac' - ], - { cwd: rootDir, stdio: 'inherit' } - ); - - for (const filename of ['Assets.car', 'AppIcon.icns']) { - const output = path.join(outputDir, filename); - if (!fs.existsSync(output)) { - throw new Error(`actool did not produce ${output}`); - } - } - - fs.rmSync(partialInfoPlist, { force: true }); - return { platform: 'macos', compiled: true, outputDir }; -} - -if (import.meta.main) { - compileMacOSIcon({ - allowFlatFallback: process.env.BPP_ALLOW_FLAT_MACOS_ICON_FALLBACK === '1' - }); -} diff --git a/bazaarplusplus-installer/scripts/release/native-recorder-input.lock.json b/bazaarplusplus-installer/scripts/release/native-recorder-input.lock.json deleted file mode 100644 index d38b012..0000000 --- a/bazaarplusplus-installer/scripts/release/native-recorder-input.lock.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "schemaVersion": 3, - "sourceRepository": "BazaarPlusPlus/bazaarplusplus-mod", - "platforms": { - "macos": { - "inputDigest": "sha256:184ac0aa66e66f70820cdc93772e6d554a41199fcd490b7ee290289d6302bdc7", - "inputFiles": { - "native/mac-audio-tap/BppMacAudio.h": "346ea70328a8c170d307069e15abe7b384645477afd7f5be1ce2fa92e96dfe85", - "native/mac-audio-tap/BppMacAudio.m": "41b8899dbee04fb7c53e0ae2fef09f5b093448fa05a12f563f349f5b098bf104", - "native/mac-audio-tap/build.sh": "ab91b19131610b590feac0a5ab472b5ef79cb9c132232b13765d51fe00b02c51", - "native/macos/BppNativeLoadSmoke.c": "373a15caacb8fda639ab4109721c38fe30f10827a2b3133c32b57a13dc89b0f3", - "native/macos/BppReplayAudioMuxer.mm": "c87afdaa4d2f8731aa59dfba198d8ff66e79740e1ea662c73181fc96b23f7cac", - "native/macos/BppReplayVideoToolbox.h": "8a2cad31234ba454bd1c8e76c76fabdc02c3517134360f63f77d7a8f9b9902d2", - "native/macos/BppReplayVideoToolbox.mm": "430686c04b00254760190e884c1ac15e1a77ac1a926baf87dccba9b9c243fedc", - "native/macos/Info.plist": "39447564e34055078259dd199bd70a32b51f7cefb5d1e43946d4824cd737f80f", - "native/macos/build.sh": "4348d1791a77765765b35584694e4d7165cb0dd8a1a250f0f8a1625dfab94254", - "native/macos/verify.sh": "4bc8d86f29b1ca4281843340240ecf869d2fd88363d12eb59b496615c4e013d3", - "src/BazaarPlusPlus/Game/CombatReplay/Audio/CoreAudioProcessTapCaptureTap.cs": "14799e5fc8ad2bd367d7134093185900f95329f93be83d969c0a2dfd00a5b7e2", - "src/BazaarPlusPlus/Game/CombatReplay/Audio/ReplayAudioCaptureFactory.cs": "1bd0f4fc76e4b90f8fced44ad62b1d5c4ebefc04f118db0554d57d2f1cf2cd32", - "src/BazaarPlusPlus/Game/CombatReplay/Video/MacMetalVideoEncoder.cs": "beece51137e74737bacb16ca88d8f48c795284ed8ed71870d1cf60ddcb96ca92", - "src/BazaarPlusPlus/Game/CombatReplay/Video/MacNativeReplayAudioMuxer.cs": "2eb6987fc81db5438146f262fc9edf1644f95c1ce2dc5e1c850aa83bdc3528ab" - }, - "policy": { - "architecture": "arm64", - "deploymentTarget": "12.0", - "signing": "adhoc" - }, - "producer": { - "repository": "BazaarPlusPlus/bazaarplusplus-mod", - "commit": "a50b60ecfe4368ad9865006185e4564878ed86e1", - "dirty": false - }, - "artifacts": { - "mac-audio": { - "destinationPath": "src-tauri/resources/SourceForBuild/macos/BepInEx/plugins/libBppMacAudio.dylib", - "content": { - "kind": "file", - "size": 53328, - "sha256": "7459bbdaa212f22233fac629ac190eacd9582107e1e72604517708be2c6a49c9" - } - }, - "mac-replay": { - "destinationPath": "src-tauri/resources/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle", - "content": { - "kind": "directory", - "entries": { - "Contents": { - "kind": "directory" - }, - "Contents/Info.plist": { - "kind": "file", - "size": 765, - "sha256": "39447564e34055078259dd199bd70a32b51f7cefb5d1e43946d4824cd737f80f" - }, - "Contents/MacOS": { - "kind": "directory" - }, - "Contents/MacOS/GfxPluginBppReplayVideoToolbox": { - "kind": "file", - "size": 102096, - "sha256": "decae99757e27842c0e572176aae09f6e954ad054f6947603ae7f45b63293886" - }, - "Contents/_CodeSignature": { - "kind": "directory" - }, - "Contents/_CodeSignature/CodeResources": { - "kind": "file", - "size": 2200, - "sha256": "6686de10a28a2fe11b36cbb86dcbacc827cfc4ea116b4dabf1845e5aee629e9b" - } - } - } - } - } - }, - "windows": { - "inputDigest": "sha256:cb2fe5f3d59363bb8464c7d09d5a4c1eaec54f46295328671956df54f930cc03", - "inputFiles": { - "native/windows/BppReplayMediaFoundation.cpp": "2f0395be1e5e8d9c008745db420b9351dccfad197db3ab2c26b5c516414546ef", - "native/windows/BppReplayMediaFoundation.h": "977b6070ac230e7c44a62bc756f9fee7bb74489ff8845928908ca0b6b573b660", - "native/windows/BppReplayMediaFoundationSmoke.cpp": "71f52734ad638350df2272d8a0ad5dd2fa1402220198c179792c4fee71e7d0b5", - "native/windows/build.ps1": "75b2a0bdb143a975fceb80c96b95e7218fce3fb926dff0badccc6d9c04bdb295", - "native/windows/test.ps1": "8556acb4b93c05aae7ffc4e83aa30321206a34961c95543bc976db76a4b43164", - "src/BazaarPlusPlus/Game/CombatReplay/Video/WindowsMediaFoundationVideoEncoder.cs": "bd9d5ba7f1d596632045ff59c224b8e8a9b279a4c3e574d0054ae262dc297f2a", - "src/BazaarPlusPlus/Game/CombatReplay/Video/WindowsNativeReplayAudioMuxer.cs": "41fa3e3f8cc809f187498a82cb53056afc6c25dc1a5c3b86ff1e57e114f0b4d8" - }, - "policy": { - "architecture": "x64", - "signing": "unsigned" - }, - "producer": { - "repository": "BazaarPlusPlus/bazaarplusplus-mod", - "commit": "65a89e1d264d6dd455284d69b66e647dc0b8e143", - "dirty": true - }, - "artifacts": { - "windows-replay": { - "destinationPath": "src-tauri/resources/SourceForBuild/windows/TheBazaar_Data/Plugins/x86_64/GfxPluginBppReplayMediaFoundation.dll", - "content": { - "kind": "file", - "size": 202752, - "sha256": "ff7594cff2343da17f29e5a8b184d3c45b8e398d23fefa55ff880fabc658bd26" - } - } - } - } - } -} diff --git a/bazaarplusplus-installer/scripts/release/release-platforms.test.mjs b/bazaarplusplus-installer/scripts/release/release-platforms.test.mjs deleted file mode 100644 index 54d343b..0000000 --- a/bazaarplusplus-installer/scripts/release/release-platforms.test.mjs +++ /dev/null @@ -1,64 +0,0 @@ -import { test, expect } from 'vitest'; -import path from 'node:path'; -import { runShell } from '../test-support/shell.mjs'; -import { - RELEASE_PLATFORMS, - replayRecorderBundlePath, - resolveBuildPlatform, - defaultTargetBuildPlatforms -} from '../../../release/release-platforms.mjs'; -import { resolveBundleCleanupPath } from './before-bundle-cleanup.mjs'; -import { resolveTargetPlatforms } from '../checks/prebuild-check.mjs'; - -test.each(RELEASE_PLATFORMS)( - 'bundle.sh facts for $buildPlatform come from the module', - (p) => { - const out = runShell( - ` - set -euo pipefail - source ./scripts/bundle.sh - printf 'rust=[%s]\\n' "$(release_platforms_cli rust-targets "$BPP_TEST_BUILD_PLATFORM")" - # Only the macOS Payload carries a replay recorder plugin bundle to sign. - if [ "$BPP_TEST_BUILD_PLATFORM" = macos ]; then - printf 'replay=%s\\n' "$(release_platforms_cli replay-recorder-bundle "$BPP_TEST_BUILD_PLATFORM")" - fi - `, - { BPP_TEST_BUILD_PLATFORM: p.buildPlatform } - ); - expect(out).toContain(`rust=[${p.rustTarget ?? ''}]`); - if (p.buildPlatform === 'macos') { - expect(out).toContain( - `replay=${replayRecorderBundlePath(p.buildPlatform)}` - ); - } - } -); - -test.each(RELEASE_PLATFORMS)( - 'before-bundle-cleanup dir for $key matches the module', - (p) => { - const expected = path.join('/root', ...p.bundleCleanupDir.split('/')); - expect(resolveBundleCleanupPath('/root', p.buildPlatform)).toBe(expected); - expect(resolveBundleCleanupPath('/root', p.nodePlatform)).toBe(expected); - } -); - -test('prebuild-check target platforms derive from the table', () => { - expect(resolveTargetPlatforms(undefined)).toEqual( - defaultTargetBuildPlatforms() - ); - expect(defaultTargetBuildPlatforms()).toEqual(['macos', 'windows']); - for (const p of RELEASE_PLATFORMS) { - expect(resolveBuildPlatform(p.nodePlatform)).toBe(p.buildPlatform); - } -}); - -test('rust-targets rejects an unsupported platform', () => { - const out = runShell(` - source ./scripts/bundle.sh - set +e - release_platforms_cli rust-targets linux 2>&1 - printf 'exit:%s\\n' "$?" - `); - expect(out).toContain('exit:1'); -}); diff --git a/bazaarplusplus-installer/scripts/tauri-source-env.mjs b/bazaarplusplus-installer/scripts/tauri-source-env.mjs deleted file mode 100644 index 6fd8fa5..0000000 --- a/bazaarplusplus-installer/scripts/tauri-source-env.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// tauri-build copies bundle resources even during clippy/test/doc. Source -// checks and binding export need no prepared release ZIP. Return a child-only -// override so subsequent packaging still checks the real bundle inputs. -export function tauriSourceEnvironment(base = process.env) { - let config; - try { - config = JSON.parse(base.TAURI_CONFIG || '{}'); - } catch { - throw new Error('Invalid TAURI_CONFIG for source verification'); - } - return { - ...base, - TAURI_CONFIG: JSON.stringify({ - ...config, - bundle: { ...config?.bundle, resources: [] } - }) - }; -} diff --git a/bazaarplusplus-installer/scripts/test-support/git-fixture.test.mjs b/bazaarplusplus-installer/scripts/test-support/git-fixture.test.mjs deleted file mode 100644 index a9e2107..0000000 --- a/bazaarplusplus-installer/scripts/test-support/git-fixture.test.mjs +++ /dev/null @@ -1,89 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, expect, test, vi } from 'vitest'; - -import { gitEnvironment } from '../../../scripts/git-command.mjs'; -import { runFixtureGit } from '../../../scripts/test-support/git-fixture.mjs'; - -// Every file under `directory`, as sorted `relative path:size` lines. Enough to -// notice a new ref, a rewritten HEAD, a config append, or a fresh object. -function directorySnapshot(directory) { - return fs - .readdirSync(directory, { recursive: true, withFileTypes: true }) - .filter((entry) => entry.isFile()) - .map((entry) => { - const filePath = path.join(entry.parentPath, entry.name); - return `${path.relative(directory, filePath)}:${fs.statSync(filePath).size}`; - }) - .sort() - .join('\n'); -} - -afterEach(() => { - vi.unstubAllEnvs(); -}); - -test('fixture git ignores an inherited repository location', () => { - const temporaryRoot = fs.mkdtempSync( - path.join(os.tmpdir(), 'bpp-git-fixture-test-') - ); - try { - const decoyRepository = path.join(temporaryRoot, 'decoy.git'); - fs.mkdirSync(decoyRepository); - runFixtureGit(['init', '--bare', '-q'], { cwd: decoyRepository }); - const decoyBefore = directorySnapshot(decoyRepository); - - // Exactly the incident: a parent process exported GIT_DIR (plus a work - // tree) before the test suite ran. - const workTree = path.join(temporaryRoot, 'decoy-worktree'); - fs.mkdirSync(workTree); - vi.stubEnv('GIT_DIR', decoyRepository); - vi.stubEnv('GIT_WORK_TREE', workTree); - expect(gitEnvironment().GIT_DIR).toBeUndefined(); - expect(gitEnvironment().GIT_WORK_TREE).toBeUndefined(); - - const fixtureRepository = path.join(temporaryRoot, 'fixture'); - fs.mkdirSync(fixtureRepository); - fs.writeFileSync(path.join(fixtureRepository, 'input.txt'), 'fixture body'); - runFixtureGit(['init', '-q'], { cwd: fixtureRepository }); - runFixtureGit(['config', 'user.name', 'Fixture Test'], { - cwd: fixtureRepository - }); - runFixtureGit(['config', 'user.email', 'fixture@example.test'], { - cwd: fixtureRepository - }); - runFixtureGit(['add', '.'], { cwd: fixtureRepository }); - runFixtureGit(['commit', '-qm', 'fixture inputs'], { - cwd: fixtureRepository - }); - - // The fixture repository is where it was asked to be, and holds the commit. - expect(fs.existsSync(path.join(fixtureRepository, '.git', 'HEAD'))).toBe( - true - ); - expect( - runFixtureGit(['log', '-1', '--pretty=%s'], { - cwd: fixtureRepository - }).trim() - ).toBe('fixture inputs'); - expect( - runFixtureGit(['config', 'user.name'], { cwd: fixtureRepository }).trim() - ).toBe('Fixture Test'); - - // The repository named by GIT_DIR never saw any of it. - expect(directorySnapshot(decoyRepository)).toBe(decoyBefore); - expect( - fs.readFileSync(path.join(decoyRepository, 'config'), 'utf8') - ).not.toMatch(/Fixture Test/); - expect(fs.readFileSync(path.join(decoyRepository, 'HEAD'), 'utf8')).toBe( - 'ref: refs/heads/main\n' - ); - } finally { - fs.rmSync(temporaryRoot, { recursive: true, force: true }); - } -}); - -test('fixture git refuses a command without an explicit fixture cwd', () => { - expect(() => runFixtureGit(['status'])).toThrow(/explicit cwd/); -}); diff --git a/bazaarplusplus-installer/scripts/test-support/shell.mjs b/bazaarplusplus-installer/scripts/test-support/shell.mjs deleted file mode 100644 index 6c1379d..0000000 --- a/bazaarplusplus-installer/scripts/test-support/shell.mjs +++ /dev/null @@ -1,56 +0,0 @@ -import { execFileSync } from 'node:child_process'; -import { existsSync } from 'node:fs'; -import { runGit } from '../../../scripts/git-command.mjs'; - -const projectDir = process.cwd(); - -// Resolve a usable bash. On Windows, `bash` is frequently absent from the PATH -// that npm spawns with (PowerShell/cmd), so fall back to the Git for Windows -// install before giving up. -export function resolveBashCommand() { - if (process.platform !== 'win32') { - return 'bash'; - } - const candidates = []; - if (process.env.BPP_BASH) { - candidates.push(process.env.BPP_BASH); - } - try { - const execPath = runGit(['--exec-path']).trim(); - const gitRoot = execPath.replace(/[/\\](mingw\d+|usr)[/\\].*$/i, ''); - if (gitRoot && gitRoot !== execPath) { - candidates.push(`${gitRoot}/bin/bash.exe`); - } - } catch { - // git not on PATH; fall back to the well-known install locations below. - } - candidates.push( - 'C:/Program Files/Git/bin/bash.exe', - 'C:/Program Files (x86)/Git/bin/bash.exe' - ); - return ( - candidates.find((candidate) => candidate && existsSync(candidate)) ?? 'bash' - ); -} - -const bashCommand = resolveBashCommand(); - -// Git Bash treats `E:\foo` as a relative path, so paths handed to bundle.sh -// must be POSIX-style absolute (`/e/foo`) on Windows. -export function toBashPath(p) { - return p - .replace(/\\/g, '/') - .replace(/^([A-Za-z]):/, (_, drive) => `/${drive.toLowerCase()}`); -} - -// Read static script text from stdin and dynamic values from the environment. -// Git Bash on Windows reinterprets quotes and globs in native process arguments. -export function runShell(script, env = {}) { - return execFileSync(bashCommand, ['-s'], { - cwd: projectDir, - env: { ...process.env, ...env }, - input: script, - encoding: 'utf8', - timeout: 120000 - }); -} diff --git a/bazaarplusplus-installer/scripts/test-support/shell.test.mjs b/bazaarplusplus-installer/scripts/test-support/shell.test.mjs deleted file mode 100644 index 2b6b966..0000000 --- a/bazaarplusplus-installer/scripts/test-support/shell.test.mjs +++ /dev/null @@ -1,32 +0,0 @@ -import { expect, test } from 'vitest'; -import { runShell } from './shell.mjs'; - -test('shell environment preserves empty values, boundaries and shell syntax', () => { - const env = { - BPP_TEST_EMPTY: '', - BPP_TEST_SPACES: 'path with spaces', - BPP_TEST_SINGLE_QUOTES: "path'with'quotes", - BPP_TEST_DOUBLE_QUOTES: 'path"with"quotes', - BPP_TEST_SUBSTITUTION: '$(printf injected)', - BPP_TEST_BACKTICKS: '`printf injected`', - BPP_TEST_COMMAND: '; printf injected #', - BPP_TEST_BACKSLASHES: 'C:\\path\\with\\backslashes', - BPP_TEST_NEWLINE: 'line\nbreak', - BPP_TEST_GLOB: '*?[glob]', - BPP_TEST_OPTION: '-option' - }; - - const output = runShell( - `printf '%s\\0' "$BPP_TEST_EMPTY" "$BPP_TEST_SPACES" \\ - "$BPP_TEST_SINGLE_QUOTES" "$BPP_TEST_DOUBLE_QUOTES" \\ - "$BPP_TEST_SUBSTITUTION" "$BPP_TEST_BACKTICKS" "$BPP_TEST_COMMAND" \\ - "$BPP_TEST_BACKSLASHES" "$BPP_TEST_NEWLINE" "$BPP_TEST_GLOB" "$BPP_TEST_OPTION"`, - env - ); - - expect(output).toBe( - Object.values(env) - .map((value) => `${value}\0`) - .join('') - ); -}); diff --git a/bazaarplusplus-installer/src-tauri/.cargo/config.toml b/bazaarplusplus-installer/src-tauri/.cargo/config.toml deleted file mode 100644 index 7e2960c..0000000 --- a/bazaarplusplus-installer/src-tauri/.cargo/config.toml +++ /dev/null @@ -1,10 +0,0 @@ -# ts-rs export directory for #[ts(export)] types (see scripts/generate-bindings.mjs). -[env] -TS_RS_EXPORT_DIR = { value = "../src/types/generated/bindings", relative = true } -TS_RS_LARGE_INT = "number" - -# Tauri builds this library as a cdylib as well as the application. MinGW's -# default all-symbol export exceeds the PE export-ordinal limit, while the -# application does not consume that cdylib's exports. -[target.x86_64-pc-windows-gnu] -rustflags = ["-C", "link-arg=-Wl,--exclude-all-symbols"] diff --git a/bazaarplusplus-installer/src-tauri/Cargo.lock b/bazaarplusplus-installer/src-tauri/Cargo.lock deleted file mode 100644 index 2f3c238..0000000 --- a/bazaarplusplus-installer/src-tauri/Cargo.lock +++ /dev/null @@ -1,6055 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "Inflector" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "alloc-no-stdlib" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" - -[[package]] -name = "alloc-stdlib" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" -dependencies = [ - "alloc-no-stdlib", -] - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - -[[package]] -name = "async-broadcast" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" -dependencies = [ - "event-listener", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-channel" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" -dependencies = [ - "concurrent-queue", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-executor" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" -dependencies = [ - "async-task", - "concurrent-queue", - "fastrand", - "futures-lite", - "pin-project-lite", - "slab", -] - -[[package]] -name = "async-io" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" -dependencies = [ - "autocfg", - "cfg-if", - "concurrent-queue", - "futures-io", - "futures-lite", - "parking", - "polling", - "rustix", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-lock" -version = "3.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" -dependencies = [ - "event-listener", - "event-listener-strategy", - "pin-project-lite", -] - -[[package]] -name = "async-process" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" -dependencies = [ - "async-channel", - "async-io", - "async-lock", - "async-signal", - "async-task", - "blocking", - "cfg-if", - "event-listener", - "futures-lite", - "rustix", -] - -[[package]] -name = "async-recursion" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "async-signal" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" -dependencies = [ - "async-io", - "async-lock", - "atomic-waker", - "cfg-if", - "futures-core", - "futures-io", - "rustix", - "signal-hook-registry", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-task" -version = "4.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "atk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" -dependencies = [ - "atk-sys", - "glib", - "libc", -] - -[[package]] -name = "atk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "axum" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" -dependencies = [ - "axum-core", - "bytes", - "form_urlencoded", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-util", - "itoa", - "matchit", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "serde_core", - "serde_json", - "serde_path_to_error", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tower", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "axum-core" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "mime", - "pin-project-lite", - "sync_wrapper", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "base64" -version = "0.21.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "base64" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" - -[[package]] -name = "bit-set" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -dependencies = [ - "serde_core", -] - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-buffer" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "block2" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" -dependencies = [ - "objc2", -] - -[[package]] -name = "blocking" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" -dependencies = [ - "async-channel", - "async-task", - "futures-io", - "futures-lite", - "piper", -] - -[[package]] -name = "bppinstaller" -version = "6.0.0" -dependencies = [ - "axum", - "base64 0.23.1", - "chrono", - "dirs", - "image", - "include_dir", - "keyvalues-parser", - "libc", - "rusqlite", - "serde", - "serde_json", - "sha2 0.11.0", - "specta", - "specta-typescript", - "tauri", - "tauri-build", - "tauri-plugin-dialog", - "tauri-plugin-opener", - "tauri-plugin-process", - "tauri-plugin-single-instance", - "tauri-plugin-updater", - "tauri-plugin-window-state", - "tauri-specta", - "tempfile", - "tokio", - "tower", - "tower-http 0.7.1", - "windows", - "winreg 0.56.0", - "zip 9.0.2", -] - -[[package]] -name = "brotli" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", -] - -[[package]] -name = "brotli-decompressor" -version = "6.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", -] - -[[package]] -name = "bs58" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "byteorder-lite" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" -dependencies = [ - "serde", -] - -[[package]] -name = "cairo-rs" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" -dependencies = [ - "bitflags 2.13.2", - "cairo-sys-rs", - "glib", - "libc", - "once_cell", - "thiserror 1.0.69", -] - -[[package]] -name = "cairo-sys-rs" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" -dependencies = [ - "glib-sys", - "libc", - "system-deps", -] - -[[package]] -name = "camino" -version = "1.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" -dependencies = [ - "serde_core", -] - -[[package]] -name = "cargo-platform" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" -dependencies = [ - "serde", -] - -[[package]] -name = "cargo_metadata" -version = "0.19.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" -dependencies = [ - "camino", - "cargo-platform", - "semver", - "serde", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "cargo_toml" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" -dependencies = [ - "semver", - "serde", - "toml 1.1.6+spec-1.1.0", -] - -[[package]] -name = "cc" -version = "1.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cesu8" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" - -[[package]] -name = "cfb" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3" -dependencies = [ - "fnv", - "uuid", - "web-time", -] - -[[package]] -name = "cfg-expr" -version = "0.15.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" -dependencies = [ - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "cfg_aliases" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "combine" -version = "4.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" -dependencies = [ - "bytes", - "memchr", -] - -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "const-oid" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" - -[[package]] -name = "cookie" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" -dependencies = [ - "time", - "version_check", -] - -[[package]] -name = "core-foundation" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "core-graphics" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", - "core-graphics-types", - "foreign-types", - "libc", -] - -[[package]] -name = "core-graphics-types" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "crypto-common" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "cssparser" -version = "0.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" -dependencies = [ - "cssparser-macros", - "dtoa-short", - "itoa", - "phf", - "smallvec", -] - -[[package]] -name = "cssparser-macros" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" -dependencies = [ - "quote", - "syn 2.0.119", -] - -[[package]] -name = "ctor" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" - -[[package]] -name = "darling" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 3.0.6", -] - -[[package]] -name = "darling_macro" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" -dependencies = [ - "darling_core", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "dbus" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" -dependencies = [ - "libc", - "libdbus-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "defmt" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" -dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "defmt-parser" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" -dependencies = [ - "thiserror 2.0.20", -] - -[[package]] -name = "deranged" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -dependencies = [ - "serde_core", -] - -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "derive_more" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" -dependencies = [ - "derive_more-impl", -] - -[[package]] -name = "derive_more-impl" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "syn 2.0.119", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", -] - -[[package]] -name = "digest" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" -dependencies = [ - "block-buffer 0.12.1", - "const-oid", - "crypto-common 0.2.2", -] - -[[package]] -name = "dirs" -version = "7.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.61.2", -] - -[[package]] -name = "dispatch2" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" -dependencies = [ - "bitflags 2.13.2", - "block2", - "libc", - "objc2", -] - -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "dlopen2" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" -dependencies = [ - "dlopen2_derive", - "libc", - "once_cell", - "winapi", -] - -[[package]] -name = "dlopen2_derive" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "dom_query" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" -dependencies = [ - "bit-set", - "cssparser", - "foldhash", - "html5ever", - "precomputed-hash", - "selectors", - "tendril", -] - -[[package]] -name = "dpi" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" -dependencies = [ - "serde", -] - -[[package]] -name = "dtoa" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" - -[[package]] -name = "dtoa-short" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" -dependencies = [ - "dtoa", -] - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "dyn-clone" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" - -[[package]] -name = "embed-resource" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd" -dependencies = [ - "cc", - "memchr", - "rustc_version", - "toml 1.1.6+spec-1.1.0", - "vswhom", - "winreg 0.55.0", -] - -[[package]] -name = "embed_plist" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" - -[[package]] -name = "endi" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" - -[[package]] -name = "enumflags2" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" -dependencies = [ - "enumflags2_derive", - "serde", -] - -[[package]] -name = "enumflags2_derive" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "erased-serde" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" -dependencies = [ - "serde", - "serde_core", - "typeid", -] - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "event-listener" -version = "5.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" -dependencies = [ - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener", - "pin-project-lite", -] - -[[package]] -name = "fallible-iterator" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" - -[[package]] -name = "fallible-streaming-iterator" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" - -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "field-offset" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" -dependencies = [ - "memoffset", - "rustc_version", -] - -[[package]] -name = "filetime" -version = "0.2.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" -dependencies = [ - "cfg-if", - "libc", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" - -[[package]] -name = "flate2" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" -dependencies = [ - "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "foreign-types" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" -dependencies = [ - "foreign-types-macros", - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-macros" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "foreign-types-shared" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-executor" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-lite" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" -dependencies = [ - "fastrand", - "futures-core", - "futures-io", - "parking", - "pin-project-lite", -] - -[[package]] -name = "futures-macro" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "gdk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" -dependencies = [ - "cairo-rs", - "gdk-pixbuf", - "gdk-sys", - "gio", - "glib", - "libc", - "pango", -] - -[[package]] -name = "gdk-pixbuf" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" -dependencies = [ - "gdk-pixbuf-sys", - "gio", - "glib", - "libc", - "once_cell", -] - -[[package]] -name = "gdk-pixbuf-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" -dependencies = [ - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gdk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" -dependencies = [ - "cairo-sys-rs", - "gdk-pixbuf-sys", - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "pango-sys", - "pkg-config", - "system-deps", -] - -[[package]] -name = "gdkwayland-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" -dependencies = [ - "gdk-sys", - "glib-sys", - "gobject-sys", - "libc", - "pkg-config", - "system-deps", -] - -[[package]] -name = "gdkx11" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" -dependencies = [ - "gdk", - "gdkx11-sys", - "gio", - "glib", - "libc", - "x11", -] - -[[package]] -name = "gdkx11-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" -dependencies = [ - "gdk-sys", - "glib-sys", - "libc", - "system-deps", - "x11", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", -] - -[[package]] -name = "gio" -version = "0.18.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-util", - "gio-sys", - "glib", - "libc", - "once_cell", - "pin-project-lite", - "smallvec", - "thiserror 1.0.69", -] - -[[package]] -name = "gio-sys" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", - "winapi", -] - -[[package]] -name = "glib" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" -dependencies = [ - "bitflags 2.13.2", - "futures-channel", - "futures-core", - "futures-executor", - "futures-task", - "futures-util", - "gio-sys", - "glib-macros", - "glib-sys", - "gobject-sys", - "libc", - "memchr", - "once_cell", - "smallvec", - "thiserror 1.0.69", -] - -[[package]] -name = "glib-macros" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" -dependencies = [ - "heck 0.4.1", - "proc-macro-crate 2.0.2", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "glib-sys" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" -dependencies = [ - "libc", - "system-deps", -] - -[[package]] -name = "glob" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" - -[[package]] -name = "gobject-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" -dependencies = [ - "glib-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gtk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" -dependencies = [ - "atk", - "cairo-rs", - "field-offset", - "futures-channel", - "gdk", - "gdk-pixbuf", - "gio", - "glib", - "gtk-sys", - "gtk3-macros", - "libc", - "pango", - "pkg-config", -] - -[[package]] -name = "gtk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" -dependencies = [ - "atk-sys", - "cairo-sys-rs", - "gdk-pixbuf-sys", - "gdk-sys", - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "pango-sys", - "system-deps", -] - -[[package]] -name = "gtk3-macros" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" -dependencies = [ - "proc-macro-crate 1.3.1", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" -dependencies = [ - "foldhash", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" -dependencies = [ - "foldhash", -] - -[[package]] -name = "hashlink" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" -dependencies = [ - "hashbrown 0.17.1", -] - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hermit-abi" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "html5ever" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" -dependencies = [ - "log", - "markup5ever", -] - -[[package]] -name = "http" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "http-body" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hybrid-array" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" -dependencies = [ - "typenum", -] - -[[package]] -name = "hyper" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-util" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "system-configuration", - "tokio", - "tower-service", - "tracing", - "windows-registry", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "ico" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371" -dependencies = [ - "byteorder", - "png 0.17.16", -] - -[[package]] -name = "icu_collections" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" - -[[package]] -name = "icu_properties" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" - -[[package]] -name = "icu_provider" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "image" -version = "0.25.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" -dependencies = [ - "bytemuck", - "byteorder-lite", - "image-webp", - "moxcms", - "num-traits", - "png 0.18.1", - "zune-core", - "zune-jpeg", -] - -[[package]] -name = "image-webp" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" -dependencies = [ - "byteorder-lite", - "quick-error", -] - -[[package]] -name = "include_dir" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" -dependencies = [ - "include_dir_macros", -] - -[[package]] -name = "include_dir_macros" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "serde", -] - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown 0.17.1", - "serde", - "serde_core", -] - -[[package]] -name = "infer" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" -dependencies = [ - "cfb", -] - -[[package]] -name = "ipnet" -version = "2.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" - -[[package]] -name = "is-docker" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" -dependencies = [ - "once_cell", -] - -[[package]] -name = "is-wsl" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" -dependencies = [ - "is-docker", - "once_cell", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "javascriptcore-rs" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" -dependencies = [ - "bitflags 1.3.2", - "glib", - "javascriptcore-rs-sys", -] - -[[package]] -name = "javascriptcore-rs-sys" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "jiff" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" -dependencies = [ - "defmt", - "jiff-core", - "jiff-static", - "jiff-tzdb-platform", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", - "windows-link", -] - -[[package]] -name = "jiff-core" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" -dependencies = [ - "defmt", - "log", -] - -[[package]] -name = "jiff-static" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" -dependencies = [ - "jiff-core", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "jiff-tzdb" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" - -[[package]] -name = "jiff-tzdb-platform" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" -dependencies = [ - "jiff-tzdb", -] - -[[package]] -name = "jni" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" -dependencies = [ - "cesu8", - "cfg-if", - "combine", - "jni-sys 0.3.1", - "log", - "thiserror 1.0.69", - "walkdir", - "windows-sys 0.45.0", -] - -[[package]] -name = "jni" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" -dependencies = [ - "cfg-if", - "combine", - "jni-macros", - "jni-sys 0.4.1", - "log", - "simd_cesu8", - "thiserror 2.0.20", - "walkdir", - "windows-link", -] - -[[package]] -name = "jni-macros" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "simd_cesu8", - "syn 2.0.119", -] - -[[package]] -name = "jni-sys" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" -dependencies = [ - "jni-sys 0.4.1", -] - -[[package]] -name = "jni-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" -dependencies = [ - "jni-sys-macros", -] - -[[package]] -name = "jni-sys-macros" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" -dependencies = [ - "quote", - "syn 2.0.119", -] - -[[package]] -name = "js-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "json-patch" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" -dependencies = [ - "jsonptr", - "serde", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "jsonptr" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "keyboard-types" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" -dependencies = [ - "bitflags 2.13.2", - "serde", -] - -[[package]] -name = "keyvalues-parser" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eded51a3b2cdcdc173e23683fd49f72e8151160b279f80c0378f7661a2ae10b7" -dependencies = [ - "pest", -] - -[[package]] -name = "libappindicator" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" -dependencies = [ - "glib", - "gtk", - "gtk-sys", - "libappindicator-sys", - "log", -] - -[[package]] -name = "libappindicator-sys" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" -dependencies = [ - "gtk-sys", - "libloading", - "once_cell", -] - -[[package]] -name = "libc" -version = "0.2.190" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" - -[[package]] -name = "libdbus-sys" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" -dependencies = [ - "pkg-config", -] - -[[package]] -name = "libloading" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" -dependencies = [ - "cfg-if", - "winapi", -] - -[[package]] -name = "libredox" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6480ccc157a1389bb2e4891b24751b0f798ba640d22386f23143fbcc89da195a" -dependencies = [ - "libc", -] - -[[package]] -name = "libsqlite3-sys" -version = "0.38.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" -dependencies = [ - "cc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "litemap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" - -[[package]] -name = "markup5ever" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" -dependencies = [ - "log", - "tendril", - "web_atoms", -] - -[[package]] -name = "matchit" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "minisign-verify" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce" - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "mio" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "moxcms" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" -dependencies = [ - "num-traits", - "pxfm", -] - -[[package]] -name = "muda" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" -dependencies = [ - "crossbeam-channel", - "dpi", - "gtk", - "keyboard-types", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "once_cell", - "png 0.18.1", - "serde", - "thiserror 2.0.20", - "windows-sys 0.61.2", -] - -[[package]] -name = "ndk" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" -dependencies = [ - "bitflags 2.13.2", - "jni-sys 0.3.1", - "log", - "ndk-sys", - "num_enum", - "raw-window-handle", - "thiserror 1.0.69", -] - -[[package]] -name = "ndk-context" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" - -[[package]] -name = "ndk-sys" -version = "0.6.0+11769913" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" -dependencies = [ - "jni-sys 0.3.1", -] - -[[package]] -name = "new_debug_unreachable" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" - -[[package]] -name = "nix" -version = "0.31.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" -dependencies = [ - "bitflags 2.13.2", - "cfg-if", - "cfg_aliases", - "libc", -] - -[[package]] -name = "num-conv" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_enum" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" -dependencies = [ - "num_enum_derive", - "rustversion", -] - -[[package]] -name = "num_enum_derive" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "objc2" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" -dependencies = [ - "objc2-encode", - "objc2-exception-helper", -] - -[[package]] -name = "objc2-app-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" -dependencies = [ - "bitflags 2.13.2", - "block2", - "objc2", - "objc2-core-foundation", - "objc2-foundation", - "objc2-quartz-core", -] - -[[package]] -name = "objc2-cloud-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-data" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" -dependencies = [ - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" -dependencies = [ - "bitflags 2.13.2", - "dispatch2", - "objc2", -] - -[[package]] -name = "objc2-core-graphics" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" -dependencies = [ - "bitflags 2.13.2", - "dispatch2", - "objc2", - "objc2-core-foundation", - "objc2-io-surface", -] - -[[package]] -name = "objc2-core-image" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" -dependencies = [ - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-location" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" -dependencies = [ - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-text" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-core-foundation", - "objc2-core-graphics", -] - -[[package]] -name = "objc2-encode" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" - -[[package]] -name = "objc2-exception-helper" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" -dependencies = [ - "cc", -] - -[[package]] -name = "objc2-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" -dependencies = [ - "bitflags 2.13.2", - "block2", - "libc", - "objc2", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-io-surface" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-osa-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-app-kit", - "objc2-foundation", -] - -[[package]] -name = "objc2-quartz-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-core-foundation", - "objc2-foundation", -] - -[[package]] -name = "objc2-ui-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" -dependencies = [ - "bitflags 2.13.2", - "block2", - "objc2", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-core-image", - "objc2-core-location", - "objc2-core-text", - "objc2-foundation", - "objc2-quartz-core", - "objc2-user-notifications", -] - -[[package]] -name = "objc2-user-notifications" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" -dependencies = [ - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-web-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" -dependencies = [ - "bitflags 2.13.2", - "block2", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "open" -version = "5.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc" -dependencies = [ - "dunce", - "is-wsl", - "libc", -] - -[[package]] -name = "openssl-probe" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - -[[package]] -name = "ordered-stream" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" -dependencies = [ - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "osakit" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" -dependencies = [ - "objc2", - "objc2-foundation", - "objc2-osa-kit", - "serde", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "pango" -version = "0.18.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" -dependencies = [ - "gio", - "glib", - "libc", - "once_cell", - "pango-sys", -] - -[[package]] -name = "pango-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pest" -version = "2.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d45aeb61b4bf818e12d4205f2466f8c4748f85f4fce0146d1c03d69d753f0ad" -dependencies = [ - "memchr", - "ucd-trie", -] - -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_macros", - "phf_shared", - "serde", -] - -[[package]] -name = "phf_codegen" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" -dependencies = [ - "phf_generator", - "phf_shared", -] - -[[package]] -name = "phf_generator" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" -dependencies = [ - "fastrand", - "phf_shared", -] - -[[package]] -name = "phf_macros" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "piper" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" -dependencies = [ - "atomic-waker", - "fastrand", - "futures-io", -] - -[[package]] -name = "pkg-config" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" - -[[package]] -name = "plist" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb" -dependencies = [ - "base64 0.23.1", - "indexmap 2.14.2", - "quick-xml", - "serde", - "time", -] - -[[package]] -name = "png" -version = "0.17.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "png" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" -dependencies = [ - "bitflags 2.13.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "polling" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" -dependencies = [ - "cfg-if", - "concurrent-queue", - "hermit-abi", - "pin-project-lite", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - -[[package]] -name = "portable-atomic-util" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" -dependencies = [ - "portable-atomic", -] - -[[package]] -name = "potential_utf" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" -dependencies = [ - "zerovec", -] - -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - -[[package]] -name = "precomputed-hash" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" - -[[package]] -name = "proc-macro-crate" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" -dependencies = [ - "once_cell", - "toml_edit 0.19.15", -] - -[[package]] -name = "proc-macro-crate" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" -dependencies = [ - "toml_datetime 0.6.3", - "toml_edit 0.20.2", -] - -[[package]] -name = "proc-macro-crate" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" -dependencies = [ - "toml_edit 0.25.15+spec-1.1.0", -] - -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote", - "syn 1.0.109", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote", - "version_check", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pxfm" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" - -[[package]] -name = "quick-error" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" - -[[package]] -name = "quick-xml" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" -dependencies = [ - "memchr", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "raw-window-handle" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "redox_users" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" -dependencies = [ - "libredox", - "thiserror 2.0.20", -] - -[[package]] -name = "ref-cast" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "reqwest" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" -dependencies = [ - "base64 0.23.1", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "rustls", - "rustls-pki-types", - "rustls-platform-verifier", - "serde", - "serde_json", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tokio-util", - "tower", - "tower-http 0.6.11", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-streams", - "web-sys", -] - -[[package]] -name = "rfd" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672" -dependencies = [ - "block2", - "dispatch2", - "glib-sys", - "gobject-sys", - "gtk-sys", - "js-sys", - "log", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "raw-window-handle", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "windows-sys 0.60.2", -] - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - -[[package]] -name = "rsqlite-vfs" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" -dependencies = [ - "hashbrown 0.16.1", - "thiserror 2.0.20", -] - -[[package]] -name = "rusqlite" -version = "0.40.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" -dependencies = [ - "bitflags 2.13.2", - "fallible-iterator", - "fallible-streaming-iterator", - "hashlink", - "libsqlite3-sys", - "smallvec", - "sqlite-wasm-rs", -] - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - -[[package]] -name = "rustix" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" -dependencies = [ - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-native-certs" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" -dependencies = [ - "openssl-probe", - "rustls-pki-types", - "schannel", - "security-framework", -] - -[[package]] -name = "rustls-pki-types" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" -dependencies = [ - "zeroize", -] - -[[package]] -name = "rustls-platform-verifier" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" -dependencies = [ - "core-foundation 0.10.1", - "core-foundation-sys", - "jni 0.22.4", - "log", - "once_cell", - "rustls", - "rustls-native-certs", - "rustls-platform-verifier-android", - "rustls-webpki", - "security-framework", - "security-framework-sys", - "webpki-root-certs", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls-platform-verifier-android" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" - -[[package]] -name = "rustls-webpki" -version = "0.103.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "ryu" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "schannel" -version = "0.1.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "schemars" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" -dependencies = [ - "dyn-clone", - "indexmap 1.9.3", - "schemars_derive", - "serde", - "serde_json", - "url", - "uuid", -] - -[[package]] -name = "schemars" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" -dependencies = [ - "dyn-clone", - "ref-cast", - "serde", - "serde_json", -] - -[[package]] -name = "schemars" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" -dependencies = [ - "dyn-clone", - "ref-cast", - "serde", - "serde_json", -] - -[[package]] -name = "schemars_derive" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals", - "syn 2.0.119", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "security-framework" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "selectors" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" -dependencies = [ - "bitflags 2.13.2", - "cssparser", - "derive_more", - "log", - "new_debug_unreachable", - "phf", - "phf_codegen", - "precomputed-hash", - "rustc-hash", - "servo_arc", - "smallvec", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde-untagged" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" -dependencies = [ - "erased-serde", - "serde", - "serde_core", - "typeid", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "serde_derive_internals" -version = "0.29.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "serde_json" -version = "1.0.152" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1741ab7a6cc54a03a89b5d563ed60075c277d9e3cfa73ad0c1f23f23974703c6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_path_to_error" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" -dependencies = [ - "itoa", - "serde", - "serde_core", -] - -[[package]] -name = "serde_repr" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "serde_spanned" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_spanned" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" -dependencies = [ - "serde_core", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_with" -version = "3.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4" -dependencies = [ - "base64 0.23.1", - "bs58", - "chrono", - "hex", - "indexmap 1.9.3", - "indexmap 2.14.2", - "jiff", - "schemars 0.9.0", - "schemars 1.2.2", - "serde_core", - "serde_json", - "serde_with_macros", - "time", -] - -[[package]] -name = "serde_with_macros" -version = "3.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d607aa01a3cb0ad757d6fd216136910db3c97b102fe686585689615a02dbcdc" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "serialize-to-javascript" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5" -dependencies = [ - "serde", - "serde_json", - "serialize-to-javascript-impl", -] - -[[package]] -name = "serialize-to-javascript-impl" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "servo_arc" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" -dependencies = [ - "stable_deref_trait", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", - "digest 0.11.3", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "simd_cesu8" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" -dependencies = [ - "rustc_version", - "simdutf8", -] - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "siphasher" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" - -[[package]] -name = "socket2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "softbuffer" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" -dependencies = [ - "bytemuck", - "js-sys", - "ndk", - "objc2", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation", - "objc2-quartz-core", - "raw-window-handle", - "redox_syscall", - "tracing", - "wasm-bindgen", - "web-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "soup3" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" -dependencies = [ - "futures-channel", - "gio", - "glib", - "libc", - "soup3-sys", -] - -[[package]] -name = "soup3-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" -dependencies = [ - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "specta" -version = "2.0.0-rc.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38f9a30cbcbb7011f1da7d73483983bf838af123883e45f2b36ed76328df9c50" -dependencies = [ - "paste", - "rustc_version", - "specta-macros", -] - -[[package]] -name = "specta-macros" -version = "2.0.0-rc.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ce14957ecc2897f1f848b8255b6531d13ddf49cbcf506b7c2c9fb1d005593bb" -dependencies = [ - "Inflector", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "specta-serde" -version = "0.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee8a72b755ddb8949fd8f17c5db43f0e8a806ea587d9bc602ee3f73240c00029" -dependencies = [ - "specta", - "specta-macros", -] - -[[package]] -name = "specta-typescript" -version = "0.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "639404ee95557f2f8b7e4cb773ffefd45304c7ab8ba21ac83b69051595e083c0" -dependencies = [ - "specta", -] - -[[package]] -name = "specta-util" -version = "0.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29b1fc02b446f7244a92924fe68c0555921209f1d342990cd1539e9138e69502" -dependencies = [ - "specta", -] - -[[package]] -name = "sqlite-wasm-rs" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" -dependencies = [ - "cc", - "js-sys", - "rsqlite-vfs", - "wasm-bindgen", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "string_cache" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" -dependencies = [ - "new_debug_unreachable", - "parking_lot", - "phf_shared", - "precomputed-hash", -] - -[[package]] -name = "string_cache_codegen" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", -] - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "swift-rs" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e" -dependencies = [ - "base64 0.21.7", - "serde", - "serde_json", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "system-configuration" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.9.4", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "system-deps" -version = "6.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" -dependencies = [ - "cfg-expr", - "heck 0.5.0", - "pkg-config", - "toml 0.8.2", - "version-compare", -] - -[[package]] -name = "tao" -version = "0.37.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400" -dependencies = [ - "bitflags 2.13.2", - "block2", - "core-foundation 0.10.1", - "core-graphics", - "crossbeam-channel", - "dbus", - "dispatch2", - "dlopen2", - "dpi", - "gdkwayland-sys", - "gdkx11-sys", - "gtk", - "jni 0.21.1", - "libc", - "log", - "ndk", - "ndk-context", - "ndk-sys", - "objc2", - "objc2-app-kit", - "objc2-foundation", - "objc2-ui-kit", - "parking_lot", - "percent-encoding", - "raw-window-handle", - "tao-macros", - "unicode-segmentation", - "url", - "windows", - "windows-core", - "windows-version", - "x11-dl", -] - -[[package]] -name = "tao-macros" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "tar" -version = "0.4.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" -dependencies = [ - "filetime", - "libc", - "xattr", -] - -[[package]] -name = "target-lexicon" -version = "0.12.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" - -[[package]] -name = "tauri" -version = "2.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d061d042ccd2df9c9f1508c1e63d835278c0a4c8801eb41764080e51f2eaaf34" -dependencies = [ - "anyhow", - "bytes", - "cookie", - "dirs", - "dunce", - "embed_plist", - "getrandom 0.3.4", - "glob", - "gtk", - "heck 0.5.0", - "http", - "image", - "jni 0.21.1", - "libc", - "log", - "mime", - "muda", - "objc2", - "objc2-app-kit", - "objc2-foundation", - "objc2-ui-kit", - "objc2-web-kit", - "percent-encoding", - "plist", - "raw-window-handle", - "reqwest", - "serde", - "serde_json", - "serde_repr", - "serialize-to-javascript", - "specta", - "swift-rs", - "tauri-build", - "tauri-macros", - "tauri-runtime", - "tauri-runtime-wry", - "tauri-utils", - "thiserror 2.0.20", - "tokio", - "tray-icon", - "url", - "webkit2gtk", - "webview2-com", - "window-vibrancy", - "windows", -] - -[[package]] -name = "tauri-build" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2eea0b6302f82c574b21af6fc6ae6e86183b9280853c22621d0abf0936911ffc" -dependencies = [ - "anyhow", - "cargo_toml", - "dirs", - "glob", - "heck 0.5.0", - "json-patch", - "schemars 0.8.22", - "semver", - "serde", - "serde_json", - "tauri-utils", - "tauri-winres", - "walkdir", -] - -[[package]] -name = "tauri-codegen" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e50213e463086ecc283d7e9f51c30cc0fd304ad457425158018be26dbf0d0a80" -dependencies = [ - "base64 0.22.1", - "brotli", - "ico", - "json-patch", - "plist", - "png 0.18.1", - "proc-macro2", - "quote", - "semver", - "serde", - "serde_json", - "sha2 0.10.9", - "syn 2.0.119", - "tauri-utils", - "thiserror 2.0.20", - "time", - "url", - "uuid", - "walkdir", -] - -[[package]] -name = "tauri-macros" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8129fb43bb6e0d6b73ad3315cd172beaab17cd28899c594b1b32c80edbbfd99c" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", - "tauri-codegen", - "tauri-utils", -] - -[[package]] -name = "tauri-plugin" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1140cf34a3b3b836a13103dcab17f18831d5cc3534cbd435dc01a5c6daa65aa2" -dependencies = [ - "anyhow", - "glob", - "plist", - "schemars 0.8.22", - "serde", - "serde_json", - "tauri-utils", - "walkdir", -] - -[[package]] -name = "tauri-plugin-dialog" -version = "2.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dca325d6e66e9170f2e1b9631722e4e544bcbc51781575d266abdaba697bd51" -dependencies = [ - "log", - "raw-window-handle", - "rfd", - "serde", - "serde_json", - "tauri", - "tauri-plugin", - "tauri-plugin-fs", - "thiserror 2.0.20", - "url", -] - -[[package]] -name = "tauri-plugin-fs" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213fae2d85d4b76b06de5915d1862db9fa74541171f9d2c15da6ac9bd6e788c6" -dependencies = [ - "anyhow", - "dunce", - "glob", - "log", - "objc2-foundation", - "percent-encoding", - "schemars 0.8.22", - "serde", - "serde_json", - "serde_repr", - "tauri", - "tauri-plugin", - "tauri-utils", - "thiserror 2.0.20", - "toml 1.1.6+spec-1.1.0", - "url", -] - -[[package]] -name = "tauri-plugin-opener" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85dead674ee41937d042ee855d785f07ee67206f19402200c12b9255964d5ac8" -dependencies = [ - "dunce", - "glob", - "objc2-app-kit", - "objc2-foundation", - "open", - "schemars 0.8.22", - "serde", - "serde_json", - "tauri", - "tauri-plugin", - "thiserror 2.0.20", - "url", - "windows", - "zbus", -] - -[[package]] -name = "tauri-plugin-process" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74ae3d8549ae564c0397377373e262f340908eb23a5b9fbe03f2a00007dc0038" -dependencies = [ - "tauri", - "tauri-plugin", -] - -[[package]] -name = "tauri-plugin-single-instance" -version = "2.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c142ed88deee222bd2d979269d35c73b6c1c0f6ebd5b79b4ff80066fcad6af1" -dependencies = [ - "serde", - "serde_json", - "tauri", - "thiserror 2.0.20", - "tokio", - "tracing", - "windows-sys 0.61.2", - "zbus", -] - -[[package]] -name = "tauri-plugin-updater" -version = "2.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "855a336eb389d2c1502244fd48fa2d8cb487a430f691bbaed025195f99a04489" -dependencies = [ - "base64 0.22.1", - "dirs", - "flate2", - "futures-util", - "http", - "infer", - "libc", - "log", - "minisign-verify", - "osakit", - "percent-encoding", - "reqwest", - "rustls", - "semver", - "serde", - "serde_json", - "tar", - "tauri", - "tauri-plugin", - "tempfile", - "thiserror 2.0.20", - "time", - "tokio", - "url", - "windows-sys 0.61.2", - "zip 4.6.1", -] - -[[package]] -name = "tauri-plugin-window-state" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6815cab7b212f9cfe16a9d79d8d22f9e14159e4a9460f7dec1467167a008e3" -dependencies = [ - "bitflags 2.13.2", - "log", - "serde", - "serde_json", - "tauri", - "tauri-plugin", - "thiserror 2.0.20", -] - -[[package]] -name = "tauri-runtime" -version = "2.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a57a2a9b8c8b7fc00d35b510fe808ded7f9f1b44fc1cdda6aee38632ea5413" -dependencies = [ - "cookie", - "dpi", - "gtk", - "http", - "jni 0.21.1", - "objc2", - "objc2-ui-kit", - "objc2-web-kit", - "raw-window-handle", - "serde", - "serde_json", - "tauri-utils", - "thiserror 2.0.20", - "url", - "webkit2gtk", - "webview2-com", - "windows", -] - -[[package]] -name = "tauri-runtime-wry" -version = "2.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f9e7e0c9f80a5130773cfabb6df4dc924518fb1b2c923726966804634b57d22" -dependencies = [ - "gtk", - "http", - "jni 0.21.1", - "log", - "objc2", - "objc2-app-kit", - "once_cell", - "percent-encoding", - "raw-window-handle", - "softbuffer", - "tao", - "tauri-runtime", - "tauri-utils", - "url", - "webkit2gtk", - "webview2-com", - "windows", - "wry", -] - -[[package]] -name = "tauri-specta" -version = "2.0.0-rc.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee080f36d2ac17ce2f3a82fb53f02d664e8345457de51b56dad3c394dacc41a2" -dependencies = [ - "heck 0.5.0", - "serde", - "serde_json", - "specta", - "specta-serde", - "specta-typescript", - "specta-util", - "tauri", - "thiserror 2.0.20", -] - -[[package]] -name = "tauri-utils" -version = "2.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ff55a614843b9a3f010f211df637c94df2607175b8d0f6e0f4a7c19e18621ee" -dependencies = [ - "anyhow", - "brotli", - "cargo_metadata", - "ctor", - "dom_query", - "dunce", - "glob", - "http", - "infer", - "json-patch", - "log", - "memchr", - "phf", - "plist", - "proc-macro2", - "quote", - "regex", - "schemars 0.8.22", - "semver", - "serde", - "serde-untagged", - "serde_json", - "serde_with", - "swift-rs", - "thiserror 2.0.20", - "toml 1.1.6+spec-1.1.0", - "url", - "urlpattern", - "uuid", - "walkdir", -] - -[[package]] -name = "tauri-winres" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6" -dependencies = [ - "dunce", - "embed-resource", - "toml 1.1.6+spec-1.1.0", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.3", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "tendril" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" -dependencies = [ - "new_debug_unreachable", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" -dependencies = [ - "thiserror-impl 2.0.20", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "time" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" -dependencies = [ - "deranged", - "num-conv", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "time-macros" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "tinystr" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" - -[[package]] -name = "tokio" -version = "1.53.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" -dependencies = [ - "bytes", - "libc", - "mio", - "pin-project-lite", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-util" -version = "0.7.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" -dependencies = [ - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.3", - "toml_edit 0.20.2", -] - -[[package]] -name = "toml" -version = "1.1.6+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" -dependencies = [ - "indexmap 2.14.2", - "serde_core", - "serde_spanned 1.1.1", - "toml_datetime 1.1.1+spec-1.1.0", - "toml_parser", - "toml_writer", - "winnow 1.0.4", -] - -[[package]] -name = "toml_datetime" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_datetime" -version = "1.1.1+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" -dependencies = [ - "serde_core", -] - -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap 2.14.2", - "toml_datetime 0.6.3", - "winnow 0.5.40", -] - -[[package]] -name = "toml_edit" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" -dependencies = [ - "indexmap 2.14.2", - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.3", - "winnow 0.5.40", -] - -[[package]] -name = "toml_edit" -version = "0.25.15+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" -dependencies = [ - "indexmap 2.14.2", - "toml_datetime 1.1.1+spec-1.1.0", - "toml_parser", - "winnow 1.0.4", -] - -[[package]] -name = "toml_parser" -version = "1.1.3+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" -dependencies = [ - "winnow 1.0.4", -] - -[[package]] -name = "toml_writer" -version = "1.1.2+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" - -[[package]] -name = "tower" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" -dependencies = [ - "futures-core", - "futures-util", - "pin-project-lite", - "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower-http" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" -dependencies = [ - "bitflags 2.13.2", - "bytes", - "futures-util", - "http", - "http-body", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", - "url", -] - -[[package]] -name = "tower-http" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" -dependencies = [ - "bitflags 2.13.2", - "bytes", - "http", - "percent-encoding", - "pin-project-lite", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "tray-icon" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" -dependencies = [ - "crossbeam-channel", - "dirs", - "libappindicator", - "muda", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation", - "once_cell", - "png 0.18.1", - "serde", - "thiserror 2.0.20", - "windows-sys 0.61.2", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "typed-path" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" - -[[package]] -name = "typeid" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "ucd-trie" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" - -[[package]] -name = "uds_windows" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" -dependencies = [ - "memoffset", - "tempfile", - "windows-sys 0.61.2", -] - -[[package]] -name = "unicode-ident" -version = "1.0.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" - -[[package]] -name = "unicode-segmentation" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", - "serde_derive", -] - -[[package]] -name = "urlpattern" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" -dependencies = [ - "icu_properties", - "regex", - "serde", - "url", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "uuid" -version = "1.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" -dependencies = [ - "getrandom 0.4.3", - "js-sys", - "serde_core", - "wasm-bindgen", -] - -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - -[[package]] -name = "version-compare" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "vswhom" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" -dependencies = [ - "libc", - "vswhom-sys", -] - -[[package]] -name = "vswhom-sys" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" -dependencies = [ - "cc", - "libc", -] - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.6", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-streams" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "web-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web_atoms" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" -dependencies = [ - "phf", - "phf_codegen", - "string_cache", - "string_cache_codegen", -] - -[[package]] -name = "webkit2gtk" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" -dependencies = [ - "bitflags 1.3.2", - "cairo-rs", - "gdk", - "gdk-sys", - "gio", - "gio-sys", - "glib", - "glib-sys", - "gobject-sys", - "gtk", - "gtk-sys", - "javascriptcore-rs", - "libc", - "once_cell", - "soup3", - "webkit2gtk-sys", -] - -[[package]] -name = "webkit2gtk-sys" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" -dependencies = [ - "bitflags 1.3.2", - "cairo-sys-rs", - "gdk-sys", - "gio-sys", - "glib-sys", - "gobject-sys", - "gtk-sys", - "javascriptcore-rs-sys", - "libc", - "pkg-config", - "soup3-sys", - "system-deps", -] - -[[package]] -name = "webpki-root-certs" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "webview2-com" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" -dependencies = [ - "webview2-com-macros", - "webview2-com-sys", - "windows", - "windows-core", -] - -[[package]] -name = "webview2-com-macros" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "webview2-com-sys" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" -dependencies = [ - "thiserror 2.0.20", - "windows", - "windows-core", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "window-vibrancy" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580" -dependencies = [ - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "objc2-quartz-core", - "raw-window-handle", - "windows-sys 0.61.2", - "windows-version", -] - -[[package]] -name = "windows" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" -dependencies = [ - "windows-collections", - "windows-core", - "windows-future", - "windows-numerics", -] - -[[package]] -name = "windows-collections" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" -dependencies = [ - "windows-core", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-future" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" -dependencies = [ - "windows-core", - "windows-link", - "windows-threading", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-numerics" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" -dependencies = [ - "windows-core", - "windows-link", -] - -[[package]] -name = "windows-registry" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" -dependencies = [ - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - -[[package]] -name = "windows-threading" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-version" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - -[[package]] -name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - -[[package]] -name = "winnow" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" -dependencies = [ - "memchr", -] - -[[package]] -name = "winreg" -version = "0.55.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" -dependencies = [ - "cfg-if", - "windows-sys 0.59.0", -] - -[[package]] -name = "winreg" -version = "0.56.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" -dependencies = [ - "cfg-if", - "windows-sys 0.61.2", -] - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "writeable" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" - -[[package]] -name = "wry" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0" -dependencies = [ - "base64 0.22.1", - "block2", - "cookie", - "crossbeam-channel", - "dirs", - "dom_query", - "dpi", - "dunce", - "gdkx11", - "gtk", - "http", - "javascriptcore-rs", - "jni 0.21.1", - "libc", - "ndk", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "objc2-ui-kit", - "objc2-web-kit", - "once_cell", - "percent-encoding", - "raw-window-handle", - "sha2 0.10.9", - "soup3", - "tao-macros", - "thiserror 2.0.20", - "url", - "webkit2gtk", - "webkit2gtk-sys", - "webview2-com", - "windows", - "windows-core", - "windows-version", - "x11-dl", -] - -[[package]] -name = "x11" -version = "2.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" -dependencies = [ - "libc", - "pkg-config", -] - -[[package]] -name = "x11-dl" -version = "2.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" -dependencies = [ - "libc", - "once_cell", - "pkg-config", -] - -[[package]] -name = "xattr" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" -dependencies = [ - "libc", - "rustix", -] - -[[package]] -name = "yoke" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", - "synstructure", -] - -[[package]] -name = "zbus" -version = "5.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" -dependencies = [ - "async-broadcast", - "async-executor", - "async-io", - "async-lock", - "async-process", - "async-recursion", - "async-task", - "async-trait", - "blocking", - "enumflags2", - "event-listener", - "futures-core", - "futures-lite", - "hex", - "libc", - "ordered-stream", - "rustix", - "serde", - "serde_repr", - "tracing", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow 1.0.4", - "zbus_macros", - "zbus_names", - "zvariant", -] - -[[package]] -name = "zbus_macros" -version = "5.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.6", - "zbus_names", - "zvariant", - "zvariant_utils", -] - -[[package]] -name = "zbus_names" -version = "4.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" -dependencies = [ - "serde", - "winnow 1.0.4", - "zvariant", -] - -[[package]] -name = "zcheapstr" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" -dependencies = [ - "serde", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" - -[[package]] -name = "zerotrie" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "zip" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" -dependencies = [ - "arbitrary", - "crc32fast", - "indexmap 2.14.2", - "memchr", -] - -[[package]] -name = "zip" -version = "9.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e2fc56a6707efb066c40aead2409ebb1224e6dde24a074e9fbc78ced500507b" -dependencies = [ - "crc32fast", - "flate2", - "indexmap 2.14.2", - "memchr", - "nix", - "typed-path", - "zopfli", -] - -[[package]] -name = "zlib-rs" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" - -[[package]] -name = "zopfli" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - -[[package]] -name = "zune-core" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" - -[[package]] -name = "zune-jpeg" -version = "0.5.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" -dependencies = [ - "zune-core", -] - -[[package]] -name = "zvariant" -version = "5.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147" -dependencies = [ - "endi", - "enumflags2", - "serde", - "winnow 1.0.4", - "zcheapstr", - "zvariant_derive", - "zvariant_utils", -] - -[[package]] -name = "zvariant_derive" -version = "5.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.6", - "zvariant_utils", -] - -[[package]] -name = "zvariant_utils" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.6", - "winnow 1.0.4", -] diff --git a/bazaarplusplus-installer/src-tauri/Cargo.toml b/bazaarplusplus-installer/src-tauri/Cargo.toml deleted file mode 100644 index a33f11f..0000000 --- a/bazaarplusplus-installer/src-tauri/Cargo.toml +++ /dev/null @@ -1,87 +0,0 @@ -[package] -name = "bppinstaller" -version = "6.0.0" -description = "BazaarPlusPlus Desktop App" -authors = ["cauyxy "] -edition = "2021" -rust-version = "1.98" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[lib] -# The `_lib` suffix may seem redundant but it is necessary -# to make the lib name unique and wouldn't conflict with the bin name. -# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519 -name = "bppinstaller_lib" -crate-type = ["staticlib", "cdylib", "rlib"] - -[[bin]] -name = "bppinstaller" -path = "src/main.rs" -# `main` only delegates to the library. Disabling its empty test harness also -# avoids linking the Windows application resources into the same target twice. -test = false -bench = false - -[build-dependencies] -tauri-build = { version = "2.6.3", features = [] } - -[dependencies] -tauri = { version = "2.11.5", features = ["tray-icon", "image-png"] } -tauri-plugin-opener = "2" -tauri-plugin-dialog = "2.7.3" -tauri-plugin-process = "2" -serde = { version = "1.0.229", features = ["derive"] } -serde_json = "1.0.151" -base64 = "0.23.1" -dirs = "7" -keyvalues-parser = "0.2" -zip = { version = "9", default-features = false, features = ["deflate"] } -axum = "0.8" -tower-http = { version = "0.7", features = ["cors"] } -tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "net"] } -rusqlite = { version = "0.40.2", features = ["bundled"] } -chrono = { version = "0.4", features = ["clock", "serde"] } -image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] } -include_dir = "0.7" -specta = { version = "=2.0.0-rc.25", features = ["derive"] } -specta-typescript = "=0.0.12" -tauri-specta = { version = "=2.0.0-rc.25", features = ["typescript"] } -tempfile = "3" -sha2 = "0.11.0" - -[target.'cfg(unix)'.dependencies] -libc = "0.2.189" - -[target.'cfg(windows)'.dependencies] -winreg = "0.56" -windows = { version = "0.62", features = [ - "Win32_Foundation", - "Win32_Storage_FileSystem", - "Win32_System_Diagnostics_ToolHelp", - "Win32_System_Threading", - "Win32_UI_Shell", - "Win32_UI_WindowsAndMessaging", -] } - -[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] -tauri-plugin-updater = "2" -tauri-plugin-single-instance = "2.4.4" -tauri-plugin-window-state = "2.4.1" - -[lints.clippy] -# A curated subset of pedantic lints: each flags a real smell and has a -# mechanical fix. `verify` promotes all warnings to errors. -redundant_closure_for_method_calls = "warn" -needless_raw_string_hashes = "warn" -unnested_or_patterns = "warn" - -[dev-dependencies] -tower = { version = "0.5", features = ["util"] } - -[profile.release] -opt-level = "z" -lto = true -codegen-units = 1 -strip = true -panic = "abort" diff --git a/bazaarplusplus-installer/src-tauri/Info.plist b/bazaarplusplus-installer/src-tauri/Info.plist deleted file mode 100644 index 107d317..0000000 --- a/bazaarplusplus-installer/src-tauri/Info.plist +++ /dev/null @@ -1,10 +0,0 @@ - - - - - CFBundleIconName - AppIcon - CFBundleIconFile - app-icon.icns - - diff --git a/bazaarplusplus-installer/src-tauri/build.rs b/bazaarplusplus-installer/src-tauri/build.rs deleted file mode 100644 index e1587c9..0000000 --- a/bazaarplusplus-installer/src-tauri/build.rs +++ /dev/null @@ -1,115 +0,0 @@ -mod build_support; - -use std::path::Path; -use std::process::Command; - -fn main() { - compile_macos_trampoline_stub(); - tauri_build::build(); - expose_windows_resources_to_test_harnesses(); -} - -/// `tauri-build` links `resource.lib` (including the Common Controls v6 -/// manifest) into application binaries only. The library test harness links -/// Tauri's Windows dialog code too, so it needs the same manifest before the -/// Windows loader can resolve `TaskDialogIndirect`. -fn expose_windows_resources_to_test_harnesses() { - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { - return; - } - - let output_dir = std::env::var_os("OUT_DIR").expect("Cargo must provide OUT_DIR"); - println!( - "cargo:rustc-link-search=native={}", - Path::new(&output_dir).display() - ); -} - -/// Compile the sole macOS launch trampoline stub (arm64) from its committed C source so -/// the bundled resource declared in `tauri.macos.conf.json` exists before -/// `tauri_build` validates resource paths. The generated binary is gitignored and -/// is replaced when it is missing, older than its source, or built against a -/// deployment target other than the supported baseline. No-op when not targeting -/// macOS. -fn compile_macos_trampoline_stub() { - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("macos") { - return; - } - - let source = "trampoline/bpp_launcher.c"; - let output = "resources/Trampoline/macos/bpp_launcher"; - // Re-run when the source changes or the generated output disappears. Merely - // running the build script must not rewrite the watched output: doing so makes - // the next Cargo command consider this package dirty again. - println!("cargo:rerun-if-changed={source}"); - println!("cargo:rerun-if-changed={output}"); - - let source_modified = std::fs::metadata(source) - .and_then(|metadata| metadata.modified()) - .unwrap_or_else(|err| panic!("cannot inspect trampoline source {source}: {err}")); - let output_modified = match std::fs::metadata(output) { - Ok(metadata) => Some( - metadata - .modified() - .unwrap_or_else(|err| panic!("cannot inspect trampoline output {output}: {err}")), - ), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => None, - Err(err) => panic!("cannot inspect trampoline output {output}: {err}"), - }; - - if !build_support::should_compile_trampoline(source_modified, output_modified) - && has_required_macos_deployment_target(output) - { - return; - } - - if let Some(parent) = Path::new(output).parent() { - std::fs::create_dir_all(parent) - .unwrap_or_else(|err| panic!("cannot create {}: {err}", parent.display())); - } - - let deployment_target_arg = format!( - "-mmacosx-version-min={}", - build_support::MACOS_TRAMPOLINE_DEPLOYMENT_TARGET - ); - let status = Command::new("clang") - .args([ - "-arch", - "arm64", - deployment_target_arg.as_str(), - "-O2", - "-o", - output, - source, - ]) - .status() - .unwrap_or_else(|err| panic!("failed to run clang for trampoline stub: {err}")); - if !status.success() { - panic!("clang failed to compile the macOS trampoline stub ({source})"); - } - - if !has_required_macos_deployment_target(output) { - panic!( - "macOS trampoline stub has no {} deployment target: {output}", - build_support::MACOS_TRAMPOLINE_DEPLOYMENT_TARGET - ); - } -} - -fn has_required_macos_deployment_target(output: &str) -> bool { - let otool_output = Command::new("otool") - .args(["-l", output]) - .output() - .unwrap_or_else(|err| panic!("failed to run otool for trampoline stub: {err}")); - if !otool_output.status.success() { - panic!( - "otool failed to inspect the macOS trampoline stub ({output}): {}", - String::from_utf8_lossy(&otool_output.stderr).trim() - ); - } - - build_support::has_macos_trampoline_deployment_target( - &String::from_utf8_lossy(&otool_output.stdout), - build_support::MACOS_TRAMPOLINE_DEPLOYMENT_TARGET, - ) -} diff --git a/bazaarplusplus-installer/src-tauri/build_support.rs b/bazaarplusplus-installer/src-tauri/build_support.rs deleted file mode 100644 index dbab43d..0000000 --- a/bazaarplusplus-installer/src-tauri/build_support.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::time::SystemTime; - -pub const MACOS_TRAMPOLINE_DEPLOYMENT_TARGET: &str = "12.0"; - -pub fn should_compile_trampoline( - source_modified: SystemTime, - output_modified: Option, -) -> bool { - match output_modified { - Some(output_modified) => source_modified > output_modified, - None => true, - } -} - -/// Return whether `otool -l` reports the required minimum macOS version for a -/// Mach-O image, read from its `LC_BUILD_VERSION` load command. -pub fn has_macos_trampoline_deployment_target(otool_output: &str, expected_version: &str) -> bool { - let mut load_command = None; - let mut is_macos_platform = false; - - for raw_line in otool_output.lines() { - let line = raw_line.trim(); - - if let Some(command) = line.strip_prefix("cmd ") { - load_command = Some(command); - is_macos_platform = false; - continue; - } - - if load_command != Some("LC_BUILD_VERSION") { - continue; - } - if line == "platform 1" { - is_macos_platform = true; - } else if is_macos_platform && line.strip_prefix("minos ") == Some(expected_version) { - return true; - } - } - - false -} diff --git a/bazaarplusplus-installer/src-tauri/capabilities/default.json b/bazaarplusplus-installer/src-tauri/capabilities/default.json deleted file mode 100644 index bc05e00..0000000 --- a/bazaarplusplus-installer/src-tauri/capabilities/default.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "default", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "core:default", - "core:window:allow-minimize", - "core:window:allow-toggle-maximize", - "core:window:allow-close", - "core:window:allow-show", - "core:window:allow-start-dragging", - "opener:default", - "updater:allow-check", - "updater:allow-download-and-install", - "process:allow-restart", - { - "identifier": "opener:allow-open-url", - "allow": [ - { - "url": "steam://*" - } - ] - }, - "dialog:default" - ] -} diff --git a/bazaarplusplus-installer/src-tauri/history-database-compatibility.json b/bazaarplusplus-installer/src-tauri/history-database-compatibility.json deleted file mode 100644 index 1cac496..0000000 --- a/bazaarplusplus-installer/src-tauri/history-database-compatibility.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "formatVersion": 1, - "dataRootDirectoryName": "BazaarPlusPlusV6", - "supportedUserVersions": [1] -} diff --git a/bazaarplusplus-installer/src-tauri/icons/app-icon.icns b/bazaarplusplus-installer/src-tauri/icons/app-icon.icns deleted file mode 100644 index dcd0da6..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/app-icon.icns and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/app-icon.ico b/bazaarplusplus-installer/src-tauri/icons/app-icon.ico deleted file mode 100644 index 1b36b9c..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/app-icon.ico and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/app-icon.png b/bazaarplusplus-installer/src-tauri/icons/app-icon.png deleted file mode 100644 index 9c9551a..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/app-icon.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/icon.png b/bazaarplusplus-installer/src-tauri/icons/icon.png deleted file mode 100644 index 041f409..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/icon.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/IconLogo-1000x1000.png b/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/IconLogo-1000x1000.png deleted file mode 100644 index 247c169..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/IconLogo-1000x1000.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/batch 2.png b/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/batch 2.png deleted file mode 100644 index e6d9c3f..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/batch 2.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s1.png b/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s1.png deleted file mode 100644 index 5c4f202..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s1.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s2.png b/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s2.png deleted file mode 100644 index 115db11..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s2.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s3.png b/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s3.png deleted file mode 100644 index 86b1b4f..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/Assets/s3.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/icon.json b/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/icon.json deleted file mode 100644 index fd9e396..0000000 --- a/bazaarplusplus-installer/src-tauri/icons/source/AppIcon.icon/icon.json +++ /dev/null @@ -1,129 +0,0 @@ -{ - "fill" : "system-dark", - "groups" : [ - { - "layers" : [ - { - "glass" : false, - "image-name" : "batch 2.png", - "name" : "batch 2", - "position" : { - "scale" : 0.9, - "translation-in-points" : [ - 0, - 263.5045456616438 - ] - } - } - ], - "position" : { - "scale" : 1, - "translation-in-points" : [ - 0, - 17.313480085524816 - ] - }, - "shadow" : { - "kind" : "neutral", - "opacity" : 0.6 - }, - "translucency" : { - "enabled" : true, - "value" : 0.2 - } - }, - { - "hidden" : false, - "layers" : [ - { - "image-name" : "s1.png", - "name" : "s1", - "position" : { - "scale" : 1, - "translation-in-points" : [ - 62.69565217391312, - 60.99999999999994 - ] - } - }, - { - "hidden" : false, - "image-name" : "s3.png", - "name" : "s3", - "position" : { - "scale" : 1, - "translation-in-points" : [ - -50.04347826086945, - 62 - ] - } - }, - { - "hidden" : true, - "image-name" : "s2.png", - "name" : "s2", - "position" : { - "scale" : 1, - "translation-in-points" : [ - -51.04347826086956, - 61 - ] - } - } - ], - "position" : { - "scale" : 1.15, - "translation-in-points" : [ - 0, - 17.313480085524816 - ] - }, - "shadow" : { - "kind" : "layer-color", - "opacity" : 0.6 - }, - "translucency" : { - "enabled" : true, - "value" : 0.2 - } - }, - { - "layers" : [ - { - "glass" : true, - "hidden" : false, - "image-name" : "IconLogo-1000x1000.png", - "name" : "IconLogo-1000x1000", - "position" : { - "scale" : 1, - "translation-in-points" : [ - 0, - -76.43679342032033 - ] - } - } - ], - "position" : { - "scale" : 0.7, - "translation-in-points" : [ - 0, - 17.313480085524816 - ] - }, - "shadow" : { - "kind" : "neutral", - "opacity" : 0.6 - }, - "translucency" : { - "enabled" : true, - "value" : 0.2 - } - } - ], - "supported-platforms" : { - "circles" : [ - "watchOS" - ], - "squares" : "shared" - } -} \ No newline at end of file diff --git a/bazaarplusplus-installer/src-tauri/icons/tray-macos-template.png b/bazaarplusplus-installer/src-tauri/icons/tray-macos-template.png deleted file mode 100644 index 01329dd..0000000 Binary files a/bazaarplusplus-installer/src-tauri/icons/tray-macos-template.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/icons/tray-macos.svg b/bazaarplusplus-installer/src-tauri/icons/tray-macos.svg deleted file mode 100644 index 44a5d35..0000000 --- a/bazaarplusplus-installer/src-tauri/icons/tray-macos.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/bazaarplusplus-installer/src-tauri/resources/BepInExSource/macos/.gitkeep b/bazaarplusplus-installer/src-tauri/resources/BepInExSource/macos/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/bazaarplusplus-installer/src-tauri/resources/BepInExSource/windows/.gitkeep b/bazaarplusplus-installer/src-tauri/resources/BepInExSource/windows/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/LICENSE b/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/LICENSE deleted file mode 100644 index fd406b1..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/LICENSE +++ /dev/null @@ -1,482 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - - NOTICE - -BepInEx - Unity -Copyright (C) 2020 BepInEx Team - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 -USA - - -Exemptions / alternate licenses are available for negotiation. \ No newline at end of file diff --git a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/BepInEx/plugins/.gitkeep b/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/BepInEx/plugins/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/Info.plist b/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/Info.plist deleted file mode 100644 index 83864e8..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - GfxPluginBppReplayVideoToolbox - CFBundleIdentifier - com.bazaarplusplus.replay.videotoolbox - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - GfxPluginBppReplayVideoToolbox - CFBundlePackageType - BNDL - CFBundleShortVersionString - 0.1 - CFBundleVersion - 1 - - diff --git a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/_CodeSignature/CodeResources b/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/_CodeSignature/CodeResources deleted file mode 100644 index d5d0fd7..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/_CodeSignature/CodeResources +++ /dev/null @@ -1,115 +0,0 @@ - - - - - files - - files2 - - rules - - ^Resources/ - - ^Resources/.*\.lproj/ - - optional - - weight - 1000 - - ^Resources/.*\.lproj/locversion.plist$ - - omit - - weight - 1100 - - ^Resources/Base\.lproj/ - - weight - 1010 - - ^version.plist$ - - - rules2 - - .*\.dSYM($|/) - - weight - 11 - - ^(.*/)?\.DS_Store$ - - omit - - weight - 2000 - - ^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/ - - nested - - weight - 10 - - ^.* - - ^Info\.plist$ - - omit - - weight - 20 - - ^PkgInfo$ - - omit - - weight - 20 - - ^Resources/ - - weight - 20 - - ^Resources/.*\.lproj/ - - optional - - weight - 1000 - - ^Resources/.*\.lproj/locversion.plist$ - - omit - - weight - 1100 - - ^Resources/Base\.lproj/ - - weight - 1010 - - ^[^/]+$ - - nested - - weight - 10 - - ^embedded\.provisionprofile$ - - weight - 20 - - ^version\.plist$ - - weight - 20 - - - - diff --git a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/version b/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/version deleted file mode 100644 index 3acfb46..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/version +++ /dev/null @@ -1 +0,0 @@ -5.4.23.5 \ No newline at end of file diff --git a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/windows/BepInEx/plugins/.gitkeep b/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/windows/BepInEx/plugins/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/windows/doorstop_config.ini b/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/windows/doorstop_config.ini deleted file mode 100644 index 97f55df..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/SourceForBuild/windows/doorstop_config.ini +++ /dev/null @@ -1,39 +0,0 @@ -# General options for Unity Doorstop -[General] - -# Enable Doorstop? -enabled = true - -# Path to the assembly to load and execute -# NOTE: The entrypoint must be of format `static void Doorstop.Entrypoint.Start()` -target_assembly=BepInEx\core\BepInEx.Preloader.dll - -# If true, Unity's output log is redirected to \output_log.txt -redirect_output_log = false - -# Overrides the default boot.config file path -boot_config_override = - -# If enabled, DOORSTOP_DISABLE env var value is ignored -# USE THIS ONLY WHEN ASKED TO OR YOU KNOW WHAT THIS MEANS -ignore_disable_switch = false - -# Options specific to running under Unity Mono runtime -[UnityMono] - -# Overrides default Mono DLL search path -# Sometimes it is needed to instruct Mono to seek its assemblies from a different path -# (e.g. mscorlib is stripped in original game) -# This option causes Mono to seek mscorlib and core libraries from a different folder before Managed -# Original Managed folder is added as a secondary folder in the search path -# To specify multiple paths, separate them with semicolons (;) -dll_search_path_override = - -# If true, Mono debugger server will be enabled -debug_enabled = false - -# When debug_enabled is true, specifies the address to use for the debugger server -debug_address = 127.0.0.1:10000 - -# If true and debug_enabled is true, Mono debugger server will suspend the game execution until a debugger is attached -debug_suspend = false \ No newline at end of file diff --git a/bazaarplusplus-installer/src-tauri/resources/app-bootstrap.json b/bazaarplusplus-installer/src-tauri/resources/app-bootstrap.json deleted file mode 100644 index 8393786..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/app-bootstrap.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "links": { - "github": "https://github.com/BazaarPlusPlus/BazaarPlusPlus", - "x": "https://x.com/yxinyu715", - "bilibili_project": "https://space.bilibili.com/3546978457750467", - "bilibili_author": "https://space.bilibili.com/1728071188", - "bilibili_core_dev": "https://space.bilibili.com/20258", - "xiaohongshu": "https://www.xiaohongshu.com/user/profile/5d414f64000000000100a5f6", - "kofi": "https://ko-fi.com/cauyxy", - "supporter_list": "https://bazaarplusplus.com/support" - }, - "credits": [ - { - "name": "cauyxy", - "role": "AUTHOR", - "href": "https://github.com/cauyxy", - "group": "team" - }, - { - "name": "timelic", - "role": "CO-AUTHOR", - "href": "https://github.com/timelic", - "group": "team" - }, - { - "name": "pengx17", - "role": "CO-AUTHOR", - "href": "https://github.com/pengx17", - "group": "team" - }, - { "name": "Codex", "role": "CO-CREATOR", "group": "team" }, - { "name": "Claude Code", "role": "CO-CREATOR", "group": "team" }, - { "name": "Cursor", "role": "CO-CREATOR", "group": "team" }, - { - "name": "BazaarDB", - "role": "GAME DATA SOURCE", - "group": "acknowledgement" - }, - { - "name": "BPP Players", - "role": "COMMUNITY RUN DATA", - "group": "acknowledgement" - }, - { - "name": "BazaarHelper", - "role": "INSPIRATION", - "group": "acknowledgement" - }, - { - "name": "BazaarPlannerMod", - "role": "INSPIRATION", - "group": "acknowledgement" - } - ], - "licenses": [ - { "name": "BepInEx", "license": "LGPL-2.1", "category": "runtime" }, - { "name": "React", "license": "MIT", "category": "frontend" }, - { "name": "Tauri", "license": "MIT", "category": "backend" }, - { "name": "Tailwind CSS", "license": "MIT", "category": "frontend" } - ] -} diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-doo.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-doo.svg deleted file mode 100644 index 213cabc..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-doo.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-dra.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-dra.svg deleted file mode 100644 index 603c932..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-dra.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-jul.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-jul.svg deleted file mode 100644 index 3278d59..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-jul.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-kar.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-kar.svg deleted file mode 100644 index d5cdd46..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-kar.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-mak.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-mak.svg deleted file mode 100644 index d89a838..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-mak.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-pyg.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-pyg.svg deleted file mode 100644 index a1b5c48..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-pyg.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-ste.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-ste.svg deleted file mode 100644 index caf7f59..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-ste.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-unk.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-unk.svg deleted file mode 100644 index c4e26bd..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-unk.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-van.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-van.svg deleted file mode 100644 index 1514469..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/heroes/hero-van.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-doo.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-doo.svg deleted file mode 100644 index ea2c071..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-doo.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-dra.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-dra.svg deleted file mode 100644 index d40749f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-dra.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-jul.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-jul.svg deleted file mode 100644 index 67a66c6..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-jul.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-kar.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-kar.svg deleted file mode 100644 index c227785..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-kar.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-mak.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-mak.svg deleted file mode 100644 index 28e47f0..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-mak.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-pyg.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-pyg.svg deleted file mode 100644 index f555189..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-pyg.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-ste.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-ste.svg deleted file mode 100644 index a6579fd..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-ste.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-unk.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-unk.svg deleted file mode 100644 index 8db4fc2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-unk.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-van.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-van.svg deleted file mode 100644 index 4f9fcc2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/herohalf/herohalf-van.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-0.svg deleted file mode 100644 index 60e724c..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-1.svg deleted file mode 100644 index 6c91c70..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-10.svg deleted file mode 100644 index b010ff8..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-11.svg deleted file mode 100644 index adba45e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-12.svg deleted file mode 100644 index f794f2a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-13.svg deleted file mode 100644 index 626e668..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-14.svg deleted file mode 100644 index 6015bfc..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-15.svg deleted file mode 100644 index 5d9bb99..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-16.svg deleted file mode 100644 index cfebabc..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-17.svg deleted file mode 100644 index 5639055..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-18.svg deleted file mode 100644 index b1e3462..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-19.svg deleted file mode 100644 index 7b95e2f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-2.svg deleted file mode 100644 index 2743843..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-20.svg deleted file mode 100644 index ab5c2c6..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-3.svg deleted file mode 100644 index c8451d2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-4.svg deleted file mode 100644 index d0bce8b..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-5.svg deleted file mode 100644 index 3f48567..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-6.svg deleted file mode 100644 index 40fed8a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-7.svg deleted file mode 100644 index c799b38..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-8.svg deleted file mode 100644 index d65b8b1..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-9.svg deleted file mode 100644 index 7ea1731..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-doo-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - DOO - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-0.svg deleted file mode 100644 index 9630bf3..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-1.svg deleted file mode 100644 index 07a97e4..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-10.svg deleted file mode 100644 index 3fa1559..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-11.svg deleted file mode 100644 index 705c20a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-12.svg deleted file mode 100644 index 6a9ee0a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-13.svg deleted file mode 100644 index 2965547..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-14.svg deleted file mode 100644 index e40cfe5..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-15.svg deleted file mode 100644 index 39e1ce7..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-16.svg deleted file mode 100644 index 3d73f1c..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-17.svg deleted file mode 100644 index 8205659..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-18.svg deleted file mode 100644 index 1b6e6ce..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-19.svg deleted file mode 100644 index 7590abc..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-2.svg deleted file mode 100644 index a626ad9..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-20.svg deleted file mode 100644 index 1fd0144..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-3.svg deleted file mode 100644 index 505e0fd..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-4.svg deleted file mode 100644 index 540f172..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-5.svg deleted file mode 100644 index bbf1039..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-6.svg deleted file mode 100644 index 9f748a9..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-7.svg deleted file mode 100644 index 9eb206f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-8.svg deleted file mode 100644 index 8dbadad..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-9.svg deleted file mode 100644 index 0b6ea23..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-dra-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - DRA - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-0.svg deleted file mode 100644 index 226a5d0..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-1.svg deleted file mode 100644 index 2c585f6..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-10.svg deleted file mode 100644 index 88010a5..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-11.svg deleted file mode 100644 index 0ed1022..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-12.svg deleted file mode 100644 index ced437d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-13.svg deleted file mode 100644 index df5745a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-14.svg deleted file mode 100644 index 693ed81..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-15.svg deleted file mode 100644 index e523960..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-16.svg deleted file mode 100644 index 7c4a5ba..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-17.svg deleted file mode 100644 index 0fdc458..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-18.svg deleted file mode 100644 index 4cadb97..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-19.svg deleted file mode 100644 index e81c323..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-2.svg deleted file mode 100644 index e2fdd1e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-20.svg deleted file mode 100644 index 317b82b..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-3.svg deleted file mode 100644 index 258374b..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-4.svg deleted file mode 100644 index 16a04ba..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-5.svg deleted file mode 100644 index 4b18cd5..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-6.svg deleted file mode 100644 index 8ad0c71..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-7.svg deleted file mode 100644 index 8121ccd..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-8.svg deleted file mode 100644 index f6cf77a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-9.svg deleted file mode 100644 index ca458c2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-jul-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - JUL - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-0.svg deleted file mode 100644 index 3ba0159..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-1.svg deleted file mode 100644 index da11d2f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-10.svg deleted file mode 100644 index b02cb50..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-11.svg deleted file mode 100644 index 20f66d2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-12.svg deleted file mode 100644 index a47d1ac..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-13.svg deleted file mode 100644 index 66e4cba..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-14.svg deleted file mode 100644 index 84c7a10..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-15.svg deleted file mode 100644 index f1c9b7a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-16.svg deleted file mode 100644 index fd0c108..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-17.svg deleted file mode 100644 index c8e319d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-18.svg deleted file mode 100644 index d986cd9..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-19.svg deleted file mode 100644 index 979f376..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-2.svg deleted file mode 100644 index 73244a7..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-20.svg deleted file mode 100644 index b1b63dc..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-3.svg deleted file mode 100644 index 82cee21..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-4.svg deleted file mode 100644 index 8f31b99..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-5.svg deleted file mode 100644 index f50bd49..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-6.svg deleted file mode 100644 index de8c258..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-7.svg deleted file mode 100644 index cba7ee9..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-8.svg deleted file mode 100644 index e70c3ae..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-9.svg deleted file mode 100644 index a1ddf67..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-kar-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - KAR - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-0.svg deleted file mode 100644 index abe084e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-1.svg deleted file mode 100644 index 15f158f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-10.svg deleted file mode 100644 index 49d4792..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-11.svg deleted file mode 100644 index 5dbaa00..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-12.svg deleted file mode 100644 index f4613fa..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-13.svg deleted file mode 100644 index ccf37fd..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-14.svg deleted file mode 100644 index 95a937d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-15.svg deleted file mode 100644 index d4bc6bb..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-16.svg deleted file mode 100644 index d3e493e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-17.svg deleted file mode 100644 index 61348b3..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-18.svg deleted file mode 100644 index db73fe7..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-19.svg deleted file mode 100644 index 2ce4753..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-2.svg deleted file mode 100644 index 1856e24..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-20.svg deleted file mode 100644 index 1b65da8..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-3.svg deleted file mode 100644 index 3c470d8..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-4.svg deleted file mode 100644 index 49dc3c9..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-5.svg deleted file mode 100644 index 7dcc7c2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-6.svg deleted file mode 100644 index 4a39a9e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-7.svg deleted file mode 100644 index 16a6bb7..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-8.svg deleted file mode 100644 index 813f5cd..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-9.svg deleted file mode 100644 index 312bf7b..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-mak-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - MAK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-0.svg deleted file mode 100644 index 1043967..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-1.svg deleted file mode 100644 index 94f3ee2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-10.svg deleted file mode 100644 index 546cb5f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-11.svg deleted file mode 100644 index b495abd..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-12.svg deleted file mode 100644 index ef65e78..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-13.svg deleted file mode 100644 index 42ea75b..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-14.svg deleted file mode 100644 index d6e19f9..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-15.svg deleted file mode 100644 index 1e0c530..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-16.svg deleted file mode 100644 index c37bc8c..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-17.svg deleted file mode 100644 index 9066d53..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-18.svg deleted file mode 100644 index 53f9271..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-19.svg deleted file mode 100644 index e3a7575..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-2.svg deleted file mode 100644 index 27cafb3..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-20.svg deleted file mode 100644 index 72d6357..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-3.svg deleted file mode 100644 index 0af8967..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-4.svg deleted file mode 100644 index 0271f13..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-5.svg deleted file mode 100644 index b504e69..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-6.svg deleted file mode 100644 index f910909..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-7.svg deleted file mode 100644 index 4c2cc0b..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-8.svg deleted file mode 100644 index d796390..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-9.svg deleted file mode 100644 index 227bf62..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-pyg-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - PYG - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-0.svg deleted file mode 100644 index dc51713..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-1.svg deleted file mode 100644 index a9ceb2f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-10.svg deleted file mode 100644 index acebe58..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-11.svg deleted file mode 100644 index a4a8228..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-12.svg deleted file mode 100644 index dad5800..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-13.svg deleted file mode 100644 index 3705c7c..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-14.svg deleted file mode 100644 index d425707..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-15.svg deleted file mode 100644 index 37c6469..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-16.svg deleted file mode 100644 index bbe3f46..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-17.svg deleted file mode 100644 index 6265ef6..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-18.svg deleted file mode 100644 index 8d8e185..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-19.svg deleted file mode 100644 index f04d6c5..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-2.svg deleted file mode 100644 index efbdc7a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-20.svg deleted file mode 100644 index d8bb001..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-3.svg deleted file mode 100644 index 741b264..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-4.svg deleted file mode 100644 index fe51a4e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-5.svg deleted file mode 100644 index edb6b4e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-6.svg deleted file mode 100644 index 6679d0a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-7.svg deleted file mode 100644 index 62a5413..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-8.svg deleted file mode 100644 index 8f940b0..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-9.svg deleted file mode 100644 index d6aa1de..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-ste-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - STE - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-0.svg deleted file mode 100644 index 77f10cb..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-1.svg deleted file mode 100644 index aaeaf97..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-10.svg deleted file mode 100644 index 3a7a428..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-11.svg deleted file mode 100644 index 111b2f1..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-12.svg deleted file mode 100644 index e334bc4..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-13.svg deleted file mode 100644 index 46a8f75..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-14.svg deleted file mode 100644 index 1db1d8e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-15.svg deleted file mode 100644 index 13d569b..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-16.svg deleted file mode 100644 index ff091ad..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-17.svg deleted file mode 100644 index 337790e..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-18.svg deleted file mode 100644 index 6d562f6..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-19.svg deleted file mode 100644 index 358320d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-2.svg deleted file mode 100644 index effe66f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-20.svg deleted file mode 100644 index c3f15c8..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-3.svg deleted file mode 100644 index 5b70ae6..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-4.svg deleted file mode 100644 index 5dc8dd5..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-5.svg deleted file mode 100644 index 1874a8f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-6.svg deleted file mode 100644 index be43bb8..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-7.svg deleted file mode 100644 index da8c6d8..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-8.svg deleted file mode 100644 index a63feed..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-9.svg deleted file mode 100644 index ee86357..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-unk-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - UNK - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-0.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-0.svg deleted file mode 100644 index 60623d0..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-0.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 0 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-1.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-1.svg deleted file mode 100644 index 96472d4..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-1.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 1 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-10.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-10.svg deleted file mode 100644 index 8c2a0bd..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-10.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 10 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-11.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-11.svg deleted file mode 100644 index 754d64f..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-11.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 11 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-12.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-12.svg deleted file mode 100644 index 5d8e087..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-12.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 12 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-13.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-13.svg deleted file mode 100644 index e6c39ee..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-13.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 13 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-14.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-14.svg deleted file mode 100644 index 79b8238..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-14.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 14 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-15.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-15.svg deleted file mode 100644 index f0711c2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-15.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 15 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-16.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-16.svg deleted file mode 100644 index 9d756a8..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-16.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 16 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-17.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-17.svg deleted file mode 100644 index 65270cb..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-17.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 17 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-18.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-18.svg deleted file mode 100644 index ed28072..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-18.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 18 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-19.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-19.svg deleted file mode 100644 index 2faa7c4..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-19.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 19 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-2.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-2.svg deleted file mode 100644 index 147d782..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-2.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 2 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-20.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-20.svg deleted file mode 100644 index 5aaa9ab..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-20.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 20 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-3.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-3.svg deleted file mode 100644 index 6ba82e3..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-3.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 3 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-4.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-4.svg deleted file mode 100644 index 738fbc7..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-4.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 4 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-5.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-5.svg deleted file mode 100644 index a439408..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-5.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 5 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-6.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-6.svg deleted file mode 100644 index 7941976..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-6.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 6 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-7.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-7.svg deleted file mode 100644 index b7f88fe..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-7.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 7 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-8.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-8.svg deleted file mode 100644 index 996927d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-8.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 8 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-9.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-9.svg deleted file mode 100644 index f79925d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/info/info-van-9.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - 9 - VAN - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-0-mis.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-0-mis.svg deleted file mode 100644 index 7ae506d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-0-mis.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 0 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-1-mis.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-1-mis.svg deleted file mode 100644 index 12fa45a..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-1-mis.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 1 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-10-dia.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-10-dia.svg deleted file mode 100644 index 3ae2a16..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-10-dia.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 10 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-10-gld.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-10-gld.svg deleted file mode 100644 index 18b832d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-10-gld.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 10 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-2-mis.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-2-mis.svg deleted file mode 100644 index c2d0cac..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-2-mis.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 2 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-3-mis.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-3-mis.svg deleted file mode 100644 index 9b32fb2..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-3-mis.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 3 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-4-brz.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-4-brz.svg deleted file mode 100644 index 31afcd5..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-4-brz.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 4 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-5-brz.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-5-brz.svg deleted file mode 100644 index 74d5dc5..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-5-brz.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 5 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-6-brz.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-6-brz.svg deleted file mode 100644 index 034af8d..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-6-brz.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 6 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-7-slv.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-7-slv.svg deleted file mode 100644 index 358eeae..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-7-slv.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 7 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-8-slv.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-8-slv.svg deleted file mode 100644 index 12c33bb..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-8-slv.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 8 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-9-slv.svg b/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-9-slv.svg deleted file mode 100644 index ead9c59..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/badges/wins/wins-9-slv.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - 9 - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/fonts/cinzel-latin.woff2 b/bazaarplusplus-installer/src-tauri/resources/stream/fonts/cinzel-latin.woff2 deleted file mode 100644 index ae41e54..0000000 Binary files a/bazaarplusplus-installer/src-tauri/resources/stream/fonts/cinzel-latin.woff2 and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/overlay.css b/bazaarplusplus-installer/src-tauri/resources/stream/overlay.css deleted file mode 100644 index eeaf1e7..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/overlay.css +++ /dev/null @@ -1,370 +0,0 @@ -/* The overlay is a standalone page served by the stream HTTP server, so it - bundles its own brand face, served from /assets/fonts for the wordmark. Latin subset only: - the only Cinzel text is the ASCII wordmark. */ -@font-face { - font-family: 'Cinzel'; - font-style: normal; - font-weight: 400 600; - font-display: swap; - src: url('/assets/fonts/cinzel-latin.woff2') format('woff2'); -} - -:root { - color-scheme: dark; - font-family: 'Palatino Linotype', 'Book Antiqua', Georgia, serif; - --bpp-text: #f2e3bf; - --bpp-soft: rgba(236, 219, 184, 0.72); - --bpp-dim: rgba(210, 188, 146, 0.54); - --bpp-accent: #d9aa58; - --bpp-panel-edge: rgba(178, 134, 64, 0.2); - --bpp-live: #7fc267; - --bpp-stale: #dd6f62; -} - -html, -body { - margin: 0; - width: 100%; - height: 100%; - overflow: hidden; - background: transparent; - color: var(--bpp-text); -} - -.overlay { - width: 100%; - min-height: 100%; - max-width: none; - padding: 0.2rem; - box-sizing: border-box; -} - -.list-shell { - display: grid; - gap: 0.3rem; - width: 100%; - padding: 0.3rem; - box-sizing: border-box; - border: 1px solid var(--bpp-panel-edge); - border-radius: 10px; - background: - linear-gradient(180deg, rgba(20, 13, 7, 0.92), rgba(9, 7, 4, 0.92)), - radial-gradient(circle at 100% 0, rgba(217, 170, 88, 0.08), transparent 28%); - box-shadow: 0 10px 26px rgba(0, 0, 0, 0.22); -} - -.overlay-header, -.header-lockup, -.status-row, -.empty-state, -.run-list, -.run-card, -.run-row, -.run-meta, -.run-stats, -.visual-stage { - position: relative; -} - -.overlay-header { - display: flex; - justify-content: center; - padding: 0.04rem 0.15rem 0; -} - -.header-lockup { - display: inline-flex; - align-items: center; - justify-content: center; - gap: 1.48em; - max-width: 100%; - min-width: 0; - white-space: nowrap; - font-size: clamp(2.1rem, 5.4vw, 3.24rem); -} - -.header-brand { - font-family: 'Cinzel', 'Palatino Linotype', 'Book Antiqua', Georgia, serif; - font-size: 1em; - letter-spacing: 0.16em; - text-transform: uppercase; - color: rgba(242, 227, 191, 0.94); - text-align: center; - white-space: nowrap; - flex: 0 1 auto; - min-width: 0; -} - -.header-signal, -.status-line, -.empty-title, -.empty-detail, -.hero-name, -.score-wins, -.score-slash, -.score-battles, -.tier-badge-label { - margin: 0; -} - -.status-line { - font-size: 0.34em; - line-height: 1; - letter-spacing: 0.14em; - text-transform: uppercase; - color: rgba(221, 236, 212, 0.84); - white-space: nowrap; -} - -.status-pill { - display: flex; - align-items: center; - gap: 0.48em; - flex: 0 0 auto; - padding: 0.24em 0.62em; - border: 1px solid rgba(178, 134, 64, 0.14); - border-radius: 999px; - background: linear-gradient( - 180deg, - rgba(16, 13, 8, 0.76), - rgba(10, 8, 5, 0.72) - ); - box-shadow: inset 0 0 0 1px rgba(255, 224, 162, 0.02); -} - -.status-dot { - width: 0.42em; - height: 0.42em; - border-radius: 999px; - background: rgba(201, 176, 132, 0.42); - box-shadow: 0 0 0 1px rgba(255, 244, 214, 0.08); -} - -.empty-state { - display: grid; - gap: 0.14rem; - padding: 0.42rem 0.5rem; - border: 1px solid rgba(178, 134, 64, 0.12); - border-radius: 8px; - background: rgba(12, 9, 5, 0.92); -} - -.empty-state[hidden] { - display: none !important; -} - -.empty-title { - font-size: 0.84rem; - color: var(--bpp-text); -} - -.empty-detail { - font-size: 0.62rem; - line-height: 1.35; - color: var(--bpp-soft); -} - -.run-list { - display: grid; - gap: 0.24rem; -} - -.run-list[hidden] { - display: none; -} - -.run-row { - min-width: 0; -} - -.run-card { - display: grid; - grid-template-columns: max-content minmax(0, 1fr); - gap: 0.06rem; - align-items: stretch; - min-width: 0; - padding: 0.14rem; - border: 1px solid rgba(178, 134, 64, 0.14); - border-radius: 7px; - overflow: hidden; - background: - linear-gradient(180deg, rgba(15, 11, 7, 0.95), rgba(7, 5, 3, 0.95)), - radial-gradient(circle at top right, rgba(217, 170, 88, 0.05), transparent 42%); -} - -.run-meta { - display: flex; - align-items: center; - justify-content: center; - gap: 0; - width: fit-content; - height: 100%; - min-width: 0; - align-self: stretch; - padding: 0; - border-radius: 9px; - border: none; - background: transparent; - box-shadow: none; -} - -.hero-name { - width: 100%; -} - -.sr-only { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} - -.meta-stack { - display: grid; - height: 100%; - gap: 0; - align-self: stretch; -} - -.meta-stack.mode-current, -.meta-stack.mode-hero { - grid-template-rows: 1fr 1fr; - aspect-ratio: 1 / 2; -} - -.meta-stack.mode-herohalf { - grid-template-rows: 2fr 1fr; - aspect-ratio: 2 / 3; -} - -.metric-tile { - width: 100%; - height: 100%; - min-width: 0; - min-height: 0; - display: block; - padding: 0; - border-radius: 0.26rem; - overflow: hidden; -} - -.metric-badge-svg { - display: block; - width: 100%; - height: 100%; -} - -.run-visual { - margin: 0; - min-width: 0; - display: flex; - align-items: center; - align-self: center; -} - -.visual-frame { - width: 100%; - display: flex; - align-items: center; - min-width: 0; - padding: 0; -} - -.visual-stage { - overflow: hidden; - width: 100%; - border-radius: 8px; - background: rgba(3, 3, 3, 0.65); -} - -.visual-stage img { - display: block; - width: 100%; - height: auto; -} - -.overlay.live .status-dot { - background: var(--bpp-live); - box-shadow: - 0 0 0 1px rgba(175, 227, 156, 0.22), - 0 0 10px rgba(127, 194, 103, 0.24); -} - -.overlay.live .status-line { - color: rgba(213, 234, 200, 0.92); -} - -.overlay.stale .status-dot { - background: var(--bpp-stale); - box-shadow: - 0 0 0 1px rgba(255, 204, 194, 0.18), - 0 0 10px rgba(221, 111, 98, 0.2); -} - -.overlay.stale .status-line { - color: rgba(255, 204, 194, 0.92); -} - -.overlay.is-updated .run-row:first-child { - animation: reveal-up 260ms ease; -} - -.tier-misfortune { - background: linear-gradient(180deg, rgba(84, 73, 73, 0.98), rgba(58, 49, 49, 0.98)); -} - -.tier-silver { - background: linear-gradient(180deg, rgba(99, 106, 117, 0.98), rgba(67, 73, 84, 0.98)); -} - -.tier-bronze { - background: linear-gradient(180deg, rgba(106, 80, 70, 0.98), rgba(71, 53, 46, 0.98)); -} - -.tier-gold { - background: linear-gradient(180deg, rgba(124, 106, 71, 0.98), rgba(88, 74, 48, 0.98)); -} - -.tier-diamond { - background: linear-gradient(180deg, rgba(116, 84, 148, 0.98), rgba(78, 55, 108, 0.98)); -} - -.tier-unknown { - background: linear-gradient(180deg, rgba(93, 88, 80, 0.98), rgba(66, 61, 55, 0.98)); -} - -@keyframes reveal-up { - from { - opacity: 0; - transform: translateY(5px); - } - - to { - opacity: 1; - transform: translateY(0); - } -} - -@media (max-width: 520px) { - .overlay { - padding: 0.15rem; - } - - .overlay-header { - justify-content: flex-start; - } - - .header-lockup { - font-size: clamp(1.8rem, 9.6vw, 2.32rem); - gap: 1.16em; - } - - .run-card { - grid-template-columns: max-content minmax(0, 1fr); - } -} diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/overlay.html b/bazaarplusplus-installer/src-tauri/resources/stream/overlay.html deleted file mode 100644 index ceeee05..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/overlay.html +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - BazaarPlusPlus Overlay - - - - -
-
-
-
- -
- -

Waiting

-
-
-
- -
-

No records yet

-

- Start a match and the overlay will update automatically. -

-
- - -
-
- - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/overlay.js b/bazaarplusplus-installer/src-tauri/resources/stream/overlay.js deleted file mode 100644 index 8bedeb6..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/overlay.js +++ /dev/null @@ -1,373 +0,0 @@ -const root = document.getElementById('overlay-root'); -const signal = document.getElementById('overlay-signal'); -const status = document.getElementById('overlay-status'); -const emptyState = document.getElementById('overlay-empty'); -const emptyTitle = document.getElementById('overlay-empty-title'); -const emptyDetail = document.getElementById('overlay-empty-detail'); -const list = document.getElementById('overlay-list'); - -let lastRecordKey = null; -let rowResizeObserver = null; -let currentDisplayMode = 'current'; - -function setClassNames(...tokens) { - if (!root) { - return; - } - - root.className = ['overlay', ...tokens].join(' '); -} - -function setText(node, value) { - if (node) { - node.textContent = value; - } -} - -function markUpdated() { - if (!root) { - return; - } - - root.classList.remove('is-updated'); - window.requestAnimationFrame(() => { - root.classList.add('is-updated'); - window.setTimeout(() => root.classList.remove('is-updated'), 500); - }); -} - -function escapeHtml(value) { - return String(value) - .replaceAll('&', '&') - .replaceAll('<', '<') - .replaceAll('>', '>') - .replaceAll('"', '"') - .replaceAll("'", '''); -} - -function buildStats(record) { - return { - wins: - typeof record?.wins === 'number' && Number.isFinite(record.wins) - ? record.wins - : null, - battles: - typeof record?.battle_count === 'number' && Number.isFinite(record.battle_count) - ? record.battle_count - : null - }; -} - -function getHeroBadgeStyle(heroName) { - const normalized = typeof heroName === 'string' ? heroName.trim() : ''; - if (!normalized) { - return { - shortCode: 'UNK', - background: 'rgba(51, 74, 97, 0.95)', - text: '#ffffff', - assetKey: 'unk' - }; - } - - const theDragonsStyle = { shortCode: 'DRA', background: 'rgb(45, 210, 208)', text: 'rgb(26, 31, 38)', assetKey: 'dra' }; - const map = { - Vanessa: { shortCode: 'VAN', background: 'rgb(192, 33, 33)', text: '#ffffff', assetKey: 'van' }, - Pygmalien: { shortCode: 'PYG', background: 'rgb(39, 103, 192)', text: '#ffffff', assetKey: 'pyg' }, - Dooley: { shortCode: 'DOO', background: 'rgb(225, 154, 8)', text: '#ffffff', assetKey: 'doo' }, - Mak: { shortCode: 'MAK', background: 'rgb(190, 230, 91)', text: 'rgb(26, 31, 38)', assetKey: 'mak' }, - Jules: { shortCode: 'JUL', background: 'rgb(180, 52, 236)', text: '#ffffff', assetKey: 'jul' }, - Karnok: { shortCode: 'KAR', background: 'rgb(59, 136, 156)', text: '#ffffff', assetKey: 'kar' }, - Stelle: { shortCode: 'STE', background: 'rgb(255, 235, 24)', text: 'rgb(26, 31, 38)', assetKey: 'ste' }, - TheDragons: theDragonsStyle, - Hero8: theDragonsStyle - }; - - if (map[normalized]) { - return map[normalized]; - } - - return { - shortCode: normalized.length <= 3 ? normalized.toUpperCase() : normalized.slice(0, 3).toUpperCase(), - background: 'rgba(57, 73, 97, 0.98)', - text: '#ffffff', - assetKey: 'unk' - }; -} - -function normalizeDisplayMode(value) { - if (value === 'hero' || value === 'herohalf') { - return value; - } - - return 'current'; -} - -function getWinsBadgeAsset(wins, battles) { - if (typeof wins !== 'number' || !Number.isFinite(wins) || wins < 0) { - return '/assets/badges/wins/wins-0-mis.svg'; - } - - const safeWins = Math.max(0, Math.min(10, Math.trunc(wins))); - if (safeWins === 10) { - if (typeof battles === 'number' && Number.isFinite(battles) && Math.trunc(battles) === 10) { - return '/assets/badges/wins/wins-10-dia.svg'; - } - return '/assets/badges/wins/wins-10-gld.svg'; - } - if (safeWins >= 7) { - return `/assets/badges/wins/wins-${safeWins}-slv.svg`; - } - if (safeWins >= 4) { - return `/assets/badges/wins/wins-${safeWins}-brz.svg`; - } - return `/assets/badges/wins/wins-${safeWins}-mis.svg`; -} - -function getInfoBadgeAsset(heroKey, battles) { - const safeHeroKey = typeof heroKey === 'string' && heroKey ? heroKey : 'unk'; - const safeBattles = - typeof battles === 'number' && Number.isFinite(battles) - ? Math.max(0, Math.min(20, Math.trunc(battles))) - : 0; - return `/assets/badges/info/info-${safeHeroKey}-${safeBattles}.svg`; -} - -function getHeroModeAsset(heroKey, displayMode) { - const safeHeroKey = typeof heroKey === 'string' && heroKey ? heroKey : 'unk'; - if (displayMode === 'hero') { - return `/assets/badges/heroes/hero-${safeHeroKey}.svg`; - } - - return `/assets/badges/herohalf/herohalf-${safeHeroKey}.svg`; -} - -function buildRowMarkup(record) { - const title = escapeHtml(record?.title || 'Unknown hero'); - const stats = buildStats(record); - const heroBadge = getHeroBadgeStyle(record?.hero_id); - const secondBadgeSrc = - currentDisplayMode === 'current' - ? getInfoBadgeAsset(heroBadge.assetKey, stats.battles) - : getHeroModeAsset(heroBadge.assetKey, currentDisplayMode); - const secondBadgeAlt = - currentDisplayMode === 'current' - ? `${stats.battles ?? 'unknown'} battles with ${escapeHtml(heroBadge.shortCode)}` - : `${escapeHtml(title)} hero badge`; - const scoreMarkup = ` -
-
- ${stats.wins ?? 'unknown'} wins -
-
- ${secondBadgeAlt} -
-
- `; - const imageUrl = - typeof record?.strip_url === 'string' && record.strip_url - ? record.strip_url - : ''; - const image = imageUrl - ? `
${title} run strip
` - : `
`; - - return ` -
-
-
-

${title}

- ${scoreMarkup} -
- ${image} -
-
- `; -} - -function renderEmpty(message) { - setClassNames('empty'); - setText(signal, 'Local feed idle'); - setText(status, 'Waiting'); - - if (emptyState) { - emptyState.hidden = false; - emptyState.style.display = ''; - } - - if (list) { - list.hidden = true; - list.innerHTML = ''; - } - - setText(emptyTitle, 'No records yet'); - setText( - emptyDetail, - message ?? 'Start a match and the overlay will update automatically.' - ); -} - -function renderRecords(records, options = {}) { - if (!list) { - return; - } - - const { stale = false, updated = false } = options; - setClassNames(stale ? 'stale' : 'live'); - setText( - signal, - stale ? 'Connection lost, showing cached data' : 'Local SQLite feed live' - ); - setText(status, stale ? 'Retrying' : 'Live'); - - if (emptyState) { - emptyState.hidden = true; - emptyState.style.display = 'none'; - } - - list.hidden = false; - list.innerHTML = records.map(buildRowMarkup).join(''); - syncRowHeights(); - - if (updated) { - markUpdated(); - } -} - -function applyRowHeight(row) { - if (!(row instanceof HTMLElement)) { - return; - } - - const visualStage = row.querySelector('.visual-stage'); - const meta = row.querySelector('.run-meta'); - if (!(visualStage instanceof HTMLElement) || !(meta instanceof HTMLElement)) { - return; - } - - const visualHeight = visualStage.getBoundingClientRect().height; - if (visualHeight > 0) { - meta.style.height = `${visualHeight}px`; - } -} - -function syncRowHeights() { - if (!(list instanceof HTMLElement)) { - return; - } - - if (rowResizeObserver) { - rowResizeObserver.disconnect(); - rowResizeObserver = null; - } - - rowResizeObserver = new ResizeObserver((entries) => { - entries.forEach((entry) => { - const row = entry.target.closest('.run-row'); - if (row instanceof HTMLElement) { - applyRowHeight(row); - } - }); - }); - - list.querySelectorAll('.run-row').forEach((row) => { - if (!(row instanceof HTMLElement)) { - return; - } - - applyRowHeight(row); - - const visualStage = row.querySelector('.visual-stage'); - const image = row.querySelector('.visual-stage img'); - - if (visualStage instanceof HTMLElement) { - rowResizeObserver.observe(visualStage); - } - - if (image instanceof HTMLImageElement) { - if (image.complete) { - applyRowHeight(row); - } else { - image.addEventListener('load', () => applyRowHeight(row), { once: true }); - } - } - }); -} - -function getRecordKey(record) { - return [ - record?.id ?? '', - record?.captured_at ?? '', - record?.wins ?? '', - record?.battle_count ?? '', - record?.strip_url ?? '' - ].join('::'); -} - -async function loadOverlaySettings() { - const response = await fetch('/api/overlay/crop-config', { cache: 'no-store' }); - if (!response.ok) { - const message = (await response.text()).trim(); - throw new Error(message || `unexpected status ${response.status}`); - } - - const payload = await response.json(); - return normalizeDisplayMode(payload?.display_mode); -} - -async function refresh() { - try { - const settingsPromise = loadOverlaySettings().catch(() => currentDisplayMode); - const endpoint = new URL('/api/stream/records', window.location.origin); - const response = await fetch(endpoint, { cache: 'no-store' }); - if (!response.ok) { - const message = (await response.text()).trim(); - throw new Error(message || `unexpected status ${response.status}`); - } - const payload = await response.json(); - const records = Array.isArray(payload) ? payload.filter((r) => r && r.strip_url) : []; - - const nextDisplayMode = await settingsPromise; - const modeChanged = nextDisplayMode !== currentDisplayMode; - currentDisplayMode = nextDisplayMode; - - if (records.length === 0) { - lastRecordKey = null; - renderEmpty(); - return; - } - - const nextKey = records.map(getRecordKey).join('|'); - const updated = nextKey !== lastRecordKey; - - if ( - !updated && - !modeChanged && - root?.classList.contains('live') && - list && - !list.hidden - ) { - return; - } - - lastRecordKey = nextKey; - renderRecords(records, { updated }); - } catch (error) { - if (lastRecordKey && list && !list.hidden) { - setClassNames('stale'); - setText(signal, 'Connection lost, showing cached data'); - setText(status, 'Retrying'); - return; - } - - renderEmpty( - error instanceof Error && error.message - ? error.message - : 'Waiting for records captured after stream start.' - ); - } -} - -renderEmpty(); -void refresh(); -window.addEventListener('resize', syncRowHeights); -window.setInterval(refresh, 4000); diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/settings.css b/bazaarplusplus-installer/src-tauri/resources/stream/settings.css deleted file mode 100644 index 6139a03..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/settings.css +++ /dev/null @@ -1,751 +0,0 @@ -:root { - color-scheme: dark; - font-family: - -apple-system, BlinkMacSystemFont, 'Noto Sans SC', 'Segoe UI', - 'Microsoft YaHei', sans-serif; - font-synthesis: none; - text-rendering: geometricPrecision; - --bpp-bg: #0a0e12; - --bpp-surface-1: #10151a; - --bpp-surface-2: #161c21; - --bpp-surface-inset: #0c1014; - --bpp-line: rgba(234, 230, 222, 0.1); - --bpp-line-subtle: rgba(234, 230, 222, 0.06); - --bpp-line-accent: rgba(236, 143, 26, 0.4); - --bpp-text-1: #e6e0d5; - --bpp-text-2: #a49e93; - --bpp-text-3: #8f8a82; - --bpp-accent: #ed8b18; - --bpp-accent-hover: #f5a53a; - --bpp-accent-muted: #bd7a2a; - --bpp-success: #57ba70; - --bpp-warning: #d9a34a; - --bpp-danger: #d55b4f; - --bpp-radius-control: 4px; - --bpp-radius-panel: 8px; - --bpp-radius-emphasis: 10px; - --crop-left: 34.2%; - --crop-top: 31.3%; - --crop-width: 58%; - --crop-height: 22%; -} - -* { - box-sizing: border-box; -} - -html { - min-width: 20rem; - background: var(--bpp-bg); -} - -body { - margin: 0; - min-height: 100vh; - color: var(--bpp-text-1); - background: - radial-gradient( - ellipse 68% 50% at 92% -8%, - rgba(36, 76, 98, 0.54), - transparent 70% - ), - radial-gradient( - ellipse 58% 44% at 16% 108%, - rgba(100, 66, 46, 0.34), - transparent 72% - ), - linear-gradient(155deg, #080d13 0%, #0d131a 48%, #10161d 100%); -} - -button, -input { - font: inherit; -} - -button, -summary, -input[type='range'] { - -webkit-tap-highlight-color: transparent; -} - -.settings-shell { - width: min(100%, 94rem); - margin: 0 auto; - padding: 1.75rem clamp(1rem, 2.6vw, 2.5rem) 2.5rem; - display: grid; - gap: 1rem; -} - -.page-header, -.workspace, -.panel-heading, -.preview-panel, -.controls-panel, -.preview-workspace, -.control-list, -.control-group, -.control-row, -.actions, -.code-block { - display: grid; -} - -.page-header { - grid-template-columns: minmax(0, 1fr) auto; - align-items: end; - gap: 2rem; - padding-bottom: 0.25rem; -} - -.page-heading { - max-width: 46rem; -} - -.eyebrow, -.panel-eyebrow, -.section-label, -.page-intro, -.page-status, -.selected-meta, -.preview-caption, -.control-hint, -.code-block p { - margin: 0; -} - -.eyebrow, -.panel-eyebrow, -.section-label, -.control-group legend { - color: var(--bpp-accent); - font-size: 0.67rem; - font-weight: 700; - letter-spacing: 0.14em; - line-height: 1.4; - text-transform: uppercase; -} - -h1, -h2 { - margin: 0; - color: var(--bpp-text-1); - letter-spacing: -0.025em; -} - -h1 { - margin-top: 0.28rem; - font-size: clamp(2rem, 4vw, 3.15rem); - font-weight: 650; - line-height: 1.05; -} - -h2 { - margin-top: 0.2rem; - font-size: 1.05rem; - font-weight: 650; - line-height: 1.3; -} - -.page-intro { - max-width: 42rem; - margin-top: 0.75rem; - color: var(--bpp-text-2); - font-size: 0.88rem; - line-height: 1.6; -} - -.calibration-steps { - display: flex; - margin: 0; - padding: 0; - list-style: none; - border: 1px solid var(--bpp-line); - border-radius: var(--bpp-radius-panel); - background: rgba(12, 16, 20, 0.7); - box-shadow: 0 18px 38px rgba(0, 0, 0, 0.16); - overflow: hidden; -} - -.calibration-steps li { - position: relative; - min-width: 8.3rem; - padding: 0.72rem 0.9rem; - display: flex; - align-items: center; - gap: 0.65rem; -} - -.calibration-steps li + li { - border-left: 1px solid var(--bpp-line); -} - -.step-number { - width: 1.65rem; - height: 1.65rem; - flex: none; - display: inline-flex; - align-items: center; - justify-content: center; - border: 1px solid var(--bpp-line-accent); - border-radius: 999px; - color: var(--bpp-accent-hover); - background: rgba(237, 139, 24, 0.08); - font-size: 0.7rem; - font-variant-numeric: tabular-nums; - font-weight: 700; -} - -.calibration-steps strong, -.calibration-steps small { - display: block; - white-space: nowrap; -} - -.calibration-steps strong { - color: var(--bpp-text-1); - font-size: 0.75rem; - font-weight: 650; -} - -.calibration-steps small { - margin-top: 0.08rem; - color: var(--bpp-text-3); - font-size: 0.65rem; -} - -.page-status { - min-height: 2.65rem; - padding: 0.66rem 0.85rem; - display: flex; - align-items: center; - gap: 0.62rem; - border: 1px solid var(--bpp-line); - border-radius: var(--bpp-radius-control); - color: var(--bpp-text-2); - background: rgba(12, 16, 20, 0.72); - font-size: 0.75rem; - line-height: 1.45; -} - -.status-indicator { - width: 0.48rem; - height: 0.48rem; - flex: none; - border-radius: 999px; - background: var(--bpp-text-3); - box-shadow: 0 0 0 3px rgba(143, 138, 130, 0.12); -} - -.page-status[data-state='loading'] .status-indicator { - background: var(--bpp-accent); - box-shadow: 0 0 0 3px rgba(237, 139, 24, 0.12); - animation: status-pulse 1.4s ease-in-out infinite; -} - -.page-status[data-state='ready'] .status-indicator, -.page-status[data-state='success'] .status-indicator { - background: var(--bpp-success); - box-shadow: 0 0 0 3px rgba(87, 186, 112, 0.12); -} - -.page-status[data-state='pending'] .status-indicator { - background: var(--bpp-warning); - box-shadow: 0 0 0 3px rgba(217, 163, 74, 0.12); -} - -.page-status[data-state='error'] .status-indicator { - background: var(--bpp-danger); - box-shadow: 0 0 0 3px rgba(213, 91, 79, 0.12); -} - -.workspace { - grid-template-columns: minmax(0, 1fr) minmax(19rem, 22rem); - gap: 1rem; - align-items: start; -} - -.preview-panel, -.controls-panel { - gap: 1rem; - padding: 1.15rem; - border: 1px solid var(--bpp-line); - border-radius: var(--bpp-radius-panel); - background: linear-gradient( - 180deg, - rgba(16, 21, 26, 0.96), - rgba(12, 16, 20, 0.96) - ); - box-shadow: 0 24px 54px rgba(0, 0, 0, 0.22); -} - -.controls-panel { - position: sticky; - top: 1rem; -} - -.panel-heading { - grid-template-columns: minmax(0, 1fr) auto; - align-items: end; - gap: 1rem; - min-height: 2.8rem; -} - -.selected-meta { - max-width: 18rem; - padding: 0.38rem 0.56rem; - border: 1px solid var(--bpp-line); - border-radius: var(--bpp-radius-control); - color: var(--bpp-text-2); - background: var(--bpp-surface-inset); - font-size: 0.7rem; - line-height: 1.4; - text-align: right; -} - -.preview-empty { - min-height: 20rem; - padding: 1.25rem; - display: grid; - place-items: center; - border: 1px dashed var(--bpp-line-accent); - border-radius: var(--bpp-radius-emphasis); - color: var(--bpp-text-2); - background: var(--bpp-surface-inset); - font-size: 0.82rem; - text-align: center; -} - -.preview-workspace { - gap: 0.85rem; -} - -.preview-workspace[hidden], -.preview-empty[hidden] { - display: none; -} - -.preview-card { - min-width: 0; - margin: 0; - padding: 0.8rem; - border: 1px solid var(--bpp-line-subtle); - border-radius: var(--bpp-radius-emphasis); - background: rgba(12, 16, 20, 0.74); -} - -.preview-card figcaption { - margin-bottom: 0.62rem; - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 1rem; -} - -.preview-caption { - color: var(--bpp-text-3); - font-size: 0.68rem; - line-height: 1.4; - text-align: right; -} - -.full-preview-stage, -.result-preview-stage { - position: relative; - overflow: hidden; - border: 1px solid var(--bpp-line); - border-radius: 6px; - background: - linear-gradient(45deg, rgba(255, 255, 255, 0.018) 25%, transparent 25%) 0 - 0 / 16px 16px, - linear-gradient(-45deg, rgba(255, 255, 255, 0.018) 25%, transparent 25%) 0 - 8px / 16px 16px, - var(--bpp-bg); -} - -.full-preview-stage img, -.result-preview-stage img { - display: block; - width: 100%; - height: auto; -} - -.crop-box { - position: absolute; - left: var(--crop-left); - top: var(--crop-top); - width: var(--crop-width); - height: var(--crop-height); - border: 2px solid var(--bpp-accent-hover); - box-shadow: - 0 0 0 999px rgba(4, 7, 10, 0.7), - 0 0 0 1px rgba(255, 233, 194, 0.28) inset, - 0 0 18px rgba(237, 139, 24, 0.2); - pointer-events: none; -} - -.crop-box::before, -.crop-box::after { - content: ''; - position: absolute; - pointer-events: none; -} - -.crop-box::before { - inset: 50% 0 auto; - border-top: 1px dashed rgba(255, 255, 255, 0.24); -} - -.crop-box::after { - inset: 0 auto 0 50%; - border-left: 1px dashed rgba(255, 255, 255, 0.24); -} - -.result-preview-card { - border-color: rgba(237, 139, 24, 0.18); - background: linear-gradient( - 135deg, - rgba(237, 139, 24, 0.055), - rgba(12, 16, 20, 0.84) - ); -} - -.result-preview-stage { - min-height: 4.5rem; - display: grid; - place-items: center; -} - -.result-preview-stage img { - max-height: 14rem; - object-fit: contain; -} - -.control-list { - gap: 0.9rem; -} - -.control-group { - min-width: 0; - margin: 0; - padding: 0.8rem; - gap: 0.78rem; - border: 1px solid var(--bpp-line-subtle); - border-radius: 6px; - background: var(--bpp-surface-inset); -} - -.control-group legend { - padding: 0 0.38rem; -} - -.control-row { - gap: 0.48rem; -} - -.control-topline { - display: flex; - align-items: center; - justify-content: space-between; - gap: 0.75rem; -} - -.control-topline > span { - color: var(--bpp-text-2); - font-size: 0.74rem; -} - -.control-row output { - min-width: 3.6rem; - padding: 0.23rem 0.4rem; - border: 1px solid var(--bpp-line); - border-radius: var(--bpp-radius-control); - color: var(--bpp-text-1); - background: var(--bpp-surface-2); - font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', monospace; - font-size: 0.7rem; - font-variant-numeric: tabular-nums; - line-height: 1.2; - text-align: right; -} - -.control-row input[type='range'] { - width: 100%; - height: 1.1rem; - margin: 0; - padding: 0; - appearance: none; - background: transparent; - cursor: ew-resize; -} - -.control-row input[type='range']::-webkit-slider-runnable-track { - height: 0.26rem; - border-radius: 999px; - background: linear-gradient( - 90deg, - var(--bpp-accent-muted), - rgba(164, 158, 147, 0.24) - ); -} - -.control-row input[type='range']::-webkit-slider-thumb { - width: 0.92rem; - height: 0.92rem; - margin-top: -0.33rem; - appearance: none; - border: 2px solid var(--bpp-surface-inset); - border-radius: 999px; - background: var(--bpp-accent-hover); - box-shadow: 0 0 0 1px rgba(245, 165, 58, 0.65); -} - -.control-row input[type='range']::-moz-range-track { - height: 0.26rem; - border: 0; - border-radius: 999px; - background: linear-gradient( - 90deg, - var(--bpp-accent-muted), - rgba(164, 158, 147, 0.24) - ); -} - -.control-row input[type='range']::-moz-range-thumb { - width: 0.82rem; - height: 0.82rem; - border: 2px solid var(--bpp-surface-inset); - border-radius: 999px; - background: var(--bpp-accent-hover); - box-shadow: 0 0 0 1px rgba(245, 165, 58, 0.65); -} - -.control-row input[type='range']:focus-visible { - outline: none; -} - -.control-row input[type='range']:focus-visible::-webkit-slider-thumb { - box-shadow: - 0 0 0 1px var(--bpp-bg), - 0 0 0 4px rgba(245, 165, 58, 0.5); -} - -.control-row input[type='range']:focus-visible::-moz-range-thumb { - box-shadow: - 0 0 0 1px var(--bpp-bg), - 0 0 0 4px rgba(245, 165, 58, 0.5); -} - -.control-hint { - color: var(--bpp-text-3); - font-size: 0.67rem; - line-height: 1.5; -} - -.actions { - grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); - gap: 0.55rem; -} - -button { - min-height: 2.45rem; - padding: 0.6rem 0.78rem; - border: 1px solid var(--bpp-line); - border-radius: var(--bpp-radius-control); - display: inline-flex; - align-items: center; - justify-content: center; - color: var(--bpp-text-2); - background: var(--bpp-surface-2); - font-size: 0.72rem; - font-weight: 650; - line-height: 1.25; - cursor: pointer; - transition: - border-color 140ms ease, - color 140ms ease, - background 140ms ease, - transform 140ms ease; -} - -button:hover:not(:disabled) { - border-color: rgba(237, 139, 24, 0.28); - color: var(--bpp-text-1); - background: #1b2228; -} - -button:active:not(:disabled) { - transform: translateY(1px); -} - -button:focus-visible, -summary:focus-visible { - outline: 2px solid var(--bpp-accent-hover); - outline-offset: 2px; -} - -button:disabled { - opacity: 0.42; - cursor: not-allowed; -} - -.primary-button { - border-color: rgba(237, 139, 24, 0.46); - color: #171007; - background: linear-gradient( - 180deg, - var(--bpp-accent-hover), - var(--bpp-accent) - ); - box-shadow: 0 8px 20px rgba(237, 139, 24, 0.12); -} - -.primary-button:hover:not(:disabled) { - border-color: var(--bpp-accent-hover); - color: #130d06; - background: linear-gradient(180deg, #ffb955, var(--bpp-accent-hover)); -} - -.code-disclosure { - border-top: 1px solid var(--bpp-line-subtle); - padding-top: 0.8rem; -} - -.code-disclosure summary { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1rem; - color: var(--bpp-text-2); - font-size: 0.7rem; - line-height: 1.4; - cursor: pointer; - list-style-position: inside; -} - -.code-format { - margin-left: auto; - color: var(--bpp-text-3); - font-family: 'SFMono-Regular', Consolas, monospace; - font-size: 0.62rem; - letter-spacing: 0.08em; - text-transform: uppercase; -} - -.code-block { - gap: 0.55rem; - padding-top: 0.7rem; -} - -.code-block p { - color: var(--bpp-text-3); - font-size: 0.66rem; - line-height: 1.5; -} - -.settings-code-text { - max-height: 6rem; - padding: 0.62rem; - display: block; - overflow: auto; - overflow-wrap: anywhere; - border: 1px solid var(--bpp-line-subtle); - border-radius: var(--bpp-radius-control); - color: var(--bpp-text-2); - background: var(--bpp-bg); - font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', monospace; - font-size: 0.64rem; - line-height: 1.45; - user-select: text; -} - -@keyframes status-pulse { - 0%, - 100% { - opacity: 0.52; - } - 50% { - opacity: 1; - } -} - -@media (max-width: 1120px) { - .page-header { - grid-template-columns: 1fr; - align-items: start; - gap: 1.15rem; - } - - .calibration-steps { - width: 100%; - } - - .calibration-steps li { - min-width: 0; - flex: 1; - } -} - -@media (max-width: 940px) { - .workspace { - grid-template-columns: 1fr; - } - - .controls-panel { - position: static; - } -} - -@media (max-width: 620px) { - .settings-shell { - padding: 1.15rem 0.75rem 1.5rem; - } - - .calibration-steps { - display: grid; - grid-template-columns: repeat(3, 1fr); - } - - .calibration-steps li { - padding: 0.62rem; - justify-content: center; - } - - .calibration-steps li + li { - border-left: 1px solid var(--bpp-line); - } - - .calibration-steps small { - display: none; - } - - .panel-heading, - .preview-card figcaption { - grid-template-columns: 1fr; - align-items: start; - } - - .panel-heading { - display: grid; - } - - .selected-meta, - .preview-caption { - max-width: none; - text-align: left; - } - - .actions { - grid-template-columns: 1fr; - } -} - -@media (prefers-reduced-motion: reduce) { - *, - *::before, - *::after { - scroll-behavior: auto !important; - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } -} diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/settings.html b/bazaarplusplus-installer/src-tauri/resources/stream/settings.html deleted file mode 100644 index 0a5f0a6..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/settings.html +++ /dev/null @@ -1,256 +0,0 @@ - - - - - - BazaarPlusPlus Overlay Calibration - - - - -
- - -
- - Loading the selected stream record... -
- -
-
-
-
-

Preview

-

- Frame your overlay precisely -

-
-

- No sample selected -

-
- -
- Waiting for screenshots with end-of-run crops. -
- - -
- - -
-
- - diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/settings.js b/bazaarplusplus-installer/src-tauri/resources/stream/settings.js deleted file mode 100644 index 376a802..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/settings.js +++ /dev/null @@ -1,520 +0,0 @@ -const DEFAULT_CROP = { - left: 0.342, - top: 0.313, - width: 0.58, - height: 0.22 -}; - -// This page is served by the local stream service on its own origin, so it -// cannot read the app's stored locale. The app appends `?lang=` when it opens -// the page; a direct visit falls back to the browser language. -const MESSAGES = { - en: { - documentTitle: 'BazaarPlusPlus Overlay Calibration', - eyebrow: 'Stream Overlay', - heading: 'Crop Calibration', - pageIntro: - 'Define the exact part of the end-of-run screenshot that appears in your stream overlay.', - stepsLabel: 'Calibration steps', - stepAdjustTitle: 'Adjust', - stepAdjustDetail: 'Frame the result', - stepPreviewTitle: 'Preview', - stepPreviewDetail: 'Check the output', - stepSaveTitle: 'Save', - stepSaveDetail: 'Apply to the overlay', - previewEyebrow: 'Preview', - previewHeading: 'Frame your overlay precisely', - previewEmpty: 'Waiting for screenshots with end-of-run crops.', - sourceImage: 'Source image', - sourceHint: 'The highlighted frame is the selected area.', - resultImage: 'Overlay output', - resultHint: 'This is what viewers will see.', - noSample: 'No sample selected', - imageAlt: 'Selected end-of-run record image', - resultAlt: 'Live preview of the cropped overlay output', - controlsEyebrow: 'Controls', - controlsHeading: 'Fine-tune the crop', - positionGroup: 'Position', - sizeGroup: 'Size', - cropLeft: 'Horizontal start', - cropTop: 'Vertical start', - cropWidth: 'Width', - cropHeight: 'Height', - controlHint: - 'Tip: focus a slider and use the arrow keys for precise adjustments.', - saveButton: 'Save changes', - saveButtonBusy: 'Saving…', - resetButton: 'Undo changes', - copyButton: 'Copy code', - settingsCodeSummary: 'Advanced: configuration code', - settingsCodeHint: - 'Use this code to transfer the same crop to another setup.', - statusLoading: 'Loading the selected stream record...', - statusLoaded: - 'Sample ready. Adjust the controls and check the overlay output before saving.', - statusEmpty: - 'No end-of-run record is available in the current stream window yet. Finish a run, then refresh this page.', - statusUnsaved: 'You have unsaved crop changes.', - statusSaving: 'Saving crop changes…', - statusSaved: 'Crop saved. The overlay will use it on the next refresh.', - statusReverted: 'Unsaved changes reverted.', - statusCopied: 'Base64 settings code copied to clipboard.', - statusSaveFailed: 'Failed to save crop.', - statusCopyFailed: 'Failed to copy code.', - statusLoadFailed: 'Failed to load calibration data.', - unknownHero: 'Unknown hero', - battles: '{count} battles' - }, - zh: { - documentTitle: 'BazaarPlusPlus 叠加层校准', - eyebrow: '直播叠加层', - heading: '裁切校准', - pageIntro: '精确选择结算截图中要显示在直播叠加层里的区域。', - stepsLabel: '校准步骤', - stepAdjustTitle: '调整', - stepAdjustDetail: '框定目标区域', - stepPreviewTitle: '预览', - stepPreviewDetail: '确认直播画面', - stepSaveTitle: '保存', - stepSaveDetail: '应用到叠加层', - previewEyebrow: '预览', - previewHeading: '精准框定直播画面', - previewEmpty: '正在等待带有结算裁切的截图。', - sourceImage: '源图像', - sourceHint: '高亮边框内是当前选择的区域。', - resultImage: '叠加层输出', - resultHint: '观众最终会看到这个画面。', - noSample: '未选择样本', - imageAlt: '当前选中的结算记录图像', - resultAlt: '裁切后的直播叠加层实时预览', - controlsEyebrow: '控制', - controlsHeading: '微调裁切范围', - positionGroup: '位置', - sizeGroup: '尺寸', - cropLeft: '横向起点', - cropTop: '纵向起点', - cropWidth: '宽', - cropHeight: '高', - controlHint: '提示:聚焦滑杆后可用方向键进行精细调整。', - saveButton: '保存更改', - saveButtonBusy: '正在保存…', - resetButton: '撤销更改', - copyButton: '复制代码', - settingsCodeSummary: '高级:配置代码', - settingsCodeHint: '可使用此代码将同一套裁切配置迁移到其他环境。', - statusLoading: '正在读取当前展示的对局记录…', - statusLoaded: '样本已就绪。调整控制项并确认叠加层输出后保存。', - statusEmpty: '当前展示窗口内还没有结算记录。完成一局对局后刷新本页即可。', - statusUnsaved: '裁切范围有尚未保存的更改。', - statusSaving: '正在保存裁切更改…', - statusSaved: '裁切已保存,叠加层将在下次刷新时使用该配置。', - statusReverted: '已撤销尚未保存的更改。', - statusCopied: 'Base64 设置代码已复制到剪贴板。', - statusSaveFailed: '保存裁切失败。', - statusCopyFailed: '复制裁切代码失败。', - statusLoadFailed: '加载校准数据失败。', - unknownHero: '未知英雄', - battles: '{count} 场战斗' - } -}; - -const locale = resolveLocale(); -const strings = MESSAGES[locale]; - -function resolveLocale() { - const candidates = []; - try { - candidates.push(new URLSearchParams(window.location.search).get('lang')); - } catch { - // A malformed query string just falls through to the browser language. - } - candidates.push(...(navigator.languages || []), navigator.language); - - for (const candidate of candidates) { - if (typeof candidate !== 'string' || !candidate) continue; - const lower = candidate.toLowerCase(); - if (lower.startsWith('zh')) return 'zh'; - if (lower.startsWith('en')) return 'en'; - } - return 'en'; -} - -function t(key, params) { - const text = strings[key] ?? MESSAGES.en[key] ?? key; - if (!params) return text; - return Object.entries(params).reduce( - (result, [name, value]) => result.replaceAll(`{${name}}`, String(value)), - text - ); -} - -function applyStaticTranslations() { - document.documentElement.lang = locale === 'zh' ? 'zh-CN' : 'en'; - document.title = t('documentTitle'); - - document.querySelectorAll('[data-i18n]').forEach((node) => { - node.textContent = t(node.dataset.i18n); - }); - document.querySelectorAll('[data-i18n-alt]').forEach((node) => { - node.setAttribute('alt', t(node.dataset.i18nAlt)); - }); - document.querySelectorAll('[data-i18n-aria-label]').forEach((node) => { - node.setAttribute('aria-label', t(node.dataset.i18nAriaLabel)); - }); -} - -const pageStatus = document.getElementById('page-status'); -const pageStatusText = document.getElementById('page-status-text'); -const previewEmpty = document.getElementById('preview-empty'); -const previewWorkspace = document.getElementById('preview-workspace'); -const fullPreviewImage = document.getElementById('full-preview-image'); -const stripPreviewImage = document.getElementById('strip-preview-image'); -const selectedMeta = document.getElementById('selected-meta'); -const codeField = document.getElementById('settings-code'); -const saveButton = document.getElementById('save-button'); -const resetButton = document.getElementById('reset-button'); -const copyButton = document.getElementById('copy-button'); -const inputs = { - left: document.getElementById('crop-left'), - top: document.getElementById('crop-top'), - width: document.getElementById('crop-width'), - height: document.getElementById('crop-height') -}; -const outputs = { - left: document.getElementById('crop-left-value'), - top: document.getElementById('crop-top-value'), - width: document.getElementById('crop-width-value'), - height: document.getElementById('crop-height-value') -}; - -let selectedRecord = null; -let currentCrop = { ...DEFAULT_CROP }; -let savedCrop = { ...DEFAULT_CROP }; -let initialized = false; -let previewNonce = 0; -let previewTimer = null; -const requestedOffset = readRequestedOffset(); - -function setStatus(message, state = 'neutral') { - if (pageStatusText) { - pageStatusText.textContent = message; - } - if (pageStatus) { - pageStatus.dataset.state = state; - } -} - -// Request failures carry the raw response body, which can be a whole HTML error -// document. That belongs in the console, not in the page's status line. -function reportFailure(error, messageKey) { - console.error('[calibration]', error); - setStatus(t(messageKey), 'error'); -} - -function readRequestedOffset() { - try { - const params = new URLSearchParams(window.location.search); - const raw = Number(params.get('offset') || '0'); - if (!Number.isFinite(raw)) { - return 0; - } - return Math.max(0, Math.trunc(raw)); - } catch { - return 0; - } -} - -function setCropVariables(crop) { - const root = document.documentElement; - root.style.setProperty('--crop-left', `${crop.left * 100}%`); - root.style.setProperty('--crop-top', `${crop.top * 100}%`); - root.style.setProperty('--crop-width', `${crop.width * 100}%`); - root.style.setProperty('--crop-height', `${crop.height * 100}%`); -} - -function formatPercent(value) { - return `${(value * 100).toFixed(1)}%`; -} - -function cropsMatch(left, right) { - return Object.keys(DEFAULT_CROP).every( - (key) => Math.abs(left[key] - right[key]) < 0.0005 - ); -} - -function updateActionState() { - const dirty = initialized && !cropsMatch(currentCrop, savedCrop); - if (saveButton) { - saveButton.disabled = !dirty; - } - if (resetButton) { - resetButton.disabled = !dirty; - } -} - -function readCropFromInputs() { - return { - left: Number(inputs.left?.value || DEFAULT_CROP.left), - top: Number(inputs.top?.value || DEFAULT_CROP.top), - width: Number(inputs.width?.value || DEFAULT_CROP.width), - height: Number(inputs.height?.value || DEFAULT_CROP.height) - }; -} - -function writeCropToInputs(crop) { - Object.entries(crop).forEach(([key, value]) => { - const input = inputs[key]; - if (input) { - input.value = value.toFixed(3); - } - const output = outputs[key]; - if (output) { - output.value = formatPercent(value); - output.textContent = formatPercent(value); - } - if (input) { - input.setAttribute('aria-valuetext', formatPercent(value)); - } - }); -} - -function buildStripUrl(recordId, crop) { - const params = new URLSearchParams({ - left: crop.left.toFixed(3), - top: crop.top.toFixed(3), - width: crop.width.toFixed(3), - height: crop.height.toFixed(3), - preview: '1', - v: String(previewNonce) - }); - - return `/images/${encodeURIComponent(recordId)}/strip?${params.toString()}`; -} - -function encodeCropCode(crop) { - const payload = JSON.stringify({ v: 1, crop }); - const bytes = new TextEncoder().encode(payload); - let binary = ''; - bytes.forEach((byte) => { - binary += String.fromCharCode(byte); - }); - return window.btoa(binary); -} - -function updateCodeField(crop) { - if (!codeField) { - return; - } - - codeField.textContent = encodeCropCode(crop); -} - -function renderPreview() { - const crop = readCropFromInputs(); - currentCrop = crop; - previewNonce += 1; - writeCropToInputs(crop); - setCropVariables(crop); - - if (!selectedRecord?.id) { - if (previewEmpty) { - previewEmpty.hidden = false; - } - if (previewWorkspace) { - previewWorkspace.hidden = true; - } - return; - } - - if (previewEmpty) { - previewEmpty.hidden = true; - } - if (previewWorkspace) { - previewWorkspace.hidden = false; - } - if (fullPreviewImage) { - const nextSource = `/images/${encodeURIComponent(selectedRecord.id)}`; - if (fullPreviewImage.getAttribute('src') !== nextSource) { - fullPreviewImage.src = nextSource; - } - } - if (stripPreviewImage) { - stripPreviewImage.src = buildStripUrl(selectedRecord.id, crop); - } - if (selectedMeta) { - selectedMeta.textContent = [ - selectedRecord.title || t('unknownHero'), - typeof selectedRecord.wins === 'number' - ? `${selectedRecord.wins}W` - : null, - typeof selectedRecord.battle_count === 'number' - ? t('battles', { count: selectedRecord.battle_count }) - : null - ] - .filter(Boolean) - .join(' · '); - } -} - -async function loadCropSettings() { - const response = await fetch('/api/overlay/crop-config', { - cache: 'no-store' - }); - if (!response.ok) { - throw new Error(await response.text()); - } - - return response.json(); -} - -async function loadRecords() { - const endpoint = new URL( - '/api/stream/records/latest', - window.location.origin - ); - if (requestedOffset > 0) { - endpoint.searchParams.set('offset', String(requestedOffset)); - } - - const response = await fetch(endpoint, { cache: 'no-store' }); - if (!response.ok) { - throw new Error(await response.text()); - } - - const payload = await response.json(); - return payload?.id ? payload : null; -} - -async function saveCrop() { - const crop = readCropFromInputs(); - if (saveButton) { - saveButton.disabled = true; - saveButton.setAttribute('aria-busy', 'true'); - saveButton.textContent = t('saveButtonBusy'); - } - if (resetButton) { - resetButton.disabled = true; - } - setStatus(t('statusSaving'), 'loading'); - const response = await fetch('/api/overlay/crop-config', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ crop }) - }); - - if (!response.ok) { - throw new Error(await response.text()); - } - - const payload = await response.json(); - currentCrop = payload.crop; - savedCrop = { ...payload.crop }; - writeCropToInputs(payload.crop); - setCropVariables(payload.crop); - updateCodeField(payload.crop); - renderPreview(); - setStatus(t('statusSaved'), 'success'); - if (saveButton) { - saveButton.removeAttribute('aria-busy'); - saveButton.textContent = t('saveButton'); - } - updateActionState(); -} - -function resetCrop() { - currentCrop = { ...savedCrop }; - writeCropToInputs(currentCrop); - setCropVariables(currentCrop); - updateCodeField(currentCrop); - renderPreview(); - updateActionState(); - setStatus(t('statusReverted'), 'neutral'); -} - -async function copyCode() { - const code = codeField?.textContent?.trim() || ''; - if (!code) { - return; - } - - await navigator.clipboard.writeText(code); - setStatus(t('statusCopied')); -} - -function bindInputHandlers() { - Object.values(inputs).forEach((input) => { - input?.addEventListener('input', () => { - currentCrop = readCropFromInputs(); - writeCropToInputs(currentCrop); - setCropVariables(currentCrop); - updateCodeField(currentCrop); - updateActionState(); - if (initialized) { - setStatus(t('statusUnsaved'), 'pending'); - } - if (previewTimer) { - window.clearTimeout(previewTimer); - } - previewTimer = window.setTimeout(() => { - renderPreview(); - }, 120); - }); - }); - - saveButton?.addEventListener('click', async () => { - try { - await saveCrop(); - } catch (error) { - reportFailure(error, 'statusSaveFailed'); - if (saveButton) { - saveButton.removeAttribute('aria-busy'); - saveButton.textContent = t('saveButton'); - } - updateActionState(); - } - }); - - resetButton?.addEventListener('click', resetCrop); - - copyButton?.addEventListener('click', async () => { - try { - await copyCode(); - } catch (error) { - reportFailure(error, 'statusCopyFailed'); - } - }); -} - -async function initialize() { - try { - applyStaticTranslations(); - bindInputHandlers(); - const [settingsPayload, latestRecord] = await Promise.all([ - loadCropSettings(), - loadRecords() - ]); - - currentCrop = settingsPayload?.crop || { ...DEFAULT_CROP }; - savedCrop = { ...currentCrop }; - writeCropToInputs(currentCrop); - setCropVariables(currentCrop); - updateCodeField(currentCrop); - - selectedRecord = latestRecord; - renderPreview(); - - initialized = true; - updateActionState(); - - setStatus( - t(selectedRecord ? 'statusLoaded' : 'statusEmpty'), - selectedRecord ? 'ready' : 'neutral' - ); - } catch (error) { - reportFailure(error, 'statusLoadFailed'); - } -} - -void initialize(); diff --git a/bazaarplusplus-installer/src-tauri/resources/stream/settings.test.js b/bazaarplusplus-installer/src-tauri/resources/stream/settings.test.js deleted file mode 100644 index 31204d0..0000000 --- a/bazaarplusplus-installer/src-tauri/resources/stream/settings.test.js +++ /dev/null @@ -1,121 +0,0 @@ -// @vitest-environment jsdom - -import { readFile } from 'node:fs/promises'; -import { resolve } from 'node:path'; -import { describe, expect, test, vi } from 'vitest'; - -const DEFAULT_CROP = { - left: 0.342, - top: 0.313, - width: 0.58, - height: 0.22 -}; - -describe('overlay calibration page', () => { - test('previews, reverts, and saves crop changes', async () => { - const html = await readFile( - resolve(process.cwd(), 'src-tauri/resources/stream/settings.html'), - 'utf8' - ); - document.open(); - document.write(html); - document.close(); - window.history.replaceState({}, '', '/settings?lang=en'); - - const requests = []; - vi.stubGlobal( - 'fetch', - vi.fn(async (input, init = {}) => { - const url = String(input); - requests.push({ url, init }); - - if ( - url.includes('/api/overlay/crop-config') && - init.method === 'POST' - ) { - return okJson(JSON.parse(init.body)); - } - if (url.includes('/api/overlay/crop-config')) { - return okJson({ crop: DEFAULT_CROP }); - } - if (url.includes('/api/stream/records/latest')) { - return okJson({ - id: 'record-1', - title: 'Mak', - wins: 7, - battle_count: 12 - }); - } - - throw new Error(`Unexpected request: ${url}`); - }) - ); - - await import('./settings.js'); - - await vi.waitFor(() => { - expect(document.getElementById('page-status-text').textContent).toBe( - 'Sample ready. Adjust the controls and check the overlay output before saving.' - ); - }); - - const left = document.getElementById('crop-left'); - const leftOutput = document.getElementById('crop-left-value'); - const stripPreview = document.getElementById('strip-preview-image'); - const save = document.getElementById('save-button'); - const reset = document.getElementById('reset-button'); - - expect(leftOutput.textContent).toBe('34.2%'); - expect(stripPreview.getAttribute('src')).toContain('left=0.342'); - expect(save.disabled).toBe(true); - expect(reset.disabled).toBe(true); - - left.value = '0.350'; - left.dispatchEvent(new Event('input', { bubbles: true })); - - expect(leftOutput.textContent).toBe('35.0%'); - expect(document.getElementById('page-status-text').textContent).toBe( - 'You have unsaved crop changes.' - ); - expect(save.disabled).toBe(false); - expect(reset.disabled).toBe(false); - - await vi.waitFor(() => { - expect(stripPreview.getAttribute('src')).toContain('left=0.350'); - }); - - reset.click(); - - expect(leftOutput.textContent).toBe('34.2%'); - expect(document.getElementById('page-status-text').textContent).toBe( - 'Unsaved changes reverted.' - ); - expect(save.disabled).toBe(true); - expect(reset.disabled).toBe(true); - - left.value = '0.350'; - left.dispatchEvent(new Event('input', { bubbles: true })); - save.click(); - - await vi.waitFor(() => { - expect(document.getElementById('page-status-text').textContent).toBe( - 'Crop saved. The overlay will use it on the next refresh.' - ); - }); - - const saveRequest = requests.find(({ init }) => init.method === 'POST'); - expect(JSON.parse(saveRequest.init.body)).toEqual({ - crop: { ...DEFAULT_CROP, left: 0.35 } - }); - expect(save.disabled).toBe(true); - expect(reset.disabled).toBe(true); - }); -}); - -function okJson(payload) { - return { - ok: true, - json: async () => payload, - text: async () => JSON.stringify(payload) - }; -} diff --git a/bazaarplusplus-installer/src-tauri/src/commands/app.rs b/bazaarplusplus-installer/src-tauri/src/commands/app.rs deleted file mode 100644 index 9758c14..0000000 --- a/bazaarplusplus-installer/src-tauri/src/commands/app.rs +++ /dev/null @@ -1,69 +0,0 @@ -use serde::{Deserialize, Serialize}; -use tauri::AppHandle; - -use crate::services::startup::InstallerContextState; - -#[derive(Debug, Deserialize)] -struct AppBootstrapStatic { - links: AppLinks, - credits: Vec, - licenses: Vec, -} - -fn load_static_bootstrap() -> AppBootstrapStatic { - const RAW: &str = include_str!("../../resources/app-bootstrap.json"); - serde_json::from_str(RAW).expect("app-bootstrap.json must parse") -} - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct AppBootstrap { - pub app_version: String, - pub bundled_bpp_version: Option, - pub links: AppLinks, - pub credits: Vec, - pub licenses: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)] -pub struct AppLinks { - pub github: String, - pub x: String, - pub bilibili_project: String, - pub bilibili_author: String, - pub bilibili_core_dev: String, - pub xiaohongshu: String, - pub kofi: String, - pub supporter_list: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)] -pub struct AppCredit { - pub name: String, - pub role: String, - pub href: Option, - pub group: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)] -pub struct AppLicense { - pub name: String, - pub license: String, - pub category: String, -} - -#[tauri::command(async)] -#[specta::specta] -pub fn get_app_bootstrap( - app: AppHandle, - state: tauri::State<'_, InstallerContextState>, -) -> AppBootstrap { - let startup = state.get_or_initialize(&app); - let static_content = load_static_bootstrap(); - AppBootstrap { - app_version: env!("CARGO_PKG_VERSION").to_string(), - bundled_bpp_version: startup.bundled_bpp_version.clone(), - links: static_content.links, - credits: static_content.credits, - licenses: static_content.licenses, - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/commands/game.rs b/bazaarplusplus-installer/src-tauri/src/commands/game.rs deleted file mode 100644 index eea67eb..0000000 --- a/bazaarplusplus-installer/src-tauri/src/commands/game.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::services::game_process; - -/// End a game process that outlived its window. Both History and Install stall -/// on that state — one cannot read the mod database, the other refuses to touch -/// installed files — so the recovery lives outside either page. -/// -/// Returns whether a process was actually terminated: finding none means the -/// state the caller was recovering from is already gone. -#[tauri::command(async)] -#[specta::specta] -pub fn end_game_process() -> Result { - game_process::terminate_game() -} diff --git a/bazaarplusplus-installer/src-tauri/src/commands/history.rs b/bazaarplusplus-installer/src-tauri/src/commands/history.rs deleted file mode 100644 index f3ca314..0000000 --- a/bazaarplusplus-installer/src-tauri/src/commands/history.rs +++ /dev/null @@ -1,70 +0,0 @@ -use crate::problem::SemanticProblem; -use crate::services::history::{ - self, HistoryRunDetail, HistoryRunList, StorageCleanupExecution, StorageCleanupPreset, - StorageCleanupPreview, StorageCleanupScope, -}; - -#[tauri::command(async)] -#[specta::specta] -pub fn list_history_runs( - app: tauri::AppHandle, - limit: usize, - offset: usize, -) -> Result { - history::list_runs(&app, limit, offset) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn get_history_run_detail( - app: tauri::AppHandle, - run_id: String, -) -> Result, SemanticProblem> { - history::get_run_detail(&app, &run_id) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn reveal_run_screenshot(app: tauri::AppHandle, run_id: String) -> Result<(), SemanticProblem> { - history::reveal_run_screenshot(&app, &run_id) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn reveal_battle_video( - app: tauri::AppHandle, - battle_id: String, - video_id: String, -) -> Result<(), SemanticProblem> { - history::reveal_battle_video(&app, &battle_id, &video_id) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn delete_battle_video( - app: tauri::AppHandle, - battle_id: String, - video_id: String, -) -> Result { - history::delete_battle_video(&app, &battle_id, &video_id) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn preview_storage_cleanup( - app: tauri::AppHandle, - scope: StorageCleanupScope, - preset: StorageCleanupPreset, -) -> Result { - history::preview_storage_cleanup(&app, scope, preset) -} - -#[tauri::command] -#[specta::specta] -pub async fn execute_storage_cleanup( - app: tauri::AppHandle, - scope: StorageCleanupScope, - preset: StorageCleanupPreset, -) -> Result { - history::execute_storage_cleanup(&app, scope, preset).await -} diff --git a/bazaarplusplus-installer/src-tauri/src/commands/install.rs b/bazaarplusplus-installer/src-tauri/src/commands/install.rs deleted file mode 100644 index 7f13d1e..0000000 --- a/bazaarplusplus-installer/src-tauri/src/commands/install.rs +++ /dev/null @@ -1,132 +0,0 @@ -pub use crate::services::install::*; - -use std::path::PathBuf; - -use tauri::Manager; -use tauri_plugin_dialog::DialogExt; - -use crate::problem::SemanticProblem; -use crate::services::{ - data_maintenance::DataMaintenanceLock, - install::{ - build_install_state, install, launch_game_via_steam, run_delete_legacy_root, - run_get_legacy_data_state, run_reset_bepinex, run_reset_bpp_data, run_uninstall, - InstallRequest, - }, - legacy_data::{DeleteLegacyRootResult, LegacyDataState}, - startup::InstallerContextState, -}; -use crate::stream::runtime::StreamRuntime; -use crate::v5_import::ImportV5HistoryResult; - -#[tauri::command(async)] -#[specta::specta] -pub fn get_install_state( - app: tauri::AppHandle, - state: tauri::State<'_, InstallerContextState>, - game_path: Option, -) -> Result { - build_install_state(app, state, game_path) -} - -#[tauri::command] -#[specta::specta] -pub async fn choose_game_directory( - app: tauri::AppHandle, -) -> Result { - let folder = - tauri::async_runtime::spawn_blocking(move || app.dialog().file().blocking_pick_folder()) - .await - .map_err(|err| format!("failed to open game directory picker: {err}")) - .map_err(|diagnostic| { - crate::services::install::install_action_problem("choose_directory", diagnostic) - })?; - let game_path = folder - .and_then(|path| path.into_path().ok()) - .map(|path| path.to_string_lossy().into_owned()); - - Ok(GameDirectorySelection { game_path }) -} - -#[tauri::command] -#[specta::specta] -pub async fn install_mod( - app: tauri::AppHandle, - game_path: String, -) -> Result { - install(app, InstallRequest { game_path }).await -} - -#[tauri::command] -#[specta::specta] -pub async fn reset_bpp_data( - app: tauri::AppHandle, - install_state: tauri::State<'_, InstallerContextState>, - stream_runtime: tauri::State<'_, StreamRuntime>, - game_path: String, -) -> Result { - run_reset_bpp_data(app, install_state, stream_runtime, game_path).await -} - -#[tauri::command] -#[specta::specta] -pub async fn reset_bepinex( - app: tauri::AppHandle, - install_state: tauri::State<'_, InstallerContextState>, - game_path: String, -) -> Result { - run_reset_bepinex(app, install_state, game_path).await -} - -#[tauri::command] -#[specta::specta] -pub async fn get_legacy_data_state( - app: tauri::AppHandle, - game_path: Option, -) -> Result { - run_get_legacy_data_state(app, game_path).await -} - -/// Imports `BazaarPlusPlusV5/` history into the current Data Root once -/// (ADR-0008) and returns the remeasured Legacy Roots. It never deletes V5. -#[tauri::command] -#[specta::specta] -pub async fn import_v5_history( - app: tauri::AppHandle, - stream_runtime: tauri::State<'_, StreamRuntime>, - game_path: String, -) -> Result { - let maintenance = app.state::().inner().clone(); - crate::v5_import::import_v5_history(&maintenance, &stream_runtime, PathBuf::from(game_path)) - .await -} - -/// Deletes one Legacy Root the user confirmed. `name` must be one of the -/// directory names `get_legacy_data_state` lists. -#[tauri::command] -#[specta::specta] -pub async fn delete_legacy_root( - app: tauri::AppHandle, - game_path: String, - name: String, -) -> Result { - run_delete_legacy_root(app, game_path, name).await -} - -#[tauri::command] -#[specta::specta] -pub async fn uninstall_mod( - app: tauri::AppHandle, - state: tauri::State<'_, InstallerContextState>, - game_path: String, -) -> Result { - run_uninstall(app, state, game_path).await -} - -#[tauri::command(async)] -#[specta::specta] -pub fn launch_game() -> Result<(), SemanticProblem> { - launch_game_via_steam().map_err(|diagnostic| { - crate::services::install::install_action_problem("launch", diagnostic) - }) -} diff --git a/bazaarplusplus-installer/src-tauri/src/commands/mod.rs b/bazaarplusplus-installer/src-tauri/src/commands/mod.rs deleted file mode 100644 index 4997b37..0000000 --- a/bazaarplusplus-installer/src-tauri/src/commands/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub mod app; -pub mod game; -pub mod history; -pub mod install; -pub mod registry; -pub mod stream; diff --git a/bazaarplusplus-installer/src-tauri/src/commands/registry.rs b/bazaarplusplus-installer/src-tauri/src/commands/registry.rs deleted file mode 100644 index 2ef94fe..0000000 --- a/bazaarplusplus-installer/src-tauri/src/commands/registry.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! Canonical Tauri IPC registration and TypeScript export. - -use tauri_specta::{collect_commands, Builder, ErrorHandlingMode}; - -pub fn builder() -> Builder { - Builder::::new() - .error_handling(ErrorHandlingMode::Throw) - .dangerously_cast_bigints_to_number() - .commands(collect_commands![ - crate::commands::app::get_app_bootstrap, - crate::tray::set_app_locale, - crate::commands::install::get_install_state, - crate::commands::install::choose_game_directory, - crate::commands::install::install_mod, - crate::commands::install::reset_bpp_data, - crate::commands::install::reset_bepinex, - crate::commands::install::get_legacy_data_state, - crate::commands::install::import_v5_history, - crate::commands::install::delete_legacy_root, - crate::commands::install::uninstall_mod, - crate::commands::install::launch_game, - crate::commands::game::end_game_process, - crate::commands::stream::get_stream_status, - crate::commands::stream::ensure_stream_session, - crate::commands::stream::prepare_history_thumbnails, - crate::commands::stream::restart_stream_session, - crate::commands::stream::set_stream_window, - crate::commands::stream::get_overlay_settings, - crate::commands::stream::save_overlay_display_mode, - crate::commands::stream::apply_overlay_crop_code, - crate::commands::stream::reset_overlay_crop, - crate::commands::history::list_history_runs, - crate::commands::history::get_history_run_detail, - crate::commands::history::reveal_run_screenshot, - crate::commands::history::reveal_battle_video, - crate::commands::history::delete_battle_video, - crate::commands::history::preview_storage_cleanup, - crate::commands::history::execute_storage_cleanup, - ]) -} - -#[cfg(test)] -mod tests { - #[test] - fn export_bindings() { - let Ok(path) = std::env::var("BPP_SPECTA_EXPORT_PATH") else { - return; - }; - - super::builder() - .export(specta_typescript::Typescript::default(), &path) - .unwrap_or_else(|error| panic!("export TypeScript bindings to {path}: {error}")); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/commands/stream.rs b/bazaarplusplus-installer/src-tauri/src/commands/stream.rs deleted file mode 100644 index 1996031..0000000 --- a/bazaarplusplus-installer/src-tauri/src/commands/stream.rs +++ /dev/null @@ -1,176 +0,0 @@ -use crate::problem::{SemanticProblem, SemanticProblemCode}; -use crate::stream::{ - overlay_settings::{ - OverlayCropSettings, OverlayCropSettingsPayload, OverlaySettingsStore, - StreamOverlayDisplayMode, - }, - runtime::StreamRuntime, - state::StreamServiceStatus, -}; - -#[tauri::command] -#[specta::specta] -pub fn get_stream_status( - runtime: tauri::State<'_, StreamRuntime>, -) -> Result { - Ok(runtime.snapshot()) -} - -#[tauri::command] -#[specta::specta] -pub async fn ensure_stream_session( - app: tauri::AppHandle, - runtime: tauri::State<'_, StreamRuntime>, -) -> Result { - runtime - .ensure(app) - .await - .map_err(|diagnostic| stream_service_problem("ensure", diagnostic)) -} - -#[tauri::command] -#[specta::specta] -pub async fn prepare_history_thumbnails( - app: tauri::AppHandle, - runtime: tauri::State<'_, StreamRuntime>, -) -> Result<(), SemanticProblem> { - runtime - .prepare_history_thumbnails(app) - .await - .map_err(history_thumbnails_problem) -} - -#[tauri::command] -#[specta::specta] -pub async fn restart_stream_session( - app: tauri::AppHandle, - runtime: tauri::State<'_, StreamRuntime>, -) -> Result { - runtime - .restart(app) - .await - .map_err(|diagnostic| stream_service_problem("restart", diagnostic)) -} - -#[tauri::command] -#[specta::specta] -pub async fn set_stream_window( - runtime: tauri::State<'_, StreamRuntime>, - offset: usize, -) -> Result { - runtime - .set_window(offset) - .await - .map_err(|diagnostic| stream_window_problem(offset, diagnostic)) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn get_overlay_settings() -> Result { - OverlaySettingsStore::default() - .load_payload() - .map_err(|diagnostic| stream_crop_problem("load", diagnostic)) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn apply_overlay_crop_code( - code: String, -) -> Result { - OverlaySettingsStore::default() - .import_code(&code) - .map_err(|diagnostic| stream_crop_problem("apply_code", diagnostic)) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn save_overlay_display_mode( - display_mode: StreamOverlayDisplayMode, -) -> Result { - OverlaySettingsStore::default() - .save_display_mode(display_mode) - .map_err(|diagnostic| stream_crop_problem("save_display_mode", diagnostic)) -} - -#[tauri::command(async)] -#[specta::specta] -pub fn reset_overlay_crop() -> Result { - OverlaySettingsStore::default() - .save(OverlayCropSettings::default()) - .map_err(|diagnostic| stream_crop_problem("reset", diagnostic)) -} - -fn stream_service_problem(operation: &str, diagnostic: String) -> SemanticProblem { - SemanticProblem::new(SemanticProblemCode::StreamServiceFailed) - .with_param("operation", operation) - .with_diagnostic(diagnostic) -} - -/// The only failure of History Thumbnail preparation is a service start -/// failure; History names it on its own while the Stream status keeps the error. -fn history_thumbnails_problem(diagnostic: String) -> SemanticProblem { - SemanticProblem::new(SemanticProblemCode::HistoryThumbnailsUnavailable) - .with_param("operation", "prepare_history_thumbnails") - .with_diagnostic(diagnostic) -} - -fn stream_window_problem(offset: usize, diagnostic: String) -> SemanticProblem { - SemanticProblem::new(SemanticProblemCode::StreamWindowFailed) - .with_param("operation", "set_window") - .with_param("offset", offset.to_string()) - .with_diagnostic(diagnostic) -} - -fn stream_crop_problem(operation: &str, diagnostic: String) -> SemanticProblem { - SemanticProblem::new(SemanticProblemCode::StreamCropFailed) - .with_param("operation", operation) - .with_diagnostic(diagnostic) -} - -#[cfg(test)] -mod tests { - use super::{ - history_thumbnails_problem, stream_crop_problem, stream_service_problem, - stream_window_problem, - }; - use crate::problem::SemanticProblemCode; - - #[test] - fn history_thumbnail_start_failure_is_its_own_problem_with_the_bind_diagnostic() { - let problem = history_thumbnails_problem("address already in use".to_string()); - assert_eq!( - problem.code, - SemanticProblemCode::HistoryThumbnailsUnavailable - ); - assert_eq!( - problem.params.get("operation").map(String::as_str), - Some("prepare_history_thumbnails") - ); - assert_eq!( - problem.diagnostic.as_deref(), - Some("address already in use") - ); - } - - #[test] - fn stream_command_failures_keep_capability_operation_and_diagnostic() { - let service = stream_service_problem("restart", "port occupied".to_string()); - assert_eq!(service.code, SemanticProblemCode::StreamServiceFailed); - assert_eq!( - service.params.get("operation").map(String::as_str), - Some("restart") - ); - assert_eq!(service.diagnostic.as_deref(), Some("port occupied")); - - let window = stream_window_problem(3, "record missing".to_string()); - assert_eq!(window.code, SemanticProblemCode::StreamWindowFailed); - assert_eq!(window.params.get("offset").map(String::as_str), Some("3")); - - let crop = stream_crop_problem("apply_code", "invalid code".to_string()); - assert_eq!(crop.code, SemanticProblemCode::StreamCropFailed); - assert_eq!( - crop.params.get("operation").map(String::as_str), - Some("apply_code") - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/config.rs b/bazaarplusplus-installer/src-tauri/src/config.rs deleted file mode 100644 index 08cb5ed..0000000 --- a/bazaarplusplus-installer/src-tauri/src/config.rs +++ /dev/null @@ -1,84 +0,0 @@ -use std::sync::OnceLock; - -/// The Data Root the mod writes under the game directory. The mod owns the name -/// (`PathConstants.DataRootDirectoryName`); `history-database-compatibility.json` -/// restates it as `dataRootDirectoryName`, which `just release::check` compares -/// against the mod's contract and a test here compares against this constant. -pub const BAZAAR_DATA_DIRECTORY: &str = "BazaarPlusPlusV6"; -pub const INSTALLER_STATE_DIRECTORY: &str = "BazaarPlusPlusInstaller"; -pub const COMBAT_REPLAYS_DIRECTORY: &str = "CombatReplays"; -pub const COMBAT_REPLAY_VIDEOS_DIRECTORY: &str = "CombatReplayVideos"; -pub const DATABASE_FILE_NAME: &str = "bazaarplusplus.db"; -pub const SCREENSHOTS_DIRECTORY: &str = "Screenshots"; - -#[derive(serde::Deserialize)] -#[serde(rename_all = "camelCase")] -struct HistoryDatabaseCompatibility { - format_version: u32, - supported_user_versions: Vec, -} - -pub fn supported_mod_db_user_versions() -> &'static [i64] { - static COMPATIBILITY: OnceLock = OnceLock::new(); - let compatibility = COMPATIBILITY.get_or_init(|| { - let compatibility: HistoryDatabaseCompatibility = - serde_json::from_str(include_str!("../history-database-compatibility.json")) - .expect("history database compatibility must be valid JSON"); - assert_eq!( - compatibility.format_version, 1, - "history database compatibility format must be supported" - ); - assert!( - !compatibility.supported_user_versions.is_empty() - && compatibility - .supported_user_versions - .windows(2) - .all(|versions| versions[0] > 0 && versions[0] < versions[1]) - && compatibility - .supported_user_versions - .last() - .is_some_and(|version| *version > 0), - "history database compatibility versions must be positive, sorted, and unique" - ); - compatibility - }); - &compatibility.supported_user_versions -} - -/// The supported versions, comma-separated, as unsupported-schema diagnostics print them. -pub fn supported_mod_db_user_versions_label() -> String { - supported_mod_db_user_versions() - .iter() - .map(i64::to_string) - .collect::>() - .join(",") -} - -#[cfg(target_os = "windows")] -pub const STEAM_LIBRARY_FALLBACK_CANDIDATES: &[&str] = &[ - r"C:\Program Files (x86)\Steam\steamapps\common\The Bazaar", - r"C:\Program Files\Steam\steamapps\common\The Bazaar", - r"D:\Steam\steamapps\common\The Bazaar", - r"D:\SteamLibrary\steamapps\common\The Bazaar", - r"E:\Steam\steamapps\common\The Bazaar", - r"E:\SteamLibrary\steamapps\common\The Bazaar", -]; - -#[cfg_attr(not(target_os = "windows"), allow(dead_code))] -#[cfg(not(target_os = "windows"))] -pub const STEAM_LIBRARY_FALLBACK_CANDIDATES: &[&str] = &[]; - -#[cfg(test)] -mod tests { - #[test] - fn compatibility_contract_names_the_data_root_the_installer_reads() { - let compatibility: serde_json::Value = - serde_json::from_str(include_str!("../history-database-compatibility.json")) - .expect("history database compatibility must be valid JSON"); - assert_eq!( - compatibility["dataRootDirectoryName"].as_str(), - Some(super::BAZAAR_DATA_DIRECTORY), - "history-database-compatibility.json dataRootDirectoryName must equal BAZAAR_DATA_DIRECTORY" - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/goldens.rs b/bazaarplusplus-installer/src-tauri/src/goldens.rs deleted file mode 100644 index cbdfbe4..0000000 --- a/bazaarplusplus-installer/src-tauri/src/goldens.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! Golden files committed under `tests/goldens/`. A test renders its output to -//! text and compares it with the committed file byte for byte; with -//! `BPP_UPDATE_GOLDENS=1` it rewrites the file instead, and the diff is -//! reviewed in the pull request. - -use std::path::{Path, PathBuf}; - -use serde::Serialize; - -pub(crate) fn golden_path(relative: &str) -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests/goldens") - .join(relative) -} - -pub(crate) fn assert_golden(relative: &str, actual: &str) { - let path = golden_path(relative); - if std::env::var("BPP_UPDATE_GOLDENS").as_deref() == Ok("1") { - std::fs::create_dir_all(path.parent().expect("golden has a directory")).unwrap(); - std::fs::write(&path, actual).unwrap(); - return; - } - let expected = std::fs::read_to_string(&path).unwrap_or_else(|error| { - panic!( - "read golden {}: {error}; regenerate with BPP_UPDATE_GOLDENS=1", - path.display() - ) - }); - assert!( - expected == actual, - "golden {} differs; review and regenerate with BPP_UPDATE_GOLDENS=1\n--- expected\n{expected}\n--- actual\n{actual}", - path.display() - ); -} - -/// Pretty JSON with every fixture root replaced by its placeholder, in both the -/// raw and the JSON-escaped spelling (Windows paths contain `\`). -pub(crate) fn json(value: &impl Serialize, roots: &[(&Path, &str)]) -> String { - let mut text = serde_json::to_string_pretty(value).unwrap(); - for (root, placeholder) in roots { - let raw = root.to_string_lossy(); - let escaped = serde_json::to_string(raw.as_ref()).unwrap(); - text = text - .replace(&escaped[1..escaped.len() - 1], placeholder) - .replace(raw.as_ref(), placeholder); - } - text.push('\n'); - text -} - -/// Every file and symlink under `root`, `/`-separated relative paths in -/// order, each with the sha256 of its bytes (`symlink:` for a link). -#[cfg(target_os = "macos")] -pub(crate) fn tree_manifest(root: &Path) -> Vec<(String, String)> { - crate::services::file_manifest::tree_manifest(root).unwrap() -} - -/// Writes one run's full `(path, sha256)` list to -/// `target/acceptance/.manifest.json`. It is not committed: signatures -/// and copied game files differ between machines, so it is for diffing two runs -/// against the same inputs. -#[cfg(target_os = "macos")] -pub(crate) fn write_run_manifest(name: &str, entries: &[(String, String)]) { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("target/acceptance") - .join(format!("{name}.manifest.json")); - std::fs::create_dir_all(path.parent().expect("manifest has a directory")).unwrap(); - let entries: Vec<_> = entries - .iter() - .map(|(path, sha256)| serde_json::json!({ "path": path, "sha256": sha256 })) - .collect(); - std::fs::write(&path, json(&entries, &[])).unwrap(); - eprintln!("Wrote the run manifest to {}", path.display()); -} diff --git a/bazaarplusplus-installer/src-tauri/src/headless.rs b/bazaarplusplus-installer/src-tauri/src/headless.rs deleted file mode 100644 index e48bd4e..0000000 --- a/bazaarplusplus-installer/src-tauri/src/headless.rs +++ /dev/null @@ -1,160 +0,0 @@ -//! Process entry for developer commands; never initializes a Tauri application. - -use std::ffi::OsString; -use std::io::Write; -use std::path::{Path, PathBuf}; - -const HELP: &str = "Usage:\n bppinstaller repair --game [--stub ] [--manifest ]\n bppinstaller import --game --manifest [--now ]\n\nrepair: Repair the macOS launch trampoline of an existing BepInEx installation.\nKeeps the installed Payload and user data. With --manifest, writes a sorted\npath/sha256 manifest outside the game directory. Packaged apps use their bundled\nstub; source checkouts must supply --stub.\n\nimport: Import BazaarPlusPlusV5 history into the current Data Root once, as the\napp does. Writes the outcome, the Data Root's path/sha256 records, and its\ndatabase rows as JSON to --manifest, outside the game directory, and exits 1\nwhen the import failed. --now fixes the clock for the replay retention window.\n\nWithout arguments, starts the desktop app."; - -pub fn run(arguments: impl IntoIterator) -> Option { - let mut args = arguments.into_iter(); - let command = args.next()?; - if command == "--help" || command == "-h" { - println!("{HELP}"); - return Some(0); - } - let result = if command == "repair" { - repair(args) - } else if command == "import" { - import(args) - } else { - Err(format!( - "Unknown command: {}\n{HELP}", - command.to_string_lossy() - )) - }; - Some(match result { - Ok(()) => 0, - Err(error) => { - eprintln!("{error}"); - 1 - } - }) -} - -/// Reads `--name value` pairs; each name may appear once. -fn options( - command: &str, - names: [&str; N], - mut args: impl Iterator, -) -> Result<[Option; N], String> { - let mut values: [Option; N] = std::array::from_fn(|_| None); - while let Some(option) = args.next() { - let Some(index) = names.iter().position(|name| option == *name) else { - return Err(format!( - "Unknown {command} option: {}", - option.to_string_lossy() - )); - }; - if values[index].is_some() { - return Err(format!("Duplicate option: {}", option.to_string_lossy())); - } - values[index] = Some( - args.next() - .ok_or_else(|| format!("Missing value for {}", option.to_string_lossy()))?, - ); - } - Ok(values) -} - -fn canonical_game(game: Option, command: &str) -> Result { - PathBuf::from(game.ok_or_else(|| format!("{command} requires --game "))?) - .canonicalize() - .map_err(|error| format!("Cannot open game directory: {error}")) -} - -/// A temporary file beside the manifest destination, published over it once -/// written. The destination must lie outside the game directory and must not -/// be a symbolic link or anything else but a regular file. -fn stage_manifest( - path: PathBuf, - game: &Path, -) -> Result<(tempfile::NamedTempFile, PathBuf), String> { - let parent = path - .parent() - .filter(|parent| !parent.as_os_str().is_empty()) - .unwrap_or(Path::new(".")); - let parent = parent - .canonicalize() - .map_err(|error| format!("Cannot open manifest directory: {error}"))?; - if parent.starts_with(game) { - return Err("Write the manifest outside the game directory".into()); - } - match std::fs::symlink_metadata(&path) { - Ok(metadata) if !metadata.file_type().is_file() => { - return Err("Manifest destination must be a regular file".into()); - } - Err(error) if error.kind() != std::io::ErrorKind::NotFound => { - return Err(format!("Cannot inspect manifest destination: {error}")); - } - _ => {} - } - let file = tempfile::NamedTempFile::new_in(parent) - .map_err(|error| format!("Cannot stage manifest: {error}"))?; - Ok((file, path)) -} - -fn publish_manifest( - (mut file, path): (tempfile::NamedTempFile, PathBuf), - output: &str, -) -> Result<(), String> { - file.write_all(output.as_bytes()) - .map_err(|error| format!("Cannot write manifest: {error}"))?; - file.persist(path) - .map_err(|error| format!("Cannot publish manifest: {error}"))?; - Ok(()) -} - -fn repair(args: impl Iterator) -> Result<(), String> { - let [game, stub, manifest] = options("repair", ["--game", "--stub", "--manifest"], args)?; - let game = canonical_game(game, "repair")?; - let stub = match stub { - Some(path) => PathBuf::from(path), - None => std::env::current_exe() - .map_err(|error| error.to_string())? - .parent() - .ok_or("Cannot locate installer executable directory")? - .join("../Resources/Trampoline/bpp_launcher"), - }; - let manifest = manifest - .map(|path| stage_manifest(PathBuf::from(path), &game)) - .transpose()?; - crate::services::bepinex::repair_deployed_game(&game, &stub)?; - match manifest { - Some(staged) => { - let entries = crate::services::file_manifest::tree_manifest(&game)?; - publish_manifest(staged, &crate::services::file_manifest::json(&entries)?) - } - None => { - println!("Repaired {}", game.display()); - Ok(()) - } - } -} - -fn import(args: impl Iterator) -> Result<(), String> { - let [game, manifest, now] = options("import", ["--game", "--manifest", "--now"], args)?; - let game = canonical_game(game, "import")?; - let manifest = manifest.ok_or("import requires --manifest ")?; - let now_ms = match now { - Some(text) => chrono::DateTime::parse_from_rfc3339(&text.to_string_lossy()) - .map_err(|error| format!("--now is not an RFC 3339 time: {error}"))? - .timestamp_millis(), - None => chrono::Utc::now().timestamp_millis(), - }; - let staged = stage_manifest(PathBuf::from(manifest), &game)?; - let outcome = tauri::async_runtime::block_on(crate::v5_import::import_v5( - &crate::services::data_maintenance::DataMaintenanceLock::default(), - &crate::stream::runtime::StreamRuntime::default(), - game.clone(), - now_ms, - )); - publish_manifest( - staged, - &crate::v5_import::manifest::manifest_json(&game, &outcome)?, - )?; - match outcome { - Ok(_) | Err(crate::v5_import::ImportError::AlreadyImported) => Ok(()), - Err(error) => Err(format!("Import failed ({}): {error}", error.code())), - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/cleanup.rs b/bazaarplusplus-installer/src-tauri/src/history/cleanup.rs deleted file mode 100644 index f5931b4..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/cleanup.rs +++ /dev/null @@ -1,3565 +0,0 @@ -use chrono::{DateTime, Datelike, Duration, NaiveDate, TimeZone, Utc}; -use rusqlite::{params, Connection}; -use std::collections::HashSet; -use std::path::{Path, PathBuf}; -use std::sync::LazyLock; - -use crate::history::files::{resolve_cleanup_file_path, resolve_data_file_path}; -use crate::history::queries::{open_cleanup_connection, open_connection}; -use crate::services::game_process::{GameProcessProbe, SystemGameProcessProbe}; - -/// Wire strings are a stable contract with the frontend preset buttons. -#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)] -pub enum StorageCleanupPreset { - #[serde(rename = "all")] - All, - #[serde(rename = "older_than_7_days")] - OlderThan7Days, - #[serde(rename = "before_this_month")] - BeforeThisMonth, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct CleanupCutoff { - /// The cutoff instant; SQL compares it with the mod's `*_at_ms` columns. - pub utc: DateTime, - /// Local calendar date of the cutoff; used for dated-folder orphan sweeps - /// (folder names come from the local capture date). - pub local_date: NaiveDate, -} - -impl CleanupCutoff { - pub fn for_preset( - preset: StorageCleanupPreset, - now: DateTime, - ) -> Option { - let instant = match preset { - StorageCleanupPreset::All => return None, - StorageCleanupPreset::OlderThan7Days => now.clone() - Duration::days(7), - StorageCleanupPreset::BeforeThisMonth => { - let first_of_month = now - .date_naive() - .with_day(1) - .expect("day 1 is always a valid day"); - let month_start = first_of_month - .and_hms_opt(0, 0, 0) - .expect("midnight is always a valid time"); - // A spring-forward DST gap can make local midnight on the 1st - // not exist, so `earliest()` returns None. That must NOT collapse - // to `None` here — `None` is the wire meaning of preset `All` - // (delete everything). Fall back to local noon (no timezone skips - // noon) so a bounded preset always yields a real cutoff. - now.timezone() - .from_local_datetime(&month_start) - .earliest() - .or_else(|| { - now.timezone() - .from_local_datetime( - &first_of_month - .and_hms_opt(12, 0, 0) - .expect("noon is always a valid time"), - ) - .earliest() - }) - .unwrap_or_else(|| now.clone() - Duration::days(31)) - } - }; - Some(CleanupCutoff { - utc: instant.with_timezone(&Utc), - local_date: instant.date_naive(), - }) - } -} - -pub(crate) const PROTECTED_RUN_PREDICATE: &str = " - r.upload_policy = 'bundle' - and r.status = 'completed' - and lower(r.game_mode) = 'ranked' - and lower(coalesce(r.build_channel, 'unknown')) <> 'ptr' - and not exists ( - select 1 - from bundle_outbox o - where o.run_id = r.run_id - and o.status in ('pending', 'uploaded') - ) - and not exists ( - select 1 - from bundle_seal_jobs j - where j.run_id = r.run_id - and j.state = 'terminal_failure' - ) - and ( - exists (select 1 from bundle_seal_jobs j where j.run_id = r.run_id) - or not exists (select 1 from bundle_outbox o where o.run_id = r.run_id) - ) -"; - -#[derive(Clone, Debug, PartialEq)] -pub struct ScreenshotCleanupItem { - pub screenshot_id: String, - pub image_relative_path: String, - /// Preview estimate only; execution resolves surviving references under the lock. - delete_image_file: bool, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct ScreenshotCleanupPlan { - pub items: Vec, - pub orphan_files: Vec, - pub estimated_bytes: i64, - pub skipped_pending_uploads: i64, -} - -#[derive(Clone, Debug, PartialEq, serde::Serialize, specta::Type)] -pub struct ScreenshotCleanupPreview { - pub screenshots: i64, - pub orphan_files: i64, - pub estimated_bytes: i64, - pub skipped_pending_uploads: i64, -} - -impl ScreenshotCleanupPlan { - pub fn empty() -> ScreenshotCleanupPlan { - ScreenshotCleanupPlan { - items: Vec::new(), - orphan_files: Vec::new(), - estimated_bytes: 0, - skipped_pending_uploads: 0, - } - } - - pub fn to_preview(&self) -> ScreenshotCleanupPreview { - ScreenshotCleanupPreview { - screenshots: self.items.len() as i64, - orphan_files: self.orphan_files.len() as i64, - estimated_bytes: self.estimated_bytes, - skipped_pending_uploads: self.skipped_pending_uploads, - } - } -} - -pub fn plan_screenshot_cleanup( - database_path: &Path, - data_root: &Path, - cutoff: Option<&CleanupCutoff>, - today_local_date: NaiveDate, -) -> Result { - if !database_path.exists() { - return Ok(ScreenshotCleanupPlan::empty()); - } - - let conn = open_connection(database_path)?; - let cutoff_ms = cutoff.map(|value| value.utc.timestamp_millis()); - let screenshots_dir = crate::services::paths::screenshots_dir_in(data_root); - let items = eligible_screenshots(&conn, cutoff_ms)?; - let path_sets = screenshot_relative_path_sets(&conn, &items)?; - let items = mark_screenshot_file_deletions(items, &path_sets.remaining); - let skipped_pending_uploads = pending_upload_count(&conn, cutoff_ms)?; - let orphan_files = scan_orphan_screenshot_files( - &screenshots_dir, - &path_sets.all, - cutoff.map(|c| c.local_date), - today_local_date, - ); - - let estimated_bytes = estimate_screenshot_bytes(&screenshots_dir, &items) - + orphan_files.iter().map(|path| file_size(path)).sum::(); - - Ok(ScreenshotCleanupPlan { - items, - orphan_files, - estimated_bytes, - skipped_pending_uploads, - }) -} - -const CLEANUP_CHUNK_SIZE: usize = 200; - -#[derive(Clone, Debug, PartialEq, serde::Serialize, specta::Type)] -pub struct ScreenshotCleanupResult { - pub deleted_rows: i64, - pub deleted_files: i64, - pub freed_bytes: i64, - pub skipped_pending_uploads: i64, -} - -pub fn execute_screenshot_cleanup( - database_path: &Path, - data_root: &Path, - cutoff: Option<&CleanupCutoff>, - today_local_date: NaiveDate, -) -> Result { - let plan = plan_screenshot_cleanup(database_path, data_root, cutoff, today_local_date)?; - execute_screenshot_cleanup_plan(database_path, data_root, plan) -} - -fn execute_screenshot_cleanup_plan( - database_path: &Path, - data_root: &Path, - plan: ScreenshotCleanupPlan, -) -> Result { - let screenshots_dir = crate::services::paths::screenshots_dir_in(data_root); - let mut deleted_rows = 0i64; - let mut deleted_files = 0i64; - let mut freed_bytes = 0i64; - if !plan.items.is_empty() || !plan.orphan_files.is_empty() { - let mut session = CleanupSession::open(database_path, data_root, &SystemGameProcessProbe)?; - let mut candidates = Vec::new(); - for chunk in plan.items.chunks(CLEANUP_CHUNK_SIZE) { - let transaction = session.conn.transaction().map_err(|err| err.to_string())?; - for item in chunk { - if delete_screenshot_if_unprotected(&transaction, &item.screenshot_id)? == 1 { - deleted_rows += 1; - candidates.push(item.image_relative_path.clone()); - } - } - transaction.commit().map_err(|err| err.to_string())?; - } - candidates.extend(plan.orphan_files.iter().filter_map(|path| { - path.strip_prefix(&screenshots_dir) - .ok() - .map(|relative| relative.to_string_lossy().into_owned()) - })); - (deleted_files, freed_bytes) = session.delete_unreferenced_files( - &screenshots_dir, - "select image_relative_path from run_screenshots", - candidates, - )?; - remove_empty_dated_directories(&screenshots_dir); - } - - Ok(ScreenshotCleanupResult { - deleted_rows, - deleted_files, - freed_bytes, - skipped_pending_uploads: plan.skipped_pending_uploads, - }) -} - -/// Owns exclusion until the last unlink, including the gaps between row commits. -/// `BEGIN EXCLUSIVE` alone is insufficient in WAL mode; EXCLUSIVE locking mode -/// keeps the connection's file lock after COMMIT. Closing the connection releases it. -struct CleanupSession { - conn: Connection, -} - -impl CleanupSession { - fn open( - database_path: &Path, - data_root: &Path, - game: &impl GameProcessProbe, - ) -> Result { - let conn = open_cleanup_connection(database_path)?; - conn.execute_batch("PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE; COMMIT;") - .map_err(|err| format!("Cannot exclusively lock history for cleanup: {err}"))?; - - // The mod can write a file before its row, so excluding SQL writers alone - // cannot exclude an in-flight capture. Probe AFTER acquiring the lock: - // a later game startup must initialize its stores in a write transaction - // before any screenshot/replay/video writer can start. The required mod - // startup ordering and its source owners are in docs/history-storage.md. - let game_path = data_root - .parent() - .ok_or("History Data Root has no game directory.")?; - match game.is_running(game_path) { - Ok(false) => Ok(Self { conn }), - Ok(true) => Err("Close The Bazaar before cleaning up history.".to_string()), - Err(err) => Err(format!( - "Cannot confirm The Bazaar is closed for history cleanup: {err}" - )), - } - } - - /// The plan nominates candidates, never permission to unlink. Compare resolved - /// paths, retain every surviving reference, and deduplicate candidates while - /// the session still excludes writers. - /// Call only after the row transactions commit: an unlink failure must not - /// roll back deleted rows into references to already removed files. - fn delete_unreferenced_files( - &self, - root: &Path, - reference_query: &str, - candidates: Vec, - ) -> Result<(i64, i64), String> { - if candidates.is_empty() { - return Ok((0, 0)); - } - let mut statement = self - .conn - .prepare(reference_query) - .map_err(|err| err.to_string())?; - let rows = statement - .query_map([], |row| row.get::<_, String>(0)) - .map_err(|err| err.to_string())?; - let mut referenced = HashSet::new(); - for row in rows { - if let Some(path) = resolve_data_file_path(root, &row.map_err(|err| err.to_string())?) { - referenced.insert(path); - } - } - let mut visited = HashSet::new(); - let mut deleted_files = 0; - let mut freed_bytes = 0; - for candidate in candidates { - let Some(path) = resolve_cleanup_file_path(root, &candidate) else { - continue; - }; - if referenced.contains(&path) || !visited.insert(path.clone()) { - continue; - } - let bytes = file_size(&path); - if remove_file_if_exists(&path)? { - deleted_files += 1; - freed_bytes += bytes; - } - } - Ok((deleted_files, freed_bytes)) - } -} - -/// Built once from `PROTECTED_RUN_PREDICATE` — the per-row delete loop must not -/// re-format a ~600-byte SQL text for every screenshot it visits. -static DELETE_SCREENSHOT_IF_UNPROTECTED_SQL: LazyLock = LazyLock::new(|| { - format!( - "delete from run_screenshots - where screenshot_id = ?1 - and not ( - is_primary = 1 - and exists ( - select 1 - from runs r - where r.run_id = run_screenshots.run_id - and r.bundle_screenshot_requested = 1 - and ({PROTECTED_RUN_PREDICATE}) - ) - )" - ) -}); - -fn delete_screenshot_if_unprotected( - conn: &Connection, - screenshot_id: &str, -) -> Result { - let mut stmt = conn - .prepare_cached(&DELETE_SCREENSHOT_IF_UNPROTECTED_SQL) - .map_err(|err| err.to_string())?; - stmt.execute([screenshot_id]).map_err(|err| err.to_string()) -} - -#[derive(Clone, Debug, PartialEq)] -pub struct RunDataVideoCleanupItem { - pub video_id: String, - pub relative_path: String, - /// Preview estimate only; execution resolves surviving references under the lock. - delete_video_file: bool, -} - -pub struct RunDataCleanupItem { - pub run_id: String, - pub battle_ids: Vec, - pub videos: Vec, - pub screenshots: Vec, -} - -pub struct RunDataCleanupPlan { - pub items: Vec, - pub estimated_bytes: i64, - pub skipped_pending_uploads: i64, -} - -#[derive(Clone, Debug, PartialEq, serde::Serialize, specta::Type)] -pub struct RunDataCleanupPreview { - pub runs: i64, - pub battles: i64, - pub videos: i64, - pub estimated_bytes: i64, - pub skipped_pending_uploads: i64, -} - -impl RunDataCleanupPlan { - pub fn empty() -> RunDataCleanupPlan { - RunDataCleanupPlan { - items: Vec::new(), - estimated_bytes: 0, - skipped_pending_uploads: 0, - } - } - - pub fn to_preview(&self) -> RunDataCleanupPreview { - RunDataCleanupPreview { - runs: self.items.len() as i64, - battles: self - .items - .iter() - .map(|item| item.battle_ids.len() as i64) - .sum(), - videos: self.items.iter().map(|item| item.videos.len() as i64).sum(), - estimated_bytes: self.estimated_bytes, - skipped_pending_uploads: self.skipped_pending_uploads, - } - } -} - -pub fn plan_run_data_cleanup( - database_path: &Path, - data_root: &Path, - cutoff: Option<&CleanupCutoff>, -) -> Result { - if !database_path.exists() { - return Ok(RunDataCleanupPlan::empty()); - } - - let conn = open_connection(database_path)?; - let cutoff_ms = cutoff.map(|value| value.utc.timestamp_millis()); - let run_ids = eligible_run_ids(&conn, cutoff_ms)?; - let skipped_pending_uploads = skipped_pending_run_count(&conn, cutoff_ms)?; - let remaining_screenshot_paths = - remaining_screenshot_relative_paths_after_run_cleanup(&conn, &run_ids)?; - let remaining_video_paths = remaining_video_relative_paths_after_run_cleanup(&conn, &run_ids)?; - - let screenshots_dir = crate::services::paths::screenshots_dir_in(data_root); - let videos_dir = crate::services::paths::combat_replay_videos_dir_in(data_root); - let replays_dir = crate::services::paths::combat_replays_dir_in(data_root); - - let mut items = Vec::new(); - let mut screenshot_items_for_estimate = Vec::new(); - let mut video_items_for_estimate = Vec::new(); - // Execution unlinks one replay payload per distinct battle id, so the - // estimate counts each payload once too — same dedupe key as - // `deleted_replay_payloads` in `execute_run_data_cleanup_plan`. - let mut estimated_replay_payloads = HashSet::new(); - let mut estimated_bytes = 0i64; - for run_id in run_ids { - let battle_ids = run_battle_ids(&conn, &run_id)?; - let videos = - mark_video_file_deletions(run_video_refs(&conn, &run_id)?, &remaining_video_paths); - let screenshots = mark_screenshot_file_deletions( - run_screenshot_items(&conn, &run_id)?, - &remaining_screenshot_paths, - ); - - for battle_id in &battle_ids { - let Some(path) = replay_payload_path(&replays_dir, battle_id) else { - continue; - }; - if !estimated_replay_payloads.insert(battle_id.trim().to_string()) { - continue; - } - estimated_bytes += file_size(&path); - } - video_items_for_estimate.extend(videos.iter().cloned()); - screenshot_items_for_estimate.extend(screenshots.iter().cloned()); - - items.push(RunDataCleanupItem { - run_id, - battle_ids, - videos, - screenshots, - }); - } - - estimated_bytes += estimate_video_bytes(&videos_dir, &video_items_for_estimate); - estimated_bytes += estimate_screenshot_bytes(&screenshots_dir, &screenshot_items_for_estimate); - - Ok(RunDataCleanupPlan { - items, - estimated_bytes, - skipped_pending_uploads, - }) -} - -/// Runs are heavier than screenshots (multiple tables + cascade per row), -/// so each transaction commits fewer rows. The cleanup session retains its -/// exclusive connection lock across these commits and the subsequent unlinks. -const RUN_CLEANUP_CHUNK_SIZE: usize = 25; - -#[derive(Clone, Debug, PartialEq, serde::Serialize, specta::Type)] -pub struct RunDataCleanupResult { - pub deleted_runs: i64, - pub deleted_files: i64, - pub freed_bytes: i64, - pub skipped_pending_uploads: i64, -} - -pub fn execute_run_data_cleanup( - database_path: &Path, - data_root: &Path, - cutoff: Option<&CleanupCutoff>, -) -> Result { - let plan = plan_run_data_cleanup(database_path, data_root, cutoff)?; - execute_run_data_cleanup_plan(database_path, data_root, plan) -} - -fn execute_run_data_cleanup_plan( - database_path: &Path, - data_root: &Path, - plan: RunDataCleanupPlan, -) -> Result { - let screenshots_dir = crate::services::paths::screenshots_dir_in(data_root); - let videos_dir = crate::services::paths::combat_replay_videos_dir_in(data_root); - let replays_dir = crate::services::paths::combat_replays_dir_in(data_root); - let mut deleted_runs = 0i64; - let mut deleted_files = 0i64; - let mut freed_bytes = 0i64; - if !plan.items.is_empty() { - let mut session = CleanupSession::open(database_path, data_root, &SystemGameProcessProbe)?; - validate_run_cleanup_cascade_fks(&session.conn)?; - let mut deleted_items = Vec::new(); - for chunk in plan.items.chunks(RUN_CLEANUP_CHUNK_SIZE) { - let transaction = session.conn.transaction().map_err(|err| err.to_string())?; - for item in chunk { - if delete_run_if_unprotected(&transaction, &item.run_id)? == 0 { - continue; - } - - // Screenshots do not cascade from runs. Their writer only inserts - // rows, so their direct Run attachment cannot change after planning. - for screenshot in &item.screenshots { - transaction - .execute( - "delete from run_screenshots where screenshot_id = ?1", - [&screenshot.screenshot_id], - ) - .map_err(|err| err.to_string())?; - } - deleted_items.push(item); - } - transaction.commit().map_err(|err| err.to_string())?; - } - - deleted_runs = deleted_items.len() as i64; - // Video ownership follows a battle whose Run attachment can change. - // Wait for ALL Run deletions, including later chunks, before checking it: - // a video moved to another deleted Run must not be mistaken for a survivor. - // Include candidates from guarded-delete misses too: their battle may - // have moved to a Run that was deleted, leaving no current owner. - for chunk in plan.items.chunks(RUN_CLEANUP_CHUNK_SIZE) { - let transaction = session.conn.transaction().map_err(|err| err.to_string())?; - for item in chunk { - for video in &item.videos { - transaction - .execute( - "delete from combat_replay_videos - where video_id = ?1 - and not exists ( - select 1 from battles b - join runs r on r.run_id = b.run_id - where b.battle_id = combat_replay_videos.battle_id - )", - [&video.video_id], - ) - .map_err(|err| err.to_string())?; - } - } - transaction.commit().map_err(|err| err.to_string())?; - } - - for (root, references, candidates) in [ - ( - &videos_dir, - "select video_relative_path from combat_replay_videos", - plan.items - .iter() - .flat_map(|item| item.videos.iter().map(|video| video.relative_path.clone())) - .collect::>(), - ), - ( - &replays_dir, - "select battle_id || '.payload.mpack.gz' from battles", - deleted_items - .iter() - .flat_map(|item| &item.battle_ids) - .filter_map(|battle_id| replay_payload_path(&replays_dir, battle_id)) - .filter_map(|path| { - path.file_name() - .map(|name| name.to_string_lossy().into_owned()) - }) - .collect(), - ), - ( - &screenshots_dir, - "select image_relative_path from run_screenshots", - deleted_items - .iter() - .flat_map(|item| { - item.screenshots - .iter() - .map(|shot| shot.image_relative_path.clone()) - }) - .collect(), - ), - ] { - let (files, bytes) = session.delete_unreferenced_files(root, references, candidates)?; - deleted_files += files; - freed_bytes += bytes; - } - remove_empty_dated_directories(&screenshots_dir); - } - - Ok(RunDataCleanupResult { - deleted_runs, - deleted_files, - freed_bytes, - skipped_pending_uploads: plan.skipped_pending_uploads, - }) -} - -/// Built once from `PROTECTED_RUN_PREDICATE`; see the screenshot twin above. -static DELETE_RUN_IF_UNPROTECTED_SQL: LazyLock = LazyLock::new(|| { - format!( - "delete from runs as r - where r.run_id = ?1 - and not ({PROTECTED_RUN_PREDICATE})" - ) -}); - -fn delete_run_if_unprotected(conn: &Connection, run_id: &str) -> Result { - let mut stmt = conn - .prepare_cached(&DELETE_RUN_IF_UNPROTECTED_SQL) - .map_err(|err| err.to_string())?; - stmt.execute([run_id]).map_err(|err| err.to_string()) -} - -fn eligible_run_ids(conn: &Connection, cutoff_ms: Option) -> Result, String> { - let sql = format!( - "select r.run_id - from runs r - where r.status <> 'active' - and (?1 is null or coalesce(r.ended_at_ms, r.last_seen_at_ms, r.started_at_ms) < ?1) - and not ({PROTECTED_RUN_PREDICATE}) - order by coalesce(r.ended_at_ms, r.last_seen_at_ms, r.started_at_ms) asc, - r.run_id asc" - ); - - let mut stmt = conn.prepare(&sql).map_err(|err| err.to_string())?; - let rows = stmt - .query_map(params![cutoff_ms], |row| row.get::<_, String>(0)) - .map_err(|err| err.to_string())?; - rows.collect::, _>>() - .map_err(|err| err.to_string()) -} - -fn skipped_pending_run_count(conn: &Connection, cutoff_ms: Option) -> Result { - let sql = format!( - "select count(*) - from runs r - where r.status <> 'active' - and (?1 is null or coalesce(r.ended_at_ms, r.last_seen_at_ms, r.started_at_ms) < ?1) - and ({PROTECTED_RUN_PREDICATE})" - ); - - conn.query_row(&sql, params![cutoff_ms], |row| row.get(0)) - .map_err(|err| err.to_string()) -} - -fn run_battle_ids(conn: &Connection, run_id: &str) -> Result, String> { - let mut stmt = conn - .prepare_cached("select battle_id from battles where run_id = ?1 order by battle_id asc") - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([run_id], |row| row.get::<_, String>(0)) - .map_err(|err| err.to_string())?; - rows.collect::, _>>() - .map_err(|err| err.to_string()) -} - -fn run_video_refs(conn: &Connection, run_id: &str) -> Result, String> { - let mut stmt = conn - .prepare_cached( - "select v.video_id, v.video_relative_path - from combat_replay_videos v - join battles b on b.battle_id = v.battle_id - where b.run_id = ?1 - order by v.video_id asc", - ) - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([run_id], |row| { - Ok(RunDataVideoCleanupItem { - video_id: row.get(0)?, - relative_path: row.get(1)?, - delete_video_file: false, - }) - }) - .map_err(|err| err.to_string())?; - rows.collect::, _>>() - .map_err(|err| err.to_string()) -} - -fn run_screenshot_items( - conn: &Connection, - run_id: &str, -) -> Result, String> { - let mut stmt = conn - .prepare_cached( - "select screenshot_id, image_relative_path - from run_screenshots - where run_id = ?1 - order by screenshot_id asc", - ) - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([run_id], |row| { - Ok(ScreenshotCleanupItem { - screenshot_id: row.get(0)?, - image_relative_path: row.get(1)?, - delete_image_file: false, - }) - }) - .map_err(|err| err.to_string())?; - rows.collect::, _>>() - .map_err(|err| err.to_string()) -} - -fn remaining_screenshot_relative_paths_after_run_cleanup( - conn: &Connection, - planned_run_ids: &[String], -) -> Result, String> { - if planned_run_ids.is_empty() { - return Ok(HashSet::new()); - } - - let planned_run_ids = planned_run_ids - .iter() - .map(String::as_str) - .collect::>(); - let mut stmt = conn - .prepare("select run_id, image_relative_path from run_screenshots") - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([], |row| { - Ok((row.get::<_, Option>(0)?, row.get::<_, String>(1)?)) - }) - .map_err(|err| err.to_string())?; - - let mut paths = HashSet::new(); - for row in rows { - let (run_id, image_relative_path) = row.map_err(|err| err.to_string())?; - if run_id - .as_deref() - .is_some_and(|run_id| planned_run_ids.contains(run_id)) - { - continue; - } - let normalized = normalize_relative_path(&image_relative_path); - if !normalized.is_empty() { - paths.insert(normalized); - } - } - Ok(paths) -} - -fn remaining_video_relative_paths_after_run_cleanup( - conn: &Connection, - planned_run_ids: &[String], -) -> Result, String> { - if planned_run_ids.is_empty() { - return Ok(HashSet::new()); - } - - let planned_run_ids = planned_run_ids - .iter() - .map(String::as_str) - .collect::>(); - let mut stmt = conn - .prepare( - "select b.run_id, v.video_relative_path - from combat_replay_videos v - left join battles b on b.battle_id = v.battle_id", - ) - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([], |row| { - Ok((row.get::<_, Option>(0)?, row.get::<_, String>(1)?)) - }) - .map_err(|err| err.to_string())?; - - let mut paths = HashSet::new(); - for row in rows { - let (run_id, video_relative_path) = row.map_err(|err| err.to_string())?; - if run_id - .as_deref() - .is_some_and(|run_id| planned_run_ids.contains(run_id)) - { - continue; - } - let normalized = normalize_relative_path(&video_relative_path); - if !normalized.is_empty() { - paths.insert(normalized); - } - } - Ok(paths) -} - -/// Replay payload path: `/.payload.mpack.gz`. -pub(crate) fn replay_payload_path(replays_dir: &Path, battle_id: &str) -> Option { - let trimmed = battle_id.trim(); - // `:` guards against a Windows drive-relative id like `C:target`, which has - // no `/`/`\\` yet escapes `replays_dir` when joined via its drive prefix. - if trimmed.is_empty() - || trimmed.contains('/') - || trimmed.contains('\\') - || trimmed.contains(':') - || trimmed.contains("..") - { - return None; - } - let path = replays_dir.join(format!("{trimmed}.payload.mpack.gz")); - path.starts_with(replays_dir).then_some(path) -} - -fn eligible_screenshots( - conn: &Connection, - cutoff_ms: Option, -) -> Result, String> { - let sql = format!( - " - select s.screenshot_id, s.image_relative_path - from run_screenshots s - where s.capture_source = 'end_of_run_auto' - and (?1 is null or s.captured_at_ms < ?1) - and not ( - s.is_primary = 1 - and exists ( - select 1 - from runs r - where r.run_id = s.run_id - and r.bundle_screenshot_requested = 1 - and ({PROTECTED_RUN_PREDICATE}) - ) - ) - order by s.captured_at_ms asc, s.screenshot_id asc - " - ); - - let mut stmt = conn.prepare(&sql).map_err(|err| err.to_string())?; - let rows = stmt - .query_map(params![cutoff_ms], |row| { - Ok(ScreenshotCleanupItem { - screenshot_id: row.get(0)?, - image_relative_path: row.get(1)?, - delete_image_file: false, - }) - }) - .map_err(|err| err.to_string())?; - - rows.collect::, _>>() - .map_err(|err| err.to_string()) -} - -fn pending_upload_count(conn: &Connection, cutoff_ms: Option) -> Result { - let sql = format!( - " - select count(*) - from run_screenshots s - where s.capture_source = 'end_of_run_auto' - and s.is_primary = 1 - and (?1 is null or s.captured_at_ms < ?1) - and exists ( - select 1 - from runs r - where r.run_id = s.run_id - and r.bundle_screenshot_requested = 1 - and ({PROTECTED_RUN_PREDICATE}) - ) - " - ); - conn.query_row(&sql, params![cutoff_ms], |row| row.get(0)) - .map_err(|err| err.to_string()) -} - -/// Both screenshot path sets a plan needs, derived from one table scan. -struct ScreenshotRelativePathSets { - /// Every referenced path, including those of the planned items. Feeds the - /// orphan sweep, which must not treat a planned row's file as unreferenced. - all: HashSet, - /// Paths still referenced once the planned rows are gone. Feeds the - /// shared-file guard that keeps a surviving row's image on disk. - remaining: HashSet, -} - -fn screenshot_relative_path_sets( - conn: &Connection, - items: &[ScreenshotCleanupItem], -) -> Result { - let planned_ids = items - .iter() - .map(|item| item.screenshot_id.as_str()) - .collect::>(); - let mut stmt = conn - .prepare("select screenshot_id, image_relative_path from run_screenshots") - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([], |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) - }) - .map_err(|err| err.to_string())?; - - let mut all = HashSet::new(); - let mut remaining = HashSet::new(); - for row in rows { - let (screenshot_id, image_relative_path) = row.map_err(|err| err.to_string())?; - let normalized = normalize_relative_path(&image_relative_path); - if normalized.is_empty() { - continue; - } - if !planned_ids.contains(screenshot_id.as_str()) { - remaining.insert(normalized.clone()); - } - all.insert(normalized); - } - Ok(ScreenshotRelativePathSets { all, remaining }) -} - -fn mark_video_file_deletions( - items: Vec, - remaining_referenced_paths: &HashSet, -) -> Vec { - items - .into_iter() - .map(|mut item| { - let normalized = normalize_relative_path(&item.relative_path); - item.delete_video_file = - !normalized.is_empty() && !remaining_referenced_paths.contains(&normalized); - item - }) - .collect() -} - -fn mark_screenshot_file_deletions( - items: Vec, - remaining_referenced_paths: &HashSet, -) -> Vec { - items - .into_iter() - .map(|mut item| { - let normalized = normalize_relative_path(&item.image_relative_path); - item.delete_image_file = - !normalized.is_empty() && !remaining_referenced_paths.contains(&normalized); - item - }) - .collect() -} - -fn estimate_video_bytes(videos_dir: &Path, items: &[RunDataVideoCleanupItem]) -> i64 { - let mut estimated_paths = HashSet::new(); - items - .iter() - .filter(|item| item.delete_video_file) - .filter_map(|item| { - let path = resolve_cleanup_file_path(videos_dir, &item.relative_path)?; - let normalized = normalize_relative_path(&item.relative_path); - estimated_paths - .insert(normalized) - .then_some(file_size(&path)) - }) - .sum() -} - -fn scan_orphan_screenshot_files( - screenshots_dir: &Path, - referenced_paths: &HashSet, - cutoff_local_date: Option, - today_local_date: NaiveDate, -) -> Vec { - if !screenshots_dir.exists() { - return Vec::new(); - } - - // Folders whose date is at or after this floor are never swept for orphans. - // Today's local-date folder is ALWAYS protected — that is why the floor is - // `today_local_date` even under preset `all` (cutoff `None`). The mod writes - // a screenshot's PNG to disk (via an atomic `.png..tmp` rename) - // BEFORE it inserts the matching `run_screenshots` row, and it names the - // dated folder from local capture time. So a file captured "now" briefly has - // no row; sweeping today's folder would classify that in-flight file (or its - // transient `.tmp` sibling) as an orphan and delete it, leaving the mod to - // insert a row pointing at a missing file. A bounded preset's cutoff is - // always <= today, so `min` keeps its existing, stricter protection. Execution - // also excludes the game and rechecks references under CleanupSession's lock, - // including late publication of a capture spanning local midnight. - let protect_from = cutoff_local_date.map_or(today_local_date, |cutoff_date| { - cutoff_date.min(today_local_date) - }); - - let mut orphan_files = Vec::new(); - let Ok(entries) = std::fs::read_dir(screenshots_dir) else { - return orphan_files; - }; - - for entry in entries { - let Ok(entry) = entry else { - continue; - }; - let Ok(file_type) = entry.file_type() else { - continue; - }; - if !file_type.is_dir() { - continue; - } - - let folder_name = entry.file_name(); - let Some(folder_name) = folder_name.to_str() else { - continue; - }; - let Ok(folder_date) = NaiveDate::parse_from_str(folder_name, "%Y-%m-%d") else { - continue; - }; - if folder_date >= protect_from { - continue; - } - - collect_dated_folder_orphan_files( - screenshots_dir, - &entry.path(), - referenced_paths, - &mut orphan_files, - ); - } - - orphan_files.sort(); - orphan_files -} - -fn collect_dated_folder_orphan_files( - screenshots_dir: &Path, - directory: &Path, - referenced_paths: &HashSet, - orphan_files: &mut Vec, -) { - let Ok(entries) = std::fs::read_dir(directory) else { - return; - }; - - for entry in entries { - let Ok(entry) = entry else { - continue; - }; - let Ok(file_type) = entry.file_type() else { - continue; - }; - if !file_type.is_file() { - continue; - } - - let path = entry.path(); - let Ok(relative) = path.strip_prefix(screenshots_dir) else { - continue; - }; - let relative = relative.to_string_lossy(); - if !referenced_paths.contains(&normalize_relative_path(&relative)) { - orphan_files.push(path); - } - } -} - -fn estimate_screenshot_bytes(screenshots_dir: &Path, items: &[ScreenshotCleanupItem]) -> i64 { - let mut estimated_paths = HashSet::new(); - items - .iter() - .filter(|item| item.delete_image_file) - .filter_map(|item| { - let path = resolve_cleanup_file_path(screenshots_dir, &item.image_relative_path)?; - let normalized = normalize_relative_path(&item.image_relative_path); - estimated_paths - .insert(normalized) - .then_some(file_size(&path)) - }) - .sum() -} - -pub(crate) fn normalize_relative_path(path: &str) -> String { - path.trim() - .split(['/', '\\']) - .filter_map(|segment| { - let segment = segment.trim(); - (!segment.is_empty() && segment != "." && segment != "..").then_some(segment) - }) - .collect::>() - .join("/") -} - -fn file_size(path: &Path) -> i64 { - std::fs::metadata(path) - .map(|metadata| metadata.len() as i64) - .unwrap_or(0) -} - -fn remove_file_if_exists(path: &Path) -> Result { - match std::fs::remove_file(path) { - Ok(()) => Ok(true), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false), - Err(err) => Err(format!("failed to remove {}: {err}", path.display())), - } -} - -fn validate_run_cleanup_cascade_fks(conn: &Connection) -> Result<(), String> { - for (child_table, child_column, parent_table) in [ - ("battles", "run_id", "runs"), - ("run_events", "run_id", "runs"), - ("battle_snapshots", "battle_id", "battles"), - ("bundle_seal_jobs", "run_id", "runs"), - ] { - if !has_on_delete_cascade_fk(conn, child_table, child_column, parent_table)? { - return Err(format!( - "run cleanup requires {child_table}.{child_column} -> {parent_table} ON DELETE CASCADE before deleting files" - )); - } - } - Ok(()) -} - -fn has_on_delete_cascade_fk( - conn: &Connection, - child_table: &str, - child_column: &str, - parent_table: &str, -) -> Result { - conn.query_row( - "select exists( - select 1 - from pragma_foreign_key_list(?1) - where \"table\" = ?2 - and \"from\" = ?3 - and upper(on_delete) = 'CASCADE' - )", - params![child_table, parent_table, child_column], - |row| row.get::<_, i64>(0), - ) - .map(|value| value != 0) - .map_err(|err| err.to_string()) -} - -fn remove_empty_dated_directories(screenshots_dir: &Path) { - let Ok(entries) = std::fs::read_dir(screenshots_dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if !path.is_dir() { - continue; - } - let name = entry.file_name().to_string_lossy().into_owned(); - if NaiveDate::parse_from_str(&name, "%Y-%m-%d").is_err() { - continue; - } - let is_empty = std::fs::read_dir(&path) - .map(|mut dir| dir.next().is_none()) - .unwrap_or(false); - if is_empty { - let _ = std::fs::remove_dir(&path); - } - } -} - -#[cfg(test)] -mod tests { - use super::{plan_screenshot_cleanup, CleanupCutoff, StorageCleanupPreset}; - use crate::history::mod_schema::create_mod_schema; - use chrono::{DateTime, FixedOffset, NaiveDate, SecondsFormat, TimeZone, Utc}; - use rusqlite::Connection; - use std::collections::HashSet; - use std::fs; - use std::path::{Path, PathBuf}; - use tempfile::TempDir; - - struct CleanupFixture { - #[allow(dead_code)] - temp_dir: TempDir, - data_root: PathBuf, - database_path: PathBuf, - screenshots_dir: PathBuf, - } - - fn create_fixture() -> CleanupFixture { - let temp_dir = TempDir::new().unwrap(); - let data_root = temp_dir.path().join(crate::config::BAZAAR_DATA_DIRECTORY); - let screenshots_dir = data_root.join("Screenshots"); - let database_path = data_root.join("bazaarplusplus.db"); - fs::create_dir_all(&screenshots_dir).unwrap(); - let conn = Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - drop(conn); - CleanupFixture { - temp_dir, - data_root, - database_path, - screenshots_dir, - } - } - - fn write_screenshot_file(screenshots_dir: &Path, relative: &str, bytes: &[u8]) -> PathBuf { - let path = screenshots_dir.join(relative); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(&path, bytes).unwrap(); - path - } - - fn cutoff(utc: &str, local_date_tuple: (i32, u32, u32)) -> CleanupCutoff { - CleanupCutoff { - utc: DateTime::parse_from_rfc3339(utc) - .unwrap() - .with_timezone(&Utc), - local_date: NaiveDate::from_ymd_opt( - local_date_tuple.0, - local_date_tuple.1, - local_date_tuple.2, - ) - .unwrap(), - } - } - - /// A fixed "today" for the generic cleanup tests. It sits strictly after - /// every dated folder those tests create, so the today-folder orphan guard - /// never masks the past-folder sweeps they assert. The guard itself is - /// exercised by the dedicated all-preset tests below. - fn test_today() -> NaiveDate { - NaiveDate::from_ymd_opt(2026, 7, 15).unwrap() - } - - /// Seeds keep RFC 3339 text for readability; the database stores Unix milliseconds. - fn ms(rfc3339: &str) -> i64 { - DateTime::parse_from_rfc3339(rfc3339) - .unwrap() - .timestamp_millis() - } - - fn insert_run( - conn: &rusqlite::Connection, - run_id: &str, - status: &str, - game_mode: &str, - ended_at_utc: &str, - ) { - conn.execute( - "insert into runs ( - run_id, started_at_ms, last_seen_at_ms, status, hero, game_mode, ended_at_ms - ) values (?1, ?2, ?2, ?3, 'Vanessa', ?4, ?2)", - rusqlite::params![run_id, ms(ended_at_utc), status, game_mode], - ) - .unwrap(); - } - - fn insert_outbox(conn: &rusqlite::Connection, run_id: &str, status: &str) { - conn.execute( - "insert into bundle_outbox ( - bundle_id, run_id, file_name, content_sha256_hex, content_digest, - total_bytes, has_screenshot, sealed_at_ms, status - ) values (?1, ?2, ?3, 'sha256', 'digest', 42, 0, 1781085600000, ?4)", - rusqlite::params![ - format!("bundle-{run_id}-{status}"), - run_id, - format!("{run_id}-{status}.zip"), - status - ], - ) - .unwrap(); - } - - fn insert_seal_job(conn: &rusqlite::Connection, run_id: &str, state: &str) { - conn.execute( - "insert into bundle_seal_jobs ( - run_id, state, screenshot_requested, screenshot_state, input_deadline_at_ms - ) values (?1, ?2, 0, 'not_requested', 1781085900000)", - rusqlite::params![run_id, state], - ) - .unwrap(); - } - - /// `source` stays explicit because `GHOST` rows (no payload state) are a - /// distinct case the run-cleanup cascade tests rely on; their remote - /// identity is derived because the `battles` CHECK admits only one shape. - fn insert_battle( - conn: &rusqlite::Connection, - battle_id: &str, - source: &str, - run_id: Option<&str>, - recorded_at_utc: &str, - local_payload_state: Option<&str>, - ) { - let ghost = source == "GHOST"; - conn.execute( - "insert into battles ( - battle_id, source, run_id, recorded_at_ms, combat_kind, - local_payload_state, remote_battle_id, uploader_account_id - ) values (?1, ?2, ?3, ?4, 'PVP', ?5, ?6, ?7)", - rusqlite::params![ - battle_id, - source, - run_id, - ms(recorded_at_utc), - local_payload_state, - ghost.then(|| format!("remote-{battle_id}")), - ghost.then_some("uploader-1") - ], - ) - .unwrap(); - } - - /// Cleanup planning selects videos by battle, never by `status`, so every - /// seed uses the completed status and the helper fixes it. - fn insert_video( - conn: &rusqlite::Connection, - video_id: &str, - battle_id: &str, - video_relative_path: &str, - started_at_utc: &str, - ) { - conn.execute( - "insert into combat_replay_videos ( - video_id, battle_id, source, video_relative_path, width, height, fps, codec, - started_at_ms, status - ) values (?1, ?2, 'GAME_CAPTURE', ?3, 1920, 1080, 60, 'h264', ?4, 'COMPLETED')", - rusqlite::params![video_id, battle_id, video_relative_path, ms(started_at_utc)], - ) - .unwrap(); - } - - /// `captured_utc_offset_minutes` is `not null` but no cleanup query reads - /// it, so the helper records the +08:00 zone the existing seeds all used. - fn insert_screenshot( - conn: &rusqlite::Connection, - screenshot_id: &str, - run_id: Option<&str>, - is_primary: i64, - image_relative_path: &str, - captured_at_utc: &str, - ) { - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, is_primary, image_relative_path, - captured_at_ms, captured_utc_offset_minutes - ) values (?1, ?2, 'end_of_run_auto', ?3, ?4, ?5, 480)", - rusqlite::params![ - screenshot_id, - run_id, - is_primary, - image_relative_path, - ms(captured_at_utc) - ], - ) - .unwrap(); - } - - #[test] - fn cleanup_session_excludes_writers_across_commits_and_unlinks() { - for journal in ["DELETE", "WAL"] { - let fixture = create_fixture(); - let setup = Connection::open(&fixture.database_path).unwrap(); - setup - .execute_batch(&format!("pragma journal_mode = {journal};")) - .unwrap(); - let relative = "2026-06-01/capture.png"; - let image = write_screenshot_file(&fixture.screenshots_dir, relative, b"old"); - insert_screenshot(&setup, "old", None, 0, relative, "2026-06-01T00:00:00Z"); - drop(setup); - - let writer = Connection::open(&fixture.database_path).unwrap(); - writer.busy_timeout(std::time::Duration::ZERO).unwrap(); - let assert_writer_blocked = || { - let error = writer - .execute_batch("BEGIN IMMEDIATE; COMMIT;") - .unwrap_err(); - assert_eq!( - error.sqlite_error_code(), - Some(rusqlite::ErrorCode::DatabaseBusy) - ); - }; - let probe = |_: &Path| { - // The probe must run after exclusion is acquired. A game starting - // after this snapshot must initialize its store before writing files. - assert_writer_blocked(); - Ok(false) - }; - let mut session = - super::CleanupSession::open(&fixture.database_path, &fixture.data_root, &probe) - .unwrap(); - let transaction = session.conn.transaction().unwrap(); - assert_eq!( - super::delete_screenshot_if_unprotected(&transaction, "old").unwrap(), - 1 - ); - transaction.commit().unwrap(); - assert_writer_blocked(); - assert_eq!( - session - .delete_unreferenced_files( - &fixture.screenshots_dir, - "select image_relative_path from run_screenshots", - vec![relative.to_string()], - ) - .unwrap(), - (1, 3) - ); - assert!(!image.exists()); - assert_writer_blocked(); - drop(session); - - // Mirrors the mandatory startup write transaction, then file-before-row - // publication: a new game can now initialize and reuse the old path safely. - writer.execute_batch("BEGIN IMMEDIATE; COMMIT;").unwrap(); - write_screenshot_file(&fixture.screenshots_dir, relative, b"new"); - insert_screenshot(&writer, "new", None, 0, relative, "2026-06-01T00:00:00Z"); - assert_eq!(fs::read(image).unwrap(), b"new"); - } - } - - #[test] - fn cleanup_session_refuses_a_running_or_uninspectable_game_and_releases_lock() { - for state in [Ok(true), Err("process inspection failed".to_string())] { - let fixture = create_fixture(); - let image = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-01/shot.png", b"keep"); - let probe = |path: &Path| { - assert_eq!(path, fixture.data_root.parent().unwrap()); - state.clone() - }; - assert!(super::CleanupSession::open( - &fixture.database_path, - &fixture.data_root, - &probe - ) - .is_err()); - assert_eq!(fs::read(image).unwrap(), b"keep"); - let writer = Connection::open(&fixture.database_path).unwrap(); - writer.busy_timeout(std::time::Duration::ZERO).unwrap(); - writer.execute_batch("BEGIN IMMEDIATE; COMMIT;").unwrap(); - } - } - - #[test] - fn file_deletion_failure_keeps_row_deletions_committed_and_releases_lock() { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - let first = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-01/first.png", b"first"); - let failure = fixture.screenshots_dir.join("2026-06-01/failure.png"); - fs::create_dir(&failure).unwrap(); - insert_screenshot( - &conn, - "a", - None, - 0, - "2026-06-01/first.png", - "2026-06-01T00:00:00Z", - ); - insert_screenshot( - &conn, - "b", - None, - 0, - "2026-06-01/failure.png", - "2026-06-01T00:00:00Z", - ); - drop(conn); - assert!(super::execute_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap_err() - .contains("failed to remove")); - assert!(!first.exists()); - assert!(failure.is_dir()); - let conn = Connection::open(&fixture.database_path).unwrap(); - conn.busy_timeout(std::time::Duration::ZERO).unwrap(); - conn.execute_batch("BEGIN IMMEDIATE; COMMIT;").unwrap(); - assert_eq!( - conn.query_row("select count(*) from run_screenshots", [], |row| row - .get::<_, i64>(0)) - .unwrap(), - 0 - ); - } - - #[test] - fn stale_run_plan_preserves_video_metadata_and_files_after_battle_reassignment() { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - conn.execute_batch("pragma journal_mode = WAL;").unwrap(); - insert_run(&conn, "old", "completed", "Normal", "2026-06-01T00:00:00Z"); - insert_run(&conn, "active", "active", "Normal", "2026-07-15T00:00:00Z"); - insert_battle( - &conn, - "battle", - "LOCAL", - Some("old"), - "2026-06-01T00:00:00Z", - Some("ready"), - ); - let replays = crate::services::paths::combat_replays_dir_in(&fixture.data_root); - fs::create_dir_all(&replays).unwrap(); - let payload = super::replay_payload_path(&replays, "battle").unwrap(); - fs::write(&payload, b"payload").unwrap(); - let videos = crate::services::paths::combat_replay_videos_dir_in(&fixture.data_root); - let video = write_screenshot_file(&videos, "shared.mp4", b"video"); - insert_video(&conn, "old", "battle", "shared.mp4", "2026-06-01T00:00:00Z"); - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - - // The battle writer updates run_id on conflict (see docs/history-storage.md). - // There is no second video row to hide loss of the original metadata. - conn.execute( - "update battles set run_id = 'active' where battle_id = 'battle'", - [], - ) - .unwrap(); - drop(conn); - let result = - super::execute_run_data_cleanup_plan(&fixture.database_path, &fixture.data_root, plan) - .unwrap(); - assert_eq!(result.deleted_runs, 1); - let conn = Connection::open(&fixture.database_path).unwrap(); - assert_eq!( - conn.query_row( - "select count(*) from combat_replay_videos where video_id = 'old' and battle_id = 'battle'", - [], - |row| row.get::<_, i64>(0), - ).unwrap(), - 1, - "the surviving Run must retain its original video metadata", - ); - assert_eq!(result.deleted_files, 0); - assert_eq!(fs::read(payload).unwrap(), b"payload"); - assert_eq!(fs::read(video).unwrap(), b"video"); - } - - #[test] - fn stale_run_plan_cleans_video_metadata_by_surviving_run_ownership() { - for destination in [ - "earlier", - "later", - "later_chunk", - "protected", - "source_protected", - "detached", - "missing_battle", - ] { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - conn.execute_batch("pragma journal_mode = WAL;").unwrap(); - insert_run(&conn, "old", "completed", "Normal", "2026-06-02T00:00:00Z"); - let has_target = !matches!(destination, "detached" | "missing_battle"); - if has_target { - let ended_at = if destination == "earlier" { - "2026-06-01T00:00:00Z" - } else { - "2026-06-04T00:00:00Z" - }; - insert_run(&conn, "target", "completed", "Normal", ended_at); - } - let filler_runs = if destination == "later_chunk" { - super::RUN_CLEANUP_CHUNK_SIZE - } else { - 0 - }; - for index in 0..filler_runs { - insert_run( - &conn, - &format!("filler-{index}"), - "completed", - "Normal", - "2026-06-03T00:00:00Z", - ); - } - insert_battle( - &conn, - "battle", - "LOCAL", - Some("old"), - "2026-06-02T00:00:00Z", - Some("ready"), - ); - let videos = crate::services::paths::combat_replay_videos_dir_in(&fixture.data_root); - let video = write_screenshot_file(&videos, "original.mp4", b"video"); - insert_video( - &conn, - "original", - "battle", - "original.mp4", - "2026-06-02T00:00:00Z", - ); - let screenshot = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-02/original.png", b"shot"); - insert_screenshot( - &conn, - "original", - Some("old"), - 0, - "2026-06-02/original.png", - "2026-06-02T00:00:00Z", - ); - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None) - .unwrap(); - - match destination { - "missing_battle" => conn - .execute("delete from battles where battle_id = 'battle'", []) - .unwrap(), - "detached" => conn - .execute( - "update battles set run_id = null where battle_id = 'battle'", - [], - ) - .unwrap(), - _ => conn - .execute( - "update battles set run_id = 'target' where battle_id = 'battle'", - [], - ) - .unwrap(), - }; - let keep_video = destination == "protected"; - let keep_screenshot = destination == "source_protected"; - if keep_video || keep_screenshot { - conn.execute( - "update runs set game_mode = 'Ranked' where run_id = ?1", - [if keep_video { "target" } else { "old" }], - ) - .unwrap(); - } - drop(conn); - let result = super::execute_run_data_cleanup_plan( - &fixture.database_path, - &fixture.data_root, - plan, - ) - .unwrap(); - assert_eq!( - result.deleted_runs, - i64::from(!keep_screenshot) - + i64::from(has_target && !keep_video) - + filler_runs as i64, - "{destination}" - ); - assert_eq!( - result.deleted_files, - i64::from(!keep_video) + i64::from(!keep_screenshot), - "{destination}" - ); - assert_eq!(video.exists(), keep_video, "{destination}"); - assert_eq!(screenshot.exists(), keep_screenshot, "{destination}"); - let conn = Connection::open(&fixture.database_path).unwrap(); - assert_eq!( - conn.query_row( - "select count(*) from combat_replay_videos where video_id = 'original'", - [], - |row| row.get::<_, i64>(0) - ) - .unwrap(), - i64::from(keep_video), - "{destination}" - ); - assert_eq!( - conn.query_row("select count(*) from run_screenshots", [], |row| row - .get::<_, i64>(0)) - .unwrap(), - i64::from(keep_screenshot), - "{destination}" - ); - } - } - - #[test] - fn stale_screenshot_plan_preserves_a_late_published_orphan() { - let fixture = create_fixture(); - let writer = Connection::open(&fixture.database_path).unwrap(); - writer.execute_batch("pragma journal_mode = WAL;").unwrap(); - // Capture writes the PNG before publishing its row. A capture spanning - // midnight uses yesterday's folder (see docs/history-storage.md). - let relative = "2026-07-14/2026-07-14_23-59-59-999_final_run-late.png"; - let image = write_screenshot_file(&fixture.screenshots_dir, relative, b"late capture"); - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap(); - assert_eq!(plan.orphan_files, vec![image.clone()]); - - insert_screenshot( - &writer, - "late", - None, - 0, - relative, - "2026-07-14T23:59:59.999Z", - ); - drop(writer); - let result = super::execute_screenshot_cleanup_plan( - &fixture.database_path, - &fixture.data_root, - plan, - ) - .unwrap(); - - assert_eq!(result.deleted_files, 0); - assert_eq!(fs::read(image).unwrap(), b"late capture"); - } - - #[test] - fn stale_cleanup_plans_preserve_a_new_shared_screenshot_reference() { - for run_cleanup in [false, true] { - let fixture = create_fixture(); - let writer = Connection::open(&fixture.database_path).unwrap(); - writer.execute_batch("pragma journal_mode = WAL;").unwrap(); - insert_run( - &writer, - "old", - "completed", - "Normal", - "2026-06-01T00:00:00Z", - ); - let relative = "2026-06-01/shared.png"; - let image = write_screenshot_file(&fixture.screenshots_dir, relative, b"shared"); - insert_screenshot( - &writer, - "old", - Some("old"), - 0, - relative, - "2026-06-01T00:00:00Z", - ); - - let screenshot_plan = (!run_cleanup).then(|| { - plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap() - }); - let run_plan = run_cleanup.then(|| { - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None) - .unwrap() - }); - insert_screenshot(&writer, "new", None, 0, relative, "2026-06-01T00:00:00Z"); - drop(writer); - - let deleted_files = if let Some(plan) = screenshot_plan { - let result = super::execute_screenshot_cleanup_plan( - &fixture.database_path, - &fixture.data_root, - plan, - ) - .unwrap(); - assert_eq!(result.deleted_rows, 1); - result.deleted_files - } else { - let result = super::execute_run_data_cleanup_plan( - &fixture.database_path, - &fixture.data_root, - run_plan.unwrap(), - ) - .unwrap(); - assert_eq!(result.deleted_runs, 1); - result.deleted_files - }; - assert_eq!(deleted_files, 0, "run_cleanup={run_cleanup}"); - assert_eq!(fs::read(image).unwrap(), b"shared"); - let conn = Connection::open(&fixture.database_path).unwrap(); - assert_eq!( - conn.query_row("select screenshot_id from run_screenshots", [], |row| { - row.get::<_, String>(0) - }) - .unwrap(), - "new" - ); - } - } - - #[test] - fn cutoff_for_all_preset_is_none() { - let tz = FixedOffset::east_opt(8 * 3600).unwrap(); - let now = tz.with_ymd_and_hms(2026, 7, 15, 10, 0, 0).unwrap(); - assert!(CleanupCutoff::for_preset(StorageCleanupPreset::All, now).is_none()); - } - - #[test] - fn cutoff_older_than_7_days_subtracts_from_now() { - let tz = FixedOffset::east_opt(8 * 3600).unwrap(); - let now = tz.with_ymd_and_hms(2026, 7, 15, 10, 0, 0).unwrap(); - let cutoff = CleanupCutoff::for_preset(StorageCleanupPreset::OlderThan7Days, now).unwrap(); - assert_eq!( - cutoff.utc.to_rfc3339_opts(SecondsFormat::Secs, true), - "2026-07-08T02:00:00Z" - ); - assert_eq!( - cutoff.local_date, - NaiveDate::from_ymd_opt(2026, 7, 8).unwrap() - ); - } - - #[test] - fn cutoff_before_this_month_is_local_month_start_in_utc() { - let tz = FixedOffset::east_opt(8 * 3600).unwrap(); - let now = tz.with_ymd_and_hms(2026, 7, 15, 10, 0, 0).unwrap(); - let cutoff = CleanupCutoff::for_preset(StorageCleanupPreset::BeforeThisMonth, now).unwrap(); - // Local 2026-07-01T00:00:00+08:00 == 2026-06-30T16:00:00Z - assert_eq!( - cutoff.utc.to_rfc3339_opts(SecondsFormat::Secs, true), - "2026-06-30T16:00:00Z" - ); - assert_eq!( - cutoff.local_date, - NaiveDate::from_ymd_opt(2026, 7, 1).unwrap() - ); - } - - #[test] - fn screenshot_plan_protects_requested_primary_for_a_protected_run() { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-protected", - "completed", - "ranked", - "2026-06-16T10:00:00Z", - ); - conn.execute( - "update runs set bundle_screenshot_requested = 1 where run_id = 'run-protected'", - [], - ) - .unwrap(); - insert_screenshot( - &conn, - "shot-old", - None, - 0, - "2026-06-15/old.png", - "2026-06-15T10:00:00+00:00", - ); - insert_screenshot( - &conn, - "shot-protected", - Some("run-protected"), - 1, - "2026-06-16/protected.png", - "2026-06-16T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-new", - None, - 0, - "2026-07-02/new.png", - "2026-07-02T10:00:00Z", - ); - drop(conn); - - write_screenshot_file(&fixture.screenshots_dir, "2026-06-15/old.png", b"12345"); - - let cutoff = cutoff("2026-07-01T00:00:00Z", (2026, 7, 1)); - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - Some(&cutoff), - test_today(), - ) - .unwrap(); - - let item_ids = plan - .items - .iter() - .map(|item| item.screenshot_id.as_str()) - .collect::>(); - assert_eq!(item_ids, vec!["shot-old"]); - assert_eq!(plan.skipped_pending_uploads, 1); - assert_eq!(plan.estimated_bytes, 5); - } - - #[test] - fn stale_screenshot_plan_preserves_primary_when_run_becomes_protected() { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-race", - "completed", - "Ranked", - "2026-06-16T10:00:00Z", - ); - conn.execute( - "update runs set bundle_screenshot_requested = 1 where run_id = 'run-race'", - [], - ) - .unwrap(); - insert_outbox(&conn, "run-race", "pending"); - insert_screenshot( - &conn, - "shot-race", - Some("run-race"), - 1, - "2026-06-16/run-race.png", - "2026-06-16T10:00:00Z", - ); - drop(conn); - let screenshot_file = write_screenshot_file( - &fixture.screenshots_dir, - "2026-06-16/run-race.png", - b"screenshot", - ); - - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap(); - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].screenshot_id, "shot-race"); - assert_eq!(plan.skipped_pending_uploads, 0); - - let conn = Connection::open(&fixture.database_path).unwrap(); - conn.execute( - "update bundle_outbox set status = 'permanent_failure' where run_id = 'run-race'", - [], - ) - .unwrap(); - insert_seal_job(&conn, "run-race", "waiting"); - drop(conn); - - let result = super::execute_screenshot_cleanup_plan( - &fixture.database_path, - &fixture.data_root, - plan, - ) - .unwrap(); - - assert_eq!(result.deleted_rows, 0); - assert_eq!(result.deleted_files, 0); - assert_eq!(result.freed_bytes, 0); - assert!(screenshot_file.exists()); - - let conn = Connection::open(&fixture.database_path).unwrap(); - assert_eq!( - conn.query_row( - "select count(*) from run_screenshots where screenshot_id = 'shot-race'", - [], - |row| row.get::<_, i64>(0), - ) - .unwrap(), - 1 - ); - } - - #[test] - fn stale_screenshot_plan_preserves_shared_file_when_primary_becomes_protected() { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-race", - "completed", - "Ranked", - "2026-06-16T10:00:00Z", - ); - conn.execute( - "update runs set bundle_screenshot_requested = 1 where run_id = 'run-race'", - [], - ) - .unwrap(); - insert_outbox(&conn, "run-race", "pending"); - insert_screenshot( - &conn, - "shot-primary", - Some("run-race"), - 1, - "2026-06-16/shared.png", - "2026-06-16T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-sibling", - Some("run-race"), - 0, - "2026-06-16/shared.png", - "2026-06-16T10:01:00Z", - ); - drop(conn); - let shared_file = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-16/shared.png", b"shared"); - - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap(); - assert_eq!(plan.items.len(), 2); - assert!(plan.items.iter().all(|item| item.delete_image_file)); - - let conn = Connection::open(&fixture.database_path).unwrap(); - conn.execute( - "update bundle_outbox set status = 'permanent_failure' where run_id = 'run-race'", - [], - ) - .unwrap(); - insert_seal_job(&conn, "run-race", "waiting"); - drop(conn); - - let result = super::execute_screenshot_cleanup_plan( - &fixture.database_path, - &fixture.data_root, - plan, - ) - .unwrap(); - - assert_eq!(result.deleted_rows, 1); - assert_eq!(result.deleted_files, 0); - assert_eq!(result.freed_bytes, 0); - assert!(shared_file.exists()); - - let conn = Connection::open(&fixture.database_path).unwrap(); - let count = |screenshot_id: &str| -> i64 { - conn.query_row( - "select count(*) from run_screenshots where screenshot_id = ?1", - [screenshot_id], - |row| row.get(0), - ) - .unwrap() - }; - assert_eq!(count("shot-primary"), 1); - assert_eq!(count("shot-sibling"), 0); - } - - #[test] - fn screenshot_plan_deletes_non_primary_from_a_protected_run() { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-protected", - "completed", - "Ranked", - "2026-06-16T10:00:00Z", - ); - conn.execute( - "update runs set bundle_screenshot_requested = 1 where run_id = 'run-protected'", - [], - ) - .unwrap(); - insert_screenshot( - &conn, - "shot-non-primary", - Some("run-protected"), - 0, - "2026-06-16/non-primary.png", - "2026-06-16T10:00:00Z", - ); - drop(conn); - - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap(); - - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].screenshot_id, "shot-non-primary"); - assert_eq!(plan.skipped_pending_uploads, 0); - } - - #[test] - fn screenshot_plan_deletes_unrequested_primary_from_a_protected_run() { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-protected", - "completed", - "Ranked", - "2026-06-16T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-unrequested", - Some("run-protected"), - 1, - "2026-06-16/unrequested.png", - "2026-06-16T10:00:00Z", - ); - drop(conn); - - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap(); - - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].screenshot_id, "shot-unrequested"); - assert_eq!(plan.skipped_pending_uploads, 0); - } - - #[test] - fn plan_detects_orphan_files_only_in_qualifying_dated_folders() { - let fixture = create_fixture(); - let conn = Connection::open(&fixture.database_path).unwrap(); - insert_screenshot( - &conn, - "shot-kept", - None, - 0, - "2026-06-15\\kept.png", - "2026-07-02T10:00:00Z", - ); - drop(conn); - - let _kept = write_screenshot_file(&fixture.screenshots_dir, "2026-06-15/kept.png", b"kept"); - let orphan = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-15/orphan.png", b"orphan"); - let _nested_user_file = write_screenshot_file( - &fixture.screenshots_dir, - "2026-06-15/nested/user-file.txt", - b"user", - ); - let _recent_orphan = write_screenshot_file( - &fixture.screenshots_dir, - "2026-07-02/recent-orphan.png", - b"recent", - ); - let _mod_owned_cache = write_screenshot_file( - &fixture.screenshots_dir, - "UploadCache/shot-gone.png", - b"gone", - ); - let _mod_owned_extensionless_cache = - write_screenshot_file(&fixture.screenshots_dir, "UploadCache/shot-extra", b"extra"); - let _kept_cache = write_screenshot_file( - &fixture.screenshots_dir, - "UploadCache/shot-kept.jpg", - b"kept", - ); - - let cutoff = cutoff("2026-07-01T00:00:00Z", (2026, 7, 1)); - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - Some(&cutoff), - test_today(), - ) - .unwrap(); - - assert!(plan.items.is_empty()); - assert_eq!(plan.orphan_files, vec![orphan]); - } - - #[test] - fn plan_all_preset_skips_todays_and_future_local_folders() { - // Under preset `all` (cutoff `None`) the orphan sweep must still protect - // today's local-date folder: the mod writes a screenshot's PNG (and a - // transient `.png..tmp`) to disk BEFORE inserting its - // run_screenshots row, so a just-captured file in today's folder has no - // row yet and must not be classified as an orphan. - let fixture = create_fixture(); - let today = NaiveDate::from_ymd_opt(2026, 7, 3).unwrap(); - - let past_orphan = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-15/past.png", b"stale"); - // Today's in-flight capture: the final PNG and its atomic temp sibling. - let _today_png = write_screenshot_file( - &fixture.screenshots_dir, - "2026-07-03/2026-07-03_14-32-15-427_final_run-abc.png", - b"live", - ); - let _today_tmp = write_screenshot_file( - &fixture.screenshots_dir, - "2026-07-03/2026-07-03_14-32-15-427_final_run-abc.png.deadbeef.tmp", - b"tmp", - ); - // A future-dated folder (installer clock behind the mod's) is protected too. - let _future = - write_screenshot_file(&fixture.screenshots_dir, "2026-07-04/ahead.png", b"ahead"); - - let plan = plan_screenshot_cleanup(&fixture.database_path, &fixture.data_root, None, today) - .unwrap(); - - assert!(plan.items.is_empty()); - assert_eq!( - plan.orphan_files, - vec![past_orphan], - "only the past-day folder is swept; today and future are protected" - ); - assert_eq!(plan.estimated_bytes, 5); - } - - #[test] - fn execute_all_preset_keeps_todays_inflight_files() { - let fixture = create_fixture(); - let today = NaiveDate::from_ymd_opt(2026, 7, 3).unwrap(); - - let past_orphan = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-15/past.png", b"stale"); - let today_png = write_screenshot_file( - &fixture.screenshots_dir, - "2026-07-03/2026-07-03_14-32-15-427_final_run-abc.png", - b"live", - ); - let today_tmp = write_screenshot_file( - &fixture.screenshots_dir, - "2026-07-03/2026-07-03_14-32-15-427_final_run-abc.png.deadbeef.tmp", - b"tmp", - ); - - let result = super::execute_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, // preset "all" - today, - ) - .unwrap(); - - assert_eq!( - result.deleted_files, 1, - "only the past-day orphan is deleted" - ); - assert_eq!(result.freed_bytes, 5); - assert!(!past_orphan.exists()); - assert!( - today_png.exists(), - "a just-captured file with no row yet must survive" - ); - assert!( - today_tmp.exists(), - "the atomic .tmp sibling must survive too" - ); - assert!(fixture.screenshots_dir.join("2026-07-03").exists()); - assert!(!fixture.screenshots_dir.join("2026-06-15").exists()); - } - - #[test] - fn plan_skips_screenshot_root_read_errors() { - let fixture = create_fixture(); - fs::remove_dir(&fixture.screenshots_dir).unwrap(); - fs::write(&fixture.screenshots_dir, b"not a directory").unwrap(); - - let cutoff = cutoff("2026-07-01T00:00:00Z", (2026, 7, 1)); - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - Some(&cutoff), - test_today(), - ) - .unwrap(); - - assert!(plan.items.is_empty()); - assert!(plan.orphan_files.is_empty()); - assert_eq!(plan.estimated_bytes, 0); - } - - #[test] - fn plan_ignores_mod_owned_upload_cache() { - let fixture = create_fixture(); - let orphan = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-15/orphan.png", b"orphan"); - fs::write( - fixture.screenshots_dir.join("UploadCache"), - b"not a directory", - ) - .unwrap(); - - let cutoff = cutoff("2026-07-01T00:00:00Z", (2026, 7, 1)); - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - Some(&cutoff), - test_today(), - ) - .unwrap(); - - assert_eq!(plan.orphan_files, vec![orphan]); - } - - #[test] - fn plan_on_missing_database_is_empty() { - let temp_dir = TempDir::new().unwrap(); - let data_root = temp_dir.path().join(crate::config::BAZAAR_DATA_DIRECTORY); - let database_path = data_root.join("bazaarplusplus.db"); - - let plan = plan_screenshot_cleanup(&database_path, &data_root, None, test_today()).unwrap(); - - assert!(plan.items.is_empty()); - assert!(plan.orphan_files.is_empty()); - assert_eq!(plan.estimated_bytes, 0); - } - - #[test] - fn plan_rejects_a_database_without_the_supported_schema_version() { - let temp_dir = TempDir::new().unwrap(); - let game_path = temp_dir.path().to_path_buf(); - let data_dir = game_path.join(crate::config::BAZAAR_DATA_DIRECTORY); - let database_path = data_dir.join("bazaarplusplus.db"); - fs::create_dir_all(&data_dir).unwrap(); - drop(Connection::open(&database_path).unwrap()); - - let error = - plan_screenshot_cleanup(&database_path, &data_dir, None, test_today()).unwrap_err(); - - assert!(error.contains("found=0"), "{error}"); - let supported = format!( - "supported={}", - crate::config::supported_mod_db_user_versions_label() - ); - assert!(error.contains(&supported), "{error}"); - } - - /// Cases owned by the mod's `BundleQueueStore.SealEligibleRunCondition`. The mod evaluates - /// the same file against its seal-job and replay-maintenance queries, so a rule change on - /// either side fails a gate until both agree. - const SEAL_ELIGIBILITY_FIXTURE: &str = include_str!( - "../../../../bazaarplusplus-mod/tests/BundleQueueSqliteStore.Tests/fixtures/bundle-seal-eligibility.json" - ); - - #[test] - fn run_plan_protects_exactly_the_shared_seal_eligibility_cases() { - let shared: serde_json::Value = serde_json::from_str(SEAL_ELIGIBILITY_FIXTURE).unwrap(); - assert_eq!(shared["formatVersion"], 2); - let cases = shared["cases"].as_array().unwrap(); - assert!(!cases.is_empty()); - - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - for case in cases { - let run_id = case["name"].as_str().unwrap(); - let run = &case["run"]; - conn.execute( - "insert into runs ( - run_id, started_at_ms, last_seen_at_ms, status, hero, - game_mode, ended_at_ms, build_channel, upload_policy - ) values (?1, ?2, ?2, ?3, 'Vanessa', ?4, ?2, ?5, ?6)", - rusqlite::params![ - run_id, - ms("2026-06-10T10:00:00Z"), - run["status"].as_str().unwrap(), - run["gameMode"].as_str().unwrap(), - run["buildChannel"].as_str(), - run["uploadPolicy"].as_str().unwrap(), - ], - ) - .unwrap(); - for outbox in case["outbox"].as_array().unwrap() { - insert_outbox(&conn, run_id, outbox["status"].as_str().unwrap()); - } - if let Some(job) = case["sealJob"].as_object() { - conn.execute( - "insert into bundle_seal_jobs ( - run_id, state, screenshot_requested, screenshot_state, - input_deadline_at_ms, last_error_code - ) values (?1, ?2, 0, 'not_requested', 1781085900000, ?3)", - rusqlite::params![ - run_id, - job["state"].as_str().unwrap(), - job["lastErrorCode"].as_str(), - ], - ) - .unwrap(); - } - } - drop(conn); - - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - - let planned = plan - .items - .iter() - .map(|item| item.run_id.as_str()) - .collect::>(); - let mut protected_count = 0; - for case in cases { - let run_id = case["name"].as_str().unwrap(); - let expected = case["expected"]["protectedFromCleanup"].as_bool().unwrap(); - assert_eq!( - !planned.contains(run_id), - expected, - "{run_id}: protectedFromCleanup" - ); - protected_count += i64::from(expected); - } - assert_eq!(plan.skipped_pending_uploads, protected_count); - } - - #[test] - fn run_plan_skips_active_runs_without_counting_them_as_pending() { - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run(&conn, "active", "active", "Ranked", "2026-06-10T10:00:00Z"); - drop(conn); - - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - - assert!(plan.items.is_empty()); - assert_eq!(plan.skipped_pending_uploads, 0); - } - - #[test] - fn stale_run_plan_preserves_all_reseal_inputs_when_run_becomes_protected() { - let fixture = create_fixture(); - let videos_dir = crate::services::paths::combat_replay_videos_dir_in(&fixture.data_root); - let replays_dir = crate::services::paths::combat_replays_dir_in(&fixture.data_root); - fs::create_dir_all(videos_dir.join("2026-06-10")).unwrap(); - fs::create_dir_all(&replays_dir).unwrap(); - let video_file = videos_dir.join("2026-06-10/run-race.mp4"); - let replay_file = replays_dir.join("battle-race.payload.mpack.gz"); - let screenshot_file = write_screenshot_file( - &fixture.screenshots_dir, - "2026-06-10/run-race.png", - b"screenshot", - ); - fs::write(&video_file, b"video").unwrap(); - fs::write(&replay_file, b"replay").unwrap(); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-race", - "completed", - "Ranked", - "2026-06-10T10:00:00Z", - ); - insert_outbox(&conn, "run-race", "pending"); - insert_battle( - &conn, - "battle-race", - "LOCAL", - Some("run-race"), - "2026-06-10T09:00:00Z", - Some("ready"), - ); - insert_video( - &conn, - "video-race", - "battle-race", - "2026-06-10/run-race.mp4", - "2026-06-10T09:05:00Z", - ); - insert_screenshot( - &conn, - "shot-race", - Some("run-race"), - 1, - "2026-06-10/run-race.png", - "2026-06-10T10:00:00Z", - ); - drop(conn); - - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].run_id, "run-race"); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - conn.execute( - "update bundle_outbox set status = 'permanent_failure' where run_id = 'run-race'", - [], - ) - .unwrap(); - insert_seal_job(&conn, "run-race", "waiting"); - drop(conn); - - let result = - super::execute_run_data_cleanup_plan(&fixture.database_path, &fixture.data_root, plan) - .unwrap(); - - assert_eq!(result.deleted_runs, 0); - assert_eq!(result.deleted_files, 0); - assert_eq!(result.freed_bytes, 0); - assert!(video_file.exists()); - assert!(replay_file.exists()); - assert!(screenshot_file.exists()); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - let count = |sql: &str| -> i64 { conn.query_row(sql, [], |row| row.get(0)).unwrap() }; - assert_eq!( - count("select count(*) from runs where run_id = 'run-race'"), - 1 - ); - assert_eq!( - count("select count(*) from combat_replay_videos where video_id = 'video-race'"), - 1 - ); - assert_eq!( - count("select count(*) from run_screenshots where screenshot_id = 'shot-race'"), - 1 - ); - } - - #[test] - fn stale_run_plan_preserves_shared_files_when_one_run_becomes_protected() { - let fixture = create_fixture(); - let videos_dir = crate::services::paths::combat_replay_videos_dir_in(&fixture.data_root); - fs::create_dir_all(videos_dir.join("2026-06-10")).unwrap(); - let shared_video = videos_dir.join("2026-06-10/shared.mp4"); - let shared_screenshot = write_screenshot_file( - &fixture.screenshots_dir, - "2026-06-10/shared.png", - b"shared-screenshot", - ); - fs::write(&shared_video, b"shared-video").unwrap(); - - let conn = Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-a", - "completed", - "Normal", - "2026-06-10T10:00:00Z", - ); - insert_run( - &conn, - "run-b", - "completed", - "Ranked", - "2026-06-10T10:01:00Z", - ); - insert_outbox(&conn, "run-b", "pending"); - insert_battle( - &conn, - "battle-a", - "LOCAL", - Some("run-a"), - "2026-06-10T09:00:00Z", - Some("missing"), - ); - insert_battle( - &conn, - "battle-b", - "LOCAL", - Some("run-b"), - "2026-06-10T09:01:00Z", - Some("missing"), - ); - insert_video( - &conn, - "video-a", - "battle-a", - "2026-06-10/shared.mp4", - "2026-06-10T09:05:00Z", - ); - insert_video( - &conn, - "video-b", - "battle-b", - "2026-06-10/shared.mp4", - "2026-06-10T09:06:00Z", - ); - insert_screenshot( - &conn, - "shot-a", - Some("run-a"), - 0, - "2026-06-10/shared.png", - "2026-06-10T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-b", - Some("run-b"), - 0, - "2026-06-10/shared.png", - "2026-06-10T10:01:00Z", - ); - drop(conn); - - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - assert_eq!(plan.items.len(), 2); - assert!(plan - .items - .iter() - .all(|item| item.screenshots[0].delete_image_file)); - assert!(plan - .items - .iter() - .all(|item| item.videos[0].delete_video_file)); - - let conn = Connection::open(&fixture.database_path).unwrap(); - conn.execute( - "update bundle_outbox set status = 'permanent_failure' where run_id = 'run-b'", - [], - ) - .unwrap(); - insert_seal_job(&conn, "run-b", "waiting"); - drop(conn); - - let result = - super::execute_run_data_cleanup_plan(&fixture.database_path, &fixture.data_root, plan) - .unwrap(); - - assert_eq!(result.deleted_runs, 1); - assert_eq!(result.deleted_files, 0); - assert_eq!(result.freed_bytes, 0); - assert!(shared_video.exists()); - assert!(shared_screenshot.exists()); - - let conn = Connection::open(&fixture.database_path).unwrap(); - let count = |sql: &str| -> i64 { conn.query_row(sql, [], |row| row.get(0)).unwrap() }; - assert_eq!(count("select count(*) from runs where run_id = 'run-a'"), 0); - assert_eq!(count("select count(*) from runs where run_id = 'run-b'"), 1); - assert_eq!( - count("select count(*) from run_screenshots where screenshot_id = 'shot-a'"), - 0 - ); - assert_eq!( - count("select count(*) from run_screenshots where screenshot_id = 'shot-b'"), - 1 - ); - assert_eq!( - count("select count(*) from combat_replay_videos where video_id = 'video-a'"), - 0 - ); - assert_eq!( - count("select count(*) from combat_replay_videos where video_id = 'video-b'"), - 1 - ); - } - - #[test] - fn seal_job_presence_does_not_protect_a_run_unless_it_is_terminal_failure() { - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-sealing", - "completed", - "Normal", - "2026-06-10T10:00:00Z", - ); - insert_seal_job(&conn, "run-sealing", "sealing"); - drop(conn); - - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].run_id, "run-sealing"); - assert_eq!(plan.skipped_pending_uploads, 0); - } - - #[test] - fn run_plan_preserves_shared_screenshot_file_referenced_by_skipped_run() { - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-clean", - "completed", - "Normal", - "2026-06-10T10:00:00Z", - ); - insert_run( - &conn, - "run-shot-pending", - "completed", - "Ranked", - "2026-06-10T10:05:00Z", - ); - insert_screenshot( - &conn, - "shot-clean", - Some("run-clean"), - 0, - "2026-06-10\\shared.png", - "2026-06-10T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-pending", - Some("run-shot-pending"), - 0, - "2026-06-10/shared.png", - "2026-06-10T10:05:00Z", - ); - drop(conn); - write_screenshot_file(&fixture.screenshots_dir, "2026-06-10/shared.png", b"shared"); - - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].run_id, "run-clean"); - assert_eq!(plan.items[0].screenshots.len(), 1); - assert_eq!(plan.items[0].screenshots[0].screenshot_id, "shot-clean"); - assert!( - !plan.items[0].screenshots[0].delete_image_file, - "pending run still references the normalized screenshot path" - ); - assert_eq!(plan.estimated_bytes, 0); - assert_eq!(plan.skipped_pending_uploads, 1); - } - - #[test] - fn run_cleanup_preserves_shared_video_file_referenced_by_skipped_run() { - let fixture = create_fixture(); - let videos_dir = crate::services::paths::combat_replay_videos_dir_in(&fixture.data_root); - fs::create_dir_all(videos_dir.join("2026-06-10")).unwrap(); - let shared_video = videos_dir.join("2026-06-10/shared.mp4"); - fs::write(&shared_video, b"shared-video").unwrap(); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-clean", - "completed", - "Normal", - "2026-06-10T10:00:00Z", - ); - insert_run( - &conn, - "run-shot-pending", - "completed", - "Ranked", - "2026-06-10T10:05:00Z", - ); - insert_battle( - &conn, - "battle-clean", - "LOCAL", - Some("run-clean"), - "2026-06-10T09:00:00Z", - Some("missing"), - ); - insert_battle( - &conn, - "battle-pending", - "LOCAL", - Some("run-shot-pending"), - "2026-06-10T09:05:00Z", - Some("missing"), - ); - insert_video( - &conn, - "video-clean", - "battle-clean", - "2026-06-10\\shared.mp4", - "2026-06-10T09:01:00Z", - ); - insert_video( - &conn, - "video-pending", - "battle-pending", - "2026-06-10/shared.mp4", - "2026-06-10T09:06:00Z", - ); - insert_screenshot( - &conn, - "shot-pending", - Some("run-shot-pending"), - 0, - "2026-06-10/pending.png", - "2026-06-10T10:05:00Z", - ); - drop(conn); - - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].run_id, "run-clean"); - assert_eq!(plan.items[0].videos.len(), 1); - assert_eq!(plan.items[0].videos[0].video_id, "video-clean"); - assert_eq!( - plan.estimated_bytes, 0, - "skipped run still references the normalized video path" - ); - - let result = - super::execute_run_data_cleanup(&fixture.database_path, &fixture.data_root, None) - .unwrap(); - - assert_eq!(result.deleted_runs, 1); - assert_eq!(result.deleted_files, 0); - assert_eq!(result.freed_bytes, 0); - assert!(shared_video.exists(), "skipped run must keep shared video"); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - let count = |sql: &str| -> i64 { conn.query_row(sql, [], |row| row.get(0)).unwrap() }; - assert_eq!( - count("select count(*) from combat_replay_videos where video_id = 'video-clean'"), - 0 - ); - assert_eq!( - count("select count(*) from combat_replay_videos where video_id = 'video-pending'"), - 1 - ); - } - - #[test] - fn run_plan_estimates_run_owned_files_with_safe_paths() { - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-files", - "completed", - "Normal", - "2026-06-10T10:00:00Z", - ); - insert_battle( - &conn, - "battle-files", - "LOCAL", - Some("run-files"), - "2026-06-10T09:00:00Z", - Some("ready"), - ); - insert_battle( - &conn, - "../battle-escape", - "LOCAL", - Some("run-files"), - "2026-06-10T09:30:00Z", - Some("ready"), - ); - insert_video( - &conn, - "video-safe", - "battle-files", - "2026-06-10/video.mp4", - "2026-06-10T09:05:00Z", - ); - insert_video( - &conn, - "video-absolute", - "battle-files", - "/tmp/outside.mp4", - "2026-06-10T09:06:00Z", - ); - insert_screenshot( - &conn, - "shot-files", - Some("run-files"), - 0, - "2026-06-10/shot.png", - "2026-06-10T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-absolute", - Some("run-files"), - 0, - "/tmp/outside.png", - "2026-06-10T10:01:00Z", - ); - drop(conn); - - let videos_dir = crate::services::paths::combat_replay_videos_dir_in(&fixture.data_root); - let replays_dir = crate::services::paths::combat_replays_dir_in(&fixture.data_root); - fs::create_dir_all(videos_dir.join("2026-06-10")).unwrap(); - fs::create_dir_all(&replays_dir).unwrap(); - fs::write(videos_dir.join("2026-06-10/video.mp4"), b"video").unwrap(); - fs::write( - replays_dir.join("battle-files.payload.mpack.gz"), - b"payload", - ) - .unwrap(); - write_screenshot_file(&fixture.screenshots_dir, "2026-06-10/shot.png", b"shot"); - - let plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - - assert_eq!(plan.items.len(), 1); - assert_eq!( - plan.items[0].battle_ids, - vec!["../battle-escape", "battle-files"] - ); - assert_eq!(plan.items[0].videos.len(), 2); - assert_eq!(plan.items[0].screenshots.len(), 2); - assert_eq!(plan.estimated_bytes, 5 + 7 + 4); - } - - #[test] - fn run_plan_resolves_per_run_files_symmetrically_against_another_data_root() { - let fixture = create_fixture(); - let other_temp_dir = TempDir::new().unwrap(); - let other_root = other_temp_dir - .path() - .join(crate::config::BAZAAR_DATA_DIRECTORY); - - let conn = Connection::open(&fixture.database_path).unwrap(); - // A seal-eligible Ranked run with no Bundle yet is protected. - for (run_id, game_mode, ended_at) in [ - ("run-a", "Normal", "2026-06-10T10:00:00Z"), - ("run-b", "Normal", "2026-06-10T10:01:00Z"), - ("run-protected", "Ranked", "2026-06-10T10:02:00Z"), - ] { - insert_run(&conn, run_id, "completed", game_mode, ended_at); - } - for (battle_id, run_id) in [ - ("battle-a", "run-a"), - ("battle-b", "run-b"), - ("battle-protected", "run-protected"), - ] { - insert_battle( - &conn, - battle_id, - "LOCAL", - Some(run_id), - "2026-06-10T09:00:00Z", - Some("ready"), - ); - } - // run-a and run-b share one screenshot file; run-a shares its video - // with the protected run, so that video file must survive. - insert_video( - &conn, - "video-a", - "battle-a", - "2026-06-10/shared.mp4", - "2026-06-10T09:05:00Z", - ); - insert_video( - &conn, - "video-protected", - "battle-protected", - "2026-06-10/shared.mp4", - "2026-06-10T09:06:00Z", - ); - insert_video( - &conn, - "video-b", - "battle-b", - "2026-06-10/b.mp4", - "2026-06-10T09:07:00Z", - ); - insert_screenshot( - &conn, - "shot-a", - Some("run-a"), - 0, - "2026-06-10/shared.png", - "2026-06-10T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-b", - Some("run-b"), - 0, - "2026-06-10/shared.png", - "2026-06-10T10:01:00Z", - ); - drop(conn); - - let write_files = |data_root: &Path| -> Vec { - let videos_dir = crate::services::paths::combat_replay_videos_dir_in(data_root); - let replays_dir = crate::services::paths::combat_replays_dir_in(data_root); - let screenshots_dir = crate::services::paths::screenshots_dir_in(data_root); - fs::create_dir_all(videos_dir.join("2026-06-10")).unwrap(); - fs::create_dir_all(&replays_dir).unwrap(); - let files = vec![ - ( - videos_dir.join("2026-06-10/shared.mp4"), - &b"shared-video"[..], - ), - (videos_dir.join("2026-06-10/b.mp4"), &b"b-video"[..]), - ( - replays_dir.join("battle-a.payload.mpack.gz"), - &b"payload-a"[..], - ), - ( - replays_dir.join("battle-b.payload.mpack.gz"), - &b"payload-b"[..], - ), - ( - write_screenshot_file(&screenshots_dir, "2026-06-10/shared.png", b"shot"), - &b"shot"[..], - ), - ]; - for (path, bytes) in &files { - fs::write(path, bytes).unwrap(); - } - files.into_iter().map(|(path, _)| path).collect() - }; - let current_files = write_files(&fixture.data_root); - let other_files = write_files(&other_root); - - type Projection = Vec<( - String, - Vec, - Vec<(String, String, bool)>, - Vec<(String, String, bool)>, - )>; - let project = |plan: &super::RunDataCleanupPlan| -> Projection { - plan.items - .iter() - .map(|item| { - ( - item.run_id.clone(), - item.battle_ids.clone(), - item.videos - .iter() - .map(|video| { - ( - video.video_id.clone(), - video.relative_path.clone(), - video.delete_video_file, - ) - }) - .collect(), - item.screenshots - .iter() - .map(|shot| { - ( - shot.screenshot_id.clone(), - shot.image_relative_path.clone(), - shot.delete_image_file, - ) - }) - .collect(), - ) - }) - .collect() - }; - - let current_plan = - super::plan_run_data_cleanup(&fixture.database_path, &fixture.data_root, None).unwrap(); - let other_plan = - super::plan_run_data_cleanup(&fixture.database_path, &other_root, None).unwrap(); - - assert_eq!(project(&other_plan), project(¤t_plan)); - assert_eq!( - other_plan.skipped_pending_uploads, - current_plan.skipped_pending_uploads - ); - // b.mp4 + both payloads + the shared screenshot counted once; the - // video shared with the protected run is not counted. - assert_eq!(current_plan.estimated_bytes, 7 + 9 + 9 + 4); - assert_eq!(other_plan.estimated_bytes, current_plan.estimated_bytes); - - let result = - super::execute_run_data_cleanup_plan(&fixture.database_path, &other_root, other_plan) - .unwrap(); - - assert_eq!(result.deleted_runs, 2); - assert_eq!(result.deleted_files, 4); - assert_eq!(result.freed_bytes, 7 + 9 + 9 + 4); - // Only the other root's run-owned files went; the shared video stays, - // and the current root is untouched. - let [other_shared_video, other_rest @ ..] = other_files.as_slice() else { - unreachable!(); - }; - assert!(other_shared_video.exists()); - assert!(other_rest.iter().all(|path| !path.exists())); - assert!(current_files.iter().all(|path| path.exists())); - } - - #[test] - fn execute_run_cleanup_cascades_rows_deletes_files_and_spares_ghosts() { - let fixture = create_fixture(); - let data_dir = fixture.data_root.clone(); - let videos_dir = data_dir.join("CombatReplayVideos"); - let replays_dir = data_dir.join("CombatReplays"); - fs::create_dir_all(videos_dir.join("2026-06-10")).unwrap(); - fs::create_dir_all(&replays_dir).unwrap(); - fs::write(videos_dir.join("2026-06-10/v1.mp4"), b"vvvv").unwrap(); - fs::write(replays_dir.join("battle-1.payload.mpack.gz"), b"ppp").unwrap(); - let ghost_payload = replays_dir.join("battle-ghost.payload.mpack.gz"); - fs::write(&ghost_payload, b"gg").unwrap(); - let shot_file = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-10/shot.png", b"ss"); - let shared_shot = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-10/shared.png", b"shared"); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-1", - "completed", - "Normal", - "2026-06-10T10:00:00Z", - ); - insert_run( - &conn, - "run-pending", - "completed", - "Ranked", - "2026-06-10T10:05:00Z", - ); - conn.execute_batch( - " - insert into run_events (run_id, seq, ts_at_ms, kind, payload_json) - values ('run-1', 1, 1781082000000, 'test', '{}'); - ", - ) - .unwrap(); - insert_battle( - &conn, - "battle-1", - "LOCAL", - Some("run-1"), - "2026-06-10T09:00:00Z", - Some("ready"), - ); - insert_battle( - &conn, - "battle-ghost", - "GHOST", - None, - "2026-06-10T09:00:00Z", - None, - ); - conn.execute_batch( - "insert into battle_snapshots ( - battle_id, player_hand_json, player_skills_json, opponent_hand_json, - opponent_skills_json - ) values ('battle-1', '[]', '[]', '[]', '[]');", - ) - .unwrap(); - insert_video( - &conn, - "video-1", - "battle-1", - "2026-06-10/v1.mp4", - "2026-06-10T09:05:00Z", - ); - insert_screenshot( - &conn, - "shot-1", - Some("run-1"), - 0, - "2026-06-10/shot.png", - "2026-06-10T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-shared", - Some("run-1"), - 0, - "2026-06-10\\shared.png", - "2026-06-10T10:01:00Z", - ); - insert_screenshot( - &conn, - "shot-pending", - Some("run-pending"), - 0, - "2026-06-10/shared.png", - "2026-06-10T10:05:00Z", - ); - insert_seal_job(&conn, "run-1", "waiting"); - insert_outbox(&conn, "run-1", "pending"); - drop(conn); - - let result = - super::execute_run_data_cleanup(&fixture.database_path, &fixture.data_root, None) - .unwrap(); - - assert_eq!(result.deleted_runs, 1); - // v1.mp4 + battle-1 payload + shot.png; shared.png stays for the pending run. - assert_eq!(result.deleted_files, 3); - assert_eq!(result.freed_bytes, 4 + 3 + 2); - assert_eq!(result.skipped_pending_uploads, 1); - - assert!(!videos_dir.join("2026-06-10/v1.mp4").exists()); - assert!(!replays_dir.join("battle-1.payload.mpack.gz").exists()); - assert!(!shot_file.exists()); - assert!( - shared_shot.exists(), - "pending run must keep shared screenshot" - ); - assert!(ghost_payload.exists(), "ghost payloads are never touched"); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - let count = |sql: &str| -> i64 { conn.query_row(sql, [], |row| row.get(0)).unwrap() }; - assert_eq!(count("select count(*) from runs where run_id = 'run-1'"), 0); - assert_eq!( - count("select count(*) from run_events where run_id = 'run-1'"), - 0, - "cascade" - ); - assert_eq!( - count("select count(*) from battle_snapshots where battle_id = 'battle-1'"), - 0, - "cascade" - ); - assert_eq!( - count("select count(*) from bundle_seal_jobs where run_id = 'run-1'"), - 0, - "cascade" - ); - assert_eq!( - count("select count(*) from run_screenshots where run_id = 'run-1'"), - 0 - ); - assert_eq!( - count("select count(*) from bundle_outbox where run_id = 'run-1'"), - 1, - "BundleOutbox is mod-owned and has no runs foreign key" - ); - assert_eq!(count("select count(*) from combat_replay_videos"), 0); - assert_eq!( - count("select count(*) from battles where source = 'GHOST'"), - 1, - "ghost battle survives" - ); - assert_eq!( - count("select count(*) from runs where run_id = 'run-pending'"), - 1 - ); - assert_eq!( - count("select count(*) from run_screenshots where screenshot_id = 'shot-pending'"), - 1 - ); - } - - #[test] - fn execute_run_cleanup_fails_before_file_deletion_when_battles_lacks_run_cascade() { - let temp_dir = TempDir::new().unwrap(); - let game_path = temp_dir.path().to_path_buf(); - let data_dir = game_path.join(crate::config::BAZAAR_DATA_DIRECTORY); - let database_path = data_dir.join("bazaarplusplus.db"); - let videos_dir = data_dir.join("CombatReplayVideos"); - let replays_dir = data_dir.join("CombatReplays"); - fs::create_dir_all(videos_dir.join("2026-06-10")).unwrap(); - fs::create_dir_all(&replays_dir).unwrap(); - let video_file = videos_dir.join("2026-06-10/v1.mp4"); - let replay_file = replays_dir.join("battle-1.payload.mpack.gz"); - fs::write(&video_file, b"video").unwrap(); - fs::write(&replay_file, b"replay").unwrap(); - - let conn = rusqlite::Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - // A deliberate mutation of the mod schema, not a copy of it: `battles` - // without the `run_id` cascade the cleanup guard requires. - conn.execute_batch( - " - pragma foreign_keys = off; - drop table battles; - create table battles ( - battle_id text primary key, - source text not null, - run_id text null, - recorded_at_ms integer not null, - combat_kind text not null default 'PVP', - deleted_at_ms integer null - ); - ", - ) - .unwrap(); - insert_run( - &conn, - "run-legacy", - "completed", - "Normal", - "2026-06-10T10:00:00Z", - ); - // Not `insert_battle`: this test replaced `battles` with the legacy - // shape that has no local-payload columns. - conn.execute_batch( - "insert into battles (battle_id, source, run_id, recorded_at_ms) - values ('battle-1', 'LOCAL', 'run-legacy', 1781082000000);", - ) - .unwrap(); - insert_video( - &conn, - "video-1", - "battle-1", - "2026-06-10/v1.mp4", - "2026-06-10T09:05:00Z", - ); - drop(conn); - - let error = super::execute_run_data_cleanup(&database_path, &data_dir, None).unwrap_err(); - - assert!( - error.contains("battles.run_id") && error.contains("ON DELETE CASCADE"), - "{error}" - ); - assert!( - video_file.exists(), - "validation must happen before video deletion" - ); - assert!( - replay_file.exists(), - "validation must happen before replay deletion" - ); - - let conn = rusqlite::Connection::open(&database_path).unwrap(); - let count = |sql: &str| -> i64 { conn.query_row(sql, [], |row| row.get(0)).unwrap() }; - assert_eq!( - count("select count(*) from runs where run_id = 'run-legacy'"), - 1 - ); - assert_eq!( - count("select count(*) from battles where battle_id = 'battle-1'"), - 1 - ); - assert_eq!( - count("select count(*) from combat_replay_videos where video_id = 'video-1'"), - 1 - ); - } - - #[test] - fn execute_deletes_rows_and_orphans_but_leaves_mod_owned_cache() { - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-protected", - "completed", - "Ranked", - "2026-06-16T10:00:00Z", - ); - conn.execute( - "update runs set bundle_screenshot_requested = 1 where run_id = 'run-protected'", - [], - ) - .unwrap(); - insert_screenshot( - &conn, - "shot-old", - None, - 0, - "2026-06-15/old.png", - "2026-06-15T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-protected", - Some("run-protected"), - 1, - "2026-06-16/pending.png", - "2026-06-16T10:00:00Z", - ); - drop(conn); - let old_file = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-15/old.png", b"12345"); - let pending_file = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-16/pending.png", b"p"); - let orphan = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-14/orphan.png", b"ooo"); - let cache = - write_screenshot_file(&fixture.screenshots_dir, "UploadCache/shot-old.png", b"cc"); - - let result = super::execute_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, // preset "all" - test_today(), - ) - .unwrap(); - - assert_eq!(result.deleted_rows, 1); - assert_eq!(result.deleted_files, 2); - assert_eq!(result.freed_bytes, 5 + 3); - assert_eq!(result.skipped_pending_uploads, 1); - - assert!(!old_file.exists()); - assert!(!orphan.exists()); - assert!(cache.exists(), "mod-owned cache must not be swept"); - assert!( - pending_file.exists(), - "protected primary screenshot must survive" - ); - // Emptied dated folders are removed; the pending one stays. - assert!(!fixture.screenshots_dir.join("2026-06-15").exists()); - assert!(!fixture.screenshots_dir.join("2026-06-14").exists()); - assert!(fixture.screenshots_dir.join("2026-06-16").exists()); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - let rows: i64 = conn - .query_row("select count(*) from run_screenshots", [], |row| row.get(0)) - .unwrap(); - assert_eq!(rows, 1); - } - - #[test] - fn execute_preserves_shared_file_referenced_by_a_protected_primary_screenshot() { - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_run( - &conn, - "run-protected", - "completed", - "Ranked", - "2026-06-15T10:05:00Z", - ); - conn.execute( - "update runs set bundle_screenshot_requested = 1 where run_id = 'run-protected'", - [], - ) - .unwrap(); - insert_screenshot( - &conn, - "shot-old", - None, - 0, - "2026-06-15/shared.png", - "2026-06-15T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-protected", - Some("run-protected"), - 1, - "2026-06-15/shared.png", - "2026-06-15T10:05:00Z", - ); - drop(conn); - let shared_file = - write_screenshot_file(&fixture.screenshots_dir, "2026-06-15/shared.png", b"shared"); - - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap(); - - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].screenshot_id, "shot-old"); - assert_eq!(plan.estimated_bytes, 0); - - let result = super::execute_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, // preset "all" - test_today(), - ) - .unwrap(); - - assert_eq!(result.deleted_rows, 1); - assert_eq!(result.deleted_files, 0); - assert_eq!(result.freed_bytes, 0); - assert_eq!(result.skipped_pending_uploads, 1); - assert!( - shared_file.exists(), - "protected screenshot must keep shared file" - ); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - let old_rows: i64 = conn - .query_row( - "select count(*) from run_screenshots where screenshot_id = 'shot-old'", - [], - |row| row.get(0), - ) - .unwrap(); - assert_eq!(old_rows, 0); - let protected_rows: i64 = conn - .query_row( - "select count(*) from run_screenshots where screenshot_id = 'shot-protected'", - [], - |row| row.get(0), - ) - .unwrap(); - assert_eq!(protected_rows, 1); - } - - #[test] - fn execute_dedupes_duplicate_planned_rows_sharing_one_file() { - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_screenshot( - &conn, - "shot-duplicate-a", - Some("run-1"), - 0, - "2026-06-15/duplicate.png", - "2026-06-15T10:00:00Z", - ); - insert_screenshot( - &conn, - "shot-duplicate-b", - Some("run-2"), - 0, - "2026-06-15/duplicate.png", - "2026-06-15T10:05:00Z", - ); - drop(conn); - let duplicate_file = write_screenshot_file( - &fixture.screenshots_dir, - "2026-06-15/duplicate.png", - b"1234", - ); - - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap(); - - assert_eq!(plan.items.len(), 2); - assert_eq!(plan.estimated_bytes, 4); - - let result = super::execute_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, // preset "all" - test_today(), - ) - .unwrap(); - - assert_eq!(result.deleted_rows, 2); - assert_eq!(result.deleted_files, 1); - assert_eq!(result.freed_bytes, 4); - assert_eq!(result.skipped_pending_uploads, 0); - assert!(!duplicate_file.exists()); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - let rows: i64 = conn - .query_row("select count(*) from run_screenshots", [], |row| row.get(0)) - .unwrap(); - assert_eq!(rows, 0); - } - - #[test] - fn execute_deletes_planned_row_when_db_file_is_missing() { - let fixture = create_fixture(); - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - insert_screenshot( - &conn, - "shot-missing-file", - Some("run-1"), - 0, - "2026-06-15/missing.png", - "2026-06-15T10:00:00Z", - ); - drop(conn); - - let plan = plan_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, - test_today(), - ) - .unwrap(); - - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.estimated_bytes, 0); - - let result = super::execute_screenshot_cleanup( - &fixture.database_path, - &fixture.data_root, - None, // preset "all" - test_today(), - ) - .unwrap(); - - assert_eq!(result.deleted_rows, 1); - assert_eq!(result.deleted_files, 0); - assert_eq!(result.freed_bytes, 0); - - let conn = rusqlite::Connection::open(&fixture.database_path).unwrap(); - let rows: i64 = conn - .query_row("select count(*) from run_screenshots", [], |row| row.get(0)) - .unwrap(); - assert_eq!(rows, 0); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/dto.rs b/bazaarplusplus-installer/src-tauri/src/history/dto.rs deleted file mode 100644 index 99e7fa7..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/dto.rs +++ /dev/null @@ -1,81 +0,0 @@ -use serde::Serialize; - -#[derive(Clone, Debug, PartialEq, Serialize, specta::Type)] -pub struct HistoryRunList { - pub summary: HistorySummary, - pub runs: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, specta::Type)] -pub struct HistorySummary { - pub runs: i64, - pub videos: i64, - pub win_rate: Option, -} - -#[derive(Clone, Debug, PartialEq, Serialize, specta::Type)] -pub struct HistoryRunRow { - pub run_id: String, - pub hero: String, - pub game_mode: String, - pub started_at_utc: String, - pub ended_at_utc: Option, - pub result: String, - pub victories: Option, - pub losses: Option, - pub final_day: Option, - pub final_player_rank: Option, - pub final_player_rating: Option, - /// The Run's rating change; `None` when the starting rating was not captured. - pub final_player_rating_delta: Option, - pub screenshot_id: Option, - /// The absolute URL of the run's History Thumbnail. - pub thumbnail_url: Option, -} - -#[derive(Clone, Debug, PartialEq, Serialize, specta::Type)] -pub struct HistoryRunDetail { - pub run: HistoryRunDetailRow, - pub battles: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, specta::Type)] -pub struct HistoryRunDetailRow { - pub run_id: String, - pub hero: String, - pub game_mode: String, - pub started_at_utc: String, - pub ended_at_utc: Option, - pub status: String, - pub result: String, - pub victories: Option, - pub losses: Option, - pub final_day: Option, - pub final_player_rank: Option, - pub final_player_rating: Option, - /// The Run's rating change; `None` when the starting rating was not captured. - pub final_player_rating_delta: Option, - pub screenshot_id: Option, - pub player_name: Option, -} - -#[derive(Clone, Debug, PartialEq, Serialize, specta::Type)] -pub struct HistoryBattleRow { - pub battle_id: String, - pub day: Option, - pub hour: Option, - pub result: String, - pub opponent_hero: Option, - pub opponent_name: Option, - pub opponent_rank: Option, - pub opponent_rating: Option, - pub video: Option, -} - -#[derive(Clone, Debug, PartialEq, Serialize, specta::Type)] -pub struct HistoryBattleVideo { - pub video_id: String, - pub status: String, - pub file_size_bytes: Option, - pub duration_ms: Option, -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/files.rs b/bazaarplusplus-installer/src-tauri/src/history/files.rs deleted file mode 100644 index 3130ddc..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/files.rs +++ /dev/null @@ -1,142 +0,0 @@ -use std::path::{Path, PathBuf}; - -/// Deletes the video file a row names. Like cleanup, it resolves through -/// [`resolve_cleanup_file_path`], so a row holding an absolute path deletes no -/// file outside the video directory. -pub fn remove_video_file(root_dir: &Path, relative_path: &str) -> Result<(), String> { - let Some(path) = resolve_cleanup_file_path(root_dir, relative_path) else { - return Ok(()); - }; - match std::fs::remove_file(&path) { - Ok(()) => Ok(()), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(err) => Err(format!("failed to remove video {}: {err}", path.display())), - } -} - -pub fn resolve_data_file_path(root_dir: &Path, raw_path: &str) -> Option { - let raw_path = raw_path.trim(); - if raw_path.is_empty() { - return None; - } - - let candidate = PathBuf::from(raw_path); - if candidate.is_absolute() { - return Some(candidate); - } - - let mut normalized = PathBuf::new(); - for segment in raw_path.split(['/', '\\']) { - let trimmed = segment.trim(); - if !trimmed.is_empty() && trimmed != "." && trimmed != ".." { - normalized.push(trimmed); - } - } - Some(root_dir.join(normalized)) -} - -/// Resolver for delete operations: unlike `resolve_screenshot_path`, absolute -/// paths stored in the DB are refused so a malformed row can never point a -/// deletion outside the data directory. -pub fn resolve_cleanup_file_path(root_dir: &Path, raw_path: &str) -> Option { - let trimmed = raw_path.trim(); - if trimmed.is_empty() || PathBuf::from(trimmed).is_absolute() { - return None; - } - let resolved = resolve_data_file_path(root_dir, trimmed)?; - // Defense in depth: a Windows drive-relative segment like `C:evil.png` is - // not `is_absolute()`, yet `PathBuf::join` treats its drive prefix as - // replacing the root, so the resolved path can escape `root_dir`. Confirm - // containment before any delete ever touches this path. - resolved.starts_with(root_dir).then_some(resolved) -} - -pub fn resolve_screenshot_path(data_root: &Path, raw_path: &str) -> Option { - let raw_path = raw_path.trim(); - if raw_path.is_empty() { - return None; - } - let candidate = PathBuf::from(raw_path); - if candidate.is_absolute() { - return Some(candidate); - } - resolve_data_file_path( - &crate::services::paths::screenshots_dir_in(data_root), - raw_path, - ) -} - -#[cfg(test)] -mod tests { - use super::{remove_video_file, resolve_cleanup_file_path}; - - #[test] - fn video_removal_never_deletes_outside_the_video_directory() { - let temp = tempfile::tempdir().unwrap(); - let video_dir = temp.path().join("videos"); - std::fs::create_dir_all(video_dir.join("2026-05-20")).unwrap(); - let inside = video_dir.join("2026-05-20/a.mp4"); - let outside = temp.path().join("outside.mp4"); - std::fs::write(&inside, b"inside").unwrap(); - std::fs::write(&outside, b"outside").unwrap(); - - remove_video_file(&video_dir, &outside.to_string_lossy()).unwrap(); - remove_video_file(&video_dir, "../outside.mp4").unwrap(); - assert!(outside.is_file()); - - remove_video_file(&video_dir, "2026-05-20/a.mp4").unwrap(); - assert!(!inside.exists()); - } - - #[test] - fn cleanup_path_rejects_absolute_paths() { - let root = std::path::Path::new("root"); - // is_absolute() is platform-specific: "/x" is not absolute on Windows. - let absolute = if cfg!(windows) { - r"C:\evil\shot.png" - } else { - "/evil/shot.png" - }; - assert_eq!(resolve_cleanup_file_path(root, absolute), None); - assert_eq!(resolve_cleanup_file_path(root, ""), None); - assert_eq!(resolve_cleanup_file_path(root, " "), None); - } - - #[test] - fn cleanup_path_never_resolves_outside_root() { - // Whatever survives resolution must stay under root_dir. On Windows a - // drive-relative segment like `C:evil.png` would otherwise escape via - // join(); on Unix it is an ordinary filename that stays contained. The - // invariant (contained or refused) must hold on every platform. - let root = std::path::Path::new("root"); - for raw in [ - "C:evil.png", - r"C:\evil.png", - r"..\..\evil.png", - "2026-06-15/shot.png", - ] { - if let Some(resolved) = resolve_cleanup_file_path(root, raw) { - assert!( - resolved.starts_with(root), - "`{raw}` resolved outside root: {resolved:?}" - ); - } - } - // On Windows the drive-relative form is a real escape and must be refused. - #[cfg(windows)] - assert_eq!(resolve_cleanup_file_path(root, "C:evil.png"), None); - } - - #[test] - fn cleanup_path_normalizes_separators_and_strips_traversal() { - let root = std::path::Path::new("root"); - assert_eq!( - resolve_cleanup_file_path(root, "2026-06-15\\shot.png"), - Some(root.join("2026-06-15").join("shot.png")) - ); - assert_eq!( - resolve_cleanup_file_path(root, "../../2026-06-15/shot.png"), - Some(root.join("2026-06-15").join("shot.png")) - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/hero.rs b/bazaarplusplus-installer/src-tauri/src/history/hero.rs deleted file mode 100644 index 27b2c4f..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/hero.rs +++ /dev/null @@ -1,50 +0,0 @@ -pub(crate) fn canonical_hero_id(raw: &str) -> String { - let trimmed = raw.trim(); - if trimmed.eq_ignore_ascii_case("Hero8") || trimmed.eq_ignore_ascii_case("TheDragons") { - return "TheDragons".to_string(); - } - - trimmed.to_string() -} - -pub(crate) fn hero_display_name(canonical: &str) -> &str { - match canonical { - "TheDragons" => "The Dragons", - _ => canonical, - } -} - -#[cfg(test)] -mod tests { - use super::{canonical_hero_id, hero_display_name}; - - /// The analyzer owns the legacy-to-canonical mapping; the installer keeps its - /// own matching rule (ASCII case-insensitive, trimmed). - const HERO_ALIASES: &str = - include_str!("../../../../bazaarplusplus-analyzer/contracts/v6/hero-aliases.json"); - - #[test] - fn hero_aliases_canonicalize_and_display() { - let file: serde_json::Value = serde_json::from_str(HERO_ALIASES).unwrap(); - assert_eq!(file["schema_version"], 1); - let aliases = file["aliases"].as_object().unwrap(); - assert!(!aliases.is_empty()); - for (alias, canonical) in aliases { - let canonical = canonical.as_str().unwrap(); - for spelling in [ - alias.clone(), - alias.to_ascii_lowercase(), - alias.to_ascii_uppercase(), - format!(" {alias}\n"), - canonical.to_string(), - canonical.to_ascii_uppercase(), - ] { - assert_eq!(canonical_hero_id(&spelling), canonical, "{spelling:?}"); - } - } - assert_eq!(hero_display_name("TheDragons"), "The Dragons"); - assert_eq!(canonical_hero_id(" Vanessa "), "Vanessa"); - assert_eq!(hero_display_name("Vanessa"), "Vanessa"); - assert_eq!(canonical_hero_id(" "), ""); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/instant.rs b/bazaarplusplus-installer/src-tauri/src/history/instant.rs deleted file mode 100644 index 3dc68e1..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/instant.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! The mod stores every instant as Unix-epoch milliseconds in `*_at_ms` columns; -//! History DTOs and stream records keep RFC 3339 text, so these convert at the -//! column boundary. - -use chrono::{DateTime, FixedOffset, SecondsFormat, Utc}; -use rusqlite::types::Type; - -/// RFC 3339 UTC text for a stored instant: `Z`, with milliseconds only when present. -pub(crate) fn utc_text(millis: i64) -> Option { - DateTime::::from_timestamp_millis(millis) - .map(|value| value.to_rfc3339_opts(SecondsFormat::AutoSi, true)) -} - -/// RFC 3339 text of a stored instant at the UTC offset recorded beside it. -pub(crate) fn local_text(millis: i64, utc_offset_minutes: i64) -> Option { - let offset = FixedOffset::east_opt(i32::try_from(utc_offset_minutes.checked_mul(60)?).ok()?)?; - DateTime::::from_timestamp_millis(millis).map(|value| { - value - .with_timezone(&offset) - .to_rfc3339_opts(SecondsFormat::AutoSi, false) - }) -} - -/// Reads an `*_at_ms` column as RFC 3339 UTC text. -pub(crate) fn utc_column(row: &rusqlite::Row<'_>, index: usize) -> rusqlite::Result { - let millis: i64 = row.get(index)?; - utc_text(millis).ok_or_else(|| out_of_range(index, millis)) -} - -/// Reads a nullable `*_at_ms` column as RFC 3339 UTC text. -pub(crate) fn optional_utc_column( - row: &rusqlite::Row<'_>, - index: usize, -) -> rusqlite::Result> { - row.get::<_, Option>(index)? - .map(|millis| utc_text(millis).ok_or_else(|| out_of_range(index, millis))) - .transpose() -} - -fn out_of_range(index: usize, millis: i64) -> rusqlite::Error { - rusqlite::Error::FromSqlConversionFailure( - index, - Type::Integer, - format!("{millis} is not a representable Unix-millisecond instant").into(), - ) -} - -#[cfg(test)] -mod tests { - use super::{local_text, utc_text}; - - #[test] - fn instants_format_as_rfc3339_text() { - assert_eq!( - utc_text(1_767_258_600_000).as_deref(), - Some("2026-01-01T09:10:00Z") - ); - assert_eq!( - utc_text(1_767_258_600_123).as_deref(), - Some("2026-01-01T09:10:00.123Z") - ); - assert_eq!( - local_text(1_767_258_600_000, 480).as_deref(), - Some("2026-01-01T17:10:00+08:00") - ); - assert_eq!(utc_text(i64::MAX), None); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/mapper.rs b/bazaarplusplus-installer/src-tauri/src/history/mapper.rs deleted file mode 100644 index 0bd2ab4..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/mapper.rs +++ /dev/null @@ -1,279 +0,0 @@ -use crate::history::dto::{ - HistoryBattleRow, HistoryBattleVideo, HistoryRunDetailRow, HistoryRunRow, -}; -use crate::history::hero::{canonical_hero_id, hero_display_name}; -use crate::history::queries::RunRow; - -/// The only real transformations a run row needs on its way to a DTO: the -/// derived result and the canonical hero display name. -struct RunDerivations { - result: String, - hero: String, -} - -fn derive_run_fields(row: &RunRow) -> RunDerivations { - RunDerivations { - result: derive_run_result(&row.status, row.victories), - hero: hero_display_name(&canonical_hero_id(&row.hero)).to_string(), - } -} - -pub fn derive_run_result(status: &str, victories: Option) -> String { - match status { - "abandoned" => "abandoned".to_string(), - "completed" if victories.unwrap_or(0) >= 10 => "win".to_string(), - "completed" => "loss".to_string(), - value if value != "completed" && value != "abandoned" => "in_progress".to_string(), - _ => "unknown".to_string(), - } -} - -pub fn map_battle_result(result: Option<&str>) -> String { - // LOCAL battles persist lowercase "win"/"loss" or NULL; GHOST rows use - // capitalized "Won"/"Lost". Normalize case (and trim) so every source - // resolves, and map NULL/empty/unrecognized to "unknown" — a neutral - // marker the frontend renders muted, never as a defeat. - match result - .map(str::trim) - .map(str::to_ascii_lowercase) - .as_deref() - { - Some("win" | "won") => "win".to_string(), - Some("loss" | "lost") => "loss".to_string(), - _ => "unknown".to_string(), - } -} - -pub fn map_run_to_list_row( - row: RunRow, - screenshot_id: Option, - thumbnail_url: impl Fn(&str) -> String, -) -> HistoryRunRow { - let derived = derive_run_fields(&row); - let thumbnail_url = screenshot_id.as_deref().map(thumbnail_url); - HistoryRunRow { - run_id: row.run_id, - hero: derived.hero, - game_mode: row.game_mode, - started_at_utc: row.started_at_utc, - ended_at_utc: row.ended_at_utc, - result: derived.result, - victories: row.victories, - losses: row.losses, - final_day: row.final_day, - final_player_rank: row.final_player_rank, - final_player_rating: row.final_player_rating, - final_player_rating_delta: row.final_player_rating_delta, - screenshot_id, - thumbnail_url, - } -} - -pub fn map_run_to_detail_row( - row: RunRow, - screenshot_id: Option, - player_name: Option, -) -> HistoryRunDetailRow { - let derived = derive_run_fields(&row); - HistoryRunDetailRow { - run_id: row.run_id, - hero: derived.hero, - game_mode: row.game_mode, - started_at_utc: row.started_at_utc, - ended_at_utc: row.ended_at_utc, - status: row.status, - result: derived.result, - victories: row.victories, - losses: row.losses, - final_day: row.final_day, - final_player_rank: row.final_player_rank, - final_player_rating: row.final_player_rating, - final_player_rating_delta: row.final_player_rating_delta, - screenshot_id, - player_name, - } -} - -pub(super) struct BattleFields { - pub(super) battle_id: String, - pub(super) day: Option, - pub(super) hour: Option, - pub(super) result: Option, - pub(super) opponent_hero: Option, - pub(super) opponent_name: Option, - pub(super) opponent_rank: Option, - pub(super) opponent_rating: Option, -} - -pub(super) struct BattleVideoFields { - pub(super) video_id: String, - pub(super) status: Option, - pub(super) file_size_bytes: Option, - pub(super) duration_ms: Option, -} - -pub(super) fn map_battle_row( - battle: BattleFields, - video: Option, -) -> HistoryBattleRow { - HistoryBattleRow { - battle_id: battle.battle_id, - day: battle.day, - hour: battle.hour, - result: map_battle_result(battle.result.as_deref()), - opponent_hero: battle - .opponent_hero - .map(|hero| hero_display_name(&canonical_hero_id(&hero)).to_string()), - opponent_name: battle.opponent_name, - opponent_rank: battle.opponent_rank, - opponent_rating: battle.opponent_rating, - video: video.map(|video| HistoryBattleVideo { - video_id: video.video_id, - status: video.status.unwrap_or_else(|| "COMPLETED".to_string()), - file_size_bytes: video.file_size_bytes, - duration_ms: video.duration_ms, - }), - } -} - -#[cfg(test)] -mod tests { - use super::{ - map_battle_result, map_battle_row, map_run_to_detail_row, map_run_to_list_row, - BattleFields, BattleVideoFields, - }; - use crate::history::dto::{HistoryBattleRow, HistoryBattleVideo}; - use crate::history::queries::RunRow; - - fn run_row(hero: &str) -> RunRow { - RunRow { - run_id: "run-1".to_string(), - hero: hero.to_string(), - game_mode: "Ranked".to_string(), - started_at_utc: "2026-08-06T12:00:00Z".to_string(), - ended_at_utc: Some("2026-08-06T13:00:00Z".to_string()), - status: "completed".to_string(), - victories: Some(10), - losses: Some(2), - final_day: Some(12), - final_player_rank: Some("Diamond".to_string()), - final_player_rating: Some(1500), - final_player_rating_delta: Some(16), - } - } - - fn battle_fields(opponent_hero: Option<&str>) -> BattleFields { - BattleFields { - battle_id: "battle-1".to_string(), - day: Some(8), - hour: Some(1), - result: Some("Won".to_string()), - opponent_hero: opponent_hero.map(str::to_string), - opponent_name: Some("Opponent A".to_string()), - opponent_rank: Some("Diamond III".to_string()), - opponent_rating: Some(1410), - } - } - - #[test] - fn run_rows_use_the_dragons_display_name() { - let list_row = map_run_to_list_row(run_row("Hero8"), None, str::to_string); - let detail_row = map_run_to_detail_row(run_row("Hero8"), None, None); - - assert_eq!(list_row.hero, "The Dragons"); - assert_eq!(detail_row.hero, "The Dragons"); - } - - #[test] - fn battle_rows_normalize_only_present_hero_names() { - let the_dragons = map_battle_row(battle_fields(Some("TheDragons")), None); - let unknown = map_battle_row(battle_fields(None), None); - let dooley = map_battle_row(battle_fields(Some("Dooley")), None); - - assert_eq!(the_dragons.opponent_hero.as_deref(), Some("The Dragons")); - assert_eq!(unknown.opponent_hero, None); - assert_eq!(dooley.opponent_hero.as_deref(), Some("Dooley")); - } - - #[test] - fn map_battle_row_preserves_battle_and_video_fields_with_default_status() { - let mapped = map_battle_row( - BattleFields { - battle_id: "battle-1".to_string(), - day: Some(8), - hour: Some(1), - result: Some("Won".to_string()), - opponent_hero: Some("Dooley".to_string()), - opponent_name: Some("Opponent A".to_string()), - opponent_rank: Some("Diamond III".to_string()), - opponent_rating: Some(1410), - }, - Some(BattleVideoFields { - video_id: "video-1".to_string(), - status: None, - file_size_bytes: Some(2200), - duration_ms: Some(1200), - }), - ); - - assert_eq!( - mapped, - HistoryBattleRow { - battle_id: "battle-1".to_string(), - day: Some(8), - hour: Some(1), - result: "win".to_string(), - opponent_hero: Some("Dooley".to_string()), - opponent_name: Some("Opponent A".to_string()), - opponent_rank: Some("Diamond III".to_string()), - opponent_rating: Some(1410), - video: Some(HistoryBattleVideo { - video_id: "video-1".to_string(), - status: "COMPLETED".to_string(), - file_size_bytes: Some(2200), - duration_ms: Some(1200), - }), - } - ); - } - - #[test] - fn map_battle_row_omits_video_without_video_id() { - let mapped = map_battle_row( - BattleFields { - battle_id: "battle-1".to_string(), - day: None, - hour: None, - result: None, - opponent_hero: None, - opponent_name: None, - opponent_rank: None, - opponent_rating: None, - }, - None, - ); - - assert_eq!(mapped.video, None); - } - - #[test] - fn map_battle_result_resolves_known_outcomes_case_insensitively() { - // Lowercase is what LOCAL (PvP) battles actually persist. - assert_eq!(map_battle_result(Some("win")), "win"); - assert_eq!(map_battle_result(Some("loss")), "loss"); - // Capitalized GHOST-style values (with stray whitespace) still resolve. - assert_eq!(map_battle_result(Some("Win")), "win"); - assert_eq!(map_battle_result(Some("Won")), "win"); - assert_eq!(map_battle_result(Some(" Lost ")), "loss"); - } - - #[test] - fn map_battle_result_maps_null_and_unrecognized_to_neutral() { - // NULL is a legitimate draw/unresolved state, not a defeat. - assert_eq!(map_battle_result(None), "unknown"); - // Empty / whitespace-only / garbage all collapse to the neutral marker. - assert_eq!(map_battle_result(Some("")), "unknown"); - assert_eq!(map_battle_result(Some(" ")), "unknown"); - assert_eq!(map_battle_result(Some("draw")), "unknown"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/mod.rs b/bazaarplusplus-installer/src-tauri/src/history/mod.rs deleted file mode 100644 index 2ddeb0e..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -pub(crate) mod cleanup; -mod dto; -pub(crate) mod files; -pub(crate) mod hero; -pub(crate) mod instant; -pub(crate) mod mapper; -pub(crate) mod mod_schema; -mod queries; -mod repo; -pub(crate) mod screenshots; - -pub(crate) use dto::{HistoryRunDetail, HistoryRunList}; -pub(crate) use queries::HistoryReadError; -pub(crate) use repo::{ - delete_battle_video, get_history_run_detail, list_history_runs, load_battle_video_path, - load_run_id_for_battle, load_run_screenshot_path, -}; diff --git a/bazaarplusplus-installer/src-tauri/src/history/mod_schema.rs b/bazaarplusplus-installer/src-tauri/src/history/mod_schema.rs deleted file mode 100644 index 6f02e15..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/mod_schema.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! The mod's local history database schema, from the mod's schema file. The mod -//! owns the schema (`RunLogSchema`) and `RunLoggingPipeline.Tests` dumps it from a -//! freshly initialized database, so a mod column change fails installer tests -//! instead of passing against a hand-copied shape. The V5 import creates a -//! missing current database from it; tests build their databases from it. - -const MOD_SCHEMA_SQL: &str = include_str!( - "../../../../bazaarplusplus-mod/src/BazaarPlusPlus.Storage/history-database-v6.schema.sql" -); - -/// Creates every table, index, and trigger of the mod's current local history -/// database on an empty connection and sets its `user_version`. Runs inside the -/// caller's transaction when one is open. -pub(crate) fn execute_mod_schema(conn: &rusqlite::Connection) -> Result<(), String> { - conn.execute_batch(MOD_SCHEMA_SQL) - .map_err(|error| format!("Cannot create the history database schema: {error}"))?; - let user_version: i64 = conn - .query_row("pragma user_version", [], |row| row.get(0)) - .map_err(|error| error.to_string())?; - if Some(&user_version) != crate::config::supported_mod_db_user_versions().last() { - return Err(format!( - "The mod schema file sets user_version {user_version}, which is not the newest \ - version history-database-compatibility.json supports" - )); - } - Ok(()) -} - -/// [`execute_mod_schema`] with foreign keys on, as the mod opens the database. -#[cfg(test)] -pub(crate) fn create_mod_schema(conn: &rusqlite::Connection) { - execute_mod_schema(conn).unwrap(); - conn.execute_batch("pragma foreign_keys = on;").unwrap(); -} - -/// The schema text as `sqlite_master` stores it, in the mod golden's dump format, -/// so a database can be compared with the file byte for byte. -#[cfg(test)] -pub(crate) fn mod_schema_sql() -> &'static str { - MOD_SCHEMA_SQL -} - -/// Dumps `conn`'s schema in the mod golden's format: `PRAGMA user_version=N;`, then -/// every `sqlite_master` statement ordered by type (table, index, trigger) and name. -#[cfg(test)] -pub(crate) fn dump_schema(conn: &rusqlite::Connection) -> String { - let user_version: i64 = conn - .query_row("pragma user_version", [], |row| row.get(0)) - .unwrap(); - let mut schema = format!("PRAGMA user_version={user_version};\n"); - let mut statement = conn - .prepare( - "select sql from sqlite_master where sql is not null and name not like 'sqlite_%' \ - order by case type when 'table' then 0 when 'index' then 1 when 'trigger' then 2 \ - else 3 end, name", - ) - .unwrap(); - let rows = statement - .query_map([], |row| row.get::<_, String>(0)) - .unwrap(); - for sql in rows { - schema.push_str(&sql.unwrap().replace("\r\n", "\n")); - schema.push_str(";\n"); - } - schema -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_database_built_from_the_schema_file_dumps_back_to_it() { - let conn = rusqlite::Connection::open_in_memory().unwrap(); - execute_mod_schema(&conn).unwrap(); - assert_eq!(dump_schema(&conn), mod_schema_sql()); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/queries.rs b/bazaarplusplus-installer/src-tauri/src/history/queries.rs deleted file mode 100644 index 03a2a5a..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/queries.rs +++ /dev/null @@ -1,582 +0,0 @@ -use std::{path::Path, time::Duration}; - -use rusqlite::{params, Connection, OpenFlags, OptionalExtension}; - -use crate::history::dto::{HistoryBattleRow, HistorySummary}; -use crate::history::instant::{optional_utc_column, utc_column}; -use crate::history::mapper::{map_battle_row, BattleFields, BattleVideoFields}; - -/// Why a history database could not be read. An unsupported schema stays typed -/// so the History page can name the found and supported versions; every other -/// failure is a diagnostic. Callers that only report a diagnostic convert it -/// to its `Display` text. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum HistoryReadError { - UnsupportedSchema { found: i64, supported: String }, - Failed(String), -} - -impl std::fmt::Display for HistoryReadError { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::UnsupportedSchema { found, supported } => write!( - formatter, - "Unsupported mod database schema: found={found}, supported={supported}." - ), - Self::Failed(diagnostic) => formatter.write_str(diagnostic), - } - } -} - -impl From for HistoryReadError { - fn from(diagnostic: String) -> Self { - Self::Failed(diagnostic) - } -} - -impl From for String { - fn from(error: HistoryReadError) -> Self { - error.to_string() - } -} - -pub struct RunRow { - pub run_id: String, - pub hero: String, - pub game_mode: String, - pub started_at_utc: String, - pub ended_at_utc: Option, - pub status: String, - pub victories: Option, - pub losses: Option, - pub final_day: Option, - pub final_player_rank: Option, - pub final_player_rating: Option, - pub final_player_rating_delta: Option, -} - -pub struct VideoRef { - pub relative_path: String, -} - -/// Backoff before each retry of a transient open. The mod writes this database -/// from the running game, so a read can land mid-checkpoint and fail once -/// before succeeding. -const OPEN_RETRY_BACKOFF: [Duration; 2] = [Duration::from_millis(50), Duration::from_millis(150)]; - -/// Read connection for every history query. -/// -/// Opened read-write on purpose. A read-only connection cannot create a missing -/// `-shm` or recover a dirty WAL, and both are exactly what a game process that -/// exited uncleanly leaves behind — so the read-only flag turns a recoverable -/// database into an unreadable one. Write access is not a requirement of this -/// path: when the file is write-protected SQLite opens it read-only by itself. -pub fn open_connection(database_path: &Path) -> Result { - open_with_retry(database_path, Writability::Optional) -} - -/// Write connection for delete and cleanup paths. Because SQLite silently -/// downgrades a write-protected database to read-only, an unwritable file would -/// otherwise open cleanly here and only fail partway through a cleanup -/// transaction; the writability check moves that failure to the open. -pub fn open_write_connection(database_path: &Path) -> Result { - open_with_retry(database_path, Writability::Required) -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum Writability { - Optional, - Required, -} - -fn open_with_retry( - database_path: &Path, - writability: Writability, -) -> Result { - let mut attempt = 0usize; - loop { - match open_probed(database_path, writability) { - Ok((conn, user_version)) => { - // A schema mismatch is a stable fact about the file, so it leaves - // the retry loop immediately with its own diagnostic. - validate_supported_schema(user_version)?; - return Ok(conn); - } - Err(err) => { - let Some(backoff) = OPEN_RETRY_BACKOFF.get(attempt).copied() else { - return Err(describe_error(&err).into()); - }; - if !is_transient_error(&err) { - return Err(describe_error(&err).into()); - } - std::thread::sleep(backoff); - attempt += 1; - } - } - } -} - -fn open_probed( - database_path: &Path, - writability: Writability, -) -> Result<(Connection, i64), rusqlite::Error> { - let conn = Connection::open_with_flags(database_path, OpenFlags::SQLITE_OPEN_READ_WRITE)?; - conn.busy_timeout(Duration::from_secs(2))?; - // Opening is lazy: the first statement is what actually touches the database - // file, the WAL and the shared-memory index, so this probe is what proves the - // connection can read. It doubles as the schema check's only query. - let user_version = conn.query_row("PRAGMA user_version", [], |row| row.get::<_, i64>(0))?; - if writability == Writability::Required && conn.is_readonly(rusqlite::MAIN_DB)? { - return Err(rusqlite::Error::SqliteFailure( - rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_READONLY), - Some("The mod database is not writable.".to_string()), - )); - } - Ok((conn, user_version)) -} - -fn is_transient_error(error: &rusqlite::Error) -> bool { - use rusqlite::ffi::ErrorCode; - - matches!( - error, - rusqlite::Error::SqliteFailure(inner, _) - if matches!( - inner.code, - ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked | ErrorCode::SystemIoFailure - ) - ) -} - -/// Diagnostics carry the SQLite extended code: the bare message collapses a -/// whole family of causes into "disk I/O error", which is not enough to tell a -/// locked shared-memory index from a failed WAL recovery when triaging a report. -fn describe_error(error: &rusqlite::Error) -> String { - match error { - rusqlite::Error::SqliteFailure(inner, _) => { - format!("{error} (sqlite extended_code={})", inner.extended_code) - } - other => other.to_string(), - } -} - -fn validate_supported_schema(found: i64) -> Result<(), HistoryReadError> { - if crate::config::supported_mod_db_user_versions().contains(&found) { - return Ok(()); - } - - Err(HistoryReadError::UnsupportedSchema { - found, - supported: crate::config::supported_mod_db_user_versions_label(), - }) -} - -/// Write connection for cleanup operations. Unlike `open_write_connection`, -/// this enables per-connection foreign-key enforcement so the mod schema's -/// ON DELETE CASCADE chains (runs -> run_events/battles/bundle_seal_jobs, -/// battles -> battle_snapshots) fire on our deletes. -pub fn open_cleanup_connection(database_path: &Path) -> Result { - let conn = open_write_connection(database_path)?; - conn.execute_batch("PRAGMA foreign_keys = ON;") - .map_err(|err| err.to_string())?; - Ok(conn) -} - -pub fn table_exists(conn: &Connection, table_name: &str) -> Result { - conn.query_row( - "select exists(select 1 from sqlite_master where type = 'table' and name = ?1)", - [table_name], - |row| row.get::<_, i64>(0), - ) - .map(|value| value != 0) - .map_err(|err| err.to_string()) -} - -pub fn sql_placeholders(count: usize) -> String { - std::iter::repeat_n("?", count) - .collect::>() - .join(", ") -} - -pub fn load_summary(conn: &Connection) -> Result { - let (runs, completed_runs, win_runs): (i64, i64, i64) = conn - .query_row( - " - select - count(*) as runs, - coalesce(sum(case when status = 'completed' then 1 else 0 end), 0) as completed_runs, - coalesce(sum(case when status = 'completed' and coalesce(victories, 0) >= 10 then 1 else 0 end), 0) as win_runs - from runs - ", - [], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), - ) - .map_err(|err| err.to_string())?; - let videos = if table_exists(conn, "combat_replay_videos")? { - conn.query_row( - "select count(*) from combat_replay_videos where status = 'COMPLETED'", - [], - |row| row.get(0), - ) - .map_err(|err| err.to_string())? - } else { - 0 - }; - - Ok(HistorySummary { - runs, - videos, - win_rate: if completed_runs > 0 { - Some(win_runs as f64 / completed_runs as f64) - } else { - None - }, - }) -} - -pub fn list_run_rows(conn: &Connection, limit: i64, offset: i64) -> Result, String> { - let mut stmt = conn - .prepare( - " - select - run_id, hero, game_mode, started_at_ms, ended_at_ms, - status, victories, losses, final_day, final_player_rank, final_player_rating, - final_player_rating_delta - from runs - order by coalesce(ended_at_ms, last_seen_at_ms, started_at_ms) desc, run_id desc - limit ?1 offset ?2 - ", - ) - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([limit, offset], map_run_row_from_statement) - .map_err(|err| err.to_string())?; - rows.collect::, _>>() - .map_err(|err| err.to_string()) -} - -pub fn load_run_row(conn: &Connection, run_id: &str) -> Result, String> { - conn.query_row( - " - select - run_id, hero, game_mode, started_at_ms, ended_at_ms, - status, victories, losses, final_day, final_player_rank, final_player_rating, - final_player_rating_delta - from runs - where run_id = ?1 - ", - [run_id], - map_run_row_from_statement, - ) - .optional() - .map_err(|err| err.to_string()) -} - -fn map_run_row_from_statement(row: &rusqlite::Row<'_>) -> rusqlite::Result { - Ok(RunRow { - run_id: row.get(0)?, - hero: row.get(1)?, - game_mode: row.get(2)?, - started_at_utc: utc_column(row, 3)?, - ended_at_utc: optional_utc_column(row, 4)?, - status: row.get(5)?, - victories: row.get(6)?, - losses: row.get(7)?, - final_day: row.get(8)?, - final_player_rank: row.get(9)?, - final_player_rating: row.get(10)?, - final_player_rating_delta: row.get(11)?, - }) -} - -fn map_battle_fields(row: &rusqlite::Row<'_>) -> rusqlite::Result { - Ok(BattleFields { - battle_id: row.get(0)?, - day: row.get(1)?, - hour: row.get(2)?, - result: row.get::<_, Option>(3)?, - opponent_hero: row.get(4)?, - opponent_name: row.get(5)?, - opponent_rank: row.get(6)?, - opponent_rating: row.get(7)?, - }) -} - -pub fn local_player_name(conn: &Connection, run_id: &str) -> Result, String> { - if !table_exists(conn, "battles")? { - return Ok(None); - } - - conn.query_row( - " - select player_name - from battles - where run_id = ?1 and source = 'LOCAL' and player_name is not null and deleted_at_ms is null - order by recorded_at_ms desc, battle_id desc - limit 1 - ", - [run_id], - |row| row.get(0), - ) - .optional() - .map_err(|err| err.to_string()) -} - -pub fn load_battle_rows(conn: &Connection, run_id: &str) -> Result, String> { - if !table_exists(conn, "battles")? { - return Ok(Vec::new()); - } - - if table_exists(conn, "combat_replay_videos")? { - let mut stmt = conn - .prepare( - " - select - b.battle_id, b.day, b.hour, b.result, - b.opponent_hero, b.opponent_name, b.opponent_rank, b.opponent_rating, - cv.video_id, cv.status, cv.file_size_bytes, cv.duration_ms - from battles b - left join combat_replay_videos cv on cv.video_id = ( - select video_id - from combat_replay_videos - where battle_id = b.battle_id and status = 'COMPLETED' - order by started_at_ms desc, video_id desc - limit 1 - ) - where b.run_id = ?1 and b.source = 'LOCAL' and b.deleted_at_ms is null - order by b.recorded_at_ms desc, b.battle_id desc - ", - ) - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([run_id], |row| { - let video_id: Option = row.get(8)?; - Ok(map_battle_row( - map_battle_fields(row)?, - video_id.map(|video_id| BattleVideoFields { - video_id, - status: row.get(9).ok().flatten(), - file_size_bytes: row.get(10).ok().flatten(), - duration_ms: row.get(11).ok().flatten(), - }), - )) - }) - .map_err(|err| err.to_string())?; - return rows - .collect::, _>>() - .map_err(|err| err.to_string()); - } - - let mut stmt = conn - .prepare( - " - select - battle_id, day, hour, result, - opponent_hero, opponent_name, opponent_rank, opponent_rating - from battles - where run_id = ?1 and source = 'LOCAL' and deleted_at_ms is null - order by recorded_at_ms desc, battle_id desc - ", - ) - .map_err(|err| err.to_string())?; - let rows = stmt - .query_map([run_id], |row| { - Ok(map_battle_row(map_battle_fields(row)?, None)) - }) - .map_err(|err| err.to_string())?; - rows.collect::, _>>() - .map_err(|err| err.to_string()) -} - -pub fn load_battle_video_ref( - conn: &Connection, - battle_id: &str, - video_id: &str, -) -> Result, String> { - if !table_exists(conn, "combat_replay_videos")? { - return Ok(None); - } - - conn.query_row( - " - select video_relative_path - from combat_replay_videos - where battle_id = ?1 and video_id = ?2 and status = 'COMPLETED' - ", - params![battle_id, video_id], - |row| { - Ok(VideoRef { - relative_path: row.get(0)?, - }) - }, - ) - .optional() - .map_err(|err| err.to_string()) -} - -pub fn load_run_id_for_battle( - conn: &Connection, - battle_id: &str, -) -> Result, String> { - if !table_exists(conn, "battles")? { - return Ok(None); - } - - conn.query_row( - "select run_id from battles where battle_id = ?1", - [battle_id], - |row| row.get(0), - ) - .optional() - .map_err(|err| err.to_string()) -} - -#[cfg(test)] -mod tests { - use super::{open_connection, open_write_connection, HistoryReadError}; - use crate::config::{supported_mod_db_user_versions, supported_mod_db_user_versions_label}; - - #[test] - fn open_connection_does_not_create_missing_database() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join("missing.db"); - - assert!(open_connection(&database_path).is_err()); - assert!(!database_path.exists()); - } - - #[test] - fn connections_reject_unsupported_mod_database_schema_versions() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join("bazaarplusplus.db"); - rusqlite::Connection::open(&database_path).unwrap(); - - for error in [ - open_connection(&database_path).unwrap_err(), - open_write_connection(&database_path).unwrap_err(), - ] { - assert_eq!( - error, - HistoryReadError::UnsupportedSchema { - found: 0, - supported: supported_mod_db_user_versions_label(), - } - ); - } - } - - #[test] - fn connections_open_supported_mod_database_schema_versions() { - for user_version in supported_mod_db_user_versions() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join("bazaarplusplus.db"); - rusqlite::Connection::open(&database_path) - .unwrap() - .execute_batch(&format!("pragma user_version = {user_version};")) - .unwrap(); - - assert!(open_connection(&database_path).is_ok()); - assert!(open_write_connection(&database_path).is_ok()); - } - } - - #[test] - fn read_connection_still_opens_a_write_protected_database() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join("bazaarplusplus.db"); - rusqlite::Connection::open(&database_path) - .unwrap() - .execute_batch("pragma user_version = 1;") - .unwrap(); - write_protect(&database_path); - - // SQLite downgrades the read-write open to read-only, which is what keeps - // history readable when the game lives in a directory we cannot write. - assert!(open_connection(&database_path).is_ok()); - } - - #[test] - fn write_connection_refuses_a_write_protected_database_at_open() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join("bazaarplusplus.db"); - rusqlite::Connection::open(&database_path) - .unwrap() - .execute_batch("pragma user_version = 1; create table runs (run_id text primary key);") - .unwrap(); - write_protect(&database_path); - - let error = open_write_connection(&database_path) - .unwrap_err() - .to_string(); - - assert!(error.contains("not writable"), "{error}"); - } - - #[test] - fn open_failure_diagnostics_carry_the_sqlite_extended_code() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join("bazaarplusplus.db"); - std::fs::write(&database_path, b"this is not a sqlite database").unwrap(); - - let error = open_connection(&database_path).unwrap_err().to_string(); - - // 26 is SQLITE_NOTADB; without the code the message alone reads as a - // generic failure and cannot be triaged from a user report. - assert!(error.contains("extended_code=26"), "{error}"); - } - - fn write_protect(path: &std::path::Path) { - let mut permissions = std::fs::metadata(path).unwrap().permissions(); - permissions.set_readonly(true); - std::fs::set_permissions(path, permissions).unwrap(); - } - - #[test] - fn connection_rejects_a_newer_mod_database_schema_version() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join("bazaarplusplus.db"); - let newer = supported_mod_db_user_versions().last().unwrap() + 1; - rusqlite::Connection::open(&database_path) - .unwrap() - .execute_batch(&format!("pragma user_version = {newer};")) - .unwrap(); - - assert_eq!( - open_connection(&database_path).unwrap_err(), - HistoryReadError::UnsupportedSchema { - found: newer, - supported: supported_mod_db_user_versions_label(), - } - ); - } - - #[test] - fn cleanup_connection_enables_foreign_key_cascade() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join("bazaarplusplus.db"); - { - let conn = rusqlite::Connection::open(&database_path).unwrap(); - conn.execute_batch( - "pragma user_version = 1; - create table parents (id text primary key); - create table children ( - id text primary key, - parent_id text not null, - foreign key (parent_id) references parents(id) on delete cascade - ); - insert into parents values ('p1'); - insert into children values ('c1', 'p1');", - ) - .unwrap(); - } - - let conn = super::open_cleanup_connection(&database_path).unwrap(); - conn.execute("delete from parents where id = 'p1'", []) - .unwrap(); - - let remaining: i64 = conn - .query_row("select count(*) from children", [], |row| row.get(0)) - .unwrap(); - assert_eq!(remaining, 0, "cascade must fire on the cleanup connection"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/repo.rs b/bazaarplusplus-installer/src-tauri/src/history/repo.rs deleted file mode 100644 index 0ba5870..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/repo.rs +++ /dev/null @@ -1,346 +0,0 @@ -use std::path::{Path, PathBuf}; - -use rusqlite::params; - -pub use crate::history::dto::{HistoryRunDetail, HistoryRunList, HistorySummary}; - -use crate::history::dto::HistoryRunDetail as HistoryRunDetailDto; -use crate::history::files::{remove_video_file, resolve_data_file_path, resolve_screenshot_path}; -use crate::history::mapper::{map_run_to_detail_row, map_run_to_list_row}; -use crate::history::queries::{ - self, list_run_rows, load_battle_rows, load_battle_video_ref, load_run_row, load_summary, - local_player_name, open_connection, open_write_connection, table_exists, HistoryReadError, -}; -use crate::history::screenshots::{primary_screenshot, primary_screenshot_ids}; - -/// `thumbnail_url` names the History Thumbnail of a screenshot id. -pub fn list_history_runs( - database_path: &Path, - limit: usize, - offset: usize, - thumbnail_url: impl Fn(&str) -> String, -) -> Result { - let empty = || HistoryRunList { - summary: HistorySummary { - runs: 0, - videos: 0, - win_rate: None, - }, - runs: Vec::new(), - }; - - if !database_path.exists() { - return Ok(empty()); - } - - let conn = open_connection(database_path)?; - if !table_exists(&conn, "runs")? { - return Ok(empty()); - } - - let summary = load_summary(&conn)?; - let effective_limit = i64::try_from(limit.max(1)).map_err(|err| err.to_string())?; - let effective_offset = i64::try_from(offset).map_err(|err| err.to_string())?; - let rows = list_run_rows(&conn, effective_limit, effective_offset)?; - let run_ids = rows - .iter() - .map(|row| row.run_id.clone()) - .collect::>(); - let screenshot_ids = primary_screenshot_ids(&conn, &run_ids)?; - - let runs = rows - .into_iter() - .map(|row| { - let screenshot_id = screenshot_ids.get(&row.run_id).cloned(); - map_run_to_list_row(row, screenshot_id, &thumbnail_url) - }) - .collect(); - - Ok(HistoryRunList { summary, runs }) -} - -pub fn get_history_run_detail( - database_path: &Path, - run_id: &str, -) -> Result, HistoryReadError> { - if !database_path.exists() { - return Ok(None); - } - - let conn = open_connection(database_path)?; - if !table_exists(&conn, "runs")? { - return Ok(None); - } - - let Some(row) = load_run_row(&conn, run_id)? else { - return Ok(None); - }; - let screenshot_id = primary_screenshot(&conn, run_id)?.map(|screenshot| screenshot.id); - let player_name = local_player_name(&conn, run_id)?; - let battles = load_battle_rows(&conn, run_id)?; - - Ok(Some(HistoryRunDetailDto { - run: map_run_to_detail_row(row, screenshot_id, player_name), - battles, - })) -} - -pub fn load_run_screenshot_path( - database_path: &Path, - data_root: &Path, - run_id: &str, -) -> Result, String> { - let conn = open_connection(database_path)?; - let path = primary_screenshot(&conn, run_id)? - .and_then(|screenshot| resolve_screenshot_path(data_root, &screenshot.image_relative_path)); - Ok(path) -} - -pub fn load_battle_video_path( - database_path: &Path, - video_dir: &Path, - battle_id: &str, - video_id: &str, -) -> Result, String> { - let conn = open_connection(database_path)?; - let row = load_battle_video_ref(&conn, battle_id, video_id)?; - Ok(row.and_then(|video| resolve_data_file_path(video_dir, &video.relative_path))) -} - -pub fn load_run_id_for_battle( - database_path: &Path, - battle_id: &str, -) -> Result, String> { - let conn = open_connection(database_path)?; - queries::load_run_id_for_battle(&conn, battle_id) -} - -pub fn delete_battle_video( - database_path: &Path, - video_dir: &Path, - battle_id: &str, - video_id: &str, -) -> Result { - let mut conn = open_write_connection(database_path)?; - let Some(video) = load_battle_video_ref(&conn, battle_id, video_id)? else { - return Ok(false); - }; - remove_video_file(video_dir, &video.relative_path)?; - let transaction = conn.transaction().map_err(|err| err.to_string())?; - let deleted = transaction - .execute( - "delete from combat_replay_videos where battle_id = ?1 and video_id = ?2", - params![battle_id, video_id], - ) - .map_err(|err| err.to_string())?; - transaction.commit().map_err(|err| err.to_string())?; - Ok(deleted > 0) -} - -#[cfg(test)] -mod tests { - use super::{delete_battle_video, get_history_run_detail, list_history_runs}; - use crate::config::DATABASE_FILE_NAME; - use crate::history::dto::{HistoryBattleRow, HistoryBattleVideo}; - use crate::history::mod_schema::create_mod_schema; - use crate::services::paths; - - #[test] - fn list_history_runs_derives_summary_results_and_thumbnail_urls() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join(DATABASE_FILE_NAME); - let conn = rusqlite::Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - conn.execute_batch( - " - insert into runs ( - run_id, started_at_ms, last_seen_at_ms, status, - hero, game_mode, ended_at_ms, final_day, victories, losses, - final_player_rank, final_player_rating, final_player_rating_delta - ) values - ('run-win', 1779271200000, 1779274800000, 'completed', - 'Vanessa', 'Ranked', 1779274800000, 10, 10, 2, 'Diamond II', 1450, 24), - ('run-loss', 1779184800000, 1779187200000, 'completed', - 'Dooley', 'Ranked', 1779187200000, 6, 4, 3, 'Gold I', 1100, -18), - ('run-live', 1779357600000, 1779358800000, 'active', - 'Mak', 'Normal', null, null, null, null, null, null, null); - - insert into run_screenshots ( - screenshot_id, run_id, hero_name, capture_source, is_primary, - image_relative_path, captured_at_ms, captured_utc_offset_minutes - ) values - ('shot-win', 'run-win', 'Vanessa', 'end_of_run_auto', 1, - 'win.png', 1779274800000, 480); - - insert into battles ( - battle_id, source, run_id, recorded_at_ms, combat_kind, opponent_name, local_payload_state - ) values - ('battle-1', 'LOCAL', 'run-win', 1779273000000, 'PVP', 'Opponent', 'missing'); - - insert into combat_replay_videos ( - video_id, battle_id, source, video_relative_path, width, height, fps, codec, - started_at_ms, duration_ms, file_size_bytes, status - ) values - ('video-1', 'battle-1', 'GAME_CAPTURE', 'Videos/video-1.mp4', 1920, 1080, 60, - 'h264', 1779273060000, 1000, 2000, 'COMPLETED'); - ", - ) - .unwrap(); - - let payload = - list_history_runs(&database_path, 20, 0, |id| format!("thumbnail:{id}")).unwrap(); - - assert_eq!(payload.summary.runs, 3); - assert_eq!(payload.summary.videos, 1); - assert_eq!(payload.summary.win_rate, Some(0.5)); - assert_eq!(payload.runs.len(), 3); - assert_eq!(payload.runs[0].run_id, "run-live"); - assert_eq!(payload.runs[0].result, "in_progress"); - assert_eq!(payload.runs[1].run_id, "run-win"); - assert_eq!(payload.runs[1].result, "win"); - assert_eq!( - payload.runs[1].thumbnail_url.as_deref(), - Some("thumbnail:shot-win") - ); - assert_eq!(payload.runs[2].run_id, "run-loss"); - assert_eq!(payload.runs[2].result, "loss"); - } - - #[test] - fn history_pages_reach_older_runs_without_duplicates_and_keep_the_full_summary() { - let temp_dir = tempfile::tempdir().unwrap(); - let database_path = temp_dir.path().join(DATABASE_FILE_NAME); - let conn = rusqlite::Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - for index in 0..235 { - conn.execute( - "insert into runs (run_id, started_at_ms, last_seen_at_ms, status, hero, game_mode) - values (?1, 1789207200000, 1789210800000, 'active', 'Vanessa', 'Ranked')", - [format!("run-{index:03}")], - ) - .unwrap(); - } - - let mut ids = Vec::new(); - for offset in [0, 50, 100, 150, 200] { - let page = list_history_runs(&database_path, 50, offset, str::to_string).unwrap(); - assert_eq!(page.summary.runs, 235); - assert_eq!(page.runs.len(), if offset == 200 { 35 } else { 50 }); - ids.extend(page.runs.into_iter().map(|run| run.run_id)); - } - let expected: Vec<_> = (0..235) - .rev() - .map(|index| format!("run-{index:03}")) - .collect(); - assert_eq!(ids, expected); - let beyond_end = list_history_runs(&database_path, 50, 250, str::to_string).unwrap(); - assert!(beyond_end.runs.is_empty()); - assert_eq!(beyond_end.summary.runs, 235); - } - - #[test] - fn run_detail_maps_local_battles_latest_completed_video_and_deletes_video_rows() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path(); - let video_dir = paths::combat_replay_videos_dir(game_path); - let dated_videos_dir = video_dir.join("2026-05-20"); - std::fs::create_dir_all(&dated_videos_dir).unwrap(); - std::fs::write(dated_videos_dir.join("new.mp4"), b"new-video").unwrap(); - std::fs::write(dated_videos_dir.join("old.mp4"), b"old-video").unwrap(); - - let database_path = paths::database_path(game_path); - let conn = rusqlite::Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - conn.execute_batch( - " - insert into runs ( - run_id, started_at_ms, last_seen_at_ms, status, - hero, game_mode, ended_at_ms, final_day, final_hour, victories, losses, - final_player_rank, final_player_rating - ) values ( - 'run-win', 1779271200000, 1779274800000, 'completed', - 'Vanessa', 'Ranked', 1779274800000, 10, 7, 10, 2, - 'Diamond II', 1450 - ); - - insert into run_screenshots ( - screenshot_id, run_id, hero_name, capture_source, is_primary, - image_relative_path, captured_at_ms, captured_utc_offset_minutes - ) values ( - 'shot-win', 'run-win', 'Vanessa', 'end_of_run_auto', 1, - 'win.png', 1779274800000, 480 - ); - - insert into battles ( - battle_id, source, run_id, recorded_at_ms, combat_kind, day, hour, - player_name, opponent_hero, opponent_name, opponent_rank, opponent_rating, result, local_payload_state, remote_battle_id, uploader_account_id - ) values - ('battle-1', 'LOCAL', 'run-win', 1779273000000, 'PVP', 8, 1, - 'cauyxy', 'Dooley', 'Opponent A', 'Diamond III', 1410, 'Won', 'ready', - null, null), - ('battle-2', 'LOCAL', 'run-win', 1779271800000, 'PVP', 7, 0, - 'cauyxy', 'Pygmalien', 'Opponent B', 'Diamond IV', 1360, 'Lost', 'missing', - null, null), - ('battle-ghost', 'GHOST', null, 1779273600000, 'PVP', 9, 0, - 'cauyxy', 'Mak', 'Ghost', 'Diamond I', 1500, 'Won', null, - 'remote-ghost', 'uploader-1'); - - insert into combat_replay_videos ( - video_id, battle_id, source, video_relative_path, width, height, fps, codec, - started_at_ms, duration_ms, file_size_bytes, status - ) values - ('video-old', 'battle-1', 'GAME_CAPTURE', '2026-05-20/old.mp4', 1920, 1080, 60, - 'h264', 1779273060000, 1000, 2000, 'COMPLETED'), - ('video-new', 'battle-1', 'GAME_CAPTURE', '2026-05-20/new.mp4', 1920, 1080, 60, - 'h264', 1779273120000, 1200, 2200, 'COMPLETED'), - ('video-failed', 'battle-2', 'GAME_CAPTURE', '2026-05-20/failed.mp4', 1920, 1080, - 60, 'h264', 1779271860000, null, null, 'FAILED'); - ", - ) - .unwrap(); - drop(conn); - - let detail = get_history_run_detail(&database_path, "run-win") - .unwrap() - .unwrap(); - assert_eq!(detail.run.player_name.as_deref(), Some("cauyxy")); - assert_eq!(detail.run.screenshot_id.as_deref(), Some("shot-win")); - assert_eq!(detail.battles.len(), 2); - assert_eq!( - detail.battles[0], - HistoryBattleRow { - battle_id: "battle-1".to_string(), - day: Some(8), - hour: Some(1), - result: "win".to_string(), - opponent_hero: Some("Dooley".to_string()), - opponent_name: Some("Opponent A".to_string()), - opponent_rank: Some("Diamond III".to_string()), - opponent_rating: Some(1410), - video: Some(HistoryBattleVideo { - video_id: "video-new".to_string(), - status: "COMPLETED".to_string(), - file_size_bytes: Some(2200), - duration_ms: Some(1200), - }), - } - ); - assert_eq!(detail.battles[1].battle_id, "battle-2"); - assert_eq!(detail.battles[1].result, "loss"); - assert_eq!(detail.battles[1].video, None); - - assert!(delete_battle_video(&database_path, &video_dir, "battle-1", "video-new").unwrap()); - assert!(!dated_videos_dir.join("new.mp4").exists()); - - let detail = get_history_run_detail(&database_path, "run-win") - .unwrap() - .unwrap(); - assert_eq!( - detail.battles[0] - .video - .as_ref() - .map(|video| video.video_id.as_str()), - Some("video-old") - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/history/screenshots.rs b/bazaarplusplus-installer/src-tauri/src/history/screenshots.rs deleted file mode 100644 index 97d44c3..0000000 --- a/bazaarplusplus-installer/src-tauri/src/history/screenshots.rs +++ /dev/null @@ -1,733 +0,0 @@ -use std::{collections::HashMap, path::Path}; - -use chrono::DateTime; -use rusqlite::{params_from_iter, Connection, OptionalExtension}; - -use crate::history::instant::{local_text, utc_text}; -use crate::history::queries::{open_connection, sql_placeholders, table_exists}; - -pub struct ScreenshotRef { - pub id: String, - pub image_relative_path: String, -} - -#[derive(Clone, Debug)] -pub struct OverlaySnapshotRow { - pub id: String, - pub hero: String, - pub game_mode: String, - pub captured_at: String, - pub captured_at_utc: String, - pub image_path: Option, - pub wins: Option, - pub battle_count: Option, - pub rank: Option, - pub rating: Option, -} - -pub fn primary_screenshot_ids( - conn: &Connection, - run_ids: &[String], -) -> Result, String> { - if run_ids.is_empty() || !table_exists(conn, "run_screenshots")? { - return Ok(HashMap::new()); - } - - let mut selected = HashMap::new(); - let placeholders = sql_placeholders(run_ids.len()); - let primary_sql = format!( - " - select run_id, screenshot_id - from run_screenshots - where run_id in ({placeholders}) and is_primary = 1 - " - ); - let mut stmt = conn.prepare(&primary_sql).map_err(|err| err.to_string())?; - let rows = stmt - .query_map(params_from_iter(run_ids.iter()), |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) - }) - .map_err(|err| err.to_string())?; - - for row in rows { - let (run_id, screenshot_id) = row.map_err(|err| err.to_string())?; - selected.entry(run_id).or_insert(screenshot_id); - } - - let missing_run_ids = run_ids - .iter() - .filter(|run_id| !selected.contains_key(*run_id)) - .collect::>(); - if missing_run_ids.is_empty() { - return Ok(selected); - } - - let placeholders = sql_placeholders(missing_run_ids.len()); - let fallback_sql = format!( - " - select run_id, screenshot_id - from run_screenshots - where run_id in ({placeholders}) and capture_source = 'end_of_run_auto' - order by run_id asc, captured_at_ms desc, screenshot_id desc - " - ); - let mut stmt = conn.prepare(&fallback_sql).map_err(|err| err.to_string())?; - let rows = stmt - .query_map(params_from_iter(missing_run_ids), |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) - }) - .map_err(|err| err.to_string())?; - - for row in rows { - let (run_id, screenshot_id) = row.map_err(|err| err.to_string())?; - selected.entry(run_id).or_insert(screenshot_id); - } - - Ok(selected) -} - -pub fn primary_screenshot( - conn: &Connection, - run_id: &str, -) -> Result, String> { - if !table_exists(conn, "run_screenshots")? { - return Ok(None); - } - - let primary = conn - .query_row( - " - select screenshot_id, image_relative_path - from run_screenshots - where run_id = ?1 and is_primary = 1 - limit 1 - ", - [run_id], - |row| { - Ok(ScreenshotRef { - id: row.get(0)?, - image_relative_path: row.get(1)?, - }) - }, - ) - .optional() - .map_err(|err| err.to_string())?; - if primary.is_some() { - return Ok(primary); - } - - conn.query_row( - " - select screenshot_id, image_relative_path - from run_screenshots - where run_id = ?1 and capture_source = 'end_of_run_auto' - order by captured_at_ms desc, screenshot_id desc - limit 1 - ", - [run_id], - |row| { - Ok(ScreenshotRef { - id: row.get(0)?, - image_relative_path: row.get(1)?, - }) - }, - ) - .optional() - .map_err(|err| err.to_string()) -} - -pub fn load_latest_overlay_snapshot( - database_path: &Path, - from: Option<&str>, - offset: usize, -) -> Result, String> { - if !database_path.exists() { - return Ok(None); - } - - let conn = open_connection(database_path)?; - if !table_exists(&conn, "run_screenshots")? { - return Ok(None); - } - - let offset_value = i64::try_from(offset).map_err(|err| err.to_string())?; - let from_ms = from.map(overlay_from_ms); - let mut stmt = if from.is_some() { - conn.prepare( - " -select - rs.screenshot_id, - coalesce(nullif(trim(rs.hero_name), ''), 'Unknown') as hero, - 'End of run' as game_mode, - rs.captured_utc_offset_minutes, - rs.image_relative_path as image_path, - rs.victories_at_capture as wins, - rs.day as battle_count, - nullif(trim(rs.player_rank), '') as player_rank, - rs.player_rating as player_rating, - rs.captured_at_ms -from run_screenshots rs -where rs.capture_source = 'end_of_run_auto' - and rs.captured_at_ms >= ?1 -order by rs.captured_at_ms desc, rs.screenshot_id desc -limit 1 offset ?2 -", - ) - } else { - conn.prepare( - " -select - rs.screenshot_id, - coalesce(nullif(trim(rs.hero_name), ''), 'Unknown') as hero, - 'End of run' as game_mode, - rs.captured_utc_offset_minutes, - rs.image_relative_path as image_path, - rs.victories_at_capture as wins, - rs.day as battle_count, - nullif(trim(rs.player_rank), '') as player_rank, - rs.player_rating as player_rating, - rs.captured_at_ms -from run_screenshots rs -where rs.capture_source = 'end_of_run_auto' -order by rs.captured_at_ms desc, rs.screenshot_id desc -limit 1 offset ?1 -", - ) - } - .map_err(|err| err.to_string())?; - let mut rows = if let Some(from_ms) = from_ms { - stmt.query((from_ms, offset_value)) - .map_err(|err| err.to_string())? - } else { - stmt.query([offset_value]).map_err(|err| err.to_string())? - }; - let Some(row) = rows.next().map_err(|err| err.to_string())? else { - return Ok(None); - }; - - Ok(Some(map_overlay_snapshot_row(row)?)) -} - -pub fn load_overlay_snapshot_count( - database_path: &Path, - from: Option<&str>, -) -> Result { - if !database_path.exists() { - return Ok(0); - } - - let conn = open_connection(database_path)?; - if !table_exists(&conn, "run_screenshots")? { - return Ok(0); - } - - let count: i64 = if let Some(from) = from { - let from_ms = overlay_from_ms(from); - conn.query_row( - " -select count(*) -from run_screenshots rs -where rs.capture_source = 'end_of_run_auto' - and rs.captured_at_ms >= ?1 -", - [from_ms], - |row| row.get(0), - ) - .map_err(|err| err.to_string())? - } else { - conn.query_row( - " -select count(*) -from run_screenshots rs -where rs.capture_source = 'end_of_run_auto' -", - [], - |row| row.get(0), - ) - .map_err(|err| err.to_string())? - }; - - usize::try_from(count).map_err(|err| err.to_string()) -} - -pub fn load_overlay_snapshot_list( - database_path: &Path, - from: Option<&str>, - limit: Option, -) -> Result, String> { - if !database_path.exists() { - return Ok(Vec::new()); - } - - let conn = open_connection(database_path)?; - if !table_exists(&conn, "run_screenshots")? { - return Ok(Vec::new()); - } - - let effective_limit = limit.unwrap_or(20); - if effective_limit == 0 { - return Ok(Vec::new()); - } - let limit_value = i64::try_from(effective_limit).map_err(|err| err.to_string())?; - let from_ms = from.map(overlay_from_ms); - - let mut records = Vec::new(); - let mut stmt = if from.is_some() { - conn.prepare( - " -select - rs.screenshot_id, - coalesce(nullif(trim(rs.hero_name), ''), 'Unknown') as hero, - 'End of run' as game_mode, - rs.captured_utc_offset_minutes, - rs.image_relative_path as image_path, - rs.victories_at_capture as wins, - rs.day as battle_count, - nullif(trim(rs.player_rank), '') as player_rank, - rs.player_rating as player_rating, - rs.captured_at_ms -from run_screenshots rs -where rs.capture_source = 'end_of_run_auto' - and rs.captured_at_ms >= ?1 -order by rs.captured_at_ms desc, rs.screenshot_id desc -limit ?2 -", - ) - } else { - conn.prepare( - " -select - rs.screenshot_id, - coalesce(nullif(trim(rs.hero_name), ''), 'Unknown') as hero, - 'End of run' as game_mode, - rs.captured_utc_offset_minutes, - rs.image_relative_path as image_path, - rs.victories_at_capture as wins, - rs.day as battle_count, - nullif(trim(rs.player_rank), '') as player_rank, - rs.player_rating as player_rating, - rs.captured_at_ms -from run_screenshots rs -where rs.capture_source = 'end_of_run_auto' -order by rs.captured_at_ms desc, rs.screenshot_id desc -limit ?1 -", - ) - } - .map_err(|err| err.to_string())?; - let mut rows = if let Some(from_ms) = from_ms { - stmt.query((from_ms, limit_value)) - .map_err(|err| err.to_string())? - } else { - stmt.query([limit_value]).map_err(|err| err.to_string())? - }; - while let Some(row) = rows.next().map_err(|err| err.to_string())? { - records.push(map_overlay_snapshot_row(row)?); - } - - Ok(records) -} - -pub fn load_overlay_snapshot_by_id( - database_path: &Path, - record_id: &str, -) -> Result, String> { - if !database_path.exists() { - return Ok(None); - } - - let conn = open_connection(database_path)?; - if !table_exists(&conn, "run_screenshots")? { - return Ok(None); - } - - let mut stmt = conn - .prepare( - " -select - rs.screenshot_id, - coalesce(nullif(trim(rs.hero_name), ''), 'Unknown') as hero, - 'End of run' as game_mode, - rs.captured_utc_offset_minutes, - rs.image_relative_path as image_path, - rs.victories_at_capture as wins, - rs.day as battle_count, - nullif(trim(rs.player_rank), '') as player_rank, - rs.player_rating as player_rating, - rs.captured_at_ms -from run_screenshots rs -where rs.capture_source = 'end_of_run_auto' - and rs.screenshot_id = ?1 -limit 1 -", - ) - .map_err(|err| err.to_string())?; - - let mut rows = stmt.query([record_id]).map_err(|err| err.to_string())?; - let Some(row) = rows.next().map_err(|err| err.to_string())? else { - return Ok(None); - }; - - Ok(Some(map_overlay_snapshot_row(row)?)) -} - -/// The stored image path of any screenshot, whatever its capture source: History -/// shows a run's primary screenshot, which need not be an end-of-run capture. -pub fn load_screenshot_image_path( - database_path: &Path, - screenshot_id: &str, -) -> Result, String> { - if !database_path.exists() { - return Ok(None); - } - - let conn = open_connection(database_path)?; - if !table_exists(&conn, "run_screenshots")? { - return Ok(None); - } - - conn.query_row( - "select image_relative_path from run_screenshots where screenshot_id = ?1", - [screenshot_id], - |row| row.get(0), - ) - .optional() - .map_err(|err| err.to_string()) -} - -fn map_overlay_snapshot_row(row: &rusqlite::Row<'_>) -> Result { - let captured_at_ms: i64 = row.get(9).map_err(|err| err.to_string())?; - let utc_offset_minutes: i64 = row.get(3).map_err(|err| err.to_string())?; - let unrepresentable = - || format!("captured_at_ms {captured_at_ms} is not a representable instant"); - Ok(OverlaySnapshotRow { - id: row.get(0).map_err(|err| err.to_string())?, - hero: row.get(1).map_err(|err| err.to_string())?, - game_mode: row.get(2).map_err(|err| err.to_string())?, - captured_at: local_text(captured_at_ms, utc_offset_minutes).ok_or_else(unrepresentable)?, - image_path: row.get(4).map_err(|err| err.to_string())?, - wins: row.get(5).map_err(|err| err.to_string())?, - battle_count: row.get(6).map_err(|err| err.to_string())?, - rank: row.get(7).map_err(|err| err.to_string())?, - rating: row.get(8).map_err(|err| err.to_string())?, - captured_at_utc: utc_text(captured_at_ms).ok_or_else(unrepresentable)?, - }) -} - -/// The overlay's `from` bound as a stored instant. A value that is not RFC 3339 -/// matches no record rather than every record. -fn overlay_from_ms(value: &str) -> i64 { - DateTime::parse_from_rfc3339(value.trim()) - .map(|parsed| parsed.timestamp_millis()) - .unwrap_or(i64::MAX) -} - -#[cfg(test)] -mod tests { - use super::{ - load_latest_overlay_snapshot, load_overlay_snapshot_by_id, load_overlay_snapshot_count, - load_overlay_snapshot_list, load_screenshot_image_path, overlay_from_ms, - }; - use crate::history::mod_schema::create_mod_schema; - - #[test] - fn latest_overlay_record_returns_none_when_database_has_no_rows() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - - let latest = load_latest_overlay_snapshot(temp.path(), None, 0).unwrap(); - assert!(latest.is_none()); - } - - #[test] - fn latest_overlay_record_reads_latest_end_of_run_snapshot() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, - captured_at_ms, day, player_rank, player_rating, player_position, victories_at_capture, hero_name - ) values ( - 'snap-1', 'run-1', 'end_of_run_auto', '2026-04-10\\shot-1.png', - 480, 1775853005000, - 14, 'Diamond', 1942, 1, 10, 'Mak' - )", - [], - ) - .unwrap(); - - let latest = load_latest_overlay_snapshot(temp.path(), None, 0) - .unwrap() - .unwrap(); - assert_eq!(latest.id, "snap-1"); - assert_eq!(latest.hero, "Mak"); - assert_eq!(latest.game_mode, "End of run"); - assert_eq!(latest.image_path.as_deref(), Some("2026-04-10\\shot-1.png")); - assert_eq!(latest.wins, Some(10)); - assert_eq!(latest.battle_count, Some(14)); - assert_eq!(latest.rank.as_deref(), Some("Diamond")); - assert_eq!(latest.rating, Some(1942)); - } - - #[test] - fn latest_overlay_record_ignores_other_snapshot_types() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, captured_at_ms - ) values - ('snap-1', 'run-1', 'pvp_battle_start', 'battle-1.png', 0, 1775853005000), - ('snap-2', 'run-2', 'end_of_run_auto', 'final-2.png', 0, 1775856605000)", - [], - ) - .unwrap(); - - let latest = load_latest_overlay_snapshot(temp.path(), None, 0) - .unwrap() - .unwrap(); - assert_eq!(latest.id, "snap-2"); - } - - #[test] - fn latest_overlay_record_returns_none_when_database_file_is_missing() { - let temp_dir = tempfile::tempdir().unwrap(); - let missing = temp_dir.path().join("missing-bazaarplusplus.db"); - let latest = load_latest_overlay_snapshot(&missing, None, 0).unwrap(); - - assert!(latest.is_none()); - } - - #[test] - fn latest_overlay_record_supports_backtracking_from_latest() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, captured_at_ms, hero_name - ) values - ('snap-1', 'run-1', 'end_of_run_auto', 'final-1.png', 0, 1775853005000, 'Mak'), - ('snap-2', 'run-2', 'end_of_run_auto', 'final-2.png', 0, 1775856605000, 'Pygmalien'), - ('snap-3', 'run-3', 'end_of_run_auto', 'final-3.png', 0, 1775860205000, 'Vanessa')", - [], - ) - .unwrap(); - - let latest = load_latest_overlay_snapshot(temp.path(), None, 0) - .unwrap() - .unwrap(); - let previous = load_latest_overlay_snapshot(temp.path(), None, 1) - .unwrap() - .unwrap(); - let oldest = load_latest_overlay_snapshot(temp.path(), None, 2) - .unwrap() - .unwrap(); - let beyond = load_latest_overlay_snapshot(temp.path(), None, 3).unwrap(); - - assert_eq!(latest.id, "snap-3"); - assert_eq!(previous.id, "snap-2"); - assert_eq!(oldest.id, "snap-1"); - assert_eq!(latest.hero, "Vanessa"); - assert_eq!(previous.hero, "Pygmalien"); - assert!(beyond.is_none()); - } - - #[test] - fn latest_overlay_record_filters_from_stream_start_time() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, captured_at_ms, hero_name - ) values - ('snap-before', 'run-1', 'end_of_run_auto', 'before.png', 0, 1775849405000, 'Mak'), - ('snap-after', 'run-2', 'end_of_run_auto', 'after.png', 0, 1775856605000, 'Pygmalien')", - [], - ) - .unwrap(); - - let latest = - load_latest_overlay_snapshot(temp.path(), Some("2026-04-10T20:00:00+00:00"), 0) - .unwrap() - .unwrap(); - - assert_eq!(latest.id, "snap-after"); - } - - #[test] - fn latest_overlay_record_normalizes_stream_start_time_to_utc() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, captured_at_ms, hero_name - ) values - ('snap-before', 'run-1', 'end_of_run_auto', 'before.png', 0, 1775849405000, 'Mak'), - ('snap-after', 'run-2', 'end_of_run_auto', 'after.png', 0, 1775856605000, 'Pygmalien')", - [], - ) - .unwrap(); - - let latest = - load_latest_overlay_snapshot(temp.path(), Some("2026-04-11T04:00:00+08:00"), 0) - .unwrap() - .unwrap(); - - assert_eq!(latest.id, "snap-after"); - assert_eq!( - overlay_from_ms("2026-04-11T04:00:00+08:00"), - 1_775_851_200_000 - ); - assert_eq!(overlay_from_ms("not a time"), i64::MAX); - } - - #[test] - fn overlay_record_count_only_counts_records_after_stream_start() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, captured_at_ms - ) values - ('snap-before', 'run-1', 'end_of_run_auto', 'before.png', 0, 1775849405000), - ('snap-after-1', 'run-2', 'end_of_run_auto', 'after-1.png', 0, 1775856605000), - ('snap-after-2', 'run-3', 'end_of_run_auto', 'after-2.png', 0, 1775860205000), - ('snap-mid', 'run-4', 'pvp_battle_start', 'mid.png', 0, 1775863805000)", - [], - ) - .unwrap(); - - let count = - load_overlay_snapshot_count(temp.path(), Some("2026-04-10T20:00:00+00:00")).unwrap(); - - assert_eq!(count, 2); - } - - #[test] - fn load_overlay_record_by_id_reads_matching_snapshot() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, captured_at_ms, hero_name - ) values ('snap-1', 'run-1', 'end_of_run_auto', 'match-1.png', 0, 1775853005000, 'Mak')", - [], - ) - .unwrap(); - - let record = load_overlay_snapshot_by_id(temp.path(), "snap-1") - .unwrap() - .unwrap(); - - assert_eq!(record.id, "snap-1"); - } - - #[test] - fn screenshot_image_path_ignores_the_capture_source_the_overlay_requires() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, is_primary, image_relative_path, - captured_utc_offset_minutes, captured_at_ms - ) values ('manual-1', 'run-1', 'manual', 1, 'manual-1.png', - 0, 1775853005000)", - [], - ) - .unwrap(); - - assert!(load_overlay_snapshot_by_id(temp.path(), "manual-1") - .unwrap() - .is_none()); - assert_eq!( - load_screenshot_image_path(temp.path(), "manual-1") - .unwrap() - .as_deref(), - Some("manual-1.png") - ); - assert_eq!( - load_screenshot_image_path(temp.path(), "missing").unwrap(), - None - ); - } - - #[test] - fn latest_overlay_record_uses_unknown_hero_when_screenshot_is_anonymous() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, captured_at_ms - ) values ( - 'snap-1', null, 'end_of_run_auto', 'anon.png', 0, 1775853005000 - )", - [], - ) - .unwrap(); - - let latest = load_latest_overlay_snapshot(temp.path(), None, 0) - .unwrap() - .unwrap(); - - assert_eq!(latest.hero, "Unknown"); - assert_eq!(latest.game_mode, "End of run"); - } - - #[test] - fn overlay_record_list_returns_latest_records_in_descending_order() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, - captured_at_ms, victories_at_capture, hero_name - ) values - ('snap-1', 'run-1', 'end_of_run_auto', 'first.png', 0, 1775853005000, 7, 'Mak'), - ('snap-2', 'run-2', 'end_of_run_auto', 'second.png', 0, 1775856605000, 10, 'Pygmalien'), - ('snap-3', 'run-3', 'end_of_run_auto', 'third.png', 0, 1775860205000, 4, 'Vanessa')", - [], - ) - .unwrap(); - - let records = load_overlay_snapshot_list(temp.path(), None, Some(2)).unwrap(); - - assert_eq!(records.len(), 2); - assert_eq!(records[0].id, "snap-3"); - assert_eq!(records[1].id, "snap-2"); - } - - #[test] - fn overlay_record_list_without_limit_returns_all_records() { - let temp = tempfile::NamedTempFile::new().unwrap(); - let conn = rusqlite::Connection::open(temp.path()).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, - captured_at_ms, hero_name - ) values - ('snap-1', 'run-1', 'end_of_run_auto', 'first.png', 0, 1775853005000, 'Mak'), - ('snap-2', 'run-2', 'end_of_run_auto', 'second.png', 0, 1775856605000, 'Pygmalien'), - ('snap-3', 'run-3', 'end_of_run_auto', 'third.png', 0, 1775860205000, 'Vanessa')", - [], - ) - .unwrap(); - - let records = load_overlay_snapshot_list(temp.path(), None, None).unwrap(); - - assert_eq!(records.len(), 3); - assert_eq!(records[0].id, "snap-3"); - assert_eq!(records[2].id, "snap-1"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/ipc_golden_tests.rs b/bazaarplusplus-installer/src-tauri/src/ipc_golden_tests.rs deleted file mode 100644 index 6ab383f..0000000 --- a/bazaarplusplus-installer/src-tauri/src/ipc_golden_tests.rs +++ /dev/null @@ -1,360 +0,0 @@ -//! IPC JSON goldens: the DTOs `get_install_state`, `get_legacy_data_state`, -//! `import_v5_history`, `delete_legacy_root`, `list_history_runs`, -//! `get_history_run_detail` and `preview_storage_cleanup` return to the frontend, produced by the service layer each command wraps from a fixture -//! game directory and database. The commands themselves are not driven through -//! the IPC bridge: through IPC, `get_install_state` and history path resolution -//! read the host's Steam installation and bundled resources (see #154), so the -//! output would not be repeatable. -//! -//! Every input is platform neutral, so macOS and Windows produce the same -//! bytes. Writes `tests/goldens/ipc/..json`; regenerate with -//! `BPP_UPDATE_GOLDENS=1 npm run generate:bindings:test` (see the installer `AGENTS.md`). - -use std::path::{Path, PathBuf}; - -use crate::goldens::{assert_golden, json}; -use crate::history::mod_schema::create_mod_schema; -use crate::services::detect::InstallEnvironmentSnapshot; -use crate::services::history::{History, StorageCleanupPreset, StorageCleanupScope}; -use crate::services::install::install_state_from_snapshot; -use crate::services::legacy_data; -use crate::services::paths; -use crate::services::vdf::SteamLaunchOptionsState; -use crate::stream::history_thumbnails::HistoryThumbnails; - -const GAME: &str = ""; -const STEAM: &str = ""; - -struct Fixture { - _temp: tempfile::TempDir, - game: PathBuf, - steam: PathBuf, -} - -impl Fixture { - fn new() -> Self { - let temp = tempfile::tempdir().unwrap(); - let game = temp.path().join("The Bazaar"); - let steam = temp.path().join("Steam"); - std::fs::create_dir_all(&game).unwrap(); - std::fs::create_dir_all(&steam).unwrap(); - Self { - _temp: temp, - game, - steam, - } - } - - fn json(&self, value: &impl serde::Serialize) -> String { - json(value, &[(&self.game, GAME), (&self.steam, STEAM)]) - } -} - -fn write(path: &Path, bytes: &[u8]) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, bytes).unwrap(); -} - -/// Detection facts for the fixture installation. The macOS bootstrap inputs -/// are the ready ones (empty launch options, current trampoline), so the -/// platform-specific warnings stay out of every state. -fn snapshot(fixture: &Fixture, installed_version: Option<&str>) -> InstallEnvironmentSnapshot { - InstallEnvironmentSnapshot { - steam_path: Some(fixture.steam.to_string_lossy().into_owned()), - game_path: Some(fixture.game.to_string_lossy().into_owned()), - game_path_valid: true, - bepinex_installed: installed_version.is_some(), - bpp_version: installed_version.map(str::to_owned), - bundled_bpp_version: Some("1.2.3".into()), - steam_launch_options: SteamLaunchOptionsState::Empty, - trampoline_current: true, - obsolete_macos_artifacts_present: false, - } -} - -fn install_installation(fixture: &Fixture) { - std::fs::create_dir_all(fixture.game.join("BepInEx/plugins")).unwrap(); - std::fs::create_dir_all(paths::bpp_data_dir(&fixture.game)).unwrap(); -} - -#[test] -fn get_install_state() { - let fixture = Fixture::new(); - let missing = InstallEnvironmentSnapshot { - steam_path: None, - game_path: None, - game_path_valid: false, - bepinex_installed: false, - bpp_version: None, - bundled_bpp_version: Some("1.2.3".into()), - steam_launch_options: SteamLaunchOptionsState::Empty, - trampoline_current: true, - obsolete_macos_artifacts_present: false, - }; - assert_golden( - "ipc/get_install_state.game-missing.json", - &fixture.json(&install_state_from_snapshot(missing)), - ); - assert_golden( - "ipc/get_install_state.installable.json", - &fixture.json(&install_state_from_snapshot(snapshot(&fixture, None))), - ); - - install_installation(&fixture); - assert_golden( - "ipc/get_install_state.installed.json", - &fixture.json(&install_state_from_snapshot(snapshot( - &fixture, - Some("1.2.3"), - ))), - ); - assert_golden( - "ipc/get_install_state.outdated.json", - &fixture.json(&install_state_from_snapshot(snapshot( - &fixture, - Some("1.2.2"), - ))), - ); -} - -/// Every Legacy Root with a few bytes, the current Data Root, and a 6.x mod -/// contract, as an upgraded 5.x user's game directory looks before importing. -fn seed_legacy_roots(fixture: &Fixture) { - let game = &fixture.game; - #[cfg(target_os = "macos")] - std::fs::create_dir_all(game.join("TheBazaar.app")).unwrap(); - #[cfg(target_os = "windows")] - write(&game.join("TheBazaar.exe"), b"exe"); - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - write(&game.join("TheBazaar"), b"exe"); - write(&game.join("BazaarPlusPlus/bazaarplusplus.db"), &[0; 12]); - write(&game.join("BazaarPlusPlusV4/bazaarplusplus.db"), &[0; 34]); - write(&game.join("BazaarPlusPlusV5/bazaarplusplus.db"), &[0; 56]); - write(&game.join("BazaarPlusPlusV5/Screenshots/run.png"), &[0; 7]); - write(&paths::database_path(game), b"current"); - write( - &game.join("BepInEx/plugins/BazaarPlusPlus.history-database.json"), - format!( - r#"{{ "formatVersion": 1, "dataRootDirectoryName": "{}", "historyDatabaseUserVersion": 1 }}"#, - crate::config::BAZAAR_DATA_DIRECTORY - ) - .as_bytes(), - ); -} - -const NO_INSTALLER_SETTINGS: &str = "/nonexistent-installer-settings"; - -#[test] -fn get_legacy_data_state() { - let fixture = Fixture::new(); - assert_golden( - "ipc/get_legacy_data_state.none.json", - &fixture.json(&legacy_data::legacy_data_state( - &fixture.game, - Path::new(NO_INSTALLER_SETTINGS), - )), - ); - - seed_legacy_roots(&fixture); - assert_golden( - "ipc/get_legacy_data_state.legacy-roots.json", - &fixture.json(&legacy_data::legacy_data_state( - &fixture.game, - Path::new(NO_INSTALLER_SETTINGS), - )), - ); -} - -#[test] -fn delete_legacy_root() { - let fixture = Fixture::new(); - seed_legacy_roots(&fixture); - let stopped = |_: &Path| Ok(false); - assert_golden( - "ipc/delete_legacy_root.removed.json", - &fixture.json( - &legacy_data::delete_legacy_root_blocking_with( - &fixture.game, - "BazaarPlusPlusV5", - Path::new(NO_INSTALLER_SETTINGS), - &stopped, - ) - .unwrap(), - ), - ); -} - -/// The V5 fixture game (`v5_import::tests_e2e`) imported with every file -/// copied, then remeasured: `BazaarPlusPlusV5` stays listed with the marker -/// inside and is no longer eligible. A game that is running refuses with the -/// import's own code. -#[test] -fn import_v5_history() { - use crate::v5_import::tests_e2e::{import_copying, v3_game}; - use crate::v5_import::ImportV5HistoryResult; - - let fixture = v3_game(); - let report = import_copying(&fixture, &|_: &Path| Ok(false)).unwrap(); - let result = ImportV5HistoryResult::new( - &report, - legacy_data::legacy_data_state(&fixture.game, Path::new(NO_INSTALLER_SETTINGS)), - ); - assert_golden( - "ipc/import_v5_history.imported.json", - &json(&result, &[(&fixture.game, GAME)]), - ); - - let running = v3_game(); - let refused = import_copying(&running, &|_: &Path| Ok(true)).unwrap_err(); - assert_golden( - "ipc/import_v5_history.blocked-by-game.json", - &json(&refused.into_problem(), &[(&running.game, GAME)]), - ); -} - -/// Three runs: a Ranked win with a primary screenshot and two battles (one -/// recorded) that is not yet sealed into a Bundle, so cleanup must skip it; a -/// Normal loss under the legacy `Hero8` name whose Bundle is already in the -/// outbox; and a run still in progress. -fn seed_history(fixture: &Fixture) { - let game = &fixture.game; - write( - &paths::screenshots_dir(game).join("2026-01-01/run-1.png"), - b"fixture screenshot 1", - ); - write( - &paths::screenshots_dir(game).join("2026-01-02/run-2.png"), - b"fixture screenshot 2", - ); - write( - &paths::combat_replay_videos_dir(game).join("2026-01-01/battle-1.mp4"), - b"fixture video", - ); - let conn = rusqlite::Connection::open(paths::database_path(game)).unwrap(); - create_mod_schema(&conn); - conn.execute_batch( - " - insert into runs ( - run_id, started_at_ms, last_seen_at_ms, status, hero, game_mode, - ended_at_ms, final_day, victories, losses, final_player_rank, final_player_rating, - final_player_rating_delta - ) values - ('run-1', 1767258000000, 1767260520000, 'completed', - 'Vanessa', 'Ranked', 1767260520000, 12, 10, 2, 'Gold', 1520, 16), - ('run-2', 1767344400000, 1767346200000, 'completed', - 'Hero8', 'Normal', 1767346200000, 8, 4, 5, null, null, null), - ('run-3', 1767430800000, 1767431400000, 'active', - 'Mak', 'Ranked', null, 3, 2, 1, null, null, null); - insert into battles ( - battle_id, source, run_id, recorded_at_ms, combat_kind, day, hour, player_name, - opponent_hero, opponent_name, opponent_rank, opponent_rating, result, local_payload_state - ) values - ('battle-1', 'LOCAL', 'run-1', 1767258600000, 'PVP', 1, 2, - 'Fixture Player', 'Pygmalien', 'Opponent A', 'Silver', 1400, 'win', 'missing'), - ('battle-2', 'LOCAL', 'run-1', 1767259200000, 'PVP', 2, 4, - 'Fixture Player', 'Dooley', null, null, null, 'loss', 'missing'), - ('battle-3', 'LOCAL', 'run-2', 1767345000000, 'PVP', 1, 1, - 'Fixture Player', 'Stelle', null, null, null, 'loss', 'missing'); - insert into run_screenshots ( - screenshot_id, run_id, hero_name, capture_source, is_primary, image_relative_path, - captured_at_ms, captured_utc_offset_minutes, day, victories_at_capture - ) values - ('shot-1', 'run-1', 'Vanessa', 'end_of_run_auto', 1, '2026-01-01/run-1.png', - 1767260520000, 480, 12, 10), - ('shot-2', 'run-2', 'Hero8', 'end_of_run_auto', 0, '2026-01-02/run-2.png', - 1767346200000, 480, 8, 4); - insert into combat_replay_videos ( - video_id, battle_id, source, video_relative_path, width, height, fps, codec, - started_at_ms, duration_ms, file_size_bytes, status - ) values - ('video-1', 'battle-1', 'GAME_CAPTURE', '2026-01-01/battle-1.mp4', 1920, 1080, 60, - 'h264', 1767258600000, 95000, 13, 'COMPLETED'); - insert into bundle_outbox ( - bundle_id, run_id, file_name, content_sha256_hex, content_digest, total_bytes, - has_screenshot, sealed_at_ms, status - ) values - ('bundle-2', 'run-2', 'bundle-2.bppbundle', 'ab', 'sha256:ab', 10, 1, - 1767346260000, 'pending'); - ", - ) - .unwrap(); -} - -fn history(fixture: &Fixture) -> History { - History::at_with(Some(fixture.game.clone()), || false).unwrap() -} - -#[test] -fn list_history_runs() { - let fixture = Fixture::new(); - std::fs::create_dir_all(paths::bpp_data_dir(&fixture.game)).unwrap(); - let conn = rusqlite::Connection::open(paths::database_path(&fixture.game)).unwrap(); - create_mod_schema(&conn); - drop(conn); - assert_golden( - "ipc/list_history_runs.empty.json", - &fixture.json( - &history(&fixture) - .list_runs_for_page(50, 0, &HistoryThumbnails::default()) - .unwrap(), - ), - ); - - let fixture = Fixture::new(); - seed_history(&fixture); - let history = history(&fixture); - assert_golden( - "ipc/list_history_runs.page-1.json", - &fixture.json( - &history - .list_runs_for_page(50, 0, &HistoryThumbnails::default()) - .unwrap(), - ), - ); - assert_golden( - "ipc/list_history_runs.page-2-of-2.json", - &fixture.json( - &history - .list_runs_for_page(2, 2, &HistoryThumbnails::default()) - .unwrap(), - ), - ); -} - -#[test] -fn get_history_run_detail() { - let fixture = Fixture::new(); - seed_history(&fixture); - let history = history(&fixture); - assert_golden( - "ipc/get_history_run_detail.found.json", - &fixture.json(&history.run_detail_for_page("run-1").unwrap()), - ); - assert_golden( - "ipc/get_history_run_detail.not-found.json", - &fixture.json(&history.run_detail_for_page("run-404").unwrap()), - ); -} - -#[test] -fn preview_storage_cleanup() { - let fixture = Fixture::new(); - seed_history(&fixture); - let history = history(&fixture); - assert_golden( - "ipc/preview_storage_cleanup.screenshots-all.json", - &fixture.json( - &history - .preview_cleanup(StorageCleanupScope::Screenshots, StorageCleanupPreset::All) - .unwrap(), - ), - ); - assert_golden( - "ipc/preview_storage_cleanup.run-data-all.json", - &fixture.json( - &history - .preview_cleanup(StorageCleanupScope::RunData, StorageCleanupPreset::All) - .unwrap(), - ), - ); -} diff --git a/bazaarplusplus-installer/src-tauri/src/lib.rs b/bazaarplusplus-installer/src-tauri/src/lib.rs deleted file mode 100644 index 3e89e09..0000000 --- a/bazaarplusplus-installer/src-tauri/src/lib.rs +++ /dev/null @@ -1,133 +0,0 @@ -mod commands; -mod config; -mod headless; -pub use headless::run as run_headless; -#[cfg(test)] -mod goldens; -mod history; -#[cfg(test)] -mod ipc_golden_tests; -mod main_window; -mod problem; -mod services; -mod stream; -mod tray; -mod v5_import; - -// The unit-test harness links the same Tauri dialog code as the application, -// but tauri-build only attaches its Common Controls v6 resource to binaries. -// Without this test-only link, Windows fails before running any test because -// comctl32!TaskDialogIndirect is unavailable from the legacy activation context. -#[cfg(all(test, target_os = "windows"))] -#[link(name = "resource", kind = "static")] -unsafe extern "C" {} - -use tauri::{Manager, WindowEvent}; -#[cfg(not(any(target_os = "android", target_os = "ios")))] -use tauri_plugin_window_state::StateFlags; - -use services::startup::InstallerContextState; -use tray::{build_tray, TrayMenuState}; - -#[cfg_attr(mobile, tauri::mobile_entry_point)] -pub fn run() { - #[allow(unused_mut)] - let mut builder = tauri::Builder::default(); - let command_builder = crate::commands::registry::builder(); - - #[cfg(not(any(target_os = "android", target_os = "ios")))] - { - // single-instance must be registered first; window-state restores only - // geometry and maximization, never visibility or frame configuration. - builder = builder - .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| { - crate::main_window::restore(app); - })) - .plugin( - tauri_plugin_window_state::Builder::default() - .with_state_flags( - StateFlags::SIZE | StateFlags::POSITION | StateFlags::MAXIMIZED, - ) - .build(), - ); - } - - let app = builder - .plugin(tauri_plugin_updater::Builder::new().build()) - .plugin(tauri_plugin_process::init()) - .plugin(tauri_plugin_dialog::init()) - .manage( - crate::services::selected_game_installation::SelectedGameInstallationState::default(), - ) - .manage(crate::stream::runtime::StreamRuntime::default()) - .manage(crate::services::data_maintenance::DataMaintenanceLock::default()) - .manage(crate::stream::history_thumbnails::HistoryThumbnails::default()) - .manage(InstallerContextState::default()) - .manage(TrayMenuState::default()) - .plugin(tauri_plugin_opener::init()) - .setup(|app| { - #[cfg(target_os = "windows")] - { - let window = app - .get_webview_window("main") - .ok_or_else(|| std::io::Error::other("main window is unavailable"))?; - window.set_decorations(false)?; - crate::main_window::enforce_minimum_size(&window)?; - - // Programmatic window-state restoration and undecorated native - // resizing can bypass the configured logical minimum on Windows. - // Correct those native resize events before the WebView can be - // left with an unusably small layout. - let size_window = window.clone(); - window.on_window_event(move |event| { - if matches!(event, WindowEvent::Resized(_)) { - if let Err(error) = crate::main_window::enforce_minimum_size(&size_window) { - eprintln!("failed to enforce the Windows window minimum: {error}"); - } - } - }); - - window.show()?; - } - - let handle = app.app_handle(); - build_tray(handle)?; - let startup_handle = handle.clone(); - tauri::async_runtime::spawn_blocking(move || { - let state = startup_handle.state::(); - let _ = state.get_or_initialize(&startup_handle); - }); - let app_handle = handle.clone(); - tauri::async_runtime::spawn(async move { - let runtime = app_handle.state::(); - let _ = runtime.ensure(app_handle.clone()).await; - }); - Ok(()) - }) - // While the stream service is running, hide the main window to the tray - // on close instead of quitting, so the local overlay HTTP server keeps - // serving OBS. The tray menu's quit action is the real exit path. - .on_window_event(|window, event| { - if window.label() != "main" { - return; - } - - if let WindowEvent::CloseRequested { api, .. } = event { - let runtime = window.state::(); - if runtime.snapshot().running { - api.prevent_close(); - let _ = window.hide(); - } - } - }) - .invoke_handler(command_builder.invoke_handler()) - .build(tauri::generate_context!()) - .expect("error while building tauri application"); - - app.run(|_app_handle, _event| { - #[cfg(target_os = "macos")] - if matches!(_event, tauri::RunEvent::Reopen { .. }) { - crate::main_window::restore(_app_handle); - } - }); -} diff --git a/bazaarplusplus-installer/src-tauri/src/main.rs b/bazaarplusplus-installer/src-tauri/src/main.rs deleted file mode 100644 index cc6ff12..0000000 --- a/bazaarplusplus-installer/src-tauri/src/main.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Prevents additional console window on Windows in release, DO NOT REMOVE!! -#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] - -fn main() { - if let Some(status) = bppinstaller_lib::run_headless(std::env::args_os().skip(1)) { - std::process::exit(status); - } - bppinstaller_lib::run() -} diff --git a/bazaarplusplus-installer/src-tauri/src/main_window.rs b/bazaarplusplus-installer/src-tauri/src/main_window.rs deleted file mode 100644 index 6a0d104..0000000 --- a/bazaarplusplus-installer/src-tauri/src/main_window.rs +++ /dev/null @@ -1,66 +0,0 @@ -use tauri::Manager; -#[cfg(target_os = "windows")] -use tauri::{LogicalSize, PhysicalSize}; - -#[cfg(target_os = "windows")] -const MAIN_WINDOW_MIN_WIDTH: f64 = 900.0; -#[cfg(target_os = "windows")] -const MAIN_WINDOW_MIN_HEIGHT: f64 = 600.0; - -#[cfg(target_os = "windows")] -fn should_enforce_minimum_size(is_minimized: bool, is_maximized: bool) -> bool { - // Reapplying a Windows size constraint mutates the inner size and restores - // a maximized window. Only correct ordinary, restored windows here. - !is_minimized && !is_maximized -} - -#[cfg(target_os = "windows")] -fn corrected_main_window_size( - current: PhysicalSize, - scale_factor: f64, -) -> Option> { - let logical = current.to_logical::(scale_factor); - let corrected = LogicalSize::new( - logical.width.max(MAIN_WINDOW_MIN_WIDTH), - logical.height.max(MAIN_WINDOW_MIN_HEIGHT), - ); - - (corrected != logical).then_some(corrected) -} - -#[cfg(target_os = "windows")] -pub(crate) fn enforce_minimum_size(window: &tauri::WebviewWindow) -> tauri::Result<()> { - if !should_enforce_minimum_size(window.is_minimized()?, window.is_maximized()?) { - return Ok(()); - } - - window.set_min_size(Some(LogicalSize::new( - MAIN_WINDOW_MIN_WIDTH, - MAIN_WINDOW_MIN_HEIGHT, - )))?; - - if let Some(corrected) = - corrected_main_window_size(window.inner_size()?, window.scale_factor()?) - { - window.set_size(corrected)?; - } - - Ok(()) -} - -pub(crate) fn restore(app: &tauri::AppHandle) { - let Some(window) = app.get_webview_window("main") else { - eprintln!("failed to restore the main window: window is unavailable"); - return; - }; - - if let Err(error) = window.show() { - eprintln!("failed to show the main window: {error}"); - } - if let Err(error) = window.unminimize() { - eprintln!("failed to unminimize the main window: {error}"); - } - if let Err(error) = window.set_focus() { - eprintln!("failed to focus the main window: {error}"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/problem.rs b/bazaarplusplus-installer/src-tauri/src/problem.rs deleted file mode 100644 index a521d81..0000000 --- a/bazaarplusplus-installer/src-tauri/src/problem.rs +++ /dev/null @@ -1,133 +0,0 @@ -use std::collections::BTreeMap; - -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)] -pub struct SemanticProblem { - pub code: SemanticProblemCode, - pub params: BTreeMap, - pub diagnostic: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)] -#[serde(rename_all = "snake_case")] -pub enum SemanticProblemCode { - HistoryUnavailable, - HistoryReadFailed, - HistoryReadBlockedByGame, - HistoryDatabaseUnsupportedSchema, - HistoryActionFailed, - HistoryThumbnailsUnavailable, - InstallDetectionFailed, - InstallActionFailed, - InstallPartialFailure, - InstallBlockedByGame, - ResetBlockedByGame, - BepinexResetBlockedByGame, - ImportBlockedByGame, - // The V5 import stopped; its `reason` parameter is `ImportError::code`. - ImportFailed, - LegacyDeleteBlockedByGame, - StreamServiceFailed, - StreamWindowFailed, - StreamCropFailed, -} - -impl SemanticProblem { - pub fn new(code: SemanticProblemCode) -> Self { - Self { - code, - params: BTreeMap::new(), - diagnostic: None, - } - } - - pub fn with_param(mut self, name: impl Into, value: impl Into) -> Self { - self.params.insert(name.into(), value.into()); - self - } - - pub fn with_diagnostic(mut self, diagnostic: impl Into) -> Self { - self.diagnostic = Some(diagnostic.into()); - self - } -} - -#[cfg(test)] -mod tests { - use super::{SemanticProblem, SemanticProblemCode}; - - #[test] - fn semantic_problem_serializes_stable_code_params_and_optional_diagnostic() { - let problem = SemanticProblem::new(SemanticProblemCode::HistoryReadFailed) - .with_param("operation", "list_runs") - .with_diagnostic("database is locked"); - - assert_eq!( - serde_json::to_value(problem).unwrap(), - serde_json::json!({ - "code": "history_read_failed", - "params": { "operation": "list_runs" }, - "diagnostic": "database is locked" - }) - ); - - assert_eq!( - serde_json::to_value(SemanticProblem::new( - SemanticProblemCode::HistoryUnavailable - )) - .unwrap(), - serde_json::json!({ - "code": "history_unavailable", - "params": {}, - "diagnostic": null - }) - ); - - assert_eq!( - serde_json::to_value(SemanticProblem::new( - SemanticProblemCode::HistoryDatabaseUnsupportedSchema - )) - .unwrap(), - serde_json::json!({ - "code": "history_database_unsupported_schema", - "params": {}, - "diagnostic": null - }) - ); - - assert_eq!( - serde_json::to_value(SemanticProblem::new( - SemanticProblemCode::HistoryThumbnailsUnavailable - )) - .unwrap(), - serde_json::json!({ - "code": "history_thumbnails_unavailable", - "params": {}, - "diagnostic": null - }) - ); - - assert_eq!( - serde_json::to_value(SemanticProblem::new( - SemanticProblemCode::InstallDetectionFailed - )) - .unwrap(), - serde_json::json!({ - "code": "install_detection_failed", - "params": {}, - "diagnostic": null - }) - ); - - assert_eq!( - serde_json::to_value(SemanticProblem::new( - SemanticProblemCode::StreamServiceFailed - )) - .unwrap(), - serde_json::json!({ - "code": "stream_service_failed", - "params": {}, - "diagnostic": null - }) - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/action_error.rs b/bazaarplusplus-installer/src-tauri/src/services/action_error.rs deleted file mode 100644 index 01dd8c7..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/action_error.rs +++ /dev/null @@ -1,93 +0,0 @@ -use std::path::PathBuf; - -use crate::problem::{SemanticProblem, SemanticProblemCode}; -use crate::services::game_process::GameRunningRefusal; - -/// Why an install-page action (install, reset, Legacy Root deletion) failed. -/// Refusals and partial failures stay typed until [`ActionError::into_problem`] -/// turns them into the problem the frontend renders; any other failure is a -/// diagnostic string. -#[derive(Debug, PartialEq, Eq)] -pub(crate) enum ActionError { - /// The game was running, or its processes could not be inspected. - Refused(GameRunningRefusal), - /// The action removed what it could and left these paths behind. - PartialFailure(Vec), - Failed(String), -} - -impl ActionError { - pub(crate) fn into_problem(self, operation: &str) -> SemanticProblem { - match self { - Self::Refused(refusal) => refusal.into_problem().with_param("operation", operation), - Self::PartialFailure(paths) => { - SemanticProblem::new(SemanticProblemCode::InstallPartialFailure) - .with_param("operation", operation) - .with_param("count", paths.len().to_string()) - // The frontend splits on `\u{1f}`, which cannot collide with - // Windows drive letters or path separators. - .with_param( - "paths", - paths - .iter() - .map(|path| path.display().to_string()) - .collect::>() - .join("\u{1f}"), - ) - } - Self::Failed(diagnostic) => { - SemanticProblem::new(SemanticProblemCode::InstallActionFailed) - .with_param("operation", operation) - .with_diagnostic(diagnostic) - } - } - } -} - -impl From for ActionError { - fn from(diagnostic: String) -> Self { - Self::Failed(diagnostic) - } -} - -impl From for ActionError { - fn from(refusal: GameRunningRefusal) -> Self { - Self::Refused(refusal) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::services::game_process::GameStoppedOperation; - - #[test] - fn each_kind_becomes_the_problem_the_install_page_renders() { - let blocked = ActionError::from(GameRunningRefusal { - operation: GameStoppedOperation::Install, - inspection_error: None, - }) - .into_problem("install"); - assert_eq!(blocked.code, SemanticProblemCode::InstallBlockedByGame); - assert_eq!( - blocked.params.get("operation").map(String::as_str), - Some("install") - ); - assert_eq!(blocked.diagnostic, None); - - let partial = - ActionError::PartialFailure(vec![PathBuf::from("/tmp/a"), PathBuf::from("/tmp/b")]) - .into_problem("reset_bpp_data"); - assert_eq!(partial.code, SemanticProblemCode::InstallPartialFailure); - assert_eq!(partial.params.get("count").map(String::as_str), Some("2")); - assert_eq!( - partial.params.get("paths").map(String::as_str), - Some("/tmp/a\u{1f}/tmp/b") - ); - assert_eq!(partial.diagnostic, None); - - let generic = ActionError::from("permission denied".to_string()).into_problem("install"); - assert_eq!(generic.code, SemanticProblemCode::InstallActionFailed); - assert_eq!(generic.diagnostic.as_deref(), Some("permission denied")); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/bepinex/bundle_root.rs b/bazaarplusplus-installer/src-tauri/src/services/bepinex/bundle_root.rs deleted file mode 100644 index b6fd90e..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/bepinex/bundle_root.rs +++ /dev/null @@ -1,551 +0,0 @@ -//! Preserve the duplicate application shipped at the root of some Steam builds. -//! Content-addressed backups make interrupted and repeated repairs resumable. -//! Only the latest backup is retained; unknown or modified backups are never removed. - -use sha2::{Digest, Sha256}; -use std::fs; -use std::io::Read; -use std::path::{Path, PathBuf}; - -const DUPLICATE: &str = "TheBazaar_ARM64.app"; -const BACKUPS: &str = ".bpp-bundle-root-stash"; - -fn io(path: &Path, result: std::io::Result) -> Result { - result.map_err(|error| format!("Cannot access {}: {error}", path.display())) -} - -fn directory(path: &Path) -> Result<(), String> { - if !io(path, fs::symlink_metadata(path))?.file_type().is_dir() { - return Err(format!("Expected a real directory at {}", path.display())); - } - Ok(()) -} - -fn children(path: &Path) -> Result, String> { - io(path, fs::read_dir(path))? - .map(|entry| io(path, entry).map(|entry| entry.path())) - .collect() -} - -// Lowercase hex, matching `shasum -a 256`; backup names depend on this exact form. -fn hex(digest: &[u8]) -> String { - digest.iter().map(|byte| format!("{byte:02x}")).collect() -} - -fn file_digest(path: &Path) -> Result { - let mut file = io(path, fs::File::open(path))?; - let mut digest = Sha256::new(); - let mut buffer = [0; 64 * 1024]; - loop { - let count = io(path, file.read(&mut buffer))?; - if count == 0 { - break; - } - digest.update(&buffer[..count]); - } - Ok(hex(&digest.finalize())) -} - -// The manifest is a persistent backup format. Reject ambiguous names and links -// instead of following them outside the owned tree. -fn fingerprint(root: &Path) -> Result { - fn visit(root: &Path, path: &Path, records: &mut Vec) -> Result<(), String> { - let relative = path.strip_prefix(root).map_err(|error| error.to_string())?; - let relative = relative - .to_str() - .filter(|name| !name.contains(['\n', '\r', '\\'])) - .ok_or_else(|| format!("Unsupported backup path: {}", path.display()))?; - let name = if relative.is_empty() { - ".".into() - } else { - format!("./{relative}") - }; - let kind = io(path, fs::symlink_metadata(path))?.file_type(); - if kind.is_dir() { - records.push(format!("D {name}\n")); - for child in children(path)? { - visit(root, &child, records)?; - } - } else if kind.is_file() { - records.push(format!("F {} {name}\n", file_digest(path)?)); - } else { - return Err(format!( - "Unsupported file or symbolic link: {}", - path.display() - )); - } - Ok(()) - } - let mut records = Vec::new(); - visit(root, root, &mut records)?; - records.sort(); - Ok(hex(&Sha256::digest(records.concat().as_bytes()))) -} - -fn read_plist(app: &Path, key: &str) -> Result { - let path = app.join("Contents/Info.plist"); - let output = std::process::Command::new("/usr/bin/plutil") - .args(["-extract", key, "raw", "-o", "-"]) - .arg(&path) - .output() - .map_err(|error| format!("Cannot read {}: {error}", path.display()))?; - if !output.status.success() { - return Err(format!("Cannot read {key} from {}", path.display())); - } - Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()) -} - -fn validate_duplicate(app: &Path, duplicate: &Path) -> Result<(), String> { - directory(duplicate)?; - for key in [ - "CFBundleIdentifier", - "CFBundleExecutable", - "CFBundleShortVersionString", - ] { - let value = read_plist(app, key)?; - if value.is_empty() || value != read_plist(duplicate, key)? { - return Err(format!( - "Unexpected {key} in {}; no files were moved", - duplicate.display() - )); - } - if key == "CFBundleIdentifier" && value != "com.TempoStorm.TheBazaar" { - return Err(format!("Unrecognized game bundle: {}", app.display())); - } - } - // Signatures and the main executable may already have been changed by BPP. - // The engine, Mono runtime and boot configuration must still match Steam's copy. - for relative in [ - "Contents/Frameworks/UnityPlayer.dylib", - "Contents/Frameworks/libmonobdwgc-2.0.dylib", - "Contents/Resources/Data/boot.config", - ] { - if file_digest(&app.join(relative))? != file_digest(&duplicate.join(relative))? { - return Err(format!( - "Duplicate game bundle differs at {relative}; no files were moved" - )); - } - } - Ok(()) -} - -fn valid_digest(value: &str) -> bool { - value.len() == 64 - && value - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) -} - -fn write_current(backups: &Path, digest: &str) -> Result<(), String> { - let staged = backups.join("current.tmp"); - io(&staged, fs::write(&staged, format!("{digest}\n")))?; - io(&staged, fs::rename(&staged, backups.join("current"))) -} - -fn retire(backups: &Path, path: &Path, digest: &str) -> Result<(), String> { - // Renaming is the commit point: a partly removed directory must never be - // mistaken for a user-modified backup or an incomplete Steam application. - let tombstone = backups.join(format!(".delete-{digest}.app")); - io(path, fs::rename(path, &tombstone))?; - io(&tombstone, fs::remove_dir_all(&tombstone)) -} - -pub(super) fn normalize(game: &Path) -> Result<(), String> { - let app = game.join("TheBazaar.app"); - directory(&app)?; - directory(&app.join("Contents"))?; - for entry in children(&app)? { - if entry - .file_name() - .is_some_and(|name| name == "Contents" || name == DUPLICATE) - { - continue; - } - // Finder metadata is explicitly permitted by macOS code signing. - if entry.file_name().is_some_and(|name| name == ".DS_Store") - && io(&entry, fs::symlink_metadata(&entry))? - .file_type() - .is_file() - { - continue; - } - return Err(format!( - "Unexpected application root entry {}; move it outside TheBazaar.app before repairing", - entry.display() - )); - } - let source = app.join(DUPLICATE); - let source_exists = source.try_exists().map_err(|error| error.to_string())? - || fs::symlink_metadata(&source).is_ok(); - let backups = game.join(BACKUPS); - if !source_exists && !backups.exists() { - return Ok(()); - } - let incoming = if source_exists { - validate_duplicate(&app, &source)?; - Some(fingerprint(&source)?) - } else { - None - }; - if !backups.exists() { - io(&backups, fs::create_dir(&backups))?; - } - directory(&backups)?; - - // Inspect every existing backup BEFORE deleting or moving anything. A legacy - // stash is adopted without changing its contents, including after an update. - let mut snapshots = Vec::new(); - let mut tombstones = Vec::new(); - let mut legacy = None; - for entry in children(&backups)? { - let name = entry - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or(""); - if name == ".DS_Store" { - if !io(&entry, fs::symlink_metadata(&entry))? - .file_type() - .is_file() - { - return Err(format!("Invalid Finder metadata: {}", entry.display())); - } - } else if name == "current" || name == "current.tmp" { - if !io(&entry, fs::symlink_metadata(&entry))? - .file_type() - .is_file() - { - return Err(format!("Invalid backup record: {}", entry.display())); - } - } else if name - .strip_prefix(".delete-") - .and_then(|name| name.strip_suffix(".app")) - .is_some_and(valid_digest) - { - directory(&entry)?; - tombstones.push(entry); - } else if name == DUPLICATE { - directory(&entry)?; - if read_plist(&entry, "CFBundleIdentifier")? != "com.TempoStorm.TheBazaar" { - return Err(format!("Unrecognized legacy backup: {}", entry.display())); - } - legacy = Some((entry.clone(), fingerprint(&entry)?)); - } else if name.strip_suffix(".app").is_some_and(valid_digest) { - let digest = fingerprint(&entry)?; - if name != format!("{digest}.app") { - return Err(format!( - "Backup was modified; preserve or move {} before repairing", - entry.display() - )); - } - snapshots.push((entry.clone(), digest)); - } else { - return Err(format!("Unexpected backup entry: {}", entry.display())); - } - } - if !tombstones.is_empty() && snapshots.is_empty() { - return Err(format!( - "No verified backup remains in {}; pending deletion was preserved", - backups.display() - )); - } - for path in tombstones { - io(&path, fs::remove_dir_all(&path))?; - } - if let Some((path, digest)) = legacy { - let target = backups.join(format!("{digest}.app")); - if incoming.is_none() && !backups.join("current").exists() { - write_current(&backups, &digest)?; - } - if target.exists() { - retire(&backups, &path, &digest)?; - } else { - io(&path, fs::rename(&path, &target))?; - snapshots.push((target, digest.clone())); - } - } - let current = if let Some(digest) = incoming { - write_current(&backups, &digest)?; - let target = backups.join(format!("{digest}.app")); - if target.exists() { - retire(&backups, &source, &digest)?; - } else { - io(&source, fs::rename(&source, &target))?; - } - digest - } else if snapshots.is_empty() { - return Ok(()); - } else if snapshots.len() == 1 && !backups.join("current").exists() { - let digest = snapshots[0].1.clone(); - write_current(&backups, &digest)?; - digest - } else { - io(&backups, fs::read_to_string(backups.join("current")))? - .trim() - .to_string() - }; - if !valid_digest(¤t) || !backups.join(format!("{current}.app")).is_dir() { - return Err(format!( - "Incomplete backup record in {}; no backups were removed", - backups.display() - )); - } - // The current contents are now preserved outside the app, even if signing or - // cleanup is interrupted. Re-entry completes cleanup without restoring bad layout. - for (path, digest) in snapshots { - if digest != current { - retire(&backups, &path, &digest)?; - } - } - Ok(()) -} - -#[cfg(test)] -pub(super) mod tests { - use super::*; - - pub(crate) fn copy_tree(source: &Path, target: &Path) { - fs::create_dir_all(target).unwrap(); - for entry in fs::read_dir(source).unwrap() { - let entry = entry.unwrap(); - let destination = target.join(entry.file_name()); - if entry.file_type().unwrap().is_dir() { - copy_tree(&entry.path(), &destination); - } else { - fs::copy(entry.path(), destination).unwrap(); - } - } - } - - pub(crate) fn make_bundle(game: &Path) -> PathBuf { - let app = game.join("TheBazaar.app"); - for directory in [ - "Contents/MacOS", - "Contents/Frameworks", - "Contents/Resources/Data", - ] { - fs::create_dir_all(app.join(directory)).unwrap(); - } - fs::write( - app.join("Contents/Info.plist"), - r#" - -CFBundleExecutableThe Bazaar -CFBundleIdentifiercom.TempoStorm.TheBazaar -CFBundlePackageTypeAPPL -CFBundleShortVersionStringtest -"#, - ) - .unwrap(); - fs::write(app.join("Contents/MacOS/The Bazaar"), b"game").unwrap(); - for relative in [ - "Contents/Frameworks/UnityPlayer.dylib", - "Contents/Frameworks/libmonobdwgc-2.0.dylib", - "Contents/Resources/Data/boot.config", - ] { - fs::write(app.join(relative), b"original").unwrap(); - } - app - } - - fn add_duplicate(game: &Path, app: &Path) { - let staged = game.join("staged.app"); - copy_tree(app, &staged); - fs::rename(staged, app.join(DUPLICATE)).unwrap(); - } - - #[test] - fn repeated_repairs_and_new_steam_contents_keep_one_verified_backup() { - let game = tempfile::tempdir().unwrap(); - let app = make_bundle(game.path()); - add_duplicate(game.path(), &app); - let original = fingerprint(&app.join(DUPLICATE)).unwrap(); - normalize(game.path()).unwrap(); - for _ in 0..3 { - normalize(game.path()).unwrap(); - add_duplicate(game.path(), &app); - normalize(game.path()).unwrap(); - assert!(!app.join(DUPLICATE).exists()); - assert!(game - .path() - .join(BACKUPS) - .join(format!("{original}.app")) - .is_dir()); - } - fs::write( - app.join("Contents/Resources/Data/boot.config"), - b"steam-update", - ) - .unwrap(); - add_duplicate(game.path(), &app); - let updated = fingerprint(&app.join(DUPLICATE)).unwrap(); - normalize(game.path()).unwrap(); - let backups = game.path().join(BACKUPS); - assert!(!backups.join(format!("{original}.app")).exists()); - assert_eq!( - fingerprint(&backups.join(format!("{updated}.app"))).unwrap(), - updated - ); - assert_eq!(children(&backups).unwrap().len(), 2); - } - - #[test] - fn interrupted_move_and_cleanup_resume_from_content_record() { - let game = tempfile::tempdir().unwrap(); - let app = make_bundle(game.path()); - add_duplicate(game.path(), &app); - normalize(game.path()).unwrap(); - fs::write( - app.join("Contents/Resources/Data/boot.config"), - b"new-build", - ) - .unwrap(); - add_duplicate(game.path(), &app); - let digest = fingerprint(&app.join(DUPLICATE)).unwrap(); - let backups = game.path().join(BACKUPS); - // A process exit after recording the intended destination but before moving. - write_current(&backups, &digest).unwrap(); - normalize(game.path()).unwrap(); - assert_eq!(children(&backups).unwrap().len(), 2); - // A process exit after moving, before cleanup. Both backups are intact. - let old = game.path().join("old"); - fs::create_dir(&old).unwrap(); - fs::write(old.join("preserved"), b"old").unwrap(); - let old_digest = fingerprint(&old).unwrap(); - fs::rename(&old, backups.join(format!("{old_digest}.app"))).unwrap(); - normalize(game.path()).unwrap(); - assert_eq!(children(&backups).unwrap().len(), 2); - assert!(backups.join(format!("{digest}.app")).is_dir()); - } - - #[test] - fn unknown_or_modified_contents_are_preserved_and_reported() { - let game = tempfile::tempdir().unwrap(); - let app = make_bundle(game.path()); - fs::write(app.join(".DS_Store"), b"Finder metadata").unwrap(); - add_duplicate(game.path(), &app); - fs::write(app.join("user-file"), b"keep").unwrap(); - assert!(normalize(game.path()) - .unwrap_err() - .contains("Unexpected application root")); - assert!(app.join(DUPLICATE).exists()); - fs::remove_file(app.join("user-file")).unwrap(); - normalize(game.path()).unwrap(); - assert_eq!(fs::read(app.join(".DS_Store")).unwrap(), b"Finder metadata"); - let backups = game.path().join(BACKUPS); - let current = fs::read_to_string(backups.join("current")).unwrap(); - let saved = backups.join(format!("{}.app", current.trim())); - fs::write(saved.join("user-file"), b"keep").unwrap(); - add_duplicate(game.path(), &app); - assert!(normalize(game.path()) - .unwrap_err() - .contains("Backup was modified")); - assert_eq!(fs::read(saved.join("user-file")).unwrap(), b"keep"); - assert!(app.join(DUPLICATE).exists()); - } - - #[test] - fn legacy_stash_is_adopted_without_restoring_invalid_root() { - let game = tempfile::tempdir().unwrap(); - let app = make_bundle(game.path()); - fs::write(app.join(".DS_Store"), b"Finder metadata").unwrap(); - let backups = game.path().join(BACKUPS); - fs::create_dir(&backups).unwrap(); - copy_tree(&app, &backups.join(DUPLICATE)); - let digest = fingerprint(&backups.join(DUPLICATE)).unwrap(); - fs::write(backups.join(".DS_Store"), b"Legacy Finder metadata").unwrap(); - normalize(game.path()).unwrap(); - normalize(game.path()).unwrap(); - add_duplicate(game.path(), &app); - normalize(game.path()).unwrap(); - assert!(!app.join(DUPLICATE).exists()); - assert_eq!( - fingerprint(&backups.join(format!("{digest}.app"))).unwrap(), - digest - ); - assert!(!backups.join(DUPLICATE).exists()); - assert_eq!(children(&backups).unwrap().len(), 3); - assert_eq!(fs::read(app.join(".DS_Store")).unwrap(), b"Finder metadata"); - assert_eq!( - fs::read(backups.join(".DS_Store")).unwrap(), - b"Legacy Finder metadata" - ); - } - - #[test] - fn backup_metadata_rejects_directories_links_and_unknown_files() { - for kind in ["directory", "symbolic-link", "unknown-file"] { - let game = tempfile::tempdir().unwrap(); - let app = make_bundle(game.path()); - add_duplicate(game.path(), &app); - let backups = game.path().join(BACKUPS); - fs::create_dir(&backups).unwrap(); - let outside = game.path().join("outside"); - fs::write(&outside, b"keep").unwrap(); - let entry = backups.join(if kind == "unknown-file" { - "user-file" - } else { - ".DS_Store" - }); - match kind { - "directory" => fs::create_dir(&entry).unwrap(), - "symbolic-link" => std::os::unix::fs::symlink(&outside, &entry).unwrap(), - _ => fs::write(&entry, b"keep").unwrap(), - } - assert!(normalize(game.path()).is_err(), "{kind}"); - assert!(app.join(DUPLICATE).is_dir()); - assert!(!backups.join("current").exists()); - assert_eq!(fs::read(&outside).unwrap(), b"keep"); - if kind == "directory" { - assert!(entry.is_dir()); - } else { - assert_eq!(fs::read(&entry).unwrap(), b"keep"); - } - } - } - - #[test] - fn partly_deleted_duplicates_and_legacy_record_gaps_are_recoverable() { - let game = tempfile::tempdir().unwrap(); - let app = make_bundle(game.path()); - add_duplicate(game.path(), &app); - normalize(game.path()).unwrap(); - let backups = game.path().join(BACKUPS); - let current = fs::read_to_string(backups.join("current")) - .unwrap() - .trim() - .to_string(); - // Cleanup was interrupted after the verified redundant directory was renamed. - let tombstone = backups.join(format!(".delete-{current}.app")); - fs::create_dir(&tombstone).unwrap(); - fs::write(tombstone.join("last-file"), b"partly deleted contents").unwrap(); - normalize(game.path()).unwrap(); - assert!(!tombstone.exists()); - assert!(backups.join(format!("{current}.app")).is_dir()); - // Adopt an intact, uniquely identifiable snapshot left by an older migration. - fs::remove_file(backups.join("current")).unwrap(); - normalize(game.path()).unwrap(); - assert_eq!( - fs::read_to_string(backups.join("current")).unwrap().trim(), - current - ); - } - - #[test] - fn mismatched_engine_and_symbolic_links_are_not_moved() { - let game = tempfile::tempdir().unwrap(); - let app = make_bundle(game.path()); - add_duplicate(game.path(), &app); - let engine = app - .join(DUPLICATE) - .join("Contents/Frameworks/UnityPlayer.dylib"); - fs::write(&engine, b"different").unwrap(); - assert!(normalize(game.path()).unwrap_err().contains("differs")); - fs::write(&engine, b"original").unwrap(); - std::os::unix::fs::symlink(game.path(), app.join(DUPLICATE).join("link")).unwrap(); - assert!(normalize(game.path()) - .unwrap_err() - .contains("symbolic link")); - assert!(app.join(DUPLICATE).exists()); - assert!(!game.path().join(BACKUPS).exists()); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/bepinex/mod.rs b/bazaarplusplus-installer/src-tauri/src/services/bepinex/mod.rs deleted file mode 100644 index c2021a4..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/bepinex/mod.rs +++ /dev/null @@ -1,426 +0,0 @@ -#[cfg(target_os = "macos")] -mod bundle_root; -mod payload; -mod trampoline; -mod zip_archive; - -pub(crate) use payload::{ensure_valid_game_path, remove_dir_with_retry}; -pub(crate) use trampoline::{ - install_trampoline, is_current_trampoline, obsolete_macos_artifacts_present, - remove_obsolete_macos_artifacts, -}; -pub(crate) use zip_archive::read_bundled_bpp_version; - -/// Repairs developer deployments without extracting the installer's bundled Payload. -pub(crate) fn repair_deployed_game(game_path: &Path, stub: &Path) -> Result<(), String> { - #[cfg(target_os = "macos")] - { - payload::ensure_valid_game_path(game_path)?; - if !game_path.join("libdoorstop.dylib").is_file() { - return Err( - "libdoorstop.dylib is missing; install BepInEx with the installer first".into(), - ); - } - trampoline::repair_with_stub(game_path, stub) - } - #[cfg(not(target_os = "macos"))] - { - let _ = (game_path, stub); - Err("Launch trampoline repair is supported only on macOS".into()) - } -} - -use std::path::Path; - -use crate::services::action_error::ActionError; -use crate::services::data_maintenance::DataMaintenanceLock; -use crate::services::game_process::{ - ensure_game_stopped_with, GameProcessProbe, GameStoppedOperation, SystemGameProcessProbe, -}; -use crate::stream::runtime::StreamRuntime; - -use super::{debug_error, debug_log}; - -pub async fn reset_bpp_data( - maintenance: &DataMaintenanceLock, - stream_runtime: &StreamRuntime, - game_path: String, -) -> Result { - reset_bpp_data_with( - maintenance, - stream_runtime, - game_path, - SystemGameProcessProbe, - ) - .await -} - -/// Holds the data maintenance lock and stops the OBS overlay, which reads the -/// database this deletes, for the whole reset. -pub(crate) async fn reset_bpp_data_with( - maintenance: &DataMaintenanceLock, - stream_runtime: &StreamRuntime, - game_path: String, - probe: impl GameProcessProbe + Send + 'static, -) -> Result { - maintenance - .run_blocking_with_overlay_stopped(stream_runtime, move || { - reset_bpp_data_blocking_with(Path::new(&game_path), &probe) - }) - .await? -} - -fn reset_bpp_data_blocking_with( - game_path: &Path, - probe: &impl GameProcessProbe, -) -> Result { - payload::ensure_valid_game_path(game_path)?; - ensure_game_stopped_with(probe, game_path, GameStoppedOperation::Reset)?; - - let data_dir = crate::services::paths::bpp_data_dir(game_path); - let had_resettable_data = data_dir.exists(); - let report = payload::cleanup_bpp_data_directory(game_path); - if !report.is_empty() { - return Err(ActionError::PartialFailure(report.failed)); - } - - debug_log!( - "Reset BazaarPlusPlus data directory at {}", - game_path.display() - ); - Ok(had_resettable_data) -} - -/// Blunt "wipe the whole BepInEx folder" repair. Deletes only `/BepInEx` -/// (including any third-party mod under it) and leaves the doorstop/trampoline -/// bootstrap untouched, so the game stays launchable and the user reinstalls -/// manually afterward. It holds the data maintenance lock; unlike -/// [`reset_bpp_data`] it touches no SQLite database, so the overlay keeps -/// running. -pub async fn reset_bepinex_folder( - maintenance: &DataMaintenanceLock, - game_path: String, -) -> Result { - reset_bepinex_folder_with(maintenance, game_path, SystemGameProcessProbe).await -} - -pub(crate) async fn reset_bepinex_folder_with( - maintenance: &DataMaintenanceLock, - game_path: String, - probe: impl GameProcessProbe + Send + 'static, -) -> Result { - maintenance - .run_blocking(move || reset_bepinex_folder_blocking_with(Path::new(&game_path), &probe)) - .await? -} - -fn reset_bepinex_folder_blocking_with( - game_path: &Path, - probe: &impl GameProcessProbe, -) -> Result { - payload::ensure_valid_game_path(game_path)?; - ensure_game_stopped_with(probe, game_path, GameStoppedOperation::BepinexReset)?; - - let had_bepinex = game_path.join("BepInEx").exists(); - let report = payload::reset_bepinex_directory(game_path); - if !report.is_empty() { - return Err(ActionError::PartialFailure(report.failed)); - } - - debug_log!("Reset BepInEx folder at {}", game_path.display()); - Ok(had_bepinex) -} - -pub fn install_bepinex(resource_dir: &Path, game_path: &Path) -> Result<(), String> { - let preserved_bpp_config = - payload::preserve_file_if_exists(game_path, payload::BPP_CONFIG_RELATIVE_PATH)?; - debug_log!("Reading bundled BepInEx.zip..."); - let relative_zip_path = zip_archive::bundled_zip_relative_path(); - let resource_path = resource_dir.join(relative_zip_path); - let zip_bytes = std::fs::read(&resource_path).map_err(|err| { - debug_error!("Cannot read bundled BepInEx.zip: {err}"); - format!("Cannot read bundled BepInEx.zip: {err}") - })?; - let incoming_relative_paths = zip_archive::zip_entry_paths(&zip_bytes)?; - - let install_backup = payload::prepare_install_target(game_path, &incoming_relative_paths)?; - - let install_result = (|| -> Result<(), String> { - debug_log!("Extracting BepInEx..."); - let _report = zip_archive::extract_zip(&zip_bytes, game_path)?; - debug_log!( - "Extracted {} files, skipped {} identical.", - _report.written.len(), - _report.skipped_identical.len() - ); - - Ok(()) - })(); - - let restore_result = preserved_bpp_config - .as_ref() - .map(|preserved| payload::restore_preserved_file(game_path, preserved)) - .transpose(); - - let final_result = match (install_result, restore_result) { - (Ok(()), Ok(_)) => Ok(()), - (Err(install_err), Ok(_)) => Err(install_err), - (Ok(()), Err(restore_err)) => Err(restore_err), - (Err(install_err), Err(restore_err)) => Err(format!( - "{install_err}; additionally failed to restore preserved config: {restore_err}" - )), - }; - - match final_result { - Ok(()) => Ok(()), - Err(err) => match install_backup.restore(game_path) { - Ok(()) => Err(err), - Err(rollback_err) => Err(format!( - "{err}; additionally failed to restore previous payload: {rollback_err}" - )), - }, - } -} - -pub fn uninstall_bpp( - _app: tauri::AppHandle, - _steam_path: String, - game_path: String, -) -> Result<(), String> { - let game_path = Path::new(&game_path); - payload::ensure_valid_game_path(game_path)?; - - #[cfg(target_os = "macos")] - if !_steam_path.trim().is_empty() { - crate::services::steam::prepare_steam_for_config_update(Path::new(&_steam_path))?; - } - - let keep_shared_bootstrap = - payload::has_third_party_plugins(game_path) || payload::has_third_party_patchers(game_path); - - // Payload removal can fail after restoring the executable or deleting a - // native plugin. Always seal the resulting bundle before returning an error. - trampoline::with_finalized_bundle(game_path, || { - // Restore the vanilla bundle only when BPP is the last installed mod. If - // another mod remains — a plugin in BepInEx/plugins or a patcher-only mod - // under BepInEx/patchers — the trampoline / launch options are shared - // BepInEx bootstrap state and removing them would disable that mod. - if !keep_shared_bootstrap { - // Call uninstall_trampoline UNCONDITIONALLY (not gated on is_trampolined): - // it self-classifies — a no-op when already vanilla, a restore when a - // `.orig` exists, and a hard error in the broken stub-without-backup state. - // If this fails, abort so we never strand a stubbed bundle whose `.orig` - // we then can't recover. No-op off macOS. - trampoline::uninstall_trampoline(game_path)?; - } - - if keep_shared_bootstrap { - payload::uninstall_payload_preserving_shared_dependencies(game_path)?; - } else { - payload::uninstall_payload(game_path)?; - // Last plugin standing: also tear down the BepInEx bootstrap so the - // Windows doorstop stops injecting and detection reports uninstalled. - payload::remove_bootstrap_files(game_path)?; - } - - if !keep_shared_bootstrap { - #[cfg(target_os = "macos")] - { - if !_steam_path.trim().is_empty() { - crate::services::vdf::clear_launch_options_for_steam(Path::new(&_steam_path))?; - } - } - } - - trampoline::remove_obsolete_macos_artifacts(game_path)?; - Ok(()) - })?; - - debug_log!( - "Uninstalled BazaarPlusPlus payload from {}", - game_path.display() - ); - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::problem::SemanticProblemCode; - - fn stopped(_: &Path) -> Result { - Ok(false) - } - - fn make_valid_game_dir() -> tempfile::TempDir { - let tmp = tempfile::tempdir().unwrap(); - - #[cfg(target_os = "macos")] - { - std::fs::create_dir_all(tmp.path().join("TheBazaar.app")).unwrap(); - } - - #[cfg(target_os = "windows")] - { - std::fs::write(tmp.path().join("TheBazaar.exe"), b"exe").unwrap(); - } - - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - { - std::fs::write(tmp.path().join("TheBazaar"), b"exe").unwrap(); - } - - tmp - } - - #[test] - fn test_reset_bpp_data_removes_bpp_data_directory() { - let tmp = make_valid_game_dir(); - let data_dir = tmp.path().join(crate::config::BAZAAR_DATA_DIRECTORY); - - std::fs::create_dir_all(&data_dir).unwrap(); - std::fs::write(data_dir.join("stale.dll"), b"dll").unwrap(); - - let removed_data = reset_bpp_data_blocking_with(tmp.path(), &stopped).unwrap(); - - assert!(removed_data); - assert!(!data_dir.exists()); - } - - #[test] - fn test_reset_bpp_data_is_noop_when_directory_missing() { - let tmp = make_valid_game_dir(); - let data_dir = tmp.path().join(crate::config::BAZAAR_DATA_DIRECTORY); - assert!(!data_dir.exists()); - - let removed_data = reset_bpp_data_blocking_with(tmp.path(), &stopped).unwrap(); - - assert!(!removed_data); - assert!(!data_dir.exists()); - } - - #[test] - fn test_reset_bpp_data_is_idempotent_when_run_twice() { - let tmp = make_valid_game_dir(); - let data_dir = tmp.path().join(crate::config::BAZAAR_DATA_DIRECTORY); - std::fs::create_dir_all(&data_dir).unwrap(); - - let removed_data = reset_bpp_data_blocking_with(tmp.path(), &stopped).unwrap(); - let removed_data_again = reset_bpp_data_blocking_with(tmp.path(), &stopped).unwrap(); - - assert!(removed_data); - assert!(!removed_data_again); - assert!(!data_dir.exists()); - } - - #[test] - fn test_reset_bepinex_folder_removes_bepinex_directory_and_foreign_mods() { - let tmp = make_valid_game_dir(); - let bepinex = tmp.path().join("BepInEx"); - std::fs::create_dir_all(bepinex.join("plugins")).unwrap(); - std::fs::write(bepinex.join("plugins/BazaarPlusPlus.dll"), b"bpp").unwrap(); - // A third-party mod under BepInEx is deliberately wiped too (blunt reset). - std::fs::write(bepinex.join("plugins/OtherMod.dll"), b"foreign").unwrap(); - - let removed = reset_bepinex_folder_blocking_with(tmp.path(), &stopped).unwrap(); - - assert!(removed); - assert!(!bepinex.exists()); - } - - #[test] - fn test_reset_bepinex_folder_leaves_bootstrap_and_game_intact() { - let tmp = make_valid_game_dir(); - std::fs::create_dir_all(tmp.path().join("BepInEx/core")).unwrap(); - // Doorstop/trampoline bootstrap lives OUTSIDE BepInEx and must survive so - // the bundle stays launchable; only BepInEx itself is removed. - std::fs::write(tmp.path().join("winhttp.dll"), b"doorstop").unwrap(); - std::fs::write(tmp.path().join("libdoorstop.dylib"), b"doorstop").unwrap(); - - let removed = reset_bepinex_folder_blocking_with(tmp.path(), &stopped).unwrap(); - - assert!(removed); - assert!(!tmp.path().join("BepInEx").exists()); - assert!(tmp.path().join("winhttp.dll").exists()); - assert!(tmp.path().join("libdoorstop.dylib").exists()); - } - - #[test] - fn test_reset_bepinex_folder_is_noop_when_directory_missing() { - let tmp = make_valid_game_dir(); - assert!(!tmp.path().join("BepInEx").exists()); - - let removed = reset_bepinex_folder_blocking_with(tmp.path(), &stopped).unwrap(); - - assert!(!removed); - } - - #[test] - fn resets_refuse_with_typed_problems_and_delete_nothing_while_the_game_runs() { - fn running(_: &Path) -> Result { - Ok(true) - } - fn unknown(_: &Path) -> Result { - Err("cannot inspect processes".to_string()) - } - type Probe = fn(&Path) -> Result; - let probes: [Probe; 2] = [running, unknown]; - for refusing in probes { - let tmp = make_valid_game_dir(); - let data_dir = tmp.path().join(crate::config::BAZAAR_DATA_DIRECTORY); - let plugins = tmp.path().join("BepInEx/plugins"); - std::fs::create_dir_all(&data_dir).unwrap(); - std::fs::write(data_dir.join("history.db"), b"db").unwrap(); - std::fs::create_dir_all(&plugins).unwrap(); - std::fs::write(plugins.join("BazaarPlusPlus.dll"), b"bpp").unwrap(); - - let reset = reset_bpp_data_blocking_with(tmp.path(), &refusing).unwrap_err(); - let bepinex_reset = - reset_bepinex_folder_blocking_with(tmp.path(), &refusing).unwrap_err(); - - assert_eq!( - reset.into_problem("reset_bpp_data").code, - SemanticProblemCode::ResetBlockedByGame - ); - assert_eq!( - bepinex_reset.into_problem("reset_bepinex").code, - SemanticProblemCode::BepinexResetBlockedByGame - ); - assert!(data_dir.join("history.db").is_file()); - assert!(plugins.join("BazaarPlusPlus.dll").is_file()); - } - } - - #[tokio::test] - async fn locked_resets_refuse_while_the_game_runs() { - let tmp = make_valid_game_dir(); - let data_dir = tmp.path().join(crate::config::BAZAAR_DATA_DIRECTORY); - std::fs::create_dir_all(&data_dir).unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx")).unwrap(); - let lock = DataMaintenanceLock::default(); - let game_path = tmp.path().to_string_lossy().into_owned(); - - let reset = reset_bpp_data_with( - &lock, - &StreamRuntime::default(), - game_path.clone(), - |_: &Path| Ok(true), - ) - .await - .unwrap_err(); - let bepinex_reset = reset_bepinex_folder_with(&lock, game_path, |_: &Path| Ok(true)) - .await - .unwrap_err(); - - assert_eq!( - reset.into_problem("reset_bpp_data").code, - SemanticProblemCode::ResetBlockedByGame - ); - assert_eq!( - bepinex_reset.into_problem("reset_bepinex").code, - SemanticProblemCode::BepinexResetBlockedByGame - ); - assert!(data_dir.is_dir()); - assert!(tmp.path().join("BepInEx").is_dir()); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/bepinex/payload.rs b/bazaarplusplus-installer/src-tauri/src/services/bepinex/payload.rs deleted file mode 100644 index 93a30fb..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/bepinex/payload.rs +++ /dev/null @@ -1,975 +0,0 @@ -// src-tauri/src/services/bepinex/payload.rs -use std::path::{Path, PathBuf}; -use std::thread; -use std::time::Duration; - -pub(super) const BPP_CONFIG_RELATIVE_PATH: &str = "BepInEx/config/BazaarPlusPlus.cfg"; - -#[derive(serde::Deserialize)] -struct PayloadInventory { - #[serde(rename = "schemaVersion")] - schema_version: u32, - files: Vec, -} - -#[derive(serde::Deserialize)] -struct PayloadEntry { - path: String, - ownership: String, - platforms: Option>, -} - -fn inventory() -> &'static PayloadInventory { - static INVENTORY: std::sync::OnceLock = std::sync::OnceLock::new(); - INVENTORY.get_or_init(|| { - let inventory: PayloadInventory = serde_json::from_str(include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../release/payload.json" - ))) - .expect("the compiled Payload Inventory must be valid JSON"); - assert_eq!(inventory.schema_version, 1, "unsupported Payload Inventory"); - for entry in &inventory.files { - let known_root = entry.path.starts_with("BepInEx/") - || entry - .path - .starts_with("TheBazaar.app/Contents/Plugins/GfxPluginBpp") - || entry - .path - .starts_with("TheBazaar_Data/Plugins/x86_64/GfxPluginBpp") - || matches!( - entry.path.as_str(), - "winhttp.dll" | "doorstop_config.ini" | "libdoorstop.dylib" - ); - assert!( - known_root - && !entry.path.contains(['\\', ':', '\0']) - && entry - .path - .split('/') - .all(|part| !part.is_empty() && part != "." && part != ".."), - "unsafe compiled Payload Inventory path" - ); - assert!(matches!( - entry.ownership.as_str(), - "private" | "dependency" | "bootstrap" - )); - } - inventory - }) -} - -fn owned_paths(ownership: &str) -> impl Iterator + '_ { - inventory() - .files - .iter() - .filter(move |entry| entry.ownership == ownership) - .map(|entry| entry.path.as_str()) -} - -/// Backoff used between retries when a file/directory removal fails. The first -/// retry runs immediately, the second after a short pause, and the last after -/// a longer pause. Windows often releases ERROR_SHARING_VIOLATION holds inside -/// 200ms once the holding process closes the handle. -const REMOVE_RETRY_DELAYS_MS: &[u64] = &[0, 50, 200]; - -pub(super) struct PreservedFile { - relative_path: &'static str, - contents: Vec, -} - -pub(super) struct InstallTargetBackup { - root: tempfile::TempDir, -} - -impl InstallTargetBackup { - fn capture(game_path: &Path) -> Result { - let root = tempfile::Builder::new() - .prefix("bpp-install-backup-") - .tempdir() - .map_err(|err| format!("Cannot create install rollback snapshot: {err}"))?; - - for relative_path in payload_root_relative_paths() { - let source = game_path.join(relative_path); - if source.exists() { - copy_path(&source, &root.path().join(relative_path))?; - } - } - - Ok(Self { root }) - } - - pub(super) fn restore(self, game_path: &Path) -> Result<(), String> { - uninstall_payload(game_path)?; - - for relative_path in payload_root_relative_paths() { - let backup_path = self.root.path().join(relative_path); - if backup_path.exists() { - copy_path(&backup_path, &game_path.join(relative_path))?; - } - } - - Ok(()) - } -} - -/// Failure report for a per-file removal pass. `failed` lists the paths the -/// walker could not delete after retrying. The list is empty on success and on -/// "nothing to do" (path didn't exist). -#[derive(Debug, Default)] -pub(crate) struct RemovalReport { - pub(crate) failed: Vec, -} - -impl RemovalReport { - pub(crate) fn is_empty(&self) -> bool { - self.failed.is_empty() - } -} - -fn remove_path_if_exists(path: &Path) -> Result<(), String> { - if !path.exists() { - return Ok(()); - } - - if path.is_dir() { - std::fs::remove_dir_all(path) - .map_err(|err| format!("Cannot remove {}: {err}", path.display())) - } else { - std::fs::remove_file(path).map_err(|err| format!("Cannot remove {}: {err}", path.display())) - } -} - -pub(crate) fn payload_root_relative_paths() -> Vec<&'static str> { - let mut paths = vec!["BepInEx"]; - let platform = std::env::consts::OS; - paths.extend( - inventory() - .files - .iter() - .filter(|entry| { - !entry.path.starts_with("BepInEx/") - && entry - .platforms - .as_ref() - .is_none_or(|platforms| platforms.iter().any(|name| name == platform)) - }) - .map(|entry| entry.path.as_str()), - ); - paths -} - -fn copy_path(source: &Path, destination: &Path) -> Result<(), String> { - let metadata = std::fs::symlink_metadata(source) - .map_err(|err| format!("Cannot inspect {}: {err}", source.display()))?; - - if metadata.file_type().is_dir() && !metadata.file_type().is_symlink() { - std::fs::create_dir_all(destination) - .map_err(|err| format!("Cannot create {}: {err}", destination.display()))?; - for entry in std::fs::read_dir(source) - .map_err(|err| format!("Cannot read {}: {err}", source.display()))? - { - let entry = entry.map_err(|err| format!("Cannot read {}: {err}", source.display()))?; - copy_path(&entry.path(), &destination.join(entry.file_name()))?; - } - std::fs::set_permissions(destination, metadata.permissions()) - .map_err(|err| format!("Cannot set permissions on {}: {err}", destination.display()))?; - return Ok(()); - } - - if let Some(parent) = destination.parent() { - std::fs::create_dir_all(parent) - .map_err(|err| format!("Cannot create {}: {err}", parent.display()))?; - } - std::fs::copy(source, destination).map_err(|err| { - format!( - "Cannot copy {} to {}: {err}", - source.display(), - destination.display() - ) - })?; - std::fs::set_permissions(destination, metadata.permissions()) - .map_err(|err| format!("Cannot set permissions on {}: {err}", destination.display())) -} - -/// Try to delete a single file or empty directory, retrying briefly to absorb -/// transient sharing violations from antivirus / explorer / a slow OS handle -/// release. Returns `true` on success or when the path didn't exist; returns -/// `false` if every retry failed. -fn try_remove_with_retry(path: &Path, is_dir: bool) -> bool { - for (attempt, delay_ms) in REMOVE_RETRY_DELAYS_MS.iter().enumerate() { - if *delay_ms > 0 { - thread::sleep(Duration::from_millis(*delay_ms)); - } - - let result = if is_dir { - std::fs::remove_dir(path) - } else { - std::fs::remove_file(path) - }; - - match result { - Ok(()) => return true, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return true, - Err(_) if attempt + 1 < REMOVE_RETRY_DELAYS_MS.len() => continue, - Err(_) => return false, - } - } - - false -} - -/// Bottom-up recursive delete that retries each entry independently and -/// collects every path it could not remove. Unlike `remove_dir_all`, this does -/// not abort on the first sharing violation, so a single locked sqlite handle -/// won't leave the rest of the BazaarPlusPlus data directory half-deleted. -pub(crate) fn remove_dir_with_retry(root: &Path) -> RemovalReport { - let mut report = RemovalReport::default(); - - if !root.exists() { - return report; - } - - let metadata = match std::fs::symlink_metadata(root) { - Ok(metadata) => metadata, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return report, - Err(_) => { - report.failed.push(root.to_path_buf()); - return report; - } - }; - - if !metadata.file_type().is_dir() || metadata.file_type().is_symlink() { - if !try_remove_with_retry(root, false) { - report.failed.push(root.to_path_buf()); - } - return report; - } - - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(_) => { - report.failed.push(root.to_path_buf()); - return report; - } - }; - - for entry in entries { - let Ok(entry) = entry else { - // We don't know which path this was; mark the parent as failed so - // callers know the directory isn't empty. - report.failed.push(root.to_path_buf()); - continue; - }; - - let entry_path = entry.path(); - let entry_metadata = match std::fs::symlink_metadata(&entry_path) { - Ok(metadata) => metadata, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, - Err(_) => { - report.failed.push(entry_path); - continue; - } - }; - - if entry_metadata.file_type().is_dir() && !entry_metadata.file_type().is_symlink() { - let mut nested = remove_dir_with_retry(&entry_path); - report.failed.append(&mut nested.failed); - } else if !try_remove_with_retry(&entry_path, false) { - report.failed.push(entry_path); - } - } - - // Only attempt to drop the directory itself if every child is gone. - if report.failed.is_empty() && !try_remove_with_retry(root, true) { - report.failed.push(root.to_path_buf()); - } - - report -} - -pub(super) fn uninstall_payload(game_path: &Path) -> Result<(), String> { - remove_bpp_files(game_path, true) -} - -pub(super) fn uninstall_payload_preserving_shared_dependencies( - game_path: &Path, -) -> Result<(), String> { - remove_bpp_files(game_path, false) -} - -fn remove_bpp_files(game_path: &Path, remove_bundled_dependencies: bool) -> Result<(), String> { - for relative_path in owned_paths("private") { - remove_path_if_exists(&game_path.join(relative_path))?; - } - - if remove_bundled_dependencies { - for relative_path in owned_paths("dependency") { - remove_path_if_exists(&game_path.join(relative_path))?; - } - } - - remove_empty_dir_if_exists(&game_path.join("BepInEx/config"))?; - remove_empty_dir_if_exists(&game_path.join("BepInEx/plugins"))?; - remove_empty_dir_if_exists(&game_path.join("BepInEx"))?; - - Ok(()) -} - -fn remove_empty_dir_if_exists(path: &Path) -> Result<(), String> { - match std::fs::remove_dir(path) { - Ok(()) => Ok(()), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(err) if err.kind() == std::io::ErrorKind::DirectoryNotEmpty => Ok(()), - Err(err) => Err(format!( - "Cannot remove empty directory {}: {err}", - path.display() - )), - } -} - -pub(super) fn remove_bootstrap_files(game_path: &Path) -> Result<(), String> { - for relative_path in owned_paths("bootstrap") { - remove_path_if_exists(&game_path.join(relative_path))?; - } - - remove_empty_dir_if_exists(&game_path.join("BepInEx/config"))?; - remove_empty_dir_if_exists(&game_path.join("BepInEx/plugins"))?; - remove_empty_dir_if_exists(&game_path.join("BepInEx/patchers"))?; - remove_empty_dir_if_exists(&game_path.join("BepInEx"))?; - - Ok(()) -} - -pub(super) fn has_third_party_plugins(game_path: &Path) -> bool { - let plugins_dir = game_path.join("BepInEx/plugins"); - let Ok(entries) = std::fs::read_dir(&plugins_dir) else { - return false; - }; - - entries.filter_map(Result::ok).any(|entry| { - let Ok(relative) = entry.path().strip_prefix(game_path).map(Path::to_path_buf) else { - return false; - }; - let relative = relative.to_string_lossy().replace('\\', "/"); - relative != "BepInEx/plugins/.gitkeep" - && !owned_paths("private").any(|owned| owned.eq_ignore_ascii_case(&relative)) - && !owned_paths("dependency").any(|owned| owned.eq_ignore_ascii_case(&relative)) - }) -} - -/// A patcher-only mod leaves nothing in `BepInEx/plugins`: its whole footprint -/// lives under `BepInEx/patchers`, which BPP never ships. Any file there means -/// a third-party mod still depends on the shared BepInEx bootstrap. -pub(super) fn has_third_party_patchers(game_path: &Path) -> bool { - dir_contains_any_file(&game_path.join("BepInEx/patchers")) -} - -fn dir_contains_any_file(dir: &Path) -> bool { - let Ok(entries) = std::fs::read_dir(dir) else { - return false; - }; - - entries.filter_map(Result::ok).any(|entry| { - let path = entry.path(); - if path.is_dir() { - dir_contains_any_file(&path) - } else { - true - } - }) -} - -pub(crate) fn ensure_valid_game_path(game_path: &Path) -> Result<(), String> { - if crate::services::detect::is_valid_game_path(game_path) { - return Ok(()); - } - - Err(format!( - "Selected path is not a valid The Bazaar installation: {}", - game_path.display() - )) -} - -pub(super) fn prepare_install_target( - game_path: &Path, - incoming_relative_paths: &std::collections::HashSet, -) -> Result { - ensure_valid_game_path(game_path)?; - let backup = InstallTargetBackup::capture(game_path)?; - if let Err(cleanup_err) = remove_stale_bpp_files(game_path, incoming_relative_paths) { - return match backup.restore(game_path) { - Ok(()) => Err(cleanup_err), - Err(restore_err) => Err(format!( - "{cleanup_err}; additionally failed to restore previous payload: {restore_err}" - )), - }; - } - - Ok(backup) -} - -/// Install-time pre-clean. Removes an owned path only when the incoming payload -/// no longer ships it; paths the zip will overwrite anyway stay in place so -/// extraction's identical-skip gate decides their fate. -fn remove_stale_bpp_files( - game_path: &Path, - incoming_relative_paths: &std::collections::HashSet, -) -> Result<(), String> { - for relative_path in owned_paths("private").chain(owned_paths("dependency")) { - if incoming_relative_paths.contains(relative_path) { - continue; - } - remove_path_if_exists(&game_path.join(relative_path))?; - } - - Ok(()) -} - -pub(super) fn preserve_file_if_exists( - base_dir: &Path, - relative_path: &'static str, -) -> Result, String> { - let path = base_dir.join(relative_path); - if !path.exists() { - return Ok(None); - } - - let contents = - std::fs::read(&path).map_err(|err| format!("Cannot preserve {}: {err}", path.display()))?; - - Ok(Some(PreservedFile { - relative_path, - contents, - })) -} - -pub(super) fn restore_preserved_file( - base_dir: &Path, - preserved: &PreservedFile, -) -> Result<(), String> { - let path = base_dir.join(preserved.relative_path); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent) - .map_err(|err| format!("Cannot recreate {}: {err}", parent.display()))?; - } - - std::fs::write(&path, &preserved.contents) - .map_err(|err| format!("Cannot restore {}: {err}", path.display())) -} - -pub(super) fn cleanup_bpp_data_directory(game_path: &Path) -> RemovalReport { - remove_dir_with_retry(&crate::services::paths::bpp_data_dir(game_path)) -} - -/// Blunt whole-folder wipe of `/BepInEx` — deletes BazaarPlusPlus AND any -/// third-party plugin/patcher living under it, unlike the surgical -/// `uninstall_payload`. Leaves the platform bootstrap (winhttp.dll on Windows; -/// libdoorstop.dylib, the macOS stub, and the `.orig` backup on macOS) in place. -/// Both loaders tolerate a missing target assembly and fall through to the real -/// game, so the bundle stays launchable and a later Reinstall re-lays BepInEx. -pub(super) fn reset_bepinex_directory(game_path: &Path) -> RemovalReport { - remove_dir_with_retry(&game_path.join("BepInEx")) -} - -#[cfg(test)] -mod tests { - use crate::config::{BAZAAR_DATA_DIRECTORY, DATABASE_FILE_NAME}; - - use super::{ - cleanup_bpp_data_directory, ensure_valid_game_path, prepare_install_target, - preserve_file_if_exists, remove_bootstrap_files, restore_preserved_file, uninstall_payload, - PreservedFile, BPP_CONFIG_RELATIVE_PATH, - }; - - #[test] - fn test_ensure_valid_game_path_rejects_non_game_directory() { - let tmp = tempfile::tempdir().unwrap(); - - let result = ensure_valid_game_path(tmp.path()); - - assert!(result.is_err()); - } - - #[test] - fn test_prepare_install_target_removes_only_stale_bpp_files() { - let tmp = tempfile::tempdir().unwrap(); - - #[cfg(target_os = "macos")] - { - std::fs::create_dir_all(tmp.path().join("TheBazaar.app")).unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/plugins")).unwrap(); - std::fs::write(tmp.path().join("libdoorstop.dylib"), b"dylib").unwrap(); - } - - #[cfg(target_os = "windows")] - { - std::fs::write(tmp.path().join("TheBazaar.exe"), b"exe").unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/plugins")).unwrap(); - std::fs::write(tmp.path().join("doorstop_config.ini"), b"cfg").unwrap(); - std::fs::write(tmp.path().join("winhttp.dll"), b"dll").unwrap(); - } - - std::fs::write(tmp.path().join("BepInEx/plugins/old.dll"), b"dll").unwrap(); - std::fs::write( - tmp.path().join("BepInEx/plugins/BazaarPlusPlus.dll"), - b"bpp", - ) - .unwrap(); - std::fs::write( - tmp.path().join("BepInEx/plugins/Microsoft.Data.Sqlite.dll"), - b"stale dep", - ) - .unwrap(); - - // The incoming payload still ships BazaarPlusPlus.dll but no longer - // ships Microsoft.Data.Sqlite.dll. - let incoming: std::collections::HashSet = - ["BepInEx/plugins/BazaarPlusPlus.dll".to_string()] - .into_iter() - .collect(); - - prepare_install_target(tmp.path(), &incoming).unwrap(); - - // Third-party file: never touched. - assert!(tmp.path().join("BepInEx/plugins/old.dll").exists()); - // Owned and shipped by the incoming zip: left for extraction to overwrite. - assert!(tmp - .path() - .join("BepInEx/plugins/BazaarPlusPlus.dll") - .exists()); - // Owned but stale: removed. - assert!(!tmp - .path() - .join("BepInEx/plugins/Microsoft.Data.Sqlite.dll") - .exists()); - #[cfg(target_os = "macos")] - { - assert!(tmp.path().join("libdoorstop.dylib").exists()); - } - #[cfg(target_os = "windows")] - { - assert!(tmp.path().join("doorstop_config.ini").exists()); - assert!(tmp.path().join("winhttp.dll").exists()); - } - } - - #[test] - fn test_install_target_backup_restores_previous_payload_after_partial_install() { - let tmp = tempfile::tempdir().unwrap(); - - #[cfg(target_os = "macos")] - { - std::fs::create_dir_all(tmp.path().join("TheBazaar.app")).unwrap(); - std::fs::write(tmp.path().join("libdoorstop.dylib"), b"old dylib").unwrap(); - } - - #[cfg(target_os = "windows")] - { - std::fs::write(tmp.path().join("TheBazaar.exe"), b"exe").unwrap(); - std::fs::write(tmp.path().join("doorstop_config.ini"), b"old cfg").unwrap(); - std::fs::write(tmp.path().join("winhttp.dll"), b"old dll").unwrap(); - } - - std::fs::create_dir_all(tmp.path().join("BepInEx/plugins")).unwrap(); - std::fs::write(tmp.path().join("BepInEx/plugins/old.dll"), b"old").unwrap(); - - let backup = prepare_install_target(tmp.path(), &std::collections::HashSet::new()).unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/plugins")).unwrap(); - std::fs::write(tmp.path().join("BepInEx/plugins/new.dll"), b"new").unwrap(); - #[cfg(target_os = "macos")] - std::fs::write(tmp.path().join("libdoorstop.dylib"), b"new dylib").unwrap(); - #[cfg(target_os = "windows")] - std::fs::write(tmp.path().join("winhttp.dll"), b"new dll").unwrap(); - - backup.restore(tmp.path()).unwrap(); - - assert!(tmp.path().join("BepInEx/plugins/old.dll").exists()); - assert!(tmp.path().join("BepInEx/plugins/new.dll").exists()); - #[cfg(target_os = "macos")] - assert_eq!( - std::fs::read(tmp.path().join("libdoorstop.dylib")).unwrap(), - b"old dylib" - ); - #[cfg(target_os = "windows")] - assert_eq!( - std::fs::read(tmp.path().join("winhttp.dll")).unwrap(), - b"old dll" - ); - } - - #[test] - fn test_prepare_install_target_preserves_bpp_data_directory() { - let tmp = tempfile::tempdir().unwrap(); - let plugins_dir = tmp.path().join("BepInEx/plugins"); - let data_dir = tmp.path().join(BAZAAR_DATA_DIRECTORY); - - #[cfg(target_os = "macos")] - { - std::fs::create_dir_all(tmp.path().join("TheBazaar.app")).unwrap(); - std::fs::write(tmp.path().join("libdoorstop.dylib"), b"dylib").unwrap(); - } - - #[cfg(target_os = "windows")] - { - std::fs::write(tmp.path().join("TheBazaar.exe"), b"exe").unwrap(); - std::fs::write(tmp.path().join("doorstop_config.ini"), b"cfg").unwrap(); - std::fs::write(tmp.path().join("winhttp.dll"), b"dll").unwrap(); - } - - std::fs::create_dir_all(&plugins_dir).unwrap(); - std::fs::create_dir_all(&data_dir).unwrap(); - std::fs::write(plugins_dir.join("BazaarPlusPlus.version"), b"4.7.0.prod").unwrap(); - std::fs::write(data_dir.join("stale.dll"), b"dll").unwrap(); - - prepare_install_target(tmp.path(), &std::collections::HashSet::new()).unwrap(); - - assert!(data_dir.exists()); - assert!(data_dir.join("stale.dll").exists()); - } - - #[test] - fn uninstall_preserves_every_data_root() { - // Uninstall's filesystem effects, in both of its modes, leave the - // current Data Root and every Legacy Root in place (ADR-0008). - for keep_shared_dependencies in [false, true] { - let tmp = tempfile::tempdir().unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/plugins")).unwrap(); - std::fs::write( - tmp.path().join("BepInEx/plugins/BazaarPlusPlus.dll"), - b"dll", - ) - .unwrap(); - let roots: Vec<_> = std::iter::once(BAZAAR_DATA_DIRECTORY) - .chain( - crate::services::legacy_data::LegacyRoot::ALL - .into_iter() - .map(crate::services::legacy_data::LegacyRoot::directory_name), - ) - .map(|name| tmp.path().join(name).join(DATABASE_FILE_NAME)) - .collect(); - for database in &roots { - std::fs::create_dir_all(database.parent().unwrap()).unwrap(); - std::fs::write(database, b"db").unwrap(); - } - - if keep_shared_dependencies { - super::uninstall_payload_preserving_shared_dependencies(tmp.path()).unwrap(); - } else { - uninstall_payload(tmp.path()).unwrap(); - remove_bootstrap_files(tmp.path()).unwrap(); - } - - assert!(!tmp - .path() - .join("BepInEx/plugins/BazaarPlusPlus.dll") - .exists()); - for database in &roots { - assert!(database.is_file(), "{} was removed", database.display()); - } - } - } - - #[test] - fn test_uninstall_payload_removes_bpp_files_only() { - let tmp = tempfile::tempdir().unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/plugins")).unwrap(); - std::fs::write( - tmp.path().join("BepInEx/plugins/BazaarPlusPlus.dll"), - b"dll", - ) - .unwrap(); - std::fs::create_dir_all( - tmp.path() - .join("BepInEx/plugins/BppReplayRecorder.app/Contents/MacOS"), - ) - .unwrap(); - std::fs::write( - tmp.path() - .join("BepInEx/plugins/BppReplayRecorder.app/Contents/MacOS/BppReplayRecorder"), - b"helper", - ) - .unwrap(); - std::fs::create_dir_all(tmp.path().join( - "TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/MacOS", - )) - .unwrap(); - std::fs::write( - tmp.path().join( - "TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/MacOS/GfxPluginBppReplayVideoToolbox", - ), - b"plugin", - ) - .unwrap(); - std::fs::create_dir_all(tmp.path().join("TheBazaar_Data/Plugins/x86_64")).unwrap(); - std::fs::write( - tmp.path() - .join("TheBazaar_Data/Plugins/x86_64/GfxPluginBppReplayMediaFoundation.dll"), - b"plugin", - ) - .unwrap(); - std::fs::write(tmp.path().join("BepInEx/plugins/OtherMod.dll"), b"dll").unwrap(); - - #[cfg(target_os = "macos")] - { - std::fs::write(tmp.path().join("libdoorstop.dylib"), b"dylib").unwrap(); - } - - #[cfg(target_os = "windows")] - { - std::fs::write(tmp.path().join("doorstop_config.ini"), b"cfg").unwrap(); - std::fs::write(tmp.path().join("winhttp.dll"), b"dll").unwrap(); - } - - uninstall_payload(tmp.path()).unwrap(); - - assert!(!tmp - .path() - .join("BepInEx/plugins/BazaarPlusPlus.dll") - .exists()); - assert!(!tmp - .path() - .join("BepInEx/plugins/BppReplayRecorder.app") - .exists()); - assert!(!tmp - .path() - .join("TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle") - .exists()); - assert!(!tmp - .path() - .join("TheBazaar_Data/Plugins/x86_64/GfxPluginBppReplayMediaFoundation.dll") - .exists()); - assert!(tmp.path().join("BepInEx/plugins/OtherMod.dll").exists()); - #[cfg(target_os = "macos")] - { - assert!(tmp.path().join("libdoorstop.dylib").exists()); - } - #[cfg(target_os = "windows")] - { - assert!(tmp.path().join("doorstop_config.ini").exists()); - assert!(tmp.path().join("winhttp.dll").exists()); - } - } - - #[test] - fn test_remove_bootstrap_files_restores_vanilla_game_root() { - let tmp = tempfile::tempdir().unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/core")).unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/cache")).unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/config")).unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/plugins")).unwrap(); - std::fs::write( - tmp.path().join("BepInEx/core/BepInEx.Preloader.dll"), - b"dll", - ) - .unwrap(); - std::fs::write(tmp.path().join("BepInEx/cache/typeloader.dat"), b"cache").unwrap(); - std::fs::write(tmp.path().join("BepInEx/config/BepInEx.cfg"), b"cfg").unwrap(); - std::fs::write(tmp.path().join("BepInEx/LogOutput.log"), b"log").unwrap(); - std::fs::write(tmp.path().join("BepInEx/plugins/.gitkeep"), b"").unwrap(); - std::fs::write(tmp.path().join("winhttp.dll"), b"dll").unwrap(); - std::fs::write(tmp.path().join("doorstop_config.ini"), b"cfg").unwrap(); - std::fs::write(tmp.path().join("libdoorstop.dylib"), b"dylib").unwrap(); - - remove_bootstrap_files(tmp.path()).unwrap(); - - assert!(!tmp.path().join("BepInEx").exists()); - assert!(!tmp.path().join("winhttp.dll").exists()); - assert!(!tmp.path().join("doorstop_config.ini").exists()); - assert!(!tmp.path().join("libdoorstop.dylib").exists()); - } - - #[test] - fn test_remove_bootstrap_files_keeps_unknown_foreign_files() { - let tmp = tempfile::tempdir().unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/core")).unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/config")).unwrap(); - std::fs::write( - tmp.path().join("BepInEx/core/BepInEx.Preloader.dll"), - b"dll", - ) - .unwrap(); - std::fs::write(tmp.path().join("BepInEx/config/OtherMod.cfg"), b"cfg").unwrap(); - - remove_bootstrap_files(tmp.path()).unwrap(); - - // Bootstrap gone, unknown foreign config (and thus BepInEx/) kept. - assert!(!tmp.path().join("BepInEx/core").exists()); - assert!(tmp.path().join("BepInEx/config/OtherMod.cfg").exists()); - assert!(tmp.path().join("BepInEx").exists()); - } - - #[test] - fn test_has_third_party_plugins_ignores_bpp_owned_files() { - let tmp = tempfile::tempdir().unwrap(); - let plugins_dir = tmp.path().join("BepInEx/plugins"); - std::fs::create_dir_all(&plugins_dir).unwrap(); - std::fs::write(plugins_dir.join("BazaarPlusPlus.dll"), b"dll").unwrap(); - std::fs::write(plugins_dir.join("Microsoft.Data.Sqlite.dll"), b"dll").unwrap(); - std::fs::create_dir_all(plugins_dir.join("BppReplayRecorder.app/Contents/MacOS")).unwrap(); - std::fs::write( - plugins_dir.join("BppReplayRecorder.app/Contents/MacOS/BppReplayRecorder"), - b"helper", - ) - .unwrap(); - - assert!(!super::has_third_party_plugins(tmp.path())); - - std::fs::write(plugins_dir.join("OtherMod.dll"), b"dll").unwrap(); - - assert!(super::has_third_party_plugins(tmp.path())); - } - - #[test] - fn test_has_third_party_patchers_requires_a_file_not_just_directories() { - let tmp = tempfile::tempdir().unwrap(); - assert!(!super::has_third_party_patchers(tmp.path())); - - std::fs::create_dir_all(tmp.path().join("BepInEx/patchers/SomeMod")).unwrap(); - assert!(!super::has_third_party_patchers(tmp.path())); - - std::fs::write( - tmp.path().join("BepInEx/patchers/SomeMod/Patcher.dll"), - b"dll", - ) - .unwrap(); - assert!(super::has_third_party_patchers(tmp.path())); - } - - #[test] - fn inventory_drives_private_cleanup_and_shared_dependency_preservation() { - let tmp = tempfile::tempdir().unwrap(); - for entry in &super::inventory().files { - if entry.ownership == "bootstrap" { - continue; - } - let target = tmp.path().join(&entry.path); - std::fs::create_dir_all(target.parent().unwrap()).unwrap(); - std::fs::write(target, b"payload").unwrap(); - } - assert!(!super::has_third_party_plugins(tmp.path())); - let foreign = tmp.path().join("BepInEx/plugins/OtherMod.dll"); - std::fs::write(&foreign, b"third party").unwrap(); - assert!(super::has_third_party_plugins(tmp.path())); - - super::uninstall_payload_preserving_shared_dependencies(tmp.path()).unwrap(); - for entry in &super::inventory().files { - if entry.ownership == "bootstrap" { - continue; - } - assert_eq!( - tmp.path().join(&entry.path).exists(), - entry.ownership == "dependency", - "{}", - entry.path - ); - } - assert!(foreign.exists()); - super::uninstall_payload(tmp.path()).unwrap(); - for relative_path in super::owned_paths("dependency") { - assert!(!tmp.path().join(relative_path).exists()); - } - assert!(foreign.exists()); - } - - #[test] - fn test_cleanup_bpp_data_directory_removes_bazaarplusplus_directory() { - let tmp = tempfile::tempdir().unwrap(); - let data_dir = tmp.path().join(BAZAAR_DATA_DIRECTORY); - std::fs::create_dir_all(&data_dir).unwrap(); - std::fs::write(data_dir.join("stale.dll"), b"dll").unwrap(); - - let report = cleanup_bpp_data_directory(tmp.path()); - - assert!( - report.is_empty(), - "unexpected failures: {:?}", - report.failed - ); - assert!(!data_dir.exists()); - } - - #[test] - fn test_cleanup_bpp_data_directory_is_no_op_when_directory_missing() { - let tmp = tempfile::tempdir().unwrap(); - - let report = cleanup_bpp_data_directory(tmp.path()); - - assert!(report.is_empty()); - } - - #[test] - fn test_cleanup_bpp_data_directory_walks_nested_subdirectories() { - let tmp = tempfile::tempdir().unwrap(); - let data_dir = tmp.path().join(BAZAAR_DATA_DIRECTORY); - let nested = data_dir.join("Identity").join("inner"); - std::fs::create_dir_all(&nested).unwrap(); - std::fs::write(data_dir.join(DATABASE_FILE_NAME), b"db").unwrap(); - std::fs::write(nested.join("auth.json"), b"auth").unwrap(); - - let report = cleanup_bpp_data_directory(tmp.path()); - - assert!( - report.is_empty(), - "unexpected failures: {:?}", - report.failed - ); - assert!(!data_dir.exists()); - } - - #[cfg(unix)] - #[test] - fn test_cleanup_bpp_data_directory_reports_locked_files_without_aborting_siblings() { - use std::os::unix::fs::PermissionsExt; - - let tmp = tempfile::tempdir().unwrap(); - let data_dir = tmp.path().join(BAZAAR_DATA_DIRECTORY); - let unwritable_subdir = data_dir.join("locked"); - std::fs::create_dir_all(&unwritable_subdir).unwrap(); - std::fs::write(data_dir.join("removable.bin"), b"x").unwrap(); - std::fs::write(unwritable_subdir.join("trapped.bin"), b"x").unwrap(); - - // Drop write permission on the parent dir so its child can't be unlinked. - std::fs::set_permissions(&unwritable_subdir, std::fs::Permissions::from_mode(0o500)) - .unwrap(); - - let report = cleanup_bpp_data_directory(tmp.path()); - - // Restore permissions so the tempdir cleanup succeeds even if the test fails. - let _ = - std::fs::set_permissions(&unwritable_subdir, std::fs::Permissions::from_mode(0o700)); - - assert!(!report.is_empty(), "expected at least one failed path"); - assert!(!data_dir.join("removable.bin").exists()); - } - - #[test] - fn test_preserve_file_if_exists_reads_existing_file() { - let tmp = tempfile::tempdir().unwrap(); - let config_path = tmp.path().join(BPP_CONFIG_RELATIVE_PATH); - std::fs::create_dir_all(config_path.parent().unwrap()).unwrap(); - std::fs::write(&config_path, b"user-config").unwrap(); - - let preserved = preserve_file_if_exists(tmp.path(), BPP_CONFIG_RELATIVE_PATH) - .unwrap() - .expect("expected preserved config"); - - assert_eq!(preserved.relative_path, BPP_CONFIG_RELATIVE_PATH); - assert_eq!(preserved.contents, b"user-config"); - } - - #[test] - fn test_restore_preserved_file_recreates_parent_directory() { - let tmp = tempfile::tempdir().unwrap(); - let preserved = PreservedFile { - relative_path: BPP_CONFIG_RELATIVE_PATH, - contents: b"user-config".to_vec(), - }; - - restore_preserved_file(tmp.path(), &preserved).unwrap(); - - assert_eq!( - std::fs::read(tmp.path().join(BPP_CONFIG_RELATIVE_PATH)).unwrap(), - b"user-config" - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/bepinex/trampoline.rs b/bazaarplusplus-installer/src-tauri/src/services/bepinex/trampoline.rs deleted file mode 100644 index a69fc99..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/bepinex/trampoline.rs +++ /dev/null @@ -1,1267 +0,0 @@ -//! macOS in-bundle Mach-O launch trampoline. -//! -//! The trampoline is the only macOS launch bootstrap. This module installs a -//! tiny arm64 stub as the bundle's `CFBundleExecutable`, renames the real Unity -//! bootstrap to `.orig`, and re-signs the real binary with the JIT -//! entitlements so Harmony can write executable memory. -//! -//! Every behaviour here is macOS-only; the public API has no-op / `false` stubs on -//! other platforms so the install orchestrator can call it unconditionally. - -use std::path::Path; - -use crate::services::action_error::ActionError; -#[cfg(target_os = "macos")] -use crate::services::game_process::{ensure_game_stopped, GameStoppedOperation}; - -#[cfg(target_os = "macos")] -use std::path::PathBuf; - -use tauri::AppHandle; - -#[cfg(target_os = "macos")] -const OBSOLETE_MACOS_ARTIFACTS: &[&str] = &["run_bepinex.sh", "bpp_launcher.c", ".bpp-launch-mode"]; - -// --------------------------------------------------------------------------- -// Trampoline install / uninstall (macOS) -// --------------------------------------------------------------------------- - -#[cfg(target_os = "macos")] -mod imp { - use super::*; - use std::process::Command; - use tauri::Manager; - - /// The 3 JIT/library-validation entitlements that must live on the REAL binary - /// (the process that runs Harmony / `mprotect` W+X). - pub(super) const TRAMPOLINE_ENTITLEMENTS: &str = r#" - - - - com.apple.security.cs.allow-jit - com.apple.security.cs.allow-unsigned-executable-memory - com.apple.security.cs.disable-library-validation - - -"#; - - /// Resolved bundle paths derived from the bundle's current `CFBundleExecutable`. - pub(super) struct BundleLayout { - pub(super) app_path: PathBuf, - pub(super) exe_path: PathBuf, - pub(super) orig_path: PathBuf, - } - - /// Read `CFBundleExecutable` and derive the stub / real-binary paths. - pub(super) fn bundle_paths(game_path: &Path) -> Result { - let app_path = game_path.join("TheBazaar.app"); - if !app_path.is_dir() { - return Err(format!( - "{} is not a valid game bundle (TheBazaar.app missing)", - game_path.display() - )); - } - let info_plist = app_path.join("Contents/Info.plist"); - let exe_name = read_cf_bundle_executable(&info_plist)?; - let macos_dir = app_path.join("Contents/MacOS"); - let exe_path = macos_dir.join(&exe_name); - let orig_path = macos_dir.join(format!("{exe_name}.orig")); - Ok(BundleLayout { - app_path, - exe_path, - orig_path, - }) - } - - fn read_cf_bundle_executable(info_plist: &Path) -> Result { - let output = Command::new("plutil") - .args(["-extract", "CFBundleExecutable", "raw", "-o", "-"]) - .arg(info_plist) - .output() - .map_err(|err| format!("Cannot run plutil on {}: {err}", info_plist.display()))?; - if !output.status.success() { - return Err(format!( - "Cannot read CFBundleExecutable from {}: {}", - info_plist.display(), - String::from_utf8_lossy(&output.stderr).trim() - )); - } - let name = String::from_utf8_lossy(&output.stdout).trim().to_string(); - if name.is_empty() { - return Err(format!( - "CFBundleExecutable is empty in {}", - info_plist.display() - )); - } - Ok(name) - } - - /// The real Unity bootstrap links `UnityPlayer.dylib`; our tiny stub does not. - /// Used to guard the rename (never rename a stray stub as if it were the game) - /// and to detect the trampolined state. The Mach-O is parsed in-process: - /// `otool` is an Xcode shim that fails until the Xcode license is accepted, - /// and a probe that cannot run must never read as "not the real binary". - pub(super) fn links_unity(path: &Path) -> Result { - let bytes = match std::fs::read(path) { - Ok(bytes) => bytes, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false), - Err(err) => { - return Err(format!( - "Cannot read game executable {}: {err}", - path.display() - )) - } - }; - Ok(macho_images(&bytes) - .into_iter() - .any(|(_, image)| image_links_unity(image))) - } - - /// Whether the executable carries an arm64 image, thin or as a universal slice. - /// Parsed in-process for the same reason as [`links_unity`]: `lipo` is an Xcode shim. - pub(super) fn has_arm64(path: &Path) -> Result { - let bytes = std::fs::read(path) - .map_err(|err| format!("Cannot inspect game architecture: {err}"))?; - Ok(macho_images(&bytes) - .into_iter() - .any(|(cpu_type, _)| cpu_type == CPU_TYPE_ARM64)) - } - - fn command_available(command: &str, args: &[&str]) -> bool { - Command::new(command).args(args).output().is_ok() - } - - fn codesign_available() -> bool { - // macOS `codesign` does not support `--version`; availability only means - // the executable can be spawned. Real signing errors are reported later. - command_available("codesign", &["-h"]) - } - - pub(super) fn stub_resource_path(app: &AppHandle) -> Result { - let stub = app - .path() - .resource_dir() - .map_err(|err| err.to_string())? - .join("Trampoline/bpp_launcher"); - if !stub.exists() { - return Err(format!( - "Bundled trampoline stub is missing at {}", - stub.display() - )); - } - Ok(stub) - } - - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - pub(super) enum RealBinarySource { - CurrentExe, - ExistingOrig, - } - - /// Decide which file holds the real Unity binary so [`install_trampoline`] - /// preserves exactly it as `.orig`. A live `` that links Unity always - /// wins — this covers a fresh install AND a Steam update/Verify that wrote a - /// NEW real binary at `` on top of a STALE `.orig` from a prior - /// trampoline (where re-running Repair must keep the fresh binary, never - /// re-stub over it and exec the stale one). Only when `` is not the real - /// binary do we fall back to an existing, genuinely-real `.orig`; anything - /// else is corrupt and only Steam can re-supply the binary. - pub(super) fn classify_real_binary( - exe_is_real: bool, - orig_exists: bool, - orig_is_real: bool, - ) -> Result { - if exe_is_real { - Ok(RealBinarySource::CurrentExe) - } else if orig_exists && orig_is_real { - Ok(RealBinarySource::ExistingOrig) - } else if orig_exists { - Err( - "The game binary backup (.orig) exists but is not the real Unity binary. Run Steam \"Verify integrity of game files\" and reinstall." - .to_string(), - ) - } else { - Err( - "The game's main executable is not the real Unity binary and no backup exists. Run Steam \"Verify integrity of game files\"." - .to_string(), - ) - } - } - - /// Mechanical filesystem swap (no signing, no Unity check — callers guard - /// first): preserve the real binary as `.orig` once, then drop the stub in - /// its place. Idempotent — never clobbers an existing `.orig`. - pub(super) fn swap_in_stub(layout: &BundleLayout, stub_src: &Path) -> Result<(), String> { - if !layout.orig_path.exists() { - std::fs::rename(&layout.exe_path, &layout.orig_path).map_err(|err| { - format!( - "Cannot rename {} to {}: {err}", - layout.exe_path.display(), - layout.orig_path.display() - ) - })?; - } - install_stub(stub_src, &layout.exe_path) - } - - /// Inverse of [`swap_in_stub`]: drop the stub and move the real binary back. - pub(super) fn restore_vanilla_layout(layout: &BundleLayout) -> Result<(), String> { - if layout.exe_path.exists() && layout.orig_path.exists() { - // exe is the stub copy; remove it so the rename can take its place. - let _ = std::fs::remove_file(&layout.exe_path); - } - if layout.orig_path.exists() { - std::fs::rename(&layout.orig_path, &layout.exe_path).map_err(|err| { - format!( - "Cannot restore {} from {}: {err}", - layout.exe_path.display(), - layout.orig_path.display() - ) - })?; - } - Ok(()) - } - - fn install_stub(stub_src: &Path, exe_dst: &Path) -> Result<(), String> { - use std::os::unix::fs::PermissionsExt; - let game_root = exe_dst - .ancestors() - .nth(4) - .ok_or_else(|| format!("Invalid game executable path: {}", exe_dst.display()))?; - let staged = tempfile::Builder::new() - .prefix(".bpp-stub-") - .tempfile_in(game_root) - .map_err(|err| format!("Cannot stage game executable: {err}"))?; - std::fs::copy(stub_src, staged.path()).map_err(|err| { - format!( - "Cannot install trampoline stub to {}: {err}", - exe_dst.display() - ) - })?; - std::fs::set_permissions(staged.path(), std::fs::Permissions::from_mode(0o755)) - .map_err(|err| format!("Cannot set permissions on {}: {err}", exe_dst.display()))?; - // Best-effort: an AMFI-relevant quarantine on the bundle main could block - // launch on macOS 27. The installer is notarized, so this is defensive. - let _ = Command::new("xattr") - .args(["-d", "com.apple.quarantine"]) - .arg(staged.path()) - .output(); - staged - .persist(exe_dst) - .map_err(|err| format!("Cannot replace {}: {err}", exe_dst.display()))?; - Ok(()) - } - - fn sign_real_binary(orig: &Path) -> Result<(), String> { - let entitlements = tempfile::Builder::new() - .prefix("bpp-ents-") - .suffix(".plist") - .tempfile() - .map_err(|err| format!("Cannot create entitlements temp file: {err}"))?; - std::fs::write(entitlements.path(), TRAMPOLINE_ENTITLEMENTS) - .map_err(|err| format!("Cannot write entitlements: {err}"))?; - run_codesign( - &[ - "--force".as_ref(), - "--sign".as_ref(), - "-".as_ref(), - "--entitlements".as_ref(), - entitlements.path().as_os_str(), - orig.as_os_str(), - ], - &format!("sign {} with JIT entitlements", orig.display()), - ) - } - - pub(super) fn seal_bundle(app: &Path) -> Result<(), String> { - // NO --deep: re-signing the bundle main + sealing resources, without - // re-signing the nested `.orig` (which would strip its entitlements). - run_codesign( - &[ - "--force".as_ref(), - "--sign".as_ref(), - "-".as_ref(), - app.as_os_str(), - ], - &format!("seal {}", app.display()), - ) - } - - pub(super) fn verify_bundle(app: &Path) -> Result<(), String> { - run_codesign( - &[ - "--verify".as_ref(), - "--deep".as_ref(), - "--strict".as_ref(), - app.as_os_str(), - ], - &format!("verify {}", app.display()), - ) - } - - fn run_codesign(args: &[&std::ffi::OsStr], context: &str) -> Result<(), String> { - let output = Command::new("codesign") - .args(args) - .output() - .map_err(|err| format!("Cannot run codesign to {context}: {err}"))?; - if output.status.success() { - Ok(()) - } else { - Err(format!( - "codesign failed to {context}: {}", - String::from_utf8_lossy(&output.stderr).trim() - )) - } - } - - pub(super) fn is_trampolined(game_path: &Path) -> Result { - let layout = bundle_paths(game_path)?; - if !layout.orig_path.exists() { - return Ok(false); - } - Ok(layout.exe_path.exists() - && !links_unity(&layout.exe_path)? - && links_unity(&layout.orig_path)?) - } - - pub(super) fn install_trampoline(resource_dir: &Path, game_path: &Path) -> Result<(), String> { - let stub = resource_dir.join("Trampoline/bpp_launcher"); - install_with_stub(game_path, &stub) - } - - pub(super) fn install_with_stub(game_path: &Path, stub: &Path) -> Result<(), String> { - install_with_finalizer(game_path, stub, |layout| { - sign_real_binary(&layout.orig_path)?; - seal_bundle(&layout.app_path)?; - verify_bundle(&layout.app_path) - }) - } - - pub(super) fn install_with_finalizer( - game_path: &Path, - stub: &Path, - finalize: impl FnOnce(&BundleLayout) -> Result<(), String>, - ) -> Result<(), String> { - // Step 0: absolute preconditions BEFORE any filesystem mutation — a - // modified-but-unsigned bundle is AMFI-killed on Apple Silicon. - if !codesign_available() { - return Err( - "codesign is unavailable; cannot install the macOS launch trampoline. Install the Xcode command line tools and retry." - .to_string(), - ); - } - let layout = bundle_paths(game_path)?; - - // Step 2: identify the real Unity binary and preserve exactly it as - // `.orig`. Critically, a Steam update/Verify can leave a FRESH real binary - // at on top of a STALE .orig; we keep the fresh one and discard - // the stale backup, never the reverse (which would re-stub over the updated - // binary and silently exec the old one). - let exe_is_real = links_unity(&layout.exe_path)?; - let orig_exists = layout.orig_path.exists(); - let orig_is_real = orig_exists && links_unity(&layout.orig_path)?; - let source = classify_real_binary(exe_is_real, orig_exists, orig_is_real)?; - let real = match source { - RealBinarySource::CurrentExe => &layout.exe_path, - RealBinarySource::ExistingOrig => &layout.orig_path, - }; - if !has_arm64(real)? { - return Err("The game executable has no arm64 architecture; restore the Steam game before repairing.".to_string()); - } - if !stub.is_file() { - return Err(format!( - "Bundled trampoline stub is missing at {}", - stub.display() - )); - } - read_macho_uuid(stub)?; - super::super::bundle_root::normalize(game_path)?; - // Preserve the selected current game binary before codesign can rewrite it. - // Initial installs and already-installed repairs share this recovery path. - let recovery = tempfile::tempdir_in(game_path) - .map_err(|err| format!("Cannot prepare game binary recovery: {err}"))?; - let recovery_exe = recovery.path().join("game-executable"); - std::fs::copy(real, &recovery_exe) - .map_err(|err| format!("Cannot back up game executable: {err}"))?; - match source { - RealBinarySource::CurrentExe => { - // is the real binary (fresh install, or Steam-updated over a - // stale backup). Drop any stale `.orig` so the swap renames the - // CURRENT binary into `.orig` instead of clobbering it. - if orig_exists { - std::fs::remove_file(&layout.orig_path).map_err(|err| { - format!("Cannot remove stale {}: {err}", layout.orig_path.display()) - })?; - } - } - RealBinarySource::ExistingOrig => { - // is our stub / a partial copy; the real binary is already - // safely preserved as `.orig` (recover a prior interrupted run). - } - } - - // Steps 3-7 with rollback on any failure. - let result = (|| -> Result<(), String> { - swap_in_stub(&layout, stub)?; // rename real -> .orig (if needed) + drop stub - finalize(&layout) - })(); - - match result { - Ok(()) => Ok(()), - Err(err) => { - let rollback = (|| { - install_stub(&recovery_exe, &layout.exe_path)?; - if layout.orig_path.exists() { - std::fs::remove_file(&layout.orig_path) - .map_err(|error| error.to_string())?; - } - seal_bundle(&layout.app_path)?; - verify_bundle(&layout.app_path) - })(); - match rollback { - Ok(()) => Err(err), - Err(restore_err) => { - let retained = recovery.keep(); - Err(format!("{err}; game recovery also failed: {restore_err}. The executable backup is retained at {}. Run Steam \"Verify integrity of game files\".", retained.display())) - } - } - } - } - } - - pub(super) fn uninstall_trampoline(game_path: &Path) -> Result<(), String> { - let layout = bundle_paths(game_path)?; - super::super::bundle_root::normalize(game_path)?; - - if layout.orig_path.exists() { - if !codesign_available() { - return Err( - "codesign is unavailable; cannot restore the vanilla game bundle. Install the Xcode command line tools and retry." - .to_string(), - ); - } - restore_vanilla_layout(&layout)?; - // The caller seals after removing all owned in-bundle payload files. - return Ok(()); - } - - // .orig missing: either already vanilla (Steam verify reverted) or broken. - if links_unity(&layout.exe_path)? { - return Ok(()); - } - Err(format!( - "The game binary backup is missing ({} not found) and {} is still the trampoline stub. Run Steam \"Verify integrity of game files\" to restore the game.", - layout.orig_path.display(), - layout.exe_path.display() - )) - } -} - -#[cfg(target_os = "macos")] -pub(crate) fn is_current_trampoline(app: &AppHandle, game_path: &Path) -> Result { - is_current_with_stub(game_path, &imp::stub_resource_path(app)?) -} - -#[cfg(target_os = "macos")] -fn is_current_with_stub(game_path: &Path, bundled: &Path) -> Result { - if !imp::is_trampolined(game_path)? { - return Ok(false); - } - let layout = imp::bundle_paths(game_path)?; - Ok(trampoline_builds_match(&layout.exe_path, bundled)? - && imp::verify_bundle(&layout.app_path).is_ok()) -} - -#[cfg(target_os = "macos")] -pub(crate) fn finalize_game_bundle(game_path: &Path) -> Result<(), String> { - super::bundle_root::normalize(game_path)?; - let layout = imp::bundle_paths(game_path)?; - imp::seal_bundle(&layout.app_path)?; - imp::verify_bundle(&layout.app_path) -} - -#[cfg(not(target_os = "macos"))] -pub(crate) fn finalize_game_bundle(_game_path: &Path) -> Result<(), String> { - Ok(()) -} - -pub(super) fn with_finalized_bundle( - game_path: &Path, - operation: impl FnOnce() -> Result<(), String>, -) -> Result<(), String> { - let result = operation(); - match (result, finalize_game_bundle(game_path)) { - (result, Ok(())) => result, - (Ok(()), Err(error)) => Err(error), - (Err(error), Err(final_error)) => Err(format!( - "{error}; final game bundle signing also failed: {final_error}" - )), - } -} - -/// Refuses while the game runs: rewriting the bundle under a live process -/// would leave it unsigned. -#[cfg(target_os = "macos")] -pub(crate) fn install_trampoline(resource_dir: &Path, game_path: &Path) -> Result<(), ActionError> { - ensure_game_stopped(game_path, GameStoppedOperation::Install)?; - Ok(imp::install_trampoline(resource_dir, game_path)?) -} - -#[cfg(target_os = "macos")] -pub(super) fn repair_with_stub(game_path: &Path, stub: &Path) -> Result<(), String> { - ensure_game_stopped(game_path, GameStoppedOperation::Install) - .map_err(|refusal| refusal.to_string())?; - imp::install_with_stub(game_path, stub) -} - -#[cfg(target_os = "macos")] -pub(crate) fn uninstall_trampoline(game_path: &Path) -> Result<(), String> { - imp::uninstall_trampoline(game_path) -} - -#[cfg(target_os = "macos")] -pub(crate) fn obsolete_macos_artifacts_present(game_path: &Path) -> bool { - OBSOLETE_MACOS_ARTIFACTS - .iter() - .any(|relative| game_path.join(relative).exists()) -} - -#[cfg(target_os = "macos")] -pub(crate) fn remove_obsolete_macos_artifacts(game_path: &Path) -> Result<(), String> { - for relative in OBSOLETE_MACOS_ARTIFACTS { - let path = game_path.join(relative); - match std::fs::remove_file(&path) { - Ok(()) => {} - Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} - Err(err) => return Err(format!("Cannot remove obsolete {}: {err}", path.display())), - } - } - Ok(()) -} - -#[cfg(target_os = "macos")] -fn trampoline_builds_match(left: &Path, right: &Path) -> Result { - Ok(read_macho_uuid(left)? == read_macho_uuid(right)?) -} - -#[cfg(target_os = "macos")] -const MH_MAGIC_64: u32 = 0xfeedfacf; -#[cfg(target_os = "macos")] -const CPU_TYPE_ARM64: u32 = 0x0100_000c; - -#[cfg(target_os = "macos")] -fn read_u32_le(bytes: &[u8], offset: usize) -> Option { - let value = bytes.get(offset..offset.checked_add(4)?)?; - Some(u32::from_le_bytes(value.try_into().ok()?)) -} - -#[cfg(target_os = "macos")] -fn read_u32_be(bytes: &[u8], offset: usize) -> Option { - let value = bytes.get(offset..offset.checked_add(4)?)?; - Some(u32::from_be_bytes(value.try_into().ok()?)) -} - -#[cfg(target_os = "macos")] -fn read_u64_be(bytes: &[u8], offset: usize) -> Option { - let value = bytes.get(offset..offset.checked_add(8)?)?; - Some(u64::from_be_bytes(value.try_into().ok()?)) -} - -/// Every 64-bit little-endian Mach-O image in `bytes` as `(cputype, image)`: the -/// file itself when thin, or each slice of a universal binary. Anything else, -/// including a truncated or malformed header, yields no images. -#[cfg(target_os = "macos")] -fn macho_images(bytes: &[u8]) -> Vec<(u32, &[u8])> { - const FAT_MAGIC: u32 = 0xcafebabe; - const FAT_MAGIC_64: u32 = 0xcafebabf; - const FAT_HEADER_SIZE: usize = 8; - - fn thin(image: &[u8]) -> Option<(u32, &[u8])> { - (read_u32_le(image, 0)? == MH_MAGIC_64).then_some((read_u32_le(image, 4)?, image)) - } - - let wide = match read_u32_be(bytes, 0) { - Some(FAT_MAGIC) => false, - Some(FAT_MAGIC_64) => true, - _ => return thin(bytes).into_iter().collect(), - }; - let entry_size = if wide { 32 } else { 20 }; - let declared = read_u32_be(bytes, 4).unwrap_or(0) as usize; - let present = bytes.len().saturating_sub(FAT_HEADER_SIZE) / entry_size; - (0..declared.min(present)) - .filter_map(|index| { - let entry = FAT_HEADER_SIZE + index * entry_size; - let (offset, size) = if wide { - ( - read_u64_be(bytes, entry + 8)?, - read_u64_be(bytes, entry + 16)?, - ) - } else { - ( - u64::from(read_u32_be(bytes, entry + 8)?), - u64::from(read_u32_be(bytes, entry + 12)?), - ) - }; - let start = usize::try_from(offset).ok()?; - let end = start.checked_add(usize::try_from(size).ok()?)?; - thin(bytes.get(start..end)?) - }) - .collect() -} - -/// The load commands of a thin 64-bit Mach-O image as `(cmd, command bytes)`. -#[cfg(target_os = "macos")] -fn load_commands(image: &[u8]) -> Result, &'static str> { - const MACH_HEADER_64_SIZE: usize = 32; - - let command_count = read_u32_le(image, 16).ok_or("an incomplete Mach-O header")?; - let command_bytes = read_u32_le(image, 20).ok_or("an incomplete Mach-O header")? as usize; - let commands_end = MACH_HEADER_64_SIZE - .checked_add(command_bytes) - .filter(|end| *end <= image.len()) - .ok_or("invalid Mach-O load commands")?; - - let mut commands = Vec::new(); - let mut offset = MACH_HEADER_64_SIZE; - for _ in 0..command_count { - let command = read_u32_le(image, offset).ok_or("an incomplete Mach-O load command")?; - let command_size = - read_u32_le(image, offset + 4).ok_or("an incomplete Mach-O load command")? as usize; - let next_offset = offset - .checked_add(command_size) - .filter(|next| command_size >= 8 && *next <= commands_end) - .ok_or("an invalid Mach-O load command")?; - commands.push((command, &image[offset..next_offset])); - offset = next_offset; - } - Ok(commands) -} - -/// Whether a thin image loads `UnityPlayer.dylib` through any dylib load command. -#[cfg(target_os = "macos")] -fn image_links_unity(image: &[u8]) -> bool { - const LC_REQ_DYLD: u32 = 0x8000_0000; - const DYLIB_LOAD_COMMANDS: [u32; 5] = [ - 0xc, // LC_LOAD_DYLIB - 0x18 | LC_REQ_DYLD, // LC_LOAD_WEAK_DYLIB - 0x1f | LC_REQ_DYLD, // LC_REEXPORT_DYLIB - 0x20, // LC_LAZY_LOAD_DYLIB - 0x23 | LC_REQ_DYLD, // LC_LOAD_UPWARD_DYLIB - ]; - - let Ok(commands) = load_commands(image) else { - return false; - }; - commands.into_iter().any(|(command, bytes)| { - DYLIB_LOAD_COMMANDS.contains(&command) - && read_u32_le(bytes, 8) - .and_then(|name_offset| bytes.get(name_offset as usize..)) - .and_then(|name| name.split(|byte| *byte == 0).next()) - .is_some_and(|name| name.ends_with(b"UnityPlayer.dylib")) - }) -} - -#[cfg(target_os = "macos")] -fn read_macho_uuid(path: &Path) -> Result<[u8; 16], String> { - const LC_UUID: u32 = 0x1b; - const LC_UUID_SIZE: usize = 24; - - let bytes = std::fs::read(path) - .map_err(|err| format!("Cannot read trampoline {}: {err}", path.display()))?; - if read_u32_le(&bytes, 0) != Some(MH_MAGIC_64) { - return Err(format!( - "Trampoline {} is not a 64-bit little-endian Mach-O image", - path.display() - )); - } - - let commands = load_commands(&bytes) - .map_err(|problem| format!("Trampoline {} has {problem}", path.display()))?; - let (_, command) = commands - .into_iter() - .find(|(command, _)| *command == LC_UUID) - .ok_or_else(|| format!("Trampoline {} has no Mach-O build UUID", path.display()))?; - command - .get(8..LC_UUID_SIZE) - .and_then(|uuid| uuid.try_into().ok()) - .ok_or_else(|| { - format!( - "Trampoline {} has an invalid Mach-O UUID command", - path.display() - ) - }) -} - -#[cfg(not(target_os = "macos"))] -pub(crate) fn is_current_trampoline(_app: &AppHandle, _game_path: &Path) -> Result { - Ok(true) -} - -#[cfg(not(target_os = "macos"))] -pub(crate) fn install_trampoline( - _resource_dir: &Path, - _game_path: &Path, -) -> Result<(), ActionError> { - Ok(()) -} - -#[cfg(not(target_os = "macos"))] -pub(crate) fn uninstall_trampoline(_game_path: &Path) -> Result<(), String> { - Ok(()) -} - -#[cfg(not(target_os = "macos"))] -pub(crate) fn obsolete_macos_artifacts_present(_game_path: &Path) -> bool { - false -} - -#[cfg(not(target_os = "macos"))] -pub(crate) fn remove_obsolete_macos_artifacts(_game_path: &Path) -> Result<(), String> { - Ok(()) -} - -#[cfg(test)] -#[cfg(target_os = "macos")] -mod tests { - use super::imp::{ - bundle_paths, classify_real_binary, is_trampolined, restore_vanilla_layout, swap_in_stub, - RealBinarySource, TRAMPOLINE_ENTITLEMENTS, - }; - use super::*; - - fn command(program: &str, args: &[&std::ffi::OsStr]) { - let mut command = std::process::Command::new(program); - if program == "clang" { - let sdk = std::process::Command::new("xcrun") - .args(["--sdk", "macosx", "--show-sdk-path"]) - .output() - .unwrap(); - assert!(sdk.status.success()); - command.args(["-isysroot", String::from_utf8_lossy(&sdk.stdout).trim()]); - } - let output = command.args(args).output().unwrap(); - assert!( - output.status.success(), - "{program}: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - fn native_bundle() -> (tempfile::TempDir, PathBuf) { - use super::super::bundle_root::tests::make_bundle; - let game = tempfile::tempdir().unwrap(); - let app = make_bundle(game.path()); - let source = game.path().join("engine.c"); - std::fs::write(&source, "int unity_probe(void) { return 0; }").unwrap(); - let engine = app.join("Contents/Frameworks/UnityPlayer.dylib"); - command( - "clang", - &[ - "-arch".as_ref(), - "arm64".as_ref(), - "-dynamiclib".as_ref(), - "-install_name".as_ref(), - "@rpath/UnityPlayer.dylib".as_ref(), - source.as_os_str(), - "-o".as_ref(), - engine.as_os_str(), - ], - ); - let mono = app.join("Contents/Frameworks/libmonobdwgc-2.0.dylib"); - std::fs::copy(&engine, &mono).unwrap(); - std::fs::write( - &source, - "extern int unity_probe(void); int main(void) { return unity_probe(); }", - ) - .unwrap(); - let executable = app.join("Contents/MacOS/The Bazaar"); - command( - "clang", - &[ - "-arch".as_ref(), - "arm64".as_ref(), - source.as_os_str(), - engine.as_os_str(), - "-Wl,-rpath,@executable_path/../Frameworks".as_ref(), - "-o".as_ref(), - executable.as_os_str(), - ], - ); - imp::seal_bundle(&app).unwrap(); - imp::verify_bundle(&app).unwrap(); - let stub = game.path().join("stub"); - std::fs::write(&source, "int main(void) { return 0; }").unwrap(); - command( - "clang", - &[ - "-arch".as_ref(), - "arm64".as_ref(), - source.as_os_str(), - "-o".as_ref(), - stub.as_os_str(), - ], - ); - (game, stub) - } - - #[test] - fn native_repair_converges_after_repetition_steam_updates_and_resource_changes() { - use super::super::bundle_root::tests::copy_tree; - let (game, stub) = native_bundle(); - let layout = bundle_paths(game.path()).unwrap(); - std::fs::write(layout.app_path.join(".DS_Store"), b"Finder metadata").unwrap(); - let backups = game.path().join(".bpp-bundle-root-stash"); - std::fs::create_dir(&backups).unwrap(); - std::fs::write(backups.join(".DS_Store"), b"Legacy Finder metadata").unwrap(); - let clean = game.path().join("steam.app"); - copy_tree(&layout.app_path, &clean); - copy_tree(&clean, &layout.app_path.join("TheBazaar_ARM64.app")); - assert!(imp::verify_bundle(&layout.app_path) - .unwrap_err() - .contains("unsealed contents")); - for _ in 0..3 { - imp::install_with_stub(game.path(), &stub).unwrap(); - assert!(is_current_with_stub(game.path(), &stub).unwrap()); - assert!(imp::links_unity(&layout.orig_path).unwrap()); - assert!(!layout.app_path.join("TheBazaar_ARM64.app").exists()); - } - let entitlements = std::process::Command::new("codesign") - .args(["-d", "--entitlements", ":-"]) - .arg(&layout.orig_path) - .output() - .unwrap(); - let entitlements = format!( - "{}{}", - String::from_utf8_lossy(&entitlements.stdout), - String::from_utf8_lossy(&entitlements.stderr) - ); - assert!(entitlements.contains("com.apple.security.cs.allow-jit")); - - // Steam restores its executable and duplicate over the existing .orig. - std::fs::copy(clean.join("Contents/MacOS/The Bazaar"), &layout.exe_path).unwrap(); - copy_tree(&clean, &layout.app_path.join("TheBazaar_ARM64.app")); - assert!(!is_current_with_stub(game.path(), &stub).unwrap()); - imp::install_with_stub(game.path(), &stub).unwrap(); - assert!(is_current_with_stub(game.path(), &stub).unwrap()); - - // Resource damage must change readiness even when the stub UUID matches. - let resource = layout.app_path.join("Contents/Resources/Data/boot.config"); - std::fs::write(&resource, b"changed").unwrap(); - assert!(!is_current_with_stub(game.path(), &stub).unwrap()); - imp::install_with_stub(game.path(), &stub).unwrap(); - assert!(is_current_with_stub(game.path(), &stub).unwrap()); - - // A shared-bootstrap uninstall removes an in-bundle plugin, then seals. - std::fs::remove_file(&resource).unwrap(); - finalize_game_bundle(game.path()).unwrap(); - assert!(is_current_with_stub(game.path(), &stub).unwrap()); - let error = with_finalized_bundle(game.path(), || { - imp::uninstall_trampoline(game.path())?; - Err("simulated payload removal failure".into()) - }) - .unwrap_err(); - assert_eq!(error, "simulated payload removal failure"); - assert!(imp::links_unity(&layout.exe_path).unwrap()); - assert!(!layout.orig_path.exists()); - imp::verify_bundle(&layout.app_path).unwrap(); - assert_eq!( - std::fs::read(layout.app_path.join(".DS_Store")).unwrap(), - b"Finder metadata" - ); - assert_eq!( - std::fs::read(backups.join(".DS_Store")).unwrap(), - b"Legacy Finder metadata" - ); - } - - #[test] - fn native_failed_repair_recovers_the_real_binary_and_can_be_retried() { - let (game, stub) = native_bundle(); - imp::install_with_stub(game.path(), &stub).unwrap(); - let error = imp::install_with_finalizer(game.path(), &stub, |layout| { - // Simulate a signing failure after the real binary has been rewritten. - std::fs::write(&layout.orig_path, b"partly rewritten signature").unwrap(); - Err("injected signing failure".into()) - }) - .unwrap_err(); - assert_eq!(error, "injected signing failure"); - let layout = bundle_paths(game.path()).unwrap(); - assert!(imp::links_unity(&layout.exe_path).unwrap()); - assert!(!layout.orig_path.exists()); - imp::verify_bundle(&layout.app_path).unwrap(); - imp::install_with_stub(game.path(), &stub).unwrap(); - assert!(is_current_with_stub(game.path(), &stub).unwrap()); - } - - #[test] - #[ignore = "macOS acceptance: run through `just installer::acceptance`; copies BPP_TEST_GAME_ROOT and never mutates it"] - fn copied_steam_bundle_repair_acceptance() { - let source = - PathBuf::from(std::env::var_os("BPP_TEST_GAME_ROOT").expect("BPP_TEST_GAME_ROOT")); - let resources = PathBuf::from( - std::env::var_os("BPP_ACCEPTANCE_RESOURCE_DIR").expect("BPP_ACCEPTANCE_RESOURCE_DIR"), - ); - let game = tempfile::tempdir().unwrap(); - let app = game.path().join("TheBazaar.app"); - command( - "/bin/cp", - &[ - "-cR".as_ref(), - source.join("TheBazaar.app").as_os_str(), - app.as_os_str(), - ], - ); - std::fs::copy( - source.join("libdoorstop.dylib"), - game.path().join("libdoorstop.dylib"), - ) - .unwrap(); - std::fs::create_dir_all(game.path().join("BepInEx/plugins")).unwrap(); - std::fs::write( - game.path().join("BepInEx/plugins/BazaarPlusPlus.dll"), - b"developer-payload", - ) - .unwrap(); - std::fs::create_dir_all(game.path().join("BazaarPlusPlusV6")).unwrap(); - std::fs::write( - game.path().join("BazaarPlusPlusV6/history-sentinel"), - b"user-data", - ) - .unwrap(); - let stub = resources.join("Trampoline/bpp_launcher"); - for iteration in 1..=3 { - imp::install_with_stub(game.path(), &stub).unwrap(); - assert!(is_current_with_stub(game.path(), &stub).unwrap()); - assert!(!app.join("TheBazaar_ARM64.app").exists()); - eprintln!("Copied Steam bundle repair {iteration}: strict signature and current stub verified"); - } - - // The game's own files differ between machines and game versions, so - // the committed golden holds only the Payload Inventory paths present - // after repair; the per-run manifest holds every file and its hash. - let manifest = crate::goldens::tree_manifest(game.path()); - crate::goldens::write_run_manifest("copied_steam_bundle_repair_acceptance", &manifest); - let inventory: serde_json::Value = serde_json::from_str( - &std::fs::read_to_string( - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../release/payload.json"), - ) - .unwrap(), - ) - .unwrap(); - let mut bpp_paths: Vec<&str> = inventory["files"] - .as_array() - .unwrap() - .iter() - .filter(|file| { - file["platforms"] - .as_array() - .is_none_or(|platforms| platforms.iter().any(|value| value == "macos")) - }) - .filter_map(|file| file["path"].as_str()) - .filter(|path| std::fs::symlink_metadata(game.path().join(path)).is_ok()) - .collect(); - bpp_paths.sort_unstable(); - let layout = imp::bundle_paths(game.path()).unwrap(); - let tree = serde_json::json!({ - "bpp_paths": bpp_paths, - "trampoline_uuid_matches_bundled": trampoline_builds_match(&layout.exe_path, &stub).unwrap(), - "codesign_verified": imp::verify_bundle(&app).is_ok(), - }); - crate::goldens::assert_golden( - "acceptance/repaired-tree.json", - &crate::goldens::json(&tree, &[]), - ); - // The CLI is the developer deployment entry. Its manifest must match the - // service outcome, and repeated repairs must preserve deployed DLLs/data. - let cli = std::env::var_os("BPP_TEST_INSTALLER_CLI").expect("BPP_TEST_INSTALLER_CLI"); - let evidence = tempfile::tempdir().unwrap(); - let manifest_path = evidence.path().join("repair.json"); - for _ in 0..2 { - let output = std::process::Command::new(&cli) - .args(["repair", "--game"]) - .arg(game.path()) - .arg("--stub") - .arg(&stub) - .arg("--manifest") - .arg(&manifest_path) - .output() - .unwrap(); - assert!( - output.status.success(), - "{}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - assert_eq!( - std::fs::read_to_string(&manifest_path).unwrap(), - crate::services::file_manifest::json(&crate::goldens::tree_manifest(game.path())) - .unwrap() - ); - assert!(is_current_with_stub(game.path(), &stub).unwrap()); - assert_eq!( - std::fs::read(game.path().join("BepInEx/plugins/BazaarPlusPlus.dll")).unwrap(), - b"developer-payload" - ); - assert_eq!( - std::fs::read(game.path().join("BazaarPlusPlusV6/history-sentinel")).unwrap(), - b"user-data" - ); - } - imp::uninstall_trampoline(game.path()).unwrap(); - finalize_game_bundle(game.path()).unwrap(); - imp::verify_bundle(&app).unwrap(); - eprintln!("Copied Steam bundle uninstall: strict signature verified"); - } - - fn write_macho_stub(path: &Path, uuid: [u8; 16], signature: &[u8]) { - const MACH_HEADER_64_SIZE: usize = 32; - const LC_UUID: u32 = 0x1b; - const LC_UUID_SIZE: u32 = 24; - - let mut bytes = vec![0; MACH_HEADER_64_SIZE]; - bytes[0..4].copy_from_slice(&0xfeedfacfu32.to_le_bytes()); - bytes[16..20].copy_from_slice(&1u32.to_le_bytes()); - bytes[20..24].copy_from_slice(&LC_UUID_SIZE.to_le_bytes()); - bytes.extend_from_slice(&LC_UUID.to_le_bytes()); - bytes.extend_from_slice(&LC_UUID_SIZE.to_le_bytes()); - bytes.extend_from_slice(&uuid); - bytes.extend_from_slice(signature); - std::fs::write(path, bytes).unwrap(); - } - - #[test] - fn trampoline_build_identity_ignores_signatures_but_rejects_different_builds() { - let tmp = tempfile::tempdir().unwrap(); - let bundled = tmp.path().join("bundled"); - let installed = tmp.path().join("installed"); - let outdated = tmp.path().join("outdated"); - - write_macho_stub(&bundled, [7; 16], b"developer-id-signature"); - write_macho_stub(&installed, [7; 16], b"adhoc-bundle-signature"); - write_macho_stub(&outdated, [8; 16], b"adhoc-bundle-signature"); - - assert!(trampoline_builds_match(&installed, &bundled).unwrap()); - assert!(!trampoline_builds_match(&outdated, &bundled).unwrap()); - } - - /// A thin arm64/x86_64 Mach-O image whose only load command is an optional dylib. - fn macho_image(cpu_type: u32, dylib: Option<&str>) -> Vec { - const LC_LOAD_DYLIB: u32 = 0xc; - const DYLIB_NAME_OFFSET: u32 = 24; - - let mut command = Vec::new(); - if let Some(name) = dylib { - let mut name = name.as_bytes().to_vec(); - name.push(0); - name.resize(name.len().next_multiple_of(8), 0); - command.extend_from_slice(&LC_LOAD_DYLIB.to_le_bytes()); - command.extend_from_slice(&(DYLIB_NAME_OFFSET + name.len() as u32).to_le_bytes()); - command.extend_from_slice(&DYLIB_NAME_OFFSET.to_le_bytes()); - command.extend_from_slice(&[0; 12]); - command.extend_from_slice(&name); - } - let mut bytes = vec![0; 32]; - bytes[0..4].copy_from_slice(&0xfeedfacfu32.to_le_bytes()); - bytes[4..8].copy_from_slice(&cpu_type.to_le_bytes()); - bytes[16..20].copy_from_slice(&u32::from(dylib.is_some()).to_le_bytes()); - bytes[20..24].copy_from_slice(&(command.len() as u32).to_le_bytes()); - bytes.extend_from_slice(&command); - bytes - } - - /// A universal binary wrapping `slices`, with 32-bit or 64-bit fat arch entries. - fn universal(slices: &[Vec], wide: bool) -> Vec { - let entry_size = if wide { 32 } else { 20 }; - let magic: u32 = if wide { 0xcafebabf } else { 0xcafebabe }; - let mut header = magic.to_be_bytes().to_vec(); - header.extend_from_slice(&(slices.len() as u32).to_be_bytes()); - let mut offset = (8 + slices.len() * entry_size).next_multiple_of(16); - let mut body = Vec::new(); - for slice in slices { - header.extend_from_slice(&slice[4..8].iter().rev().copied().collect::>()); - header.extend_from_slice(&[0; 4]); - if wide { - header.extend_from_slice(&(offset as u64).to_be_bytes()); - header.extend_from_slice(&(slice.len() as u64).to_be_bytes()); - header.extend_from_slice(&[0; 8]); - } else { - header.extend_from_slice(&(offset as u32).to_be_bytes()); - header.extend_from_slice(&(slice.len() as u32).to_be_bytes()); - header.extend_from_slice(&[0; 4]); - } - body.push((offset, slice)); - offset = (offset + slice.len()).next_multiple_of(16); - } - let mut bytes = header; - for (start, slice) in body { - bytes.resize(start, 0); - bytes.extend_from_slice(slice); - } - bytes - } - - #[test] - fn unity_linkage_and_arm64_are_read_without_xcode_tools() { - const ARM64: u32 = 0x0100_000c; - const X86_64: u32 = 0x0100_0007; - const UNITY: &str = "@executable_path/../Frameworks/UnityPlayer.dylib"; - let tmp = tempfile::tempdir().unwrap(); - let probe = |name: &str, bytes: &[u8]| { - let path = tmp.path().join(name); - std::fs::write(&path, bytes).unwrap(); - ( - imp::links_unity(&path).unwrap(), - imp::has_arm64(&path).unwrap(), - ) - }; - - assert_eq!( - probe("thin-unity", &macho_image(ARM64, Some(UNITY))), - (true, true) - ); - assert_eq!( - probe( - "thin-stub", - &macho_image(ARM64, Some("/usr/lib/libSystem.B.dylib")) - ), - (false, true) - ); - assert_eq!( - probe("intel-unity", &macho_image(X86_64, Some(UNITY))), - (true, false) - ); - // The Steam build ships as a universal x86_64 + arm64 binary. - for wide in [false, true] { - let slices = [ - macho_image(X86_64, Some(UNITY)), - macho_image(ARM64, Some(UNITY)), - ]; - assert_eq!(probe("universal", &universal(&slices, wide)), (true, true)); - } - assert_eq!(probe("not-macho", b"STUB"), (false, false)); - assert!(!imp::links_unity(&tmp.path().join("missing")).unwrap()); - } - - /// Build a minimal `TheBazaar.app` fixture with a fake main executable. - fn make_bundle(real_contents: &[u8]) -> tempfile::TempDir { - let tmp = tempfile::tempdir().unwrap(); - let macos_dir = tmp.path().join("TheBazaar.app/Contents/MacOS"); - std::fs::create_dir_all(&macos_dir).unwrap(); - std::fs::write( - tmp.path().join("TheBazaar.app/Contents/Info.plist"), - r#" - - - - CFBundleExecutableThe Bazaar - - -"#, - ) - .unwrap(); - std::fs::write(macos_dir.join("The Bazaar"), real_contents).unwrap(); - tmp - } - - #[test] - fn test_bundle_paths_reads_cf_bundle_executable() { - let tmp = make_bundle(b"real"); - let layout = bundle_paths(tmp.path()).unwrap(); - assert!(layout.exe_path.ends_with("Contents/MacOS/The Bazaar")); - assert!(layout.orig_path.ends_with("Contents/MacOS/The Bazaar.orig")); - } - - #[test] - fn test_is_trampolined_is_false_for_vanilla_bundle() { - let tmp = make_bundle(b"real"); - // No `.orig` -> not trampolined; short-circuits before inspecting the executable. - assert!(!is_trampolined(tmp.path()).unwrap()); - } - - #[test] - fn test_classify_real_binary_prefers_live_exe_over_stale_orig() { - // Fresh install: exe is real, no backup. - assert_eq!( - classify_real_binary(true, false, false).unwrap(), - RealBinarySource::CurrentExe - ); - // Steam-updated binary at on top of a STALE real .orig — keep . - assert_eq!( - classify_real_binary(true, true, true).unwrap(), - RealBinarySource::CurrentExe - ); - // Interrupted prior run: exe is the stub, .orig is the preserved real binary. - assert_eq!( - classify_real_binary(false, true, true).unwrap(), - RealBinarySource::ExistingOrig - ); - // Corrupt: neither side is the real binary. - assert!(classify_real_binary(false, true, false).is_err()); - assert!(classify_real_binary(false, false, false).is_err()); - } - - #[test] - fn test_swap_in_stub_preserves_real_binary_and_is_idempotent() { - let tmp = make_bundle(b"REAL-UNITY"); - let layout = bundle_paths(tmp.path()).unwrap(); - let stub = tmp.path().join("stub"); - std::fs::write(&stub, b"STUB").unwrap(); - - swap_in_stub(&layout, &stub).unwrap(); - assert_eq!(std::fs::read(&layout.exe_path).unwrap(), b"STUB"); - assert_eq!(std::fs::read(&layout.orig_path).unwrap(), b"REAL-UNITY"); - - // Second call must NOT clobber the preserved real binary. - std::fs::write(&stub, b"STUB2").unwrap(); - swap_in_stub(&layout, &stub).unwrap(); - assert_eq!(std::fs::read(&layout.exe_path).unwrap(), b"STUB2"); - assert_eq!(std::fs::read(&layout.orig_path).unwrap(), b"REAL-UNITY"); - } - - #[test] - fn test_restore_vanilla_layout_moves_real_binary_back() { - let tmp = make_bundle(b"REAL-UNITY"); - let layout = bundle_paths(tmp.path()).unwrap(); - let stub = tmp.path().join("stub"); - std::fs::write(&stub, b"STUB").unwrap(); - - swap_in_stub(&layout, &stub).unwrap(); - restore_vanilla_layout(&layout).unwrap(); - - assert_eq!(std::fs::read(&layout.exe_path).unwrap(), b"REAL-UNITY"); - assert!(!layout.orig_path.exists()); - } - - #[test] - fn test_obsolete_macos_artifacts_are_detected_and_removed_without_parsing() { - let tmp = tempfile::tempdir().unwrap(); - for relative in OBSOLETE_MACOS_ARTIFACTS { - std::fs::write(tmp.path().join(relative), b"arbitrary old content").unwrap(); - } - - assert!(obsolete_macos_artifacts_present(tmp.path())); - remove_obsolete_macos_artifacts(tmp.path()).unwrap(); - assert!(!obsolete_macos_artifacts_present(tmp.path())); - remove_obsolete_macos_artifacts(tmp.path()).unwrap(); - } - - #[test] - fn test_trampoline_entitlements_are_complete() { - for key in [ - "com.apple.security.cs.allow-jit", - "com.apple.security.cs.allow-unsigned-executable-memory", - "com.apple.security.cs.disable-library-validation", - ] { - assert!( - TRAMPOLINE_ENTITLEMENTS.contains(key), - "trampoline entitlements missing {key}" - ); - } - assert_eq!( - TRAMPOLINE_ENTITLEMENTS - .matches("com.apple.security.cs.") - .count(), - 3 - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/bepinex/zip_archive.rs b/bazaarplusplus-installer/src-tauri/src/services/bepinex/zip_archive.rs deleted file mode 100644 index da1f3ed..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/bepinex/zip_archive.rs +++ /dev/null @@ -1,192 +0,0 @@ -use std::fs::File; -use std::io::{Cursor, Read}; -use std::path::Path; -use tauri::Manager; - -pub(super) fn bundled_zip_relative_path() -> &'static str { - "BepInExSource/BepInEx.zip" -} - -pub(crate) fn read_bundled_bpp_version(app: &tauri::AppHandle) -> Result, String> { - let resource_path = app - .path() - .resource_dir() - .map_err(|err| err.to_string())? - .join(bundled_zip_relative_path()); - let file = File::open(&resource_path) - .map_err(|err| format!("Cannot read bundled BepInEx.zip: {err}"))?; - let mut archive = zip::ZipArchive::new(file).map_err(|err| err.to_string())?; - - for index in 0..archive.len() { - let mut file = archive.by_index(index).map_err(|err| err.to_string())?; - let is_version_file = file - .name() - .map_err(|err| err.to_string())? - .ends_with("BazaarPlusPlus.version"); - if is_version_file { - let mut version = String::new(); - file.read_to_string(&mut version) - .map_err(|err| err.to_string())?; - let version = version.trim(); - return Ok((!version.is_empty()).then(|| version.to_string())); - } - } - - Ok(None) -} - -pub(super) struct ExtractReport { - pub(super) written: Vec, - pub(super) skipped_identical: Vec, -} - -pub(super) fn extract_zip(zip_bytes: &[u8], dest_dir: &Path) -> Result { - let reader = Cursor::new(zip_bytes); - let mut archive = zip::ZipArchive::new(reader).map_err(|err| err.to_string())?; - let mut report = ExtractReport { - written: Vec::new(), - skipped_identical: Vec::new(), - }; - - for index in 0..archive.len() { - let mut file = archive.by_index(index).map_err(|err| err.to_string())?; - let Some(relative_path) = file.enclosed_name().map(|path| path.to_path_buf()) else { - return Err(format!( - "Zip entry has unsafe path: {}", - String::from_utf8_lossy(file.name_raw()) - )); - }; - let output_path = dest_dir.join(relative_path); - - if file.is_dir() { - std::fs::create_dir_all(&output_path).map_err(|err| err.to_string())?; - continue; - } - - if let Some(parent) = output_path.parent() { - std::fs::create_dir_all(parent).map_err(|err| err.to_string())?; - } - - let mut contents = Vec::new(); - file.read_to_end(&mut contents) - .map_err(|err| err.to_string())?; - - if existing_file_is_identical(&output_path, &contents) { - report - .skipped_identical - .push(output_path.to_string_lossy().into_owned()); - continue; - } - - std::fs::write(&output_path, contents).map_err(|err| err.to_string())?; - report - .written - .push(output_path.to_string_lossy().into_owned()); - } - - Ok(report) -} - -pub(super) fn zip_entry_paths( - zip_bytes: &[u8], -) -> Result, String> { - let reader = Cursor::new(zip_bytes); - let archive = zip::ZipArchive::new(reader).map_err(|err| err.to_string())?; - archive - .file_names() - .filter_map(|name| match name { - Ok(name) if name.ends_with('/') => None, - Ok(name) => Some(Ok(name.replace('\\', "/"))), - Err(err) => Some(Err(err.to_string())), - }) - .collect() -} - -/// A shared dll another mod ships at the same version must not be rewritten -/// on every BPP install; the length gate keeps the multi-MB payload entries -/// from being read unless they could actually match. -fn existing_file_is_identical(path: &Path, contents: &[u8]) -> bool { - match std::fs::metadata(path) { - Ok(metadata) if metadata.is_file() && metadata.len() == contents.len() as u64 => { - std::fs::read(path) - .map(|existing| existing == contents) - .unwrap_or(false) - } - _ => false, - } -} - -#[cfg(test)] -mod tests { - use super::{bundled_zip_relative_path, extract_zip, zip_entry_paths}; - use std::io::{Cursor, Write}; - - fn make_test_zip() -> Vec { - let buffer = Cursor::new(Vec::new()); - let mut zip = zip::ZipWriter::new(buffer); - let options = zip::write::SimpleFileOptions::default(); - - zip.add_directory("BepInEx/", options).unwrap(); - zip.start_file("BepInEx/core/BepInEx.Core.dll", options) - .unwrap(); - zip.write_all(b"fake dll content").unwrap(); - - zip.finish().unwrap().into_inner() - } - - #[test] - fn test_extract_zip_creates_files() { - let zip_bytes = make_test_zip(); - let tmp = tempfile::tempdir().unwrap(); - - let report = extract_zip(&zip_bytes, tmp.path()).unwrap(); - assert!(!report.written.is_empty()); - assert!(report.skipped_identical.is_empty()); - assert!(tmp.path().join("BepInEx/core/BepInEx.Core.dll").exists()); - } - - #[test] - fn test_extract_zip_skips_byte_identical_existing_files() { - let zip_bytes = make_test_zip(); - let tmp = tempfile::tempdir().unwrap(); - let target = tmp.path().join("BepInEx/core/BepInEx.Core.dll"); - std::fs::create_dir_all(target.parent().unwrap()).unwrap(); - std::fs::write(&target, b"fake dll content").unwrap(); - - let report = extract_zip(&zip_bytes, tmp.path()).unwrap(); - - assert!(report.written.is_empty()); - assert_eq!(report.skipped_identical.len(), 1); - assert_eq!(std::fs::read(&target).unwrap(), b"fake dll content"); - } - - #[test] - fn test_extract_zip_overwrites_differing_existing_files() { - let zip_bytes = make_test_zip(); - let tmp = tempfile::tempdir().unwrap(); - let target = tmp.path().join("BepInEx/core/BepInEx.Core.dll"); - std::fs::create_dir_all(target.parent().unwrap()).unwrap(); - std::fs::write(&target, b"other mod's different version").unwrap(); - - let report = extract_zip(&zip_bytes, tmp.path()).unwrap(); - - assert_eq!(report.written.len(), 1); - assert!(report.skipped_identical.is_empty()); - assert_eq!(std::fs::read(&target).unwrap(), b"fake dll content"); - } - - #[test] - fn test_zip_entry_paths_lists_files_not_directories() { - let zip_bytes = make_test_zip(); - - let paths = zip_entry_paths(&zip_bytes).unwrap(); - - assert!(paths.contains("BepInEx/core/BepInEx.Core.dll")); - assert!(!paths.iter().any(|path| path.ends_with('/'))); - } - - #[test] - fn test_bundled_zip_relative_path_matches_supported_targets() { - assert_eq!(bundled_zip_relative_path(), "BepInExSource/BepInEx.zip"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/data_maintenance.rs b/bazaarplusplus-installer/src-tauri/src/services/data_maintenance.rs deleted file mode 100644 index 0bb5c8c..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/data_maintenance.rs +++ /dev/null @@ -1,163 +0,0 @@ -use std::sync::Arc; - -use tokio::sync::Mutex as AsyncMutex; - -use crate::stream::runtime::StreamRuntime; - -/// The installer's process-wide data maintenance lock. Every operation that -/// deletes or rewrites user data under a game directory (History cleanup, -/// Reset, BepInEx reset, Legacy Root deletion) runs while holding it, so two of -/// them never interleave. -/// -/// Lock order: this lock first, then the stream lifecycle gate inside -/// [`StreamRuntime::exclusive_maintenance`]. Nothing that holds the lifecycle -/// gate waits for this lock, so a long cleanup never stalls overlay start and -/// stop, and the two cannot deadlock. -#[derive(Clone, Default)] -pub(crate) struct DataMaintenanceLock { - gate: Arc>, -} - -impl DataMaintenanceLock { - /// Runs `task` on the blocking pool while holding the lock. The guard moves - /// into the task, so the lock outlives a dropped caller until the - /// filesystem work actually finishes. - pub(crate) async fn run_blocking(&self, task: F) -> Result - where - T: Send + 'static, - F: FnOnce() -> T + Send + 'static, - { - let guard = self.gate.clone().lock_owned().await; - run_on_blocking_pool(guard, task).await - } - - /// Like [`Self::run_blocking`], and also stops the OBS overlay for the - /// duration, for work that deletes the database the overlay reads. - pub(crate) async fn run_blocking_with_overlay_stopped( - &self, - stream_runtime: &StreamRuntime, - task: F, - ) -> Result - where - T: Send + 'static, - F: FnOnce() -> T + Send + 'static, - { - let guard = self.gate.clone().lock_owned().await; - stream_runtime - .exclusive_maintenance(|| run_on_blocking_pool(guard, task)) - .await - } -} - -async fn run_on_blocking_pool( - guard: tokio::sync::OwnedMutexGuard<()>, - task: F, -) -> Result -where - T: Send + 'static, - F: FnOnce() -> T + Send + 'static, -{ - tauri::async_runtime::spawn_blocking(move || { - let _guard = guard; - task() - }) - .await - .map_err(|err| format!("data maintenance task failed: {err}")) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::services::history::{ - execute_storage_cleanup_with, StorageCleanupPreset, StorageCleanupScope, - }; - use std::path::Path; - use std::sync::mpsc; - use std::time::Duration; - - fn game_dir_with_data() -> tempfile::TempDir { - let tmp = tempfile::tempdir().unwrap(); - #[cfg(target_os = "macos")] - std::fs::create_dir_all(tmp.path().join("TheBazaar.app")).unwrap(); - #[cfg(target_os = "windows")] - std::fs::write(tmp.path().join("TheBazaar.exe"), b"exe").unwrap(); - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - std::fs::write(tmp.path().join("TheBazaar"), b"exe").unwrap(); - let data_dir = crate::services::paths::bpp_data_dir(tmp.path()); - std::fs::create_dir_all(&data_dir).unwrap(); - std::fs::write(crate::services::paths::database_path(tmp.path()), b"db").unwrap(); - tmp - } - - #[tokio::test] - async fn cleanup_started_during_reset_waits_until_the_reset_finishes() { - let lock = DataMaintenanceLock::default(); - let stream_runtime = StreamRuntime::default(); - let game = game_dir_with_data(); - let game_path = game.path().to_path_buf(); - let data_dir = crate::services::paths::bpp_data_dir(&game_path); - - // The reset's process probe parks inside the locked section until - // released, holding the reset mid-operation. - let (probe_entered_tx, probe_entered) = mpsc::channel::<()>(); - let (release_probe, probe_release) = mpsc::channel::<()>(); - let probe_release = std::sync::Mutex::new(probe_release); - let probe = move |_: &Path| { - probe_entered_tx.send(()).unwrap(); - probe_release.lock().unwrap().recv().unwrap(); - Ok(false) - }; - let reset = tokio::spawn({ - let lock = lock.clone(); - let stream_runtime = stream_runtime.clone(); - let game_path = game_path.to_string_lossy().into_owned(); - async move { - crate::services::bepinex::reset_bpp_data_with( - &lock, - &stream_runtime, - game_path, - probe, - ) - .await - } - }); - tokio::task::spawn_blocking(move || probe_entered.recv_timeout(Duration::from_secs(10))) - .await - .unwrap() - .expect("reset reached its game check"); - - // Cleanup resolves its installation only once it holds the lock, so the - // data directory it observes tells whether the reset already finished. - let (resolved_tx, resolved) = mpsc::channel::(); - let cleanup = tokio::spawn({ - let lock = lock.clone(); - let game_path = game_path.clone(); - let data_dir = data_dir.clone(); - async move { - execute_storage_cleanup_with( - &lock, - move || { - resolved_tx.send(data_dir.exists()).unwrap(); - Some(game_path) - }, - StorageCleanupScope::RunData, - StorageCleanupPreset::All, - ) - .await - } - }); - for _ in 0..16 { - tokio::task::yield_now().await; - } - tokio::time::sleep(Duration::from_millis(50)).await; - assert!(!cleanup.is_finished()); - assert!(resolved.try_recv().is_err(), "cleanup entered during reset"); - - release_probe.send(()).unwrap(); - assert_eq!(reset.await.unwrap(), Ok(true)); - // The cleanup ran after the reset removed the data, so it finds no - // history; what matters is that it observed the finished reset. - let _ = cleanup.await.unwrap(); - assert_eq!(resolved.try_recv(), Ok(false)); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/detect/game.rs b/bazaarplusplus-installer/src-tauri/src/services/detect/game.rs deleted file mode 100644 index 34bb5c4..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/detect/game.rs +++ /dev/null @@ -1,92 +0,0 @@ -use std::path::Path; - -pub(crate) fn is_bepinex_installed(game_path: &Path) -> bool { - if !game_path - .join("BepInEx/core/BepInEx.Preloader.dll") - .exists() - { - return false; - } - - #[cfg(target_os = "macos")] - return game_path.join("libdoorstop.dylib").exists(); - - #[cfg(target_os = "windows")] - return game_path.join("doorstop_config.ini").exists() - && game_path.join("winhttp.dll").exists(); - - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - return true; -} - -pub(super) fn read_installed_bpp_version(game_path: &Path) -> Option { - let version_path = game_path.join("BepInEx/plugins/BazaarPlusPlus.version"); - let version = std::fs::read_to_string(version_path).ok()?; - let version = version.trim(); - (!version.is_empty()).then(|| version.to_string()) -} - -pub(crate) fn is_valid_game_path(base: &Path) -> bool { - #[cfg(target_os = "macos")] - return base.join("TheBazaar.app").exists(); - - #[cfg(target_os = "windows")] - return base.join("TheBazaar.exe").exists(); - - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - return base.join("TheBazaar").exists(); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_read_installed_bpp_version_trims_contents() { - let temp_root = std::env::temp_dir().join(format!( - "bppinstaller-version-test-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system time before epoch") - .as_nanos() - )); - let plugins_dir = temp_root.join("BepInEx/plugins"); - std::fs::create_dir_all(&plugins_dir).expect("create plugins dir"); - std::fs::write( - plugins_dir.join("BazaarPlusPlus.version"), - "1.2.3+2026-03-10 12:34:56\n", - ) - .expect("write version file"); - - let version = read_installed_bpp_version(&temp_root); - - std::fs::remove_dir_all(&temp_root).expect("cleanup temp dir"); - - assert_eq!(version.as_deref(), Some("1.2.3+2026-03-10 12:34:56")); - } - - #[test] - fn test_is_bepinex_installed_detects_core_payload_without_version_file() { - let tmp = tempfile::tempdir().unwrap(); - std::fs::create_dir_all(tmp.path().join("BepInEx/core")).unwrap(); - std::fs::write( - tmp.path().join("BepInEx/core/BepInEx.Preloader.dll"), - b"dll", - ) - .unwrap(); - - #[cfg(target_os = "macos")] - { - std::fs::write(tmp.path().join("libdoorstop.dylib"), b"dylib").unwrap(); - } - - #[cfg(target_os = "windows")] - { - std::fs::write(tmp.path().join("doorstop_config.ini"), b"cfg").unwrap(); - std::fs::write(tmp.path().join("winhttp.dll"), b"dll").unwrap(); - } - - assert!(is_bepinex_installed(tmp.path())); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/detect/mod.rs b/bazaarplusplus-installer/src-tauri/src/services/detect/mod.rs deleted file mode 100644 index 34463a7..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/detect/mod.rs +++ /dev/null @@ -1,96 +0,0 @@ -mod game; -mod steam; - -pub(crate) use game::{is_bepinex_installed, is_valid_game_path}; -pub(crate) use steam::detect_installation_paths; - -use crate::services::game_path::GamePathAcceptance; -use crate::services::selected_game_installation::SelectedGameInstallationState; -use crate::services::startup::InstallerContextState; -use crate::services::vdf::SteamLaunchOptionsState; -use game::read_installed_bpp_version; -use tauri::{AppHandle, Manager, State}; - -#[derive(Debug, Clone)] -pub(crate) struct InstallEnvironmentSnapshot { - pub steam_path: Option, - pub game_path: Option, - pub game_path_valid: bool, - pub bepinex_installed: bool, - pub bpp_version: Option, - pub bundled_bpp_version: Option, - pub steam_launch_options: SteamLaunchOptionsState, - pub trampoline_current: bool, - pub obsolete_macos_artifacts_present: bool, -} - -pub fn detect_for_install( - app: AppHandle, - state: State<'_, InstallerContextState>, - game_path: Option, -) -> Result { - crate::services::debug_log!( - "[detect_for_install] start requested_game_path={:?}", - game_path - ); - // Read cached startup context. On first call this lazily initializes: - // reads the bundled payload and resolves Steam/game paths. - let startup = state.get_or_initialize(&app); - - let steam_path = startup.steam_path.clone(); - let game_path = app - .state::() - .resolve(&app, game_path, GamePathAcceptance::DetectionPick) - .map(|resolution| resolution.game_path); - let game_path_valid = game_path - .as_ref() - .map(|path| is_valid_game_path(path)) - .unwrap_or(false); - let bpp_version = game_path - .as_ref() - .and_then(|path| read_installed_bpp_version(path)); - let bepinex_installed = game_path - .as_ref() - .map(|path| is_bepinex_installed(path)) - .unwrap_or(false); - - // macOS bootstrap facts are recomputed on every detection so Steam Verify, - // game updates, launch-option edits, and obsolete files immediately route - // the UI to Repair. Other platforms have no Steam launch-option invariant. - let trampoline_current = game_path - .as_ref() - .map(|path| crate::services::bepinex::is_current_trampoline(&app, path).unwrap_or(false)) - .unwrap_or(false); - let obsolete_macos_artifacts_present = game_path - .as_ref() - .map(|path| crate::services::bepinex::obsolete_macos_artifacts_present(path)) - .unwrap_or(false); - let steam_launch_options = if cfg!(target_os = "macos") { - steam_path - .as_deref() - .map(crate::services::vdf::inspect_launch_options_for_steam) - .unwrap_or(SteamLaunchOptionsState::Unavailable) - } else { - SteamLaunchOptionsState::Empty - }; - - crate::services::debug_log!( - "[detect_for_install] resolved steam_path={:?} game_path={:?} bepinex_installed={} bundled_bpp_version={:?}", - steam_path.as_ref().map(|path| path.display().to_string()), - game_path.as_ref().map(|path| path.display().to_string()), - bepinex_installed, - startup.bundled_bpp_version - ); - - Ok(InstallEnvironmentSnapshot { - steam_path: steam_path.map(|path| path.to_string_lossy().into_owned()), - game_path: game_path.map(|path| path.to_string_lossy().into_owned()), - game_path_valid, - bepinex_installed, - bpp_version, - bundled_bpp_version: startup.bundled_bpp_version.clone(), - steam_launch_options, - trampoline_current, - obsolete_macos_artifacts_present, - }) -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/detect/steam.rs b/bazaarplusplus-installer/src-tauri/src/services/detect/steam.rs deleted file mode 100644 index 5fb7174..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/detect/steam.rs +++ /dev/null @@ -1,423 +0,0 @@ -use crate::services::vdf::THE_BAZAAR_APP_ID; -use keyvalues_parser::{Obj, Parser, Value}; -use std::path::{Path, PathBuf}; - -#[derive(Debug, Clone)] -pub(crate) struct SteamInstallPaths { - pub(crate) steam_path: Option, - pub(crate) game_path: Option, -} - -#[cfg(debug_assertions)] -fn debug_paths_label(paths: &[PathBuf]) -> Vec { - paths - .iter() - .map(|path| path.display().to_string()) - .collect() -} - -fn first_obj<'a, 'text>(values: &'a [Value<'text>]) -> Option<&'a Obj<'text>> -where - 'a: 'text, -{ - values.first()?.get_obj() -} - -fn first_str<'a, 'text>(values: &'a [Value<'text>]) -> Option<&'a str> -where - 'a: 'text, -{ - values.first()?.get_str() -} - -fn library_has_app(folder: &Obj<'_>, app_id: &str) -> bool { - folder - .get("apps") - .and_then(|values| first_obj(values)) - .map(|apps| apps.contains_key(app_id)) - .unwrap_or(false) -} - -fn parse_library_folders(vdf_content: &str, app_id: &str) -> Option> { - let parsed = Parser::new() - .literal_special_chars(true) - .parse(vdf_content) - .ok()?; - let libraries = parsed.value.get_obj()?; - let mut folders = Vec::new(); - - for values in libraries.values() { - let Some(folder) = first_obj(values) else { - continue; - }; - let Some(library_path) = folder.get("path").and_then(|values| first_str(values)) else { - continue; - }; - - folders.push((library_path.to_string(), library_has_app(folder, app_id))); - } - - (!folders.is_empty()).then_some(folders) -} - -fn candidate_steam_paths() -> Vec { - let mut candidates = Vec::new(); - - #[cfg(target_os = "macos")] - { - if let Some(path) = - dirs::home_dir().map(|home| home.join("Library/Application Support/Steam")) - { - if path.exists() { - candidates.push(path); - } - } - } - - #[cfg(target_os = "windows")] - { - use std::collections::HashSet; - use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE}; - use winreg::RegKey; - - let mut seen = HashSet::new(); - let registry_candidates = [ - (HKEY_CURRENT_USER, r"Software\Valve\Steam", "SteamPath"), - (HKEY_CURRENT_USER, r"Software\Valve\Steam", "InstallPath"), - (HKEY_LOCAL_MACHINE, r"Software\Valve\Steam", "InstallPath"), - (HKEY_LOCAL_MACHINE, r"Software\Valve\Steam", "SteamPath"), - ( - HKEY_LOCAL_MACHINE, - r"Software\WOW6432Node\Valve\Steam", - "InstallPath", - ), - ( - HKEY_LOCAL_MACHINE, - r"Software\WOW6432Node\Valve\Steam", - "SteamPath", - ), - ]; - - for (root, key_path, value_name) in registry_candidates { - let root_key = RegKey::predef(root); - if let Ok(key) = root_key.open_subkey(key_path) { - if let Ok(path) = key.get_value::(value_name) { - let path = PathBuf::from(path.trim()); - if path.exists() && seen.insert(path.clone()) { - candidates.push(path); - } - } - } - } - - let default_candidates = [ - std::env::var_os("ProgramFiles(x86)") - .map(PathBuf::from) - .map(|path| path.join("Steam")), - std::env::var_os("ProgramFiles") - .map(PathBuf::from) - .map(|path| path.join("Steam")), - Some(PathBuf::from(r"C:\Program Files (x86)\Steam")), - Some(PathBuf::from(r"C:\Program Files\Steam")), - ]; - - for candidate in default_candidates.into_iter().flatten() { - if candidate.exists() && seen.insert(candidate.clone()) { - candidates.push(candidate); - } - } - } - - crate::services::debug_log!( - "[detect::steam] steam root candidates={:?}", - debug_paths_label(&candidates) - ); - - candidates -} - -fn get_game_path_from_single_steam_root(steam_path: &Path) -> Option { - crate::services::debug_log!( - "[detect::steam] probing steam root={}", - steam_path.display() - ); - - if let Some(path) = get_game_path_from_vdf(steam_path) { - crate::services::debug_log!( - "[detect::steam] hit from libraryfolders.vdf root={} game_path={}", - steam_path.display(), - path.display() - ); - return Some(path); - } - - let candidate = steam_path.join("steamapps/common/The Bazaar"); - if candidate.exists() { - crate::services::debug_log!( - "[detect::steam] hit from default steam library root={} game_path={}", - steam_path.display(), - candidate.display() - ); - return Some(candidate); - } - - crate::services::debug_log!( - "[detect::steam] miss for steam root={}", - steam_path.display() - ); - None -} - -fn get_game_path_from_detected_steam_roots( - primary_steam_root: &Path, - candidate_roots: &[PathBuf], -) -> Option { - let mut steam_roots = vec![primary_steam_root.to_path_buf()]; - for candidate in candidate_roots { - if !steam_roots.contains(candidate) { - steam_roots.push(candidate.clone()); - } - } - - crate::services::debug_log!( - "[detect::steam] ordered steam roots for game lookup={:?}", - debug_paths_label(&steam_roots) - ); - - if let Some(path) = steam_roots - .iter() - .find_map(|root| get_game_path_from_single_steam_root(root)) - { - return Some(path); - } - - #[cfg(target_os = "windows")] - { - if let Some(path) = crate::services::game_path::find_existing_fallback_game_path() { - crate::services::debug_log!( - "[detect::steam] hit from common Windows candidate game_path={}", - path.display() - ); - return Some(path); - } - } - - crate::services::debug_log!("[detect::steam] failed to resolve game path"); - None -} - -pub(crate) fn detect_installation_paths() -> SteamInstallPaths { - let steam_roots = candidate_steam_paths(); - let steam_path = steam_roots.first().cloned(); - let game_path = steam_path - .as_deref() - .and_then(|path| get_game_path_from_detected_steam_roots(path, &steam_roots)); - crate::services::debug_log!( - "[detect::steam] detected startup paths steam_path={:?} game_path={:?}", - steam_path.as_ref().map(|path| path.display().to_string()), - game_path.as_ref().map(|path| path.display().to_string()) - ); - - SteamInstallPaths { - steam_path, - game_path, - } -} - -fn get_game_path_from_vdf(steam_path: &Path) -> Option { - let library_vdf_path = steam_path.join("steamapps/libraryfolders.vdf"); - let library_vdf = match std::fs::read_to_string(&library_vdf_path) { - Ok(content) => content, - Err(_error) => { - crate::services::debug_log!( - "[detect::steam] cannot read libraryfolders.vdf path={} error={}", - library_vdf_path.display(), - _error - ); - return None; - } - }; - - let parsed_folders = match parse_library_folders(&library_vdf, THE_BAZAAR_APP_ID) { - Some(folders) => folders, - None => { - crate::services::debug_log!( - "[detect::steam] failed to parse libraryfolders.vdf path={}", - library_vdf_path.display() - ); - return None; - } - }; - - crate::services::debug_log!( - "[detect::steam] parsed libraryfolders path={} folders={:?}", - library_vdf_path.display(), - parsed_folders - .iter() - .map(|(path, has_app)| format!("{path} [has_app={has_app}]")) - .collect::>() - ); - - // The library that declares the app wins; every other parsed library stays a - // fallback for installs Steam has not recorded under `apps`. - parsed_folders - .iter() - .filter(|(_, has_app)| *has_app) - .chain(parsed_folders.iter().filter(|(_, has_app)| !*has_app)) - .map(|(library_root, _)| PathBuf::from(library_root).join("steamapps/common/The Bazaar")) - .find(|candidate| candidate.exists()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_parse_library_folders_marks_the_library_declaring_the_app() { - let vdf = r#" -"libraryfolders" -{ - "0" - { - "path" "C:\Program Files (x86)\Steam" - "apps" - { - "730" "1" - } - } - "1" - { - "path" "D:\SteamLibrary" - "apps" - { - "1617400" "1" - } - } -}"#; - - let folders = parse_library_folders(vdf, THE_BAZAAR_APP_ID).expect("parsed folders"); - - assert_eq!( - folders, - vec![ - (r"C:\Program Files (x86)\Steam".to_string(), false), - (r"D:\SteamLibrary".to_string(), true) - ] - ); - } - - #[test] - fn test_parse_library_folders_reports_no_app_when_the_id_is_missing() { - let vdf = r#" -"libraryfolders" -{ - "0" - { - "path" "C:\Program Files (x86)\Steam" - "apps" - { - "730" "1" - } - } -}"#; - - let folders = parse_library_folders(vdf, THE_BAZAAR_APP_ID).expect("parsed folders"); - - assert!(folders.iter().all(|(_, has_app)| !has_app)); - } - - #[test] - fn test_parse_library_folders_keeps_paths_without_app_listing() { - let vdf = r#" -"libraryfolders" -{ - "0" - { - "path" "C:\Program Files (x86)\Steam" - } - "1" - { - "path" "D:\SteamLibrary" - "apps" - { - "1617400" "1" - } - } -}"#; - - let folders = parse_library_folders(vdf, THE_BAZAAR_APP_ID).expect("parsed folders"); - - assert_eq!( - folders, - vec![ - (r"C:\Program Files (x86)\Steam".to_string(), false), - (r"D:\SteamLibrary".to_string(), true) - ] - ); - } - - #[test] - fn test_get_game_path_from_vdf_falls_back_to_existing_library_folder() { - let tmp = tempfile::tempdir().unwrap(); - let steam_root = tmp.path().join("Steam"); - let library_root = tmp.path().join("Library"); - let steamapps_dir = steam_root.join("steamapps"); - let game_dir = library_root.join("steamapps/common/The Bazaar"); - - std::fs::create_dir_all(&steamapps_dir).unwrap(); - std::fs::create_dir_all(&game_dir).unwrap(); - - let library_root_string = library_root.to_string_lossy().replace('\\', "\\\\"); - let vdf = format!( - "\"libraryfolders\"\n{{\n \"0\"\n {{\n \"path\" \"{library_root_string}\"\n }}\n}}" - ); - std::fs::write(steamapps_dir.join("libraryfolders.vdf"), vdf).unwrap(); - - let path = get_game_path_from_vdf(&steam_root); - - assert_eq!(path, Some(game_dir)); - } - - #[test] - fn test_get_game_path_from_vdf_prefers_the_library_declaring_the_app() { - let tmp = tempfile::tempdir().unwrap(); - let steam_root = tmp.path().join("Steam"); - let listed_first = tmp.path().join("ListedFirst"); - let declaring = tmp.path().join("Declaring"); - let steamapps_dir = steam_root.join("steamapps"); - let declared_game_dir = declaring.join("steamapps/common/The Bazaar"); - - std::fs::create_dir_all(&steamapps_dir).unwrap(); - std::fs::create_dir_all(listed_first.join("steamapps/common/The Bazaar")).unwrap(); - std::fs::create_dir_all(&declared_game_dir).unwrap(); - - let listed_first_string = listed_first.to_string_lossy().replace('\\', "\\\\"); - let declaring_string = declaring.to_string_lossy().replace('\\', "\\\\"); - let vdf = format!( - "\"libraryfolders\"\n{{\n \"0\"\n {{\n \"path\" \"{listed_first_string}\"\n }}\n \"1\"\n {{\n \"path\" \"{declaring_string}\"\n \"apps\"\n {{\n \"{THE_BAZAAR_APP_ID}\" \"1\"\n }}\n }}\n}}" - ); - std::fs::write(steamapps_dir.join("libraryfolders.vdf"), vdf).unwrap(); - - let path = get_game_path_from_vdf(&steam_root); - - assert_eq!(path, Some(declared_game_dir)); - } - - #[test] - fn test_detected_steam_roots_try_the_secondary_root() { - let tmp = tempfile::tempdir().unwrap(); - let primary_root = tmp.path().join("PrimarySteam"); - let secondary_root = tmp.path().join("SecondarySteam"); - let game_dir = secondary_root.join("steamapps/common/The Bazaar"); - - std::fs::create_dir_all(primary_root.join("steamapps")).unwrap(); - std::fs::create_dir_all(&game_dir).unwrap(); - - let path = get_game_path_from_detected_steam_roots( - &primary_root, - &[primary_root.clone(), secondary_root], - ); - - assert_eq!(path, Some(game_dir)); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/file_manifest.rs b/bazaarplusplus-installer/src-tauri/src/services/file_manifest.rs deleted file mode 100644 index 3081d74..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/file_manifest.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Deterministic filesystem evidence shared by headless repair and acceptance. - -use std::io::Read; -use std::path::Path; - -use sha2::{Digest, Sha256}; - -pub(crate) fn tree_manifest(root: &Path) -> Result, String> { - fn walk( - root: &Path, - directory: &Path, - entries: &mut Vec<(String, String)>, - ) -> std::io::Result<()> { - for entry in std::fs::read_dir(directory)? { - let path = entry?.path(); - let relative = path - .strip_prefix(root) - .expect("walk stays under root") - .to_string_lossy() - .replace('\\', "/"); - let kind = std::fs::symlink_metadata(&path)?.file_type(); - if kind.is_symlink() { - entries.push(( - relative, - format!("symlink:{}", std::fs::read_link(&path)?.display()), - )); - } else if kind.is_dir() { - walk(root, &path, entries)?; - } else if kind.is_file() { - let mut file = std::fs::File::open(&path)?; - let mut digest = Sha256::new(); - let mut buffer = [0; 64 * 1024]; - loop { - let count = file.read(&mut buffer)?; - if count == 0 { - break; - } - digest.update(&buffer[..count]); - } - let hash = digest - .finalize() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(); - entries.push((relative, hash)); - } else { - return Err(std::io::Error::other(format!( - "Unsupported file: {}", - path.display() - ))); - } - } - Ok(()) - } - let mut entries = Vec::new(); - walk(root, root, &mut entries) - .map_err(|error| format!("Cannot inspect {}: {error}", root.display()))?; - entries.sort(); - Ok(entries) -} - -pub(crate) fn json(entries: &[(String, String)]) -> Result { - let entries: Vec<_> = entries - .iter() - .map(|(path, sha256)| serde_json::json!({"path": path, "sha256": sha256})) - .collect(); - serde_json::to_string_pretty(&entries) - .map(|text| text + "\n") - .map_err(|error| error.to_string()) -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/game_path.rs b/bazaarplusplus-installer/src-tauri/src/services/game_path.rs deleted file mode 100644 index ba12fd2..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/game_path.rs +++ /dev/null @@ -1,563 +0,0 @@ -#[cfg(target_os = "windows")] -use crate::config::STEAM_LIBRARY_FALLBACK_CANDIDATES; -use crate::services::paths; -use std::path::{Path, PathBuf}; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum GamePathSource { - Explicit, - Selected, - Startup, - Fallback, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct GamePathResolution { - pub game_path: PathBuf, - /// Present iff probed present at resolution time. Always `None` under - /// `DetectionPick`, where the database is never probed. - pub database_path: Option, - pub source: GamePathSource, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum GamePathAcceptance { - /// Return the first detection pick without gating it or walking the - /// session/database fallback tail. - DetectionPick, - /// Accept any picked directory and attach its database path iff present. - Any, - /// Accept only a directory whose BazaarPlusPlus database exists. - DatabaseExists, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum GamePathProbe { - GameInstalled, - DatabaseFile, -} - -pub(crate) struct GamePathInputs { - pub(crate) requested: Option, - pub(crate) selected: Option, - pub(crate) startup: Option, -} - -pub(crate) fn resolve_game_path_core( - inputs: GamePathInputs, - acceptance: GamePathAcceptance, - candidates: impl Fn() -> Vec, - probe: impl Fn(GamePathProbe, &Path) -> bool, -) -> Option { - let mut memo: Option> = None; - - for (game_path, source) in [ - (inputs.requested, GamePathSource::Explicit), - (inputs.selected, GamePathSource::Selected), - (inputs.startup, GamePathSource::Startup), - ] { - let Some(game_path) = game_path else { - continue; - }; - match acceptance { - GamePathAcceptance::DetectionPick => { - return Some(GamePathResolution { - game_path, - database_path: None, - source, - }); - } - GamePathAcceptance::Any => { - return Some(with_probed_db(game_path, source, &probe)); - } - GamePathAcceptance::DatabaseExists => { - if probe(GamePathProbe::DatabaseFile, &game_path) { - return Some(GamePathResolution { - database_path: Some(paths::database_path(&game_path)), - game_path, - source, - }); - } - } - } - } - - if acceptance != GamePathAcceptance::DatabaseExists { - if let Some(game_path) = memo - .get_or_insert_with(&candidates) - .iter() - .find(|path| probe(GamePathProbe::GameInstalled, path)) - .cloned() - { - return Some(match acceptance { - GamePathAcceptance::DetectionPick => GamePathResolution { - game_path, - database_path: None, - source: GamePathSource::Fallback, - }, - GamePathAcceptance::Any => { - with_probed_db(game_path, GamePathSource::Fallback, &probe) - } - GamePathAcceptance::DatabaseExists => unreachable!(), - }); - } - } - - if acceptance == GamePathAcceptance::DetectionPick { - return None; - } - - memo.get_or_insert_with(&candidates) - .iter() - .find(|path| probe(GamePathProbe::DatabaseFile, path)) - .map(|path| GamePathResolution { - game_path: path.clone(), - database_path: Some(paths::database_path(path)), - source: GamePathSource::Fallback, - }) -} - -fn with_probed_db( - game_path: PathBuf, - source: GamePathSource, - probe: &impl Fn(GamePathProbe, &Path) -> bool, -) -> GamePathResolution { - let database_path = - probe(GamePathProbe::DatabaseFile, &game_path).then(|| paths::database_path(&game_path)); - GamePathResolution { - game_path, - database_path, - source, - } -} - -pub(crate) fn fs_probe(probe: GamePathProbe, path: &Path) -> bool { - match probe { - GamePathProbe::GameInstalled => crate::services::detect::is_valid_game_path(path), - GamePathProbe::DatabaseFile => paths::database_path(path).exists(), - } -} - -pub(crate) fn find_fallback_game_path_with_database() -> Option { - fallback_game_candidates() - .into_iter() - .find(|path| fs_probe(GamePathProbe::DatabaseFile, path)) -} - -#[cfg(target_os = "windows")] -pub(crate) fn find_existing_fallback_game_path() -> Option { - let candidates = fallback_game_candidates(); - crate::services::debug_log!( - "[detect::steam] probing common Windows candidates count={}", - candidates.len() - ); - candidates.into_iter().find(|path| path.exists()) -} - -pub(crate) fn fallback_game_candidates() -> Vec { - let mut candidates = Vec::new(); - - #[cfg(target_os = "macos")] - { - if let Some(path) = dirs::home_dir() - .map(|home| home.join("Library/Application Support/Steam/steamapps/common/The Bazaar")) - { - push_unique(&mut candidates, path); - } - } - - #[cfg(target_os = "windows")] - { - use windows::Win32::Storage::FileSystem::GetLogicalDrives; - - // Only probe drive letters that actually exist. The previous - // unconditional C..=Z scan issued ~48 `stat`s, and probing a - // disconnected/removable drive can stall for seconds on Windows. - let present = present_drive_letters(unsafe { GetLogicalDrives() }); - for drive in present.into_iter().filter(|letter| *letter >= 'C') { - for root in ["Steam", "SteamLibrary"] { - push_unique( - &mut candidates, - PathBuf::from(format!("{drive}:\\{root}\\steamapps\\common\\The Bazaar")), - ); - } - } - - for candidate in STEAM_LIBRARY_FALLBACK_CANDIDATES { - push_unique(&mut candidates, PathBuf::from(candidate)); - } - } - - candidates -} - -fn push_unique(paths: &mut Vec, path: PathBuf) { - if !paths.iter().any(|existing| existing == &path) { - paths.push(path); - } -} - -/// Parse the bitmask returned by `GetLogicalDrives` (bit 0 = `A:`, ..., -/// bit 25 = `Z:`) into the drive letters that currently exist. Kept pure so -/// the bit math is unit-testable without the Win32 call. -#[cfg_attr(not(any(target_os = "windows", test)), allow(dead_code))] -fn present_drive_letters(bitmask: u32) -> Vec { - ('A'..='Z') - .enumerate() - .filter(|(index, _)| bitmask & (1 << index) != 0) - .map(|(_, letter)| letter) - .collect() -} - -#[cfg(test)] -mod tests { - use super::present_drive_letters; - - #[test] - fn present_drive_letters_parses_c_and_d() { - // bit2 (C:) + bit3 (D:) - assert_eq!(present_drive_letters(0b1100), vec!['C', 'D']); - } - - #[test] - fn present_drive_letters_is_empty_when_no_bits_set() { - assert!(present_drive_letters(0).is_empty()); - } - - #[test] - fn present_drive_letters_parses_a_and_z_extremes() { - // bit0 (A:) + bit25 (Z:) guards the enumerate/shift bounds. - assert_eq!(present_drive_letters(0b1 | (1 << 25)), vec!['A', 'Z']); - } -} - -#[cfg(test)] -mod resolve_tests { - use super::*; - use std::cell::RefCell; - use std::collections::HashSet; - - fn p(value: &str) -> PathBuf { - PathBuf::from(value) - } - - struct Row { - name: &'static str, - requested: Option<&'static str>, - startup: Option<&'static str>, - selected: Option<&'static str>, - fallback: &'static [&'static str], - game_installed: &'static [&'static str], - has_db: &'static [&'static str], - acceptance: GamePathAcceptance, - expect: Option<(&'static str, GamePathSource, bool)>, - expect_probe_log: &'static [&'static str], - expect_candidate_calls: usize, - } - - fn run(row: &Row) { - let game: HashSet = row.game_installed.iter().map(|value| p(value)).collect(); - let db: HashSet = row.has_db.iter().map(|value| p(value)).collect(); - let log = RefCell::new(Vec::new()); - let candidate_calls = RefCell::new(0usize); - let candidates = || { - *candidate_calls.borrow_mut() += 1; - row.fallback.iter().map(|value| p(value)).collect() - }; - let probe = |kind: GamePathProbe, path: &Path| match kind { - GamePathProbe::GameInstalled => { - log.borrow_mut().push(format!("exe:{}", path.display())); - game.contains(path) - } - GamePathProbe::DatabaseFile => { - log.borrow_mut().push(format!("db:{}", path.display())); - db.contains(path) - } - }; - - let got = resolve_game_path_core( - GamePathInputs { - requested: row.requested.map(p), - startup: row.startup.map(p), - selected: row.selected.map(p), - }, - row.acceptance, - candidates, - probe, - ); - - match &row.expect { - None => assert!(got.is_none(), "{}", row.name), - Some((path, source, database_attached)) => { - let resolution = got.expect(row.name); - assert_eq!(resolution.game_path, p(path), "{}", row.name); - assert_eq!(&resolution.source, source, "{}", row.name); - assert_eq!( - resolution.database_path.is_some(), - *database_attached, - "{}: database attachment", - row.name - ); - } - } - assert_eq!( - *candidate_calls.borrow(), - row.expect_candidate_calls, - "{}: candidate list laziness", - row.name - ); - assert!( - *candidate_calls.borrow() <= 1, - "{}: candidates built more than once", - row.name - ); - assert_eq!( - *log.borrow(), - row.expect_probe_log - .iter() - .map(std::string::ToString::to_string) - .collect::>(), - "{}: probe order", - row.name - ); - } - - const ROWS: &[Row] = &[ - Row { - name: "requested is verbatim and unprobed", - requested: Some("/r"), - startup: Some("/s"), - selected: None, - fallback: &["/f"], - game_installed: &["/s", "/f"], - has_db: &[], - acceptance: GamePathAcceptance::DetectionPick, - expect: Some(("/r", GamePathSource::Explicit, false)), - expect_probe_log: &[], - expect_candidate_calls: 0, - }, - Row { - name: "startup beats fallback without probing", - requested: None, - startup: Some("/s"), - selected: None, - fallback: &["/f"], - game_installed: &["/f"], - has_db: &[], - acceptance: GamePathAcceptance::DetectionPick, - expect: Some(("/s", GamePathSource::Startup, false)), - expect_probe_log: &[], - expect_candidate_calls: 0, - }, - Row { - name: "detection fallback scan stops at second hit", - requested: None, - startup: None, - selected: None, - fallback: &["/f1", "/f2"], - game_installed: &["/f2"], - has_db: &[], - acceptance: GamePathAcceptance::DetectionPick, - expect: Some(("/f2", GamePathSource::Fallback, false)), - expect_probe_log: &["exe:/f1", "exe:/f2"], - expect_candidate_calls: 1, - }, - Row { - name: "detection fallback scan stops at first hit", - requested: None, - startup: None, - selected: None, - fallback: &["/f1", "/f2"], - game_installed: &["/f1", "/f2"], - has_db: &[], - acceptance: GamePathAcceptance::DetectionPick, - expect: Some(("/f1", GamePathSource::Fallback, false)), - expect_probe_log: &["exe:/f1"], - expect_candidate_calls: 1, - }, - Row { - name: "detection suppresses database-only tail", - requested: None, - startup: None, - selected: None, - fallback: &["/f1"], - game_installed: &[], - has_db: &["/f1"], - acceptance: GamePathAcceptance::DetectionPick, - expect: None, - expect_probe_log: &["exe:/f1"], - expect_candidate_calls: 1, - }, - Row { - name: "any accepts database-less detection pick", - requested: Some("/r"), - startup: None, - selected: None, - fallback: &[], - game_installed: &[], - has_db: &[], - acceptance: GamePathAcceptance::Any, - expect: Some(("/r", GamePathSource::Explicit, false)), - expect_probe_log: &["db:/r"], - expect_candidate_calls: 0, - }, - Row { - name: "any attaches database to detection pick", - requested: Some("/r"), - startup: None, - selected: None, - fallback: &[], - game_installed: &[], - has_db: &["/r"], - acceptance: GamePathAcceptance::Any, - expect: Some(("/r", GamePathSource::Explicit, true)), - expect_probe_log: &["db:/r"], - expect_candidate_calls: 0, - }, - Row { - name: "any session beats database fallback without gate", - requested: None, - startup: None, - selected: Some("/sess"), - fallback: &["/f1"], - game_installed: &[], - has_db: &["/f1"], - acceptance: GamePathAcceptance::Any, - expect: Some(("/sess", GamePathSource::Selected, false)), - expect_probe_log: &["db:/sess"], - expect_candidate_calls: 0, - }, - Row { - name: "any reuses candidates for database fallback tail", - requested: None, - startup: None, - selected: None, - fallback: &["/f1", "/f2"], - game_installed: &[], - has_db: &["/f2"], - acceptance: GamePathAcceptance::Any, - expect: Some(("/f2", GamePathSource::Fallback, true)), - expect_probe_log: &["exe:/f1", "exe:/f2", "db:/f1", "db:/f2"], - expect_candidate_calls: 1, - }, - Row { - name: "database gate accepts detection pick", - requested: Some("/r"), - startup: None, - selected: None, - fallback: &["/f"], - game_installed: &[], - has_db: &["/r"], - acceptance: GamePathAcceptance::DatabaseExists, - expect: Some(("/r", GamePathSource::Explicit, true)), - expect_probe_log: &["db:/r"], - expect_candidate_calls: 0, - }, - Row { - name: "database gate falls through explicit to startup", - requested: Some("/r"), - startup: Some("/s"), - selected: None, - fallback: &[], - game_installed: &[], - has_db: &["/s"], - acceptance: GamePathAcceptance::DatabaseExists, - expect: Some(("/s", GamePathSource::Startup, true)), - expect_probe_log: &["db:/r", "db:/s"], - expect_candidate_calls: 0, - }, - Row { - name: "startup wins without rebuilding fallback candidates", - requested: Some("/r"), - startup: Some("/s"), - selected: None, - fallback: &["/s"], - game_installed: &[], - has_db: &["/s"], - acceptance: GamePathAcceptance::DatabaseExists, - expect: Some(("/s", GamePathSource::Startup, true)), - expect_probe_log: &["db:/r", "db:/s"], - expect_candidate_calls: 0, - }, - Row { - name: "database gate permits session rescue", - requested: Some("/r"), - startup: None, - selected: Some("/sess"), - fallback: &["/f"], - game_installed: &[], - has_db: &["/sess"], - acceptance: GamePathAcceptance::DatabaseExists, - expect: Some(("/sess", GamePathSource::Selected, true)), - expect_probe_log: &["db:/r", "db:/sess"], - expect_candidate_calls: 0, - }, - Row { - name: "database tail preserves candidate order", - requested: Some("/r"), - startup: None, - selected: Some("/sess"), - fallback: &["/f1", "/f2"], - game_installed: &[], - has_db: &["/f2"], - acceptance: GamePathAcceptance::DatabaseExists, - expect: Some(("/f2", GamePathSource::Fallback, true)), - expect_probe_log: &["db:/r", "db:/sess", "db:/f1", "db:/f2"], - expect_candidate_calls: 1, - }, - Row { - name: "database gate returns none when every rung misses", - requested: None, - startup: None, - selected: None, - fallback: &["/f1"], - game_installed: &[], - has_db: &[], - acceptance: GamePathAcceptance::DatabaseExists, - expect: None, - expect_probe_log: &["db:/f1"], - expect_candidate_calls: 1, - }, - ]; - - #[test] - fn ladder_order_predicates_and_io_shape() { - for row in ROWS { - run(row); - } - } - - #[test] - fn fs_probe_maps_game_and_database_artifacts_to_their_probe_kinds() { - let temp_root = std::env::temp_dir().join(format!( - "bppinstaller-game-path-probe-test-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system time before epoch") - .as_nanos() - )); - std::fs::create_dir_all(&temp_root).expect("create temp game directory"); - - assert!(!fs_probe(GamePathProbe::GameInstalled, &temp_root)); - assert!(!fs_probe(GamePathProbe::DatabaseFile, &temp_root)); - - #[cfg(target_os = "macos")] - std::fs::create_dir(temp_root.join("TheBazaar.app")).expect("create game app marker"); - #[cfg(target_os = "windows")] - std::fs::write(temp_root.join("TheBazaar.exe"), b"exe").expect("create game exe marker"); - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - std::fs::write(temp_root.join("TheBazaar"), b"exe").expect("create game marker"); - - assert!(fs_probe(GamePathProbe::GameInstalled, &temp_root)); - assert!(!fs_probe(GamePathProbe::DatabaseFile, &temp_root)); - - let database_path = paths::database_path(&temp_root); - std::fs::create_dir_all(database_path.parent().expect("database parent")) - .expect("create database directory"); - std::fs::write(&database_path, b"sqlite").expect("create database marker"); - assert!(fs_probe(GamePathProbe::DatabaseFile, &temp_root)); - - std::fs::remove_dir_all(&temp_root).expect("cleanup temp game directory"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/game_process.rs b/bazaarplusplus-installer/src-tauri/src/services/game_process.rs deleted file mode 100644 index 70ab52e..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/game_process.rs +++ /dev/null @@ -1,310 +0,0 @@ -use std::path::Path; - -use crate::problem::{SemanticProblem, SemanticProblemCode}; - -#[cfg(target_os = "windows")] -const BAZAAR_PROCESS_NAME: &str = "TheBazaar.exe"; - -#[cfg(target_os = "windows")] -fn is_bazaar_running() -> Result { - crate::services::process_snapshot::process_is_running(BAZAAR_PROCESS_NAME) -} - -/// Best-effort hint for History reads, which name a still-running game as the -/// likely cause of an unreadable database. It never gates a destructive -/// operation; those use [`ensure_game_stopped`]. On platforms without a -/// path-free probe (macOS today) it returns false. -pub(crate) fn is_bazaar_running_best_effort() -> bool { - #[cfg(target_os = "windows")] - { - is_bazaar_running().unwrap_or(false) - } - - #[cfg(not(target_os = "windows"))] - { - false - } -} - -/// Kill any leftover game process, returning whether one was actually -/// terminated. The game can keep the mod database open after its window closes; -/// the user's only other recourse is `taskkill` or a reboot. -pub(crate) fn terminate_game() -> Result { - #[cfg(target_os = "windows")] - { - crate::services::process_snapshot::terminate_processes(BAZAAR_PROCESS_NAME) - .map(|terminated| terminated > 0) - } - - #[cfg(not(target_os = "windows"))] - { - Err("Ending the game process is not supported on this platform.".to_string()) - } -} - -/// An installer operation that writes or deletes files the game or its mod may -/// hold open, and therefore refuses while The Bazaar runs. Each one reports its -/// own semantic problem code so the frontend names the blocked action. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum GameStoppedOperation { - Install, - Reset, - BepinexReset, - /// The one-time V5 history import. - Import, - /// Deletion of one confirmed Legacy Root. - LegacyDelete, -} - -impl GameStoppedOperation { - #[cfg(test)] - const ALL: [Self; 5] = [ - Self::Install, - Self::Reset, - Self::BepinexReset, - Self::Import, - Self::LegacyDelete, - ]; - - pub(crate) fn problem_code(self) -> SemanticProblemCode { - match self { - Self::Install => SemanticProblemCode::InstallBlockedByGame, - Self::Reset => SemanticProblemCode::ResetBlockedByGame, - Self::BepinexReset => SemanticProblemCode::BepinexResetBlockedByGame, - Self::Import => SemanticProblemCode::ImportBlockedByGame, - Self::LegacyDelete => SemanticProblemCode::LegacyDeleteBlockedByGame, - } - } - - /// The serialized problem code, which a refusal's diagnostic text starts - /// with. - fn token(self) -> &'static str { - match self { - Self::Install => "install_blocked_by_game", - Self::Reset => "reset_blocked_by_game", - Self::BepinexReset => "bepinex_reset_blocked_by_game", - Self::Import => "import_blocked_by_game", - Self::LegacyDelete => "legacy_delete_blocked_by_game", - } - } -} - -/// Refusal from [`ensure_game_stopped`]: the game is running, or its processes -/// could not be inspected (`inspection_error`), which counts as running. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct GameRunningRefusal { - pub(crate) operation: GameStoppedOperation, - pub(crate) inspection_error: Option, -} - -impl GameRunningRefusal { - pub(crate) fn into_problem(self) -> SemanticProblem { - let problem = SemanticProblem::new(self.operation.problem_code()); - match self.inspection_error { - Some(diagnostic) => problem.with_diagnostic(diagnostic), - None => problem, - } - } -} - -impl std::fmt::Display for GameRunningRefusal { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(self.operation.token())?; - if let Some(error) = &self.inspection_error { - write!(f, ": {error}")?; - } - Ok(()) - } -} - -/// Reports whether the game installed at a path is running. Destructive flows -/// take it as a parameter so tests can simulate a running game or a failed -/// inspection without touching real processes. -pub(crate) trait GameProcessProbe { - fn is_running(&self, game_path: &Path) -> Result; -} - -impl GameProcessProbe for F -where - F: Fn(&Path) -> Result, -{ - fn is_running(&self, game_path: &Path) -> Result { - self(game_path) - } -} - -/// The operating system's process list. -#[derive(Clone, Copy, Debug, Default)] -pub(crate) struct SystemGameProcessProbe; - -impl GameProcessProbe for SystemGameProcessProbe { - fn is_running(&self, game_path: &Path) -> Result { - #[cfg(target_os = "macos")] - { - let game_path = game_path - .canonicalize() - .map_err(|err| format!("Cannot resolve the game directory: {err}"))?; - let output = std::process::Command::new("/bin/ps") - .args(["-axo", "comm="]) - .output() - .map_err(|err| format!("Cannot inspect game processes: {err}"))?; - if !output.status.success() { - return Err(format!( - "Cannot inspect game processes: ps exited with {}", - output.status - )); - } - let processes = String::from_utf8(output.stdout) - .map_err(|err| format!("Cannot inspect game processes: {err}"))?; - Ok(contains_game_process(&processes, &game_path)) - } - #[cfg(target_os = "windows")] - { - let _ = game_path; - is_bazaar_running() - } - // The game ships no build for other platforms, so no process of it can - // run here. - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - { - let _ = game_path; - Ok(false) - } - } -} - -/// Fail-closed check run before `operation` touches files under `game_path`. -pub(crate) fn ensure_game_stopped( - game_path: &Path, - operation: GameStoppedOperation, -) -> Result<(), GameRunningRefusal> { - ensure_game_stopped_with(&SystemGameProcessProbe, game_path, operation) -} - -pub(crate) fn ensure_game_stopped_with( - probe: &impl GameProcessProbe, - game_path: &Path, - operation: GameStoppedOperation, -) -> Result<(), GameRunningRefusal> { - match probe.is_running(game_path) { - Ok(false) => Ok(()), - Ok(true) => Err(GameRunningRefusal { - operation, - inspection_error: None, - }), - Err(error) => Err(GameRunningRefusal { - operation, - inspection_error: Some(error), - }), - } -} - -#[cfg(any(target_os = "macos", test))] -fn contains_game_process(processes: &str, game_path: &Path) -> bool { - let bundle = game_path.join("TheBazaar.app"); - processes.lines().any(|line| { - let process = Path::new(line.trim()); - process.starts_with(&bundle) - && process - .parent() - .is_some_and(|parent| parent.ends_with("Contents/MacOS")) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn macos_matching_finds_native_and_trampoline_processes_of_this_install_only() { - let root = Path::new("/Games/The Bazaar"); - for executable in ["The Bazaar", "The Bazaar.orig"] { - assert!(contains_game_process( - &format!("/Games/The Bazaar/TheBazaar.app/Contents/MacOS/{executable}\n"), - root - )); - } - // Surrounding blanks in `ps` output do not hide a match. - assert!(contains_game_process( - "/usr/sbin/cfprefsd\n /Games/The Bazaar/TheBazaar.app/Contents/MacOS/The Bazaar \n", - root - )); - assert!(!contains_game_process("/Applications/Steam.app/Contents/MacOS/steam_osx\n/Other/TheBazaar.app/Contents/MacOS/The Bazaar.orig", root)); - assert!(!contains_game_process( - "/Games/The Bazaar/TheBazaar.app.backup/Contents/MacOS/The Bazaar", - root - )); - assert!(!contains_game_process( - "/Games/The Bazaar/TheBazaar.app/Contents/Frameworks/UnityPlayer.dylib", - root - )); - assert!(!contains_game_process("", root)); - } - - #[test] - fn each_operation_refuses_with_its_own_problem_code_while_the_game_runs() { - let running = |_: &Path| Ok(true); - let expected = [ - ( - GameStoppedOperation::Install, - SemanticProblemCode::InstallBlockedByGame, - ), - ( - GameStoppedOperation::Reset, - SemanticProblemCode::ResetBlockedByGame, - ), - ( - GameStoppedOperation::BepinexReset, - SemanticProblemCode::BepinexResetBlockedByGame, - ), - ( - GameStoppedOperation::Import, - SemanticProblemCode::ImportBlockedByGame, - ), - ( - GameStoppedOperation::LegacyDelete, - SemanticProblemCode::LegacyDeleteBlockedByGame, - ), - ]; - assert_eq!(expected.len(), GameStoppedOperation::ALL.len()); - - for (operation, code) in expected { - let refusal = ensure_game_stopped_with(&running, Path::new("/game"), operation) - .expect_err("a running game must refuse"); - assert_eq!(refusal.operation, operation); - let problem = refusal.into_problem(); - assert_eq!(problem.code, code); - assert_eq!(problem.diagnostic, None); - // The diagnostic token is the serialized code, so refusal text and - // the frontend's code name never drift apart. - assert_eq!( - serde_json::to_value(code).unwrap(), - serde_json::json!(operation.token()) - ); - } - } - - #[test] - fn failed_inspection_refuses_like_a_running_game() { - let broken = |_: &Path| Err("ps failed".to_string()); - - let problem = - ensure_game_stopped_with(&broken, Path::new("/game"), GameStoppedOperation::Reset) - .unwrap_err() - .into_problem(); - - assert_eq!(problem.code, SemanticProblemCode::ResetBlockedByGame); - assert_eq!(problem.diagnostic.as_deref(), Some("ps failed")); - } - - #[test] - fn stopped_game_passes() { - let stopped = |_: &Path| Ok(false); - for operation in GameStoppedOperation::ALL { - assert_eq!( - ensure_game_stopped_with(&stopped, Path::new("/game"), operation), - Ok(()) - ); - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/history.rs b/bazaarplusplus-installer/src-tauri/src/services/history.rs deleted file mode 100644 index e42cc29..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/history.rs +++ /dev/null @@ -1,796 +0,0 @@ -use std::path::{Path, PathBuf}; -use std::process::Command; - -use crate::history::{ - cleanup::{ - self, RunDataCleanupPreview, RunDataCleanupResult, ScreenshotCleanupPreview, - ScreenshotCleanupResult, - }, - delete_battle_video as delete_battle_video_in_repo, get_history_run_detail, list_history_runs, - load_battle_video_path, load_run_id_for_battle, load_run_screenshot_path, HistoryReadError, -}; -use crate::problem::{SemanticProblem, SemanticProblemCode}; -use crate::services::data_maintenance::DataMaintenanceLock; -use crate::services::game_path::GamePathAcceptance; -use crate::services::paths; -use crate::services::selected_game_installation::SelectedGameInstallationState; -use crate::stream::history_thumbnails::{self, HistoryThumbnails}; -use tauri::Manager; - -pub use crate::history::cleanup::StorageCleanupPreset; -pub(crate) use crate::history::{HistoryRunDetail, HistoryRunList}; - -const REVEAL_SCREENSHOT: &str = "reveal_screenshot"; -const REVEAL_VIDEO: &str = "reveal_video"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)] -#[serde(rename_all = "snake_case")] -pub enum StorageCleanupScope { - Screenshots, - RunData, -} - -#[derive(Clone, Debug, PartialEq, serde::Serialize, specta::Type)] -#[serde(tag = "scope", rename_all = "snake_case")] -pub enum StorageCleanupPreview { - Screenshots { preview: ScreenshotCleanupPreview }, - RunData { preview: RunDataCleanupPreview }, -} - -#[derive(Clone, Debug, PartialEq, serde::Serialize, specta::Type)] -#[serde(tag = "scope", rename_all = "snake_case")] -pub enum StorageCleanupExecution { - Screenshots { result: ScreenshotCleanupResult }, - RunData { result: RunDataCleanupResult }, -} - -struct HistoryStorage { - game_path: PathBuf, - data_root: PathBuf, - combat_replay_videos_dir: PathBuf, - database_path: PathBuf, -} - -pub(crate) struct History { - paths: HistoryStorage, - is_game_running: fn() -> bool, -} - -impl History { - fn resolved_game_path(app: &tauri::AppHandle) -> Option { - app.state::() - .resolve(app, None, GamePathAcceptance::DatabaseExists) - .map(|resolution| resolution.game_path) - } - - /// History of the selected installation that has a history database. - fn selected(app: &tauri::AppHandle) -> Result { - Self::at(Self::resolved_game_path(app)) - } - - fn at(game_path: Option) -> Result { - Self::at_with( - game_path, - crate::services::game_process::is_bazaar_running_best_effort, - ) - } - - pub(crate) fn at_with( - game_path: Option, - is_game_running: fn() -> bool, - ) -> Result { - let game_path = game_path - .ok_or_else(|| SemanticProblem::new(SemanticProblemCode::HistoryUnavailable))?; - Ok(Self { - paths: history_paths_for_game_path(game_path), - is_game_running, - }) - } - - pub(crate) fn list_runs_for_page( - &self, - limit: usize, - offset: usize, - thumbnails: &HistoryThumbnails, - ) -> Result { - // The page's thumbnails stay bound to the installation it was read from. - let source = thumbnails.register(&self.paths.game_path); - list_history_runs( - &self.paths.database_path, - limit.clamp(1, 200), - offset, - |screenshot_id| history_thumbnails::url(source, screenshot_id), - ) - .map_err(|error| history_read_problem_with("list_runs", error, self.is_game_running)) - } - - pub(crate) fn run_detail_for_page( - &self, - run_id: &str, - ) -> Result, SemanticProblem> { - get_history_run_detail(&self.paths.database_path, run_id).map_err(|error| { - history_read_problem_with("get_run_detail", error, self.is_game_running) - }) - } - - fn run_detail(&self, run_id: &str) -> Result { - get_history_run_detail(&self.paths.database_path, run_id)? - .ok_or_else(|| format!("History run {run_id} was not found.")) - } - - /// The screenshot file `reveal_run_screenshot` shows for `run_id`. - fn run_screenshot_path(&self, run_id: &str) -> Result { - as_action_problem(REVEAL_SCREENSHOT, || { - self.require_database_exists()?; - load_run_screenshot_path(&self.paths.database_path, &self.paths.data_root, run_id)? - .ok_or_else(|| format!("No screenshot is available for run {run_id}.")) - }) - } - - /// The video file `reveal_battle_video` shows for `battle_id`. - fn battle_video_path( - &self, - battle_id: &str, - video_id: &str, - ) -> Result { - as_action_problem(REVEAL_VIDEO, || { - self.require_database_exists()?; - let path = load_battle_video_path( - &self.paths.database_path, - &self.paths.combat_replay_videos_dir, - battle_id, - video_id, - )? - .ok_or_else(|| format!("No completed video is available for battle {battle_id}."))?; - require_video_file_exists(&path)?; - Ok(path) - }) - } - - fn delete_battle_video( - &self, - battle_id: &str, - video_id: &str, - ) -> Result { - as_action_problem("delete_video", || { - self.require_database_exists()?; - let run_id = load_run_id_for_battle(&self.paths.database_path, battle_id)? - .ok_or_else(|| format!("Battle {battle_id} was not found."))?; - let deleted = delete_battle_video_in_repo( - &self.paths.database_path, - &self.paths.combat_replay_videos_dir, - battle_id, - video_id, - )?; - if !deleted { - return Err(format!( - "Video {video_id} was not found for battle {battle_id}." - )); - } - - self.run_detail(&run_id) - }) - } - - pub(crate) fn preview_cleanup( - &self, - scope: StorageCleanupScope, - preset: StorageCleanupPreset, - ) -> Result { - as_action_problem("preview_storage_cleanup", || { - let now = chrono::Local::now(); - let today = now.date_naive(); - let cutoff = cleanup::CleanupCutoff::for_preset(preset, now); - match scope { - StorageCleanupScope::Screenshots => { - let plan = cleanup::plan_screenshot_cleanup( - &self.paths.database_path, - &self.paths.data_root, - cutoff.as_ref(), - today, - )?; - Ok(StorageCleanupPreview::Screenshots { - preview: plan.to_preview(), - }) - } - StorageCleanupScope::RunData => { - let plan = cleanup::plan_run_data_cleanup( - &self.paths.database_path, - &self.paths.data_root, - cutoff.as_ref(), - )?; - Ok(StorageCleanupPreview::RunData { - preview: plan.to_preview(), - }) - } - } - }) - } - - fn execute_cleanup( - &self, - scope: StorageCleanupScope, - preset: StorageCleanupPreset, - ) -> Result { - as_action_problem("execute_storage_cleanup", || { - let now = chrono::Local::now(); - let today = now.date_naive(); - let cutoff = cleanup::CleanupCutoff::for_preset(preset, now); - match scope { - StorageCleanupScope::Screenshots => cleanup::execute_screenshot_cleanup( - &self.paths.database_path, - &self.paths.data_root, - cutoff.as_ref(), - today, - ) - .map(|result| StorageCleanupExecution::Screenshots { result }), - StorageCleanupScope::RunData => cleanup::execute_run_data_cleanup( - &self.paths.database_path, - &self.paths.data_root, - cutoff.as_ref(), - ) - .map(|result| StorageCleanupExecution::RunData { result }), - } - }) - } - - fn require_database_exists(&self) -> Result<(), String> { - self.paths - .database_path - .exists() - .then_some(()) - .ok_or_else(|| { - format!( - "History database was not found at {}.", - self.paths.database_path.display() - ) - }) - } -} - -pub fn list_runs( - app: &tauri::AppHandle, - limit: usize, - offset: usize, -) -> Result { - History::selected(app)?.list_runs_for_page(limit, offset, &app.state::()) -} - -pub fn get_run_detail( - app: &tauri::AppHandle, - run_id: &str, -) -> Result, SemanticProblem> { - History::selected(app)?.run_detail_for_page(run_id) -} - -pub fn reveal_run_screenshot(app: &tauri::AppHandle, run_id: &str) -> Result<(), SemanticProblem> { - let path = History::selected(app)?.run_screenshot_path(run_id)?; - as_action_problem(REVEAL_SCREENSHOT, || reveal_in_file_browser(&path)) -} - -pub fn reveal_battle_video( - app: &tauri::AppHandle, - battle_id: &str, - video_id: &str, -) -> Result<(), SemanticProblem> { - let path = History::selected(app)?.battle_video_path(battle_id, video_id)?; - as_action_problem(REVEAL_VIDEO, || reveal_in_file_browser(&path)) -} - -pub fn delete_battle_video( - app: &tauri::AppHandle, - battle_id: &str, - video_id: &str, -) -> Result { - History::selected(app)?.delete_battle_video(battle_id, video_id) -} - -pub fn preview_storage_cleanup( - app: &tauri::AppHandle, - scope: StorageCleanupScope, - preset: StorageCleanupPreset, -) -> Result { - History::selected(app)?.preview_cleanup(scope, preset) -} - -pub async fn execute_storage_cleanup( - app: &tauri::AppHandle, - scope: StorageCleanupScope, - preset: StorageCleanupPreset, -) -> Result { - let maintenance = app.state::().inner().clone(); - let app = app.clone(); - execute_storage_cleanup_with( - &maintenance, - move || History::resolved_game_path(&app), - scope, - preset, - ) - .await -} - -/// Cleanup holds the data maintenance lock and resolves the installation only -/// once it holds it, so it never acts on a data root a Reset is deleting. -pub(crate) async fn execute_storage_cleanup_with( - maintenance: &DataMaintenanceLock, - resolve_game_path: impl FnOnce() -> Option + Send + 'static, - scope: StorageCleanupScope, - preset: StorageCleanupPreset, -) -> Result { - maintenance - .run_blocking(move || History::at(resolve_game_path())?.execute_cleanup(scope, preset)) - .await - .map_err(|diagnostic| { - SemanticProblem::new(SemanticProblemCode::HistoryActionFailed) - .with_param("operation", "execute_storage_cleanup") - .with_diagnostic(diagnostic) - })? -} - -fn history_paths_for_game_path(game_path: PathBuf) -> HistoryStorage { - HistoryStorage { - data_root: paths::bpp_data_dir(&game_path), - combat_replay_videos_dir: paths::combat_replay_videos_dir(&game_path), - database_path: paths::database_path(&game_path), - game_path, - } -} - -/// Runs one history action and reports its diagnostic as the semantic -/// `HistoryActionFailed` problem the frontend renders for `operation`. -fn as_action_problem( - operation: &str, - action: impl FnOnce() -> Result, -) -> Result { - action().map_err(|diagnostic| { - SemanticProblem::new(SemanticProblemCode::HistoryActionFailed) - .with_param("operation", operation) - .with_diagnostic(diagnostic) - }) -} - -fn history_read_problem_with( - operation: &str, - error: HistoryReadError, - is_game_running: impl FnOnce() -> bool, -) -> SemanticProblem { - let diagnostic = error.to_string(); - if let HistoryReadError::UnsupportedSchema { found, supported } = error { - return SemanticProblem::new(SemanticProblemCode::HistoryDatabaseUnsupportedSchema) - .with_param("found", found.to_string()) - .with_param("supported", supported) - .with_diagnostic(diagnostic); - } - - // The game keeps this database open, and a game process that outlived its - // window is the one cause the user can act on. Naming it turns an opaque - // SQLite failure into a fixable one, so it wins over the generic read code - // whenever the process is still there. - if is_game_running() { - return SemanticProblem::new(SemanticProblemCode::HistoryReadBlockedByGame) - .with_param("operation", operation) - .with_diagnostic(diagnostic); - } - - SemanticProblem::new(SemanticProblemCode::HistoryReadFailed) - .with_param("operation", operation) - .with_diagnostic(diagnostic) -} - -fn require_video_file_exists(path: &Path) -> Result<(), String> { - path.try_exists() - .map_err(|err| format!("Failed to inspect video file at {}: {err}", path.display()))? - .then_some(()) - .ok_or_else(|| format!("Video file was not found at {}.", path.display())) -} - -#[cfg(target_os = "windows")] -fn strip_extended_length_prefix(value: &str) -> String { - if let Some(stripped) = value.strip_prefix(r"\\?\UNC\") { - format!(r"\\{stripped}") - } else if let Some(stripped) = value.strip_prefix(r"\\?\") { - stripped.to_string() - } else { - value.to_string() - } -} - -fn reveal_in_file_browser(path: &Path) -> Result<(), String> { - #[cfg(target_os = "windows")] - { - use std::os::windows::process::CommandExt; - - let canonical = std::fs::canonicalize(path) - .map(|buf| strip_extended_length_prefix(&buf.to_string_lossy())) - .unwrap_or_else(|_| path.to_string_lossy().into_owned()); - - Command::new("explorer") - .raw_arg(format!("/select,\"{}\"", canonical)) - .spawn() - .map_err(|err| format!("failed to reveal file in Explorer: {err}"))?; - Ok(()) - } - - #[cfg(target_os = "macos")] - { - Command::new("open") - .args(["-R", &path.to_string_lossy()]) - .spawn() - .map_err(|err| format!("failed to reveal file in Finder: {err}"))?; - Ok(()) - } - - #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))] - { - let parent = path - .parent() - .ok_or_else(|| "file parent directory is missing".to_string())?; - Command::new("xdg-open") - .arg(parent) - .spawn() - .map_err(|err| format!("failed to open file directory: {err}"))?; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::{ - history_paths_for_game_path, history_read_problem_with, history_thumbnails, - require_video_file_exists, History, HistoryReadError, HistoryThumbnails, - StorageCleanupExecution, StorageCleanupPreset, StorageCleanupPreview, StorageCleanupScope, - }; - use crate::history::mod_schema::create_mod_schema; - use crate::problem::SemanticProblemCode; - use crate::services::paths; - use std::path::Path; - - #[test] - fn history_paths_use_combat_replay_videos_as_video_root() { - let game_path = std::path::PathBuf::from("/tmp/The Bazaar"); - - let resolved = history_paths_for_game_path(game_path.clone()); - - assert_eq!( - resolved.combat_replay_videos_dir, - paths::combat_replay_videos_dir(&game_path) - ); - assert_eq!(resolved.database_path, paths::database_path(&game_path)); - } - - #[test] - fn history_page_list_uses_semantic_unavailable_and_read_failed_problems() { - let unavailable = History::at(None).err().unwrap(); - assert_eq!(unavailable.code, SemanticProblemCode::HistoryUnavailable); - assert!(unavailable.params.is_empty()); - assert_eq!(unavailable.diagnostic, None); - - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("The Bazaar"); - let history = History::at_with(Some(game_path.clone()), || false).unwrap(); - std::fs::create_dir_all(history.paths.database_path.parent().unwrap()).unwrap(); - std::fs::write(&history.paths.database_path, b"not sqlite").unwrap(); - - let read_failed = history - .list_runs_for_page(50, 0, &HistoryThumbnails::default()) - .unwrap_err(); - assert_eq!(read_failed.code, SemanticProblemCode::HistoryReadFailed); - assert_eq!( - read_failed.params.get("operation").map(String::as_str), - Some("list_runs") - ); - assert!(read_failed.diagnostic.is_some()); - } - - #[test] - fn history_read_problem_uses_the_injected_game_state() { - let problem = history_read_problem_with( - "list_runs", - HistoryReadError::Failed("database busy".to_string()), - || true, - ); - - assert_eq!(problem.code, SemanticProblemCode::HistoryReadBlockedByGame); - assert_eq!( - problem.params.get("operation").map(String::as_str), - Some("list_runs") - ); - assert_eq!(problem.diagnostic.as_deref(), Some("database busy")); - } - - #[test] - fn history_pages_map_unsupported_schema_to_a_specific_problem() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("The Bazaar"); - let history = History::at(Some(game_path)).unwrap(); - std::fs::create_dir_all(history.paths.database_path.parent().unwrap()).unwrap(); - rusqlite::Connection::open(&history.paths.database_path).unwrap(); - - for problem in [ - history - .list_runs_for_page(50, 0, &HistoryThumbnails::default()) - .unwrap_err(), - history.run_detail_for_page("run-1").unwrap_err(), - ] { - assert_eq!( - problem.code, - SemanticProblemCode::HistoryDatabaseUnsupportedSchema - ); - assert_eq!(problem.params.get("found").map(String::as_str), Some("0")); - assert_eq!( - problem.params.get("supported"), - Some(&crate::config::supported_mod_db_user_versions_label()) - ); - assert!(problem.diagnostic.is_some()); - } - } - - #[test] - fn cleanup_keeps_unsupported_schema_on_the_existing_action_problem_surface() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("The Bazaar"); - let history = History::at(Some(game_path)).unwrap(); - std::fs::create_dir_all(history.paths.database_path.parent().unwrap()).unwrap(); - rusqlite::Connection::open(&history.paths.database_path).unwrap(); - - let problem = history - .preview_cleanup(StorageCleanupScope::RunData, StorageCleanupPreset::All) - .unwrap_err(); - - assert_eq!(problem.code, SemanticProblemCode::HistoryActionFailed); - let supported = format!( - "supported={}", - crate::config::supported_mod_db_user_versions_label() - ); - assert!(problem - .diagnostic - .as_deref() - .is_some_and(|value| value.contains("found=0") && value.contains(&supported))); - } - - #[test] - fn run_detail_page_distinguishes_not_found_read_and_action_problems() { - let unavailable = History::at(None).err().unwrap(); - assert_eq!(unavailable.code, SemanticProblemCode::HistoryUnavailable); - - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("The Bazaar"); - let history = History::at_with(Some(game_path.clone()), || false).unwrap(); - assert_eq!(history.run_detail_for_page("missing").unwrap(), None); - - std::fs::create_dir_all(history.paths.database_path.parent().unwrap()).unwrap(); - std::fs::write(&history.paths.database_path, b"not sqlite").unwrap(); - - let read_failed = history.run_detail_for_page("run-1").unwrap_err(); - assert_eq!(read_failed.code, SemanticProblemCode::HistoryReadFailed); - assert_eq!( - read_failed.params.get("operation").map(String::as_str), - Some("get_run_detail") - ); - assert!(read_failed.diagnostic.is_some()); - - std::fs::remove_file(&history.paths.database_path).unwrap(); - for (operation, problem) in [ - ( - "reveal_screenshot", - history.run_screenshot_path("run-1").unwrap_err(), - ), - ( - "reveal_video", - history - .battle_video_path("battle-1", "video-1") - .unwrap_err(), - ), - ( - "delete_video", - history - .delete_battle_video("battle-1", "video-1") - .unwrap_err(), - ), - ] { - assert_eq!(problem.code, SemanticProblemCode::HistoryActionFailed); - assert_eq!( - problem.params.get("operation").map(String::as_str), - Some(operation) - ); - assert!(problem.diagnostic.is_some()); - } - } - - #[test] - fn storage_cleanup_page_classifies_preview_and_execute_failures() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("The Bazaar"); - let history = History::at(Some(game_path.clone())).unwrap(); - std::fs::create_dir_all(history.paths.database_path.parent().unwrap()).unwrap(); - std::fs::write(&history.paths.database_path, b"not sqlite").unwrap(); - - for (operation, problem) in [ - ( - "preview_storage_cleanup", - history - .preview_cleanup(StorageCleanupScope::RunData, StorageCleanupPreset::All) - .unwrap_err(), - ), - ( - "execute_storage_cleanup", - history - .execute_cleanup(StorageCleanupScope::RunData, StorageCleanupPreset::All) - .unwrap_err(), - ), - ] { - assert_eq!(problem.code, SemanticProblemCode::HistoryActionFailed); - assert_eq!( - problem.params.get("operation").map(String::as_str), - Some(operation) - ); - assert!(problem.diagnostic.is_some()); - } - } - - #[test] - fn video_file_exists_accepts_existing_file_and_rejects_missing_file() { - let dir = tempfile::tempdir().expect("tempdir"); - let existing = dir.path().join("battle.mp4"); - std::fs::write(&existing, b"video").expect("write video file"); - - assert!(require_video_file_exists(&existing).is_ok()); - let missing = dir.path().join("missing.mp4"); - assert_eq!( - require_video_file_exists(&missing).unwrap_err(), - format!("Video file was not found at {}.", missing.display()) - ); - } - - #[test] - fn history_facade_owns_paths_queries_reveals_deletes_and_cleanup() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("The Bazaar"); - let database_path = paths::database_path(&game_path); - let screenshots_dir = paths::screenshots_dir(&game_path); - let videos_dir = paths::combat_replay_videos_dir(&game_path); - std::fs::create_dir_all(database_path.parent().unwrap()).unwrap(); - std::fs::create_dir_all(screenshots_dir.join("2026-01-01")).unwrap(); - std::fs::create_dir_all(videos_dir.join("2026-01-01")).unwrap(); - let screenshot_path = screenshots_dir.join("2026-01-01/run.png"); - let video_path = videos_dir.join("2026-01-01/battle.mp4"); - std::fs::write(&screenshot_path, b"shot").unwrap(); - std::fs::write(&video_path, b"video").unwrap(); - - let conn = rusqlite::Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - conn.execute_batch( - " - insert into runs ( - run_id, started_at_ms, last_seen_at_ms, status, - hero, game_mode, ended_at_ms, victories, losses - ) values ( - 'run-1', 1767258000000, 1767261600000, - 'completed', 'Vanessa', 'Normal', 1767261600000, 10, 2 - ); - insert into battles ( - battle_id, source, run_id, recorded_at_ms, combat_kind, player_name, - opponent_hero, opponent_name, result, local_payload_state - ) values ( - 'battle-1', 'LOCAL', 'run-1', 1767259800000, 'PVP', 'Player', - 'Dooley', 'Opponent', 'win', 'missing' - ); - insert into run_screenshots ( - screenshot_id, run_id, capture_source, is_primary, - image_relative_path, captured_at_ms, captured_utc_offset_minutes - ) values ( - 'shot-1', 'run-1', 'end_of_run_auto', 1, - '2026-01-01/run.png', 1767261600000, - 480 - ); - insert into combat_replay_videos ( - video_id, battle_id, source, video_relative_path, width, height, fps, codec, - started_at_ms, file_size_bytes, status - ) values ( - 'video-1', 'battle-1', 'GAME_CAPTURE', '2026-01-01/battle.mp4', 1920, 1080, 60, - 'h264', 1767259800000, 5, 'COMPLETED' - ); - ", - ) - .unwrap(); - drop(conn); - - let history = History::at_with(Some(game_path.clone()), || false).unwrap(); - let thumbnails = HistoryThumbnails::default(); - thumbnails.register(Path::new("/another/installation")); - let list = history.list_runs_for_page(50, 0, &thumbnails).unwrap(); - assert_eq!( - list.runs[0].thumbnail_url, - Some(history_thumbnails::url( - thumbnails.register(&game_path), - "shot-1" - )) - ); - assert_eq!(list.summary.runs, 1); - assert_eq!(list.summary.videos, 1); - assert_eq!(list.runs.len(), 1); - assert_eq!(history.run_detail("run-1").unwrap().battles.len(), 1); - - assert_eq!( - history.run_screenshot_path("run-1").unwrap(), - screenshot_path - ); - assert_eq!( - history.battle_video_path("battle-1", "video-1").unwrap(), - video_path - ); - - let detail = history.delete_battle_video("battle-1", "video-1").unwrap(); - assert_eq!(detail.battles[0].video, None); - assert!(!video_path.exists()); - - let preview = history - .preview_cleanup(StorageCleanupScope::Screenshots, StorageCleanupPreset::All) - .unwrap(); - let StorageCleanupPreview::Screenshots { preview } = preview else { - panic!("expected screenshot preview"); - }; - assert_eq!(preview.screenshots, 1); - let execution = history - .execute_cleanup(StorageCleanupScope::Screenshots, StorageCleanupPreset::All) - .unwrap(); - let StorageCleanupExecution::Screenshots { result } = execution else { - panic!("expected screenshot result"); - }; - assert_eq!(result.deleted_rows, 1); - assert!(!screenshot_path.exists()); - - let preview = history - .preview_cleanup(StorageCleanupScope::RunData, StorageCleanupPreset::All) - .unwrap(); - let StorageCleanupPreview::RunData { preview } = preview else { - panic!("expected run-data preview"); - }; - assert_eq!(preview.runs, 1); - assert_eq!(preview.battles, 1); - let execution = history - .execute_cleanup(StorageCleanupScope::RunData, StorageCleanupPreset::All) - .unwrap(); - let StorageCleanupExecution::RunData { result } = execution else { - panic!("expected run-data result"); - }; - assert_eq!(result.deleted_runs, 1); - assert_eq!( - history - .list_runs_for_page(50, 0, &HistoryThumbnails::default()) - .unwrap() - .summary - .runs, - 0 - ); - } - - #[test] - fn storage_cleanup_preview_serializes_as_a_scope_tagged_result() { - let preview = StorageCleanupPreview::Screenshots { - preview: crate::history::cleanup::ScreenshotCleanupPreview { - screenshots: 2, - orphan_files: 1, - estimated_bytes: 42, - skipped_pending_uploads: 0, - }, - }; - - assert_eq!( - serde_json::to_value(preview).unwrap(), - serde_json::json!({ - "scope": "screenshots", - "preview": { - "screenshots": 2, - "orphan_files": 1, - "estimated_bytes": 42, - "skipped_pending_uploads": 0 - } - }) - ); - assert_eq!( - serde_json::to_value(StorageCleanupScope::Screenshots).unwrap(), - serde_json::json!("screenshots") - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/install/mod.rs b/bazaarplusplus-installer/src-tauri/src/services/install/mod.rs deleted file mode 100644 index 119ef31..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/install/mod.rs +++ /dev/null @@ -1,383 +0,0 @@ -mod operation; -mod plan; -mod types; - -pub(crate) use operation::{install, InstallRequest}; -pub use types::{ - GameDirectorySelection, InstallActions, InstallGameState, InstallModState, InstallState, - InstallWarning, InstallWarningCode, ResetBepinexResult, ResetBppDataResult, -}; - -use std::process::Command; - -use tauri::Manager; - -use std::path::Path; - -use crate::services::game_path::GamePathAcceptance; -use crate::services::{ - action_error::ActionError, - bepinex::{reset_bepinex_folder, reset_bpp_data, uninstall_bpp}, - data_maintenance::DataMaintenanceLock, - detect::detect_for_install, - legacy_data::{ - delete_legacy_root, installer_settings_directory, legacy_data_state, - DeleteLegacyRootResult, LegacyDataState, - }, - selected_game_installation::SelectedGameInstallationState, - startup::InstallerContextState, -}; -use crate::{ - problem::{SemanticProblem, SemanticProblemCode}, - stream::runtime::StreamRuntime, -}; - -const STEAM_BAZAAR_URL: &str = "steam://rungameid/1617400"; - -pub fn build_install_state( - app: tauri::AppHandle, - state: tauri::State<'_, InstallerContextState>, - game_path: Option, -) -> Result { - build_install_state_raw(app, state, game_path).map_err(install_detection_problem) -} - -pub(super) fn build_install_state_raw( - app: tauri::AppHandle, - state: tauri::State<'_, InstallerContextState>, - game_path: Option, -) -> Result { - let snapshot = detect_for_install(app, state, game_path)?; - Ok(install_state_from_snapshot(snapshot)) -} - -pub async fn run_reset_bpp_data( - app: tauri::AppHandle, - install_state: tauri::State<'_, InstallerContextState>, - stream_runtime: tauri::State<'_, StreamRuntime>, - game_path: String, -) -> Result { - let maintenance = app.state::().inner().clone(); - let removed_data = reset_bpp_data(&maintenance, &stream_runtime, game_path.clone()) - .await - .map_err(|diagnostic| install_action_problem("reset_bpp_data", diagnostic))?; - let state = build_install_state(app, install_state, Some(game_path))?; - Ok(ResetBppDataResult { - state, - removed_data, - }) -} - -pub async fn run_reset_bepinex( - app: tauri::AppHandle, - install_state: tauri::State<'_, InstallerContextState>, - game_path: String, -) -> Result { - let maintenance = app.state::().inner().clone(); - let removed = reset_bepinex_folder(&maintenance, game_path.clone()) - .await - .map_err(|diagnostic| install_action_problem("reset_bepinex", diagnostic))?; - let state = build_install_state(app, install_state, Some(game_path))?; - Ok(ResetBepinexResult { state, removed }) -} - -/// Legacy Roots of the selected game directory. History needs a database to -/// resolve its directory; this accepts any directory, so a user with only V5 -/// data still sees it. Sizes are measured on the blocking pool. -pub async fn run_get_legacy_data_state( - app: tauri::AppHandle, - game_path: Option, -) -> Result { - let resolved = app - .state::() - .resolve(&app, game_path, GamePathAcceptance::Any) - .map(|resolution| resolution.game_path); - let Some(game_path) = resolved else { - return Ok(LegacyDataState::without_game()); - }; - let settings_dir = installer_settings_directory(); - tauri::async_runtime::spawn_blocking(move || legacy_data_state(&game_path, &settings_dir)) - .await - .map_err(|err| { - install_action_problem( - "get_legacy_data_state", - format!("failed to measure legacy data: {err}"), - ) - }) -} - -pub async fn run_delete_legacy_root( - app: tauri::AppHandle, - game_path: String, - name: String, -) -> Result { - let maintenance = app.state::().inner().clone(); - delete_legacy_root(&maintenance, game_path, name) - .await - .map_err(|diagnostic| install_action_problem("delete_legacy_root", diagnostic)) -} - -pub async fn run_uninstall( - app: tauri::AppHandle, - state: tauri::State<'_, InstallerContextState>, - game_path: String, -) -> Result { - let before = detect_for_install(app.clone(), state, Some(game_path.clone())) - .map_err(install_detection_problem)?; - let app_for_task = app.clone(); - let steam_path = before.steam_path.clone().unwrap_or_default(); - let game_path_for_task = game_path.clone(); - tauri::async_runtime::spawn_blocking(move || { - uninstall_bpp(app_for_task, steam_path, game_path_for_task) - }) - .await - .map_err(|err| { - install_action_problem("uninstall", format!("failed to run uninstall task: {err}")) - })? - .map_err(|diagnostic| install_action_problem("uninstall", diagnostic))?; - - let app_for_state = app.clone(); - let state = app_for_state.state::(); - build_install_state(app, state, Some(game_path)) -} - -pub fn launch_game_via_steam() -> Result<(), String> { - open_url(STEAM_BAZAAR_URL) -} - -pub(crate) fn install_state_from_snapshot( - env: crate::services::detect::InstallEnvironmentSnapshot, -) -> InstallState { - let selected_game_path = env.game_path.clone(); - let game_found = selected_game_path.is_some(); - let installed = env.bepinex_installed; - let ready = plan::plan_install(&env).is_empty(); - let can_launch = game_found && env.game_path_valid; - let has_resettable_data = has_resettable_bpp_data(env.game_path.as_deref()); - let has_bepinex_files = has_bepinex_directory(env.game_path.as_deref()); - let warnings = install_warnings( - game_found, - env.game_path_valid, - env.steam_launch_options, - env.trampoline_current, - env.obsolete_macos_artifacts_present, - ); - - InstallState { - selected_game_path, - steam_path: env.steam_path, - game: InstallGameState { - path_valid: env.game_path_valid, - }, - mod_state: InstallModState { installed, ready }, - actions: InstallActions { - can_install: can_launch && !installed, - can_reinstall: can_launch && installed, - can_reset_data: can_launch && has_resettable_data, - can_reset_bepinex: can_launch && has_bepinex_files, - can_uninstall: can_launch && installed, - can_launch, - }, - has_resettable_data, - has_bepinex_files, - warnings, - } -} - -fn install_warnings( - game_found: bool, - game_path_valid: bool, - steam_launch_options: crate::services::vdf::SteamLaunchOptionsState, - trampoline_current: bool, - obsolete_macos_artifacts_present: bool, -) -> Vec { - let mut warnings = Vec::new(); - if !game_found || !game_path_valid { - warnings.push(InstallWarning { - code: InstallWarningCode::GameMissing, - params: Default::default(), - }); - } - if cfg!(target_os = "macos") { - match steam_launch_options { - crate::services::vdf::SteamLaunchOptionsState::Empty => {} - crate::services::vdf::SteamLaunchOptionsState::NonEmpty => { - warnings.push(InstallWarning { - code: InstallWarningCode::LaunchOptionsNotEmpty, - params: Default::default(), - }); - } - crate::services::vdf::SteamLaunchOptionsState::Unavailable => { - warnings.push(InstallWarning { - code: InstallWarningCode::SteamConfigUnavailable, - params: Default::default(), - }); - } - } - if !trampoline_current { - warnings.push(InstallWarning { - code: InstallWarningCode::TrampolineNotReady, - params: Default::default(), - }); - } - if obsolete_macos_artifacts_present { - warnings.push(InstallWarning { - code: InstallWarningCode::ObsoleteMacosArtifacts, - params: Default::default(), - }); - } - } - warnings -} - -fn install_detection_problem(diagnostic: String) -> SemanticProblem { - SemanticProblem::new(SemanticProblemCode::InstallDetectionFailed) - .with_param("operation", "detect_state") - .with_diagnostic(diagnostic) -} - -pub(crate) fn install_action_problem( - operation: &str, - error: impl Into, -) -> SemanticProblem { - error.into().into_problem(operation) -} - -fn has_resettable_bpp_data(game_path: Option<&str>) -> bool { - game_path - .map(Path::new) - .map(|path| crate::services::paths::bpp_data_dir(path).exists()) - .unwrap_or(false) -} - -fn has_bepinex_directory(game_path: Option<&str>) -> bool { - game_path - .map(Path::new) - .map(|path| path.join("BepInEx").is_dir()) - .unwrap_or(false) -} - -fn open_url(url: &str) -> Result<(), String> { - #[cfg(target_os = "windows")] - { - Command::new("cmd") - .args(["/C", "start", "", url]) - .spawn() - .map_err(|err| format!("failed to open URL: {err}"))?; - Ok(()) - } - - #[cfg(target_os = "macos")] - { - Command::new("open") - .arg(url) - .spawn() - .map_err(|err| format!("failed to open URL: {err}"))?; - Ok(()) - } - - #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))] - { - Command::new("xdg-open") - .arg(url) - .spawn() - .map_err(|err| format!("failed to open URL: {err}"))?; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::{ - has_bepinex_directory, has_resettable_bpp_data, install_warnings, InstallWarningCode, - }; - - #[test] - fn test_has_resettable_bpp_data_detects_existing_data_directory() { - let tmp = tempfile::tempdir().unwrap(); - std::fs::create_dir_all(tmp.path().join(crate::config::BAZAAR_DATA_DIRECTORY)).unwrap(); - let path = tmp.path().to_string_lossy().into_owned(); - - assert!(has_resettable_bpp_data(Some(path.as_str()))); - } - - #[test] - fn test_has_resettable_bpp_data_is_false_when_missing() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().to_string_lossy().into_owned(); - - assert!(!has_resettable_bpp_data(Some(path.as_str()))); - assert!(!has_resettable_bpp_data(None)); - } - - #[test] - fn test_has_bepinex_directory_detects_existing_folder() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().to_string_lossy().into_owned(); - assert!(!has_bepinex_directory(Some(path.as_str()))); - - std::fs::create_dir_all(tmp.path().join("BepInEx")).unwrap(); - - assert!(has_bepinex_directory(Some(path.as_str()))); - assert!(!has_bepinex_directory(None)); - } - - #[test] - fn install_warnings_are_semantic_codes_without_backend_copy() { - let warnings = install_warnings( - false, - false, - crate::services::vdf::SteamLaunchOptionsState::Empty, - true, - false, - ); - - assert_eq!( - warnings - .iter() - .map(|warning| warning.code) - .collect::>(), - vec![InstallWarningCode::GameMissing] - ); - assert!(warnings.iter().all(|warning| warning.params.is_empty())); - } - - #[cfg(target_os = "macos")] - #[test] - fn install_warnings_include_macos_bootstrap_problems() { - let warnings = install_warnings( - true, - true, - crate::services::vdf::SteamLaunchOptionsState::Unavailable, - false, - true, - ); - - assert_eq!( - warnings - .iter() - .map(|warning| warning.code) - .collect::>(), - vec![ - InstallWarningCode::SteamConfigUnavailable, - InstallWarningCode::TrampolineNotReady, - InstallWarningCode::ObsoleteMacosArtifacts, - ] - ); - assert!(warnings.iter().all(|warning| warning.params.is_empty())); - } - - #[cfg(not(target_os = "macos"))] - #[test] - fn install_warnings_ignore_macos_bootstrap_inputs_on_other_platforms() { - let warnings = install_warnings( - true, - true, - crate::services::vdf::SteamLaunchOptionsState::Unavailable, - false, - true, - ); - - assert!(warnings.is_empty()); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/install/operation.rs b/bazaarplusplus-installer/src-tauri/src/services/install/operation.rs deleted file mode 100644 index 8827624..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/install/operation.rs +++ /dev/null @@ -1,366 +0,0 @@ -use std::path::Path; - -use tauri::Manager; - -use super::plan::{plan_install, InstallEffect}; -use super::{build_install_state_raw, install_action_problem, InstallState}; -use crate::problem::SemanticProblem; -use crate::services::{ - action_error::ActionError, - bepinex::{self, install_bepinex}, - detect::{detect_for_install, InstallEnvironmentSnapshot}, - startup::InstallerContextState, - steam::prepare_steam_for_config_update, - vdf::{clear_launch_options_for_steam, SteamLaunchOptionsState}, -}; - -pub(crate) struct InstallRequest { - pub(crate) game_path: String, -} - -pub(crate) async fn install( - app: tauri::AppHandle, - request: InstallRequest, -) -> Result { - let task_app = app.clone(); - tauri::async_runtime::spawn_blocking(move || -> Result<_, ActionError> { - let installer_state = task_app.state::(); - let before = detect_for_install( - task_app.clone(), - installer_state, - Some(request.game_path.clone()), - )?; - let steam_path = before.steam_path.clone().unwrap_or_default(); - let requires_macos_bootstrap = cfg!(target_os = "macos"); - if requires_macos_bootstrap - && (steam_path.trim().is_empty() - || before.steam_launch_options == SteamLaunchOptionsState::Unavailable) - { - return Err(ActionError::Failed( - "Steam localconfig.vdf is unavailable; start Steam once, close it, and retry." - .to_string(), - )); - } - let mut effects = ProductionInstallEffects { - resource_dir: task_app - .path() - .resource_dir() - .map_err(|err| err.to_string())?, - steam_path, - game_path: request.game_path.clone(), - }; - - execute_and_refresh(&before, &mut effects, || { - let installer_state = task_app.state::(); - build_install_state_raw(task_app.clone(), installer_state, Some(request.game_path)) - }) - }) - .await - .map_err(|error| { - install_action_problem("install", format!("failed to run install task: {error}")) - })? - .map_err(|error| install_action_problem("install", error)) -} - -trait InstallEffects { - fn execute(&mut self, effect: InstallEffect) -> Result<(), ActionError>; -} - -struct ProductionInstallEffects { - resource_dir: std::path::PathBuf, - steam_path: String, - game_path: String, -} - -impl InstallEffects for ProductionInstallEffects { - fn execute(&mut self, effect: InstallEffect) -> Result<(), ActionError> { - let steam = Path::new(&self.steam_path); - let game = Path::new(&self.game_path); - match effect { - InstallEffect::EnsureGameStopped => crate::services::game_process::ensure_game_stopped( - game, - crate::services::game_process::GameStoppedOperation::Install, - )?, - InstallEffect::CloseSteam => prepare_steam_for_config_update(steam)?, - InstallEffect::InstallBepInEx => install_bepinex(&self.resource_dir, game)?, - InstallEffect::InstallTrampoline => { - bepinex::install_trampoline(&self.resource_dir, game)? - } - InstallEffect::ClearLaunchOptions => clear_launch_options_for_steam(steam)?, - InstallEffect::RemoveObsoleteMacosArtifacts => { - bepinex::remove_obsolete_macos_artifacts(game)? - } - } - Ok(()) - } -} - -fn execute_and_refresh( - facts: &InstallEnvironmentSnapshot, - effects: &mut impl InstallEffects, - refresh: impl FnOnce() -> Result, -) -> Result { - for effect in plan_install(facts) { - effects.execute(effect)?; - } - Ok(refresh()?) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[derive(Default)] - struct Recorder { - effects: Vec, - fail_on: Option, - } - - impl InstallEffects for Recorder { - fn execute(&mut self, effect: InstallEffect) -> Result<(), ActionError> { - self.effects.push(effect); - if self.fail_on == Some(effect) { - return Err("effect failed".to_string().into()); - } - Ok(()) - } - } - - fn facts(payload_current: bool, bootstrap_satisfied: bool) -> InstallEnvironmentSnapshot { - InstallEnvironmentSnapshot { - steam_path: Some("steam".into()), - game_path: None, - game_path_valid: false, - bepinex_installed: payload_current, - bpp_version: payload_current.then(|| "2".into()), - bundled_bpp_version: Some("2".into()), - steam_launch_options: if bootstrap_satisfied { - SteamLaunchOptionsState::Empty - } else { - SteamLaunchOptionsState::NonEmpty - }, - trampoline_current: bootstrap_satisfied, - obsolete_macos_artifacts_present: false, - } - } - - #[test] - fn complete_install_stops_on_first_error_and_does_not_refresh() { - let mut recorder = Recorder { - fail_on: Some(InstallEffect::InstallBepInEx), - ..Recorder::default() - }; - let mut refreshed = false; - - let error = execute_and_refresh(&facts(false, false), &mut recorder, || { - refreshed = true; - Ok(()) - }) - .unwrap_err(); - - assert_eq!(error, ActionError::Failed("effect failed".to_string())); - assert!(!refreshed); - assert_eq!( - recorder.effects.last(), - Some(&InstallEffect::InstallBepInEx) - ); - } -} - -#[cfg(all(test, target_os = "macos"))] -mod fresh_install_acceptance { - use super::*; - use std::io::Read; - use std::process::Command; - - fn run(command: &mut Command) { - let output = command.output().expect("run native tool"); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - } - - // All filesystem effects are production effects. Only Steam shutdown is - // intercepted so a regression cannot close the developer's Steam session. - struct KeepSteamRunning(ProductionInstallEffects); - impl InstallEffects for KeepSteamRunning { - fn execute(&mut self, effect: InstallEffect) -> Result<(), ActionError> { - assert_ne!( - effect, - InstallEffect::CloseSteam, - "fresh install attempted to quit Steam" - ); - self.0.execute(effect) - } - } - - #[test] - #[ignore = "macOS acceptance: run through `just installer::acceptance`"] - fn fresh_install_writes_payload_and_signed_trampoline_without_quitting_steam() { - let resources = std::path::PathBuf::from( - std::env::var("BPP_ACCEPTANCE_RESOURCE_DIR").expect("resource directory required"), - ); - assert!(resources.join("BepInExSource/BepInEx.zip").is_file()); - assert!(resources.join("Trampoline/bpp_launcher").is_file()); - let temporary = tempfile::tempdir().unwrap(); - let game = temporary.path().join("The Bazaar"); - let bundle = game.join("TheBazaar.app"); - let macos = bundle.join("Contents/MacOS"); - let frameworks = bundle.join("Contents/Frameworks"); - std::fs::create_dir_all(&macos).unwrap(); - std::fs::create_dir_all(&frameworks).unwrap(); - std::fs::write(bundle.join("Contents/Info.plist"), r#"CFBundleExecutableThe BazaarCFBundleIdentifiercom.bpp.acceptance.fixtureCFBundlePackageTypeAPPL"#).unwrap(); - let library_source = temporary.path().join("unity.c"); - let main_source = temporary.path().join("main.c"); - std::fs::write(&library_source, "int fixture_unity(void) { return 0; }").unwrap(); - std::fs::write( - &main_source, - "extern int fixture_unity(void); int main(void) { return fixture_unity(); }", - ) - .unwrap(); - let library = frameworks.join("UnityPlayer.dylib"); - let executable = macos.join("The Bazaar"); - run(Command::new("clang") - .args([ - "-arch", - "arm64", - "-dynamiclib", - "-install_name", - "@executable_path/../Frameworks/UnityPlayer.dylib", - ]) - .arg(&library_source) - .arg("-o") - .arg(&library)); - run(Command::new("clang") - .args(["-arch", "arm64"]) - .arg(&main_source) - .arg(&library) - .arg("-o") - .arg(&executable)); - run(Command::new("codesign") - .args(["--force", "--sign", "-"]) - .arg(&library)); - run(Command::new("codesign") - .args(["--force", "--sign", "-"]) - .arg(&bundle)); - - let steam = temporary.path().join("Steam"); - let config = steam.join("userdata/123/config/localconfig.vdf"); - std::fs::create_dir_all(config.parent().unwrap()).unwrap(); - let original_config = r#""UserLocalConfigStore" -{ - "Software" - { - "Valve" - { - "Steam" - { - "apps" - { - "1617400" - { - "LaunchOptions" "" - } - } - } - } - } -} -"#; - std::fs::write(&config, original_config).unwrap(); - let options = crate::services::vdf::inspect_launch_options_for_steam(&steam); - assert_eq!(options, SteamLaunchOptionsState::Empty); - assert!(!game.join("BepInEx").exists()); - assert!(!macos.join("The Bazaar.orig").exists()); - let facts = InstallEnvironmentSnapshot { - steam_path: Some(steam.to_string_lossy().into_owned()), - game_path: Some(game.to_string_lossy().into_owned()), - game_path_valid: true, - bepinex_installed: false, - bpp_version: None, - bundled_bpp_version: Some("packaged".into()), - steam_launch_options: options, - trampoline_current: false, - obsolete_macos_artifacts_present: false, - }; - let mut effects = KeepSteamRunning(ProductionInstallEffects { - resource_dir: resources.clone(), - steam_path: steam.to_string_lossy().into_owned(), - game_path: game.to_string_lossy().into_owned(), - }); - let verified = execute_and_refresh(&facts, &mut effects, || { - let mut archive = zip::ZipArchive::new( - std::fs::File::open(resources.join("BepInExSource/BepInEx.zip")).unwrap(), - ) - .unwrap(); - let mut verified_files = 0; - for index in 0..archive.len() { - let mut entry = archive.by_index(index).unwrap(); - if entry.is_dir() { - continue; - } - let path = game.join(entry.enclosed_name().expect("safe packaged path")); - let mut expected = Vec::new(); - entry.read_to_end(&mut expected).unwrap(); - assert_eq!( - std::fs::read(&path).unwrap(), - expected, - "payload mismatch: {}", - path.display() - ); - verified_files += 1; - } - assert!(verified_files > 0); - eprintln!("Verified all {verified_files} packaged files byte-for-byte."); - assert!(game.join("BepInEx/core/BepInEx.Preloader.dll").is_file()); - assert!(game.join("BepInEx/plugins/BazaarPlusPlus.dll").is_file()); - assert!(game.join("libdoorstop.dylib").is_file()); - assert!(macos.join("The Bazaar.orig").is_file()); - assert_eq!(std::fs::read_to_string(&config).unwrap(), original_config); - assert!(!config.with_extension("vdf.bak").exists()); - let codesign_verified = Command::new("codesign") - .args(["--verify", "--deep", "--strict"]) - .arg(&bundle) - .status() - .unwrap() - .success(); - let uuid = |path: &std::path::Path| { - let output = Command::new("dwarfdump") - .arg("--uuid") - .arg(path) - .output() - .unwrap(); - String::from_utf8_lossy(&output.stdout) - .split_whitespace() - .nth(1) - .map(str::to_owned) - }; - let installed_uuid = uuid(&executable); - let uuid_matches = installed_uuid.is_some() - && installed_uuid == uuid(&resources.join("Trampoline/bpp_launcher")); - Ok((codesign_verified, uuid_matches)) - }) - .unwrap(); - let (codesign_verified, uuid_matches) = verified; - - // Signatures change on every signing, so the committed golden holds the - // installed path set; the per-run manifest holds the hashes. - let manifest = crate::goldens::tree_manifest(&game); - crate::goldens::write_run_manifest( - "fresh_install_writes_payload_and_signed_trampoline_without_quitting_steam", - &manifest, - ); - let tree = serde_json::json!({ - "paths": manifest.iter().map(|(path, _)| path).collect::>(), - "trampoline_uuid_matches_bundled": uuid_matches, - "codesign_verified": codesign_verified, - }); - crate::goldens::assert_golden( - "acceptance/installed-tree.json", - &crate::goldens::json(&tree, &[]), - ); - eprintln!("Fresh install passed: packaged payload, .orig preservation, trampoline UUID, deep signature, unchanged Steam config; temporary directory removed on exit."); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/install/plan.rs b/bazaarplusplus-installer/src-tauri/src/services/install/plan.rs deleted file mode 100644 index 068f4f1..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/install/plan.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! Private install planner: turns gathered facts into ordered effects. -//! macOS has one bootstrap only: trampoline plus empty Steam launch options. - -use crate::services::detect::InstallEnvironmentSnapshot; -use crate::services::vdf::SteamLaunchOptionsState; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum InstallEffect { - /// Refuse to modify an active game installation. - EnsureGameStopped, - /// Quit Steam only when its launch options need changing. - CloseSteam, - /// Extract the current BepInEx and BazaarPlusPlus payload. - InstallBepInEx, - /// Install or refresh the bundled trampoline and verify the signed bundle. - InstallTrampoline, - /// Remove every LaunchOptions entry for The Bazaar and verify the result. - ClearLaunchOptions, - /// Delete installer-owned files that are not part of the canonical bootstrap. - RemoveObsoleteMacosArtifacts, -} - -pub(super) fn plan_install(env: &InstallEnvironmentSnapshot) -> Vec { - plan_install_for_platform(env, cfg!(target_os = "macos")) -} - -fn plan_install_for_platform( - env: &InstallEnvironmentSnapshot, - requires_macos_bootstrap: bool, -) -> Vec { - let payload_current = env.bepinex_installed - && env.bpp_version.as_ref().is_some_and(|installed| { - env.bundled_bpp_version - .as_ref() - .is_none_or(|bundled| installed == bundled) - }); - let launch_options_empty = env.steam_launch_options == SteamLaunchOptionsState::Empty; - let bootstrap_ready = !requires_macos_bootstrap - || (env.trampoline_current - && launch_options_empty - && !env.obsolete_macos_artifacts_present); - if payload_current && bootstrap_ready { - return Vec::new(); - } - - let mut steps = Vec::new(); - if requires_macos_bootstrap { - steps.push(InstallEffect::EnsureGameStopped); - if !launch_options_empty { - steps.push(InstallEffect::CloseSteam); - } - } - if !payload_current { - steps.push(InstallEffect::InstallBepInEx); - } - if requires_macos_bootstrap { - steps.extend([ - InstallEffect::InstallTrampoline, - InstallEffect::RemoveObsoleteMacosArtifacts, - ]); - if !launch_options_empty { - steps.push(InstallEffect::ClearLaunchOptions); - } - } - steps -} - -#[cfg(test)] -mod tests { - use super::super::install_state_from_snapshot; - use super::*; - - #[test] - fn detected_facts_drive_readiness_and_effects_on_both_platforms() { - use InstallEffect::*; - use SteamLaunchOptionsState::*; - - for (installed, version, bundled, payload_current) in [ - (false, None, Some("2"), false), - (false, Some("2"), Some("2"), false), - (true, None, Some("2"), false), - (true, None, None, false), - (true, Some("1"), Some("2"), false), - (true, Some("2"), Some("2"), true), - (true, Some("2"), None, true), - ] { - for (trampoline, options, obsolete, bootstrap_ready) in [ - (true, Empty, false, true), - (false, Empty, false, false), - (true, NonEmpty, false, false), - (true, Unavailable, false, false), - (true, Empty, true, false), - ] { - let env = InstallEnvironmentSnapshot { - steam_path: Some("steam".into()), - game_path: None, - game_path_valid: false, - bepinex_installed: installed, - bpp_version: version.map(str::to_owned), - bundled_bpp_version: bundled.map(str::to_owned), - steam_launch_options: options, - trampoline_current: trampoline, - obsolete_macos_artifacts_present: obsolete, - }; - for macos in [false, true] { - let ready = payload_current && (!macos || bootstrap_ready); - let steps = plan_install_for_platform(&env, macos); - assert_eq!(steps.is_empty(), ready, "{env:?}, macos={macos}"); - assert_eq!(steps.contains(&InstallBepInEx), !payload_current); - assert_eq!(steps.contains(&InstallTrampoline), macos && !ready); - assert_eq!( - steps.contains(&RemoveObsoleteMacosArtifacts), - macos && !ready - ); - assert_eq!(steps.contains(&CloseSteam), macos && options != Empty); - assert_eq!( - steps.contains(&ClearLaunchOptions), - macos && options != Empty - ); - if macos && !ready { - assert_eq!(steps.first(), Some(&EnsureGameStopped)); - } else if !macos && !ready { - assert_eq!(steps, vec![InstallBepInEx]); - } - if macos == cfg!(target_os = "macos") { - assert_eq!( - install_state_from_snapshot(env.clone()).mod_state.ready, - ready, - "{env:?}" - ); - } - } - } - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/install/types.rs b/bazaarplusplus-installer/src-tauri/src/services/install/types.rs deleted file mode 100644 index fd39049..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/install/types.rs +++ /dev/null @@ -1,73 +0,0 @@ -use std::collections::BTreeMap; - -use serde::Serialize; - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct InstallState { - pub selected_game_path: Option, - pub steam_path: Option, - pub game: InstallGameState, - pub mod_state: InstallModState, - pub actions: InstallActions, - pub has_resettable_data: bool, - /// Whether a `BepInEx/` directory physically exists — gates the blunt - /// "reset BepInEx folder" action independently of a healthy install, so it - /// stays usable when BepInEx is broken/half-installed. - pub has_bepinex_files: bool, - pub warnings: Vec, -} - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct ResetBppDataResult { - pub state: InstallState, - pub removed_data: bool, -} - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct ResetBepinexResult { - pub state: InstallState, - pub removed: bool, -} - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct InstallGameState { - pub path_valid: bool, -} - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct InstallModState { - pub installed: bool, - /// Payload version and the platform launch bootstrap are both ready. - pub ready: bool, -} - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct InstallActions { - pub can_install: bool, - pub can_reinstall: bool, - pub can_reset_data: bool, - pub can_reset_bepinex: bool, - pub can_uninstall: bool, - pub can_launch: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)] -#[serde(rename_all = "snake_case")] -pub enum InstallWarningCode { - GameMissing, - SteamConfigUnavailable, - LaunchOptionsNotEmpty, - TrampolineNotReady, - ObsoleteMacosArtifacts, -} - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct InstallWarning { - pub code: InstallWarningCode, - pub params: BTreeMap, -} - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct GameDirectorySelection { - pub game_path: Option, -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/legacy_data.rs b/bazaarplusplus-installer/src-tauri/src/services/legacy_data.rs deleted file mode 100644 index 8f8cb6d..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/legacy_data.rs +++ /dev/null @@ -1,713 +0,0 @@ -//! Legacy Roots: Data Roots an earlier major version wrote into the game -//! directory. They are user-owned (ADR-0008): the installer measures them and -//! deletes one only after the user confirms that root. Nothing here runs on its -//! own, and Reset and uninstall never reach these directories. - -use std::fs::Metadata; -use std::io; -use std::path::{Path, PathBuf}; - -use serde::Serialize; - -use crate::config::BAZAAR_DATA_DIRECTORY; -use crate::services::action_error::ActionError; -use crate::services::bepinex::{ensure_valid_game_path, remove_dir_with_retry}; -use crate::services::data_maintenance::DataMaintenanceLock; -use crate::services::game_process::{ - ensure_game_stopped_with, GameProcessProbe, GameStoppedOperation, SystemGameProcessProbe, -}; - -/// Diagnostic prefix for a name that is not a Legacy Root this installer may -/// delete. -const LEGACY_ROOT_ERR_UNKNOWN: &str = "legacy_root_unknown"; - -/// The mod's Payload file that names the Data Root it writes. Mods before 6.0 -/// ship it without `dataRootDirectoryName`. -pub(crate) const INSTALLED_HISTORY_DATABASE_CONTRACT: &str = - "BepInEx/plugins/BazaarPlusPlus.history-database.json"; - -/// One Legacy Root. [`LegacyRoot::ALL`] is the only list of them in the -/// installer; it never contains the current Data Root. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)] -pub enum LegacyRoot { - #[serde(rename = "BazaarPlusPlus")] - Original, - #[serde(rename = "BazaarPlusPlusV4")] - V4, - #[serde(rename = "BazaarPlusPlusV5")] - V5, -} - -impl LegacyRoot { - pub(crate) const ALL: [Self; 3] = [Self::Original, Self::V4, Self::V5]; - - pub(crate) fn directory_name(self) -> &'static str { - match self { - Self::Original => "BazaarPlusPlus", - Self::V4 => "BazaarPlusPlusV4", - Self::V5 => "BazaarPlusPlusV5", - } - } - - pub(crate) fn from_directory_name(name: &str) -> Option { - Self::ALL - .into_iter() - .find(|root| root.directory_name() == name) - } - - pub(crate) fn path_in(self, game_path: &Path) -> PathBuf { - game_path.join(self.directory_name()) - } -} - -/// One Legacy Root present in the selected game directory, measured without -/// following symbolic links. A file with more than one hard link is counted in -/// `size_bytes` and in `hard_linked_file_count`: deleting the root frees its -/// blocks only when no other link remains, so the size is an upper bound on -/// what deletion reclaims. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, specta::Type)] -pub struct LegacyDataRoot { - pub name: LegacyRoot, - pub size_bytes: u64, - pub file_count: u64, - pub hard_linked_file_count: u64, - /// Entries whose metadata or contents could not be read; their size is - /// missing from `size_bytes`. - pub unreadable_entry_count: u64, -} - -/// Which Data Root the installed mod writes, from its Payload contract file. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)] -#[serde(rename_all = "snake_case")] -pub enum InstalledModDataRoot { - /// The contract names `BAZAAR_DATA_DIRECTORY`. - Current, - /// The contract is missing, unreadable, has no `dataRootDirectoryName`, or - /// names another directory: the installed mod predates the current Data - /// Root and must be reinstalled. - ReinstallRequired, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, specta::Type)] -pub struct LegacyDataState { - pub game_path: Option, - pub roots: Vec, - pub installed_mod_data_root: InstalledModDataRoot, - /// The one-time V5 import may run (`v5_import::is_v5_import_eligible`). - pub v5_import_eligible: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, specta::Type)] -pub struct DeleteLegacyRootResult { - /// False when the root was already gone: nothing was deleted. - pub removed: bool, - pub state: LegacyDataState, -} - -impl LegacyDataState { - pub(crate) fn without_game() -> Self { - Self { - game_path: None, - roots: Vec::new(), - installed_mod_data_root: InstalledModDataRoot::ReinstallRequired, - v5_import_eligible: false, - } - } -} - -/// The installer's own settings folder (`legacy_overlay_settings_path`'s -/// parent). It shares the `BazaarPlusPlusV4` name but is never a Legacy Root. -pub(crate) fn installer_settings_directory() -> PathBuf { - let settings = crate::services::paths::legacy_overlay_settings_path(); - settings.parent().map(Path::to_path_buf).unwrap_or(settings) -} - -/// Measures the Legacy Roots in `game_path`. Blocking: it walks every file. -pub(crate) fn legacy_data_state( - game_path: &Path, - installer_settings_dir: &Path, -) -> LegacyDataState { - LegacyDataState { - game_path: Some(game_path.to_string_lossy().into_owned()), - roots: present_legacy_roots(game_path, installer_settings_dir) - .into_iter() - .map(|root| measure_root(root, &root.path_in(game_path))) - .collect(), - installed_mod_data_root: installed_mod_data_root(game_path), - v5_import_eligible: crate::v5_import::is_v5_import_eligible(game_path), - } -} - -/// The Legacy Roots that exist as real directories directly under `game_path`. -/// A file or symbolic link with a Legacy Root's name is not one. -fn present_legacy_roots(game_path: &Path, installer_settings_dir: &Path) -> Vec { - LegacyRoot::ALL - .into_iter() - .filter(|root| { - let path = root.path_in(game_path); - is_real_directory(&path) && !same_directory(&path, installer_settings_dir) - }) - .collect() -} - -pub(crate) fn is_real_directory(path: &Path) -> bool { - std::fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_dir()) -} - -fn same_directory(left: &Path, right: &Path) -> bool { - match (left.canonicalize(), right.canonicalize()) { - (Ok(left), Ok(right)) => left == right, - _ => left == right, - } -} - -fn measure_root(name: LegacyRoot, root: &Path) -> LegacyDataRoot { - let mut usage = LegacyDataRoot { - name, - size_bytes: 0, - file_count: 0, - hard_linked_file_count: 0, - unreadable_entry_count: 0, - }; - let mut pending = vec![root.to_path_buf()]; - while let Some(directory) = pending.pop() { - let Ok(entries) = std::fs::read_dir(&directory) else { - usage.unreadable_entry_count += 1; - continue; - }; - for entry in entries { - let Ok(entry) = entry else { - usage.unreadable_entry_count += 1; - continue; - }; - let path = entry.path(); - // `symlink_metadata` describes a link itself, so links are never - // followed out of the root. - let Ok(metadata) = std::fs::symlink_metadata(&path) else { - usage.unreadable_entry_count += 1; - continue; - }; - let file_type = metadata.file_type(); - if file_type.is_dir() { - pending.push(path); - } else if file_type.is_file() { - usage.size_bytes += metadata.len(); - usage.file_count += 1; - match link_count(&path, &metadata) { - Ok(links) if links > 1 => usage.hard_linked_file_count += 1, - Ok(_) => {} - Err(_) => usage.unreadable_entry_count += 1, - } - } - } - } - usage -} - -#[cfg(unix)] -fn link_count(_path: &Path, metadata: &Metadata) -> io::Result { - use std::os::unix::fs::MetadataExt; - Ok(metadata.nlink()) -} - -#[cfg(windows)] -fn link_count(path: &Path, _metadata: &Metadata) -> io::Result { - use std::os::windows::fs::OpenOptionsExt; - use std::os::windows::io::AsRawHandle; - - use windows::Win32::Foundation::HANDLE; - use windows::Win32::Storage::FileSystem::{ - GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, - }; - - // Access mode 0 queries metadata without read access, so a file the game - // or another process holds open still reports its link count. - let file = std::fs::OpenOptions::new().access_mode(0).open(path)?; - let mut information = BY_HANDLE_FILE_INFORMATION::default(); - // SAFETY: `file` owns a valid handle for the duration of the call and - // `information` is a writable struct of the expected layout. - unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle()), &raw mut information) }?; - Ok(u64::from(information.nNumberOfLinks)) -} - -#[cfg(not(any(unix, windows)))] -fn link_count(_path: &Path, _metadata: &Metadata) -> io::Result { - Ok(1) -} - -/// Which Data Root the installed mod writes. Any doubt reads as -/// [`InstalledModDataRoot::ReinstallRequired`]. -pub(crate) fn installed_mod_data_root(game_path: &Path) -> InstalledModDataRoot { - let named = std::fs::read(game_path.join(INSTALLED_HISTORY_DATABASE_CONTRACT)) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) - .and_then(|contract| { - contract - .get("dataRootDirectoryName") - .and_then(serde_json::Value::as_str) - .map(str::to_owned) - }); - if named.as_deref() == Some(BAZAAR_DATA_DIRECTORY) { - InstalledModDataRoot::Current - } else { - InstalledModDataRoot::ReinstallRequired - } -} - -/// Deletes the confirmed Legacy Root `name` under the data maintenance lock, -/// refusing while the game runs, and returns the remeasured state. -pub(crate) async fn delete_legacy_root( - maintenance: &DataMaintenanceLock, - game_path: String, - name: String, -) -> Result { - let installer_settings_dir = installer_settings_directory(); - maintenance - .run_blocking(move || { - delete_legacy_root_blocking_with( - Path::new(&game_path), - &name, - &installer_settings_dir, - &SystemGameProcessProbe, - ) - }) - .await? -} - -pub(crate) fn delete_legacy_root_blocking_with( - game_path: &Path, - name: &str, - installer_settings_dir: &Path, - probe: &impl GameProcessProbe, -) -> Result { - let root = LegacyRoot::from_directory_name(name) - .ok_or_else(|| format!("{LEGACY_ROOT_ERR_UNKNOWN}:{name}"))?; - ensure_valid_game_path(game_path)?; - ensure_game_stopped_with(probe, game_path, GameStoppedOperation::LegacyDelete)?; - - let path = root.path_in(game_path); - if same_directory(&path, installer_settings_dir) { - return Err(format!("{LEGACY_ROOT_ERR_UNKNOWN}:{name}").into()); - } - let removed = is_real_directory(&path); - if removed { - // The same removal Reset uses for the current Data Root. - let report = remove_dir_with_retry(&path); - if !report.is_empty() { - return Err(ActionError::PartialFailure(report.failed)); - } - } - Ok(DeleteLegacyRootResult { - removed, - state: legacy_data_state(game_path, installer_settings_dir), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::problem::SemanticProblemCode; - - fn stopped(_: &Path) -> Result { - Ok(false) - } - - fn valid_game_dir() -> tempfile::TempDir { - let tmp = tempfile::tempdir().unwrap(); - #[cfg(target_os = "macos")] - std::fs::create_dir_all(tmp.path().join("TheBazaar.app")).unwrap(); - #[cfg(target_os = "windows")] - std::fs::write(tmp.path().join("TheBazaar.exe"), b"exe").unwrap(); - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - std::fs::write(tmp.path().join("TheBazaar"), b"exe").unwrap(); - tmp - } - - fn write(path: &Path, bytes: &[u8]) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, bytes).unwrap(); - } - - /// Three Legacy Roots of known size and the current Data Root. - fn seed_legacy_roots(game: &Path) { - write(&game.join("BazaarPlusPlus/bazaarplusplus.db"), &[0; 10]); - write(&game.join("BazaarPlusPlusV4/a/b/c.png"), &[0; 7]); - write(&game.join("BazaarPlusPlusV4/d.txt"), &[0; 3]); - write(&game.join("BazaarPlusPlusV5/bazaarplusplus.db"), &[0; 100]); - write(&game.join("BazaarPlusPlusV5/Screenshots/run.png"), &[0; 20]); - write( - &game.join(BAZAAR_DATA_DIRECTORY).join("bazaarplusplus.db"), - &[0; 1000], - ); - } - - fn no_settings_dir() -> PathBuf { - PathBuf::from("/nonexistent-installer-settings") - } - - #[test] - fn the_legacy_root_list_never_names_the_current_data_root() { - for root in LegacyRoot::ALL { - assert_ne!(root.directory_name(), BAZAAR_DATA_DIRECTORY); - assert_eq!( - serde_json::to_value(root).unwrap(), - serde_json::json!(root.directory_name()) - ); - assert_eq!( - LegacyRoot::from_directory_name(root.directory_name()), - Some(root) - ); - } - assert_eq!(LegacyRoot::from_directory_name(BAZAAR_DATA_DIRECTORY), None); - } - - #[test] - fn lists_only_present_legacy_root_directories_with_their_sizes() { - let game = tempfile::tempdir().unwrap(); - seed_legacy_roots(game.path()); - // Files beside the roots, named after one, are not roots. - write(&game.path().join("BazaarPlusPlusV5.zip"), &[0; 64]); - write(&game.path().join("BazaarPlusPlusV4.txt"), b"file"); - - let state = legacy_data_state(game.path(), &no_settings_dir()); - - assert_eq!( - state - .roots - .iter() - .map(|root| (root.name, root.size_bytes, root.file_count)) - .collect::>(), - vec![ - (LegacyRoot::Original, 10, 1), - (LegacyRoot::V4, 10, 2), - (LegacyRoot::V5, 120, 2), - ] - ); - assert!(state - .roots - .iter() - .all(|root| root.hard_linked_file_count == 0 && root.unreadable_entry_count == 0)); - } - - #[test] - fn a_file_named_like_a_legacy_root_is_not_listed() { - let game = tempfile::tempdir().unwrap(); - write(&game.path().join("BazaarPlusPlusV5"), b"file"); - - assert!(legacy_data_state(game.path(), &no_settings_dir()) - .roots - .is_empty()); - } - - #[test] - fn the_installer_settings_folder_is_never_a_legacy_root() { - // The installer keeps overlay settings in a `BazaarPlusPlusV4` folder of - // its config directory. Even when that directory is the selected one, - // the folder is neither listed nor deleted. - let config = valid_game_dir(); - let settings = config.path().join("BazaarPlusPlusV4"); - write(&settings.join("stream-overlay-crop.json"), b"{}"); - - let state = legacy_data_state(config.path(), &settings); - assert!(state.roots.is_empty()); - - let refused = delete_legacy_root_blocking_with( - config.path(), - "BazaarPlusPlusV4", - &settings, - &stopped, - ) - .unwrap_err(); - assert_eq!( - refused.into_problem("delete_legacy_root").code, - SemanticProblemCode::InstallActionFailed - ); - assert!(settings.join("stream-overlay-crop.json").is_file()); - } - - #[test] - fn the_real_installer_settings_path_is_the_legacy_overlay_settings_folder() { - assert_eq!( - installer_settings_directory().join("stream-overlay-crop.json"), - crate::services::paths::legacy_overlay_settings_path() - ); - } - - #[cfg(unix)] - #[test] - fn measurement_does_not_follow_symbolic_links_and_counts_hard_links() { - let game = tempfile::tempdir().unwrap(); - let outside = tempfile::tempdir().unwrap(); - write(&outside.path().join("big.bin"), &[0; 4096]); - write(&game.path().join("BazaarPlusPlusV5/own.bin"), &[0; 5]); - std::os::unix::fs::symlink(outside.path(), game.path().join("BazaarPlusPlusV5/outside")) - .unwrap(); - std::fs::hard_link( - game.path().join("BazaarPlusPlusV5/own.bin"), - outside.path().join("linked.bin"), - ) - .unwrap(); - // A symlinked Legacy Root name is not a Legacy Root directory. - std::os::unix::fs::symlink(outside.path(), game.path().join("BazaarPlusPlusV4")).unwrap(); - - let state = legacy_data_state(game.path(), &no_settings_dir()); - - assert_eq!(state.roots.len(), 1); - let root = &state.roots[0]; - assert_eq!(root.name, LegacyRoot::V5); - assert_eq!(root.size_bytes, 5); - assert_eq!(root.file_count, 1); - assert_eq!(root.hard_linked_file_count, 1); - } - - #[test] - fn installed_mod_data_root_requires_the_current_name_in_the_contract() { - let game = tempfile::tempdir().unwrap(); - let contract = game.path().join(INSTALLED_HISTORY_DATABASE_CONTRACT); - - // No mod contract at all. - assert_eq!( - installed_mod_data_root(game.path()), - InstalledModDataRoot::ReinstallRequired - ); - - // 5.7.0 shipped the contract without `dataRootDirectoryName`. - write( - &contract, - br#"{ "formatVersion": 1, "historyDatabaseUserVersion": 3 }"#, - ); - assert_eq!( - installed_mod_data_root(game.path()), - InstalledModDataRoot::ReinstallRequired - ); - - // A contract naming another directory. - write( - &contract, - br#"{ "formatVersion": 1, "dataRootDirectoryName": "BazaarPlusPlusV5" }"#, - ); - assert_eq!( - installed_mod_data_root(game.path()), - InstalledModDataRoot::ReinstallRequired - ); - - // Corrupt JSON. - write(&contract, br#"{ "dataRootDirectoryName": "#); - assert_eq!( - installed_mod_data_root(game.path()), - InstalledModDataRoot::ReinstallRequired - ); - - // The contract the current mod ships. - let current = std::fs::read( - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json"), - ) - .unwrap(); - write(&contract, ¤t); - assert_eq!( - installed_mod_data_root(game.path()), - InstalledModDataRoot::Current - ); - } - - #[test] - fn deletes_only_the_confirmed_root_and_reports_an_absent_one() { - let game = valid_game_dir(); - seed_legacy_roots(game.path()); - - let result = delete_legacy_root_blocking_with( - game.path(), - "BazaarPlusPlusV4", - &no_settings_dir(), - &stopped, - ) - .unwrap(); - - assert!(result.removed); - assert!(!game.path().join("BazaarPlusPlusV4").exists()); - assert!(game.path().join("BazaarPlusPlus").is_dir()); - assert!(game.path().join("BazaarPlusPlusV5").is_dir()); - assert!(game.path().join(BAZAAR_DATA_DIRECTORY).is_dir()); - assert_eq!( - result - .state - .roots - .iter() - .map(|root| root.name) - .collect::>(), - vec![LegacyRoot::Original, LegacyRoot::V5] - ); - - let again = delete_legacy_root_blocking_with( - game.path(), - "BazaarPlusPlusV4", - &no_settings_dir(), - &stopped, - ) - .unwrap(); - assert!(!again.removed); - } - - #[test] - fn a_name_outside_the_list_is_refused_and_nothing_changes() { - let game = valid_game_dir(); - seed_legacy_roots(game.path()); - write( - &game.path().join("BepInEx/plugins/BazaarPlusPlus.dll"), - b"bpp", - ); - - for name in [ - BAZAAR_DATA_DIRECTORY, - "BepInEx", - "bazaarplusplusv5", - "BazaarPlusPlusV5/Screenshots", - "../BazaarPlusPlusV5", - "", - ] { - let refused = - delete_legacy_root_blocking_with(game.path(), name, &no_settings_dir(), &stopped) - .unwrap_err(); - let problem = refused.into_problem("delete_legacy_root"); - assert_eq!(problem.code, SemanticProblemCode::InstallActionFailed); - assert_eq!( - problem.params.get("operation").map(String::as_str), - Some("delete_legacy_root") - ); - } - - assert!(game - .path() - .join(BAZAAR_DATA_DIRECTORY) - .join("bazaarplusplus.db") - .is_file()); - assert!(game - .path() - .join("BepInEx/plugins/BazaarPlusPlus.dll") - .is_file()); - assert!(game - .path() - .join("BazaarPlusPlusV5/Screenshots/run.png") - .is_file()); - assert_eq!( - legacy_data_state(game.path(), &no_settings_dir()) - .roots - .len(), - 3 - ); - } - - #[test] - fn deletion_refuses_while_the_game_runs_or_cannot_be_inspected() { - fn running(_: &Path) -> Result { - Ok(true) - } - fn unknown(_: &Path) -> Result { - Err("cannot inspect processes".to_string()) - } - type Probe = fn(&Path) -> Result; - let probes: [Probe; 2] = [running, unknown]; - for refusing in probes { - let game = valid_game_dir(); - seed_legacy_roots(game.path()); - - let refused = delete_legacy_root_blocking_with( - game.path(), - "BazaarPlusPlusV5", - &no_settings_dir(), - &refusing, - ) - .unwrap_err(); - - assert_eq!( - refused.into_problem("delete_legacy_root").code, - SemanticProblemCode::LegacyDeleteBlockedByGame - ); - assert!(game - .path() - .join("BazaarPlusPlusV5/bazaarplusplus.db") - .is_file()); - assert!(game - .path() - .join("BazaarPlusPlusV5/Screenshots/run.png") - .is_file()); - } - } - - #[tokio::test] - async fn locked_deletion_refuses_while_the_game_runs() { - let game = valid_game_dir(); - seed_legacy_roots(game.path()); - let lock = DataMaintenanceLock::default(); - let game_path = game.path().to_path_buf(); - - let refused = lock - .run_blocking(move || { - delete_legacy_root_blocking_with( - &game_path, - "BazaarPlusPlusV5", - &no_settings_dir(), - &|_: &Path| Ok(true), - ) - }) - .await - .unwrap() - .unwrap_err(); - - assert_eq!( - refused.into_problem("delete_legacy_root").code, - SemanticProblemCode::LegacyDeleteBlockedByGame - ); - assert!(game.path().join("BazaarPlusPlusV5").is_dir()); - } - - #[tokio::test] - async fn reset_leaves_every_legacy_root_in_place() { - let game = valid_game_dir(); - seed_legacy_roots(game.path()); - - let removed = crate::services::bepinex::reset_bpp_data_with( - &DataMaintenanceLock::default(), - &crate::stream::runtime::StreamRuntime::default(), - game.path().to_string_lossy().into_owned(), - stopped, - ) - .await - .unwrap(); - - assert!(removed); - assert!(!game.path().join(BAZAAR_DATA_DIRECTORY).exists()); - let state = legacy_data_state(game.path(), &no_settings_dir()); - assert_eq!( - state - .roots - .iter() - .map(|root| (root.name, root.size_bytes)) - .collect::>(), - vec![ - (LegacyRoot::Original, 10), - (LegacyRoot::V4, 10), - (LegacyRoot::V5, 120), - ] - ); - } - - #[test] - fn listing_and_measuring_never_delete() { - let game = valid_game_dir(); - seed_legacy_roots(game.path()); - write( - &crate::v5_import::v5_import_marker_path(game.path()), - b"imported", - ); - - for _ in 0..2 { - let state = legacy_data_state(game.path(), &no_settings_dir()); - assert_eq!(state.roots.len(), 3); - } - for root in LegacyRoot::ALL { - assert!(root.path_in(game.path()).is_dir()); - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/mod.rs b/bazaarplusplus-installer/src-tauri/src/services/mod.rs deleted file mode 100644 index 07d3851..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -pub(crate) mod action_error; -pub mod bepinex; -pub(crate) mod data_maintenance; -pub mod detect; -pub(crate) mod file_manifest; -pub mod game_path; -pub mod game_process; -pub mod history; -pub mod install; -pub(crate) mod legacy_data; -pub mod paths; -pub(crate) mod placement; -pub mod process_snapshot; -pub mod selected_game_installation; -pub mod startup; -pub mod steam; -pub mod vdf; - -macro_rules! debug_log { - ($($arg:tt)*) => { - #[cfg(debug_assertions)] - println!($($arg)*); - }; -} - -macro_rules! debug_error { - ($($arg:tt)*) => { - #[cfg(debug_assertions)] - eprintln!($($arg)*); - }; -} - -pub(crate) use debug_error; -pub(crate) use debug_log; diff --git a/bazaarplusplus-installer/src-tauri/src/services/paths.rs b/bazaarplusplus-installer/src-tauri/src/services/paths.rs deleted file mode 100644 index bfd9f7a..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/paths.rs +++ /dev/null @@ -1,68 +0,0 @@ -use std::path::{Path, PathBuf}; - -use crate::config::{ - BAZAAR_DATA_DIRECTORY, COMBAT_REPLAYS_DIRECTORY, COMBAT_REPLAY_VIDEOS_DIRECTORY, - DATABASE_FILE_NAME, INSTALLER_STATE_DIRECTORY, SCREENSHOTS_DIRECTORY, -}; - -const LEGACY_OVERLAY_SETTINGS_DIRECTORY: &str = "BazaarPlusPlusV4"; -const OVERLAY_CACHE_DIRECTORY: &str = "stream-overlay-cache"; -const OVERLAY_SETTINGS_FILE_NAME: &str = "stream-overlay-crop.json"; - -pub fn bpp_data_dir(game_path: &Path) -> PathBuf { - game_path.join(BAZAAR_DATA_DIRECTORY) -} - -pub fn database_path(game_path: &Path) -> PathBuf { - bpp_data_dir(game_path).join(DATABASE_FILE_NAME) -} - -pub fn screenshots_dir(game_path: &Path) -> PathBuf { - screenshots_dir_in(&bpp_data_dir(game_path)) -} - -pub fn combat_replay_videos_dir(game_path: &Path) -> PathBuf { - combat_replay_videos_dir_in(&bpp_data_dir(game_path)) -} - -/// The `*_dir_in` variants resolve against an explicit Data Root, which need -/// not be the current game's: a Legacy Root such as `BazaarPlusPlusV5/` is -/// laid out the same way. -pub fn screenshots_dir_in(data_root: &Path) -> PathBuf { - data_root.join(SCREENSHOTS_DIRECTORY) -} - -pub fn combat_replay_videos_dir_in(data_root: &Path) -> PathBuf { - data_root.join(COMBAT_REPLAY_VIDEOS_DIRECTORY) -} - -pub fn combat_replays_dir_in(data_root: &Path) -> PathBuf { - data_root.join(COMBAT_REPLAYS_DIRECTORY) -} - -pub fn overlay_cache_dir() -> PathBuf { - let base = dirs::cache_dir() - .or_else(dirs::config_dir) - .or_else(dirs::data_local_dir) - .unwrap_or_else(std::env::temp_dir); - base.join(INSTALLER_STATE_DIRECTORY) - .join(OVERLAY_CACHE_DIRECTORY) -} - -fn overlay_settings_base_dir() -> PathBuf { - dirs::config_dir() - .or_else(dirs::data_local_dir) - .unwrap_or_else(std::env::temp_dir) -} - -pub fn overlay_settings_path() -> PathBuf { - overlay_settings_base_dir() - .join(INSTALLER_STATE_DIRECTORY) - .join(OVERLAY_SETTINGS_FILE_NAME) -} - -pub fn legacy_overlay_settings_path() -> PathBuf { - overlay_settings_base_dir() - .join(LEGACY_OVERLAY_SETTINGS_DIRECTORY) - .join(OVERLAY_SETTINGS_FILE_NAME) -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/placement.rs b/bazaarplusplus-installer/src-tauri/src/services/placement.rs deleted file mode 100644 index 1ddd41c..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/placement.rs +++ /dev/null @@ -1,827 +0,0 @@ -//! Places source files at target paths without overwriting anything, and can -//! undo exactly what it placed. -//! -//! A target on the source's volume shares the source's data: a `clonefile` -//! clone on macOS, otherwise a hard link. Anything else is copied into a -//! partial file next to the target and renamed into place, so an interrupted -//! copy never leaves a file at the target path. An existing target is accepted -//! only when its size and sha256 match the source. Free space for every copy is -//! checked before the first write. - -use std::collections::{BTreeMap, HashSet}; -use std::fmt; -use std::fs; -use std::io::{self, Read}; -use std::path::{Path, PathBuf}; - -use sha2::{Digest, Sha256}; - -/// One file to place: `source` must be a regular file. -#[derive(Debug, Clone)] -pub(crate) struct PlacementRequest { - pub source: PathBuf, - pub target: PathBuf, -} - -/// How a target came to hold the source's bytes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum PlacementMethod { - Clone, - HardLink, - Copy, - /// The target already held identical bytes; nothing was written. - AlreadyPresent, -} - -/// A placement that shares the source's data instead of copying it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum LinkKind { - #[cfg_attr(not(target_os = "macos"), allow(dead_code))] - Clone, - HardLink, -} - -#[derive(Debug)] -pub(crate) enum PlacementError { - /// The target exists with different bytes; it is left untouched. - TargetConflict { - target: PathBuf, - }, - /// The copies bound for one volume need more space than it has. - InsufficientSpace { - volume: PathBuf, - required: u64, - available: u64, - }, - Io { - path: PathBuf, - source: io::Error, - }, -} - -impl fmt::Display for PlacementError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::TargetConflict { target } => { - write!( - f, - "{} already exists with different content", - target.display() - ) - } - Self::InsufficientSpace { - volume, - required, - available, - } => write!( - f, - "{} needs {required} bytes free but has {available}", - volume.display() - ), - Self::Io { path, source } => write!(f, "{}: {source}", path.display()), - } - } -} - -impl std::error::Error for PlacementError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Io { source, .. } => Some(source), - _ => None, - } - } -} - -fn io_error(path: &Path) -> impl FnOnce(io::Error) -> PlacementError + '_ { - move |source| PlacementError::Io { - path: path.to_path_buf(), - source, - } -} - -/// The filesystem operations whose outcome depends on the platform or volume. -pub(crate) trait PlacementBackend { - /// A key equal for two existing paths exactly when they share a volume. - fn volume_id(&self, existing: &Path) -> io::Result; - /// Bytes the current user may still write on the volume holding `existing`. - fn available_space(&self, existing: &Path) -> io::Result; - /// Creates `target` sharing `source`'s data, or fails when the volume - /// cannot. - fn link(&self, source: &Path, target: &Path) -> io::Result; - /// Writes `source`'s bytes durably to `partial`, replacing any content. - fn copy(&self, source: &Path, partial: &Path) -> io::Result<()>; -} - -/// The real filesystem. -#[derive(Debug, Default, Clone, Copy)] -pub(crate) struct SystemBackend; - -impl PlacementBackend for SystemBackend { - fn volume_id(&self, existing: &Path) -> io::Result { - platform::volume_id(existing) - } - - fn available_space(&self, existing: &Path) -> io::Result { - platform::available_space(existing) - } - - fn link(&self, source: &Path, target: &Path) -> io::Result { - #[cfg(target_os = "macos")] - if platform::clone_file(source, target).is_ok() { - return Ok(LinkKind::Clone); - } - fs::hard_link(source, target).map(|()| LinkKind::HardLink) - } - - fn copy(&self, source: &Path, partial: &Path) -> io::Result<()> { - fs::copy(source, partial)?; - // Windows flushes only through a handle opened for writing. - fs::OpenOptions::new().write(true).open(partial)?.sync_all() - } -} - -#[cfg(unix)] -mod platform { - use std::ffi::CString; - use std::io; - use std::os::unix::ffi::OsStrExt; - use std::os::unix::fs::MetadataExt; - use std::path::Path; - - fn c_path(path: &Path) -> io::Result { - Ok(CString::new(path.as_os_str().as_bytes())?) - } - - pub(super) fn volume_id(existing: &Path) -> io::Result { - Ok(std::fs::metadata(existing)?.dev().to_string()) - } - - // `fsblkcnt_t` and `c_ulong` are not `u64` on every unix target. - #[allow(clippy::unnecessary_cast)] - pub(super) fn available_space(existing: &Path) -> io::Result { - let path = c_path(existing)?; - let mut stat = std::mem::MaybeUninit::::zeroed(); - // SAFETY: `path` is NUL-terminated and `stat` is a writable statvfs. - if unsafe { libc::statvfs(path.as_ptr(), stat.as_mut_ptr()) } != 0 { - return Err(io::Error::last_os_error()); - } - // SAFETY: statvfs returned 0, so it filled the struct. - let stat = unsafe { stat.assume_init() }; - Ok((stat.f_bavail as u64).saturating_mul(stat.f_frsize as u64)) - } - - #[cfg(target_os = "macos")] - pub(super) fn clone_file(source: &Path, target: &Path) -> io::Result<()> { - let source = c_path(source)?; - let target = c_path(target)?; - // SAFETY: both paths are NUL-terminated and outlive the call. - if unsafe { libc::clonefile(source.as_ptr(), target.as_ptr(), 0) } == 0 { - Ok(()) - } else { - Err(io::Error::last_os_error()) - } - } -} - -#[cfg(windows)] -mod platform { - use std::io; - use std::os::windows::ffi::OsStrExt; - use std::path::Path; - - use windows::core::PCWSTR; - use windows::Win32::Storage::FileSystem::{GetDiskFreeSpaceExW, GetVolumePathNameW}; - - fn wide(path: &Path) -> Vec { - path.as_os_str().encode_wide().chain(Some(0)).collect() - } - - pub(super) fn volume_id(existing: &Path) -> io::Result { - let path = wide(existing); - // The volume path is a prefix of the input, so the input's length bounds it. - let mut volume = vec![0u16; path.len().max(261)]; - // SAFETY: `path` is NUL-terminated and `volume` is a writable buffer. - unsafe { GetVolumePathNameW(PCWSTR(path.as_ptr()), &mut volume) }?; - let len = volume.iter().position(|&c| c == 0).unwrap_or(volume.len()); - Ok(String::from_utf16_lossy(&volume[..len]).to_lowercase()) - } - - pub(super) fn available_space(existing: &Path) -> io::Result { - let path = wide(existing); - let mut available = 0u64; - // SAFETY: `path` is NUL-terminated and `available` outlives the call. - unsafe { - GetDiskFreeSpaceExW(PCWSTR(path.as_ptr()), Some(&raw mut available), None, None) - }?; - Ok(available) - } -} - -#[derive(Debug, Clone, Copy)] -enum Plan { - AlreadyPresent, - Link, - Copy, -} - -#[derive(Debug)] -enum Created { - File(PathBuf), - Directory(PathBuf), -} - -/// Places files and journals every path it creates so `rollback` can remove -/// them again. -pub(crate) struct Placer { - backend: B, - created: Vec, -} - -impl Placer { - pub(crate) fn new(backend: B) -> Self { - Self { - backend, - created: Vec::new(), - } - } - - /// Every file and directory this placer created, in creation order. - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn created_paths(&self) -> impl Iterator { - self.created.iter().map(|created| match created { - Created::File(path) | Created::Directory(path) => path.as_path(), - }) - } - - /// Places every request, or fails before the first write when a target - /// conflicts or a volume lacks space for its copies. A failure after - /// writing began leaves the journal intact for `rollback`. - pub(crate) fn place( - &mut self, - requests: &[PlacementRequest], - ) -> Result, PlacementError> { - let mut plans = Vec::with_capacity(requests.len()); - // Volume id -> (an existing path on it, bytes still to copy there). - let mut pending: BTreeMap = BTreeMap::new(); - let mut targets = HashSet::new(); - for request in requests { - if !targets.insert(request.target.as_path()) { - return Err(PlacementError::Io { - path: request.target.clone(), - source: io::Error::new(io::ErrorKind::InvalidInput, "duplicate target"), - }); - } - let (plan, volume, anchor, len) = self.plan(request)?; - if matches!(plan, Plan::Link | Plan::Copy) { - let entry = pending.entry(volume).or_insert((anchor, 0)); - if matches!(plan, Plan::Copy) { - entry.1 += len; - } - } - plans.push((plan, len)); - } - for (anchor, required) in pending.values() { - self.ensure_space(anchor, *required)?; - } - - let mut methods = Vec::with_capacity(requests.len()); - for (request, (plan, len)) in requests.iter().zip(plans) { - let method = match plan { - Plan::AlreadyPresent => PlacementMethod::AlreadyPresent, - Plan::Link => { - self.create_parents(&request.target)?; - match self.backend.link(&request.source, &request.target) { - Ok(kind) => { - self.created.push(Created::File(request.target.clone())); - match kind { - LinkKind::Clone => PlacementMethod::Clone, - LinkKind::HardLink => PlacementMethod::HardLink, - } - } - Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { - return Err(PlacementError::TargetConflict { - target: request.target.clone(), - }); - } - Err(_) => { - // The volume refused to share data (FAT, exFAT, a - // network share): this file now needs real space on - // top of the copies still pending there. - let volume = self.anchor_volume(&request.target)?; - let entry = pending.entry(volume.0).or_insert((volume.1, 0)); - entry.1 += len; - self.ensure_space(&entry.0, entry.1)?; - self.copy_into_place(request)?; - entry.1 -= len; - PlacementMethod::Copy - } - } - } - Plan::Copy => { - self.create_parents(&request.target)?; - self.copy_into_place(request)?; - let volume = self.anchor_volume(&request.target)?; - if let Some(entry) = pending.get_mut(&volume.0) { - entry.1 = entry.1.saturating_sub(len); - } - PlacementMethod::Copy - } - }; - methods.push(method); - } - Ok(methods) - } - - /// Removes every path this placer created, newest first. Keeps going past - /// failures and reports the first; a directory that gained foreign files - /// is left in place. - pub(crate) fn rollback(&mut self) -> Result<(), PlacementError> { - let mut first_error = None; - while let Some(created) = self.created.pop() { - let (path, result) = match &created { - Created::File(path) => (path, fs::remove_file(path)), - Created::Directory(path) => (path, fs::remove_dir(path)), - }; - match result { - Ok(()) => {} - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => { - first_error.get_or_insert_with(|| io_error(path)(error)); - } - } - } - first_error.map_or(Ok(()), Err) - } - - fn plan( - &self, - request: &PlacementRequest, - ) -> Result<(Plan, String, PathBuf, u64), PlacementError> { - let source = fs::metadata(&request.source).map_err(io_error(&request.source))?; - if !source.is_file() { - return Err(PlacementError::Io { - path: request.source.clone(), - source: io::Error::new(io::ErrorKind::InvalidInput, "source is not a file"), - }); - } - let len = source.len(); - match fs::symlink_metadata(&request.target) { - Ok(target) => { - if target.is_file() - && target.len() == len - && sha256(&request.source)? == sha256(&request.target)? - { - return Ok((Plan::AlreadyPresent, String::new(), PathBuf::new(), len)); - } - return Err(PlacementError::TargetConflict { - target: request.target.clone(), - }); - } - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => return Err(io_error(&request.target)(error)), - } - let (volume, anchor) = self.anchor_volume(&request.target)?; - let source_volume = self - .backend - .volume_id(&request.source) - .map_err(io_error(&request.source))?; - let plan = if source_volume == volume { - Plan::Link - } else { - Plan::Copy - }; - Ok((plan, volume, anchor, len)) - } - - /// The volume id of `target`'s nearest existing ancestor, and that ancestor. - fn anchor_volume(&self, target: &Path) -> Result<(String, PathBuf), PlacementError> { - let mut anchor = target.parent().unwrap_or(target); - while !anchor.exists() { - match anchor.parent() { - Some(parent) => anchor = parent, - None => break, - } - } - let volume = self.backend.volume_id(anchor).map_err(io_error(anchor))?; - Ok((volume, anchor.to_path_buf())) - } - - fn ensure_space(&self, anchor: &Path, required: u64) -> Result<(), PlacementError> { - if required == 0 { - return Ok(()); - } - let available = self - .backend - .available_space(anchor) - .map_err(io_error(anchor))?; - if available < required { - return Err(PlacementError::InsufficientSpace { - volume: anchor.to_path_buf(), - required, - available, - }); - } - Ok(()) - } - - fn create_parents(&mut self, target: &Path) -> Result<(), PlacementError> { - let mut missing = Vec::new(); - let mut directory = target.parent(); - while let Some(path) = directory { - if path.as_os_str().is_empty() || path.exists() { - break; - } - missing.push(path); - directory = path.parent(); - } - for path in missing.into_iter().rev() { - match fs::create_dir(path) { - Ok(()) => self.created.push(Created::Directory(path.to_path_buf())), - Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {} - Err(error) => return Err(io_error(path)(error)), - } - } - Ok(()) - } - - /// Copies into a partial file beside the target, then renames it into - /// place, so the target path only ever holds complete bytes. A partial - /// file left by an interrupted earlier attempt is overwritten. - fn copy_into_place(&mut self, request: &PlacementRequest) -> Result<(), PlacementError> { - let partial = partial_path(&request.target); - if let Err(error) = self.backend.copy(&request.source, &partial) { - let _ = fs::remove_file(&partial); - return Err(io_error(&partial)(error)); - } - // Planning saw no target; refuse to replace one that appeared since. - if fs::symlink_metadata(&request.target).is_ok() { - let _ = fs::remove_file(&partial); - return Err(PlacementError::TargetConflict { - target: request.target.clone(), - }); - } - if let Err(error) = fs::rename(&partial, &request.target) { - let _ = fs::remove_file(&partial); - return Err(io_error(&request.target)(error)); - } - self.created.push(Created::File(request.target.clone())); - Ok(()) - } -} - -fn partial_path(target: &Path) -> PathBuf { - let mut name = std::ffi::OsString::from("."); - name.push(target.file_name().unwrap_or_default()); - name.push(".bpp-partial"); - target.with_file_name(name) -} - -fn sha256(path: &Path) -> Result<[u8; 32], PlacementError> { - let mut file = fs::File::open(path).map_err(io_error(path))?; - let mut digest = Sha256::new(); - let mut buffer = [0; 64 * 1024]; - loop { - let count = file.read(&mut buffer).map_err(io_error(path))?; - if count == 0 { - break; - } - digest.update(&buffer[..count]); - } - Ok(digest.finalize().into()) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::cell::Cell; - use std::io::Write; - - /// The real filesystem with optional injected volume layout, link - /// support, free space and copy interruption. - #[derive(Default)] - struct TestBackend { - separate_volumes: bool, - refuse_links: bool, - available: Option, - interrupt_copy: bool, - writes: Cell, - } - - impl PlacementBackend for TestBackend { - fn volume_id(&self, existing: &Path) -> io::Result { - if self.separate_volumes { - // Sources live under `source/`, targets under `target/`. - let side = existing - .components() - .any(|part| part.as_os_str() == "source"); - return Ok(if side { "source" } else { "target" }.to_string()); - } - SystemBackend.volume_id(existing) - } - - fn available_space(&self, existing: &Path) -> io::Result { - match self.available { - Some(available) => Ok(available), - None => SystemBackend.available_space(existing), - } - } - - fn link(&self, source: &Path, target: &Path) -> io::Result { - if self.refuse_links { - return Err(io::Error::new(io::ErrorKind::Unsupported, "no links here")); - } - self.writes.set(self.writes.get() + 1); - SystemBackend.link(source, target) - } - - fn copy(&self, source: &Path, partial: &Path) -> io::Result<()> { - self.writes.set(self.writes.get() + 1); - if self.interrupt_copy { - let bytes = fs::read(source)?; - let mut file = fs::File::create(partial)?; - file.write_all(&bytes[..bytes.len() / 2])?; - return Err(io::Error::new(io::ErrorKind::Interrupted, "copy cut short")); - } - SystemBackend.copy(source, partial) - } - } - - struct Fixture { - _root: tempfile::TempDir, - source: PathBuf, - target: PathBuf, - } - - fn fixture() -> Fixture { - let root = tempfile::tempdir().unwrap(); - let source = root.path().join("source"); - let target = root.path().join("target"); - fs::create_dir_all(source.join("Screenshots")).unwrap(); - fs::create_dir_all(&target).unwrap(); - fs::write(source.join("a.bin"), vec![7u8; 4096]).unwrap(); - fs::write(source.join("Screenshots/run.png"), b"png bytes").unwrap(); - fs::write(target.join("keep.txt"), b"user data").unwrap(); - Fixture { - source, - target, - _root: root, - } - } - - fn requests(fixture: &Fixture) -> Vec { - ["a.bin", "Screenshots/run.png"] - .into_iter() - .map(|relative| PlacementRequest { - source: fixture.source.join(relative), - target: fixture.target.join("nested").join(relative), - }) - .collect() - } - - /// Every directory and file under `root` with its bytes. - fn snapshot(root: &Path) -> Vec<(PathBuf, Option>)> { - fn walk(path: &Path, out: &mut Vec<(PathBuf, Option>)>) { - for entry in fs::read_dir(path).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { - out.push((path.clone(), None)); - walk(&path, out); - } else { - out.push((path.clone(), Some(fs::read(&path).unwrap()))); - } - } - } - let mut out = Vec::new(); - walk(root, &mut out); - out.sort(); - out - } - - fn assert_placed(fixture: &Fixture) { - for request in requests(fixture) { - assert_eq!( - fs::read(&request.target).unwrap(), - fs::read(&request.source).unwrap() - ); - } - } - - #[test] - fn same_volume_shares_data_instead_of_copying() { - let fixture = fixture(); - let mut placer = Placer::new(SystemBackend); - - let methods = placer.place(&requests(&fixture)).unwrap(); - - #[cfg(not(target_os = "macos"))] - assert_eq!(methods, [PlacementMethod::HardLink; 2]); - #[cfg(target_os = "macos")] - assert!(methods - .iter() - .all(|m| matches!(m, PlacementMethod::Clone | PlacementMethod::HardLink))); - assert_placed(&fixture); - } - - #[cfg(all(unix, not(target_os = "macos")))] - #[test] - fn hard_link_shares_the_source_inode() { - use std::os::unix::fs::MetadataExt; - let fixture = fixture(); - let request = &requests(&fixture)[..1]; - let mut placer = Placer::new(SystemBackend); - - assert_eq!(placer.place(request).unwrap(), [PlacementMethod::HardLink]); - - let source = fs::metadata(&request[0].source).unwrap(); - let target = fs::metadata(&request[0].target).unwrap(); - assert_eq!(source.ino(), target.ino()); - } - - #[test] - fn refused_link_falls_back_to_copy() { - let fixture = fixture(); - let mut placer = Placer::new(TestBackend { - refuse_links: true, - ..TestBackend::default() - }); - - let methods = placer.place(&requests(&fixture)).unwrap(); - - assert_eq!(methods, [PlacementMethod::Copy; 2]); - assert_placed(&fixture); - } - - #[test] - fn other_volume_copies() { - let fixture = fixture(); - let mut placer = Placer::new(TestBackend { - separate_volumes: true, - ..TestBackend::default() - }); - - let methods = placer.place(&requests(&fixture)).unwrap(); - - assert_eq!(methods, [PlacementMethod::Copy; 2]); - assert_placed(&fixture); - } - - #[test] - fn interrupted_copy_leaves_no_target_and_a_retry_completes_it() { - let fixture = fixture(); - let requests = requests(&fixture); - let mut interrupted = Placer::new(TestBackend { - separate_volumes: true, - interrupt_copy: true, - ..TestBackend::default() - }); - - assert!(matches!( - interrupted.place(&requests), - Err(PlacementError::Io { .. }) - )); - assert!(!requests[0].target.exists()); - // A crash would also skip cleanup: leave a half-written partial file. - fs::write(partial_path(&requests[0].target), [7u8; 10]).unwrap(); - - let mut retry = Placer::new(TestBackend { - separate_volumes: true, - ..TestBackend::default() - }); - let methods = retry.place(&requests).unwrap(); - - assert_eq!(methods, [PlacementMethod::Copy; 2]); - assert_placed(&fixture); - assert!(!partial_path(&requests[0].target).exists()); - } - - #[test] - fn identical_existing_target_is_skipped() { - let fixture = fixture(); - let requests = requests(&fixture); - fs::create_dir_all(requests[0].target.parent().unwrap()).unwrap(); - fs::copy(&requests[0].source, &requests[0].target).unwrap(); - let mut placer = Placer::new(TestBackend::default()); - - let methods = placer.place(&requests).unwrap(); - - assert_eq!(methods[0], PlacementMethod::AlreadyPresent); - assert!(placer - .created_paths() - .all(|path| path != requests[0].target)); - assert_placed(&fixture); - } - - #[test] - fn different_existing_target_fails_before_writing() { - let fixture = fixture(); - let requests = requests(&fixture); - // Same size, different bytes: only the hash tells them apart. - let target = &requests[1].target; - fs::create_dir_all(target.parent().unwrap()).unwrap(); - fs::write(target, b"PNG BYTES").unwrap(); - let before = snapshot(&fixture.target); - let backend = TestBackend::default(); - let mut placer = Placer::new(backend); - - let error = placer.place(&requests).unwrap_err(); - - assert!(matches!(error, PlacementError::TargetConflict { target: t } if t == *target)); - assert_eq!(snapshot(&fixture.target), before); - assert_eq!(placer.created_paths().count(), 0); - } - - #[test] - fn rollback_restores_the_tree_byte_for_byte() { - for backend in [ - TestBackend::default(), - TestBackend { - separate_volumes: true, - ..TestBackend::default() - }, - ] { - let fixture = fixture(); - let requests = requests(&fixture); - // One target already holds identical bytes and must survive rollback. - fs::create_dir_all(requests[0].target.parent().unwrap()).unwrap(); - fs::copy(&requests[0].source, &requests[0].target).unwrap(); - let before = snapshot(&fixture.target); - let sources = snapshot(&fixture.source); - let mut placer = Placer::new(backend); - - placer.place(&requests).unwrap(); - assert_ne!(snapshot(&fixture.target), before); - placer.rollback().unwrap(); - - assert_eq!(snapshot(&fixture.target), before); - assert_eq!(snapshot(&fixture.source), sources); - assert_eq!(placer.created_paths().count(), 0); - } - } - - #[test] - fn insufficient_space_fails_before_writing() { - let fixture = fixture(); - let before = snapshot(&fixture.target); - let mut placer = Placer::new(TestBackend { - separate_volumes: true, - available: Some(4096), - ..TestBackend::default() - }); - - let error = placer.place(&requests(&fixture)).unwrap_err(); - - assert!(matches!( - error, - PlacementError::InsufficientSpace { - required: 4105, - available: 4096, - .. - } - )); - assert_eq!(placer.backend.writes.get(), 0); - assert_eq!(snapshot(&fixture.target), before); - } - - #[test] - fn links_need_no_free_space() { - let fixture = fixture(); - let mut placer = Placer::new(TestBackend { - available: Some(0), - ..TestBackend::default() - }); - - placer.place(&requests(&fixture)).unwrap(); - - assert_placed(&fixture); - } - - #[test] - fn refused_link_rechecks_space_before_copying() { - let fixture = fixture(); - let mut placer = Placer::new(TestBackend { - refuse_links: true, - available: Some(100), - ..TestBackend::default() - }); - - let error = placer.place(&requests(&fixture)).unwrap_err(); - - assert!(matches!( - error, - PlacementError::InsufficientSpace { required: 4096, .. } - )); - assert!(!requests(&fixture)[0].target.exists()); - placer.rollback().unwrap(); - assert!(!fixture.target.join("nested").exists()); - } - - #[test] - fn real_volume_reports_free_space() { - let root = tempfile::tempdir().unwrap(); - assert!(SystemBackend.available_space(root.path()).unwrap() > 0); - assert_eq!( - SystemBackend.volume_id(root.path()).unwrap(), - SystemBackend.volume_id(&root.path().join(".")).unwrap() - ); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/process_snapshot.rs b/bazaarplusplus-installer/src-tauri/src/services/process_snapshot.rs deleted file mode 100644 index 542c93d..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/process_snapshot.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! "Is a process named X running?" without spawning `tasklist`. -//! -//! On Windows this walks an in-process toolhelp snapshot instead of launching -//! the `tasklist` subprocess. That removes the per-call `CreateProcess` + -//! console-window flash + Defender scan of `tasklist.exe` from the flows that -//! close Steam (launch-option writes) and guard destructive resets. - -/// Case-insensitive comparison of a process image name (e.g. `"Steam.exe"`) -/// against a target (e.g. `"steam.exe"`). -#[cfg(target_os = "windows")] -pub(crate) fn image_name_matches(candidate: &str, target: &str) -> bool { - candidate.eq_ignore_ascii_case(target) -} - -/// Return whether any running process has the given image name. Windows-only; -/// callers on other platforms use their own probe (e.g. `pgrep`). -#[cfg(target_os = "windows")] -pub(crate) fn process_is_running(target: &str) -> Result { - use windows::Win32::Foundation::CloseHandle; - use windows::Win32::System::Diagnostics::ToolHelp::{ - CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, - TH32CS_SNAPPROCESS, - }; - - // SAFETY: a process snapshot is created, iterated with a correctly-sized - // PROCESSENTRY32W, and the snapshot handle is always closed before return. - unsafe { - let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) - .map_err(|err| format!("Failed to inspect process state: {err}"))?; - - let mut entry = PROCESSENTRY32W { - dwSize: std::mem::size_of::() as u32, - ..Default::default() - }; - - let mut found = false; - if Process32FirstW(snapshot, &mut entry).is_ok() { - loop { - if image_name_matches(&image_name_from_entry(&entry), target) { - found = true; - break; - } - if Process32NextW(snapshot, &mut entry).is_err() { - break; - } - } - } - - let _ = CloseHandle(snapshot); - Ok(found) - } -} - -/// Terminate every running process with the given image name and return how -/// many were killed. Windows-only. Used to clear a game process that outlived -/// its window and still holds the mod database open; a process that exits on -/// its own between the snapshot and the kill is not an error. -#[cfg(target_os = "windows")] -pub(crate) fn terminate_processes(target: &str) -> Result { - use windows::Win32::Foundation::CloseHandle; - use windows::Win32::System::Diagnostics::ToolHelp::{ - CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, - TH32CS_SNAPPROCESS, - }; - use windows::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE}; - - // SAFETY: the snapshot is iterated with a correctly-sized PROCESSENTRY32W and - // every handle opened here is closed before the loop advances; the snapshot - // handle is closed before return. - unsafe { - let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) - .map_err(|err| format!("Failed to inspect process state: {err}"))?; - - let mut entry = PROCESSENTRY32W { - dwSize: std::mem::size_of::() as u32, - ..Default::default() - }; - - let mut terminated = 0u32; - if Process32FirstW(snapshot, &mut entry).is_ok() { - loop { - if image_name_matches(&image_name_from_entry(&entry), target) { - if let Ok(process) = OpenProcess(PROCESS_TERMINATE, false, entry.th32ProcessID) - { - if TerminateProcess(process, 1).is_ok() { - terminated += 1; - } - let _ = CloseHandle(process); - } - } - if Process32NextW(snapshot, &mut entry).is_err() { - break; - } - } - } - - let _ = CloseHandle(snapshot); - Ok(terminated) - } -} - -/// Decode the NUL-terminated UTF-16 `szExeFile` field into a Rust string. -#[cfg(target_os = "windows")] -fn image_name_from_entry( - entry: &windows::Win32::System::Diagnostics::ToolHelp::PROCESSENTRY32W, -) -> String { - let name = &entry.szExeFile; - let len = name.iter().position(|&c| c == 0).unwrap_or(name.len()); - String::from_utf16_lossy(&name[..len]) -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/selected_game_installation.rs b/bazaarplusplus-installer/src-tauri/src/services/selected_game_installation.rs deleted file mode 100644 index 787f3fd..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/selected_game_installation.rs +++ /dev/null @@ -1,262 +0,0 @@ -use std::{ - path::{Path, PathBuf}, - sync::{Arc, Mutex}, -}; - -use crate::services::game_path::{ - fallback_game_candidates, fs_probe, resolve_game_path_core, GamePathAcceptance, GamePathInputs, - GamePathProbe, GamePathResolution, -}; -use crate::services::startup::InstallerContextState; -use tauri::Manager; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct SelectedGameInstallation { - game_path: PathBuf, -} - -impl SelectedGameInstallation { - pub(crate) fn game_path(&self) -> &Path { - &self.game_path - } -} - -#[derive(Clone, Default)] -pub struct SelectedGameInstallationState { - selected: Arc>>, -} - -impl SelectedGameInstallationState { - pub(crate) fn snapshot(&self) -> Option { - self.selected - .lock() - .expect("selected game installation poisoned") - .clone() - } - - pub(crate) fn accept_explicit_path( - &self, - game_path: PathBuf, - ) -> Result { - if !crate::services::detect::is_valid_game_path(&game_path) { - return Err(format!( - "The selected directory is not a valid The Bazaar installation: {}", - game_path.display() - )); - } - - let installation = SelectedGameInstallation { game_path }; - *self - .selected - .lock() - .expect("selected game installation poisoned") = Some(installation.clone()); - Ok(installation) - } - - pub(crate) fn resolve( - &self, - app: &tauri::AppHandle, - requested_game_path: Option, - acceptance: GamePathAcceptance, - ) -> Option { - let requested = normalize_requested_game_path(requested_game_path); - if let Some(game_path) = requested.as_ref() { - let _ = self.accept_explicit_path(game_path.clone()); - } - let startup = app - .state::() - .get_or_initialize(app) - .game_path - .clone(); - let resolved = self.resolve_with( - requested, - startup, - acceptance, - fallback_game_candidates, - fs_probe, - ); - crate::services::debug_log!( - "[selected_game_installation] acceptance={:?} -> game_path={:?} source={:?} db={}", - acceptance, - resolved - .as_ref() - .map(|resolution| resolution.game_path.display().to_string()), - resolved.as_ref().map(|resolution| &resolution.source), - resolved - .as_ref() - .map(|resolution| resolution.database_path.is_some()) - .unwrap_or(false), - ); - resolved - } - - fn resolve_with( - &self, - requested: Option, - startup: Option, - acceptance: GamePathAcceptance, - candidates: impl Fn() -> Vec, - probe: impl Fn(GamePathProbe, &Path) -> bool, - ) -> Option { - resolve_game_path_core( - GamePathInputs { - requested, - selected: self - .snapshot() - .map(|installation| installation.game_path().to_path_buf()), - startup, - }, - acceptance, - candidates, - probe, - ) - } -} - -fn normalize_requested_game_path(game_path: Option) -> Option { - game_path - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()) - .map(PathBuf::from) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::services::game_path::GamePathSource; - use std::collections::HashSet; - - fn path(value: &str) -> PathBuf { - PathBuf::from(value) - } - - fn mark_valid_game(game_path: &Path) { - std::fs::create_dir_all(game_path).unwrap(); - #[cfg(target_os = "macos")] - std::fs::create_dir(game_path.join("TheBazaar.app")).unwrap(); - #[cfg(target_os = "windows")] - std::fs::write(game_path.join("TheBazaar.exe"), b"exe").unwrap(); - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - std::fs::write(game_path.join("TheBazaar"), b"exe").unwrap(); - } - - #[test] - fn selected_game_installation_uses_explicit_selected_startup_fallback_priority() { - struct Row { - requested: Option<&'static str>, - selected: Option<&'static str>, - startup: Option<&'static str>, - fallback: &'static [&'static str], - installed: &'static [&'static str], - expected: &'static str, - source: GamePathSource, - } - - let rows = [ - Row { - requested: Some("/explicit"), - selected: Some("/selected"), - startup: Some("/startup"), - fallback: &["/fallback"], - installed: &["/fallback"], - expected: "/explicit", - source: GamePathSource::Explicit, - }, - Row { - requested: None, - selected: Some("/selected"), - startup: Some("/startup"), - fallback: &["/fallback"], - installed: &["/fallback"], - expected: "/selected", - source: GamePathSource::Selected, - }, - Row { - requested: None, - selected: None, - startup: Some("/startup"), - fallback: &["/fallback"], - installed: &["/fallback"], - expected: "/startup", - source: GamePathSource::Startup, - }, - Row { - requested: None, - selected: None, - startup: None, - fallback: &["/fallback"], - installed: &["/fallback"], - expected: "/fallback", - source: GamePathSource::Fallback, - }, - ]; - - for row in rows { - let state = SelectedGameInstallationState::default(); - if let Some(selected) = row.selected { - *state.selected.lock().unwrap() = Some(SelectedGameInstallation { - game_path: path(selected), - }); - } - let installed: HashSet = row.installed.iter().map(|item| path(item)).collect(); - let resolved = state - .resolve_with( - row.requested.map(path), - row.startup.map(path), - GamePathAcceptance::DetectionPick, - || row.fallback.iter().map(|item| path(item)).collect(), - |probe, candidate| { - probe == GamePathProbe::GameInstalled && installed.contains(candidate) - }, - ) - .unwrap(); - - assert_eq!(resolved.game_path, path(row.expected)); - assert_eq!(resolved.source, row.source); - } - } - - #[test] - fn invalid_explicit_path_does_not_replace_a_valid_selection() { - let root = tempfile::tempdir().unwrap(); - let valid = root.path().join("valid"); - let invalid = root.path().join("invalid"); - mark_valid_game(&valid); - std::fs::create_dir(&invalid).unwrap(); - let state = SelectedGameInstallationState::default(); - - state.accept_explicit_path(valid.clone()).unwrap(); - assert!(state.accept_explicit_path(invalid).is_err()); - - assert_eq!(state.snapshot().unwrap().game_path(), valid); - } - - #[test] - fn selected_installation_is_not_persisted_across_state_recreation() { - let root = tempfile::tempdir().unwrap(); - let valid = root.path().join("valid"); - mark_valid_game(&valid); - let first_session = SelectedGameInstallationState::default(); - first_session.accept_explicit_path(valid).unwrap(); - - let next_session = SelectedGameInstallationState::default(); - - assert!(next_session.snapshot().is_none()); - } - - #[test] - fn resolving_without_any_installation_returns_none() { - let state = SelectedGameInstallationState::default(); - - let resolved = state.resolve_with( - None, - None, - GamePathAcceptance::DetectionPick, - Vec::new, - |_, _| false, - ); - - assert!(resolved.is_none()); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/startup.rs b/bazaarplusplus-installer/src-tauri/src/services/startup.rs deleted file mode 100644 index 56f14d8..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/startup.rs +++ /dev/null @@ -1,57 +0,0 @@ -use std::path::PathBuf; -use std::sync::{Arc, OnceLock}; - -use tauri::AppHandle; - -use super::bepinex; -use super::detect::detect_installation_paths; - -/// Startup-time installer context. -/// -/// These inputs don't change during a session, so we read them once, cache the -/// result, and let every subsequent `resolve_game_path` or `detect_for_install` -/// call reuse the cached values. Before this split, each detection pass re-read -/// the bundled `BepInEx.zip`, which on Windows was a dominant source of -/// detect-flow latency because Defender scans the zip on every `CreateFile`. -pub(crate) struct InstallerStartup { - pub(crate) bundled_bpp_version: Option, - pub(crate) steam_path: Option, - pub(crate) game_path: Option, -} - -#[derive(Default)] -pub struct InstallerContextState { - inner: OnceLock>, -} - -impl InstallerContextState { - pub(crate) fn get_or_initialize(&self, app: &AppHandle) -> Arc { - self.inner - .get_or_init(|| Arc::new(compute_startup(app))) - .clone() - } -} - -fn compute_startup(app: &AppHandle) -> InstallerStartup { - let bundled_bpp_version = bepinex::read_bundled_bpp_version(app).ok().flatten(); - let detected_paths = detect_installation_paths(); - - crate::services::debug_log!( - "[startup] initialized bundled_bpp_version={:?} steam_path={:?} game_path={:?}", - bundled_bpp_version, - detected_paths - .steam_path - .as_ref() - .map(|path| path.display().to_string()), - detected_paths - .game_path - .as_ref() - .map(|path| path.display().to_string()), - ); - - InstallerStartup { - bundled_bpp_version, - steam_path: detected_paths.steam_path, - game_path: detected_paths.game_path, - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/steam.rs b/bazaarplusplus-installer/src-tauri/src/services/steam.rs deleted file mode 100644 index 3885992..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/steam.rs +++ /dev/null @@ -1,240 +0,0 @@ -use crate::services::debug_log; -use std::path::Path; -use std::process::Command; -use std::time::Duration; - -#[cfg(target_os = "windows")] -const STEAM_PROCESS_NAME: &str = "steam.exe"; -#[cfg(any(target_os = "macos", target_os = "windows"))] -const STEAM_EXIT_WAIT_ATTEMPTS: usize = 60; -#[cfg(any(target_os = "macos", target_os = "windows"))] -const STEAM_EXIT_WAIT_INTERVAL: Duration = Duration::from_millis(500); - -fn has_steam_userdata(steam_path: &Path) -> bool { - steam_path.join("userdata").is_dir() -} - -#[cfg(any(target_os = "macos", test))] -fn steam_running_from_pgrep( - status_code: Option, - stdout: &[u8], - stderr: &[u8], -) -> Result { - match status_code { - Some(0) => { - let output = String::from_utf8_lossy(stdout); - Ok(output.lines().any(|line| line.contains("steam_osx"))) - } - Some(1) => Ok(false), - _ => { - let stderr = String::from_utf8_lossy(stderr).trim().to_string(); - if stderr.is_empty() { - Err("Failed to inspect Steam process state.".to_string()) - } else { - Err(format!("Failed to inspect Steam process state: {stderr}")) - } - } - } -} - -fn ensure_process_stopped_with( - process_name: &str, - mut is_running: IsRunning, - mut request_quit: RequestQuit, - mut sleep: Sleep, - attempts: usize, - interval: Duration, -) -> Result -where - IsRunning: FnMut() -> Result, - RequestQuit: FnMut() -> Result<(), String>, - Sleep: FnMut(Duration), -{ - if !is_running()? { - return Ok(false); - } - - request_quit()?; - - for _ in 0..attempts { - sleep(interval); - if !is_running()? { - return Ok(true); - } - } - - Err(format!( - "{process_name} did not close in time. Please quit it manually and try again." - )) -} - -#[cfg(target_os = "macos")] -fn is_steam_running() -> Result { - let output = Command::new("pgrep") - .args(["-alf", "Steam"]) - .output() - .map_err(|err| format!("Failed to inspect Steam process state: {err}"))?; - - steam_running_from_pgrep(output.status.code(), &output.stdout, &output.stderr) -} - -#[cfg(target_os = "windows")] -fn is_steam_running() -> Result { - crate::services::process_snapshot::process_is_running(STEAM_PROCESS_NAME) -} - -#[cfg(target_os = "macos")] -fn request_steam_quit() -> Result<(), String> { - let output = Command::new("osascript") - .args(["-e", "tell application \"Steam\" to quit"]) - .output() - .map_err(|err| format!("Failed to ask Steam to quit: {err}"))?; - - if output.status.success() { - return Ok(()); - } - - let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); - if stderr.is_empty() { - Err("Failed to ask Steam to quit.".to_string()) - } else { - Err(format!("Failed to ask Steam to quit: {stderr}")) - } -} - -#[cfg(target_os = "windows")] -fn request_steam_quit() -> Result<(), String> { - let output = Command::new("taskkill") - .args(["/IM", STEAM_PROCESS_NAME, "/T"]) - .output() - .map_err(|err| format!("Failed to ask Steam to quit: {err}"))?; - - if output.status.success() { - return Ok(()); - } - - let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); - if stderr.is_empty() { - Err("Failed to ask Steam to quit.".to_string()) - } else { - Err(format!("Failed to ask Steam to quit: {stderr}")) - } -} - -#[cfg(any(target_os = "macos", target_os = "windows"))] -fn close_steam_internal() -> Result { - ensure_process_stopped_with( - "Steam", - is_steam_running, - request_steam_quit, - std::thread::sleep, - STEAM_EXIT_WAIT_ATTEMPTS, - STEAM_EXIT_WAIT_INTERVAL, - ) -} - -#[cfg(any(target_os = "macos", target_os = "windows"))] -pub fn prepare_steam_for_config_update(steam_path: &Path) -> Result<(), String> { - if !has_steam_userdata(steam_path) { - return Err(format!( - "Steam userdata was not found at {}", - steam_path.display() - )); - } - - let stopped = close_steam_internal()?; - - if stopped { - debug_log!("Steam was running and has been closed."); - } - - Ok(()) -} - -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -pub fn prepare_steam_for_config_update(_steam_path: &Path) -> Result<(), String> { - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::{ensure_process_stopped_with, steam_running_from_pgrep}; - use std::time::Duration; - - #[test] - fn test_steam_running_from_pgrep_detects_macos_main_process() { - let stdout = b"1871 /Users/test/Steam.AppBundle/Steam/Contents/MacOS/steam_osx\n"; - - let running = steam_running_from_pgrep(Some(0), stdout, b"").unwrap(); - - assert!(running); - } - - #[test] - fn test_steam_running_from_pgrep_ignores_helper_only_output() { - let stdout = b"1901 /Users/test/Steam Helper.app/Contents/MacOS/Steam Helper\n"; - - let running = steam_running_from_pgrep(Some(0), stdout, b"").unwrap(); - - assert!(!running); - } - - #[test] - fn test_ensure_process_stopped_with_skips_quit_when_process_is_not_running() { - let mut quit_called = false; - let result = ensure_process_stopped_with( - "Steam", - || Ok(false), - || { - quit_called = true; - Ok(()) - }, - |_| {}, - 3, - Duration::from_millis(1), - ); - - assert!(!result.unwrap()); - assert!(!quit_called); - } - - #[test] - fn test_ensure_process_stopped_with_requests_quit_and_waits_for_exit() { - let mut running_checks = 0; - let mut quit_called = false; - - let result = ensure_process_stopped_with( - "Steam", - || { - running_checks += 1; - Ok(running_checks < 3) - }, - || { - quit_called = true; - Ok(()) - }, - |_| {}, - 5, - Duration::from_millis(1), - ); - - assert!(result.unwrap()); - assert!(quit_called); - } - - #[test] - fn test_ensure_process_stopped_with_errors_when_process_never_exits() { - let result = ensure_process_stopped_with( - "Steam", - || Ok(true), - || Ok(()), - |_| {}, - 2, - Duration::from_millis(1), - ); - - let error = result.unwrap_err(); - assert!(error.contains("Steam")); - assert!(error.contains("close")); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/vdf/launch_options.rs b/bazaarplusplus-installer/src-tauri/src/services/vdf/launch_options.rs deleted file mode 100644 index 86a43fc..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/vdf/launch_options.rs +++ /dev/null @@ -1,164 +0,0 @@ -use std::path::{Path, PathBuf}; - -use crate::services::debug_log; - -use super::parse::{clear_launch_options, launch_options_empty_in_content, THE_BAZAAR_APP_ID}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum SteamLaunchOptionsState { - Empty, - NonEmpty, - Unavailable, -} - -struct LocalconfigUpdate { - path: PathBuf, - original_content: String, - new_content: String, -} - -pub fn find_localconfig_paths(steam_path: &Path) -> Vec { - let Ok(entries) = std::fs::read_dir(steam_path.join("userdata")) else { - return Vec::new(); - }; - - let mut paths = entries - .filter_map(std::result::Result::ok) - .filter_map(|entry| { - let user_name = entry.file_name(); - let user_name = user_name.to_str()?; - if !user_name.chars().all(|ch| ch.is_ascii_digit()) { - return None; - } - - let localconfig = entry.path().join("config/localconfig.vdf"); - localconfig.exists().then_some(localconfig) - }) - .collect::>(); - paths.sort(); - paths -} - -fn backup_localconfig_once(localconfig: &Path) -> Result<(), String> { - let backup = localconfig.with_extension("vdf.bak"); - if backup.exists() { - return Ok(()); - } - - std::fs::copy(localconfig, &backup).map_err(|err| err.to_string())?; - Ok(()) -} - -fn write_localconfig(localconfig: &Path, content: &str) -> Result<(), String> { - let tmp = localconfig.with_extension("vdf.tmp"); - std::fs::write(&tmp, content).map_err(|err| err.to_string())?; - std::fs::rename(&tmp, localconfig).map_err(|err| err.to_string()) -} - -fn plan_localconfig_updates( - steam_path: &Path, - mut transform: F, -) -> Result, String> -where - F: FnMut(&str) -> Result, String>, -{ - let localconfigs = find_localconfig_paths(steam_path); - if localconfigs.is_empty() { - return Err("Could not find any localconfig.vdf under Steam/userdata".to_string()); - } - - let mut planned = Vec::new(); - for localconfig in localconfigs { - let content = std::fs::read_to_string(&localconfig).map_err(|err| err.to_string())?; - let Some(new_content) = transform(&content)? else { - debug_log!( - "Skipped {} because app {} is not present.", - localconfig.display(), - THE_BAZAAR_APP_ID - ); - continue; - }; - - planned.push(LocalconfigUpdate { - path: localconfig, - original_content: content, - new_content, - }); - } - - Ok(planned) -} - -fn apply_localconfig_updates(updates: Vec) -> Result { - let mut applied: Vec = Vec::new(); - - for update in &updates { - backup_localconfig_once(&update.path)?; - debug_log!("Backed up {}", update.path.display()); - } - - for update in updates { - if let Err(err) = write_localconfig(&update.path, &update.new_content) { - for applied_update in &applied { - let _ = write_localconfig(&applied_update.path, &applied_update.original_content); - } - return Err(format!( - "Failed updating {}: {err}. Rolled back {} file(s).", - update.path.display(), - applied.len() - )); - } - - debug_log!("Updated {}", update.path.display()); - applied.push(update); - } - - Ok(applied.len()) -} - -fn inspect_launch_options_for_steam_raw( - steam_path: &Path, -) -> Result { - let localconfigs = find_localconfig_paths(steam_path); - if localconfigs.is_empty() { - return Err(format!( - "Could not find any localconfig.vdf under {}", - steam_path.join("userdata").display() - )); - } - - for localconfig in localconfigs { - let content = std::fs::read_to_string(&localconfig).map_err(|err| err.to_string())?; - if launch_options_empty_in_content(&content)? == Some(false) { - return Ok(SteamLaunchOptionsState::NonEmpty); - } - } - - Ok(SteamLaunchOptionsState::Empty) -} - -pub(crate) fn inspect_launch_options_for_steam(steam_path: &Path) -> SteamLaunchOptionsState { - match inspect_launch_options_for_steam_raw(steam_path) { - Ok(state) => state, - Err(_err) => { - debug_log!("Cannot inspect Steam launch options: {_err}"); - SteamLaunchOptionsState::Unavailable - } - } -} - -pub fn clear_launch_options_for_steam(steam_path: &Path) -> Result<(), String> { - let planned = plan_localconfig_updates(steam_path, clear_launch_options)?; - if !planned.is_empty() { - apply_localconfig_updates(planned)?; - } - match inspect_launch_options_for_steam_raw(steam_path)? { - SteamLaunchOptionsState::Empty => Ok(()), - SteamLaunchOptionsState::NonEmpty => Err(format!( - "Steam launch options for app {THE_BAZAAR_APP_ID} are still non-empty after cleanup" - )), - SteamLaunchOptionsState::Unavailable => { - unreachable!("raw inspection never returns unavailable") - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/vdf/mod.rs b/bazaarplusplus-installer/src-tauri/src/services/vdf/mod.rs deleted file mode 100644 index 56cb7e7..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/vdf/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -mod launch_options; -mod parse; - -#[cfg(test)] -mod tests; - -pub use launch_options::clear_launch_options_for_steam; -pub(crate) use launch_options::{inspect_launch_options_for_steam, SteamLaunchOptionsState}; -pub(crate) use parse::THE_BAZAAR_APP_ID; diff --git a/bazaarplusplus-installer/src-tauri/src/services/vdf/parse.rs b/bazaarplusplus-installer/src-tauri/src/services/vdf/parse.rs deleted file mode 100644 index 53ec388..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/vdf/parse.rs +++ /dev/null @@ -1,167 +0,0 @@ -pub(crate) const THE_BAZAAR_APP_ID: &str = "1617400"; -pub(crate) const LAUNCH_OPTIONS_KEY: &str = "LaunchOptions"; -pub(crate) fn launch_options_empty_in_content(vdf_content: &str) -> Result, String> { - let lines = vdf_content.lines().map(str::to_string).collect::>(); - let Some((apps_open, apps_close)) = find_apps_block(&lines) else { - return Err("Malformed VDF: could not locate Steam/apps object".to_string()); - }; - let Some((app_open, app_close)) = - find_named_block(&lines, apps_open..=apps_close, THE_BAZAAR_APP_ID) - else { - return Ok(None); - }; - - let mut nested_depth = 0usize; - for line in &lines[app_open + 1..app_close] { - match line.trim() { - "{" => { - nested_depth += 1; - continue; - } - "}" => { - nested_depth = nested_depth.saturating_sub(1); - continue; - } - _ => {} - } - if nested_depth == 0 - && parse_line_pair(line) - .is_some_and(|(key, value)| key == LAUNCH_OPTIONS_KEY && !value.is_empty()) - { - return Ok(Some(false)); - } - } - Ok(Some(true)) -} - -fn parse_line_pair(line: &str) -> Option<(&str, &str)> { - let trimmed = &line[line.find('"')?..]; - - fn parse_quoted(input: &str) -> Option<(&str, &str)> { - let mut escaped = false; - let mut end = None; - let chars = input.char_indices(); - - for (idx, ch) in chars.skip(1) { - if escaped { - escaped = false; - continue; - } - - if ch == '\\' { - escaped = true; - continue; - } - - if ch == '"' { - end = Some(idx); - break; - } - } - - let end = end?; - Some((&input[1..end], &input[end + 1..])) - } - - let (key, rest) = parse_quoted(trimmed)?; - let rest = rest.trim_start(); - let (value, remainder) = parse_quoted(rest)?; - if !remainder.trim().is_empty() { - return None; - } - - Some((key, value)) -} - -fn find_apps_block(lines: &[String]) -> Option<(usize, usize)> { - let start = lines - .iter() - .position(|line| line.trim().eq_ignore_ascii_case("\"apps\""))?; - let open = (start + 1..lines.len()).find(|&idx| lines[idx].trim() == "{")?; - let mut depth = 0usize; - - for (idx, line) in lines.iter().enumerate().skip(open) { - match line.trim() { - "{" => depth += 1, - "}" => { - depth = depth.saturating_sub(1); - if depth == 0 { - return Some((open, idx)); - } - } - _ => {} - } - } - - None -} - -fn find_named_block( - lines: &[String], - range: std::ops::RangeInclusive, - key: &str, -) -> Option<(usize, usize)> { - let mut idx = *range.start(); - while idx <= *range.end() { - if lines[idx].trim() == format!("\"{key}\"") { - let open = (idx + 1..=*range.end()).find(|&line_idx| lines[line_idx].trim() == "{")?; - let mut depth = 0usize; - for (offset, line) in lines[open..=*range.end()].iter().enumerate() { - let line_idx = open + offset; - match line.trim() { - "{" => depth += 1, - "}" => { - depth = depth.saturating_sub(1); - if depth == 0 { - return Some((open, line_idx)); - } - } - _ => {} - } - } - } - idx += 1; - } - None -} - -pub fn clear_launch_options(vdf_content: &str) -> Result, String> { - let mut lines = vdf_content.lines().map(str::to_string).collect::>(); - let Some((apps_open, apps_close)) = find_apps_block(&lines) else { - return Err("Malformed VDF: could not locate Steam/apps object".to_string()); - }; - let Some((app_open, app_close)) = - find_named_block(&lines, apps_open..=apps_close, THE_BAZAAR_APP_ID) - else { - return Ok(None); - }; - - let mut nested_depth = 0usize; - let mut launch_option_lines = Vec::new(); - for (idx, line) in lines.iter().enumerate().take(app_close).skip(app_open + 1) { - match line.trim() { - "{" => { - nested_depth += 1; - continue; - } - "}" => { - nested_depth = nested_depth.saturating_sub(1); - continue; - } - _ => {} - } - if nested_depth == 0 - && parse_line_pair(line).is_some_and(|(key, _value)| key == LAUNCH_OPTIONS_KEY) - { - launch_option_lines.push(idx); - } - } - if launch_option_lines.is_empty() { - return Ok(None); - } - for idx in launch_option_lines.into_iter().rev() { - lines.remove(idx); - } - - Ok(Some(lines.join("\n"))) -} diff --git a/bazaarplusplus-installer/src-tauri/src/services/vdf/tests.rs b/bazaarplusplus-installer/src-tauri/src/services/vdf/tests.rs deleted file mode 100644 index 517d36c..0000000 --- a/bazaarplusplus-installer/src-tauri/src/services/vdf/tests.rs +++ /dev/null @@ -1,147 +0,0 @@ -use super::launch_options::*; -use super::parse::*; - -fn fixture_vdf(launch_options: Option<&str>) -> String { - let launch_line = launch_options - .map(|value| format!(" \"LaunchOptions\" \"{value}\"\n")) - .unwrap_or_default(); - format!( - r#" -"UserLocalConfigStore" -{{ - "Software" - {{ - "Valve" - {{ - "Steam" - {{ - "apps" - {{ - "1617400" - {{ -{launch_line} "LastPlayed" "1700000000" - }} - }} - }} - }} - }} -}}"# - ) -} - -fn write_localconfig(root: &std::path::Path, user: &str, content: &str) { - let config = root.join("userdata").join(user).join("config"); - std::fs::create_dir_all(&config).unwrap(); - std::fs::write(config.join("localconfig.vdf"), content).unwrap(); -} - -#[test] -fn launch_options_absent_or_empty_is_clean() { - assert_eq!( - launch_options_empty_in_content(&fixture_vdf(None)).unwrap(), - Some(true) - ); - assert_eq!( - launch_options_empty_in_content(&fixture_vdf(Some(""))).unwrap(), - Some(true) - ); -} - -#[test] -fn any_non_empty_launch_options_are_dirty_without_content_matching() { - for value in [ - "--developer-mode", - "\\\"/some/path/run_bepinex.sh\\\" %command%", - "%command% --custom", - ] { - assert_eq!( - launch_options_empty_in_content(&fixture_vdf(Some(value))).unwrap(), - Some(false), - "{value}" - ); - } -} - -#[test] -fn missing_app_is_logically_empty() { - let other_app = fixture_vdf(None).replace("\"1617400\"", "\"730\""); - assert_eq!(launch_options_empty_in_content(&other_app).unwrap(), None); -} - -#[test] -fn nested_launch_options_are_not_the_bazaar_property() { - let nested = fixture_vdf(None).replace( - " \"LastPlayed\"", - " \"Cloud\"\n {\n \"LaunchOptions\" \"nested\"\n }\n \"LastPlayed\"", - ); - assert_eq!( - launch_options_empty_in_content(&nested).unwrap(), - Some(true) - ); -} - -#[test] -fn clear_removes_every_direct_launch_options_entry() { - let duplicate = fixture_vdf(Some("FIRST")).replace( - " \"LastPlayed\"", - " \"LaunchOptions\" \"SECOND\"\n \"LastPlayed\"", - ); - let cleared = clear_launch_options(&duplicate).unwrap().unwrap(); - assert!(!cleared.contains("\"LaunchOptions\"")); - assert_eq!( - launch_options_empty_in_content(&cleared).unwrap(), - Some(true) - ); -} - -#[test] -fn steam_inspection_checks_every_numeric_account() { - let tmp = tempfile::tempdir().unwrap(); - write_localconfig(tmp.path(), "100", &fixture_vdf(None)); - write_localconfig(tmp.path(), "200", &fixture_vdf(Some("CUSTOM"))); - write_localconfig(tmp.path(), "not-a-user", &fixture_vdf(Some("IGNORED"))); - - assert_eq!( - inspect_launch_options_for_steam(tmp.path()), - SteamLaunchOptionsState::NonEmpty - ); -} - -#[test] -fn clear_updates_all_accounts_and_verifies_the_result() { - let tmp = tempfile::tempdir().unwrap(); - write_localconfig(tmp.path(), "100", &fixture_vdf(Some("FIRST"))); - write_localconfig(tmp.path(), "200", &fixture_vdf(Some("SECOND"))); - - clear_launch_options_for_steam(tmp.path()).unwrap(); - - assert_eq!( - inspect_launch_options_for_steam(tmp.path()), - SteamLaunchOptionsState::Empty - ); - for path in find_localconfig_paths(tmp.path()) { - assert!(!std::fs::read_to_string(path) - .unwrap() - .contains("\"LaunchOptions\"")); - } -} - -#[test] -fn unavailable_localconfig_is_not_treated_as_clean() { - let tmp = tempfile::tempdir().unwrap(); - assert_eq!( - inspect_launch_options_for_steam(tmp.path()), - SteamLaunchOptionsState::Unavailable - ); - assert!(clear_launch_options_for_steam(tmp.path()).is_err()); -} - -#[test] -fn malformed_vdf_is_unavailable() { - let tmp = tempfile::tempdir().unwrap(); - write_localconfig(tmp.path(), "100", "not a Steam VDF"); - assert_eq!( - inspect_launch_options_for_steam(tmp.path()), - SteamLaunchOptionsState::Unavailable - ); -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/history_thumbnails/mod.rs b/bazaarplusplus-installer/src-tauri/src/stream/history_thumbnails/mod.rs deleted file mode 100644 index 3ab2055..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/history_thumbnails/mod.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! History Thumbnails: the cropped strip of a run's screenshot on a History -//! List card. This module owns the process-local source registry, the only -//! thumbnail URL builder, the image route, and the per-installation cache. - -use super::{ - http::{png_response, run_record_task}, - overlay_settings::OverlaySettingsStore, - records::resolve_overlay_image_path, - server, - strip::{cached_strip, TEMP_SUFFIX}, -}; -use crate::{history::screenshots::load_screenshot_image_path, services::paths}; -use axum::{ - extract::{Path as RoutePath, State}, - http::StatusCode, - response::{IntoResponse, Response}, - routing::get, - Router, -}; -use sha2::{Digest, Sha256}; -use std::{ - path::{Path, PathBuf}, - sync::{Arc, Mutex, OnceLock}, - time::{Duration, SystemTime, UNIX_EPOCH}, -}; - -#[cfg(test)] -mod tests; - -pub(super) const ROUTE: &str = "/history/{source}/images/{screenshot_id}/strip"; -/// Beneath the service cache root; the OBS strips at that root stay unswept. -const CACHE_DIRECTORY: &str = "history-thumbnails"; -/// Where History strips were cached per source file before this namespace. -const LEGACY_CACHE_DIRECTORY: &str = "history"; -const CACHE_LIMITS: CacheLimits = CacheLimits { - unused_for: Duration::from_secs(30 * 24 * 60 * 60), - max_entries: 1000, - fresh_for: Duration::from_secs(10), -}; - -/// An opaque handle for one registered installation path. It stays valid, and -/// names the same path, until the installer exits. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct ThumbnailSource(usize); - -#[derive(Clone, Default)] -pub(crate) struct HistoryThumbnails { - sources: Arc>>, -} - -impl HistoryThumbnails { - /// Registers the installation a History page was read from. The path is - /// stored as given and its database is resolved on each request, so a - /// database that appears after startup is still found. - pub(crate) fn register(&self, game_path: &Path) -> ThumbnailSource { - let mut sources = self.sources.lock().expect("thumbnail sources poisoned"); - let index = match sources.iter().position(|path| path == game_path) { - Some(index) => index, - None => { - sources.push(game_path.to_path_buf()); - sources.len() - 1 - } - }; - ThumbnailSource(index) - } - - fn game_path(&self, source: usize) -> Option { - self.sources - .lock() - .expect("thumbnail sources poisoned") - .get(source) - .cloned() - } -} - -/// The absolute URL of a screenshot's History Thumbnail. -pub(crate) fn url(source: ThumbnailSource, screenshot_id: &str) -> String { - let route = ROUTE - .replace("{source}", &source.0.to_string()) - .replace("{screenshot_id}", screenshot_id); - format!("{}{route}", server::origin()) -} - -#[derive(Clone)] -struct RouteState { - thumbnails: HistoryThumbnails, - settings: OverlaySettingsStore, - cache_root: PathBuf, -} - -pub(super) fn router( - thumbnails: HistoryThumbnails, - settings: OverlaySettingsStore, - cache_root: PathBuf, -) -> Router { - Router::new() - .route(ROUTE, get(thumbnail)) - .with_state(RouteState { - thumbnails, - settings, - cache_root, - }) -} - -async fn thumbnail( - RoutePath((source, screenshot_id)): RoutePath<(usize, String)>, - State(state): State, -) -> Response { - let Some(game_path) = state.thumbnails.game_path(source) else { - return StatusCode::NOT_FOUND.into_response(); - }; - let RouteState { - settings, - cache_root, - .. - } = state; - match run_record_task(move || render(&game_path, &screenshot_id, &settings, &cache_root)).await - { - Ok(Some(bytes)) => png_response(bytes), - Ok(None) => StatusCode::NOT_FOUND.into_response(), - Err(message) => (StatusCode::INTERNAL_SERVER_ERROR, message).into_response(), - } -} - -/// `None` when the database, the screenshot row or its image is missing. -fn render( - game_path: &Path, - screenshot_id: &str, - settings: &OverlaySettingsStore, - cache_root: &Path, -) -> Result>, String> { - let crop = settings.load()?.crop; - let stored = load_screenshot_image_path(&paths::database_path(game_path), screenshot_id)?; - let Some(image_path) = - resolve_overlay_image_path(Some(game_path.to_path_buf()), stored.as_deref()) - .filter(|path| path.exists()) - else { - return Ok(None); - }; - cached_strip( - &cache_directory(cache_root, game_path), - screenshot_id, - &image_path, - crop, - ) - .map(Some) -} - -/// One directory per installation path, stable across restarts. -fn cache_directory(cache_root: &Path, game_path: &Path) -> PathBuf { - let digest = Sha256::digest(game_path.as_os_str().as_encoded_bytes()); - let namespace = digest[..8] - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); - cache_root.join(CACHE_DIRECTORY).join(namespace) -} - -/// Sweeps the History Thumbnail cache once per process, off the async runtime. -pub(super) fn sweep_cache() { - static SWEPT: OnceLock<()> = OnceLock::new(); - if SWEPT.set(()).is_err() { - return; - } - let cache_root = paths::overlay_cache_dir(); - tauri::async_runtime::spawn_blocking(move || { - sweep(&cache_root, SystemTime::now(), &CACHE_LIMITS); - }); -} - -struct CacheLimits { - /// An entry not read or written for longer is removed. - unused_for: Duration, - /// The oldest entries beyond this count are removed. - max_entries: usize, - /// Entries this recent may be in use and are left alone. - fresh_for: Duration, -} - -/// Every deletion is best effort: Windows refuses to remove an open file. -/// Namespace directories stay, so a concurrent write never loses its parent. -fn sweep(cache_root: &Path, now: SystemTime, limits: &CacheLimits) { - let _ = std::fs::remove_dir_all(cache_root.join(LEGACY_CACHE_DIRECTORY)); - - let Ok(namespaces) = std::fs::read_dir(cache_root.join(CACHE_DIRECTORY)) else { - return; - }; - let mut kept = Vec::new(); - for namespace in namespaces.flatten() { - let Ok(files) = std::fs::read_dir(namespace.path()) else { - continue; - }; - for file in files.flatten() { - let Ok(metadata) = file.metadata() else { - continue; - }; - if !metadata.is_file() { - continue; - } - let modified = metadata.modified().unwrap_or(UNIX_EPOCH); - let age = now.duration_since(modified).unwrap_or_default(); - if age < limits.fresh_for { - continue; - } - let path = file.path(); - let orphan = path.to_string_lossy().ends_with(TEMP_SUFFIX); - if orphan || age > limits.unused_for { - let _ = std::fs::remove_file(&path); - } else { - kept.push((modified, path)); - } - } - } - - if kept.len() > limits.max_entries { - kept.sort_by_key(|(modified, _)| *modified); - let excess = kept.len() - limits.max_entries; - for (_, path) in kept.into_iter().take(excess) { - let _ = std::fs::remove_file(path); - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/history_thumbnails/tests.rs b/bazaarplusplus-installer/src-tauri/src/stream/history_thumbnails/tests.rs deleted file mode 100644 index cabff19..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/history_thumbnails/tests.rs +++ /dev/null @@ -1,515 +0,0 @@ -use super::{ - cache_directory, sweep, url, CacheLimits, HistoryThumbnails, CACHE_DIRECTORY, - LEGACY_CACHE_DIRECTORY, -}; -use crate::stream::{ - runtime::{ - test_support::{installation, TestServer}, - StreamInstallation, StreamRuntime, - }, - server, -}; -use std::{ - path::{Path, PathBuf}, - sync::{atomic::Ordering, Arc}, - time::{Duration, SystemTime}, -}; -use tokio::sync::Notify; - -/// Adds a screenshot row and its image, creating the database on first use. -fn add_screenshot(game_path: &Path, id: &str, capture_source: &str, color: [u8; 4]) -> PathBuf { - let screenshots = crate::services::paths::screenshots_dir(game_path); - std::fs::create_dir_all(&screenshots).unwrap(); - let file_name = format!("{id}.png"); - let path = screenshots.join(&file_name); - image::RgbaImage::from_pixel(64, 32, image::Rgba(color)) - .save(&path) - .unwrap(); - let database_path = crate::services::paths::database_path(game_path); - let first_use = !database_path.exists(); - let connection = rusqlite::Connection::open(database_path).unwrap(); - if first_use { - crate::history::mod_schema::create_mod_schema(&connection); - } - connection - .execute( - "insert into run_screenshots ( - screenshot_id, capture_source, is_primary, image_relative_path, hero_name, - captured_utc_offset_minutes, captured_at_ms, victories_at_capture, day - ) values ( - ?1, ?2, 1, ?3, 'Vanessa', 0, - 1788220800000, 10, 10 - )", - [id, capture_source, &file_name], - ) - .unwrap(); - path -} - -fn screenshot_fixture(game_path: &Path, color: [u8; 4]) -> PathBuf { - add_screenshot(game_path, "shot-1", "end_of_run_auto", color) -} - -fn history_router( - runtime: &StreamRuntime, - thumbnails: &HistoryThumbnails, - overlay_path: &Path, - root: &Path, -) -> axum::Router { - crate::stream::http::router( - crate::stream::records::OverlayRecordRepository::new(Some(overlay_path.to_path_buf())), - runtime.clone(), - thumbnails.clone(), - crate::stream::overlay_settings::OverlaySettingsStore::new( - root.join("settings.json"), - None, - ), - root.join("cache"), - ) -} - -/// The request path of an absolute service URL. -fn route_of(url: &str) -> &str { - url.strip_prefix(&server::origin()) - .unwrap_or_else(|| panic!("{url} is not on the service origin")) -} - -async fn get(router: axum::Router, uri: &str) -> (axum::http::StatusCode, Vec) { - use tower::ServiceExt; - let response = router - .oneshot( - axum::http::Request::builder() - .uri(uri) - .body(axum::body::Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) - .await - .unwrap(); - (status, bytes.to_vec()) -} - -async fn image_pixel(router: axum::Router, uri: &str) -> [u8; 4] { - let (status, bytes) = get(router, uri).await; - assert_eq!( - status, - axum::http::StatusCode::OK, - "{}", - String::from_utf8_lossy(&bytes) - ); - image::load_from_memory(&bytes) - .unwrap() - .to_rgba8() - .get_pixel(0, 0) - .0 -} - -fn files_in(directory: &Path) -> Vec { - let mut files = std::fs::read_dir(directory) - .map(|entries| entries.map(|entry| entry.unwrap().path()).collect()) - .unwrap_or_else(|_| Vec::new()); - files.sort(); - files -} - -fn set_age(path: &Path, now: SystemTime, age: Duration) { - std::fs::File::options() - .write(true) - .open(path) - .unwrap() - .set_modified(now - age) - .unwrap(); -} - -#[test] -fn urls_are_absolute_on_the_service_origin_and_stable_per_path() { - let thumbnails = HistoryThumbnails::default(); - let a = thumbnails.register(Path::new("/Games/A")); - let b = thumbnails.register(Path::new("/Games/B")); - - assert_eq!(thumbnails.register(Path::new("/Games/A")), a); - assert_ne!(a, b); - assert_eq!( - url(a, "shot-1"), - "http://127.0.0.1:17654/history/0/images/shot-1/strip" - ); - assert_eq!( - url(b, "shot-1"), - "http://127.0.0.1:17654/history/1/images/shot-1/strip" - ); -} - -#[test] -fn cache_namespace_is_a_stable_digest_of_the_installation_path() { - let root = Path::new("/cache"); - - assert_eq!( - cache_directory(root, Path::new("/Games/The Bazaar")), - root.join("history-thumbnails").join("66c8b33aa11cd442") - ); -} - -#[tokio::test] -async fn one_installation_caches_its_thumbnails_in_one_namespace() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("game"); - add_screenshot(&game_path, "shot-1", "end_of_run_auto", [255, 0, 0, 255]); - add_screenshot(&game_path, "shot-2", "end_of_run_auto", [0, 255, 0, 255]); - let thumbnails = HistoryThumbnails::default(); - let source = thumbnails.register(&game_path); - let router = history_router( - &StreamRuntime::default(), - &thumbnails, - &game_path, - temp.path(), - ); - - for id in ["shot-1", "shot-2"] { - image_pixel(router.clone(), route_of(&url(source, id))).await; - } - - let cache_root = temp.path().join("cache"); - let namespaces = files_in(&cache_root.join(CACHE_DIRECTORY)); - assert_eq!(namespaces, [cache_directory(&cache_root, &game_path)]); - assert_eq!(files_in(&namespaces[0]).len(), 2); -} - -#[tokio::test] -async fn thumbnails_serve_a_primary_screenshot_whatever_its_capture_source() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("game"); - let color = [30, 60, 90, 255]; - add_screenshot(&game_path, "manual-1", "manual", color); - let thumbnails = HistoryThumbnails::default(); - let source = thumbnails.register(&game_path); - let router = history_router( - &StreamRuntime::default(), - &thumbnails, - &game_path, - temp.path(), - ); - - assert_eq!( - image_pixel(router.clone(), route_of(&url(source, "manual-1"))).await, - color - ); - // The OBS overlay still shows only end-of-run captures. - assert_eq!( - get(router, "/images/manual-1/strip").await.0, - axum::http::StatusCode::NOT_FOUND - ); -} - -#[tokio::test] -async fn unknown_sources_and_missing_screenshots_are_not_found() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("game"); - let thumbnails = HistoryThumbnails::default(); - let source = thumbnails.register(&game_path); - let router = history_router( - &StreamRuntime::default(), - &thumbnails, - &game_path, - temp.path(), - ); - - for uri in [ - "/history/7/images/shot-1/strip".to_string(), - route_of(&url(source, "shot-1")).to_string(), - ] { - assert_eq!( - get(router.clone(), &uri).await.0, - axum::http::StatusCode::NOT_FOUND - ); - } -} - -#[tokio::test] -async fn a_cache_hit_marks_the_entry_as_recently_used() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("game"); - screenshot_fixture(&game_path, [1, 2, 3, 255]); - let thumbnails = HistoryThumbnails::default(); - let uri = url(thumbnails.register(&game_path), "shot-1"); - let router = history_router( - &StreamRuntime::default(), - &thumbnails, - &game_path, - temp.path(), - ); - image_pixel(router.clone(), route_of(&uri)).await; - let [entry] = files_in(&cache_directory(&temp.path().join("cache"), &game_path)) - .try_into() - .unwrap(); - let stale = SystemTime::now() - Duration::from_secs(90 * 24 * 60 * 60); - set_age( - &entry, - SystemTime::now(), - Duration::from_secs(90 * 24 * 60 * 60), - ); - - image_pixel(router, route_of(&uri)).await; - - assert!(std::fs::metadata(&entry).unwrap().modified().unwrap() > stale); -} - -#[test] -fn sweep_removes_the_legacy_tree_stale_entries_and_orphans_but_keeps_fresh_ones() { - let temp = tempfile::tempdir().unwrap(); - let root = temp.path(); - let now = SystemTime::now(); - let limits = CacheLimits { - unused_for: Duration::from_secs(3600), - max_entries: 100, - fresh_for: Duration::from_secs(10), - }; - let legacy = root.join(LEGACY_CACHE_DIRECTORY).join("0123456789abcdef"); - std::fs::create_dir_all(&legacy).unwrap(); - std::fs::write(legacy.join("shot-1-strip.png"), b"old").unwrap(); - let obs_entry = root.join("shot-1-strip.png"); - std::fs::write(&obs_entry, b"obs").unwrap(); - set_age(&obs_entry, now, Duration::from_secs(7200)); - let namespace = cache_directory(root, Path::new("/Games/The Bazaar")); - std::fs::create_dir_all(&namespace).unwrap(); - let entry = |name: &str, age: u64| { - let path = namespace.join(name); - std::fs::write(&path, b"png").unwrap(); - set_age(&path, now, Duration::from_secs(age)); - path - }; - let stale = entry("stale-strip.png", 7200); - let used = entry("used-strip.png", 60); - let orphan = entry("used-strip.png.1-0.tmp", 60); - let writing = entry("used-strip.png.1-1.tmp", 1); - let just_served = entry("just-served-strip.png", 1); - - sweep(root, now, &limits); - - assert!(!root.join(LEGACY_CACHE_DIRECTORY).exists()); - assert!(!stale.exists()); - assert!(!orphan.exists()); - assert!(used.exists()); - assert!(writing.exists()); - assert!(just_served.exists()); - // The OBS strips at the cache root are not History's to sweep. - assert!(obs_entry.exists()); -} - -#[test] -fn sweep_caps_the_entry_count_by_removing_the_oldest() { - let temp = tempfile::tempdir().unwrap(); - let root = temp.path(); - let now = SystemTime::now(); - let limits = CacheLimits { - unused_for: Duration::from_secs(3600), - max_entries: 2, - fresh_for: Duration::from_secs(10), - }; - let entries = ["/Games/A", "/Games/B", "/Games/A"] - .into_iter() - .zip([300, 200, 100]) - .enumerate() - .map(|(index, (game_path, age))| { - let namespace = cache_directory(root, Path::new(game_path)); - std::fs::create_dir_all(&namespace).unwrap(); - let path = namespace.join(format!("shot-{index}-strip.png")); - std::fs::write(&path, b"png").unwrap(); - set_age(&path, now, Duration::from_secs(age)); - path - }) - .collect::>(); - - sweep(root, now, &limits); - - assert_eq!( - entries.iter().map(|path| path.exists()).collect::>(), - [false, true, true] - ); -} - -#[tokio::test] -async fn preparation_preserves_obs_and_isolates_sources_and_cached_pixels() { - let temp = tempfile::tempdir().unwrap(); - let a = temp.path().join("A"); - let b = temp.path().join("B"); - let red = [255, 0, 0, 255]; - let blue = [0, 0, 255, 255]; - let first_image = screenshot_fixture(&a, red); - let second_image = screenshot_fixture(&b, blue); - // Equal id, length, mtime and crop: only the installation tells them apart. - let length = std::fs::metadata(&first_image) - .unwrap() - .len() - .max(std::fs::metadata(&second_image).unwrap().len()); - for path in [&first_image, &second_image] { - let mut bytes = std::fs::read(path).unwrap(); - bytes.resize(length as usize, 0); - std::fs::write(path, bytes).unwrap(); - std::fs::File::options() - .write(true) - .open(path) - .unwrap() - .set_times(std::fs::FileTimes::new().set_modified( - std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000), - )) - .unwrap(); - } - let runtime = StreamRuntime::default(); - let server = TestServer::default(); - let requested = StreamInstallation { - game_path: Some(a.clone()), - record_game_path: Some(a.clone()), - }; - runtime.ensure_with(&server, requested).await.unwrap(); - runtime - .set_window_with(|_, _| Ok((Some("2026-08-01T00:00:00Z".into()), 3))) - .await - .unwrap(); - let before = serde_json::to_value(runtime.snapshot()).unwrap(); - let thumbnails = HistoryThumbnails::default(); - let url_a = url(thumbnails.register(&a), "shot-1"); - let url_b = url(thumbnails.register(&b), "shot-1"); - runtime - .prepare_history_thumbnails_with(&server, || StreamInstallation { - game_path: Some(b.clone()), - record_game_path: Some(b.clone()), - }) - .await - .unwrap(); - assert_eq!(serde_json::to_value(runtime.snapshot()).unwrap(), before); - assert_eq!(server.starts.load(Ordering::SeqCst), 1); - let router = history_router(&runtime, &thumbnails, &a, temp.path()); - assert_eq!( - image_pixel(router.clone(), "/images/shot-1/strip").await, - red - ); - assert_eq!(image_pixel(router.clone(), route_of(&url_a)).await, red); - assert_eq!(image_pixel(router.clone(), route_of(&url_b)).await, blue); - // Cached requests, and the old A URL after B was registered, retain their source. - assert_eq!(image_pixel(router.clone(), route_of(&url_b)).await, blue); - assert_eq!(image_pixel(router.clone(), route_of(&url_a)).await, red); - assert_eq!(image_pixel(router, "/images/shot-1/strip").await, red); - runtime.stop().await.unwrap(); -} - -#[tokio::test] -async fn thumbnails_work_when_the_database_appears_after_an_empty_startup() { - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("game"); - let runtime = StreamRuntime::default(); - let server = TestServer::default(); - runtime - .prepare_history_thumbnails_with(&server, || StreamInstallation { - game_path: Some(game_path.clone()), - record_game_path: None, - }) - .await - .unwrap(); - assert!(!crate::services::paths::database_path(&game_path).exists()); - let color = [20, 80, 160, 255]; - screenshot_fixture(&game_path, color); - let thumbnails = HistoryThumbnails::default(); - let uri = url(thumbnails.register(&game_path), "shot-1"); - runtime - .prepare_history_thumbnails_with(&server, || panic!("running OBS must not be rebound")) - .await - .unwrap(); - // An unbound OBS repository must not be consulted for History's image path. - let router = history_router( - &runtime, - &thumbnails, - &temp.path().join("unbound"), - temp.path(), - ); - assert_eq!(image_pixel(router, route_of(&uri)).await, color); - assert_eq!(server.starts.load(Ordering::SeqCst), 1); - runtime.stop().await.unwrap(); -} - -#[tokio::test] -async fn preparation_coalesces_starts_and_recovers_after_stop() { - let runtime = StreamRuntime::default(); - let server = TestServer::default(); - let (first, second) = tokio::join!( - runtime.prepare_history_thumbnails_with(&server, || installation("/A")), - runtime.prepare_history_thumbnails_with(&server, || installation("/B")), - ); - first.unwrap(); - second.unwrap(); - assert!(runtime.snapshot().running); - assert_eq!(server.starts.load(Ordering::SeqCst), 1); - runtime.stop().await.unwrap(); - assert!(!runtime.snapshot().running); - runtime - .prepare_history_thumbnails_with(&server, || installation("/B")) - .await - .unwrap(); - assert!(runtime.snapshot().running); - assert_eq!(server.starts.load(Ordering::SeqCst), 2); - runtime.stop().await.unwrap(); -} - -#[tokio::test] -async fn preparation_waits_for_maintenance_and_then_resumes() { - let runtime = StreamRuntime::default(); - let server = TestServer::default(); - runtime - .prepare_history_thumbnails_with(&server, || installation("/A")) - .await - .unwrap(); - let entered = Arc::new(Notify::new()); - let release = Arc::new(Notify::new()); - let worker = runtime.clone(); - let entering = entered.clone(); - let releasing = release.clone(); - let maintenance = tokio::spawn(async move { - worker - .exclusive_maintenance(|| async move { - entering.notify_one(); - releasing.notified().await; - Ok(()) - }) - .await - }); - entered.notified().await; - let worker = runtime.clone(); - let starting_server = server.clone(); - let preparation = tokio::spawn(async move { - worker - .prepare_history_thumbnails_with(&starting_server, || installation("/A")) - .await - }); - for _ in 0..8 { - tokio::task::yield_now().await; - } - assert!(!preparation.is_finished()); - assert!(!runtime.snapshot().running); - assert_eq!(server.starts.load(Ordering::SeqCst), 1); - release.notify_one(); - maintenance.await.unwrap().unwrap(); - preparation.await.unwrap().unwrap(); - assert!(runtime.snapshot().running); - assert_eq!(server.starts.load(Ordering::SeqCst), 2); - runtime.stop().await.unwrap(); -} - -#[tokio::test] -async fn history_preparation_keeps_start_errors_visible_to_stream_status() { - let runtime = StreamRuntime::default(); - let server = TestServer::failing("port occupied"); - assert_eq!( - runtime - .prepare_history_thumbnails_with(&server, || installation("/A")) - .await - .unwrap_err(), - "port occupied" - ); - assert!(!runtime.snapshot().running); - assert_eq!( - runtime.snapshot().last_error.as_deref(), - Some("port occupied") - ); -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/http.rs b/bazaarplusplus-installer/src-tauri/src/stream/http.rs deleted file mode 100644 index 5b0c914..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/http.rs +++ /dev/null @@ -1,757 +0,0 @@ -use super::history_thumbnails::{self, HistoryThumbnails}; -use super::overlay_settings::{validate_crop_settings, OverlayCropSettings, OverlaySettingsStore}; -use super::records::OverlayRecordRepository; -use super::runtime::StreamRuntime; -use super::strip::{render_strip, StripRequest}; -use axum::http::StatusCode; -use axum::{ - extract::{Path, Query, State}, - http::{header, HeaderValue, Method}, - response::{Html, IntoResponse, Response}, - routing::get, - Json, Router, -}; -use include_dir::{include_dir, Dir}; -use serde::Deserialize; -use std::{ - borrow::Cow, - path::{Path as FsPath, PathBuf}, -}; -use tower_http::cors::{AllowOrigin, CorsLayer}; - -const OVERLAY_HTML: &str = include_str!("../../resources/stream/overlay.html"); -const OVERLAY_CSS: &str = include_str!("../../resources/stream/overlay.css"); -const OVERLAY_JS: &str = include_str!("../../resources/stream/overlay.js"); -const SETTINGS_HTML: &str = include_str!("../../resources/stream/settings.html"); -const SETTINGS_CSS: &str = include_str!("../../resources/stream/settings.css"); -const SETTINGS_JS: &str = include_str!("../../resources/stream/settings.js"); -static BADGES_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/resources/stream/badges"); -const CINZEL_FONT: &[u8] = include_bytes!("../../resources/stream/fonts/cinzel-latin.woff2"); -const OVERLAY_ROUTE: &str = "/overlay"; -const SETTINGS_ROUTE: &str = "/settings"; -const LATEST_RECORD_ROUTE: &str = "/api/stream/records/latest"; -const RECORD_LIST_ROUTE: &str = "/api/stream/records"; -const CROP_CONFIG_ROUTE: &str = "/api/overlay/crop-config"; -const STRIP_IMAGE_ROUTE: &str = "/images/{record_id}/strip"; -const RECORD_IMAGE_ROUTE: &str = "/images/{record_id}"; -const OVERLAY_CSS_ROUTE: &str = "/assets/overlay.css"; -const OVERLAY_JS_ROUTE: &str = "/assets/overlay.js"; -const SETTINGS_CSS_ROUTE: &str = "/assets/settings.css"; -const SETTINGS_JS_ROUTE: &str = "/assets/settings.js"; -const BADGE_ROUTE: &str = "/assets/badges/{category}/{file_name}"; -const CINZEL_FONT_ROUTE: &str = "/assets/fonts/cinzel-latin.woff2"; - -#[derive(Clone)] -struct HttpAppState { - overlay_records: OverlayRecordRepository, - runtime: StreamRuntime, - overlay_settings: OverlaySettingsStore, - cache_directory: PathBuf, -} - -#[derive(Debug, Deserialize)] -struct LatestRecordQuery { - offset: Option, - from: Option, -} - -#[derive(Debug, Deserialize)] -struct RecordListQuery { - limit: Option, - from: Option, -} - -#[derive(Debug, Deserialize)] -struct SaveCropConfigRequest { - crop: OverlayCropSettings, -} - -#[derive(Debug, Deserialize)] -struct StripPreviewQuery { - left: Option, - top: Option, - width: Option, - height: Option, - preview: Option, -} - -pub(super) fn router( - overlay_records: OverlayRecordRepository, - runtime: StreamRuntime, - history_thumbnails: HistoryThumbnails, - overlay_settings: OverlaySettingsStore, - cache_directory: PathBuf, -) -> Router { - let cors = CorsLayer::new() - .allow_origin(AllowOrigin::predicate(|origin, _| { - is_allowed_cors_origin(origin) - })) - .allow_methods([Method::GET, Method::POST]) - .allow_headers([header::CONTENT_TYPE]); - - let history_thumbnails = history_thumbnails::router( - history_thumbnails, - overlay_settings.clone(), - cache_directory.clone(), - ); - - Router::new() - .route(OVERLAY_ROUTE, get(overlay_page)) - .route(SETTINGS_ROUTE, get(settings_page)) - .route(LATEST_RECORD_ROUTE, get(latest_record)) - .route(RECORD_LIST_ROUTE, get(record_list)) - .route( - CROP_CONFIG_ROUTE, - get(get_crop_config).post(save_crop_config), - ) - .route(STRIP_IMAGE_ROUTE, get(record_strip_image)) - .route(RECORD_IMAGE_ROUTE, get(record_image)) - .route(OVERLAY_CSS_ROUTE, get(overlay_css)) - .route(OVERLAY_JS_ROUTE, get(overlay_js)) - .route(SETTINGS_CSS_ROUTE, get(settings_css)) - .route(SETTINGS_JS_ROUTE, get(settings_js)) - .route(BADGE_ROUTE, get(badge_asset)) - .route(CINZEL_FONT_ROUTE, get(cinzel_font)) - .with_state(HttpAppState { - overlay_records, - runtime, - overlay_settings, - cache_directory, - }) - .merge(history_thumbnails) - .layer(cors) -} - -fn is_allowed_cors_origin(origin: &HeaderValue) -> bool { - matches!( - origin.to_str().ok(), - Some( - "tauri://localhost" - | "http://tauri.localhost" - | "https://tauri.localhost" - | "http://localhost:14207" - | "http://127.0.0.1:14207" - ) - ) -} - -#[cfg(any(debug_assertions, test))] -fn overlay_asset_path(file_name: &str) -> PathBuf { - FsPath::new(env!("CARGO_MANIFEST_DIR")) - .join("resources") - .join("stream") - .join(file_name) -} - -#[cfg(debug_assertions)] -fn badge_asset_path(category: &str, file_name: &str) -> PathBuf { - FsPath::new(env!("CARGO_MANIFEST_DIR")) - .join("resources") - .join("stream") - .join("badges") - .join(category) - .join(file_name) -} - -/// Borrowed in release so the six static asset routes serve the embedded text -/// without copying; owned only on the debug-only filesystem hot-reload path. -async fn load_overlay_asset(_file_name: &str, embedded: &'static str) -> Cow<'static, str> { - #[cfg(debug_assertions)] - { - let path = overlay_asset_path(_file_name); - let read = move || std::fs::read_to_string(path).map_err(|err| err.to_string()); - if let Ok(contents) = run_record_task(read).await { - return Cow::Owned(contents); - } - } - - Cow::Borrowed(embedded) -} - -async fn overlay_page() -> Html> { - Html(load_overlay_asset("overlay.html", OVERLAY_HTML).await) -} - -async fn settings_page() -> Html> { - Html(load_overlay_asset("settings.html", SETTINGS_HTML).await) -} - -async fn latest_record( - State(app_state): State, - Query(query): Query, -) -> Response { - let offset = query.offset.unwrap_or(0); - let snapshot = app_state.runtime.snapshot(); - let from = query.from.or(snapshot.active_from); - let repository = app_state.overlay_records; - - match run_record_task(move || repository.load_record_at_offset(from.as_deref(), offset)).await { - Ok(record) => Json(record).into_response(), - Err(message) => (StatusCode::INTERNAL_SERVER_ERROR, message).into_response(), - } -} - -async fn record_list( - State(app_state): State, - Query(query): Query, -) -> Response { - let limit = query.limit.unwrap_or(20); - let snapshot = app_state.runtime.snapshot(); - let from = query.from.or(snapshot.active_from); - let repository = app_state.overlay_records; - - match run_record_task(move || repository.load_record_list(from.as_deref(), Some(limit))).await { - Ok(records) => Json(records).into_response(), - Err(message) => (StatusCode::INTERNAL_SERVER_ERROR, message).into_response(), - } -} - -async fn get_crop_config(State(app_state): State) -> Response { - let settings = app_state.overlay_settings; - match run_record_task(move || settings.load_payload()).await { - Ok(payload) => Json(payload).into_response(), - Err(message) => (StatusCode::INTERNAL_SERVER_ERROR, message).into_response(), - } -} - -async fn save_crop_config( - State(app_state): State, - Json(request): Json, -) -> Response { - let settings = app_state.overlay_settings; - match run_record_task(move || settings.save(request.crop)).await { - Ok(payload) => Json(payload).into_response(), - Err(message) => (StatusCode::BAD_REQUEST, message).into_response(), - } -} - -async fn record_image( - Path(record_id): Path, - State(app_state): State, -) -> Response { - let repository = app_state.overlay_records; - let (path, bytes) = match run_record_task(move || repository.load_image(&record_id)).await { - Ok(Some(value)) => value, - Ok(None) => return StatusCode::NOT_FOUND.into_response(), - Err(message) => return (StatusCode::INTERNAL_SERVER_ERROR, message).into_response(), - }; - - let content_type = detect_content_type(&path); - - ( - [( - header::CONTENT_TYPE, - HeaderValue::from_str(content_type) - .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")), - )], - bytes, - ) - .into_response() -} - -async fn record_strip_image( - Path(record_id): Path, - Query(query): Query, - State(app_state): State, -) -> Response { - let crop = match requested_strip_crop(&query) { - Ok(crop) => crop, - Err(message) => return (StatusCode::BAD_REQUEST, message).into_response(), - }; - let request = StripRequest { - record_id, - crop, - preview: query.preview.unwrap_or(false), - }; - let records = app_state.overlay_records; - let settings = app_state.overlay_settings; - let cache_root = app_state.cache_directory; - - match run_record_task(move || render_strip(&records, &settings, &cache_root, &request)).await { - Ok(Some(bytes)) => png_response(bytes), - Ok(None) => StatusCode::NOT_FOUND.into_response(), - Err(message) => (StatusCode::INTERNAL_SERVER_ERROR, message).into_response(), - } -} - -/// A rendered strip; `no-store` because the saved crop can change its pixels. -pub(super) fn png_response(bytes: Vec) -> Response { - ( - [ - (header::CONTENT_TYPE, HeaderValue::from_static("image/png")), - (header::CACHE_CONTROL, HeaderValue::from_static("no-store")), - ], - bytes, - ) - .into_response() -} - -/// Every SQLite or filesystem access a handler makes runs here: a SQLite open -/// can sleep on a busy database, and file reads and writes block, so none may -/// run on the shared tokio workers that also serve the Tauri async commands. -pub(super) async fn run_record_task(task: F) -> Result -where - T: Send + 'static, - F: FnOnce() -> Result + Send + 'static, -{ - tauri::async_runtime::spawn_blocking(task) - .await - .map_err(|err| format!("Overlay record task failed: {err}"))? -} - -/// A crop given in the query, validated before any blocking work; `None` means -/// the saved overlay settings apply. -fn requested_strip_crop(query: &StripPreviewQuery) -> Result, String> { - if query.left.is_none() - && query.top.is_none() - && query.width.is_none() - && query.height.is_none() - { - return Ok(None); - } - - let defaults = OverlayCropSettings::default(); - validate_crop_settings(OverlayCropSettings { - left: query.left.unwrap_or(defaults.left), - top: query.top.unwrap_or(defaults.top), - width: query.width.unwrap_or(defaults.width), - height: query.height.unwrap_or(defaults.height), - }) - .map(Some) -} - -fn detect_content_type(path: &FsPath) -> &'static str { - match path - .extension() - .and_then(|ext| ext.to_str()) - .map(str::to_ascii_lowercase) - .as_deref() - { - Some("png") => "image/png", - Some("jpg" | "jpeg") => "image/jpeg", - Some("webp") => "image/webp", - _ => "application/octet-stream", - } -} - -async fn overlay_css() -> Response { - ( - [( - header::CONTENT_TYPE, - HeaderValue::from_static("text/css; charset=utf-8"), - )], - load_overlay_asset("overlay.css", OVERLAY_CSS).await, - ) - .into_response() -} - -async fn overlay_js() -> Response { - ( - [( - header::CONTENT_TYPE, - HeaderValue::from_static("application/javascript; charset=utf-8"), - )], - load_overlay_asset("overlay.js", OVERLAY_JS).await, - ) - .into_response() -} - -async fn settings_css() -> Response { - ( - [( - header::CONTENT_TYPE, - HeaderValue::from_static("text/css; charset=utf-8"), - )], - load_overlay_asset("settings.css", SETTINGS_CSS).await, - ) - .into_response() -} - -async fn settings_js() -> Response { - ( - [( - header::CONTENT_TYPE, - HeaderValue::from_static("application/javascript; charset=utf-8"), - )], - load_overlay_asset("settings.js", SETTINGS_JS).await, - ) - .into_response() -} - -async fn cinzel_font() -> Response { - ( - [ - (header::CONTENT_TYPE, HeaderValue::from_static("font/woff2")), - ( - header::CACHE_CONTROL, - HeaderValue::from_static("public, max-age=31536000, immutable"), - ), - ], - CINZEL_FONT, - ) - .into_response() -} - -async fn badge_asset(Path((category, file_name)): Path<(String, String)>) -> Response { - if !file_name.ends_with(".svg") { - return StatusCode::NOT_FOUND.into_response(); - } - - #[cfg(debug_assertions)] - { - let path = badge_asset_path(&category, &file_name); - let read = move || std::fs::read(path).map_err(|err| err.to_string()); - if let Ok(bytes) = run_record_task(read).await { - return ( - [( - header::CONTENT_TYPE, - HeaderValue::from_static("image/svg+xml; charset=utf-8"), - )], - bytes, - ) - .into_response(); - } - } - - let relative = format!("{category}/{file_name}"); - match BADGES_DIR.get_file(&relative) { - Some(file) => ( - [( - header::CONTENT_TYPE, - HeaderValue::from_static("image/svg+xml; charset=utf-8"), - )], - file.contents(), - ) - .into_response(), - None => StatusCode::NOT_FOUND.into_response(), - } -} - -#[cfg(test)] -mod tests { - use super::{ - history_thumbnails, router, HistoryThumbnails, OverlayRecordRepository, - OverlaySettingsStore, StreamRuntime, - }; - use super::{ - is_allowed_cors_origin, BADGES_DIR, BADGE_ROUTE, CINZEL_FONT, CINZEL_FONT_ROUTE, - CROP_CONFIG_ROUTE, LATEST_RECORD_ROUTE, OVERLAY_CSS, OVERLAY_CSS_ROUTE, OVERLAY_JS_ROUTE, - OVERLAY_ROUTE, RECORD_IMAGE_ROUTE, RECORD_LIST_ROUTE, SETTINGS_CSS_ROUTE, - SETTINGS_JS_ROUTE, SETTINGS_ROUTE, STRIP_IMAGE_ROUTE, - }; - use axum::http::HeaderValue; - - #[test] - fn embedded_badge_assets_are_complete_for_every_hero() { - for hero_key in [ - "van", "pyg", "doo", "mak", "jul", "kar", "ste", "dra", "unk", - ] { - for path in [ - format!("heroes/hero-{hero_key}.svg"), - format!("herohalf/herohalf-{hero_key}.svg"), - ] { - assert!(BADGES_DIR.get_file(&path).is_some(), "missing {path}"); - } - - for battle_count in 0..=20 { - let path = format!("info/info-{hero_key}-{battle_count}.svg"); - assert!(BADGES_DIR.get_file(&path).is_some(), "missing {path}"); - } - } - } - - #[test] - fn production_routes_remain_stable() { - assert_eq!( - [ - OVERLAY_ROUTE, - SETTINGS_ROUTE, - LATEST_RECORD_ROUTE, - RECORD_LIST_ROUTE, - CROP_CONFIG_ROUTE, - STRIP_IMAGE_ROUTE, - history_thumbnails::ROUTE, - RECORD_IMAGE_ROUTE, - OVERLAY_CSS_ROUTE, - OVERLAY_JS_ROUTE, - SETTINGS_CSS_ROUTE, - SETTINGS_JS_ROUTE, - BADGE_ROUTE, - CINZEL_FONT_ROUTE, - ], - [ - "/overlay", - "/settings", - "/api/stream/records/latest", - "/api/stream/records", - "/api/overlay/crop-config", - "/images/{record_id}/strip", - "/history/{source}/images/{screenshot_id}/strip", - "/images/{record_id}", - "/assets/overlay.css", - "/assets/overlay.js", - "/assets/settings.css", - "/assets/settings.js", - "/assets/badges/{category}/{file_name}", - "/assets/fonts/cinzel-latin.woff2", - ] - ); - } - - #[test] - fn overlay_css_font_url_resolves_to_a_served_route() { - assert!( - OVERLAY_CSS.contains(&format!("url('{CINZEL_FONT_ROUTE}')")), - "overlay.css must load the brand face from the route the server exposes" - ); - assert_eq!( - &CINZEL_FONT[..4], - b"wOF2", - "the embedded brand face must be a woff2 payload" - ); - } - - #[test] - fn cors_origin_policy_allows_only_tauri_and_repo_dev_origins() { - for allowed in [ - "tauri://localhost", - "http://tauri.localhost", - "https://tauri.localhost", - "http://localhost:14207", - "http://127.0.0.1:14207", - ] { - let origin = HeaderValue::from_static(allowed); - assert!( - is_allowed_cors_origin(&origin), - "{allowed} should be allowed" - ); - } - - for denied in ["https://example.com", "http://localhost:3000", "null"] { - let origin = HeaderValue::from_static(denied); - assert!( - !is_allowed_cors_origin(&origin), - "{denied} should be denied" - ); - } - } - - fn locked_screenshot_fixture(game_path: &std::path::Path) -> rusqlite::Connection { - let screenshots = crate::services::paths::screenshots_dir(game_path); - std::fs::create_dir_all(&screenshots).unwrap(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([20, 80, 160, 255])) - .save(screenshots.join("shot.png")) - .unwrap(); - // The default rollback journal lets an exclusive lock block readers, as a - // game write or checkpoint can. - let connection = - rusqlite::Connection::open(crate::services::paths::database_path(game_path)).unwrap(); - crate::history::mod_schema::create_mod_schema(&connection); - connection - .execute_batch( - "insert into run_screenshots ( - screenshot_id, capture_source, image_relative_path, hero_name, - captured_utc_offset_minutes, captured_at_ms, victories_at_capture, day - ) values ( - 'shot-1', 'end_of_run_auto', 'shot.png', 'Vanessa', - 0, 1788220800000, 10, 10 - ); - begin exclusive;", - ) - .unwrap(); - connection - } - - #[tokio::test] - async fn strip_requests_leave_the_async_runtime_free_while_the_database_is_locked() { - use tower::ServiceExt; - let temp = tempfile::tempdir().unwrap(); - let game_path = temp.path().join("game"); - let lock = locked_screenshot_fixture(&game_path); - let thumbnails = HistoryThumbnails::default(); - let thumbnail_url = history_thumbnails::url(thumbnails.register(&game_path), "shot-1"); - let app = router( - OverlayRecordRepository::new(Some(game_path)), - StreamRuntime::default(), - thumbnails, - OverlaySettingsStore::new(temp.path().join("settings.json"), None), - temp.path().join("cache"), - ); - let requests = [ - "/images/shot-1/strip".to_string(), - thumbnail_url.replace("http://127.0.0.1:17654", ""), - "/images/shot-1/strip?preview=true&left=0.1".to_string(), - ] - .map(|uri| { - tokio::spawn( - app.clone().oneshot( - axum::http::Request::builder() - .uri(uri) - .body(axum::body::Body::empty()) - .unwrap(), - ), - ) - }); - - // This current-thread runtime is the only worker: the ticker advances - // only if every pending strip request has yielded it. - let started = std::time::Instant::now(); - for _ in 0..32 { - tokio::task::yield_now().await; - } - assert!( - started.elapsed() < std::time::Duration::from_millis(500), - "ticker stalled for {:?}", - started.elapsed() - ); - assert!(requests.iter().all(|request| !request.is_finished())); - - drop(lock); - for request in requests { - let response = request.await.unwrap().unwrap(); - let status = response.status(); - let headers = response.headers().clone(); - let body = axum::body::to_bytes(response.into_body(), 1024 * 1024) - .await - .unwrap(); - assert_eq!( - status, - axum::http::StatusCode::OK, - "{}", - String::from_utf8_lossy(&body) - ); - assert_eq!(headers["content-type"], "image/png"); - assert_eq!(headers["cache-control"], "no-store"); - image::load_from_memory(&body).unwrap(); - } - } - - /// Opening a FIFO blocks until the other end opens, so the settings file - /// stalls whichever thread reads or writes it until `serve` runs. - #[cfg(unix)] - fn blocking_settings_file( - path: &std::path::Path, - serve: impl FnOnce(&std::path::Path) + Send + 'static, - ) -> std::sync::mpsc::Sender<()> { - let status = std::process::Command::new("mkfifo") - .arg(path) - .status() - .unwrap(); - assert!(status.success()); - let (release, released) = std::sync::mpsc::channel(); - let path = path.to_path_buf(); - std::thread::spawn(move || { - // Serves anyway after the timeout, so a handler that blocks the - // runtime fails the ticker assertion instead of hanging the test. - let _ = released.recv_timeout(std::time::Duration::from_secs(2)); - serve(&path); - }); - release - } - - #[cfg(unix)] - async fn assert_request_leaves_the_async_runtime_free( - app: axum::Router, - request: axum::http::Request, - release: std::sync::mpsc::Sender<()>, - ) -> (axum::http::StatusCode, serde_json::Value) { - use tower::ServiceExt; - let request = tokio::spawn(app.oneshot(request)); - - // This current-thread runtime is the only worker: the ticker advances - // only if the pending request has yielded it. - let started = std::time::Instant::now(); - for _ in 0..32 { - tokio::task::yield_now().await; - } - assert!( - started.elapsed() < std::time::Duration::from_millis(500), - "ticker stalled for {:?}", - started.elapsed() - ); - assert!(!request.is_finished()); - - release.send(()).unwrap(); - let response = request.await.unwrap().unwrap(); - let status = response.status(); - let body = axum::body::to_bytes(response.into_body(), 1024 * 1024) - .await - .unwrap(); - (status, serde_json::from_slice(&body).unwrap()) - } - - #[cfg(unix)] - #[tokio::test] - async fn crop_config_requests_leave_the_async_runtime_free_while_the_settings_file_blocks() { - use std::io::{Read, Write}; - let temp = tempfile::tempdir().unwrap(); - let settings_path = temp.path().join("settings.json"); - let app = router( - OverlayRecordRepository::new(None), - StreamRuntime::default(), - HistoryThumbnails::default(), - OverlaySettingsStore::new(settings_path.clone(), None), - temp.path().join("cache"), - ); - let saved = serde_json::json!({ - "v": 4, - "crop": { "left": 0.1, "top": 0.2, "width": 0.3, "height": 0.4 }, - "display_mode": "hero" - }); - - let document = saved.to_string(); - let release = blocking_settings_file(&settings_path, move |path| { - let mut writer = std::fs::OpenOptions::new().write(true).open(path).unwrap(); - writer.write_all(document.as_bytes()).unwrap(); - }); - let (status, payload) = assert_request_leaves_the_async_runtime_free( - app.clone(), - axum::http::Request::builder() - .uri(CROP_CONFIG_ROUTE) - .body(axum::body::Body::empty()) - .unwrap(), - release, - ) - .await; - assert_eq!(status, axum::http::StatusCode::OK); - assert_eq!( - payload["crop"], - serde_json::json!({ "left": 0.1, "top": 0.2, "width": 0.3, "height": 0.4 }) - ); - assert_eq!(payload["display_mode"], "hero"); - - std::fs::remove_file(&settings_path).unwrap(); - let (written_tx, written_rx) = std::sync::mpsc::channel(); - let release = blocking_settings_file(&settings_path, move |path| { - // An empty read makes the save keep the default display mode. - drop(std::fs::OpenOptions::new().write(true).open(path).unwrap()); - let mut written = String::new(); - std::fs::File::open(path) - .unwrap() - .read_to_string(&mut written) - .unwrap(); - written_tx.send(written).unwrap(); - }); - let (status, payload) = assert_request_leaves_the_async_runtime_free( - app, - axum::http::Request::builder() - .method("POST") - .uri(CROP_CONFIG_ROUTE) - .header("content-type", "application/json") - .body(axum::body::Body::from( - r#"{"crop":{"left":0.25,"top":0.25,"width":0.5,"height":0.5}}"#, - )) - .unwrap(), - release, - ) - .await; - assert_eq!(status, axum::http::StatusCode::OK); - assert_eq!( - payload["crop"], - serde_json::json!({ "left": 0.25, "top": 0.25, "width": 0.5, "height": 0.5 }) - ); - let written: serde_json::Value = serde_json::from_str(&written_rx.recv().unwrap()).unwrap(); - assert_eq!(written["crop"], payload["crop"]); - assert_eq!(written["display_mode"], "current"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/http_golden_tests.rs b/bazaarplusplus-installer/src-tauri/src/stream/http_golden_tests.rs deleted file mode 100644 index 58f9f18..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/http_golden_tests.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! HTTP goldens for the stream service: requests go through the production -//! `router` with `tower::ServiceExt::oneshot` against a fixture database, the -//! committed screenshots in `tests/goldens/http/fixtures/` and a temporary -//! cache directory. -//! -//! Writes `tests/goldens/http/records.json`, `records-latest.json` and -//! `strip-hashes.json` (the sha256 of every rendered strip PNG). Regenerate with -//! `BPP_UPDATE_GOLDENS=1 npm run generate:bindings:test` (see the installer `AGENTS.md`); -//! an `image` crate upgrade can change the PNG bytes, which needs a regenerate -//! and a note in the pull request. - -use super::history_thumbnails::{self, HistoryThumbnails}; -use super::http::router; -use super::overlay_settings::OverlaySettingsStore; -use super::records::OverlayRecordRepository; -use super::runtime::StreamRuntime; -use crate::goldens::{assert_golden, golden_path, json}; -use crate::history::mod_schema::create_mod_schema; -use crate::services::paths; -use sha2::{Digest, Sha256}; -use tower::ServiceExt; - -/// One screenshot per subtitle shape: wins and battles, wins only, battles only -/// (its image file is missing, so it has no strip), and neither. -fn seed(game: &std::path::Path) { - let screenshots = paths::screenshots_dir(game); - std::fs::create_dir_all(screenshots.join("2026-01-01")).unwrap(); - for name in ["run-a.png", "run-b.png"] { - std::fs::copy( - golden_path(&format!("http/fixtures/{name}")), - screenshots.join("2026-01-01").join(name), - ) - .unwrap(); - } - let conn = rusqlite::Connection::open(paths::database_path(game)).unwrap(); - create_mod_schema(&conn); - conn.execute_batch( - " - insert into run_screenshots ( - screenshot_id, run_id, hero_name, capture_source, is_primary, image_relative_path, - captured_at_ms, captured_utc_offset_minutes, day, victories_at_capture, player_rank, - player_rating - ) values - ('shot-1', 'run-1', 'Vanessa', 'end_of_run_auto', 1, '2026-01-01/run-a.png', - 1767260400000, 480, 14, 10, 'Gold', 1520), - ('shot-2', 'run-2', 'Hero8', 'end_of_run_auto', 1, '2026-01-01/run-b.png', - 1767259800000, 480, null, 7, null, null), - ('shot-3', 'run-3', 'Mak', 'end_of_run_auto', 1, '2026-01-01/missing.png', - 1767259200000, 480, 3, null, null, null), - ('shot-4', 'run-4', null, 'end_of_run_auto', 1, '2026-01-01/run-a.png', - 1767258600000, 480, null, null, null, null); - ", - ) - .unwrap(); -} - -async fn get(app: &axum::Router, uri: &str) -> (axum::http::StatusCode, Vec) { - let response = app - .clone() - .oneshot( - axum::http::Request::builder() - .uri(uri) - .body(axum::body::Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = axum::body::to_bytes(response.into_body(), 16 * 1024 * 1024) - .await - .unwrap(); - (status, body.to_vec()) -} - -#[tokio::test] -async fn stream_routes_match_goldens() { - let temp = tempfile::tempdir().unwrap(); - let game = temp.path().join("The Bazaar"); - seed(&game); - let thumbnails = HistoryThumbnails::default(); - let source = thumbnails.register(&game); - let app = router( - OverlayRecordRepository::new(Some(game.clone())), - StreamRuntime::default(), - thumbnails, - OverlaySettingsStore::new(temp.path().join("settings.json"), None), - temp.path().join("cache"), - ); - let roots = [(game.as_path(), "")]; - - for (uri, golden) in [ - ("/api/stream/records", "http/records.json"), - ("/api/stream/records/latest", "http/records-latest.json"), - ] { - let (status, body) = get(&app, uri).await; - assert_eq!(status, axum::http::StatusCode::OK, "{uri}"); - let value: serde_json::Value = serde_json::from_slice(&body).unwrap(); - assert_golden(golden, &json(&value, &roots)); - } - - let mut hashes = Vec::new(); - for record in ["shot-1", "shot-2", "shot-3", "shot-4"] { - let thumbnail = history_thumbnails::url(source, record); - let thumbnail = &thumbnail[thumbnail.find("/history/").unwrap()..]; - for (route, uri) in [ - ( - "/images/{record_id}/strip", - format!("/images/{record}/strip"), - ), - (history_thumbnails::ROUTE, thumbnail.to_string()), - ] { - let (status, body) = get(&app, &uri).await; - let sha256 = (status == axum::http::StatusCode::OK).then(|| { - Sha256::digest(&body) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::() - }); - hashes.push(serde_json::json!({ - "route": route, - "record": record, - "status": status.as_u16(), - "sha256": sha256, - })); - } - } - assert_golden("http/strip-hashes.json", &json(&hashes, &roots)); -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/mod.rs b/bazaarplusplus-installer/src-tauri/src/stream/mod.rs deleted file mode 100644 index f332660..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -pub(crate) mod history_thumbnails; -mod http; -#[cfg(test)] -mod http_golden_tests; -pub(crate) mod overlay_settings; -mod records; -pub(crate) mod runtime; -mod server; -pub(crate) mod state; -mod strip; diff --git a/bazaarplusplus-installer/src-tauri/src/stream/overlay_settings.rs b/bazaarplusplus-installer/src-tauri/src/stream/overlay_settings.rs deleted file mode 100644 index a115b17..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/overlay_settings.rs +++ /dev/null @@ -1,451 +0,0 @@ -use base64::{engine::general_purpose::STANDARD, Engine as _}; -use serde::{Deserialize, Serialize}; -use std::path::PathBuf; - -const OVERLAY_SETTINGS_VERSION: u8 = 4; - -#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, specta::Type)] -#[serde(rename = "StreamOverlayCropSettings")] -pub struct OverlayCropSettings { - pub left: f64, - pub top: f64, - pub width: f64, - pub height: f64, -} - -#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Default, specta::Type)] -#[serde(rename = "StreamOverlayDisplayMode")] -#[serde(rename_all = "snake_case")] -pub enum StreamOverlayDisplayMode { - #[default] - Current, - Hero, - Herohalf, -} - -#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq)] -pub struct OverlaySettings { - pub crop: OverlayCropSettings, - pub display_mode: StreamOverlayDisplayMode, -} - -impl Default for OverlayCropSettings { - fn default() -> Self { - Self { - left: 0.342, - top: 0.313, - width: 0.58, - height: 0.22, - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] -struct OverlayCropDocument { - v: u8, - #[serde(flatten)] - settings: OverlaySettings, -} - -#[derive(Clone, Debug, Serialize, PartialEq, specta::Type)] -#[serde(rename = "StreamOverlayCropSettingsPayload")] -pub struct OverlayCropSettingsPayload { - pub crop: OverlayCropSettings, - pub code: String, - pub display_mode: StreamOverlayDisplayMode, -} - -#[derive(Clone, Debug)] -pub struct OverlaySettingsStore { - path: PathBuf, - legacy_path: Option, -} - -impl Default for OverlaySettingsStore { - fn default() -> Self { - Self::new(default_settings_path(), Some(legacy_settings_path())) - } -} - -impl OverlaySettingsStore { - pub(crate) fn new(path: PathBuf, legacy_path: Option) -> Self { - Self { path, legacy_path } - } - - pub fn load(&self) -> Result { - let read_path = if self.path.exists() { - &self.path - } else if let Some(legacy_path) = self - .legacy_path - .as_ref() - .filter(|legacy_path| legacy_path.exists()) - { - legacy_path - } else { - return Ok(OverlaySettings::default()); - }; - - let raw = match std::fs::read_to_string(read_path) { - Ok(raw) => raw, - Err(err) => { - crate::services::debug_error!( - "Failed to read overlay crop settings from {}: {err}", - read_path.display() - ); - return Ok(OverlaySettings::default()); - } - }; - let document = match serde_json::from_str::(&raw) { - Ok(document) => document, - Err(err) => { - crate::services::debug_error!( - "Failed to parse overlay crop settings from {}: {err}", - read_path.display() - ); - return Ok(OverlaySettings::default()); - } - }; - if document.v != OVERLAY_SETTINGS_VERSION { - crate::services::debug_error!( - "Unsupported overlay crop settings version {}.", - document.v - ); - return Ok(OverlaySettings::default()); - } - - let crop = match validate_crop_settings(document.settings.crop) { - Ok(crop) => crop, - Err(err) => { - crate::services::debug_error!( - "Invalid overlay crop settings in {}: {err}", - read_path.display() - ); - return Ok(OverlaySettings::default()); - } - }; - Ok(OverlaySettings { - crop, - display_mode: document.settings.display_mode, - }) - } - - pub fn save(&self, crop: OverlayCropSettings) -> Result { - let crop = validate_crop_settings(crop)?; - let display_mode = self - .load() - .map(|settings| settings.display_mode) - .unwrap_or_default(); - self.write_settings(OverlaySettings { crop, display_mode }) - } - - pub fn save_display_mode( - &self, - display_mode: StreamOverlayDisplayMode, - ) -> Result { - let crop = self - .load() - .map(|settings| settings.crop) - .unwrap_or_default(); - self.write_settings(OverlaySettings { crop, display_mode }) - } - - fn write_settings( - &self, - settings: OverlaySettings, - ) -> Result { - let document = OverlayCropDocument { - v: OVERLAY_SETTINGS_VERSION, - settings, - }; - let raw = serde_json::to_string_pretty(&document) - .map_err(|err| format!("Failed to serialize overlay crop settings: {err}"))?; - - if let Some(parent) = self.path.parent() { - std::fs::create_dir_all(parent).map_err(|err| { - format!( - "Failed to create overlay settings directory {}: {err}", - parent.display() - ) - })?; - } - - std::fs::write(&self.path, raw).map_err(|err| { - format!( - "Failed to write overlay crop settings to {}: {err}", - self.path.display() - ) - })?; - - Ok(self.payload(settings)) - } - - pub fn payload(&self, settings: OverlaySettings) -> OverlayCropSettingsPayload { - OverlayCropSettingsPayload { - crop: settings.crop, - code: encode_crop_code(settings.crop), - display_mode: settings.display_mode, - } - } - - pub fn load_payload(&self) -> Result { - let settings = self.load()?; - Ok(self.payload(settings)) - } - - pub fn import_code(&self, code: &str) -> Result { - let crop = decode_crop_code(code)?; - self.save(crop) - } -} - -fn default_settings_path() -> PathBuf { - crate::services::paths::overlay_settings_path() -} - -fn legacy_settings_path() -> PathBuf { - crate::services::paths::legacy_overlay_settings_path() -} - -pub fn validate_crop_settings(crop: OverlayCropSettings) -> Result { - fn valid_ratio(value: f64) -> bool { - value.is_finite() && value > 0.0 && value < 1.0 - } - - if !valid_ratio(crop.left) { - return Err("Overlay crop left must be between 0 and 1.".to_string()); - } - if !valid_ratio(crop.top) { - return Err("Overlay crop top must be between 0 and 1.".to_string()); - } - if !valid_ratio(crop.width) { - return Err("Overlay crop width must be between 0 and 1.".to_string()); - } - if !valid_ratio(crop.height) { - return Err("Overlay crop height must be between 0 and 1.".to_string()); - } - if crop.left + crop.width > 1.0 { - return Err("Overlay crop left + width must stay within the image.".to_string()); - } - if crop.top + crop.height > 1.0 { - return Err("Overlay crop top + height must stay within the image.".to_string()); - } - - Ok(crop) -} - -pub fn encode_crop_code(crop: OverlayCropSettings) -> String { - let document = OverlayCropDocument { - v: OVERLAY_SETTINGS_VERSION, - settings: OverlaySettings { - crop, - display_mode: StreamOverlayDisplayMode::Current, - }, - }; - let raw = - serde_json::to_vec(&document).expect("overlay crop document should serialize to JSON"); - STANDARD.encode(raw) -} - -pub fn decode_crop_code(code: &str) -> Result { - let trimmed = code.trim(); - if trimmed.is_empty() { - return Err("Overlay crop code is empty.".to_string()); - } - - let bytes = STANDARD - .decode(trimmed) - .map_err(|err| format!("Overlay crop code is not valid Base64: {err}"))?; - let document = serde_json::from_slice::(&bytes) - .map_err(|err| format!("Overlay crop code payload is invalid JSON: {err}"))?; - - if document.v != OVERLAY_SETTINGS_VERSION { - return Err(format!( - "Unsupported overlay crop code version {}.", - document.v - )); - } - - validate_crop_settings(document.settings.crop) -} - -#[cfg(test)] -mod tests { - use super::{ - decode_crop_code, encode_crop_code, OverlayCropSettings, OverlaySettingsStore, - StreamOverlayDisplayMode, - }; - - fn sample_crop() -> OverlayCropSettings { - OverlayCropSettings { - left: 0.29, - top: 0.27, - width: 0.61, - height: 0.21, - } - } - - fn write_settings_document( - path: &std::path::Path, - crop: OverlayCropSettings, - display_mode: StreamOverlayDisplayMode, - ) -> String { - let raw = serde_json::json!({ - "v": 4, - "crop": crop, - "display_mode": display_mode, - }) - .to_string(); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, &raw).unwrap(); - raw - } - - #[test] - fn crop_code_round_trip_preserves_values() { - let crop = OverlayCropSettings { - left: 0.31, - top: 0.28, - width: 0.55, - height: 0.19, - }; - - let decoded = decode_crop_code(&encode_crop_code(crop)).unwrap(); - - assert_eq!(decoded, crop); - } - - #[test] - fn store_returns_default_when_file_is_missing() { - let dir = tempfile::tempdir().unwrap(); - let store = OverlaySettingsStore::new(dir.path().join("missing.json"), None); - - let loaded = store.load_payload().unwrap(); - - assert_eq!(loaded.crop, OverlayCropSettings::default()); - assert_eq!(loaded.display_mode, StreamOverlayDisplayMode::Current); - } - - #[test] - fn store_loads_legacy_settings_then_saves_only_to_the_new_path() { - let dir = tempfile::tempdir().unwrap(); - let new_path = dir.path().join("new/overlay.json"); - let legacy_path = dir.path().join("legacy/overlay.json"); - let legacy_crop = sample_crop(); - let legacy_raw = write_settings_document( - &legacy_path, - legacy_crop, - StreamOverlayDisplayMode::Herohalf, - ); - let store = OverlaySettingsStore::new(new_path.clone(), Some(legacy_path.clone())); - - let loaded = store.load().unwrap(); - assert_eq!(loaded.crop, legacy_crop); - assert_eq!(loaded.display_mode, StreamOverlayDisplayMode::Herohalf); - - let new_crop = OverlayCropSettings { - left: 0.25, - top: 0.2, - width: 0.5, - height: 0.3, - }; - store.save(new_crop).unwrap(); - - assert_eq!(std::fs::read_to_string(&legacy_path).unwrap(), legacy_raw); - let saved = OverlaySettingsStore::new(new_path, None).load().unwrap(); - assert_eq!(saved.crop, new_crop); - assert_eq!(saved.display_mode, StreamOverlayDisplayMode::Herohalf); - } - - #[test] - fn store_prefers_new_settings_when_both_paths_exist() { - let dir = tempfile::tempdir().unwrap(); - let new_path = dir.path().join("new/overlay.json"); - let legacy_path = dir.path().join("legacy/overlay.json"); - let new_crop = sample_crop(); - let legacy_crop = OverlayCropSettings { - left: 0.2, - top: 0.25, - width: 0.5, - height: 0.25, - }; - write_settings_document(&new_path, new_crop, StreamOverlayDisplayMode::Hero); - write_settings_document( - &legacy_path, - legacy_crop, - StreamOverlayDisplayMode::Herohalf, - ); - let store = OverlaySettingsStore::new(new_path, Some(legacy_path)); - - let loaded = store.load().unwrap(); - - assert_eq!(loaded.crop, new_crop); - assert_eq!(loaded.display_mode, StreamOverlayDisplayMode::Hero); - } - - #[test] - fn store_returns_default_when_new_and_legacy_settings_are_missing() { - let dir = tempfile::tempdir().unwrap(); - let store = OverlaySettingsStore::new( - dir.path().join("new/overlay.json"), - Some(dir.path().join("legacy/overlay.json")), - ); - - let loaded = store.load().unwrap(); - - assert_eq!(loaded, super::OverlaySettings::default()); - } - - #[test] - fn store_can_save_and_reload_payload() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("overlay.json"); - let store = OverlaySettingsStore::new(path, None); - let crop = sample_crop(); - - let saved = store.save(crop).unwrap(); - let loaded = store.load_payload().unwrap(); - - assert_eq!(saved, loaded); - assert_eq!(loaded.crop, crop); - assert_eq!(loaded.display_mode, StreamOverlayDisplayMode::Current); - } - - #[test] - fn store_uses_default_for_old_crop_document() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("old-overlay.json"); - let store = OverlaySettingsStore::new(path.clone(), None); - - std::fs::write( - path, - serde_json::json!({ - "v": 1, - "crop": sample_crop() - }) - .to_string(), - ) - .unwrap(); - - let loaded = store.load_payload().unwrap(); - - assert_eq!(loaded.crop, OverlayCropSettings::default()); - assert_eq!(loaded.display_mode, StreamOverlayDisplayMode::Current); - } - - #[test] - fn store_can_save_and_reload_display_mode() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("overlay.json"); - let store = OverlaySettingsStore::new(path, None); - - store.save(sample_crop()).unwrap(); - let saved = store - .save_display_mode(StreamOverlayDisplayMode::Herohalf) - .unwrap(); - let loaded = store.load_payload().unwrap(); - - assert_eq!(saved, loaded); - assert_eq!(loaded.crop, sample_crop()); - assert_eq!(loaded.display_mode, StreamOverlayDisplayMode::Herohalf); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/records/image.rs b/bazaarplusplus-installer/src-tauri/src/stream/records/image.rs deleted file mode 100644 index 5eef51a..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/records/image.rs +++ /dev/null @@ -1,108 +0,0 @@ -use std::path::{Component, PathBuf}; - -use crate::services::paths; - -pub fn resolve_overlay_image_path( - game_path: Option, - raw_path: Option<&str>, -) -> Option { - let raw_path = raw_path?.trim(); - if raw_path.is_empty() { - return None; - } - - let candidate = PathBuf::from(raw_path); - if candidate.is_absolute() { - return None; - } - - let game_path = game_path?; - let screenshots_directory = paths::screenshots_dir(&game_path); - let normalized_relative_path = normalized_relative_image_path(raw_path)?; - let from_screenshots = Some(screenshots_directory.join(normalized_relative_path)); - if let Some(path) = from_screenshots.as_ref().filter(|path| path.exists()) { - return Some(path.clone()); - } - - from_screenshots -} - -fn normalized_relative_image_path(raw_path: &str) -> Option { - let mut normalized = PathBuf::new(); - for segment in raw_path.split(['/', '\\']) { - let trimmed = segment.trim(); - if trimmed.is_empty() || trimmed == "." { - continue; - } - if trimmed == ".." || PathBuf::from(trimmed).components().any(is_unsafe_component) { - return None; - } - normalized.push(trimmed); - } - - (!normalized.as_os_str().is_empty()).then_some(normalized) -} - -fn is_unsafe_component(component: Component<'_>) -> bool { - matches!( - component, - Component::ParentDir | Component::RootDir | Component::Prefix(_) - ) -} - -#[cfg(test)] -mod tests { - use super::resolve_overlay_image_path; - use crate::services::paths; - - #[test] - fn resolve_overlay_image_path_rejects_absolute_inputs() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path().join("TheBazaar"); - let absolute_input = paths::screenshots_dir(temp_dir.path()).join("match-2.png"); - - let absolute = - resolve_overlay_image_path(Some(game_path), Some(absolute_input.to_str().unwrap())); - - assert!(absolute.is_none()); - } - - #[test] - fn resolve_overlay_image_path_supports_bazaarplusplus_screenshots_directory() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path().join("TheBazaar"); - let screenshots_dir = paths::screenshots_dir(&game_path); - std::fs::create_dir_all(&screenshots_dir).unwrap(); - std::fs::write(screenshots_dir.join("match-1.png"), b"png").unwrap(); - - let resolved = resolve_overlay_image_path(Some(game_path), Some("match-1.png")).unwrap(); - - assert_eq!(resolved, screenshots_dir.join("match-1.png")); - } - - #[test] - fn resolve_overlay_image_path_normalizes_nested_backslash_relative_paths() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path().join("TheBazaar"); - let screenshots_dir = paths::screenshots_dir(&game_path); - let dated_dir = screenshots_dir.join("2026-04-16"); - std::fs::create_dir_all(&dated_dir).unwrap(); - std::fs::write(dated_dir.join("match-1.png"), b"png").unwrap(); - - let resolved = - resolve_overlay_image_path(Some(game_path), Some(r"2026-04-16\match-1.png")).unwrap(); - - assert_eq!(resolved, dated_dir.join("match-1.png")); - } - - #[test] - fn resolve_overlay_image_path_rejects_path_traversal() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path().join("TheBazaar"); - - let resolved = - resolve_overlay_image_path(Some(game_path), Some(r"2026-04-16\..\secret.txt")); - - assert!(resolved.is_none()); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/records/locator.rs b/bazaarplusplus-installer/src-tauri/src/stream/records/locator.rs deleted file mode 100644 index 9a25826..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/records/locator.rs +++ /dev/null @@ -1,34 +0,0 @@ -use std::path::{Path, PathBuf}; - -use crate::config::DATABASE_FILE_NAME; -use crate::services::game_path::find_fallback_game_path_with_database; -use crate::services::paths; - -pub fn resolve_database_path(game_path: &Path) -> Result { - let data_dir = paths::bpp_data_dir(game_path); - if !data_dir.exists() { - return Err(format!( - "BazaarPlusPlus data directory not found: {}", - data_dir.display() - )); - } - - let candidate = paths::database_path(game_path); - if candidate.exists() { - return Ok(candidate); - } - - Err(format!( - "Expected stream database at {}, but {DATABASE_FILE_NAME} was not found.", - candidate.display() - )) -} - -pub fn find_database_path_anywhere() -> Result { - if let Some(game_path) = find_fallback_game_path_with_database() { - return Ok(paths::database_path(&game_path)); - } - Err(format!( - "{DATABASE_FILE_NAME} not found: game path is not configured and no known Steam library path contains it." - )) -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/records/mapper.rs b/bazaarplusplus-installer/src-tauri/src/stream/records/mapper.rs deleted file mode 100644 index ebe0064..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/records/mapper.rs +++ /dev/null @@ -1,65 +0,0 @@ -use std::path::{Path, PathBuf}; - -use serde::Serialize; - -use crate::history::hero::{canonical_hero_id, hero_display_name}; -use crate::history::screenshots::OverlaySnapshotRow; - -use super::image::resolve_overlay_image_path; - -/// The OBS overlay's strip route for a screenshot, relative to the service origin. -fn strip_url_for_screenshot(screenshot_id: &str) -> String { - format!("/images/{screenshot_id}/strip") -} - -#[derive(Clone, Debug, Serialize)] -pub struct OverlayRecord { - pub id: String, - pub hero_id: String, - pub title: String, - pub subtitle: String, - pub captured_at: String, - pub captured_at_utc: String, - pub strip_url: Option, - pub wins: Option, - pub battle_count: Option, - pub rank: Option, - pub rating: Option, -} - -pub(super) fn to_overlay_record( - game_path: Option<&Path>, - row: OverlaySnapshotRow, -) -> OverlayRecord { - let image_path = - resolve_overlay_image_path(game_path.map(PathBuf::from), row.image_path.as_deref()) - .filter(|path| path.exists()); - let strip_url = image_path - .as_ref() - .map(|_| strip_url_for_screenshot(&row.id)); - let hero_id = canonical_hero_id(&row.hero); - let title = hero_display_name(&hero_id).to_string(); - - OverlayRecord { - id: row.id, - hero_id, - title, - subtitle: build_subtitle(&row.game_mode, row.wins, row.battle_count), - captured_at: row.captured_at, - captured_at_utc: row.captured_at_utc, - strip_url, - wins: row.wins, - battle_count: row.battle_count, - rank: row.rank, - rating: row.rating, - } -} - -fn build_subtitle(game_mode: &str, wins: Option, battle_count: Option) -> String { - match (wins, battle_count) { - (Some(wins), Some(battles)) => format!("{game_mode} · {wins}W · {battles} battles"), - (Some(wins), None) => format!("{game_mode} · {wins}W"), - (None, Some(battles)) => format!("{game_mode} · {battles} battles"), - (None, None) => game_mode.to_owned(), - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/records/mod.rs b/bazaarplusplus-installer/src-tauri/src/stream/records/mod.rs deleted file mode 100644 index c078527..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/records/mod.rs +++ /dev/null @@ -1,195 +0,0 @@ -mod image; -mod locator; -mod mapper; - -use crate::history::screenshots::{ - load_latest_overlay_snapshot, load_overlay_snapshot_by_id, load_overlay_snapshot_count, - load_overlay_snapshot_list, -}; -pub(in crate::stream) use image::resolve_overlay_image_path; -pub use locator::{find_database_path_anywhere, resolve_database_path}; -use mapper::to_overlay_record; -pub use mapper::OverlayRecord; -use std::path::PathBuf; - -#[derive(Clone, Debug)] -pub struct OverlayRecordRepository { - game_path: Option, -} - -impl OverlayRecordRepository { - pub fn new(game_path: Option) -> Self { - Self { game_path } - } - - pub fn load_record_at_offset( - &self, - from: Option<&str>, - offset: usize, - ) -> Result, String> { - let database_path = self.database_path()?; - Ok(load_latest_overlay_snapshot(&database_path, from, offset)? - .map(|row| to_overlay_record(self.game_path.as_deref(), row))) - } - - pub fn count_since(&self, from: Option<&str>) -> Result { - let database_path = self.database_path()?; - load_overlay_snapshot_count(&database_path, from) - } - - pub fn load_record_list( - &self, - from: Option<&str>, - limit: Option, - ) -> Result, String> { - let database_path = self.database_path()?; - Ok(load_overlay_snapshot_list(&database_path, from, limit)? - .into_iter() - .map(|row| to_overlay_record(self.game_path.as_deref(), row)) - .collect()) - } - - pub fn load_image(&self, record_id: &str) -> Result)>, String> { - let Some(image_path) = self.load_image_path(record_id)? else { - return Ok(None); - }; - let bytes = std::fs::read(&image_path).map_err(|err| err.to_string())?; - - Ok(Some((image_path, bytes))) - } - - pub fn load_image_path(&self, record_id: &str) -> Result, String> { - let database_path = self.database_path()?; - let Some(row) = load_overlay_snapshot_by_id(&database_path, record_id)? else { - return Ok(None); - }; - - Ok(self - .resolve_image_path(row.image_path.as_deref()) - .filter(|path| path.exists())) - } - - fn database_path(&self) -> Result { - if let Some(game_path) = &self.game_path { - return resolve_database_path(game_path); - } - find_database_path_anywhere() - } - - fn resolve_image_path(&self, raw_path: Option<&str>) -> Option { - resolve_overlay_image_path(self.game_path.clone(), raw_path) - } -} - -#[cfg(test)] -mod tests { - use super::OverlayRecordRepository; - use crate::history::mod_schema::create_mod_schema; - use crate::services::paths; - - #[test] - fn repository_rejects_unsupported_database_schema() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path().join("TheBazaar"); - let data_dir = paths::bpp_data_dir(&game_path); - std::fs::create_dir_all(&data_dir).unwrap(); - rusqlite::Connection::open(paths::database_path(&game_path)).unwrap(); - - let error = OverlayRecordRepository::new(Some(game_path)) - .load_record_at_offset(None, 0) - .unwrap_err(); - - assert!(error.contains("found=0"), "{error}"); - assert!(error.contains("supported=1"), "{error}"); - } - - #[test] - fn repository_sets_strip_url_when_relative_image_exists() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path().join("TheBazaar"); - let screenshots_dir = paths::screenshots_dir(&game_path); - std::fs::create_dir_all(&screenshots_dir).unwrap(); - std::fs::write(screenshots_dir.join("match-1.png"), b"png").unwrap(); - - let database_path = paths::database_path(&game_path); - let conn = rusqlite::Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, - captured_at_ms, victories_at_capture - ) values ( - 'snap-1', 'run-1', 'end_of_run_auto', 'match-1.png', - 0, 1775853005000, 10 - )", - [], - ) - .unwrap(); - - let repository = OverlayRecordRepository::new(Some(game_path)); - let latest = repository.load_record_at_offset(None, 0).unwrap().unwrap(); - - assert_eq!(latest.strip_url.as_deref(), Some("/images/snap-1/strip")); - } - - #[test] - fn repository_preserves_optional_snapshot_metrics() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path().join("TheBazaar"); - let data_dir = paths::bpp_data_dir(&game_path); - std::fs::create_dir_all(&data_dir).unwrap(); - - let database_path = paths::database_path(&game_path); - let conn = rusqlite::Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, - captured_at_ms, day, victories_at_capture, player_position, player_rank, player_rating, hero_name - ) values ( - 'snap-1', 'run-1', 'end_of_run_auto', 'match-1.png', - 0, 1775853005000, - 14, 10, 1, 'Diamond', 500, 'Mak' - )", - [], - ) - .unwrap(); - - let repository = OverlayRecordRepository::new(Some(game_path)); - let latest = repository.load_record_at_offset(None, 0).unwrap().unwrap(); - - assert_eq!(latest.wins, Some(10)); - assert_eq!(latest.battle_count, Some(14)); - assert_eq!(latest.rank.as_deref(), Some("Diamond")); - assert_eq!(latest.rating, Some(500)); - } - - #[test] - fn repository_canonicalizes_the_dragons_legacy_hero_name() { - let temp_dir = tempfile::tempdir().unwrap(); - let game_path = temp_dir.path().join("TheBazaar"); - let data_dir = paths::bpp_data_dir(&game_path); - std::fs::create_dir_all(&data_dir).unwrap(); - - let database_path = paths::database_path(&game_path); - let conn = rusqlite::Connection::open(&database_path).unwrap(); - create_mod_schema(&conn); - conn.execute( - "insert into run_screenshots ( - screenshot_id, run_id, capture_source, image_relative_path, captured_utc_offset_minutes, - captured_at_ms, hero_name - ) values ( - 'snap-dra', 'run-dra', 'end_of_run_auto', 'dragons.png', - 0, 1786048205000, 'Hero8' - )", - [], - ) - .unwrap(); - - let repository = OverlayRecordRepository::new(Some(game_path)); - let latest = repository.load_record_at_offset(None, 0).unwrap().unwrap(); - - assert_eq!(latest.hero_id, "TheDragons"); - assert_eq!(latest.title, "The Dragons"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/runtime.rs b/bazaarplusplus-installer/src-tauri/src/stream/runtime.rs deleted file mode 100644 index 60016e6..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/runtime.rs +++ /dev/null @@ -1,598 +0,0 @@ -use super::{ - history_thumbnails::HistoryThumbnails, - records::OverlayRecordRepository, - server::ProductionServer, - state::{StreamDbStatus, StreamServiceStatus}, -}; -use crate::services::{ - game_path::GamePathAcceptance, selected_game_installation::SelectedGameInstallationState, -}; -use std::{ - future::Future, - path::{Path, PathBuf}, - pin::Pin, - sync::{Arc, Mutex}, -}; -use tauri::Manager; -use tokio::sync::{oneshot, Mutex as AsyncMutex}; - -pub(super) type StartFuture<'a> = - Pin> + Send + 'a>>; - -pub(super) trait StreamServerAdapter: Send + Sync { - fn start(&self, runtime: StreamRuntime, installation: StreamInstallation) -> StartFuture<'_>; -} - -#[derive(Clone, Debug)] -pub(super) struct StreamInstallation { - pub(super) game_path: Option, - pub(super) record_game_path: Option, -} - -pub(super) struct StartedStream { - pub(super) status: StreamServiceStatus, - pub(super) task: StreamTaskHandle, - pub(super) active_installation_path: Option, - pub(super) active_record_game_path: Option, -} - -pub(super) struct StreamTaskHandle { - pub(super) shutdown: oneshot::Sender<()>, - pub(super) join_handle: tauri::async_runtime::JoinHandle<()>, -} - -#[derive(Clone, Default)] -pub(crate) struct StreamRuntime { - lifecycle: Arc>, - inner: Arc>, -} - -#[derive(Default)] -struct StreamRuntimeInner { - status: StreamServiceStatus, - task: Option, - active_installation_path: Option, - active_record_game_path: Option, -} - -impl StreamRuntime { - /// Makes History Thumbnails servable: starts a stopped service for the - /// selected installation and leaves a running OBS session as it is. - pub(crate) async fn prepare_history_thumbnails( - &self, - app: tauri::AppHandle, - ) -> Result<(), String> { - self.prepare_history_thumbnails_with(&production_server(&app), || { - resolve_installation(&app) - }) - .await - } - - pub(super) async fn prepare_history_thumbnails_with( - &self, - server: &A, - installation: F, - ) -> Result<(), String> - where - A: StreamServerAdapter + ?Sized, - F: FnOnce() -> StreamInstallation, - { - let _lifecycle = self.lifecycle.lock().await; - if !self.snapshot().running { - self.ensure_locked(server, installation()).await?; - } - Ok(()) - } - - pub(crate) fn snapshot(&self) -> StreamServiceStatus { - self.inner - .lock() - .expect("stream runtime poisoned") - .status - .clone() - } - - pub(crate) async fn ensure( - &self, - app: tauri::AppHandle, - ) -> Result { - self.ensure_with(&production_server(&app), resolve_installation(&app)) - .await - } - - pub(crate) async fn restart( - &self, - app: tauri::AppHandle, - ) -> Result { - self.restart_with(&production_server(&app), resolve_installation(&app)) - .await - } - - pub(crate) async fn stop(&self) -> Result { - let _lifecycle = self.lifecycle.lock().await; - self.stop_locked().await - } - - pub(crate) async fn set_window(&self, offset: usize) -> Result { - self.set_window_with(|snapshot, record_game_path| { - stream_window_for_offset(snapshot, record_game_path, offset) - }) - .await - } - - pub(crate) async fn exclusive_maintenance(&self, operation: F) -> Result - where - F: FnOnce() -> Fut, - Fut: Future>, - { - let _lifecycle = self.lifecycle.lock().await; - self.stop_locked().await?; - operation().await - } - - pub(super) async fn ensure_with( - &self, - server: &A, - installation: StreamInstallation, - ) -> Result - where - A: StreamServerAdapter + ?Sized, - { - let _lifecycle = self.lifecycle.lock().await; - self.ensure_locked(server, installation).await - } - - async fn ensure_locked( - &self, - server: &A, - installation: StreamInstallation, - ) -> Result - where - A: StreamServerAdapter + ?Sized, - { - if self.is_running_for_game_path(installation.game_path.as_deref()) { - return Ok(self.snapshot()); - } - if self.snapshot().running { - self.stop_locked().await?; - } - - self.clear_error(); - match server.start(self.clone(), installation).await { - Ok(started) => { - let status = started.status.clone(); - self.set_running(started); - Ok(status) - } - Err(message) => { - self.set_error(message.clone()); - Err(message) - } - } - } - - async fn restart_with( - &self, - server: &A, - installation: StreamInstallation, - ) -> Result - where - A: StreamServerAdapter + ?Sized, - { - let _lifecycle = self.lifecycle.lock().await; - self.restart_locked(server, installation).await - } - - async fn restart_locked( - &self, - server: &A, - installation: StreamInstallation, - ) -> Result - where - A: StreamServerAdapter + ?Sized, - { - self.stop_locked().await?; - self.clear_error(); - match server.start(self.clone(), installation).await { - Ok(started) => { - let status = started.status.clone(); - self.set_running(started); - Ok(status) - } - Err(message) => { - self.set_error(message.clone()); - Err(message) - } - } - } - - async fn stop_locked(&self) -> Result { - let task = self - .inner - .lock() - .expect("stream runtime poisoned") - .task - .take(); - if let Some(task) = task { - let _ = task.shutdown.send(()); - let _ = task.join_handle.await; - } - - Ok(self.set_idle()) - } - - pub(super) async fn set_window_with(&self, apply: F) -> Result - where - F: FnOnce(&StreamServiceStatus, Option) -> Result<(Option, usize), String>, - { - let _lifecycle = self.lifecycle.lock().await; - let snapshot = self.snapshot(); - if !snapshot.running { - return Ok(snapshot); - } - let record_game_path = self - .inner - .lock() - .expect("stream runtime poisoned") - .active_record_game_path - .clone(); - let (active_from, active_window_offset) = apply(&snapshot, record_game_path)?; - Ok(self.set_active_window(active_from, active_window_offset)) - } - - fn is_running_for_game_path(&self, requested_game_path: Option<&Path>) -> bool { - let inner = self.inner.lock().expect("stream runtime poisoned"); - if !inner.status.running { - return false; - } - - match requested_game_path { - Some(path) => inner.active_installation_path.as_deref() == Some(path), - None => true, - } - } - - fn set_running(&self, started: StartedStream) { - let mut inner = self.inner.lock().expect("stream runtime poisoned"); - inner.status = started.status; - inner.task = Some(started.task); - inner.active_installation_path = started.active_installation_path; - inner.active_record_game_path = started.active_record_game_path; - } - - fn set_active_window( - &self, - active_from: Option, - active_window_offset: usize, - ) -> StreamServiceStatus { - let mut inner = self.inner.lock().expect("stream runtime poisoned"); - inner.status.active_from = active_from; - inner.status.active_window_offset = active_window_offset; - inner.status.clone() - } - - fn set_idle(&self) -> StreamServiceStatus { - let mut inner = self.inner.lock().expect("stream runtime poisoned"); - inner.status.running = false; - inner.status.port = None; - inner.status.overlay_url = None; - inner.status.settings_url = None; - inner.status.started_at = None; - inner.status.active_from = None; - inner.status.active_window_offset = 0; - inner.status.db = StreamDbStatus::default(); - inner.task = None; - inner.active_installation_path = None; - inner.active_record_game_path = None; - inner.status.clone() - } - - fn set_error(&self, message: String) { - let mut inner = self.inner.lock().expect("stream runtime poisoned"); - inner.status = StreamServiceStatus { - last_error: Some(message), - ..StreamServiceStatus::default() - }; - inner.task = None; - inner.active_installation_path = None; - inner.active_record_game_path = None; - } - - fn clear_error(&self) { - self.inner - .lock() - .expect("stream runtime poisoned") - .status - .last_error = None; - } - - #[cfg(test)] - fn has_task(&self) -> bool { - self.inner - .lock() - .expect("stream runtime poisoned") - .task - .is_some() - } -} - -fn production_server(app: &tauri::AppHandle) -> ProductionServer { - ProductionServer { - thumbnails: app.state::().inner().clone(), - } -} - -fn resolve_installation(app: &tauri::AppHandle) -> StreamInstallation { - let selected_installation = app.state::(); - let game_resolution = selected_installation.resolve(app, None, GamePathAcceptance::Any); - let record_resolution = game_resolution - .as_ref() - .filter(|resolution| resolution.database_path.is_some()) - .cloned() - .or_else(|| selected_installation.resolve(app, None, GamePathAcceptance::DatabaseExists)); - - StreamInstallation { - game_path: game_resolution.map(|resolution| resolution.game_path), - record_game_path: record_resolution.map(|resolution| resolution.game_path), - } -} - -fn stream_window_for_offset( - snapshot: &StreamServiceStatus, - record_game_path: Option, - offset: usize, -) -> Result<(Option, usize), String> { - let started_at = snapshot - .started_at - .clone() - .ok_or_else(|| "Stream start time is unavailable.".to_string())?; - let repository = OverlayRecordRepository::new(record_game_path); - - if offset == 0 { - return Ok((Some(started_at), 0)); - } - - let captured_since_start = repository.count_since(Some(started_at.as_str()))?; - let total = repository.count_since(None)?; - let existing_before_start = total.saturating_sub(captured_since_start); - if offset > existing_before_start { - return Err(format!( - "Requested stream window offset {offset} exceeds the available {existing_before_start} earlier record(s)." - )); - } - - let record_offset = captured_since_start + offset - 1; - let record = repository - .load_record_at_offset(None, record_offset)? - .ok_or_else(|| { - format!("No end-of-run record is available for stream window offset {offset}.") - })?; - - Ok((Some(record.captured_at_utc), offset)) -} - -/// A lifecycle double shared by the runtime's tests and the History Thumbnail -/// preparation tests. -#[cfg(test)] -pub(super) mod test_support { - use super::{ - StartFuture, StartedStream, StreamInstallation, StreamRuntime, StreamServerAdapter, - StreamTaskHandle, - }; - use crate::stream::state::StreamServiceStatus; - use std::{ - path::PathBuf, - sync::{ - atomic::{AtomicUsize, Ordering}, - Arc, - }, - }; - use tokio::sync::oneshot; - - #[derive(Clone, Default)] - pub(in crate::stream) struct TestServer { - pub(in crate::stream) starts: Arc, - pub(in crate::stream) stops: Arc, - failure: Option, - } - - impl TestServer { - pub(in crate::stream) fn failing(message: &str) -> Self { - Self { - failure: Some(message.to_string()), - ..Self::default() - } - } - } - - impl StreamServerAdapter for TestServer { - fn start( - &self, - _runtime: StreamRuntime, - installation: StreamInstallation, - ) -> StartFuture<'_> { - Box::pin(async move { - self.starts.fetch_add(1, Ordering::SeqCst); - if let Some(message) = &self.failure { - return Err(message.clone()); - } - - let (shutdown, shutdown_rx) = oneshot::channel(); - let stops = self.stops.clone(); - let join_handle = tauri::async_runtime::spawn(async move { - let _ = shutdown_rx.await; - stops.fetch_add(1, Ordering::SeqCst); - }); - let started_at = "2026-07-18T10:00:00+08:00".to_string(); - Ok(StartedStream { - status: StreamServiceStatus { - running: true, - port: Some(17654), - overlay_url: Some("http://127.0.0.1:17654/overlay".to_string()), - settings_url: Some("http://127.0.0.1:17654/settings".to_string()), - started_at: Some(started_at.clone()), - active_from: Some(started_at), - ..StreamServiceStatus::default() - }, - task: StreamTaskHandle { - shutdown, - join_handle, - }, - active_installation_path: installation.game_path, - active_record_game_path: installation.record_game_path, - }) - }) - } - } - - pub(in crate::stream) fn installation(path: &str) -> StreamInstallation { - StreamInstallation { - game_path: Some(PathBuf::from(path)), - record_game_path: Some(PathBuf::from(path)), - } - } -} - -#[cfg(test)] -mod tests { - use super::{ - test_support::{installation, TestServer}, - StreamRuntime, - }; - use std::sync::{atomic::Ordering, Arc}; - use tokio::sync::Notify; - - #[tokio::test] - async fn stream_runtime_concurrent_ensure_starts_exactly_one_task() { - let runtime = StreamRuntime::default(); - let server = TestServer::default(); - let requested = installation("/Games/The Bazaar"); - - let (first, second) = tokio::join!( - runtime.ensure_with(&server, requested.clone()), - runtime.ensure_with(&server, requested), - ); - - assert!(first.unwrap().running); - assert!(second.unwrap().running); - assert_eq!(server.starts.load(Ordering::SeqCst), 1); - runtime.stop().await.unwrap(); - assert_eq!(server.stops.load(Ordering::SeqCst), 1); - } - - #[tokio::test] - async fn stream_runtime_lifecycle_transitions_keep_snapshot_and_task_consistent() { - let runtime = StreamRuntime::default(); - let server = TestServer::default(); - let requested = installation("/Games/The Bazaar"); - - runtime - .ensure_with(&server, requested.clone()) - .await - .unwrap(); - assert!(runtime.snapshot().running); - - runtime - .set_window_with(|status, record_game_path| { - assert!(status.running); - assert_eq!( - record_game_path.as_deref(), - Some(std::path::Path::new("/Games/The Bazaar")) - ); - Ok((Some("2026-07-17T10:00:00Z".to_string()), 2)) - }) - .await - .unwrap(); - assert_eq!(runtime.snapshot().active_window_offset, 2); - - runtime.restart_with(&server, requested).await.unwrap(); - assert_eq!(server.starts.load(Ordering::SeqCst), 2); - assert_eq!(server.stops.load(Ordering::SeqCst), 1); - assert_eq!(runtime.snapshot().active_window_offset, 0); - - let stopped = runtime.stop().await.unwrap(); - assert!(!stopped.running); - assert_eq!(server.stops.load(Ordering::SeqCst), 2); - assert!(!runtime.has_task()); - } - - #[tokio::test] - async fn stream_runtime_failed_start_leaves_an_idle_runtime_without_a_task() { - let runtime = StreamRuntime::default(); - let server = TestServer::failing("bind failed"); - - let error = runtime - .ensure_with(&server, installation("/Games/The Bazaar")) - .await - .unwrap_err(); - - assert_eq!(error, "bind failed"); - assert!(!runtime.snapshot().running); - assert_eq!( - runtime.snapshot().last_error.as_deref(), - Some("bind failed") - ); - assert!(!runtime.has_task()); - } - - #[tokio::test] - async fn stream_runtime_exclusive_maintenance_blocks_lifecycle_calls_and_does_not_resume() { - let runtime = StreamRuntime::default(); - let server = TestServer::default(); - let requested = installation("/Games/The Bazaar"); - runtime - .ensure_with(&server, requested.clone()) - .await - .unwrap(); - - let entered = Arc::new(Notify::new()); - let release = Arc::new(Notify::new()); - let maintenance_runtime = runtime.clone(); - let maintenance_entered = entered.clone(); - let maintenance_release = release.clone(); - let maintenance = tokio::spawn(async move { - maintenance_runtime - .exclusive_maintenance(|| async move { - maintenance_entered.notify_one(); - maintenance_release.notified().await; - Ok(()) - }) - .await - }); - entered.notified().await; - assert!(!runtime.snapshot().running); - - let ensure_runtime = runtime.clone(); - let ensure_server = server.clone(); - let ensure_requested = requested.clone(); - let ensure = tokio::spawn(async move { - ensure_runtime - .ensure_with(&ensure_server, ensure_requested) - .await - }); - let restart_runtime = runtime.clone(); - let restart_server = server.clone(); - let restart = tokio::spawn(async move { - restart_runtime - .restart_with(&restart_server, requested) - .await - }); - let window_runtime = runtime.clone(); - let window = tokio::spawn(async move { window_runtime.set_window(1).await }); - for _ in 0..8 { - tokio::task::yield_now().await; - } - assert_eq!(server.starts.load(Ordering::SeqCst), 1); - assert!(!ensure.is_finished()); - assert!(!restart.is_finished()); - assert!(!window.is_finished()); - - ensure.abort(); - restart.abort(); - window.abort(); - release.notify_one(); - maintenance.await.unwrap().unwrap(); - assert!(!runtime.snapshot().running); - assert!(!runtime.has_task()); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/server.rs b/bazaarplusplus-installer/src-tauri/src/stream/server.rs deleted file mode 100644 index 4d1dfa9..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/server.rs +++ /dev/null @@ -1,145 +0,0 @@ -use super::{ - history_thumbnails::{self, HistoryThumbnails}, - http, - overlay_settings::OverlaySettingsStore, - records::OverlayRecordRepository, - runtime::{ - StartFuture, StartedStream, StreamInstallation, StreamRuntime, StreamServerAdapter, - StreamTaskHandle, - }, - state::{StreamDbStatus, StreamServiceStatus}, -}; -use crate::services::paths; -use chrono::{Local, SecondsFormat}; -use std::path::PathBuf; -use tokio::{net::TcpListener, sync::oneshot}; - -const HOST: &str = "127.0.0.1"; -const PREFERRED_PORT: u16 = 17654; - -pub(super) struct ProductionServer { - pub(super) thumbnails: HistoryThumbnails, -} - -impl StreamServerAdapter for ProductionServer { - fn start(&self, runtime: StreamRuntime, installation: StreamInstallation) -> StartFuture<'_> { - Box::pin(async move { - let listener = bind_listener(HOST, PREFERRED_PORT).await?; - history_thumbnails::sweep_cache(); - let urls = service_urls(); - let started_at = current_timestamp(); - let active_record_game_path = installation.record_game_path.clone(); - let overlay_record_repository = - OverlayRecordRepository::new(installation.record_game_path); - let db = stream_db_status(installation.game_path.as_ref()); - let overlay_settings = OverlaySettingsStore::default(); - let router = http::router( - overlay_record_repository, - runtime, - self.thumbnails.clone(), - overlay_settings, - paths::overlay_cache_dir(), - ); - let (shutdown_tx, shutdown_rx) = oneshot::channel(); - - let join_handle = tauri::async_runtime::spawn(async move { - let server = axum::serve(listener, router).with_graceful_shutdown(async move { - let _ = shutdown_rx.await; - }); - - if let Err(err) = server.await { - eprintln!("stream service stopped with error: {err}"); - } - }); - - Ok(StartedStream { - status: StreamServiceStatus { - running: true, - host: HOST.to_string(), - port: Some(PREFERRED_PORT), - overlay_url: Some(urls.overlay_url), - settings_url: Some(urls.settings_url), - last_error: None, - started_at: Some(started_at.clone()), - active_from: Some(started_at), - active_window_offset: 0, - db, - }, - task: StreamTaskHandle { - shutdown: shutdown_tx, - join_handle, - }, - active_installation_path: installation.game_path, - active_record_game_path, - }) - }) - } -} - -fn stream_db_status(game_path: Option<&PathBuf>) -> StreamDbStatus { - let Some(game_path) = game_path else { - return StreamDbStatus::default(); - }; - let database_path = paths::database_path(game_path); - StreamDbStatus { - found: database_path.exists(), - } -} - -struct ServiceUrls { - overlay_url: String, - settings_url: String, -} - -/// The origin every service URL is built from; `bind_listener` has no fallback -/// port, so a running service always answers here. -pub(super) fn origin() -> String { - format!("http://{HOST}:{PREFERRED_PORT}") -} - -fn service_urls() -> ServiceUrls { - let origin = origin(); - ServiceUrls { - overlay_url: format!("{origin}/overlay"), - settings_url: format!("{origin}/settings"), - } -} - -async fn bind_listener(host: &str, port: u16) -> Result { - TcpListener::bind((host, port)).await.map_err(|err| { - format!( - "OBS overlay port {port} is unavailable on {host}. Free that port and try again. ({err})" - ) - }) -} - -fn current_timestamp() -> String { - Local::now().to_rfc3339_opts(SecondsFormat::Secs, false) -} - -#[cfg(test)] -mod tests { - use super::{bind_listener, origin, service_urls, HOST, PREFERRED_PORT}; - use tokio::net::TcpListener; - - #[tokio::test] - async fn bind_listener_returns_error_when_port_is_occupied() { - let occupied = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); - let occupied_port = occupied.local_addr().unwrap().port(); - - let error = bind_listener("127.0.0.1", occupied_port).await.unwrap_err(); - - assert!(error.contains("OBS overlay port")); - } - - #[test] - fn production_service_urls_remain_stable() { - assert_eq!(HOST, "127.0.0.1"); - assert_eq!(PREFERRED_PORT, 17654); - let urls = service_urls(); - - assert_eq!(origin(), "http://127.0.0.1:17654"); - assert_eq!(urls.overlay_url, "http://127.0.0.1:17654/overlay"); - assert_eq!(urls.settings_url, "http://127.0.0.1:17654/settings"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/state.rs b/bazaarplusplus-installer/src-tauri/src/stream/state.rs deleted file mode 100644 index 4ce1472..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/state.rs +++ /dev/null @@ -1,39 +0,0 @@ -use serde::Serialize; - -const DEFAULT_HOST: &str = "127.0.0.1"; - -#[derive(Clone, Debug, Serialize, specta::Type)] -pub struct StreamServiceStatus { - pub running: bool, - pub host: String, - pub port: Option, - pub overlay_url: Option, - pub settings_url: Option, - pub last_error: Option, - pub started_at: Option, - pub active_from: Option, - pub active_window_offset: usize, - pub db: StreamDbStatus, -} - -#[derive(Clone, Debug, Default, Serialize, specta::Type)] -pub struct StreamDbStatus { - pub found: bool, -} - -impl Default for StreamServiceStatus { - fn default() -> Self { - Self { - running: false, - host: DEFAULT_HOST.to_string(), - port: None, - overlay_url: None, - settings_url: None, - last_error: None, - started_at: None, - active_from: None, - active_window_offset: 0, - db: StreamDbStatus::default(), - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/stream/strip.rs b/bazaarplusplus-installer/src-tauri/src/stream/strip.rs deleted file mode 100644 index 1d777dd..0000000 --- a/bazaarplusplus-installer/src-tauri/src/stream/strip.rs +++ /dev/null @@ -1,263 +0,0 @@ -//! Strip rendering: crop a screenshot, cache the PNG, and serve it. Every step -//! blocks (SQLite, settings file, image decode, cache I/O), so callers run -//! these functions on a blocking thread. - -use super::overlay_settings::{OverlayCropSettings, OverlaySettingsStore}; -use super::records::OverlayRecordRepository; -use image::{DynamicImage, ImageFormat}; -use std::{ - io::{Cursor, ErrorKind}, - path::{Path, PathBuf}, - sync::atomic::{AtomicU64, Ordering}, - time::{SystemTime, UNIX_EPOCH}, -}; - -/// Suffix of an in-flight cache write; a leftover one is an orphan. -pub(super) const TEMP_SUFFIX: &str = ".tmp"; - -#[derive(Debug)] -pub(super) struct StripRequest { - pub(super) record_id: String, - /// A crop supplied by the request; `None` uses the saved overlay settings. - pub(super) crop: Option, - /// Render without reading or writing the cache. - pub(super) preview: bool, -} - -/// Returns the OBS overlay's PNG strip for a record, cached at the root of -/// `cache_root`, or `None` when the record or its screenshot is missing. -pub(super) fn render_strip( - records: &OverlayRecordRepository, - settings: &OverlaySettingsStore, - cache_root: &Path, - request: &StripRequest, -) -> Result>, String> { - let crop = match request.crop { - Some(crop) => crop, - None => settings.load()?.crop, - }; - let Some(path) = records.load_image_path(&request.record_id)? else { - return Ok(None); - }; - - if request.preview { - let bytes = std::fs::read(&path) - .map_err(|err| format!("Failed to read overlay source image: {err}"))?; - return crop_strip_image(&bytes, crop).map(Some); - } - - cached_strip(cache_root, &request.record_id, &path, crop).map(Some) -} - -fn sanitized_cache_name(value: &str) -> String { - value - .chars() - .map(|ch| match ch { - 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch, - _ => '_', - }) - .collect() -} - -fn crop_cache_path( - cache_directory: &Path, - record_id: &str, - source_path: &Path, - crop: OverlayCropSettings, -) -> Result { - let metadata = std::fs::metadata(source_path).map_err(|err| { - format!( - "Failed to read source image metadata from {}: {err}", - source_path.display() - ) - })?; - let modified = metadata - .modified() - .ok() - .and_then(|value| value.duration_since(UNIX_EPOCH).ok()) - .map(|value| value.as_secs()) - .unwrap_or(0); - let cache_name = format!( - "{}-{}-{}-{}-{}-{}-{}-strip.png", - sanitized_cache_name(record_id), - metadata.len(), - modified, - (crop.left * 10_000.0).round() as i64, - (crop.top * 10_000.0).round() as i64, - (crop.width * 10_000.0).round() as i64, - (crop.height * 10_000.0).round() as i64 - ); - - Ok(cache_directory.join(cache_name)) -} - -/// Returns the strip for `source_path` and `crop` cached in `cache_directory`, -/// rendering and storing it on a miss. A hit refreshes the entry's -/// modification time so an age-based sweep sees it as recently used. -pub(super) fn cached_strip( - cache_directory: &Path, - record_id: &str, - source_path: &Path, - crop: OverlayCropSettings, -) -> Result, String> { - let cache_path = crop_cache_path(cache_directory, record_id, source_path, crop)?; - match std::fs::read(&cache_path) { - Ok(bytes) => { - touch(&cache_path); - return Ok(bytes); - } - Err(err) if err.kind() == ErrorKind::NotFound => {} - Err(err) => { - return Err(format!( - "Failed to read cached overlay strip from {}: {err}", - cache_path.display() - )) - } - } - - let source_bytes = std::fs::read(source_path).map_err(|err| { - format!( - "Failed to read overlay source image from {}: {err}", - source_path.display() - ) - })?; - let bytes = crop_strip_image(&source_bytes, crop)?; - write_cache_entry(&cache_path, &bytes)?; - Ok(bytes) -} - -/// Best effort: a file another process holds open (Windows) keeps its time. -fn touch(path: &Path) { - if let Ok(file) = std::fs::File::options().write(true).open(path) { - let _ = file.set_modified(SystemTime::now()); - } -} - -/// Writes through a uniquely named temporary file, so concurrent requests for -/// one entry never read a partial PNG. -fn write_cache_entry(cache_path: &Path, bytes: &[u8]) -> Result<(), String> { - static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); - - if let Some(parent) = cache_path.parent() { - std::fs::create_dir_all(parent).map_err(|err| { - format!( - "Failed to create overlay cache directory {}: {err}", - parent.display() - ) - })?; - } - let mut temp_name = cache_path.file_name().unwrap_or_default().to_os_string(); - temp_name.push(format!( - ".{}-{}{TEMP_SUFFIX}", - std::process::id(), - NEXT_TEMP.fetch_add(1, Ordering::Relaxed) - )); - let temp_path = cache_path.with_file_name(temp_name); - - if let Err(err) = std::fs::write(&temp_path, bytes) { - let _ = std::fs::remove_file(&temp_path); - return Err(format!( - "Failed to write cached overlay strip to {}: {err}", - temp_path.display() - )); - } - match std::fs::rename(&temp_path, cache_path) { - Ok(()) => Ok(()), - Err(err) => { - let _ = std::fs::remove_file(&temp_path); - // Windows refuses to replace an entry another request holds open; - // that entry already has the same content. - if cache_path.exists() { - Ok(()) - } else { - Err(format!( - "Failed to store cached overlay strip at {}: {err}", - cache_path.display() - )) - } - } - } -} - -fn crop_strip_image(source_bytes: &[u8], crop: OverlayCropSettings) -> Result, String> { - let image = image::load_from_memory(source_bytes) - .map_err(|err| format!("Failed to decode overlay source image: {err}"))?; - let cropped = crop_dynamic_image(image, crop)?; - let mut output = Cursor::new(Vec::new()); - cropped - .write_to(&mut output, ImageFormat::Png) - .map_err(|err| format!("Failed to encode overlay strip image: {err}"))?; - Ok(output.into_inner()) -} - -fn crop_dynamic_image( - image: DynamicImage, - crop: OverlayCropSettings, -) -> Result { - let width = image.width(); - let height = image.height(); - if width == 0 || height == 0 { - return Err("Overlay source image is empty.".to_string()); - } - - let left = ((width as f64) * crop.left) - .floor() - .clamp(0.0, (width - 1) as f64) as u32; - let top = ((height as f64) * crop.top) - .floor() - .clamp(0.0, (height - 1) as f64) as u32; - let crop_width = ((width as f64) * crop.width) - .round() - .clamp(1.0, (width - left) as f64) as u32; - let crop_height = ((height as f64) * crop.height) - .round() - .clamp(1.0, (height - top) as f64) as u32; - - Ok(image.crop_imm(left, top, crop_width, crop_height)) -} - -#[cfg(test)] -mod tests { - use super::{cached_strip, crop_cache_path, crop_dynamic_image, TEMP_SUFFIX}; - use crate::stream::overlay_settings::OverlayCropSettings; - use image::{DynamicImage, GenericImageView, RgbaImage}; - - #[test] - fn crop_dynamic_image_returns_expected_dimensions() { - let image = DynamicImage::ImageRgba8(RgbaImage::new(1000, 500)); - let crop = OverlayCropSettings { - left: 0.25, - top: 0.2, - width: 0.5, - height: 0.3, - }; - - let cropped = crop_dynamic_image(image, crop).unwrap(); - - assert_eq!(cropped.dimensions(), (500, 150)); - } - - #[test] - fn strip_cache_miss_stores_one_entry_without_a_temporary_file() { - let temp_dir = tempfile::tempdir().unwrap(); - let source_path = temp_dir.path().join("source.png"); - let cache_directory = temp_dir.path().join("cache"); - let crop = OverlayCropSettings::default(); - RgbaImage::from_pixel(64, 32, image::Rgba([1, 2, 3, 255])) - .save(&source_path) - .unwrap(); - - let bytes = cached_strip(&cache_directory, "shot-1", &source_path, crop).unwrap(); - - let entries = std::fs::read_dir(&cache_directory) - .unwrap() - .map(|entry| entry.unwrap().path()) - .collect::>(); - assert_eq!( - entries, - [crop_cache_path(&cache_directory, "shot-1", &source_path, crop).unwrap()] - ); - assert!(!entries[0].to_string_lossy().ends_with(TEMP_SUFFIX)); - assert_eq!(std::fs::read(&entries[0]).unwrap(), bytes); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/tray.rs b/bazaarplusplus-installer/src-tauri/src/tray.rs deleted file mode 100644 index 0c5611c..0000000 --- a/bazaarplusplus-installer/src-tauri/src/tray.rs +++ /dev/null @@ -1,248 +0,0 @@ -use std::sync::Mutex; - -use tauri::{ - menu::{Menu, MenuItem, MenuItemBuilder}, - tray::{MouseButton, TrayIconBuilder, TrayIconEvent}, - Manager, -}; - -#[cfg(target_os = "macos")] -const MACOS_TRAY_ICON: &[u8] = include_bytes!("../icons/tray-macos-template.png"); - -pub fn build_tray(app: &tauri::AppHandle) -> tauri::Result<()> { - let labels = tray_menu_labels(TrayLocale::Zh); - let show_window = MenuItemBuilder::with_id("show_window", labels.show_window).build(app)?; - let copy_obs_url = MenuItemBuilder::with_id("copy_obs_url", labels.copy_obs_url).build(app)?; - let stop_stream_service = - MenuItemBuilder::with_id("stop_stream_service", labels.stop_stream_service).build(app)?; - let quit = MenuItemBuilder::with_id("quit_app", labels.quit).build(app)?; - let menu = Menu::with_items( - app, - &[&show_window, ©_obs_url, &stop_stream_service, &quit], - )?; - - app.state::().set_items(TrayMenuItems { - show_window: show_window.clone(), - copy_obs_url: copy_obs_url.clone(), - stop_stream_service: stop_stream_service.clone(), - quit: quit.clone(), - }); - - let mut tray = TrayIconBuilder::with_id("main-tray") - .menu(&menu) - .tooltip("BazaarPlusPlus") - .show_menu_on_left_click(false) - .on_menu_event(|app, event| match event.id().as_ref() { - "show_window" => show_main_window(app), - "copy_obs_url" => { - let runtime = app.state::(); - if let Some(url) = runtime.snapshot().overlay_url { - let _ = copy_text_to_clipboard(&url); - } - } - "stop_stream_service" => { - let app_handle = app.clone(); - tauri::async_runtime::spawn(async move { - let runtime = app_handle.state::(); - let _ = runtime.stop().await; - }); - } - "quit_app" => quit_app(app), - _ => {} - }) - .on_tray_icon_event(|tray, event| { - if should_show_main_window_for_tray_event(&event) { - show_main_window(tray.app_handle()); - } - }); - - #[cfg(target_os = "macos")] - { - let icon = tauri::image::Image::from_bytes(MACOS_TRAY_ICON)?; - tray = tray.icon(icon).icon_as_template(true); - } - - #[cfg(not(target_os = "macos"))] - if let Some(icon) = app.default_window_icon().cloned() { - tray = tray.icon(icon); - } - - let _ = tray.build(app)?; - Ok(()) -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum TrayLocale { - En, - Zh, -} - -impl TrayLocale { - fn from_code(locale: &str) -> Self { - match locale { - "en" => Self::En, - _ => Self::Zh, - } - } -} - -struct TrayMenuLabels { - show_window: &'static str, - copy_obs_url: &'static str, - stop_stream_service: &'static str, - quit: &'static str, -} - -fn tray_menu_labels(locale: TrayLocale) -> TrayMenuLabels { - match locale { - TrayLocale::En => TrayMenuLabels { - show_window: "Show Window", - copy_obs_url: "Copy OBS URL", - stop_stream_service: "Stop Stream Service", - quit: "Quit", - }, - TrayLocale::Zh => TrayMenuLabels { - show_window: "显示窗口", - copy_obs_url: "复制 OBS 地址", - stop_stream_service: "关闭直播服务", - quit: "退出", - }, - } -} - -struct TrayMenuItems { - show_window: MenuItem, - copy_obs_url: MenuItem, - stop_stream_service: MenuItem, - quit: MenuItem, -} - -#[derive(Default)] -pub struct TrayMenuState { - items: Mutex>, -} - -impl TrayMenuState { - fn set_items(&self, items: TrayMenuItems) { - *self.items.lock().expect("tray menu state poisoned") = Some(items); - } - - fn apply_locale(&self, locale: TrayLocale) -> Result<(), String> { - let labels = tray_menu_labels(locale); - let items = self.items.lock().expect("tray menu state poisoned"); - let items = items - .as_ref() - .ok_or_else(|| "Tray menu is not initialized.".to_string())?; - - items - .show_window - .set_text(labels.show_window) - .map_err(|err| format!("Failed to update tray menu text: {err}"))?; - items - .copy_obs_url - .set_text(labels.copy_obs_url) - .map_err(|err| format!("Failed to update tray menu text: {err}"))?; - items - .stop_stream_service - .set_text(labels.stop_stream_service) - .map_err(|err| format!("Failed to update tray menu text: {err}"))?; - items - .quit - .set_text(labels.quit) - .map_err(|err| format!("Failed to update tray menu text: {err}"))?; - Ok(()) - } -} - -#[tauri::command] -#[specta::specta] -pub async fn set_app_locale( - state: tauri::State<'_, TrayMenuState>, - locale: String, -) -> Result<(), String> { - let normalized = match locale.as_str() { - "en" => "en", - _ => "zh", - }; - state.apply_locale(TrayLocale::from_code(normalized))?; - Ok(()) -} - -fn should_show_main_window_for_tray_event(event: &TrayIconEvent) -> bool { - matches!( - event, - TrayIconEvent::Click { - button: MouseButton::Left, - .. - } | TrayIconEvent::DoubleClick { - button: MouseButton::Left, - .. - } - ) -} - -fn quit_app(app: &tauri::AppHandle) { - let app_handle = app.clone(); - tauri::async_runtime::spawn(async move { - let runtime = app_handle.state::(); - let _ = runtime.stop().await; - app_handle.exit(0); - }); -} - -fn show_main_window(app: &tauri::AppHandle) { - crate::main_window::restore(app); -} - -fn copy_text_to_clipboard(text: &str) -> Result<(), String> { - #[cfg(target_os = "macos")] - { - use std::io::Write; - use std::process::{Command, Stdio}; - - let mut child = Command::new("pbcopy") - .stdin(Stdio::piped()) - .spawn() - .map_err(|err| format!("failed to launch pbcopy: {err}"))?; - let stdin = child - .stdin - .as_mut() - .ok_or_else(|| "pbcopy stdin unavailable".to_string())?; - stdin - .write_all(text.as_bytes()) - .map_err(|err| format!("failed to write to pbcopy: {err}"))?; - child - .wait() - .map_err(|err| format!("failed to wait for pbcopy: {err}"))?; - Ok(()) - } - - #[cfg(target_os = "windows")] - { - use std::io::Write; - use std::process::{Command, Stdio}; - - let mut child = Command::new("cmd") - .args(["/C", "clip"]) - .stdin(Stdio::piped()) - .spawn() - .map_err(|err| format!("failed to launch clip: {err}"))?; - let stdin = child - .stdin - .as_mut() - .ok_or_else(|| "clip stdin unavailable".to_string())?; - stdin - .write_all(text.as_bytes()) - .map_err(|err| format!("failed to write to clip: {err}"))?; - child - .wait() - .map_err(|err| format!("failed to wait for clip: {err}"))?; - Ok(()) - } - - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - { - let _ = text; - Err("clipboard copy is unsupported on this platform".to_string()) - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/app.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/app.rs deleted file mode 100644 index 1f8d71d..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/app.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! The Install page's entry to the import: the `import_v5_history` command's -//! result and the semantic problems an [`ImportError`] becomes. - -use std::path::PathBuf; - -use serde::Serialize; - -use super::run::{import_v5, ImportReport}; -use super::ImportError; -use crate::problem::{SemanticProblem, SemanticProblemCode}; -use crate::services::data_maintenance::DataMaintenanceLock; -use crate::services::legacy_data::{ - installer_settings_directory, legacy_data_state, LegacyDataState, -}; -use crate::services::placement::PlacementError; -use crate::stream::runtime::StreamRuntime; - -/// The `operation` parameter of every problem the import reports. -const IMPORT_OPERATION: &str = "import_v5_history"; - -/// A completed import. `BazaarPlusPlusV5/` stays in `state.roots`: deleting it -/// is a separate confirmation. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, specta::Type)] -pub struct ImportV5HistoryResult { - pub imported_run_count: u64, - /// Runs the current database already held, left as they were. - pub skipped_run_count: u64, - /// Screenshot and video rows whose file could not be carried over: outside - /// the V5 folder, or already gone from it. - pub unavailable_file_count: u64, - /// The Legacy Roots remeasured after the import. - pub state: LegacyDataState, -} - -impl ImportV5HistoryResult { - pub(crate) fn new(report: &ImportReport, state: LegacyDataState) -> Self { - let count = |len: usize| u64::try_from(len).unwrap_or(u64::MAX); - Self { - imported_run_count: count(report.plan.imported_runs.len()), - skipped_run_count: count(report.plan.skipped_runs.len()), - unavailable_file_count: count( - report.plan.dropped_references.len() + report.plan.missing_files.len(), - ), - state, - } - } -} - -/// Runs the import for the app with the current clock, then remeasures the -/// Legacy Roots on the blocking pool. -pub(crate) async fn import_v5_history( - maintenance: &DataMaintenanceLock, - stream_runtime: &StreamRuntime, - game_path: PathBuf, -) -> Result { - let now_ms = chrono::Utc::now().timestamp_millis(); - let report = import_v5(maintenance, stream_runtime, game_path.clone(), now_ms) - .await - .map_err(ImportError::into_problem)?; - let settings_dir = installer_settings_directory(); - let state = - tauri::async_runtime::spawn_blocking(move || legacy_data_state(&game_path, &settings_dir)) - .await - .map_err(|error| { - ImportError::Target(format!("failed to measure legacy data: {error}")) - .into_problem() - })?; - Ok(ImportV5HistoryResult::new(&report, state)) -} - -impl ImportError { - /// A running game keeps its own refusal code, with the `stage` that found - /// it. Every other failure is `import_failed` with `reason` set to - /// [`ImportError::code`]; a shortage of space also carries the byte counts. - pub(crate) fn into_problem(self) -> SemanticProblem { - let problem = match &self { - Self::GameRunning { refusal, stage } => { - return refusal - .clone() - .into_problem() - .with_param("operation", IMPORT_OPERATION) - .with_param("stage", *stage); - } - Self::Placement(PlacementError::InsufficientSpace { - required, - available, - .. - }) => SemanticProblem::new(SemanticProblemCode::ImportFailed) - .with_param("required_bytes", required.to_string()) - .with_param("available_bytes", available.to_string()), - _ => SemanticProblem::new(SemanticProblemCode::ImportFailed), - }; - problem - .with_param("operation", IMPORT_OPERATION) - .with_param("reason", self.code()) - .with_diagnostic(self.to_string()) - } -} - -#[cfg(test)] -mod tests { - use std::path::PathBuf; - - use super::*; - use crate::services::game_process::{GameRunningRefusal, GameStoppedOperation}; - - #[test] - fn a_running_game_keeps_the_import_refusal_code_and_its_stage() { - let problem = ImportError::GameRunning { - refusal: GameRunningRefusal { - operation: GameStoppedOperation::Import, - inspection_error: None, - }, - stage: "before_commit", - } - .into_problem(); - - assert_eq!(problem.code, SemanticProblemCode::ImportBlockedByGame); - assert_eq!(problem.params["operation"], IMPORT_OPERATION); - assert_eq!(problem.params["stage"], "before_commit"); - } - - #[test] - fn other_failures_carry_their_stable_code_as_the_reason() { - for error in [ - ImportError::AlreadyImported, - ImportError::NotEligible("installed_mod_writes_old_root"), - ImportError::V5DatabaseMissing, - ImportError::UnsupportedV5Schema(9), - ImportError::MarkerNotWritten("denied".into()), - ] { - let code = error.code(); - let problem = error.into_problem(); - assert_eq!(problem.code, SemanticProblemCode::ImportFailed); - assert_eq!(problem.params["reason"], code); - assert_eq!(problem.params["operation"], IMPORT_OPERATION); - assert!(problem.diagnostic.is_some()); - } - } - - #[test] - fn insufficient_space_reports_the_byte_counts() { - let problem = ImportError::Placement(PlacementError::InsufficientSpace { - volume: PathBuf::from("/volume"), - required: 2048, - available: 1024, - }) - .into_problem(); - - assert_eq!(problem.params["reason"], "insufficient_space"); - assert_eq!(problem.params["required_bytes"], "2048"); - assert_eq!(problem.params["available_bytes"], "1024"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/error.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/error.rs deleted file mode 100644 index 3e8c217..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/error.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! Why an import did not complete. Every variant except [`ImportError::MarkerNotWritten`] -//! leaves the current Data Root as it was and writes no marker. - -use std::fmt; - -use crate::services::game_process::GameRunningRefusal; -use crate::services::placement::PlacementError; - -#[derive(Debug)] -pub(crate) enum ImportError { - InvalidGamePath, - /// The marker exists: an earlier import completed. Nothing is done. - AlreadyImported, - /// `installed_mod_writes_old_root` or `no_v5_data_root`. - NotEligible(&'static str), - /// Refused before starting (`stage` `start`) or found running just before - /// the commit (`before_commit`), which rolls everything back. - GameRunning { - refusal: GameRunningRefusal, - stage: &'static str, - }, - /// The installed mod's history database contract lacks the replay retention. - ModContract(String), - V5DatabaseMissing, - V5Unreadable(String), - UnsupportedV5Schema(i64), - /// A required table (`column` None) or column is missing from the V5 database. - MissingV5Column { - table: String, - column: Option, - }, - InvalidV5Value { - table: &'static str, - id: String, - column: &'static str, - value: String, - }, - TargetUnsupported(i64), - Target(String), - Placement(PlacementError), - /// The import committed but the marker could not be written; running the - /// import again skips every Run and writes it. - MarkerNotWritten(String), -} - -impl ImportError { - /// Stable code for the manifest and, later, the frontend. - pub(crate) fn code(&self) -> &'static str { - match self { - Self::InvalidGamePath => "invalid_game_path", - Self::AlreadyImported => "already_imported", - Self::NotEligible(_) => "not_eligible", - Self::GameRunning { .. } => "import_blocked_by_game", - Self::ModContract(_) => "mod_contract_invalid", - Self::V5DatabaseMissing => "v5_database_missing", - Self::V5Unreadable(_) => "v5_database_unreadable", - Self::UnsupportedV5Schema(_) => "v5_schema_unsupported", - Self::MissingV5Column { .. } => "v5_schema_missing_column", - Self::InvalidV5Value { .. } => "v5_value_invalid", - Self::TargetUnsupported(_) => "target_schema_unsupported", - Self::Target(_) => "target_write_failed", - Self::Placement(PlacementError::InsufficientSpace { .. }) => "insufficient_space", - Self::Placement(PlacementError::TargetConflict { .. }) => "file_conflict", - Self::Placement(PlacementError::Io { .. }) => "file_placement_failed", - Self::MarkerNotWritten(_) => "marker_not_written", - } - } -} - -impl fmt::Display for ImportError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidGamePath => f.write_str("not a The Bazaar installation"), - Self::AlreadyImported => f.write_str("the V5 history was already imported"), - Self::NotEligible(reason) => write!(f, "the import cannot run: {reason}"), - Self::GameRunning { refusal, stage } => write!(f, "{refusal} ({stage})"), - Self::ModContract(detail) - | Self::V5Unreadable(detail) - | Self::Target(detail) - | Self::MarkerNotWritten(detail) => f.write_str(detail), - Self::V5DatabaseMissing => f.write_str("BazaarPlusPlusV5 has no history database"), - Self::UnsupportedV5Schema(version) => { - write!(f, "unsupported V5 database user_version {version}") - } - Self::MissingV5Column { table, column } => match column { - Some(column) => write!(f, "V5 table {table} has no column {column}"), - None => write!(f, "V5 database has no table {table}"), - }, - Self::InvalidV5Value { - table, - id, - column, - value, - } => write!(f, "{table} {id}: {column} is not an instant: {value}"), - Self::TargetUnsupported(version) => { - write!(f, "unsupported current database user_version {version}") - } - Self::Placement(error) => write!(f, "{error}"), - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/instant.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/instant.rs deleted file mode 100644 index 1b0d31c..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/instant.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! V5 stored every instant as text; V6 stores Unix milliseconds. This is the one -//! conversion between them. -//! -//! It accepts what the V5 mod wrote and read back: `DateTimeOffset.ToString("o")` -//! (`2026-10-01T12:00:00.0000000+00:00`), `Z` text, and SQLite `datetime()` text -//! (`2026-10-05 14:18:00`). Text without an offset is UTC, as the mod's -//! `SqliteUtcInstant.Parse` read it (`DateTimeStyles.AssumeUniversal`). -//! Fractional seconds are truncated to the millisecond, as -//! `DateTimeOffset.ToUnixTimeMilliseconds` truncates ticks. - -use chrono::{DateTime, NaiveDateTime}; - -const OFFSET_FREE_FORMATS: [&str; 4] = [ - "%Y-%m-%d %H:%M:%S%.f", - "%Y-%m-%dT%H:%M:%S%.f", - "%Y-%m-%d %H:%M", - "%Y-%m-%dT%H:%M", -]; - -/// Unix milliseconds of a V5 instant, or `None` when the text is not one. -pub(crate) fn parse_v5_instant_ms(text: &str) -> Option { - let text = text.trim(); - if text.is_empty() { - return None; - } - if let Ok(value) = DateTime::parse_from_rfc3339(text) { - return Some(value.timestamp_millis()); - } - // RFC 3339 requires seconds; `o` text always has them, but a hand-edited or - // `strftime` value may carry an offset without them. - for format in ["%Y-%m-%dT%H:%M%:z", "%Y-%m-%d %H:%M%:z"] { - if let Ok(value) = DateTime::parse_from_str(text, format) { - return Some(value.timestamp_millis()); - } - } - let naive = text.strip_suffix(['Z', 'z']).unwrap_or(text); - OFFSET_FREE_FORMATS.iter().find_map(|format| { - NaiveDateTime::parse_from_str(naive, format) - .ok() - .map(|value| value.and_utc().timestamp_millis()) - }) -} - -/// The UTC offset in minutes a V5 local instant was written with (`captured_at_local`), -/// 0 for UTC or offset-free text, or `None` when the text is not an instant. -pub(crate) fn parse_v5_offset_minutes(text: &str) -> Option { - let text = text.trim(); - parse_v5_instant_ms(text)?; - Some( - DateTime::parse_from_rfc3339(text) - .ok() - .or_else(|| { - ["%Y-%m-%dT%H:%M%:z", "%Y-%m-%d %H:%M%:z"] - .iter() - .find_map(|format| DateTime::parse_from_str(text, format).ok()) - }) - .map_or(0, |value| i64::from(value.offset().local_minus_utc() / 60)), - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - const ALPHA_START_MS: i64 = 1_790_856_000_000; // 2026-10-01T12:00:00Z - - #[test] - fn round_trip_text_converts_to_utc_milliseconds() { - assert_eq!( - parse_v5_instant_ms("2026-10-01T12:00:00.0000000+00:00"), - Some(ALPHA_START_MS) - ); - assert_eq!( - parse_v5_instant_ms("2026-10-01T12:00:00Z"), - Some(ALPHA_START_MS) - ); - // A local offset names the same instant. - assert_eq!( - parse_v5_instant_ms("2026-10-01T20:00:00.0000000+08:00"), - Some(ALPHA_START_MS) - ); - assert_eq!( - parse_v5_instant_ms("2026-10-01T07:30:00-04:30"), - Some(ALPHA_START_MS) - ); - } - - #[test] - fn fractional_seconds_truncate_to_the_millisecond() { - assert_eq!( - parse_v5_instant_ms("2026-10-01T12:00:00.1239999+00:00"), - Some(ALPHA_START_MS + 123) - ); - assert_eq!( - parse_v5_instant_ms("2026-10-01T12:00:00.5Z"), - Some(ALPHA_START_MS + 500) - ); - // Before the epoch, truncating ticks floors the millisecond. - assert_eq!(parse_v5_instant_ms("1969-12-31T23:59:59.9995Z"), Some(-1)); - } - - #[test] - fn offset_free_text_is_utc() { - assert_eq!( - parse_v5_instant_ms("2026-10-01 12:00:00"), - Some(ALPHA_START_MS) - ); - assert_eq!( - parse_v5_instant_ms("2026-10-01T12:00:00.250"), - Some(ALPHA_START_MS + 250) - ); - assert_eq!( - parse_v5_instant_ms(" 2026-10-01 12:00 "), - Some(ALPHA_START_MS) - ); - assert_eq!( - parse_v5_instant_ms("2026-10-01T20:00+08:00"), - Some(ALPHA_START_MS) - ); - } - - #[test] - fn non_instants_are_refused() { - for text in [ - "", - " ", - "t", - "2026-13-01T00:00:00Z", - "yesterday", - "2026-10-01", - ] { - assert_eq!(parse_v5_instant_ms(text), None, "{text:?}"); - } - } - - #[test] - fn local_offsets_convert_to_minutes() { - assert_eq!( - parse_v5_offset_minutes("2026-10-01T20:15:04.1200000+08:00"), - Some(480) - ); - assert_eq!( - parse_v5_offset_minutes("2026-10-01T07:30:00-04:30"), - Some(-270) - ); - assert_eq!(parse_v5_offset_minutes("2026-10-01T12:00:00Z"), Some(0)); - assert_eq!(parse_v5_offset_minutes("2026-10-01 12:00:00"), Some(0)); - assert_eq!(parse_v5_offset_minutes("nope"), None); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/manifest.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/manifest.rs deleted file mode 100644 index aa8be4e..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/manifest.rs +++ /dev/null @@ -1,152 +0,0 @@ -//! The headless `import` command's evidence: the outcome, the current Data -//! Root's files as sorted path/SHA-256 records, and every row of its history -//! database. Byte-for-byte stable for the same inputs and `--now`, so tests -//! compare it with goldens. - -use std::path::Path; - -use rusqlite::types::Value; -use rusqlite::{Connection, OpenFlags}; - -use super::run::ImportReport; -use super::ImportError; -use crate::config::DATABASE_FILE_NAME; - -/// The current database's tables with the order their rows are listed in. -const TABLE_ORDER: [(&str, &str); 8] = [ - ("runs", "run_id"), - ("run_events", "run_id, seq"), - ("battles", "battle_id"), - ("battle_snapshots", "battle_id"), - ("run_screenshots", "screenshot_id"), - ("combat_replay_videos", "video_id"), - ("bundle_seal_jobs", "run_id"), - ("bundle_outbox", "bundle_id"), -]; - -pub(crate) fn manifest_json( - game_path: &Path, - outcome: &Result, -) -> Result { - let data_root = crate::services::paths::bpp_data_dir(game_path); - let mut manifest = serde_json::Map::new(); - match outcome { - Ok(report) => { - manifest.insert("status".into(), "imported".into()); - manifest.insert( - "report".into(), - serde_json::to_value(report).map_err(|error| error.to_string())?, - ); - } - Err(ImportError::AlreadyImported) => { - manifest.insert("status".into(), "already_imported".into()); - } - Err(error) => { - manifest.insert("status".into(), "failed".into()); - manifest.insert( - "error".into(), - serde_json::json!({"code": error.code(), "message": error.to_string()}), - ); - } - } - manifest.insert( - "marker".into(), - std::fs::symlink_metadata(super::v5_import_marker_path(game_path)) - .is_ok() - .into(), - ); - manifest.insert("dataRootFiles".into(), data_root_files(&data_root)?); - manifest.insert("database".into(), database_rows(&data_root)?); - serde_json::to_string_pretty(&serde_json::Value::Object(manifest)) - .map(|text| text + "\n") - .map_err(|error| error.to_string()) -} - -/// The Data Root's files except the database, whose bytes depend on SQLite's -/// page layout; its rows are listed instead. `null` without a Data Root. -fn data_root_files(data_root: &Path) -> Result { - if !data_root.is_dir() { - return Ok(serde_json::Value::Null); - } - let entries = crate::services::file_manifest::tree_manifest(data_root)?; - Ok(entries - .into_iter() - .filter(|(path, _)| { - !path - .strip_prefix(DATABASE_FILE_NAME) - .is_some_and(|suffix| ["", "-wal", "-shm", "-journal"].contains(&suffix)) - }) - .map(|(path, sha256)| serde_json::json!({"path": path, "sha256": sha256})) - .collect()) -} - -/// `{"userVersion", "journalMode", "tables": {table: [row, ...]}}`, or `null` -/// without a database. -fn database_rows(data_root: &Path) -> Result { - let path = data_root.join(DATABASE_FILE_NAME); - if !path.is_file() { - return Ok(serde_json::Value::Null); - } - let conn = Connection::open_with_flags( - &path, - OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX, - ) - .map_err(|error| error.to_string())?; - let user_version: i64 = conn - .query_row("pragma user_version", [], |row| row.get(0)) - .map_err(|error| error.to_string())?; - let journal_mode: String = conn - .query_row("pragma journal_mode", [], |row| row.get(0)) - .map_err(|error| error.to_string())?; - let mut tables = serde_json::Map::new(); - for (table, order) in TABLE_ORDER { - let exists: bool = conn - .query_row( - "select exists (select 1 from sqlite_master where type = 'table' and name = ?1)", - [table], - |row| row.get(0), - ) - .map_err(|error| error.to_string())?; - if !exists { - continue; - } - let mut statement = conn - .prepare(&format!("select * from \"{table}\" order by {order}")) - .map_err(|error| error.to_string())?; - let columns: Vec = statement - .column_names() - .into_iter() - .map(str::to_owned) - .collect(); - let rows = statement - .query_map([], |row| { - let mut object = serde_json::Map::new(); - for (index, column) in columns.iter().enumerate() { - object.insert(column.clone(), json_value(row.get::<_, Value>(index)?)); - } - Ok(serde_json::Value::Object(object)) - }) - .and_then(|rows| rows.collect::, _>>()) - .map_err(|error| error.to_string())?; - tables.insert(table.into(), rows.into()); - } - Ok(serde_json::json!({ - "userVersion": user_version, - "journalMode": journal_mode, - "tables": tables, - })) -} - -fn json_value(value: Value) -> serde_json::Value { - match value { - Value::Null => serde_json::Value::Null, - Value::Integer(value) => value.into(), - Value::Real(value) => value.into(), - Value::Text(text) => text.into(), - Value::Blob(bytes) => bytes - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::() - .into(), - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/mod.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/mod.rs deleted file mode 100644 index 2808d56..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/mod.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! The one-time import of V5 history into the current Data Root (ADR-0008). -//! This module is deleted before 6.2.0; `release::check` refuses that version -//! while it exists. V5 constants and directory names appear only here. -//! -//! `run.rs` is the operation, `app.rs` its Install page entry, `source.rs` -//! reads V5, `plan.rs` maps rows and files, `target.rs` writes the current -//! database, and `manifest.rs` is the headless command's evidence. - -mod app; -mod error; -mod instant; -pub(crate) mod manifest; -mod plan; -mod run; -mod source; -mod target; -#[cfg(test)] -pub(crate) mod tests_e2e; - -use std::path::{Path, PathBuf}; - -pub(crate) use app::{import_v5_history, ImportV5HistoryResult}; -pub(crate) use error::ImportError; -pub(crate) use run::import_v5; - -use crate::services::legacy_data::{ - installed_mod_data_root, is_real_directory, InstalledModDataRoot, LegacyRoot, -}; - -/// The marker a completed import writes inside `BazaarPlusPlusV5/`. It lives -/// in the Legacy Root rather than the current Data Root, so a Reset does not -/// trigger a second import and deleting V5 removes the marker with it. Any -/// entry with this name counts, whatever its contents. -pub(crate) const V5_IMPORT_MARKER_FILE_NAME: &str = "imported-to-BazaarPlusPlusV6"; - -pub(crate) fn v5_import_marker_path(game_path: &Path) -> PathBuf { - LegacyRoot::V5 - .path_in(game_path) - .join(V5_IMPORT_MARKER_FILE_NAME) -} - -/// The import may run: the installed mod writes the current Data Root, -/// `BazaarPlusPlusV5/` exists, and no earlier import left its marker. -pub(crate) fn is_v5_import_eligible(game_path: &Path) -> bool { - installed_mod_data_root(game_path) == InstalledModDataRoot::Current - && is_real_directory(&LegacyRoot::V5.path_in(game_path)) - && std::fs::symlink_metadata(v5_import_marker_path(game_path)).is_err() -} - -#[cfg(test)] -mod tests { - use super::*; - - fn write(path: &Path, bytes: &[u8]) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, bytes).unwrap(); - } - - fn install_mod_contract(game: &Path, data_root: Option<&str>) { - let contract = match data_root { - Some(name) => format!(r#"{{ "formatVersion": 1, "dataRootDirectoryName": "{name}" }}"#), - None => r#"{ "formatVersion": 1, "historyDatabaseUserVersion": 3 }"#.to_string(), - }; - write( - &game.join("BepInEx/plugins/BazaarPlusPlus.history-database.json"), - contract.as_bytes(), - ); - } - - #[test] - fn eligible_only_with_a_current_mod_a_v5_root_and_no_marker() { - let game = tempfile::tempdir().unwrap(); - let game = game.path(); - assert!(!is_v5_import_eligible(game)); - - write(&game.join("BazaarPlusPlusV5/bazaarplusplus.db"), b"db"); - // No mod installed. - assert!(!is_v5_import_eligible(game)); - - // A 5.x mod still writes V5. - install_mod_contract(game, None); - assert!(!is_v5_import_eligible(game)); - - install_mod_contract(game, Some(crate::config::BAZAAR_DATA_DIRECTORY)); - assert!(is_v5_import_eligible(game)); - - write(&v5_import_marker_path(game), b""); - assert!(!is_v5_import_eligible(game)); - assert!(v5_import_marker_path(game).starts_with(game.join("BazaarPlusPlusV5"))); - } - - #[test] - fn a_file_named_like_the_v5_root_is_not_eligible() { - let game = tempfile::tempdir().unwrap(); - install_mod_contract(game.path(), Some(crate::config::BAZAAR_DATA_DIRECTORY)); - write(&game.path().join("BazaarPlusPlusV5"), b"file"); - - assert!(!is_v5_import_eligible(game.path())); - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/plan.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/plan.rs deleted file mode 100644 index aa547c8..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/plan.rs +++ /dev/null @@ -1,838 +0,0 @@ -//! Turns V5 rows into the rows and file placements the current Data Root gets. -//! -//! Every imported Run is History-Only. A Run already in the current database is -//! skipped with all its children, and so is a Run whose battle, screenshot, or -//! video id the current database already holds. Ghost battles, the Bundle -//! outbox, and seal jobs are never read (see `source.rs`). - -use std::collections::{BTreeMap, HashSet}; -use std::path::{Path, PathBuf}; - -use rusqlite::types::Value; -use rusqlite::{Connection, OptionalExtension}; -use serde::Serialize; - -use super::instant::{parse_v5_instant_ms, parse_v5_offset_minutes}; -use super::source::{V5History, V5Row, V5Shape}; -use super::ImportError; -use crate::history::cleanup::{normalize_relative_path, replay_payload_path}; -use crate::history::files::resolve_cleanup_file_path; -use crate::services::paths::{ - combat_replay_videos_dir_in, combat_replays_dir_in, screenshots_dir_in, -}; -use crate::services::placement::PlacementRequest; - -const DAY_MS: i64 = 24 * 60 * 60 * 1000; - -/// One row for the current database, as `(column, value)` pairs. -pub(crate) type V6Row = Vec<(&'static str, Value)>; - -/// The mod's replay payload retention, from the installed mod's contract. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct ReplayRetention { - pub(crate) newest_count: usize, - pub(crate) age_days: i64, -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct SkippedRun { - pub(crate) run_id: String, - /// `already_present`: the current database has the Run id. - /// `conflicting_id`: it has one of the Run's battle, screenshot, or video ids. - pub(crate) reason: &'static str, -} - -/// A screenshot or video row and the path it stored. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct FileReference { - pub(crate) table: &'static str, - pub(crate) id: String, - pub(crate) path: String, - pub(crate) reason: &'static str, -} - -#[derive(Debug, Default, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct PlanReport { - pub(crate) imported_runs: Vec, - /// Unfinished Runs closed as `abandoned` at their last-seen time. - pub(crate) closed_runs: Vec, - pub(crate) skipped_runs: Vec, - /// Rows not imported because of their file: a path outside the V5 Data - /// Root, or a video V5 had already deleted or could not have recorded. - pub(crate) dropped_references: Vec, - /// Rows imported although their file is gone from V5. - pub(crate) missing_files: Vec, - /// Replay payloads the mod's retention would delete; their battles are - /// imported as `evicted`. - pub(crate) evicted_replays: Vec, -} - -pub(crate) struct ImportPlan { - /// `(table, row)` in insert order: parents before children. - pub(crate) rows: Vec<(&'static str, V6Row)>, - pub(crate) placements: Vec, - pub(crate) report: PlanReport, -} - -struct Context<'a> { - v5_root: &'a Path, - v6_root: &'a Path, - now_ms: i64, -} - -pub(crate) fn plan_import( - history: &V5History, - target: &Connection, - v5_root: &Path, - v6_root: &Path, - now_ms: i64, - retention: ReplayRetention, -) -> Result { - let context = Context { - v5_root, - v6_root, - now_ms, - }; - let shape = history.shape.unwrap_or(V5Shape::Lifecycle); - let by_run = |rows: &[V5Row]| { - let mut grouped: BTreeMap> = BTreeMap::new(); - for row in rows { - if let Some(run_id) = row.text("run_id") { - grouped.entry(run_id).or_default().push(row.clone()); - } - } - grouped - }; - let by_battle = |rows: &[V5Row]| { - let mut grouped: BTreeMap> = BTreeMap::new(); - for row in rows { - if let Some(battle_id) = row.text("battle_id") { - grouped.entry(battle_id).or_default().push(row.clone()); - } - } - grouped - }; - let events = by_run(&history.run_events); - let battles = by_run(&history.battles); - let screenshots = by_run(&history.screenshots); - let snapshots = by_battle(&history.battle_snapshots); - let videos = by_battle(&history.videos); - let none = Vec::new(); - - let mut report = PlanReport::default(); - let mut imported = Vec::new(); - for run in &history.runs { - let run_id = run.text("run_id").unwrap_or_default(); - let run_battles = battles.get(&run_id).unwrap_or(&none); - let run_screenshots = screenshots.get(&run_id).unwrap_or(&none); - if exists(target, "select 1 from runs where run_id = ?1", &run_id)? { - report.skipped_runs.push(SkippedRun { - run_id, - reason: "already_present", - }); - continue; - } - let mut conflict = false; - for battle in run_battles { - let battle_id = battle.text("battle_id").unwrap_or_default(); - conflict |= exists( - target, - "select 1 from battles where battle_id = ?1", - &battle_id, - )? || exists( - target, - "select 1 from battle_snapshots where battle_id = ?1", - &battle_id, - )?; - for video in videos.get(&battle_id).unwrap_or(&none) { - conflict |= exists( - target, - "select 1 from combat_replay_videos where video_id = ?1", - &video.text("video_id").unwrap_or_default(), - )?; - } - } - for screenshot in run_screenshots { - conflict |= exists( - target, - "select 1 from run_screenshots where screenshot_id = ?1", - &screenshot.text("screenshot_id").unwrap_or_default(), - )?; - } - if conflict { - report.skipped_runs.push(SkippedRun { - run_id, - reason: "conflicting_id", - }); - continue; - } - imported.push((run, run_id, run_battles, run_screenshots)); - } - - // Battles first: the replay retention ranks every imported payload together - // with the payloads the current Data Root already keeps. - let mut battle_rows = Vec::new(); - let mut candidates = Vec::new(); - for (_, _, run_battles, _) in &imported { - for battle in run_battles.iter() { - let (row, ready) = map_battle(&context, shape, battle)?; - if ready { - candidates.push(( - integer(&row, "recorded_at_ms"), - battle.text("battle_id").unwrap_or_default(), - )); - } - battle_rows.push((battle, row)); - } - } - let retained = retained_payloads(target, v6_root, &candidates, now_ms, retention)?; - - let mut rows = Vec::new(); - let mut placements = Placements::default(); - for (run, run_id, _, _) in &imported { - let (row, closed) = map_run(run)?; - rows.push(("runs", row)); - report.imported_runs.push(run_id.clone()); - if closed { - report.closed_runs.push(run_id.clone()); - } - for event in events.get(run_id).unwrap_or(&none) { - rows.push(("run_events", map_run_event(event)?)); - } - } - for (battle, mut row) in battle_rows { - let battle_id = battle.text("battle_id").unwrap_or_default(); - if text_of(&row, "local_payload_state") == Some("ready") { - if retained.contains(&battle_id) { - let source = replay_payload_path(&combat_replays_dir_in(v5_root), &battle_id); - let target = replay_payload_path(&combat_replays_dir_in(v6_root), &battle_id); - if let (Some(source), Some(target)) = (source, target) { - placements.add(source, target); - } - } else { - set( - &mut row, - "local_payload_state", - Value::Text("evicted".into()), - ); - set( - &mut row, - "local_payload_maintenance_at_ms", - Value::Integer(now_ms), - ); - report.evicted_replays.push(battle_id.clone()); - } - } - rows.push(("battles", row)); - for snapshot in snapshots.get(&battle_id).unwrap_or(&none) { - rows.push(("battle_snapshots", copy(snapshot, SNAPSHOT_COLUMNS))); - } - for video in videos.get(&battle_id).unwrap_or(&none) { - if let Some(row) = map_video(&context, shape, video, &mut placements, &mut report)? { - rows.push(("combat_replay_videos", row)); - } - } - } - for (_, _, _, run_screenshots) in &imported { - for screenshot in run_screenshots.iter() { - if let Some(row) = map_screenshot(&context, screenshot, &mut placements, &mut report)? { - rows.push(("run_screenshots", row)); - } - } - } - - report.skipped_runs.sort(); - report.dropped_references.sort(); - report.missing_files.sort(); - report.evicted_replays.sort(); - Ok(ImportPlan { - rows, - placements: placements.into_requests(), - report, - }) -} - -const SNAPSHOT_COLUMNS: &[&str] = &[ - "battle_id", - "player_hand_json", - "player_skills_json", - "opponent_hand_json", - "opponent_skills_json", -]; - -/// V6 `runs` columns copied unchanged. -const RUN_COPIED: &[&str] = &[ - "run_id", - "hero", - "game_mode", - "player_rank", - "player_rating", - "day", - "hour", - "max_health", - "prestige", - "level", - "income", - "gold", - "last_seq", - "final_day", - "final_hour", - "victories", - "losses", - "final_player_rank", - "final_player_rating", - "final_player_rating_delta", - "reason", - "build_channel", - "player_account_id", - "bundle_screenshot_requested", - "mod_version", -]; - -/// V6 `battles` columns copied unchanged. -const BATTLE_COPIED: &[&str] = &[ - "battle_id", - "remote_battle_id", - "uploader_account_id", - "source", - "run_id", - "local_player_account_id", - "day", - "hour", - "encounter_id", - "combat_kind", - "player_name", - "player_account_id", - "player_hero", - "player_rank", - "player_rating", - "player_level", - "player_prestige", - "player_income", - "player_gold", - "player_victories", - "player_hand_item_count", - "player_skill_count", - "opponent_name", - "opponent_account_id", - "opponent_hero", - "opponent_rank", - "opponent_rating", - "opponent_level", - "opponent_prestige", - "opponent_victories", - "opponent_hand_item_count", - "opponent_skill_count", - "result", - "winner_combatant_id", - "loser_combatant_id", - "is_final_battle", - "bundle_id", - "download_url", - "download_url_expires_at_ms", - "ghost_replay_state", - "ghost_replay_unavailable_reason", -]; - -/// V6 `combat_replay_videos` columns copied unchanged. -const VIDEO_COPIED: &[&str] = &[ - "video_id", - "battle_id", - "source", - "width", - "height", - "fps", - "codec", - "crf", - "preset", - "duration_ms", - "captured_frames", - "dropped_frames", - "file_size_bytes", - "status", - "error", -]; - -/// V6 `run_screenshots` columns copied unchanged. -const SCREENSHOT_COPIED: &[&str] = &[ - "screenshot_id", - "run_id", - "hero_name", - "capture_source", - "is_primary", - "day", - "player_rank", - "player_rating", - "player_position", - "victories_at_capture", -]; - -const PAYLOAD_STATES: [&str; 4] = ["ready", "delete_pending", "evicted", "missing"]; - -fn copy(row: &V5Row, columns: &[&'static str]) -> V6Row { - columns - .iter() - .map(|column| (*column, row.value(column))) - .collect() -} - -fn set(row: &mut V6Row, column: &'static str, value: Value) { - match row.iter_mut().find(|(name, _)| *name == column) { - Some(entry) => entry.1 = value, - None => row.push((column, value)), - } -} - -fn get<'a>(row: &'a [(&'static str, Value)], column: &str) -> Option<&'a Value> { - row.iter() - .find(|(name, _)| *name == column) - .map(|(_, value)| value) -} - -fn text_of<'a>(row: &'a [(&'static str, Value)], column: &str) -> Option<&'a str> { - match get(row, column) { - Some(Value::Text(text)) => Some(text), - _ => None, - } -} - -fn integer(row: &[(&'static str, Value)], column: &str) -> i64 { - match get(row, column) { - Some(Value::Integer(value)) => *value, - _ => 0, - } -} - -fn exists(conn: &Connection, sql: &str, key: &str) -> Result { - conn.query_row(sql, [key], |_| Ok(())) - .optional() - .map(|found| found.is_some()) - .map_err(|error| ImportError::Target(error.to_string())) -} - -/// The instant in `column` of a V5 row as Unix milliseconds. NULL stays NULL; -/// text that is no instant fails the import rather than inventing a time. -fn instant( - row: &V5Row, - table: &'static str, - id_column: &str, - column: &'static str, -) -> Result, ImportError> { - match row.value(column) { - Value::Null => Ok(None), - Value::Text(text) => { - parse_v5_instant_ms(&text) - .map(Some) - .ok_or_else(|| ImportError::InvalidV5Value { - table, - id: row.text(id_column).unwrap_or_default(), - column, - value: text, - }) - } - other => Err(ImportError::InvalidV5Value { - table, - id: row.text(id_column).unwrap_or_default(), - column, - value: format!("{other:?}"), - }), - } -} - -fn required_instant( - row: &V5Row, - table: &'static str, - id_column: &str, - column: &'static str, -) -> Result { - instant(row, table, id_column, column)?.ok_or_else(|| ImportError::InvalidV5Value { - table, - id: row.text(id_column).unwrap_or_default(), - column, - value: "NULL".into(), - }) -} - -fn nullable(value: Option) -> Value { - value.map_or(Value::Null, Value::Integer) -} - -/// Returns the V6 row and whether the Run was unfinished and is closed here. -fn map_run(run: &V5Row) -> Result<(V6Row, bool), ImportError> { - let started = required_instant(run, "runs", "run_id", "started_at_utc")?; - let last_seen = required_instant(run, "runs", "run_id", "last_seen_at_utc")?; - let ended = instant(run, "runs", "run_id", "ended_at_utc")?; - let status = run.text("status").unwrap_or_default(); - // As the mod's MarkRunAbandoned closes a Run: abandoned at its last-seen time. - let finished = - run.integer("completed") == Some(1) && matches!(status.as_str(), "completed" | "abandoned"); - let mut row = copy(run, RUN_COPIED); - row.push(("started_at_ms", Value::Integer(started))); - row.push(("last_seen_at_ms", Value::Integer(last_seen))); - if finished { - row.push(("status", Value::Text(status))); - row.push(("ended_at_ms", nullable(ended))); - } else { - row.push(("status", Value::Text("abandoned".into()))); - row.push(("ended_at_ms", Value::Integer(last_seen))); - } - row.push(("upload_policy", Value::Text("history_only".into()))); - Ok((row, !finished)) -} - -fn map_run_event(event: &V5Row) -> Result { - let mut row = copy(event, &["run_id", "seq", "kind", "payload_json"]); - row.push(( - "ts_at_ms", - Value::Integer(required_instant(event, "run_events", "run_id", "ts_utc")?), - )); - Ok(row) -} - -/// The V6 battle row, and whether its payload is a retention candidate: -/// `ready` with the file present in V5. A `ready` battle without its file is -/// `missing`; `delete_pending` is `evicted`, since V5 had chosen to delete it. -fn map_battle( - context: &Context<'_>, - shape: V5Shape, - battle: &V5Row, -) -> Result<(V6Row, bool), ImportError> { - let mut row = copy(battle, BATTLE_COPIED); - row.push(( - "recorded_at_ms", - Value::Integer(required_instant( - battle, - "battles", - "battle_id", - "recorded_at_utc", - )?), - )); - row.push(( - "deleted_at_ms", - nullable(instant(battle, "battles", "battle_id", "deleted_at_utc")?), - )); - // UpgradeToLifecycleColumns derived the state from has_local_payload; an - // upgraded table has no CHECK, so an unknown state is derived the same way. - let stored = match shape { - V5Shape::First => None, - V5Shape::Lifecycle => battle - .text("local_payload_state") - .filter(|state| PAYLOAD_STATES.contains(&state.as_str())), - }; - let maintenance = match (shape, &stored) { - (V5Shape::Lifecycle, Some(_)) => instant( - battle, - "battles", - "battle_id", - "local_payload_maintenance_at_utc", - )?, - _ => None, - }; - let state = stored.unwrap_or_else(|| { - if battle.integer("has_local_payload") == Some(1) { - "ready".into() - } else { - "missing".into() - } - }); - let battle_id = battle.text("battle_id").unwrap_or_default(); - let (state, maintenance, candidate) = match state.as_str() { - "ready" => { - let present = replay_payload_path(&combat_replays_dir_in(context.v5_root), &battle_id) - .is_some_and(|path| is_regular_file(&path)); - if present { - ("ready", maintenance, true) - } else { - ("missing", Some(context.now_ms), false) - } - } - "delete_pending" => ("evicted", Some(context.now_ms), false), - "evicted" => ("evicted", maintenance, false), - _ => ("missing", maintenance, false), - }; - row.push(("local_payload_state", Value::Text(state.into()))); - row.push(("local_payload_maintenance_at_ms", nullable(maintenance))); - Ok((row, candidate)) -} - -/// The payloads the mod's retention keeps among `candidates` and the payloads -/// the current Data Root already holds: the newest `newest_count` by recorded -/// time (battle id breaking ties), plus everything inside the age window -/// (`ReplayPayloadRetentionPolicy.SelectEvictionCandidates`). -fn retained_payloads( - target: &Connection, - v6_root: &Path, - candidates: &[(i64, String)], - now_ms: i64, - retention: ReplayRetention, -) -> Result, ImportError> { - let mut statement = target - .prepare( - "select recorded_at_ms, battle_id from battles \ - where source = 'LOCAL' and local_payload_state = 'ready'", - ) - .map_err(|error| ImportError::Target(error.to_string()))?; - let existing = statement - .query_map([], |row| { - Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)) - }) - .and_then(|rows| rows.collect::, _>>()) - .map_err(|error| ImportError::Target(error.to_string()))?; - let v6_replays = combat_replays_dir_in(v6_root); - let mut ranked: Vec<(i64, &str, bool)> = existing - .iter() - .filter(|(_, battle_id)| { - replay_payload_path(&v6_replays, battle_id).is_some_and(|path| is_regular_file(&path)) - }) - .map(|(recorded, battle_id)| (*recorded, battle_id.as_str(), false)) - .chain( - candidates - .iter() - .map(|(recorded, battle_id)| (*recorded, battle_id.as_str(), true)), - ) - .collect(); - ranked.sort_by(|left, right| right.0.cmp(&left.0).then_with(|| right.1.cmp(left.1))); - let cutoff = now_ms.saturating_sub(retention.age_days.saturating_mul(DAY_MS)); - Ok(ranked - .iter() - .enumerate() - .filter(|(index, (recorded, _, imported))| { - *imported && (*index < retention.newest_count || *recorded >= cutoff) - }) - .map(|(_, (_, battle_id, _))| (*battle_id).to_string()) - .collect()) -} - -fn map_video( - context: &Context<'_>, - shape: V5Shape, - video: &V5Row, - placements: &mut Placements, - report: &mut PlanReport, -) -> Result, ImportError> { - let video_id = video.text("video_id").unwrap_or_default(); - let raw_path = video.text("video_relative_path").unwrap_or_default(); - let reference = |reason| FileReference { - table: "combat_replay_videos", - id: video_id.clone(), - path: raw_path.clone(), - reason, - }; - let (attachment, file_state) = match shape { - V5Shape::First => ("attached".to_string(), "pending".to_string()), - V5Shape::Lifecycle => ( - video.text("attachment_state").unwrap_or_default(), - video.text("file_state").unwrap_or_default(), - ), - }; - // V6 keeps no row for a deleted video file; the CHECK limits status. - if file_state == "deleted" { - report.dropped_references.push(reference("file_deleted")); - return Ok(None); - } - let status = video.text("status").unwrap_or_default(); - if !matches!(status.as_str(), "RECORDING" | "COMPLETED" | "FAILED") { - report.dropped_references.push(reference("invalid_status")); - return Ok(None); - } - let directory = combat_replay_videos_dir_in(context.v5_root); - let Some(relative) = data_relative_path(&raw_path, &directory) else { - report - .dropped_references - .push(reference("outside_data_root")); - return Ok(None); - }; - place( - placements, - report, - &directory, - &combat_replay_videos_dir_in(context.v6_root), - &relative, - reference("source_missing"), - ); - - let mut row = copy(video, VIDEO_COPIED); - row.push(("video_relative_path", Value::Text(relative))); - row.push(( - "started_at_ms", - Value::Integer(required_instant( - video, - "combat_replay_videos", - "video_id", - "started_at_utc", - )?), - )); - row.push(( - "ended_at_ms", - nullable(instant( - video, - "combat_replay_videos", - "video_id", - "ended_at_utc", - )?), - )); - // An upgraded table has no CHECK on these; the video belongs to an imported - // battle, so it is attached, and the mod reconciles an unknown file state. - let attachment = if matches!(attachment.as_str(), "attached" | "detached") { - attachment - } else { - "attached".into() - }; - let file_state = if matches!(file_state.as_str(), "pending" | "present" | "missing") { - file_state - } else { - "pending".into() - }; - row.push(("attachment_state", Value::Text(attachment))); - row.push(("file_state", Value::Text(file_state))); - for (v6, v5) in [ - ("detached_at_ms", "detached_at_utc"), - ("missing_at_ms", "missing_at_utc"), - ("last_reconciled_at_ms", "last_reconciled_at_utc"), - ] { - let value = match shape { - V5Shape::First => None, - V5Shape::Lifecycle => instant(video, "combat_replay_videos", "video_id", v5)?, - }; - row.push((v6, nullable(value))); - } - Ok(Some(row)) -} - -fn map_screenshot( - context: &Context<'_>, - screenshot: &V5Row, - placements: &mut Placements, - report: &mut PlanReport, -) -> Result, ImportError> { - let screenshot_id = screenshot.text("screenshot_id").unwrap_or_default(); - let raw_path = screenshot.text("image_relative_path").unwrap_or_default(); - let reference = |reason| FileReference { - table: "run_screenshots", - id: screenshot_id.clone(), - path: raw_path.clone(), - reason, - }; - let directory = screenshots_dir_in(context.v5_root); - let Some(relative) = data_relative_path(&raw_path, &directory) else { - report - .dropped_references - .push(reference("outside_data_root")); - return Ok(None); - }; - let local = screenshot.text("captured_at_local").unwrap_or_default(); - let offset = parse_v5_offset_minutes(&local).ok_or_else(|| ImportError::InvalidV5Value { - table: "run_screenshots", - id: screenshot_id.clone(), - column: "captured_at_local", - value: local.clone(), - })?; - let captured = required_instant( - screenshot, - "run_screenshots", - "screenshot_id", - "captured_at_utc", - )?; - place( - placements, - report, - &directory, - &screenshots_dir_in(context.v6_root), - &relative, - reference("source_missing"), - ); - - let mut row = copy(screenshot, SCREENSHOT_COPIED); - row.push(("image_relative_path", Value::Text(relative))); - row.push(("captured_at_ms", Value::Integer(captured))); - row.push(("captured_utc_offset_minutes", Value::Integer(offset))); - Ok(Some(row)) -} - -/// The stored path as a `/`-separated path under `directory`, the V5 folder its -/// kind of file lives in. A relative path stays relative (`.` and `..` dropped, -/// as History cleanup resolves it); an absolute path is kept only when it lies -/// under `directory`. `None` for anything else. -fn data_relative_path(raw: &str, directory: &Path) -> Option { - let trimmed = raw.trim(); - if trimmed.is_empty() { - return None; - } - let relative = if Path::new(trimmed).is_absolute() { - // A `\\?\` path treats `/` as part of a name, so a root written that - // way followed by `/`-joined segments never matches; Windows reads - // either separator the same in any other absolute path. - let written = if cfg!(windows) { - trimmed.replace('/', "\\") - } else { - trimmed.to_owned() - }; - // Compare as written and with links resolved: the game directory may be - // reached through a symbolic link, as macOS temporary folders are. - let path = Path::new(&written); - let paths = [Some(path.to_path_buf()), path.canonicalize().ok()]; - let bases = [Some(directory.to_path_buf()), directory.canonicalize().ok()]; - let rest = paths.iter().flatten().find_map(|path| { - bases - .iter() - .flatten() - .find_map(|base| path.strip_prefix(base).ok().map(Path::to_path_buf)) - })?; - normalize_relative_path(&rest.to_string_lossy()) - } else { - normalize_relative_path(trimmed) - }; - if relative.is_empty() { - return None; - } - // `C:name` is not absolute on Windows, yet joining it replaces the root. - resolve_cleanup_file_path(directory, &relative)?; - Some(relative) -} - -fn place( - placements: &mut Placements, - report: &mut PlanReport, - source_directory: &Path, - target_directory: &Path, - relative: &str, - missing: FileReference, -) { - let (Some(source), Some(target)) = ( - resolve_cleanup_file_path(source_directory, relative), - resolve_cleanup_file_path(target_directory, relative), - ) else { - return; - }; - if is_regular_file(&source) { - placements.add(source, target); - } else { - report.missing_files.push(missing); - } -} - -/// A regular file, not a symbolic link: the import never follows a link out of -/// the V5 Data Root. -fn is_regular_file(path: &Path) -> bool { - std::fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_file()) -} - -/// Placement requests, one per target: Runs that share a file place it once. -#[derive(Default)] -struct Placements(BTreeMap); - -impl Placements { - fn add(&mut self, source: PathBuf, target: PathBuf) { - self.0.entry(target).or_insert(source); - } - - fn into_requests(self) -> Vec { - self.0 - .into_iter() - .map(|(target, source)| PlacementRequest { source, target }) - .collect() - } -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/run.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/run.rs deleted file mode 100644 index 1b40107..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/run.rs +++ /dev/null @@ -1,176 +0,0 @@ -//! The import as one operation: everything it writes into the current Data Root -//! commits together, or none of it stays. -//! -//! Order: data maintenance lock (OBS overlay stopped) -> marker and eligibility -//! -> fail-closed game check -> read V5 -> exclusive transaction on the current -//! database -> place files -> insert rows -> game check again -> commit -> -//! marker. The checks run inside the lock so nothing can change between check -//! and use. A failure before the commit rolls back the transaction, removes -//! every file and directory this import placed, removes a database or Data -//! Root directory it created, and writes no marker. - -use std::path::{Path, PathBuf}; - -use serde::Serialize; - -use super::plan::{plan_import, PlanReport, ReplayRetention}; -use super::source::read_v5_history; -use super::target::Target; -use super::{is_v5_import_eligible, v5_import_marker_path, ImportError}; -use crate::services::data_maintenance::DataMaintenanceLock; -use crate::services::game_process::{ - ensure_game_stopped_with, GameProcessProbe, GameStoppedOperation, SystemGameProcessProbe, -}; -use crate::services::legacy_data::{ - installed_mod_data_root, InstalledModDataRoot, LegacyRoot, INSTALLED_HISTORY_DATABASE_CONTRACT, -}; -use crate::services::placement::{PlacementBackend, Placer, SystemBackend}; -use crate::stream::runtime::StreamRuntime; - -/// The marker's contents; any entry with the marker's name counts. -const MARKER_TEXT: &str = - "BazaarPlusPlus imported this folder's history into BazaarPlusPlusV6 once.\n\ - Deleting this file lets the installer offer the import again.\n"; - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct ImportReport { - #[serde(flatten)] - pub(crate) plan: PlanReport, - /// Files the imported rows reference, relative to the current Data Root. - pub(crate) files: Vec, -} - -/// Runs the import for the app and the headless CLI: under the data maintenance -/// lock with the overlay stopped, on the blocking pool. -pub(crate) async fn import_v5( - maintenance: &DataMaintenanceLock, - stream_runtime: &StreamRuntime, - game_path: PathBuf, - now_ms: i64, -) -> Result { - maintenance - .run_blocking_with_overlay_stopped(stream_runtime, move || { - import_blocking_with(&game_path, &SystemGameProcessProbe, SystemBackend, now_ms) - }) - .await - .map_err(ImportError::Target)? -} - -/// The import itself; the caller holds the data maintenance lock. -pub(crate) fn import_blocking_with( - game_path: &Path, - probe: &impl GameProcessProbe, - backend: B, - now_ms: i64, -) -> Result { - if !crate::services::detect::is_valid_game_path(game_path) { - return Err(ImportError::InvalidGamePath); - } - if std::fs::symlink_metadata(v5_import_marker_path(game_path)).is_ok() { - return Err(ImportError::AlreadyImported); - } - if !is_v5_import_eligible(game_path) { - return Err(ImportError::NotEligible( - if installed_mod_data_root(game_path) == InstalledModDataRoot::Current { - "no_v5_data_root" - } else { - "installed_mod_writes_old_root" - }, - )); - } - let check_game = |stage| { - ensure_game_stopped_with(probe, game_path, GameStoppedOperation::Import) - .map_err(|refusal| ImportError::GameRunning { refusal, stage }) - }; - check_game("start")?; - let retention = read_retention(game_path)?; - - let v5_root = LegacyRoot::V5.path_in(game_path); - let v6_root = crate::services::paths::bpp_data_dir(game_path); - let history = read_v5_history(&v5_root)?; - - let mut target = Target::begin(&v6_root)?; - let mut placer = Placer::new(backend); - let staged = (|| { - let plan = plan_import( - &history, - target.conn(), - &v5_root, - target.data_root(), - now_ms, - retention, - )?; - placer - .place(&plan.placements) - .map_err(ImportError::Placement)?; - for (table, row) in &plan.rows { - target.insert(table, row)?; - } - check_game("before_commit")?; - target.commit()?; - Ok(plan) - })(); - let plan = match staged { - Ok(plan) => plan, - Err(error) => { - // Best effort: a file the rollback cannot remove stays an orphan the - // mod and History cleanup already handle; the error that stopped the - // import is the one to report. - let _ = placer.rollback(); - target.abort(); - return Err(error); - } - }; - target.finish()?; - - let mut files: Vec = plan - .placements - .iter() - .filter_map(|request| request.target.strip_prefix(&v6_root).ok()) - .map(|path| path.to_string_lossy().replace('\\', "/")) - .collect(); - files.sort(); - write_marker(game_path)?; - Ok(ImportReport { - plan: plan.report, - files, - }) -} - -/// The replay retention the installed mod applies, from its contract file. -fn read_retention(game_path: &Path) -> Result { - let path = game_path.join(INSTALLED_HISTORY_DATABASE_CONTRACT); - let contract: serde_json::Value = std::fs::read(&path) - .map_err(|error| error.to_string()) - .and_then(|bytes| serde_json::from_slice(&bytes).map_err(|error| error.to_string())) - .map_err(|error| ImportError::ModContract(format!("{}: {error}", path.display())))?; - let positive = |field: &str| { - contract - .get(field) - .and_then(serde_json::Value::as_u64) - .filter(|value| *value > 0) - .ok_or_else(|| { - ImportError::ModContract(format!("{} has no positive {field}", path.display())) - }) - }; - Ok(ReplayRetention { - newest_count: usize::try_from(positive("replayPayloadRetainedNewestCount")?) - .unwrap_or(usize::MAX), - age_days: i64::try_from(positive("replayPayloadRetainedAgeDays")?).unwrap_or(i64::MAX), - }) -} - -fn write_marker(game_path: &Path) -> Result<(), ImportError> { - use std::io::Write; - let path = v5_import_marker_path(game_path); - std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) - .and_then(|mut file| { - file.write_all(MARKER_TEXT.as_bytes())?; - file.sync_all() - }) - .map_err(|error| ImportError::MarkerNotWritten(format!("{}: {error}", path.display()))) -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/source.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/source.rs deleted file mode 100644 index d621845..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/source.rs +++ /dev/null @@ -1,424 +0,0 @@ -//! Reads a V5 local history database without changing it. -//! -//! The database file, with its `-wal` and `-journal`, is copied into a scratch -//! directory and the copy is opened. SQLite then replays frames a crashed game -//! left in the write-ahead log and rebuilds a missing `-shm`, and nothing in -//! `BazaarPlusPlusV5/` is written. The installer's History opener is not used: -//! its compatibility list names V6 versions, and V5's `user_version` 1 would -//! pass it. -//! -//! Four physical shapes exist (installer `tests/fixtures/v5-import/README.md`): -//! `user_version` 1, 2, 3 created fresh, and 3 upgraded from 1 by `ALTER TABLE` -//! without the table CHECKs. They are told apart by `user_version` and column -//! names, and every row is read through an explicit column list. - -use std::collections::BTreeMap; -use std::path::Path; - -use rusqlite::types::Value; -use rusqlite::{Connection, OpenFlags}; - -use super::ImportError; -use crate::config::DATABASE_FILE_NAME; - -/// Which V5 lineage a database belongs to. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum V5Shape { - /// `user_version` 1: no lifecycle columns; `UpgradeToLifecycleColumns` - /// derived them from `has_local_payload` and battle existence. - First, - /// `user_version` 2 or 3, created fresh or upgraded. - Lifecycle, -} - -pub(crate) const RUN_COLUMNS: &[&str] = &[ - "run_id", - "started_at_utc", - "last_seen_at_utc", - "status", - "completed", - "hero", - "game_mode", - "player_rank", - "player_rating", - "day", - "hour", - "max_health", - "prestige", - "level", - "income", - "gold", - "last_seq", - "ended_at_utc", - "final_day", - "final_hour", - "victories", - "losses", - "final_player_rank", - "final_player_rating", - "final_player_rating_delta", - "reason", - "build_channel", - "player_account_id", - "bundle_screenshot_requested", - "mod_version", -]; -const RUN_EVENT_COLUMNS: &[&str] = &["run_id", "seq", "ts_utc", "kind", "payload_json"]; -pub(crate) const BATTLE_COLUMNS: &[&str] = &[ - "battle_id", - "remote_battle_id", - "uploader_account_id", - "source", - "run_id", - "local_player_account_id", - "recorded_at_utc", - "day", - "hour", - "encounter_id", - "combat_kind", - "player_name", - "player_account_id", - "player_hero", - "player_rank", - "player_rating", - "player_level", - "player_prestige", - "player_income", - "player_gold", - "player_victories", - "player_hand_item_count", - "player_skill_count", - "opponent_name", - "opponent_account_id", - "opponent_hero", - "opponent_rank", - "opponent_rating", - "opponent_level", - "opponent_prestige", - "opponent_victories", - "opponent_hand_item_count", - "opponent_skill_count", - "result", - "winner_combatant_id", - "loser_combatant_id", - "is_final_battle", - "has_local_payload", - "bundle_id", - "download_url", - "download_url_expires_at_ms", - "ghost_replay_state", - "ghost_replay_unavailable_reason", - "deleted_at_utc", -]; -const BATTLE_LIFECYCLE_COLUMNS: &[&str] = - &["local_payload_state", "local_payload_maintenance_at_utc"]; -const BATTLE_SNAPSHOT_COLUMNS: &[&str] = &[ - "battle_id", - "player_hand_json", - "player_skills_json", - "opponent_hand_json", - "opponent_skills_json", -]; -const SCREENSHOT_COLUMNS: &[&str] = &[ - "screenshot_id", - "run_id", - "hero_name", - "capture_source", - "is_primary", - "image_relative_path", - "captured_at_local", - "captured_at_utc", - "day", - "player_rank", - "player_rating", - "player_position", - "victories_at_capture", -]; -const VIDEO_COLUMNS: &[&str] = &[ - "video_id", - "battle_id", - "source", - "video_relative_path", - "width", - "height", - "fps", - "codec", - "crf", - "preset", - "started_at_utc", - "ended_at_utc", - "duration_ms", - "captured_frames", - "dropped_frames", - "file_size_bytes", - "status", - "error", -]; -const VIDEO_LIFECYCLE_COLUMNS: &[&str] = &[ - "attachment_state", - "file_state", - "detached_at_utc", - "missing_at_utc", - "last_reconciled_at_utc", -]; - -/// One V5 row, keyed by column name. -#[derive(Clone, Debug, Default)] -pub(crate) struct V5Row(BTreeMap<&'static str, Value>); - -impl V5Row { - pub(crate) fn value(&self, column: &str) -> Value { - self.0.get(column).cloned().unwrap_or(Value::Null) - } - - pub(crate) fn text(&self, column: &str) -> Option { - match self.0.get(column) { - Some(Value::Text(text)) => Some(text.clone()), - Some(Value::Integer(value)) => Some(value.to_string()), - Some(Value::Real(value)) => Some(value.to_string()), - _ => None, - } - } - - pub(crate) fn integer(&self, column: &str) -> Option { - match self.0.get(column) { - Some(Value::Integer(value)) => Some(*value), - Some(Value::Text(text)) => text.trim().parse().ok(), - _ => None, - } - } -} - -/// Every row the import may bring over, in primary-key order. -#[derive(Debug, Default)] -pub(crate) struct V5History { - pub(crate) shape: Option, - pub(crate) runs: Vec, - pub(crate) run_events: Vec, - /// `source = 'LOCAL'` battles that belong to a Run; Ghost battles are never read. - pub(crate) battles: Vec, - pub(crate) battle_snapshots: Vec, - /// Screenshots that belong to a Run. - pub(crate) screenshots: Vec, - /// Videos of the battles above. - pub(crate) videos: Vec, -} - -/// Copies the V5 database next to nothing it could disturb and reads it. -pub(crate) fn read_v5_history(v5_root: &Path) -> Result { - let database = v5_root.join(DATABASE_FILE_NAME); - match std::fs::symlink_metadata(&database) { - Ok(metadata) if metadata.file_type().is_file() => {} - Ok(_) => { - return Err(ImportError::V5Unreadable(format!( - "{} is not a regular file", - database.display() - ))) - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - return Err(ImportError::V5DatabaseMissing) - } - Err(error) => return Err(ImportError::V5Unreadable(error.to_string())), - } - let scratch = tempfile::tempdir().map_err(|error| { - ImportError::V5Unreadable(format!("Cannot create a scratch directory: {error}")) - })?; - let copy = scratch.path().join(DATABASE_FILE_NAME); - for suffix in ["", "-wal", "-journal"] { - let source = v5_root.join(format!("{DATABASE_FILE_NAME}{suffix}")); - let is_file = - std::fs::symlink_metadata(&source).is_ok_and(|metadata| metadata.file_type().is_file()); - if !is_file { - continue; - } - std::fs::copy( - &source, - scratch.path().join(format!("{DATABASE_FILE_NAME}{suffix}")), - ) - .map_err(|error| { - ImportError::V5Unreadable(format!("Cannot copy {}: {error}", source.display())) - })?; - } - let conn = Connection::open_with_flags( - ©, - OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX, - ) - .map_err(|error| ImportError::V5Unreadable(error.to_string()))?; - let history = read_connection(&conn)?; - drop(conn); - drop(scratch); - Ok(history) -} - -fn read_connection(conn: &Connection) -> Result { - let user_version: i64 = conn - .query_row("pragma user_version", [], |row| row.get(0)) - .map_err(|error| ImportError::V5Unreadable(error.to_string()))?; - let shape = match user_version { - 1 => V5Shape::First, - 2 | 3 => V5Shape::Lifecycle, - other => return Err(ImportError::UnsupportedV5Schema(other)), - }; - - let lifecycle = shape == V5Shape::Lifecycle; - let battle_columns = with_lifecycle(BATTLE_COLUMNS, BATTLE_LIFECYCLE_COLUMNS, lifecycle); - let video_columns = with_lifecycle(VIDEO_COLUMNS, VIDEO_LIFECYCLE_COLUMNS, lifecycle); - - // `runs` is required; a table a V5 version created lazily may be missing - // and reads as empty. A present table must carry every column read below. - if !table_exists(conn, "runs")? { - return Err(ImportError::MissingV5Column { - table: "runs".into(), - column: None, - }); - } - for (table, columns) in [ - ("runs", RUN_COLUMNS), - ("run_events", RUN_EVENT_COLUMNS), - ("battles", battle_columns.as_slice()), - ("battle_snapshots", BATTLE_SNAPSHOT_COLUMNS), - ("run_screenshots", SCREENSHOT_COLUMNS), - ("combat_replay_videos", video_columns.as_slice()), - ] { - require_columns(conn, table, columns)?; - } - - let has_battles = table_exists(conn, "battles")?; - let local_battles = "b.source = 'LOCAL' and b.run_id is not null"; - Ok(V5History { - shape: Some(shape), - runs: select(conn, "runs", "r", RUN_COLUMNS, "1 = 1", "r.run_id")?, - run_events: select( - conn, - "run_events", - "e", - RUN_EVENT_COLUMNS, - "1 = 1", - "e.run_id, e.seq", - )?, - battles: select( - conn, - "battles", - "b", - &battle_columns, - local_battles, - "b.battle_id", - )?, - battle_snapshots: if has_battles { - select( - conn, - "battle_snapshots", - "s", - BATTLE_SNAPSHOT_COLUMNS, - &format!( - "exists (select 1 from battles b where b.battle_id = s.battle_id \ - and {local_battles})" - ), - "s.battle_id", - )? - } else { - Vec::new() - }, - screenshots: select( - conn, - "run_screenshots", - "s", - SCREENSHOT_COLUMNS, - "s.run_id is not null", - "s.screenshot_id", - )?, - videos: if has_battles { - select( - conn, - "combat_replay_videos", - "v", - &video_columns, - &format!( - "exists (select 1 from battles b where b.battle_id = v.battle_id \ - and {local_battles})" - ), - "v.video_id", - )? - } else { - Vec::new() - }, - }) -} - -fn with_lifecycle( - base: &[&'static str], - lifecycle: &[&'static str], - include: bool, -) -> Vec<&'static str> { - let mut columns = base.to_vec(); - if include { - columns.extend_from_slice(lifecycle); - } - columns -} - -fn table_exists(conn: &Connection, table: &str) -> Result { - conn.query_row( - "select exists (select 1 from sqlite_master where type = 'table' and name = ?1)", - [table], - |row| row.get(0), - ) - .map_err(|error| ImportError::V5Unreadable(error.to_string())) -} - -fn require_columns(conn: &Connection, table: &str, columns: &[&str]) -> Result<(), ImportError> { - if !table_exists(conn, table)? { - return Ok(()); - } - let mut statement = conn - .prepare("select name from pragma_table_info(?1)") - .map_err(|error| ImportError::V5Unreadable(error.to_string()))?; - let present = statement - .query_map([table], |row| row.get::<_, String>(0)) - .and_then(Iterator::collect::, _>>) - .map_err(|error| ImportError::V5Unreadable(error.to_string()))?; - match columns - .iter() - .find(|column| !present.iter().any(|name| name == *column)) - { - Some(column) => Err(ImportError::MissingV5Column { - table: table.into(), - column: Some((*column).into()), - }), - None => Ok(()), - } -} - -/// Reads `columns` of `table` by name; a missing table reads as no rows. -fn select( - conn: &Connection, - table: &str, - alias: &str, - columns: &[&'static str], - filter: &str, - order: &str, -) -> Result, ImportError> { - if !table_exists(conn, table)? { - return Ok(Vec::new()); - } - let list = columns - .iter() - .map(|column| format!("{alias}.\"{column}\"")) - .collect::>() - .join(", "); - let sql = format!("select {list} from \"{table}\" {alias} where {filter} order by {order}"); - let mut statement = conn - .prepare(&sql) - .map_err(|error| ImportError::V5Unreadable(error.to_string()))?; - let rows = statement - .query_map([], |row| { - let mut values = BTreeMap::new(); - for (index, column) in columns.iter().enumerate() { - values.insert(*column, row.get::<_, Value>(index)?); - } - Ok(V5Row(values)) - }) - .and_then(Iterator::collect::, _>>) - .map_err(|error| ImportError::V5Unreadable(error.to_string()))?; - Ok(rows) -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/target.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/target.rs deleted file mode 100644 index 0695841..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/target.rs +++ /dev/null @@ -1,201 +0,0 @@ -//! The current Data Root's history database as the import writes it: created -//! from the mod's schema file when missing, otherwise merged into under one -//! exclusive transaction. Until [`Target::commit`] succeeds, [`Target::abort`] leaves the -//! database and the Data Root directory as they were. - -use std::path::{Path, PathBuf}; - -use rusqlite::types::Value; -use rusqlite::{Connection, OpenFlags}; - -use super::ImportError; -use crate::config::DATABASE_FILE_NAME; - -const SIDE_FILE_SUFFIXES: [&str; 3] = ["-wal", "-shm", "-journal"]; - -pub(crate) struct Target { - conn: Option, - data_root: PathBuf, - created_root: bool, - created_database: bool, - /// The schema was created in this transaction: a new file, or an empty one - /// an interrupted earlier import left behind. - fresh: bool, -} - -impl Target { - /// Opens or creates the database under `data_root` and begins an exclusive - /// transaction on it. - pub(crate) fn begin(data_root: &Path) -> Result { - let created_root = match std::fs::symlink_metadata(data_root) { - Ok(metadata) if metadata.file_type().is_dir() => false, - Ok(_) => { - return Err(ImportError::Target(format!( - "{} is not a directory", - data_root.display() - ))) - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - std::fs::create_dir(data_root).map_err(|error| { - ImportError::Target(format!("Cannot create {}: {error}", data_root.display())) - })?; - true - } - Err(error) => return Err(ImportError::Target(error.to_string())), - }; - let mut target = Self { - conn: None, - data_root: data_root.to_path_buf(), - created_root, - created_database: false, - fresh: false, - }; - match target.open() { - Ok(()) => Ok(target), - Err(error) => { - target.abort(); - Err(error) - } - } - } - - fn database_path(&self) -> PathBuf { - self.data_root.join(DATABASE_FILE_NAME) - } - - fn open(&mut self) -> Result<(), ImportError> { - let path = self.database_path(); - self.created_database = match std::fs::symlink_metadata(&path) { - Ok(metadata) if metadata.file_type().is_file() => false, - Ok(_) => { - return Err(ImportError::Target(format!( - "{} is not a regular file", - path.display() - ))) - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => true, - Err(error) => return Err(ImportError::Target(error.to_string())), - }; - let conn = Connection::open_with_flags( - &path, - OpenFlags::SQLITE_OPEN_READ_WRITE - | OpenFlags::SQLITE_OPEN_CREATE - | OpenFlags::SQLITE_OPEN_NO_MUTEX, - ) - .map_err(target_error)?; - conn.busy_timeout(std::time::Duration::from_secs(5)) - .map_err(target_error)?; - // The mod opens with foreign keys on; the import's rows must satisfy them. - conn.execute_batch("pragma foreign_keys = on; begin exclusive;") - .map_err(target_error)?; - self.conn = Some(conn); - let conn = self.conn.as_ref().expect("just opened"); - let user_version: i64 = conn - .query_row("pragma user_version", [], |row| row.get(0)) - .map_err(target_error)?; - let objects: i64 = conn - .query_row("select count(*) from sqlite_master", [], |row| row.get(0)) - .map_err(target_error)?; - let newest = crate::config::supported_mod_db_user_versions() - .last() - .copied() - .unwrap_or_default(); - if user_version == 0 && objects == 0 { - self.fresh = true; - crate::history::mod_schema::execute_mod_schema(conn).map_err(ImportError::Target)?; - } else if user_version != newest { - return Err(ImportError::TargetUnsupported(user_version)); - } - Ok(()) - } - - pub(crate) fn conn(&self) -> &Connection { - self.conn - .as_ref() - .expect("target is open until commit or abort") - } - - pub(crate) fn data_root(&self) -> &Path { - &self.data_root - } - - pub(crate) fn insert(&self, table: &str, row: &[(&str, Value)]) -> Result<(), ImportError> { - let columns = row - .iter() - .map(|(column, _)| format!("\"{column}\"")) - .collect::>() - .join(", "); - let placeholders = (1..=row.len()) - .map(|index| format!("?{index}")) - .collect::>() - .join(", "); - let mut statement = self - .conn() - .prepare_cached(&format!( - "insert into \"{table}\" ({columns}) values ({placeholders})" - )) - .map_err(target_error)?; - statement - .execute(rusqlite::params_from_iter( - row.iter().map(|(_, value)| value), - )) - .map_err(|error| ImportError::Target(format!("insert into {table}: {error}")))?; - Ok(()) - } - - /// Commits the transaction. On failure the transaction is still open and - /// [`Self::abort`] undoes it. - pub(crate) fn commit(&mut self) -> Result<(), ImportError> { - self.conn().execute_batch("commit").map_err(target_error) - } - - /// After [`Self::commit`]: puts a database this import created into WAL - /// mode, as the mod keeps it, checks its version, and closes it. Nothing is - /// undone on failure; the rows are already committed. - pub(crate) fn finish(mut self) -> Result<(), ImportError> { - let conn = self.conn.take().expect("target is open until finish"); - if self.fresh { - let mode: String = conn - .query_row("pragma journal_mode = wal", [], |row| row.get(0)) - .map_err(target_error)?; - if !mode.eq_ignore_ascii_case("wal") { - return Err(ImportError::Target(format!( - "journal_mode is {mode}, not wal" - ))); - } - } - let user_version: i64 = conn - .query_row("pragma user_version", [], |row| row.get(0)) - .map_err(target_error)?; - if Some(&user_version) != crate::config::supported_mod_db_user_versions().last() { - return Err(ImportError::TargetUnsupported(user_version)); - } - conn.close().map_err(|(_, error)| target_error(error)) - } - - /// Rolls back and removes the database file and the Data Root directory when - /// this import created them. Files placed into the directory are the - /// placer's to remove first. - pub(crate) fn abort(mut self) { - if let Some(conn) = self.conn.take() { - let _ = conn.execute_batch("rollback"); - let _ = conn.close(); - } - if self.created_database { - let path = self.database_path(); - let _ = std::fs::remove_file(&path); - for suffix in SIDE_FILE_SUFFIXES { - let mut side = path.clone().into_os_string(); - side.push(suffix); - let _ = std::fs::remove_file(PathBuf::from(side)); - } - } - if self.created_root { - let _ = std::fs::remove_dir(&self.data_root); - } - } -} - -fn target_error(error: rusqlite::Error) -> ImportError { - ImportError::Target(error.to_string()) -} diff --git a/bazaarplusplus-installer/src-tauri/src/v5_import/tests_e2e.rs b/bazaarplusplus-installer/src-tauri/src/v5_import/tests_e2e.rs deleted file mode 100644 index b515a37..0000000 --- a/bazaarplusplus-installer/src-tauri/src/v5_import/tests_e2e.rs +++ /dev/null @@ -1,683 +0,0 @@ -//! End-to-end import tests over a copy of the frozen V5 fixtures -//! (`tests/fixtures/v5-import/`), with an injected game probe and placement -//! backend for the failures a real system cannot be driven into on demand. -//! The headless goldens in `tests/v5_import_cli.rs` cover the successful shapes. -//! `ipc_golden_tests.rs` reuses [`v3_game`] and [`import_copying`] for the -//! `import_v5_history` DTO goldens. - -use std::cell::Cell; -use std::io; -use std::path::{Path, PathBuf}; - -use rusqlite::Connection; -use tempfile::TempDir; - -use super::run::{import_blocking_with, ImportReport}; -use super::{v5_import_marker_path, ImportError}; -use crate::services::file_manifest::tree_manifest; -use crate::services::placement::{LinkKind, PlacementBackend, SystemBackend}; - -const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/v5-import"); -const V1_SCHEMA: &str = include_str!("../../tests/fixtures/v5-import/v1.schema.sql"); -const V3_SCHEMA: &str = include_str!("../../tests/fixtures/v5-import/v3.schema.sql"); -const V3_UPGRADED_SCHEMA: &str = - include_str!("../../tests/fixtures/v5-import/v3-upgraded-from-v1.schema.sql"); -const ROWS_COMMON: &str = include_str!("../../tests/fixtures/v5-import/rows-common.sql"); -const BATTLES_V1: &str = include_str!("../../tests/fixtures/v5-import/battles-v1.sql"); -const BATTLES_V2_V3: &str = include_str!("../../tests/fixtures/v5-import/battles-v2-v3.sql"); -const MOD_CONTRACT: &str = include_str!( - "../../../../bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json" -); -/// The fixtures' reference clock, 2026-10-10T00:00:00Z. -const NOW_MS: i64 = 1_791_590_400_000; - -pub(crate) struct FixtureGame { - _dir: TempDir, - pub(crate) game: PathBuf, -} - -impl FixtureGame { - fn v5(&self) -> PathBuf { - self.game.join("BazaarPlusPlusV5") - } - - fn v6(&self) -> PathBuf { - crate::services::paths::bpp_data_dir(&self.game) - } - - fn snapshot(&self) -> Vec<(String, String)> { - tree_manifest(&self.game).unwrap() - } - - fn import(&self) -> Result { - import_blocking_with(&self.game, &stopped, SystemBackend, NOW_MS) - } -} - -fn stopped(_: &Path) -> Result { - Ok(false) -} - -fn copy_tree(source: &Path, target: &Path) { - std::fs::create_dir_all(target).unwrap(); - for entry in std::fs::read_dir(source).unwrap() { - let entry = entry.unwrap(); - let to = target.join(entry.file_name()); - if entry.file_type().unwrap().is_dir() { - copy_tree(&entry.path(), &to); - } else { - std::fs::copy(entry.path(), to).unwrap(); - } - } -} - -fn write(path: &Path, bytes: &[u8]) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, bytes).unwrap(); -} - -/// A game directory with the installed 6.x mod contract and the V5 Data Root -/// sample, its database built from `schema` and the seed rows. -pub(super) fn fixture_game(schema: &str, battles: &str) -> FixtureGame { - let dir = tempfile::tempdir().unwrap(); - let root = dir.path().canonicalize().unwrap(); - let game = root.join("game"); - copy_tree(&Path::new(FIXTURES).join("game"), &game); - copy_tree(&Path::new(FIXTURES).join("outside"), &root.join("outside")); - #[cfg(target_os = "macos")] - std::fs::create_dir_all(game.join("TheBazaar.app")).unwrap(); - #[cfg(target_os = "windows")] - write(&game.join("TheBazaar.exe"), b"exe"); - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - write(&game.join("TheBazaar"), b"exe"); - write( - &game.join("BepInEx/plugins/BazaarPlusPlus.history-database.json"), - MOD_CONTRACT.as_bytes(), - ); - let sql_path = |path: PathBuf| path.to_str().unwrap().replace('\'', "''"); - let substitute = |sql: &str| { - sql.replace("{{V5_ROOT}}", &sql_path(game.join("BazaarPlusPlusV5"))) - .replace("{{OUTSIDE_ROOT}}", &sql_path(root.join("outside"))) - }; - let conn = Connection::open(game.join("BazaarPlusPlusV5/bazaarplusplus.db")).unwrap(); - conn.execute_batch(schema).unwrap(); - conn.execute_batch(&substitute(ROWS_COMMON)).unwrap(); - conn.execute_batch(&substitute(battles)).unwrap(); - drop(conn); - FixtureGame { _dir: dir, game } -} - -pub(crate) fn v3_game() -> FixtureGame { - fixture_game(V3_SCHEMA, BATTLES_V2_V3) -} - -fn strings(conn: &Connection, sql: &str) -> Vec { - let mut statement = conn.prepare(sql).unwrap(); - statement - .query_map([], |row| row.get(0)) - .unwrap() - .collect::>() - .unwrap() -} - -fn count(conn: &Connection, sql: &str) -> i64 { - conn.query_row(sql, [], |row| row.get(0)).unwrap() -} - -/// The V6 database a successful import leaves. -fn v6_conn(fixture: &FixtureGame) -> Connection { - Connection::open(fixture.v6().join("bazaarplusplus.db")).unwrap() -} - -#[test] -fn a_new_current_database_is_the_mods_schema_in_wal_mode_with_history_only_runs() { - for (schema, battles) in [ - (V1_SCHEMA, BATTLES_V1), - (V3_SCHEMA, BATTLES_V2_V3), - (V3_UPGRADED_SCHEMA, BATTLES_V2_V3), - ] { - let fixture = fixture_game(schema, battles); - let v5_before = tree_manifest(&fixture.v5()).unwrap(); - let report = fixture.import().unwrap(); - - let conn = v6_conn(&fixture); - // The file the mod's EnsureInitialized creates, so it accepts this one. - assert_eq!( - crate::history::mod_schema::dump_schema(&conn), - crate::history::mod_schema::mod_schema_sql() - ); - let mode: String = conn - .query_row("pragma journal_mode", [], |row| row.get(0)) - .unwrap(); - assert_eq!(mode, "wal"); - - // Shared seal eligibility: no imported Run is a seal candidate or - // protected from cleanup, and none can be resumed. - assert_eq!( - count( - &conn, - "select count(*) from runs where upload_policy <> 'history_only'" - ), - 0 - ); - let protected = format!( - "select count(*) from runs r where {}", - crate::history::cleanup::PROTECTED_RUN_PREDICATE - ); - assert_eq!(count(&conn, &protected), 0); - assert_eq!( - count(&conn, "select count(*) from runs where status = 'active'"), - 0 - ); - assert_eq!(report.plan.closed_runs, ["run-foxtrot"]); - assert_eq!( - count( - &conn, - "select count(*) from runs where run_id = 'run-foxtrot' \ - and status = 'abandoned' and ended_at_ms = last_seen_at_ms" - ), - 1 - ); - - // No Ghost battle, Bundle outbox row, seal job, or Ghost payload. - assert_eq!( - count( - &conn, - "select count(*) from battles where source <> 'LOCAL'" - ), - 0 - ); - assert_eq!(count(&conn, "select count(*) from bundle_outbox"), 0); - assert_eq!(count(&conn, "select count(*) from bundle_seal_jobs"), 0); - for absent in ["GhostBattlePayloads", "BundleOutbox", "builds.json"] { - assert!(!fixture.v6().join(absent).exists(), "{absent}"); - } - - // Run ids, collision ids included, and hero names are copied verbatim. - assert_eq!( - strings(&conn, "select run_id from runs order by run_id"), - [ - "run-alpha", - "run-bravo", - "run-charlie", - "run-delta", - "run-echo", - "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "run-foxtrot", - "run-golf", - ] - ); - assert_eq!( - strings(&conn, "select hero from runs where run_id = 'run-golf'"), - ["hero8"] - ); - - // An absolute path inside the V5 root becomes relative; one outside - // it is neither copied nor referenced. - assert_eq!( - strings( - &conn, - "select image_relative_path from run_screenshots where screenshot_id = 'shot-charlie'" - ), - ["2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png"] - ); - assert_eq!( - strings( - &conn, - "select video_relative_path from combat_replay_videos where video_id = 'video-charlie-1'" - ), - ["battle-charlie-1.20261003-211000.rec0003.mp4"] - ); - assert_eq!( - count( - &conn, - "select count(*) from run_screenshots where screenshot_id = 'shot-delta'" - ), - 0 - ); - assert_eq!( - report - .plan - .dropped_references - .iter() - .map(|reference| (reference.id.as_str(), reference.reason)) - .collect::>(), - [ - ("video-delta-1", "outside_data_root"), - ("shot-delta", "outside_data_root") - ] - ); - assert!(!fixture.v6().join("Pictures").exists()); - - // V5 is untouched except for the marker. - let mut v5_after = tree_manifest(&fixture.v5()).unwrap(); - v5_after.retain(|(path, _)| path != super::V5_IMPORT_MARKER_FILE_NAME); - assert_eq!(v5_after, v5_before); - assert!(v5_import_marker_path(&fixture.game).is_file()); - } -} - -#[test] -fn the_installed_mods_retention_decides_which_replays_are_copied() { - let fixture = v3_game(); - write( - &fixture - .game - .join("BepInEx/plugins/BazaarPlusPlus.history-database.json"), - br#"{"formatVersion":1,"dataRootDirectoryName":"BazaarPlusPlusV6","historyDatabaseUserVersion":1,"replayPayloadRetainedNewestCount":2,"replayPayloadRetainedAgeDays":30}"#, - ); - let report = fixture.import().unwrap(); - - // Newest two (foxtrot, echo) plus the 30-day window (bravo, alpha); golf is - // older than both. - assert_eq!(report.plan.evicted_replays, ["battle-golf-1"]); - let conn = v6_conn(&fixture); - assert_eq!( - strings( - &conn, - "select battle_id || ':' || local_payload_state || ':' || \ - coalesce(local_payload_maintenance_at_ms, '') from battles order by battle_id" - ), - [ - "battle-alpha-1:ready:", - "battle-bravo-1:ready:", - "battle-charlie-1:evicted:1791072000000", - "battle-delta-1:missing:", - "battle-echo-1:ready:", - "battle-foxtrot-1:ready:", - &format!("battle-golf-1:evicted:{NOW_MS}"), - ] - ); - let replays = fixture.v6().join("CombatReplays"); - assert!(!replays.join("battle-golf-1.payload.mpack.gz").exists()); - assert!(replays.join("battle-alpha-1.payload.mpack.gz").is_file()); -} - -#[test] -fn a_game_started_before_the_commit_rolls_everything_back() { - for existing_v6 in [false, true] { - let fixture = v3_game(); - if existing_v6 { - std::fs::create_dir_all(fixture.v6()).unwrap(); - let conn = v6_conn(&fixture); - crate::history::mod_schema::execute_mod_schema(&conn).unwrap(); - conn.query_row("pragma journal_mode = wal", [], |_| Ok(())) - .unwrap(); - drop(conn); - write(&fixture.v6().join("Screenshots/keep.png"), b"keep"); - } - let before = fixture.snapshot(); - let checks = Cell::new(0); - let probe = |_: &Path| { - checks.set(checks.get() + 1); - Ok(checks.get() > 1) - }; - - let error = import_blocking_with(&fixture.game, &probe, SystemBackend, NOW_MS).unwrap_err(); - - assert!( - matches!( - error, - ImportError::GameRunning { - stage: "before_commit", - .. - } - ), - "{error:?}" - ); - assert_eq!(error.code(), "import_blocked_by_game"); - assert_eq!(checks.get(), 2); - assert_eq!(fixture.snapshot(), before, "existing V6: {existing_v6}"); - assert_eq!(fixture.v6().exists(), existing_v6); - } -} - -#[test] -fn a_game_running_at_the_start_changes_nothing() { - let fixture = v3_game(); - let before = fixture.snapshot(); - let error = import_blocking_with(&fixture.game, &|_: &Path| Ok(true), SystemBackend, NOW_MS) - .unwrap_err(); - assert!(matches!( - error, - ImportError::GameRunning { stage: "start", .. } - )); - let error = import_blocking_with( - &fixture.game, - &|_: &Path| Err("ps failed".to_string()), - SystemBackend, - NOW_MS, - ) - .unwrap_err(); - assert!(matches!( - error, - ImportError::GameRunning { stage: "start", .. } - )); - assert_eq!(fixture.snapshot(), before); -} - -/// Imports `fixture` with `probe`, copying every file so the result does not -/// depend on whether the platform links or clones. -pub(crate) fn import_copying( - fixture: &FixtureGame, - probe: &impl crate::services::game_process::GameProcessProbe, -) -> Result { - import_blocking_with( - &fixture.game, - probe, - CopyOnlyBackend { - available: u64::MAX, - }, - NOW_MS, - ) -} - -/// The real filesystem on a volume that cannot link and has `available` bytes free. -struct CopyOnlyBackend { - available: u64, -} - -impl PlacementBackend for CopyOnlyBackend { - fn volume_id(&self, existing: &Path) -> io::Result { - SystemBackend.volume_id(existing) - } - - fn available_space(&self, _: &Path) -> io::Result { - Ok(self.available) - } - - fn link(&self, _: &Path, _: &Path) -> io::Result { - Err(io::Error::other("links unsupported")) - } - - fn copy(&self, source: &Path, partial: &Path) -> io::Result<()> { - SystemBackend.copy(source, partial) - } -} - -#[test] -fn insufficient_space_fails_before_anything_is_kept() { - let fixture = v3_game(); - let before = fixture.snapshot(); - - let error = import_blocking_with( - &fixture.game, - &stopped, - CopyOnlyBackend { available: 10 }, - NOW_MS, - ) - .unwrap_err(); - - assert_eq!(error.code(), "insufficient_space", "{error}"); - assert_eq!(fixture.snapshot(), before); - - // With room, the same volume copies instead of linking. - import_blocking_with( - &fixture.game, - &stopped, - CopyOnlyBackend { - available: u64::MAX, - }, - NOW_MS, - ) - .unwrap(); -} - -#[test] -fn a_retry_after_an_interrupted_import_completes() { - let reference = v3_game(); - reference.import().unwrap(); - let expected = super::manifest::manifest_json(&reference.game, &reference.import()) - .unwrap() - .replace("already_imported", "_"); - - // An import killed mid-way: the new database file exists but its - // transaction never committed, and some files were already placed. - let fixture = v3_game(); - std::fs::create_dir_all(fixture.v6()).unwrap(); - Connection::open(fixture.v6().join("bazaarplusplus.db")) - .unwrap() - .query_row("pragma journal_mode = wal", [], |_| Ok(())) - .unwrap(); - let placed = "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png"; - copy_tree( - &fixture.v5().join("Screenshots"), - &fixture.v6().join("Screenshots"), - ); - assert!(fixture.v6().join(placed).is_file()); - - fixture.import().unwrap(); - let actual = super::manifest::manifest_json(&fixture.game, &fixture.import()) - .unwrap() - .replace("already_imported", "_"); - assert_eq!(actual, expected); -} - -#[test] -fn an_unclean_wal_without_shm_is_read_and_left_as_it_was() { - let fixture = v3_game(); - let database = fixture.v5().join("bazaarplusplus.db"); - // Write a Run into the WAL of a copy and abandon the connection without a - // checkpoint, as a crashed game would; then keep only the db and -wal. - let staging = tempfile::tempdir().unwrap(); - let staged = staging.path().join("bazaarplusplus.db"); - std::fs::copy(&database, &staged).unwrap(); - let conn = Connection::open(&staged).unwrap(); - conn.query_row("pragma journal_mode = wal", [], |_| Ok(())) - .unwrap(); - conn.execute_batch( - "pragma wal_autocheckpoint = 0; - insert into runs (run_id, started_at_utc, last_seen_at_utc, status, completed, hero, - game_mode, ended_at_utc) - values ('run-in-wal', '2026-10-07T13:00:00.0000000+00:00', - '2026-10-07T13:20:00.0000000+00:00', 'completed', 1, 'Mak', 'Ranked', - '2026-10-07T13:20:00.0000000+00:00');", - ) - .unwrap(); - std::fs::copy(&staged, &database).unwrap(); - std::fs::copy( - staged.with_file_name("bazaarplusplus.db-wal"), - database.with_file_name("bazaarplusplus.db-wal"), - ) - .unwrap(); - drop(conn); - assert!( - std::fs::metadata(database.with_file_name("bazaarplusplus.db-wal")) - .unwrap() - .len() - > 0 - ); - assert!(!database.with_file_name("bazaarplusplus.db-shm").exists()); - let v5_before = tree_manifest(&fixture.v5()).unwrap(); - - let report = fixture.import().unwrap(); - - assert!(report - .plan - .imported_runs - .iter() - .any(|run| run == "run-in-wal")); - let mut v5_after = tree_manifest(&fixture.v5()).unwrap(); - v5_after.retain(|(path, _)| path != super::V5_IMPORT_MARKER_FILE_NAME); - assert_eq!(v5_after, v5_before); -} - -#[test] -fn an_unknown_v5_shape_is_refused_without_changes() { - for (sql, code) in [ - ("pragma user_version = 4;", "v5_schema_unsupported"), - ("pragma user_version = 0;", "v5_schema_unsupported"), - ( - "alter table run_screenshots drop column captured_at_local;", - "v5_schema_missing_column", - ), - ("drop table runs;", "v5_schema_missing_column"), - ] { - let fixture = v3_game(); - let conn = Connection::open(fixture.v5().join("bazaarplusplus.db")).unwrap(); - conn.execute_batch(&format!("pragma foreign_keys = off; {sql}")) - .unwrap(); - drop(conn); - let before = fixture.snapshot(); - - let error = fixture.import().unwrap_err(); - - assert_eq!(error.code(), code, "{sql}: {error}"); - assert_eq!(fixture.snapshot(), before, "{sql}"); - } -} - -#[test] -fn an_unreadable_instant_fails_the_import_without_changes() { - let fixture = v3_game(); - let conn = Connection::open(fixture.v5().join("bazaarplusplus.db")).unwrap(); - conn.execute( - "update battles set recorded_at_utc = 'soon' where battle_id = 'battle-echo-1'", - [], - ) - .unwrap(); - drop(conn); - let before = fixture.snapshot(); - - let error = fixture.import().unwrap_err(); - - assert_eq!(error.code(), "v5_value_invalid"); - assert!(error.to_string().contains("battle-echo-1"), "{error}"); - assert_eq!(fixture.snapshot(), before); -} - -#[test] -fn an_existing_marker_means_nothing_is_done() { - let fixture = v3_game(); - write(&v5_import_marker_path(&fixture.game), b""); - let before = fixture.snapshot(); - - assert!(matches!( - fixture.import().unwrap_err(), - ImportError::AlreadyImported - )); - assert_eq!(fixture.snapshot(), before); - - // A completed import is not repeated. - let fixture = v3_game(); - fixture.import().unwrap(); - let after_first = fixture.snapshot(); - assert!(matches!( - fixture.import().unwrap_err(), - ImportError::AlreadyImported - )); - assert_eq!(fixture.snapshot(), after_first); -} - -#[test] -fn an_ineligible_game_is_refused_without_changes() { - // A 5.x mod is still installed: it would keep writing V5. - let fixture = v3_game(); - write( - &fixture - .game - .join("BepInEx/plugins/BazaarPlusPlus.history-database.json"), - br#"{"formatVersion":1,"historyDatabaseUserVersion":3}"#, - ); - let before = fixture.snapshot(); - let error = fixture.import().unwrap_err(); - assert_eq!(error.code(), "not_eligible"); - assert!(error.to_string().contains("installed_mod_writes_old_root")); - assert_eq!(fixture.snapshot(), before); - - // No V5 Data Root. - let fixture = v3_game(); - std::fs::remove_dir_all(fixture.v5()).unwrap(); - let before = fixture.snapshot(); - let error = fixture.import().unwrap_err(); - assert!(error.to_string().contains("no_v5_data_root"), "{error}"); - assert_eq!(fixture.snapshot(), before); - - // A 6.x mod contract without the replay retention. - let fixture = v3_game(); - write( - &fixture - .game - .join("BepInEx/plugins/BazaarPlusPlus.history-database.json"), - br#"{"formatVersion":1,"dataRootDirectoryName":"BazaarPlusPlusV6","historyDatabaseUserVersion":1}"#, - ); - let before = fixture.snapshot(); - assert_eq!(fixture.import().unwrap_err().code(), "mod_contract_invalid"); - assert_eq!(fixture.snapshot(), before); -} - -#[tokio::test] -async fn history_cleanup_started_during_an_import_waits_for_it() { - use crate::services::data_maintenance::DataMaintenanceLock; - use crate::services::history::{ - execute_storage_cleanup_with, StorageCleanupPreset, StorageCleanupScope, - }; - use std::sync::mpsc; - use std::time::Duration; - - let lock = DataMaintenanceLock::default(); - let fixture = std::sync::Arc::new(v3_game()); - - // The import's first game check parks inside the locked section. - let (entered_tx, entered) = mpsc::channel::<()>(); - let (release_tx, release) = mpsc::channel::<()>(); - let import = tokio::spawn({ - let lock = lock.clone(); - let fixture = fixture.clone(); - async move { - lock.run_blocking(move || { - let release = std::sync::Mutex::new(release); - let probe = |_: &Path| { - if entered_tx.send(()).is_ok() { - release.lock().unwrap().recv().unwrap(); - } - Ok(false) - }; - import_blocking_with(&fixture.game, &probe, SystemBackend, NOW_MS) - .map(|report| report.plan.imported_runs.len()) - .map_err(|error| error.to_string()) - }) - .await - } - }); - tokio::task::spawn_blocking(move || entered.recv_timeout(Duration::from_secs(10))) - .await - .unwrap() - .expect("import reached its game check"); - - // Cleanup resolves its installation only once it holds the lock. - let (resolved_tx, resolved) = mpsc::channel::(); - let cleanup = tokio::spawn({ - let lock = lock.clone(); - let fixture = fixture.clone(); - async move { - let game = fixture.game.clone(); - let database = fixture.v6().join("bazaarplusplus.db"); - execute_storage_cleanup_with( - &lock, - move || { - resolved_tx.send(database.exists()).unwrap(); - Some(game) - }, - StorageCleanupScope::RunData, - StorageCleanupPreset::All, - ) - .await - } - }); - for _ in 0..16 { - tokio::task::yield_now().await; - } - tokio::time::sleep(Duration::from_millis(50)).await; - assert!(!cleanup.is_finished()); - assert!( - resolved.try_recv().is_err(), - "cleanup entered during the import" - ); - - release_tx.send(()).unwrap(); - assert_eq!(import.await.unwrap(), Ok(Ok(8))); - let _ = cleanup.await.unwrap(); - // Cleanup saw the committed import. - assert_eq!(resolved.try_recv(), Ok(true)); -} diff --git a/bazaarplusplus-installer/src-tauri/tauri.conf.json b/bazaarplusplus-installer/src-tauri/tauri.conf.json deleted file mode 100644 index 6dd7bdf..0000000 --- a/bazaarplusplus-installer/src-tauri/tauri.conf.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "$schema": "https://schema.tauri.app/config/2", - "productName": "BazaarPlusPlus", - "version": "6.0.0", - "identifier": "com.bazaarplusplus.bppinstaller", - "build": { - "beforeDevCommand": "npm run dev", - "devUrl": "http://localhost:14207", - "beforeBuildCommand": "npm run build", - "beforeBundleCommand": "node scripts/release/before-bundle-cleanup.mjs && node scripts/release/compile-macos-icon.mjs", - "frontendDist": "../build" - }, - "app": { - "windows": [ - { - "title": "BazaarPlusPlus", - "width": 1020, - "height": 680, - "minWidth": 900, - "minHeight": 600, - "resizable": true, - "maximizable": true, - "fullscreen": false, - "backgroundColor": "#11100f", - "titleBarStyle": "Overlay", - "hiddenTitle": true, - "trafficLightPosition": { "x": 14, "y": 22 } - } - ], - "security": { - "csp": null - } - }, - "bundle": { - "active": true, - "createUpdaterArtifacts": true - }, - "plugins": { - "updater": { - "endpoints": [ - "https://bppinstaller.bazaarplusplus.com/latest/{{target}}-{{arch}}.json", - "https://bppinstaller.bazaarplusplus.com/latest.json" - ], - "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEY1RTAyMzg1RUFEQUNFRUYKUldUdnp0cnFoU1BnOVEzYjFlMFZMcEpmQ014VUZkNWtoRGtybW9pU0UwVjhIUmJmRjdoSmFSTVoK" - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/tauri.macos.conf.json b/bazaarplusplus-installer/src-tauri/tauri.macos.conf.json deleted file mode 100644 index bbd421a..0000000 --- a/bazaarplusplus-installer/src-tauri/tauri.macos.conf.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "https://schema.tauri.app/config/2", - "bundle": { - "targets": ["app", "dmg"], - "icon": ["icons/app-icon.icns"], - "macOS": { - "files": { - "Resources/AppIcon.icon": "icons/source/AppIcon.icon", - "Resources/Assets.car": "icons/macos-generated/Assets.car", - "Resources/AppIcon.icns": "icons/macos-generated/AppIcon.icns" - }, - "infoPlist": "Info.plist" - }, - "resources": { - "resources/BepInExSource/macos/BepInEx.zip": "BepInExSource/BepInEx.zip", - "resources/Trampoline/macos/bpp_launcher": "Trampoline/bpp_launcher" - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/tauri.release.conf.json b/bazaarplusplus-installer/src-tauri/tauri.release.conf.json deleted file mode 100644 index 6d6033a..0000000 --- a/bazaarplusplus-installer/src-tauri/tauri.release.conf.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "$schema": "https://schema.tauri.app/config/2", - "build": { - "beforeBuildCommand": null - } -} diff --git a/bazaarplusplus-installer/src-tauri/tauri.windows.conf.json b/bazaarplusplus-installer/src-tauri/tauri.windows.conf.json deleted file mode 100644 index 4713361..0000000 --- a/bazaarplusplus-installer/src-tauri/tauri.windows.conf.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "$schema": "https://schema.tauri.app/config/2", - "app": { - "windows": [ - { - "title": "BazaarPlusPlus", - "width": 972, - "height": 612, - "minWidth": 900, - "minHeight": 600, - "resizable": true, - "maximizable": true, - "fullscreen": false, - "decorations": false, - "backgroundColor": "#11100f", - "shadow": false, - "visible": false - } - ] - }, - "bundle": { - "targets": ["nsis"], - "icon": ["icons/app-icon.ico"], - "resources": { - "resources/BepInExSource/windows/BepInEx.zip": "BepInExSource/BepInEx.zip" - }, - "windows": { - "nsis": { - "installerIcon": "icons/app-icon.ico" - } - } - } -} diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/README.md b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/README.md deleted file mode 100644 index 2fe774c..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# V5 import fixtures - -Frozen inputs for the one-time V5 import (installer ADR-0008): the V5 local history database in each shape real users have, seed rows, and a minimal `BazaarPlusPlusV5/` Data Root. They are frozen because the mod's V5 schema and migration code is being deleted; after that nothing in the repository can produce these shapes again. Do not regenerate them from a later mod. - -Everything is text. No `.db` file is committed: a test builds each database from its `*.schema.sql` (rusqlite `execute_batch`), then loads the rows. `tests/v5_import_fixtures.rs` asserts each fixture's `user_version` and `PRAGMA table_info` columns and that the seed rows match the Data Root sample. - -## Schemas - -Each `*.schema.sql` uses the mod golden's dump format: `PRAGMA user_version=N;`, then every `sqlite_master` statement ordered by type (table, index, trigger) and name, each ending in `;` and LF. The index expressions contain the literal control and Unicode whitespace characters of `RunLogSchema.HistoryWhitespace`, a lone CR included; edit these files only through the generator. - -| File | `user_version` | Source | -|---|---|---| -| `v1.schema.sql` | 1 | `RunLogSchema.BootstrapSql` at `d16fee6192f4539f7c853cdd10a653fb2d76df8d` (`LocalDatabaseSchemaVersion = 1`), run on an empty database. | -| `v2.schema.sql` | 2 | `RunLogSchema.BootstrapSql` at tag `5.5.0` (`c5c9c919e08b79ce0e9621f10681e679d19e97c4`, `LocalDatabaseSchemaVersion = 2`), run on an empty database. | -| `v3.schema.sql` | 3 | A database created fresh by 5.6.0 and 5.7.0: byte copy of `history-database-v3.schema.sql`, the mod's `RunLoggingPipeline.Tests` golden, at `3c8e50556b97e059ef8f1eb56c552e3b9437603e`. The generator also renders that commit's `BootstrapSql` and checks it reproduces the golden. | -| `v3-upgraded-from-v1.schema.sql` | 3 | `v1.schema.sql`'s database opened by `RunLogSchema.EnsureInitialized` at `3c8e50556b97e059ef8f1eb56c552e3b9437603e`: the shape of every user who started before 5.5.0. | - -`generate-schemas.py` (Python 3 standard library only) regenerates all four from those commits through `git show`, so it does not depend on the working tree; `python3 generate-schemas.py --check` verifies the committed files instead. It renders the C# raw interpolated strings, substituting `RunLogSchema`'s string constants. - -The upgraded fixture was produced by replaying `EnsureInitialized`'s SQL with Python's `sqlite3`, not by running the C#, because no .NET SDK was available when the fixtures were frozen. The replay runs, in order: the `UpgradeToLifecycleColumns` script (`ALTER TABLE ... ADD COLUMN`, its `UPDATE`s, index, triggers, `user_version = 2`), `DropDriftedIndexes` (no index drifted), then `BootstrapSql` (`CREATE ... IF NOT EXISTS`, `DROP INDEX IF EXISTS idx_runs_status_last_seen`, the new indexes, `user_version = 3`). The remaining steps cannot change the shape: `ValidateLifecycleColumns` only reads, and `BundleQueueStore.RecoverLegacyJsonFailures` and `BundleQueueStore.NormalizeSealJobDeadlines` only update rows. - -Both v3 fixtures, and `v2.schema.sql`, have the version 3 column shape `b3458fe8b3a4f5c5` (`ShippedColumnShapes` in the mod's `RunLogSchemaColumnShapeTests`): `ALTER TABLE ADD COLUMN` appends each lifecycle column right after the last v1 column, where a fresh v3 also declares it, so `PRAGMA table_info` lists the same columns in the same order. What differs is the stored table definition. The upgraded `battles` lacks the table-level `local_payload_state` CHECK (its lifecycle triggers still guard inserts and updates), and the upgraded `combat_replay_videos` lacks the `attachment_state` and `file_state` CHECKs, so it accepts values outside those lists. Indexes and triggers are identical. - -## Rows - -`rows-common.sql` holds the tables whose columns are the same in every shape; load it first. Then load `battles-v1.sql` for `v1.schema.sql`, or `battles-v2-v3.sql` for the other three; the two hold the same battles and videos, with and without the lifecycle columns. Before loading, replace `{{V5_ROOT}}` with the absolute path of the sample's `game/BazaarPlusPlusV5` (or a copy of it) and `{{OUTSIDE_ROOT}}` with that of `outside/`, doubling any `'`. The row values are shared across shapes and are not tied to the mod version that would have written each shape. - -The rows cover: - -- `run-alpha` and `run-bravo` share one screenshot file and one replay video file. -- Absolute references: `run-charlie`'s screenshot and video point inside the V5 Data Root, `run-delta`'s outside it (into `outside/`). -- `run-echo` and its collision id `run-echo:bpp:<32 hex>`; `run-echo`'s screenshot path uses Windows separators. -- `run-foxtrot` is unfinished (`completed = 0`, `status = 'active'`). -- `run-golf` has the internal hero id `hero8`. -- Ghost battles that must not be imported: `ghost-local-ready` (payload in `GhostBattlePayloads/`) and `ghost-remote-only` (never downloaded). -- `bundle_outbox`: `bundle-alpha` uploaded, `bundle-bravo` pending with its file in `BundleOutbox/`. Seal jobs: `run-echo` waiting with an ISO `"o"` `input_deadline_at_utc`, the collision run in `terminal_failure` with SQLite `datetime()` text. -- Replay retention, at the reference clock 2026-10-10T00:00:00Z and the 30-day window of `ReplayPayloadRetentionPolicy.RetainedAge`: `battle-golf-1` (2026-08-01) has a payload outside the window; the alpha, bravo, echo, and foxtrot battles have payloads inside it. `battle-charlie-1` is `evicted` and `battle-delta-1` `missing` in the v2/v3 rows. - -## Data Root sample - -`game/BazaarPlusPlusV5/` is a minimal V5 Data Root holding every file the rows name: `Screenshots/`, `CombatReplays/`, `CombatReplayVideos/`, `GhostBattlePayloads/`, `BundleOutbox/`, and the mod's remote caches `builds.json`, `supporter-list.json`, `voice-lines.json`, and `EncounterPreview/preview-plans.json`. `outside/` stands for a location outside the Data Root. File contents are one-line text placeholders, not decodable images, videos, payloads, or Bundles; only the names and presence matter. diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/battles-v1.sql b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/battles-v1.sql deleted file mode 100644 index a12cb7e..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/battles-v1.sql +++ /dev/null @@ -1,86 +0,0 @@ --- Battles, battle snapshots, and replay videos for the user_version 1 shape, which has no --- lifecycle columns. Load after rows-common.sql. --- battles-v2-v3.sql holds the same rows with the lifecycle columns; keep the two in step. --- Reference clock for the 30-day replay retention window: 2026-10-10T00:00:00Z. - -INSERT INTO battles ( - battle_id, remote_battle_id, uploader_account_id, source, run_id, local_player_account_id, - recorded_at_utc, day, hour, encounter_id, combat_kind, player_name, player_account_id, - player_hero, opponent_name, opponent_account_id, opponent_hero, result, - winner_combatant_id, loser_combatant_id, is_final_battle, has_local_payload, bundle_id, - download_url, download_url_expires_at_ms, ghost_replay_state, - ghost_replay_unavailable_reason, deleted_at_utc -) VALUES - -- Local replays inside the retention window (payload files in CombatReplays/). - ('battle-alpha-1', NULL, NULL, 'LOCAL', 'run-alpha', NULL, - '2026-10-01T12:10:00.0000000+00:00', 9, 4, 'encounter-alpha-1', 'PVPCombat', 'Player', - 'account-001', 'Vanessa', 'Rival A', 'account-101', 'Pygmalien', 'Win', - 'player', 'opponent', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL), - ('battle-bravo-1', NULL, NULL, 'LOCAL', 'run-bravo', NULL, - '2026-10-02T13:10:00.0000000+00:00', 8, 2, 'encounter-bravo-1', 'PVPCombat', 'Player', - 'account-001', 'Dooley', 'Rival B', 'account-102', 'Vanessa', 'Loss', - 'opponent', 'player', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL), - ('battle-echo-1', NULL, NULL, 'LOCAL', 'run-echo', NULL, - '2026-10-05T13:10:00.0000000+00:00', 9, 5, 'encounter-echo-1', 'PVPCombat', 'Player', - 'account-001', 'Stelle', 'Rival E', 'account-105', 'Jules', 'Win', - 'player', 'opponent', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL), - ('battle-foxtrot-1', NULL, NULL, 'LOCAL', 'run-foxtrot', NULL, - '2026-10-06T13:05:00.0000000+00:00', 3, 1, 'encounter-foxtrot-1', 'PVPCombat', 'Player', - 'account-001', 'Jules', 'Rival F', 'account-106', 'Mak', 'Win', - 'player', 'opponent', 0, 1, NULL, NULL, NULL, NULL, NULL, NULL), - -- Local replay outside the retention window (its payload file is still on disk). - ('battle-golf-1', NULL, NULL, 'LOCAL', 'run-golf', NULL, - '2026-08-01T13:10:00.0000000+00:00', 11, 2, 'encounter-golf-1', 'PVPCombat', 'Player', - 'account-001', 'hero8', 'Rival G', 'account-107', 'Dooley', 'Win', - 'player', 'opponent', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL), - -- Local battles whose payload is gone. - ('battle-charlie-1', NULL, NULL, 'LOCAL', 'run-charlie', NULL, - '2026-10-03T13:10:00.0000000+00:00', 10, 1, 'encounter-charlie-1', 'PVPCombat', 'Player', - 'account-001', 'Pygmalien', 'Rival C', 'account-103', 'Stelle', 'Win', - 'player', 'opponent', 1, 0, NULL, NULL, NULL, NULL, NULL, NULL), - ('battle-delta-1', NULL, NULL, 'LOCAL', 'run-delta', NULL, - '2026-10-04T13:10:00.0000000+00:00', 7, 3, 'encounter-delta-1', 'PVPCombat', 'Player', - 'account-001', 'Mak', 'Rival D', 'account-104', 'Vanessa', 'Loss', - 'opponent', 'player', 1, 0, NULL, NULL, NULL, NULL, NULL, NULL), - -- Ghost battles, which the import does not bring over: one downloaded (payload in - -- GhostBattlePayloads/), one only listed remotely. - ('ghost-local-ready', 'remote-901', 'account-777', 'GHOST', NULL, 'account-001', - '2026-10-02T09:00:00.0000000+00:00', 12, 0, 'encounter-ghost-1', 'PVPCombat', 'Ghost Owner', - 'account-777', 'Mak', 'Player', 'account-001', 'Vanessa', 'Win', - 'player', 'opponent', 0, 0, 'bundle-remote-901', NULL, NULL, 'local_ready', NULL, NULL), - ('ghost-remote-only', 'remote-902', 'account-778', 'GHOST', NULL, 'account-001', - '2026-10-03T09:00:00.0000000+00:00', 10, 1, 'encounter-ghost-2', 'PVPCombat', - 'Other Owner', 'account-778', 'Jules', 'Player', 'account-001', 'Dooley', 'Loss', - 'opponent', 'player', 0, 0, 'bundle-remote-902', - 'https://example.invalid/ghost/remote-902', 1791763200000, 'remote_available', NULL, NULL); - -INSERT INTO battle_snapshots ( - battle_id, player_hand_json, player_skills_json, opponent_hand_json, opponent_skills_json -) VALUES - ('battle-alpha-1', '[{"template_id":"item-1","tier":"Gold"}]', '[]', - '[{"template_id":"item-2","tier":"Silver"}]', '[]'); - -INSERT INTO combat_replay_videos ( - video_id, battle_id, source, video_relative_path, width, height, fps, codec, crf, preset, - started_at_utc, ended_at_utc, duration_ms, captured_frames, dropped_frames, - file_size_bytes, status, error -) VALUES - ('video-alpha-1', 'battle-alpha-1', 'LocalSaved', - 'battle-alpha-1.20261001-201000.rec0001.mp4', 1920, 1080, 60, 'h264', 23, 'p4', - '2026-10-01T12:10:00.0000000+00:00', '2026-10-01T12:11:30.0000000+00:00', 90000, 5400, 0, - 36, 'COMPLETED', NULL), - -- Same file as video-alpha-1. - ('video-bravo-1', 'battle-bravo-1', 'LocalSaved', - 'battle-alpha-1.20261001-201000.rec0001.mp4', 1920, 1080, 60, 'h264', 23, 'p4', - '2026-10-02T13:10:00.0000000+00:00', '2026-10-02T13:11:30.0000000+00:00', 90000, 5400, 0, - 36, 'COMPLETED', NULL), - ('video-charlie-1', 'battle-charlie-1', 'LocalSaved', - '{{V5_ROOT}}/CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4', - 1920, 1080, 60, 'h264', 23, 'p4', - '2026-10-03T13:10:00.0000000+00:00', '2026-10-03T13:11:30.0000000+00:00', 90000, 5400, 0, - 36, 'COMPLETED', NULL), - ('video-delta-1', 'battle-delta-1', 'LocalSaved', - '{{OUTSIDE_ROOT}}/Videos/battle-delta-1.20261004-211000.rec0004.mp4', - 1920, 1080, 60, 'h264', 23, 'p4', - '2026-10-04T13:10:00.0000000+00:00', '2026-10-04T13:11:30.0000000+00:00', 90000, 5400, 0, - 36, 'COMPLETED', NULL); diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/battles-v2-v3.sql b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/battles-v2-v3.sql deleted file mode 100644 index d6e3398..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/battles-v2-v3.sql +++ /dev/null @@ -1,95 +0,0 @@ --- Battles, battle snapshots, and replay videos for the user_version 2 and 3 shapes (both --- v3 fixtures), which carry the lifecycle columns. Load after rows-common.sql. --- battles-v1.sql holds the same rows without the lifecycle columns; keep the two in step. --- Reference clock for the 30-day replay retention window: 2026-10-10T00:00:00Z. - -INSERT INTO battles ( - battle_id, remote_battle_id, uploader_account_id, source, run_id, local_player_account_id, - recorded_at_utc, day, hour, encounter_id, combat_kind, player_name, player_account_id, - player_hero, opponent_name, opponent_account_id, opponent_hero, result, - winner_combatant_id, loser_combatant_id, is_final_battle, has_local_payload, bundle_id, - download_url, download_url_expires_at_ms, ghost_replay_state, - ghost_replay_unavailable_reason, deleted_at_utc, local_payload_state, - local_payload_maintenance_at_utc -) VALUES - -- Local replays inside the retention window (payload files in CombatReplays/). - ('battle-alpha-1', NULL, NULL, 'LOCAL', 'run-alpha', NULL, - '2026-10-01T12:10:00.0000000+00:00', 9, 4, 'encounter-alpha-1', 'PVPCombat', 'Player', - 'account-001', 'Vanessa', 'Rival A', 'account-101', 'Pygmalien', 'Win', - 'player', 'opponent', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL, 'ready', NULL), - ('battle-bravo-1', NULL, NULL, 'LOCAL', 'run-bravo', NULL, - '2026-10-02T13:10:00.0000000+00:00', 8, 2, 'encounter-bravo-1', 'PVPCombat', 'Player', - 'account-001', 'Dooley', 'Rival B', 'account-102', 'Vanessa', 'Loss', - 'opponent', 'player', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL, 'ready', NULL), - ('battle-echo-1', NULL, NULL, 'LOCAL', 'run-echo', NULL, - '2026-10-05T13:10:00.0000000+00:00', 9, 5, 'encounter-echo-1', 'PVPCombat', 'Player', - 'account-001', 'Stelle', 'Rival E', 'account-105', 'Jules', 'Win', - 'player', 'opponent', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL, 'ready', NULL), - ('battle-foxtrot-1', NULL, NULL, 'LOCAL', 'run-foxtrot', NULL, - '2026-10-06T13:05:00.0000000+00:00', 3, 1, 'encounter-foxtrot-1', 'PVPCombat', 'Player', - 'account-001', 'Jules', 'Rival F', 'account-106', 'Mak', 'Win', - 'player', 'opponent', 0, 1, NULL, NULL, NULL, NULL, NULL, NULL, 'ready', NULL), - -- Local replay outside the retention window (its payload file is still on disk). - ('battle-golf-1', NULL, NULL, 'LOCAL', 'run-golf', NULL, - '2026-08-01T13:10:00.0000000+00:00', 11, 2, 'encounter-golf-1', 'PVPCombat', 'Player', - 'account-001', 'hero8', 'Rival G', 'account-107', 'Dooley', 'Win', - 'player', 'opponent', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL, 'ready', NULL), - -- Local battles whose payload is gone. - ('battle-charlie-1', NULL, NULL, 'LOCAL', 'run-charlie', NULL, - '2026-10-03T13:10:00.0000000+00:00', 10, 1, 'encounter-charlie-1', 'PVPCombat', 'Player', - 'account-001', 'Pygmalien', 'Rival C', 'account-103', 'Stelle', 'Win', - 'player', 'opponent', 1, 0, NULL, NULL, NULL, NULL, NULL, NULL, 'evicted', - '2026-10-04T00:00:00.0000000+00:00'), - ('battle-delta-1', NULL, NULL, 'LOCAL', 'run-delta', NULL, - '2026-10-04T13:10:00.0000000+00:00', 7, 3, 'encounter-delta-1', 'PVPCombat', 'Player', - 'account-001', 'Mak', 'Rival D', 'account-104', 'Vanessa', 'Loss', - 'opponent', 'player', 1, 0, NULL, NULL, NULL, NULL, NULL, NULL, 'missing', NULL), - -- Ghost battles, which the import does not bring over: one downloaded (payload in - -- GhostBattlePayloads/), one only listed remotely. - ('ghost-local-ready', 'remote-901', 'account-777', 'GHOST', NULL, 'account-001', - '2026-10-02T09:00:00.0000000+00:00', 12, 0, 'encounter-ghost-1', 'PVPCombat', 'Ghost Owner', - 'account-777', 'Mak', 'Player', 'account-001', 'Vanessa', 'Win', - 'player', 'opponent', 0, 0, 'bundle-remote-901', NULL, NULL, 'local_ready', NULL, NULL, - NULL, NULL), - ('ghost-remote-only', 'remote-902', 'account-778', 'GHOST', NULL, 'account-001', - '2026-10-03T09:00:00.0000000+00:00', 10, 1, 'encounter-ghost-2', 'PVPCombat', - 'Other Owner', 'account-778', 'Jules', 'Player', 'account-001', 'Dooley', 'Loss', - 'opponent', 'player', 0, 0, 'bundle-remote-902', - 'https://example.invalid/ghost/remote-902', 1791763200000, 'remote_available', NULL, NULL, - NULL, NULL); - -INSERT INTO battle_snapshots ( - battle_id, player_hand_json, player_skills_json, opponent_hand_json, opponent_skills_json -) VALUES - ('battle-alpha-1', '[{"template_id":"item-1","tier":"Gold"}]', '[]', - '[{"template_id":"item-2","tier":"Silver"}]', '[]'); - -INSERT INTO combat_replay_videos ( - video_id, battle_id, source, video_relative_path, width, height, fps, codec, crf, preset, - started_at_utc, ended_at_utc, duration_ms, captured_frames, dropped_frames, - file_size_bytes, status, error, attachment_state, file_state, detached_at_utc, - missing_at_utc, last_reconciled_at_utc -) VALUES - ('video-alpha-1', 'battle-alpha-1', 'LocalSaved', - 'battle-alpha-1.20261001-201000.rec0001.mp4', 1920, 1080, 60, 'h264', 23, 'p4', - '2026-10-01T12:10:00.0000000+00:00', '2026-10-01T12:11:30.0000000+00:00', 90000, 5400, 0, - 36, 'COMPLETED', NULL, 'attached', 'present', NULL, NULL, - '2026-10-01T12:20:00.0000000+00:00'), - -- Same file as video-alpha-1. - ('video-bravo-1', 'battle-bravo-1', 'LocalSaved', - 'battle-alpha-1.20261001-201000.rec0001.mp4', 1920, 1080, 60, 'h264', 23, 'p4', - '2026-10-02T13:10:00.0000000+00:00', '2026-10-02T13:11:30.0000000+00:00', 90000, 5400, 0, - 36, 'COMPLETED', NULL, 'attached', 'present', NULL, NULL, - '2026-10-02T13:20:00.0000000+00:00'), - ('video-charlie-1', 'battle-charlie-1', 'LocalSaved', - '{{V5_ROOT}}/CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4', - 1920, 1080, 60, 'h264', 23, 'p4', - '2026-10-03T13:10:00.0000000+00:00', '2026-10-03T13:11:30.0000000+00:00', 90000, 5400, 0, - 36, 'COMPLETED', NULL, 'attached', 'present', NULL, NULL, - '2026-10-03T13:20:00.0000000+00:00'), - ('video-delta-1', 'battle-delta-1', 'LocalSaved', - '{{OUTSIDE_ROOT}}/Videos/battle-delta-1.20261004-211000.rec0004.mp4', - 1920, 1080, 60, 'h264', 23, 'p4', - '2026-10-04T13:10:00.0000000+00:00', '2026-10-04T13:11:30.0000000+00:00', 90000, 5400, 0, - 36, 'COMPLETED', NULL, 'attached', 'present', NULL, NULL, - '2026-10-04T13:20:00.0000000+00:00'); diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/BundleOutbox/bundle-bravo.bundle b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/BundleOutbox/bundle-bravo.bundle deleted file mode 100644 index 77b8535..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/BundleOutbox/bundle-bravo.bundle +++ /dev/null @@ -1 +0,0 @@ -v5-import fixture placeholder: bundle-bravo.bundle diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4 b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4 deleted file mode 100644 index a8997db..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4 +++ /dev/null @@ -1 +0,0 @@ -v5-import fixture placeholder: battle-alpha-1.20261001-201000.rec0001.mp4 diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4 b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4 deleted file mode 100644 index 5b7800c..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4 +++ /dev/null @@ -1 +0,0 @@ -v5-import fixture placeholder: battle-charlie-1.20261003-211000.rec0003.mp4 diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/EncounterPreview/preview-plans.json b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/EncounterPreview/preview-plans.json deleted file mode 100644 index 9dd0d29..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/EncounterPreview/preview-plans.json +++ /dev/null @@ -1 +0,0 @@ -{"plans":[]} diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png deleted file mode 100644 index 9b4bb03..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png +++ /dev/null @@ -1 +0,0 @@ -v5-import fixture placeholder: 2026-10-01_20-15-04-120_final_run-run-alpha.png diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png deleted file mode 100644 index 50c2003..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png +++ /dev/null @@ -1 +0,0 @@ -v5-import fixture placeholder: 2026-10-03_21-21-00-000_final_run-run-charlie.png diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png deleted file mode 100644 index 3560c09..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png +++ /dev/null @@ -1 +0,0 @@ -v5-import fixture placeholder: 2026-10-05_21-18-00-000_final_run-run-echo.png diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/builds.json b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/builds.json deleted file mode 100644 index 4b8f4a0..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/builds.json +++ /dev/null @@ -1 +0,0 @@ -{"builds":[]} diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/supporter-list.json b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/supporter-list.json deleted file mode 100644 index 54f5e0d..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/supporter-list.json +++ /dev/null @@ -1 +0,0 @@ -{"supporters":[]} diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/voice-lines.json b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/voice-lines.json deleted file mode 100644 index 3829cb8..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/game/BazaarPlusPlusV5/voice-lines.json +++ /dev/null @@ -1 +0,0 @@ -{"lines":[]} diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/generate-schemas.py b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/generate-schemas.py deleted file mode 100644 index 0126070..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/generate-schemas.py +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/env python3 -"""Regenerates the frozen V5 schema fixtures in this directory from pinned commits. - -Run from anywhere inside the repository: `python3 generate-schemas.py`. It reads only -git objects at the pinned commits below, never the working tree, so it keeps working -after the V5 migration code is deleted. `--check` compares instead of writing. - -Every fixture is a dump in the format of the mod's history database golden: -`PRAGMA user_version=N;`, then each `sqlite_master` statement ordered by type -(table, index, trigger) and name, each ending in `;` and LF. -""" - -import pathlib -import re -import sqlite3 -import subprocess -import sys - -SCHEMA_PATH = "bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs" -V3_GOLDEN_PATH = ( - "bazaarplusplus-mod/tests/RunLoggingPipeline.Tests/fixtures/history-database-v3.schema.sql" -) -# The last commit whose RunLogSchema had LocalDatabaseSchemaVersion = 1. -V1_COMMIT = "d16fee6192f4539f7c853cdd10a653fb2d76df8d" -# Tag 5.5.0: LocalDatabaseSchemaVersion = 2. -V2_COMMIT = "c5c9c919e08b79ce0e9621f10681e679d19e97c4" -# master when the fixtures were frozen: LocalDatabaseSchemaVersion = 3, still carrying -# UpgradeToLifecycleColumns and the v3 golden under its current name. -V3_COMMIT = "3c8e50556b97e059ef8f1eb56c552e3b9437603e" - -HERE = pathlib.Path(__file__).resolve().parent - - -def git_show(commit, path): - return subprocess.run( - ["git", "show", f"{commit}:{path}"], - cwd=HERE, - check=True, - capture_output=True, - ).stdout.decode("utf-8") # bytes: text mode would turn the lone CR in HistoryWhitespace into LF - - -def decode_csharp_string(literal): - """Decodes the body of a regular C# string literal (the escapes RunLogSchema uses).""" - simple = {"t": "\t", "n": "\n", "v": "\v", "f": "\f", "r": "\r", "0": "\0", - "'": "'", '"': '"', "\\": "\\"} - out, i = [], 0 - while i < len(literal): - ch = literal[i] - if ch != "\\": - out.append(ch) - i += 1 - continue - code = literal[i + 1] - if code == "u": - out.append(chr(int(literal[i + 2:i + 6], 16))) - i += 6 - elif code in simple: - out.append(simple[code]) - i += 2 - else: - raise ValueError(f"unsupported C# escape \\{code}") - return "".join(out) - - -def string_constants(source): - """Evaluates every `const string X = "..." + Y + "...";` in declaration order.""" - constants = {} - pattern = re.compile(r"const string (\w+)\s*=\s*(.*?);\s*$", re.S | re.M) - for name, expression in pattern.findall(source): - value = [] - for token in re.findall(r'"(?:[^"\\]|\\.)*"|\w+', expression): - if token.startswith('"'): - value.append(decode_csharp_string(token[1:-1])) - else: - value.append(constants[token]) - constants[name] = "".join(value) - for name, number in re.findall(r"const int (\w+)\s*=\s*(\d+);", source): - constants[name] = number - return constants - - -def raw_interpolated(source, start, constants): - """Renders the `$\"\"\"...\"\"\"` raw interpolated string that begins after `start`.""" - begin = source.index('$"""', source.index(start)) + 4 - end = source.index('"""', begin) - body = source[begin:end] - assert body.startswith("\n"), "raw string must start on its own line" - lines = body[1:].split("\n") - closing_indent = lines.pop() - assert closing_indent.strip() == "", "closing quotes must be on their own line" - dedented = [] - for line in lines: - if line.strip(): - assert line.startswith(closing_indent), line - dedented.append(line[len(closing_indent):]) - else: - dedented.append("") - text = "\n".join(dedented) - return re.sub(r"\{(\w+)\}", lambda m: constants[m.group(1)], text) - - -def schema_at(commit): - source = git_show(commit, SCHEMA_PATH) - return source, string_constants(source) - - -def execute(conn, sql): - conn.executescript("BEGIN IMMEDIATE;\n" + sql + "\nCOMMIT;") - - -def user_version(conn): - return conn.execute("PRAGMA user_version;").fetchone()[0] - - -def dump(conn): - rows = conn.execute( - """ - SELECT sql FROM sqlite_master - WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' - ORDER BY CASE type WHEN 'table' THEN 0 WHEN 'index' THEN 1 WHEN 'trigger' THEN 2 ELSE 3 END, - name; - """ - ).fetchall() - text = f"PRAGMA user_version={user_version(conn)};\n" - for (sql,) in rows: - text += sql.replace("\r\n", "\n") + ";\n" - return text - - -def open_db(): - return sqlite3.connect(":memory:", isolation_level=None) - - -def fresh(bootstrap_sql): - conn = open_db() - execute(conn, bootstrap_sql) - return conn - - -def index_definitions(conn): - return dict( - conn.execute( - "SELECT name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL;" - ).fetchall() - ) - - -def upgrade_v1_with_master(conn): - """Replays RunLogSchema.EnsureInitialized at V3_COMMIT on a user_version 1 database. - - UpgradeToLifecycleColumns runs its raw SQL; EnsureInitialized then runs - DropDriftedIndexes and BootstrapSql. ValidateLifecycleColumns only reads, and - RecoverLegacyJsonFailures / NormalizeSealJobDeadlines only UPDATE rows, so none of - them changes the shape this dump records. - """ - source, constants = schema_at(V3_COMMIT) - upgrade_sql = raw_interpolated(source, "private static void UpgradeToLifecycleColumns", constants) - bootstrap_sql = raw_interpolated(source, "public static string BootstrapSql", constants) - - assert user_version(conn) == int(constants["FirstSchemaVersion"]) - execute(conn, upgrade_sql) - assert user_version(conn) == int(constants["LifecycleColumnsSchemaVersion"]) - - expected = index_definitions(fresh(bootstrap_sql)) - drifted = [ - name - for name, stored in index_definitions(conn).items() - if name in expected and expected[name] != stored - ] - execute(conn, "".join(f'DROP INDEX "{name}";\n' for name in drifted) + bootstrap_sql) - assert user_version(conn) == int(constants["LocalDatabaseSchemaVersion"]) - return drifted - - -def build(): - v1_source, v1_constants = schema_at(V1_COMMIT) - assert v1_constants["LocalDatabaseSchemaVersion"] == "1" - v1_bootstrap = raw_interpolated(v1_source, "public static string BootstrapSql", v1_constants) - v1 = fresh(v1_bootstrap) - - v2_source, v2_constants = schema_at(V2_COMMIT) - assert v2_constants["LocalDatabaseSchemaVersion"] == "2" - v2 = fresh(raw_interpolated(v2_source, "public static string BootstrapSql", v2_constants)) - - v3_source, v3_constants = schema_at(V3_COMMIT) - assert v3_constants["LocalDatabaseSchemaVersion"] == "3" - v3 = fresh(raw_interpolated(v3_source, "public static string BootstrapSql", v3_constants)) - v3_dump = dump(v3) - golden = git_show(V3_COMMIT, V3_GOLDEN_PATH) - assert v3_dump == golden, "rendered BootstrapSql does not reproduce the v3 golden" - - upgraded = fresh(v1_bootstrap) - drifted = upgrade_v1_with_master(upgraded) - assert drifted == [], f"unexpected drifted indexes: {drifted}" - - return { - "v1.schema.sql": dump(v1), - "v2.schema.sql": dump(v2), - "v3.schema.sql": golden, - "v3-upgraded-from-v1.schema.sql": dump(upgraded), - } - - -def main(): - check = "--check" in sys.argv[1:] - stale = [] - for name, text in build().items(): - path = HERE / name - if check: - if not path.exists() or path.read_bytes() != text.encode("utf-8"): - stale.append(name) - else: - path.write_bytes(text.encode("utf-8")) - if stale: - sys.exit(f"stale: {', '.join(stale)}") - - -if __name__ == "__main__": - main() diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/outside/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/outside/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png deleted file mode 100644 index d6c5fef..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/outside/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png +++ /dev/null @@ -1 +0,0 @@ -v5-import fixture placeholder: 2026-10-04_21-19-00-000_final_run-run-delta.png diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/outside/Videos/battle-delta-1.20261004-211000.rec0004.mp4 b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/outside/Videos/battle-delta-1.20261004-211000.rec0004.mp4 deleted file mode 100644 index 39f8cd9..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/outside/Videos/battle-delta-1.20261004-211000.rec0004.mp4 +++ /dev/null @@ -1 +0,0 @@ -v5-import fixture placeholder: battle-delta-1.20261004-211000.rec0004.mp4 diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/rows-common.sql b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/rows-common.sql deleted file mode 100644 index e3a8613..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/rows-common.sql +++ /dev/null @@ -1,126 +0,0 @@ --- Seed rows whose columns are the same in every V5 shape (user_version 1, 2, and 3). --- Load after a *.schema.sql and before the battles-*.sql that matches its shape. --- {{V5_ROOT}} and {{OUTSIDE_ROOT}} are replaced with absolute directories before loading; --- see README.md. Reference clock for the replay retention window: 2026-10-10T00:00:00Z. - -INSERT INTO runs ( - run_id, started_at_utc, last_seen_at_utc, status, completed, hero, game_mode, - player_rank, player_rating, day, hour, last_seq, ended_at_utc, final_day, final_hour, - victories, losses, final_player_rank, final_player_rating, final_player_rating_delta, - reason, build_channel, player_account_id, bundle_screenshot_requested, mod_version -) VALUES - -- Shares its end-of-run screenshot file and a replay video file with run-bravo. - -- Its Bundle was uploaded. - ('run-alpha', '2026-10-01T12:00:00.0000000+00:00', '2026-10-01T12:15:04.0000000+00:00', - 'completed', 1, 'Vanessa', 'Ranked', 'Gold 2', 1420, 9, 4, 3, - '2026-10-01T12:15:04.0000000+00:00', 9, 4, 10, 3, 'Gold 1', 1436, 16, - 'run_state_exit', 'Online', 'account-001', 1, '5.6.0'), - -- Points at run-alpha's screenshot and video files. Its Bundle is pending in BundleOutbox/. - ('run-bravo', '2026-10-02T13:00:00.0000000+00:00', '2026-10-02T13:20:00.0000000+00:00', - 'completed', 1, 'Dooley', 'Ranked', 'Gold 1', 1436, 8, 2, 2, - '2026-10-02T13:20:00.0000000+00:00', 8, 2, 7, 3, 'Gold 1', 1430, -6, - 'run_state_exit', 'Online', 'account-001', 1, '5.6.0'), - -- Absolute screenshot and video paths inside the V5 Data Root. - ('run-charlie', '2026-10-03T13:00:00.0000000+00:00', '2026-10-03T13:21:00.0000000+00:00', - 'completed', 1, 'Pygmalien', 'Ranked', 'Gold 1', 1430, 10, 1, 2, - '2026-10-03T13:21:00.0000000+00:00', 10, 1, 10, 2, 'Gold 1', 1452, 22, - 'run_state_exit', 'Online', 'account-001', 1, '5.6.0'), - -- Absolute screenshot and video paths outside the V5 Data Root. - ('run-delta', '2026-10-04T13:00:00.0000000+00:00', '2026-10-04T13:19:00.0000000+00:00', - 'completed', 1, 'Mak', 'Ranked', 'Gold 1', 1452, 7, 3, 2, - '2026-10-04T13:19:00.0000000+00:00', 7, 3, 4, 3, 'Gold 1', 1440, -12, - 'run_state_exit', 'Online', 'account-001', 1, '5.6.0'), - -- run-echo and its collision id (RunLogRunIdentity.CreateCollisionId appends - -- ':bpp:' and 32 hex digits when a game run id is reused). - ('run-echo', '2026-10-05T13:00:00.0000000+00:00', '2026-10-05T13:18:00.0000000+00:00', - 'completed', 1, 'Stelle', 'Ranked', 'Gold 1', 1440, 9, 5, 2, - '2026-10-05T13:18:00.0000000+00:00', 9, 5, 8, 3, 'Gold 1', 1446, 6, - 'run_state_exit', 'Online', 'account-001', 1, '5.7.0'), - ('run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0', '2026-10-05T14:00:00.0000000+00:00', - '2026-10-05T14:16:00.0000000+00:00', 'abandoned', 1, 'Stelle', 'Ranked', 'Gold 1', 1446, - 4, 2, 1, '2026-10-05T14:16:00.0000000+00:00', 4, 2, NULL, NULL, NULL, NULL, NULL, - 'session_mismatch', 'Online', 'account-001', 1, '5.7.0'), - -- Not finished: completed = 0, never ended. - ('run-foxtrot', '2026-10-06T13:00:00.0000000+00:00', '2026-10-06T13:09:00.0000000+00:00', - 'active', 0, 'Jules', 'Ranked', 'Gold 1', 1446, 3, 1, 1, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, 'Online', 'account-001', 0, '5.7.0'), - -- The internal hero id 'hero8' (History shows it as The Dragons); its replay is older than - -- the 30-day V6 replay retention window. - ('run-golf', '2026-08-01T13:00:00.0000000+00:00', '2026-08-01T13:25:00.0000000+00:00', - 'completed', 1, 'hero8', 'Ranked', 'Silver 1', 1210, 11, 2, 3, - '2026-08-01T13:25:00.0000000+00:00', 11, 2, 10, 1, 'Silver 1', 1236, 26, - 'run_state_exit', 'Online', 'account-001', 1, '5.5.0'); - -INSERT INTO run_events (run_id, seq, ts_utc, kind, payload_json) VALUES - ('run-alpha', 1, '2026-10-01T12:00:00.0000000+00:00', 'run_started', - '{"schema_version":3,"run_id":"run-alpha","seq":1,"ts":"2026-10-01T12:00:00.000+00:00","kind":"run_started","day":1,"hour":0,"hero":"Vanessa","game_mode":"Ranked"}'), - ('run-alpha', 2, '2026-10-01T12:10:00.0000000+00:00', 'pvp_combat_recorded', - '{"schema_version":3,"run_id":"run-alpha","seq":2,"ts":"2026-10-01T12:10:00.000+00:00","kind":"pvp_combat_recorded","day":9,"hour":4,"combat_kind":"PVPCombat","battle_id":"battle-alpha-1"}'), - ('run-alpha', 3, '2026-10-01T12:15:04.0000000+00:00', 'run_completed', - '{"schema_version":3,"run_id":"run-alpha","seq":3,"ts":"2026-10-01T12:15:04.000+00:00","kind":"run_completed","victories":10,"losses":3}'), - ('run-foxtrot', 1, '2026-10-06T13:00:00.0000000+00:00', 'run_started', - '{"schema_version":3,"run_id":"run-foxtrot","seq":1,"ts":"2026-10-06T13:00:00.000+00:00","kind":"run_started","day":1,"hour":0,"hero":"Jules","game_mode":"Ranked"}'), - ('run-golf', 1, '2026-08-01T13:00:00.0000000+00:00', 'run_started', - '{"schema_version":3,"run_id":"run-golf","seq":1,"ts":"2026-08-01T13:00:00.000+00:00","kind":"run_started","day":1,"hour":0,"hero":"hero8","game_mode":"Ranked"}'); - -INSERT INTO run_screenshots ( - screenshot_id, run_id, hero_name, battle_id, capture_source, is_primary, - image_relative_path, captured_at_local, captured_at_utc, day, player_rank, player_rating, - player_position, victories_at_capture, build_channel -) VALUES - ('shot-alpha', 'run-alpha', 'Vanessa', NULL, 'end_of_run_auto', 1, - '2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png', - '2026-10-01T20:15:04.1200000+08:00', '2026-10-01T12:15:04.1200000+00:00', - 9, 'Gold 1', 1436, 1, 10, 'Online'), - -- Same file as shot-alpha. - ('shot-bravo', 'run-bravo', 'Dooley', NULL, 'end_of_run_auto', 1, - '2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png', - '2026-10-02T21:20:00.0000000+08:00', '2026-10-02T13:20:00.0000000+00:00', - 8, 'Gold 1', 1430, 2, 7, 'Online'), - ('shot-charlie', 'run-charlie', 'Pygmalien', NULL, 'end_of_run_auto', 1, - '{{V5_ROOT}}/Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png', - '2026-10-03T21:21:00.0000000+08:00', '2026-10-03T13:21:00.0000000+00:00', - 10, 'Gold 1', 1452, 1, 10, 'Online'), - ('shot-delta', 'run-delta', 'Mak', NULL, 'end_of_run_auto', 1, - '{{OUTSIDE_ROOT}}/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png', - '2026-10-04T21:19:00.0000000+08:00', '2026-10-04T13:19:00.0000000+00:00', - 7, 'Gold 1', 1440, 3, 4, 'Online'), - -- A Windows relative path, as Path.Combine writes it there. - ('shot-echo', 'run-echo', 'Stelle', NULL, 'end_of_run_auto', 1, - '2026-10-05\2026-10-05_21-18-00-000_final_run-run-echo.png', - '2026-10-05T21:18:00.0000000+08:00', '2026-10-05T13:18:00.0000000+00:00', - 9, 'Gold 1', 1446, 1, 8, 'Online'); - --- input_deadline_at_utc: run-echo carries the ISO "o" text FailOutboxAndScheduleReseal used to --- write (NormalizeSealJobDeadlines rewrites it on the mod's next open); the collision run carries --- the SQLite datetime() text written today. -INSERT INTO bundle_seal_jobs ( - run_id, state, player_account_id, screenshot_requested, screenshot_state, - input_deadline_at_utc, bundle_id, created_at_ms, attempts, last_attempt_at_utc, - last_error_code, last_error_detail -) VALUES - ('run-echo', 'waiting', 'account-001', 1, 'available', - '2026-10-05T13:20:00.0000000+00:00', NULL, NULL, 1, '2026-10-05T13:19:00.0000000+00:00', - 'bundle_file_invalid', 'outbox file failed validation'), - ('run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0', 'terminal_failure', 'account-001', 1, - 'timed_out', '2026-10-05 14:18:00', NULL, NULL, 3, '2026-10-05T14:20:00.0000000+00:00', - 'bundle_build_failed', 'run has no recorded battles'); - -INSERT INTO bundle_outbox ( - bundle_id, run_id, file_name, content_sha256_hex, content_digest, total_bytes, - has_screenshot, sealed_at_utc, status, attempts, last_attempt_at_utc, next_attempt_at_utc, - failed_at_utc, last_error_code, last_error_detail, server_request_id, server_outcome, - uploaded_at_utc -) VALUES - ('bundle-alpha', 'run-alpha', 'bundle-alpha.bundle', - 'a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1', - 'sha256:a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1', 4096, 1, - '2026-10-01T12:16:00.0000000+00:00', 'uploaded', 1, '2026-10-01T12:16:30.0000000+00:00', - NULL, NULL, NULL, NULL, 'req-alpha', 'accepted', '2026-10-01T12:16:31.0000000+00:00'), - ('bundle-bravo', 'run-bravo', 'bundle-bravo.bundle', - 'b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2', - 'sha256:b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2', 4096, 1, - '2026-10-02T13:21:00.0000000+00:00', 'pending', 2, '2026-10-02T13:30:00.0000000+00:00', - '2026-10-02T14:30:00.0000000+00:00', NULL, 'network_error', 'connection reset', NULL, - NULL, NULL); diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v1.schema.sql b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v1.schema.sql deleted file mode 100644 index c2c2d2d..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v1.schema.sql +++ /dev/null @@ -1,216 +0,0 @@ -PRAGMA user_version=1; -CREATE TABLE battle_snapshots ( - battle_id TEXT PRIMARY KEY, - player_hand_json TEXT NOT NULL, - player_skills_json TEXT NOT NULL, - opponent_hand_json TEXT NOT NULL, - opponent_skills_json TEXT NOT NULL, - FOREIGN KEY (battle_id) REFERENCES battles(battle_id) ON DELETE CASCADE -); -CREATE TABLE battles ( - battle_id TEXT PRIMARY KEY, - remote_battle_id TEXT NULL, - uploader_account_id TEXT NULL, - source TEXT NOT NULL, - run_id TEXT NULL, - local_player_account_id TEXT NULL, - recorded_at_utc TEXT NOT NULL, - day INTEGER NULL, - hour INTEGER NULL, - encounter_id TEXT NULL, - combat_kind TEXT NOT NULL, - player_name TEXT NULL, - player_account_id TEXT NULL, - player_hero TEXT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_level INTEGER NULL, - player_prestige INTEGER NULL, - player_income INTEGER NULL, - player_gold INTEGER NULL, - player_victories INTEGER NULL, - player_hand_item_count INTEGER NULL, - player_skill_count INTEGER NULL, - opponent_name TEXT NULL, - opponent_account_id TEXT NULL, - opponent_hero TEXT NULL, - opponent_rank TEXT NULL, - opponent_rating INTEGER NULL, - opponent_level INTEGER NULL, - opponent_prestige INTEGER NULL, - opponent_victories INTEGER NULL, - opponent_hand_item_count INTEGER NULL, - opponent_skill_count INTEGER NULL, - result TEXT NULL, - winner_combatant_id TEXT NULL, - loser_combatant_id TEXT NULL, - is_final_battle INTEGER NOT NULL DEFAULT 0, - has_local_payload INTEGER NOT NULL DEFAULT 0, - bundle_id TEXT NULL, - download_url TEXT NULL, - download_url_expires_at_ms INTEGER NULL, - ghost_replay_state TEXT NULL, - ghost_replay_unavailable_reason TEXT NULL, - deleted_at_utc TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK ( - (source = 'LOCAL' AND remote_battle_id IS NULL AND uploader_account_id IS NULL) - OR - (source = 'GHOST' AND run_id IS NULL AND remote_battle_id IS NOT NULL AND uploader_account_id IS NOT NULL) - ), - CHECK ( - ghost_replay_state IS NULL OR ghost_replay_state IN ( - 'remote_available', 'local_ready', 'unavailable_payload', 'expired' - ) - ) -); -CREATE TABLE bundle_outbox ( - bundle_id TEXT PRIMARY KEY, - run_id TEXT NOT NULL, - file_name TEXT NOT NULL UNIQUE, - content_sha256_hex TEXT NOT NULL, - content_digest TEXT NOT NULL, - total_bytes INTEGER NOT NULL, - has_screenshot INTEGER NOT NULL, - sealed_at_utc TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_utc TEXT NULL, - next_attempt_at_utc TEXT NULL, - failed_at_utc TEXT NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - server_request_id TEXT NULL, - server_outcome TEXT NULL, - uploaded_at_utc TEXT NULL, - CHECK (status IN ('pending', 'uploaded', 'permanent_failure')) -); -CREATE TABLE bundle_seal_jobs ( - run_id TEXT PRIMARY KEY, - state TEXT NOT NULL DEFAULT 'waiting', - player_account_id TEXT NULL, - screenshot_requested INTEGER NOT NULL, - screenshot_state TEXT NOT NULL DEFAULT 'waiting', - input_deadline_at_utc TEXT NOT NULL, - bundle_id TEXT NULL UNIQUE, - created_at_ms INTEGER NULL, - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_utc TEXT NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK (state IN ('waiting', 'sealing', 'terminal_failure')), - CHECK (screenshot_state IN ('not_requested', 'waiting', 'available', 'unavailable', 'timed_out')) -); -CREATE TABLE combat_replay_videos ( - video_id TEXT PRIMARY KEY, - battle_id TEXT NOT NULL, - source TEXT NOT NULL, - video_relative_path TEXT NOT NULL, - width INTEGER NOT NULL, - height INTEGER NOT NULL, - fps INTEGER NOT NULL, - codec TEXT NOT NULL, - crf INTEGER NULL, - preset TEXT NULL, - started_at_utc TEXT NOT NULL, - ended_at_utc TEXT NULL, - duration_ms INTEGER NULL, - captured_frames INTEGER NOT NULL DEFAULT 0, - dropped_frames INTEGER NOT NULL DEFAULT 0, - file_size_bytes INTEGER NULL, - status TEXT NOT NULL, - error TEXT NULL -); -CREATE TABLE run_events ( - run_id TEXT NOT NULL, - seq INTEGER NOT NULL, - ts_utc TEXT NOT NULL, - kind TEXT NOT NULL, - payload_json TEXT NOT NULL, - PRIMARY KEY (run_id, seq), - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE -); -CREATE TABLE run_screenshots ( - screenshot_id TEXT PRIMARY KEY, - run_id TEXT NULL, - hero_name TEXT NULL, - battle_id TEXT NULL, - capture_source TEXT NOT NULL, - is_primary INTEGER NOT NULL DEFAULT 0, - image_relative_path TEXT NOT NULL, - captured_at_local TEXT NOT NULL, - captured_at_utc TEXT NOT NULL, - day INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_position INTEGER NULL, - victories_at_capture INTEGER NULL, - build_channel TEXT NULL -); -CREATE TABLE runs ( - run_id TEXT PRIMARY KEY, - started_at_utc TEXT NOT NULL, - last_seen_at_utc TEXT NOT NULL, - status TEXT NOT NULL, - completed INTEGER NOT NULL DEFAULT 0, - hero TEXT NOT NULL, - game_mode TEXT NOT NULL, - seed INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - day INTEGER NULL, - hour INTEGER NULL, - max_health INTEGER NULL, - prestige INTEGER NULL, - level INTEGER NULL, - income INTEGER NULL, - gold INTEGER NULL, - last_seq INTEGER NOT NULL DEFAULT 0, - ended_at_utc TEXT NULL, - final_day INTEGER NULL, - final_hour INTEGER NULL, - victories INTEGER NULL, - losses INTEGER NULL, - final_player_rank TEXT NULL, - final_player_rating INTEGER NULL, - final_player_rating_delta INTEGER NULL, - reason TEXT NULL, - build_channel TEXT NULL, - player_account_id TEXT NULL, - bundle_screenshot_requested INTEGER NOT NULL DEFAULT 0, - mod_version TEXT NULL -); -CREATE INDEX idx_battles_ghost_discovery - ON battles(local_player_account_id, source, recorded_at_utc DESC); -CREATE UNIQUE INDEX idx_battles_ghost_identity - ON battles(uploader_account_id, remote_battle_id) - WHERE source = 'GHOST'; -CREATE INDEX idx_battles_local_player_recent - ON battles(local_player_account_id, recorded_at_utc DESC); -CREATE INDEX idx_battles_run_id_recorded - ON battles(run_id, recorded_at_utc DESC); -CREATE INDEX idx_battles_source_recorded - ON battles(source, recorded_at_utc DESC); -CREATE UNIQUE INDEX idx_bundle_outbox_active_run - ON bundle_outbox(run_id) - WHERE status = 'pending'; -CREATE INDEX idx_bundle_outbox_due - ON bundle_outbox(status, next_attempt_at_utc, attempts, sealed_at_utc); -CREATE INDEX idx_bundle_seal_jobs_state - ON bundle_seal_jobs(state, input_deadline_at_utc, run_id); -CREATE INDEX idx_combat_replay_videos_battle - ON combat_replay_videos(battle_id, started_at_utc DESC); -CREATE INDEX idx_run_events_ts_utc - ON run_events(ts_utc); -CREATE UNIQUE INDEX idx_run_screenshots_primary_run - ON run_screenshots(run_id) - WHERE is_primary = 1 AND run_id IS NOT NULL; -CREATE INDEX idx_run_screenshots_run_id_captured_at_utc - ON run_screenshots(run_id, captured_at_utc DESC); -CREATE INDEX idx_run_screenshots_source_captured - ON run_screenshots(capture_source, captured_at_utc ASC, screenshot_id ASC); -CREATE INDEX idx_runs_started_at_utc - ON runs(started_at_utc DESC); -CREATE INDEX idx_runs_status_last_seen - ON runs(status, last_seen_at_utc DESC); diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v2.schema.sql b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v2.schema.sql deleted file mode 100644 index 950f578..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v2.schema.sql +++ /dev/null @@ -1,282 +0,0 @@ -PRAGMA user_version=2; -CREATE TABLE battle_snapshots ( - battle_id TEXT PRIMARY KEY, - player_hand_json TEXT NOT NULL, - player_skills_json TEXT NOT NULL, - opponent_hand_json TEXT NOT NULL, - opponent_skills_json TEXT NOT NULL, - FOREIGN KEY (battle_id) REFERENCES battles(battle_id) ON DELETE CASCADE -); -CREATE TABLE battles ( - battle_id TEXT PRIMARY KEY, - remote_battle_id TEXT NULL, - uploader_account_id TEXT NULL, - source TEXT NOT NULL, - run_id TEXT NULL, - local_player_account_id TEXT NULL, - recorded_at_utc TEXT NOT NULL, - day INTEGER NULL, - hour INTEGER NULL, - encounter_id TEXT NULL, - combat_kind TEXT NOT NULL, - player_name TEXT NULL, - player_account_id TEXT NULL, - player_hero TEXT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_level INTEGER NULL, - player_prestige INTEGER NULL, - player_income INTEGER NULL, - player_gold INTEGER NULL, - player_victories INTEGER NULL, - player_hand_item_count INTEGER NULL, - player_skill_count INTEGER NULL, - opponent_name TEXT NULL, - opponent_account_id TEXT NULL, - opponent_hero TEXT NULL, - opponent_rank TEXT NULL, - opponent_rating INTEGER NULL, - opponent_level INTEGER NULL, - opponent_prestige INTEGER NULL, - opponent_victories INTEGER NULL, - opponent_hand_item_count INTEGER NULL, - opponent_skill_count INTEGER NULL, - result TEXT NULL, - winner_combatant_id TEXT NULL, - loser_combatant_id TEXT NULL, - is_final_battle INTEGER NOT NULL DEFAULT 0, - has_local_payload INTEGER NOT NULL DEFAULT 0, - bundle_id TEXT NULL, - download_url TEXT NULL, - download_url_expires_at_ms INTEGER NULL, - ghost_replay_state TEXT NULL, - ghost_replay_unavailable_reason TEXT NULL, - deleted_at_utc TEXT NULL, - local_payload_state TEXT NULL, - local_payload_maintenance_at_utc TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK ( - (source = 'LOCAL' AND remote_battle_id IS NULL AND uploader_account_id IS NULL) - OR - (source = 'GHOST' AND run_id IS NULL AND remote_battle_id IS NOT NULL AND uploader_account_id IS NOT NULL) - ), - CHECK ( - ghost_replay_state IS NULL OR ghost_replay_state IN ( - 'remote_available', 'local_ready', 'unavailable_payload', 'expired' - ) - ), - CHECK ( - (source = 'LOCAL' AND local_payload_state IS NOT NULL AND ( - (local_payload_state = 'ready' AND has_local_payload = 1) - OR - (local_payload_state IN ('delete_pending', 'evicted', 'missing') - AND has_local_payload = 0) - )) - OR - (source <> 'LOCAL' AND local_payload_state IS NULL) - ) -); -CREATE TABLE bundle_outbox ( - bundle_id TEXT PRIMARY KEY, - run_id TEXT NOT NULL, - file_name TEXT NOT NULL UNIQUE, - content_sha256_hex TEXT NOT NULL, - content_digest TEXT NOT NULL, - total_bytes INTEGER NOT NULL, - has_screenshot INTEGER NOT NULL, - sealed_at_utc TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_utc TEXT NULL, - next_attempt_at_utc TEXT NULL, - failed_at_utc TEXT NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - server_request_id TEXT NULL, - server_outcome TEXT NULL, - uploaded_at_utc TEXT NULL, - CHECK (status IN ('pending', 'uploaded', 'permanent_failure')) -); -CREATE TABLE bundle_seal_jobs ( - run_id TEXT PRIMARY KEY, - state TEXT NOT NULL DEFAULT 'waiting', - player_account_id TEXT NULL, - screenshot_requested INTEGER NOT NULL, - screenshot_state TEXT NOT NULL DEFAULT 'waiting', - input_deadline_at_utc TEXT NOT NULL, - bundle_id TEXT NULL UNIQUE, - created_at_ms INTEGER NULL, - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_utc TEXT NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK (state IN ('waiting', 'sealing', 'terminal_failure')), - CHECK (screenshot_state IN ('not_requested', 'waiting', 'available', 'unavailable', 'timed_out')) -); -CREATE TABLE combat_replay_videos ( - video_id TEXT PRIMARY KEY, - battle_id TEXT NOT NULL, - source TEXT NOT NULL, - video_relative_path TEXT NOT NULL, - width INTEGER NOT NULL, - height INTEGER NOT NULL, - fps INTEGER NOT NULL, - codec TEXT NOT NULL, - crf INTEGER NULL, - preset TEXT NULL, - started_at_utc TEXT NOT NULL, - ended_at_utc TEXT NULL, - duration_ms INTEGER NULL, - captured_frames INTEGER NOT NULL DEFAULT 0, - dropped_frames INTEGER NOT NULL DEFAULT 0, - file_size_bytes INTEGER NULL, - status TEXT NOT NULL, - error TEXT NULL, - attachment_state TEXT NOT NULL DEFAULT 'attached', - file_state TEXT NOT NULL DEFAULT 'pending', - detached_at_utc TEXT NULL, - missing_at_utc TEXT NULL, - last_reconciled_at_utc TEXT NULL, - CHECK (attachment_state IN ('attached', 'detached')), - CHECK (file_state IN ('pending', 'present', 'missing', 'deleted')) -); -CREATE TABLE run_events ( - run_id TEXT NOT NULL, - seq INTEGER NOT NULL, - ts_utc TEXT NOT NULL, - kind TEXT NOT NULL, - payload_json TEXT NOT NULL, - PRIMARY KEY (run_id, seq), - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE -); -CREATE TABLE run_screenshots ( - screenshot_id TEXT PRIMARY KEY, - run_id TEXT NULL, - hero_name TEXT NULL, - battle_id TEXT NULL, - capture_source TEXT NOT NULL, - is_primary INTEGER NOT NULL DEFAULT 0, - image_relative_path TEXT NOT NULL, - captured_at_local TEXT NOT NULL, - captured_at_utc TEXT NOT NULL, - day INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_position INTEGER NULL, - victories_at_capture INTEGER NULL, - build_channel TEXT NULL -); -CREATE TABLE runs ( - run_id TEXT PRIMARY KEY, - started_at_utc TEXT NOT NULL, - last_seen_at_utc TEXT NOT NULL, - status TEXT NOT NULL, - completed INTEGER NOT NULL DEFAULT 0, - hero TEXT NOT NULL, - game_mode TEXT NOT NULL, - seed INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - day INTEGER NULL, - hour INTEGER NULL, - max_health INTEGER NULL, - prestige INTEGER NULL, - level INTEGER NULL, - income INTEGER NULL, - gold INTEGER NULL, - last_seq INTEGER NOT NULL DEFAULT 0, - ended_at_utc TEXT NULL, - final_day INTEGER NULL, - final_hour INTEGER NULL, - victories INTEGER NULL, - losses INTEGER NULL, - final_player_rank TEXT NULL, - final_player_rating INTEGER NULL, - final_player_rating_delta INTEGER NULL, - reason TEXT NULL, - build_channel TEXT NULL, - player_account_id TEXT NULL, - bundle_screenshot_requested INTEGER NOT NULL DEFAULT 0, - mod_version TEXT NULL -); -CREATE INDEX idx_battles_ghost_discovery - ON battles(local_player_account_id, source, recorded_at_utc DESC); -CREATE UNIQUE INDEX idx_battles_ghost_identity - ON battles(uploader_account_id, remote_battle_id) - WHERE source = 'GHOST'; -CREATE INDEX idx_battles_history_ghost ON battles(local_player_account_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL; -CREATE INDEX idx_battles_history_ghost_day ON battles(local_player_account_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL AND day >= 10; -CREATE INDEX idx_battles_history_ghost_day_outcome ON battles(local_player_account_id, CASE lower(trim(winner_combatant_id,' - …             

   ')) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 ELSE CASE lower(trim(result,' - …             

   ')) WHEN 'win' THEN 1 WHEN 'won' THEN 1 WHEN 'loss' THEN -1 WHEN 'lost' THEN -1 ELSE 0 END END, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL AND day >= 10; -CREATE INDEX idx_battles_history_ghost_outcome ON battles(local_player_account_id, CASE lower(trim(winner_combatant_id,' - …             

   ')) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 ELSE CASE lower(trim(result,' - …             

   ')) WHEN 'win' THEN 1 WHEN 'won' THEN 1 WHEN 'loss' THEN -1 WHEN 'lost' THEN -1 ELSE 0 END END, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL; -CREATE INDEX idx_battles_history_local ON battles(run_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'LOCAL'; -CREATE INDEX idx_battles_local_player_recent - ON battles(local_player_account_id, recorded_at_utc DESC); -CREATE INDEX idx_battles_run_id_recorded - ON battles(run_id, recorded_at_utc DESC); -CREATE INDEX idx_battles_source_recorded - ON battles(source, recorded_at_utc DESC); -CREATE UNIQUE INDEX idx_bundle_outbox_active_run - ON bundle_outbox(run_id) - WHERE status = 'pending'; -CREATE INDEX idx_bundle_outbox_due - ON bundle_outbox(status, next_attempt_at_utc, attempts, sealed_at_utc); -CREATE INDEX idx_bundle_seal_jobs_state - ON bundle_seal_jobs(state, input_deadline_at_utc, run_id); -CREATE INDEX idx_combat_replay_videos_attachment - ON combat_replay_videos( - attachment_state, started_at_utc DESC, video_id - ); -CREATE INDEX idx_combat_replay_videos_battle - ON combat_replay_videos(battle_id, started_at_utc DESC); -CREATE INDEX idx_run_events_ts_utc - ON run_events(ts_utc); -CREATE UNIQUE INDEX idx_run_screenshots_primary_run - ON run_screenshots(run_id) - WHERE is_primary = 1 AND run_id IS NOT NULL; -CREATE INDEX idx_run_screenshots_run_id_captured_at_utc - ON run_screenshots(run_id, captured_at_utc DESC); -CREATE INDEX idx_run_screenshots_source_captured - ON run_screenshots(capture_source, captured_at_utc ASC, screenshot_id ASC); -CREATE INDEX idx_runs_completed_last_seen - ON runs(completed, last_seen_at_utc DESC); -CREATE INDEX idx_runs_history_hero ON runs(CASE lower(trim(hero,' - …             

   ')) WHEN 'hero8' THEN 'thedragons' ELSE lower(trim(hero,' - …             

   ')) END, COALESCE(ended_at_utc,last_seen_at_utc,started_at_utc) DESC, run_id DESC); -CREATE INDEX idx_runs_history_recent ON runs(COALESCE(ended_at_utc,last_seen_at_utc,started_at_utc) DESC, run_id DESC); -CREATE INDEX idx_runs_started_at_utc - ON runs(started_at_utc DESC); -CREATE TRIGGER trg_battles_local_payload_insert -BEFORE INSERT ON battles -WHEN NOT ( - (NEW.source = 'LOCAL' AND NEW.local_payload_state IS NOT NULL AND ( - (NEW.local_payload_state = 'ready' AND NEW.has_local_payload = 1) - OR - (NEW.local_payload_state IN ('delete_pending', 'evicted', 'missing') - AND NEW.has_local_payload = 0) - )) - OR - (NEW.source <> 'LOCAL' AND NEW.local_payload_state IS NULL) -) -BEGIN - SELECT RAISE(ABORT, 'invalid local payload lifecycle state'); -END; -CREATE TRIGGER trg_battles_local_payload_update -BEFORE UPDATE OF source, has_local_payload, local_payload_state ON battles -WHEN NOT ( - (NEW.source = 'LOCAL' AND NEW.local_payload_state IS NOT NULL AND ( - (NEW.local_payload_state = 'ready' AND NEW.has_local_payload = 1) - OR - (NEW.local_payload_state IN ('delete_pending', 'evicted', 'missing') - AND NEW.has_local_payload = 0) - )) - OR - (NEW.source <> 'LOCAL' AND NEW.local_payload_state IS NULL) -) -BEGIN - SELECT RAISE(ABORT, 'invalid local payload lifecycle state'); -END; diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v3-upgraded-from-v1.schema.sql b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v3-upgraded-from-v1.schema.sql deleted file mode 100644 index 6c03e2c..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v3-upgraded-from-v1.schema.sql +++ /dev/null @@ -1,265 +0,0 @@ -PRAGMA user_version=3; -CREATE TABLE battle_snapshots ( - battle_id TEXT PRIMARY KEY, - player_hand_json TEXT NOT NULL, - player_skills_json TEXT NOT NULL, - opponent_hand_json TEXT NOT NULL, - opponent_skills_json TEXT NOT NULL, - FOREIGN KEY (battle_id) REFERENCES battles(battle_id) ON DELETE CASCADE -); -CREATE TABLE battles ( - battle_id TEXT PRIMARY KEY, - remote_battle_id TEXT NULL, - uploader_account_id TEXT NULL, - source TEXT NOT NULL, - run_id TEXT NULL, - local_player_account_id TEXT NULL, - recorded_at_utc TEXT NOT NULL, - day INTEGER NULL, - hour INTEGER NULL, - encounter_id TEXT NULL, - combat_kind TEXT NOT NULL, - player_name TEXT NULL, - player_account_id TEXT NULL, - player_hero TEXT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_level INTEGER NULL, - player_prestige INTEGER NULL, - player_income INTEGER NULL, - player_gold INTEGER NULL, - player_victories INTEGER NULL, - player_hand_item_count INTEGER NULL, - player_skill_count INTEGER NULL, - opponent_name TEXT NULL, - opponent_account_id TEXT NULL, - opponent_hero TEXT NULL, - opponent_rank TEXT NULL, - opponent_rating INTEGER NULL, - opponent_level INTEGER NULL, - opponent_prestige INTEGER NULL, - opponent_victories INTEGER NULL, - opponent_hand_item_count INTEGER NULL, - opponent_skill_count INTEGER NULL, - result TEXT NULL, - winner_combatant_id TEXT NULL, - loser_combatant_id TEXT NULL, - is_final_battle INTEGER NOT NULL DEFAULT 0, - has_local_payload INTEGER NOT NULL DEFAULT 0, - bundle_id TEXT NULL, - download_url TEXT NULL, - download_url_expires_at_ms INTEGER NULL, - ghost_replay_state TEXT NULL, - ghost_replay_unavailable_reason TEXT NULL, - deleted_at_utc TEXT NULL, local_payload_state TEXT NULL, local_payload_maintenance_at_utc TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK ( - (source = 'LOCAL' AND remote_battle_id IS NULL AND uploader_account_id IS NULL) - OR - (source = 'GHOST' AND run_id IS NULL AND remote_battle_id IS NOT NULL AND uploader_account_id IS NOT NULL) - ), - CHECK ( - ghost_replay_state IS NULL OR ghost_replay_state IN ( - 'remote_available', 'local_ready', 'unavailable_payload', 'expired' - ) - ) -); -CREATE TABLE bundle_outbox ( - bundle_id TEXT PRIMARY KEY, - run_id TEXT NOT NULL, - file_name TEXT NOT NULL UNIQUE, - content_sha256_hex TEXT NOT NULL, - content_digest TEXT NOT NULL, - total_bytes INTEGER NOT NULL, - has_screenshot INTEGER NOT NULL, - sealed_at_utc TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_utc TEXT NULL, - next_attempt_at_utc TEXT NULL, - failed_at_utc TEXT NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - server_request_id TEXT NULL, - server_outcome TEXT NULL, - uploaded_at_utc TEXT NULL, - CHECK (status IN ('pending', 'uploaded', 'permanent_failure')) -); -CREATE TABLE bundle_seal_jobs ( - run_id TEXT PRIMARY KEY, - state TEXT NOT NULL DEFAULT 'waiting', - player_account_id TEXT NULL, - screenshot_requested INTEGER NOT NULL, - screenshot_state TEXT NOT NULL DEFAULT 'waiting', - input_deadline_at_utc TEXT NOT NULL, - bundle_id TEXT NULL UNIQUE, - created_at_ms INTEGER NULL, - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_utc TEXT NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK (state IN ('waiting', 'sealing', 'terminal_failure')), - CHECK (screenshot_state IN ('not_requested', 'waiting', 'available', 'unavailable', 'timed_out')) -); -CREATE TABLE combat_replay_videos ( - video_id TEXT PRIMARY KEY, - battle_id TEXT NOT NULL, - source TEXT NOT NULL, - video_relative_path TEXT NOT NULL, - width INTEGER NOT NULL, - height INTEGER NOT NULL, - fps INTEGER NOT NULL, - codec TEXT NOT NULL, - crf INTEGER NULL, - preset TEXT NULL, - started_at_utc TEXT NOT NULL, - ended_at_utc TEXT NULL, - duration_ms INTEGER NULL, - captured_frames INTEGER NOT NULL DEFAULT 0, - dropped_frames INTEGER NOT NULL DEFAULT 0, - file_size_bytes INTEGER NULL, - status TEXT NOT NULL, - error TEXT NULL -, attachment_state TEXT NOT NULL DEFAULT 'attached', file_state TEXT NOT NULL DEFAULT 'pending', detached_at_utc TEXT NULL, missing_at_utc TEXT NULL, last_reconciled_at_utc TEXT NULL); -CREATE TABLE run_events ( - run_id TEXT NOT NULL, - seq INTEGER NOT NULL, - ts_utc TEXT NOT NULL, - kind TEXT NOT NULL, - payload_json TEXT NOT NULL, - PRIMARY KEY (run_id, seq), - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE -); -CREATE TABLE run_screenshots ( - screenshot_id TEXT PRIMARY KEY, - run_id TEXT NULL, - hero_name TEXT NULL, - battle_id TEXT NULL, - capture_source TEXT NOT NULL, - is_primary INTEGER NOT NULL DEFAULT 0, - image_relative_path TEXT NOT NULL, - captured_at_local TEXT NOT NULL, - captured_at_utc TEXT NOT NULL, - day INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_position INTEGER NULL, - victories_at_capture INTEGER NULL, - build_channel TEXT NULL -); -CREATE TABLE runs ( - run_id TEXT PRIMARY KEY, - started_at_utc TEXT NOT NULL, - last_seen_at_utc TEXT NOT NULL, - status TEXT NOT NULL, - completed INTEGER NOT NULL DEFAULT 0, - hero TEXT NOT NULL, - game_mode TEXT NOT NULL, - seed INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - day INTEGER NULL, - hour INTEGER NULL, - max_health INTEGER NULL, - prestige INTEGER NULL, - level INTEGER NULL, - income INTEGER NULL, - gold INTEGER NULL, - last_seq INTEGER NOT NULL DEFAULT 0, - ended_at_utc TEXT NULL, - final_day INTEGER NULL, - final_hour INTEGER NULL, - victories INTEGER NULL, - losses INTEGER NULL, - final_player_rank TEXT NULL, - final_player_rating INTEGER NULL, - final_player_rating_delta INTEGER NULL, - reason TEXT NULL, - build_channel TEXT NULL, - player_account_id TEXT NULL, - bundle_screenshot_requested INTEGER NOT NULL DEFAULT 0, - mod_version TEXT NULL -); -CREATE INDEX idx_battles_ghost_discovery - ON battles(local_player_account_id, source, recorded_at_utc DESC); -CREATE UNIQUE INDEX idx_battles_ghost_identity - ON battles(uploader_account_id, remote_battle_id) - WHERE source = 'GHOST'; -CREATE INDEX idx_battles_history_ghost ON battles(local_player_account_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL; -CREATE INDEX idx_battles_history_ghost_day ON battles(local_player_account_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL AND day >= 10; -CREATE INDEX idx_battles_history_ghost_day_outcome ON battles(local_player_account_id, CASE lower(trim(winner_combatant_id,' - …             

   ')) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 ELSE CASE lower(trim(result,' - …             

   ')) WHEN 'win' THEN 1 WHEN 'won' THEN 1 WHEN 'loss' THEN -1 WHEN 'lost' THEN -1 ELSE 0 END END, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL AND day >= 10; -CREATE INDEX idx_battles_history_ghost_outcome ON battles(local_player_account_id, CASE lower(trim(winner_combatant_id,' - …             

   ')) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 ELSE CASE lower(trim(result,' - …             

   ')) WHEN 'win' THEN 1 WHEN 'won' THEN 1 WHEN 'loss' THEN -1 WHEN 'lost' THEN -1 ELSE 0 END END, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL; -CREATE INDEX idx_battles_history_local ON battles(run_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'LOCAL'; -CREATE INDEX idx_battles_local_player_recent - ON battles(local_player_account_id, recorded_at_utc DESC); -CREATE INDEX idx_battles_run_id_recorded - ON battles(run_id, recorded_at_utc DESC); -CREATE INDEX idx_battles_source_recorded - ON battles(source, recorded_at_utc DESC); -CREATE UNIQUE INDEX idx_bundle_outbox_active_run - ON bundle_outbox(run_id) - WHERE status = 'pending'; -CREATE INDEX idx_bundle_outbox_due - ON bundle_outbox(status, next_attempt_at_utc, attempts, sealed_at_utc); -CREATE INDEX idx_bundle_outbox_run - ON bundle_outbox(run_id, status); -CREATE INDEX idx_bundle_seal_jobs_state - ON bundle_seal_jobs(state, input_deadline_at_utc, run_id); -CREATE INDEX idx_combat_replay_videos_attachment - ON combat_replay_videos( - attachment_state, started_at_utc DESC, video_id - ); -CREATE INDEX idx_combat_replay_videos_battle - ON combat_replay_videos(battle_id, started_at_utc DESC); -CREATE INDEX idx_run_events_ts_utc - ON run_events(ts_utc); -CREATE UNIQUE INDEX idx_run_screenshots_primary_run - ON run_screenshots(run_id) - WHERE is_primary = 1 AND run_id IS NOT NULL; -CREATE INDEX idx_run_screenshots_run_id_captured_at_utc - ON run_screenshots(run_id, captured_at_utc DESC); -CREATE INDEX idx_run_screenshots_source_captured - ON run_screenshots(capture_source, captured_at_utc ASC, screenshot_id ASC); -CREATE INDEX idx_runs_completed_last_seen - ON runs(completed, last_seen_at_utc DESC); -CREATE INDEX idx_runs_history_hero ON runs(CASE lower(trim(hero,' - …             

   ')) WHEN 'hero8' THEN 'thedragons' ELSE lower(trim(hero,' - …             

   ')) END, COALESCE(ended_at_utc,last_seen_at_utc,started_at_utc) DESC, run_id DESC); -CREATE INDEX idx_runs_history_recent ON runs(COALESCE(ended_at_utc,last_seen_at_utc,started_at_utc) DESC, run_id DESC); -CREATE INDEX idx_runs_started_at_utc - ON runs(started_at_utc DESC); -CREATE TRIGGER trg_battles_local_payload_insert -BEFORE INSERT ON battles -WHEN NOT ( - (NEW.source = 'LOCAL' AND NEW.local_payload_state IS NOT NULL AND ( - (NEW.local_payload_state = 'ready' AND NEW.has_local_payload = 1) - OR - (NEW.local_payload_state IN ('delete_pending', 'evicted', 'missing') - AND NEW.has_local_payload = 0) - )) - OR - (NEW.source <> 'LOCAL' AND NEW.local_payload_state IS NULL) -) -BEGIN - SELECT RAISE(ABORT, 'invalid local payload lifecycle state'); -END; -CREATE TRIGGER trg_battles_local_payload_update -BEFORE UPDATE OF source, has_local_payload, local_payload_state ON battles -WHEN NOT ( - (NEW.source = 'LOCAL' AND NEW.local_payload_state IS NOT NULL AND ( - (NEW.local_payload_state = 'ready' AND NEW.has_local_payload = 1) - OR - (NEW.local_payload_state IN ('delete_pending', 'evicted', 'missing') - AND NEW.has_local_payload = 0) - )) - OR - (NEW.source <> 'LOCAL' AND NEW.local_payload_state IS NULL) -) -BEGIN - SELECT RAISE(ABORT, 'invalid local payload lifecycle state'); -END; diff --git a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v3.schema.sql b/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v3.schema.sql deleted file mode 100644 index 86b0da2..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/fixtures/v5-import/v3.schema.sql +++ /dev/null @@ -1,284 +0,0 @@ -PRAGMA user_version=3; -CREATE TABLE battle_snapshots ( - battle_id TEXT PRIMARY KEY, - player_hand_json TEXT NOT NULL, - player_skills_json TEXT NOT NULL, - opponent_hand_json TEXT NOT NULL, - opponent_skills_json TEXT NOT NULL, - FOREIGN KEY (battle_id) REFERENCES battles(battle_id) ON DELETE CASCADE -); -CREATE TABLE battles ( - battle_id TEXT PRIMARY KEY, - remote_battle_id TEXT NULL, - uploader_account_id TEXT NULL, - source TEXT NOT NULL, - run_id TEXT NULL, - local_player_account_id TEXT NULL, - recorded_at_utc TEXT NOT NULL, - day INTEGER NULL, - hour INTEGER NULL, - encounter_id TEXT NULL, - combat_kind TEXT NOT NULL, - player_name TEXT NULL, - player_account_id TEXT NULL, - player_hero TEXT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_level INTEGER NULL, - player_prestige INTEGER NULL, - player_income INTEGER NULL, - player_gold INTEGER NULL, - player_victories INTEGER NULL, - player_hand_item_count INTEGER NULL, - player_skill_count INTEGER NULL, - opponent_name TEXT NULL, - opponent_account_id TEXT NULL, - opponent_hero TEXT NULL, - opponent_rank TEXT NULL, - opponent_rating INTEGER NULL, - opponent_level INTEGER NULL, - opponent_prestige INTEGER NULL, - opponent_victories INTEGER NULL, - opponent_hand_item_count INTEGER NULL, - opponent_skill_count INTEGER NULL, - result TEXT NULL, - winner_combatant_id TEXT NULL, - loser_combatant_id TEXT NULL, - is_final_battle INTEGER NOT NULL DEFAULT 0, - has_local_payload INTEGER NOT NULL DEFAULT 0, - bundle_id TEXT NULL, - download_url TEXT NULL, - download_url_expires_at_ms INTEGER NULL, - ghost_replay_state TEXT NULL, - ghost_replay_unavailable_reason TEXT NULL, - deleted_at_utc TEXT NULL, - local_payload_state TEXT NULL, - local_payload_maintenance_at_utc TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK ( - (source = 'LOCAL' AND remote_battle_id IS NULL AND uploader_account_id IS NULL) - OR - (source = 'GHOST' AND run_id IS NULL AND remote_battle_id IS NOT NULL AND uploader_account_id IS NOT NULL) - ), - CHECK ( - ghost_replay_state IS NULL OR ghost_replay_state IN ( - 'remote_available', 'local_ready', 'unavailable_payload', 'expired' - ) - ), - CHECK ( - (source = 'LOCAL' AND local_payload_state IS NOT NULL AND ( - (local_payload_state = 'ready' AND has_local_payload = 1) - OR - (local_payload_state IN ('delete_pending', 'evicted', 'missing') - AND has_local_payload = 0) - )) - OR - (source <> 'LOCAL' AND local_payload_state IS NULL) - ) -); -CREATE TABLE bundle_outbox ( - bundle_id TEXT PRIMARY KEY, - run_id TEXT NOT NULL, - file_name TEXT NOT NULL UNIQUE, - content_sha256_hex TEXT NOT NULL, - content_digest TEXT NOT NULL, - total_bytes INTEGER NOT NULL, - has_screenshot INTEGER NOT NULL, - sealed_at_utc TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_utc TEXT NULL, - next_attempt_at_utc TEXT NULL, - failed_at_utc TEXT NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - server_request_id TEXT NULL, - server_outcome TEXT NULL, - uploaded_at_utc TEXT NULL, - CHECK (status IN ('pending', 'uploaded', 'permanent_failure')) -); -CREATE TABLE bundle_seal_jobs ( - run_id TEXT PRIMARY KEY, - state TEXT NOT NULL DEFAULT 'waiting', - player_account_id TEXT NULL, - screenshot_requested INTEGER NOT NULL, - screenshot_state TEXT NOT NULL DEFAULT 'waiting', - input_deadline_at_utc TEXT NOT NULL, - bundle_id TEXT NULL UNIQUE, - created_at_ms INTEGER NULL, - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_utc TEXT NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK (state IN ('waiting', 'sealing', 'terminal_failure')), - CHECK (screenshot_state IN ('not_requested', 'waiting', 'available', 'unavailable', 'timed_out')) -); -CREATE TABLE combat_replay_videos ( - video_id TEXT PRIMARY KEY, - battle_id TEXT NOT NULL, - source TEXT NOT NULL, - video_relative_path TEXT NOT NULL, - width INTEGER NOT NULL, - height INTEGER NOT NULL, - fps INTEGER NOT NULL, - codec TEXT NOT NULL, - crf INTEGER NULL, - preset TEXT NULL, - started_at_utc TEXT NOT NULL, - ended_at_utc TEXT NULL, - duration_ms INTEGER NULL, - captured_frames INTEGER NOT NULL DEFAULT 0, - dropped_frames INTEGER NOT NULL DEFAULT 0, - file_size_bytes INTEGER NULL, - status TEXT NOT NULL, - error TEXT NULL, - attachment_state TEXT NOT NULL DEFAULT 'attached', - file_state TEXT NOT NULL DEFAULT 'pending', - detached_at_utc TEXT NULL, - missing_at_utc TEXT NULL, - last_reconciled_at_utc TEXT NULL, - CHECK (attachment_state IN ('attached', 'detached')), - CHECK (file_state IN ('pending', 'present', 'missing', 'deleted')) -); -CREATE TABLE run_events ( - run_id TEXT NOT NULL, - seq INTEGER NOT NULL, - ts_utc TEXT NOT NULL, - kind TEXT NOT NULL, - payload_json TEXT NOT NULL, - PRIMARY KEY (run_id, seq), - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE -); -CREATE TABLE run_screenshots ( - screenshot_id TEXT PRIMARY KEY, - run_id TEXT NULL, - hero_name TEXT NULL, - battle_id TEXT NULL, - capture_source TEXT NOT NULL, - is_primary INTEGER NOT NULL DEFAULT 0, - image_relative_path TEXT NOT NULL, - captured_at_local TEXT NOT NULL, - captured_at_utc TEXT NOT NULL, - day INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_position INTEGER NULL, - victories_at_capture INTEGER NULL, - build_channel TEXT NULL -); -CREATE TABLE runs ( - run_id TEXT PRIMARY KEY, - started_at_utc TEXT NOT NULL, - last_seen_at_utc TEXT NOT NULL, - status TEXT NOT NULL, - completed INTEGER NOT NULL DEFAULT 0, - hero TEXT NOT NULL, - game_mode TEXT NOT NULL, - seed INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - day INTEGER NULL, - hour INTEGER NULL, - max_health INTEGER NULL, - prestige INTEGER NULL, - level INTEGER NULL, - income INTEGER NULL, - gold INTEGER NULL, - last_seq INTEGER NOT NULL DEFAULT 0, - ended_at_utc TEXT NULL, - final_day INTEGER NULL, - final_hour INTEGER NULL, - victories INTEGER NULL, - losses INTEGER NULL, - final_player_rank TEXT NULL, - final_player_rating INTEGER NULL, - final_player_rating_delta INTEGER NULL, - reason TEXT NULL, - build_channel TEXT NULL, - player_account_id TEXT NULL, - bundle_screenshot_requested INTEGER NOT NULL DEFAULT 0, - mod_version TEXT NULL -); -CREATE INDEX idx_battles_ghost_discovery - ON battles(local_player_account_id, source, recorded_at_utc DESC); -CREATE UNIQUE INDEX idx_battles_ghost_identity - ON battles(uploader_account_id, remote_battle_id) - WHERE source = 'GHOST'; -CREATE INDEX idx_battles_history_ghost ON battles(local_player_account_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL; -CREATE INDEX idx_battles_history_ghost_day ON battles(local_player_account_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL AND day >= 10; -CREATE INDEX idx_battles_history_ghost_day_outcome ON battles(local_player_account_id, CASE lower(trim(winner_combatant_id,' - …             

   ')) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 ELSE CASE lower(trim(result,' - …             

   ')) WHEN 'win' THEN 1 WHEN 'won' THEN 1 WHEN 'loss' THEN -1 WHEN 'lost' THEN -1 ELSE 0 END END, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL AND day >= 10; -CREATE INDEX idx_battles_history_ghost_outcome ON battles(local_player_account_id, CASE lower(trim(winner_combatant_id,' - …             

   ')) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 ELSE CASE lower(trim(result,' - …             

   ')) WHEN 'win' THEN 1 WHEN 'won' THEN 1 WHEN 'loss' THEN -1 WHEN 'lost' THEN -1 ELSE 0 END END, recorded_at_utc DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_utc IS NULL; -CREATE INDEX idx_battles_history_local ON battles(run_id, recorded_at_utc DESC, battle_id DESC) WHERE source = 'LOCAL'; -CREATE INDEX idx_battles_local_player_recent - ON battles(local_player_account_id, recorded_at_utc DESC); -CREATE INDEX idx_battles_run_id_recorded - ON battles(run_id, recorded_at_utc DESC); -CREATE INDEX idx_battles_source_recorded - ON battles(source, recorded_at_utc DESC); -CREATE UNIQUE INDEX idx_bundle_outbox_active_run - ON bundle_outbox(run_id) - WHERE status = 'pending'; -CREATE INDEX idx_bundle_outbox_due - ON bundle_outbox(status, next_attempt_at_utc, attempts, sealed_at_utc); -CREATE INDEX idx_bundle_outbox_run - ON bundle_outbox(run_id, status); -CREATE INDEX idx_bundle_seal_jobs_state - ON bundle_seal_jobs(state, input_deadline_at_utc, run_id); -CREATE INDEX idx_combat_replay_videos_attachment - ON combat_replay_videos( - attachment_state, started_at_utc DESC, video_id - ); -CREATE INDEX idx_combat_replay_videos_battle - ON combat_replay_videos(battle_id, started_at_utc DESC); -CREATE INDEX idx_run_events_ts_utc - ON run_events(ts_utc); -CREATE UNIQUE INDEX idx_run_screenshots_primary_run - ON run_screenshots(run_id) - WHERE is_primary = 1 AND run_id IS NOT NULL; -CREATE INDEX idx_run_screenshots_run_id_captured_at_utc - ON run_screenshots(run_id, captured_at_utc DESC); -CREATE INDEX idx_run_screenshots_source_captured - ON run_screenshots(capture_source, captured_at_utc ASC, screenshot_id ASC); -CREATE INDEX idx_runs_completed_last_seen - ON runs(completed, last_seen_at_utc DESC); -CREATE INDEX idx_runs_history_hero ON runs(CASE lower(trim(hero,' - …             

   ')) WHEN 'hero8' THEN 'thedragons' ELSE lower(trim(hero,' - …             

   ')) END, COALESCE(ended_at_utc,last_seen_at_utc,started_at_utc) DESC, run_id DESC); -CREATE INDEX idx_runs_history_recent ON runs(COALESCE(ended_at_utc,last_seen_at_utc,started_at_utc) DESC, run_id DESC); -CREATE INDEX idx_runs_started_at_utc - ON runs(started_at_utc DESC); -CREATE TRIGGER trg_battles_local_payload_insert -BEFORE INSERT ON battles -WHEN NOT ( - (NEW.source = 'LOCAL' AND NEW.local_payload_state IS NOT NULL AND ( - (NEW.local_payload_state = 'ready' AND NEW.has_local_payload = 1) - OR - (NEW.local_payload_state IN ('delete_pending', 'evicted', 'missing') - AND NEW.has_local_payload = 0) - )) - OR - (NEW.source <> 'LOCAL' AND NEW.local_payload_state IS NULL) -) -BEGIN - SELECT RAISE(ABORT, 'invalid local payload lifecycle state'); -END; -CREATE TRIGGER trg_battles_local_payload_update -BEFORE UPDATE OF source, has_local_payload, local_payload_state ON battles -WHEN NOT ( - (NEW.source = 'LOCAL' AND NEW.local_payload_state IS NOT NULL AND ( - (NEW.local_payload_state = 'ready' AND NEW.has_local_payload = 1) - OR - (NEW.local_payload_state IN ('delete_pending', 'evicted', 'missing') - AND NEW.has_local_payload = 0) - )) - OR - (NEW.source <> 'LOCAL' AND NEW.local_payload_state IS NULL) -) -BEGIN - SELECT RAISE(ABORT, 'invalid local payload lifecycle state'); -END; diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/acceptance/installed-tree.json b/bazaarplusplus-installer/src-tauri/tests/goldens/acceptance/installed-tree.json deleted file mode 100644 index 1988b28..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/acceptance/installed-tree.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "codesign_verified": true, - "paths": [ - "BepInEx/core/0Harmony.dll", - "BepInEx/core/0Harmony.xml", - "BepInEx/core/0Harmony20.dll", - "BepInEx/core/BepInEx.Harmony.dll", - "BepInEx/core/BepInEx.Harmony.xml", - "BepInEx/core/BepInEx.Preloader.dll", - "BepInEx/core/BepInEx.Preloader.xml", - "BepInEx/core/BepInEx.dll", - "BepInEx/core/BepInEx.xml", - "BepInEx/core/HarmonyXInterop.dll", - "BepInEx/core/Mono.Cecil.Mdb.dll", - "BepInEx/core/Mono.Cecil.Pdb.dll", - "BepInEx/core/Mono.Cecil.Rocks.dll", - "BepInEx/core/Mono.Cecil.dll", - "BepInEx/core/MonoMod.Backports.dll", - "BepInEx/core/MonoMod.Backports.xml", - "BepInEx/core/MonoMod.Core.dll", - "BepInEx/core/MonoMod.Core.xml", - "BepInEx/core/MonoMod.ILHelpers.dll", - "BepInEx/core/MonoMod.Iced.dll", - "BepInEx/core/MonoMod.Iced.xml", - "BepInEx/core/MonoMod.RuntimeDetour.dll", - "BepInEx/core/MonoMod.RuntimeDetour.xml", - "BepInEx/core/MonoMod.Utils.dll", - "BepInEx/core/MonoMod.Utils.xml", - "BepInEx/plugins/.gitkeep", - "BepInEx/plugins/BazaarPlusPlus.Localization.dll", - "BepInEx/plugins/BazaarPlusPlus.ModApi.dll", - "BepInEx/plugins/BazaarPlusPlus.Storage.dll", - "BepInEx/plugins/BazaarPlusPlus.dll", - "BepInEx/plugins/BazaarPlusPlus.history-database.json", - "BepInEx/plugins/BazaarPlusPlus.version", - "BepInEx/plugins/Microsoft.Data.Sqlite.dll", - "BepInEx/plugins/SQLitePCLRaw.batteries_v2.dll", - "BepInEx/plugins/SQLitePCLRaw.core.dll", - "BepInEx/plugins/SQLitePCLRaw.provider.e_sqlite3.dll", - "BepInEx/plugins/SixLabors.ImageSharp.dll", - "BepInEx/plugins/System.Buffers.dll", - "BepInEx/plugins/System.Numerics.Vectors.dll", - "BepInEx/plugins/System.Text.Encoding.CodePages.dll", - "BepInEx/plugins/libBppMacAudio.dylib", - "BepInEx/plugins/libe_sqlite3.dylib", - "TheBazaar.app/Contents/Frameworks/UnityPlayer.dylib", - "TheBazaar.app/Contents/Info.plist", - "TheBazaar.app/Contents/MacOS/The Bazaar", - "TheBazaar.app/Contents/MacOS/The Bazaar.orig", - "TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/Info.plist", - "TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/MacOS/GfxPluginBppReplayVideoToolbox", - "TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle/Contents/_CodeSignature/CodeResources", - "TheBazaar.app/Contents/_CodeSignature/CodeResources", - "libdoorstop.dylib" - ], - "trampoline_uuid_matches_bundled": true -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/acceptance/repaired-tree.json b/bazaarplusplus-installer/src-tauri/tests/goldens/acceptance/repaired-tree.json deleted file mode 100644 index 34f8472..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/acceptance/repaired-tree.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "bpp_paths": [ - "BepInEx/plugins/BazaarPlusPlus.dll", - "TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle", - "libdoorstop.dylib" - ], - "codesign_verified": true, - "trampoline_uuid_matches_bundled": true -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/http/fixtures/run-a.png b/bazaarplusplus-installer/src-tauri/tests/goldens/http/fixtures/run-a.png deleted file mode 100644 index 60dda5a..0000000 Binary files a/bazaarplusplus-installer/src-tauri/tests/goldens/http/fixtures/run-a.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/http/fixtures/run-b.png b/bazaarplusplus-installer/src-tauri/tests/goldens/http/fixtures/run-b.png deleted file mode 100644 index 4aa747d..0000000 Binary files a/bazaarplusplus-installer/src-tauri/tests/goldens/http/fixtures/run-b.png and /dev/null differ diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/http/records-latest.json b/bazaarplusplus-installer/src-tauri/tests/goldens/http/records-latest.json deleted file mode 100644 index acc2363..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/http/records-latest.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "battle_count": 14, - "captured_at": "2026-01-01T17:40:00+08:00", - "captured_at_utc": "2026-01-01T09:40:00Z", - "hero_id": "Vanessa", - "id": "shot-1", - "rank": "Gold", - "rating": 1520, - "strip_url": "/images/shot-1/strip", - "subtitle": "End of run · 10W · 14 battles", - "title": "Vanessa", - "wins": 10 -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/http/records.json b/bazaarplusplus-installer/src-tauri/tests/goldens/http/records.json deleted file mode 100644 index d4954ed..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/http/records.json +++ /dev/null @@ -1,54 +0,0 @@ -[ - { - "battle_count": 14, - "captured_at": "2026-01-01T17:40:00+08:00", - "captured_at_utc": "2026-01-01T09:40:00Z", - "hero_id": "Vanessa", - "id": "shot-1", - "rank": "Gold", - "rating": 1520, - "strip_url": "/images/shot-1/strip", - "subtitle": "End of run · 10W · 14 battles", - "title": "Vanessa", - "wins": 10 - }, - { - "battle_count": null, - "captured_at": "2026-01-01T17:30:00+08:00", - "captured_at_utc": "2026-01-01T09:30:00Z", - "hero_id": "TheDragons", - "id": "shot-2", - "rank": null, - "rating": null, - "strip_url": "/images/shot-2/strip", - "subtitle": "End of run · 7W", - "title": "The Dragons", - "wins": 7 - }, - { - "battle_count": 3, - "captured_at": "2026-01-01T17:20:00+08:00", - "captured_at_utc": "2026-01-01T09:20:00Z", - "hero_id": "Mak", - "id": "shot-3", - "rank": null, - "rating": null, - "strip_url": null, - "subtitle": "End of run · 3 battles", - "title": "Mak", - "wins": null - }, - { - "battle_count": null, - "captured_at": "2026-01-01T17:10:00+08:00", - "captured_at_utc": "2026-01-01T09:10:00Z", - "hero_id": "Unknown", - "id": "shot-4", - "rank": null, - "rating": null, - "strip_url": "/images/shot-4/strip", - "subtitle": "End of run", - "title": "Unknown", - "wins": null - } -] diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/http/strip-hashes.json b/bazaarplusplus-installer/src-tauri/tests/goldens/http/strip-hashes.json deleted file mode 100644 index 2094f6c..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/http/strip-hashes.json +++ /dev/null @@ -1,50 +0,0 @@ -[ - { - "record": "shot-1", - "route": "/images/{record_id}/strip", - "sha256": "6c234a683fa240a22270bf9f6dee30d027852c45e29a618b3847a51e74e9e9e7", - "status": 200 - }, - { - "record": "shot-1", - "route": "/history/{source}/images/{screenshot_id}/strip", - "sha256": "6c234a683fa240a22270bf9f6dee30d027852c45e29a618b3847a51e74e9e9e7", - "status": 200 - }, - { - "record": "shot-2", - "route": "/images/{record_id}/strip", - "sha256": "ccf0da6b90376589f23964a45bdf1dee6504770f05607a01264cbe3f9fb162ea", - "status": 200 - }, - { - "record": "shot-2", - "route": "/history/{source}/images/{screenshot_id}/strip", - "sha256": "ccf0da6b90376589f23964a45bdf1dee6504770f05607a01264cbe3f9fb162ea", - "status": 200 - }, - { - "record": "shot-3", - "route": "/images/{record_id}/strip", - "sha256": null, - "status": 404 - }, - { - "record": "shot-3", - "route": "/history/{source}/images/{screenshot_id}/strip", - "sha256": null, - "status": 404 - }, - { - "record": "shot-4", - "route": "/images/{record_id}/strip", - "sha256": "6c234a683fa240a22270bf9f6dee30d027852c45e29a618b3847a51e74e9e9e7", - "status": 200 - }, - { - "record": "shot-4", - "route": "/history/{source}/images/{screenshot_id}/strip", - "sha256": "6c234a683fa240a22270bf9f6dee30d027852c45e29a618b3847a51e74e9e9e7", - "status": 200 - } -] diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/delete_legacy_root.removed.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/delete_legacy_root.removed.json deleted file mode 100644 index 09137c7..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/delete_legacy_root.removed.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "removed": true, - "state": { - "game_path": "", - "roots": [ - { - "name": "BazaarPlusPlus", - "size_bytes": 12, - "file_count": 1, - "hard_linked_file_count": 0, - "unreadable_entry_count": 0 - }, - { - "name": "BazaarPlusPlusV4", - "size_bytes": 34, - "file_count": 1, - "hard_linked_file_count": 0, - "unreadable_entry_count": 0 - } - ], - "installed_mod_data_root": "current", - "v5_import_eligible": false - } -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_history_run_detail.found.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_history_run_detail.found.json deleted file mode 100644 index f8930fa..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_history_run_detail.found.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "run": { - "run_id": "run-1", - "hero": "Vanessa", - "game_mode": "Ranked", - "started_at_utc": "2026-01-01T09:00:00Z", - "ended_at_utc": "2026-01-01T09:42:00Z", - "status": "completed", - "result": "win", - "victories": 10, - "losses": 2, - "final_day": 12, - "final_player_rank": "Gold", - "final_player_rating": 1520, - "final_player_rating_delta": 16, - "screenshot_id": "shot-1", - "player_name": "Fixture Player" - }, - "battles": [ - { - "battle_id": "battle-2", - "day": 2, - "hour": 4, - "result": "loss", - "opponent_hero": "Dooley", - "opponent_name": null, - "opponent_rank": null, - "opponent_rating": null, - "video": null - }, - { - "battle_id": "battle-1", - "day": 1, - "hour": 2, - "result": "win", - "opponent_hero": "Pygmalien", - "opponent_name": "Opponent A", - "opponent_rank": "Silver", - "opponent_rating": 1400, - "video": { - "video_id": "video-1", - "status": "COMPLETED", - "file_size_bytes": 13, - "duration_ms": 95000 - } - } - ] -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_history_run_detail.not-found.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_history_run_detail.not-found.json deleted file mode 100644 index 19765bd..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_history_run_detail.not-found.json +++ /dev/null @@ -1 +0,0 @@ -null diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.game-missing.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.game-missing.json deleted file mode 100644 index 443bf3a..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.game-missing.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "selected_game_path": null, - "steam_path": null, - "game": { - "path_valid": false - }, - "mod_state": { - "installed": false, - "ready": false - }, - "actions": { - "can_install": false, - "can_reinstall": false, - "can_reset_data": false, - "can_reset_bepinex": false, - "can_uninstall": false, - "can_launch": false - }, - "has_resettable_data": false, - "has_bepinex_files": false, - "warnings": [ - { - "code": "game_missing", - "params": {} - } - ] -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.installable.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.installable.json deleted file mode 100644 index a9527bc..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.installable.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "selected_game_path": "", - "steam_path": "", - "game": { - "path_valid": true - }, - "mod_state": { - "installed": false, - "ready": false - }, - "actions": { - "can_install": true, - "can_reinstall": false, - "can_reset_data": false, - "can_reset_bepinex": false, - "can_uninstall": false, - "can_launch": true - }, - "has_resettable_data": false, - "has_bepinex_files": false, - "warnings": [] -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.installed.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.installed.json deleted file mode 100644 index 1bfc1d6..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.installed.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "selected_game_path": "", - "steam_path": "", - "game": { - "path_valid": true - }, - "mod_state": { - "installed": true, - "ready": true - }, - "actions": { - "can_install": false, - "can_reinstall": true, - "can_reset_data": true, - "can_reset_bepinex": true, - "can_uninstall": true, - "can_launch": true - }, - "has_resettable_data": true, - "has_bepinex_files": true, - "warnings": [] -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.outdated.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.outdated.json deleted file mode 100644 index 1dc4b83..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_install_state.outdated.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "selected_game_path": "", - "steam_path": "", - "game": { - "path_valid": true - }, - "mod_state": { - "installed": true, - "ready": false - }, - "actions": { - "can_install": false, - "can_reinstall": true, - "can_reset_data": true, - "can_reset_bepinex": true, - "can_uninstall": true, - "can_launch": true - }, - "has_resettable_data": true, - "has_bepinex_files": true, - "warnings": [] -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_legacy_data_state.legacy-roots.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_legacy_data_state.legacy-roots.json deleted file mode 100644 index 8b009e4..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_legacy_data_state.legacy-roots.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "game_path": "", - "roots": [ - { - "name": "BazaarPlusPlus", - "size_bytes": 12, - "file_count": 1, - "hard_linked_file_count": 0, - "unreadable_entry_count": 0 - }, - { - "name": "BazaarPlusPlusV4", - "size_bytes": 34, - "file_count": 1, - "hard_linked_file_count": 0, - "unreadable_entry_count": 0 - }, - { - "name": "BazaarPlusPlusV5", - "size_bytes": 63, - "file_count": 2, - "hard_linked_file_count": 0, - "unreadable_entry_count": 0 - } - ], - "installed_mod_data_root": "current", - "v5_import_eligible": true -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_legacy_data_state.none.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_legacy_data_state.none.json deleted file mode 100644 index 575d7a2..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/get_legacy_data_state.none.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "game_path": "", - "roots": [], - "installed_mod_data_root": "reinstall_required", - "v5_import_eligible": false -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/import_v5_history.blocked-by-game.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/import_v5_history.blocked-by-game.json deleted file mode 100644 index 7adaad1..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/import_v5_history.blocked-by-game.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "code": "import_blocked_by_game", - "params": { - "operation": "import_v5_history", - "stage": "start" - }, - "diagnostic": null -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/import_v5_history.imported.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/import_v5_history.imported.json deleted file mode 100644 index 460d2a1..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/import_v5_history.imported.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "imported_run_count": 8, - "skipped_run_count": 0, - "unavailable_file_count": 2, - "state": { - "game_path": "", - "roots": [ - { - "name": "BazaarPlusPlusV5", - "size_bytes": 193524, - "file_count": 18, - "hard_linked_file_count": 0, - "unreadable_entry_count": 0 - } - ], - "installed_mod_data_root": "current", - "v5_import_eligible": false - } -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.empty.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.empty.json deleted file mode 100644 index e19de44..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.empty.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "summary": { - "runs": 0, - "videos": 0, - "win_rate": null - }, - "runs": [] -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.page-1.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.page-1.json deleted file mode 100644 index 05cadc7..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.page-1.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "summary": { - "runs": 3, - "videos": 1, - "win_rate": 0.5 - }, - "runs": [ - { - "run_id": "run-3", - "hero": "Mak", - "game_mode": "Ranked", - "started_at_utc": "2026-01-03T09:00:00Z", - "ended_at_utc": null, - "result": "in_progress", - "victories": 2, - "losses": 1, - "final_day": 3, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "screenshot_id": null, - "thumbnail_url": null - }, - { - "run_id": "run-2", - "hero": "The Dragons", - "game_mode": "Normal", - "started_at_utc": "2026-01-02T09:00:00Z", - "ended_at_utc": "2026-01-02T09:30:00Z", - "result": "loss", - "victories": 4, - "losses": 5, - "final_day": 8, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "screenshot_id": "shot-2", - "thumbnail_url": "http://127.0.0.1:17654/history/0/images/shot-2/strip" - }, - { - "run_id": "run-1", - "hero": "Vanessa", - "game_mode": "Ranked", - "started_at_utc": "2026-01-01T09:00:00Z", - "ended_at_utc": "2026-01-01T09:42:00Z", - "result": "win", - "victories": 10, - "losses": 2, - "final_day": 12, - "final_player_rank": "Gold", - "final_player_rating": 1520, - "final_player_rating_delta": 16, - "screenshot_id": "shot-1", - "thumbnail_url": "http://127.0.0.1:17654/history/0/images/shot-1/strip" - } - ] -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.page-2-of-2.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.page-2-of-2.json deleted file mode 100644 index 953e675..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/list_history_runs.page-2-of-2.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "summary": { - "runs": 3, - "videos": 1, - "win_rate": 0.5 - }, - "runs": [ - { - "run_id": "run-1", - "hero": "Vanessa", - "game_mode": "Ranked", - "started_at_utc": "2026-01-01T09:00:00Z", - "ended_at_utc": "2026-01-01T09:42:00Z", - "result": "win", - "victories": 10, - "losses": 2, - "final_day": 12, - "final_player_rank": "Gold", - "final_player_rating": 1520, - "final_player_rating_delta": 16, - "screenshot_id": "shot-1", - "thumbnail_url": "http://127.0.0.1:17654/history/0/images/shot-1/strip" - } - ] -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/preview_storage_cleanup.run-data-all.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/preview_storage_cleanup.run-data-all.json deleted file mode 100644 index 255e448..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/preview_storage_cleanup.run-data-all.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "scope": "run_data", - "preview": { - "runs": 1, - "battles": 1, - "videos": 0, - "estimated_bytes": 20, - "skipped_pending_uploads": 1 - } -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/preview_storage_cleanup.screenshots-all.json b/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/preview_storage_cleanup.screenshots-all.json deleted file mode 100644 index c8d6549..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/ipc/preview_storage_cleanup.screenshots-all.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "scope": "screenshots", - "preview": { - "screenshots": 2, - "orphan_files": 0, - "estimated_bytes": 40, - "skipped_pending_uploads": 0 - } -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/refused-unknown-user-version.json b/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/refused-unknown-user-version.json deleted file mode 100644 index 0cfa09f..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/refused-unknown-user-version.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "dataRootFiles": null, - "database": null, - "error": { - "code": "v5_schema_unsupported", - "message": "unsupported V5 database user_version 7" - }, - "marker": false, - "status": "failed" -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v1.json b/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v1.json deleted file mode 100644 index 59ad85a..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v1.json +++ /dev/null @@ -1,872 +0,0 @@ -{ - "dataRootFiles": [ - { - "path": "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "sha256": "9ce75744ad250f08dcaa7c9cc8f89c3210709e587aa31d9b6acc1003a6fd3552" - }, - { - "path": "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "sha256": "ca9e18831161cfd7d6a58970980a5cf5cf740cccd98ece50797c8be30e944cc0" - }, - { - "path": "CombatReplays/battle-alpha-1.payload.mpack.gz", - "sha256": "9af0a0ffa4d8e2bd932979ed17a500009cf90bcb3efabe571af07f5a778406fb" - }, - { - "path": "CombatReplays/battle-bravo-1.payload.mpack.gz", - "sha256": "a2b0b763f07ec867caaa2973d582d8b5268ffcc06b832d78401defe5612e0beb" - }, - { - "path": "CombatReplays/battle-echo-1.payload.mpack.gz", - "sha256": "badb7840e3e9a758c2d27c0eb10d1876fd3737aef08d4ac82eab377fabae7d2d" - }, - { - "path": "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "sha256": "a2e4fda50cddf0e14cbc2c4a53f163aec6c80be6243ad050d571af5bd486a493" - }, - { - "path": "CombatReplays/battle-golf-1.payload.mpack.gz", - "sha256": "02a5d1b251f2458b1cf5083abd178195cf56e016e7f07fd8306f7866b808f191" - }, - { - "path": "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "sha256": "331ee0745a32a77b7297e347edfefad13f71f8b6c17ccfbcb5d780dbc3f700f6" - }, - { - "path": "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "sha256": "df526d0d60ff5a7ccdef7eedaf7274cde6c52c2742fb12c35efde5d7a710dae4" - }, - { - "path": "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "sha256": "1f7c152066590d335196d0792597cdaad49c5b2f60d82ca25fe0c6dbe5f4befc" - } - ], - "database": { - "journalMode": "wal", - "tables": { - "battle_snapshots": [ - { - "battle_id": "battle-alpha-1", - "opponent_hand_json": "[{\"template_id\":\"item-2\",\"tier\":\"Silver\"}]", - "opponent_skills_json": "[]", - "player_hand_json": "[{\"template_id\":\"item-1\",\"tier\":\"Gold\"}]", - "player_skills_json": "[]" - } - ], - "battles": [ - { - "battle_id": "battle-alpha-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-alpha-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 4, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-101", - "opponent_hand_item_count": null, - "opponent_hero": "Pygmalien", - "opponent_level": null, - "opponent_name": "Rival A", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Vanessa", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790856600000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-alpha", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-bravo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 8, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-bravo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-102", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival B", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Dooley", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790946600000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-bravo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-charlie-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 10, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-charlie-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "missing", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-103", - "opponent_hand_item_count": null, - "opponent_hero": "Stelle", - "opponent_level": null, - "opponent_name": "Rival C", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Pygmalien", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791033000000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-charlie", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-delta-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 7, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-delta-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 3, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "missing", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-104", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival D", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Mak", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791119400000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-delta", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-echo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-echo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 5, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-105", - "opponent_hand_item_count": null, - "opponent_hero": "Jules", - "opponent_level": null, - "opponent_name": "Rival E", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Stelle", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791205800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-echo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-foxtrot-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 3, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-foxtrot-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 0, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-106", - "opponent_hand_item_count": null, - "opponent_hero": "Mak", - "opponent_level": null, - "opponent_name": "Rival F", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Jules", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791291900000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-foxtrot", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-golf-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 11, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-golf-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-107", - "opponent_hand_item_count": null, - "opponent_hero": "Dooley", - "opponent_level": null, - "opponent_name": "Rival G", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "hero8", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1785589800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-golf", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - } - ], - "bundle_outbox": [], - "bundle_seal_jobs": [], - "combat_replay_videos": [ - { - "attachment_state": "attached", - "battle_id": "battle-alpha-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790856690000, - "error": null, - "file_size_bytes": 36, - "file_state": "pending", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": null, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790856600000, - "status": "COMPLETED", - "video_id": "video-alpha-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-bravo-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790946690000, - "error": null, - "file_size_bytes": 36, - "file_state": "pending", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": null, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790946600000, - "status": "COMPLETED", - "video_id": "video-bravo-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-charlie-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1791033090000, - "error": null, - "file_size_bytes": 36, - "file_state": "pending", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": null, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1791033000000, - "status": "COMPLETED", - "video_id": "video-charlie-1", - "video_relative_path": "battle-charlie-1.20261003-211000.rec0003.mp4", - "width": 1920 - } - ], - "run_events": [ - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":1,\"ts\":\"2026-10-01T12:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Vanessa\",\"game_mode\":\"Ranked\"}", - "run_id": "run-alpha", - "seq": 1, - "ts_at_ms": 1790856000000 - }, - { - "kind": "pvp_combat_recorded", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":2,\"ts\":\"2026-10-01T12:10:00.000+00:00\",\"kind\":\"pvp_combat_recorded\",\"day\":9,\"hour\":4,\"combat_kind\":\"PVPCombat\",\"battle_id\":\"battle-alpha-1\"}", - "run_id": "run-alpha", - "seq": 2, - "ts_at_ms": 1790856600000 - }, - { - "kind": "run_completed", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":3,\"ts\":\"2026-10-01T12:15:04.000+00:00\",\"kind\":\"run_completed\",\"victories\":10,\"losses\":3}", - "run_id": "run-alpha", - "seq": 3, - "ts_at_ms": 1790856904000 - }, - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-foxtrot\",\"seq\":1,\"ts\":\"2026-10-06T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Jules\",\"game_mode\":\"Ranked\"}", - "run_id": "run-foxtrot", - "seq": 1, - "ts_at_ms": 1791291600000 - }, - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-golf\",\"seq\":1,\"ts\":\"2026-08-01T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"hero8\",\"game_mode\":\"Ranked\"}", - "run_id": "run-golf", - "seq": 1, - "ts_at_ms": 1785589200000 - } - ], - "run_screenshots": [ - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790856904120, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Vanessa", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1436, - "run_id": "run-alpha", - "screenshot_id": "shot-alpha", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790947200000, - "captured_utc_offset_minutes": 480, - "day": 8, - "hero_name": "Dooley", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 2, - "player_rank": "Gold 1", - "player_rating": 1430, - "run_id": "run-bravo", - "screenshot_id": "shot-bravo", - "victories_at_capture": 7 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791033660000, - "captured_utc_offset_minutes": 480, - "day": 10, - "hero_name": "Pygmalien", - "image_relative_path": "2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1452, - "run_id": "run-charlie", - "screenshot_id": "shot-charlie", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791206280000, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Stelle", - "image_relative_path": "2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1446, - "run_id": "run-echo", - "screenshot_id": "shot-echo", - "victories_at_capture": 8 - } - ], - "runs": [ - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1790856904000, - "final_day": 9, - "final_hour": 4, - "final_player_rank": "Gold 1", - "final_player_rating": 1436, - "final_player_rating_delta": 16, - "game_mode": "Ranked", - "gold": null, - "hero": "Vanessa", - "hour": 4, - "income": null, - "last_seen_at_ms": 1790856904000, - "last_seq": 3, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 2", - "player_rating": 1420, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-alpha", - "started_at_ms": 1790856000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 8, - "ended_at_ms": 1790947200000, - "final_day": 8, - "final_hour": 2, - "final_player_rank": "Gold 1", - "final_player_rating": 1430, - "final_player_rating_delta": -6, - "game_mode": "Ranked", - "gold": null, - "hero": "Dooley", - "hour": 2, - "income": null, - "last_seen_at_ms": 1790947200000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1436, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-bravo", - "started_at_ms": 1790946000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 7 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 10, - "ended_at_ms": 1791033660000, - "final_day": 10, - "final_hour": 1, - "final_player_rank": "Gold 1", - "final_player_rating": 1452, - "final_player_rating_delta": 22, - "game_mode": "Ranked", - "gold": null, - "hero": "Pygmalien", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791033660000, - "last_seq": 2, - "level": null, - "losses": 2, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1430, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-charlie", - "started_at_ms": 1791032400000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 7, - "ended_at_ms": 1791119940000, - "final_day": 7, - "final_hour": 3, - "final_player_rank": "Gold 1", - "final_player_rating": 1440, - "final_player_rating_delta": -12, - "game_mode": "Ranked", - "gold": null, - "hero": "Mak", - "hour": 3, - "income": null, - "last_seen_at_ms": 1791119940000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1452, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-delta", - "started_at_ms": 1791118800000, - "status": "completed", - "upload_policy": "history_only", - "victories": 4 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1791206280000, - "final_day": 9, - "final_hour": 5, - "final_player_rank": "Gold 1", - "final_player_rating": 1446, - "final_player_rating_delta": 6, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 5, - "income": null, - "last_seen_at_ms": 1791206280000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1440, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-echo", - "started_at_ms": 1791205200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 8 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 4, - "ended_at_ms": 1791209760000, - "final_day": 4, - "final_hour": 2, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 2, - "income": null, - "last_seen_at_ms": 1791209760000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": "session_mismatch", - "run_id": "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "started_at_ms": 1791208800000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 0, - "day": 3, - "ended_at_ms": 1791292140000, - "final_day": null, - "final_hour": null, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Jules", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791292140000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": null, - "run_id": "run-foxtrot", - "started_at_ms": 1791291600000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 11, - "ended_at_ms": 1785590700000, - "final_day": 11, - "final_hour": 2, - "final_player_rank": "Silver 1", - "final_player_rating": 1236, - "final_player_rating_delta": 26, - "game_mode": "Ranked", - "gold": null, - "hero": "hero8", - "hour": 2, - "income": null, - "last_seen_at_ms": 1785590700000, - "last_seq": 3, - "level": null, - "losses": 1, - "max_health": null, - "mod_version": "5.5.0", - "player_account_id": "account-001", - "player_rank": "Silver 1", - "player_rating": 1210, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-golf", - "started_at_ms": 1785589200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - } - ] - }, - "userVersion": 1 - }, - "marker": true, - "report": { - "closedRuns": [ - "run-foxtrot" - ], - "droppedReferences": [ - { - "id": "video-delta-1", - "path": "{{OUTSIDE_ROOT}}/Videos/battle-delta-1.20261004-211000.rec0004.mp4", - "reason": "outside_data_root", - "table": "combat_replay_videos" - }, - { - "id": "shot-delta", - "path": "{{OUTSIDE_ROOT}}/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png", - "reason": "outside_data_root", - "table": "run_screenshots" - } - ], - "evictedReplays": [], - "files": [ - "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "CombatReplays/battle-alpha-1.payload.mpack.gz", - "CombatReplays/battle-bravo-1.payload.mpack.gz", - "CombatReplays/battle-echo-1.payload.mpack.gz", - "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "CombatReplays/battle-golf-1.payload.mpack.gz", - "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png" - ], - "importedRuns": [ - "run-alpha", - "run-bravo", - "run-charlie", - "run-delta", - "run-echo", - "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "run-foxtrot", - "run-golf" - ], - "missingFiles": [], - "skippedRuns": [] - }, - "status": "imported" -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v2.json b/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v2.json deleted file mode 100644 index a095d31..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v2.json +++ /dev/null @@ -1,872 +0,0 @@ -{ - "dataRootFiles": [ - { - "path": "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "sha256": "9ce75744ad250f08dcaa7c9cc8f89c3210709e587aa31d9b6acc1003a6fd3552" - }, - { - "path": "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "sha256": "ca9e18831161cfd7d6a58970980a5cf5cf740cccd98ece50797c8be30e944cc0" - }, - { - "path": "CombatReplays/battle-alpha-1.payload.mpack.gz", - "sha256": "9af0a0ffa4d8e2bd932979ed17a500009cf90bcb3efabe571af07f5a778406fb" - }, - { - "path": "CombatReplays/battle-bravo-1.payload.mpack.gz", - "sha256": "a2b0b763f07ec867caaa2973d582d8b5268ffcc06b832d78401defe5612e0beb" - }, - { - "path": "CombatReplays/battle-echo-1.payload.mpack.gz", - "sha256": "badb7840e3e9a758c2d27c0eb10d1876fd3737aef08d4ac82eab377fabae7d2d" - }, - { - "path": "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "sha256": "a2e4fda50cddf0e14cbc2c4a53f163aec6c80be6243ad050d571af5bd486a493" - }, - { - "path": "CombatReplays/battle-golf-1.payload.mpack.gz", - "sha256": "02a5d1b251f2458b1cf5083abd178195cf56e016e7f07fd8306f7866b808f191" - }, - { - "path": "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "sha256": "331ee0745a32a77b7297e347edfefad13f71f8b6c17ccfbcb5d780dbc3f700f6" - }, - { - "path": "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "sha256": "df526d0d60ff5a7ccdef7eedaf7274cde6c52c2742fb12c35efde5d7a710dae4" - }, - { - "path": "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "sha256": "1f7c152066590d335196d0792597cdaad49c5b2f60d82ca25fe0c6dbe5f4befc" - } - ], - "database": { - "journalMode": "wal", - "tables": { - "battle_snapshots": [ - { - "battle_id": "battle-alpha-1", - "opponent_hand_json": "[{\"template_id\":\"item-2\",\"tier\":\"Silver\"}]", - "opponent_skills_json": "[]", - "player_hand_json": "[{\"template_id\":\"item-1\",\"tier\":\"Gold\"}]", - "player_skills_json": "[]" - } - ], - "battles": [ - { - "battle_id": "battle-alpha-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-alpha-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 4, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-101", - "opponent_hand_item_count": null, - "opponent_hero": "Pygmalien", - "opponent_level": null, - "opponent_name": "Rival A", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Vanessa", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790856600000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-alpha", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-bravo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 8, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-bravo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-102", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival B", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Dooley", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790946600000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-bravo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-charlie-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 10, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-charlie-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": 1791072000000, - "local_payload_state": "evicted", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-103", - "opponent_hand_item_count": null, - "opponent_hero": "Stelle", - "opponent_level": null, - "opponent_name": "Rival C", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Pygmalien", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791033000000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-charlie", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-delta-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 7, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-delta-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 3, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "missing", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-104", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival D", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Mak", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791119400000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-delta", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-echo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-echo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 5, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-105", - "opponent_hand_item_count": null, - "opponent_hero": "Jules", - "opponent_level": null, - "opponent_name": "Rival E", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Stelle", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791205800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-echo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-foxtrot-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 3, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-foxtrot-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 0, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-106", - "opponent_hand_item_count": null, - "opponent_hero": "Mak", - "opponent_level": null, - "opponent_name": "Rival F", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Jules", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791291900000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-foxtrot", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-golf-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 11, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-golf-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-107", - "opponent_hand_item_count": null, - "opponent_hero": "Dooley", - "opponent_level": null, - "opponent_name": "Rival G", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "hero8", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1785589800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-golf", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - } - ], - "bundle_outbox": [], - "bundle_seal_jobs": [], - "combat_replay_videos": [ - { - "attachment_state": "attached", - "battle_id": "battle-alpha-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790856690000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1790857200000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790856600000, - "status": "COMPLETED", - "video_id": "video-alpha-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-bravo-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790946690000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1790947200000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790946600000, - "status": "COMPLETED", - "video_id": "video-bravo-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-charlie-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1791033090000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1791033600000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1791033000000, - "status": "COMPLETED", - "video_id": "video-charlie-1", - "video_relative_path": "battle-charlie-1.20261003-211000.rec0003.mp4", - "width": 1920 - } - ], - "run_events": [ - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":1,\"ts\":\"2026-10-01T12:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Vanessa\",\"game_mode\":\"Ranked\"}", - "run_id": "run-alpha", - "seq": 1, - "ts_at_ms": 1790856000000 - }, - { - "kind": "pvp_combat_recorded", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":2,\"ts\":\"2026-10-01T12:10:00.000+00:00\",\"kind\":\"pvp_combat_recorded\",\"day\":9,\"hour\":4,\"combat_kind\":\"PVPCombat\",\"battle_id\":\"battle-alpha-1\"}", - "run_id": "run-alpha", - "seq": 2, - "ts_at_ms": 1790856600000 - }, - { - "kind": "run_completed", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":3,\"ts\":\"2026-10-01T12:15:04.000+00:00\",\"kind\":\"run_completed\",\"victories\":10,\"losses\":3}", - "run_id": "run-alpha", - "seq": 3, - "ts_at_ms": 1790856904000 - }, - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-foxtrot\",\"seq\":1,\"ts\":\"2026-10-06T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Jules\",\"game_mode\":\"Ranked\"}", - "run_id": "run-foxtrot", - "seq": 1, - "ts_at_ms": 1791291600000 - }, - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-golf\",\"seq\":1,\"ts\":\"2026-08-01T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"hero8\",\"game_mode\":\"Ranked\"}", - "run_id": "run-golf", - "seq": 1, - "ts_at_ms": 1785589200000 - } - ], - "run_screenshots": [ - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790856904120, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Vanessa", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1436, - "run_id": "run-alpha", - "screenshot_id": "shot-alpha", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790947200000, - "captured_utc_offset_minutes": 480, - "day": 8, - "hero_name": "Dooley", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 2, - "player_rank": "Gold 1", - "player_rating": 1430, - "run_id": "run-bravo", - "screenshot_id": "shot-bravo", - "victories_at_capture": 7 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791033660000, - "captured_utc_offset_minutes": 480, - "day": 10, - "hero_name": "Pygmalien", - "image_relative_path": "2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1452, - "run_id": "run-charlie", - "screenshot_id": "shot-charlie", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791206280000, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Stelle", - "image_relative_path": "2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1446, - "run_id": "run-echo", - "screenshot_id": "shot-echo", - "victories_at_capture": 8 - } - ], - "runs": [ - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1790856904000, - "final_day": 9, - "final_hour": 4, - "final_player_rank": "Gold 1", - "final_player_rating": 1436, - "final_player_rating_delta": 16, - "game_mode": "Ranked", - "gold": null, - "hero": "Vanessa", - "hour": 4, - "income": null, - "last_seen_at_ms": 1790856904000, - "last_seq": 3, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 2", - "player_rating": 1420, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-alpha", - "started_at_ms": 1790856000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 8, - "ended_at_ms": 1790947200000, - "final_day": 8, - "final_hour": 2, - "final_player_rank": "Gold 1", - "final_player_rating": 1430, - "final_player_rating_delta": -6, - "game_mode": "Ranked", - "gold": null, - "hero": "Dooley", - "hour": 2, - "income": null, - "last_seen_at_ms": 1790947200000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1436, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-bravo", - "started_at_ms": 1790946000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 7 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 10, - "ended_at_ms": 1791033660000, - "final_day": 10, - "final_hour": 1, - "final_player_rank": "Gold 1", - "final_player_rating": 1452, - "final_player_rating_delta": 22, - "game_mode": "Ranked", - "gold": null, - "hero": "Pygmalien", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791033660000, - "last_seq": 2, - "level": null, - "losses": 2, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1430, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-charlie", - "started_at_ms": 1791032400000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 7, - "ended_at_ms": 1791119940000, - "final_day": 7, - "final_hour": 3, - "final_player_rank": "Gold 1", - "final_player_rating": 1440, - "final_player_rating_delta": -12, - "game_mode": "Ranked", - "gold": null, - "hero": "Mak", - "hour": 3, - "income": null, - "last_seen_at_ms": 1791119940000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1452, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-delta", - "started_at_ms": 1791118800000, - "status": "completed", - "upload_policy": "history_only", - "victories": 4 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1791206280000, - "final_day": 9, - "final_hour": 5, - "final_player_rank": "Gold 1", - "final_player_rating": 1446, - "final_player_rating_delta": 6, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 5, - "income": null, - "last_seen_at_ms": 1791206280000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1440, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-echo", - "started_at_ms": 1791205200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 8 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 4, - "ended_at_ms": 1791209760000, - "final_day": 4, - "final_hour": 2, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 2, - "income": null, - "last_seen_at_ms": 1791209760000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": "session_mismatch", - "run_id": "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "started_at_ms": 1791208800000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 0, - "day": 3, - "ended_at_ms": 1791292140000, - "final_day": null, - "final_hour": null, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Jules", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791292140000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": null, - "run_id": "run-foxtrot", - "started_at_ms": 1791291600000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 11, - "ended_at_ms": 1785590700000, - "final_day": 11, - "final_hour": 2, - "final_player_rank": "Silver 1", - "final_player_rating": 1236, - "final_player_rating_delta": 26, - "game_mode": "Ranked", - "gold": null, - "hero": "hero8", - "hour": 2, - "income": null, - "last_seen_at_ms": 1785590700000, - "last_seq": 3, - "level": null, - "losses": 1, - "max_health": null, - "mod_version": "5.5.0", - "player_account_id": "account-001", - "player_rank": "Silver 1", - "player_rating": 1210, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-golf", - "started_at_ms": 1785589200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - } - ] - }, - "userVersion": 1 - }, - "marker": true, - "report": { - "closedRuns": [ - "run-foxtrot" - ], - "droppedReferences": [ - { - "id": "video-delta-1", - "path": "{{OUTSIDE_ROOT}}/Videos/battle-delta-1.20261004-211000.rec0004.mp4", - "reason": "outside_data_root", - "table": "combat_replay_videos" - }, - { - "id": "shot-delta", - "path": "{{OUTSIDE_ROOT}}/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png", - "reason": "outside_data_root", - "table": "run_screenshots" - } - ], - "evictedReplays": [], - "files": [ - "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "CombatReplays/battle-alpha-1.payload.mpack.gz", - "CombatReplays/battle-bravo-1.payload.mpack.gz", - "CombatReplays/battle-echo-1.payload.mpack.gz", - "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "CombatReplays/battle-golf-1.payload.mpack.gz", - "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png" - ], - "importedRuns": [ - "run-alpha", - "run-bravo", - "run-charlie", - "run-delta", - "run-echo", - "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "run-foxtrot", - "run-golf" - ], - "missingFiles": [], - "skippedRuns": [] - }, - "status": "imported" -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v3-upgraded-from-v1.json b/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v3-upgraded-from-v1.json deleted file mode 100644 index a095d31..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v3-upgraded-from-v1.json +++ /dev/null @@ -1,872 +0,0 @@ -{ - "dataRootFiles": [ - { - "path": "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "sha256": "9ce75744ad250f08dcaa7c9cc8f89c3210709e587aa31d9b6acc1003a6fd3552" - }, - { - "path": "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "sha256": "ca9e18831161cfd7d6a58970980a5cf5cf740cccd98ece50797c8be30e944cc0" - }, - { - "path": "CombatReplays/battle-alpha-1.payload.mpack.gz", - "sha256": "9af0a0ffa4d8e2bd932979ed17a500009cf90bcb3efabe571af07f5a778406fb" - }, - { - "path": "CombatReplays/battle-bravo-1.payload.mpack.gz", - "sha256": "a2b0b763f07ec867caaa2973d582d8b5268ffcc06b832d78401defe5612e0beb" - }, - { - "path": "CombatReplays/battle-echo-1.payload.mpack.gz", - "sha256": "badb7840e3e9a758c2d27c0eb10d1876fd3737aef08d4ac82eab377fabae7d2d" - }, - { - "path": "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "sha256": "a2e4fda50cddf0e14cbc2c4a53f163aec6c80be6243ad050d571af5bd486a493" - }, - { - "path": "CombatReplays/battle-golf-1.payload.mpack.gz", - "sha256": "02a5d1b251f2458b1cf5083abd178195cf56e016e7f07fd8306f7866b808f191" - }, - { - "path": "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "sha256": "331ee0745a32a77b7297e347edfefad13f71f8b6c17ccfbcb5d780dbc3f700f6" - }, - { - "path": "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "sha256": "df526d0d60ff5a7ccdef7eedaf7274cde6c52c2742fb12c35efde5d7a710dae4" - }, - { - "path": "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "sha256": "1f7c152066590d335196d0792597cdaad49c5b2f60d82ca25fe0c6dbe5f4befc" - } - ], - "database": { - "journalMode": "wal", - "tables": { - "battle_snapshots": [ - { - "battle_id": "battle-alpha-1", - "opponent_hand_json": "[{\"template_id\":\"item-2\",\"tier\":\"Silver\"}]", - "opponent_skills_json": "[]", - "player_hand_json": "[{\"template_id\":\"item-1\",\"tier\":\"Gold\"}]", - "player_skills_json": "[]" - } - ], - "battles": [ - { - "battle_id": "battle-alpha-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-alpha-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 4, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-101", - "opponent_hand_item_count": null, - "opponent_hero": "Pygmalien", - "opponent_level": null, - "opponent_name": "Rival A", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Vanessa", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790856600000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-alpha", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-bravo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 8, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-bravo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-102", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival B", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Dooley", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790946600000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-bravo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-charlie-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 10, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-charlie-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": 1791072000000, - "local_payload_state": "evicted", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-103", - "opponent_hand_item_count": null, - "opponent_hero": "Stelle", - "opponent_level": null, - "opponent_name": "Rival C", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Pygmalien", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791033000000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-charlie", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-delta-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 7, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-delta-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 3, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "missing", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-104", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival D", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Mak", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791119400000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-delta", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-echo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-echo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 5, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-105", - "opponent_hand_item_count": null, - "opponent_hero": "Jules", - "opponent_level": null, - "opponent_name": "Rival E", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Stelle", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791205800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-echo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-foxtrot-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 3, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-foxtrot-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 0, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-106", - "opponent_hand_item_count": null, - "opponent_hero": "Mak", - "opponent_level": null, - "opponent_name": "Rival F", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Jules", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791291900000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-foxtrot", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-golf-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 11, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-golf-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-107", - "opponent_hand_item_count": null, - "opponent_hero": "Dooley", - "opponent_level": null, - "opponent_name": "Rival G", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "hero8", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1785589800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-golf", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - } - ], - "bundle_outbox": [], - "bundle_seal_jobs": [], - "combat_replay_videos": [ - { - "attachment_state": "attached", - "battle_id": "battle-alpha-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790856690000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1790857200000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790856600000, - "status": "COMPLETED", - "video_id": "video-alpha-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-bravo-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790946690000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1790947200000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790946600000, - "status": "COMPLETED", - "video_id": "video-bravo-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-charlie-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1791033090000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1791033600000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1791033000000, - "status": "COMPLETED", - "video_id": "video-charlie-1", - "video_relative_path": "battle-charlie-1.20261003-211000.rec0003.mp4", - "width": 1920 - } - ], - "run_events": [ - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":1,\"ts\":\"2026-10-01T12:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Vanessa\",\"game_mode\":\"Ranked\"}", - "run_id": "run-alpha", - "seq": 1, - "ts_at_ms": 1790856000000 - }, - { - "kind": "pvp_combat_recorded", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":2,\"ts\":\"2026-10-01T12:10:00.000+00:00\",\"kind\":\"pvp_combat_recorded\",\"day\":9,\"hour\":4,\"combat_kind\":\"PVPCombat\",\"battle_id\":\"battle-alpha-1\"}", - "run_id": "run-alpha", - "seq": 2, - "ts_at_ms": 1790856600000 - }, - { - "kind": "run_completed", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":3,\"ts\":\"2026-10-01T12:15:04.000+00:00\",\"kind\":\"run_completed\",\"victories\":10,\"losses\":3}", - "run_id": "run-alpha", - "seq": 3, - "ts_at_ms": 1790856904000 - }, - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-foxtrot\",\"seq\":1,\"ts\":\"2026-10-06T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Jules\",\"game_mode\":\"Ranked\"}", - "run_id": "run-foxtrot", - "seq": 1, - "ts_at_ms": 1791291600000 - }, - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-golf\",\"seq\":1,\"ts\":\"2026-08-01T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"hero8\",\"game_mode\":\"Ranked\"}", - "run_id": "run-golf", - "seq": 1, - "ts_at_ms": 1785589200000 - } - ], - "run_screenshots": [ - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790856904120, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Vanessa", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1436, - "run_id": "run-alpha", - "screenshot_id": "shot-alpha", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790947200000, - "captured_utc_offset_minutes": 480, - "day": 8, - "hero_name": "Dooley", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 2, - "player_rank": "Gold 1", - "player_rating": 1430, - "run_id": "run-bravo", - "screenshot_id": "shot-bravo", - "victories_at_capture": 7 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791033660000, - "captured_utc_offset_minutes": 480, - "day": 10, - "hero_name": "Pygmalien", - "image_relative_path": "2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1452, - "run_id": "run-charlie", - "screenshot_id": "shot-charlie", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791206280000, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Stelle", - "image_relative_path": "2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1446, - "run_id": "run-echo", - "screenshot_id": "shot-echo", - "victories_at_capture": 8 - } - ], - "runs": [ - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1790856904000, - "final_day": 9, - "final_hour": 4, - "final_player_rank": "Gold 1", - "final_player_rating": 1436, - "final_player_rating_delta": 16, - "game_mode": "Ranked", - "gold": null, - "hero": "Vanessa", - "hour": 4, - "income": null, - "last_seen_at_ms": 1790856904000, - "last_seq": 3, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 2", - "player_rating": 1420, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-alpha", - "started_at_ms": 1790856000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 8, - "ended_at_ms": 1790947200000, - "final_day": 8, - "final_hour": 2, - "final_player_rank": "Gold 1", - "final_player_rating": 1430, - "final_player_rating_delta": -6, - "game_mode": "Ranked", - "gold": null, - "hero": "Dooley", - "hour": 2, - "income": null, - "last_seen_at_ms": 1790947200000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1436, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-bravo", - "started_at_ms": 1790946000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 7 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 10, - "ended_at_ms": 1791033660000, - "final_day": 10, - "final_hour": 1, - "final_player_rank": "Gold 1", - "final_player_rating": 1452, - "final_player_rating_delta": 22, - "game_mode": "Ranked", - "gold": null, - "hero": "Pygmalien", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791033660000, - "last_seq": 2, - "level": null, - "losses": 2, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1430, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-charlie", - "started_at_ms": 1791032400000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 7, - "ended_at_ms": 1791119940000, - "final_day": 7, - "final_hour": 3, - "final_player_rank": "Gold 1", - "final_player_rating": 1440, - "final_player_rating_delta": -12, - "game_mode": "Ranked", - "gold": null, - "hero": "Mak", - "hour": 3, - "income": null, - "last_seen_at_ms": 1791119940000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1452, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-delta", - "started_at_ms": 1791118800000, - "status": "completed", - "upload_policy": "history_only", - "victories": 4 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1791206280000, - "final_day": 9, - "final_hour": 5, - "final_player_rank": "Gold 1", - "final_player_rating": 1446, - "final_player_rating_delta": 6, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 5, - "income": null, - "last_seen_at_ms": 1791206280000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1440, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-echo", - "started_at_ms": 1791205200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 8 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 4, - "ended_at_ms": 1791209760000, - "final_day": 4, - "final_hour": 2, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 2, - "income": null, - "last_seen_at_ms": 1791209760000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": "session_mismatch", - "run_id": "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "started_at_ms": 1791208800000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 0, - "day": 3, - "ended_at_ms": 1791292140000, - "final_day": null, - "final_hour": null, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Jules", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791292140000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": null, - "run_id": "run-foxtrot", - "started_at_ms": 1791291600000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 11, - "ended_at_ms": 1785590700000, - "final_day": 11, - "final_hour": 2, - "final_player_rank": "Silver 1", - "final_player_rating": 1236, - "final_player_rating_delta": 26, - "game_mode": "Ranked", - "gold": null, - "hero": "hero8", - "hour": 2, - "income": null, - "last_seen_at_ms": 1785590700000, - "last_seq": 3, - "level": null, - "losses": 1, - "max_health": null, - "mod_version": "5.5.0", - "player_account_id": "account-001", - "player_rank": "Silver 1", - "player_rating": 1210, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-golf", - "started_at_ms": 1785589200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - } - ] - }, - "userVersion": 1 - }, - "marker": true, - "report": { - "closedRuns": [ - "run-foxtrot" - ], - "droppedReferences": [ - { - "id": "video-delta-1", - "path": "{{OUTSIDE_ROOT}}/Videos/battle-delta-1.20261004-211000.rec0004.mp4", - "reason": "outside_data_root", - "table": "combat_replay_videos" - }, - { - "id": "shot-delta", - "path": "{{OUTSIDE_ROOT}}/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png", - "reason": "outside_data_root", - "table": "run_screenshots" - } - ], - "evictedReplays": [], - "files": [ - "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "CombatReplays/battle-alpha-1.payload.mpack.gz", - "CombatReplays/battle-bravo-1.payload.mpack.gz", - "CombatReplays/battle-echo-1.payload.mpack.gz", - "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "CombatReplays/battle-golf-1.payload.mpack.gz", - "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png" - ], - "importedRuns": [ - "run-alpha", - "run-bravo", - "run-charlie", - "run-delta", - "run-echo", - "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "run-foxtrot", - "run-golf" - ], - "missingFiles": [], - "skippedRuns": [] - }, - "status": "imported" -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v3.json b/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v3.json deleted file mode 100644 index a095d31..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v3.json +++ /dev/null @@ -1,872 +0,0 @@ -{ - "dataRootFiles": [ - { - "path": "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "sha256": "9ce75744ad250f08dcaa7c9cc8f89c3210709e587aa31d9b6acc1003a6fd3552" - }, - { - "path": "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "sha256": "ca9e18831161cfd7d6a58970980a5cf5cf740cccd98ece50797c8be30e944cc0" - }, - { - "path": "CombatReplays/battle-alpha-1.payload.mpack.gz", - "sha256": "9af0a0ffa4d8e2bd932979ed17a500009cf90bcb3efabe571af07f5a778406fb" - }, - { - "path": "CombatReplays/battle-bravo-1.payload.mpack.gz", - "sha256": "a2b0b763f07ec867caaa2973d582d8b5268ffcc06b832d78401defe5612e0beb" - }, - { - "path": "CombatReplays/battle-echo-1.payload.mpack.gz", - "sha256": "badb7840e3e9a758c2d27c0eb10d1876fd3737aef08d4ac82eab377fabae7d2d" - }, - { - "path": "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "sha256": "a2e4fda50cddf0e14cbc2c4a53f163aec6c80be6243ad050d571af5bd486a493" - }, - { - "path": "CombatReplays/battle-golf-1.payload.mpack.gz", - "sha256": "02a5d1b251f2458b1cf5083abd178195cf56e016e7f07fd8306f7866b808f191" - }, - { - "path": "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "sha256": "331ee0745a32a77b7297e347edfefad13f71f8b6c17ccfbcb5d780dbc3f700f6" - }, - { - "path": "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "sha256": "df526d0d60ff5a7ccdef7eedaf7274cde6c52c2742fb12c35efde5d7a710dae4" - }, - { - "path": "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "sha256": "1f7c152066590d335196d0792597cdaad49c5b2f60d82ca25fe0c6dbe5f4befc" - } - ], - "database": { - "journalMode": "wal", - "tables": { - "battle_snapshots": [ - { - "battle_id": "battle-alpha-1", - "opponent_hand_json": "[{\"template_id\":\"item-2\",\"tier\":\"Silver\"}]", - "opponent_skills_json": "[]", - "player_hand_json": "[{\"template_id\":\"item-1\",\"tier\":\"Gold\"}]", - "player_skills_json": "[]" - } - ], - "battles": [ - { - "battle_id": "battle-alpha-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-alpha-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 4, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-101", - "opponent_hand_item_count": null, - "opponent_hero": "Pygmalien", - "opponent_level": null, - "opponent_name": "Rival A", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Vanessa", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790856600000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-alpha", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-bravo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 8, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-bravo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-102", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival B", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Dooley", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790946600000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-bravo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-charlie-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 10, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-charlie-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": 1791072000000, - "local_payload_state": "evicted", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-103", - "opponent_hand_item_count": null, - "opponent_hero": "Stelle", - "opponent_level": null, - "opponent_name": "Rival C", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Pygmalien", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791033000000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-charlie", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-delta-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 7, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-delta-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 3, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "missing", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-104", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival D", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Mak", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791119400000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-delta", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-echo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-echo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 5, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-105", - "opponent_hand_item_count": null, - "opponent_hero": "Jules", - "opponent_level": null, - "opponent_name": "Rival E", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Stelle", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791205800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-echo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-foxtrot-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 3, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-foxtrot-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 0, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-106", - "opponent_hand_item_count": null, - "opponent_hero": "Mak", - "opponent_level": null, - "opponent_name": "Rival F", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Jules", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791291900000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-foxtrot", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-golf-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 11, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-golf-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-107", - "opponent_hand_item_count": null, - "opponent_hero": "Dooley", - "opponent_level": null, - "opponent_name": "Rival G", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "hero8", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1785589800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-golf", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - } - ], - "bundle_outbox": [], - "bundle_seal_jobs": [], - "combat_replay_videos": [ - { - "attachment_state": "attached", - "battle_id": "battle-alpha-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790856690000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1790857200000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790856600000, - "status": "COMPLETED", - "video_id": "video-alpha-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-bravo-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790946690000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1790947200000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790946600000, - "status": "COMPLETED", - "video_id": "video-bravo-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-charlie-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1791033090000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1791033600000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1791033000000, - "status": "COMPLETED", - "video_id": "video-charlie-1", - "video_relative_path": "battle-charlie-1.20261003-211000.rec0003.mp4", - "width": 1920 - } - ], - "run_events": [ - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":1,\"ts\":\"2026-10-01T12:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Vanessa\",\"game_mode\":\"Ranked\"}", - "run_id": "run-alpha", - "seq": 1, - "ts_at_ms": 1790856000000 - }, - { - "kind": "pvp_combat_recorded", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":2,\"ts\":\"2026-10-01T12:10:00.000+00:00\",\"kind\":\"pvp_combat_recorded\",\"day\":9,\"hour\":4,\"combat_kind\":\"PVPCombat\",\"battle_id\":\"battle-alpha-1\"}", - "run_id": "run-alpha", - "seq": 2, - "ts_at_ms": 1790856600000 - }, - { - "kind": "run_completed", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-alpha\",\"seq\":3,\"ts\":\"2026-10-01T12:15:04.000+00:00\",\"kind\":\"run_completed\",\"victories\":10,\"losses\":3}", - "run_id": "run-alpha", - "seq": 3, - "ts_at_ms": 1790856904000 - }, - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-foxtrot\",\"seq\":1,\"ts\":\"2026-10-06T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Jules\",\"game_mode\":\"Ranked\"}", - "run_id": "run-foxtrot", - "seq": 1, - "ts_at_ms": 1791291600000 - }, - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-golf\",\"seq\":1,\"ts\":\"2026-08-01T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"hero8\",\"game_mode\":\"Ranked\"}", - "run_id": "run-golf", - "seq": 1, - "ts_at_ms": 1785589200000 - } - ], - "run_screenshots": [ - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790856904120, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Vanessa", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1436, - "run_id": "run-alpha", - "screenshot_id": "shot-alpha", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790947200000, - "captured_utc_offset_minutes": 480, - "day": 8, - "hero_name": "Dooley", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 2, - "player_rank": "Gold 1", - "player_rating": 1430, - "run_id": "run-bravo", - "screenshot_id": "shot-bravo", - "victories_at_capture": 7 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791033660000, - "captured_utc_offset_minutes": 480, - "day": 10, - "hero_name": "Pygmalien", - "image_relative_path": "2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1452, - "run_id": "run-charlie", - "screenshot_id": "shot-charlie", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791206280000, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Stelle", - "image_relative_path": "2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1446, - "run_id": "run-echo", - "screenshot_id": "shot-echo", - "victories_at_capture": 8 - } - ], - "runs": [ - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1790856904000, - "final_day": 9, - "final_hour": 4, - "final_player_rank": "Gold 1", - "final_player_rating": 1436, - "final_player_rating_delta": 16, - "game_mode": "Ranked", - "gold": null, - "hero": "Vanessa", - "hour": 4, - "income": null, - "last_seen_at_ms": 1790856904000, - "last_seq": 3, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 2", - "player_rating": 1420, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-alpha", - "started_at_ms": 1790856000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 8, - "ended_at_ms": 1790947200000, - "final_day": 8, - "final_hour": 2, - "final_player_rank": "Gold 1", - "final_player_rating": 1430, - "final_player_rating_delta": -6, - "game_mode": "Ranked", - "gold": null, - "hero": "Dooley", - "hour": 2, - "income": null, - "last_seen_at_ms": 1790947200000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1436, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-bravo", - "started_at_ms": 1790946000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 7 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 10, - "ended_at_ms": 1791033660000, - "final_day": 10, - "final_hour": 1, - "final_player_rank": "Gold 1", - "final_player_rating": 1452, - "final_player_rating_delta": 22, - "game_mode": "Ranked", - "gold": null, - "hero": "Pygmalien", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791033660000, - "last_seq": 2, - "level": null, - "losses": 2, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1430, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-charlie", - "started_at_ms": 1791032400000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 7, - "ended_at_ms": 1791119940000, - "final_day": 7, - "final_hour": 3, - "final_player_rank": "Gold 1", - "final_player_rating": 1440, - "final_player_rating_delta": -12, - "game_mode": "Ranked", - "gold": null, - "hero": "Mak", - "hour": 3, - "income": null, - "last_seen_at_ms": 1791119940000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1452, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-delta", - "started_at_ms": 1791118800000, - "status": "completed", - "upload_policy": "history_only", - "victories": 4 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1791206280000, - "final_day": 9, - "final_hour": 5, - "final_player_rank": "Gold 1", - "final_player_rating": 1446, - "final_player_rating_delta": 6, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 5, - "income": null, - "last_seen_at_ms": 1791206280000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1440, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-echo", - "started_at_ms": 1791205200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 8 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 4, - "ended_at_ms": 1791209760000, - "final_day": 4, - "final_hour": 2, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 2, - "income": null, - "last_seen_at_ms": 1791209760000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": "session_mismatch", - "run_id": "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "started_at_ms": 1791208800000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 0, - "day": 3, - "ended_at_ms": 1791292140000, - "final_day": null, - "final_hour": null, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Jules", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791292140000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": null, - "run_id": "run-foxtrot", - "started_at_ms": 1791291600000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 11, - "ended_at_ms": 1785590700000, - "final_day": 11, - "final_hour": 2, - "final_player_rank": "Silver 1", - "final_player_rating": 1236, - "final_player_rating_delta": 26, - "game_mode": "Ranked", - "gold": null, - "hero": "hero8", - "hour": 2, - "income": null, - "last_seen_at_ms": 1785590700000, - "last_seq": 3, - "level": null, - "losses": 1, - "max_health": null, - "mod_version": "5.5.0", - "player_account_id": "account-001", - "player_rank": "Silver 1", - "player_rating": 1210, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-golf", - "started_at_ms": 1785589200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - } - ] - }, - "userVersion": 1 - }, - "marker": true, - "report": { - "closedRuns": [ - "run-foxtrot" - ], - "droppedReferences": [ - { - "id": "video-delta-1", - "path": "{{OUTSIDE_ROOT}}/Videos/battle-delta-1.20261004-211000.rec0004.mp4", - "reason": "outside_data_root", - "table": "combat_replay_videos" - }, - { - "id": "shot-delta", - "path": "{{OUTSIDE_ROOT}}/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png", - "reason": "outside_data_root", - "table": "run_screenshots" - } - ], - "evictedReplays": [], - "files": [ - "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "CombatReplays/battle-alpha-1.payload.mpack.gz", - "CombatReplays/battle-bravo-1.payload.mpack.gz", - "CombatReplays/battle-echo-1.payload.mpack.gz", - "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "CombatReplays/battle-golf-1.payload.mpack.gz", - "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png" - ], - "importedRuns": [ - "run-alpha", - "run-bravo", - "run-charlie", - "run-delta", - "run-echo", - "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "run-foxtrot", - "run-golf" - ], - "missingFiles": [], - "skippedRuns": [] - }, - "status": "imported" -} diff --git a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v6-overlap.json b/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v6-overlap.json deleted file mode 100644 index 001e566..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/goldens/v5-import/v6-overlap.json +++ /dev/null @@ -1,816 +0,0 @@ -{ - "dataRootFiles": [ - { - "path": "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "sha256": "9ce75744ad250f08dcaa7c9cc8f89c3210709e587aa31d9b6acc1003a6fd3552" - }, - { - "path": "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "sha256": "ca9e18831161cfd7d6a58970980a5cf5cf740cccd98ece50797c8be30e944cc0" - }, - { - "path": "CombatReplays/battle-alpha-1.payload.mpack.gz", - "sha256": "81a1080d0ecb11b36f372833a713caae97fa21c22e67e74023a200a1472b3b29" - }, - { - "path": "CombatReplays/battle-bravo-1.payload.mpack.gz", - "sha256": "a2b0b763f07ec867caaa2973d582d8b5268ffcc06b832d78401defe5612e0beb" - }, - { - "path": "CombatReplays/battle-echo-1.payload.mpack.gz", - "sha256": "badb7840e3e9a758c2d27c0eb10d1876fd3737aef08d4ac82eab377fabae7d2d" - }, - { - "path": "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "sha256": "a2e4fda50cddf0e14cbc2c4a53f163aec6c80be6243ad050d571af5bd486a493" - }, - { - "path": "CombatReplays/battle-golf-1.payload.mpack.gz", - "sha256": "81a1080d0ecb11b36f372833a713caae97fa21c22e67e74023a200a1472b3b29" - }, - { - "path": "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "sha256": "331ee0745a32a77b7297e347edfefad13f71f8b6c17ccfbcb5d780dbc3f700f6" - }, - { - "path": "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "sha256": "df526d0d60ff5a7ccdef7eedaf7274cde6c52c2742fb12c35efde5d7a710dae4" - }, - { - "path": "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "sha256": "1f7c152066590d335196d0792597cdaad49c5b2f60d82ca25fe0c6dbe5f4befc" - } - ], - "database": { - "journalMode": "wal", - "tables": { - "battle_snapshots": [], - "battles": [ - { - "battle_id": "battle-alpha-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": null, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": null, - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": null, - "is_final_battle": 0, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": null, - "opponent_account_id": null, - "opponent_hand_item_count": null, - "opponent_hero": null, - "opponent_level": null, - "opponent_name": null, - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": null, - "player_gold": null, - "player_hand_item_count": null, - "player_hero": null, - "player_income": null, - "player_level": null, - "player_name": null, - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790856600000, - "remote_battle_id": null, - "result": null, - "run_id": "run-alpha", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": null - }, - { - "battle_id": "battle-bravo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 8, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-bravo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 2, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-102", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival B", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Dooley", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1790946600000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-bravo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-charlie-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 10, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-charlie-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": 1791072000000, - "local_payload_state": "evicted", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-103", - "opponent_hand_item_count": null, - "opponent_hero": "Stelle", - "opponent_level": null, - "opponent_name": "Rival C", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Pygmalien", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791033000000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-charlie", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-delta-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 7, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-delta-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 3, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "missing", - "local_player_account_id": null, - "loser_combatant_id": "player", - "opponent_account_id": "account-104", - "opponent_hand_item_count": null, - "opponent_hero": "Vanessa", - "opponent_level": null, - "opponent_name": "Rival D", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Mak", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791119400000, - "remote_battle_id": null, - "result": "Loss", - "run_id": "run-delta", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "opponent" - }, - { - "battle_id": "battle-echo-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 9, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-echo-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 5, - "is_final_battle": 1, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-105", - "opponent_hand_item_count": null, - "opponent_hero": "Jules", - "opponent_level": null, - "opponent_name": "Rival E", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Stelle", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791205800000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-echo", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-foxtrot-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": 3, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": "encounter-foxtrot-1", - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": 1, - "is_final_battle": 0, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": "opponent", - "opponent_account_id": "account-106", - "opponent_hand_item_count": null, - "opponent_hero": "Mak", - "opponent_level": null, - "opponent_name": "Rival F", - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": "account-001", - "player_gold": null, - "player_hand_item_count": null, - "player_hero": "Jules", - "player_income": null, - "player_level": null, - "player_name": "Player", - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791291900000, - "remote_battle_id": null, - "result": "Win", - "run_id": "run-foxtrot", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": "player" - }, - { - "battle_id": "battle-golf-1", - "bundle_id": null, - "combat_kind": "PVPCombat", - "day": null, - "deleted_at_ms": null, - "download_url": null, - "download_url_expires_at_ms": null, - "encounter_id": null, - "ghost_replay_state": null, - "ghost_replay_unavailable_reason": null, - "hour": null, - "is_final_battle": 0, - "local_payload_maintenance_at_ms": null, - "local_payload_state": "ready", - "local_player_account_id": null, - "loser_combatant_id": null, - "opponent_account_id": null, - "opponent_hand_item_count": null, - "opponent_hero": null, - "opponent_level": null, - "opponent_name": null, - "opponent_prestige": null, - "opponent_rank": null, - "opponent_rating": null, - "opponent_skill_count": null, - "opponent_victories": null, - "player_account_id": null, - "player_gold": null, - "player_hand_item_count": null, - "player_hero": null, - "player_income": null, - "player_level": null, - "player_name": null, - "player_prestige": null, - "player_rank": null, - "player_rating": null, - "player_skill_count": null, - "player_victories": null, - "recorded_at_ms": 1791504600000, - "remote_battle_id": null, - "result": null, - "run_id": "run-v6", - "source": "LOCAL", - "uploader_account_id": null, - "winner_combatant_id": null - } - ], - "bundle_outbox": [], - "bundle_seal_jobs": [], - "combat_replay_videos": [ - { - "attachment_state": "attached", - "battle_id": "battle-bravo-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1790946690000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1790947200000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1790946600000, - "status": "COMPLETED", - "video_id": "video-bravo-1", - "video_relative_path": "battle-alpha-1.20261001-201000.rec0001.mp4", - "width": 1920 - }, - { - "attachment_state": "attached", - "battle_id": "battle-charlie-1", - "captured_frames": 5400, - "codec": "h264", - "crf": 23, - "detached_at_ms": null, - "dropped_frames": 0, - "duration_ms": 90000, - "ended_at_ms": 1791033090000, - "error": null, - "file_size_bytes": 36, - "file_state": "present", - "fps": 60, - "height": 1080, - "last_reconciled_at_ms": 1791033600000, - "missing_at_ms": null, - "preset": "p4", - "source": "LocalSaved", - "started_at_ms": 1791033000000, - "status": "COMPLETED", - "video_id": "video-charlie-1", - "video_relative_path": "battle-charlie-1.20261003-211000.rec0003.mp4", - "width": 1920 - } - ], - "run_events": [ - { - "kind": "run_started", - "payload_json": "{\"schema_version\":3,\"run_id\":\"run-foxtrot\",\"seq\":1,\"ts\":\"2026-10-06T13:00:00.000+00:00\",\"kind\":\"run_started\",\"day\":1,\"hour\":0,\"hero\":\"Jules\",\"game_mode\":\"Ranked\"}", - "run_id": "run-foxtrot", - "seq": 1, - "ts_at_ms": 1791291600000 - } - ], - "run_screenshots": [ - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790856904120, - "captured_utc_offset_minutes": 480, - "day": null, - "hero_name": "Vanessa", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": null, - "player_rank": null, - "player_rating": null, - "run_id": "run-alpha", - "screenshot_id": "shot-alpha", - "victories_at_capture": null - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1790947200000, - "captured_utc_offset_minutes": 480, - "day": 8, - "hero_name": "Dooley", - "image_relative_path": "2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "is_primary": 1, - "player_position": 2, - "player_rank": "Gold 1", - "player_rating": 1430, - "run_id": "run-bravo", - "screenshot_id": "shot-bravo", - "victories_at_capture": 7 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791033660000, - "captured_utc_offset_minutes": 480, - "day": 10, - "hero_name": "Pygmalien", - "image_relative_path": "2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1452, - "run_id": "run-charlie", - "screenshot_id": "shot-charlie", - "victories_at_capture": 10 - }, - { - "capture_source": "end_of_run_auto", - "captured_at_ms": 1791206280000, - "captured_utc_offset_minutes": 480, - "day": 9, - "hero_name": "Stelle", - "image_relative_path": "2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png", - "is_primary": 1, - "player_position": 1, - "player_rank": "Gold 1", - "player_rating": 1446, - "run_id": "run-echo", - "screenshot_id": "shot-echo", - "victories_at_capture": 8 - } - ], - "runs": [ - { - "build_channel": "Online", - "bundle_screenshot_requested": 0, - "day": null, - "ended_at_ms": 1790856904000, - "final_day": null, - "final_hour": null, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Vanessa", - "hour": null, - "income": null, - "last_seen_at_ms": 1790856904000, - "last_seq": 0, - "level": null, - "losses": null, - "max_health": null, - "mod_version": null, - "player_account_id": null, - "player_rank": null, - "player_rating": null, - "prestige": null, - "reason": null, - "run_id": "run-alpha", - "started_at_ms": 1790856000000, - "status": "completed", - "upload_policy": "bundle", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 8, - "ended_at_ms": 1790947200000, - "final_day": 8, - "final_hour": 2, - "final_player_rank": "Gold 1", - "final_player_rating": 1430, - "final_player_rating_delta": -6, - "game_mode": "Ranked", - "gold": null, - "hero": "Dooley", - "hour": 2, - "income": null, - "last_seen_at_ms": 1790947200000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1436, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-bravo", - "started_at_ms": 1790946000000, - "status": "completed", - "upload_policy": "history_only", - "victories": 7 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 10, - "ended_at_ms": 1791033660000, - "final_day": 10, - "final_hour": 1, - "final_player_rank": "Gold 1", - "final_player_rating": 1452, - "final_player_rating_delta": 22, - "game_mode": "Ranked", - "gold": null, - "hero": "Pygmalien", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791033660000, - "last_seq": 2, - "level": null, - "losses": 2, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1430, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-charlie", - "started_at_ms": 1791032400000, - "status": "completed", - "upload_policy": "history_only", - "victories": 10 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 7, - "ended_at_ms": 1791119940000, - "final_day": 7, - "final_hour": 3, - "final_player_rank": "Gold 1", - "final_player_rating": 1440, - "final_player_rating_delta": -12, - "game_mode": "Ranked", - "gold": null, - "hero": "Mak", - "hour": 3, - "income": null, - "last_seen_at_ms": 1791119940000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.6.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1452, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-delta", - "started_at_ms": 1791118800000, - "status": "completed", - "upload_policy": "history_only", - "victories": 4 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 9, - "ended_at_ms": 1791206280000, - "final_day": 9, - "final_hour": 5, - "final_player_rank": "Gold 1", - "final_player_rating": 1446, - "final_player_rating_delta": 6, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 5, - "income": null, - "last_seen_at_ms": 1791206280000, - "last_seq": 2, - "level": null, - "losses": 3, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1440, - "prestige": null, - "reason": "run_state_exit", - "run_id": "run-echo", - "started_at_ms": 1791205200000, - "status": "completed", - "upload_policy": "history_only", - "victories": 8 - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 1, - "day": 4, - "ended_at_ms": 1791209760000, - "final_day": 4, - "final_hour": 2, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Stelle", - "hour": 2, - "income": null, - "last_seen_at_ms": 1791209760000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": "session_mismatch", - "run_id": "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "started_at_ms": 1791208800000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 0, - "day": 3, - "ended_at_ms": 1791292140000, - "final_day": null, - "final_hour": null, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Jules", - "hour": 1, - "income": null, - "last_seen_at_ms": 1791292140000, - "last_seq": 1, - "level": null, - "losses": null, - "max_health": null, - "mod_version": "5.7.0", - "player_account_id": "account-001", - "player_rank": "Gold 1", - "player_rating": 1446, - "prestige": null, - "reason": null, - "run_id": "run-foxtrot", - "started_at_ms": 1791291600000, - "status": "abandoned", - "upload_policy": "history_only", - "victories": null - }, - { - "build_channel": "Online", - "bundle_screenshot_requested": 0, - "day": null, - "ended_at_ms": 1791505200000, - "final_day": null, - "final_hour": null, - "final_player_rank": null, - "final_player_rating": null, - "final_player_rating_delta": null, - "game_mode": "Ranked", - "gold": null, - "hero": "Mak", - "hour": null, - "income": null, - "last_seen_at_ms": 1791505200000, - "last_seq": 0, - "level": null, - "losses": null, - "max_health": null, - "mod_version": null, - "player_account_id": null, - "player_rank": null, - "player_rating": null, - "prestige": null, - "reason": null, - "run_id": "run-v6", - "started_at_ms": 1791504000000, - "status": "completed", - "upload_policy": "bundle", - "victories": null - } - ] - }, - "userVersion": 1 - }, - "marker": true, - "report": { - "closedRuns": [ - "run-foxtrot" - ], - "droppedReferences": [ - { - "id": "video-delta-1", - "path": "{{OUTSIDE_ROOT}}/Videos/battle-delta-1.20261004-211000.rec0004.mp4", - "reason": "outside_data_root", - "table": "combat_replay_videos" - }, - { - "id": "shot-delta", - "path": "{{OUTSIDE_ROOT}}/Pictures/2026-10-04_21-19-00-000_final_run-run-delta.png", - "reason": "outside_data_root", - "table": "run_screenshots" - } - ], - "evictedReplays": [], - "files": [ - "CombatReplayVideos/battle-alpha-1.20261001-201000.rec0001.mp4", - "CombatReplayVideos/battle-charlie-1.20261003-211000.rec0003.mp4", - "CombatReplays/battle-bravo-1.payload.mpack.gz", - "CombatReplays/battle-echo-1.payload.mpack.gz", - "CombatReplays/battle-foxtrot-1.payload.mpack.gz", - "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png", - "Screenshots/2026-10-03/2026-10-03_21-21-00-000_final_run-run-charlie.png", - "Screenshots/2026-10-05/2026-10-05_21-18-00-000_final_run-run-echo.png" - ], - "importedRuns": [ - "run-bravo", - "run-charlie", - "run-delta", - "run-echo", - "run-echo:bpp:0f1e2d3c4b5a69788796a5b4c3d2e1f0", - "run-foxtrot" - ], - "missingFiles": [], - "skippedRuns": [ - { - "reason": "already_present", - "runId": "run-alpha" - }, - { - "reason": "conflicting_id", - "runId": "run-golf" - } - ] - }, - "status": "imported" -} diff --git a/bazaarplusplus-installer/src-tauri/tests/headless.rs b/bazaarplusplus-installer/src-tauri/tests/headless.rs deleted file mode 100644 index 7a4a569..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/headless.rs +++ /dev/null @@ -1,48 +0,0 @@ -use std::process::Command; - -#[test] -fn headless_help_exits_without_starting_the_desktop_shell() { - let output = Command::new(env!("CARGO_BIN_EXE_bppinstaller")) - .arg("--help") - .output() - .unwrap(); - assert!(output.status.success()); - assert!(String::from_utf8_lossy(&output.stdout).contains("repair --game")); -} - -#[test] -fn invalid_repair_leaves_the_target_untouched_and_returns_failure() { - let game = tempfile::tempdir().unwrap(); - let sentinel = game.path().join("user-history"); - std::fs::write(&sentinel, b"keep").unwrap(); - let output = Command::new(env!("CARGO_BIN_EXE_bppinstaller")) - .args(["repair", "--game"]) - .arg(game.path()) - .args(["--stub", "missing-stub"]) - .output() - .unwrap(); - assert!(!output.status.success()); - assert_eq!(std::fs::read(&sentinel).unwrap(), b"keep"); - assert_eq!(std::fs::read_dir(game.path()).unwrap().count(), 1); -} - -#[cfg(unix)] -#[test] -fn manifest_symlink_cannot_overwrite_game_files() { - let game = tempfile::tempdir().unwrap(); - let evidence = tempfile::tempdir().unwrap(); - let target = game.path().join("libdoorstop.dylib"); - std::fs::write(&target, b"doorstop").unwrap(); - let manifest = evidence.path().join("manifest.json"); - std::os::unix::fs::symlink(&target, &manifest).unwrap(); - let output = Command::new(env!("CARGO_BIN_EXE_bppinstaller")) - .args(["repair", "--game"]) - .arg(game.path()) - .arg("--manifest") - .arg(&manifest) - .output() - .unwrap(); - assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr).contains("regular file")); - assert_eq!(std::fs::read(&target).unwrap(), b"doorstop"); -} diff --git a/bazaarplusplus-installer/src-tauri/tests/trampoline_build_support.rs b/bazaarplusplus-installer/src-tauri/tests/trampoline_build_support.rs deleted file mode 100644 index 7cb2514..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/trampoline_build_support.rs +++ /dev/null @@ -1,38 +0,0 @@ -// `build.rs` is the only caller of the build-time freshness check. -#[allow(dead_code)] -#[path = "../build_support.rs"] -mod build_support; - -#[test] -fn macos_build_version_with_required_minimum_is_accepted() { - let output = r" -Load command 10 - cmd LC_BUILD_VERSION - cmdsize 32 - platform 1 - minos 12.0 - sdk 27.0 -"; - - assert!(build_support::has_macos_trampoline_deployment_target( - output, - build_support::MACOS_TRAMPOLINE_DEPLOYMENT_TARGET - )); -} - -#[test] -fn newer_macos_build_version_is_rejected() { - let output = r" -Load command 10 - cmd LC_BUILD_VERSION - cmdsize 32 - platform 1 - minos 27.0 - sdk 27.0 -"; - - assert!(!build_support::has_macos_trampoline_deployment_target( - output, - build_support::MACOS_TRAMPOLINE_DEPLOYMENT_TARGET - )); -} diff --git a/bazaarplusplus-installer/src-tauri/tests/v5_import_cli.rs b/bazaarplusplus-installer/src-tauri/tests/v5_import_cli.rs deleted file mode 100644 index 01144b0..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/v5_import_cli.rs +++ /dev/null @@ -1,331 +0,0 @@ -//! `bppinstaller import` end to end: each frozen V5 shape (`tests/fixtures/v5-import/`) -//! and a current Data Root that already holds some of its Runs, imported by the -//! built binary. The manifest it writes (outcome, Data Root files, database -//! rows) must equal `tests/goldens/v5-import/.json` byte for byte; -//! `BPP_UPDATE_GOLDENS=1` rewrites the goldens. Failure modes that need an -//! injected game probe or volume run in `src/v5_import/tests_e2e.rs`. - -use std::path::{Path, PathBuf}; -use std::process::Command; - -use rusqlite::Connection; -use sha2::{Digest, Sha256}; - -const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/v5-import"); -const ROWS_COMMON: &str = include_str!("fixtures/v5-import/rows-common.sql"); -const BATTLES_V1: &str = include_str!("fixtures/v5-import/battles-v1.sql"); -const BATTLES_V2_V3: &str = include_str!("fixtures/v5-import/battles-v2-v3.sql"); -const MOD_CONTRACT: &str = include_str!( - "../../../bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json" -); -const MOD_SCHEMA: &str = include_str!( - "../../../bazaarplusplus-mod/src/BazaarPlusPlus.Storage/history-database-v6.schema.sql" -); -const NOW: &str = "2026-10-10T00:00:00Z"; - -struct Case { - name: &'static str, - schema: &'static str, - battles: &'static str, -} - -const V1: Case = Case { - name: "v1", - schema: include_str!("fixtures/v5-import/v1.schema.sql"), - battles: BATTLES_V1, -}; -const V2: Case = Case { - name: "v2", - schema: include_str!("fixtures/v5-import/v2.schema.sql"), - battles: BATTLES_V2_V3, -}; -const V3: Case = Case { - name: "v3", - schema: include_str!("fixtures/v5-import/v3.schema.sql"), - battles: BATTLES_V2_V3, -}; -const V3_UPGRADED: Case = Case { - name: "v3-upgraded-from-v1", - schema: include_str!("fixtures/v5-import/v3-upgraded-from-v1.schema.sql"), - battles: BATTLES_V2_V3, -}; - -struct Game { - _dir: tempfile::TempDir, - root: PathBuf, - game: PathBuf, -} - -impl Game { - fn v5(&self) -> PathBuf { - self.game.join("BazaarPlusPlusV5") - } - - fn v6(&self) -> PathBuf { - self.game.join("BazaarPlusPlusV6") - } -} - -fn copy_tree(source: &Path, target: &Path) { - std::fs::create_dir_all(target).unwrap(); - for entry in std::fs::read_dir(source).unwrap() { - let entry = entry.unwrap(); - let to = target.join(entry.file_name()); - if entry.file_type().unwrap().is_dir() { - copy_tree(&entry.path(), &to); - } else { - std::fs::copy(entry.path(), to).unwrap(); - } - } -} - -fn write(path: &Path, bytes: &[u8]) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, bytes).unwrap(); -} - -/// A game directory with the installed 6.x mod contract and the V5 Data Root -/// sample; `outside/` sits beside it. -fn game(case: &Case) -> Game { - let dir = tempfile::tempdir().unwrap(); - let root = dir.path().canonicalize().unwrap(); - let game = root.join("game"); - copy_tree(&Path::new(FIXTURES).join("game"), &game); - copy_tree(&Path::new(FIXTURES).join("outside"), &root.join("outside")); - if cfg!(target_os = "macos") { - std::fs::create_dir_all(game.join("TheBazaar.app")).unwrap(); - } else if cfg!(windows) { - write(&game.join("TheBazaar.exe"), b"exe"); - } else { - write(&game.join("TheBazaar"), b"exe"); - } - write( - &game.join("BepInEx/plugins/BazaarPlusPlus.history-database.json"), - MOD_CONTRACT.as_bytes(), - ); - let sql_path = |path: PathBuf| path.to_str().unwrap().replace('\'', "''"); - let substitute = |sql: &str| { - sql.replace("{{V5_ROOT}}", &sql_path(game.join("BazaarPlusPlusV5"))) - .replace("{{OUTSIDE_ROOT}}", &sql_path(root.join("outside"))) - }; - let conn = Connection::open(game.join("BazaarPlusPlusV5/bazaarplusplus.db")).unwrap(); - conn.execute_batch(case.schema).unwrap(); - conn.execute_batch(&substitute(ROWS_COMMON)).unwrap(); - conn.execute_batch(&substitute(case.battles)).unwrap(); - drop(conn); - Game { - _dir: dir, - root, - game, - } -} - -/// Every file under `root` with the sha256 of its bytes. -fn tree(root: &Path) -> Vec<(String, String)> { - fn walk(root: &Path, directory: &Path, entries: &mut Vec<(String, String)>) { - for entry in std::fs::read_dir(directory).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { - walk(root, &path, entries); - } else { - let relative = path.strip_prefix(root).unwrap().to_string_lossy(); - let digest: String = Sha256::digest(std::fs::read(&path).unwrap()) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(); - entries.push((relative.replace('\\', "/"), digest)); - } - } - } - let mut entries = Vec::new(); - walk(root, root, &mut entries); - entries.sort(); - entries -} - -struct Outcome { - success: bool, - stderr: String, - manifest: String, -} - -fn import(game: &Game) -> Outcome { - let manifest = game.root.join("manifest.json"); - let output = Command::new(env!("CARGO_BIN_EXE_bppinstaller")) - .args(["import", "--game"]) - .arg(&game.game) - .arg("--manifest") - .arg(&manifest) - .args(["--now", NOW]) - .output() - .unwrap(); - let mut text = std::fs::read_to_string(&manifest).unwrap(); - for (path, placeholder) in [ - (game.v5(), "{{V5_ROOT}}"), - (game.root.join("outside"), "{{OUTSIDE_ROOT}}"), - (game.game.clone(), "{{GAME}}"), - ] { - let raw = path.to_string_lossy(); - let escaped = serde_json::to_string(raw.as_ref()).unwrap(); - text = text - .replace(&escaped[1..escaped.len() - 1], placeholder) - .replace(raw.as_ref(), placeholder); - } - Outcome { - success: output.status.success(), - stderr: String::from_utf8_lossy(&output.stderr).into_owned(), - manifest: text, - } -} - -fn assert_golden(name: &str, actual: &str) { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests/goldens/v5-import") - .join(format!("{name}.json")); - if std::env::var("BPP_UPDATE_GOLDENS").as_deref() == Ok("1") { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(&path, actual).unwrap(); - return; - } - let expected = std::fs::read_to_string(&path).unwrap_or_else(|error| { - panic!( - "read golden {}: {error}; regenerate with BPP_UPDATE_GOLDENS=1", - path.display() - ) - }); - assert!( - expected == actual, - "golden {} differs; review and regenerate with BPP_UPDATE_GOLDENS=1\n--- expected\n{expected}\n--- actual\n{actual}", - path.display() - ); -} - -fn assert_imports_to_golden(case: &Case) { - let game = game(case); - let v5_before = tree(&game.v5()); - - let outcome = import(&game); - - assert!(outcome.success, "{}", outcome.stderr); - assert_golden(case.name, &outcome.manifest); - let mut v5_after = tree(&game.v5()); - v5_after.retain(|(path, _)| path != "imported-to-BazaarPlusPlusV6"); - assert_eq!(v5_after, v5_before, "V5 changed beyond the marker"); -} - -#[test] -fn imports_a_v1_database() { - assert_imports_to_golden(&V1); -} - -#[test] -fn imports_a_v2_database() { - assert_imports_to_golden(&V2); -} - -#[test] -fn imports_a_fresh_v3_database() { - assert_imports_to_golden(&V3); -} - -#[test] -fn imports_a_v3_database_upgraded_from_v1() { - assert_imports_to_golden(&V3_UPGRADED); -} - -/// The game ran the 6.x mod before the import: the current Data Root holds -/// `run-alpha` with its screenshot and replay, and a Run whose battle id is -/// V5's `battle-golf-1`. Both V5 Runs are skipped with all their children; -/// `run-bravo` shares `run-alpha`'s screenshot file, which is already in place. -#[test] -fn merges_into_a_current_database_that_already_holds_runs() { - let game = game(&V3); - std::fs::create_dir_all(game.v6()).unwrap(); - let conn = Connection::open(game.v6().join("bazaarplusplus.db")).unwrap(); - conn.execute_batch(MOD_SCHEMA).unwrap(); - conn.query_row("pragma journal_mode = wal", [], |_| Ok(())) - .unwrap(); - conn.execute_batch( - "insert into runs (run_id, started_at_ms, last_seen_at_ms, status, hero, game_mode, - ended_at_ms, build_channel, upload_policy) - values ('run-alpha', 1790856000000, 1790856904000, 'completed', 'Vanessa', 'Ranked', - 1790856904000, 'Online', 'bundle'), - ('run-v6', 1791504000000, 1791505200000, 'completed', 'Mak', 'Ranked', - 1791505200000, 'Online', 'bundle'); - insert into battles (battle_id, source, run_id, recorded_at_ms, combat_kind, - local_payload_state) - values ('battle-alpha-1', 'LOCAL', 'run-alpha', 1790856600000, 'PVPCombat', 'ready'), - ('battle-golf-1', 'LOCAL', 'run-v6', 1791504600000, 'PVPCombat', 'ready'); - insert into run_screenshots (screenshot_id, run_id, hero_name, capture_source, - is_primary, image_relative_path, captured_at_ms, captured_utc_offset_minutes) - values ('shot-alpha', 'run-alpha', 'Vanessa', 'end_of_run_auto', 1, - '2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png', 1790856904120, 480);", - ) - .unwrap(); - drop(conn); - let shot = "Screenshots/2026-10-01/2026-10-01_20-15-04-120_final_run-run-alpha.png"; - write( - &game.v6().join(shot), - &std::fs::read(game.v5().join(shot)).unwrap(), - ); - for battle in ["battle-alpha-1", "battle-golf-1"] { - let payload = format!("CombatReplays/{battle}.payload.mpack.gz"); - write(&game.v6().join(&payload), b"current payload\n"); - } - - let outcome = import(&game); - - assert!(outcome.success, "{}", outcome.stderr); - assert_golden("v6-overlap", &outcome.manifest); -} - -#[test] -fn a_refused_import_reports_failure_and_changes_nothing() { - let game = game(&V3); - Connection::open(game.v5().join("bazaarplusplus.db")) - .unwrap() - .execute_batch("pragma user_version = 7;") - .unwrap(); - let before = tree(&game.game); - - let outcome = import(&game); - - assert!(!outcome.success); - assert!( - outcome.stderr.contains("v5_schema_unsupported"), - "{}", - outcome.stderr - ); - assert_golden("refused-unknown-user-version", &outcome.manifest); - assert_eq!(tree(&game.game), before); -} - -#[test] -fn an_import_already_done_succeeds_without_changes() { - let game = game(&V3); - assert!(import(&game).success); - let before = tree(&game.game); - - let outcome = import(&game); - - assert!(outcome.success, "{}", outcome.stderr); - assert!(outcome - .manifest - .contains("\"status\": \"already_imported\"")); - assert_eq!(tree(&game.game), before); -} - -#[test] -fn the_manifest_must_be_written_outside_the_game_directory() { - let game = game(&V3); - let output = Command::new(env!("CARGO_BIN_EXE_bppinstaller")) - .args(["import", "--game"]) - .arg(&game.game) - .arg("--manifest") - .arg(game.game.join("manifest.json")) - .output() - .unwrap(); - assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr).contains("outside the game directory")); - assert!(!game.v6().exists()); -} diff --git a/bazaarplusplus-installer/src-tauri/tests/v5_import_fixtures.rs b/bazaarplusplus-installer/src-tauri/tests/v5_import_fixtures.rs deleted file mode 100644 index 8f8d7aa..0000000 --- a/bazaarplusplus-installer/src-tauri/tests/v5_import_fixtures.rs +++ /dev/null @@ -1,651 +0,0 @@ -//! The frozen V5 history databases the V5 import reads (`tests/fixtures/v5-import/`). -//! Each schema fixture must build into a database with its `user_version` and -//! column set, and the seed rows and Data Root sample must agree with each other. -//! README.md beside the fixtures records where each one came from. - -use std::path::{Path, PathBuf}; - -use rusqlite::Connection; -use sha2::{Digest, Sha256}; - -const V1_SCHEMA: &str = include_str!("fixtures/v5-import/v1.schema.sql"); -const V2_SCHEMA: &str = include_str!("fixtures/v5-import/v2.schema.sql"); -const V3_SCHEMA: &str = include_str!("fixtures/v5-import/v3.schema.sql"); -const V3_UPGRADED_SCHEMA: &str = include_str!("fixtures/v5-import/v3-upgraded-from-v1.schema.sql"); -const ROWS_COMMON: &str = include_str!("fixtures/v5-import/rows-common.sql"); -const BATTLES_V1: &str = include_str!("fixtures/v5-import/battles-v1.sql"); -const BATTLES_V2_V3: &str = include_str!("fixtures/v5-import/battles-v2-v3.sql"); - -/// `ShippedColumnShapes[3]` in the mod's `RunLogSchemaColumnShapeTests`: version 3 and -/// version 2 share it. -const V3_COLUMN_SHAPE: &str = "b3458fe8b3a4f5c5"; - -/// Start of the 30-day replay retention window at the fixtures' reference clock, -/// 2026-10-10T00:00:00Z. -const RETENTION_CUTOFF: &str = "2026-09-10"; - -const RUNS: &[&str] = &[ - "run_id", - "started_at_utc", - "last_seen_at_utc", - "status", - "completed", - "hero", - "game_mode", - "seed", - "player_rank", - "player_rating", - "day", - "hour", - "max_health", - "prestige", - "level", - "income", - "gold", - "last_seq", - "ended_at_utc", - "final_day", - "final_hour", - "victories", - "losses", - "final_player_rank", - "final_player_rating", - "final_player_rating_delta", - "reason", - "build_channel", - "player_account_id", - "bundle_screenshot_requested", - "mod_version", -]; -const RUN_EVENTS: &[&str] = &["run_id", "seq", "ts_utc", "kind", "payload_json"]; -const BATTLES_V1_COLUMNS: &[&str] = &[ - "battle_id", - "remote_battle_id", - "uploader_account_id", - "source", - "run_id", - "local_player_account_id", - "recorded_at_utc", - "day", - "hour", - "encounter_id", - "combat_kind", - "player_name", - "player_account_id", - "player_hero", - "player_rank", - "player_rating", - "player_level", - "player_prestige", - "player_income", - "player_gold", - "player_victories", - "player_hand_item_count", - "player_skill_count", - "opponent_name", - "opponent_account_id", - "opponent_hero", - "opponent_rank", - "opponent_rating", - "opponent_level", - "opponent_prestige", - "opponent_victories", - "opponent_hand_item_count", - "opponent_skill_count", - "result", - "winner_combatant_id", - "loser_combatant_id", - "is_final_battle", - "has_local_payload", - "bundle_id", - "download_url", - "download_url_expires_at_ms", - "ghost_replay_state", - "ghost_replay_unavailable_reason", - "deleted_at_utc", -]; -const BATTLES_LIFECYCLE: &[&str] = &["local_payload_state", "local_payload_maintenance_at_utc"]; -const BATTLE_SNAPSHOTS: &[&str] = &[ - "battle_id", - "player_hand_json", - "player_skills_json", - "opponent_hand_json", - "opponent_skills_json", -]; -const RUN_SCREENSHOTS: &[&str] = &[ - "screenshot_id", - "run_id", - "hero_name", - "battle_id", - "capture_source", - "is_primary", - "image_relative_path", - "captured_at_local", - "captured_at_utc", - "day", - "player_rank", - "player_rating", - "player_position", - "victories_at_capture", - "build_channel", -]; -const VIDEOS_V1_COLUMNS: &[&str] = &[ - "video_id", - "battle_id", - "source", - "video_relative_path", - "width", - "height", - "fps", - "codec", - "crf", - "preset", - "started_at_utc", - "ended_at_utc", - "duration_ms", - "captured_frames", - "dropped_frames", - "file_size_bytes", - "status", - "error", -]; -const VIDEOS_LIFECYCLE: &[&str] = &[ - "attachment_state", - "file_state", - "detached_at_utc", - "missing_at_utc", - "last_reconciled_at_utc", -]; -const BUNDLE_SEAL_JOBS: &[&str] = &[ - "run_id", - "state", - "player_account_id", - "screenshot_requested", - "screenshot_state", - "input_deadline_at_utc", - "bundle_id", - "created_at_ms", - "attempts", - "last_attempt_at_utc", - "last_error_code", - "last_error_detail", -]; -const BUNDLE_OUTBOX: &[&str] = &[ - "bundle_id", - "run_id", - "file_name", - "content_sha256_hex", - "content_digest", - "total_bytes", - "has_screenshot", - "sealed_at_utc", - "status", - "attempts", - "last_attempt_at_utc", - "next_attempt_at_utc", - "failed_at_utc", - "last_error_code", - "last_error_detail", - "server_request_id", - "server_outcome", - "uploaded_at_utc", -]; - -struct Fixture { - name: &'static str, - schema: &'static str, - battles: &'static str, - user_version: i64, - lifecycle_columns: bool, -} - -const FIXTURES: &[Fixture] = &[ - Fixture { - name: "v1", - schema: V1_SCHEMA, - battles: BATTLES_V1, - user_version: 1, - lifecycle_columns: false, - }, - Fixture { - name: "v2", - schema: V2_SCHEMA, - battles: BATTLES_V2_V3, - user_version: 2, - lifecycle_columns: true, - }, - Fixture { - name: "v3", - schema: V3_SCHEMA, - battles: BATTLES_V2_V3, - user_version: 3, - lifecycle_columns: true, - }, - Fixture { - name: "v3-upgraded-from-v1", - schema: V3_UPGRADED_SCHEMA, - battles: BATTLES_V2_V3, - user_version: 3, - lifecycle_columns: true, - }, -]; - -fn fixture_dir() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/v5-import") -} - -fn v5_root() -> PathBuf { - fixture_dir().join("game/BazaarPlusPlusV5") -} - -fn outside_root() -> PathBuf { - fixture_dir().join("outside") -} - -fn build(schema: &str) -> Connection { - let conn = Connection::open_in_memory().unwrap(); - conn.execute_batch(schema).unwrap(); - conn -} - -/// Loads the seed rows with foreign keys on, as the mod opens the database. -fn seed(conn: &Connection, battles: &str) { - let sql_path = |path: PathBuf| path.to_str().unwrap().replace('\'', "''"); - let substitute = |sql: &str| { - sql.replace("{{V5_ROOT}}", &sql_path(v5_root())) - .replace("{{OUTSIDE_ROOT}}", &sql_path(outside_root())) - }; - conn.execute_batch("pragma foreign_keys = on;").unwrap(); - conn.execute_batch(&substitute(ROWS_COMMON)).unwrap(); - conn.execute_batch(&substitute(battles)).unwrap(); - let violations: i64 = conn - .query_row("select count(*) from pragma_foreign_key_check", [], |row| { - row.get(0) - }) - .unwrap(); - assert_eq!(violations, 0); -} - -fn user_version(conn: &Connection) -> i64 { - conn.query_row("pragma user_version", [], |row| row.get(0)) - .unwrap() -} - -fn tables(conn: &Connection) -> Vec { - strings( - conn, - "select name from sqlite_master where type = 'table' and name not like 'sqlite_%' \ - order by name", - ) -} - -fn columns(conn: &Connection, table: &str) -> Vec { - strings( - conn, - &format!("select name from pragma_table_info('{table}') order by cid"), - ) -} - -fn strings(conn: &Connection, sql: &str) -> Vec { - let mut statement = conn.prepare(sql).unwrap(); - statement - .query_map([], |row| row.get(0)) - .unwrap() - .collect::>() - .unwrap() -} - -fn count(conn: &Connection, sql: &str) -> i64 { - conn.query_row(sql, [], |row| row.get(0)).unwrap() -} - -fn table_sql(conn: &Connection, table: &str) -> String { - conn.query_row( - "select sql from sqlite_master where type = 'table' and name = ?1", - [table], - |row| row.get(0), - ) - .unwrap() -} - -/// The mod's `RunLogSchemaColumnShapeTests.FreshColumnShape` over an already built -/// database: name, declared type, NOT NULL, default, and primary-key position of every -/// column, table by table, hashed with SHA-256 and cut to 16 hex digits. -fn column_shape(conn: &Connection) -> String { - let mut shape = String::new(); - for table in tables(conn) { - shape.push_str(&table); - shape.push('('); - let mut statement = conn - .prepare(&format!("pragma table_info({table})")) - .unwrap(); - let mut rows = statement.query([]).unwrap(); - while let Some(row) = rows.next().unwrap() { - let name: String = row.get(1).unwrap(); - let declared: String = row.get(2).unwrap(); - let not_null: i64 = row.get(3).unwrap(); - let default: Option = row.get(4).unwrap(); - let primary_key: i64 = row.get(5).unwrap(); - shape.push_str(&format!( - "{name} {declared} {not_null} {} {primary_key};", - default.as_deref().unwrap_or("-") - )); - } - shape.push_str(")\n"); - } - Sha256::digest(shape.as_bytes())[..8] - .iter() - .map(|byte| format!("{byte:02x}")) - .collect() -} - -fn concat(base: &[&str], extra: &[&str]) -> Vec { - base.iter().chain(extra).map(ToString::to_string).collect() -} - -#[test] -fn every_fixture_builds_with_its_user_version_and_columns() { - for fixture in FIXTURES { - let conn = build(fixture.schema); - assert_eq!( - user_version(&conn), - fixture.user_version, - "{}", - fixture.name - ); - assert_eq!( - tables(&conn), - [ - "battle_snapshots", - "battles", - "bundle_outbox", - "bundle_seal_jobs", - "combat_replay_videos", - "run_events", - "run_screenshots", - "runs", - ], - "{}", - fixture.name - ); - let (battles, videos): (&[&str], &[&str]) = if fixture.lifecycle_columns { - (BATTLES_LIFECYCLE, VIDEOS_LIFECYCLE) - } else { - (&[], &[]) - }; - for (table, expected) in [ - ("runs", concat(RUNS, &[])), - ("run_events", concat(RUN_EVENTS, &[])), - ("battles", concat(BATTLES_V1_COLUMNS, battles)), - ("battle_snapshots", concat(BATTLE_SNAPSHOTS, &[])), - ("run_screenshots", concat(RUN_SCREENSHOTS, &[])), - ("combat_replay_videos", concat(VIDEOS_V1_COLUMNS, videos)), - ("bundle_seal_jobs", concat(BUNDLE_SEAL_JOBS, &[])), - ("bundle_outbox", concat(BUNDLE_OUTBOX, &[])), - ] { - assert_eq!(columns(&conn, table), expected, "{} {table}", fixture.name); - } - } -} - -#[test] -fn v2_and_both_v3_shapes_carry_the_shipped_version_3_column_shape() { - for schema in [V2_SCHEMA, V3_SCHEMA, V3_UPGRADED_SCHEMA] { - assert_eq!(column_shape(&build(schema)), V3_COLUMN_SHAPE); - } - assert_ne!(column_shape(&build(V1_SCHEMA)), V3_COLUMN_SHAPE); -} - -#[test] -fn upgraded_v3_differs_from_fresh_v3_only_in_its_table_definitions() { - let fresh = build(V3_SCHEMA); - let upgraded = build(V3_UPGRADED_SCHEMA); - - // ALTER TABLE ADD COLUMN appends each lifecycle column after the last v1 column, - // which is where a fresh v3 declares it, so the column order is the same. - for table in tables(&fresh) { - assert_eq!( - columns(&fresh, &table), - columns(&upgraded, &table), - "{table}" - ); - } - - // Indexes and triggers are identical. - let others = "select type, name, sql from sqlite_master \ - where type <> 'table' and sql is not null order by type, name"; - let dump = |conn: &Connection| -> Vec<(String, String, String)> { - let mut statement = conn.prepare(others).unwrap(); - statement - .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))) - .unwrap() - .collect::>() - .unwrap() - }; - assert_eq!(dump(&fresh), dump(&upgraded)); - - // The table definitions differ: ALTER cannot add the table-level CHECKs a fresh v3 - // declares on the lifecycle columns, and appends the new definitions on one line. - let lifecycle_check = "(source <> 'LOCAL' AND local_payload_state IS NULL)"; - let video_checks = [ - "CHECK (attachment_state IN ('attached', 'detached'))", - "CHECK (file_state IN ('pending', 'present', 'missing', 'deleted'))", - ]; - let fresh_battles = table_sql(&fresh, "battles"); - let upgraded_battles = table_sql(&upgraded, "battles"); - assert!(fresh_battles.contains(lifecycle_check)); - assert!(!upgraded_battles.contains(lifecycle_check)); - assert!(upgraded_battles.contains( - "deleted_at_utc TEXT NULL, local_payload_state TEXT NULL, \ - local_payload_maintenance_at_utc TEXT NULL," - )); - let fresh_videos = table_sql(&fresh, "combat_replay_videos"); - let upgraded_videos = table_sql(&upgraded, "combat_replay_videos"); - for check in video_checks { - assert!(fresh_videos.contains(check), "{check}"); - assert!(!upgraded_videos.contains(check), "{check}"); - } - for table in tables(&fresh) { - let differs = table_sql(&fresh, &table) != table_sql(&upgraded, &table); - assert_eq!( - differs, - table == "battles" || table == "combat_replay_videos", - "{table}" - ); - } - - // Only the upgraded shape stores a video state outside the CHECK lists. Battles stay - // guarded in both by the lifecycle triggers. - let invalid_video = "insert into combat_replay_videos ( - video_id, battle_id, source, video_relative_path, width, height, fps, codec, - started_at_utc, status, attachment_state, file_state - ) values ('v', 'b', 'LocalSaved', 'v.mp4', 1, 1, 1, 'h264', 't', 'COMPLETED', - 'orphaned', 'unknown')"; - let error = fresh.execute(invalid_video, []).unwrap_err().to_string(); - assert!(error.contains("CHECK constraint failed"), "{error}"); - upgraded.execute(invalid_video, []).unwrap(); - let invalid_battle = "insert into battles ( - battle_id, source, run_id, recorded_at_utc, combat_kind, has_local_payload, - local_payload_state - ) values ('b', 'LOCAL', null, 't', 'PVPCombat', 0, 'ready')"; - for conn in [&fresh, &upgraded] { - let error = conn.execute(invalid_battle, []).unwrap_err().to_string(); - assert!( - error.contains("invalid local payload lifecycle state"), - "{error}" - ); - } -} - -#[test] -fn seed_rows_load_into_every_fixture() { - for fixture in FIXTURES { - let conn = build(fixture.schema); - seed(&conn, fixture.battles); - for (table, rows) in [ - ("runs", 8), - ("run_events", 5), - ("battles", 9), - ("battle_snapshots", 1), - ("run_screenshots", 5), - ("combat_replay_videos", 4), - ("bundle_seal_jobs", 2), - ("bundle_outbox", 2), - ] { - assert_eq!( - count(&conn, &format!("select count(*) from {table}")), - rows, - "{} {table}", - fixture.name - ); - } - } -} - -/// Every case the import must handle is present in the rows, and every file the rows -/// name exists in the Data Root sample (or outside it, where the row says so). -#[test] -fn seed_rows_cover_the_import_cases_and_match_the_data_root_sample() { - let conn = build(V3_SCHEMA); - seed(&conn, BATTLES_V2_V3); - let root = v5_root(); - let outside = outside_root(); - - // Several runs share one screenshot file and one video file. - assert_eq!( - count( - &conn, - "select count(*) from (select image_relative_path from run_screenshots \ - group by 1 having count(distinct run_id) > 1)" - ), - 1 - ); - assert_eq!( - count( - &conn, - "select count(*) from (select v.video_relative_path from combat_replay_videos v \ - join battles b using (battle_id) group by 1 having count(distinct b.run_id) > 1)" - ), - 1 - ); - - // Every screenshot and video resolves to a sample file; absolute paths point once - // inside the V5 root and once outside it, for images and for videos alike. - for (sql, directory) in [ - ( - "select image_relative_path from run_screenshots", - "Screenshots", - ), - ( - "select video_relative_path from combat_replay_videos", - "CombatReplayVideos", - ), - ] { - let paths = strings(&conn, sql); - let mut inside = 0; - let mut beyond = 0; - for raw in &paths { - let path = PathBuf::from(raw); - let resolved = if path.is_absolute() { - if path.starts_with(&root) { - inside += 1; - } else { - assert!(path.starts_with(&outside), "{raw}"); - beyond += 1; - } - path - } else { - raw.split(['/', '\\']) - .fold(root.join(directory), |dir, part| dir.join(part)) - }; - assert!(resolved.is_file(), "{raw} -> {}", resolved.display()); - } - assert_eq!((inside, beyond), (1, 1), "{sql}"); - } - - // A game run id and its ':bpp:' collision id. - assert_eq!( - count( - &conn, - "select count(*) from runs c join runs r \ - on substr(c.run_id, 1, length(r.run_id) + 5) = r.run_id || ':bpp:' \ - where length(c.run_id) = length(r.run_id) + 37" - ), - 1 - ); - assert_eq!( - count(&conn, "select count(*) from runs where completed = 0"), - 1 - ); - assert_eq!( - count(&conn, "select count(*) from runs where hero = 'hero8'"), - 1 - ); - - // Ghost battles: one downloaded, one only listed remotely. - assert_eq!( - strings( - &conn, - "select ghost_replay_state from battles where source = 'GHOST' order by 1" - ), - ["local_ready", "remote_available"] - ); - for battle_id in strings( - &conn, - "select battle_id from battles where ghost_replay_state = 'local_ready'", - ) { - let payload = root - .join("GhostBattlePayloads") - .join(format!("{battle_id}.ghost.mpack.gz")); - assert!(payload.is_file(), "{}", payload.display()); - } - - // Outbox: one uploaded, one pending whose Bundle file is still queued. - assert_eq!( - strings(&conn, "select status from bundle_outbox order by 1"), - ["pending", "uploaded"] - ); - for file_name in strings( - &conn, - "select file_name from bundle_outbox where status = 'pending'", - ) { - assert!(root.join("BundleOutbox").join(&file_name).is_file()); - } - - // Seal jobs: one deadline in the old ISO "o" text, one in SQLite datetime() text. - assert_eq!( - strings( - &conn, - "select input_deadline_at_utc from bundle_seal_jobs order by run_id" - ), - ["2026-10-05T13:20:00.0000000+00:00", "2026-10-05 14:18:00"] - ); - - // Local replay payloads on disk, inside and outside the retention window. - let ready = strings( - &conn, - "select battle_id from battles where source = 'LOCAL' and has_local_payload = 1", - ); - for battle_id in &ready { - let payload = root - .join("CombatReplays") - .join(format!("{battle_id}.payload.mpack.gz")); - assert!(payload.is_file(), "{}", payload.display()); - } - let before_cutoff = format!( - "select count(*) from battles where source = 'LOCAL' and has_local_payload = 1 \ - and recorded_at_utc < '{RETENTION_CUTOFF}'" - ); - assert_eq!(count(&conn, &before_cutoff), 1); - assert!(ready.len() > 1); - - // Remote caches the mod keeps in the Data Root. - for cache in [ - "builds.json", - "supporter-list.json", - "voice-lines.json", - "EncounterPreview/preview-plans.json", - ] { - assert!(root.join(cache).is_file(), "{cache}"); - } -} diff --git a/bazaarplusplus-installer/src-tauri/trampoline/bpp_launcher.c b/bazaarplusplus-installer/src-tauri/trampoline/bpp_launcher.c deleted file mode 100644 index f98fac8..0000000 --- a/bazaarplusplus-installer/src-tauri/trampoline/bpp_launcher.c +++ /dev/null @@ -1,53 +0,0 @@ -// BazaarPlusPlus macOS launch trampoline. -// -// This is the only macOS launch bootstrap. It is installed as the game bundle's -// CFBundleExecutable. The real Unity bootstrap is preserved beside it as -// ".orig" and re-signed with JIT entitlements by the installer. The stub -// configures Doorstop, preserves Steam's injected libraries, and execs Unity. -#include -#include -#include -#include -#include -#include -#include -#include - -int main(int argc, char **argv) { - char raw[PATH_MAX]; uint32_t sz = sizeof(raw); - if (_NSGetExecutablePath(raw, &sz) != 0) { fprintf(stderr, "bpp: exe path too long\n"); return 70; } - char exe[PATH_MAX]; - if (!realpath(raw, exe)) { strncpy(exe, raw, sizeof(exe)); exe[sizeof(exe)-1]=0; } - char exe_copy[PATH_MAX]; strncpy(exe_copy, exe, sizeof(exe_copy)); exe_copy[sizeof(exe_copy)-1]=0; - char macos_dir[PATH_MAX]; strncpy(macos_dir, dirname(exe_copy), sizeof(macos_dir)); macos_dir[sizeof(macos_dir)-1]=0; - char gd_raw[PATH_MAX]; snprintf(gd_raw, sizeof(gd_raw), "%s/../../..", macos_dir); - char game_dir[PATH_MAX]; - if (!realpath(gd_raw, game_dir)) { fprintf(stderr, "bpp: cannot resolve game dir from %s\n", gd_raw); return 71; } - - char buf[PATH_MAX*2]; - setenv("DOORSTOP_ENABLED", "1", 1); - snprintf(buf, sizeof(buf), "%s/BepInEx/core/BepInEx.Preloader.dll", game_dir); - setenv("DOORSTOP_TARGET_ASSEMBLY", buf, 1); - setenv("DOORSTOP_BOOT_CONFIG_OVERRIDE", "", 1); - setenv("DOORSTOP_IGNORE_DISABLED_ENV", "0", 1); - setenv("DOORSTOP_MONO_DLL_SEARCH_PATH_OVERRIDE", "", 1); - setenv("DOORSTOP_MONO_DEBUG_ENABLED", "0", 1); - setenv("DOORSTOP_MONO_DEBUG_ADDRESS", "127.0.0.1:10000", 1); - setenv("DOORSTOP_MONO_DEBUG_SUSPEND", "0", 1); - setenv("DOORSTOP_CLR_RUNTIME_CORECLR_PATH", ".dylib", 1); - setenv("DOORSTOP_CLR_CORLIB_DIR", "", 1); - { const char *cur = getenv("DYLD_LIBRARY_PATH"); - if (cur && cur[0]) snprintf(buf, sizeof(buf), "%s:%s", game_dir, cur); else snprintf(buf, sizeof(buf), "%s", game_dir); - setenv("DYLD_LIBRARY_PATH", buf, 1); } - { char dylib[PATH_MAX]; snprintf(dylib, sizeof(dylib), "%s/libdoorstop.dylib", game_dir); - const char *cur = getenv("DYLD_INSERT_LIBRARIES"); - if (cur && cur[0]) snprintf(buf, sizeof(buf), "%s:%s", dylib, cur); else snprintf(buf, sizeof(buf), "%s", dylib); - setenv("DYLD_INSERT_LIBRARIES", buf, 1); } - - // Derive the preserved binary name from CFBundleExecutable at runtime. - char base_copy[PATH_MAX]; strncpy(base_copy, exe, sizeof(base_copy)); base_copy[sizeof(base_copy)-1]=0; - char real[PATH_MAX]; snprintf(real, sizeof(real), "%s/%s.orig", macos_dir, basename(base_copy)); - execv(real, argv); - fprintf(stderr, "bpp: execv(%s) failed: %s (run installer Repair)\n", real, strerror(errno)); - return 127; -} diff --git a/bazaarplusplus-installer/src/App.tsx b/bazaarplusplus-installer/src/App.tsx deleted file mode 100644 index 502d626..0000000 --- a/bazaarplusplus-installer/src/App.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'; -import GlobalShell from './layouts/GlobalShell'; -import About from './pages/About'; -import History from './pages/History'; -import Install from './pages/Install'; -import RunDetail from './pages/RunDetail'; -import Stream from './pages/Stream'; - -/** The route tree without a router, so it also renders under a MemoryRouter. */ -export function AppRoutes() { - return ( - - }> - } /> - } /> - } /> - } /> - } /> - } /> - - - ); -} - -export default function App() { - return ( - - - - ); -} diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/about.bootstrap-failed.html b/bazaarplusplus-installer/src/__shell_snapshots__/about.bootstrap-failed.html deleted file mode 100644 index 29171e5..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/about.bootstrap-failed.html +++ /dev/null @@ -1,282 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

关于

-
- -
-
- -
-

BazaarPlusPlus

-

The Bazaar 数据增强与分析工具

-
- -GitHub - -
-
-应用 -v«version» - - -插件 -不可用 - - -
-
-
-

致谢

-
-
-

贡献者

- -
-
-

数据与灵感

-
    -
  • -BazaarDB -GAME DATA SOURCE -
  • -
  • -BPP Players -COMMUNITY RUN DATA -
  • -
  • -BazaarHelper -INSPIRATION -
  • -
  • -BazaarPlannerMod -INSPIRATION -
  • -
-
-
-
-
-开源许可 - -
    -
  • -BepInEx -LGPL-2.1 -
  • -
  • -React -MIT -
  • -
  • -Tauri -MIT -
  • -
  • -Tailwind CSS -MIT -
  • -
-
-
-Fable 5 认证 -
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/about.current.html b/bazaarplusplus-installer/src/__shell_snapshots__/about.current.html deleted file mode 100644 index 56ef4ef..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/about.current.html +++ /dev/null @@ -1,268 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

关于

-
-
- -
-
-

当前为浏览器预览,显示随应用打包的备用数据。

-
-
-
-
-
- -
-

BazaarPlusPlus

-

The Bazaar 数据增强与分析工具

-
- -GitHub - -
-
-应用 -v1.2.3 - - -插件 -v1.2.3 - - -
-
-
-

致谢

-
-
-

贡献者

- -
-
-

数据与灵感

-
    -
  • -BazaarDB -GAME DATA SOURCE -
  • -
  • -BPP Players -COMMUNITY RUN DATA -
  • -
  • -BazaarHelper -INSPIRATION -
  • -
  • -BazaarPlannerMod -INSPIRATION -
  • -
-
-
-
-
-开源许可 - -
    -
  • -BepInEx -LGPL-2.1 -
  • -
  • -React -MIT -
  • -
  • -Tauri -MIT -
  • -
  • -Tailwind CSS -MIT -
  • -
-
-
-Fable 5 认证 -
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/about.loading.html b/bazaarplusplus-installer/src/__shell_snapshots__/about.loading.html deleted file mode 100644 index 22af3aa..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/about.loading.html +++ /dev/null @@ -1,268 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

关于

-
-
- -
-
-

正在获取本机应用信息,暂时显示随应用打包的备用数据。

-
-
-
-
-
- -
-

BazaarPlusPlus

-

The Bazaar 数据增强与分析工具

-
- -GitHub - -
-
-应用 -v«version» - - -插件 -不可用 - - -
-
-
-

致谢

-
-
-

贡献者

- -
-
-

数据与灵感

-
    -
  • -BazaarDB -GAME DATA SOURCE -
  • -
  • -BPP Players -COMMUNITY RUN DATA -
  • -
  • -BazaarHelper -INSPIRATION -
  • -
  • -BazaarPlannerMod -INSPIRATION -
  • -
-
-
-
-
-开源许可 - -
    -
  • -BepInEx -LGPL-2.1 -
  • -
  • -React -MIT -
  • -
  • -Tauri -MIT -
  • -
  • -Tailwind CSS -MIT -
  • -
-
-
-Fable 5 认证 -
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/about.update-available.html b/bazaarplusplus-installer/src/__shell_snapshots__/about.update-available.html deleted file mode 100644 index 9a17a93..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/about.update-available.html +++ /dev/null @@ -1,283 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

关于

-
-
-
- -
-

BazaarPlusPlus

-

The Bazaar 数据增强与分析工具

-
- -GitHub - -
-
-应用 -v1.2.3 - - -插件 -v1.2.3 - - -
-
-
-

致谢

-
-
-

贡献者

- -
-
-

数据与灵感

-
    -
  • -BazaarDB -GAME DATA SOURCE -
  • -
  • -BPP Players -COMMUNITY RUN DATA -
  • -
  • -BazaarHelper -INSPIRATION -
  • -
  • -BazaarPlannerMod -INSPIRATION -
  • -
-
-
-
-
-开源许可 - -
    -
  • -BepInEx -LGPL-2.1 -
  • -
  • -React -MIT -
  • -
  • -Tauri -MIT -
  • -
  • -Tailwind CSS -MIT -
  • -
-
-
-Fable 5 认证 -
-
-
-
-
-
- -
-
- -
-

发现新版本

-
-
-
-

BazaarPlusPlus 9.9.0 已可用。

-
-

更新内容

-

Fixture release notes.

-
-
- -
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/history.empty.html b/bazaarplusplus-installer/src/__shell_snapshots__/history.empty.html deleted file mode 100644 index d9eaf72..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/history.empty.html +++ /dev/null @@ -1,239 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

战绩

-
- -
-
-
-
-
-
-
对局数
-
-0 -
-
-
-
视频数
-
-0 -
-
-
-
十胜达成率
-
-— -尚无已完成对局 -
-
-
- -
- -
-
-
-
- -

暂无本地战绩

-

完成一局 The Bazaar 对局后,战绩会自动显示在这里。你也可以刷新,或前往安装页检查游戏目录。

-
- -检查游戏目录 -
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/history.multi-page.html b/bazaarplusplus-installer/src/__shell_snapshots__/history.multi-page.html deleted file mode 100644 index dc15593..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/history.multi-page.html +++ /dev/null @@ -1,1867 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

战绩

-
- -
-
-
-
-
-
-
对局数
-
-120 -
-
-
-
视频数
-
-7 -
-
-
-
十胜达成率
-
-67% -十胜对局 / 已完成对局 -
-
-
- -
- -
-
- -
-
-

缩略图服务无法启动,本地端口可能被占用;战绩仍可正常浏览。

-
-
-
-
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1502+10 - -黄金 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -马克 - - - - - -4 -胜场 -青铜胜利 - - -— -段位分 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -斯黛拉 - - - - - -10 -胜场 -黄金胜利 - - -1504+8 - -黄金 -天数 12 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -朱尔斯 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -凡妮莎 - - - - - -4 -胜场 -青铜胜利 - - -1506+6 - -黄金 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1508+4 - -黄金 -天数 12 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -马克 - - - - - -4 -胜场 -青铜胜利 - - -— -段位分 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -斯黛拉 - - - - - -10 -胜场 -黄金胜利 - - -1510+2 - -黄金 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -朱尔斯 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -凡妮莎 - - - - - -4 -胜场 -青铜胜利 - - -1512±0 - -黄金 -天数 8 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1514-2 - -黄金 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -马克 - - - - - -4 -胜场 -青铜胜利 - - -— -段位分 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -斯黛拉 - - - - - -10 -胜场 -黄金胜利 - - -1516-4 - -黄金 -天数 12 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -朱尔斯 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -凡妮莎 - - - - - -4 -胜场 -青铜胜利 - - -1518-6 - -黄金 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1520-8 - -黄金 -天数 12 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -马克 - - - - - -4 -胜场 -青铜胜利 - - -— -段位分 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -斯黛拉 - - - - - -10 -胜场 -黄金胜利 - - -1522-10 - -黄金 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -朱尔斯 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -凡妮莎 - - - - - -4 -胜场 -青铜胜利 - - -1524-12 - -黄金 -天数 8 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1526-14 - -黄金 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -马克 - - - - - -4 -胜场 -青铜胜利 - - -— -段位分 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -斯黛拉 - - - - - -10 -胜场 -黄金胜利 - - -1528-16 - -黄金 -天数 12 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -朱尔斯 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -凡妮莎 - - - - - -4 -胜场 -青铜胜利 - - -1530-18 - -黄金 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1532-20 - -黄金 -天数 12 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -马克 - - - - - -4 -胜场 -青铜胜利 - - -— -段位分 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -斯黛拉 - - - - - -10 -胜场 -黄金胜利 - - -1534-22 - -黄金 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -朱尔斯 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -凡妮莎 - - - - - -4 -胜场 -青铜胜利 - - -1536-24 - -黄金 -天数 8 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1538-26 - -黄金 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -马克 - - - - - -4 -胜场 -青铜胜利 - - -— -段位分 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -斯黛拉 - - - - - -10 -胜场 -黄金胜利 - - -1540-28 - -黄金 -天数 12 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -朱尔斯 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -凡妮莎 - - - - - -4 -胜场 -青铜胜利 - - -1542-30 - -黄金 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1544-32 - -黄金 -天数 12 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -马克 - - - - - -4 -胜场 -青铜胜利 - - -— -段位分 -天数 8 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -斯黛拉 - - - - - -10 -胜场 -黄金胜利 - - -1546-34 - -黄金 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -朱尔斯 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -凡妮莎 - - - - - -4 -胜场 -青铜胜利 - - -1548-36 - -黄金 -天数 8 - - - - -普通 - - -
- -
- - -暂无截图 - -
- - -皮格马利翁 - - - - - -10 -胜场 -黄金胜利 - - -— -段位分 -天数 12 - - - - -排位 - - -
- -
- - -暂无截图 - -
- - -杜利 - - - - - -10 -胜场 -黄金胜利 - - -1550-38 - -黄金 -天数 12 - - - - -排位 - - -
-
- -
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/history.read-failed.html b/bazaarplusplus-installer/src/__shell_snapshots__/history.read-failed.html deleted file mode 100644 index f9a8d0c..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/history.read-failed.html +++ /dev/null @@ -1,169 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

战绩

-
- -
-
- -
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/history.unavailable-v5-import.html b/bazaarplusplus-installer/src/__shell_snapshots__/history.unavailable-v5-import.html deleted file mode 100644 index 8c9ded9..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/history.unavailable-v5-import.html +++ /dev/null @@ -1,164 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

战绩

-
- -
-
- -
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/install.detection-failed.html b/bazaarplusplus-installer/src/__shell_snapshots__/install.detection-failed.html deleted file mode 100644 index b20c457..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/install.detection-failed.html +++ /dev/null @@ -1,164 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

安装

-
- -
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/install.game-missing.html b/bazaarplusplus-installer/src/__shell_snapshots__/install.game-missing.html deleted file mode 100644 index dd2ddc8..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/install.game-missing.html +++ /dev/null @@ -1,219 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

安装

-
-
-
- -
-

BazaarPlusPlus未安装 -

-

选择游戏目录后即可安装插件

-
- -
-
-游戏目录 -未选择 The Bazaar 游戏目录 - - - - -应用版本 -1.2.3开发版 - - - -
-
-
- -
-
-
    -
  • 未找到有效的 The Bazaar 游戏目录,请选择游戏目录。
  • -
-
-
-
-
- - -高级操作 -卸载插件、重置 BepInEx 或删除本地数据 - - - -
-
-卸载 -移除所有组件 -
- -
-
-
-删除 BepInEx 文件夹 -重置插件环境 -
- -
-
-
-删除本地数据 -删除本地数据库、截图与回放视频 -
- -
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/install.installable.html b/bazaarplusplus-installer/src/__shell_snapshots__/install.installable.html deleted file mode 100644 index 5398f33..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/install.installable.html +++ /dev/null @@ -1,206 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

安装

-
-
-
- -
-

BazaarPlusPlus未安装 -

-

选择游戏目录后即可安装插件

-
- -
-
-游戏目录 -/Games/The Bazaar - - - - -应用版本 -1.2.3开发版 - - - -
-
-
- - -高级操作 -卸载插件、重置 BepInEx 或删除本地数据 - - - -
-
-卸载 -移除所有组件 -
- -
-
-
-删除 BepInEx 文件夹 -重置插件环境 -
- -
-
-
-暂无本地数据 -当前没有可删除的本地数据 -
- -
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/install.installed.html b/bazaarplusplus-installer/src/__shell_snapshots__/install.installed.html deleted file mode 100644 index b6afa8c..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/install.installed.html +++ /dev/null @@ -1,206 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

安装

-
-
-
- -
-

BazaarPlusPlus已安装 -

-

所有组件运行正常

-
- -
-
-游戏目录 -/Games/The Bazaar - - - - -应用版本 -1.2.3开发版 - - - -
-
-
- - -高级操作 -卸载插件、重置 BepInEx 或删除本地数据 - - - -
-
-卸载 -移除所有组件 -
- -
-
-
-删除 BepInEx 文件夹 -重置插件环境 -
- -
-
-
-删除本地数据 -删除本地数据库、截图与回放视频 -
- -
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/install.legacy-roots.html b/bazaarplusplus-installer/src/__shell_snapshots__/install.legacy-roots.html deleted file mode 100644 index 619ec8b..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/install.legacy-roots.html +++ /dev/null @@ -1,250 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

安装

-
-
-
- -
-

BazaarPlusPlus已安装 -

-

所有组件运行正常

-
- -
-
-游戏目录 -/Games/The Bazaar - - - - -应用版本 -1.2.3开发版 - - - -
-
-
-
- - -旧版本数据 -早期版本写入游戏目录的数据文件夹。当前版本不再读取它们,只有在你确认后才会删除。 - -
-
-
- -
-
已安装的 BazaarPlusPlus 仍在写入旧的数据文件夹。请重新安装,让它改用 BazaarPlusPlusV6。
-
-
-
-
-
-BazaarPlusPlus -512 KB,3 个文件 -
- -
-
-
-BazaarPlusPlusV4 -12 MB,40 个文件 -
- -
-
-
-BazaarPlusPlusV5 -1.5 GB,1200 个文件 -其中 12 个文件与其他位置共用磁盘空间,删除后实际释放的空间可能更少。 -有 1 个项目无法读取,未计入大小。 -
- -
-
-
- - -高级操作 -卸载插件、重置 BepInEx 或删除本地数据 - - - -
-
-卸载 -移除所有组件 -
- -
-
-
-删除 BepInEx 文件夹 -重置插件环境 -
- -
-
-
-删除本地数据 -删除本地数据库、截图与回放视频 -
- -
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/install.v5-import.html b/bazaarplusplus-installer/src/__shell_snapshots__/install.v5-import.html deleted file mode 100644 index 6211d75..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/install.v5-import.html +++ /dev/null @@ -1,232 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

安装

-
-
-
- -
-

BazaarPlusPlus已安装 -

-

所有组件运行正常

-
- -
-
-游戏目录 -/Games/The Bazaar - - - - -应用版本 -1.2.3开发版 - - - -
-
-
-
- - -旧版本数据 -早期版本写入游戏目录的数据文件夹。当前版本不再读取它们,只有在你确认后才会删除。 - -
-
- -
-导入 V5 历史记录 -把 BazaarPlusPlusV5 中的对局、截图和回放导入 BazaarPlusPlusV6,只需一次。导入的对局只显示在本地战绩中,不会上传;BazaarPlusPlusV5 保持不变。 -
- -
-
-
-BazaarPlusPlusV5 -1.5 GB,1200 个文件 -
- -
-
-
- - -高级操作 -卸载插件、重置 BepInEx 或删除本地数据 - - - -
-
-卸载 -移除所有组件 -
- -
-
-
-删除 BepInEx 文件夹 -重置插件环境 -
- -
-
-
-删除本地数据 -删除本地数据库、截图与回放视频 -
- -
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.loaded.html b/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.loaded.html deleted file mode 100644 index dc32260..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.loaded.html +++ /dev/null @@ -1,247 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
- -

凡妮莎

-排位 · 已完成 -
- -
-
-
-
-黄金胜利 -
-玩家 Fixture Player -09/12 10:00 – 09/12 10:42 -
- -
-
-
-胜 / 负 -10 / 2 -
-
-结束日 -12 -
-
-最终段位 -黄金 -
-
-段位分 -1520 +16 -
-
-
-
-
- --------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
天数结果对手英雄对手玩家段位段位分视频
1胜皮格马利翁Opponent A白银1400 -
-1分钟 35秒 · 50 MB - - -
-
2负杜利--- - - - -
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.not-found.html b/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.not-found.html deleted file mode 100644 index a305352..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.not-found.html +++ /dev/null @@ -1,165 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
- -

没有找到这局战绩

-
- -
-
-
-
- -

没有找到这局战绩

-
- -
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.read-failed.html b/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.read-failed.html deleted file mode 100644 index a64e892..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/run-detail.read-failed.html +++ /dev/null @@ -1,173 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
- -

战绩不可用

-
- -
-
- -
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/stream.macos-idle.html b/bazaarplusplus-installer/src/__shell_snapshots__/stream.macos-idle.html deleted file mode 100644 index 33b4ce4..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/stream.macos-idle.html +++ /dev/null @@ -1,230 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

直播

- -直播服务未启动 - -
- - -
-
-

直播服务尚未启动

-
-

OBS 地址

-
-
直播服务启动后显示 OBS Browser Source 地址
- -
-
-
-
-
-展示窗口 -当前展示最新记录 -
-
- - -
-
-
-主机 -127.0.0.1 - - -端口 -- - - -数据库 -数据库未找到 - - -窗口 -0 - - -
-
-
-

叠加层配置

-
-显示样式 -
- - - -
-
-
- -
- - - - -
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-error.html b/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-error.html deleted file mode 100644 index 1a51461..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-error.html +++ /dev/null @@ -1,242 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

直播

- -直播服务错误 - -
- - -
-
-

直播服务未能启动。请确认端口 17654 可用后重试。

-
-

OBS 地址

-
-
直播服务启动后显示 OBS Browser Source 地址
- -
-
-
-
-
-展示窗口 -当前展示最新记录 -
-
- - -
-
-
-主机 -127.0.0.1 - - -端口 -- - - -数据库 -数据库未找到 - - -窗口 -0 - - -
-
-
-

叠加层配置

-
-显示样式 -
- - - -
-
-
- -
- - - - -
-
-
-
-
-
-
-
-
-
- -
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-idle.html b/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-idle.html deleted file mode 100644 index 33b4ce4..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-idle.html +++ /dev/null @@ -1,230 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

直播

- -直播服务未启动 - -
- - -
-
-

直播服务尚未启动

-
-

OBS 地址

-
-
直播服务启动后显示 OBS Browser Source 地址
- -
-
-
-
-
-展示窗口 -当前展示最新记录 -
-
- - -
-
-
-主机 -127.0.0.1 - - -端口 -- - - -数据库 -数据库未找到 - - -窗口 -0 - - -
-
-
-

叠加层配置

-
-显示样式 -
- - - -
-
-
- -
- - - - -
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-running.html b/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-running.html deleted file mode 100644 index daa8189..0000000 --- a/bazaarplusplus-installer/src/__shell_snapshots__/stream.windows-running.html +++ /dev/null @@ -1,230 +0,0 @@ -
-
-
- -

BazaarPlusPlus

-v«version» -
-
-
- - - - - - - - - - - -
- - - - - - - - - - -
-来小红书找我 -
-

来小红书找我

-

VibeCoding 日常和碎碎念

-
-
-
-
- -
-来抖音找我 -
-

来抖音找我

-

短视频、开发切片和日常

-
-
-
-
- -
-
- - -
-
-
- -
-
-
-
-
-

直播

- -直播服务运行中 - -
- - -
-
-

端口 17654 · 数据库已连接

-
-

OBS 地址

-
-
http://127.0.0.1:17654/overlay
- -
-
-
-
-
-展示窗口 -当前展示最新记录 -
-
- - -
-
-
-主机 -127.0.0.1 - - -端口 -17654 - - -数据库 -数据库已连接 - - -窗口 -0 - - -
-
-
-

叠加层配置

-
-显示样式 -
- - - -
-
-
- -
- - - - -
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file diff --git a/bazaarplusplus-installer/src/api/commandAdapter.ts b/bazaarplusplus-installer/src/api/commandAdapter.ts deleted file mode 100644 index e0fb398..0000000 --- a/bazaarplusplus-installer/src/api/commandAdapter.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { commands as generatedCommands } from '../types/generated/commands'; - -/** Shared contract implemented by both the generated native client and Preview. */ -export type CommandAdapter = typeof generatedCommands; diff --git a/bazaarplusplus-installer/src/api/commandClient.dispatch.test.ts b/bazaarplusplus-installer/src/api/commandClient.dispatch.test.ts deleted file mode 100644 index 609f80c..0000000 --- a/bazaarplusplus-installer/src/api/commandClient.dispatch.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { invoke } from '@tauri-apps/api/core'; -import type { CommandAdapter } from './commandAdapter'; - -vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() })); -const invokeMock = vi.mocked(invoke); - -afterEach(() => { - vi.unstubAllGlobals(); - vi.resetModules(); - invokeMock.mockReset(); -}); - -describe('native command adapter', () => { - it('selects the generated native client once when the runtime is present', async () => { - vi.stubGlobal('window', { __TAURI_INTERNALS__: {} }); - invokeMock.mockResolvedValueOnce({ marker: true }); - const { commandClient } = await import('./commandClient'); - - await expect(commandClient.getInstallState('/game')).resolves.toEqual({ - marker: true - }); - expect(invokeMock).toHaveBeenCalledWith('get_install_state', { - gamePath: '/game' - }); - }); - - it('normalizes string rejections from generated commands', async () => { - vi.stubGlobal('window', { __TAURI_INTERNALS__: {} }); - invokeMock.mockRejectedValueOnce('raw backend failure'); - const { commandClient } = await import('./commandClient'); - - await expect(commandClient.listHistoryRuns(50, 0)).rejects.toMatchObject({ - message: 'raw backend failure' - }); - }); - - it.each([ - { - call: 'listHistoryRuns', - run: (client: CommandAdapter) => client.listHistoryRuns(50, 100), - command: 'list_history_runs', - args: { limit: 50, offset: 100 }, - problem: { - code: 'history_read_failed', - params: { operation: 'list_runs' }, - diagnostic: 'database is locked' - } - }, - { - call: 'resetBppData', - run: (client: CommandAdapter) => client.resetBppData('/game'), - command: 'reset_bpp_data', - args: { gamePath: '/game' }, - problem: { - code: 'install_partial_failure', - params: { - operation: 'reset_bpp_data', - count: '2', - paths: '/tmp/a\u001f/tmp/b' - }, - diagnostic: null - } - }, - { - call: 'applyOverlayCropCode', - run: (client: CommandAdapter) => client.applyOverlayCropCode('bad'), - command: 'apply_overlay_crop_code', - args: { code: 'bad' }, - problem: { - code: 'stream_crop_failed', - params: { operation: 'apply_code' }, - diagnostic: 'invalid crop payload' - } - }, - { - call: 'executeStorageCleanup', - run: (client: CommandAdapter) => - client.executeStorageCleanup('run_data', 'all'), - command: 'execute_storage_cleanup', - args: { scope: 'run_data', preset: 'all' }, - problem: { - code: 'history_action_failed', - params: { operation: 'execute_storage_cleanup' }, - diagnostic: 'database is locked' - } - } - ])( - 'preserves the semantic problem a generated $call rejects with', - async ({ run, command, args, problem }) => { - vi.stubGlobal('window', { __TAURI_INTERNALS__: {} }); - invokeMock.mockRejectedValueOnce(problem); - const { commandClient } = await import('./commandClient'); - - await expect(run(commandClient)).rejects.toMatchObject({ - name: 'SemanticProblemError', - message: problem.code, - problem - }); - expect(invokeMock).toHaveBeenCalledWith(command, args); - } - ); -}); - -describe('normalizeBackendError sentinel contract', () => { - it('keeps string errors verbatim and passes Error instances through', async () => { - const { normalizeBackendError } = await import('./nativeCommands'); - const error = new Error('boom'); - - expect( - normalizeBackendError('bpp_data_reset_blocked_by_game').message - ).toBe('bpp_data_reset_blocked_by_game'); - expect(normalizeBackendError(error)).toBe(error); - }); - - it('wraps unknown shapes', async () => { - const { normalizeBackendError } = await import('./nativeCommands'); - expect(normalizeBackendError({ weird: true }).message).toBe( - 'Backend command failed.' - ); - expect( - normalizeBackendError({ - code: 'toString', - params: {}, - diagnostic: null - }).message - ).toBe('Backend command failed.'); - }); -}); diff --git a/bazaarplusplus-installer/src/api/commandClient.ts b/bazaarplusplus-installer/src/api/commandClient.ts deleted file mode 100644 index 20fed84..0000000 --- a/bazaarplusplus-installer/src/api/commandClient.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { hasTauriRuntime } from './runtime'; -import { nativeCommands } from './nativeCommands'; -import { createPreviewCommands } from './previewCommands'; - -/** Runtime selection happens once; feature modules only see this semantic client. */ -export const commandClient = hasTauriRuntime() - ? nativeCommands - : createPreviewCommands(nativeCommands); diff --git a/bazaarplusplus-installer/src/api/nativeCommands.ts b/bazaarplusplus-installer/src/api/nativeCommands.ts deleted file mode 100644 index 0775314..0000000 --- a/bazaarplusplus-installer/src/api/nativeCommands.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { commands as generatedCommands } from '../types/generated/commands'; -import type { CommandAdapter } from './commandAdapter'; -import { isSemanticProblem, SemanticProblemError } from './problems'; - -export function normalizeBackendError(error: unknown): Error { - if (error instanceof Error) { - return error; - } - if (isSemanticProblem(error)) { - return new SemanticProblemError(error); - } - if (typeof error === 'string') { - return new Error(error); - } - return new Error('Backend command failed.'); -} - -function withNormalizedErrors( - client: typeof generatedCommands -): CommandAdapter { - return new Proxy(client, { - get(target, property, receiver) { - const command = Reflect.get(target, property, receiver); - if (typeof command !== 'function') return command; - - return async (...args: unknown[]) => { - try { - return await command(...args); - } catch (error) { - throw normalizeBackendError(error); - } - }; - } - }); -} - -export const nativeCommands = withNormalizedErrors(generatedCommands); diff --git a/bazaarplusplus-installer/src/api/previewCommands.test.ts b/bazaarplusplus-installer/src/api/previewCommands.test.ts deleted file mode 100644 index 9c0d754..0000000 --- a/bazaarplusplus-installer/src/api/previewCommands.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { commandClient } from './commandClient'; -import { - defaultCropSettings, - emptyHistoryRunList, - emptyInstallState, - fallbackBootstrap, - idleStreamStatus -} from './previewDefaults'; - -describe('browser-preview command adapter', () => { - it('returns the shared seed references', async () => { - expect(await commandClient.getInstallState(null)).toBe(emptyInstallState); - expect(await commandClient.getStreamStatus()).toBe(idleStreamStatus); - expect(await commandClient.ensureStreamSession()).toBe(idleStreamStatus); - expect(await commandClient.restartStreamSession()).toBe(idleStreamStatus); - expect(await commandClient.setStreamWindow(3)).toBe(idleStreamStatus); - expect(await commandClient.getOverlaySettings()).toBe(defaultCropSettings); - expect(await commandClient.resetOverlayCrop()).toBe(defaultCropSettings); - expect(await commandClient.listHistoryRuns(50, 0)).toBe( - emptyHistoryRunList - ); - expect( - await commandClient.previewStorageCleanup('screenshots', 'all') - ).toEqual({ - scope: 'screenshots', - preview: { - screenshots: 0, - orphan_files: 0, - estimated_bytes: 0, - skipped_pending_uploads: 0 - } - }); - expect( - await commandClient.previewStorageCleanup('run_data', 'all') - ).toEqual({ - scope: 'run_data', - preview: { - runs: 0, - battles: 0, - videos: 0, - estimated_bytes: 0, - skipped_pending_uploads: 0 - } - }); - expect( - await commandClient.executeStorageCleanup('screenshots', 'all') - ).toEqual({ - scope: 'screenshots', - result: { - deleted_rows: 0, - deleted_files: 0, - freed_bytes: 0, - skipped_pending_uploads: 0 - } - }); - expect( - await commandClient.executeStorageCleanup('run_data', 'all') - ).toEqual({ - scope: 'run_data', - result: { - deleted_runs: 0, - deleted_files: 0, - freed_bytes: 0, - skipped_pending_uploads: 0 - } - }); - expect(await commandClient.getAppBootstrap()).toBe(fallbackBootstrap); - }); - - it('reproduces input-dependent overlay fallbacks', async () => { - expect(await commandClient.applyOverlayCropCode('x')).toEqual({ - ...defaultCropSettings, - code: 'x' - }); - expect(await commandClient.saveOverlayDisplayMode('hero')).toEqual({ - ...defaultCropSettings, - display_mode: 'hero' - }); - }); - - it('returns inline preview literals', async () => { - expect(await commandClient.chooseGameDirectory()).toEqual({ - game_path: null - }); - }); - - it('preserves nullable read-only desktop preview results', async () => { - expect(await commandClient.getHistoryRunDetail('r')).toBeNull(); - }); - - it('reports History Thumbnails unavailable because the preview has no image service', async () => { - await expect( - commandClient.prepareHistoryThumbnails() - ).rejects.toMatchObject({ - name: 'SemanticProblemError', - problem: { - code: 'history_thumbnails_unavailable', - params: { operation: 'prepare_history_thumbnails' } - } - }); - }); - - it('returns null for Tauri unit-returning no-ops', async () => { - expect(await commandClient.setAppLocale('en')).toBeNull(); - expect(await commandClient.launchGame()).toBeNull(); - expect(await commandClient.revealRunScreenshot('r')).toBeNull(); - expect(await commandClient.revealBattleVideo('b', 'v')).toBeNull(); - }); - - it('keeps preview bootstrap and install gates wired to real defaults', () => { - expect(fallbackBootstrap.app_version).toBe(__FRONTEND_VERSION__); - expect(fallbackBootstrap.bundled_bpp_version).toBeNull(); - expect(fallbackBootstrap.links).toBeTruthy(); - expect(emptyInstallState.selected_game_path).toBeNull(); - expect(emptyInstallState.has_resettable_data).toBe(false); - expect(emptyInstallState.has_bepinex_files).toBe(false); - expect(emptyInstallState.warnings.map((warning) => warning.code)).toEqual([ - 'game_missing' - ]); - }); - - it('passes native-only preview commands through to the normalized client', async () => { - await expect(commandClient.installMod('x')).rejects.toBeInstanceOf(Error); - await expect( - commandClient.deleteBattleVideo('b', 'v') - ).rejects.toBeInstanceOf(Error); - }); -}); diff --git a/bazaarplusplus-installer/src/api/previewCommands.ts b/bazaarplusplus-installer/src/api/previewCommands.ts deleted file mode 100644 index 656f9eb..0000000 --- a/bazaarplusplus-installer/src/api/previewCommands.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { CommandAdapter } from './commandAdapter'; -import { SemanticProblemError } from './problems'; -import { - defaultCropSettings, - emptyHistoryRunList, - emptyInstallState, - emptyLegacyDataState, - emptyRunDataCleanupPreview, - emptyRunDataCleanupResult, - emptyScreenshotCleanupPreview, - emptyScreenshotCleanupResult, - fallbackBootstrap, - idleStreamStatus -} from './previewDefaults'; - -export function createPreviewCommands(native: CommandAdapter): CommandAdapter { - return { - getAppBootstrap: async () => fallbackBootstrap, - setAppLocale: async () => null, - getInstallState: async () => emptyInstallState, - chooseGameDirectory: async () => ({ game_path: null }), - installMod: (...args) => native.installMod(...args), - resetBppData: (...args) => native.resetBppData(...args), - resetBepinex: (...args) => native.resetBepinex(...args), - getLegacyDataState: async () => emptyLegacyDataState, - importV5History: (...args) => native.importV5History(...args), - deleteLegacyRoot: (...args) => native.deleteLegacyRoot(...args), - uninstallMod: (...args) => native.uninstallMod(...args), - launchGame: async () => null, - endGameProcess: async () => false, - getStreamStatus: async () => idleStreamStatus, - ensureStreamSession: async () => idleStreamStatus, - // Browser Preview serves no images, so History shows its unavailable notice. - prepareHistoryThumbnails: async () => { - throw new SemanticProblemError({ - code: 'history_thumbnails_unavailable', - params: { operation: 'prepare_history_thumbnails' }, - diagnostic: null - }); - }, - restartStreamSession: async () => idleStreamStatus, - setStreamWindow: async () => idleStreamStatus, - getOverlaySettings: async () => defaultCropSettings, - saveOverlayDisplayMode: async (displayMode) => ({ - ...defaultCropSettings, - display_mode: displayMode - }), - applyOverlayCropCode: async (code) => ({ ...defaultCropSettings, code }), - resetOverlayCrop: async () => defaultCropSettings, - listHistoryRuns: async () => emptyHistoryRunList, - getHistoryRunDetail: async () => null, - revealRunScreenshot: async () => null, - revealBattleVideo: async () => null, - deleteBattleVideo: (...args) => native.deleteBattleVideo(...args), - previewStorageCleanup: async (scope) => - scope === 'screenshots' - ? { scope, preview: emptyScreenshotCleanupPreview } - : { scope, preview: emptyRunDataCleanupPreview }, - executeStorageCleanup: async (scope) => - scope === 'screenshots' - ? { scope, result: emptyScreenshotCleanupResult } - : { scope, result: emptyRunDataCleanupResult } - } satisfies CommandAdapter; -} diff --git a/bazaarplusplus-installer/src/api/previewDefaults.ts b/bazaarplusplus-installer/src/api/previewDefaults.ts deleted file mode 100644 index 5155114..0000000 --- a/bazaarplusplus-installer/src/api/previewDefaults.ts +++ /dev/null @@ -1,122 +0,0 @@ -// LEAF MODULE: value-mirrors of generated types, consumed as BOTH useState seeds -// (features/**) and preview command results. MUST NOT import from command clients -// or features/** — that would recreate the runtime import cycle this file avoids. -import type { - AppBootstrap, - HistoryRunList, - InstallState, - LegacyDataState, - RunDataCleanupPreview, - RunDataCleanupResult, - ScreenshotCleanupPreview, - ScreenshotCleanupResult, - StreamOverlayCropSettingsPayload, - StreamServiceStatus -} from '../types/backend'; -import bootstrapResource from '../../src-tauri/resources/app-bootstrap.json'; - -export const emptyInstallState: InstallState = { - // These falsy fields gate preview-unreachable install/reset commands. - selected_game_path: null, - steam_path: null, - game: { - path_valid: false - }, - mod_state: { - installed: false, - ready: false - }, - actions: { - can_install: false, - can_reinstall: false, - can_reset_data: false, - can_reset_bepinex: false, - can_uninstall: false, - can_launch: false - }, - has_resettable_data: false, - has_bepinex_files: false, - warnings: [{ code: 'game_missing', params: {} }] -}; - -export const emptyLegacyDataState: LegacyDataState = { - game_path: null, - roots: [], - installed_mod_data_root: 'reinstall_required', - v5_import_eligible: false -}; - -export const idleStreamStatus: StreamServiceStatus = { - // The loopback host and zero active-window offset are deliberate defaults. - running: false, - host: '127.0.0.1', - port: null, - overlay_url: null, - settings_url: null, - last_error: null, - started_at: null, - active_from: null, - active_window_offset: 0, - db: { - found: false - } -}; - -export const defaultCropSettings: StreamOverlayCropSettingsPayload = { - // This is the real preview crop rectangle, not a normalized zero-value. - crop: { - left: 0.342, - top: 0.313, - width: 0.58, - height: 0.22 - }, - code: '', - display_mode: 'current' -}; - -export const emptyHistoryRunList: HistoryRunList = { - summary: { - runs: 0, - videos: 0, - win_rate: null - }, - runs: [] -}; - -export const emptyScreenshotCleanupPreview: ScreenshotCleanupPreview = { - screenshots: 0, - orphan_files: 0, - estimated_bytes: 0, - skipped_pending_uploads: 0 -}; - -export const emptyRunDataCleanupPreview: RunDataCleanupPreview = { - runs: 0, - battles: 0, - videos: 0, - estimated_bytes: 0, - skipped_pending_uploads: 0 -}; - -export const emptyScreenshotCleanupResult: ScreenshotCleanupResult = { - deleted_rows: 0, - deleted_files: 0, - freed_bytes: 0, - skipped_pending_uploads: 0 -}; - -export const emptyRunDataCleanupResult: RunDataCleanupResult = { - deleted_runs: 0, - deleted_files: 0, - freed_bytes: 0, - skipped_pending_uploads: 0 -}; - -export const fallbackBootstrap: AppBootstrap = { - ...(bootstrapResource as Pick< - AppBootstrap, - 'links' | 'credits' | 'licenses' - >), - app_version: __FRONTEND_VERSION__, - bundled_bpp_version: null -}; diff --git a/bazaarplusplus-installer/src/api/problems.ts b/bazaarplusplus-installer/src/api/problems.ts deleted file mode 100644 index 8864e23..0000000 --- a/bazaarplusplus-installer/src/api/problems.ts +++ /dev/null @@ -1,62 +0,0 @@ -import type { SemanticProblem } from '../types/backend'; - -const semanticProblemCodes: Record = { - history_unavailable: true, - history_read_failed: true, - history_read_blocked_by_game: true, - history_database_unsupported_schema: true, - history_action_failed: true, - history_thumbnails_unavailable: true, - install_detection_failed: true, - install_action_failed: true, - install_partial_failure: true, - install_blocked_by_game: true, - reset_blocked_by_game: true, - bepinex_reset_blocked_by_game: true, - import_blocked_by_game: true, - import_failed: true, - legacy_delete_blocked_by_game: true, - stream_service_failed: true, - stream_window_failed: true, - stream_crop_failed: true -}; - -export class SemanticProblemError extends Error { - readonly problem: SemanticProblem; - - constructor(problem: SemanticProblem) { - super(problem.code); - this.name = 'SemanticProblemError'; - this.problem = problem; - } -} - -export function isSemanticProblem(value: unknown): value is SemanticProblem { - if ( - !isRecord(value) || - typeof value.code !== 'string' || - !Object.hasOwn(semanticProblemCodes, value.code) - ) { - return false; - } - if (!isRecord(value.params)) { - return false; - } - if (!Object.values(value.params).every((item) => typeof item === 'string')) { - return false; - } - return value.diagnostic === null || typeof value.diagnostic === 'string'; -} - -export function semanticProblemFromError( - error: unknown -): SemanticProblem | null { - if (error instanceof SemanticProblemError) { - return error.problem; - } - return isSemanticProblem(error) ? error : null; -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} diff --git a/bazaarplusplus-installer/src/api/runtime.ts b/bazaarplusplus-installer/src/api/runtime.ts deleted file mode 100644 index d61126f..0000000 --- a/bazaarplusplus-installer/src/api/runtime.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function hasTauriRuntime(): boolean { - return typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window; -} diff --git a/bazaarplusplus-installer/src/components/ui/Button.tsx b/bazaarplusplus-installer/src/components/ui/Button.tsx deleted file mode 100644 index 8a88cd1..0000000 --- a/bazaarplusplus-installer/src/components/ui/Button.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import clsx from 'clsx'; -import { Loader2 } from 'lucide-react'; -import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from 'react'; - -export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger'; -export type ButtonSize = 'md' | 'sm' | 'icon' | 'icon-sm'; - -/** Class list for anything that should look like a Button, such as a router - * `Link` or an external ``. */ -export function buttonClassName({ - variant = 'secondary', - size = 'md', - className -}: { - variant?: ButtonVariant; - size?: ButtonSize; - className?: string; -} = {}): string { - return clsx('bpp-btn', `bpp-btn-${variant}`, `bpp-btn-${size}`, className); -} - -export interface ButtonProps extends ButtonHTMLAttributes { - variant?: ButtonVariant; - size?: ButtonSize; - /** Leading icon. Replaced by a spinner while `busy`. */ - icon?: ReactNode; - busy?: boolean; - /** Label shown while busy; the button keeps the wider label's width. */ - busyLabel?: string; -} - -export const Button = forwardRef( - function Button( - { - variant = 'secondary', - size = 'md', - icon, - busy = false, - busyLabel, - disabled, - type = 'button', - className, - children, - ...buttonProps - }, - ref - ) { - const leading = busy ? ( - - {t('viewTutorial')} - - - - - }> -

- {t( - isWindowsPlatform() - ? 'installSteamNotice' - : willCloseSteam - ? 'installSteamNoticeMacos' - : 'installCloseGameNotice' - )} -

-
- - {problem && } - - ); -} diff --git a/bazaarplusplus-installer/src/features/install/InstallProblemBanner.tsx b/bazaarplusplus-installer/src/features/install/InstallProblemBanner.tsx deleted file mode 100644 index 803723e..0000000 --- a/bazaarplusplus-installer/src/features/install/InstallProblemBanner.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { ProblemBanner } from '../../components/ui/ProblemBanner'; -import { useI18n } from '../../i18n/LocaleProvider'; -import { presentInstallProblem, type InstallProblem } from './installProblems'; - -export function InstallProblemBanner({ - problem, - onRetry -}: { - problem: InstallProblem; - onRetry?: () => void; -}) { - const { t } = useI18n(); - return ( - - ); -} diff --git a/bazaarplusplus-installer/src/features/install/InstallStatusPanel.tsx b/bazaarplusplus-installer/src/features/install/InstallStatusPanel.tsx deleted file mode 100644 index 7e4db76..0000000 --- a/bazaarplusplus-installer/src/features/install/InstallStatusPanel.tsx +++ /dev/null @@ -1,139 +0,0 @@ -import { Copy, Check, Folder } from 'lucide-react'; -import { useState } from 'react'; -import { Button } from '../../components/ui/Button'; -import { StatusBadge } from '../../components/ui/StatusBadge'; -import { StatusBanner } from '../../components/ui/StatusBanner'; -import { useI18n } from '../../i18n/LocaleProvider'; -import brandLogo from '../../../static/brand/bazaarplusplus-logo.webp'; -import { PrimaryInstallActionButton } from './PrimaryInstallActionButton'; -import { presentInstallWarning } from './installProblems'; -import type { - InstallPageSnapshot, - InstallWorkflowIntents -} from './installWorkflow'; - -export function InstallStatusPanel({ - snapshot, - intents, - appVersion -}: { - snapshot: Extract; - intents: InstallWorkflowIntents; - appVersion: string; -}) { - const { t } = useI18n(); - const [copied, setCopied] = useState(false); - const state = snapshot.data; - const installed = state.mod_state.installed; - const healthy = state.mod_state.ready; - const needsReinstall = installed && !state.mod_state.ready; - const status = healthy - ? { tone: 'ok' as const, label: t('installed') } - : needsReinstall - ? { tone: 'warn' as const, label: t('modNeedsReinstall') } - : { tone: 'neutral' as const, label: t('notInstalled') }; - const description = healthy - ? t('installOverviewHealthyShort') - : needsReinstall - ? t('installOverviewUpdateDescription') - : t('installOverviewNotInstalledDescription'); - const selectedPath = state.selected_game_path; - - const copyPath = async () => { - if (!selectedPath) return; - await navigator.clipboard.writeText(selectedPath); - setCopied(true); - window.setTimeout(() => setCopied(false), 1600); - }; - - return ( - <> -
-
- -
-

- BazaarPlusPlus - {status.label} -

-

- {description} -

-
- -
- -
- - {t('installationDirectoryHeading')} - - - {selectedPath ?? t('gamePathEmpty')} - - - - - - {t('applicationVersionHeading')} - - {appVersion} - - {import.meta.env.DEV ? t('developmentBuild') : t('stableBuild')} - - - -
-
- - {state.warnings.length > 0 && ( - - {state.warnings.map((warning) => ( -
  • {presentInstallWarning(warning, t)}
  • - ))} - - } - /> - )} - - ); -} diff --git a/bazaarplusplus-installer/src/features/install/LegacyDataPanel.test.tsx b/bazaarplusplus-installer/src/features/install/LegacyDataPanel.test.tsx deleted file mode 100644 index e8490cc..0000000 --- a/bazaarplusplus-installer/src/features/install/LegacyDataPanel.test.tsx +++ /dev/null @@ -1,239 +0,0 @@ -// @vitest-environment jsdom - -// The import card's states as the Install page shows them: hidden behind the -// reinstall hint while the installed mod writes an old Data Root, offered when -// eligible, in progress, and failed with its typed recovery copy. -import { act } from 'react'; -import { createRoot, type Root } from 'react-dom/client'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { SemanticProblemError } from '../../api/problems'; -import { LocaleProvider } from '../../i18n/LocaleProvider'; -import { formatMessage, LOCALE_STORAGE_KEY } from '../../i18n/messages'; -import type { - ImportV5HistoryResult, - LegacyDataState -} from '../../types/backend'; -import { LegacyDataPanel } from './LegacyDataPanel'; -import { LegacyRootDeleteConfirmModal } from './LegacyRootDeleteConfirmModal'; -import { - createLegacyDataWorkflow, - type LegacyDataCommandPort, - type LegacyDataWorkflow -} from './legacyDataWorkflow'; - -const GAME = '/Games/The Bazaar'; -const zh = (key: Parameters[1]) => - formatMessage('zh', key); - -function state(overrides: Partial): LegacyDataState { - return { - game_path: GAME, - roots: [ - { - name: 'BazaarPlusPlusV5', - size_bytes: 4096, - file_count: 3, - hard_linked_file_count: 0, - unreadable_entry_count: 0 - } - ], - installed_mod_data_root: 'current', - v5_import_eligible: true, - ...overrides - }; -} - -let container: HTMLDivElement; -let root: Root; - -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); - localStorage.setItem(LOCALE_STORAGE_KEY, 'zh'); - container = document.createElement('div'); - document.body.append(container); - root = createRoot(container); - // jsdom does not implement the native dialog lifecycle. - Object.defineProperty(HTMLDialogElement.prototype, 'showModal', { - configurable: true, - value: function (this: HTMLDialogElement) { - this.open = true; - } - }); - Object.defineProperty(HTMLDialogElement.prototype, 'close', { - configurable: true, - value: function (this: HTMLDialogElement) { - this.open = false; - } - }); -}); - -afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - vi.unstubAllGlobals(); -}); - -async function show( - data: LegacyDataState, - overrides: Partial = {} -): Promise { - const workflow = createLegacyDataWorkflow({ - commands: { - getLegacyDataState: vi.fn(async () => data), - importV5History: vi.fn(async () => ({ - imported_run_count: 1, - skipped_run_count: 0, - unavailable_file_count: 0, - state: state({ v5_import_eligible: false }) - })), - deleteLegacyRoot: vi.fn(), - ...overrides - } - }); - await workflow.load(GAME); - const render = () => - root.render( - - - - ); - workflow.subscribe(render); - await act(async () => render()); - return workflow; -} - -function importButton() { - return [...container.querySelectorAll('button')].find( - (button) => button.textContent === zh('legacyImportAction') - ); -} - -describe('V5 import card', () => { - it('shows only the reinstall hint while the mod writes an old Data Root', async () => { - await show( - state({ - installed_mod_data_root: 'reinstall_required', - v5_import_eligible: false - }) - ); - - expect(container.textContent).toContain(zh('legacyModReinstallRequired')); - expect(container.textContent).not.toContain(zh('legacyImportHeading')); - expect(importButton()).toBeUndefined(); - }); - - it('offers the import when eligible', async () => { - await show(state({})); - - expect(container.querySelector('#legacy-data')).not.toBeNull(); - expect(container.textContent).toContain(zh('legacyImportHeading')); - expect(container.textContent).not.toContain( - zh('legacyModReinstallRequired') - ); - expect(importButton()?.disabled).toBe(false); - }); - - it('shows progress and blocks deletion while importing', async () => { - let finish!: () => void; - await show(state({}), { - importV5History: vi.fn( - () => - new Promise((resolve) => { - finish = () => - resolve({ - imported_run_count: 1, - skipped_run_count: 0, - unavailable_file_count: 0, - state: state({ v5_import_eligible: false }) - }); - }) - ) - }); - - await act(async () => importButton()!.click()); - - expect(container.querySelector('[role="status"]')?.textContent).toBe( - zh('legacyImportRunning') - ); - const deleteButton = container.querySelector( - `button[aria-label="${formatMessage('zh', 'legacyDeleteAction', { - name: 'BazaarPlusPlusV5' - })}"]` - ); - expect(deleteButton?.disabled).toBe(true); - - await act(async () => finish()); - // Imported: the card leaves, and V5 stays listed until a confirmation. - expect(container.textContent).not.toContain(zh('legacyImportHeading')); - expect(container.textContent).toContain('BazaarPlusPlusV5'); - }); - - it('shows the typed failure and keeps the card for a retry', async () => { - await show(state({}), { - importV5History: vi.fn(async () => { - throw new SemanticProblemError({ - code: 'import_failed', - params: { operation: 'import_v5_history', reason: 'file_conflict' }, - diagnostic: null - }); - }) - }); - - await act(async () => importButton()!.click()); - - expect(container.textContent).toContain(zh('importFailedFiles')); - expect(importButton()?.disabled).toBe(false); - }); -}); - -describe('offer to delete V5 after an import', () => { - it('reports the import, promises no reclaimed space, and can be kept', async () => { - const onClose = vi.fn(); - await act(async () => - root.render( - - {}} - onClose={onClose} - onConfirm={() => {}} - /> - - ) - ); - - const text = container.textContent ?? ''; - expect(text).toContain( - formatMessage('zh', 'legacyDeleteAfterImport', { imported: 8 }) - ); - expect(text).toContain( - formatMessage('zh', 'legacyDeleteAfterImportSkipped', { count: 1 }) - ); - expect(text).not.toContain( - formatMessage('zh', 'legacyDeleteAfterImportUnavailableFiles', { - count: 0 - }) - ); - expect(text).toContain(zh('legacyDeleteConfirmSpace')); - const keep = [...container.querySelectorAll('button')].find( - (button) => button.textContent === zh('legacyDeleteKeep') - ); - await act(async () => keep!.click()); - expect(onClose).toHaveBeenCalled(); - }); -}); diff --git a/bazaarplusplus-installer/src/features/install/LegacyDataPanel.tsx b/bazaarplusplus-installer/src/features/install/LegacyDataPanel.tsx deleted file mode 100644 index 232b912..0000000 --- a/bazaarplusplus-installer/src/features/install/LegacyDataPanel.tsx +++ /dev/null @@ -1,153 +0,0 @@ -import { FolderClock, HardDriveDownload, Loader2 } from 'lucide-react'; -import { Button } from '../../components/ui/Button'; -import { StatusBanner } from '../../components/ui/StatusBanner'; -import { useI18n } from '../../i18n/LocaleProvider'; -import { formatBytes } from '../history/format'; -import { InstallProblemBanner } from './InstallProblemBanner'; -import type { - LegacyDataSnapshot, - LegacyDataWorkflow -} from './legacyDataWorkflow'; - -/** - * Folders earlier major versions wrote into the game directory. Each one is - * deleted only after its own confirmation; the installed-mod hint asks for a - * reinstall when the mod on disk still writes one of them, and only then is - * the V5 import card replaced by that hint. `LEGACY_DATA_SECTION_ID` is the - * anchor History links to when it has no current database. - */ -export const LEGACY_DATA_SECTION_ID = 'legacy-data'; - -export function LegacyDataPanel({ - snapshot, - workflow, - modInstalled, - gamePath -}: { - snapshot: LegacyDataSnapshot; - workflow: LegacyDataWorkflow; - modInstalled: boolean; - gamePath: string | null; -}) { - const { t, locale } = useI18n(); - const load = snapshot.load; - - if (load.phase === 'failed') { - return ( - void workflow.load(gamePath)} - /> - ); - } - const data = load.phase === 'idle' ? null : load.data; - // Without a game directory there is nothing to list or reinstall into. - if (!data?.game_path) return null; - - const reinstallRequired = - modInstalled && data.installed_mod_data_root === 'reinstall_required'; - if (data.roots.length === 0 && !reinstallRequired) return null; - - const deleting = - snapshot.confirmation?.phase === 'running' - ? snapshot.confirmation.target.name - : null; - const importRun = snapshot.importRun; - const importing = importRun.phase === 'running'; - const showImport = - !reinstallRequired && (data.v5_import_eligible || importing); - - return ( -
    -
    -
    - {reinstallRequired && ( -
    - -
    - )} - {showImport && ( -
    -
    - )} - {showImport && importRun.phase === 'failed' && ( -
    - void workflow.importV5()} - /> -
    - )} - {data.roots.map((root) => ( -
    -
    - {root.name} - - {t('legacyRootSize', { - size: formatBytes(root.size_bytes, locale), - files: root.file_count - })} - - {root.hard_linked_file_count > 0 && ( - - {t('legacyRootHardLinked', { - count: root.hard_linked_file_count - })} - - )} - {root.unreadable_entry_count > 0 && ( - - {t('legacyRootUnreadable', { - count: root.unreadable_entry_count - })} - - )} -
    - -
    - ))} -
    - ); -} diff --git a/bazaarplusplus-installer/src/features/install/LegacyRootDeleteConfirmModal.tsx b/bazaarplusplus-installer/src/features/install/LegacyRootDeleteConfirmModal.tsx deleted file mode 100644 index 9b1918b..0000000 --- a/bazaarplusplus-installer/src/features/install/LegacyRootDeleteConfirmModal.tsx +++ /dev/null @@ -1,101 +0,0 @@ -import { CircleCheck, FolderX, ShieldCheck } from 'lucide-react'; -import { - ConfirmDialog, - ConfirmNote, - ConfirmTarget -} from '../../components/ui/ConfirmDialog'; -import { useI18n } from '../../i18n/LocaleProvider'; -import { InstallProblemBanner } from './InstallProblemBanner'; -import { ResetDataFailureDetails } from './ResetDataFailureDetails'; -import type { InstallProblem } from './installProblems'; -import type { LegacyImportSummary } from './legacyDataWorkflow'; - -/** Deletes one Legacy Root. After a V5 import (`afterImport`) it is the offer - * to delete `BazaarPlusPlusV5`, which the user may decline and keep. */ -export function LegacyRootDeleteConfirmModal({ - busy, - acknowledged, - targetPath, - name, - problem, - failurePaths, - afterImport, - onAcknowledgedChange, - onClose, - onConfirm -}: { - busy: boolean; - acknowledged: boolean; - targetPath: string; - name: string; - problem: InstallProblem | null; - failurePaths: string[]; - afterImport?: LegacyImportSummary; - onAcknowledgedChange: (acknowledged: boolean) => void; - onClose: () => void; - onConfirm: () => void | Promise; -}) { - const { t } = useI18n(); - - return ( - - {afterImport && ( - }> -

    - {t('legacyDeleteAfterImport', { - imported: afterImport.imported_run_count - })} -

    - {afterImport.skipped_run_count > 0 && ( -

    - {t('legacyDeleteAfterImportSkipped', { - count: afterImport.skipped_run_count - })} -

    - )} - {afterImport.unavailable_file_count > 0 && ( -

    - {t('legacyDeleteAfterImportUnavailableFiles', { - count: afterImport.unavailable_file_count - })} -

    - )} -

    {t('legacyDeleteAfterImportOffer')}

    -
    - )} - - {t('legacyDeleteTarget', { path: targetPath, name })} - - }> -

    {t('legacyDeleteConfirmBody', { name })}

    -

    {t('legacyDeleteConfirmSpace')}

    -
    - }> -

    {t('legacyDeleteConfirmKeepsCurrent')}

    -

    {t('resetDataConfirmGameClosed')}

    -
    - {problem && } - {failurePaths.length > 0 && ( - - )} -
    - ); -} diff --git a/bazaarplusplus-installer/src/features/install/PrimaryInstallActionButton.tsx b/bazaarplusplus-installer/src/features/install/PrimaryInstallActionButton.tsx deleted file mode 100644 index c87a087..0000000 --- a/bazaarplusplus-installer/src/features/install/PrimaryInstallActionButton.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import { DownloadCloud, Folder, Play, RefreshCw } from 'lucide-react'; -import { Button } from '../../components/ui/Button'; -import { useI18n } from '../../i18n/LocaleProvider'; -import type { - InstallPageSnapshot, - InstallWorkflowIntents -} from './installWorkflow'; - -export function PrimaryInstallActionButton({ - snapshot, - intents, - descriptionId, - descriptionText -}: { - snapshot: Extract; - intents: InstallWorkflowIntents; - descriptionId?: string; - descriptionText?: string; -}) { - const { t } = useI18n(); - const primary = snapshot.primaryAction; - const mode = primary.mode; - const isLaunch = mode === 'launch'; - const isChoose = mode === 'choose-directory'; - const isRepair = mode === 'repair'; - const label = isChoose - ? t('actionChooseDirectory') - : isLaunch - ? t('launchGame') - : isRepair - ? t('actionReinstall') - : t('actionInstall'); - const Icon = isChoose - ? Folder - : isLaunch - ? Play - : isRepair - ? RefreshCw - : DownloadCloud; - const explainDisabled = primary.disabled && !primary.running; - - const onClick = () => { - if (isChoose) { - void intents.chooseDirectory(); - return; - } - if (isLaunch) { - void intents.launch(); - return; - } - intents.requestInstall(); - }; - - return ( - - ); -} diff --git a/bazaarplusplus-installer/src/features/install/ResetBepinexConfirmModal.tsx b/bazaarplusplus-installer/src/features/install/ResetBepinexConfirmModal.tsx deleted file mode 100644 index c5e1b71..0000000 --- a/bazaarplusplus-installer/src/features/install/ResetBepinexConfirmModal.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { FolderX, ShieldCheck } from 'lucide-react'; -import { - ConfirmDialog, - ConfirmNote, - ConfirmTarget -} from '../../components/ui/ConfirmDialog'; -import { useI18n } from '../../i18n/LocaleProvider'; -import { InstallProblemBanner } from './InstallProblemBanner'; -import type { InstallProblem } from './installProblems'; - -export function ResetBepinexConfirmModal({ - busy, - acknowledged, - targetPath, - problem, - onAcknowledgedChange, - onClose, - onConfirm -}: { - busy: boolean; - acknowledged: boolean; - targetPath: string; - problem: InstallProblem | null; - onAcknowledgedChange: (acknowledged: boolean) => void; - onClose: () => void; - onConfirm: () => void | Promise; -}) { - const { t } = useI18n(); - - return ( - - - {t('resetBepinexTarget', { path: targetPath })} - - }> -

    {t('resetBepinexConfirmBody')}

    -

    {t('resetBepinexConfirmOtherMods')}

    -
    - }> -

    {t('resetBepinexConfirmReinstall')}

    -

    {t('resetBepinexConfirmGameClosed')}

    -
    - {problem && } -
    - ); -} diff --git a/bazaarplusplus-installer/src/features/install/ResetDataConfirmModal.tsx b/bazaarplusplus-installer/src/features/install/ResetDataConfirmModal.tsx deleted file mode 100644 index a7be49d..0000000 --- a/bazaarplusplus-installer/src/features/install/ResetDataConfirmModal.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { Database, ShieldCheck } from 'lucide-react'; -import { - ConfirmDialog, - ConfirmNote, - ConfirmTarget -} from '../../components/ui/ConfirmDialog'; -import { useI18n } from '../../i18n/LocaleProvider'; -import { InstallProblemBanner } from './InstallProblemBanner'; -import { ResetDataFailureDetails } from './ResetDataFailureDetails'; -import type { InstallProblem } from './installProblems'; - -export function ResetDataConfirmModal({ - busy, - acknowledged, - targetPath, - problem, - failurePaths, - onAcknowledgedChange, - onClose, - onConfirm -}: { - busy: boolean; - acknowledged: boolean; - targetPath: string; - problem: InstallProblem | null; - failurePaths: string[]; - onAcknowledgedChange: (acknowledged: boolean) => void; - onClose: () => void; - onConfirm: () => void | Promise; -}) { - const { t } = useI18n(); - - return ( - - - {t('resetDataTarget', { path: targetPath })} - - }> -

    {t('resetDataConfirmBody')}

    -
    - }> -

    {t('resetDataConfirmKeepsInstall')}

    -

    {t('resetDataConfirmGameClosed')}

    -
    - {problem && } - {failurePaths.length > 0 && ( - - )} -
    - ); -} diff --git a/bazaarplusplus-installer/src/features/install/ResetDataFailureDetails.tsx b/bazaarplusplus-installer/src/features/install/ResetDataFailureDetails.tsx deleted file mode 100644 index dc4f61e..0000000 --- a/bazaarplusplus-installer/src/features/install/ResetDataFailureDetails.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { ChevronRight, Clipboard, ListX } from 'lucide-react'; -import { useState } from 'react'; -import { Button } from '../../components/ui/Button'; -import { useI18n } from '../../i18n/LocaleProvider'; - -export function ResetDataFailureDetails({ paths }: { paths: string[] }) { - const { t } = useI18n(); - const [copyState, setCopyState] = useState<'idle' | 'copied' | 'failed'>( - 'idle' - ); - - if (paths.length === 0) return null; - - const diagnosticText = [ - 'BazaarPlusPlus reset local data partial failure:', - ...paths.map((path) => `- ${path}`) - ].join('\n'); - - const copyDiagnostics = () => { - const write = navigator.clipboard?.writeText(diagnosticText); - if (!write) { - setCopyState('failed'); - window.setTimeout(() => setCopyState('idle'), 2400); - return; - } - void write - .then(() => { - setCopyState('copied'); - window.setTimeout(() => setCopyState('idle'), 1600); - }) - .catch(() => { - setCopyState('failed'); - window.setTimeout(() => setCopyState('idle'), 2400); - }); - }; - - return ( -
    - - - - {t('resetDataFailureDetails')} - -
    -
      - {paths.map((path) => ( -
    • - {path} -
    • - ))} -
    - -
    -
    - ); -} diff --git a/bazaarplusplus-installer/src/features/install/UninstallConfirmModal.tsx b/bazaarplusplus-installer/src/features/install/UninstallConfirmModal.tsx deleted file mode 100644 index 2e7d767..0000000 --- a/bazaarplusplus-installer/src/features/install/UninstallConfirmModal.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { PackageMinus, ShieldCheck } from 'lucide-react'; -import { - ConfirmDialog, - ConfirmNote, - ConfirmTarget -} from '../../components/ui/ConfirmDialog'; -import { useI18n } from '../../i18n/LocaleProvider'; -import { InstallProblemBanner } from './InstallProblemBanner'; -import type { InstallProblem } from './installProblems'; - -export function UninstallConfirmModal({ - busy, - targetPath, - problem, - onClose, - onConfirm -}: { - busy: boolean; - targetPath: string; - problem: InstallProblem | null; - onClose: () => void; - onConfirm: () => void | Promise; -}) { - const { t } = useI18n(); - - return ( - - - {t('uninstallTarget', { path: targetPath })} - - }> -

    {t('uninstallConfirmBody')}

    -
    - }> -

    {t('uninstallConfirmKeepsData')}

    -
    - {problem && } -
    - ); -} diff --git a/bazaarplusplus-installer/src/features/install/installProblems.test.ts b/bazaarplusplus-installer/src/features/install/installProblems.test.ts deleted file mode 100644 index bc5c510..0000000 --- a/bazaarplusplus-installer/src/features/install/installProblems.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { formatMessage } from '../../i18n/messages'; -import { createUiProblem } from '../shared/problems'; -import { - installFailurePaths, - presentInstallProblem, - presentInstallWarning -} from './installProblems'; - -const warnings = [ - { code: 'game_missing', params: {} }, - { code: 'steam_config_unavailable', params: {} }, - { code: 'launch_options_not_empty', params: {} }, - { code: 'trampoline_not_ready', params: {} }, - { code: 'obsolete_macos_artifacts', params: {} } -] as const; - -const problems = [ - createUiProblem('install_detection_failed', { - params: { operation: 'detect_state' } - }), - createUiProblem('install_action_failed', { - params: { operation: 'choose_directory' } - }), - createUiProblem('install_action_failed', { - params: { operation: 'install' } - }), - createUiProblem('install_action_failed', { - params: { operation: 'uninstall' } - }), - createUiProblem('install_action_failed', { - params: { operation: 'launch' } - }), - createUiProblem('install_blocked_by_game'), - createUiProblem('reset_blocked_by_game'), - createUiProblem('bepinex_reset_blocked_by_game'), - createUiProblem('import_blocked_by_game'), - createUiProblem('legacy_delete_blocked_by_game'), - createUiProblem('install_partial_failure', { - params: { operation: 'reset_bpp_data', count: '2' } - }), - createUiProblem('install_partial_failure', { - params: { operation: 'reset_bepinex', count: '2' } - }), - createUiProblem('install_action_failed', { - params: { operation: 'get_legacy_data_state' } - }), - createUiProblem('install_action_failed', { - params: { operation: 'delete_legacy_root' } - }), - createUiProblem('install_partial_failure', { - params: { operation: 'delete_legacy_root', count: '2' } - }), - ...[ - 'already_imported', - 'not_eligible', - 'mod_contract_invalid', - 'v5_schema_unsupported', - 'insufficient_space', - 'file_placement_failed', - 'target_write_failed', - 'marker_not_written' - ].map((reason) => - createUiProblem('import_failed', { - params: { operation: 'import_v5_history', reason } - }) - ), - createUiProblem('install_unexpected') -] as const; - -const presentImportFailure = (reason: string) => - presentInstallProblem( - createUiProblem('import_failed', { - params: { operation: 'import_v5_history', reason } - }), - (key, params) => formatMessage('en', key, params) - ); - -describe('Install semantic presentation', () => { - it.each(warnings)( - 'localizes warning $code in Chinese and English', - (warning) => { - const zh = presentInstallWarning(warning, (key, params) => - formatMessage('zh', key, params) - ); - const en = presentInstallWarning(warning, (key, params) => - formatMessage('en', key, params) - ); - - expect(zh).not.toBe(warning.code); - expect(en).not.toBe(warning.code); - expect(en).not.toBe(zh); - } - ); - - it.each(problems)( - 'localizes problem $code $params with recovery copy', - (problem) => { - const zh = presentInstallProblem(problem, (key, params) => - formatMessage('zh', key, params) - ); - const en = presentInstallProblem(problem, (key, params) => - formatMessage('en', key, params) - ); - - expect(zh).not.toBe(problem.code); - expect(en).not.toBe(problem.code); - expect(en).not.toBe(zh); - } - ); - - it('names the legacy folder, not local data, when its deletion partly fails', () => { - expect( - presentInstallProblem( - createUiProblem('install_partial_failure', { - params: { operation: 'delete_legacy_root', count: '2' } - }), - (key, params) => formatMessage('en', key, params) - ) - ).toBe(formatMessage('en', 'legacyDeletePartialFailure', { count: '2' })); - }); - - it('tells an import that committed without its marker apart from one rolled back', () => { - expect(presentImportFailure('marker_not_written')).toBe( - formatMessage('en', 'importFailedMarker') - ); - expect(presentImportFailure('file_conflict')).toBe( - formatMessage('en', 'importFailedFiles') - ); - // A reason this build does not know still says the import was undone. - expect(presentImportFailure('some_future_reason')).toBe( - formatMessage('en', 'importFailedTarget') - ); - }); - - it('recovers partial-failure paths from semantic parameters', () => { - expect( - installFailurePaths( - createUiProblem('install_partial_failure', { - params: { paths: '/tmp/a\u001f/tmp/b', count: '2' } - }) - ) - ).toEqual(['/tmp/a', '/tmp/b']); - }); -}); diff --git a/bazaarplusplus-installer/src/features/install/installProblems.ts b/bazaarplusplus-installer/src/features/install/installProblems.ts deleted file mode 100644 index 16259d9..0000000 --- a/bazaarplusplus-installer/src/features/install/installProblems.ts +++ /dev/null @@ -1,199 +0,0 @@ -import type { Translate } from '../../i18n/LocaleProvider'; -import type { MessageKey } from '../../i18n/messages'; -import { - createUiProblem, - problemFromError, - type UiProblem -} from '../shared/problems'; - -export type InstallProblemCode = - | 'install_detection_failed' - | 'install_action_failed' - | 'install_partial_failure' - | 'import_failed' - | GameRunningProblemCode - | 'install_unexpected'; - -/** One code per operation that refuses while The Bazaar runs. */ -type GameRunningProblemCode = - | 'install_blocked_by_game' - | 'reset_blocked_by_game' - | 'bepinex_reset_blocked_by_game' - | 'import_blocked_by_game' - | 'legacy_delete_blocked_by_game'; - -export type InstallProblem = UiProblem; - -type InstallWarning = { - code: string; - params: Record; -}; - -export function installProblemFromError(error: unknown): InstallProblem { - const problem: UiProblem = problemFromError(error, 'install_unexpected'); - switch (problem.code) { - case 'install_detection_failed': - case 'install_action_failed': - case 'install_partial_failure': - case 'import_failed': - case 'install_blocked_by_game': - case 'reset_blocked_by_game': - case 'bepinex_reset_blocked_by_game': - case 'import_blocked_by_game': - case 'legacy_delete_blocked_by_game': - case 'install_unexpected': - return problem as InstallProblem; - default: - return createUiProblem('install_unexpected', { - params: problem.params, - diagnostic: problem.diagnostic - }); - } -} - -export function presentInstallWarning( - warning: InstallWarning, - t: Translate -): string { - return t(installWarningMessageKey(warning.code), warning.params); -} - -export function presentInstallProblem( - problem: InstallProblem, - t: Translate -): string { - return t(installProblemMessageKey(problem), problem.params); -} - -export function installFailurePaths(problem: InstallProblem): string[] { - if (problem.code !== 'install_partial_failure') return []; - return (problem.params.paths ?? '') - .split('\u001f') - .map((path) => path.trim()) - .filter(Boolean); -} - -export type InstallNoticePresentationCode = - | 'install_done' - | 'uninstall_done' - | 'reset_data_done' - | 'reset_data_nothing_to_delete' - | 'reset_bepinex_done' - | 'reset_bepinex_nothing_to_delete'; - -export function presentInstallNotice( - code: InstallNoticePresentationCode, - t: Translate -): string { - switch (code) { - case 'install_done': - return t('installDone'); - case 'uninstall_done': - return t('uninstallDone'); - case 'reset_data_done': - return t('resetDataDone'); - case 'reset_data_nothing_to_delete': - return t('resetDataNothingToDelete'); - case 'reset_bepinex_done': - return t('resetBepinexDone'); - case 'reset_bepinex_nothing_to_delete': - return t('resetBepinexNothingToDelete'); - } -} - -function installWarningMessageKey(code: string): MessageKey { - switch (code) { - case 'game_missing': - return 'installWarningGameMissing'; - case 'steam_config_unavailable': - return 'installWarningSteamConfigUnavailable'; - case 'launch_options_not_empty': - return 'installWarningLaunchOptionsNotEmpty'; - case 'trampoline_not_ready': - return 'installWarningTrampolineNotReady'; - case 'obsolete_macos_artifacts': - return 'installWarningObsoleteMacosArtifacts'; - default: - return 'installWarningUnexpected'; - } -} - -function installProblemMessageKey(problem: InstallProblem): MessageKey { - switch (problem.code) { - case 'install_detection_failed': - return 'installProblemDetectionFailed'; - case 'install_blocked_by_game': - return 'installBlockedByGame'; - case 'reset_blocked_by_game': - return 'resetDataBlockedByGame'; - case 'bepinex_reset_blocked_by_game': - return 'resetBepinexBlockedByGame'; - case 'import_blocked_by_game': - return 'importBlockedByGame'; - case 'legacy_delete_blocked_by_game': - return 'legacyDeleteBlockedByGame'; - case 'import_failed': - return importFailureMessageKey(problem.params.reason); - case 'install_partial_failure': - switch (problem.params.operation) { - case 'reset_bepinex': - return 'resetBepinexPartialFailure'; - case 'delete_legacy_root': - return 'legacyDeletePartialFailure'; - default: - return 'resetDataPartialFailure'; - } - case 'install_action_failed': - switch (problem.params.operation) { - case 'choose_directory': - return 'installProblemChooseDirectoryFailed'; - case 'install': - return 'installProblemInstallFailed'; - case 'reset_bpp_data': - return 'installProblemResetDataFailed'; - case 'reset_bepinex': - return 'installProblemResetBepinexFailed'; - case 'uninstall': - return 'installProblemUninstallFailed'; - case 'launch': - return 'installProblemLaunchFailed'; - case 'get_legacy_data_state': - return 'installProblemLegacyDataFailed'; - case 'delete_legacy_root': - return 'installProblemLegacyDeleteFailed'; - default: - return 'installProblemUnexpected'; - } - case 'install_unexpected': - return 'installProblemUnexpected'; - } -} - -/** `reason` is the native `ImportError::code`; an unknown one reads as a - * failed write, which the import always rolls back. */ -function importFailureMessageKey(reason: string | undefined): MessageKey { - switch (reason) { - case 'already_imported': - return 'importFailedAlreadyImported'; - case 'not_eligible': - case 'invalid_game_path': - return 'importFailedNotEligible'; - case 'mod_contract_invalid': - return 'importFailedModContract'; - case 'v5_database_missing': - case 'v5_database_unreadable': - case 'v5_schema_unsupported': - case 'v5_schema_missing_column': - case 'v5_value_invalid': - return 'importFailedV5Database'; - case 'insufficient_space': - return 'importFailedInsufficientSpace'; - case 'file_conflict': - case 'file_placement_failed': - return 'importFailedFiles'; - case 'marker_not_written': - return 'importFailedMarker'; - default: - return 'importFailedTarget'; - } -} diff --git a/bazaarplusplus-installer/src/features/install/installWorkflow.test.ts b/bazaarplusplus-installer/src/features/install/installWorkflow.test.ts deleted file mode 100644 index dc7dc36..0000000 --- a/bazaarplusplus-installer/src/features/install/installWorkflow.test.ts +++ /dev/null @@ -1,594 +0,0 @@ -// Isolated on purpose: the Install page's rendered states (game missing, -// installable, installed, detection failed) are anchored by -// src/shell.snapshot.test.tsx. These cases cover transitions and settle order a -// static snapshot cannot observe. -// - A blocking detection failure cannot be recovered by refresh, or a refresh -// failure drops a ready snapshot. -// - A second operation queues behind or interleaves with a running one. -// - Directory selection and its state load run as two operations, or a -// cancelled selection drops the current state. -// - A confirmation retargets mid-operation, or a retry runs with different -// parameters than the confirmed ones. -// - A mutation's returned state is read again, a failed mutation does not -// reconcile against its fixed target, or a reconciliation failure hides the -// action problem. -// - A notice repeats or needs a timer to clear, or a completion that settles -// after dispose updates the page. -import { describe, expect, it, vi } from 'vitest'; -import type { InstallState } from '../../types/backend'; -import { - createInstallWorkflow, - type InstallCommandPort -} from './installWorkflow'; - -function installState(overrides: Partial = {}): InstallState { - return { - selected_game_path: '/Applications/The Bazaar', - steam_path: '/Applications/Steam', - game: { path_valid: true }, - mod_state: { - installed: false, - ready: false - }, - actions: { - can_install: true, - can_reinstall: false, - can_reset_data: true, - can_reset_bepinex: true, - can_uninstall: false, - can_launch: true - }, - has_resettable_data: true, - has_bepinex_files: true, - warnings: [], - ...overrides - }; -} - -function installedState(overrides: Partial = {}): InstallState { - return installState({ - mod_state: { - installed: true, - ready: true - }, - actions: { - can_install: false, - can_reinstall: true, - can_reset_data: true, - can_reset_bepinex: true, - can_uninstall: true, - can_launch: true - }, - ...overrides - }); -} - -function deferred() { - let resolve!: (value: T) => void; - let reject!: (error: unknown) => void; - const promise = new Promise((resolvePromise, rejectPromise) => { - resolve = resolvePromise; - reject = rejectPromise; - }); - return { promise, resolve, reject }; -} - -function fakeCommands( - overrides: Partial = {} -): InstallCommandPort { - return { - getInstallState: vi.fn().mockResolvedValue(installState()), - chooseGameDirectory: vi - .fn() - .mockResolvedValue({ game_path: '/Applications/The Bazaar' }), - installMod: vi.fn().mockResolvedValue(installedState()), - resetBppData: vi.fn().mockResolvedValue({ - state: installedState({ has_resettable_data: false }), - removed_data: true - }), - resetBepinex: vi.fn().mockResolvedValue({ - state: installedState({ has_bepinex_files: false }), - removed: true - }), - uninstallMod: vi.fn().mockResolvedValue(installState()), - launchGame: vi.fn().mockResolvedValue(undefined), - ...overrides - }; -} - -function setup(commandOverrides: Partial = {}) { - const commands = fakeCommands(commandOverrides); - const workflow = createInstallWorkflow({ commands }); - return { workflow, commands }; -} - -async function flush() { - await Promise.resolve(); - await Promise.resolve(); -} - -describe('install workflow loading and refresh', () => { - it('loads authoritative state on start and retries from blocking failure', async () => { - const getInstallState = vi - .fn() - .mockRejectedValueOnce(new Error('detect failed')) - .mockResolvedValueOnce(installState()); - const { workflow } = setup({ getInstallState }); - - await workflow.start(); - expect(workflow.getSnapshot()).toMatchObject({ - phase: 'blocking-failure', - problem: { diagnostic: 'detect failed' } - }); - expect(await workflow.intents.refresh()).toBe(true); - expect(workflow.getSnapshot()).toMatchObject({ - phase: 'ready', - data: { selected_game_path: '/Applications/The Bazaar' }, - refresh: { phase: 'idle' } - }); - }); - - it('preserves ready install state during refresh and after refresh failure', async () => { - const ready = installState(); - const refresh = deferred(); - const getInstallState = vi - .fn() - .mockResolvedValueOnce(ready) - .mockImplementationOnce(() => refresh.promise); - const { workflow } = setup({ getInstallState }); - await workflow.start(); - - const refreshPromise = workflow.intents.refresh(); - await flush(); - expect(workflow.getSnapshot()).toMatchObject({ - phase: 'ready', - data: ready, - refresh: { phase: 'refreshing' }, - operation: 'refresh' - }); - - refresh.reject(new Error('refresh failed')); - expect(await refreshPromise).toBe(false); - expect(workflow.getSnapshot()).toMatchObject({ - phase: 'ready', - data: ready, - refresh: { - phase: 'failed', - problem: { diagnostic: 'refresh failed' } - }, - operation: null - }); - }); -}); - -describe('install workflow concurrency and directory selection', () => { - it('rejects conflicting operations instead of queuing them', async () => { - const slow = deferred(); - const getInstallState = vi - .fn() - .mockResolvedValueOnce(installState()) - .mockImplementation(() => slow.promise); - const { workflow, commands } = setup({ getInstallState }); - await workflow.start(); - - const first = workflow.intents.refresh(); - await flush(); - expect(await workflow.intents.refresh()).toBe(false); - expect(await workflow.intents.chooseDirectory()).toBe(false); - expect(workflow.intents.requestInstall()).toBe(false); - expect(workflow.intents.requestUninstall()).toBe(false); - expect(await workflow.intents.launch()).toBe(false); - - slow.resolve(installState()); - expect(await first).toBe(true); - expect(commands.getInstallState).toHaveBeenCalledTimes(2); - }); - - it('treats directory selection plus state load as one operation and keeps state on cancel', async () => { - const ready = installState(); - const selection = deferred<{ game_path: string | null }>(); - const getInstallState = vi.fn().mockResolvedValue(ready); - const { workflow, commands } = setup({ - getInstallState, - chooseGameDirectory: vi.fn(() => selection.promise) - }); - await workflow.start(); - - const choosePromise = workflow.intents.chooseDirectory(); - await flush(); - expect(workflow.getSnapshot().operation).toBe('choose'); - expect(await workflow.intents.refresh()).toBe(false); - - selection.resolve({ game_path: null }); - expect(await choosePromise).toBe(true); - expect(workflow.getSnapshot()).toMatchObject({ - phase: 'ready', - data: ready, - operation: null - }); - expect(commands.getInstallState).toHaveBeenCalledTimes(1); - - const next = installState({ - selected_game_path: '/Games/The Bazaar', - mod_state: { - installed: true, - ready: true - } - }); - ( - commands.chooseGameDirectory as ReturnType - ).mockResolvedValue({ game_path: '/Games/The Bazaar' }); - (commands.getInstallState as ReturnType).mockResolvedValue( - next - ); - expect(await workflow.intents.chooseDirectory()).toBe(true); - expect(workflow.getSnapshot().data?.selected_game_path).toBe( - '/Games/The Bazaar' - ); - }); -}); - -describe('install workflow confirmation lifecycle', () => { - it('captures and locks the install target while the operation runs', async () => { - const installMod = vi.fn().mockResolvedValue(installedState()); - const { workflow } = setup({ installMod }); - await workflow.start(); - - expect(workflow.intents.requestInstall()).toBe(true); - expect(workflow.getSnapshot().confirmation).toMatchObject({ - phase: 'confirming', - target: { - kind: 'install', - gamePath: '/Applications/The Bazaar' - } - }); - expect(workflow.getSnapshot().actions.chooseDirectory).toBe(false); - expect(await workflow.intents.refresh()).toBe(false); - - const running = deferred(); - installMod.mockImplementationOnce(() => running.promise); - const confirmPromise = workflow.intents.confirm(); - await flush(); - - expect(workflow.getSnapshot().confirmation).toMatchObject({ - phase: 'running', - target: { - gamePath: '/Applications/The Bazaar' - } - }); - expect(workflow.intents.dismissConfirmation()).toBe(false); - expect(await workflow.intents.refresh()).toBe(false); - - running.resolve(installedState()); - expect(await confirmPromise).toBe(true); - expect(installMod).toHaveBeenCalledWith('/Applications/The Bazaar'); - expect(workflow.getSnapshot().confirmation).toBeNull(); - expect(workflow.getSnapshot().notice?.code).toBe('install_done'); - }); - - it('retains fixed reset targets through failure, exact retry, and safe exit', async () => { - const resetBppData = vi - .fn() - .mockRejectedValueOnce(new Error('reset failed')) - .mockResolvedValueOnce({ - state: installedState({ has_resettable_data: false }), - removed_data: true - }); - const getInstallState = vi - .fn() - .mockResolvedValueOnce(installedState()) - .mockResolvedValue(installedState({ has_resettable_data: true })); - const { workflow } = setup({ getInstallState, resetBppData }); - await workflow.start(); - - expect(workflow.intents.requestResetData()).toBe(true); - expect(workflow.getSnapshot().confirmation).toMatchObject({ - phase: 'confirming', - target: { - kind: 'reset-data', - gamePath: '/Applications/The Bazaar' - } - }); - - expect(await workflow.intents.confirm()).toBe(false); - expect(workflow.getSnapshot().confirmation).toMatchObject({ - phase: 'failed', - target: { - kind: 'reset-data', - gamePath: '/Applications/The Bazaar' - }, - problem: { diagnostic: 'reset failed' } - }); - expect(resetBppData).toHaveBeenCalledWith('/Applications/The Bazaar'); - - expect(await workflow.intents.confirm()).toBe(true); - expect(resetBppData).toHaveBeenLastCalledWith('/Applications/The Bazaar'); - expect(workflow.getSnapshot().notice?.code).toBe('reset_data_done'); - expect(workflow.getSnapshot().confirmation).toBeNull(); - - expect(workflow.intents.requestResetBepinex()).toBe(true); - expect(workflow.intents.dismissConfirmation()).toBe(true); - expect(workflow.getSnapshot().confirmation).toBeNull(); - }); - - it('keeps install confirmation open after failure and retries original params', async () => { - const installMod = vi - .fn() - .mockRejectedValueOnce(new Error('install failed')) - .mockResolvedValueOnce(installedState()); - const { workflow } = setup({ installMod }); - await workflow.start(); - - expect(workflow.intents.requestInstall()).toBe(true); - expect(await workflow.intents.confirm()).toBe(false); - expect(workflow.getSnapshot().confirmation).toMatchObject({ - phase: 'failed', - target: { - kind: 'install', - gamePath: '/Applications/The Bazaar' - }, - problem: { diagnostic: 'install failed' } - }); - - expect(await workflow.intents.confirm()).toBe(true); - expect(installMod).toHaveBeenLastCalledWith('/Applications/The Bazaar'); - expect(workflow.getSnapshot().confirmation).toBeNull(); - }); -}); - -describe('install workflow mutation outcomes', () => { - it('adopts returned install state without an extra read', async () => { - const returned = installedState({ - selected_game_path: '/Applications/The Bazaar', - mod_state: { - installed: true, - ready: true - } - }); - const getInstallState = vi.fn().mockResolvedValue(installState()); - const { workflow, commands } = setup({ - getInstallState, - installMod: vi.fn().mockResolvedValue(returned) - }); - await workflow.start(); - expect(getInstallState).toHaveBeenCalledTimes(1); - - expect(workflow.intents.requestInstall()).toBe(true); - expect(await workflow.intents.confirm()).toBe(true); - expect(workflow.getSnapshot().data).toBe(returned); - expect(getInstallState).toHaveBeenCalledTimes(1); - expect(commands.installMod).toHaveBeenCalledTimes(1); - }); - - it('reconciles against the fixed target after failure and keeps the action problem primary', async () => { - const reconciled = installedState({ - warnings: [{ code: 'trampoline_not_ready', params: {} }] - }); - const getInstallState = vi - .fn() - .mockResolvedValueOnce(installState()) - .mockResolvedValueOnce(reconciled); - const { workflow } = setup({ - getInstallState, - installMod: vi.fn().mockRejectedValue(new Error('partial native work')) - }); - await workflow.start(); - - expect(workflow.intents.requestInstall()).toBe(true); - expect(await workflow.intents.confirm()).toBe(false); - expect(workflow.getSnapshot().confirmation).toMatchObject({ - phase: 'failed', - problem: { diagnostic: 'partial native work' } - }); - expect(workflow.getSnapshot().data).toEqual(reconciled); - expect(workflow.getSnapshot().reconciliationProblem).toBeNull(); - expect(getInstallState).toHaveBeenLastCalledWith( - '/Applications/The Bazaar' - ); - }); - - it('retains prior snapshot and records a separate reconciliation problem when both calls fail', async () => { - const ready = installState(); - const getInstallState = vi - .fn() - .mockResolvedValueOnce(ready) - .mockRejectedValueOnce(new Error('reconcile failed')); - const { workflow } = setup({ - getInstallState, - uninstallMod: vi.fn().mockRejectedValue(new Error('uninstall failed')) - }); - await workflow.start(); - - expect(workflow.intents.requestUninstall()).toBe(true); - expect(await workflow.intents.confirm()).toBe(false); - expect(workflow.getSnapshot()).toMatchObject({ - phase: 'ready', - data: ready, - confirmation: { - phase: 'failed', - problem: { diagnostic: 'uninstall failed' } - }, - reconciliationProblem: { diagnostic: 'reconcile failed' } - }); - }); - - it('distinguishes removed and nothing-to-delete reset notices', async () => { - const { workflow, commands } = setup({ - getInstallState: vi.fn().mockResolvedValue( - installedState({ - has_resettable_data: false, - has_bepinex_files: false - }) - ), - resetBppData: vi.fn().mockResolvedValue({ - state: installedState({ has_resettable_data: false }), - removed_data: false - }), - resetBepinex: vi.fn().mockResolvedValue({ - state: installedState({ has_bepinex_files: false }), - removed: false - }) - }); - await workflow.start(); - - expect(workflow.intents.requestResetData()).toBe(true); - expect(await workflow.intents.confirm()).toBe(true); - expect(workflow.getSnapshot().notice?.code).toBe( - 'reset_data_nothing_to_delete' - ); - expect(commands.resetBppData).not.toHaveBeenCalled(); - - expect(workflow.intents.requestResetBepinex()).toBe(true); - expect(await workflow.intents.confirm()).toBe(true); - expect(workflow.getSnapshot().notice?.code).toBe( - 'reset_bepinex_nothing_to_delete' - ); - expect(commands.resetBepinex).not.toHaveBeenCalled(); - }); - - it('uninstalls through confirmation and launches without install-state reconciliation', async () => { - const getInstallState = vi.fn().mockResolvedValue(installedState()); - const { workflow, commands } = setup({ - getInstallState, - uninstallMod: vi.fn().mockResolvedValue(installState()), - launchGame: vi.fn().mockResolvedValue(undefined) - }); - await workflow.start(); - - expect(workflow.intents.requestUninstall()).toBe(true); - expect(workflow.getSnapshot().confirmation).toMatchObject({ - phase: 'confirming', - target: { kind: 'uninstall', gamePath: '/Applications/The Bazaar' } - }); - expect(commands.uninstallMod).not.toHaveBeenCalled(); - - expect(await workflow.intents.confirm()).toBe(true); - expect(workflow.getSnapshot().notice?.code).toBe('uninstall_done'); - expect(workflow.getSnapshot().confirmation).toBeNull(); - expect(commands.uninstallMod).toHaveBeenCalledTimes(1); - - expect(await workflow.intents.launch()).toBe(true); - expect(commands.launchGame).toHaveBeenCalledTimes(1); - expect(getInstallState).toHaveBeenCalledTimes(1); - }); -}); - -describe('install workflow notices, lifecycle, and availability', () => { - it('publishes unique notices for acknowledgement without timers', async () => { - const { workflow } = setup({ - uninstallMod: vi.fn().mockResolvedValue(installState()) - }); - await workflow.start(); - - expect(workflow.intents.requestUninstall()).toBe(true); - expect(await workflow.intents.confirm()).toBe(true); - const first = workflow.getSnapshot().notice; - expect(first).toMatchObject({ code: 'uninstall_done' }); - expect(first?.id).toEqual(expect.any(Number)); - - workflow.intents.acknowledgeNotice(first!.id); - expect(workflow.getSnapshot().notice).toBeNull(); - - expect(workflow.intents.requestUninstall()).toBe(true); - expect(await workflow.intents.confirm()).toBe(true); - const second = workflow.getSnapshot().notice; - expect(second?.id).not.toBe(first?.id); - }); - - it('ignores late completions after dispose and reloads on a new start', async () => { - const firstLoad = deferred(); - const secondLoad = deferred(); - const getInstallState = vi - .fn() - .mockImplementationOnce(() => firstLoad.promise) - .mockImplementationOnce(() => secondLoad.promise); - const { workflow } = setup({ getInstallState }); - - const firstStart = workflow.start(); - const before = workflow.getSnapshot(); - workflow.dispose(); - firstLoad.resolve(installState({ selected_game_path: '/stale' })); - await firstStart; - expect(workflow.getSnapshot()).toBe(before); - - const secondStart = workflow.start(); - secondLoad.resolve(installState({ selected_game_path: '/fresh' })); - await secondStart; - expect(workflow.getSnapshot()).toMatchObject({ - phase: 'ready', - data: { selected_game_path: '/fresh' } - }); - }); - - it.each([ - { - name: 'invalid or missing path', - state: installState({ - selected_game_path: null, - game: { path_valid: false }, - actions: { - can_install: false, - can_reinstall: false, - can_reset_data: false, - can_reset_bepinex: false, - can_uninstall: false, - can_launch: false - } - }), - mode: 'choose-directory', - operation: 'choose' - }, - { - name: 'valid path without the mod', - state: installState(), - mode: 'install', - operation: 'install' - }, - { - name: 'installed version mismatch', - state: installedState({ - mod_state: { - installed: true, - ready: false - } - }), - mode: 'repair', - operation: 'install' - }, - { - name: 'platform bootstrap needs repair', - state: installedState({ - mod_state: { - installed: true, - ready: false - } - }), - mode: 'repair', - operation: 'install' - }, - { - name: 'current installed state', - state: installedState(), - mode: 'launch', - operation: 'launch' - } - ])( - 'derives primary action and availability for $name', - async ({ state, mode, operation }) => { - const { workflow } = setup({ - getInstallState: vi.fn().mockResolvedValue(state) - }); - await workflow.start(); - const snapshot = workflow.getSnapshot(); - expect(snapshot.phase).toBe('ready'); - if (snapshot.phase !== 'ready') return; - expect(snapshot.primaryAction).toMatchObject({ - mode, - operation, - disabled: false, - running: false - }); - expect(snapshot.actions.chooseDirectory).toBe(true); - } - ); -}); diff --git a/bazaarplusplus-installer/src/features/install/installWorkflow.ts b/bazaarplusplus-installer/src/features/install/installWorkflow.ts deleted file mode 100644 index e93b11f..0000000 --- a/bazaarplusplus-installer/src/features/install/installWorkflow.ts +++ /dev/null @@ -1,710 +0,0 @@ -import type { CommandAdapter } from '../../api/commandAdapter'; -import type { InstallState } from '../../types/backend'; -import { - createConfirmedOperationController, - type ConfirmedOperationOutcome -} from '../shared/confirmedOperation'; -import type { PageRefreshState } from '../shared/pageState'; -import { - installProblemFromError, - type InstallProblem -} from './installProblems'; - -export type InstallOperation = - | 'refresh' - | 'choose' - | 'install' - | 'resetData' - | 'resetBepinex' - | 'uninstall' - | 'launch'; - -export type InstallPrimaryActionMode = - 'choose-directory' | 'install' | 'repair' | 'launch'; - -export type InstallPrimaryAction = { - mode: InstallPrimaryActionMode; - operation: Extract; - disabled: boolean; - running: boolean; -}; - -export type InstallConfirmationTarget = - | { kind: 'install'; gamePath: string } - | { kind: 'reset-data'; gamePath: string } - | { kind: 'reset-bepinex'; gamePath: string } - | { kind: 'uninstall'; gamePath: string }; - -export type InstallConfirmation = - | { - phase: 'confirming' | 'running'; - target: InstallConfirmationTarget; - problem: null; - } - | { - phase: 'failed'; - target: InstallConfirmationTarget; - problem: InstallProblem; - }; - -export type InstallNoticeCode = - | 'install_done' - | 'uninstall_done' - | 'reset_data_done' - | 'reset_data_nothing_to_delete' - | 'reset_bepinex_done' - | 'reset_bepinex_nothing_to_delete'; - -export type InstallNotice = { - id: number; - code: InstallNoticeCode; -}; - -export type InstallActionAvailability = { - chooseDirectory: boolean; - requestResetData: boolean; - requestResetBepinex: boolean; - requestUninstall: boolean; -}; - -export type InstallPageSnapshot = - | { - phase: 'initial-loading'; - data: null; - refresh: null; - problem: null; - operation: InstallOperation | null; - confirmation: InstallConfirmation | null; - primaryAction: null; - actions: InstallActionAvailability; - actionProblem: InstallProblem | null; - reconciliationProblem: InstallProblem | null; - notice: InstallNotice | null; - } - | { - phase: 'blocking-failure'; - data: null; - refresh: null; - problem: InstallProblem; - operation: InstallOperation | null; - confirmation: InstallConfirmation | null; - primaryAction: null; - actions: InstallActionAvailability; - actionProblem: InstallProblem | null; - reconciliationProblem: InstallProblem | null; - notice: InstallNotice | null; - } - | { - phase: 'ready'; - data: InstallState; - refresh: PageRefreshState; - problem: null; - operation: InstallOperation | null; - confirmation: InstallConfirmation | null; - primaryAction: InstallPrimaryAction; - actions: InstallActionAvailability; - actionProblem: InstallProblem | null; - reconciliationProblem: InstallProblem | null; - notice: InstallNotice | null; - }; - -export type InstallCommandPort = Pick< - CommandAdapter, - | 'getInstallState' - | 'chooseGameDirectory' - | 'installMod' - | 'resetBppData' - | 'resetBepinex' - | 'uninstallMod' - | 'launchGame' ->; - -export interface InstallWorkflowIntents { - refresh(): Promise; - chooseDirectory(): Promise; - requestInstall(): boolean; - requestResetData(): boolean; - requestResetBepinex(): boolean; - requestUninstall(): boolean; - confirm(): Promise; - dismissConfirmation(): boolean; - launch(): Promise; - acknowledgeNotice(id: number): void; -} - -export interface InstallWorkflow { - getSnapshot(): InstallPageSnapshot; - subscribe(listener: () => void): () => void; - start(): Promise; - dispose(): void; - readonly intents: InstallWorkflowIntents; -} - -interface InstallWorkflowPorts { - commands: InstallCommandPort; -} - -type ResourcePhase = - | { kind: 'initial-loading' } - | { kind: 'blocking-failure'; problem: InstallProblem } - | { - kind: 'ready'; - data: InstallState; - refresh: PageRefreshState; - }; - -interface MutableState { - resource: ResourcePhase; - operation: InstallOperation | null; - actionProblem: InstallProblem | null; - reconciliationProblem: InstallProblem | null; - notice: InstallNotice | null; -} - -class DefaultInstallWorkflow implements InstallWorkflow { - private readonly listeners = new Set<() => void>(); - private readonly confirmation = createConfirmedOperationController< - InstallConfirmationTarget, - InstallProblem - >(); - private state: MutableState = initialState(); - private snapshot: InstallPageSnapshot; - private started = false; - private disposed = false; - private lifecycleEpoch = 0; - private requestId = 0; - private noticeId = 0; - - readonly intents: InstallWorkflowIntents = { - refresh: () => this.refresh(), - chooseDirectory: () => this.chooseDirectory(), - requestInstall: () => this.requestInstall(), - requestResetData: () => this.requestResetData(), - requestResetBepinex: () => this.requestResetBepinex(), - requestUninstall: () => this.requestUninstall(), - confirm: () => this.confirm(), - dismissConfirmation: () => this.dismissConfirmation(), - launch: () => this.launch(), - acknowledgeNotice: (id) => this.acknowledgeNotice(id) - }; - - constructor(private readonly ports: InstallWorkflowPorts) { - this.snapshot = this.deriveSnapshot(); - this.confirmation.subscribe(() => { - this.publish(); - }); - } - - getSnapshot = () => this.snapshot; - - subscribe = (listener: () => void) => { - this.listeners.add(listener); - return () => this.listeners.delete(listener); - }; - - async start() { - if (this.started) return; - this.started = true; - this.disposed = false; - const lifecycle = ++this.lifecycleEpoch; - this.state = initialState(); - this.confirmation.clear(); - this.publish(); - await this.loadState(null, lifecycle); - } - - dispose() { - if (this.disposed) return; - this.disposed = true; - this.started = false; - this.lifecycleEpoch += 1; - this.requestId += 1; - this.state.operation = null; - this.confirmation.clear(); - this.listeners.clear(); - } - - private async refresh(): Promise { - if (!this.canEnterLane() || this.hasActiveConfirmation()) return false; - const lifecycle = this.lifecycleEpoch; - const path = - this.state.resource.kind === 'ready' - ? (this.state.resource.data.selected_game_path ?? null) - : null; - return this.loadState(path, lifecycle); - } - - private async chooseDirectory(): Promise { - if (!this.canEnterLane() || this.hasActiveConfirmation()) return false; - if (this.state.resource.kind !== 'ready') return false; - - const lifecycle = this.lifecycleEpoch; - this.beginOperation('choose'); - try { - const selection = await this.ports.commands.chooseGameDirectory(); - if (!this.isCurrentLifecycle(lifecycle)) return false; - if (!selection.game_path) { - return true; - } - const data = await this.ports.commands.getInstallState( - selection.game_path - ); - if (!this.isCurrentLifecycle(lifecycle)) return false; - this.applyReadyData(data); - return true; - } catch (caught) { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.actionProblem = installProblemFromError(caught); - } - return false; - } finally { - this.endOperation(lifecycle); - } - } - - private requestInstall(): boolean { - if (!this.canOpenConfirmation()) return false; - const data = this.readyData(); - if (!data?.selected_game_path) return false; - return this.confirmation.request({ - kind: 'install', - gamePath: data.selected_game_path - }); - } - - private requestResetData(): boolean { - if (!this.canOpenConfirmation()) return false; - const data = this.readyData(); - if (!data?.selected_game_path) return false; - return this.confirmation.request({ - kind: 'reset-data', - gamePath: data.selected_game_path - }); - } - - private requestResetBepinex(): boolean { - if (!this.canOpenConfirmation()) return false; - const data = this.readyData(); - if (!data?.selected_game_path) return false; - return this.confirmation.request({ - kind: 'reset-bepinex', - gamePath: data.selected_game_path - }); - } - - private requestUninstall(): boolean { - if (!this.canOpenConfirmation()) return false; - const data = this.readyData(); - if (!data?.selected_game_path) return false; - return this.confirmation.request({ - kind: 'uninstall', - gamePath: data.selected_game_path - }); - } - - private async confirm(): Promise { - if (this.disposed || this.state.operation !== null) return false; - const current = this.confirmation.getSnapshot(); - if (!current || current.phase === 'running') return false; - - const lifecycle = this.lifecycleEpoch; - const operation = operationForConfirmation(current.target); - this.state.operation = operation; - this.state.actionProblem = null; - this.state.reconciliationProblem = null; - this.clearNotice(); - this.publish(); - - const completed = await this.confirmation.run( - (target) => this.executeConfirmed(target, lifecycle), - installProblemFromError - ); - - if (this.isCurrentLifecycle(lifecycle)) { - this.state.operation = null; - this.publish(); - } - return completed; - } - - private dismissConfirmation(): boolean { - if (this.state.operation !== null) return false; - return this.confirmation.dismiss(); - } - - private async launch(): Promise { - if (!this.canEnterLane() || this.hasActiveConfirmation()) return false; - if (this.state.resource.kind !== 'ready') return false; - - const lifecycle = this.lifecycleEpoch; - this.beginOperation('launch'); - try { - await this.ports.commands.launchGame(); - return this.isCurrentLifecycle(lifecycle); - } catch (caught) { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.actionProblem = installProblemFromError(caught); - } - return false; - } finally { - this.endOperation(lifecycle); - } - } - - private acknowledgeNotice(id: number) { - if (this.disposed) return; - if (this.state.notice?.id !== id) return; - this.state.notice = null; - this.publish(); - } - - private async executeConfirmed( - target: InstallConfirmationTarget, - lifecycle: number - ): Promise> { - try { - switch (target.kind) { - case 'install': { - const next = await this.ports.commands.installMod(target.gamePath); - if (!this.isCurrentLifecycle(lifecycle)) return { ok: true }; - this.applyReadyData(next); - this.showNotice('install_done'); - return { ok: true }; - } - case 'reset-data': { - const data = this.readyData(); - if (data && !data.has_resettable_data) { - if (!this.isCurrentLifecycle(lifecycle)) return { ok: true }; - this.showNotice('reset_data_nothing_to_delete'); - return { ok: true }; - } - const result = await this.ports.commands.resetBppData( - target.gamePath - ); - if (!this.isCurrentLifecycle(lifecycle)) return { ok: true }; - this.applyReadyData(result.state); - this.showNotice( - result.removed_data - ? 'reset_data_done' - : 'reset_data_nothing_to_delete' - ); - return { ok: true }; - } - case 'reset-bepinex': { - const data = this.readyData(); - if (data && !data.has_bepinex_files) { - if (!this.isCurrentLifecycle(lifecycle)) return { ok: true }; - this.showNotice('reset_bepinex_nothing_to_delete'); - return { ok: true }; - } - const result = await this.ports.commands.resetBepinex( - target.gamePath - ); - if (!this.isCurrentLifecycle(lifecycle)) return { ok: true }; - this.applyReadyData(result.state); - this.showNotice( - result.removed - ? 'reset_bepinex_done' - : 'reset_bepinex_nothing_to_delete' - ); - return { ok: true }; - } - case 'uninstall': { - const next = await this.ports.commands.uninstallMod(target.gamePath); - if (!this.isCurrentLifecycle(lifecycle)) return { ok: true }; - this.applyReadyData(next); - this.showNotice('uninstall_done'); - return { ok: true }; - } - } - } catch (caught) { - if (!this.isCurrentLifecycle(lifecycle)) { - return { ok: false, problem: installProblemFromError(caught) }; - } - const problem = installProblemFromError(caught); - await this.reconcile(target.gamePath, lifecycle); - return { ok: false, problem }; - } - } - - private async loadState( - gamePath: string | null, - lifecycle: number - ): Promise { - if (!this.isCurrentLifecycle(lifecycle)) return false; - if (this.state.operation !== null) return false; - - const requestId = ++this.requestId; - this.state.operation = 'refresh'; - this.state.actionProblem = null; - this.state.reconciliationProblem = null; - this.clearNotice(); - - if (this.state.resource.kind === 'ready') { - this.state.resource = { - ...this.state.resource, - refresh: { phase: 'refreshing' } - }; - } else { - this.state.resource = { kind: 'initial-loading' }; - } - this.publish(); - - try { - const data = await this.ports.commands.getInstallState(gamePath); - if (!this.isCurrentLifecycle(lifecycle) || requestId !== this.requestId) { - return false; - } - this.applyReadyData(data); - return true; - } catch (caught) { - if (!this.isCurrentLifecycle(lifecycle) || requestId !== this.requestId) { - return false; - } - const problem = installProblemFromError(caught); - if (this.state.resource.kind === 'ready') { - this.state.resource = { - ...this.state.resource, - refresh: { phase: 'failed', problem } - }; - } else { - this.state.resource = { kind: 'blocking-failure', problem }; - } - return false; - } finally { - if (this.isCurrentLifecycle(lifecycle) && requestId === this.requestId) { - this.state.operation = null; - this.publish(); - } - } - } - - private async reconcile(gamePath: string, lifecycle: number) { - try { - const data = await this.ports.commands.getInstallState(gamePath); - if (!this.isCurrentLifecycle(lifecycle)) return; - this.applyReadyData(data); - this.state.reconciliationProblem = null; - } catch (caught) { - if (!this.isCurrentLifecycle(lifecycle)) return; - this.state.reconciliationProblem = installProblemFromError(caught); - } - } - - private beginOperation(operation: InstallOperation) { - this.state.operation = operation; - this.state.actionProblem = null; - this.state.reconciliationProblem = null; - this.clearNotice(); - this.publish(); - } - - private endOperation(lifecycle: number) { - if (!this.isCurrentLifecycle(lifecycle)) return; - this.state.operation = null; - this.publish(); - } - - private applyReadyData(data: InstallState) { - this.state.resource = { - kind: 'ready', - data, - refresh: { phase: 'idle' } - }; - } - - private showNotice(code: InstallNoticeCode) { - this.noticeId += 1; - this.state.notice = { id: this.noticeId, code }; - } - - private clearNotice() { - this.state.notice = null; - } - - private readyData(): InstallState | null { - return this.state.resource.kind === 'ready' - ? this.state.resource.data - : null; - } - - private hasActiveConfirmation() { - return this.confirmation.getSnapshot() !== null; - } - - private canEnterLane() { - return !this.disposed && this.state.operation === null; - } - - private canOpenConfirmation() { - return ( - this.canEnterLane() && - !this.hasActiveConfirmation() && - this.state.resource.kind === 'ready' && - this.state.resource.refresh.phase !== 'refreshing' - ); - } - - private isCurrentLifecycle(lifecycle: number) { - return !this.disposed && lifecycle === this.lifecycleEpoch; - } - - private deriveSnapshot(): InstallPageSnapshot { - const confirmation = this.confirmation.getSnapshot(); - const operation = this.state.operation; - const busy = operation !== null; - const confirmationActive = confirmation !== null; - const refreshing = - this.state.resource.kind === 'ready' && - this.state.resource.refresh.phase === 'refreshing'; - - const baseActions: InstallActionAvailability = { - chooseDirectory: false, - requestResetData: false, - requestResetBepinex: false, - requestUninstall: false - }; - - if (this.state.resource.kind === 'initial-loading') { - return { - phase: 'initial-loading', - data: null, - refresh: null, - problem: null, - operation, - confirmation, - primaryAction: null, - actions: baseActions, - actionProblem: this.state.actionProblem, - reconciliationProblem: this.state.reconciliationProblem, - notice: this.state.notice - }; - } - - if (this.state.resource.kind === 'blocking-failure') { - return { - phase: 'blocking-failure', - data: null, - refresh: null, - problem: this.state.resource.problem, - operation, - confirmation, - primaryAction: null, - actions: baseActions, - actionProblem: this.state.actionProblem, - reconciliationProblem: this.state.reconciliationProblem, - notice: this.state.notice - }; - } - - const ready = this.state.resource; - const primaryAction = deriveInstallPrimaryAction( - ready.data, - operation, - refreshing || confirmationActive - ); - - return { - phase: 'ready', - data: ready.data, - refresh: ready.refresh, - problem: null, - operation, - confirmation, - primaryAction, - actions: { - chooseDirectory: !busy && !confirmationActive && !refreshing, - requestResetData: - !busy && - !confirmationActive && - !refreshing && - ready.data.actions.can_reset_data, - requestResetBepinex: - !busy && - !confirmationActive && - !refreshing && - ready.data.actions.can_reset_bepinex, - requestUninstall: - !busy && - !confirmationActive && - !refreshing && - ready.data.actions.can_uninstall - }, - actionProblem: this.state.actionProblem, - reconciliationProblem: this.state.reconciliationProblem, - notice: this.state.notice - }; - } - - private publish() { - if (this.disposed) return; - this.snapshot = this.deriveSnapshot(); - for (const listener of this.listeners) listener(); - } -} - -function initialState(): MutableState { - return { - resource: { kind: 'initial-loading' }, - operation: null, - actionProblem: null, - reconciliationProblem: null, - notice: null - }; -} - -function operationForConfirmation( - target: InstallConfirmationTarget -): InstallOperation { - switch (target.kind) { - case 'install': - return 'install'; - case 'reset-data': - return 'resetData'; - case 'reset-bepinex': - return 'resetBepinex'; - case 'uninstall': - return 'uninstall'; - } -} - -function deriveInstallPrimaryAction( - state: InstallState, - current: InstallOperation | null, - blocked: boolean -): InstallPrimaryAction { - let mode: InstallPrimaryActionMode; - let operation: InstallPrimaryAction['operation']; - let allowed: boolean; - - if (!state.selected_game_path || !state.game.path_valid) { - mode = 'choose-directory'; - operation = 'choose'; - allowed = true; - } else if (!state.mod_state.installed) { - mode = 'install'; - operation = 'install'; - allowed = state.actions.can_install; - } else if (!state.mod_state.ready) { - mode = 'repair'; - operation = 'install'; - allowed = state.actions.can_reinstall; - } else { - mode = 'launch'; - operation = 'launch'; - allowed = state.actions.can_launch; - } - - return { - mode, - operation, - disabled: blocked || current !== null || !allowed, - running: current === operation - }; -} - -export function createInstallWorkflow( - ports: InstallWorkflowPorts -): InstallWorkflow { - return new DefaultInstallWorkflow(ports); -} diff --git a/bazaarplusplus-installer/src/features/install/legacyDataWorkflow.test.ts b/bazaarplusplus-installer/src/features/install/legacyDataWorkflow.test.ts deleted file mode 100644 index 6fcf971..0000000 --- a/bazaarplusplus-installer/src/features/install/legacyDataWorkflow.test.ts +++ /dev/null @@ -1,325 +0,0 @@ -// Covers what the Install page cannot show statically: deletion runs only -// after a confirmation fixed to one listed root, a refusal keeps the root and -// the dialog for retry, a slower stale load never overwrites newer data, and -// the V5 import runs, fails, or completes into an offer to delete V5 that the -// user may decline. -import { describe, expect, it, vi } from 'vitest'; -import { SemanticProblemError } from '../../api/problems'; -import type { LegacyDataState } from '../../types/backend'; -import { - createLegacyDataWorkflow, - type LegacyDataCommandPort -} from './legacyDataWorkflow'; - -const GAME = '/Games/The Bazaar'; - -function state( - names: LegacyDataState['roots'][number]['name'][], - v5ImportEligible = false -) { - return { - game_path: GAME, - roots: names.map((name) => ({ - name, - size_bytes: 1024, - file_count: 1, - hard_linked_file_count: 0, - unreadable_entry_count: 0 - })), - installed_mod_data_root: 'current', - v5_import_eligible: v5ImportEligible - } satisfies LegacyDataState; -} - -function deferred() { - let resolve!: (value: T) => void; - const promise = new Promise((settle) => { - resolve = settle; - }); - return { promise, resolve: (value: T) => resolve(value) }; -} - -function commands( - overrides: Partial = {} -): LegacyDataCommandPort { - return { - getLegacyDataState: vi.fn(async () => - state(['BazaarPlusPlusV4', 'BazaarPlusPlusV5']) - ), - importV5History: vi.fn(async () => ({ - imported_run_count: 8, - skipped_run_count: 1, - unavailable_file_count: 2, - state: state(['BazaarPlusPlusV4', 'BazaarPlusPlusV5']) - })), - deleteLegacyRoot: vi.fn(async () => ({ - removed: true, - state: state(['BazaarPlusPlusV4']) - })), - ...overrides - }; -} - -describe('legacy data workflow', () => { - it('lists roots and never deletes without a confirmation', async () => { - const port = commands(); - const workflow = createLegacyDataWorkflow({ commands: port }); - - await workflow.load(GAME); - - expect(workflow.getSnapshot().load).toEqual({ - phase: 'ready', - data: state(['BazaarPlusPlusV4', 'BazaarPlusPlusV5']) - }); - expect(await workflow.confirmDelete()).toBe(false); - expect(port.deleteLegacyRoot).not.toHaveBeenCalled(); - }); - - it('deletes the confirmed root and installs the returned state', async () => { - const port = commands(); - const workflow = createLegacyDataWorkflow({ commands: port }); - await workflow.load(GAME); - - expect(workflow.requestDelete('BazaarPlusPlusV5')).toBe(true); - // A second request cannot retarget the open confirmation. - expect(workflow.requestDelete('BazaarPlusPlusV4')).toBe(false); - expect(await workflow.confirmDelete()).toBe(true); - - expect(port.deleteLegacyRoot).toHaveBeenCalledExactlyOnceWith( - GAME, - 'BazaarPlusPlusV5' - ); - const snapshot = workflow.getSnapshot(); - expect(snapshot.confirmation).toBeNull(); - expect(snapshot.load).toEqual({ - phase: 'ready', - data: state(['BazaarPlusPlusV4']) - }); - expect(snapshot.notice).toMatchObject({ - name: 'BazaarPlusPlusV5', - removed: true - }); - workflow.acknowledgeNotice(snapshot.notice!.id); - expect(workflow.getSnapshot().notice).toBeNull(); - }); - - it('refuses to request a root that is not listed', async () => { - const workflow = createLegacyDataWorkflow({ commands: commands() }); - await workflow.load(GAME); - - expect(workflow.requestDelete('BazaarPlusPlus')).toBe(false); - expect(workflow.getSnapshot().confirmation).toBeNull(); - }); - - it('keeps the confirmation with its problem when the game blocks deletion', async () => { - const port = commands({ - deleteLegacyRoot: vi.fn(async () => { - throw new SemanticProblemError({ - code: 'legacy_delete_blocked_by_game', - params: { operation: 'delete_legacy_root' }, - diagnostic: null - }); - }) - }); - const workflow = createLegacyDataWorkflow({ commands: port }); - await workflow.load(GAME); - workflow.requestDelete('BazaarPlusPlusV5'); - - expect(await workflow.confirmDelete()).toBe(false); - - const snapshot = workflow.getSnapshot(); - expect(snapshot.confirmation).toMatchObject({ - phase: 'failed', - target: { gamePath: GAME, name: 'BazaarPlusPlusV5' }, - problem: { code: 'legacy_delete_blocked_by_game' } - }); - expect(snapshot.load).toMatchObject({ - phase: 'ready', - data: state(['BazaarPlusPlusV4', 'BazaarPlusPlusV5']) - }); - expect(snapshot.notice).toBeNull(); - }); - - it('drops a load that settles after a newer one', async () => { - const pending = deferred(); - const port = commands({ - getLegacyDataState: vi - .fn() - .mockImplementationOnce(() => pending.promise) - .mockImplementationOnce(async () => state(['BazaarPlusPlus'])) - }); - const workflow = createLegacyDataWorkflow({ commands: port }); - - const first = workflow.load('/old'); - await workflow.load(GAME); - pending.resolve(state(['BazaarPlusPlusV5'])); - await first; - - expect(workflow.getSnapshot().load).toEqual({ - phase: 'ready', - data: state(['BazaarPlusPlus']) - }); - }); - - describe('V5 import', () => { - const eligible = () => state(['BazaarPlusPlusV5'], true); - - it('runs only while eligible', async () => { - const port = commands(); - const workflow = createLegacyDataWorkflow({ commands: port }); - await workflow.load(GAME); - - expect(await workflow.importV5()).toBe(false); - expect(port.importV5History).not.toHaveBeenCalled(); - }); - - it('blocks deletion while importing, then offers to delete V5', async () => { - const pending = deferred<{ - imported_run_count: number; - skipped_run_count: number; - unavailable_file_count: number; - state: LegacyDataState; - }>(); - const port = commands({ - getLegacyDataState: vi.fn(async () => eligible()), - importV5History: vi.fn(() => pending.promise) - }); - const workflow = createLegacyDataWorkflow({ commands: port }); - await workflow.load(GAME); - - const running = workflow.importV5(); - expect(workflow.getSnapshot().importRun).toEqual({ - phase: 'running', - gamePath: GAME - }); - expect(workflow.requestDelete('BazaarPlusPlusV5')).toBe(false); - expect(await workflow.importV5()).toBe(false); - - pending.resolve({ - imported_run_count: 8, - skipped_run_count: 1, - unavailable_file_count: 0, - state: state(['BazaarPlusPlusV5']) - }); - expect(await running).toBe(true); - - expect(port.importV5History).toHaveBeenCalledExactlyOnceWith(GAME); - const snapshot = workflow.getSnapshot(); - expect(snapshot.importRun).toEqual({ phase: 'idle' }); - expect(snapshot.load).toEqual({ - phase: 'ready', - data: state(['BazaarPlusPlusV5']) - }); - expect(snapshot.confirmation).toEqual({ - phase: 'confirming', - target: { - gamePath: GAME, - name: 'BazaarPlusPlusV5', - afterImport: { - imported_run_count: 8, - skipped_run_count: 1, - unavailable_file_count: 0 - } - }, - problem: null - }); - // Nothing is deleted until the user confirms the offer. - expect(port.deleteLegacyRoot).not.toHaveBeenCalled(); - }); - - it('keeps V5 listed when the user declines the offer', async () => { - const port = commands({ - getLegacyDataState: vi.fn(async () => eligible()) - }); - const workflow = createLegacyDataWorkflow({ commands: port }); - await workflow.load(GAME); - await workflow.importV5(); - - expect(workflow.dismissDelete()).toBe(true); - - const snapshot = workflow.getSnapshot(); - expect(snapshot.confirmation).toBeNull(); - expect(port.deleteLegacyRoot).not.toHaveBeenCalled(); - expect(snapshot.load).toMatchObject({ - phase: 'ready', - data: { - roots: [{ name: 'BazaarPlusPlusV4' }, { name: 'BazaarPlusPlusV5' }] - } - }); - // A later delete of V5 is the ordinary confirmation, without the offer. - expect(workflow.requestDelete('BazaarPlusPlusV5')).toBe(true); - expect(workflow.getSnapshot().confirmation?.target).toEqual({ - gamePath: GAME, - name: 'BazaarPlusPlusV5' - }); - }); - - it('deletes V5 when the user accepts the offer', async () => { - const port = commands({ - getLegacyDataState: vi.fn(async () => eligible()) - }); - const workflow = createLegacyDataWorkflow({ commands: port }); - await workflow.load(GAME); - await workflow.importV5(); - - expect(await workflow.confirmDelete()).toBe(true); - expect(port.deleteLegacyRoot).toHaveBeenCalledExactlyOnceWith( - GAME, - 'BazaarPlusPlusV5' - ); - }); - - it('keeps a failed import as a typed problem and rereads the roots', async () => { - const port = commands({ - getLegacyDataState: vi.fn(async () => eligible()), - importV5History: vi.fn(async () => { - throw new SemanticProblemError({ - code: 'import_failed', - params: { - operation: 'import_v5_history', - reason: 'insufficient_space' - }, - diagnostic: 'needs 2048 bytes' - }); - }) - }); - const workflow = createLegacyDataWorkflow({ commands: port }); - await workflow.load(GAME); - - expect(await workflow.importV5()).toBe(false); - - const snapshot = workflow.getSnapshot(); - expect(snapshot.importRun).toMatchObject({ - phase: 'failed', - problem: { - code: 'import_failed', - params: { reason: 'insufficient_space' } - } - }); - expect(snapshot.confirmation).toBeNull(); - expect(port.getLegacyDataState).toHaveBeenCalledTimes(2); - expect(port.deleteLegacyRoot).not.toHaveBeenCalled(); - }); - - it('reports a game that blocks the import with its own code', async () => { - const port = commands({ - getLegacyDataState: vi.fn(async () => eligible()), - importV5History: vi.fn(async () => { - throw new SemanticProblemError({ - code: 'import_blocked_by_game', - params: { operation: 'import_v5_history', stage: 'start' }, - diagnostic: null - }); - }) - }); - const workflow = createLegacyDataWorkflow({ commands: port }); - await workflow.load(GAME); - await workflow.importV5(); - - expect(workflow.getSnapshot().importRun).toMatchObject({ - phase: 'failed', - problem: { code: 'import_blocked_by_game' } - }); - }); - }); -}); diff --git a/bazaarplusplus-installer/src/features/install/legacyDataWorkflow.ts b/bazaarplusplus-installer/src/features/install/legacyDataWorkflow.ts deleted file mode 100644 index 25929c7..0000000 --- a/bazaarplusplus-installer/src/features/install/legacyDataWorkflow.ts +++ /dev/null @@ -1,203 +0,0 @@ -import type { CommandAdapter } from '../../api/commandAdapter'; -import type { - ImportV5HistoryResult, - LegacyDataState, - LegacyRoot -} from '../../types/backend'; -import { - createConfirmedOperationController, - type ConfirmedOperationState -} from '../shared/confirmedOperation'; -import { - installProblemFromError, - type InstallProblem -} from './installProblems'; - -export type LegacyDataCommandPort = Pick< - CommandAdapter, - 'getLegacyDataState' | 'importV5History' | 'deleteLegacyRoot' ->; - -/** What a completed V5 import reports beside the offer to delete V5. */ -export type LegacyImportSummary = Omit; - -/** - * Fixed when the confirmation opens, so a refresh cannot retarget it. - * `afterImport` marks the offer to delete `BazaarPlusPlusV5` that follows a - * completed import. - */ -export type LegacyDeleteTarget = { - gamePath: string; - name: LegacyRoot; - afterImport?: LegacyImportSummary; -}; - -/** The one-time V5 import, which runs without a confirmation: it only adds to - * the current Data Root and leaves `BazaarPlusPlusV5` as it was. */ -export type LegacyImportRun = - | { phase: 'idle' } - | { phase: 'running'; gamePath: string } - | { phase: 'failed'; problem: InstallProblem }; - -export type LegacyDataLoad = - | { phase: 'idle' } - | { phase: 'loading'; data: LegacyDataState | null } - | { phase: 'ready'; data: LegacyDataState } - | { phase: 'failed'; problem: InstallProblem }; - -export type LegacyDeleteNotice = { - id: number; - name: LegacyRoot; - removed: boolean; -}; - -export type LegacyDataSnapshot = { - load: LegacyDataLoad; - confirmation: ConfirmedOperationState; - importRun: LegacyImportRun; - notice: LegacyDeleteNotice | null; -}; - -export interface LegacyDataWorkflow { - getSnapshot(): LegacyDataSnapshot; - subscribe(listener: () => void): () => void; - load(gamePath: string | null): Promise; - importV5(): Promise; - requestDelete(name: LegacyRoot): boolean; - confirmDelete(): Promise; - dismissDelete(): boolean; - acknowledgeNotice(id: number): void; -} - -/** - * Lists the selected game directory's Legacy Roots, runs the one-time V5 - * import, and deletes one root at a time after an explicit confirmation. A - * completed import only opens the confirmation for `BazaarPlusPlusV5`; nothing - * here deletes on its own. - */ -export function createLegacyDataWorkflow({ - commands -}: { - commands: LegacyDataCommandPort; -}): LegacyDataWorkflow { - const confirmation = createConfirmedOperationController< - LegacyDeleteTarget, - InstallProblem - >(); - const listeners = new Set<() => void>(); - let load: LegacyDataLoad = { phase: 'idle' }; - let importRun: LegacyImportRun = { phase: 'idle' }; - let notice: LegacyDeleteNotice | null = null; - let nextNoticeId = 1; - // Each load or deletion bumps the generation; an older response is dropped. - let generation = 0; - let snapshot: LegacyDataSnapshot = { - load, - confirmation: confirmation.getSnapshot(), - importRun, - notice - }; - - const publish = () => { - snapshot = { - load, - confirmation: confirmation.getSnapshot(), - importRun, - notice - }; - for (const listener of listeners) listener(); - }; - confirmation.subscribe(publish); - - const currentData = (): LegacyDataState | null => - load.phase === 'ready' || load.phase === 'loading' ? load.data : null; - - const loadState = async (gamePath: string | null) => { - const requested = ++generation; - load = { phase: 'loading', data: currentData() }; - publish(); - try { - const data = await commands.getLegacyDataState(gamePath); - if (requested !== generation) return; - load = { phase: 'ready', data }; - } catch (caught) { - if (requested !== generation) return; - load = { phase: 'failed', problem: installProblemFromError(caught) }; - } - publish(); - }; - - return { - getSnapshot: () => snapshot, - subscribe: (listener) => { - listeners.add(listener); - return () => listeners.delete(listener); - }, - load: loadState, - importV5: async () => { - const data = currentData(); - if (!data?.game_path || !data.v5_import_eligible) return false; - if (importRun.phase === 'running' || confirmation.getSnapshot()) { - return false; - } - const gamePath = data.game_path; - importRun = { phase: 'running', gamePath }; - publish(); - let result: ImportV5HistoryResult; - try { - result = await commands.importV5History(gamePath); - } catch (caught) { - importRun = { - phase: 'failed', - problem: installProblemFromError(caught) - }; - publish(); - // The refusal may stem from a state this page has not seen yet, such - // as an import that completed from another window. - void loadState(gamePath); - return false; - } - generation += 1; - importRun = { phase: 'idle' }; - load = { phase: 'ready', data: result.state }; - publish(); - const { state, ...summary } = result; - if (state.roots.some((root) => root.name === 'BazaarPlusPlusV5')) { - confirmation.request({ - gamePath, - name: 'BazaarPlusPlusV5', - afterImport: summary - }); - } - return true; - }, - requestDelete: (name) => { - const data = currentData(); - if (!data?.game_path) return false; - if (importRun.phase === 'running') return false; - if (!data.roots.some((root) => root.name === name)) return false; - return confirmation.request({ gamePath: data.game_path, name }); - }, - confirmDelete: () => - confirmation.run(async (target) => { - const result = await commands.deleteLegacyRoot( - target.gamePath, - target.name - ); - generation += 1; - load = { phase: 'ready', data: result.state }; - notice = { - id: nextNoticeId++, - name: target.name, - removed: result.removed - }; - return { ok: true }; - }, installProblemFromError), - dismissDelete: () => confirmation.dismiss(), - acknowledgeNotice: (id) => { - if (notice?.id !== id) return; - notice = null; - publish(); - } - }; -} diff --git a/bazaarplusplus-installer/src/features/install/useInstallPage.ts b/bazaarplusplus-installer/src/features/install/useInstallPage.ts deleted file mode 100644 index 0478c6b..0000000 --- a/bazaarplusplus-installer/src/features/install/useInstallPage.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { useEffect, useMemo, useSyncExternalStore } from 'react'; -import { commandClient } from '../../api/commandClient'; -import { createInstallWorkflow } from './installWorkflow'; - -export function useInstallPage() { - const workflow = useMemo( - () => - createInstallWorkflow({ - commands: commandClient - }), - [] - ); - const snapshot = useSyncExternalStore( - workflow.subscribe, - workflow.getSnapshot, - workflow.getSnapshot - ); - - useEffect(() => { - void workflow.start(); - return () => workflow.dispose(); - }, [workflow]); - - return { snapshot, intents: workflow.intents }; -} diff --git a/bazaarplusplus-installer/src/features/install/useLegacyData.ts b/bazaarplusplus-installer/src/features/install/useLegacyData.ts deleted file mode 100644 index 86d8c52..0000000 --- a/bazaarplusplus-installer/src/features/install/useLegacyData.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { useEffect, useMemo, useSyncExternalStore } from 'react'; -import { commandClient } from '../../api/commandClient'; -import type { InstallState } from '../../types/backend'; -import { createLegacyDataWorkflow } from './legacyDataWorkflow'; - -/** - * Legacy Roots of the selected game directory, reloaded whenever the install - * state is redetected, for example after a reinstall changes which Data Root - * the mod writes. Nothing loads until the install state is known. - */ -export function useLegacyData(installState: InstallState | null) { - const workflow = useMemo( - () => createLegacyDataWorkflow({ commands: commandClient }), - [] - ); - const snapshot = useSyncExternalStore( - workflow.subscribe, - workflow.getSnapshot, - workflow.getSnapshot - ); - - useEffect(() => { - if (!installState) return; - void workflow.load(installState.selected_game_path); - }, [workflow, installState]); - - return { snapshot, workflow }; -} diff --git a/bazaarplusplus-installer/src/features/shared/confirmedOperation.test.ts b/bazaarplusplus-installer/src/features/shared/confirmedOperation.test.ts deleted file mode 100644 index 53fb50f..0000000 --- a/bazaarplusplus-installer/src/features/shared/confirmedOperation.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { - createConfirmedOperationController, - type ConfirmedOperationOutcome -} from './confirmedOperation'; - -function deferred() { - let resolve!: (value: T) => void; - const promise = new Promise((resolvePromise) => { - resolve = resolvePromise; - }); - return { promise, resolve }; -} - -describe('confirmed operation controller', () => { - it('keeps a non-cancelable target visible, blocks dismissal and repeated submission, then closes on success', async () => { - const controller = createConfirmedOperationController< - { kind: 'cleanup'; scope: 'screenshots' }, - string - >(); - const completion = deferred>(); - const execute = vi.fn(() => completion.promise); - - expect(controller.request({ kind: 'cleanup', scope: 'screenshots' })).toBe( - true - ); - const first = controller.run(execute, String); - - expect(controller.getSnapshot()).toMatchObject({ - phase: 'running', - target: { kind: 'cleanup', scope: 'screenshots' } - }); - expect(controller.dismiss()).toBe(false); - await expect(controller.run(execute, String)).resolves.toBe(false); - expect(execute).toHaveBeenCalledTimes(1); - - completion.resolve({ ok: true }); - await expect(first).resolves.toBe(true); - expect(controller.getSnapshot()).toBeNull(); - }); - - it('keeps target and problem on failure, supports retry, and allows a safe exit', async () => { - const controller = createConfirmedOperationController< - { kind: 'delete-video'; battleId: string }, - string - >(); - controller.request({ kind: 'delete-video', battleId: 'battle-7' }); - - await expect( - controller.run( - async () => ({ ok: false, problem: 'delete failed' }), - String - ) - ).resolves.toBe(false); - expect(controller.getSnapshot()).toEqual({ - phase: 'failed', - target: { kind: 'delete-video', battleId: 'battle-7' }, - problem: 'delete failed' - }); - - await expect( - controller.run(async () => ({ ok: true }), String) - ).resolves.toBe(true); - expect(controller.getSnapshot()).toBeNull(); - - controller.request({ kind: 'delete-video', battleId: 'battle-8' }); - expect(controller.dismiss()).toBe(true); - expect(controller.getSnapshot()).toBeNull(); - }); - - it.each([ - ['cleanup', { kind: 'cleanup', target: 'run_data:before_this_month' }], - ['reset', { kind: 'reset-data', target: '/game/BazaarPlusPlusV6' }], - ['delete', { kind: 'delete-video', target: 'battle-2/video-3' }] - ])( - '%s feature uses the shared success/failure lifecycle', - async (_, target) => { - const controller = createConfirmedOperationController< - { kind: string; target: string }, - string - >(); - controller.request(target); - await controller.run( - async () => ({ ok: false, problem: 'failed' }), - String - ); - expect(controller.getSnapshot()).toEqual({ - phase: 'failed', - target, - problem: 'failed' - }); - await controller.run(async () => ({ ok: true }), String); - expect(controller.getSnapshot()).toBeNull(); - } - ); -}); diff --git a/bazaarplusplus-installer/src/features/shared/confirmedOperation.ts b/bazaarplusplus-installer/src/features/shared/confirmedOperation.ts deleted file mode 100644 index 532111f..0000000 --- a/bazaarplusplus-installer/src/features/shared/confirmedOperation.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { useMemo, useSyncExternalStore } from 'react'; - -export type ConfirmedOperationOutcome = - { ok: true } | { ok: false; problem: TProblem }; - -export type ConfirmedOperationState = - | { - phase: 'confirming' | 'running'; - target: TTarget; - problem: null; - } - | { - phase: 'failed'; - target: TTarget; - problem: TProblem; - } - | null; - -export interface ConfirmedOperationController { - getSnapshot(): ConfirmedOperationState; - subscribe(listener: () => void): () => void; - request(target: TTarget): boolean; - dismiss(): boolean; - clear(): void; - run( - execute: (target: TTarget) => Promise>, - problemFromError: (error: unknown) => TProblem - ): Promise; -} - -export function createConfirmedOperationController< - TTarget, - TProblem ->(): ConfirmedOperationController { - let state: ConfirmedOperationState = null; - const listeners = new Set<() => void>(); - - const publish = (next: ConfirmedOperationState) => { - state = next; - for (const listener of listeners) listener(); - }; - - return { - getSnapshot: () => state, - subscribe: (listener) => { - listeners.add(listener); - return () => listeners.delete(listener); - }, - request: (target) => { - if (state !== null) return false; - publish({ phase: 'confirming', target, problem: null }); - return true; - }, - dismiss: () => { - if (!state || state.phase === 'running') return false; - publish(null); - return true; - }, - clear: () => { - publish(null); - }, - run: async (execute, problemFromError) => { - if (!state || state.phase === 'running') return false; - const target = state.target; - publish({ phase: 'running', target, problem: null }); - - let outcome: ConfirmedOperationOutcome; - try { - outcome = await execute(target); - } catch (caught) { - outcome = { ok: false, problem: problemFromError(caught) }; - } - - if (outcome.ok) { - publish(null); - return true; - } - - publish({ phase: 'failed', target, problem: outcome.problem }); - return false; - } - }; -} - -export function useConfirmedOperation() { - const controller = useMemo( - () => createConfirmedOperationController(), - [] - ); - const state = useSyncExternalStore( - controller.subscribe, - controller.getSnapshot, - controller.getSnapshot - ); - - return { state, controller }; -} diff --git a/bazaarplusplus-installer/src/features/shared/modalCoordinator.integration.test.ts b/bazaarplusplus-installer/src/features/shared/modalCoordinator.integration.test.ts deleted file mode 100644 index bbe13ef..0000000 --- a/bazaarplusplus-installer/src/features/shared/modalCoordinator.integration.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { createModalCoordinator } from './modalCoordinator'; - -describe('shell and routed modal integration', () => { - it('queues background shell sources behind a routed confirmation across source unmounts', () => { - const coordinator = createModalCoordinator(); - coordinator.register({ - id: 'route:delete-video', - priority: 'confirmation' - }); - coordinator.register({ - id: 'shell:update', - priority: 'system' - }); - coordinator.register({ - id: 'shell:payment', - priority: 'informational' - }); - - expect(coordinator.getSnapshot().active?.id).toBe('route:delete-video'); - - coordinator.update('route:delete-video', { - priority: 'critical' - }); - expect(coordinator.getSnapshot().active).toMatchObject({ - id: 'route:delete-video', - priority: 'critical' - }); - - coordinator.unregister('route:delete-video'); - expect(coordinator.getSnapshot().active?.id).toBe('shell:update'); - - coordinator.unregister('shell:update'); - expect(coordinator.getSnapshot().active?.id).toBe('shell:payment'); - }); -}); diff --git a/bazaarplusplus-installer/src/features/shared/modalCoordinator.test.ts b/bazaarplusplus-installer/src/features/shared/modalCoordinator.test.ts deleted file mode 100644 index 58c2867..0000000 --- a/bazaarplusplus-installer/src/features/shared/modalCoordinator.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { - createModalCoordinator, - restoreModalFocus, - type ModalPriority, - type ModalRequest -} from './modalCoordinator'; - -function request(id: string, priority: ModalPriority): ModalRequest { - return { id, priority }; -} - -describe('modal coordinator', () => { - it('uses critical, confirmation, system, then informational priority', () => { - const coordinator = createModalCoordinator(); - - coordinator.register(request('payment', 'informational')); - expect(coordinator.getSnapshot().active?.id).toBe('payment'); - - coordinator.register(request('update', 'system')); - expect(coordinator.getSnapshot().active?.id).toBe('update'); - - coordinator.register(request('reset', 'confirmation')); - expect(coordinator.getSnapshot().active?.id).toBe('reset'); - - coordinator.register(request('delete-running', 'critical')); - expect(coordinator.getSnapshot().active?.id).toBe('delete-running'); - }); - - it('does not let update or support requests interrupt an active confirmation', () => { - const coordinator = createModalCoordinator(); - coordinator.register(request('cleanup', 'confirmation')); - coordinator.register(request('update', 'system')); - coordinator.register(request('payment', 'informational')); - - expect(coordinator.getSnapshot().active?.id).toBe('cleanup'); - expect(coordinator.getSnapshot().queued.map(({ id }) => id)).toEqual([ - 'update', - 'payment' - ]); - }); - - it('keeps equal priorities FIFO and safely removes a queued source', () => { - const coordinator = createModalCoordinator(); - coordinator.register(request('first-reset', 'confirmation')); - coordinator.register(request('second-delete', 'confirmation')); - coordinator.register(request('third-cleanup', 'confirmation')); - - coordinator.unregister('second-delete'); - coordinator.unregister('first-reset'); - - expect(coordinator.getSnapshot().active?.id).toBe('third-cleanup'); - expect(coordinator.getSnapshot().queued).toEqual([]); - }); - - it('retains an active confirmation when it adopts critical priority', () => { - const coordinator = createModalCoordinator(); - coordinator.register(request('reset', 'confirmation')); - coordinator.register(request('other-confirmation', 'confirmation')); - - coordinator.update('reset', { priority: 'critical' }); - - expect(coordinator.getSnapshot().active).toMatchObject({ - id: 'reset', - priority: 'critical' - }); - expect(coordinator.getSnapshot().queued.map(({ id }) => id)).toEqual([ - 'other-confirmation' - ]); - }); - - it('returns to a preempted source after critical work unregisters', () => { - const coordinator = createModalCoordinator(); - coordinator.register(request('update', 'system')); - coordinator.register(request('reset', 'confirmation')); - coordinator.register(request('native-critical', 'critical')); - - expect(coordinator.getSnapshot().active?.id).toBe('native-critical'); - coordinator.unregister('native-critical'); - expect(coordinator.getSnapshot().active?.id).toBe('reset'); - }); -}); - -describe('modal focus restoration', () => { - it('prefers a still-connected trigger', () => { - const trigger = { isConnected: true, focus: vi.fn() }; - const heading = { isConnected: true, focus: vi.fn() }; - - expect(restoreModalFocus(trigger, [heading])).toBe(trigger); - expect(trigger.focus).toHaveBeenCalledOnce(); - expect(heading.focus).not.toHaveBeenCalled(); - }); - - it('falls back to the first connected page target after route unmount', () => { - const staleTrigger = { isConnected: false, focus: vi.fn() }; - const staleHeading = { isConnected: false, focus: vi.fn() }; - const main = { isConnected: true, focus: vi.fn() }; - - expect(restoreModalFocus(staleTrigger, [staleHeading, main])).toBe(main); - expect(main.focus).toHaveBeenCalledOnce(); - }); -}); diff --git a/bazaarplusplus-installer/src/features/shared/modalCoordinator.ts b/bazaarplusplus-installer/src/features/shared/modalCoordinator.ts deleted file mode 100644 index 3e85ca8..0000000 --- a/bazaarplusplus-installer/src/features/shared/modalCoordinator.ts +++ /dev/null @@ -1,121 +0,0 @@ -export type ModalPriority = - 'critical' | 'confirmation' | 'system' | 'informational'; - -export type ModalDismissalPolicy = 'dismissible' | 'blocked'; - -export interface ModalFocusTarget { - readonly isConnected: boolean; - focus(): void; -} - -export interface ModalRequest { - id: string; - priority: ModalPriority; - restoreFocusTo?: () => ModalFocusTarget | null; -} - -export type RegisteredModal = ModalRequest & { sequence: number }; - -export type ModalCoordinatorSnapshot = { - active: RegisteredModal | null; - queued: readonly RegisteredModal[]; -}; - -export interface ModalCoordinator { - getSnapshot(): ModalCoordinatorSnapshot; - subscribe(listener: () => void): () => void; - register(request: ModalRequest): () => void; - update(id: string, patch: Partial>): boolean; - unregister(id: string): boolean; -} - -const PRIORITY_RANK: Record = { - critical: 4, - confirmation: 3, - system: 2, - informational: 1 -}; - -export function createModalCoordinator(): ModalCoordinator { - const entries = new Map(); - const listeners = new Set<() => void>(); - let nextSequence = 0; - let activeId: string | null = null; - let snapshot: ModalCoordinatorSnapshot = { active: null, queued: [] }; - - const sortedEntries = () => - [...entries.values()].sort( - (left, right) => - PRIORITY_RANK[right.priority] - PRIORITY_RANK[left.priority] || - left.sequence - right.sequence - ); - - const publish = () => { - const ordered = sortedEntries(); - const current = activeId ? entries.get(activeId) : null; - if (!current) { - activeId = ordered[0]?.id ?? null; - } else { - const challenger = ordered.find(({ id }) => id !== current.id); - if ( - challenger && - PRIORITY_RANK[challenger.priority] > PRIORITY_RANK[current.priority] - ) { - activeId = challenger.id; - } - } - - const active = activeId ? (entries.get(activeId) ?? null) : null; - snapshot = { - active, - queued: sortedEntries().filter(({ id }) => id !== active?.id) - }; - for (const listener of listeners) listener(); - }; - - const unregister = (id: string) => { - if (!entries.delete(id)) return false; - if (activeId === id) activeId = null; - publish(); - return true; - }; - - return { - getSnapshot: () => snapshot, - subscribe: (listener) => { - listeners.add(listener); - return () => listeners.delete(listener); - }, - register: (request) => { - const existing = entries.get(request.id); - entries.set(request.id, { - ...request, - sequence: existing?.sequence ?? nextSequence++ - }); - publish(); - return () => { - unregister(request.id); - }; - }, - update: (id, patch) => { - const existing = entries.get(id); - if (!existing) return false; - entries.set(id, { ...existing, ...patch, id }); - publish(); - return true; - }, - unregister - }; -} - -export function restoreModalFocus( - preferred: ModalFocusTarget | null, - fallbacks: readonly (ModalFocusTarget | null)[] -): ModalFocusTarget | null { - const target = [preferred, ...fallbacks].find( - (candidate): candidate is ModalFocusTarget => - candidate !== null && candidate.isConnected - ); - target?.focus(); - return target ?? null; -} diff --git a/bazaarplusplus-installer/src/features/shared/notoSansSc.ts b/bazaarplusplus-installer/src/features/shared/notoSansSc.ts deleted file mode 100644 index f641b5d..0000000 --- a/bazaarplusplus-installer/src/features/shared/notoSansSc.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { isWindowsPlatform } from './platform'; - -const NOTO_SANS_SC_CSS_URL = - 'https://fonts.googleapis.cn/css2?family=Noto+Sans+SC:wght@400;500;600;700&display=swap'; -const CACHE_NAME = 'bpp-noto-sans-sc-css-v1'; - -let scheduled = false; - -function installStyleSheet(css: string) { - if (document.querySelector('style[data-bpp-noto-sans-sc]')) return; - - const style = document.createElement('style'); - style.dataset.bppNotoSansSc = 'true'; - style.textContent = css; - document.head.append(style); -} - -async function fetchStyleSheet() { - const response = await fetch(NOTO_SANS_SC_CSS_URL, { - credentials: 'omit', - mode: 'cors' - }); - if (!response.ok) { - throw new Error( - `Noto Sans SC stylesheet request failed: ${response.status}` - ); - } - return response; -} - -async function loadPersistedStyleSheet() { - if (typeof caches === 'undefined') { - return (await fetchStyleSheet()).text(); - } - - try { - const cache = await caches.open(CACHE_NAME); - const cached = await cache.match(NOTO_SANS_SC_CSS_URL); - if (cached) return cached.text(); - - const response = await fetchStyleSheet(); - await cache.put(NOTO_SANS_SC_CSS_URL, response.clone()); - return response.text(); - } catch { - // Cache Storage is unavailable in some WebView configurations. The font - // mirror still supplies long-lived HTTP caching for its font files. - return (await fetchStyleSheet()).text(); - } -} - -async function loadNotoSansSc() { - const root = document.documentElement; - const windows = isWindowsPlatform(); - if (!windows) return; - - try { - installStyleSheet(await loadPersistedStyleSheet()); - await document.fonts.load('400 1em "Noto Sans SC"', '因热爱而生'); - if (windows) root.dataset.bppNotoSansSc = 'ready'; - } catch { - // The system font remains in use when the optional background download - // is unavailable. A later app launch retries unless the stylesheet cache - // was successfully written. - } -} - -/** - * Starts the optional CJK font download after the first frame. It is kept out - * of bundled assets and the stylesheet is retained in persistent Cache Storage. - */ -export function scheduleNotoSansScLoad() { - if (scheduled || typeof window === 'undefined') return; - scheduled = true; - - const start = () => void loadNotoSansSc(); - if (window.requestIdleCallback) { - window.requestIdleCallback(start, { timeout: 2_000 }); - } else { - window.setTimeout(start, 1_200); - } -} diff --git a/bazaarplusplus-installer/src/features/shared/pageState.ts b/bazaarplusplus-installer/src/features/shared/pageState.ts deleted file mode 100644 index 7fe01ce..0000000 --- a/bazaarplusplus-installer/src/features/shared/pageState.ts +++ /dev/null @@ -1,4 +0,0 @@ -export type PageRefreshState = - | { phase: 'idle' } - | { phase: 'refreshing' } - | { phase: 'failed'; problem: Problem }; diff --git a/bazaarplusplus-installer/src/features/shared/platform.ts b/bazaarplusplus-installer/src/features/shared/platform.ts deleted file mode 100644 index e13ab55..0000000 --- a/bazaarplusplus-installer/src/features/shared/platform.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Host-platform detection for copy that names OS-specific UI (Task Manager vs -// Activity Monitor, Start menu vs Applications). The webview user agent is the -// only signal available in both the Tauri runtime and the browser preview. -export function isWindowsPlatform(): boolean { - return ( - typeof navigator !== 'undefined' && navigator.userAgent.includes('Windows') - ); -} diff --git a/bazaarplusplus-installer/src/features/shared/problems.ts b/bazaarplusplus-installer/src/features/shared/problems.ts deleted file mode 100644 index e998517..0000000 --- a/bazaarplusplus-installer/src/features/shared/problems.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { SemanticProblem } from '../../types/backend'; -import { semanticProblemFromError } from '../../api/problems'; - -export type UiProblem = Omit< - SemanticProblem, - 'code' -> & { - code: Code; -}; - -export function createUiProblem( - code: Code, - options?: { - params?: Record; - diagnostic?: string | null; - } -): UiProblem { - return { - code, - params: options?.params ?? {}, - diagnostic: options?.diagnostic ?? null - }; -} - -export function problemFromError( - error: unknown, - fallbackCode: Code -): UiProblem { - const semantic = semanticProblemFromError(error); - if (semantic) { - return semantic; - } - return createUiProblem(fallbackCode, { diagnostic: diagnosticFrom(error) }); -} - -export function formatProblemDiagnostic(problem: UiProblem): string { - const params = Object.entries(problem.params) - .map(([name, value]) => `${name}=${value}`) - .join(' '); - return [problem.code, params, problem.diagnostic].filter(Boolean).join('\n'); -} - -function diagnosticFrom(error: unknown): string { - if (error instanceof Error) { - return error.message; - } - if (typeof error === 'string') { - return error; - } - return 'Unknown command failure'; -} diff --git a/bazaarplusplus-installer/src/features/stream/streamCapabilityState.test.ts b/bazaarplusplus-installer/src/features/stream/streamCapabilityState.test.ts deleted file mode 100644 index f22e35f..0000000 --- a/bazaarplusplus-installer/src/features/stream/streamCapabilityState.test.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { formatMessage } from '../../i18n/messages'; -import { - defaultCropSettings, - idleStreamStatus -} from '../../api/previewDefaults'; -import type { - StreamOverlayCropSettingsPayload, - StreamServiceStatus -} from '../../types/backend'; -import { - createStreamWorkflow, - type StreamCommandPort, - type StreamScheduler -} from './streamWorkflow'; -import { presentStreamSnapshot } from './streamPresentation'; -import { presentStreamProblem } from './streamProblems'; - -function runningStatus( - overrides: Partial = {} -): StreamServiceStatus { - return { - ...idleStreamStatus, - running: true, - port: 17654, - overlay_url: 'http://127.0.0.1:17654/overlay', - settings_url: 'http://127.0.0.1:17654/settings', - db: { found: true }, - ...overrides - }; -} - -function deferred() { - let resolve!: (value: T) => void; - let reject!: (error: unknown) => void; - const promise = new Promise((resolvePromise, rejectPromise) => { - resolve = resolvePromise; - reject = rejectPromise; - }); - return { promise, resolve, reject }; -} - -class FakeScheduler implements StreamScheduler { - private nextId = 1; - readonly intervals = new Map void>(); - readonly timeouts = new Map void>(); - - setInterval(callback: () => void) { - const id = this.nextId++; - this.intervals.set(id, callback); - return id; - } - - clearInterval(handle: unknown) { - this.intervals.delete(handle as number); - } - - setTimeout(callback: () => void) { - const id = this.nextId++; - this.timeouts.set(id, callback); - return id; - } - - clearTimeout(handle: unknown) { - this.timeouts.delete(handle as number); - } - - fireIntervals() { - for (const callback of Array.from(this.intervals.values())) callback(); - } -} - -function commands( - overrides: Partial = {} -): StreamCommandPort { - return { - ensureStreamSession: vi.fn().mockResolvedValue(runningStatus()), - getStreamStatus: vi.fn().mockResolvedValue(runningStatus()), - restartStreamSession: vi.fn().mockResolvedValue(runningStatus()), - setStreamWindow: vi.fn().mockResolvedValue(runningStatus()), - getOverlaySettings: vi.fn().mockResolvedValue(defaultCropSettings), - applyOverlayCropCode: vi.fn().mockResolvedValue(defaultCropSettings), - saveOverlayDisplayMode: vi.fn().mockResolvedValue(defaultCropSettings), - resetOverlayCrop: vi.fn().mockResolvedValue(defaultCropSettings), - ...overrides - }; -} - -function setup(commandOverrides: Partial = {}) { - const scheduler = new FakeScheduler(); - const commandPort = commands(commandOverrides); - const workflow = createStreamWorkflow({ - commands: commandPort, - scheduler, - clipboard: { writeText: vi.fn().mockResolvedValue(undefined) }, - opener: { open: vi.fn().mockResolvedValue(undefined) }, - currentLocale: () => 'zh' - }); - return { workflow, scheduler, commands: commandPort }; -} - -async function flush() { - await Promise.resolve(); - await Promise.resolve(); -} - -describe('Stream capability state', () => { - it('publishes crop availability while service initialization is still loading', async () => { - const status = deferred(); - const { workflow } = setup({ ensureStreamSession: () => status.promise }); - - const start = workflow.start(); - await flush(); - - expect(workflow.getSnapshot().service.phase).toBe('loading'); - expect(workflow.getSnapshot().crop.canEdit).toBe(true); - - status.resolve(runningStatus()); - await start; - }); - - it('keeps service and window controls usable when crop configuration degrades', async () => { - const { workflow } = setup({ - getOverlaySettings: vi - .fn() - .mockRejectedValue(new Error('crop unavailable')) - }); - - await workflow.start(); - const snapshot = workflow.getSnapshot(); - - expect(snapshot.service.phase).toBe('available'); - expect(snapshot.crop.problem).toMatchObject({ - code: 'stream_crop_failed', - diagnostic: 'crop unavailable' - }); - expect(snapshot.service.canRestart).toBe(true); - expect(snapshot.window.canMoveMoreHistory).toBe(true); - expect(snapshot.crop.canEdit).toBe(true); - }); - - it('marks failed polling as stale without claiming the last running value is authoritative', async () => { - const getStreamStatus = vi - .fn() - .mockRejectedValue(new Error('poll unavailable')); - const { workflow, scheduler } = setup({ getStreamStatus }); - await workflow.start(); - - for (let attempt = 0; attempt < 3; attempt += 1) { - scheduler.fireIntervals(); - await flush(); - } - - const stale = workflow.getSnapshot(); - expect(stale.service.status?.running).toBe(true); - expect(stale.polling).toMatchObject({ - freshness: 'stale', - problem: { code: 'stream_poll_failed' } - }); - expect(stale.crop.canEdit).toBe(true); - - const zh = presentStreamSnapshot(stale, (key, params) => - formatMessage('zh', key, params) - ); - expect(zh.status.label).toBe(formatMessage('zh', 'streamStatusStale')); - expect(zh.status.detail).not.toBe( - formatMessage('zh', 'streamPortDetail', { port: 17654 }) - ); - - getStreamStatus.mockResolvedValueOnce( - runningStatus({ active_window_offset: 1 }) - ); - expect(await workflow.intents.retryStatus()).toBe(true); - expect(workflow.getSnapshot().polling).toMatchObject({ - freshness: 'fresh', - problem: null - }); - }); - - it('scopes action failures and operation gates to their capabilities', async () => { - const pendingCrop = deferred(); - const { workflow } = setup({ - applyOverlayCropCode: () => pendingCrop.promise, - setStreamWindow: vi.fn().mockRejectedValue(new Error('window failed')) - }); - await workflow.start(); - - const cropAction = workflow.intents.submitCropCode(); - expect(workflow.getSnapshot().crop.canEdit).toBe(false); - expect(workflow.getSnapshot().service.canRestart).toBe(true); - expect(workflow.getSnapshot().window.canMoveMoreHistory).toBe(true); - - pendingCrop.reject(new Error('crop failed')); - expect(await cropAction).toBe(false); - expect(workflow.getSnapshot().crop.problem?.code).toBe( - 'stream_crop_failed' - ); - - expect(await workflow.intents.moveWindow(1)).toBe(false); - expect(workflow.getSnapshot().window.problem).toMatchObject({ - code: 'stream_window_failed', - diagnostic: 'window failed' - }); - expect(workflow.getSnapshot().crop.canEdit).toBe(true); - expect(workflow.getSnapshot().service.problem).toBeNull(); - }); - - it('re-presents one live workflow in either locale without starting it again', async () => { - const ensureStreamSession = vi.fn().mockResolvedValue(runningStatus()); - const { workflow } = setup({ ensureStreamSession }); - await workflow.start(); - const snapshot = workflow.getSnapshot(); - - const zh = presentStreamSnapshot(snapshot, (key, params) => - formatMessage('zh', key, params) - ); - const en = presentStreamSnapshot(snapshot, (key, params) => - formatMessage('en', key, params) - ); - - expect(zh.status.label).not.toBe(en.status.label); - expect(ensureStreamSession).toHaveBeenCalledTimes(1); - expect(workflow.getSnapshot()).toBe(snapshot); - }); -}); - -describe('Stream problem presentation', () => { - it.each([ - ['stream_service_failed', { operation: 'restart' }], - ['stream_poll_failed', { operation: 'poll_status' }], - ['stream_window_failed', { operation: 'set_window' }], - ['stream_crop_failed', { operation: 'apply_code' }], - ['stream_copy_failed', { operation: 'copy_obs_url' }], - ['stream_open_failed', { operation: 'open_overlay' }], - ['stream_unexpected', {}] - ] as const)('localizes %s with recovery copy', (code, params) => { - const problem = { code, params, diagnostic: 'native detail' }; - const zh = presentStreamProblem(problem, (key, values) => - formatMessage('zh', key, values) - ); - const en = presentStreamProblem(problem, (key, values) => - formatMessage('en', key, values) - ); - - expect(zh).not.toContain('native detail'); - expect(en).not.toContain('native detail'); - expect(zh).not.toBe(en); - }); -}); diff --git a/bazaarplusplus-installer/src/features/stream/streamPresentation.ts b/bazaarplusplus-installer/src/features/stream/streamPresentation.ts deleted file mode 100644 index 376e273..0000000 --- a/bazaarplusplus-installer/src/features/stream/streamPresentation.ts +++ /dev/null @@ -1,79 +0,0 @@ -import type { Translate } from '../../i18n/LocaleProvider'; -import type { StreamPageSnapshot } from './streamWorkflow'; -import { presentStreamNotice, presentStreamProblem } from './streamProblems'; - -export type StreamStatusPresentation = { - label: string; - detail: string; - tone: 'loading' | 'running' | 'idle' | 'degraded' | 'stale'; -}; - -export type StreamPagePresentation = { - status: StreamStatusPresentation; - dbLabel: string; - windowLabel: string; - notice: string | null; -}; - -export function presentStreamSnapshot( - snapshot: StreamPageSnapshot, - t: Translate -): StreamPagePresentation { - const status = snapshot.service.status; - let statusPresentation: StreamStatusPresentation; - - if (snapshot.service.phase === 'loading') { - statusPresentation = { - label: t('streamStatusStarting'), - detail: t('streamStarting'), - tone: 'loading' - }; - } else if (snapshot.service.problem) { - statusPresentation = { - label: t('streamStatusError'), - detail: presentStreamProblem(snapshot.service.problem, t), - tone: 'degraded' - }; - } else if (snapshot.polling.freshness === 'stale') { - statusPresentation = { - label: t('streamStatusStale'), - detail: status?.running - ? t('streamStaleRunningDetail') - : t('streamStaleIdleDetail'), - tone: 'stale' - }; - } else if (status?.running) { - statusPresentation = { - label: t('streamStatusRunning'), - detail: - status.port === null - ? t('streamStatusUnavailableDetail') - : t('streamPortDetail', { port: status.port }), - tone: 'running' - }; - } else if (status) { - statusPresentation = { - label: t('streamStatusIdle'), - detail: t('streamIdleDetail'), - tone: 'idle' - }; - } else { - statusPresentation = { - label: t('streamStatusUnavailable'), - detail: t('streamStatusUnavailableDetail'), - tone: 'degraded' - }; - } - - return { - status: statusPresentation, - dbLabel: status?.db.found ? t('dbConnected') : t('dbMissing'), - windowLabel: - (status?.active_window_offset ?? 0) === 0 - ? t('streamWindowLatest') - : t('streamWindowOffset', { - count: status?.active_window_offset ?? 0 - }), - notice: presentStreamNotice(snapshot.notice, t) - }; -} diff --git a/bazaarplusplus-installer/src/features/stream/streamProblems.ts b/bazaarplusplus-installer/src/features/stream/streamProblems.ts deleted file mode 100644 index 78f63f0..0000000 --- a/bazaarplusplus-installer/src/features/stream/streamProblems.ts +++ /dev/null @@ -1,111 +0,0 @@ -import type { Translate } from '../../i18n/LocaleProvider'; -import type { MessageKey } from '../../i18n/messages'; -import { - createUiProblem, - problemFromError, - type UiProblem -} from '../shared/problems'; - -export type StreamProblemCode = - | 'stream_service_failed' - | 'stream_poll_failed' - | 'stream_window_failed' - | 'stream_crop_failed' - | 'stream_copy_failed' - | 'stream_open_failed' - | 'stream_unexpected'; - -export type StreamProblem = UiProblem; - -export type StreamNoticeCode = - 'stream_obs_url_copied' | 'stream_crop_saved' | 'stream_crop_reset'; - -export type StreamNotice = { - code: StreamNoticeCode; -}; - -export function streamProblemFromError( - error: unknown, - fallbackCode: StreamProblemCode, - fallbackParams: Record = {} -): StreamProblem { - const problem: UiProblem = problemFromError(error, fallbackCode); - if (isStreamProblemCode(problem.code)) { - return { - ...problem, - code: problem.code, - params: { ...fallbackParams, ...problem.params } - }; - } - - return createUiProblem(fallbackCode, { - params: { ...fallbackParams, ...problem.params }, - diagnostic: problem.diagnostic - }); -} - -export function streamRuntimeProblem(diagnostic: string): StreamProblem { - return createUiProblem('stream_service_failed', { - params: { operation: 'runtime' }, - diagnostic - }); -} - -export function presentStreamProblem( - problem: StreamProblem, - t: Translate -): string { - return t(streamProblemMessageKey(problem), problem.params); -} - -export function presentStreamNotice( - notice: StreamNotice | null, - t: Translate -): string | null { - if (!notice) return null; - switch (notice.code) { - case 'stream_obs_url_copied': - return t('streamCopied'); - case 'stream_crop_saved': - return t('streamCropSaved'); - case 'stream_crop_reset': - return t('streamCropReset'); - } -} - -function isStreamProblemCode(code: string): code is StreamProblemCode { - return ( - code === 'stream_service_failed' || - code === 'stream_poll_failed' || - code === 'stream_window_failed' || - code === 'stream_crop_failed' || - code === 'stream_copy_failed' || - code === 'stream_open_failed' || - code === 'stream_unexpected' - ); -} - -function streamProblemMessageKey(problem: StreamProblem): MessageKey { - switch (problem.code) { - case 'stream_service_failed': - return problem.params.operation === 'restart' - ? 'streamProblemRestartFailed' - : 'streamProblemServiceFailed'; - case 'stream_poll_failed': - return 'streamProblemPollFailed'; - case 'stream_window_failed': - return 'streamProblemWindowFailed'; - case 'stream_crop_failed': - return problem.params.operation === 'load' - ? 'streamProblemCropLoadFailed' - : 'streamProblemCropSaveFailed'; - case 'stream_copy_failed': - return 'streamCopyFailed'; - case 'stream_open_failed': - return problem.params.operation === 'open_settings' - ? 'streamProblemOpenSettingsFailed' - : 'streamProblemOpenOverlayFailed'; - case 'stream_unexpected': - return 'streamProblemUnexpected'; - } -} diff --git a/bazaarplusplus-installer/src/features/stream/streamWorkflow.test.ts b/bazaarplusplus-installer/src/features/stream/streamWorkflow.test.ts deleted file mode 100644 index f210fdf..0000000 --- a/bazaarplusplus-installer/src/features/stream/streamWorkflow.test.ts +++ /dev/null @@ -1,309 +0,0 @@ -// Isolated on purpose: the Stream page's rendered states (idle, running, -// runtime error) are anchored by src/shell.snapshot.test.tsx. These cases cover -// polling and settle order a static snapshot cannot observe. -// - An older poll overwrites a newer status, a slow poll overwrites a completed -// restart, or an older failed poll marks a newer status stale. -// - A poll that only changes the reported error is not published. -// - A runtime error is reported as polling staleness, or the reverse. -// - A semantic notice persists, or a one-off failure leaks to other targets. -// - Responses or timers fire after dispose, or a dispose-start replay accepts -// the old initialization. -import { describe, expect, it, vi } from 'vitest'; -import { - defaultCropSettings, - idleStreamStatus -} from '../../api/previewDefaults'; -import type { - StreamOverlayCropSettingsPayload, - StreamServiceStatus -} from '../../types/backend'; -import { - createStreamWorkflow, - type StreamCommandPort, - type StreamScheduler -} from './streamWorkflow'; - -function runningStatus( - overrides: Partial = {} -): StreamServiceStatus { - return { - ...idleStreamStatus, - running: true, - port: 17654, - overlay_url: 'http://127.0.0.1:17654/overlay', - settings_url: 'http://127.0.0.1:17654/settings', - db: { found: true }, - ...overrides - }; -} - -function deferred() { - let resolve!: (value: T) => void; - let reject!: (error: unknown) => void; - const promise = new Promise((resolvePromise, rejectPromise) => { - resolve = resolvePromise; - reject = rejectPromise; - }); - return { promise, resolve, reject }; -} - -class FakeScheduler implements StreamScheduler { - private nextId = 1; - readonly intervals = new Map void>(); - readonly timeouts = new Map void>(); - - setInterval(callback: () => void) { - const id = this.nextId++; - this.intervals.set(id, callback); - return id; - } - - clearInterval(handle: unknown) { - this.intervals.delete(handle as number); - } - - setTimeout(callback: () => void) { - const id = this.nextId++; - this.timeouts.set(id, callback); - return id; - } - - clearTimeout(handle: unknown) { - this.timeouts.delete(handle as number); - } - - fireIntervals() { - for (const callback of Array.from(this.intervals.values())) callback(); - } - - fireTimeouts() { - const callbacks = [...this.timeouts.values()]; - this.timeouts.clear(); - for (const callback of callbacks) callback(); - } -} - -function fakeCommands( - overrides: Partial = {} -): StreamCommandPort { - return { - ensureStreamSession: vi.fn().mockResolvedValue(runningStatus()), - getStreamStatus: vi.fn().mockResolvedValue(runningStatus()), - restartStreamSession: vi.fn().mockResolvedValue(runningStatus()), - setStreamWindow: vi.fn().mockResolvedValue(runningStatus()), - getOverlaySettings: vi.fn().mockResolvedValue(defaultCropSettings), - applyOverlayCropCode: vi.fn().mockResolvedValue(defaultCropSettings), - saveOverlayDisplayMode: vi.fn().mockResolvedValue(defaultCropSettings), - resetOverlayCrop: vi.fn().mockResolvedValue(defaultCropSettings), - ...overrides - }; -} - -function setup( - commandOverrides: Partial = {}, - clipboard = { writeText: vi.fn().mockResolvedValue(undefined) }, - opener = { open: vi.fn().mockResolvedValue(undefined) } -) { - const scheduler = new FakeScheduler(); - const commands = fakeCommands(commandOverrides); - const workflow = createStreamWorkflow({ - commands, - scheduler, - clipboard, - opener, - currentLocale: () => 'zh' - }); - return { workflow, commands, scheduler, clipboard, opener }; -} - -async function flush() { - await Promise.resolve(); - await Promise.resolve(); -} - -describe('stream workflow lifecycle and effects', () => { - it('ignores an older poll after a newer poll succeeds', async () => { - const first = deferred(); - const second = deferred(); - const getStreamStatus = vi - .fn() - .mockImplementationOnce(() => first.promise) - .mockImplementationOnce(() => second.promise); - const { workflow, scheduler } = setup({ getStreamStatus }); - await workflow.start(); - - scheduler.fireIntervals(); - scheduler.fireIntervals(); - second.resolve(runningStatus({ active_window_offset: 2 })); - await flush(); - first.resolve(runningStatus({ active_window_offset: 1 })); - await flush(); - - expect(workflow.getSnapshot().service.status?.active_window_offset).toBe(2); - }); - - it('still publishes when a poll changes the reported error', async () => { - const getStreamStatus = vi - .fn() - .mockResolvedValueOnce(runningStatus()) - .mockResolvedValue(runningStatus({ last_error: 'overlay port lost' })); - const { workflow, scheduler } = setup({ getStreamStatus }); - await workflow.start(); - - scheduler.fireIntervals(); - await flush(); - const before = workflow.getSnapshot(); - - scheduler.fireIntervals(); - await flush(); - - expect(workflow.getSnapshot()).not.toBe(before); - expect(workflow.getSnapshot().service.status?.last_error).toBe( - 'overlay port lost' - ); - }); - - it('does not mark a newer status stale when an older poll fails', async () => { - const first = deferred(); - const second = deferred(); - const getStreamStatus = vi - .fn() - .mockImplementationOnce(() => first.promise) - .mockImplementationOnce(() => second.promise); - const { workflow, scheduler } = setup({ getStreamStatus }); - await workflow.start(); - - scheduler.fireIntervals(); - scheduler.fireIntervals(); - second.resolve(runningStatus({ active_window_offset: 2 })); - await flush(); - first.reject(new Error('outdated failure')); - await flush(); - - expect(workflow.getSnapshot().polling).toMatchObject({ - freshness: 'fresh', - problem: null - }); - }); - - it('does not let a slow poll overwrite a completed restart', async () => { - const slowPoll = deferred(); - const refreshed = runningStatus({ active_window_offset: 3 }); - const { workflow, scheduler } = setup({ - getStreamStatus: vi.fn(() => slowPoll.promise), - restartStreamSession: vi.fn().mockResolvedValue(refreshed) - }); - await workflow.start(); - - scheduler.fireIntervals(); - await flush(); - expect(await workflow.intents.restart()).toBe(true); - slowPoll.resolve(runningStatus({ active_window_offset: 1 })); - await flush(); - - expect(workflow.getSnapshot().service.status).toBe(refreshed); - }); - - it('maps an authoritative runtime error separately from polling staleness', async () => { - const failedStatus = { - ...idleStreamStatus, - last_error: 'port occupied' - }; - const { workflow } = setup({ - ensureStreamSession: vi.fn().mockResolvedValue(failedStatus) - }); - await workflow.start(); - - expect(workflow.getSnapshot().service).toMatchObject({ - phase: 'degraded', - status: failedStatus, - problem: { - code: 'stream_service_failed', - diagnostic: 'port occupied' - } - }); - expect(workflow.getSnapshot().polling.freshness).toBe('fresh'); - }); - - it('keeps semantic notices transient and one-off failures target-scoped', async () => { - const clipboard = { - writeText: vi - .fn() - .mockResolvedValueOnce(undefined) - .mockRejectedValueOnce(new Error('clipboard denied')) - }; - const opener = { - open: vi.fn().mockRejectedValueOnce(new Error('open denied')) - }; - const { workflow, scheduler } = setup({}, clipboard, opener); - await workflow.start(); - - expect(await workflow.intents.copyObsUrl()).toBe(true); - expect(workflow.getSnapshot().notice?.code).toBe('stream_obs_url_copied'); - scheduler.fireTimeouts(); - expect(workflow.getSnapshot().notice).toBeNull(); - - expect(await workflow.intents.copyObsUrl()).toBe(false); - expect(workflow.getSnapshot().oneOff.problems.copy).toMatchObject({ - code: 'stream_copy_failed', - diagnostic: 'clipboard denied' - }); - expect(await workflow.intents.openOverlay()).toBe(false); - expect(workflow.getSnapshot().oneOff.problems.open_overlay).toMatchObject({ - code: 'stream_open_failed', - diagnostic: 'open denied' - }); - expect(workflow.getSnapshot().crop.canEdit).toBe(true); - }); - - it('ignores responses and cancels timers after disposal', async () => { - const slow = deferred(); - const { workflow, scheduler } = setup({ - getStreamStatus: () => slow.promise - }); - await workflow.start(); - - scheduler.fireIntervals(); - const before = workflow.getSnapshot(); - workflow.dispose(); - slow.resolve(runningStatus({ active_window_offset: 9 })); - await flush(); - - expect(workflow.getSnapshot()).toBe(before); - expect(scheduler.intervals.size).toBe(0); - }); - - it('supports a dispose-start replay without accepting old initialization', async () => { - const firstStatus = deferred(); - const firstCrop = deferred(); - const secondStatus = deferred(); - const secondCrop = deferred(); - const ensureStreamSession = vi - .fn() - .mockImplementationOnce(() => firstStatus.promise) - .mockImplementationOnce(() => secondStatus.promise); - const getOverlaySettings = vi - .fn() - .mockImplementationOnce(() => firstCrop.promise) - .mockImplementationOnce(() => secondCrop.promise); - const { workflow, scheduler } = setup({ - ensureStreamSession, - getOverlaySettings - }); - - const firstStart = workflow.start(); - workflow.dispose(); - const secondStart = workflow.start(); - firstStatus.resolve(runningStatus({ active_window_offset: 1 })); - firstCrop.resolve({ ...defaultCropSettings, code: 'stale' }); - await firstStart; - - secondStatus.resolve(runningStatus({ active_window_offset: 2 })); - secondCrop.resolve({ ...defaultCropSettings, code: 'current' }); - await secondStart; - - expect(workflow.getSnapshot().service.status?.active_window_offset).toBe(2); - expect(workflow.getSnapshot().crop.code).toBe('current'); - expect(scheduler.intervals.size).toBe(1); - }); -}); diff --git a/bazaarplusplus-installer/src/features/stream/streamWorkflow.ts b/bazaarplusplus-installer/src/features/stream/streamWorkflow.ts deleted file mode 100644 index 1b03150..0000000 --- a/bazaarplusplus-installer/src/features/stream/streamWorkflow.ts +++ /dev/null @@ -1,768 +0,0 @@ -import type { CommandAdapter } from '../../api/commandAdapter'; -import type { - StreamOverlayCropSettingsPayload, - StreamOverlayDisplayMode, - StreamServiceStatus -} from '../../types/backend'; -import { defaultCropSettings } from '../../api/previewDefaults'; -import { - streamProblemFromError, - streamRuntimeProblem, - type StreamNotice, - type StreamProblem, - type StreamProblemCode -} from './streamProblems'; - -type StatusOperation = 'restart' | 'window'; -type CropOperation = 'load' | 'crop' | 'display_mode' | 'reset'; -type OneOffAction = 'copy' | 'open_overlay' | 'open_settings'; - -export type StreamCommandPort = Pick< - CommandAdapter, - | 'ensureStreamSession' - | 'getStreamStatus' - | 'restartStreamSession' - | 'setStreamWindow' - | 'getOverlaySettings' - | 'applyOverlayCropCode' - | 'saveOverlayDisplayMode' - | 'resetOverlayCrop' ->; - -export interface StreamScheduler { - setInterval(callback: () => void, delayMs: number): unknown; - clearInterval(handle: unknown): void; - setTimeout(callback: () => void, delayMs: number): unknown; - clearTimeout(handle: unknown): void; -} - -export interface StreamClipboard { - writeText(value: string): Promise; -} - -export interface StreamOpener { - open(url: string): Promise; -} - -export interface StreamPageSnapshot { - service: { - phase: 'loading' | 'available' | 'degraded'; - status: StreamServiceStatus | null; - problem: StreamProblem | null; - operation: Extract | null; - canRestart: boolean; - }; - polling: { - freshness: 'unknown' | 'fresh' | 'stale'; - problem: StreamProblem | null; - }; - window: { - problem: StreamProblem | null; - canMoveMoreHistory: boolean; - canMoveLessHistory: boolean; - }; - crop: { - settings: StreamOverlayCropSettingsPayload; - code: string; - problem: StreamProblem | null; - canEdit: boolean; - }; - oneOff: { - problems: Record; - obsUrl: string | null; - canOpenOverlay: boolean; - canCopyObsUrl: boolean; - canOpenSettings: boolean; - }; - notice: StreamNotice | null; -} - -export interface StreamWorkflowIntents { - restart(): Promise; - retryStatus(): Promise; - reloadCropSettings(): Promise; - copyObsUrl(): Promise; - openOverlay(): Promise; - openSettings(): Promise; - changeDisplayMode(displayMode: StreamOverlayDisplayMode): Promise; - setCropCode(value: string): void; - submitCropCode(): Promise; - resetCropCode(): Promise; - moveWindow(delta: number): Promise; -} - -export interface StreamWorkflow { - getSnapshot(): StreamPageSnapshot; - subscribe(listener: () => void): () => void; - start(): Promise; - dispose(): void; - readonly intents: StreamWorkflowIntents; -} - -interface StreamWorkflowPorts { - commands: StreamCommandPort; - scheduler: StreamScheduler; - clipboard: StreamClipboard; - opener: StreamOpener; - // The calibration page is served from the stream service's own origin, so it - // cannot read the app's locale. Read it live, since the user can toggle - // language while the page is mounted. - currentLocale: () => string; -} - -interface MutableState { - status: StreamServiceStatus | null; - serviceLoading: boolean; - serviceProblem: StreamProblem | null; - pollingFreshness: 'unknown' | 'fresh' | 'stale'; - pollingProblem: StreamProblem | null; - cropSettings: StreamOverlayCropSettingsPayload; - cropCode: string; - cropLoading: boolean; - cropProblem: StreamProblem | null; - statusOperation: StatusOperation | null; - windowProblem: StreamProblem | null; - cropOperation: CropOperation | null; - oneOffOperations: Set; - oneOffProblems: Record; - notice: StreamNotice | null; -} - -const POLL_INTERVAL_MS = 2_000; -const POLL_FAILURE_THRESHOLD = 3; -const TRANSIENT_MESSAGE_MS = 3_000; - -class DefaultStreamWorkflow implements StreamWorkflow { - private readonly listeners = new Set<() => void>(); - private state: MutableState = initialState(); - private snapshot: StreamPageSnapshot; - private started = false; - private disposed = false; - private lifecycleEpoch = 0; - private statusEpoch = 0; - private latestPollRequest = 0; - private consecutivePollFailures = 0; - private intervalHandle: unknown = null; - private noticeTimeoutHandle: unknown = null; - - readonly intents: StreamWorkflowIntents = { - restart: () => this.restart(), - retryStatus: () => this.poll(), - reloadCropSettings: () => this.reloadCropSettings(), - copyObsUrl: () => this.copyObsUrl(), - openOverlay: () => this.openOverlay(), - openSettings: () => this.openSettings(), - changeDisplayMode: (displayMode) => this.changeDisplayMode(displayMode), - setCropCode: (value) => this.setCropCode(value), - submitCropCode: () => this.submitCropCode(), - resetCropCode: () => this.resetCropCode(), - moveWindow: (delta) => this.moveWindow(delta) - }; - - constructor(private readonly ports: StreamWorkflowPorts) { - this.snapshot = this.deriveSnapshot(); - } - - getSnapshot = () => this.snapshot; - - subscribe = (listener: () => void) => { - this.listeners.add(listener); - return () => this.listeners.delete(listener); - }; - - async start() { - if (this.started) return; - this.started = true; - this.disposed = false; - const lifecycle = ++this.lifecycleEpoch; - const statusEpoch = ++this.statusEpoch; - this.state = initialState(); - this.consecutivePollFailures = 0; - this.clearNoticeTimer(); - this.publish(); - - const statusLoad = this.loadInitialStatus(lifecycle, statusEpoch); - const cropLoad = this.loadInitialCrop(lifecycle); - await Promise.all([statusLoad, cropLoad]); - if (!this.isCurrentLifecycle(lifecycle)) return; - - this.intervalHandle = this.ports.scheduler.setInterval( - () => void this.poll(), - POLL_INTERVAL_MS - ); - } - - dispose() { - if (this.disposed) return; - this.disposed = true; - this.started = false; - this.lifecycleEpoch += 1; - this.statusEpoch += 1; - this.latestPollRequest += 1; - this.state.statusOperation = null; - this.state.cropOperation = null; - this.state.oneOffOperations.clear(); - if (this.intervalHandle !== null) { - this.ports.scheduler.clearInterval(this.intervalHandle); - this.intervalHandle = null; - } - this.clearNoticeTimer(); - this.listeners.clear(); - } - - private async loadInitialStatus(lifecycle: number, epoch: number) { - try { - const status = await this.ports.commands.ensureStreamSession(); - if (!this.isCurrentLifecycle(lifecycle) || epoch !== this.statusEpoch) { - return; - } - this.applyStatus(status); - } catch (caught) { - if (!this.isCurrentLifecycle(lifecycle) || epoch !== this.statusEpoch) { - return; - } - this.state.serviceProblem = streamProblemFromError( - caught, - 'stream_service_failed', - { operation: 'ensure' } - ); - this.state.pollingFreshness = 'unknown'; - } finally { - if (this.isCurrentLifecycle(lifecycle) && epoch === this.statusEpoch) { - this.state.serviceLoading = false; - this.publish(); - } - } - } - - private async loadInitialCrop(lifecycle: number) { - try { - const settings = await this.ports.commands.getOverlaySettings(); - if (!this.isCurrentLifecycle(lifecycle)) return; - this.applyCropSettings(settings); - this.state.cropProblem = null; - } catch (caught) { - if (!this.isCurrentLifecycle(lifecycle)) return; - this.state.cropProblem = streamProblemFromError( - caught, - 'stream_crop_failed', - { operation: 'load' } - ); - } finally { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.cropLoading = false; - this.publish(); - } - } - } - - private async poll(): Promise { - if (this.disposed || this.state.statusOperation !== null) return false; - const lifecycle = this.lifecycleEpoch; - const epoch = this.statusEpoch; - const request = ++this.latestPollRequest; - - try { - const status = await this.ports.commands.getStreamStatus(); - if ( - !this.isCurrentLifecycle(lifecycle) || - epoch !== this.statusEpoch || - request !== this.latestPollRequest - ) { - return false; - } - this.applyStatus(status); - return true; - } catch (caught) { - if ( - !this.isCurrentLifecycle(lifecycle) || - epoch !== this.statusEpoch || - request !== this.latestPollRequest - ) { - return false; - } - this.consecutivePollFailures += 1; - if (this.consecutivePollFailures >= POLL_FAILURE_THRESHOLD) { - this.state.pollingFreshness = 'stale'; - this.state.pollingProblem = streamProblemFromError( - caught, - 'stream_poll_failed', - { operation: 'poll_status' } - ); - } - return false; - } finally { - if (this.isCurrentLifecycle(lifecycle)) { - this.publish(); - } - } - } - - private async restart(): Promise { - if ( - this.disposed || - this.state.serviceLoading || - this.state.statusOperation !== null - ) { - return false; - } - const lifecycle = this.lifecycleEpoch; - this.state.statusOperation = 'restart'; - this.state.serviceProblem = null; - this.invalidateStatusRequests(); - this.publish(); - - try { - const status = await this.ports.commands.restartStreamSession(); - if (!this.isCurrentLifecycle(lifecycle)) return false; - this.applyStatus(status); - return true; - } catch (caught) { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.serviceProblem = streamProblemFromError( - caught, - 'stream_service_failed', - { operation: 'restart' } - ); - this.state.pollingFreshness = 'stale'; - } - return false; - } finally { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.statusOperation = null; - this.publish(); - } - } - } - - private async reloadCropSettings(): Promise { - if ( - this.disposed || - this.state.cropLoading || - this.state.cropOperation !== null - ) { - return false; - } - const lifecycle = this.lifecycleEpoch; - this.state.cropLoading = true; - this.state.cropOperation = 'load'; - this.state.cropProblem = null; - this.publish(); - try { - const settings = await this.ports.commands.getOverlaySettings(); - if (!this.isCurrentLifecycle(lifecycle)) return false; - this.applyCropSettings(settings); - return true; - } catch (caught) { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.cropProblem = streamProblemFromError( - caught, - 'stream_crop_failed', - { operation: 'load' } - ); - } - return false; - } finally { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.cropLoading = false; - this.state.cropOperation = null; - this.publish(); - } - } - } - - private copyObsUrl() { - const url = this.state.status?.overlay_url; - if (!url) return Promise.resolve(false); - return this.runOneOff( - 'copy', - () => this.ports.clipboard.writeText(url), - 'stream_copy_failed', - { operation: 'copy_obs_url' }, - { code: 'stream_obs_url_copied' } - ); - } - - private openOverlay() { - const url = this.state.status?.overlay_url; - if (!url) return Promise.resolve(false); - return this.runOneOff( - 'open_overlay', - () => this.ports.opener.open(url), - 'stream_open_failed', - { operation: 'open_overlay' } - ); - } - - private openSettings() { - const url = this.state.status?.settings_url; - if (!url) return Promise.resolve(false); - const localized = withLocaleParam(url, this.ports.currentLocale()); - return this.runOneOff( - 'open_settings', - () => this.ports.opener.open(localized), - 'stream_open_failed', - { operation: 'open_settings' } - ); - } - - private changeDisplayMode(displayMode: StreamOverlayDisplayMode) { - return this.runCropAction( - 'display_mode', - () => this.ports.commands.saveOverlayDisplayMode(displayMode), - { operation: 'save_display_mode' }, - false - ); - } - - private setCropCode(value: string) { - if (this.disposed) return; - this.state.cropCode = value; - this.publish(); - } - - private submitCropCode() { - return this.runCropAction( - 'crop', - () => - this.ports.commands.applyOverlayCropCode(this.state.cropCode.trim()), - { operation: 'apply_code' }, - true, - { code: 'stream_crop_saved' } - ); - } - - private resetCropCode() { - return this.runCropAction( - 'reset', - () => this.ports.commands.resetOverlayCrop(), - { operation: 'reset' }, - true, - { code: 'stream_crop_reset' } - ); - } - - private async moveWindow(delta: number): Promise { - if ( - this.disposed || - this.state.statusOperation !== null || - !this.state.status?.running || - this.state.pollingFreshness !== 'fresh' - ) { - return false; - } - const lifecycle = this.lifecycleEpoch; - const offset = Math.max( - 0, - Math.trunc(this.state.status.active_window_offset + delta) - ); - this.state.statusOperation = 'window'; - this.state.windowProblem = null; - this.invalidateStatusRequests(); - this.publish(); - - try { - const status = await this.ports.commands.setStreamWindow(offset); - if (!this.isCurrentLifecycle(lifecycle)) return false; - this.applyStatus(status); - return true; - } catch (caught) { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.windowProblem = streamProblemFromError( - caught, - 'stream_window_failed', - { operation: 'set_window', offset: String(offset) } - ); - } - return false; - } finally { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.statusOperation = null; - this.publish(); - } - } - } - - private async runCropAction( - operation: Exclude, - task: () => Promise, - params: Record, - updateCode: boolean, - notice: StreamNotice | null = null - ): Promise { - if ( - this.disposed || - this.state.cropLoading || - this.state.cropOperation !== null - ) { - return false; - } - const lifecycle = this.lifecycleEpoch; - this.state.cropOperation = operation; - this.state.cropProblem = null; - if (notice) this.clearNotice(); - this.publish(); - - try { - const settings = await task(); - if (!this.isCurrentLifecycle(lifecycle)) return false; - this.applyCropSettings(settings, updateCode); - if (notice) this.showNotice(notice); - return true; - } catch (caught) { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.cropProblem = streamProblemFromError( - caught, - 'stream_crop_failed', - params - ); - } - return false; - } finally { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.cropOperation = null; - this.publish(); - } - } - } - - private async runOneOff( - action: OneOffAction, - task: () => Promise, - fallbackCode: StreamProblemCode, - params: Record, - notice: StreamNotice | null = null - ): Promise { - if (this.disposed || this.state.oneOffOperations.has(action)) return false; - const lifecycle = this.lifecycleEpoch; - this.state.oneOffOperations.add(action); - this.state.oneOffProblems[action] = null; - if (notice) this.clearNotice(); - this.publish(); - - try { - await task(); - if (!this.isCurrentLifecycle(lifecycle)) return false; - if (notice) this.showNotice(notice); - return true; - } catch (caught) { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.oneOffProblems[action] = streamProblemFromError( - caught, - fallbackCode, - params - ); - } - return false; - } finally { - if (this.isCurrentLifecycle(lifecycle)) { - this.state.oneOffOperations.delete(action); - this.publish(); - } - } - } - - private applyStatus(status: StreamServiceStatus) { - this.state.status = status; - this.state.serviceProblem = status.last_error - ? streamRuntimeProblem(status.last_error) - : null; - this.state.pollingFreshness = 'fresh'; - this.state.pollingProblem = null; - this.consecutivePollFailures = 0; - } - - private applyCropSettings( - settings: StreamOverlayCropSettingsPayload, - updateCode = true - ) { - this.state.cropSettings = settings; - if (updateCode) this.state.cropCode = settings.code; - this.state.cropProblem = null; - } - - private invalidateStatusRequests() { - this.statusEpoch += 1; - this.latestPollRequest += 1; - } - - private showNotice(notice: StreamNotice) { - const lifecycle = this.lifecycleEpoch; - this.clearNoticeTimer(); - this.state.notice = notice; - this.noticeTimeoutHandle = this.ports.scheduler.setTimeout(() => { - this.noticeTimeoutHandle = null; - if (!this.isCurrentLifecycle(lifecycle)) return; - this.state.notice = null; - this.publish(); - }, TRANSIENT_MESSAGE_MS); - this.publish(); - } - - private clearNotice() { - this.clearNoticeTimer(); - this.state.notice = null; - } - - private clearNoticeTimer() { - if (this.noticeTimeoutHandle === null) return; - this.ports.scheduler.clearTimeout(this.noticeTimeoutHandle); - this.noticeTimeoutHandle = null; - } - - private isCurrentLifecycle(lifecycle: number) { - return !this.disposed && lifecycle === this.lifecycleEpoch; - } - - private deriveSnapshot(): StreamPageSnapshot { - const status = this.state.status; - const servicePhase = this.state.serviceLoading - ? 'loading' - : this.state.serviceProblem - ? 'degraded' - : 'available'; - const authoritativeRunning = - status?.running === true && - this.state.pollingFreshness === 'fresh' && - this.state.serviceProblem === null; - const statusOperationBusy = this.state.statusOperation !== null; - const copyBusy = this.state.oneOffOperations.has('copy'); - const overlayBusy = this.state.oneOffOperations.has('open_overlay'); - const settingsBusy = this.state.oneOffOperations.has('open_settings'); - - return { - service: { - phase: servicePhase, - status, - problem: this.state.serviceProblem, - operation: this.state.statusOperation === 'restart' ? 'restart' : null, - canRestart: !this.state.serviceLoading && !statusOperationBusy - }, - polling: { - freshness: this.state.pollingFreshness, - problem: this.state.pollingProblem - }, - window: { - problem: this.state.windowProblem, - canMoveMoreHistory: authoritativeRunning && !statusOperationBusy, - canMoveLessHistory: - authoritativeRunning && - !statusOperationBusy && - (status?.active_window_offset ?? 0) > 0 - }, - crop: { - settings: this.state.cropSettings, - code: this.state.cropCode, - problem: this.state.cropProblem, - canEdit: !this.state.cropLoading && this.state.cropOperation === null - }, - oneOff: { - problems: { ...this.state.oneOffProblems }, - obsUrl: status?.overlay_url ?? null, - canOpenOverlay: - authoritativeRunning && !statusOperationBusy && !overlayBusy, - canCopyObsUrl: status?.overlay_url != null && !copyBusy, - canOpenSettings: - authoritativeRunning && !statusOperationBusy && !settingsBusy - }, - notice: this.state.notice - }; - } - - private publish() { - if (this.disposed) return; - const next = this.deriveSnapshot(); - // A poll that changes nothing must not hand React a new object, or the - // Stream page re-renders every tick forever. - if (!structurallyEqual(this.snapshot, next)) { - this.snapshot = next; - } - for (const listener of this.listeners) listener(); - } -} - -/** - * Structural equality over a whole derived snapshot. The snapshot is plain - * JSON-shaped data — objects, arrays, strings, numbers, booleans and null — so - * comparing it generically keeps `publish` honest when a field is added to - * `StreamPageSnapshot` or to the Rust-generated `StreamServiceStatus`; a - * hand-written field list would silently ignore the new field and pin the page - * to a stale snapshot. Anything this shape does not cover (a function, Date, - * Map or class instance) counts as unequal unless it is the same reference, - * which errs toward publishing. - */ -function structurallyEqual(a: unknown, b: unknown): boolean { - if (Object.is(a, b)) return true; - if ( - typeof a !== 'object' || - typeof b !== 'object' || - a === null || - b === null - ) { - return false; - } - if (Array.isArray(a) || Array.isArray(b)) { - if (!Array.isArray(a) || !Array.isArray(b)) return false; - return ( - a.length === b.length && - a.every((item, index) => structurallyEqual(item, b[index])) - ); - } - if (!isPlainObject(a) || !isPlainObject(b)) return false; - - const left = a as Record; - const right = b as Record; - const keys = Object.keys(left); - if (keys.length !== Object.keys(right).length) return false; - return keys.every( - (key) => - Object.prototype.hasOwnProperty.call(right, key) && - structurallyEqual(left[key], right[key]) - ); -} - -function isPlainObject(value: object): boolean { - const prototype: unknown = Object.getPrototypeOf(value); - return prototype === Object.prototype || prototype === null; -} - -function initialState(): MutableState { - return { - status: null, - serviceLoading: true, - serviceProblem: null, - pollingFreshness: 'unknown', - pollingProblem: null, - cropSettings: defaultCropSettings, - cropCode: defaultCropSettings.code, - cropLoading: true, - cropProblem: null, - statusOperation: null, - windowProblem: null, - cropOperation: null, - oneOffOperations: new Set(), - oneOffProblems: { - copy: null, - open_overlay: null, - open_settings: null - }, - notice: null - }; -} - -function withLocaleParam(url: string, locale: string): string { - try { - const parsed = new URL(url); - parsed.searchParams.set('lang', locale); - return parsed.toString(); - } catch { - // A URL the backend did not produce is still worth opening as-is. - return url; - } -} - -export function createStreamWorkflow( - ports: StreamWorkflowPorts -): StreamWorkflow { - return new DefaultStreamWorkflow(ports); -} diff --git a/bazaarplusplus-installer/src/features/stream/useShellStreamServiceRunning.ts b/bazaarplusplus-installer/src/features/stream/useShellStreamServiceRunning.ts deleted file mode 100644 index defb0ae..0000000 --- a/bazaarplusplus-installer/src/features/stream/useShellStreamServiceRunning.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { useEffect, useState } from 'react'; -import { commandClient } from '../../api/commandClient'; - -/** Low-frequency shell hint for window-close copy. Not the Stream page source of truth. */ -const SHELL_STREAM_STATUS_POLL_MS = 4000; - -export function useShellStreamServiceRunning() { - const [running, setRunning] = useState(false); - - useEffect(() => { - let cancelled = false; - - const poll = async () => { - try { - const status = await commandClient.getStreamStatus(); - if (!cancelled) { - setRunning(status.running); - } - } catch { - if (!cancelled) { - setRunning(false); - } - } - }; - - void poll(); - const timer = window.setInterval(() => { - void poll(); - }, SHELL_STREAM_STATUS_POLL_MS); - - return () => { - cancelled = true; - window.clearInterval(timer); - }; - }, []); - - return running; -} diff --git a/bazaarplusplus-installer/src/features/stream/useStreamPage.ts b/bazaarplusplus-installer/src/features/stream/useStreamPage.ts deleted file mode 100644 index ba38820..0000000 --- a/bazaarplusplus-installer/src/features/stream/useStreamPage.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react'; -import { openUrl } from '@tauri-apps/plugin-opener'; -import { commandClient } from '../../api/commandClient'; -import { hasTauriRuntime } from '../../api/runtime'; -import { useI18n } from '../../i18n/LocaleProvider'; -import { - createStreamWorkflow, - type StreamClipboard, - type StreamOpener, - type StreamScheduler -} from './streamWorkflow'; - -const browserScheduler: StreamScheduler = { - setInterval: (callback, delayMs) => window.setInterval(callback, delayMs), - clearInterval: (handle) => window.clearInterval(handle as number), - setTimeout: (callback, delayMs) => window.setTimeout(callback, delayMs), - clearTimeout: (handle) => window.clearTimeout(handle as number) -}; - -const browserClipboard: StreamClipboard = { - writeText: (value) => navigator.clipboard.writeText(value) -}; - -const streamOpener: StreamOpener = { - async open(url) { - if (hasTauriRuntime()) { - await openUrl(url); - return; - } - - window.open(url, '_blank', 'noopener,noreferrer'); - } -}; - -export function useStreamPage() { - // The workflow is created once, so the locale enters as a live read rather - // than a captured value. - const { locale } = useI18n(); - const localeRef = useRef(locale); - localeRef.current = locale; - - const workflow = useMemo( - () => - createStreamWorkflow({ - commands: commandClient, - scheduler: browserScheduler, - clipboard: browserClipboard, - opener: streamOpener, - currentLocale: () => localeRef.current - }), - [] - ); - const snapshot = useSyncExternalStore( - workflow.subscribe, - workflow.getSnapshot, - workflow.getSnapshot - ); - - useEffect(() => { - void workflow.start(); - return () => workflow.dispose(); - }, [workflow]); - - return { snapshot, intents: workflow.intents }; -} diff --git a/bazaarplusplus-installer/src/i18n/LocaleProvider.tsx b/bazaarplusplus-installer/src/i18n/LocaleProvider.tsx deleted file mode 100644 index c773c0e..0000000 --- a/bazaarplusplus-installer/src/i18n/LocaleProvider.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import { - createContext, - use, - useCallback, - useEffect, - useMemo, - useState -} from 'react'; -import type { ReactNode } from 'react'; -import { commandClient } from '../api/commandClient'; -import { - LOCALE_STORAGE_KEY, - formatMessage, - messages, - resolveInitialLocale, - type Locale, - type MessageKey, - type TranslateParams -} from './messages'; - -export type Translate = (key: MessageKey, params?: TranslateParams) => string; - -export interface I18nController { - locale: Locale; - t: Translate; - toggle: () => void; -} - -const I18nContext = createContext(null); - -export function LocaleProvider({ children }: { children: ReactNode }) { - const [locale, setLocale] = useState(resolveInitialLocale); - - // Locale is authoritative on the frontend: persist it to localStorage so it - // survives a reload, reflect it on , and sync the desktop tray. - useEffect(() => { - if (typeof document !== 'undefined') { - document.documentElement.lang = messages[locale].htmlLang; - } - if (typeof window !== 'undefined') { - window.localStorage.setItem(LOCALE_STORAGE_KEY, locale); - } - void syncTrayLocale(locale); - }, [locale]); - - const toggle = useCallback( - () => setLocale((current) => (current === 'zh' ? 'en' : 'zh')), - [] - ); - - const t = useCallback( - (key, params) => formatMessage(locale, key, params), - [locale] - ); - - const value = useMemo( - () => ({ locale, t, toggle }), - [locale, t, toggle] - ); - - return {children}; -} - -export function useI18n(): I18nController { - const controller = use(I18nContext); - if (!controller) { - throw new Error('useI18n must be used inside LocaleProvider.'); - } - return controller; -} - -async function syncTrayLocale(locale: Locale) { - try { - await commandClient.setAppLocale(locale); - } catch { - // The web UI still switches even when the desktop tray sync fails. - } -} diff --git a/bazaarplusplus-installer/src/i18n/messages.test.ts b/bazaarplusplus-installer/src/i18n/messages.test.ts deleted file mode 100644 index 9f4565e..0000000 --- a/bazaarplusplus-installer/src/i18n/messages.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { formatMessage } from './messages'; - -describe('formatMessage', () => { - it('returns the raw message when no params are given', () => { - expect(formatMessage('en', 'updateInstall')).toBe('Download & Install'); - }); - - it('interpolates named placeholders', () => { - expect(formatMessage('en', 'updateModalBody', { version: '4.1.0' })).toBe( - 'BazaarPlusPlus 4.1.0 is available.' - ); - expect(formatMessage('zh', 'streamWindowOffset', { count: 3 })).toBe( - '向前补 3 条记录' - ); - }); - - it('selects the English singular or plural form from the count', () => { - expect(formatMessage('en', 'streamWindowOffset', { count: 1 })).toBe( - 'Back 1 record' - ); - expect(formatMessage('en', 'streamWindowOffset', { count: 3 })).toBe( - 'Back 3 records' - ); - }); - - it('selects each count independently in one message', () => { - expect( - formatMessage('en', 'storageCleanupRunDataDone', { - runs: 1, - files: 4, - size: '2 MB' - }) - ).toBe('Deleted 1 run and 4 files, freed about 2 MB.'); - expect( - formatMessage('en', 'storageCleanupRunDataDone', { - runs: 2, - files: 1, - size: '2 MB' - }) - ).toBe('Deleted 2 runs and 1 file, freed about 2 MB.'); - }); - - it('leaves a plural token untouched when its count is absent', () => { - expect(formatMessage('en', 'streamWindowOffset', { other: 1 })).toContain( - '{count|record|records}' - ); - }); -}); diff --git a/bazaarplusplus-installer/src/i18n/messages.ts b/bazaarplusplus-installer/src/i18n/messages.ts deleted file mode 100644 index e4b9377..0000000 --- a/bazaarplusplus-installer/src/i18n/messages.ts +++ /dev/null @@ -1,1157 +0,0 @@ -// Frontend translation catalog. `zh` is the source of truth for the set of -// message keys; `en` is typed `Record`, so TypeScript fails -// the build whenever a translation is missing or stale. Interpolate runtime -// values with `{name}` placeholders and pass them through `formatMessage`. -// -// Count-dependent English wording uses `{name|singular|plural}`, which selects -// on the numeric value of the `name` parameter. Chinese has no plural form, so -// zh copy simply omits the token. -// -// Product vocabulary, keep it consistent: -// BazaarPlusPlus 本体 = 插件 / plugin -// 插件 + BepInEx 等一起写入游戏目录的文件 = 组件 / components -// 本地 HTTP 服务 = 直播服务 / stream service -// 直播画面上的那一层 = 叠加层 / overlay - -export type Locale = 'en' | 'zh'; - -export const defaultLocale: Locale = 'zh'; - -export const LOCALE_STORAGE_KEY = 'locale'; - -const zh = { - // Document - htmlLang: 'zh-CN', - - // Header / brand - // Label shown on the language button for the CURRENT locale; clicking it - // switches to the other language, so the zh copy invites English. - languageToggle: 'Switch to English', - headerCheckUpdate: '检查更新', - headerCheckingUpdate: '检查中', - supportProject: '支持项目', - primaryNavigation: '主导航', - - // Window controls (Windows custom chrome) - windowControls: '窗口控制', - minimizeWindow: '最小化窗口', - maximizeWindow: '最大化窗口', - restoreWindow: '还原窗口', - closeWindow: '关闭窗口', - hideToTray: '隐藏到托盘', - hideToTrayWhileStreaming: '隐藏到托盘(直播服务仍在运行)', - - // Header social links - socialXiaohongshu: '小红书', - socialXiaohongshuTitle: '来小红书找我', - socialXiaohongshuSubtitle: 'VibeCoding 日常和碎碎念', - socialDouyin: '抖音', - socialDouyinTitle: '来抖音找我', - socialDouyinSubtitle: '短视频、开发切片和日常', - socialBilibili: 'B 站', - bilibiliProjectSubtitle: '教程、演示和项目内容', - bilibiliAuthorSubtitle: 'BazaarLine 作者', - bilibiliCoreDevSubtitle: 'CoreDev', - - // Support menu + payment modal - wechatPay: '微信支付', - wechatPayOpen: '打开收款码', - kofiSubtitle: '请作者喝杯咖啡', - supporterList: '支持者名单', - supporterListSubtitle: '查看名单', - wechatPayTagline: '请 Bazaar++ 喝一杯', - supportLine1: '有你支持,Bazaar++ 会冒出更多好东西', - supportLine2: '如果愿意,欢迎在备注里留一个支持者 ID', - - // Navigation rail - navInstall: '安装', - navHistory: '战绩', - navStream: '直播', - navAbout: '关于', - navSupport: '支持', - navLanguage: 'EN', - - // Shared actions - close: '关闭', - notifications: '通知', - cancel: '取消', - copy: '复制', - refresh: '刷新', - retry: '重试', - problemDiagnostics: '查看诊断信息', - - // Page titles - installTitle: '安装', - historyTitle: '战绩', - streamTitle: '直播', - aboutTitle: '关于', - - // Install page - gamePathEmpty: '未选择 The Bazaar 游戏目录', - installDetecting: '正在检测 The Bazaar 与 BazaarPlusPlus', - installRefreshing: '正在重新检测安装状态', - actionChooseDirectory: '选择游戏目录', - actionInstall: '安装', - actionReinstall: '重新安装', - actionResetData: '删除本地数据', - actionNoResettableData: '暂无本地数据', - actionResetBepinex: '删除 BepInEx 文件夹', - actionUninstall: '卸载', - actionDelete: '删除', - launchGame: '启动游戏', - installed: '已安装', - notInstalled: '未安装', - ready: '就绪', - modNeedsReinstall: '需要重新安装', - installDone: '安装完成', - resetDataConfirmTitle: '删除本地数据', - resetDataTarget: '目标:{path} 内的 BazaarPlusPlusV6 文件夹', - resetDataConfirmBody: - '这会删除 The Bazaar 游戏目录中 BazaarPlusPlusV6 下的本地数据库、截图和战斗回放视频。这包括尚未上传的对局数据。', - resetDataConfirmKeepsInstall: - '不会卸载 The Bazaar,也不会卸载 BazaarPlusPlus 插件。', - resetDataConfirmGameClosed: '请先退出 The Bazaar,避免数据文件仍被占用。', - resetDataConfirmAcknowledge: '我知道这些本地数据会被删除。', - resetDataConfirmAction: '删除本地数据', - resetDataRunning: '正在删除目标本地数据…', - resetDataDone: '本地数据已删除', - resetDataNothingToDelete: '未找到可删除的本地数据', - resetDataBlockedByGame: - 'The Bazaar 仍在运行,或无法确认游戏已退出。请先退出游戏,再删除本地数据。', - resetDataPartialFailure: - '有 {count} 个本地数据项目未能删除。请关闭游戏和直播来源后重试。', - resetDataFailureDetails: '查看未删除项目', - resetDataFailureCopy: '复制诊断信息', - resetDataFailureCopied: '已复制', - resetDataFailureCopyFailed: '复制失败,请手动选择文本复制', - resetBepinexConfirmTitle: '删除 BepInEx 文件夹', - resetBepinexTarget: '目标:{path} 内的 BepInEx 文件夹', - resetBepinexConfirmBody: - '这会删除 The Bazaar 游戏目录中的整个 BepInEx 文件夹。', - resetBepinexConfirmOtherMods: - '文件夹内的所有内容都会被删除,包括你安装的其他 BepInEx 插件。', - resetBepinexConfirmReinstall: - '删除后 BazaarPlusPlus 将不再生效,需要重新点击“安装”来恢复。', - resetBepinexConfirmGameClosed: '请先退出 The Bazaar,避免文件仍被占用。', - resetBepinexConfirmAcknowledge: - '我知道整个 BepInEx 文件夹(含其他插件)会被删除。', - resetBepinexConfirmAction: '删除 BepInEx 文件夹', - resetBepinexRunning: '正在删除目标 BepInEx 文件夹…', - resetBepinexDone: 'BepInEx 文件夹已删除', - resetBepinexNothingToDelete: '未找到 BepInEx 文件夹', - resetBepinexBlockedByGame: - 'The Bazaar 仍在运行,或无法确认游戏已退出。请先退出游戏,再删除 BepInEx 文件夹。', - resetBepinexPartialFailure: '有 {count} 个项目未能删除。请关闭游戏后重试。', - operationCannotBeCancelled: '操作已开始,完成前无法取消或关闭此窗口。', - uninstallConfirmTitle: '卸载 BazaarPlusPlus', - uninstallTarget: '目标:{path}', - uninstallConfirmBody: '将移除 BepInEx 与插件文件,保留本地数据与游戏本体。', - uninstallConfirmKeepsData: '本地数据库、截图与回放视频不会被删除。', - uninstallConfirmAction: '卸载', - uninstallRunning: '正在卸载…', - uninstallDone: '卸载完成', - installWarningGameMissing: - '未找到有效的 The Bazaar 游戏目录,请选择游戏目录。', - installWarningSteamConfigUnavailable: - '无法读取 Steam 启动项配置。请先启动一次 Steam,然后完全退出并重试。', - installWarningLaunchOptionsNotEmpty: - 'The Bazaar 的 Steam 启动项必须为空;修复会移除其中的全部内容。', - installWarningTrampolineNotReady: - 'macOS 游戏启动配置缺失或不是当前版本,需要修复。', - installWarningObsoleteMacosArtifacts: - '检测到不属于当前 macOS 安装方式的文件,需要清理。', - installWarningUnexpected: - '检测到未知的安装警告,请重新检测;若持续出现,请查看诊断信息。', - installBlockedByGame: - 'The Bazaar 仍在运行,或无法确认游戏已退出。请先退出游戏,再安装 BazaarPlusPlus。', - importBlockedByGame: - 'The Bazaar 仍在运行,或无法确认游戏已退出。请先退出游戏,再导入 V5 历史记录。', - legacyDeleteBlockedByGame: - 'The Bazaar 仍在运行,或无法确认游戏已退出。请先退出游戏,再删除旧数据文件夹。', - installProblemDetectionFailed: '检测安装状态失败,请重试。', - installProblemChooseDirectoryFailed: '无法打开游戏目录选择器,请重试。', - installProblemInstallFailed: - '安装或修复失败。请退出 The Bazaar 与 Steam,检查目录权限后重试。', - installProblemResetDataFailed: - '重置本地数据失败,请关闭占用文件的程序后重试。', - installProblemResetBepinexFailed: - '重置 BepInEx 失败,请退出 The Bazaar 后重试。', - installProblemUninstallFailed: - '卸载失败,请退出 The Bazaar 与 Steam 后重试。', - installProblemLaunchFailed: - '无法通过 Steam 启动游戏,请确认 Steam 正在运行后重试。', - installProblemUnexpected: '处理安装状态时发生意外错误,请重试。', - installProblemLegacyDataFailed: '无法读取旧版本数据文件夹,请重试。', - installProblemLegacyDeleteFailed: - '删除旧数据文件夹失败,请关闭占用文件的程序后重试。', - - // Legacy Roots - legacyDataHeading: '旧版本数据', - legacyDataHint: - '早期版本写入游戏目录的数据文件夹。当前版本不再读取它们,只有在你确认后才会删除。', - legacyRootSize: '{size},{files} 个文件', - legacyRootHardLinked: - '其中 {count} 个文件与其他位置共用磁盘空间,删除后实际释放的空间可能更少。', - legacyRootUnreadable: '有 {count} 个项目无法读取,未计入大小。', - legacyModReinstallRequired: - '已安装的 BazaarPlusPlus 仍在写入旧的数据文件夹。请重新安装,让它改用 BazaarPlusPlusV6。', - legacyDeleteAction: '删除 {name}', - legacyDeleteConfirmTitle: '删除旧数据文件夹', - legacyDeleteTarget: '目标:{path} 内的 {name} 文件夹', - legacyDeleteConfirmBody: - '这会永久删除 {name} 中的全部内容,包括早期版本的数据库、截图和回放。', - legacyDeleteConfirmSpace: - '部分文件可能与其他位置共用磁盘空间,删除后释放的空间可能少于显示的大小。', - legacyDeleteConfirmKeepsCurrent: - '当前数据(BazaarPlusPlusV6)、插件和游戏本体都不会受影响。', - legacyDeleteConfirmAcknowledge: '我知道 {name} 文件夹会被永久删除。', - legacyDeleteConfirmAction: '删除文件夹', - legacyDeleteRunning: '正在删除旧数据文件夹…', - legacyDeleteDone: '{name} 已删除', - legacyDeleteNothingToDelete: '{name} 已不存在', - legacyDeletePartialFailure: '有 {count} 个项目未能删除。请关闭游戏后重试。', - legacyDeleteAfterImport: - '导入完成,BazaarPlusPlusV6 中新增 {imported} 局。导入的对局只保存在本地,不会上传。', - legacyDeleteAfterImportSkipped: - '有 {count} 局 BazaarPlusPlusV6 中已经存在,未重复导入。', - legacyDeleteAfterImportUnavailableFiles: - '有 {count} 个截图或视频文件不在 BazaarPlusPlusV5 中,未能导入。', - legacyDeleteAfterImportOffer: - '现在可以删除 BazaarPlusPlusV5,也可以保留它。保留的话,它会继续列在“旧版本数据”中,之后随时可以删除。', - legacyDeleteKeep: '保留', - - // V5 import - legacyImportHeading: '导入 V5 历史记录', - legacyImportHint: - '把 BazaarPlusPlusV5 中的对局、截图和回放导入 BazaarPlusPlusV6,只需一次。导入的对局只显示在本地战绩中,不会上传;BazaarPlusPlusV5 保持不变。', - legacyImportAction: '导入', - legacyImportRunning: - '正在导入 V5 历史记录。请保持游戏关闭,完成前不要退出安装器。', - importFailedAlreadyImported: 'V5 历史记录已经导入过,无需再次导入。', - importFailedNotEligible: - '现在无法导入。请确认已安装当前版本的 BazaarPlusPlus,且 BazaarPlusPlusV5 文件夹仍在游戏目录中。', - importFailedModContract: - '已安装的 BazaarPlusPlus 缺少导入所需的信息。请重新安装后再导入。', - importFailedV5Database: - 'BazaarPlusPlusV5 中的战绩数据库缺失或无法识别,无法导入。BazaarPlusPlusV6 未被修改。', - importFailedInsufficientSpace: - '磁盘空间不足,无法复制 V5 的文件。导入已撤销,请释放空间后重试。', - importFailedFiles: - '复制 V5 的截图或回放文件失败,导入已撤销。请关闭占用这些文件的程序后重试。', - importFailedTarget: '写入 BazaarPlusPlusV6 失败,导入已撤销。请重试。', - importFailedMarker: - '历史记录已导入,但未能在 BazaarPlusPlusV5 中写入导入标记。请重试以完成,已导入的对局不会重复。', - - // Install confirmation modal - installModalTitle: '安装 BazaarPlusPlus', - tutorialKicker: '使用教程', - installModalBody: '安装完成后,从 Steam 启动游戏即可使用。', - viewTutorial: '查看教程', - installSteamNotice: - '安装前请先关闭 Steam;如果 Steam 正在运行,请手动退出后再继续。', - installSteamNoticeMacos: '请先退出游戏。继续安装将关闭 Steam。', - installCloseGameNotice: '请先退出游戏,再继续安装。', - installAcknowledge: '我了解使用第三方插件的风险,并自行承担。', - installing: '安装中…', - confirmInstall: '确认安装', - - // Update check (header) - updaterPreview: '浏览器预览', - updaterCurrent: '已是最新', - headerCheckFailed: '检查失败', - updateHeaderAvailable: '发现更新', - updateModalTitle: '发现新版本', - updateModalBody: 'BazaarPlusPlus {version} 已可用。', - updateMainlandDownloadTitle: '中国大陆下载', - updateMainlandDownloadHint: '自动更新较慢时,可通过大陆渠道手动下载。', - updateMainlandDownloadFailedHint: - '自动更新失败时,可通过大陆渠道下载安装包手动安装。', - updateMainlandDownload: '打开下载页', - updateModalLater: '稍后', - updateInstall: '下载并安装', - updateNotesLabel: '更新内容', - updateDownloading: '正在下载…', - updateInstalling: '正在安装…', - updateInstallingBody: '下载已完成,正在安装 BazaarPlusPlus {version}。', - updateReady: '更新完成,重启后生效', - updateReadyBody: 'BazaarPlusPlus {version} 已安装完成。重启应用后即可使用。', - updateRestartNow: '立即重启', - updateRestarting: '正在重启…', - updateError: '自动更新失败', - updateRestartFailedTitle: '自动重启失败', - updateRetry: '重试', - updateRetryRestart: '再次尝试重启', - updateDownloadProgressLabel: '更新下载进度', - updateDownloadProgressUnknown: '已下载 {downloaded} MB', - updateDownloadProgressKnown: '已下载 {downloaded} / {total} MB({percent}%)', - updaterProblemCheckFailed: '无法检查更新。请检查网络连接后重试。', - updaterProblemDownloadFailed: '更新下载失败。请检查网络连接后重试。', - updaterProblemInstallFailed: - '更新安装失败。请重试;如果问题持续,请重新打开应用后再次检查更新。', - updaterProblemRestartFailedMac: - '自动重启失败,但 BazaarPlusPlus {version} 已安装完成。请退出 BazaarPlusPlus,再从“应用程序”中重新打开。', - updaterProblemRestartFailedWindows: - '自动重启失败,但 BazaarPlusPlus {version} 已安装完成。请退出 BazaarPlusPlus,再从开始菜单重新打开。', - - // History page - historyLoading: '读取战绩中', - noLocalRuns: '暂无本地战绩', - historyEmptyDescription: - '完成一局 The Bazaar 对局后,战绩会自动显示在这里。你也可以刷新,或前往安装页检查游戏目录。', - historyEmptyRefresh: '刷新战绩', - historyEmptyInstall: '检查游戏目录', - viewDetail: '查看详情', - historySummaryRuns: '对局数', - historySummaryVideos: '视频数', - historySummaryWinRate: '十胜达成率', - historyOverviewLabel: '战绩概览', - historyPagination: '战绩分页', - historyPageRange: '第 {start}–{end} 局,共 {total} 局', - historyPageNumber: '{page} / {total} 页', - historyPreviousPage: '上一页', - historyNextPage: '下一页', - runModeRanked: '排位', - runModeUnranked: '匹配', - runModeNormal: '普通', - // Game data stays English at rest; History translates heroes and rank tiers - // at display time. Names follow the game's official Simplified Chinese copy. - heroVanessa: '凡妮莎', - heroPygmalien: '皮格马利翁', - heroDooley: '杜利', - heroMak: '马克', - heroJules: '朱尔斯', - heroStelle: '斯黛拉', - heroKarnok: '卡诺克', - heroTheDragons: '双龙', - rankBronze: '青铜', - rankSilver: '白银', - rankGold: '黄金', - rankDiamond: '钻石', - rankMaster: '大师', - rankLegendary: '传奇', - historyProblemUnavailable: - '未找到可用的本地战绩数据库。请先在安装页选择正确的游戏目录。', - historyProblemReadFailed: - '读取本地战绩失败。请关闭可能占用数据库的程序后重试。', - historyProblemBlockedByGame: - 'The Bazaar 仍在后台运行,正占用战绩数据库。关闭游戏窗口后进程有时不会退出;结束该进程即可读取战绩。', - historyEndGameProcess: '结束游戏进程', - historyEndGameProcessDone: '已结束游戏进程,正在重新读取战绩。', - historyEndGameProcessNotFound: '游戏进程已经退出,正在重新读取战绩。', - historyEndGameProcessFailedWindows: - '结束游戏进程失败。请在任务管理器中结束 TheBazaar.exe 后重试。', - historyEndGameProcessFailedMac: - '结束游戏进程失败。请在“活动监视器”中结束 The Bazaar 后重试。', - historyProblemUnsupportedSchema: - '战绩数据库版本不受支持(当前 {found},支持 {supported})。请更新 BazaarPlusPlus 插件或安装器。', - historyProblemUnexpected: '加载本地战绩时发生意外错误。请重试。', - historyOpenInstall: '前往安装页', - historyUnavailableImport: - '还没有 BazaarPlusPlusV6 战绩数据库,但游戏目录中有 BazaarPlusPlusV5 的历史记录。可以在安装页导入它们。', - historyUnavailableReinstall: - '游戏目录中有 BazaarPlusPlusV5 的历史记录,但已安装的 BazaarPlusPlus 仍在写入旧文件夹。请在安装页重新安装,然后导入。', - historyOpenImport: '前往导入', - historyPreviewFallback: '缩略图不可用;刷新页面可重试。', - historyPreviewEmpty: '暂无截图', - historyPreviewLoading: '正在加载截图…', - historyProblemThumbnailsUnavailable: - '缩略图服务无法启动,本地端口可能被占用;战绩仍可正常浏览。', - runResultMisfortune: '惨淡旅程', - runResultBronze: '青铜胜利', - runResultSilver: '白银胜利', - runResultGold: '黄金胜利', - runResultDiamond: '钻石胜利', - runResultAbandoned: '中途放弃', - runResultActive: '正在进行', - runMetricWins: '胜场', - runMetricDays: '天数', - runStatRank: '段位', - runStatRating: '段位分', - - // Run detail page - runDetailBack: '返回战绩列表', - runDetailLoading: '读取详情中', - runDetailNotFound: '没有找到这局战绩', - runDetailUnavailable: '战绩不可用', - runDetailRefreshing: '正在刷新详情', - runDetailProblemUnavailable: - '未找到可用的本地战绩数据库。请先在安装页选择正确的游戏目录。', - runDetailProblemReadFailed: - '读取这局战绩失败。请关闭可能占用数据库的程序后重试。', - runDetailProblemRevealScreenshotFailed: - '无法打开这局战绩的截图位置,请重试。', - runDetailProblemRevealVideoFailed: '无法打开这场战斗的视频位置,请重试。', - runDetailProblemDeleteVideoFailed: '删除这场战斗的视频失败,请重试。', - runDetailProblemUnexpected: '处理这局战绩时发生意外错误,请重试。', - runDetailPlayer: '玩家', - runStatusCompleted: '已完成', - runStatusAbandoned: '已放弃', - runStatusActive: '进行中', - openScreenshotLocation: '打开截图位置', - statWinLoss: '胜 / 负', - statFinalDay: '结束日', - statFinalRank: '最终段位', - statFinalRating: '段位分', - noLocalBattles: '暂无本地战斗记录', - noLocalBattlesDescription: '对局完成后战斗记录会自动出现在这里;也可刷新重试', - battleColDay: '天数', - battleColResult: '结果', - battleColOpponentHero: '对手英雄', - battleColOpponentPlayer: '对手玩家', - battleColRank: '段位', - battleColRating: '段位分', - battleColVideo: '视频', - battleResultWin: '胜', - battleResultLoss: '负', - battleResultNeutral: '平局', - openVideoLocation: '打开视频位置', - deleteVideo: '删除视频', - deleteVideoConfirmTitle: '删除视频', - deleteVideoTarget: '目标:战斗 {battleId} · 视频 {videoId}', - deleteVideoRunDate: '对局时间', - deleteVideoBattle: '战斗', - deleteVideoBattleDescription: '第 {day} 天 · {opponent}', - deleteVideoDuration: '视频时长', - deleteVideoTechnicalDetails: '技术详情', - battleVideoActionLabel: '{action}:第 {day} 天,对手 {opponent}', - deleteVideoConfirmBody: '这会永久删除该场战斗的回放视频文件,且无法恢复。', - deleteVideoConfirmAction: '删除视频', - deleteVideoRunning: '正在删除目标视频…', - - // Storage cleanup (History page) - storageCleanupTitle: '存储管理', - storageCleanupRangeLabel: '{scope}的清理时间范围', - storageCleanupPreviewLabel: '预览清理{scope}', - storageCleanupPreviewAction: '预览清理', - storageCleanupScreenshotsLabel: '对局结算截图', - storageCleanupRunDataLabel: '对局数据', - storageCleanupPresetAll: '全部', - storageCleanupPresetOlderThan7Days: '7 天前', - storageCleanupPresetBeforeThisMonth: '本月以前', - storageCleanupConfirmTitle: '确认清理', - storageCleanupTarget: '目标:{scope} · 范围:{preset}', - storageCleanupScreenshotsConfirmBody: - '清理完成前请保持游戏关闭。将删除 {count} 张结算截图(约 {size}),删除后无法恢复。', - storageCleanupRunDataConfirmBody: - '清理完成前请保持游戏关闭。将删除 {runs} 局对局记录,包括 {battles} 场战斗、{videos} 个回放视频及相关截图(约 {size}),删除后无法恢复。', - storageCleanupSkippedPending: '另有 {count} 项尚未完成上传,将自动跳过。', - storageCleanupNothingToClean: '没有符合条件的可清理数据。', - storageCleanupConfirmAction: '确认清理', - storageCleanupRunningScreenshots: '正在删除结算截图…', - storageCleanupRunningRunData: '正在删除对局数据…', - storageCleanupProblemUnavailable: - '未找到可清理的本地战绩数据库,请先在安装页选择正确的游戏目录。', - storageCleanupProblemPreviewFailed: '无法预览清理范围,请重试。', - storageCleanupProblemExecuteFailed: - '清理未完成,目标和范围已保留;请确认游戏已关闭,并查看诊断后重试或安全关闭。', - storageCleanupProblemUnexpected: '清理存储时发生意外错误,请重试。', - storageCleanupScreenshotsDone: '已删除 {files} 个文件,释放约 {size}。', - storageCleanupRunDataDone: - '已删除 {runs} 局对局和 {files} 个文件,释放约 {size}。', - noVideo: '无视频', - - // Stream page - streamDisplayModeLabel: '显示样式', - streamModeCurrent: '战斗场数', - streamModeHero: '完整英雄', - streamModeHeroHalf: '半高英雄', - streamOpenOverlay: '预览叠加层', - streamStart: '启动服务', - streamRestart: '重启服务', - streamObsPlaceholder: '直播服务启动后显示 OBS Browser Source 地址', - streamWindowSection: '展示窗口', - streamWindowLatest: '当前展示最新记录', - streamWindowOffset: '向前补 {count} 条记录', - streamMoreHistory: '更多历史', - streamLessHistory: '更少历史', - streamOverlayConfig: '叠加层配置', - streamCropCodeLabel: '裁切代码', - streamCropCodePlaceholder: '输入裁切代码…', - streamApplyCrop: '应用裁切代码', - streamResetCrop: '恢复默认裁切', - streamOpenSettings: '校准叠加层', - streamObsUrlLabel: 'OBS 地址', - streamInfoHost: '主机', - streamInfoPort: '端口', - streamInfoDb: '数据库', - streamInfoWindow: '窗口', - streamStatusError: '直播服务错误', - streamStatusStarting: '正在启动直播服务', - streamStatusRunning: '直播服务运行中', - streamStatusIdle: '直播服务未启动', - streamStatusStale: '直播服务状态可能已过期', - streamStatusUnavailable: '直播服务状态不可用', - streamStarting: '正在启动本地直播服务', - streamIdleDetail: '直播服务尚未启动', - streamStaleRunningDetail: '上次检测为运行中,正在等待最新的直播服务状态', - streamStaleIdleDetail: '上次检测为未运行,正在等待最新的直播服务状态', - streamStatusUnavailableDetail: '尚未取得可信的直播服务状态', - streamPortDetail: '端口 {port}', - streamRetryStatus: '重新获取状态', - streamRetryCrop: '重新加载配置', - streamCopied: 'OBS 地址已复制', - streamCopyFailed: '复制失败,请手动选择文本复制', - streamCropSaved: '裁切代码已保存', - streamCropReset: '裁切设置已恢复默认', - streamProblemServiceFailed: '直播服务未能启动。请确认端口 17654 可用后重试。', - streamProblemRestartFailed: '直播服务重启失败。请确认端口 17654 可用后重试。', - streamProblemPollFailed: - '暂时无法确认直播服务的最新状态;上次状态已标记为过期,请重新获取。', - streamProblemWindowFailed: '无法调整展示窗口,请重试。', - streamProblemCropLoadFailed: - '无法加载叠加层配置;其他直播控制仍可使用,请重新加载。', - streamProblemCropSaveFailed: '无法保存叠加层配置;请检查裁切代码并重试。', - streamProblemOpenOverlayFailed: '无法打开叠加层预览,请重试。', - streamProblemOpenSettingsFailed: '无法打开叠加层校准页,请重试。', - streamProblemUnexpected: '处理直播功能时发生意外错误,请重试。', - dbConnected: '数据库已连接', - dbMissing: '数据库未找到', - - // About page - aboutAppLabel: '应用', - aboutBppLabel: '插件', - aboutCredits: '致谢', - aboutContributors: '贡献者', - aboutAcknowledgements: '数据与灵感', - aboutLicenses: '开源许可', - aboutVerifiedBadge: 'Fable 5 认证', - aboutLoadingBootstrap: '正在获取本机应用信息,暂时显示随应用打包的备用数据。', - aboutFallbackPreview: '当前为浏览器预览,显示随应用打包的备用数据。', - aboutProblemBootstrapFailed: - '无法获取本机应用信息。已保留可用的备用数据,请重试。', - aboutUnavailableValue: '不可用', - aboutRetrying: '正在重试', - - // Refined dashboard copy - installOverviewHealthyShort: '所有组件运行正常', - installOverviewUpdateDescription: '当前组件版本不一致,重新安装即可完成更新', - installOverviewNotInstalledDescription: '选择游戏目录后即可安装插件', - installationDirectoryHeading: '游戏目录', - copyPath: '复制路径', - pathCopied: '已复制', - selectDirectory: '选择目录', - applicationVersionHeading: '应用版本', - developmentBuild: '开发版', - stableBuild: '正式版', - maintenanceToolsHeading: '高级操作', - maintenanceToolsHint: '卸载插件、重置 BepInEx 或删除本地数据', - maintenanceResetDataDescription: '删除本地数据库、截图与回放视频', - maintenanceNoResettableDataDescription: '当前没有可删除的本地数据', - maintenanceResetBepinexDescription: '重置插件环境', - maintenanceUninstallDescription: '移除所有组件', - historySummaryWinRateDescription: '十胜对局 / 已完成对局', - historySummaryWinRateUnavailable: '尚无已完成对局', - storageCleanupScreenshotsDescription: '保存对局结算时的截图文件', - storageCleanupRunDataDescription: '保存对局产生的各类数据文件', - aboutTagline: 'The Bazaar 数据增强与分析工具' -} as const; - -export type MessageKey = keyof typeof zh; - -const en: Record = { - htmlLang: 'en', - - languageToggle: '切换中文', - headerCheckUpdate: 'Check Updates', - headerCheckingUpdate: 'Checking', - supportProject: 'Support', - primaryNavigation: 'Primary navigation', - - windowControls: 'Window controls', - minimizeWindow: 'Minimize window', - maximizeWindow: 'Maximize window', - restoreWindow: 'Restore window', - closeWindow: 'Close window', - hideToTray: 'Hide to tray', - hideToTrayWhileStreaming: 'Hide to tray (stream service keeps running)', - - socialXiaohongshu: 'Xiaohongshu', - socialXiaohongshuTitle: 'Find me on Xiaohongshu', - socialXiaohongshuSubtitle: 'VibeCoding notes and daily life', - socialDouyin: 'Douyin', - socialDouyinTitle: 'Find me on Douyin', - socialDouyinSubtitle: 'Short videos, dev clips, and daily life', - socialBilibili: 'Bilibili', - bilibiliProjectSubtitle: 'Tutorials, demos, and project content', - bilibiliAuthorSubtitle: 'BazaarLine author', - bilibiliCoreDevSubtitle: 'CoreDev', - - wechatPay: 'WeChat Pay', - wechatPayOpen: 'Open QR code', - kofiSubtitle: 'Buy the author a coffee', - supporterList: 'Supporters', - supporterListSubtitle: 'View the list', - wechatPayTagline: 'Buy Bazaar++ a drink', - supportLine1: 'With your support, Bazaar++ keeps growing new things', - supportLine2: 'If you like, leave a supporter ID in the note', - - navInstall: 'Install', - navHistory: 'History', - navStream: 'Stream', - navAbout: 'About', - navSupport: 'Support', - navLanguage: '中文', - - close: 'Close', - notifications: 'Notifications', - cancel: 'Cancel', - copy: 'Copy', - refresh: 'Refresh', - retry: 'Retry', - problemDiagnostics: 'Show diagnostics', - - installTitle: 'Install', - historyTitle: 'History', - streamTitle: 'Stream', - aboutTitle: 'About', - - gamePathEmpty: 'No game directory selected for The Bazaar', - installDetecting: 'Detecting The Bazaar and BazaarPlusPlus', - installRefreshing: 'Re-detecting installation state', - actionChooseDirectory: 'Choose Game Directory', - actionInstall: 'Install', - actionReinstall: 'Reinstall', - actionResetData: 'Delete Local Data', - actionNoResettableData: 'No Local Data', - actionResetBepinex: 'Delete BepInEx Folder', - actionUninstall: 'Uninstall', - actionDelete: 'Delete', - launchGame: 'Launch Game', - installed: 'Installed', - notInstalled: 'Not Installed', - ready: 'Ready', - modNeedsReinstall: 'Reinstall required', - installDone: 'Install complete', - resetDataConfirmTitle: 'Delete Local Data', - resetDataTarget: 'Target: the BazaarPlusPlusV6 folder inside {path}', - resetDataConfirmBody: - 'This deletes the local database, screenshots, and combat replay videos under BazaarPlusPlusV6 in The Bazaar install directory. This includes battle data that has not been uploaded yet.', - resetDataConfirmKeepsInstall: - 'This does not uninstall The Bazaar or the BazaarPlusPlus plugin.', - resetDataConfirmGameClosed: - 'Quit The Bazaar first so data files are not held open.', - resetDataConfirmAcknowledge: 'I understand this local data will be deleted.', - resetDataConfirmAction: 'Delete Local Data', - resetDataRunning: 'Deleting the target local data…', - resetDataDone: 'Local data deleted', - resetDataNothingToDelete: 'No local data found to delete', - resetDataBlockedByGame: - 'The Bazaar is still running, or the installer could not confirm that it has closed. Quit the game before deleting local data.', - resetDataPartialFailure: - '{count} local data {count|item|items} could not be deleted. Close the game and stream sources, then try again.', - resetDataFailureDetails: 'Show undeleted items', - resetDataFailureCopy: 'Copy Diagnostics', - resetDataFailureCopied: 'Copied', - resetDataFailureCopyFailed: 'Copy failed. Select the text and copy manually.', - resetBepinexConfirmTitle: 'Delete BepInEx Folder', - resetBepinexTarget: 'Target: the BepInEx folder inside {path}', - resetBepinexConfirmBody: - 'This deletes the entire BepInEx folder in The Bazaar install directory.', - resetBepinexConfirmOtherMods: - 'Everything inside it is removed, including any other BepInEx plugins you installed.', - resetBepinexConfirmReinstall: - 'After this, BazaarPlusPlus stops working — click Install again to restore it.', - resetBepinexConfirmGameClosed: - 'Quit The Bazaar first so the files are not held open.', - resetBepinexConfirmAcknowledge: - 'I understand the entire BepInEx folder (including other plugins) will be deleted.', - resetBepinexConfirmAction: 'Delete BepInEx Folder', - resetBepinexRunning: 'Deleting the target BepInEx folder…', - resetBepinexDone: 'BepInEx folder deleted', - resetBepinexNothingToDelete: 'No BepInEx folder found', - resetBepinexBlockedByGame: - 'The Bazaar is still running, or the installer could not confirm that it has closed. Quit the game before deleting the BepInEx folder.', - resetBepinexPartialFailure: - '{count} {count|item|items} could not be deleted. Close the game, then try again.', - operationCannotBeCancelled: - 'This operation has started and cannot be canceled or dismissed until it finishes.', - uninstallConfirmTitle: 'Uninstall BazaarPlusPlus', - uninstallTarget: 'Target: {path}', - uninstallConfirmBody: - 'This removes BepInEx and plugin files while keeping local data and the base game.', - uninstallConfirmKeepsData: - 'Local database, screenshots, and replay videos are not deleted.', - uninstallConfirmAction: 'Uninstall', - uninstallRunning: 'Uninstalling…', - uninstallDone: 'Uninstall complete', - installWarningGameMissing: - 'No valid The Bazaar installation was found. Choose the game directory.', - installWarningSteamConfigUnavailable: - 'Steam launch-option configuration could not be read. Start Steam once, quit it completely, and retry.', - installWarningLaunchOptionsNotEmpty: - "The Bazaar's Steam launch options must be empty; Repair removes all of their contents.", - installWarningTrampolineNotReady: - 'The macOS game bootstrap is missing or is not the current version and needs repair.', - installWarningObsoleteMacosArtifacts: - 'Files outside the current macOS installation layout were found and need cleanup.', - installWarningUnexpected: - 'An unknown installation warning was detected. Re-detect; if it persists, check the diagnostics.', - installBlockedByGame: - 'The Bazaar is still running, or the installer could not confirm that it has closed. Quit the game before installing BazaarPlusPlus.', - importBlockedByGame: - 'The Bazaar is still running, or the installer could not confirm that it has closed. Quit the game before importing V5 history.', - legacyDeleteBlockedByGame: - 'The Bazaar is still running, or the installer could not confirm that it has closed. Quit the game before deleting the legacy data folder.', - installProblemDetectionFailed: - 'Installation state could not be detected. Please retry.', - installProblemChooseDirectoryFailed: - 'The game directory picker could not be opened. Please retry.', - installProblemInstallFailed: - 'Install or repair failed. Quit The Bazaar and Steam, check directory permissions, then retry.', - installProblemResetDataFailed: - 'Local data could not be reset. Close apps using those files, then retry.', - installProblemResetBepinexFailed: - 'BepInEx could not be reset. Quit The Bazaar, then retry.', - installProblemUninstallFailed: - 'Uninstall failed. Quit The Bazaar and Steam, then retry.', - installProblemLaunchFailed: - 'The game could not be launched through Steam. Make sure Steam is running, then retry.', - installProblemUnexpected: - 'Something unexpected happened while handling installation state. Please retry.', - installProblemLegacyDataFailed: - 'Data folders from earlier versions could not be read. Please retry.', - installProblemLegacyDeleteFailed: - 'The legacy data folder could not be deleted. Close apps using those files, then retry.', - - legacyDataHeading: 'Data from earlier versions', - legacyDataHint: - 'Folders earlier versions wrote into the game directory. This version no longer reads them, and they are deleted only after you confirm.', - legacyRootSize: '{size}, {files} {files|file|files}', - legacyRootHardLinked: - '{count} {count|file shares|files share} disk space with another location, so deleting may free less space.', - legacyRootUnreadable: - '{count} {count|item|items} could not be read and {count|is|are} not counted.', - legacyModReinstallRequired: - 'The installed BazaarPlusPlus still writes to an old data folder. Reinstall it so it uses BazaarPlusPlusV6.', - legacyDeleteAction: 'Delete {name}', - legacyDeleteConfirmTitle: 'Delete Legacy Data Folder', - legacyDeleteTarget: 'Target: the {name} folder inside {path}', - legacyDeleteConfirmBody: - 'This permanently deletes everything in {name}, including databases, screenshots, and replays from earlier versions.', - legacyDeleteConfirmSpace: - 'Some files may share disk space with another location, so deleting may free less space than shown.', - legacyDeleteConfirmKeepsCurrent: - 'Current data (BazaarPlusPlusV6), the mod, and the game are not affected.', - legacyDeleteConfirmAcknowledge: - 'I understand the {name} folder will be permanently deleted.', - legacyDeleteConfirmAction: 'Delete Folder', - legacyDeleteRunning: 'Deleting the legacy data folder…', - legacyDeleteDone: '{name} deleted', - legacyDeleteNothingToDelete: '{name} no longer exists', - legacyDeletePartialFailure: - '{count} {count|item|items} could not be deleted. Close the game, then try again.', - legacyDeleteAfterImport: - 'Import complete: {imported} {imported|run was|runs were} added to BazaarPlusPlusV6. Imported runs stay local and are never uploaded.', - legacyDeleteAfterImportSkipped: - '{count} {count|run was|runs were} already in BazaarPlusPlusV6 and {count|was|were} not imported again.', - legacyDeleteAfterImportUnavailableFiles: - '{count} {count|screenshot or video file was|screenshot or video files were} not in BazaarPlusPlusV5 and could not be imported.', - legacyDeleteAfterImportOffer: - 'You can delete BazaarPlusPlusV5 now or keep it. If you keep it, it stays listed under Data from earlier versions, and you can delete it later.', - legacyDeleteKeep: 'Keep Folder', - - legacyImportHeading: 'Import V5 History', - legacyImportHint: - 'Import the runs, screenshots, and replays in BazaarPlusPlusV5 into BazaarPlusPlusV6, once. Imported runs appear only in local History and are never uploaded; BazaarPlusPlusV5 is left as it is.', - legacyImportAction: 'Import', - legacyImportRunning: - 'Importing V5 history. Keep the game closed and do not quit the installer until it finishes.', - importFailedAlreadyImported: - 'V5 history was already imported; there is nothing to import again.', - importFailedNotEligible: - 'The import cannot run now. Make sure the current BazaarPlusPlus is installed and the BazaarPlusPlusV5 folder is still in the game directory.', - importFailedModContract: - 'The installed BazaarPlusPlus lacks what the import needs. Reinstall it, then import.', - importFailedV5Database: - 'The History database in BazaarPlusPlusV5 is missing or not recognized, so it cannot be imported. BazaarPlusPlusV6 was not changed.', - importFailedInsufficientSpace: - 'There is not enough disk space to copy the V5 files. The import was undone; free some space, then retry.', - importFailedFiles: - 'V5 screenshots or replays could not be copied, so the import was undone. Close apps using those files, then retry.', - importFailedTarget: - 'BazaarPlusPlusV6 could not be written, so the import was undone. Please retry.', - importFailedMarker: - 'History was imported, but the import marker could not be written to BazaarPlusPlusV5. Retry to finish; imported runs are not duplicated.', - - installModalTitle: 'Install BazaarPlusPlus', - tutorialKicker: 'Tutorial', - installModalBody: - 'After installation, launch the game from Steam to use the mod.', - viewTutorial: 'View tutorial', - installSteamNotice: - 'Please close Steam before installing. If Steam is running, quit it manually before continuing.', - installSteamNoticeMacos: 'Close the game first. Continuing will quit Steam.', - installCloseGameNotice: 'Close the game before continuing.', - installAcknowledge: - 'I understand and accept the risks of using third-party mods.', - installing: 'Installing…', - confirmInstall: 'Confirm Install', - - updaterPreview: 'Preview mode', - updaterCurrent: 'Up to date', - headerCheckFailed: 'Check failed', - updateHeaderAvailable: 'Update available', - updateModalTitle: 'Update Available', - updateModalBody: 'BazaarPlusPlus {version} is available.', - updateMainlandDownloadTitle: 'Mainland China download', - updateMainlandDownloadHint: - 'If automatic updates are slow, use the mainland download channel.', - updateMainlandDownloadFailedHint: - 'If the automatic update failed, download the installer from the mainland channel and install it manually.', - updateMainlandDownload: 'Open download', - updateModalLater: 'Later', - updateInstall: 'Download & Install', - updateNotesLabel: "What's new", - updateDownloading: 'Downloading…', - updateInstalling: 'Installing…', - updateInstallingBody: - 'The download is complete. Installing BazaarPlusPlus {version}.', - updateReady: 'Update ready — restart to apply', - updateReadyBody: - 'BazaarPlusPlus {version} is installed. Restart the app to use it.', - updateRestartNow: 'Restart Now', - updateRestarting: 'Restarting…', - updateError: 'Update failed', - updateRestartFailedTitle: 'Automatic restart failed', - updateRetry: 'Retry', - updateRetryRestart: 'Try Restart Again', - updateDownloadProgressLabel: 'Update download progress', - updateDownloadProgressUnknown: 'Downloaded {downloaded} MB', - updateDownloadProgressKnown: - 'Downloaded {downloaded} / {total} MB ({percent}%)', - updaterProblemCheckFailed: - 'Could not check for updates. Check your network connection, then retry.', - updaterProblemDownloadFailed: - 'The update could not be downloaded. Check your network connection, then retry.', - updaterProblemInstallFailed: - 'The update could not be installed. Retry; if the problem continues, reopen the app and check again.', - updaterProblemRestartFailedMac: - 'Automatic restart failed, but BazaarPlusPlus {version} is installed. Quit BazaarPlusPlus, then open it again from Applications.', - updaterProblemRestartFailedWindows: - 'Automatic restart failed, but BazaarPlusPlus {version} is installed. Quit BazaarPlusPlus, then open it again from the Start menu.', - - historyLoading: 'Loading runs', - noLocalRuns: 'No local runs yet', - historyEmptyDescription: - 'Completed The Bazaar runs appear here automatically. Refresh, or check the selected game directory on the Install page.', - historyEmptyRefresh: 'Refresh History', - historyEmptyInstall: 'Check Game Directory', - viewDetail: 'View Details', - historySummaryRuns: 'Runs', - historySummaryVideos: 'Videos', - historySummaryWinRate: '10-Win Rate', - historyOverviewLabel: 'History overview', - historyPagination: 'History pages', - historyPageRange: 'Runs {start}–{end} of {total}', - historyPageNumber: 'Page {page} of {total}', - historyPreviousPage: 'Previous', - historyNextPage: 'Next', - runModeRanked: 'Ranked', - runModeUnranked: 'Unranked', - runModeNormal: 'Normal', - heroVanessa: 'Vanessa', - heroPygmalien: 'Pygmalien', - heroDooley: 'Dooley', - heroMak: 'Mak', - heroJules: 'Jules', - heroStelle: 'Stelle', - heroKarnok: 'Karnok', - heroTheDragons: 'The Dragons', - rankBronze: 'Bronze', - rankSilver: 'Silver', - rankGold: 'Gold', - rankDiamond: 'Diamond', - rankMaster: 'Master', - rankLegendary: 'Legendary', - historyProblemUnavailable: - 'No local History database is available. Select the correct game directory on the Install page.', - historyProblemReadFailed: - 'Local History could not be read. Close apps that may be using the database, then retry.', - historyProblemBlockedByGame: - 'The Bazaar is still running in the background and holding the History database. Closing the game window does not always end its process; end it to read History.', - historyEndGameProcess: 'End Game Process', - historyEndGameProcessDone: 'Game process ended. Reloading History.', - historyEndGameProcessNotFound: - 'The game process had already exited. Reloading History.', - historyEndGameProcessFailedWindows: - 'The game process could not be ended. End TheBazaar.exe from Task Manager, then retry.', - historyEndGameProcessFailedMac: - 'The game process could not be ended. Quit The Bazaar from Activity Monitor, then retry.', - historyProblemUnsupportedSchema: - 'The History database schema is unsupported (found {found}, supported {supported}). Update the BazaarPlusPlus plugin or installer.', - historyProblemUnexpected: - 'Something unexpected happened while loading local History. Please retry.', - historyOpenInstall: 'Open Install', - historyUnavailableImport: - 'There is no BazaarPlusPlusV6 History database yet, but the game directory holds BazaarPlusPlusV5 history. Import it on the Install page.', - historyUnavailableReinstall: - 'The game directory holds BazaarPlusPlusV5 history, but the installed BazaarPlusPlus still writes to an old folder. Reinstall it on the Install page, then import.', - historyOpenImport: 'Open Import', - historyPreviewFallback: 'Thumbnail unavailable; refresh to retry.', - historyPreviewEmpty: 'No screenshot', - historyPreviewLoading: 'Loading screenshot…', - historyProblemThumbnailsUnavailable: - "Thumbnails can't load: the local image service couldn't start (its port may be in use). History still works.", - runResultMisfortune: 'MISFORTUNE JOURNEY', - runResultBronze: 'BRONZE VICTORY', - runResultSilver: 'SILVER VICTORY', - runResultGold: 'GOLD VICTORY', - runResultDiamond: 'DIAMOND VICTORY', - runResultAbandoned: 'ABANDONED', - runResultActive: 'ACTIVE', - runMetricWins: 'Wins', - runMetricDays: 'Days', - runStatRank: 'Rank', - runStatRating: 'Rating', - - runDetailBack: 'Back to History', - runDetailLoading: 'Loading details', - runDetailNotFound: 'This run was not found', - runDetailUnavailable: 'Run unavailable', - runDetailRefreshing: 'Refreshing details', - runDetailProblemUnavailable: - 'No local History database is available. Select the correct game directory on the Install page.', - runDetailProblemReadFailed: - 'This run could not be read. Close apps that may be using the database, then retry.', - runDetailProblemRevealScreenshotFailed: - 'The screenshot location could not be opened. Please retry.', - runDetailProblemRevealVideoFailed: - 'The video location could not be opened. Please retry.', - runDetailProblemDeleteVideoFailed: - 'The battle video could not be deleted. Please retry.', - runDetailProblemUnexpected: - 'Something unexpected happened while handling this run. Please retry.', - runDetailPlayer: 'Player', - runStatusCompleted: 'Completed', - runStatusAbandoned: 'Abandoned', - runStatusActive: 'Active', - openScreenshotLocation: 'Open screenshot location', - statWinLoss: 'Wins / Losses', - statFinalDay: 'Final Day', - statFinalRank: 'Final Rank', - statFinalRating: 'Rating', - noLocalBattles: 'No local battle records', - noLocalBattlesDescription: - 'Battle records appear here automatically after a run finishes. You can also refresh to retry.', - battleColDay: 'Day', - battleColResult: 'Result', - battleColOpponentHero: 'Opponent Hero', - battleColOpponentPlayer: 'Opponent Player', - battleColRank: 'Rank', - battleColRating: 'Rating', - battleColVideo: 'Video', - battleResultWin: 'WIN', - battleResultLoss: 'LOSS', - battleResultNeutral: 'DRAW', - openVideoLocation: 'Open Video Location', - deleteVideo: 'Delete Video', - deleteVideoConfirmTitle: 'Delete Video', - deleteVideoTarget: 'Target: battle {battleId} · video {videoId}', - deleteVideoRunDate: 'Run started', - deleteVideoBattle: 'Battle', - deleteVideoBattleDescription: 'Day {day} · {opponent}', - deleteVideoDuration: 'Video duration', - deleteVideoTechnicalDetails: 'Technical details', - battleVideoActionLabel: '{action}: day {day}, opponent {opponent}', - deleteVideoConfirmBody: - 'This permanently deletes the replay video file for this battle and cannot be undone.', - deleteVideoConfirmAction: 'Delete Video', - deleteVideoRunning: 'Deleting the target video…', - - storageCleanupTitle: 'Storage', - storageCleanupRangeLabel: 'Cleanup time range for {scope}', - storageCleanupPreviewLabel: 'Review cleanup of {scope}', - storageCleanupPreviewAction: 'Review cleanup', - storageCleanupScreenshotsLabel: 'End-of-run screenshots', - storageCleanupRunDataLabel: 'Run data', - storageCleanupPresetAll: 'All', - storageCleanupPresetOlderThan7Days: 'Older than 7 days', - storageCleanupPresetBeforeThisMonth: 'Before this month', - storageCleanupConfirmTitle: 'Confirm Cleanup', - storageCleanupTarget: 'Target: {scope} · Range: {preset}', - storageCleanupScreenshotsConfirmBody: - 'Keep The Bazaar closed until cleanup finishes. This will permanently delete {count} end-of-run {count|screenshot|screenshots} (about {size}). This cannot be undone.', - storageCleanupRunDataConfirmBody: - 'Keep The Bazaar closed until cleanup finishes. This will permanently delete {runs} {runs|run|runs}, including {battles} {battles|battle|battles}, {videos} replay {videos|video|videos} and related screenshots (about {size}). This cannot be undone.', - storageCleanupSkippedPending: - '{count} {count|item is|items are} still pending upload and will be skipped.', - storageCleanupNothingToClean: 'Nothing matches the selected range.', - storageCleanupConfirmAction: 'Clean Up', - storageCleanupRunningScreenshots: 'Deleting end-of-run screenshots…', - storageCleanupRunningRunData: 'Deleting run data…', - storageCleanupProblemUnavailable: - 'No local History database is available to clean. Select the correct game directory on the Install page.', - storageCleanupProblemPreviewFailed: - 'The cleanup range could not be previewed. Please retry.', - storageCleanupProblemExecuteFailed: - 'Cleanup did not finish. The target and range are preserved; make sure The Bazaar is closed and review diagnostics, then retry or close safely.', - storageCleanupProblemUnexpected: - 'Something unexpected happened while cleaning storage. Please retry.', - storageCleanupScreenshotsDone: - 'Deleted {files} {files|file|files}, freed about {size}.', - storageCleanupRunDataDone: - 'Deleted {runs} {runs|run|runs} and {files} {files|file|files}, freed about {size}.', - noVideo: 'No Video', - - streamDisplayModeLabel: 'Display style', - streamModeCurrent: 'Battle Count', - streamModeHero: 'Full Hero', - streamModeHeroHalf: 'Half Hero', - streamOpenOverlay: 'Preview Overlay', - streamStart: 'Start Service', - streamRestart: 'Restart Service', - streamObsPlaceholder: - 'The OBS Browser Source URL appears after the stream service starts', - streamWindowSection: 'Display Window', - streamWindowLatest: 'Showing the latest record', - streamWindowOffset: 'Back {count} {count|record|records}', - streamMoreHistory: 'More History', - streamLessHistory: 'Less History', - streamOverlayConfig: 'Overlay Config', - streamCropCodeLabel: 'Crop code', - streamCropCodePlaceholder: 'Enter crop code…', - streamApplyCrop: 'Apply Crop Code', - streamResetCrop: 'Reset Crop', - streamOpenSettings: 'Calibrate Overlay', - streamObsUrlLabel: 'OBS URL', - streamInfoHost: 'Host', - streamInfoPort: 'Port', - streamInfoDb: 'DB', - streamInfoWindow: 'Window', - streamStatusError: 'Stream Service Error', - streamStatusStarting: 'Stream Service Starting', - streamStatusRunning: 'Stream Service Running', - streamStatusIdle: 'Stream Service Stopped', - streamStatusStale: 'Stream Service Status May Be Stale', - streamStatusUnavailable: 'Stream Service Status Unavailable', - streamStarting: 'Starting the local stream service', - streamIdleDetail: 'The stream service is not running', - streamStaleRunningDetail: - 'Last seen running; waiting for an up-to-date stream service status', - streamStaleIdleDetail: - 'Last seen stopped; waiting for an up-to-date stream service status', - streamStatusUnavailableDetail: - 'No authoritative stream service status is available', - streamPortDetail: 'Port {port}', - streamRetryStatus: 'Refresh Status', - streamRetryCrop: 'Reload Config', - streamCopied: 'OBS URL copied', - streamCopyFailed: 'Copy failed. Select the text and copy manually.', - streamCropSaved: 'Crop code saved', - streamCropReset: 'Crop settings reset to default', - streamProblemServiceFailed: - 'The stream service could not start. Make sure port 17654 is available, then retry.', - streamProblemRestartFailed: - 'The stream service could not restart. Make sure port 17654 is available, then retry.', - streamProblemPollFailed: - 'The latest stream service status could not be confirmed. The previous value is marked stale; refresh it.', - streamProblemWindowFailed: 'The display window could not be changed. Retry.', - streamProblemCropLoadFailed: - 'Overlay configuration could not be loaded. Other stream controls remain available; reload it.', - streamProblemCropSaveFailed: - 'Overlay configuration could not be saved. Check the crop code and retry.', - streamProblemOpenOverlayFailed: - 'The overlay preview could not be opened. Retry.', - streamProblemOpenSettingsFailed: - 'The overlay calibration page could not be opened. Retry.', - streamProblemUnexpected: - 'Something unexpected happened while handling Stream. Please retry.', - dbConnected: 'DB Connected', - dbMissing: 'DB Missing', - - aboutAppLabel: 'App', - aboutBppLabel: 'Plugin', - aboutCredits: 'Credits', - aboutContributors: 'Contributors', - aboutAcknowledgements: 'Data & Inspiration', - aboutLicenses: 'Licenses', - aboutVerifiedBadge: 'Fable 5 Verified', - aboutLoadingBootstrap: - 'Loading native app information. Packaged fallback data is shown for now.', - aboutFallbackPreview: - 'Browser Preview is showing fallback data packaged with the app.', - aboutProblemBootstrapFailed: - 'Native app information could not be loaded. Usable fallback data remains available; please retry.', - aboutUnavailableValue: 'Unavailable', - aboutRetrying: 'Retrying', - - installOverviewHealthyShort: 'All components are running normally', - installOverviewUpdateDescription: - 'Component versions differ; reinstall to finish updating', - installOverviewNotInstalledDescription: - 'Choose the game directory to install the plugin', - installationDirectoryHeading: 'Game Directory', - copyPath: 'Copy Path', - pathCopied: 'Copied', - selectDirectory: 'Choose Directory', - applicationVersionHeading: 'App Version', - developmentBuild: 'Development', - stableBuild: 'Stable', - maintenanceToolsHeading: 'Advanced', - maintenanceToolsHint: 'Uninstall, reset BepInEx, or delete local data', - maintenanceResetDataDescription: - 'Delete the local database, screenshots, and replay videos', - maintenanceNoResettableDataDescription: 'No local data to delete right now', - maintenanceResetBepinexDescription: 'Reset the plugin environment', - maintenanceUninstallDescription: 'Remove all components', - historySummaryWinRateDescription: '10-win runs / completed runs', - historySummaryWinRateUnavailable: 'No completed runs yet', - storageCleanupScreenshotsDescription: 'Screenshot files saved at run end', - storageCleanupRunDataDescription: 'Data files generated by completed runs', - aboutTagline: 'Data enhancement and analysis for The Bazaar' -}; - -export const messages: Record> = { zh, en }; - -export type TranslateParams = Record; - -// `{name|singular|plural}` selects on the numeric value of `params[name]`. -const PLURAL_TOKEN = /\{([a-zA-Z0-9_]+)\|([^|{}]*)\|([^|{}]*)\}/g; - -export function formatMessage( - locale: Locale, - key: MessageKey, - params?: TranslateParams -): string { - let text = messages[locale][key]; - if (!params) { - return text; - } - text = text.replace(PLURAL_TOKEN, (match, name, one, other) => { - const value = params[name]; - if (value === undefined) return match; - return Number(value) === 1 ? one : other; - }); - for (const [name, value] of Object.entries(params)) { - text = text.replaceAll(`{${name}}`, String(value)); - } - return text; -} - -function normalizeLocale(value: string | undefined | null): Locale | null { - if (!value) return null; - const lower = value.toLowerCase(); - if (lower.startsWith('zh')) return 'zh'; - if (lower.startsWith('en')) return 'en'; - return null; -} - -export function resolveInitialLocale(): Locale { - if (typeof window === 'undefined') { - return defaultLocale; - } - const saved = window.localStorage.getItem(LOCALE_STORAGE_KEY); - if (saved === 'en' || saved === 'zh') { - return saved; - } - // No stored choice yet: follow the host language before falling back to zh. - const languages = - typeof navigator === 'undefined' - ? [] - : [...(navigator.languages ?? []), navigator.language]; - for (const language of languages) { - const resolved = normalizeLocale(language); - if (resolved) return resolved; - } - return defaultLocale; -} diff --git a/bazaarplusplus-installer/src/layouts/GlobalShell.tsx b/bazaarplusplus-installer/src/layouts/GlobalShell.tsx deleted file mode 100644 index 528ebd9..0000000 --- a/bazaarplusplus-installer/src/layouts/GlobalShell.tsx +++ /dev/null @@ -1,174 +0,0 @@ -import { Outlet, useLocation } from 'react-router-dom'; -import { useEffect, useRef, useState } from 'react'; -import { - AppBootstrapProvider, - useAppBootstrap -} from '../features/about/AppBootstrapProvider'; -import { UpdaterProvider, useUpdater } from '../features/about/UpdaterProvider'; -import { getUpdaterUiContract } from '../features/about/updaterPresentation'; -import { ShellHeader } from './ShellHeader'; -import { ShellNavRail } from './ShellNavRail'; -import { ShellPaymentModal } from './ShellPaymentModal'; -import { ShellUpdateModal } from './ShellUpdateModal'; -import { - ModalCoordinatorProvider, - ModalSource -} from '../components/ui/ModalCoordinator'; -import { ToastProvider, useToast } from '../components/ui/Toast'; -import { presentUpdaterProblem } from '../features/about/updaterProblems'; -import { useI18n } from '../i18n/LocaleProvider'; -import { useRouteScroll } from './useRouteScroll'; - -export default function GlobalShell() { - return ( - - - - - - - - - - ); -} - -function GlobalShellContent() { - const mainRef = useRouteScroll(); - const [showBilibili, setShowBilibili] = useState(false); - const [showSupport, setShowSupport] = useState(false); - const [showPaymentModal, setShowPaymentModal] = useState(false); - const bilibiliTriggerRef = useRef(null); - const supportTriggerRef = useRef(null); - const app = useAppBootstrap(); - const updater = useUpdater(); - const { t } = useI18n(); - const { showToast } = useToast(); - const updaterUi = getUpdaterUiContract(updater); - const previousUpdaterPhase = useRef(updater.phase); - - useEffect(() => { - const changed = previousUpdaterPhase.current !== updater.phase; - previousUpdaterPhase.current = updater.phase; - if (!changed) return; - - if (updater.phase === 'current') { - showToast({ - id: 'updater:check', - tone: 'success', - message: t('updaterCurrent') - }); - } else if (updater.phase === 'preview') { - showToast({ - id: 'updater:check', - tone: 'info', - message: t('updaterPreview') - }); - } else if ( - updater.phase === 'failed' && - updater.problem.code === 'updater_check_failed' - ) { - showToast({ - id: 'updater:check', - tone: 'error', - message: presentUpdaterProblem(updater.problem, t), - action: { label: t('retry'), onClick: updater.checkNow } - }); - } - }, [showToast, t, updater.phase, updater.problem, updater.checkNow]); - - // Close the header popovers on Escape or a click outside them — the native - // behaviour these controlled dropdowns were missing. - useEffect(() => { - if (!showBilibili && !showSupport) return; - const closeMenus = (restoreFocus = false) => { - const focusTarget = showBilibili - ? bilibiliTriggerRef.current - : supportTriggerRef.current; - setShowBilibili(false); - setShowSupport(false); - if (restoreFocus) queueMicrotask(() => focusTarget?.focus()); - }; - const onKeyDown = (event: KeyboardEvent) => { - if (event.key === 'Escape') closeMenus(true); - }; - const onPointerDown = (event: PointerEvent) => { - const target = event.target as HTMLElement | null; - if (!target?.closest('[data-dropdown]')) closeMenus(); - }; - window.addEventListener('keydown', onKeyDown); - window.addEventListener('pointerdown', onPointerDown); - return () => { - window.removeEventListener('keydown', onKeyDown); - window.removeEventListener('pointerdown', onPointerDown); - }; - }, [showBilibili, showSupport]); - - return ( -
    - { - setShowBilibili((open) => !open); - setShowSupport(false); - }} - onCloseBilibili={() => setShowBilibili(false)} - /> - -
    - { - setShowSupport((open) => !open); - setShowBilibili(false); - }} - onOpenPayment={() => { - setShowSupport(false); - setShowPaymentModal(true); - }} - onCloseSupport={() => setShowSupport(false)} - /> -
    -
    - -
    -
    -
    - - - setShowPaymentModal(false)} /> - - - {updaterUi.modal && ( - - )} - -
    - ); -} - -/** Route changes are immediate; the keyed wrapper only replays a short, - * non-blocking fade so the new page settles in. */ -function RouteOutlet() { - const location = useLocation(); - return ( -
    - -
    - ); -} diff --git a/bazaarplusplus-installer/src/layouts/ShellHeader.test.tsx b/bazaarplusplus-installer/src/layouts/ShellHeader.test.tsx deleted file mode 100644 index a409f7b..0000000 --- a/bazaarplusplus-installer/src/layouts/ShellHeader.test.tsx +++ /dev/null @@ -1,272 +0,0 @@ -// @vitest-environment jsdom - -import { act } from 'react'; -import { MemoryRouter } from 'react-router-dom'; -import { createRoot } from 'react-dom/client'; -import { renderToStaticMarkup } from 'react-dom/server'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import type { AppBootstrapController } from '../features/about/useAppBootstrap'; -import { UpdaterProvider } from '../features/about/UpdaterProvider'; -import { LocaleProvider } from '../i18n/LocaleProvider'; -import { LOCALE_STORAGE_KEY } from '../i18n/messages'; -import { idleStreamStatus } from '../api/previewDefaults'; -import { commandClient } from '../api/commandClient'; -import { ShellHeader } from './ShellHeader'; - -const tauriWindow = vi.hoisted(() => { - const state: { resizeHandler?: () => void } = {}; - const unlisten = vi.fn(); - return { - state, - api: { - minimize: vi.fn(async () => undefined), - toggleMaximize: vi.fn(async () => undefined), - close: vi.fn(async () => undefined), - isMaximized: vi.fn(async () => false), - onResized: vi.fn(async (handler: () => void) => { - state.resizeHandler = handler; - return unlisten; - }) - } - }; -}); - -vi.mock('@tauri-apps/api/window', () => ({ - getCurrentWindow: () => tauriWindow.api -})); - -vi.mock('../api/commandClient', async (importOriginal) => { - const actual = await importOriginal(); - return { - commandClient: { - ...actual.commandClient, - getStreamStatus: vi.fn(async () => ({ running: false })) - } - }; -}); -const { getStreamStatus } = commandClient; - -const bootstrap: AppBootstrapController['bootstrap'] = { - app_version: '4.4.0', - bundled_bpp_version: '4.4.0', - links: { - github: 'https://example.com/github', - x: 'https://example.com/x', - bilibili_project: 'https://example.com/bilibili-project', - bilibili_author: 'https://example.com/bilibili-author', - bilibili_core_dev: 'https://example.com/bilibili-core-dev', - xiaohongshu: 'https://example.com/xiaohongshu', - kofi: 'https://example.com/kofi', - supporter_list: 'https://example.com/supporters' - }, - credits: [], - licenses: [] -}; - -const app: AppBootstrapController = { - bootstrap, - resource: { - phase: 'authoritative', - data: bootstrap, - problem: null, - retrying: false - }, - retry: () => undefined -}; - -function renderHeader({ - showBilibili = false -}: { - showBilibili?: boolean; -} = {}) { - return renderToStaticMarkup( - - - - undefined} - onCloseBilibili={() => undefined} - /> - - - - ); -} - -describe('ShellHeader', () => { - // These assertions are written against the Chinese copy, and the locale now - // follows the host language when nothing is stored. - beforeEach(() => { - window.localStorage.setItem(LOCALE_STORAGE_KEY, 'zh'); - vi.mocked(getStreamStatus).mockClear(); - }); - - it('exposes controlled keyboard-operable disclosure semantics', () => { - const closed = renderHeader(); - const bilibiliOpen = renderHeader({ showBilibili: true }); - - expect(closed).toContain('aria-controls="shell-bilibili-menu"'); - expect(closed.match(/aria-expanded="false"/g)).toHaveLength(1); - expect(bilibiliOpen).toContain('id="shell-bilibili-menu"'); - expect(bilibiliOpen).toContain('aria-expanded="true"'); - }); - - it('never polls the stream service off Windows', async () => { - const container = document.createElement('div'); - document.body.append(container); - const root = createRoot(container); - - await act(async () => { - root.render( - - - - undefined} - onCloseBilibili={() => undefined} - /> - - - - ); - }); - - expect( - container.querySelectorAll('.bpp-window-control-button') - ).toHaveLength(0); - expect(getStreamStatus).not.toHaveBeenCalled(); - - await act(async () => root.unmount()); - container.remove(); - }); - - it('renders Windows controls and switches maximize copy after resize', async () => { - const userAgent = Object.getOwnPropertyDescriptor(navigator, 'userAgent'); - Object.defineProperty(navigator, 'userAgent', { - configurable: true, - value: 'Windows' - }); - Object.defineProperty(window, '__TAURI_INTERNALS__', { - configurable: true, - value: {} - }); - tauriWindow.api.isMaximized.mockResolvedValue(false); - tauriWindow.state.resizeHandler = undefined; - - const container = document.createElement('div'); - document.body.append(container); - const root = createRoot(container); - - await act(async () => { - root.render( - - - - undefined} - onCloseBilibili={() => undefined} - /> - - - - ); - }); - - expect( - container.querySelectorAll('.bpp-window-control-button') - ).toHaveLength(3); - const maximize = container.querySelector('button[aria-label="最大化窗口"]'); - expect(maximize).not.toBeNull(); - expect(maximize?.getAttribute('title')).toBe('最大化窗口'); - expect( - container.querySelector('button[aria-label="最小化窗口"]') - ).not.toBeNull(); - expect( - container.querySelector('button[aria-label="关闭窗口"]') - ).not.toBeNull(); - - await act(async () => { - maximize?.dispatchEvent(new MouseEvent('click', { bubbles: true })); - }); - expect(tauriWindow.api.toggleMaximize).toHaveBeenCalledOnce(); - - tauriWindow.api.isMaximized.mockResolvedValue(true); - await act(async () => { - tauriWindow.state.resizeHandler?.(); - }); - const restore = container.querySelector('button[aria-label="还原窗口"]'); - expect(restore).not.toBeNull(); - expect(restore?.getAttribute('title')).toBe('还原窗口'); - - await act(async () => root.unmount()); - container.remove(); - delete (window as Window & { __TAURI_INTERNALS__?: unknown }) - .__TAURI_INTERNALS__; - if (userAgent) { - Object.defineProperty(navigator, 'userAgent', userAgent); - } - }); - it.each([ - ['zh', '/history', '隐藏到托盘'], - ['en', '/history?page=2', 'Hide to tray'], - ['zh', '/stream', '隐藏到托盘(直播服务仍在运行)'], - ['en', '/stream', 'Hide to tray (stream service keeps running)'] - ] as const)( - 'keeps the %s close action accurate at %s', - async (locale, path, label) => { - const userAgent = Object.getOwnPropertyDescriptor(navigator, 'userAgent'); - Object.defineProperty(navigator, 'userAgent', { - configurable: true, - value: 'Windows' - }); - Object.defineProperty(window, '__TAURI_INTERNALS__', { - configurable: true, - value: {} - }); - window.localStorage.setItem(LOCALE_STORAGE_KEY, locale); - vi.mocked(getStreamStatus).mockResolvedValue({ - ...idleStreamStatus, - running: true - }); - const container = document.createElement('div'); - document.body.append(container); - const root = createRoot(container); - try { - await act(async () => - root.render( - - - - undefined} - onCloseBilibili={() => undefined} - /> - - - - ) - ); - const close = container.querySelector( - '.bpp-window-control-button:last-child' - ); - expect(close?.getAttribute('aria-label')).toBe(label); - expect(close?.getAttribute('title')).toBe(label); - } finally { - await act(async () => root.unmount()); - container.remove(); - delete (window as Window & { __TAURI_INTERNALS__?: unknown }) - .__TAURI_INTERNALS__; - if (userAgent) Object.defineProperty(navigator, 'userAgent', userAgent); - vi.mocked(getStreamStatus).mockResolvedValue(idleStreamStatus); - } - } - ); -}); diff --git a/bazaarplusplus-installer/src/layouts/ShellHeader.tsx b/bazaarplusplus-installer/src/layouts/ShellHeader.tsx deleted file mode 100644 index badb22e..0000000 --- a/bazaarplusplus-installer/src/layouts/ShellHeader.tsx +++ /dev/null @@ -1,551 +0,0 @@ -import { - Copy, - Minus, - MonitorPlay, - RefreshCw, - Square, - Users, - X -} from 'lucide-react'; -import { getCurrentWindow } from '@tauri-apps/api/window'; -import { useEffect, useState, type ReactNode, type RefObject } from 'react'; -import { useMatch } from 'react-router-dom'; -import { hasTauriRuntime } from '../api/runtime'; -import { Button } from '../components/ui/Button'; -import { useUpdater } from '../features/about/UpdaterProvider'; -import type { AppBootstrapController } from '../features/about/useAppBootstrap'; -import { isWindowsPlatform } from '../features/shared/platform'; -import { useShellStreamServiceRunning } from '../features/stream/useShellStreamServiceRunning'; -import { useI18n } from '../i18n/LocaleProvider'; -import douyinPng from '../../static/support/douyin.png'; -import xiaohongshuSvg from '../../static/support/xiaohongshu.svg'; -import brandLogo from '../../static/brand/bazaarplusplus-logo.webp'; - -type ShellHeaderProps = { - app: AppBootstrapController; - bilibiliTriggerRef?: RefObject; - showBilibili: boolean; - onToggleBilibili: () => void; - onCloseBilibili: () => void; -}; - -export function ShellHeader({ - app, - bilibiliTriggerRef, - showBilibili, - onToggleBilibili, - onCloseBilibili -}: ShellHeaderProps) { - const { bootstrap } = app; - - return ( -
    - - - -
    - ); -} - -function ShellBrand() { - return ( -
    - -

    BazaarPlusPlus

    - v{__FRONTEND_VERSION__} -
    - ); -} - -type ShellHeaderActionsProps = { - bootstrap: AppBootstrapController['bootstrap']; - bilibiliTriggerRef?: RefObject; - showBilibili: boolean; - onToggleBilibili: () => void; - onCloseBilibili: () => void; -}; - -function ShellHeaderActions({ - bootstrap, - bilibiliTriggerRef, - showBilibili, - onToggleBilibili, - onCloseBilibili -}: ShellHeaderActionsProps) { - return ( -
    -
    - -
    - -
    - ); -} - -/** App-wide update check; the updater opens its own dialog when a release is - * available and reports "already current" through a toast. */ -function ShellUpdateCheck() { - const { t } = useI18n(); - const updater = useUpdater(); - const checking = updater.phase === 'checking'; - return ( - - ); -} - -/** - * The macOS overlay title bar hides its traffic lights in native fullscreen; - * mirror that state so the header drops the inset reserved for them. - */ -function MacFullscreenWatcher() { - const [overlayTitlebar] = useState( - () => document.documentElement.dataset.bppTitlebar === 'overlay' - ); - useEffect(() => { - if (!overlayTitlebar) return; - let active = true; - let unlisten: (() => void) | undefined; - const window = getCurrentWindow(); - const sync = async () => { - try { - const fullscreen = await window.isFullscreen(); - if (!active) return; - if (fullscreen) document.documentElement.dataset.bppFullscreen = ''; - else delete document.documentElement.dataset.bppFullscreen; - } catch (error) { - console.error('Failed to read the macOS fullscreen state.', error); - } - }; - void sync(); - void window - .onResized(() => void sync()) - .then((stop) => { - if (active) unlisten = stop; - else stop(); - }) - .catch((error) => { - console.error('Failed to listen for macOS resize events.', error); - }); - return () => { - active = false; - unlisten?.(); - }; - }, [overlayTitlebar]); - return null; -} - -function isWindowsTauriRuntime() { - return hasTauriRuntime() && isWindowsPlatform(); -} - -/** - * Gate, not a wrapper: the hooks that poll native state live in the inner - * component so they are never scheduled off Windows, where the controls render - * nothing at all. - */ -function WindowsWindowControls() { - const [isWindowsRuntime] = useState(isWindowsTauriRuntime); - if (!isWindowsRuntime) return null; - return ; -} - -function minimizeWindow() { - void getCurrentWindow() - .minimize() - .catch((error) => { - console.error('Failed to minimize the Windows window.', error); - }); -} - -function toggleMaximizeWindow() { - void getCurrentWindow() - .toggleMaximize() - .catch((error) => { - console.error('Failed to toggle the Windows window size.', error); - }); -} - -function closeWindow() { - void getCurrentWindow() - .close() - .catch((error) => { - console.error('Failed to close the Windows window.', error); - }); -} - -function WindowsWindowControlsContent() { - const { t } = useI18n(); - const streamRunning = useShellStreamServiceRunning(); - const historyRoute = useMatch('/history/*'); - const [isMaximized, setIsMaximized] = useState(false); - const closeLabel = streamRunning - ? t(historyRoute ? 'hideToTray' : 'hideToTrayWhileStreaming') - : t('closeWindow'); - const maximizeLabel = isMaximized ? t('restoreWindow') : t('maximizeWindow'); - - useEffect(() => { - let active = true; - let unlisten: (() => void) | undefined; - const window = getCurrentWindow(); - const updateMaximized = async () => { - try { - const maximized = await window.isMaximized(); - if (active) setIsMaximized(maximized); - } catch (error) { - console.error( - 'Failed to read the Windows window maximized state.', - error - ); - } - }; - - void updateMaximized(); - void window - .onResized(() => { - void updateMaximized(); - }) - .then((stopListening) => { - if (active) { - unlisten = stopListening; - } else { - stopListening(); - } - }) - .catch((error) => { - console.error( - 'Failed to listen for Windows window resize events.', - error - ); - }); - - return () => { - active = false; - unlisten?.(); - }; - }, []); - - return ( -
    - - - -
    - ); -} - -type QrSocialEntryProps = { - href?: string; - label: string; - qrAlt: string; - qrSrc: string; - qrRound?: boolean; - subtitle: string; - title: string; - children: ReactNode; -}; - -function QrSocialEntry({ - href, - label, - qrAlt, - qrSrc, - qrRound = false, - subtitle, - title, - children -}: QrSocialEntryProps) { - const triggerClassName = 'bpp-header-icon-control'; - - const trigger = href ? ( - - {children} - - ) : ( - - ); - - return ( -
    - {trigger} -
    - {qrAlt} -
    -

    {title}

    -

    {subtitle}

    -
    -
    -
    - ); -} - -function ShellSocialLinks({ - bootstrap, - triggerRef, - showBilibili, - onToggleBilibili, - onCloseBilibili -}: { - bootstrap: AppBootstrapController['bootstrap']; - triggerRef?: RefObject; - showBilibili: boolean; - onToggleBilibili: () => void; - onCloseBilibili: () => void; -}) { - const { t } = useI18n(); - return ( - <> - - - - - - - - - - - - - - - - - - - - - - - - - - ); -} diff --git a/bazaarplusplus-installer/src/layouts/ShellNavRail.test.tsx b/bazaarplusplus-installer/src/layouts/ShellNavRail.test.tsx deleted file mode 100644 index f2dd870..0000000 --- a/bazaarplusplus-installer/src/layouts/ShellNavRail.test.tsx +++ /dev/null @@ -1,62 +0,0 @@ -// @vitest-environment jsdom - -import { renderToStaticMarkup } from 'react-dom/server'; -import { MemoryRouter } from 'react-router-dom'; -import { beforeEach, describe, expect, it } from 'vitest'; -import type { AppBootstrapController } from '../features/about/useAppBootstrap'; -import { LocaleProvider } from '../i18n/LocaleProvider'; -import { LOCALE_STORAGE_KEY } from '../i18n/messages'; -import { ShellNavRail } from './ShellNavRail'; - -const bootstrap = { - links: { - kofi: 'https://example.com/kofi', - supporter_list: 'https://example.com/supporters' - } -} as AppBootstrapController['bootstrap']; - -function renderRail({ - path = '/', - showSupport = false -}: { path?: string; showSupport?: boolean } = {}) { - return renderToStaticMarkup( - - - undefined} - onOpenPayment={() => undefined} - onCloseSupport={() => undefined} - /> - - - ); -} - -describe('ShellNavRail', () => { - beforeEach(() => { - window.localStorage.setItem(LOCALE_STORAGE_KEY, 'zh'); - }); - - it('lists the four pages and marks the current one', () => { - const html = renderRail({ path: '/history/run-1' }); - - for (const label of ['安装', '战绩', '直播', '关于']) { - expect(html).toContain(`>${label}`); - } - expect(html.match(/aria-current="page"/g)).toHaveLength(1); - expect(html).toMatch(/]*aria-current="page"[^>]*href="\/history"/); - }); - - it('puts support and language at the foot of the rail', () => { - const closed = renderRail(); - const open = renderRail({ showSupport: true }); - - expect(closed).toContain('aria-controls="shell-support-menu"'); - expect(closed).toContain('aria-expanded="false"'); - expect(closed).toContain('lucide-languages'); - expect(open).toContain('id="shell-support-menu"'); - expect(open).toContain('https://example.com/kofi'); - }); -}); diff --git a/bazaarplusplus-installer/src/layouts/ShellNavRail.tsx b/bazaarplusplus-installer/src/layouts/ShellNavRail.tsx deleted file mode 100644 index 8e1b2d7..0000000 --- a/bazaarplusplus-installer/src/layouts/ShellNavRail.tsx +++ /dev/null @@ -1,83 +0,0 @@ -import { NavLink } from 'react-router-dom'; -import type { ReactNode, RefObject } from 'react'; -import { Download, History, Info, Languages, MonitorPlay } from 'lucide-react'; -import clsx from 'clsx'; -import type { AppBootstrapController } from '../features/about/useAppBootstrap'; -import { useI18n } from '../i18n/LocaleProvider'; -import { ShellSupportMenu } from './ShellSupportMenu'; - -/** Icon rail: the four pages, then support and language at its foot. Route - * changes are immediate; nothing waits on an animation before navigating. */ -export function ShellNavRail({ - bootstrap, - supportTriggerRef, - showSupport, - onToggleSupport, - onOpenPayment, - onCloseSupport -}: { - bootstrap: AppBootstrapController['bootstrap']; - supportTriggerRef?: RefObject; - showSupport: boolean; - onToggleSupport: () => void; - onOpenPayment: () => void; - onCloseSupport: () => void; -}) { - const { t, toggle } = useI18n(); - - return ( - - ); -} - -function RailItem({ - to, - end = false, - icon, - label -}: { - to: string; - end?: boolean; - icon: ReactNode; - label: string; -}) { - return ( - - clsx('bpp-rail-item', isActive && 'is-active') - } - > - - {label} - - ); -} diff --git a/bazaarplusplus-installer/src/layouts/ShellPaymentModal.tsx b/bazaarplusplus-installer/src/layouts/ShellPaymentModal.tsx deleted file mode 100644 index 0235a51..0000000 --- a/bazaarplusplus-installer/src/layouts/ShellPaymentModal.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import wechatPaySvg from '../../static/support/wechat-pay.svg'; -import { - Dialog, - DialogBody, - DialogCard, - DialogHeader -} from '../components/ui/Dialog'; -import { useI18n } from '../i18n/LocaleProvider'; - -export function ShellPaymentModal({ onClose }: { onClose: () => void }) { - const { t } = useI18n(); - return ( - - - - - {t('wechatPay')} -
    -

    - {t('wechatPay')} -

    -

    {t('wechatPayTagline')}

    -
    -
    -

    {t('supportLine1')}

    -

    {t('supportLine2')}

    -
    -
    -
    -
    - ); -} diff --git a/bazaarplusplus-installer/src/layouts/ShellSupportMenu.tsx b/bazaarplusplus-installer/src/layouts/ShellSupportMenu.tsx deleted file mode 100644 index c2a4c82..0000000 --- a/bazaarplusplus-installer/src/layouts/ShellSupportMenu.tsx +++ /dev/null @@ -1,93 +0,0 @@ -import { Coffee, Heart, QrCode, Users } from 'lucide-react'; -import type { RefObject } from 'react'; -import type { AppBootstrapController } from '../features/about/useAppBootstrap'; -import { useI18n } from '../i18n/LocaleProvider'; - -/** The rail's support entry: WeChat Pay, Ko-fi and the supporter list. The - * menu opens beside the rail, growing upward from its trigger. */ -export function ShellSupportMenu({ - bootstrap, - triggerRef, - showSupport, - onToggleSupport, - onOpenPayment, - onCloseSupport -}: { - bootstrap: AppBootstrapController['bootstrap']; - triggerRef?: RefObject; - showSupport: boolean; - onToggleSupport: () => void; - onOpenPayment: () => void; - onCloseSupport: () => void; -}) { - const { t } = useI18n(); - return ( -
    - - {showSupport && ( - - )} -
    - ); -} diff --git a/bazaarplusplus-installer/src/layouts/ShellUpdateModal.test.tsx b/bazaarplusplus-installer/src/layouts/ShellUpdateModal.test.tsx deleted file mode 100644 index 1a324c3..0000000 --- a/bazaarplusplus-installer/src/layouts/ShellUpdateModal.test.tsx +++ /dev/null @@ -1,165 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server'; -import { describe, expect, it } from 'vitest'; -import type { UpdaterController } from '../features/about/useUpdater'; -import type { UpdaterSnapshot } from '../features/about/updater'; -import { getUpdaterUiContract } from '../features/about/updaterPresentation'; -import { updaterProblemFromError } from '../features/about/updaterProblems'; -import { LocaleProvider } from '../i18n/LocaleProvider'; -import { ShellUpdateModal } from './ShellUpdateModal'; - -function controller(snapshot: UpdaterSnapshot): UpdaterController { - return { - ...snapshot, - checkNow: () => undefined, - install: () => undefined, - restart: () => undefined, - dismiss: () => undefined - }; -} - -function renderModal(snapshot: UpdaterSnapshot): string { - const presentation = getUpdaterUiContract(snapshot).modal; - if (!presentation) throw new Error('test snapshot must render a modal'); - return renderToStaticMarkup( - - - - ); -} - -describe('ShellUpdateModal', () => { - it('links an available update to the matching mainland mirror', () => { - const html = renderModal({ - phase: 'available', - version: '5.1.0', - notes: '', - mainlandDownloadUrl: 'https://cauyxy.lanzout.com/bppmac510', - progress: null, - problem: null - }); - - expect(html).toContain('BazaarPlusPlus 5.1.0 已可用。'); - expect(html).not.toContain('BazaarPlusPlus Installer'); - expect(html).toContain('中国大陆下载'); - expect(html).toContain('自动更新较慢时,可通过大陆渠道手动下载。'); - expect(html).toContain('打开下载页'); - expect(html).toContain('https://cauyxy.lanzout.com/bppmac510'); - expect(html).toContain('tabindex="-1"'); - }); - - it('renders no mirror block when the manifest published none', () => { - const html = renderModal({ - phase: 'available', - version: '5.1.0', - notes: '', - mainlandDownloadUrl: null, - progress: null, - problem: null - }); - - expect(html).toContain('BazaarPlusPlus 5.1.0 已可用。'); - expect(html).not.toContain('中国大陆下载'); - expect(html).not.toContain('lanzout.com'); - }); - - it('keeps the mainland mirror reachable while the automatic download runs', () => { - const html = renderModal({ - phase: 'downloading', - version: '5.1.0', - notes: '', - mainlandDownloadUrl: 'https://cauyxy.lanzout.com/bppmac510', - progress: { downloaded: 1024, total: null }, - problem: null - }); - - expect(html).toContain('role="progressbar"'); - expect(html).toContain('自动更新较慢时,可通过大陆渠道手动下载。'); - expect(html).toContain('https://cauyxy.lanzout.com/bppmac510'); - }); - - it('offers the mainland mirror after the automatic download fails', () => { - const html = renderModal({ - phase: 'failed', - version: '5.1.0', - notes: '', - mainlandDownloadUrl: 'https://cauyxy.lanzout.com/bppmac510', - progress: null, - problem: updaterProblemFromError( - new Error('timed out'), - 'download', - '5.1.0' - ) - }); - - expect(html).toContain('更新下载失败。请检查网络连接后重试。'); - expect(html).toContain('重试'); - expect(html).toContain( - '自动更新失败时,可通过大陆渠道下载安装包手动安装。' - ); - expect(html).toContain('https://cauyxy.lanzout.com/bppmac510'); - }); - - it('exposes determinate progress value, minimum, maximum, label, and status', () => { - const mib = 1024 * 1024; - const html = renderModal({ - phase: 'downloading', - version: '5.1.0', - notes: '', - mainlandDownloadUrl: 'https://cauyxy.lanzout.com/bppmac510', - progress: { downloaded: 25 * mib, total: 100 * mib }, - problem: null - }); - - expect(html).toContain('role="progressbar"'); - expect(html).toContain('aria-label="更新下载进度"'); - expect(html).toContain('aria-valuemin="0"'); - expect(html).toContain(`aria-valuemax="${100 * mib}"`); - expect(html).toContain(`aria-valuenow="${25 * mib}"`); - expect(html).toContain('role="status"'); - expect(html).toContain('已下载 25.0 / 100.0 MB(25%)'); - expect(html).not.toContain('稍后'); - }); - - it('announces indeterminate downloaded bytes without inventing a maximum', () => { - const html = renderModal({ - phase: 'downloading', - version: '5.1.0', - notes: '', - mainlandDownloadUrl: 'https://cauyxy.lanzout.com/bppmac510', - progress: { downloaded: 2 * 1024 * 1024, total: null }, - problem: null - }); - - expect(html).not.toContain('aria-valuemax'); - expect(html).not.toContain('aria-valuenow'); - expect(html).toContain('aria-valuetext="已下载 2.0 MB"'); - }); - - it('shows restart recovery, retry, and optional diagnostics after install succeeded', () => { - const html = renderModal({ - phase: 'failed', - version: '5.1.0', - notes: '', - mainlandDownloadUrl: 'https://cauyxy.lanzout.com/bppmac510', - progress: null, - problem: updaterProblemFromError( - new Error('native relaunch detail'), - 'restart', - '5.1.0' - ) - }); - - expect(html).toContain('自动重启失败'); - expect(html).toContain( - '自动重启失败,但 BazaarPlusPlus 5.1.0 已安装完成。请退出 BazaarPlusPlus,再从“应用程序”中重新打开。' - ); - expect(html).not.toContain('BazaarPlusPlus Installer'); - expect(html).toContain('再次尝试重启'); - expect(html).toContain('查看诊断信息'); - expect(html).toContain('native relaunch detail'); - expect(html).not.toContain('lanzout.com'); - }); -}); diff --git a/bazaarplusplus-installer/src/layouts/ShellUpdateModal.tsx b/bazaarplusplus-installer/src/layouts/ShellUpdateModal.tsx deleted file mode 100644 index 3410386..0000000 --- a/bazaarplusplus-installer/src/layouts/ShellUpdateModal.tsx +++ /dev/null @@ -1,256 +0,0 @@ -import { - CloudDownload, - Download, - ExternalLink, - LoaderCircle, - RefreshCw -} from 'lucide-react'; -import { openUrl } from '@tauri-apps/plugin-opener'; -import { hasTauriRuntime } from '../api/runtime'; -import { Button } from '../components/ui/Button'; -import { ConfirmNote } from '../components/ui/ConfirmDialog'; -import { - Dialog, - DialogBody, - DialogCard, - DialogFooter, - DialogHeader -} from '../components/ui/Dialog'; -import { ProblemBanner } from '../components/ui/ProblemBanner'; -import type { UpdaterController } from '../features/about/useUpdater'; -import type { UpdaterUiContract } from '../features/about/updaterPresentation'; -import { presentUpdaterProblem } from '../features/about/updaterProblems'; -import { useI18n } from '../i18n/LocaleProvider'; -import type { MessageKey } from '../i18n/messages'; - -type ShellUpdateModalProps = { - updater: UpdaterController; - presentation: NonNullable; -}; - -function formatMegabytes(bytes: number): string { - return (bytes / (1024 * 1024)).toFixed(1); -} - -export function ShellUpdateModal({ - updater, - presentation -}: ShellUpdateModalProps) { - const { locale, t } = useI18n(); - const dismissible = presentation.dismissalPolicy === 'dismissible'; - const action = presentation.action; - const actionHandler = - action === 'install' || action === 'retry-install' - ? updater.install - : updater.restart; - // The mainland mirror only helps users on that side of the network, and the - // zh locale is the closest signal the frontend has for them. The address is - // whatever the Release Manifest published for this host, or nothing. - const mainlandDownloadUrl = - presentation.offersMainlandMirror && locale === 'zh' - ? updater.mainlandDownloadUrl - : null; - - return ( - - - - ) : updater.phase === 'ready-to-restart' || - (updater.phase === 'failed' && - updater.problem.code === 'updater_restart_failed') ? ( - - ) : ( - - ) - } - /> - - - {updater.phase === 'available' && ( - <> -

    - {t('updateModalBody', { version: updater.version })} -

    - {mainlandDownloadUrl && ( - - )} - {updater.notes && ( -
    -

    - {t('updateNotesLabel')} -

    -

    - {updater.notes} -

    -
    - )} - - )} - - {updater.phase === 'downloading' && ( - <> - - {mainlandDownloadUrl && ( - - )} - - )} - - {updater.phase === 'installing' && ( -

    - {t('updateInstallingBody', { version: updater.version })} -

    - )} - - {updater.phase === 'ready-to-restart' && ( -

    {t('updateReadyBody', { version: updater.version })}

    - )} - - {updater.phase === 'restarting' && ( -

    - {t('updateRestarting')} -

    - )} - - {updater.phase === 'failed' && ( - <> - - {mainlandDownloadUrl && ( - - )} - - )} -
    - - {dismissible && ( - - - {action && presentation.actionLabelKey && ( - - )} - - )} -
    -
    - ); -} - -function MainlandMirrorNote({ - url, - hintKey -}: { - url: string; - hintKey: MessageKey; -}) { - const { t } = useI18n(); - const openMainlandDownload = (event: React.MouseEvent) => { - if (!hasTauriRuntime()) return; - event.preventDefault(); - void openUrl(url).catch((error: unknown) => { - console.error('Failed to open the mainland installer download.', error); - }); - }; - - return ( - }> -

    {t('updateMainlandDownloadTitle')}

    -

    {t(hintKey)}

    - - {t('updateMainlandDownload')} - -
    - ); -} - -export function UpdateDownloadProgress({ - progress -}: { - progress: UpdaterController['progress']; -}) { - const { t } = useI18n(); - const downloaded = progress?.downloaded ?? 0; - const total = progress?.total ?? null; - const percent = - total && total > 0 - ? Math.min(100, Math.round((downloaded / total) * 100)) - : null; - const accessibleValue = - total === null ? undefined : Math.min(downloaded, total); - const status = - percent === null - ? t('updateDownloadProgressUnknown', { - downloaded: formatMegabytes(downloaded) - }) - : t('updateDownloadProgressKnown', { - downloaded: formatMegabytes(downloaded), - total: formatMegabytes(total ?? 0), - percent - }); - - return ( -
    -
    -
    -
    -

    - {status} -

    -
    - ); -} diff --git a/bazaarplusplus-installer/src/layouts/useRouteScroll.test.tsx b/bazaarplusplus-installer/src/layouts/useRouteScroll.test.tsx deleted file mode 100644 index 16454cb..0000000 --- a/bazaarplusplus-installer/src/layouts/useRouteScroll.test.tsx +++ /dev/null @@ -1,133 +0,0 @@ -// @vitest-environment jsdom - -import { act } from 'react'; -import { createRoot, type Root } from 'react-dom/client'; -import { - MemoryRouter, - useLocation, - useNavigate, - type NavigateFunction -} from 'react-router-dom'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { useRouteScroll } from './useRouteScroll'; - -let navigate: NavigateFunction; -let root: Root; -let container: HTMLDivElement; -let resize: () => void; -let maximum = 3000; -let offset = 0; - -function Shell() { - navigate = useNavigate(); - const location = useLocation(); - const ref = useRouteScroll(); - return ( -
    -
    {location.pathname + location.search}
    -
    - ); -} - -beforeEach(async () => { - maximum = 3000; - offset = 0; - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); - vi.stubGlobal( - 'ResizeObserver', - class { - constructor(callback: () => void) { - resize = callback; - } - observe() {} - disconnect() {} - } - ); - vi.spyOn(HTMLElement.prototype, 'scrollTop', 'get').mockImplementation( - () => offset - ); - vi.spyOn(HTMLElement.prototype, 'scrollTop', 'set').mockImplementation( - (value) => { - offset = Math.min(value, maximum); - } - ); - container = document.createElement('div'); - document.body.append(container); - root = createRoot(container); - await act(async () => { - root.render( - - - - ); - }); -}); - -afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - vi.restoreAllMocks(); - vi.unstubAllGlobals(); -}); - -function scrollTo(value: number) { - container.querySelector('main')!.scrollTop = value; - container.querySelector('main')!.dispatchEvent(new Event('scroll')); -} - -describe('route scrolling', () => { - it('opens a main navigation destination at the top', async () => { - scrollTo(450); - await act(async () => navigate('/stream')); - expect(offset).toBe(0); - scrollTo(110); - await act(async () => navigate('/about')); - expect(offset).toBe(0); - }); - - it('restores the matching history page after its delayed content arrives', async () => { - scrollTo(1450); - await act(async () => navigate('/history/run-123')); - expect(offset).toBe(0); - maximum = 0; - await act(async () => navigate('/history?page=3')); - expect(offset).toBe(0); - maximum = 3000; - resize(); - expect(offset).toBe(1450); - }); - - it('restores pagination on browser Back but starts a new page at the top', async () => { - scrollTo(1450); - await act(async () => navigate('/history?page=4')); - expect(offset).toBe(0); - scrollTo(900); - await act(async () => navigate(-1)); - expect(container.textContent).toBe('/history?page=3'); - expect(offset).toBe(1450); - }); - - it('forgets an older offset when the list is reopened through main navigation', async () => { - scrollTo(1450); - await act(async () => navigate('/about')); - await act(async () => navigate('/history?page=3')); - expect(offset).toBe(0); - await act(async () => navigate('/history/run-123')); - await act(async () => navigate('/history?page=3')); - expect(offset).toBe(0); - }); - - it('lets user input cancel a pending restoration', async () => { - scrollTo(1450); - await act(async () => navigate('/history/run-123')); - maximum = 0; - await act(async () => navigate(-1)); - container.querySelector('main')!.dispatchEvent(new Event('wheel')); - maximum = 3000; - scrollTo(100); - expect(offset).toBe(100); - await act(async () => navigate('/about')); - await act(async () => navigate(-1)); - expect(offset).toBe(100); - }); -}); diff --git a/bazaarplusplus-installer/src/layouts/useRouteScroll.ts b/bazaarplusplus-installer/src/layouts/useRouteScroll.ts deleted file mode 100644 index 3ac3a77..0000000 --- a/bazaarplusplus-installer/src/layouts/useRouteScroll.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { useLayoutEffect, useRef } from 'react'; -import { - NavigationType, - useLocation, - useNavigationType -} from 'react-router-dom'; - -export function useRouteScroll() { - const mainRef = useRef(null); - const positions = useRef(new Map()); - const previousPath = useRef(''); - const location = useLocation(); - const navigationType = useNavigationType(); - const path = location.pathname + location.search; - - useLayoutEffect(() => { - const main = mainRef.current; - if (!main) return; - const returningToHistory = - location.pathname === '/history' && - previousPath.current.startsWith('/history/'); - const restore = navigationType === NavigationType.Pop || returningToHistory; - const target = restore ? (positions.current.get(path) ?? 0) : 0; - previousPath.current = path; - let pending = target > 0; - - // A returning page can be shorter while its data is loading. Keep the - // saved offset until content can accommodate it or the user takes over. - const observer = new ResizeObserver(() => { - if (pending) applyPosition(); - }); - function applyPosition() { - main!.scrollTop = target; - pending = main!.scrollTop < target; - if (!pending) observer.disconnect(); - } - const savePosition = () => { - if (!pending) positions.current.set(path, main.scrollTop); - }; - const cancelRestore = () => { - pending = false; - observer.disconnect(); - savePosition(); - }; - applyPosition(); - savePosition(); - if (pending && main.firstElementChild) { - observer.observe(main.firstElementChild); - } - main.addEventListener('scroll', savePosition); - main.addEventListener('wheel', cancelRestore, { passive: true }); - main.addEventListener('touchstart', cancelRestore, { passive: true }); - main.addEventListener('pointerdown', cancelRestore); - main.addEventListener('keydown', cancelRestore); - return () => { - observer.disconnect(); - main.removeEventListener('scroll', savePosition); - main.removeEventListener('wheel', cancelRestore); - main.removeEventListener('touchstart', cancelRestore); - main.removeEventListener('pointerdown', cancelRestore); - main.removeEventListener('keydown', cancelRestore); - }; - }, [location.key, location.pathname, navigationType, path]); - - return mainRef; -} diff --git a/bazaarplusplus-installer/src/main.tsx b/bazaarplusplus-installer/src/main.tsx deleted file mode 100644 index f5ce5f8..0000000 --- a/bazaarplusplus-installer/src/main.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { StrictMode } from 'react'; -import { createRoot } from 'react-dom/client'; -import App from './App'; -import { scheduleNotoSansScLoad } from './features/shared/notoSansSc'; -import { isWindowsPlatform } from './features/shared/platform'; -import { hasTauriRuntime } from './api/runtime'; -import { LocaleProvider } from './i18n/LocaleProvider'; -import './styles/index.css'; - -// Platform-dependent chrome (Windows fonts, the macOS overlay title bar's -// traffic-light inset) must be right on the first frame. -const windows = isWindowsPlatform(); -document.documentElement.dataset.bppPlatform = windows ? 'windows' : 'macos'; -if (!windows && hasTauriRuntime()) { - document.documentElement.dataset.bppTitlebar = 'overlay'; -} - -createRoot(document.getElementById('root')!).render( - - - - - -); - -scheduleNotoSansScLoad(); diff --git a/bazaarplusplus-installer/src/pages/About.tsx b/bazaarplusplus-installer/src/pages/About.tsx deleted file mode 100644 index e986837..0000000 --- a/bazaarplusplus-installer/src/pages/About.tsx +++ /dev/null @@ -1,245 +0,0 @@ -import { ChevronDown, ExternalLink } from 'lucide-react'; -import { buttonClassName } from '../components/ui/Button'; -import { PageShell } from '../components/ui/PageShell'; -import { ProblemBanner } from '../components/ui/ProblemBanner'; -import { useAppBootstrap } from '../features/about/AppBootstrapProvider'; -import type { AppBootstrapSnapshot } from '../features/about/appBootstrap'; -import { presentAboutProblem } from '../features/about/aboutProblems'; -import { useI18n } from '../i18n/LocaleProvider'; -import type { MessageKey } from '../i18n/messages'; -import type { AppBootstrap, AppCredit } from '../types/backend'; -import fableVerifiedBadge from '../../static/about/fable-5-verified.webp'; -import brandLogo from '../../static/brand/bazaarplusplus-logo.webp'; - -// Credits are split into ordered groups by their `group` field so contributors -// stay separate from the external data/inspiration sources we acknowledge. -const CREDIT_GROUP_LABELS: Record = { - team: 'aboutContributors', - acknowledgement: 'aboutAcknowledgements' -}; - -function groupCredits( - credits: readonly AppCredit[] -): { key: string; items: AppCredit[] }[] { - const groups: { key: string; items: AppCredit[] }[] = []; - for (const credit of credits) { - const existing = groups.find((group) => group.key === credit.group); - if (existing) { - existing.items.push(credit); - } else { - groups.push({ key: credit.group, items: [credit] }); - } - } - return groups; -} - -export default function About() { - const { resource, retry } = useAppBootstrap(); - - return ; -} - -function AboutView({ - resource, - onRetry -}: { - resource: AppBootstrapSnapshot; - onRetry: () => void; -}) { - const { t } = useI18n(); - - return ( - - - - - ); -} - -function AboutBootstrapContent({ bootstrap }: { bootstrap: AppBootstrap }) { - const { t } = useI18n(); - // Both values are versions, so both read with the same `v` prefix. The - // bundled version comes from a file inside the payload zip, so it may or may - // not already carry one. - const bppVersionLabel = bootstrap.bundled_bpp_version - ? bootstrap.bundled_bpp_version.replace(/^v?/i, 'v') - : t('aboutUnavailableValue'); - - return ( - <> -
    -
    - -
    -

    BazaarPlusPlus

    -

    - {t('aboutTagline')} -

    -
    - - - GitHub - -
    -
    - {t('aboutAppLabel')} - - v{bootstrap.app_version} - - - {t('aboutBppLabel')} - - {bppVersionLabel} - - -
    -
    - -
    -

    {t('aboutCredits')}

    -
    - {groupCredits(bootstrap.credits).map((group) => ( -
    -

    - {t(CREDIT_GROUP_LABELS[group.key] ?? 'aboutContributors')} -

    -
      - {group.items.map((credit) => ( - - ))} -
    -
    - ))} -
    -
    - -
    - - {t('aboutLicenses')} - -
      - {bootstrap.licenses.map((license) => ( - - ))} -
    -
    - -
    - {t('aboutVerifiedBadge')} -
    - - ); -} - -function AboutBootstrapFeedback({ - resource, - onRetry -}: { - resource: AppBootstrapSnapshot; - onRetry: () => void; -}) { - const { t } = useI18n(); - if (resource.phase === 'authoritative') return null; - - if (resource.phase === 'initial-loading') { - return ( - - ); - } - - const retry = resource.problem ? onRetry : undefined; - - return ( - - ); -} - -function ListItem({ - name, - role, - href -}: { - name: string; - role?: string; - href?: string | null; -}) { - return ( -
  • - {href ? ( - - {name} - - ) : ( - {name} - )} - {role && {role}} -
  • - ); -} - -function GithubMark() { - return ( - - ); -} diff --git a/bazaarplusplus-installer/src/pages/History.test.tsx b/bazaarplusplus-installer/src/pages/History.test.tsx deleted file mode 100644 index 226978d..0000000 --- a/bazaarplusplus-installer/src/pages/History.test.tsx +++ /dev/null @@ -1,540 +0,0 @@ -// @vitest-environment jsdom - -import { act, StrictMode } from 'react'; -import { createRoot, type Root } from 'react-dom/client'; -import { MemoryRouter, useLocation } from 'react-router-dom'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { - emptyHistoryRunList, - emptyLegacyDataState, - idleStreamStatus -} from '../api/previewDefaults'; -import { commandClient } from '../api/commandClient'; -import { ToastProvider } from '../components/ui/Toast'; -import { LocaleProvider } from '../i18n/LocaleProvider'; -import { formatMessage, LOCALE_STORAGE_KEY } from '../i18n/messages'; -import type { LegacyDataState } from '../types/backend'; -import History from './History'; - -vi.mock('../api/commandClient', () => ({ - commandClient: { - listHistoryRuns: vi.fn(), - endGameProcess: vi.fn(), - prepareHistoryThumbnails: vi.fn(), - getStreamStatus: vi.fn(), - getLegacyDataState: vi.fn() - } -})); -const { listHistoryRuns, endGameProcess, prepareHistoryThumbnails } = - commandClient; -vi.mock('../features/history/HistoryOverview', () => ({ - HistoryOverview: () => null -})); - -const runs = Array.from({ length: 235 }, (_, index) => ({ - run_id: `run-${index + 1}`, - hero: `Hero ${index + 1}`, - game_mode: 'Ranked', - started_at_utc: '2026-09-12T10:00:00Z', - ended_at_utc: '2026-09-12T11:00:00Z', - result: 'win', - victories: 10, - losses: 0, - final_day: 10, - final_player_rank: null, - final_player_rating: null, - final_player_rating_delta: null, - screenshot_id: null, - thumbnail_url: null -})); -const loadedPage = (offset = 0, total = 235) => ({ - ...emptyHistoryRunList, - summary: { ...emptyHistoryRunList.summary, runs: total }, - runs: runs.slice(0, total).slice(offset, offset + 50) -}); -let container: HTMLDivElement; -let root: Root; - -function Route({ remountOnNavigation }: { remountOnNavigation: boolean }) { - const location = useLocation(); - return ( - <> - - {location.pathname + location.search} - - ); -} - -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); - localStorage.setItem(LOCALE_STORAGE_KEY, 'zh'); - vi.mocked(listHistoryRuns) - .mockReset() - .mockImplementation(async (_limit, offset) => loadedPage(offset ?? 0)); - vi.mocked(endGameProcess).mockReset().mockResolvedValue(true); - vi.mocked(prepareHistoryThumbnails).mockReset().mockResolvedValue(null); - vi.mocked(commandClient.getStreamStatus) - .mockReset() - .mockResolvedValue(idleStreamStatus); - vi.mocked(commandClient.getLegacyDataState) - .mockReset() - .mockResolvedValue(emptyLegacyDataState); - container = document.createElement('div'); - document.body.append(container); - root = createRoot(container); -}); - -afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - vi.unstubAllGlobals(); - vi.restoreAllMocks(); -}); - -async function render(path: string, remountOnNavigation = false) { - await act(async () => - root.render( - - - - - - - - - - ) - ); -} - -async function click(label: string) { - const button = [...container.querySelectorAll('button')].find( - (candidate) => candidate.textContent === label - ); - expect(button).toBeDefined(); - await act(async () => button!.click()); -} - -describe('history pagination', () => { - it('reaches records beyond 200 and keeps summary totals independent of the page', async () => { - await render('/history?page=5'); - expect(container.querySelectorAll('.bpp-history-run-card')).toHaveLength( - 35 - ); - expect(container.textContent).toContain('第 201–235 局,共 235 局'); - expect( - container.querySelector('.bpp-history-run-card')?.getAttribute('href') - ).toBe('/history/run-201'); - const next = [...container.querySelectorAll('button')].find( - (button) => button.textContent === '下一页' - ); - expect(next?.disabled).toBe(true); - await click('上一页'); - expect(container.querySelectorAll('.bpp-history-run-card')).toHaveLength( - 50 - ); - expect(container.textContent).toContain('第 151–200 局,共 235 局'); - }); - - it('shows a page failure without stale rows and retries that same page', async () => { - await render('/history'); - vi.mocked(listHistoryRuns).mockRejectedValueOnce({ - code: 'history_read_failed', - params: {}, - diagnostic: null - }); - await click('下一页'); - expect(container.querySelectorAll('.bpp-history-run-card')).toHaveLength(0); - expect(container.textContent).toContain('读取本地战绩失败'); - await click('重试'); - expect(container.textContent).toContain('第 51–100 局,共 235 局'); - }); - - it('moves to the last available page after the record count shrinks', async () => { - vi.mocked(listHistoryRuns).mockImplementation(async (_limit, offset) => - loadedPage(offset ?? 0, 52) - ); - await render('/history?page=5'); - expect(container.querySelectorAll('.bpp-history-run-card')).toHaveLength(2); - expect(container.textContent).toContain('第 51–52 局,共 52 局'); - expect(container.querySelector('[data-testid="route"]')?.textContent).toBe( - '/history?page=2' - ); - }); - - it('refreshes the current page when recovery started on an older page', async () => { - let finishRecovery!: (result: boolean) => void; - vi.mocked(endGameProcess).mockReturnValueOnce( - new Promise((resolve) => { - finishRecovery = resolve; - }) - ); - await render('/history'); - vi.mocked(listHistoryRuns).mockRejectedValueOnce({ - code: 'history_read_blocked_by_game', - params: {}, - diagnostic: null - }); - await click('刷新'); - await click('结束游戏进程'); - expect(endGameProcess).toHaveBeenCalledOnce(); - await click('下一页'); - expect( - container.querySelector('.bpp-history-run-card')?.getAttribute('href') - ).toBe('/history/run-51'); - - await act(async () => finishRecovery(true)); - - expect(listHistoryRuns).toHaveBeenLastCalledWith(50, 50); - expect( - container.querySelector('.bpp-history-run-card')?.getAttribute('href') - ).toBe('/history/run-51'); - expect(container.textContent).toContain('第 51–100 局,共 235 局'); - }); - - it('treats an invalid page parameter as the first page', async () => { - await render('/history?page=Infinity'); - expect(container.textContent).toContain('第 1–50 局,共 235 局'); - }); - - it('does not refresh an unmounted page when recovery completes after navigation', async () => { - let finishRecovery!: (result: boolean) => void; - vi.mocked(endGameProcess).mockReturnValueOnce( - new Promise((resolve) => { - finishRecovery = resolve; - }) - ); - // AnimatedOutlet remounts route content on location.key in the production shell. - await render('/history', true); - vi.mocked(listHistoryRuns).mockRejectedValueOnce({ - code: 'history_read_blocked_by_game', - params: {}, - diagnostic: null - }); - await click('刷新'); - await click('结束游戏进程'); - await click('下一页'); - const callsAfterNavigation = vi.mocked(listHistoryRuns).mock.calls.length; - expect( - container.querySelector('.bpp-history-run-card')?.getAttribute('href') - ).toBe('/history/run-51'); - - await act(async () => finishRecovery(true)); - - expect(listHistoryRuns).toHaveBeenCalledTimes(callsAfterNavigation); - expect(listHistoryRuns).toHaveBeenLastCalledWith(50, 50); - expect( - container.querySelector('.bpp-history-run-card')?.getAttribute('href') - ).toBe('/history/run-51'); - }); -}); - -const thumbnailUrl = (source: number, shot = 'shot-1') => - `http://127.0.0.1:17654/history/${source}/images/${shot}/strip`; -const thumbnailPage = (source: number, hero: string) => ({ - ...loadedPage(0, 1), - runs: [ - { - ...runs[0], - hero, - screenshot_id: 'shot-1', - thumbnail_url: thumbnailUrl(source) - } - ] -}); - -describe('History thumbnails', () => { - it('loads the list before preparation completes, then displays the prepared image', async () => { - let ready!: () => void; - const preparing = new Promise((resolve) => { - ready = () => resolve(null); - }); - vi.mocked(listHistoryRuns).mockResolvedValue(thumbnailPage(0, 'Vanessa')); - vi.mocked(prepareHistoryThumbnails).mockReturnValue(preparing); - await render('/history'); - expect(container.textContent).toContain('凡妮莎'); - expect(container.textContent).toContain('正在加载截图…'); - expect(container.textContent).not.toContain('刷新页面可重试'); - expect(container.querySelector('.bpp-history-run-preview img')).toBeNull(); - await act(async () => ready()); - expect( - container - .querySelector('.bpp-history-run-preview img') - ?.getAttribute('src') - ).toBe(thumbnailUrl(0)); - expect(container.querySelector('a[href="/stream"]')).toBeNull(); - }); - - it.each([ - ['zh', '暂无截图', '缩略图不可用;刷新页面可重试。', '刷新'], - [ - 'en', - 'No screenshot', - 'Thumbnail unavailable; refresh to retry.', - 'Refresh' - ] - ] as const)( - 'keeps missing screenshots distinct from failed thumbnails in %s', - async (locale, empty, failed, refresh) => { - localStorage.setItem(LOCALE_STORAGE_KEY, locale); - vi.mocked(listHistoryRuns).mockResolvedValue({ - ...loadedPage(0, 2), - runs: [runs[1], ...thumbnailPage(0, 'Vanessa').runs] - }); - vi.mocked(prepareHistoryThumbnails).mockRejectedValue( - new Error('unavailable') - ); - await render('/history'); - const cards = container.querySelectorAll('.bpp-history-run-card'); - expect(cards[0].textContent).toContain(empty); - expect(cards[0].textContent).not.toContain(failed); - expect(cards[1].textContent).toContain(failed); - - vi.mocked(prepareHistoryThumbnails).mockResolvedValue(null); - await click(refresh); - expect(cards[0].textContent).toContain(empty); - expect(cards[0].querySelector('img')).toBeNull(); - expect(cards[1].querySelector('img')).not.toBeNull(); - } - ); - - it.each([ - ['zh', '缩略图不可用;刷新页面可重试。', '刷新'], - ['en', 'Thumbnail unavailable; refresh to retry.', 'Refresh'] - ] as const)( - 'uses only the card fallback on failure in %s and retries the same image', - async (locale, fallback, refresh) => { - localStorage.setItem(LOCALE_STORAGE_KEY, locale); - vi.mocked(listHistoryRuns).mockResolvedValue(thumbnailPage(0, 'Vanessa')); - vi.mocked(prepareHistoryThumbnails).mockRejectedValue( - new Error('port occupied') - ); - await render('/history'); - expect(container.textContent).toContain( - locale === 'zh' ? '凡妮莎' : 'Vanessa' - ); - expect(container.textContent).toContain(fallback); - expect(container.textContent).not.toMatch( - /Stream|service|服务|直播|port occupied/ - ); - expect(container.querySelector('a[href="/stream"]')).toBeNull(); - vi.mocked(prepareHistoryThumbnails).mockResolvedValue(null); - await click(refresh); - const image = container.querySelector('.bpp-history-run-preview img'); - expect(image).not.toBeNull(); - await act(async () => image!.dispatchEvent(new Event('error'))); - expect( - container.querySelector('.bpp-history-run-preview img') - ).toBeNull(); - expect(container.textContent).toContain(fallback); - await click(refresh); - expect( - container - .querySelector('.bpp-history-run-preview img') - ?.getAttribute('src') - ).toBe(thumbnailUrl(0)); - } - ); - - it.each([ - [ - 'zh', - '缩略图服务无法启动,本地端口可能被占用;战绩仍可正常浏览。', - '缩略图不可用;刷新页面可重试。', - '刷新' - ], - [ - 'en', - "Thumbnails can't load: the local image service couldn't start (its port may be in use). History still works.", - 'Thumbnail unavailable; refresh to retry.', - 'Refresh' - ] - ] as const)( - 'tells %s readers when the image service cannot start, above cards that keep their fallback', - async (locale, notice, fallback, refresh) => { - localStorage.setItem(LOCALE_STORAGE_KEY, locale); - vi.mocked(listHistoryRuns).mockResolvedValue(thumbnailPage(0, 'Vanessa')); - vi.mocked(prepareHistoryThumbnails).mockRejectedValue({ - code: 'history_thumbnails_unavailable', - params: { operation: 'prepare_history_thumbnails' }, - diagnostic: 'Address already in use (os error 48)' - }); - await render('/history'); - const status = [...container.querySelectorAll('[role="status"]')].find( - (element) => element.textContent?.includes(notice) - ); - expect(status).toBeDefined(); - expect(status!.querySelector('button, a')).toBeNull(); - expect( - status!.compareDocumentPosition( - container.querySelector('.bpp-history-run-list')! - ) & Node.DOCUMENT_POSITION_FOLLOWING - ).toBeTruthy(); - expect(container.textContent).toContain( - locale === 'zh' ? '凡妮莎' : 'Vanessa' - ); - expect( - container.querySelector('.bpp-history-run-preview-empty')?.textContent - ).toBe(fallback); - - vi.mocked(prepareHistoryThumbnails).mockResolvedValue(null); - await click(refresh); - expect(container.textContent).not.toContain(notice); - expect( - container - .querySelector('.bpp-history-run-preview img') - ?.getAttribute('src') - ).toBe(thumbnailUrl(0)); - } - ); - - it('keeps loaded thumbnails through a focus refresh and retries only failed ones', async () => { - vi.mocked(listHistoryRuns).mockResolvedValue({ - ...loadedPage(0, 2), - runs: [ - { ...runs[0], screenshot_id: 'shot-1', thumbnail_url: thumbnailUrl(0) }, - { - ...runs[1], - screenshot_id: 'shot-2', - thumbnail_url: thumbnailUrl(0, 'shot-2') - } - ] - }); - await render('/history'); - const [loaded, broken] = container.querySelectorAll( - '.bpp-history-run-preview img' - ); - await act(async () => broken.dispatchEvent(new Event('error'))); - expect( - container.querySelectorAll('.bpp-history-run-preview img') - ).toHaveLength(1); - - let ready!: () => void; - vi.mocked(prepareHistoryThumbnails).mockReturnValueOnce( - new Promise((resolve) => { - ready = () => resolve(null); - }) - ); - await act(async () => window.dispatchEvent(new Event('focus'))); - expect(container.querySelector('.bpp-history-run-preview img')).toBe( - loaded - ); - await act(async () => ready()); - const images = container.querySelectorAll('.bpp-history-run-preview img'); - expect(images).toHaveLength(2); - expect(images[0]).toBe(loaded); - expect(images[1]).not.toBe(broken); - expect(images[1].getAttribute('src')).toBe(thumbnailUrl(0, 'shot-2')); - }); - - it('refreshes the current list and images when the same window becomes visible or regains focus', async () => { - vi.mocked(listHistoryRuns).mockResolvedValue( - thumbnailPage(0, 'Installation A') - ); - await render('/history'); - const visibility = vi.spyOn(document, 'visibilityState', 'get'); - visibility.mockReturnValue('hidden'); - await act(async () => - document.dispatchEvent(new Event('visibilitychange')) - ); - // B acquired a database while this window was hidden; its list and URLs must refresh together. - vi.mocked(listHistoryRuns).mockResolvedValue( - thumbnailPage(1, 'Installation B') - ); - visibility.mockReturnValue('visible'); - await act(async () => - document.dispatchEvent(new Event('visibilitychange')) - ); - expect(container.textContent).toContain('Installation B'); - expect(container.textContent).not.toContain('Installation A'); - expect( - container - .querySelector('.bpp-history-run-preview img') - ?.getAttribute('src') - ).toBe(thumbnailUrl(1)); - vi.mocked(prepareHistoryThumbnails).mockRejectedValue(new Error('stopped')); - await act(async () => window.dispatchEvent(new Event('focus'))); - expect(container.querySelector('.bpp-history-run-preview img')).toBeNull(); - vi.mocked(prepareHistoryThumbnails).mockResolvedValue(null); - await act(async () => window.dispatchEvent(new Event('focus'))); - expect( - container.querySelector('.bpp-history-run-preview img') - ).not.toBeNull(); - }); -}); - -const v5Only = (overrides: Partial): LegacyDataState => ({ - game_path: '/Games/The Bazaar', - roots: [ - { - name: 'BazaarPlusPlusV5', - size_bytes: 4096, - file_count: 3, - hard_linked_file_count: 0, - unreadable_entry_count: 0 - } - ], - installed_mod_data_root: 'current', - v5_import_eligible: true, - ...overrides -}); - -describe('history without a current database', () => { - function installLink() { - return [...container.querySelectorAll('a')].find( - (link) => - link.getAttribute('href')?.startsWith('/#') || - link.getAttribute('href') === '/' - ); - } - - beforeEach(() => { - vi.mocked(listHistoryRuns).mockRejectedValue({ - code: 'history_unavailable', - params: {}, - diagnostic: null - }); - }); - - it('points at the Install page import card when V5 history can be imported', async () => { - vi.mocked(commandClient.getLegacyDataState).mockResolvedValue(v5Only({})); - await render('/history'); - - expect(commandClient.getLegacyDataState).toHaveBeenCalledWith(null); - expect(container.textContent).toContain( - formatMessage('zh', 'historyUnavailableImport') - ); - const link = installLink(); - expect(link?.getAttribute('href')).toBe('/#legacy-data'); - expect(link?.textContent).toBe(formatMessage('zh', 'historyOpenImport')); - }); - - it('points at the reinstall hint when the mod still writes an old folder', async () => { - vi.mocked(commandClient.getLegacyDataState).mockResolvedValue( - v5Only({ - installed_mod_data_root: 'reinstall_required', - v5_import_eligible: false - }) - ); - await render('/history'); - - expect(container.textContent).toContain( - formatMessage('zh', 'historyUnavailableReinstall') - ); - expect(installLink()?.getAttribute('href')).toBe('/#legacy-data'); - }); - - it('keeps the plain Install link without V5 history', async () => { - vi.mocked(commandClient.getLegacyDataState).mockRejectedValue( - new Error('unreadable') - ); - await render('/history'); - - expect(container.textContent).toContain( - formatMessage('zh', 'historyProblemUnavailable') - ); - const link = installLink(); - expect(link?.getAttribute('href')).toBe('/'); - expect(link?.textContent).toBe(formatMessage('zh', 'historyOpenInstall')); - }); -}); diff --git a/bazaarplusplus-installer/src/pages/History.tsx b/bazaarplusplus-installer/src/pages/History.tsx deleted file mode 100644 index dc49798..0000000 --- a/bazaarplusplus-installer/src/pages/History.tsx +++ /dev/null @@ -1,413 +0,0 @@ -import { useState } from 'react'; -import { - ChevronRight, - History as HistoryIcon, - Image as ImageIcon, - ImageOff, - RefreshCw -} from 'lucide-react'; -import { Link } from 'react-router-dom'; -import { Button, buttonClassName } from '../components/ui/Button'; -import { EmptyState } from '../components/ui/EmptyState'; -import { LoadingPanel } from '../components/ui/LoadingPanel'; -import { PageShell } from '../components/ui/PageShell'; -import { ProblemBanner } from '../components/ui/ProblemBanner'; -import { StatusBanner } from '../components/ui/StatusBanner'; -import { - formatDateTime, - formatGameMode, - formatHero, - formatRank, - formatRatingDelta, - formatRunResultLabel, - ratingDeltaTrend -} from '../features/history/format'; -import { HistoryOverview } from '../features/history/HistoryOverview'; -import { - presentHistoryProblem, - type HistoryPageProblem -} from '../features/history/historyProblems'; -import { useHistoryPage } from '../features/history/useHistoryPage'; -import { useHistoryUnavailableGuidance } from '../features/history/useHistoryUnavailableGuidance'; -import { LEGACY_DATA_SECTION_ID } from '../features/install/LegacyDataPanel'; -import type { - EndGameProcessOutcome, - HistoryThumbnails -} from '../features/history/historyListWorkflow'; -import { isWindowsPlatform } from '../features/shared/platform'; -import { useToast } from '../components/ui/Toast'; -import { useI18n } from '../i18n/LocaleProvider'; -import type { MessageKey } from '../i18n/messages'; -import type { HistoryRunRow } from '../types/backend'; - -export default function History() { - const page = useHistoryPage(); - const { t } = useI18n(); - const { pagination } = page; - - return ( - } - > - {t('refresh')} - - } - > - {page.state.phase === 'initial-loading' ? ( - - ) : page.state.phase === 'blocking-failure' ? ( - - ) : ( - <> - - - {page.state.refresh.phase === 'failed' && ( - - )} - - {page.state.phase === 'ready-content' && - page.thumbnailsUnavailable && ( - } - message={ -

    - {t('historyProblemThumbnailsUnavailable')} -

    - } - /> - )} - -
    - {page.state.phase === 'ready-empty' ? ( -
    - } - heading={t('noLocalRuns')} - description={t('historyEmptyDescription')} - primaryAction={ - - } - secondaryAction={ - - {t('historyEmptyInstall')} - - } - /> -
    - ) : ( - page.state.data.runs.map((run: HistoryRunRow) => ( - - )) - )} -
    - {page.state.phase === 'ready-content' && ( - - )} - - )} -
    - ); -} - -function RunRow({ - run, - pageNumber, - thumbnailUrl, - thumbnailAttempt, - thumbnails -}: { - run: HistoryRunRow; - pageNumber: number; - thumbnailUrl: string | null; - thumbnailAttempt: number; - thumbnails: HistoryThumbnails; -}) { - const { locale, t } = useI18n(); - const result = formatRunResultLabel(run); - // A change without a rating to anchor it is not shown. - const ratingDelta = - run.final_player_rating === null - ? null - : formatRatingDelta(run.final_player_rating_delta); - const detailPath = `/history/${encodeURIComponent(run.run_id)}`; - const fallbackLabel = t( - !run.screenshot_id - ? 'historyPreviewEmpty' - : thumbnails === 'pending' - ? 'historyPreviewLoading' - : 'historyPreviewFallback' - ); - - return ( - - - - - - {formatHero(run.hero, t)} - - - - - - - {run.victories ?? '—'} - - - {t('runMetricWins')} - - - {t(result.key)} - - - - - {run.final_player_rating ?? '—'} - {ratingDelta && run.final_player_rating_delta !== null ? ( - - {ratingDelta} - - ) : null} - - - {run.final_player_rank - ? formatRank(run.final_player_rank, t) - : t('runStatRating')} - - - {t('runMetricDays')} {run.final_day ?? '—'} - - - - - - {formatGameMode(run.game_mode, t)} - - - - ); -} - -function RunThumbnail({ - thumbnailUrl, - thumbnailAttempt, - fallbackLabel -}: { - thumbnailUrl: string | null; - thumbnailAttempt: number; - fallbackLabel: string; -}) { - // A failed image retries after the next thumbnail preparation, not on every render. - const [failed, setFailed] = useState<{ - url: string; - attempt: number; - } | null>(null); - const visibleUrl = - thumbnailUrl && - !(failed?.url === thumbnailUrl && failed.attempt === thumbnailAttempt) - ? thumbnailUrl - : null; - - return ( -
    - {visibleUrl ? ( - // Preserve the complete server-generated strip. Its rounded crop - // dimensions can vary by a few pixels between source resolutions. - - setFailed({ url: visibleUrl, attempt: thumbnailAttempt }) - } - className="bpp-history-run-preview-image" - /> - ) : ( - - - )} -
    - ); -} - -function HistoryProblemBanner({ - problem, - onRetry, - onEndGameProcess, - endingGameProcess -}: { - problem: HistoryPageProblem; - onRetry: () => void; - onEndGameProcess: () => Promise; - endingGameProcess: boolean; -}) { - const { t } = useI18n(); - const { showToast } = useToast(); - // Only V5 data and no current database: point at the Install page's import - // or reinstall card instead of a bare Install link. - const guidance = useHistoryUnavailableGuidance( - problem.code === 'history_unavailable' - ); - - const endGameProcess = async () => { - const outcome = await onEndGameProcess(); - showToast({ - tone: outcome === 'failed' ? 'error' : 'success', - message: t(endGameProcessMessageKey(outcome)) - }); - }; - - return ( - - {problem.code === 'history_unavailable' && ( - - {guidance === 'import' - ? t('historyOpenImport') - : t('historyOpenInstall')} - - )} - {problem.code === 'history_read_blocked_by_game' && ( - - )} - - } - /> - ); -} - -function endGameProcessMessageKey(outcome: EndGameProcessOutcome): MessageKey { - switch (outcome) { - case 'terminated': - return 'historyEndGameProcessDone'; - case 'already-exited': - return 'historyEndGameProcessNotFound'; - case 'failed': - // The recovery step names a real OS surface, so it has to match the host. - return isWindowsPlatform() - ? 'historyEndGameProcessFailedWindows' - : 'historyEndGameProcessFailedMac'; - } -} diff --git a/bazaarplusplus-installer/src/pages/Install.tsx b/bazaarplusplus-installer/src/pages/Install.tsx deleted file mode 100644 index ade6d71..0000000 --- a/bazaarplusplus-installer/src/pages/Install.tsx +++ /dev/null @@ -1,253 +0,0 @@ -import { useEffect, useState } from 'react'; -import { Loader2 } from 'lucide-react'; -import { useLocation } from 'react-router-dom'; -import { PageShell } from '../components/ui/PageShell'; -import { LoadingPanel } from '../components/ui/LoadingPanel'; -import { useAppBootstrap } from '../features/about/AppBootstrapProvider'; -import { InstallActionsPanel } from '../features/install/InstallActionsPanel'; -import { InstallConfirmModal } from '../features/install/InstallConfirmModal'; -import { InstallStatusPanel } from '../features/install/InstallStatusPanel'; -import { - LEGACY_DATA_SECTION_ID, - LegacyDataPanel -} from '../features/install/LegacyDataPanel'; -import { LegacyRootDeleteConfirmModal } from '../features/install/LegacyRootDeleteConfirmModal'; -import { useLegacyData } from '../features/install/useLegacyData'; -import { ResetBepinexConfirmModal } from '../features/install/ResetBepinexConfirmModal'; -import { ResetDataConfirmModal } from '../features/install/ResetDataConfirmModal'; -import { UninstallConfirmModal } from '../features/install/UninstallConfirmModal'; -import { useInstallPage } from '../features/install/useInstallPage'; -import { useI18n } from '../i18n/LocaleProvider'; -import { InstallProblemBanner } from '../features/install/InstallProblemBanner'; -import { - installFailurePaths, - presentInstallNotice, - presentInstallProblem -} from '../features/install/installProblems'; -import { ModalSource } from '../components/ui/ModalCoordinator'; -import { useToast } from '../components/ui/Toast'; - -export default function Install() { - const { t } = useI18n(); - const app = useAppBootstrap(); - const { snapshot, intents } = useInstallPage(); - const { dismissToast, showToast } = useToast(); - const { hash } = useLocation(); - const [installAcknowledged, setInstallAcknowledged] = useState(false); - const [resetDataAcknowledged, setResetDataAcknowledged] = useState(false); - const [resetBepinexAcknowledged, setResetBepinexAcknowledged] = - useState(false); - const [legacyDeleteAcknowledged, setLegacyDeleteAcknowledged] = - useState(false); - const legacy = useLegacyData( - snapshot.phase === 'ready' ? snapshot.data : null - ); - const legacyConfirmation = legacy.snapshot.confirmation; - const legacyConfirmationRunning = legacyConfirmation?.phase === 'running'; - const legacyConfirmationProblem = - legacyConfirmation?.phase === 'failed' ? legacyConfirmation.problem : null; - const legacyTargetName = legacyConfirmation?.target.name ?? null; - const appVersion = app.bootstrap.app_version; - const confirmation = snapshot.confirmation; - const confirmationKind = confirmation?.target.kind ?? null; - const confirmationOpen = confirmation !== null; - const confirmationRunning = confirmation?.phase === 'running'; - const confirmationFailed = - confirmation?.phase === 'failed' ? confirmation.problem : null; - const resetFailurePaths = confirmationFailed - ? installFailurePaths(confirmationFailed) - : []; - - useEffect(() => { - setInstallAcknowledged(false); - setResetDataAcknowledged(false); - setResetBepinexAcknowledged(false); - }, [confirmationKind, confirmationOpen]); - - useEffect(() => { - setLegacyDeleteAcknowledged(false); - }, [legacyTargetName]); - - // History links here when it has no current database; bring the import or - // reinstall card into view once the Legacy Roots have loaded. - const legacyLoaded = legacy.snapshot.load.phase === 'ready'; - useEffect(() => { - if (hash !== `#${LEGACY_DATA_SECTION_ID}` || !legacyLoaded) return; - document.getElementById(LEGACY_DATA_SECTION_ID)?.scrollIntoView?.({ - block: 'start' - }); - }, [hash, legacyLoaded]); - - useEffect(() => { - const notice = legacy.snapshot.notice; - if (!notice) return; - showToast({ - id: `install:legacy-notice:${notice.id}`, - tone: 'success', - message: notice.removed - ? t('legacyDeleteDone', { name: notice.name }) - : t('legacyDeleteNothingToDelete', { name: notice.name }) - }); - legacy.workflow.acknowledgeNotice(notice.id); - }, [legacy.snapshot.notice, legacy.workflow, showToast, t]); - - useEffect(() => { - if (!snapshot.notice) return; - const notice = snapshot.notice; - showToast({ - id: `install:notice:${notice.id}`, - tone: 'success', - message: presentInstallNotice(notice.code, t) - }); - intents.acknowledgeNotice(notice.id); - }, [intents, showToast, snapshot.notice, t]); - - useEffect(() => { - if (!snapshot.actionProblem) { - dismissToast('install:action-problem'); - return; - } - showToast({ - id: 'install:action-problem', - tone: 'error', - message: presentInstallProblem(snapshot.actionProblem, t) - }); - }, [dismissToast, showToast, snapshot.actionProblem, t]); - - return ( - - {snapshot.phase === 'initial-loading' ? ( - - ) : snapshot.phase === 'blocking-failure' ? ( - void intents.refresh()} - /> - ) : snapshot.phase === 'ready' ? ( - <> - {snapshot.refresh.phase === 'failed' && ( - void intents.refresh()} - /> - )} - {snapshot.reconciliationProblem && ( - - )} - {snapshot.refresh.phase === 'refreshing' && ( -

    -

    - )} - - - - - ) : null} - - - {confirmation?.target.kind === 'install' && - snapshot.phase === 'ready' && ( - warning.code === 'launch_options_not_empty' - )} - busy={confirmationRunning} - installAcknowledged={installAcknowledged} - onAcknowledgedChange={setInstallAcknowledged} - problem={confirmationFailed} - onClose={() => intents.dismissConfirmation()} - onConfirm={() => void intents.confirm()} - /> - )} - - - - {confirmation?.target.kind === 'reset-data' && ( - intents.dismissConfirmation()} - onConfirm={() => void intents.confirm()} - /> - )} - - {confirmation?.target.kind === 'reset-bepinex' && ( - intents.dismissConfirmation()} - onConfirm={() => void intents.confirm()} - /> - )} - - {confirmation?.target.kind === 'uninstall' && ( - intents.dismissConfirmation()} - onConfirm={() => void intents.confirm()} - /> - )} - - - - {legacyConfirmation && ( - legacy.workflow.dismissDelete()} - onConfirm={() => void legacy.workflow.confirmDelete()} - /> - )} - -
    - ); -} diff --git a/bazaarplusplus-installer/src/pages/RunDetail.test.tsx b/bazaarplusplus-installer/src/pages/RunDetail.test.tsx deleted file mode 100644 index 4a4e853..0000000 --- a/bazaarplusplus-installer/src/pages/RunDetail.test.tsx +++ /dev/null @@ -1,179 +0,0 @@ -// @vitest-environment jsdom - -import { act, StrictMode } from 'react'; -import { createRoot, type Root } from 'react-dom/client'; -import { Link, MemoryRouter, Route, Routes } from 'react-router-dom'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { ModalCoordinatorProvider } from '../components/ui/ModalCoordinator'; -import { commandClient } from '../api/commandClient'; -import { LocaleProvider } from '../i18n/LocaleProvider'; -import { LOCALE_STORAGE_KEY } from '../i18n/messages'; -import type { HistoryRunDetail } from '../types/backend'; -import RunDetail from './RunDetail'; - -vi.mock('../api/commandClient', () => ({ - commandClient: { - getHistoryRunDetail: vi.fn(), - revealRunScreenshot: vi.fn(), - revealBattleVideo: vi.fn(), - deleteBattleVideo: vi.fn() - } -})); -const commands = commandClient; - -function detail(runId = 'run-1'): HistoryRunDetail { - return { - run: { - run_id: runId, - hero: runId === 'run-1' ? 'Vanessa' : 'Mak', - game_mode: 'Ranked', - started_at_utc: '2026-09-12T10:00:00Z', - ended_at_utc: null, - status: 'completed', - result: 'win', - victories: 10, - losses: 0, - final_day: 10, - final_player_rank: null, - final_player_rating: null, - final_player_rating_delta: null, - screenshot_id: 's1', - player_name: null - }, - battles: [ - { - battle_id: 'battle-1', - day: 1, - hour: 2, - result: 'win', - opponent_hero: 'Pygmalien', - opponent_name: null, - opponent_rank: null, - opponent_rating: null, - video: { - video_id: 'video-1', - status: 'completed', - file_size_bytes: 100, - duration_ms: 2000 - } - } - ] - }; -} - -let container: HTMLDivElement; -let root: Root; - -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); - localStorage.setItem(LOCALE_STORAGE_KEY, 'en'); - vi.mocked(commands.getHistoryRunDetail) - .mockReset() - .mockImplementation(async (runId) => detail(runId)); - vi.mocked(commands.deleteBattleVideo).mockReset(); - Object.defineProperty(HTMLDialogElement.prototype, 'showModal', { - configurable: true, - value: function (this: HTMLDialogElement) { - this.open = true; - } - }); - Object.defineProperty(HTMLDialogElement.prototype, 'close', { - configurable: true, - value: function (this: HTMLDialogElement) { - this.open = false; - } - }); - container = document.createElement('div'); - document.body.append(container); - root = createRoot(container); -}); - -afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - Reflect.deleteProperty(HTMLDialogElement.prototype, 'showModal'); - Reflect.deleteProperty(HTMLDialogElement.prototype, 'close'); - vi.unstubAllGlobals(); -}); - -async function render() { - await act(async () => - root.render( - - - - - Another run - - } /> - - - - - - ) - ); -} - -async function click(selector: string) { - const button = container.querySelector(selector); - expect(button).not.toBeNull(); - await act(async () => button!.click()); -} - -describe('Run Detail workflow binding', () => { - it('renders new detail after navigation even without a keyed route remount', async () => { - await render(); - expect(container.querySelector('[data-page-heading]')?.textContent).toBe( - 'Vanessa' - ); - await click('a[href="/history/run-2"]'); - expect(container.querySelector('[data-page-heading]')?.textContent).toBe( - 'Mak' - ); - expect(commands.getHistoryRunDetail).toHaveBeenLastCalledWith('run-2'); - }); - - it('keeps failed video deletion retryable and blocks dismissal while retry runs', async () => { - let finish!: (value: HistoryRunDetail) => void; - const deletion = new Promise((resolve) => { - finish = resolve; - }); - vi.mocked(commands.deleteBattleVideo) - .mockRejectedValueOnce(new Error('disk busy')) - .mockReturnValueOnce(deletion); - await render(); - await click('button[title="Delete Video"]'); - expect(container.querySelector('dialog')?.textContent).toContain( - 'Pygmalien' - ); - await click('dialog button.bpp-confirm-submit'); - expect(container.querySelector('dialog')?.textContent).toContain( - 'disk busy' - ); - expect( - container.querySelector('dialog button.bpp-confirm-submit')?.textContent - ).toContain('Retry'); - await click('dialog button.bpp-confirm-submit'); - expect( - container.querySelector( - 'dialog button[aria-label="Close"]' - )?.disabled - ).toBe(true); - await act(async () => - container - .querySelector('dialog')! - .dispatchEvent(new Event('cancel', { cancelable: true })) - ); - expect(container.querySelector('dialog')?.open).toBe(true); - const updated = detail(); - updated.battles[0].video = null; - await act(async () => finish(updated)); - expect(container.querySelector('dialog')).toBeNull(); - expect(container.querySelector('button[title="Delete Video"]')).toBeNull(); - expect(commands.deleteBattleVideo).toHaveBeenLastCalledWith( - 'battle-1', - 'video-1' - ); - }); -}); diff --git a/bazaarplusplus-installer/src/pages/RunDetail.tsx b/bazaarplusplus-installer/src/pages/RunDetail.tsx deleted file mode 100644 index 41429cf..0000000 --- a/bazaarplusplus-installer/src/pages/RunDetail.tsx +++ /dev/null @@ -1,502 +0,0 @@ -import { - ArrowLeft, - FileQuestion, - FolderOpen, - Image as ImageIcon, - Loader2, - RefreshCw, - Trash2, - Video -} from 'lucide-react'; -import { Link, useLocation, useNavigate } from 'react-router-dom'; -import { Button, buttonClassName } from '../components/ui/Button'; -import { ConfirmDialog } from '../components/ui/ConfirmDialog'; -import { EmptyState } from '../components/ui/EmptyState'; -import { LoadingPanel } from '../components/ui/LoadingPanel'; -import { PageShell } from '../components/ui/PageShell'; -import { ProblemBanner } from '../components/ui/ProblemBanner'; -import type { HistoryBattleRow } from '../types/backend'; -import { useRunDetailPage } from '../features/history/useRunDetailPage'; -import { - formatBattleResult, - formatBytes, - formatDateTime, - formatDuration, - formatGameMode, - formatHero, - formatRank, - formatRatingDelta, - formatRunResultLabel, - formatRunStatusKey, - toneColorClass -} from '../features/history/format'; -import { - presentRunDetailProblem, - runDetailProblemFromError, - type RunDetailProblem -} from '../features/history/runDetailProblems'; -import { useConfirmedOperation } from '../features/shared/confirmedOperation'; -import { useI18n } from '../i18n/LocaleProvider'; -import { ModalSource } from '../components/ui/ModalCoordinator'; -import { - historyListPath, - parseHistoryPage -} from '../features/history/pagination'; -import { - VideoDeleteSummary, - type VideoDeleteTarget -} from '../features/history/VideoDeleteSummary'; - -export default function RunDetail() { - const navigate = useNavigate(); - const location = useLocation(); - const historyPage = parseHistoryPage( - String(location.state?.historyPage ?? 1) - ); - const page = useRunDetailPage(); - const detail = page.detail; - const { locale, t } = useI18n(); - const runResult = detail ? formatRunResultLabel(detail.run) : null; - const deleteOperation = useConfirmedOperation< - VideoDeleteTarget, - RunDetailProblem - >(); - const pendingDelete = deleteOperation.state?.target ?? null; - const screenshotAvailability = page.screenshot; - const screenshotFailure = page.screenshot.problem; - - const confirmDelete = () => - deleteOperation.controller.run( - (target) => page.deleteVideo(target.battleId, target.videoId), - runDetailProblemFromError - ); - - // Only the loading phase may claim to be loading; every terminal phase - // without a run needs a heading that matches what the body actually says. - const pageTitle = - (detail ? formatHero(detail.run.hero, t) : undefined) ?? - (page.state.phase === 'initial-loading' - ? t('runDetailLoading') - : page.state.phase === 'not-found' - ? t('runDetailNotFound') - : t('runDetailUnavailable')); - - return ( - navigate(historyListPath(historyPage))} - title={t('runDetailBack')} - aria-label={t('runDetailBack')} - icon={} - /> - } - meta={ - detail - ? `${formatGameMode(detail.run.game_mode, t)} · ${t(formatRunStatusKey(detail.run.status))}` - : undefined - } - action={ - - } - > - {page.state.phase === 'initial-loading' ? ( - - ) : page.state.phase === 'not-found' ? ( -
    - } - heading={t('runDetailNotFound')} - primaryAction={ - - } - /> -
    - ) : page.state.phase === 'blocking-failure' ? ( - void page.refresh()} - /> - ) : detail ? ( - <> - {page.state.refresh.phase === 'failed' && ( - void page.refresh()} - /> - )} - - {page.state.refresh.phase === 'refreshing' && ( -

    -

    - )} - -
    -
    - - {runResult ? t(runResult.key) : '-'} - -
    - - {t('runDetailPlayer')} {detail.run.player_name ?? '-'} - - - {formatDateTime(detail.run.started_at_utc, locale)} –{' '} - {formatDateTime(detail.run.ended_at_utc, locale)} - -
    - -
    - - {screenshotFailure && ( -
    - void page.revealScreenshot()} - /> -
    - )} - -
    - - - - -
    -
    - -
    -
    - - - - - - - - - - - - - - - - - - - - - - - {detail.battles.length === 0 ? ( - - - - ) : ( - detail.battles.map((battle) => ( - { - if (!target.video) return; - deleteOperation.controller.request({ - kind: 'delete-video', - battleId: target.battle_id, - videoId: target.video.video_id, - runStartedAt: detail.run.started_at_utc, - day: target.day, - opponent: - [ - target.opponent_name, - target.opponent_hero && - formatHero(target.opponent_hero, t) - ] - .filter(Boolean) - .join(' · ') || '-', - durationMs: target.video.duration_ms - }); - }} - /> - )) - )} - -
    {t('battleColDay')}{t('battleColResult')}{t('battleColOpponentHero')}{t('battleColOpponentPlayer')}{t('battleColRank')}{t('battleColRating')} - {t('battleColVideo')} -
    - } - heading={t('noLocalBattles')} - description={t('noLocalBattlesDescription')} - primaryAction={ - - } - /> -
    -
    -
    - - ) : null} - - - {pendingDelete && ( - - -

    {t('deleteVideoConfirmBody')}

    - {deleteOperation.state?.phase === 'failed' && ( - - )} -
    - )} -
    -
    - ); -} - -function StatBlock({ label, value }: { label: string; value: string }) { - return ( -
    - {label} - - {value} - -
    - ); -} - -function BattleRow({ - battle, - page, - onRequestDelete -}: { - battle: HistoryBattleRow; - page: ReturnType; - onRequestDelete: (battle: HistoryBattleRow) => void; -}) { - const { locale, t } = useI18n(); - const battleResult = formatBattleResult(battle.result); - const { - reveal: videoAvailability, - delete: deleteAvailability, - failure - } = page.battles[battle.battle_id]; - const actionLabel = (action: string) => - t('battleVideoActionLabel', { - action, - day: battle.day ?? '-', - opponent: - battle.opponent_name ?? - (battle.opponent_hero ? formatHero(battle.opponent_hero, t) : '-') - }); - - const retryFailure = () => { - if (!battle.video || !failure) return; - if (failure.action === 'reveal') { - void page.revealVideo(battle.battle_id, battle.video.video_id); - return; - } - onRequestDelete(battle); - }; - - return ( - <> - - - {battle.day === null ? '-' : String(battle.day)} - - - {t(battleResult.key)} - - - {battle.opponent_hero ? formatHero(battle.opponent_hero, t) : '-'} - - - {battle.opponent_name ?? '-'} - - - {battle.opponent_rank ? formatRank(battle.opponent_rank, t) : '-'} - - - {battle.opponent_rating === null ? '-' : battle.opponent_rating} - - - - {battle.video ? ( -
    - - {formatDuration(battle.video.duration_ms, locale)} ·{' '} - {formatBytes(battle.video.file_size_bytes, locale)} - -
    - ) : ( - - - - )} - - - - {failure && ( - - - - - - )} - - ); -} - -function RunDetailProblemBanner({ - problem, - onRetry -}: { - problem: RunDetailProblem; - onRetry?: () => void; -}) { - const { t } = useI18n(); - return ( - - {t('historyOpenInstall')} - - ) : undefined - } - /> - ); -} diff --git a/bazaarplusplus-installer/src/pages/Stream.tsx b/bazaarplusplus-installer/src/pages/Stream.tsx deleted file mode 100644 index 72f6202..0000000 --- a/bazaarplusplus-installer/src/pages/Stream.tsx +++ /dev/null @@ -1,316 +0,0 @@ -import { - Copy, - ExternalLink, - Minus, - Play, - Plus, - RotateCw, - Settings2 -} from 'lucide-react'; -import { useEffect, useMemo } from 'react'; -import type { StreamOverlayDisplayMode } from '../types/backend'; -import { Button } from '../components/ui/Button'; -import { PageShell } from '../components/ui/PageShell'; -import { StatusBadge } from '../components/ui/StatusBadge'; -import { SegmentedControl } from '../components/ui/SegmentedControl'; -import { useToast, type ToastTone } from '../components/ui/Toast'; -import { useStreamPage } from '../features/stream/useStreamPage'; -import { presentStreamSnapshot } from '../features/stream/streamPresentation'; -import { - presentStreamProblem, - type StreamProblem -} from '../features/stream/streamProblems'; -import { useI18n } from '../i18n/LocaleProvider'; -import type { MessageKey } from '../i18n/messages'; - -const displayModes: Array<{ - value: StreamOverlayDisplayMode; - labelKey: MessageKey; -}> = [ - { value: 'current', labelKey: 'streamModeCurrent' }, - { value: 'hero', labelKey: 'streamModeHero' }, - { value: 'herohalf', labelKey: 'streamModeHeroHalf' } -]; - -export default function Stream() { - const { t } = useI18n(); - const { snapshot, intents } = useStreamPage(); - const presentation = useMemo( - () => presentStreamSnapshot(snapshot, t), - [snapshot, t] - ); - const status = snapshot.service.status; - const cropSettings = snapshot.crop.settings; - const statusTone = presentation.status.tone; - - useStreamProblemToast( - snapshot.service.problem, - 'stream:service', - 'error', - t('streamRestart'), - intents.restart - ); - useStreamProblemToast( - snapshot.polling.problem, - 'stream:polling', - 'warning', - t('streamRetryStatus'), - intents.retryStatus - ); - useStreamProblemToast( - snapshot.oneOff.problems.open_overlay, - 'stream:open-overlay' - ); - useStreamProblemToast(snapshot.oneOff.problems.copy, 'stream:copy'); - useStreamProblemToast(snapshot.window.problem, 'stream:window'); - useStreamProblemToast( - snapshot.crop.problem, - 'stream:crop', - 'error', - snapshot.crop.problem?.params.operation === 'load' - ? t('streamRetryCrop') - : undefined, - snapshot.crop.problem?.params.operation === 'load' - ? intents.reloadCropSettings - : undefined - ); - useStreamProblemToast( - snapshot.oneOff.problems.open_settings, - 'stream:open-settings' - ); - useStreamNoticeToast(presentation.notice); - - const statusBadge = ( - { - loading: 'busy', - running: 'ok', - idle: 'neutral', - degraded: 'bad', - stale: 'warn' - } as const - )[statusTone]; - - return ( - - {presentation.status.label} - - } - action={ - <> - - - - } - > -

    - {presentation.status.detail} - {status?.running && snapshot.polling.freshness === 'fresh' - ? ` · ${presentation.dbLabel}` - : ''} -

    - -
    -

    {t('streamObsUrlLabel')}

    -
    -
    - {snapshot.oneOff.obsUrl ?? t('streamObsPlaceholder')} -
    - -
    -
    - -
    -
    -
    - {t('streamWindowSection')} - - {presentation.windowLabel} - -
    -
    - - -
    -
    -
    - - - - -
    -
    - -
    -

    {t('streamOverlayConfig')}

    -
    - {t('streamDisplayModeLabel')} - ({ - value: mode.value, - label: t(mode.labelKey) - }))} - onChange={(mode) => void intents.changeDisplayMode(mode)} - /> -
    -
    - -
    - intents.setCropCode(event.target.value)} - className="bpp-input mono min-w-[180px] flex-1" - /> - - - -
    -
    -
    -
    - ); -} - -function useStreamProblemToast( - problem: StreamProblem | null, - id: string, - tone: Extract = 'error', - actionLabel?: string, - onAction?: () => void -) { - const { t } = useI18n(); - const { dismissToast, showToast } = useToast(); - - useEffect(() => { - if (!problem) { - dismissToast(id); - return; - } - showToast({ - id, - tone, - message: presentStreamProblem(problem, t), - action: - actionLabel && onAction - ? { label: actionLabel, onClick: onAction } - : undefined - }); - }, [actionLabel, dismissToast, id, onAction, problem, showToast, t, tone]); -} - -function useStreamNoticeToast(notice: string | null) { - const { dismissToast, showToast } = useToast(); - - useEffect(() => { - if (!notice) { - dismissToast('stream:notice'); - return; - } - showToast({ id: 'stream:notice', tone: 'success', message: notice }); - }, [dismissToast, notice, showToast]); -} - -function InfoMetric({ - label, - value, - mono = false -}: { - label: string; - value: string; - mono?: boolean; -}) { - return ( - <> - {label} - - {value} - - - - ); -} diff --git a/bazaarplusplus-installer/src/shell.snapshot.test.tsx b/bazaarplusplus-installer/src/shell.snapshot.test.tsx deleted file mode 100644 index 63d18d3..0000000 --- a/bazaarplusplus-installer/src/shell.snapshot.test.tsx +++ /dev/null @@ -1,366 +0,0 @@ -// @vitest-environment jsdom - -// Shell DOM snapshot anchor: the whole app (GlobalShell, nav rail, header and -// the routed page) rendered per route x state from Browser Preview commands -// seeded with src/test-fixtures/shell/. Each case writes -// src/__shell_snapshots__/..html; review those diffs in the PR. -// Regenerate: BPP_UPDATE_GOLDENS=1 npx vitest run src/shell.snapshot.test.tsx - -import { act, StrictMode } from 'react'; -import { createRoot, type Root } from 'react-dom/client'; -import { MemoryRouter } from 'react-router-dom'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { AppRoutes } from './App'; -import { commandClient } from './api/commandClient'; -import { SemanticProblemError } from './api/problems'; -import { LocaleProvider } from './i18n/LocaleProvider'; -import { LOCALE_STORAGE_KEY } from './i18n/messages'; -import * as fixtures from './test-fixtures/shell/fixtures'; -import type { CommandAdapter } from './api/commandAdapter'; -import type { SemanticProblem } from './types/backend'; - -// Dates render through Intl in the host time zone; CI runs in UTC. The zone -// must be fixed before any formatter module is imported. -const host = vi.hoisted(() => { - process.env.TZ = 'UTC'; - return { runtime: false, windows: false }; -}); - -vi.mock('./api/runtime', () => ({ hasTauriRuntime: () => host.runtime })); -vi.mock('./features/shared/platform', () => ({ - isWindowsPlatform: () => host.windows -})); -vi.mock('./api/commandClient', async () => { - const { createPreviewCommands } = await import('./api/previewCommands'); - const { nativeCommands } = await import('./api/nativeCommands'); - return { commandClient: createPreviewCommands(nativeCommands) }; -}); -vi.mock('@tauri-apps/plugin-updater', () => ({ check: vi.fn() })); -// Every case is a fresh app launch, so the once-per-process startup check is -// always claimable. -vi.mock('./features/about/updater', async (importOriginal) => ({ - ...(await importOriginal()), - claimStartupCheck: () => true -})); - -type Seed = (commands: CommandAdapter) => void; - -type Case = { - route: string; - page: string; - state: string; - seed?: Seed; - windows?: boolean; - /** Runs inside the Tauri runtime; only the updater case needs it. */ - runtime?: boolean; - update?: boolean; -}; - -const reject = (problem: SemanticProblem) => async () => { - throw new SemanticProblemError(problem); -}; - -const cases: Case[] = [ - { - route: '/', - page: 'install', - state: 'game-missing', - seed: (c) => { - vi.spyOn(c, 'getInstallState').mockResolvedValue(fixtures.gameMissing); - } - }, - { - route: '/', - page: 'install', - state: 'installable', - seed: (c) => { - vi.spyOn(c, 'getInstallState').mockResolvedValue(fixtures.installable); - } - }, - { - route: '/', - page: 'install', - state: 'installed', - seed: (c) => { - vi.spyOn(c, 'getInstallState').mockResolvedValue(fixtures.installed); - } - }, - { - route: '/', - page: 'install', - state: 'legacy-roots', - seed: (c) => { - vi.spyOn(c, 'getInstallState').mockResolvedValue(fixtures.installed); - vi.spyOn(c, 'getLegacyDataState').mockResolvedValue( - fixtures.legacyRootsNeedingReinstall - ); - } - }, - { - route: '/', - page: 'install', - state: 'v5-import', - seed: (c) => { - vi.spyOn(c, 'getInstallState').mockResolvedValue(fixtures.installed); - vi.spyOn(c, 'getLegacyDataState').mockResolvedValue( - fixtures.v5ImportEligible - ); - } - }, - { - route: '/', - page: 'install', - state: 'detection-failed', - seed: (c) => { - vi.spyOn(c, 'getInstallState').mockImplementation( - reject(fixtures.installDetectionFailed) - ); - } - }, - { - route: '/history', - page: 'history', - state: 'empty', - seed: (c) => { - vi.spyOn(c, 'listHistoryRuns').mockResolvedValue(fixtures.historyEmpty); - } - }, - { - route: '/history', - page: 'history', - state: 'multi-page', - seed: (c) => { - vi.spyOn(c, 'listHistoryRuns').mockResolvedValue( - fixtures.historyFirstPage - ); - } - }, - { - route: '/history', - page: 'history', - state: 'read-failed', - seed: (c) => { - vi.spyOn(c, 'listHistoryRuns').mockImplementation( - reject(fixtures.historyReadFailed) - ); - } - }, - { - route: '/history', - page: 'history', - state: 'unavailable-v5-import', - seed: (c) => { - vi.spyOn(c, 'listHistoryRuns').mockImplementation( - reject(fixtures.historyUnavailable) - ); - vi.spyOn(c, 'getLegacyDataState').mockResolvedValue( - fixtures.v5ImportEligible - ); - } - }, - { - route: '/history/run-1', - page: 'run-detail', - state: 'loaded', - seed: (c) => { - vi.spyOn(c, 'getHistoryRunDetail').mockResolvedValue(fixtures.runDetail); - } - }, - { - route: '/history/run-1', - page: 'run-detail', - state: 'read-failed', - seed: (c) => { - vi.spyOn(c, 'getHistoryRunDetail').mockImplementation( - reject(fixtures.runDetailReadFailed) - ); - } - }, - { - route: '/history/run-404', - page: 'run-detail', - state: 'not-found', - seed: (c) => { - vi.spyOn(c, 'getHistoryRunDetail').mockResolvedValue(null); - } - }, - { - route: '/stream', - page: 'stream', - state: 'windows-idle', - windows: true, - seed: (c) => { - vi.spyOn(c, 'getStreamStatus').mockResolvedValue(fixtures.streamIdle); - vi.spyOn(c, 'ensureStreamSession').mockResolvedValue(fixtures.streamIdle); - } - }, - { - route: '/stream', - page: 'stream', - state: 'windows-running', - windows: true, - seed: (c) => { - vi.spyOn(c, 'getStreamStatus').mockResolvedValue(fixtures.streamRunning); - vi.spyOn(c, 'ensureStreamSession').mockResolvedValue( - fixtures.streamRunning - ); - } - }, - { - route: '/stream', - page: 'stream', - state: 'windows-error', - windows: true, - seed: (c) => { - vi.spyOn(c, 'getStreamStatus').mockResolvedValue(fixtures.streamError); - vi.spyOn(c, 'ensureStreamSession').mockResolvedValue( - fixtures.streamError - ); - } - }, - { - route: '/stream', - page: 'stream', - state: 'macos-idle', - seed: (c) => { - vi.spyOn(c, 'getStreamStatus').mockResolvedValue(fixtures.streamIdle); - vi.spyOn(c, 'ensureStreamSession').mockResolvedValue(fixtures.streamIdle); - } - }, - { route: '/about', page: 'about', state: 'current' }, - { - route: '/about', - page: 'about', - state: 'loading', - seed: (c) => { - vi.spyOn(c, 'getAppBootstrap').mockReturnValue(new Promise(() => {})); - } - }, - { - route: '/about', - page: 'about', - state: 'bootstrap-failed', - seed: (c) => { - vi.spyOn(c, 'getAppBootstrap').mockRejectedValue( - new Error('fixture: IPC unavailable') - ); - } - }, - { - route: '/about', - page: 'about', - state: 'update-available', - runtime: true, - update: true - } -]; - -let container: HTMLDivElement; -let root: Root; - -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); - vi.stubGlobal( - 'ResizeObserver', - class { - observe() {} - disconnect() {} - } - ); - localStorage.setItem(LOCALE_STORAGE_KEY, 'zh'); - Object.defineProperty(HTMLDialogElement.prototype, 'showModal', { - configurable: true, - value: function (this: HTMLDialogElement) { - this.open = true; - } - }); - Object.defineProperty(HTMLDialogElement.prototype, 'close', { - configurable: true, - value: function (this: HTMLDialogElement) { - this.open = false; - } - }); - container = document.createElement('div'); - document.body.append(container); - root = createRoot(container); -}); - -afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - Reflect.deleteProperty(HTMLDialogElement.prototype, 'showModal'); - Reflect.deleteProperty(HTMLDialogElement.prototype, 'close'); - host.runtime = false; - host.windows = false; - localStorage.clear(); - vi.unstubAllGlobals(); - vi.restoreAllMocks(); -}); - -/** Each pass waits one animation frame and then a macrotask, so loads, their - * follow-up reads and frame-deferred UI (a toast's `is-present`) have all - * settled however fast the host runs. */ -async function settle() { - for (let pass = 0; pass < 5; pass += 1) { - await act(async () => { - await new Promise((resolve) => - requestAnimationFrame(() => setTimeout(resolve, 0)) - ); - }); - } -} - -/** Drops only React's generated ids, the compiled-in package version (the - * header stamp and the packaged About fallback) and lucide's glyph paths, - * keeping each icon's tag and name, so a version or dependency bump does not - * rewrite every snapshot. Copy and ARIA attributes stay. One tag per line - * keeps the snapshot diff reviewable. */ -function normalize(html: string): string { - return html - .replace(/«r[0-9a-z]+»|_r_[0-9a-z]+_|:r[0-9a-z]+:/g, '«id»') - .replace( - /(]*\bclass="lucide [^"]*"[^>]*>)[\s\S]*?<\/svg>/g, - '$1' - ) - .replaceAll(__FRONTEND_VERSION__, '«version»') - .replaceAll('><', '>\n<'); -} - -describe('shell DOM snapshots', () => { - it.each(cases)( - '$page $state', - async ({ route, page, state, seed, windows, runtime, update }) => { - host.windows = windows ?? false; - host.runtime = runtime ?? false; - vi.spyOn(commandClient, 'getAppBootstrap').mockResolvedValue( - fixtures.bootstrap - ); - seed?.(commandClient); - if (update) { - const { check } = await import('@tauri-apps/plugin-updater'); - vi.mocked(check).mockResolvedValue({ - ...fixtures.availableUpdate, - downloadAndInstall: vi.fn(), - close: vi.fn() - } as unknown as Awaited>); - } - - await act(async () => - root.render( - - - - - - - - ) - ); - await settle(); - - await expect(normalize(container.innerHTML)).toMatchFileSnapshot( - `./__shell_snapshots__/${page}.${state}.html` - ); - } - ); -}); diff --git a/bazaarplusplus-installer/src/styles/index.css b/bazaarplusplus-installer/src/styles/index.css deleted file mode 100644 index 0995220..0000000 --- a/bazaarplusplus-installer/src/styles/index.css +++ /dev/null @@ -1,1800 +0,0 @@ -@import 'tailwindcss'; -@import './tokens.css'; - -/* Tailwind utilities read the product tokens; there is no second palette. */ -@theme { - --color-canvas: var(--bg-canvas); - --color-sidebar: var(--bg-sidebar); - --color-panel: var(--bg-panel); - --color-hover: var(--bg-hover); - --color-selected: var(--bg-selected); - --color-line: var(--line); - --color-line-strong: var(--line-strong); - --color-fg-1: var(--text-1); - --color-fg-2: var(--text-2); - --color-fg-3: var(--text-3); - --color-accent: var(--accent); - --color-success: var(--success); - --color-warning: var(--warning); - --color-danger: var(--danger); - --font-sans: var(--font-ui); - --font-mono: var(--font-mono); -} - -/* Windows swaps in Noto Sans SC once the optional background download lands - (features/shared/notoSansSc.ts). */ -html[data-bpp-platform='windows'] { - --font-ui: - 'Segoe UI Variable Text', 'Segoe UI', 'Microsoft YaHei UI', - 'Microsoft YaHei', 'Noto Sans SC', sans-serif; -} -html[data-bpp-platform='windows'][data-bpp-noto-sans-sc='ready'] { - --font-ui: - 'Noto Sans SC', 'Segoe UI Variable Text', 'Segoe UI', 'Microsoft YaHei UI', - sans-serif; -} - -/* The root keeps the 16px default so Tailwind's rem scale is standard; the - app's 13px body size lives on body. */ -html, -body { - height: 100%; - margin: 0; - overflow: hidden; - background: var(--bg-canvas); - color: var(--text-1); - font-family: var(--font-ui); -} -body { - font-size: 13px; - line-height: 1.55; - font-synthesis: none; - -webkit-font-smoothing: antialiased; -} -#root { - height: 100%; - display: flex; - flex-direction: column; -} -::selection { - background: rgba(238, 142, 31, 0.32); - color: var(--text-1); -} -.mono { - font-family: var(--font-mono); - font-size: 0.94em; -} -.tnum { - font-variant-numeric: tabular-nums; -} -.selectable, -.selectable *, -.user-content * { - -webkit-user-select: text; - user-select: text; -} -.bpp-spin { - animation: bpp-spin 0.8s linear infinite; -} -@keyframes bpp-spin { - to { - transform: rotate(360deg); - } -} - -/* ── Shell ─────────────────────────────────────────────────────────── */ -.bpp-app { - display: flex; - height: 100%; - min-height: 0; - flex-direction: column; - background: var(--bg-canvas); -} -.bpp-header { - position: relative; - z-index: 40; - display: flex; - flex: none; - height: 40px; - align-items: center; - justify-content: space-between; - gap: 16px; - padding: 0 8px 0 14px; - border-bottom: 1px solid var(--line); - background: var(--bg-sidebar); -} -/* macOS draws its traffic lights over the title bar (overlay style). */ -html[data-bpp-titlebar='overlay'] .bpp-header { - padding-left: 78px; -} -html[data-bpp-titlebar='overlay'][data-bpp-fullscreen] .bpp-header { - padding-left: 14px; -} -html[data-bpp-platform='windows'] .bpp-header { - padding-right: 0; -} -.bpp-brand { - display: flex; - min-width: 0; - align-items: center; - gap: 8px; -} -.bpp-brand-logo { - width: 18px; - height: 18px; - border-radius: 4px; - object-fit: contain; -} -.bpp-brand-title { - margin: 0; - font-size: 13px; - font-weight: 600; - white-space: nowrap; -} -.bpp-brand-version { - color: var(--text-3); - font-size: 12px; - font-variant-numeric: tabular-nums; -} -.bpp-header-actions { - display: flex; - height: 100%; - align-items: center; - gap: 4px; -} -.bpp-header-group { - display: flex; - align-items: center; - gap: 2px; -} -.bpp-header-actions-divider { - width: 1px; - height: 16px; - margin: 0 6px; - background: var(--line-strong); -} -.bpp-header-icon-control { - display: inline-flex; - width: 28px; - height: 28px; - align-items: center; - justify-content: center; - border: 0; - border-radius: var(--r-control); - color: var(--text-2); - background: transparent; - transition: - background var(--t-fast) var(--ease), - color var(--t-fast) var(--ease); -} -.bpp-header-icon-control:hover, -.bpp-header-icon-control[aria-expanded='true'] { - color: var(--text-1); - background: var(--bg-hover); -} -.bpp-header-icon-control svg { - width: 16px; - height: 16px; -} - -/* Header popovers and menus: the only floating layers in the shell. */ -.bpp-popover { - position: absolute; - z-index: 50; - top: calc(100% + 6px); - border: 1px solid var(--line-strong); - border-radius: var(--r-panel); - background: var(--bg-selected); - box-shadow: var(--shadow-float); - color: var(--text-1); -} -.bpp-menu { - display: flex; - min-width: 232px; - flex-direction: column; - padding: 4px; - animation: bpp-float-in var(--t-base) var(--ease) both; -} -.bpp-menu.is-right { - right: 0; -} -/* Opens beside the rail, growing upward from its trigger. */ -.bpp-menu.is-beside { - top: auto; - bottom: 0; - left: calc(100% + 8px); -} -.bpp-menu.is-centered { - left: 50%; - translate: -50% 0; -} -.bpp-menu-item { - display: flex; - align-items: center; - gap: 10px; - padding: 7px 8px; - border: 0; - border-radius: var(--r-control); - color: var(--text-1); - background: transparent; - text-align: left; - text-decoration: none; -} -.bpp-menu-item:hover, -.bpp-menu-item:focus-visible { - background: var(--bg-hover); -} -.bpp-menu-item svg { - width: 16px; - height: 16px; - flex: none; - color: var(--text-2); -} -.bpp-menu-title { - display: block; - font-size: 13px; - font-weight: 500; -} -.bpp-menu-subtitle { - display: block; - color: var(--text-2); - font-size: 12px; -} -.bpp-qr-popover { - left: 50%; - display: flex; - width: 232px; - flex-direction: column; - align-items: center; - gap: 12px; - padding: 16px; - opacity: 0; - pointer-events: none; - translate: -50% -4px; - transition: - opacity var(--t-base) var(--ease), - translate var(--t-base) var(--ease); -} -.group:hover > .bpp-qr-popover, -.group:focus-within > .bpp-qr-popover { - opacity: 1; - pointer-events: auto; - translate: -50% 0; -} -.bpp-qr-image { - width: 168px; - height: 168px; - padding: 8px; - border-radius: var(--r-panel); - background: #fff; -} -.bpp-qr-image.is-round { - border-radius: 50%; -} -.bpp-qr-title { - margin: 0; - font-size: 13px; - font-weight: 600; - text-align: center; -} -.bpp-qr-subtitle { - margin: 2px 0 0; - color: var(--text-2); - font-size: 12px; - text-align: center; -} -@keyframes bpp-float-in { - from { - opacity: 0; - transform: scale(0.98); - } -} - -.bpp-window-controls { - display: flex; - height: 100%; - margin-left: 4px; -} -.bpp-window-control-button { - display: inline-flex; - width: 46px; - height: 100%; - align-items: center; - justify-content: center; - border: 0; - color: var(--text-2); - background: transparent; - transition: - background var(--t-fast) var(--ease), - color var(--t-fast) var(--ease); -} -.bpp-window-control-button:hover { - color: var(--text-1); - background: var(--bg-hover); -} -.bpp-window-close-button:hover { - color: #fff; - background: #c42b1c; -} - -.bpp-shell-body { - display: grid; - min-height: 0; - flex: 1; - grid-template-columns: 72px minmax(0, 1fr); -} -/* Icon rail: pages at the top, support and language at the foot. */ -.bpp-nav { - display: flex; - min-height: 0; - flex-direction: column; - align-items: center; - gap: 4px; - padding: 10px 0; - border-right: 1px solid var(--line); - background: var(--bg-sidebar); -} -.bpp-rail-item { - display: flex; - width: 58px; - height: 52px; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 3px; - border: 0; - border-radius: var(--r-panel); - color: var(--text-2); - background: transparent; - font-size: 11px; - font-weight: 500; - line-height: 1.2; - text-decoration: none; - transition: - background var(--t-fast) var(--ease), - color var(--t-fast) var(--ease); -} -.bpp-rail-item svg { - width: 20px; - height: 20px; - flex: none; -} -.bpp-rail-item:hover, -.bpp-rail-item[aria-expanded='true'] { - color: var(--text-1); - background: var(--bg-hover); -} -.bpp-rail-item.is-active { - color: var(--text-1); - background: var(--bg-selected); -} -.bpp-rail-item.is-active svg { - color: var(--accent); -} -.bpp-rail-item:focus-visible { - outline-offset: -2px; -} -.bpp-nav-footer { - display: flex; - flex-direction: column; - align-items: center; - gap: 4px; - margin-top: auto; -} -.bpp-main { - position: relative; - min-width: 0; - min-height: 0; - overflow: auto; - scrollbar-gutter: stable; -} -.bpp-main:focus { - outline: none; -} -.bpp-main-inner { - width: 100%; - max-width: 1080px; - min-height: 100%; - margin: 0 auto; - padding: 22px 28px 40px; -} -/* Route changes are instant; new content settles in without blocking input. */ -.bpp-route-page { - min-height: 100%; - animation: bpp-route-in 120ms var(--ease) both; -} -@keyframes bpp-route-in { - from { - opacity: 0.55; - } -} - -/* ── Page structure ────────────────────────────────────────────────── */ -.bpp-page { - display: flex; - min-height: 100%; - flex-direction: column; - gap: 16px; -} -.bpp-page-header { - display: flex; - min-height: 32px; - align-items: center; - gap: 12px; -} -.bpp-page-title { - margin: 0; - overflow: hidden; - font-size: 20px; - font-weight: 650; - letter-spacing: -0.01em; - text-overflow: ellipsis; - white-space: nowrap; -} -.bpp-page-title:focus { - outline: none; -} -.bpp-page-meta { - color: var(--text-3); - font-size: 13px; -} -.bpp-page-actions { - display: flex; - flex: none; - align-items: center; - gap: 8px; - margin-left: auto; -} -.bpp-section-title { - margin: 4px 0 -8px; - color: var(--text-3); - font-size: 12px; - font-weight: 600; -} -.bpp-panel { - border: 1px solid var(--line); - border-radius: var(--r-panel); - background: var(--bg-panel); -} -.bpp-panel-pad { - display: flex; - flex-direction: column; - gap: 14px; - padding: 16px; -} -.bpp-panel-title { - margin: 0; - font-size: 13px; - font-weight: 600; -} -.bpp-row { - display: flex; - min-width: 0; - align-items: center; - gap: 16px; - padding: 12px 16px; - border-bottom: 1px solid var(--line); -} -.bpp-row:last-child { - border-bottom: 0; -} -.bpp-row-copy { - display: flex; - min-width: 0; - flex: 1; - flex-direction: column; - gap: 2px; -} -.bpp-row-title { - font-weight: 500; -} -.bpp-row-description { - color: var(--text-3); - font-size: 12px; -} -.bpp-kv { - display: grid; - grid-template-columns: 136px minmax(0, 1fr) auto; - align-items: center; -} -.bpp-kv > * { - display: flex; - min-width: 0; - min-height: 40px; - align-items: center; - padding: 6px 16px; - border-bottom: 1px solid var(--line); -} -.bpp-kv > :nth-last-child(-n + 3) { - border-bottom: 0; -} -.bpp-kv-key { - color: var(--text-3); - white-space: nowrap; -} -.bpp-kv-value { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.bpp-kv-value.is-empty { - color: var(--text-3); -} -.bpp-kv-actions { - gap: 4px; - justify-content: flex-end; -} - -/* ── Buttons ───────────────────────────────────────────────────────── */ -.bpp-btn { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - gap: 6px; - border: 1px solid transparent; - border-radius: var(--r-control); - font-weight: 500; - line-height: 1; - text-decoration: none; - white-space: nowrap; - transition: - background var(--t-fast) var(--ease), - border-color var(--t-fast) var(--ease), - color var(--t-fast) var(--ease); -} -.bpp-btn svg { - flex: none; -} -.bpp-btn-md { - height: 32px; - padding: 0 12px; - font-size: 13px; -} -.bpp-btn-md svg { - width: 15px; - height: 15px; -} -.bpp-btn-sm { - height: 26px; - padding: 0 9px; - font-size: 12px; -} -.bpp-btn-sm svg { - width: 13px; - height: 13px; -} -.bpp-btn-icon { - width: 32px; - height: 32px; -} -.bpp-btn-icon svg { - width: 16px; - height: 16px; -} -.bpp-btn-icon-sm { - width: 26px; - height: 26px; -} -.bpp-btn-icon-sm svg { - width: 14px; - height: 14px; -} -.bpp-btn-primary { - color: var(--on-accent); - background: var(--accent); - font-weight: 600; -} -.bpp-btn-primary:hover:not(:disabled) { - background: var(--accent-hover); -} -.bpp-btn-secondary { - border-color: var(--line-strong); - color: var(--text-1); - background: var(--bg-panel); -} -.bpp-btn-secondary:hover:not(:disabled) { - background: var(--bg-hover); -} -.bpp-btn-ghost { - color: var(--text-2); - background: transparent; -} -.bpp-btn-ghost:hover:not(:disabled) { - color: var(--text-1); - background: var(--bg-hover); -} -.bpp-btn-danger { - border-color: rgba(229, 88, 78, 0.35); - color: var(--danger-text); - background: var(--danger-subtle); -} -.bpp-btn-danger:hover:not(:disabled) { - background: rgba(229, 88, 78, 0.22); -} -.bpp-btn:disabled, -.bpp-btn[aria-disabled='true'] { - opacity: 0.45; -} -.bpp-btn[data-busy] { - opacity: 0.8; -} -/* Both labels share one grid cell so the button keeps the wider width. */ -.bpp-busy-label { - display: inline-grid; -} -.bpp-busy-label > * { - grid-area: 1 / 1; - text-align: center; -} -.bpp-busy-label > [aria-hidden='true'] { - visibility: hidden; -} - -/* ── Badges ────────────────────────────────────────────────────────── */ -.bpp-badge { - display: inline-flex; - height: 22px; - flex: none; - align-items: center; - gap: 6px; - padding: 0 8px; - border-radius: 11px; - color: var(--text-2); - background: var(--bg-hover); - font-size: 12px; - font-weight: 500; - white-space: nowrap; -} -.bpp-badge::before { - width: 6px; - height: 6px; - border-radius: 50%; - background: currentColor; - content: ''; -} -.bpp-badge.no-dot::before { - display: none; -} -.bpp-badge-ok { - color: var(--success); - background: var(--success-subtle); -} -.bpp-badge-warn { - color: var(--warning); - background: var(--warning-subtle); -} -.bpp-badge-bad { - color: var(--danger); - background: var(--danger-subtle); -} -.bpp-badge-busy, -.bpp-badge-accent { - color: var(--accent); - background: var(--accent-subtle); -} -.bpp-badge-busy::before { - animation: bpp-pulse 1.2s ease-in-out infinite; -} -@keyframes bpp-pulse { - 50% { - opacity: 0.3; - } -} - -/* Run outcome tiers mirror the mod's HistoryPanelFormatter tiers. */ -.bpp-outcome { - --tier: var(--text-2); - display: inline-flex; - height: 22px; - align-items: center; - gap: 6px; - padding: 0 8px; - border-radius: 11px; - color: var(--tier); - background: color-mix(in srgb, var(--tier) 14%, transparent); - font-size: 12px; - font-weight: 600; - white-space: nowrap; -} -.bpp-outcome[data-tier='misfortune'] { - --tier: var(--text-3); -} -.bpp-outcome[data-tier='bronze'] { - --tier: #c8915f; -} -.bpp-outcome[data-tier='silver'] { - --tier: #bfc3ca; -} -.bpp-outcome[data-tier='gold'] { - --tier: var(--accent); -} -.bpp-outcome[data-tier='diamond'] { - --tier: #7cc6ee; -} -.bpp-outcome[data-state='active'] { - --tier: var(--success); -} - -/* ── Banners ───────────────────────────────────────────────────────── */ -.bpp-banner { - display: flex; - align-items: flex-start; - gap: 10px; - padding: 10px 12px; - border: 1px solid var(--line); - border-radius: var(--r-panel); - background: var(--bg-panel); - font-size: 13px; -} -.bpp-banner.is-warning { - border-color: rgba(217, 163, 59, 0.3); - background: var(--warning-subtle); -} -.bpp-banner.is-error { - border-color: rgba(229, 88, 78, 0.3); - background: var(--danger-subtle); -} -.bpp-banner.is-success { - border-color: rgba(69, 178, 107, 0.3); - background: var(--success-subtle); -} -.bpp-banner-icon { - display: flex; - margin-top: 2px; - color: var(--text-2); -} -.is-warning > .bpp-banner-icon { - color: var(--warning); -} -.is-error > .bpp-banner-icon { - color: var(--danger); -} -.is-success > .bpp-banner-icon { - color: var(--success); -} -.bpp-banner-body { - display: flex; - min-width: 0; - flex: 1; - flex-direction: column; - gap: 6px; -} -.bpp-banner-actions { - display: flex; - flex: none; - align-items: center; - gap: 6px; -} -.bpp-banner-diagnostic summary { - color: var(--text-2); - font-size: 12px; -} -.bpp-banner-diagnostic pre { - margin: 6px 0 0; - padding: 8px 10px; - border-radius: var(--r-control); - color: var(--text-2); - background: var(--bg-canvas); - font-family: var(--font-mono); - font-size: 11px; - white-space: pre-wrap; -} - -/* ── Toasts (Popover API top layer, above modals) ──────────────────── */ -.bpp-toast-viewport { - position: fixed; - inset: unset; - top: 52px; - right: 16px; - margin: 0; - display: flex; - width: min(340px, calc(100vw - 32px)); - flex-direction: column; - align-items: flex-end; - gap: 8px; - border: 0; - padding: 0; - overflow: visible; - background: transparent; - color: inherit; - pointer-events: none; -} -.bpp-toast-viewport:popover-open { - display: flex; -} -.bpp-toast { - display: grid; - grid-template-columns: auto minmax(0, 1fr) auto; - align-items: start; - min-width: 240px; - max-width: 340px; - gap: 8px; - padding: 9px 8px 9px 12px; - border: 1px solid var(--line-strong); - border-radius: var(--r-panel); - background: var(--bg-selected); - box-shadow: var(--shadow-float); - opacity: 0; - pointer-events: auto; - transform: translateY(-4px); - transition: - opacity var(--t-base) var(--ease), - transform var(--t-base) var(--ease); -} -.bpp-toast.is-present { - opacity: 1; - transform: none; -} -.bpp-toast.is-closing { - transition-duration: var(--t-fast); -} -.bpp-toast-icon { - margin-top: 2px; - color: var(--text-2); -} -.bpp-toast.is-success .bpp-toast-icon { - color: var(--success); -} -.bpp-toast.is-warning .bpp-toast-icon { - color: var(--warning); -} -.bpp-toast.is-error .bpp-toast-icon { - color: var(--danger); -} -.bpp-toast-copy { - display: flex; - min-width: 0; - flex-direction: column; - align-items: flex-start; - gap: 4px; -} -.bpp-toast-message { - margin: 0; - font-size: 13px; -} -.bpp-toast-action { - padding: 0; - border: 0; - color: var(--accent); - background: none; - font-size: 12px; - font-weight: 600; -} -.bpp-toast-action:hover { - color: var(--accent-hover); -} -.bpp-toast-close { - display: inline-flex; - width: 22px; - height: 22px; - align-items: center; - justify-content: center; - border: 0; - border-radius: var(--r-control); - color: var(--text-2); - background: transparent; -} -.bpp-toast-close:hover { - color: var(--text-1); - background: var(--bg-hover); -} - -/* ── Dialogs ───────────────────────────────────────────────────────── */ -/* Native modal via : top-layer, Escape-to-close, focus trap and a - real backdrop from the platform. The dialog fills the viewport and centers - its card; ::backdrop dims without blur. */ -.bpp-dialog { - width: 100vw; - height: 100vh; - max-width: 100vw; - max-height: 100vh; - margin: 0; - padding: 0; - border: none; - background: transparent; - color: inherit; - overflow: visible; - align-items: center; - justify-content: center; -} -.bpp-dialog[open] { - display: flex; -} -.bpp-dialog:focus { - outline: none; -} -.bpp-dialog::backdrop { - background: rgba(0, 0, 0, 0.55); -} -.bpp-dialog-card { - display: flex; - width: calc(100vw - 32px); - max-height: calc(100vh - 48px); - flex-direction: column; - border: 1px solid var(--line-strong); - border-radius: var(--r-dialog); - background: var(--bg-panel); - box-shadow: var(--shadow-float); - animation: bpp-float-in var(--t-base) var(--ease) both; -} -.bpp-dialog-card.is-sm { - max-width: 380px; -} -.bpp-dialog-card.is-md { - max-width: 440px; -} -.bpp-dialog-card.is-lg { - max-width: 520px; -} -.bpp-dialog-header { - display: flex; - align-items: flex-start; - gap: 12px; - padding: 16px 14px 0 18px; -} -.bpp-dialog-icon { - display: flex; - width: 32px; - height: 32px; - flex: none; - align-items: center; - justify-content: center; - border-radius: var(--r-panel); - color: var(--text-2); - background: var(--bg-hover); -} -.bpp-dialog-icon.is-accent { - color: var(--accent); - background: var(--accent-subtle); -} -.bpp-dialog-icon.is-danger { - color: var(--danger); - background: var(--danger-subtle); -} -.bpp-dialog-heading { - display: flex; - min-width: 0; - flex: 1; - flex-direction: column; - gap: 2px; - padding-top: 5px; -} -.bpp-dialog-title { - margin: 0; - font-size: 15px; - font-weight: 600; -} -.bpp-dialog-subtitle { - margin: 0; - color: var(--text-2); - font-size: 12px; -} -.bpp-dialog-body { - display: flex; - min-height: 0; - flex-direction: column; - gap: 12px; - overflow: auto; - padding: 14px 18px 16px; - color: var(--text-2); -} -.bpp-dialog-body p { - margin: 0; -} -.bpp-dialog-footer { - display: flex; - align-items: center; - justify-content: flex-end; - gap: 8px; - padding: 12px 18px; - border-top: 1px solid var(--line); -} -.bpp-confirm-blocked-status { - margin: 0 auto 0 0; - color: var(--text-3); - font-size: 12px; -} -.bpp-confirm-ack { - display: flex; - align-items: flex-start; - gap: 8px; - color: var(--text-1); -} -.bpp-confirm-ack input { - margin-top: 3px; - accent-color: var(--accent); -} -.bpp-confirm-note { - display: flex; - gap: 10px; - padding: 10px 12px; - border: 1px solid var(--line); - border-radius: var(--r-panel); - color: var(--text-1); - background: var(--bg-canvas); -} -.bpp-confirm-note.is-danger { - border-color: rgba(229, 88, 78, 0.28); - background: var(--danger-subtle); -} -.bpp-confirm-note.is-warning { - border-color: rgba(217, 163, 59, 0.28); - background: var(--warning-subtle); -} -.bpp-confirm-note-icon { - display: flex; - margin-top: 2px; - color: var(--text-2); -} -.bpp-confirm-note.is-danger .bpp-confirm-note-icon { - color: var(--danger); -} -.bpp-confirm-note.is-warning .bpp-confirm-note-icon { - color: var(--warning); -} -.bpp-confirm-note-body { - display: flex; - min-width: 0; - flex-direction: column; - gap: 6px; -} -.bpp-confirm-note-body p { - margin: 0; -} -.bpp-confirm-target { - padding: 8px 10px; - border: 1px solid var(--line); - border-radius: var(--r-control); - color: var(--text-2); - background: var(--bg-canvas); - font-family: var(--font-mono); - font-size: 12px; - overflow-wrap: anywhere; -} -.bpp-dialog-link { - display: inline-flex; - align-items: center; - gap: 4px; - color: var(--accent); - font-weight: 500; - text-decoration: none; - white-space: nowrap; -} -.bpp-dialog-link:hover { - color: var(--accent-hover); -} -.bpp-video-delete-summary { - display: grid; - grid-template-columns: auto 1fr; - gap: 4px 14px; - margin: 0; - font-family: var(--font-ui); - font-size: 13px; -} -.bpp-video-delete-summary dt { - color: var(--text-3); -} -.bpp-video-delete-summary dd { - margin: 0; - color: var(--text-1); -} -.bpp-video-delete-diagnostics { - margin-top: 8px; - font-family: var(--font-ui); -} -.bpp-video-delete-diagnostics summary { - color: var(--text-2); - font-size: 12px; -} -.bpp-video-delete-diagnostics p { - margin: 6px 0 0; - font-family: var(--font-mono); -} -.bpp-details { - padding: 8px 12px; - border: 1px solid var(--line); - border-radius: var(--r-panel); - color: var(--text-2); - background: var(--bg-canvas); - font-size: 12px; -} -.bpp-details summary { - display: flex; - align-items: center; - gap: 6px; - list-style: none; -} -.bpp-details summary::-webkit-details-marker { - display: none; -} -.bpp-details[open] .bpp-details-chevron { - rotate: 90deg; -} -.bpp-details-chevron { - transition: rotate var(--t-fast) var(--ease); -} - -/* ── Form controls ─────────────────────────────────────────────────── */ -.bpp-input, -.bpp-select { - height: 32px; - min-width: 0; - padding: 0 10px; - border: 1px solid var(--line-strong); - border-radius: var(--r-control); - color: var(--text-1); - background: var(--bg-canvas); - font-size: 13px; - transition: - border-color var(--t-fast) var(--ease), - box-shadow var(--t-fast) var(--ease); -} -.bpp-input::placeholder { - color: var(--text-3); -} -.bpp-input:focus, -.bpp-select:focus { - border-color: var(--accent); - outline: none; - box-shadow: 0 0 0 3px var(--accent-subtle); -} -.bpp-input:disabled, -.bpp-select:disabled { - opacity: 0.5; -} -.bpp-input.is-readonly { - display: flex; - align-items: center; - overflow: hidden; - color: var(--text-2); - text-overflow: ellipsis; - white-space: nowrap; -} -.bpp-select { - appearance: none; - padding-right: 28px; -} -.bpp-select-wrap { - position: relative; - display: inline-flex; -} -.bpp-select-wrap > svg { - position: absolute; - top: 50%; - right: 9px; - color: var(--text-3); - pointer-events: none; - translate: 0 -50%; -} -.bpp-field { - display: flex; - min-width: 0; - flex-direction: column; - gap: 6px; -} -.bpp-field-label { - color: var(--text-2); - font-size: 12px; - font-weight: 500; -} -.bpp-field-hint { - margin: 0; - color: var(--text-3); - font-size: 12px; -} -.bpp-field-row { - display: flex; - min-width: 0; - flex-wrap: wrap; - align-items: center; - gap: 8px; -} - -.bpp-segmented-control { - display: inline-flex; - gap: 2px; - padding: 2px; - border: 1px solid var(--line); - border-radius: var(--r-control); - background: var(--bg-canvas); -} -.bpp-segmented-label { - position: relative; - display: inline-flex; -} -.bpp-segmented-input { - position: absolute; - opacity: 0; - pointer-events: none; -} -.bpp-segmented-option { - padding: 4px 10px; - border-radius: 4px; - color: var(--text-2); - font-size: 12px; - font-weight: 500; - transition: - background var(--t-fast) var(--ease), - color var(--t-fast) var(--ease); -} -.bpp-segmented-label:hover .bpp-segmented-option { - color: var(--text-1); -} -.bpp-segmented-input:checked + .bpp-segmented-option { - color: var(--text-1); - background: var(--bg-selected); -} -.bpp-segmented-input:focus-visible + .bpp-segmented-option { - outline: 2px solid var(--accent); -} -.bpp-segmented-input:disabled + .bpp-segmented-option { - opacity: 0.45; -} - -/* ── Empty and loading states ──────────────────────────────────────── */ -.bpp-empty-state { - display: flex; - flex-direction: column; - align-items: center; - gap: 8px; - padding: 36px 16px; - color: var(--text-2); - text-align: center; -} -.bpp-empty-state-icon { - display: flex; - color: var(--text-3); -} -.bpp-empty-state-heading { - margin: 4px 0 0; - color: var(--text-1); - font-size: 14px; - font-weight: 600; -} -.bpp-empty-state-description { - max-width: 44ch; - margin: 0; -} -.bpp-empty-state-actions { - display: flex; - gap: 8px; - margin-top: 8px; -} -.bpp-loading-panel { - display: flex; - align-items: center; - justify-content: center; - gap: 8px; - border: 1px solid var(--line); - border-radius: var(--r-panel); - color: var(--text-2); - background: var(--bg-panel); -} -.bpp-inline-status { - display: flex; - align-items: center; - gap: 8px; - margin: 0; - color: var(--text-3); - font-size: 12px; -} - -/* Folded section: a summary row that opens a list of rows. */ -.bpp-disclosure-summary { - display: flex; - align-items: center; - gap: 16px; - padding: 12px 16px; - list-style: none; -} -.bpp-disclosure-summary::-webkit-details-marker { - display: none; -} -.bpp-disclosure-summary > svg { - flex: none; - color: var(--text-3); - transition: rotate var(--t-fast) var(--ease); -} -.bpp-disclosure-summary:hover > svg { - color: var(--text-1); -} -.bpp-disclosure[open] > .bpp-disclosure-summary { - border-bottom: 1px solid var(--line); -} -.bpp-disclosure[open] > .bpp-disclosure-summary > svg { - rotate: 180deg; -} - -/* ── Install ───────────────────────────────────────────────────────── */ -.bpp-install-status-top { - display: flex; - min-width: 0; - align-items: center; - gap: 12px; - padding: 16px; - border-bottom: 1px solid var(--line); -} -.bpp-install-status-logo { - width: 40px; - height: 40px; - flex: none; - border-radius: 9px; -} -.bpp-install-status-name { - display: flex; - min-width: 0; - flex: 1; - flex-direction: column; - gap: 3px; -} -.bpp-install-status-title { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 8px; - margin: 0; - font-size: 15px; - font-weight: 600; -} -.bpp-install-status-description { - margin: 0; - color: var(--text-2); - font-size: 12px; -} - -/* ── History ───────────────────────────────────────────────────────── */ -.bpp-history-overview-bar { - display: flex; - min-width: 0; - align-items: center; - gap: 12px; - padding: 10px 10px 10px 16px; -} -.bpp-history-stats { - display: flex; - min-width: 0; - flex: 1; - flex-wrap: wrap; - gap: 4px 28px; - margin: 0; -} -.bpp-history-stat { - display: flex; - align-items: baseline; - gap: 8px; -} -.bpp-history-stat-label { - color: var(--text-3); - font-size: 12px; -} -.bpp-history-stat-reading { - display: flex; - align-items: baseline; - gap: 6px; - margin: 0; -} -.bpp-history-stat-value { - font-size: 15px; - font-weight: 600; - font-variant-numeric: tabular-nums; -} -.bpp-history-stat.is-accent .bpp-history-stat-value { - color: var(--accent); -} -.bpp-history-stat-detail { - color: var(--text-3); - font-size: 12px; -} -.bpp-history-cleanup-chevron { - transition: rotate var(--t-fast) var(--ease); -} -[aria-expanded='true'] > .bpp-history-cleanup-chevron { - rotate: 180deg; -} -.bpp-history-cleanup-reveal { - display: grid; - grid-template-rows: 0fr; - transition: grid-template-rows var(--t-base) var(--ease); -} -.bpp-history-overview.is-open .bpp-history-cleanup-reveal { - grid-template-rows: 1fr; -} -.bpp-history-cleanup-content { - min-height: 0; - overflow: hidden; -} -.bpp-history-overview.is-open .bpp-history-cleanup-content { - border-top: 1px solid var(--line); -} -.bpp-history-cleanup-content > .bpp-banner { - margin: 12px 16px 0; -} -.bpp-history-cleanup-outcome { - margin: 0; - padding: 0 16px 12px; - color: var(--success); - font-size: 12px; -} -/* Each run is a card led by its end-of-run board screenshot. */ -.bpp-history-run-list { - display: flex; - flex-direction: column; - gap: 12px; - container-type: inline-size; -} -.bpp-history-run-card { - display: flex; - min-width: 0; - overflow: hidden; - border: 1px solid var(--line); - border-radius: var(--r-panel); - color: inherit; - background: var(--bg-panel); - text-decoration: none; - transition: - border-color var(--t-fast) var(--ease), - background var(--t-fast) var(--ease); -} -.bpp-history-run-card:hover { - border-color: var(--line-strong); - background: var(--bg-hover); -} -.bpp-history-run-card:focus-visible { - outline-offset: 2px; -} -/* Keep the reference composition at every width: the strip sets the row - height, and the facts scale with the list using container-relative type. */ -.bpp-history-run-preview { - display: flex; - min-width: 0; - flex: 0 0 71%; - aspect-ratio: 2004 / 428; - align-items: center; - justify-content: center; - overflow: hidden; - border-right: 1px solid var(--line); - background: var(--bg-canvas); -} -.bpp-history-run-preview-image { - display: block; - width: 100%; - height: 100%; - object-fit: contain; -} -.bpp-history-run-preview-empty { - display: flex; - flex-direction: column; - align-items: center; - gap: 0.5em; - color: var(--text-3); - font-size: 1.5cqw; -} -.bpp-history-run-info { - display: flex; - width: 29%; - flex: none; - min-width: 0; - flex-direction: column; - gap: 0.3em; - padding: 0.5em 0.8em; - font-size: 1.5cqw; - line-height: 1.2; - font-variant-numeric: tabular-nums; -} -.bpp-history-run-title { - display: flex; - align-items: center; - gap: 0.5em; -} -.bpp-history-run-hero { - font-size: 1.15em; - font-weight: 600; - overflow-wrap: anywhere; -} -/* Wins and rating lead; days and the full timestamp remain supporting facts. */ -.bpp-history-run-metrics { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 0.5em; - margin-block: auto; -} -.bpp-history-run-metric { - display: flex; - min-width: 0; - flex-direction: column; - align-items: center; - gap: 0.15em; - text-align: center; -} -.bpp-history-run-metric-value { - font-size: 1.9em; - font-weight: 650; - line-height: 1.1; - letter-spacing: -0.02em; -} -.bpp-history-run-wins { - color: var(--accent); -} -.bpp-history-rating-delta { - margin-inline-start: 0.3em; - font-size: 0.55em; - font-weight: 600; - letter-spacing: 0; - color: var(--text-2); -} -.bpp-history-rating-delta[data-trend='up'] { - color: var(--success); -} -.bpp-history-rating-delta[data-trend='down'] { - color: var(--danger); -} -.bpp-history-run-metric-label, -.bpp-history-run-days, -.bpp-history-run-footer { - color: var(--text-2); - font-size: 1em; - font-weight: 400; -} -.bpp-history-run-metric-label { - overflow-wrap: anywhere; -} -.bpp-history-run-footer { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 0.25em 0.5em; -} -.bpp-history-run-when { - display: block; - white-space: normal; -} -.bpp-history-run-days { - white-space: nowrap; -} -.bpp-history-run-metric .bpp-outcome, -.bpp-history-run-metric .bpp-history-run-days { - margin-top: 0.3em; - font-size: 0.75em; - line-height: 1.2; -} -.bpp-history-run-metric .bpp-outcome { - height: auto; - padding: 0; - border-radius: 0; - background: none; - white-space: normal; -} -.bpp-history-run-chevron { - width: 1em; - height: 1em; - flex: none; - margin-left: auto; - color: var(--text-2); -} -.bpp-history-run-card:hover .bpp-history-run-chevron { - color: var(--text-1); -} -.bpp-history-run-preview-empty svg { - width: 1.5em; - height: 1.5em; -} -.bpp-history-pagination { - display: flex; - align-items: center; - justify-content: space-between; - gap: 12px; - color: var(--text-3); - font-size: 12px; - font-variant-numeric: tabular-nums; -} - -/* ── Run detail ────────────────────────────────────────────────────── */ -.bpp-run-detail-stats { - display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); - border-top: 1px solid var(--line); -} -.bpp-run-detail-stat { - display: flex; - min-width: 0; - flex-direction: column; - gap: 2px; - padding: 12px 16px; - border-right: 1px solid var(--line); -} -.bpp-run-detail-stat:last-child { - border-right: 0; -} -.bpp-run-detail-stat-label { - color: var(--text-3); - font-size: 12px; -} -.bpp-run-detail-stat-value { - overflow: hidden; - font-size: 16px; - font-weight: 600; - font-variant-numeric: tabular-nums; - text-overflow: ellipsis; - white-space: nowrap; -} -.bpp-table { - width: 100%; - border-collapse: collapse; - table-layout: fixed; -} -.bpp-table th { - padding: 10px 12px; - border-bottom: 1px solid var(--line); - color: var(--text-3); - font-size: 12px; - font-weight: 500; - text-align: left; - white-space: nowrap; -} -.bpp-table td { - overflow: hidden; - padding: 8px 12px; - border-bottom: 1px solid var(--line); - text-overflow: ellipsis; - white-space: nowrap; -} -.bpp-table tbody tr:last-child td { - border-bottom: 0; -} -.bpp-table tbody tr:hover td { - background: var(--bg-hover); -} -.bpp-table .is-num { - font-variant-numeric: tabular-nums; -} -.bpp-table .is-muted { - color: var(--text-2); -} - -/* ── About ─────────────────────────────────────────────────────────── */ -.bpp-credit-list { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - margin: 0; - padding: 0; - list-style: none; -} -.bpp-credit-group { - margin: 0; - padding: 10px 16px 6px; - color: var(--text-3); - font-size: 12px; - font-weight: 600; -} -.bpp-credit-list + .bpp-credit-group, -div + div > .bpp-credit-group { - border-top: 1px solid var(--line); -} -.bpp-credit-item { - display: flex; - min-width: 0; - align-items: baseline; - justify-content: space-between; - gap: 12px; - padding: 7px 16px; - border-bottom: 1px solid var(--line); -} -.bpp-credit-name { - display: inline-flex; - min-width: 0; - align-items: center; - gap: 4px; - overflow: hidden; - color: var(--text-1); - font-weight: 500; - text-decoration: none; - text-overflow: ellipsis; - white-space: nowrap; -} -a.bpp-credit-name:hover { - color: var(--accent); -} -.bpp-credit-role { - flex: none; - color: var(--text-3); - font-size: 12px; -} -.bpp-panel-summary { - display: flex; - align-items: center; - justify-content: space-between; - padding: 12px 16px; - list-style: none; - font-weight: 600; -} -.bpp-panel-summary::-webkit-details-marker { - display: none; -} -details[open] > .bpp-panel-summary { - border-bottom: 1px solid var(--line); -} -details[open] > .bpp-panel-summary > svg { - rotate: 180deg; -} - -/* ── Native-feel base: this is a desktop app, not a web page ─────────── */ -@layer base { - /* Desktop apps use the arrow cursor everywhere; only text fields get a - caret. Listed explicitly so this beats Preflight's button cursor, while - Tailwind cursor-* utilities (utilities layer) still win where opted in. */ - *, - *::before, - *::after { - cursor: default; - } - a, - button, - [role='button'], - label, - summary, - select { - cursor: default; - } - input:not([type='checkbox']):not([type='radio']):not([type='range']), - textarea, - [contenteditable='true'] { - cursor: text; - } - - /* Chrome is not selectable; opt real content back in with .selectable. */ - :root { - -webkit-user-select: none; - user-select: none; - } - input:not([type='checkbox']):not([type='radio']), - textarea, - [contenteditable='true'] { - -webkit-user-select: text; - user-select: text; - } - - :focus-visible { - outline: 2px solid var(--accent); - outline-offset: 2px; - } - - button:disabled { - cursor: default; - } -} - -/* Thin, themed scrollbars everywhere. */ -* { - scrollbar-width: thin; - scrollbar-color: var(--line-strong) transparent; -} -::-webkit-scrollbar { - width: 10px; - height: 10px; -} -::-webkit-scrollbar-track { - background: transparent; -} -::-webkit-scrollbar-thumb { - border: 2px solid transparent; - border-radius: 10px; - background-clip: padding-box; - background-color: var(--line-strong); -} -::-webkit-scrollbar-thumb:hover { - background-color: #4a4640; -} - -/* Respect the OS "reduce motion" setting. */ -@media (prefers-reduced-motion: reduce) { - *, - *::before, - *::after { - animation-duration: 0.001ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.001ms !important; - scroll-behavior: auto !important; - } -} diff --git a/bazaarplusplus-installer/src/styles/tokens.css b/bazaarplusplus-installer/src/styles/tokens.css deleted file mode 100644 index d6f0739..0000000 --- a/bazaarplusplus-installer/src/styles/tokens.css +++ /dev/null @@ -1,53 +0,0 @@ -/* BazaarPlusPlus design tokens: the owning copy. The site copies this file at - build time; ownership is described in docs/design.md. */ -:root { - color-scheme: dark; - - /* Near-black neutrals with a slight warm bias toward the logo's amber gem. - Elevation is expressed by these fill steps plus 1px lines, not shadows. */ - --bg-canvas: #11100f; - --bg-sidebar: #171615; - --bg-panel: #1d1c1a; - --bg-hover: #262422; - --bg-selected: #2c2a27; - --line: #2a2826; - --line-strong: #3a3733; - - --text-1: #edebe7; - --text-2: #a5a19a; - /* Only on canvas, sidebar and panel fills; hover/selected rows use text-2. */ - --text-3: #8a857e; - - /* The logo gem. Primary action, selected icon, key numbers. */ - --accent: #ee8e1f; - --accent-hover: #f5a142; - --accent-subtle: rgba(238, 142, 31, 0.13); - --accent-line: rgba(238, 142, 31, 0.42); - --on-accent: #1a1206; - - /* Status only; never decoration. */ - --success: #45b26b; - --success-subtle: rgba(69, 178, 107, 0.14); - --warning: #d9a33b; - --warning-subtle: rgba(217, 163, 59, 0.14); - --danger: #e5584e; - --danger-subtle: rgba(229, 88, 78, 0.14); - --danger-text: #ff8a80; - - --r-control: 6px; - --r-panel: 8px; - --r-dialog: 12px; - - /* Floating layers (dialog, menu, toast) only. */ - --shadow-float: 0 12px 32px rgba(0, 0, 0, 0.45); - - --ease: cubic-bezier(0.2, 0, 0, 1); - --t-fast: 100ms; - --t-base: 160ms; - - --font-ui: - -apple-system, BlinkMacSystemFont, 'Segoe UI Variable Text', 'Segoe UI', - 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei UI', 'Microsoft YaHei', - 'Noto Sans SC', sans-serif; - --font-mono: ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, monospace; -} diff --git a/bazaarplusplus-installer/src/test-fixtures/shell/fixtures.ts b/bazaarplusplus-installer/src/test-fixtures/shell/fixtures.ts deleted file mode 100644 index b4aa447..0000000 --- a/bazaarplusplus-installer/src/test-fixtures/shell/fixtures.ts +++ /dev/null @@ -1,235 +0,0 @@ -// Seed data for the shell snapshot anchor (src/shell.snapshot.test.tsx). -// Every value is fixed: no clock reads, no build version, no host paths. -import { - emptyHistoryRunList, - emptyInstallState, - fallbackBootstrap, - idleStreamStatus -} from '../../api/previewDefaults'; -import type { - AppBootstrap, - HistoryRunDetail, - HistoryRunList, - HistoryRunRow, - InstallState, - LegacyDataState, - SemanticProblem, - StreamServiceStatus -} from '../../types/backend'; - -/** Replaces `__FRONTEND_VERSION__` so a version bump does not churn snapshots. */ -export const bootstrap: AppBootstrap = { - ...fallbackBootstrap, - app_version: '1.2.3', - bundled_bpp_version: '1.2.3' -}; - -export const gameMissing: InstallState = emptyInstallState; - -export const installable: InstallState = { - selected_game_path: '/Games/The Bazaar', - steam_path: '/Games/Steam', - game: { path_valid: true }, - mod_state: { installed: false, ready: false }, - actions: { - can_install: true, - can_reinstall: false, - can_reset_data: false, - can_reset_bepinex: false, - can_uninstall: false, - can_launch: true - }, - has_resettable_data: false, - has_bepinex_files: false, - warnings: [] -}; - -export const installed: InstallState = { - ...installable, - mod_state: { installed: true, ready: true }, - actions: { - can_install: false, - can_reinstall: true, - can_reset_data: true, - can_reset_bepinex: true, - can_uninstall: true, - can_launch: true - }, - has_resettable_data: true, - has_bepinex_files: true -}; - -/** An upgraded 5.x user who has not reinstalled yet: three Legacy Roots, one - * sharing files by hard link, and a mod that still writes an old root. */ -export const legacyRootsNeedingReinstall: LegacyDataState = { - game_path: '/Games/The Bazaar', - roots: [ - { - name: 'BazaarPlusPlus', - size_bytes: 524_288, - file_count: 3, - hard_linked_file_count: 0, - unreadable_entry_count: 0 - }, - { - name: 'BazaarPlusPlusV4', - size_bytes: 12_582_912, - file_count: 40, - hard_linked_file_count: 0, - unreadable_entry_count: 0 - }, - { - name: 'BazaarPlusPlusV5', - size_bytes: 1_610_612_736, - file_count: 1200, - hard_linked_file_count: 12, - unreadable_entry_count: 1 - } - ], - installed_mod_data_root: 'reinstall_required', - v5_import_eligible: false -}; - -/** A 6.x mod reinstalled over V5 data that has not been imported yet. */ -export const v5ImportEligible: LegacyDataState = { - game_path: '/Games/The Bazaar', - roots: [ - { - name: 'BazaarPlusPlusV5', - size_bytes: 1_610_612_736, - file_count: 1200, - hard_linked_file_count: 0, - unreadable_entry_count: 0 - } - ], - installed_mod_data_root: 'current', - v5_import_eligible: true -}; - -export const installDetectionFailed: SemanticProblem = { - code: 'install_detection_failed', - params: { operation: 'detect_state' }, - diagnostic: 'fixture: Steam library unreadable' -}; - -const heroes = ['Vanessa', 'Pygmalien', 'Dooley', 'Mak', 'Stelle', 'Jules']; - -function run(index: number): HistoryRunRow { - const won = index % 3 !== 0; - return { - run_id: `run-${index}`, - hero: heroes[index % heroes.length], - game_mode: index % 4 === 0 ? 'Normal' : 'Ranked', - started_at_utc: '2026-09-12T10:00:00Z', - ended_at_utc: '2026-09-12T10:42:30Z', - result: won ? 'win' : 'loss', - victories: won ? 10 : 4, - losses: won ? 2 : 5, - final_day: won ? 12 : 8, - final_player_rank: index % 2 === 0 ? 'Gold' : null, - final_player_rating: index % 2 === 0 ? 1500 + index : null, - final_player_rating_delta: index % 2 === 0 ? 12 - index : null, - screenshot_id: null, - thumbnail_url: null - }; -} - -/** 120 runs: the first page of a three-page list. */ -export const historyFirstPage: HistoryRunList = { - summary: { runs: 120, videos: 7, win_rate: 0.67 }, - runs: Array.from({ length: 50 }, (_, index) => run(index + 1)) -}; - -export const historyEmpty: HistoryRunList = emptyHistoryRunList; - -export const historyReadFailed: SemanticProblem = { - code: 'history_read_failed', - params: { operation: 'list_runs' }, - diagnostic: 'fixture: database is locked' -}; - -export const runDetail: HistoryRunDetail = { - run: { - run_id: 'run-1', - hero: 'Vanessa', - game_mode: 'Ranked', - started_at_utc: '2026-09-12T10:00:00Z', - ended_at_utc: '2026-09-12T10:42:30Z', - status: 'completed', - result: 'win', - victories: 10, - losses: 2, - final_day: 12, - final_player_rank: 'Gold', - final_player_rating: 1520, - final_player_rating_delta: 16, - screenshot_id: null, - player_name: 'Fixture Player' - }, - battles: [ - { - battle_id: 'battle-1', - day: 1, - hour: 2, - result: 'win', - opponent_hero: 'Pygmalien', - opponent_name: 'Opponent A', - opponent_rank: 'Silver', - opponent_rating: 1400, - video: { - video_id: 'video-1', - status: 'completed', - file_size_bytes: 52_428_800, - duration_ms: 95_000 - } - }, - { - battle_id: 'battle-2', - day: 2, - hour: 4, - result: 'loss', - opponent_hero: 'Dooley', - opponent_name: null, - opponent_rank: null, - opponent_rating: null, - video: null - } - ] -}; - -export const runDetailReadFailed: SemanticProblem = { - code: 'history_read_failed', - params: { operation: 'get_run_detail' }, - diagnostic: 'fixture: database is locked' -}; - -export const streamIdle: StreamServiceStatus = idleStreamStatus; - -export const streamRunning: StreamServiceStatus = { - ...idleStreamStatus, - running: true, - port: 17654, - overlay_url: 'http://127.0.0.1:17654/overlay', - settings_url: 'http://127.0.0.1:17654/settings', - started_at: '2026-09-12T10:00:00Z', - active_from: '2026-09-12T10:00:00Z', - db: { found: true } -}; - -export const streamError: StreamServiceStatus = { - ...idleStreamStatus, - last_error: 'fixture: address already in use' -}; - -export const availableUpdate = { - version: '9.9.0', - body: 'Fixture release notes.', - rawJson: {} -}; - -/** History before any V6 run: only the V5 Data Root exists. */ -export const historyUnavailable: SemanticProblem = { - code: 'history_unavailable', - params: {}, - diagnostic: null -}; diff --git a/bazaarplusplus-installer/src/types/backend.ts b/bazaarplusplus-installer/src/types/backend.ts deleted file mode 100644 index a88e83b..0000000 --- a/bazaarplusplus-installer/src/types/backend.ts +++ /dev/null @@ -1 +0,0 @@ -export type * from './generated/commands'; diff --git a/bazaarplusplus-installer/src/types/generated/commands.ts b/bazaarplusplus-installer/src/types/generated/commands.ts deleted file mode 100644 index c589890..0000000 --- a/bazaarplusplus-installer/src/types/generated/commands.ts +++ /dev/null @@ -1,362 +0,0 @@ -// This file has been generated by Tauri Specta. Do not edit this file manually. - -import { invoke as __TAURI_INVOKE } from "@tauri-apps/api/core"; - -/** Commands */ -export const commands = { - getAppBootstrap: () => __TAURI_INVOKE("get_app_bootstrap"), - setAppLocale: (locale: string) => __TAURI_INVOKE("set_app_locale", { locale }), - getInstallState: (gamePath: string | null) => __TAURI_INVOKE("get_install_state", { gamePath }), - chooseGameDirectory: () => __TAURI_INVOKE("choose_game_directory"), - installMod: (gamePath: string) => __TAURI_INVOKE("install_mod", { gamePath }), - resetBppData: (gamePath: string) => __TAURI_INVOKE("reset_bpp_data", { gamePath }), - resetBepinex: (gamePath: string) => __TAURI_INVOKE("reset_bepinex", { gamePath }), - getLegacyDataState: (gamePath: string | null) => __TAURI_INVOKE("get_legacy_data_state", { gamePath }), - /** - * Imports `BazaarPlusPlusV5/` history into the current Data Root once - * (ADR-0008) and returns the remeasured Legacy Roots. It never deletes V5. - */ - importV5History: (gamePath: string) => __TAURI_INVOKE("import_v5_history", { gamePath }), - /** - * Deletes one Legacy Root the user confirmed. `name` must be one of the - * directory names `get_legacy_data_state` lists. - */ - deleteLegacyRoot: (gamePath: string, name: string) => __TAURI_INVOKE("delete_legacy_root", { gamePath, name }), - uninstallMod: (gamePath: string) => __TAURI_INVOKE("uninstall_mod", { gamePath }), - launchGame: () => __TAURI_INVOKE("launch_game"), - /** - * End a game process that outlived its window. Both History and Install stall - * on that state — one cannot read the mod database, the other refuses to touch - * installed files — so the recovery lives outside either page. - * - * Returns whether a process was actually terminated: finding none means the - * state the caller was recovering from is already gone. - */ - endGameProcess: () => __TAURI_INVOKE("end_game_process"), - getStreamStatus: () => __TAURI_INVOKE("get_stream_status"), - ensureStreamSession: () => __TAURI_INVOKE("ensure_stream_session"), - prepareHistoryThumbnails: () => __TAURI_INVOKE("prepare_history_thumbnails"), - restartStreamSession: () => __TAURI_INVOKE("restart_stream_session"), - setStreamWindow: (offset: number) => __TAURI_INVOKE("set_stream_window", { offset }), - getOverlaySettings: () => __TAURI_INVOKE("get_overlay_settings"), - saveOverlayDisplayMode: (displayMode: StreamOverlayDisplayMode) => __TAURI_INVOKE("save_overlay_display_mode", { displayMode }), - applyOverlayCropCode: (code: string) => __TAURI_INVOKE("apply_overlay_crop_code", { code }), - resetOverlayCrop: () => __TAURI_INVOKE("reset_overlay_crop"), - listHistoryRuns: (limit: number, offset: number) => __TAURI_INVOKE("list_history_runs", { limit, offset }), - getHistoryRunDetail: (runId: string) => __TAURI_INVOKE<{ - run: HistoryRunDetailRow, - battles: HistoryBattleRow[], -} | null>("get_history_run_detail", { runId }), - revealRunScreenshot: (runId: string) => __TAURI_INVOKE("reveal_run_screenshot", { runId }), - revealBattleVideo: (battleId: string, videoId: string) => __TAURI_INVOKE("reveal_battle_video", { battleId, videoId }), - deleteBattleVideo: (battleId: string, videoId: string) => __TAURI_INVOKE("delete_battle_video", { battleId, videoId }), - previewStorageCleanup: (scope: StorageCleanupScope, preset: StorageCleanupPreset) => __TAURI_INVOKE("preview_storage_cleanup", { scope, preset }), - executeStorageCleanup: (scope: StorageCleanupScope, preset: StorageCleanupPreset) => __TAURI_INVOKE("execute_storage_cleanup", { scope, preset }), -}; - -/* Types */ -export type AppBootstrap = { - app_version: string, - bundled_bpp_version: string | null, - links: AppLinks, - credits: AppCredit[], - licenses: AppLicense[], -}; - -export type AppCredit = { - name: string, - role: string, - href: string | null, - group: string, -}; - -export type AppLicense = { - name: string, - license: string, - category: string, -}; - -export type AppLinks = { - github: string, - x: string, - bilibili_project: string, - bilibili_author: string, - bilibili_core_dev: string, - xiaohongshu: string, - kofi: string, - supporter_list: string, -}; - -export type DeleteLegacyRootResult = { - /** False when the root was already gone: nothing was deleted. */ - removed: boolean, - state: LegacyDataState, -}; - -export type GameDirectorySelection = { - game_path: string | null, -}; - -export type HistoryBattleRow = { - battle_id: string, - day: number | null, - hour: number | null, - result: string, - opponent_hero: string | null, - opponent_name: string | null, - opponent_rank: string | null, - opponent_rating: number | null, - video: HistoryBattleVideo | null, -}; - -export type HistoryBattleVideo = { - video_id: string, - status: string, - file_size_bytes: number | null, - duration_ms: number | null, -}; - -export type HistoryRunDetail = { - run: HistoryRunDetailRow, - battles: HistoryBattleRow[], -}; - -export type HistoryRunDetailRow = { - run_id: string, - hero: string, - game_mode: string, - started_at_utc: string, - ended_at_utc: string | null, - status: string, - result: string, - victories: number | null, - losses: number | null, - final_day: number | null, - final_player_rank: string | null, - final_player_rating: number | null, - /** The Run's rating change; `None` when the starting rating was not captured. */ - final_player_rating_delta: number | null, - screenshot_id: string | null, - player_name: string | null, -}; - -export type HistoryRunList = { - summary: HistorySummary, - runs: HistoryRunRow[], -}; - -export type HistoryRunRow = { - run_id: string, - hero: string, - game_mode: string, - started_at_utc: string, - ended_at_utc: string | null, - result: string, - victories: number | null, - losses: number | null, - final_day: number | null, - final_player_rank: string | null, - final_player_rating: number | null, - /** The Run's rating change; `None` when the starting rating was not captured. */ - final_player_rating_delta: number | null, - screenshot_id: string | null, - /** The absolute URL of the run's History Thumbnail. */ - thumbnail_url: string | null, -}; - -export type HistorySummary = { - runs: number, - videos: number, - win_rate: number | null, -}; - -/** - * A completed import. `BazaarPlusPlusV5/` stays in `state.roots`: deleting it - * is a separate confirmation. - */ -export type ImportV5HistoryResult = { - imported_run_count: number, - /** Runs the current database already held, left as they were. */ - skipped_run_count: number, - /** - * Screenshot and video rows whose file could not be carried over: outside - * the V5 folder, or already gone from it. - */ - unavailable_file_count: number, - /** The Legacy Roots remeasured after the import. */ - state: LegacyDataState, -}; - -export type InstallActions = { - can_install: boolean, - can_reinstall: boolean, - can_reset_data: boolean, - can_reset_bepinex: boolean, - can_uninstall: boolean, - can_launch: boolean, -}; - -export type InstallGameState = { - path_valid: boolean, -}; - -export type InstallModState = { - installed: boolean, - /** Payload version and the platform launch bootstrap are both ready. */ - ready: boolean, -}; - -export type InstallState = { - selected_game_path: string | null, - steam_path: string | null, - game: InstallGameState, - mod_state: InstallModState, - actions: InstallActions, - has_resettable_data: boolean, - /** - * Whether a `BepInEx/` directory physically exists — gates the blunt - * "reset BepInEx folder" action independently of a healthy install, so it - * stays usable when BepInEx is broken/half-installed. - */ - has_bepinex_files: boolean, - warnings: InstallWarning[], -}; - -export type InstallWarning = { - code: InstallWarningCode, - params: { [key in string]: string }, -}; - -export type InstallWarningCode = "game_missing" | "steam_config_unavailable" | "launch_options_not_empty" | "trampoline_not_ready" | "obsolete_macos_artifacts"; - -/** Which Data Root the installed mod writes, from its Payload contract file. */ -export type InstalledModDataRoot = -/** The contract names `BAZAAR_DATA_DIRECTORY`. */ -"current" | -/** - * The contract is missing, unreadable, has no `dataRootDirectoryName`, or - * names another directory: the installed mod predates the current Data - * Root and must be reinstalled. - */ -"reinstall_required"; - -/** - * One Legacy Root present in the selected game directory, measured without - * following symbolic links. A file with more than one hard link is counted in - * `size_bytes` and in `hard_linked_file_count`: deleting the root frees its - * blocks only when no other link remains, so the size is an upper bound on - * what deletion reclaims. - */ -export type LegacyDataRoot = { - name: LegacyRoot, - size_bytes: number, - file_count: number, - hard_linked_file_count: number, - /** - * Entries whose metadata or contents could not be read; their size is - * missing from `size_bytes`. - */ - unreadable_entry_count: number, -}; - -export type LegacyDataState = { - game_path: string | null, - roots: LegacyDataRoot[], - installed_mod_data_root: InstalledModDataRoot, - /** The one-time V5 import may run (`v5_import::is_v5_import_eligible`). */ - v5_import_eligible: boolean, -}; - -/** - * One Legacy Root. [`LegacyRoot::ALL`] is the only list of them in the - * installer; it never contains the current Data Root. - */ -export type LegacyRoot = "BazaarPlusPlus" | "BazaarPlusPlusV4" | "BazaarPlusPlusV5"; - -export type ResetBepinexResult = { - state: InstallState, - removed: boolean, -}; - -export type ResetBppDataResult = { - state: InstallState, - removed_data: boolean, -}; - -export type RunDataCleanupPreview = { - runs: number, - battles: number, - videos: number, - estimated_bytes: number, - skipped_pending_uploads: number, -}; - -export type RunDataCleanupResult = { - deleted_runs: number, - deleted_files: number, - freed_bytes: number, - skipped_pending_uploads: number, -}; - -export type ScreenshotCleanupPreview = { - screenshots: number, - orphan_files: number, - estimated_bytes: number, - skipped_pending_uploads: number, -}; - -export type ScreenshotCleanupResult = { - deleted_rows: number, - deleted_files: number, - freed_bytes: number, - skipped_pending_uploads: number, -}; - -export type SemanticProblem = { - code: SemanticProblemCode, - params: { [key in string]: string }, - diagnostic: string | null, -}; - -export type SemanticProblemCode = "history_unavailable" | "history_read_failed" | "history_read_blocked_by_game" | "history_database_unsupported_schema" | "history_action_failed" | "history_thumbnails_unavailable" | "install_detection_failed" | "install_action_failed" | "install_partial_failure" | "install_blocked_by_game" | "reset_blocked_by_game" | "bepinex_reset_blocked_by_game" | "import_blocked_by_game" | "import_failed" | "legacy_delete_blocked_by_game" | "stream_service_failed" | "stream_window_failed" | "stream_crop_failed"; - -export type StorageCleanupExecution = { scope: "screenshots"; result: ScreenshotCleanupResult } | { scope: "run_data"; result: RunDataCleanupResult }; - -/** Wire strings are a stable contract with the frontend preset buttons. */ -export type StorageCleanupPreset = "all" | "older_than_7_days" | "before_this_month"; - -export type StorageCleanupPreview = { scope: "screenshots"; preview: ScreenshotCleanupPreview } | { scope: "run_data"; preview: RunDataCleanupPreview }; - -export type StorageCleanupScope = "screenshots" | "run_data"; - -export type StreamDbStatus = { - found: boolean, -}; - -export type StreamOverlayCropSettings = { - left: number | null, - top: number | null, - width: number | null, - height: number | null, -}; - -export type StreamOverlayCropSettingsPayload = { - crop: StreamOverlayCropSettings, - code: string, - display_mode: StreamOverlayDisplayMode, -}; - -export type StreamOverlayDisplayMode = "current" | "hero" | "herohalf"; - -export type StreamServiceStatus = { - running: boolean, - host: string, - port: number | null, - overlay_url: string | null, - settings_url: string | null, - last_error: string | null, - started_at: string | null, - active_from: string | null, - active_window_offset: number, - db: StreamDbStatus, -}; diff --git a/bazaarplusplus-installer/src/vite-env.d.ts b/bazaarplusplus-installer/src/vite-env.d.ts deleted file mode 100644 index 1a1f2fc..0000000 --- a/bazaarplusplus-installer/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare const __FRONTEND_VERSION__: string; diff --git a/bazaarplusplus-installer/static/about/fable-5-verified.webp b/bazaarplusplus-installer/static/about/fable-5-verified.webp deleted file mode 100644 index 2007522..0000000 Binary files a/bazaarplusplus-installer/static/about/fable-5-verified.webp and /dev/null differ diff --git a/bazaarplusplus-installer/static/brand/bazaarplusplus-logo.webp b/bazaarplusplus-installer/static/brand/bazaarplusplus-logo.webp deleted file mode 100644 index 7e9136f..0000000 Binary files a/bazaarplusplus-installer/static/brand/bazaarplusplus-logo.webp and /dev/null differ diff --git a/bazaarplusplus-installer/static/support/douyin.png b/bazaarplusplus-installer/static/support/douyin.png deleted file mode 100644 index a0f9097..0000000 Binary files a/bazaarplusplus-installer/static/support/douyin.png and /dev/null differ diff --git a/bazaarplusplus-installer/static/support/wechat-pay.svg b/bazaarplusplus-installer/static/support/wechat-pay.svg deleted file mode 100644 index d51249d..0000000 --- a/bazaarplusplus-installer/static/support/wechat-pay.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/bazaarplusplus-installer/static/support/xiaohongshu.svg b/bazaarplusplus-installer/static/support/xiaohongshu.svg deleted file mode 100644 index 314cf58..0000000 --- a/bazaarplusplus-installer/static/support/xiaohongshu.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/bazaarplusplus-installer/tsconfig.json b/bazaarplusplus-installer/tsconfig.json deleted file mode 100644 index 00f3596..0000000 --- a/bazaarplusplus-installer/tsconfig.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2023", - "useDefineForClassFields": true, - "lib": ["ES2023", "DOM", "DOM.Iterable"], - "allowJs": false, - "skipLibCheck": true, - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "strict": true, - "forceConsistentCasingInFileNames": true, - "module": "ESNext", - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true, - "jsx": "react-jsx", - "types": ["node", "vite/client", "react", "react-dom"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "scripts/**/*.mjs", - "vitest.config.ts", - "vite.config.ts" - ] -} diff --git a/bazaarplusplus-installer/vite.config.ts b/bazaarplusplus-installer/vite.config.ts deleted file mode 100644 index 62d2869..0000000 --- a/bazaarplusplus-installer/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { readFileSync } from 'node:fs'; -import tailwindcss from '@tailwindcss/vite'; -import react from '@vitejs/plugin-react'; -import { defineConfig } from 'vite'; - -const host = process.env.TAURI_DEV_HOST; -const pkg = JSON.parse(readFileSync('package.json', 'utf-8')) as { - version: string; -}; - -export default defineConfig({ - plugins: [tailwindcss(), react()], - define: { - __FRONTEND_VERSION__: JSON.stringify(pkg.version) - }, - build: { - outDir: 'build', - emptyOutDir: true - }, - clearScreen: false, - server: { - port: 14207, - strictPort: true, - host: host || '0.0.0.0', - hmr: host - ? { - protocol: 'ws', - host, - port: 14208 - } - : undefined, - watch: { - ignored: ['**/src-tauri/**'] - } - } -}); diff --git a/bazaarplusplus-installer/vitest.config.ts b/bazaarplusplus-installer/vitest.config.ts deleted file mode 100644 index 675f8b7..0000000 --- a/bazaarplusplus-installer/vitest.config.ts +++ /dev/null @@ -1,22 +0,0 @@ -import viteConfig from './vite.config.ts'; -import { configDefaults, defineConfig, mergeConfig } from 'vitest/config'; - -// The UI formats times in the viewer's zone; pin the zone so date assertions -// give the same result on every machine. Workers inherit it. -process.env.TZ = 'UTC'; - -export default defineConfig( - mergeConfig(viteConfig, { - test: { - environment: 'node', - // The repository-wide golden regeneration switch; `-u` still works. - update: process.env.BPP_UPDATE_GOLDENS === '1', - exclude: [ - ...configDefaults.exclude, - '.claude/**', - '.superpowers/**', - '.worktrees/**' - ] - } - }) -); diff --git a/bazaarplusplus-mod/.config/dotnet-tools.json b/bazaarplusplus-mod/.config/dotnet-tools.json deleted file mode 100644 index 1016873..0000000 --- a/bazaarplusplus-mod/.config/dotnet-tools.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": 1, - "isRoot": true, - "tools": { - "csharpier": { - "version": "1.3.0", - "commands": ["csharpier"], - "rollForward": false - } - } -} diff --git a/bazaarplusplus-mod/.editorconfig b/bazaarplusplus-mod/.editorconfig deleted file mode 100644 index 7584c56..0000000 --- a/bazaarplusplus-mod/.editorconfig +++ /dev/null @@ -1,94 +0,0 @@ -root = true - -[*] -indent_style = space -indent_size = 4 -max_line_length = 100 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[*.{xml,csproj,props,targets}] -indent_size = 2 - -[*.json] -indent_size = 2 - -# Production and build sources compiled into tests (Compile-Include) keep -# File.ReadAllText; tests themselves go through TestInputs (ADR-0009). -[src/**.cs] -dotnet_diagnostic.RS0030.severity = none -# Persisted values, file names, and identifiers must use InvariantCulture; -# player-facing text passes CurrentCulture explicitly. -dotnet_diagnostic.CA1305.severity = warning - -[build/**.cs] -dotnet_diagnostic.RS0030.severity = none - -[*.cs] - -# ── Using directives ────────────────────────────────────────────── -dotnet_sort_system_directives_first = true -dotnet_separate_import_directive_groups = false -csharp_using_directive_placement = outside_namespace:warning - -# IDE0005: Remove unnecessary using -dotnet_diagnostic.IDE0005.severity = warning -# IDE0065: Using directive placement -dotnet_diagnostic.IDE0065.severity = warning - -# ── Namespace ───────────────────────────────────────────────────── -csharp_style_namespace_declarations = file_scoped:warning -# The `:warning` suffix above only affects the IDE; the build needs the -# diagnostic severity to enforce it. -dotnet_diagnostic.IDE0161.severity = warning - -# ── var preferences ─────────────────────────────────────────────── -csharp_style_var_for_built_in_types = false:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion -csharp_style_var_elsewhere = false:suggestion - -# ── this. qualification ────────────────────────────────────────── -dotnet_style_qualification_for_field = false:suggestion -dotnet_style_qualification_for_property = false:suggestion -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_event = false:suggestion - -# ── Layout ─────────────────────────────────────────────────────── -# Brace placement, new lines, indentation, and spacing are owned by CSharpier -# (just mod::fmt / mod::fmt-check); do not restate them here. - -# ── Braces ─────────────────────────────────────────────────────── -csharp_prefer_braces = true:suggestion - -# ── Expression-bodied members ──────────────────────────────────── -csharp_style_expression_bodied_methods = when_on_single_line:suggestion -csharp_style_expression_bodied_constructors = false:suggestion -csharp_style_expression_bodied_operators = when_on_single_line:suggestion -csharp_style_expression_bodied_properties = when_on_single_line:suggestion -csharp_style_expression_bodied_indexers = when_on_single_line:suggestion -csharp_style_expression_bodied_accessors = when_on_single_line:suggestion -csharp_style_expression_bodied_lambdas = when_on_single_line:suggestion -csharp_style_expression_bodied_local_functions = when_on_single_line:suggestion - -# ── Pattern matching ───────────────────────────────────────────── -csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion -csharp_style_pattern_matching_over_as_with_null_check = true:suggestion - -# ── Null checking ──────────────────────────────────────────────── -csharp_style_throw_expression = true:suggestion -csharp_style_conditional_delegate_call = true:suggestion - -# ── Modifiers ──────────────────────────────────────────────────── -dotnet_style_require_accessibility_modifiers = for_non_interface_members:warning -dotnet_diagnostic.IDE0040.severity = warning -csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:suggestion - -# ── Language keywords vs framework types ───────────────────────── -dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion -dotnet_style_predefined_type_for_member_access = true:suggestion - -# Build-generated sources (e.g. BepInEx MyPluginInfo) are not held to style rules. -[**/obj/**.cs] -generated_code = true diff --git a/bazaarplusplus-mod/.gitignore b/bazaarplusplus-mod/.gitignore deleted file mode 100644 index 3210543..0000000 --- a/bazaarplusplus-mod/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# Game assemblies and decompiled game source: local only, never redistributed. -game-libs/ -decompiled/ -decompiled-*/ - -# Native Windows build output (MSVC) -native/windows/build/ -*.obj -*.lib -*.exp - -# Reports written by just mod::test-corpus and the mod::test compatibility check -/artifacts/ diff --git a/bazaarplusplus-mod/AGENTS.md b/bazaarplusplus-mod/AGENTS.md deleted file mode 100644 index b12ef99..0000000 --- a/bazaarplusplus-mod/AGENTS.md +++ /dev/null @@ -1,44 +0,0 @@ -# AGENTS.md - -The BepInEx mod. Repo-wide rules are in `../AGENTS.md`; this file holds what is specific to the mod and points at everything else. - -| When you are about to | Read | -|---|---| -| Touch any code | `docs/MEMORY.md` | -| Change a feature | its `docs/architecture/` doc, Gotchas included; `docs/ARCHITECTURE.md` routes by feature | -| Name a domain concept | `CONTEXT.md` | -| Find who owns or constructs something | `docs/ARCHITECTURE.md` | -| Reopen a settled decision | `docs/adr/` | -| Add, move, or delete a document | `docs/README.md` | - -## Build and test - -`just --list mod` lists every command; recipes live in `mod.just` and run `scripts/*.sh`. Deploy only through `just mod::build --deploy`: a raw `dotnet build` skips the macOS trampoline repair every game update needs. Game assemblies resolve via `ManagedPath` from the Snapshot Lock (`build/ManagedPath.props`, root `CONTEXT.md`); override with `-p:ManagedPath=...`, and `just mod::fetch ` explains a mismatch. - -What `just --list mod` cannot tell you: - -- `just mod::locks-check` runs a locked restore so NuGet graph drift fails in the mod, not later in the installer build. -- Doc edits are gated by `just mod::test`: `tests/Architecture.Tests/DocsHygieneTests.cs` enforces byte budgets on this file and `docs/MEMORY.md` and checks that links resolve; stay under a budget by merging entries, not appending. -- A deletion is proved by deleting: `just mod::build` and `just mod::test` must both pass, because test projects compile fakes and source-shadow capsules that `build` never touches. - -## Logs and debugging - -Runtime console output goes to `/BepInEx/LogOutput.log`, the sibling of the `BepInEx/plugins/` folder the build copies into. Mod log lines are structured events shaped `[BPP][] event= field=value ...`. `Debug` events emit only from Debug builds; `Info`, `Warning`, and `Error` always emit. - -Runtime validation that needs the game running launches The Bazaar through Steam (App ID 1617400) so Steam runtime state is present: `open "steam://run/1617400"` on macOS, `start steam://run/1617400` on Windows. Launching `TheBazaar.app` directly, or via `run_bepinex.sh` on macOS, bypasses that state and fails in subtle ways. A long-running automation task relaunches the game through the same Steam URL after a crash or exit and continues until the goal is met. - -## Where new code goes - -The layering traps, not a map of what exists: - -- Reusable adapters over The Bazaar and Unity runtime surfaces go in `GameInterop/`. Feature workflows, UI state, product policy, filtering and classification rules, upload decisions, and storage orchestration go in `Game/`, even when they mention a game enum or DTO. -- When two features need the same runtime, prefab, or static-data behavior, extract the adapter to `GameInterop//` and have both consume that seam instead of one importing the other's internals. -- Patches reach feature services only through `BppPatchHost`, the static service locator. Shared Harmony reflection helpers and native runtime adapters live in `GameInterop/` or `Infrastructure/`, outside any feature directory. -- A boundary the compiler cannot enforce gets an architecture test over compiled artifacts in the same change (ADR-0009). - -## Game behavior - -- The current repo code and `decompiled/` are the source of truth for game behavior and APIs. `decompiled/` is local only (generate it with `just mod::decompile `) and stays unedited; re-check `docs/` claims against live code. -- Root-cause game-behavior bugs against the decompiled game source before forming a hypothesis. Ground every conclusion in `file:line` citations, and when the obvious fix fails, enumerate alternative cause mechanisms before writing another patch. -- When the user says a problem has failed repeatedly, stop reading implementation and decompiled source and first open or update a GitHub issue recording the background, the current problem, candidate approaches, and the verification method. -- Validate a hypothesis with a temporary probe on the main path (the user builds and reloads to verify), or record it as a to-verify item on that issue and ship. Delete a probe in the commit that acts on its measurement. diff --git a/bazaarplusplus-mod/CONTEXT.md b/bazaarplusplus-mod/CONTEXT.md deleted file mode 100644 index 72063df..0000000 --- a/bazaarplusplus-mod/CONTEXT.md +++ /dev/null @@ -1,194 +0,0 @@ -# BazaarPlusPlus Mod - -In-game mod for *The Bazaar*. This glossary captures the project-specific vocabulary that recurs across features. Definitions pin down what a term means and where its boundary sits; responsibilities and mechanics live in code and `docs/ARCHITECTURE.md`. - -## Run / encounters - -**Encounter**: -A single stop on a run — a combat, PvP combat, event, shop, pedestal, loot, or level-up — that the player reaches and enters. -_Avoid_: node, map node - -**Pedestal**: -An encounter that upgrades or enchants one of the player's existing items rather than granting a new one. Which pedestal kind the current Choice screen offers drives the upgrade/enchant preview's "smart" mode. - -**Encounter Status Probe**: -The on-demand, pull-based read of the player's *current* run/encounter state (`IEncounterStateProbe`). The project's chosen way to expose "where is the player in the run right now" — status queries, not a recorded timeline (see [ADR-0001](docs/adr/0001-encounter-status-probe-not-timeline-tracker.md)). -_Avoid_: encounter tracker, run timeline - -**Run Snapshot Probe**: -The on-demand, pull-based read of the current run's recordable facts — day/hour, win/loss, hero, mode, player stats, rank, leaderboard placement (`IRunSnapshotProbe`). Consumers map the snapshot into their own records instead of reading game globals directly. -_Avoid_: run tracker - -**Game Build Channel**: -The client's `Online`, `Ptr`, or `Unknown` classification, resolved at startup by `GameBuildInfoResolver`; conflicting signals resolve to `Ptr`. `Ptr` covers PTR and staging, while the raw version preserves branch identity. The channel gates uploads and is recorded on runs to keep test data out of production. -_Avoid_: environment, server flag - -**Run Logging Intake**: -The pure `IBppFeature` that owns run-log subscriptions, session transitions, and persistence/checkpoint ordering. It consumes event-bus inputs; it is not a mounted Unity controller and does not own a run timeline. -_Avoid_: RunLoggingController, run logger MonoBehaviour - -**Encounter Preview Module**: -The feature-owned query boundary for event cards, encounter-step rewards, and hero level rewards. Callers supply only a stable template id, current level, and native text they already hold; the module owns everything from plan generation to final presentation. - -**End-of-Run Capture Workflow**: -The single run-scoped state machine that owns the end-of-run screenshot flow — readiness, bounded attempts, clean-frame preparation, artifact validation, fail-open terminal outcomes. Harmony patches express only Continue and reveal-start intents through `IEndOfRunCaptureWorkflow` and never drive capture directly. -_Avoid_: screenshot gate - -**Ghost Battle**: -A PvP battle fetched from the mod backend in which the local player's uploaded build fought inside another player's run (the game's PvP is asynchronous — opponents are ghosts). Stored payloads keep the recorder's perspective, stamped as `PerspectiveVersion` (see [ADR-0002](docs/adr/0002-replay-exit-and-ghost-perspective.md)); only the HistoryPanel list row is projected to local perspective, by `GhostBattleLocalProjector`. -_Avoid_: remote battle, opponent battle - -## Combat replay - -**Replay Payload**: -The local serialized combat input used to replay a recorded PvP battle. It is a recoverable cache governed by `ReplayPayloadRetentionPolicy`; the battle fact remains after eviction, but only a favorite's own copy still offers Replay. - -**Replay Availability**: -Whether History can replay a battle: Remote (a Ghost Battle not yet downloaded), Saved (a local Replay Payload exists), Expired, or Unavailable. Local battles are only Saved or Unavailable. `ReplayAvailabilityCodec` alone maps it to stored columns. -_Avoid_: replay state, downloaded flag - -**Replay Video Artifact**: -A user-requested MP4 plus its metadata. Attachment to a battle and file health are separate facts: deleting a run detaches the metadata without deleting a completed MP4. -_Avoid_: replay cache, orphan video - -**Saved Replay Lifecycle**: -The single pure owner (`SavedReplayLifecycle`) of a saved-replay playback session's state algebra; the runtime feeds observations and executes the returned decisions. It never exits `ReplayState` itself; per ADR-0002 there is no programmatic replay exit. - -## Overlay panels - -**Live Build Refresh**: -The manual update of the Live Build Panel's recommendation corpus. One successful remote pull is allowed per panel lifetime; failed pulls remain retryable, and closing the panel does not cancel a pending pull. - -**Main Overlay Panel**: -A full-screen mod overlay — Collection Panel, History Panel, or Live Build Panel. At most one is open at a time; the Overlay Panel Host enforces the exclusivity. -_Avoid_: popup, window - -**Overlay Panel Host**: -The single module that owns main-overlay-panel lifecycle: mutual exclusion, scene-change policy, combat gating, hotkey and escape routing, and the per-frame tick. Panels register content callbacks with the host instead of re-implementing the lifecycle. -_Avoid_: panel mutex - -**Cursor Page / Counted Page**: -One read of a History list. A cursor page holds rows plus time/ID anchors and whether newer or older rows exist; the battle timeline and Ghost recovery use it. A counted page adds the one-based position of its first row and the filtered total, from which the neighbours follow; the Runs and Ghost archives use it. -_Avoid_: page with optional counts - -**Native Card Preview Host**: -The sole owning module (`GameInterop/CardPreview`) for the game's native card prefabs: setup, full visibility, hover, tooltip replacement, pooling, and destruction. Consumers open their own scopes through the host instead of holding runtime, reflection, or pool internals. -_Avoid_: global preview pool - -**Native Card Preview Scope / Session**: -A scope is one real UI owner's resource boundary, with its own pool; closing it settles pending acquisitions and destroys its objects. A session is an opaque lease of one set-up card, exposing only the layout root/rect and show/hide/hover intents — callers never hold native components or setup tasks. -_Avoid_: preview handle - -## Fonts - -**Native Game Typography**: -The single adapter (`GameInterop/Fonts/NativeGameTypography`) through which every BPP surface gets text rendering. It reuses the game's own font assets and zh-CN fallback chains and never exposes a raw `Font`/`TMP_FontAsset`; BPP embeds no fonts of its own. -_Avoid_: custom font, font selector - -## Settings dock - -**Cycling Settings Dock Entry**: -The unified settings-dock concept for entries that cycle through an ordered value ladder on click, highlight when off-default, and render localized state. Features contribute data only, not behavior classes; a bool toggle is the two-value special case. Action buttons and lock toggles are not this concept. - -## Uploads - -**Run Bundle Contract**: -The shared V6 reader/writer boundary that opens a Bundle, verifies manifest-to-payload Run identity, -and decides whether a Battle has the exact snapshot and replay inputs required for import. Bundle -composition and Ghost Battle import use the same contract. - -**Mod API Response**: -The bounded HTTP response boundary for mod-backend JSON: nested and legacy error-envelope shape, -request ID precedence, `Retry-After`, and the separation between a closed user code and diagnostic -exception. Endpoint-specific disposition and retry policy stay with each client. - -**Mod API Session**: -One owned transport lifetime for one mod-backend consumer. It combines normalized routes, standard -headers and timeout with typed Bundle, Ghost Battle, and health operations, without exposing its -`HttpClient` or endpoint adapters. Plugin History, each Upload Feed activation, and tools own -separate sessions. -_Avoid_: shared global HttpClient, public endpoint-client chain - -**Bundle Seal Convergence**: -The pure decision core for one Bundle seal pass. It receives the remaining relative deadline and -observed input facts, then decides whether to continue, wait, degrade the screenshot, or terminate; -it owns no clock, SQLite connection, file, codec, or Unity object. Its failure half, -`BundleSealFailurePolicy`, maps a failure and the seal stage it happened in to retry with backoff, -park until next launch, reseal, degrade, skip, or terminal, plus the log event. - -**Environment-Blocked Seal**: -A waiting seal job whose failure came from the loaded runtime (a missing member, type load, or -assembly binding failure) rather than its data. It is retried once per launch, so an update revives -it without a migration, and a pending file that fails this way is never resealed. -_Avoid_: JSON failure - -**Seal-Eligible Run**: -A completed, non-PTR Ranked Run, not History-Only, with neither a seal job nor any outbox row; -the next seal pass gives it a waiting job. `BundleQueueStore.SealEligibleRunCondition` is the one SQL rule, and installer -History cleanup is pinned to it through a shared fixture. -_Avoid_: sealable run - -**Bundle Queue Store**: -The concrete Storage owner of `bundle_seal_jobs` and `bundle_outbox` rows, SQL, and multi-row -transactions. Game workflows translate its storage records into composition and upload behavior; -there is deliberately no same-shape single-implementation repository interface. -_Avoid_: outbox repository interface - -**Bundle Outbox Files**: -The Game-owned file port for sealed Bundle artifacts. It exposes root-confined open, existence, -length, enumeration, and deletion so upload ordering and retention can be tested without moving -filesystem policy into Storage. - -**Upload Feed Session**: -The behavior object (`BundleUploadFeed.Session`) the Bundle feed returns from activation: one upload attempt, feed-private arm signals, and resource disposal. The background pump owns only the Unity cadence, the shutdown drain, and the shared gates (PTR channel precondition, run-lifecycle and `UploadArmRequested` arm signals); it never rewires feed internals. -_Avoid_: per-feed upload controller - -## Collection panel - -**Collection View State**: -The single owner of the Collection Panel's presentable state (`CollectionViewState`) — filter selections, search, catalog acceptance, and the derived render model. Commands and lifecycle events go in; a complete render outcome comes out; the panel's Unity surface only forwards commands and applies outcomes. Nothing outside the module reads or writes the filter. -_Avoid_: ApplyFilters/RefreshView pairing - -## Collection sources - -**Collection Source Catalog**: -The versioned in-mod catalog that defines merchant and trainer source filters for the Collection Panel. It is built from `collection-sources.json`, validated against `CollectionSourceCatalog.ExpectedSchemaVersion`, and keyed by stable source keys plus source template ids. - -**Offer Pool**: -The set of card templates a source can offer, expressed through structured rules (`CollectionSourceEntry.OfferSegments`) rather than runtime encounter fallback heuristics. Resolution keeps both the union of offered card ids and per-card source matches. - -**Collection Source Kind**: -The source category used by CollectionPanel source chips: `Merchant` maps to Item sources, `Trainer` maps to Skill sources. - -## Day tiers - -**Day Tier Resolver**: -The shared GameInterop adapter (`GameInterop/DayTiers/GameDataDayTierResolver`) that resolves the current run day's item/skill tier distribution from live GameData into a normalized weight table plus `MaximumTier` — the highest usable Bronze-to-Diamond tier, not the largest probability. Consumers (Collection's Day gate, Event Preview) fail open when the table is unavailable. -_Avoid_: DayTierSchedule, hardcoded tier table - -## Remote embedded data - -**Remote Embedded Catalog**: -The shared runtime lifecycle for data shipped as an embedded seed, cached under `/BazaarPlusPlusV6/`, and refreshed from a remote source (`IRemoteEmbeddedCatalog`). The interface exposes only current-snapshot lookup, warm-up, explicit refresh, and disposal; feature modules keep their own parser, logging, and user-facing refresh policy. -_Avoid_: feature repository loader - -**Supporter Catalog Module**: -The composition-owned Remote Embedded Catalog consumer for supporter data: fixed-list bypass, -session-stable snapshots through the supporter facade, retry/disposal ownership. - -**Platform Release Manifest**: -The per-platform release record defined in `../CONTEXT.md`. The mod reads only the `version` of its -own platform's manifest for the main-menu update check, through `ReleaseManifestEndpoints`, and -falls back to the lockstep Release Manifest only on an undeclared platform. Its HTTP/JSON adapter and request-generation lifecycle are separate from -Mod API health and installer runtime state. -_Avoid_: Mod API health - -**Build Seed Fetch**: -The build-time transport operation that stages remote embedded seeds, checks coarse transfer -integrity, runs feature-owned semantic gates, and promotes the complete seed set transactionally. - -## Build - -**Game-supplied library**: -A third-party library the game's `Managed/` directory loads for the mod (Newtonsoft.Json, MessagePack). The mod compiles against the game's file, never a package, and never publicizes or ships it (`build/GameLibraries.props`, ADR-0010). -_Avoid_: game JSON runtime, compile-only package diff --git a/bazaarplusplus-mod/Directory.Build.props b/bazaarplusplus-mod/Directory.Build.props deleted file mode 100644 index 319eb5f..0000000 --- a/bazaarplusplus-mod/Directory.Build.props +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - $(MSBuildThisFileDirectory)../VERSION - $([System.IO.File]::ReadAllText('$(BppProductVersionFile)').Trim()) - $(BppProductVersion) - true - - false - - - - - - - - - - BundlePipeline.Tests;BundleQueueSqliteStore.Tests;BundleSealConvergence.Tests;BundleV6Codec.Tests;CollectionFilterEngine.Tests;CollectionGridLayout.Tests;CollectionSourceFiltering.Tests;CollectionViewState.Tests;CombatReplayAudioVideo.Tests;CombatReplayRecording.Tests;EndOfRunScreenshotGate.Tests;GhostBattleSync.Tests;HistoryPanelDecisions.Tests;HistoryPanelFactory.Tests;HistoryPanelFiltering.Tests;HistoryPanelPreview.Tests;HistoryPanelRepository.Tests;HotkeyBindingPath.Tests;ItemEnchantPreview.Tests;LiveBuildPanel.Tests;LiveBuildRecommendations.Tests;MainMenuVersionLabel.Tests;ModApi.Tests;NativeCardArtwork.Tests;OverlayPanelLifecycle.Tests;ReleaseManifestClient.Tests;RemoteEmbeddedDataPipeline.Tests;RunLoggingPipeline.Tests;StaticCardMapCompatibility.Tests;Storage.Tests;SupporterCatalogModule.Tests;Supporters.Tests;TooltipPreviewTargetResolver.Tests;UiFoundation.Tests;UpgradePreviewTooltip.Tests - - - - - enable - true - true - - true - - $(NoWarn);CS1591 - - - - - true - true - - diff --git a/bazaarplusplus-mod/Directory.Packages.props b/bazaarplusplus-mod/Directory.Packages.props deleted file mode 100644 index 5a97e73..0000000 --- a/bazaarplusplus-mod/Directory.Packages.props +++ /dev/null @@ -1,45 +0,0 @@ - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bazaarplusplus-mod/LICENSE b/bazaarplusplus-mod/LICENSE deleted file mode 100644 index a549209..0000000 --- a/bazaarplusplus-mod/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2026 Xinyu YANG -Copyright (c) 2026 BazaarPlusPlus Team - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/bazaarplusplus-mod/NuGet.Config b/bazaarplusplus-mod/NuGet.Config deleted file mode 100644 index ba91d25..0000000 --- a/bazaarplusplus-mod/NuGet.Config +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bazaarplusplus-mod/README.md b/bazaarplusplus-mod/README.md deleted file mode 100644 index 729b0de..0000000 --- a/bazaarplusplus-mod/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# BazaarPlusPlus - -面向《The Bazaar》的 BepInEx 5 模组。它不改变游戏平衡,只做信息增强与记录:战斗界面增强、附魔 / 升级预览、run 记录与历史回放、终局自动截图与阵容推荐,以及可选的后台云同步。 - -## 功能 - -**对局界面** - -| 功能 | 说明 | 操作 | -|---|---|---| -| 战斗状态条 | 局内底部显示黄铜铭牌,复用游戏原生贴图与字体,提供逻辑战斗时间、0.5× / 0.67× / 1× 速度和暂停 / 继续 | 设置中的「战斗状态」开关控制显示;点击倍速数字循环,点击右侧按钮暂停 / 继续 | -| 附魔 / 升级预览 | 预览物品升级 / 附魔后的效果,三档可视性(Off / 智能 / 常显,默认常显) | 按住 Ctrl / Shift 手动覆盖 | -| 卡牌图鉴 | 全屏 Item / Skill 图鉴,支持英雄、品质、体型、来源、天数筛选 | Tab 键或大厅 dock 按钮 | -| 终局阵容面板 | 展示实时 shop / board / stash,并按候选物品推荐匹配的十胜终局 build | 局内 CapsLock 开关 | - -**记录与回放** - -- 活跃 run 自动写入本地 SQLite;游戏内历史面板可浏览 runs、PVP battles、ghost battles,并预览保存的战斗快照。 -- PVP 战斗回放数据本地保存,条件满足时可在历史面板中回放。 -- 终局总结页动画稳定后自动截图并保存元数据,之后才放行 `Continue` 按钮。 - -**云同步(可选,默认按项说明)** - -- run / replay 后台上传到 V6 后端,仅在不处于 live run 时执行。 -- BazaarDB 截图上传默认关闭;启用后终局截图快照推到 V6 后端,由 BazaarDB 队列拉取。 -- Anonymous Mode 可将本地玩家名替换为 `Anonymous`。 - -## 安装(玩家) - -用[安装器](https://bazaarplusplus.com/download)安装:mod 的 DLL、依赖和原生组件由仓库根目录的 Payload Inventory 定义,手动复制容易漏。首次运行后,配置文件生成于 `BepInEx/config/BazaarPlusPlus.cfg`。 - -## 从源码构建(开发者) - -在仓库根目录用 `just mod::<命令>` 构建和测试,`just --list mod` 列出全部命令;环境要求见[开发命令](../docs/development.md)。`just mod::build` 只编译,部署进游戏用 `just mod::build --deploy`(它会在游戏更新后修复 macOS trampoline,`dotnet build` 不做这一步)。游戏程序集通过 `ManagedPath` 从快照锁 `build/game-libs.lock.json` 解析(词条见根 `CONTEXT.md` 的 Snapshot Lock):先执行 `just mod::fetch macos online`(Windows 用 `windows`),它接受 `globalgamemanagers` 版本串与锁条目一致的本机 Steam 安装,否则从私有存储取包到 `game-libs/`;两者都不满足时报错并列出两个版本串,切换 Steam 分支或等锁更新。显式 `-p:ManagedPath=/path/to/Managed` 覆盖解析,但 `mod::check` 仍按锁条目核对该目录的 sha256,`release::prepare` 拒绝不对应任何锁条目的目录。 - -## 数据与网络行为 - -- run 记录、战斗回放与终局截图均保存在本地(SQLite、replay payload、截图文件)。 -- 云同步不携带任何鉴权凭证,且只在非 live run 状态下执行上传扫描。 -- 语音字幕与终局 build 种子由构建管线嵌入,运行时在本地缓存过期后后台刷新。 -- 云端后端(上传、ghost battles、BazaarDB 快照投递)在 monorepo 的 `bazaarplusplus-server/`;mod 侧 HTTP 客户端在 `src/BazaarPlusPlus.ModApi/`。 - -## 文档 - -文档与代码冲突时,以实际实现为准。从 [docs/README.md](docs/README.md) 的文档索引开始;后续工作、需求与 bug 在 [GitHub Issues](https://github.com/BazaarPlusPlus/BazaarPlusPlus/issues)。 - -## License - -MIT License,见 [LICENSE](LICENSE)。 diff --git a/bazaarplusplus-mod/build/GameLibraries.props b/bazaarplusplus-mod/build/GameLibraries.props deleted file mode 100644 index 0998def..0000000 --- a/bazaarplusplus-mod/build/GameLibraries.props +++ /dev/null @@ -1,85 +0,0 @@ - - - - Newtonsoft.Json;MessagePack;MessagePack.Annotations - - Microsoft.NET.StringTools - - - - - - - - <_BppGameLibraryFile Include="@(BppGameLibrary);@(BppGameLibraryDependency)" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_BppGameLibrarySource - Include="$(ManagedPath)/%(_BppGameLibraryFile.Identity).dll" - Condition="Exists('$(TargetDir)%(_BppGameLibraryFile.Identity).dll')" - Copy="$(TargetDir)%(_BppGameLibraryFile.Identity).dll" - /> - - - - - - <_BppGameLibraryCopy - Include="%(_BppGameLibrarySourceHash.Copy)" - Expected="%(_BppGameLibrarySourceHash.FileHash)" - /> - - - - - - - diff --git a/bazaarplusplus-mod/build/ManagedPath.props b/bazaarplusplus-mod/build/ManagedPath.props deleted file mode 100644 index a9c25e0..0000000 --- a/bazaarplusplus-mod/build/ManagedPath.props +++ /dev/null @@ -1,90 +0,0 @@ - - - - $(MSBuildThisFileDirectory)game-libs.lock.json - $([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)', '..', 'game-libs')) - macos - windows - online - \d+\.\d+\.\d+(?:-[a-z0-9]+)*-(?:macos|windows)-[a-z0-9]+-[0-9a-f]+ - - - - - <_BppMacSteamRoot>$(HOME)/Library/Application Support/Steam/steamapps/common/The Bazaar - <_BppMacSteamManaged>$(_BppMacSteamRoot)/TheBazaar.app/Contents/Resources/Data/Managed - <_BppWinSteamRootC>C:\Program Files (x86)\Steam\steamapps\common\The Bazaar - <_BppWinSteamRootD>D:\Program Files (x86)\Steam\steamapps\common\The Bazaar - <_BppWinSteamRootE>E:\Program Files (x86)\Steam\steamapps\common\The Bazaar - - - $(_BppWinSteamRootC)\TheBazaar_Data\Managed - $(_BppWinSteamRootC) - - - $(_BppWinSteamRootD)\TheBazaar_Data\Managed - $(_BppWinSteamRootD) - - - $(_BppWinSteamRootE)\TheBazaar_Data\Managed - $(_BppWinSteamRootE) - - - $(_BppMacSteamManaged) - $(_BppMacSteamRoot) - - - - <_BppSteamGameData>$([System.IO.File]::ReadAllText('$(BppSteamManagedPath)/../globalgamemanagers')) - $([System.Text.RegularExpressions.Regex]::Match($(_BppSteamGameData), $(BppGameVersionPattern)).Value) - <_BppSteamGameData /> - - - - - <_BppLockText>$([System.IO.File]::ReadAllText('$(BppGameLibsLock)')) - <_BppLockEntry>$([System.Text.RegularExpressions.Regex]::Match($(_BppLockText), '"$(BppSnapshotPlatform)-$(BppSnapshotChannel)"\s*:\s*\{[^}]*\}').Value) - $([System.Text.RegularExpressions.Regex]::Match($(_BppLockEntry), '(?<="gameVersion"\s*:\s*")[^"]+').Value) - $(BppGameLibsRoot)$(BppSnapshotPlatform)-$(BppSnapshotChannel)-$(BppLockGameVersion)/Managed - - - $(BppSnapshotManagedPath) - snapshot - - - $(BppSteamManagedPath) - steam - - - - <_BppLockText /> - <_BppLockEntry /> - explicit - - - - - - - diff --git a/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/Program.cs b/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/Program.cs deleted file mode 100644 index f3f699e..0000000 --- a/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/Program.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Net.Http.Headers; -using BazaarPlusPlus.RemoteEmbeddedDataFetcher; - -try -{ - return args.Length == 0 - ? Usage() - : args[0] switch - { - "fetch" => await FetchAsync(args), - "promote" => Promote(args), - _ => Usage(), - }; -} -catch (Exception ex) -{ - Console.Error.WriteLine( - $"[BazaarPlusPlus] Remote embedded data operation failed: {ex.Message}" - ); - return 2; -} - -static async Task FetchAsync(string[] args) -{ - if (args.Length != 5 || !long.TryParse(args[3], out var minimumBytes)) - return Usage(); - - using var client = RemoteEmbeddedDataHttpClient.Create(TimeSpan.FromSeconds(30)); - client.DefaultRequestHeaders.UserAgent.Add( - new ProductInfoHeaderValue("BazaarPlusPlusBuild", args[4]) - ); - Console.WriteLine($"[BazaarPlusPlus] Downloading {args[1]} to {args[2]}"); - await RemoteEmbeddedDataFetch.FetchAsync( - client, - new RemoteEmbeddedDataRequest(new Uri(args[1]), args[2], minimumBytes) - ); - return 0; -} - -static int Promote(string[] args) -{ - if (args.Length < 4) - return Usage(); - var stagedDirectory = args[1]; - var canonicalDirectory = args[2]; - var seeds = args.Skip(3) - .Select(name => new SeedPromotion( - Path.Combine(stagedDirectory, name), - Path.Combine(canonicalDirectory, name) - )) - .ToArray(); - RemoteEmbeddedDataFetch.PromoteSeedSet(seeds); - return 0; -} - -static int Usage() -{ - Console.Error.WriteLine( - "Usage: RemoteEmbeddedDataFetcher fetch " - ); - Console.Error.WriteLine( - " RemoteEmbeddedDataFetcher promote ..." - ); - return 1; -} diff --git a/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataFetch.cs b/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataFetch.cs deleted file mode 100644 index e21625d..0000000 --- a/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataFetch.cs +++ /dev/null @@ -1,236 +0,0 @@ -#nullable enable -using System.Text; - -namespace BazaarPlusPlus.RemoteEmbeddedDataFetcher; - -internal readonly record struct RemoteEmbeddedDataRequest( - Uri Source, - string DestinationPath, - long MinimumBytes -); - -internal readonly record struct SeedPromotion(string StagedPath, string CanonicalPath); - -internal static class RemoteEmbeddedDataFetch -{ - private const int MaximumAttempts = 5; - private static readonly TimeSpan MaximumOperationTime = TimeSpan.FromMinutes(2); - - internal static async Task FetchAsync( - HttpClient client, - RemoteEmbeddedDataRequest request, - CancellationToken cancellationToken = default - ) - { - ArgumentNullException.ThrowIfNull(client); - if (request.MinimumBytes < 0) - throw new ArgumentOutOfRangeException(nameof(request)); - if (string.IsNullOrWhiteSpace(request.DestinationPath)) - throw new ArgumentException("A destination path is required.", nameof(request)); - - var directory = Path.GetDirectoryName(request.DestinationPath); - if (string.IsNullOrWhiteSpace(directory)) - throw new ArgumentException("The destination must have a directory.", nameof(request)); - Directory.CreateDirectory(directory); - - using var operationTimeout = CancellationTokenSource.CreateLinkedTokenSource( - cancellationToken - ); - operationTimeout.CancelAfter(MaximumOperationTime); - var operationToken = operationTimeout.Token; - - for (var attempt = 1; ; attempt++) - { - try - { - await FetchOnceAsync(client, request, operationToken).ConfigureAwait(false); - return; - } - catch (Exception ex) when (ShouldRetry(ex, operationToken, attempt)) - { - var delay = RetryDelay(attempt); - var rootCause = ex.GetBaseException(); - Console.Error.WriteLine( - $"[BazaarPlusPlus] Remote embedded data retry host={request.Source.IdnHost} attempt={attempt}/{MaximumAttempts} delay_ms={(int)delay.TotalMilliseconds} error={rootCause.GetType().Name} message={rootCause.Message}" - ); - await Task.Delay(delay, operationToken).ConfigureAwait(false); - } - } - } - - private static async Task FetchOnceAsync( - HttpClient client, - RemoteEmbeddedDataRequest request, - CancellationToken cancellationToken - ) - { - var temporaryPath = request.DestinationPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; - try - { - using var response = await client - .GetAsync( - request.Source, - HttpCompletionOption.ResponseHeadersRead, - cancellationToken - ) - .ConfigureAwait(false); - response.EnsureSuccessStatusCode(); - await using (var input = await response.Content.ReadAsStreamAsync(cancellationToken)) - await using ( - var output = new FileStream( - temporaryPath, - FileMode.CreateNew, - FileAccess.Write, - FileShare.None, - 81920, - useAsync: true - ) - ) - { - await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); - } - - ValidateTransport(temporaryPath, request.MinimumBytes); - File.Move(temporaryPath, request.DestinationPath, overwrite: true); - } - finally - { - if (File.Exists(temporaryPath)) - File.Delete(temporaryPath); - } - } - - private static bool ShouldRetry( - Exception exception, - CancellationToken cancellationToken, - int attempt - ) - { - if (attempt >= MaximumAttempts || cancellationToken.IsCancellationRequested) - return false; - - return exception switch - { - HttpRequestException { StatusCode: null } => true, - HttpRequestException { StatusCode: var statusCode } => statusCode - == System.Net.HttpStatusCode.RequestTimeout - || statusCode == System.Net.HttpStatusCode.TooManyRequests - || (int)statusCode >= 500, - TaskCanceledException => true, - _ => false, - }; - } - - private static TimeSpan RetryDelay(int attempt) - { - var exponentialMilliseconds = 200 * (1 << (attempt - 1)); - return TimeSpan.FromMilliseconds(exponentialMilliseconds + Random.Shared.Next(0, 101)); - } - - internal static void PromoteSeedSet(IReadOnlyList seeds) => - PromoteSeedSet(seeds, beforePromote: null); - - internal static void PromoteSeedSet( - IReadOnlyList seeds, - Action? beforePromote - ) - { - ArgumentNullException.ThrowIfNull(seeds); - if (seeds.Count == 0) - throw new ArgumentException("At least one seed is required.", nameof(seeds)); - foreach (var seed in seeds) - { - if (!File.Exists(seed.StagedPath)) - throw new FileNotFoundException("A staged seed is missing.", seed.StagedPath); - } - - var transactionRoot = Path.Combine( - Path.GetTempPath(), - "bpp-seed-promote-" + Guid.NewGuid().ToString("N") - ); - Directory.CreateDirectory(transactionRoot); - var backups = new string?[seeds.Count]; - try - { - for (var i = 0; i < seeds.Count; i++) - { - var canonical = seeds[i].CanonicalPath; - var directory = Path.GetDirectoryName(canonical); - if (string.IsNullOrWhiteSpace(directory)) - throw new ArgumentException("A canonical seed must have a directory."); - Directory.CreateDirectory(directory); - if (!File.Exists(canonical)) - continue; - backups[i] = Path.Combine(transactionRoot, i + ".backup"); - File.Copy(canonical, backups[i]!); - } - - try - { - for (var i = 0; i < seeds.Count; i++) - { - beforePromote?.Invoke(i); - ReplaceFromCopy(seeds[i].StagedPath, seeds[i].CanonicalPath); - } - } - catch - { - for (var i = 0; i < seeds.Count; i++) - { - if (backups[i] != null) - ReplaceFromCopy(backups[i]!, seeds[i].CanonicalPath); - else if (File.Exists(seeds[i].CanonicalPath)) - File.Delete(seeds[i].CanonicalPath); - } - throw; - } - } - finally - { - Directory.Delete(transactionRoot, recursive: true); - } - } - - private static void ValidateTransport(string path, long minimumBytes) - { - var length = new FileInfo(path).Length; - if (length < minimumBytes) - { - throw new InvalidDataException( - $"downloaded {length} bytes, below the required minimum of {minimumBytes} bytes" - ); - } - - using var reader = new StreamReader( - path, - Encoding.UTF8, - detectEncodingFromByteOrderMarks: true - ); - int next; - do - { - next = reader.Read(); - } while (next >= 0 && char.IsWhiteSpace((char)next)); - if (next != '{' && next != '[') - { - throw new InvalidDataException( - "the first non-whitespace character is neither '{' nor '['" - ); - } - } - - private static void ReplaceFromCopy(string source, string destination) - { - var temporaryPath = destination + "." + Guid.NewGuid().ToString("N") + ".tmp"; - try - { - File.Copy(source, temporaryPath); - File.Move(temporaryPath, destination, overwrite: true); - } - finally - { - if (File.Exists(temporaryPath)) - File.Delete(temporaryPath); - } - } -} diff --git a/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataFetcher.csproj b/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataFetcher.csproj deleted file mode 100644 index 75591be..0000000 --- a/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataFetcher.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - Exe - net10.0 - enable - enable - true - RemoteEmbeddedDataFetcher - BazaarPlusPlus.RemoteEmbeddedDataFetcher - - diff --git a/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataHttpClient.cs b/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataHttpClient.cs deleted file mode 100644 index 79c6e5c..0000000 --- a/bazaarplusplus-mod/build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataHttpClient.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System.Collections.Concurrent; -using System.Net; -using System.Net.Sockets; - -namespace BazaarPlusPlus.RemoteEmbeddedDataFetcher; - -internal readonly record struct RemoteConnectionAttempt( - string Host, - IPAddress Address, - int Attempt -); - -internal static class RemoteEmbeddedDataHttpClient -{ - internal static HttpClient Create(TimeSpan timeout) - { - var connector = new RotatingDnsConnector(attempt => - Console.Error.WriteLine( - $"[BazaarPlusPlus] Remote embedded data connection host={attempt.Host} address={attempt.Address} attempt={attempt.Attempt}" - ) - ); - var handler = new SocketsHttpHandler - { - ConnectCallback = connector.ConnectAsync, - ConnectTimeout = TimeSpan.FromSeconds(10), - PooledConnectionLifetime = TimeSpan.FromMinutes(1), - }; - return new HttpClient(handler) { Timeout = timeout }; - } -} - -internal sealed class RotatingDnsConnector -{ - private readonly Func> _resolve; - private readonly Func> _connect; - private readonly Action? _observeAttempt; - private readonly ConcurrentDictionary _addressesByHost = new( - StringComparer.OrdinalIgnoreCase - ); - private readonly ConcurrentDictionary _nextAddressByHost = new( - StringComparer.OrdinalIgnoreCase - ); - - internal RotatingDnsConnector(Action? observeAttempt = null) - : this(Dns.GetHostAddressesAsync, ConnectSocketAsync, observeAttempt) { } - - internal RotatingDnsConnector( - Func> resolve, - Func> connect, - Action? observeAttempt = null - ) - { - _resolve = resolve ?? throw new ArgumentNullException(nameof(resolve)); - _connect = connect ?? throw new ArgumentNullException(nameof(connect)); - _observeAttempt = observeAttempt; - } - - internal ValueTask ConnectAsync( - SocketsHttpConnectionContext context, - CancellationToken cancellationToken - ) => ConnectAsync(context.DnsEndPoint, cancellationToken); - - internal async ValueTask ConnectAsync( - DnsEndPoint endpoint, - CancellationToken cancellationToken - ) - { - var addresses = await ResolveAddressesAsync(endpoint.Host, cancellationToken) - .ConfigureAwait(false); - if (addresses.Length == 0) - throw new SocketException((int)SocketError.HostNotFound); - - List? failures = null; - for (var offset = 0; offset < addresses.Length; offset++) - { - var sequence = _nextAddressByHost.AddOrUpdate( - endpoint.Host, - addValue: 0, - static (_, current) => current == int.MaxValue ? 0 : current + 1 - ); - var address = addresses[sequence % addresses.Length]; - if ((sequence + 1) % addresses.Length == 0) - _addressesByHost.TryRemove(endpoint.Host, out _); - _observeAttempt?.Invoke( - new RemoteConnectionAttempt(endpoint.Host, address, sequence + 1) - ); - try - { - return await _connect(address, endpoint.Port, cancellationToken) - .ConfigureAwait(false); - } - catch (Exception ex) when (ex is SocketException or IOException) - { - (failures ??= new List()).Add(ex); - } - } - - throw new HttpRequestException( - $"Could not connect to any resolved address for {endpoint.Host}.", - failures is null ? null : new AggregateException(failures) - ); - } - - private async Task ResolveAddressesAsync( - string host, - CancellationToken cancellationToken - ) - { - if (_addressesByHost.TryGetValue(host, out var cached)) - return cached; - - var resolved = (await _resolve(host, cancellationToken).ConfigureAwait(false)) - .Where(IsSupported) - .Distinct() - .ToArray(); - return _addressesByHost.GetOrAdd(host, resolved); - } - - private static bool IsSupported(IPAddress address) => - address.AddressFamily == AddressFamily.InterNetwork - || (Socket.OSSupportsIPv6 && address.AddressFamily == AddressFamily.InterNetworkV6); - - private static async ValueTask ConnectSocketAsync( - IPAddress address, - int port, - CancellationToken cancellationToken - ) - { - var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) - { - NoDelay = true, - }; - try - { - await socket - .ConnectAsync(new IPEndPoint(address, port), cancellationToken) - .ConfigureAwait(false); - return new NetworkStream(socket, ownsSocket: true); - } - catch - { - socket.Dispose(); - throw; - } - } -} diff --git a/bazaarplusplus-mod/build/game-libs.lock.json b/bazaarplusplus-mod/build/game-libs.lock.json deleted file mode 100644 index fb89068..0000000 --- a/bazaarplusplus-mod/build/game-libs.lock.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "schemaVersion": 1, - "staleAfterDays": 30, - "entries": { - "macos-online": { - "gameVersion": "1.0.12651-prod-macos-arm64-d5cc730f", - "sha256": "270baaff5abe943c0d2b1bab4f306e9b3e7c276e50ed614768b34d9343dbc4d7", - "buildid": "25778800", - "steamBranch": "public", - "capturedAt": "2026-10-08T00:58:48.051Z" - }, - "macos-staging": { - "gameVersion": "1.0.12645-staging-macos-arm64-d5cc730f", - "sha256": "543762c245353bbb05157e9e195aafc06d27b34ce62843a7f541e10e66b2b390", - "buildid": "25761508", - "steamBranch": "staging", - "capturedAt": "2026-10-08T00:55:18.810Z" - }, - "macos-ptr": { - "gameVersion": "1.0.12254-ptr-macos-arm64-a2cd5c3b", - "sha256": "38a6da21c4e5dec66ad35ed6507a5f2ced9e1b04f9ecc8ef477d8b364e0d0cdb", - "buildid": "25141468", - "steamBranch": "public_test_realm", - "capturedAt": "2026-10-04T14:27:15.170Z" - }, - "windows-online": { - "gameVersion": "1.0.12650-prod-windows-x64-d5cc730f", - "sha256": "58342142e6ebad879cdfc0b61c42d58b6f12575d81212bac3f5b53d6c2da44ba", - "buildid": "25778800", - "steamBranch": "public", - "capturedAt": "2026-10-08T00:53:20.908Z" - }, - "windows-staging": { - "gameVersion": "1.0.12646-staging-windows-x64-d5cc730f", - "sha256": "747e1cecf7eadef1d2d28f98a144601f62d53429c3e3e270b93ed3799077254f", - "buildid": "25761508", - "steamBranch": "staging", - "capturedAt": "2026-10-08T02:22:12.464Z" - }, - "windows-ptr": { - "gameVersion": "1.0.12253-ptr-windows-x64-a2cd5c3b", - "sha256": "34c3f6dee51421bd883f4a28e2e4fcfef0486fa8a700e2971a13342b952c370b", - "buildid": "25141468", - "steamBranch": "public_test_realm", - "capturedAt": "2026-10-06T02:57:52.955Z" - } - } -} diff --git a/bazaarplusplus-mod/docs/ARCHITECTURE.md b/bazaarplusplus-mod/docs/ARCHITECTURE.md deleted file mode 100644 index 82511ae..0000000 --- a/bazaarplusplus-mod/docs/ARCHITECTURE.md +++ /dev/null @@ -1,104 +0,0 @@ -# BazaarPlusPlus Architecture - -How the plugin is assembled: startup and teardown order, the layer and assembly boundaries, the seams that more than one feature consumes, and where runtime data lives. Per-feature detail is disclosed under [architecture/](architecture/); this file covers only what holds across features. - -Terms used here are defined in [../CONTEXT.md](../CONTEXT.md). Why a boundary is where it is lives in [adr/](adr/), indexed one line each in [MEMORY.md](MEMORY.md). - -## Runtime Shape - -`Plugin.Awake()` resolves the game build channel via `GameBuildInfoResolver`, creates `BppComposition`, installs static facades such as `BppLog`, `BppPatchHost`, localization, settings dock entries, supporters, and hotkeys, applies Harmony patches per patch class, starts feature modules, builds the owner-scoped Mod API session and separate BazaarDB-link client, then mounts Unity components onto the plugin `GameObject` (`src/BazaarPlusPlus/Plugin.cs`). - -`BppComposition` is the manual composition root; there is no DI container. It receives the resolved `IGameBuildInfo` and wires feature modules through `BppFeatureRegistry`, Unity components through `BppMountableRegistry`, and in-game settings rows through `SettingsDockEntryRegistry` (`src/BazaarPlusPlus/BppComposition.cs`). Simple components mount through `ComponentMount`; a bespoke mount exists only where a feature owns additional dependencies or object lifecycles, and `CombatReplayRuntime` is the bootstrap exception because other modules need it before mountables run. - -Three ordering facts in this file are load-bearing, because each one fails silently when reordered: - -- **Patches apply per class** via `CreateClassProcessor(type).Patch()`, never `PatchAll()`. One broken game target (a game update, a PTR branch) then degrades only its own feature instead of aborting the whole plugin. -- **Teardown unmounts Unity components, disposes the composition (stopping pure features in reverse registration order), and only then destroys `CombatReplayRuntime`.** That lets Run Logging settle a deferred completion while replay persistence state is still readable. -- **The run-log database is released only after every writer is gone.** Microsoft.Data.Sqlite pools connections, so without an explicit release the native handle, the `-wal`/`-shm` files, and an uncheckpointed WAL all survive the process, and the installer would have to recover the database rather than read it. `SqliteShutdown.ReleaseRunLogDatabase` clears the pool, truncates the WAL, and clears again (`src/BazaarPlusPlus.Storage/Sqlite/SqliteShutdown.cs`). Static teardown then releases native font handles, scopes, and cloned font assets through `NativeGameTypography.Reset()`. - -## Game Build Channel And PTR Isolation - -`GameBuildInfoResolver` classifies the running client as Online, Ptr, or Unknown from the bundleVersion `-ptr` token plus a corroborating `TheBazaar.Config.ServerOption` type probe (`src/BazaarPlusPlus/GameInterop/GameBuildInfoResolver.cs`). A `-staging` version resolves directly to Ptr: staging lacks ServerOption, so its absence cannot establish a production client. Reusing the persisted Ptr category also excludes staging runs after switching back to Online. - -Disagreement resolves to **Ptr**, and the asymmetry is the whole reason. Classifying a PTR client as Online silently pollutes the production dataset and cannot be undone, while classifying an Online client as Ptr only pauses its uploads. The channel is injected into the composition, stamped onto recorded runs by `RunLoggingModule`, and `BundleSealCoordinator` excludes PTR runs before a bundle can enter the outbox. - -Newer-only combat events and enum members stay behind runtime adapters in `GameInterop/CombatSimulation`, so a Production build lacking them skips only the optional metrics. Premise tests live in `tests/RuntimeIntegration.Tests/GamePremiseCompatibilityTests.cs`. - -## Assemblies And Boundaries - -Four assemblies ship. - -| Assembly | Contents | -|---|---| -| `BazaarPlusPlus.dll` | the BepInEx plugin: Unity/game integration, feature modules, Harmony patches, embedded resources, composition root | -| `BazaarPlusPlus.ModApi.dll` | HTTP client, routes, DTOs, MessagePack/gzip helpers for the mod backend | -| `BazaarPlusPlus.Storage.dll` | SQLite schema, repositories, path interfaces, local persistence models | -| `BazaarPlusPlus.Localization.dll` | localization resolution engine, language and mode helpers | - -`ModApi`, `Storage`, and `Localization` keep **zero game, Unity, and BepInEx references**, an invariant enforced by architecture tests, not by the compiler. - -Inside the main assembly: - -| Directory | Owns | -|---|---| -| `Core/` | pure mod abstractions: config, event bus, runtime service interfaces, run context, path contracts, the run-snapshot contract | -| `GameInterop/` | adapters over game, Unity, or publicized runtime surfaces | -| `Game/` | feature workflows, UI, user-facing policy, filtering, upload orchestration, storage use | -| `Patches/` | Harmony patches, reaching services through `BppPatchHost` rather than constructor injection | -| `Infrastructure/` | cross-cutting logging, UI tokens, stable text helpers, generic seams | - -The main project targets `netstandard2.1`, uses C# 12, and publicizes game assemblies, so `internal` game members are accessible. Remote seed data is declared in `RemoteEmbeddedData.targets` and delegates transport to `build/RemoteEmbeddedDataFetcher`; `BppVersion` in `Directory.Build.props` reads the workspace-root `VERSION`. The shared Payload Inventory generates the MSBuild copy items; production assembly versions are checked from compiled metadata. `just release::prepare ` runs isolated preparation through the [product release coordinator](../../docs/release.md). - -Architecture tests ratchet dependency boundaries, shared ownership, and test/build safety contracts over compiled assemblies (`tests/Architecture.Tests/`, ADR-0009). Concrete composition behavior remains in `tests/CompositionRuntime.Tests/` and is compiled by `RuntimeIntegration.Tests`: feature start/stop is fault-isolated, while `BppMountableRegistry.MountAll` deliberately is not. - -## Shared Seams - -Each of these is consumed by two or more features. Reaching around one to re-implement its behavior inside a feature is the failure this section exists to prevent. - -| Seam | Owner | Consumers | -|---|---|---| -| Overlay panel lifecycle | `Game/OverlayPanels/OverlayPanelHost.cs` | Collection, History, LiveBuild | -| Native asset loading compatibility | `GameInterop/AssetLoading/` | Card preview, portraits, replay warmers | -| Native card preview | `GameInterop/CardPreview/` | Collection, combat recap | -| Native tooltip suppression | `GameInterop/Tooltips/NativeTooltipSuppression` | replay recording, end-of-run capture | -| Item board planning / native boards | `GameInterop/ItemBoardPreview/`, `GameInterop/MonsterBoardPreview/` | History, LiveBuild | -| Day tier resolution | `GameInterop/DayTiers/` | Collection's Day gate, Encounter Preview | -| Hero portraits | `GameInterop/HeroPortraits/` | History, LiveBuild, ghost rows | -| Text rendering | `GameInterop/Fonts/NativeGameTypography` | every BPP surface | -| Remote embedded catalogs | `Infrastructure/RemoteEmbeddedCatalog/` | voice lines, ten-win builds, supporters | -| Atomic payload files | `Infrastructure/` `FileBackedPayloadStore` | combat replay, ghost payloads | -| Deduped async loads | `Infrastructure/` `AsyncLoadCache` | hero and encounter portrait providers | -| Active scene name | `GameInterop/Scenes/ActiveSceneNameCache.cs` | Collection dock button, replay recording button | - -`RemoteEmbeddedCatalog` owns cache → embedded → remote loading with feature-supplied freshness: single-flight warm and refresh, per-caller cancellation over shared flights, typed outcomes, atomic cache writes, retry re-arming, monotonic publication, and generation-guarded disposal. A queued cold-start refresh takes ownership atomically when its refresh flight begins, so cancelling the originating warm flight before that handoff prevents the remote operation. Feature observers are serialized against disposal on a separate gate, so `TryGet` never waits for feature-side logging or index rebuilds. - -Operational logging is written at the call site: `BppLog.*Event(new BppLogEvent(scope, "dotted.snake.id", storm: [...]), ("name", value, policy)...)`, with the scope taken from the closed `BppLogFeatureScope` set and the id under that scope's prefix. Each line renders as `[BPP][] event= name=value ...` in call order; a field's `Short` or `Hash` policy shortens or hashes it at render time, and an attached exception renders as `exception_type=` plus the escaped `exception=` text. `BppLogPipeline` writes a warning once per storm key per window and summarizes the repeats; an error with a storm key merges on its correlation fields and exception type. Debug events compile out of Release (`src/BazaarPlusPlus/Infrastructure/Logging/Core/`). - -## Data And File Locations - -Runtime data that BazaarPlusPlus owns is rooted at `/BazaarPlusPlusV6/`. `BepInExPathProvider` exposes that single root, and storage and feature modules derive the SQLite database, bundle outbox, replay, ghost payload, screenshot, video, voice, LiveBuild, supporter, and Encounter Preview paths from it. No runtime cache uses the process temporary directory. - -The V6 database starts a new schema at `user_version` 1 with no migration path: `EnsureInitialized` creates an empty database or opens one already at 1 and refuses any other version, including a V5 database. Every instant is a Unix-millisecond `*_at_ms` integer; `RunPayloadComposer` copies them unchanged into the V6 Run segment. Beyond run facts, events, battles, snapshots, screenshots, and replay-video metadata it holds `bundle_seal_jobs` and a non-FK `bundle_outbox`; ghost rows carry remote bundle identity, presigned URL and expiry, and replay state. V4 sync cursors, dirty/checkpoint upload state, and independent screenshot upload state do not exist (`src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs`). - -## Event Flow - -An in-memory event bus decouples runtime coordination between feature modules registered at startup (`src/BazaarPlusPlus/BppComposition.cs` — the `Register` call order is the authoritative roster). - -`RunLoggingModule` is the feature-owned event intake. `Start` creates its replicated/queued store chain and session manager only after composition construction succeeds, subscribes once to run lifecycle, run initialization, PvP recording, and replay-drained events, then maps a matching `PVPCombat` manifest directly to persistence. Battles attach to the stable active or deferred run id before the event append and checkpoint. Interrupted runs stay resumable; normal completion owns an active, cancellable two-second replay-persistence deadline; `Stop` is a quiescence barrier that forces any deferred completion before unsubscribing and disposing the store. No Run Logging `MonoBehaviour` is mounted. Every time it writes comes from the module's one injected clock, which it hands to `RunLogRecordMapper` and `RunLogSessionManager`. `tests/RunLoggingPipeline.Tests` is its end-to-end anchor: it drives the real bus, queue, and SQLite stores from an empty database and fails unless the schema dump and per-step rows match `src/BazaarPlusPlus.Storage/history-database-v6.schema.sql` (the schema file the installer's tests load) and `tests/RunLoggingPipeline.Tests/fixtures/history-database-v6.rows.json` byte for byte. Regenerate them only with `BPP_UPDATE_GOLDENS=1` and review the diff (`HistoryDatabaseArtifacts`). - -PvP battle evidence is a shared `Game/PvpBattles` module rather than a `GameInterop` adapter; it captures local and opponent identities and board snapshots from live game state and net messages. - -## Per-feature detail - -Each feature doc ends with the Gotchas that bite only that feature. - -| To work on | Read | -|---|---| -| Collection filtering, sorting, the source catalog, grid virtualization | [architecture/collection.md](architecture/collection.md) | -| Opening or closing an overlay panel, HistoryPanel, LiveBuildPanel, item boards | [architecture/panels.md](architecture/panels.md) | -| Encounter Preview, native card previews, tooltip presentation | [architecture/previews.md](architecture/previews.md) | -| Combat replay, video recording, screenshots, bundle sealing, uploads, ghost battles | [architecture/capture.md](architecture/capture.md) | -| Desktop native build freshness, local promotion, and signing | [architecture/native-artifacts.md](architecture/native-artifacts.md) | -| Hotkey bindings and settings dock rows | [architecture/input-and-settings.md](architecture/input-and-settings.md) | -| Fonts, localization, voice subtitles, supporter attribution | [architecture/text.md](architecture/text.md) | -| The V6 bundle wire format | [contracts/run-payload-v6.md](contracts/run-payload-v6.md) | diff --git a/bazaarplusplus-mod/docs/MEMORY.md b/bazaarplusplus-mod/docs/MEMORY.md deleted file mode 100644 index f59cfd7..0000000 --- a/bazaarplusplus-mod/docs/MEMORY.md +++ /dev/null @@ -1,57 +0,0 @@ -# BazaarPlusPlus — Durable Memory - -What an agent cannot recover by reading the code in front of it, for any change: domain invariants, the decisions already settled, and the cross-feature traps that fail silently. A trap that bites only one feature lives in the Gotchas section of that feature's [architecture/](architecture/) doc; [ARCHITECTURE.md](ARCHITECTURE.md) routes to it. Rationale is in [adr/](adr/), process in [../AGENTS.md](../AGENTS.md). - -## Rules - -Constraints and patterns every change keeps. - -- MessagePack-serialized DTOs in the Unity/Mono runtime must keep their whole serialized graph `public`. -- Key entities by template GUID; package cards are `EHiddenTag.Package` via `PackageIdentity.IsPackage` — never display name or `ArtKey`. [`src/BazaarPlusPlus/GameInterop/Cards/PackageIdentity.cs`] -- Bump `RunLogSchema.LocalDatabaseSchemaVersion` only for a column change; a data repair never bumps it, and there is no upload-payload version. Index and trigger DDL needs no bump; open rebuilds an index whose SQL drifted from `BootstrapSql`, but a retired index or changed trigger needs a `DROP`. [`src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs` | ADR-0006 | ADR-0011] -- Mod-authored user-facing strings use `LocalizedTextSet` (en + zh-Hans, optional zh-Hant + de/pt/ko/it; anything else falls back to English). [`src/BazaarPlusPlus.Localization/LocalizedTextSet.cs`] -- A categorized degradation event names the category field in its call-site storm key, `storm: ["reason_code", ...]` — a shared key lets one category's failure suppress every later category during the storm window. A key naming a field with a correlation policy never suppresses. [`src/BazaarPlusPlus/Infrastructure/Logging/Core/BppLogPipeline.cs`] -- Anchor mod file-write paths on `BepInEx.Paths.GameRootPath` or `/BazaarPlusPlusV6/`, which BepInEx special-cases on macOS to the directory containing the `.app`. A path built from `Application.dataPath` writes unsealed files inside the `.app` bundle, breaking `codesign` re-signing and the trampoline repair — and therefore `just mod::build --deploy` after every game update. [`src/BazaarPlusPlus/Core/Paths/BepInExPathProvider.cs`] -- Reuse the game's native UI components (`CardPreviewBase.SetUp` and the like) and existing prior art instead of hand-rolling a render or upload chain. -- Keep Unity-adjacent logic free of Unity types and Compile-Include it into a test project, so the test needs no InternalsVisibleTo and no ManagedPath; a core that touches `BazaarGameShared` types still needs the game assemblies. [ADR-0005] - -## Architecture decisions - -One line each, full record in [adr/](adr/). A line here exists to stop a settled question from being reopened; the ADR says why. - -- ADR-0001: Expose run/encounter state via on-demand `IEncounterStateProbe`, not an event-sourced timeline tracker. -- ADR-0002: Replay exit is explicit — there is no programmatic `ReplayState` exit; ghost payloads are stored in recorder perspective, stamped by `PerspectiveVersion`. -- ADR-0003: Keep behavior-specific seams; a unification that only looks tidier is rejected. -- ADR-0004: One Collection `Destroy` chip covers the whole destroy-mechanic cluster on base templates; `TTriggerOnCardRepaired` is deliberately excluded. -- ADR-0005: Timing invariants live in pure decision cores, not MonoBehaviour glue. -- ADR-0006: Outbound Mod API rules each have one protocol or persistence owner. -- ADR-0007: Remote data separates runtime catalogs, the release manifest, and build-time seed fetch into three lifecycles. -- ADR-0008: Combat Impact numbers are ledger entries with typed residuals; attribution is graph-driven, never card-GUID constants. -- ADR-0009: Tests assert behavior or compiled artifacts, never source text; RS0030 bans file-to-text reads. -- ADR-0010: Compile against the game-supplied libraries in `build/GameLibraries.props`: no NuGet package, publicizing, or shipped copy. -- ADR-0011: The local `user_version` names the column shape the installer reads; data repairs never bump it. - - -## Gotchas - -Each of these failed silently, or reported something misleading, at least once. - -### Game runtime - -- Runtime `Card` tags do not carry static template tags — hidden *and* public (`DTOUtils.CreateCard` never copies them and snapshot updates overwrite) — derive identity from template tags and static data, merging runtime+template+enchantment as `CombatImpactEntityTags` does. [`decompiled/TheBazaarRuntime/TheBazaar/DTOUtils.cs` | `src/BazaarPlusPlus/Game/PostCombatImpact/Data/CombatImpactEntityTags.cs`] -- A generated IL2CPP `Nullable` property/method return wraps an empty native value in `new Nullable(IntPtr.Zero)`, which throws `NullReferenceException`; read card `Enchantment`/`Section`/`LeftSocketId` through `NativeCardOptionalFields` and other nullable returns through `NativeNullableResult`. [`src/BazaarPlusPlus/GameInterop/Cards/NativeCardOptionalFields.cs` | `src/BazaarPlusPlus/Infrastructure/NativeNullableResult.cs`] -- Static-data lookup is fallible on degraded and test paths: catch and return a safe default, as the current resolvers do. [`src/BazaarPlusPlus/GameInterop/GameBuildInfoResolver.cs`] -- A Harmony postfix on an `async Task` game method runs at the first await suspension, not at completion — bind pre-state in a **prefix**. -- A programmatic native `Button.onClick` invoke can return silently through interaction gates such as `AllowInteraction` without throwing — verify the expected game-state transition before treating the action as successful. -- `PublicizeAll` makes `ConfigEntry.SettingChanged` ambiguous (CS0229), so no BPP code subscribes to it; invalidate config-derived caches by raw-value compare. [`src/BazaarPlusPlus/Game/Input/BppHotkeyService.cs`] -- Portrait providers negative-cache exceptions past their service-readiness gates, so one transient asset-load exception caches a null portrait until restart. Preserved by design through the `AsyncLoadCache` migration — changing it is a behavior change. [`src/BazaarPlusPlus/GameInterop/HeroPortraits/`] -- `AssetLoader` signatures vary by game build; route them through `NativeAssetLoaderInvocation`. Process-static caches must load `Global` because scene-scope handles die across lobby↔run; smoke native cards and hero chips across that transition. [`src/BazaarPlusPlus/GameInterop/AssetLoading/`] -- A Harmony postfix whose `__result` is a reference-bearing struct wider than 16 bytes (`CardTooltipData.GetPassiveTooltipBlock` returns `ValueTuple`) SIGSEGVs ARM64 IL2CPP at the first card tooltip: the detour's return-buffer copy hands the postfix non-pointer data that it dereferences. A by-value `Nullable` parameter fails the same way: AAPCS64 passes it in a register and the detour reads that as a pointer (`HeroBannerController.SetLeaderboardPosition` / `UpdatePlayer`, AccessViolationException at the main menu). Keep every such patch behind `[HarmonyPrepare] => false` under `BPP_ANDROID`. [`src/BazaarPlusPlus/Patches/CollectionPanel/CollectionTierTooltipPatch.cs` | `src/BazaarPlusPlus/Patches/Tooltips/PackageMerchantSummaryTooltipPatch.cs` | `src/BazaarPlusPlus/Patches/LegendaryPosition/LegendaryPositionDisplayPatches.cs`] - -### Build and tests - -- Source-shadow scenario capsules pin production files through explicit Compile-Include and may define mutually incompatible runtime shims. Keep them in the closed `BppScenarioRunnerProjects` list and execute them only through the process-isolated `ScenarioRunner.Tests` host; `dotnet run --project tests//.csproj` only diagnoses one capsule. [`Directory.Build.props` | `tests/ScenarioRunner.Tests/`] -- Architecture-test file sweeps (absence assertions, reference scans) must enumerate from the `src/` and `tests/` roots, never recurse from the repo root — embedded worktrees such as `.claude/worktrees/` hold stale checkouts that still contain removed code and turn the sweep red. [`tests/Architecture.Tests/CoreLayeringTests.cs`] -- `rg 'new TypeName('` misses target-typed `new(...)` call sites, so a "zero call sites" grep proves nothing; prove a deletion by deleting (AGENTS.md, Build and test). [`tests/PureBehavior.Tests/PureBehavior.Tests.csproj`] -- `src/` and `tests/` both set `BppEnableWarningGate`, so `TreatWarningsAsErrors` turns an unused using (IDE0005) or an unread private field (CS0414) into a build error. [`Directory.Build.props` | `src/Directory.Build.props`] -- Some `*.Tests` directories own no `.csproj`; directory wildcards in two host projects absorb their sources. Deleting or renaming one leaves its wildcard matching zero Compile items instead of failing, so those tests silently stop running. [`tests/PureBehavior.Tests/PureBehavior.Tests.csproj` | `tests/RuntimeIntegration.Tests/RuntimeIntegration.Tests.csproj`] diff --git a/bazaarplusplus-mod/docs/README.md b/bazaarplusplus-mod/docs/README.md deleted file mode 100644 index e6c1869..0000000 --- a/bazaarplusplus-mod/docs/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# BazaarPlusPlus Docs - -The documentation inventory, and the mod-specific rules for changing it. `AGENTS.md`'s header table decides when to open each document; the repo-wide documentation policy is in `../AGENTS.md`. - -## Inventory - -- [MEMORY.md](MEMORY.md) — invariants, settled decisions, and cross-feature traps that fail silently. -- [ARCHITECTURE.md](ARCHITECTURE.md) — how the plugin is assembled and what seams are shared, with per-feature detail under [architecture/](architecture/). -- [../CONTEXT.md](../CONTEXT.md) — the glossary. -- [adr/](adr/) — decision records. -- [contracts/](contracts/) — wire and payload formats that outlive any one implementation. -- [../README.md](../README.md) — the human entry point: features, install, quick start. - -## Decision records - -Every record in [adr/](adr/) is accepted; filenames carry the topic, and [MEMORY.md](MEMORY.md)'s "Architecture decisions" section is the one-line index. An ADR keeps the decision, its load-bearing rationale, guardrails, and current code evidence, and may be corrected or compressed when the code drifts. A record whose decision has become plain system description is retired: its residual value moves into ARCHITECTURE or MEMORY and the file is deleted. Numbers are never reused, so the sequence may have gaps; retired records live in git history. - -## Document lifecycle - -Each layer owns one thing, and links rather than restating: `AGENTS.md` owns process, `MEMORY.md` knowledge, `ARCHITECTURE.md` structure, `adr/` rationale, GitHub issues the work. - -**Work goes to GitHub issues** ([issue tracker](../../docs/agents/issue-tracker.md)). Task plans, feature requests, bugs, acceptance checklists, implementation orders, and "pending confirmation" notes are issues. A document here describes how the system is, not what someone intends to do next. - -**Knowledge lands in its destination directly; there is no drafts buffer.** A design record, root-cause analysis, or decision analysis produced mid-session distills straight into MEMORY, an ADR, or ARCHITECTURE in the same session; remaining work goes to a GitHub issue; nothing is parked in the tree awaiting a later sweep. - -**Edit policy.** `ARCHITECTURE.md`, `architecture/`, `contracts/`, and `adr/` may be corrected the moment the code drifts. `MEMORY.md` and this file take dense one-line entries directly; the byte budgets below are what keep them curated. Point at the test that pins a number instead of restating the number; a count in prose drifts silently. - -**Budgets are in bytes, not lines.** `AGENTS.md` and `MEMORY.md` carry dense one-line entries, so a line count says nothing about what they cost an agent. The enforced ceilings live in `tests/Architecture.Tests/DocsHygieneTests.cs`; keeping under them means merging entries, not appending. A gotcha is never compressed to hit a budget; one that bites a single feature moves to the Gotchas section of that feature's `architecture/` doc, which is read only when that feature changes. - -## Historical material - -Retired documents live only in git history. The last complete `docs/archive/` tree is recoverable at commit `82412f0c` (`git show 82412f0c:docs/archive/`). Recheck any historical claim against current code before acting on it. diff --git a/bazaarplusplus-mod/docs/adr/0001-encounter-status-probe-not-timeline-tracker.md b/bazaarplusplus-mod/docs/adr/0001-encounter-status-probe-not-timeline-tracker.md deleted file mode 100644 index 54a6259..0000000 --- a/bazaarplusplus-mod/docs/adr/0001-encounter-status-probe-not-timeline-tracker.md +++ /dev/null @@ -1,17 +0,0 @@ -# ADR-0001: Query current encounter state; do not record a timeline - -Status: Accepted - -## Decision - -Expose current encounter state through the pull-based `IEncounterStateProbe`: cheap encounter ids and choice/pedestal classification. Do not turn this seam into an event-sourced run timeline. - -## Why - -A timeline needs explicit attribution for rerolls, interrupts, PVP combat, item transforms, and recovery gaps. No shipped consumer requires that history; current UI consumers need only “what is true now.” - -## Guardrails - -- Keep reads split by cost and main-thread only; the implementation caches each result per frame ([interface](../../src/BazaarPlusPlus/Core/GameState/IEncounterStateProbe.cs), [implementation](../../src/BazaarPlusPlus/GameInterop/Encounter/EncounterStateProbe.cs)). -- Consumers may share pure identity resolvers, but must not infer historical ordering from probe snapshots. -- Reopen only for a concrete persisted or uploaded timeline consumer with explicit attribution and recovery semantics. diff --git a/bazaarplusplus-mod/docs/adr/0002-replay-exit-and-ghost-perspective.md b/bazaarplusplus-mod/docs/adr/0002-replay-exit-and-ghost-perspective.md deleted file mode 100644 index 49e79d8..0000000 --- a/bazaarplusplus-mod/docs/adr/0002-replay-exit-and-ghost-perspective.md +++ /dev/null @@ -1,20 +0,0 @@ -# ADR-0002: Replay exit is explicit and single-owner - -Status: Accepted - -## Decision - -Nothing exits `ReplayState` on a tick or a timer. There is no programmatic `ReplayState` exit: the native recap continue click and the bootstrapped `Exit()` prefix are the only exit paths. - -## Why - -A replay remains in `ReplayState` after playback ends. Video finalization depends on the eventual exit, so a tick-driven auto-exit races whoever is orchestrating the replay and can orphan a recording. Exit timing must stay explicit and owned by one caller. - -## Guardrails - -- Do not add a programmatic `ReplayState` exit. Bootstrapped saved replays leave through the `Exit()` prefix, which routes into `CombatReplayRuntime.TryExitBootstrappedSavedReplayToMenu` ([runtime](../../src/BazaarPlusPlus/Game/CombatReplay/CombatReplayRuntime.cs)). -- Keep replay transport primitive and policy-free: one recording per battle; batching and concatenation stay external. Mid-playback skipping remains out of scope; phase races fail safely and retry on a later snapshot. - -## Ghost payload perspective contract - -The manifest inside a ghost replay payload always uses the recorder perspective: the challenger occupies the `Player` side. `GhostBattlePayload.PerspectiveVersion` identifies the stored convention: `0` is the legacy local perspective and is migrated automatically when loaded; `1` is the recorder perspective. External delivery must send ghost payloads with `PerspectiveVersion = 1`. diff --git a/bazaarplusplus-mod/docs/adr/0003-preserve-behavior-specific-boundaries.md b/bazaarplusplus-mod/docs/adr/0003-preserve-behavior-specific-boundaries.md deleted file mode 100644 index 82f2583..0000000 --- a/bazaarplusplus-mod/docs/adr/0003-preserve-behavior-specific-boundaries.md +++ /dev/null @@ -1,22 +0,0 @@ -# ADR-0003: Preserve behavior-specific boundaries; reject cosmetic unification - -Status: Accepted - -## Decision - -Share a seam only when its consumers share behavior, ownership, and lifecycle. Preserve these deliberate boundaries: - -- `IGameStateProbe` and `IRunContext` remain separate active seams; configuration is the concrete `BppConfig`. -- HistoryPanel replay, health, account-link, and ghost-sync operations retain separate handlers because their cancellation, rollback, and status semantics differ. `HistoryPanelCoordinator` remains their single mutable-state owner; showing the panel resets replay/account-link state while preserving in-flight ghost sync and health probes ([coordinator](../../src/BazaarPlusPlus/Game/HistoryPanel/HistoryPanelCoordinator.cs)). -- Enchant-section normalization preserves multiline content; quest-reward normalization trims and joins lines. Each keeps its own formatter ([enchant](../../src/BazaarPlusPlus/Game/ItemEnchantPreview/ItemEnchantPreviewFormatting.cs), [quest](../../src/BazaarPlusPlus/Patches/Tooltips/QuestRewardPreviewTooltipPatch.cs)). -- Collection facet availability is recomputed beside catalog publication in `CollectionViewState`, not attached to catalog results or repeated on refresh ([state](../../src/BazaarPlusPlus/Game/CollectionPanel/CollectionViewState.cs)). -- Feature and mountable order follows explicit dependency evidence. Registration order and reverse teardown are already pinned by executable tests ([feature tests](../../tests/CompositionRuntime.Tests/BppFeatureRegistryTests.cs), [mountable tests](../../tests/CompositionRuntime.Tests/BppMountableRegistryTests.cs)). -- Mod API endpoints share bounded response parsing, request correlation, and retry extraction, while Bundle, Ghost, BazaarDB, and health retain their own outcome types and product mappings. - -## Why - -These surfaces look similar but fail, recover, and publish state differently. A generic wrapper would move those differences into configuration or introduce an abstraction with no second behavioral consumer. - -## Guardrail - -Reopen one boundary at a time, with code evidence that its behavior and ownership now match the proposed peer. Visual repetition alone is not evidence. diff --git a/bazaarplusplus-mod/docs/adr/0004-merged-destroy-collection-filter.md b/bazaarplusplus-mod/docs/adr/0004-merged-destroy-collection-filter.md deleted file mode 100644 index e320798..0000000 --- a/bazaarplusplus-mod/docs/adr/0004-merged-destroy-collection-filter.md +++ /dev/null @@ -1,29 +0,0 @@ -# ADR-0004: One Destroy chip covers the full destroy-mechanic cluster - -Status: Accepted - -## Decision - -The Collection Panel exposes one `CollectionMechanic.Destroy` flag and one primary-section chip. A card matches when its base template contains any of these facts: - -| Surface | Match | -| --- | --- | -| Action | `TActionCardDestroy`, `TActionCardRepair`, or `TActionCardTransformDestroyed`, including under `TActionAnd` | -| Trigger | `TTriggerOnBeforeCardDestroyed`, `TTriggerOnCardDestroyed`, or `TTriggerOnCardPerformedDestruction`, including under `TTriggerOr` | -| Hidden tag | `EHiddenTag.AbsorbDestroy`, mapped into Destroy rather than exposed as a keyword chip | -| Attribute | Positive base `ECardAttributeType.DestroyImmunity` at any supported tier | - -The projection excludes `TTriggerOnCardRepaired`, abilities spawned by `TActionCardTransformDestroyed`, enchantment-provided facts, text matches, and inactive abilities absent from every tier's `AbilityIds`. Product copy stays on the game's native Destroy label; no second “Destroy Related” chip exists. - -## Why - -Players search for the whole destruction mechanic, not only active `TActionCardDestroy` effects. Splitting reactions, repair, replacement, absorb, and immunity into another chip would divide one mental category and make Any/All combinations necessary. - -## Guardrails - -- Project once at the catalog VM boundary through [`CollectionCardVm.From`](../../src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionCardVm.From.cs) and [`CollectionMechanicFacts.Project`](../../src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionMechanicFacts.cs). Filtering and refreshes consume the cached flag; architecture tests keep effect-graph types off those paths ([tests](../../tests/Architecture.Tests/CollectionMechanicArchitectureTests.cs)). -- Traverse active actions and triggers once per card, with base attributes in the tier loop. -- Keep `AbsorbDestroy` off `CollectionKeywordWhitelist.Ordered`; its hidden-tag mapping feeds only the Destroy mechanic. -- Reclassifying `TTriggerOnCardRepaired` or splitting the cluster requires a new product decision. - -Executable semantics live in [`CollectionFilterEngine.Tests`](../../tests/CollectionFilterEngine.Tests/Program.cs). diff --git a/bazaarplusplus-mod/docs/adr/0005-pure-decision-cores-for-timing-invariants.md b/bazaarplusplus-mod/docs/adr/0005-pure-decision-cores-for-timing-invariants.md deleted file mode 100644 index 994bb33..0000000 --- a/bazaarplusplus-mod/docs/adr/0005-pure-decision-cores-for-timing-invariants.md +++ /dev/null @@ -1,25 +0,0 @@ -# ADR-0005: Timing invariants live in pure decision cores, not MonoBehaviour glue - -Status: Accepted - -## Context - -Runtime orchestration used to hold race-safety and timing state inside `MonoBehaviour` callbacks. The behavior was difficult to exercise without Unity, while source-shape assertions could only prove that tokens appeared in an expected order. - -## Decision - -Put orchestration state algebra in pure decision cores. A core accepts observations and relative time, owns transitions, and returns decisions; the runtime translates those decisions into Unity, I/O, and publication effects. - -A pure core is effect-free, not necessarily dependency-free. Use the smallest real domain dependency and keep Unity types, held delegates, clocks, files, codecs, and runtime objects outside. Do not invent mirror enums solely to make a source file compile without game assemblies. - -## Load-bearing guardrails - -- [`SavedReplayLifecycle`](../../src/BazaarPlusPlus/Game/CombatReplay/SavedReplayLifecycle.cs) commits replay start in three stages, decides exit in two phases around the ended publication, and owns one 15-second suppression latch shared by the bootstrapped and native exits. Pending menu return and start progress are parallel states. -- [`CollectionViewState`](../../src/BazaarPlusPlus/Game/CollectionPanel/CollectionViewState.cs) returns `null` for a same-value no-op. Catalog-driven hero normalization does not write the user's preference; grid unavailability does not trigger normalization write-back or cache invalidation; the run day used by open selection is captured when the panel opens. -- [`BackgroundUploadPump`](../../src/BazaarPlusPlus/Game/Upload/BackgroundUploadPump.cs) has a two-point shutdown: release arm subscriptions first, then dispose the feed session after the drain callback. This keeps in-flight attempts away from disposed resources. -- [`BundleSealConvergence`](../../src/BazaarPlusPlus/Game/BundlePipeline/BundleSealConvergence.cs) receives relative time and input facts and returns continue, wait, degradation, or terminal decisions. Its failure half, `BundleSealFailurePolicy`, classifies a failure by walking the whole exception graph (an environment link anywhere wins) and decides retry backoff, once-per-launch parking, reseal, degradation, or termination; every exception the seal path catches is logged through its decision, while convergence terminals and failures to write the queue row log directly. Storage parses persisted UTC time and the coordinator performs the one relative-time translation. -- [`EndOfRunCleanFramePreparationCore`](../../src/BazaarPlusPlus/Game/Screenshots/EndOfRunCleanFramePreparationCore.cs) owns the bounded post-tooltip-cleanup pose window and the wait/clean-capture/degraded-capture decision. The Unity attempt supplies native visibility audits, structural card snapshots, and relative time; clean-frame proof is best-effort and cannot by itself suppress the end-of-run artifact. - -## Evidence - -Behavior tests exercise the cores directly: [`SavedReplayLifecycleTests`](../../tests/PureBehavior.Tests/SavedReplayLifecycleTests.cs), [`CollectionViewState.Tests`](../../tests/CollectionViewState.Tests/), and [`BundleSealConvergence.Tests`](../../tests/BundleSealConvergence.Tests/). diff --git a/bazaarplusplus-mod/docs/adr/0006-outbound-network-ownership.md b/bazaarplusplus-mod/docs/adr/0006-outbound-network-ownership.md deleted file mode 100644 index 366283d..0000000 --- a/bazaarplusplus-mod/docs/adr/0006-outbound-network-ownership.md +++ /dev/null @@ -1,36 +0,0 @@ -# ADR-0006: Outbound Mod API rules have protocol and persistence owners - -Status: Accepted - -## Context - -Bundle composition and Ghost import once carried different replayability rules, endpoint clients repeated response parsing, transport lifetime leaked through a client bag, and Bundle queue SQL was split across Game workflows. The shared protocol rules needed one owner without collapsing distinct endpoint behavior. - -## Decision - -### Wire contract - -[`RunBundleV6Contract`](../../src/BazaarPlusPlus.ModApi/Bundle/RunBundleV6Contract.cs) is the shared Run Bundle reader/writer. It verifies the container, payload, Run and player identities, and the exact replayability predicate. `BundleV6Codec` remains an opaque container codec. - -[`ModApiResponse`](../../src/BazaarPlusPlus.ModApi/Http/ModApiResponse.cs) is the single bounded JSON-response reader. It owns nested and legacy envelope recognition, request-ID precedence, `Retry-After`, and the closed user-facing code. Endpoint clients explicitly allow-list remote codes that change product behavior and keep their own disposition, cooldown, expiry, and presentation mappings. Raw bodies and exceptions remain diagnostics rather than user text. - -`MessagePackGzipFraming` owns bounded gzip framing and failure classification. `RunPayloadV6Codec` owns payload limits, untrusted-data options, version checks, and Run payload error codes. The local replay codec retains its compatibility and user-text behavior. - -### Transport lifetime - -[`ModApiSession`](../../src/BazaarPlusPlus.ModApi/Clients/ModApiSession.cs) owns one normalized route set, one configured `HttpClient`, typed Bundle/Ghost/health operations, and one disposal boundary. Plugin History, each upload-feed activation, and tools own independent sessions. BazaarDB remains separate because it has a different host and workflow. - -The API base URL is a constant; failing to construct the session fails plugin startup. - -### Durable queue - -[`BundleQueueStore`](../../src/BazaarPlusPlus.Storage/BundleQueue/BundleQueueStore.cs) alone owns `bundle_seal_jobs` and `bundle_outbox` SQL, row materialization, and their transactions. Allocation is idempotent; publication verifies allocation and atomically creates the outbox row before deleting the seal job; invalid artifacts fail and schedule reseal in one transaction. - -Storage owns neither Bundle files nor codecs, HTTP, upload, or retention policy. Game reaches files through [`IBundleOutboxFiles`](../../src/BazaarPlusPlus/Game/BundlePipeline/BundleOutboxFiles.cs), drives seal timing through [`BundleSealConvergence`](../../src/BazaarPlusPlus/Game/BundlePipeline/BundleSealConvergence.cs), commits an accepted upload before deletion, and retains artifacts for transient outcomes. Tests use the concrete Storage module against temporary SQLite databases; an interface is reserved for substitutable effects, not mirrored shapes. - -## Guardrails - -- Keep protocol parsing in ModApi, durable queue state in Storage, and orchestration/product mappings in Game. -- Keep endpoint outcomes typed by behavior; a generic `Result` must not encode their differences as configuration. -- Keep one transport owner per consumer session; no process-global transport or public endpoint-client bag. -- Keep Bundle file policy out of Storage and keep one active queue path. diff --git a/bazaarplusplus-mod/docs/adr/0007-remote-data-and-release-boundaries.md b/bazaarplusplus-mod/docs/adr/0007-remote-data-and-release-boundaries.md deleted file mode 100644 index 30cf6c7..0000000 --- a/bazaarplusplus-mod/docs/adr/0007-remote-data-and-release-boundaries.md +++ /dev/null @@ -1,26 +0,0 @@ -# ADR-0007: Remote data separates runtime catalogs, release manifests, and build seed fetch - -Status: Accepted - -## Context - -Runtime catalogs, the release manifest, and production build seeds are all remote data, but they have different owners, freshness rules, validation, and failure recovery. Sharing an HTTP primitive does not make them one lifecycle. - -## Decision - -| Lifecycle | Owner and contract | -| --- | --- | -| Supporter runtime catalog | [`SupporterCatalogModule`](../../src/BazaarPlusPlus/Game/Supporters/SupporterCatalogModule.cs) owns an `IRemoteEmbeddedCatalog` session. Fixed-list mode creates no catalog; normal mode publishes a session-stable snapshot, retries a missing snapshot after five minutes, and rejects late publications after disposal. The static facade contains projection and fixed-list policy only. | -| Release manifest | [`ReleaseManifestClient`](../../src/BazaarPlusPlus/Infrastructure/ReleaseManifest/ReleaseManifestClient.cs) maps the installer manifest request into typed outcomes. [`ReleaseManifestCheckLifecycle`](../../src/BazaarPlusPlus/Game/Lobby/ReleaseManifestCheckLifecycle.cs) owns request generation, cancellation, disposal, and the current-request publication gate. This request is separate from Mod API health and `ModApiSession`. | -| Build seed fetch | [`RemoteEmbeddedDataFetcher`](../../build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataFetch.cs) stages one streamed download, checks transfer integrity, and cleans temporary files. `just mod::fetch-data` stages the complete seed set, runs feature-owned semantic parsers, then promotes the set transactionally with rollback. | - -## Why - -One shared lifecycle would make a long-lived cached catalog, a short-lived UI request, and a pre-compilation transaction pretend to share cancellation and publication semantics. It would also create a second schema owner if the transport layer validated feature payloads. - -## Guardrails - -- Share HTTP primitives only where their contracts match; keep the three lifecycles independent. -- Gate every asynchronous publication by the current owner generation and dispose the owner exactly once. -- Keep feature parsers as the semantic source of truth for seed data. -- Promote a build seed set only after every member passes validation; a failure leaves the canonical set unchanged. diff --git a/bazaarplusplus-mod/docs/adr/0008-combat-impact-accounting-contract.md b/bazaarplusplus-mod/docs/adr/0008-combat-impact-accounting-contract.md deleted file mode 100644 index bf8c007..0000000 --- a/bazaarplusplus-mod/docs/adr/0008-combat-impact-accounting-contract.md +++ /dev/null @@ -1,32 +0,0 @@ -# ADR-0008: Combat Impact numbers are ledger entries, reconciled per view - -Status: Accepted - -## Context - -Combat Impact used to place effect applications, activation observations, amounts, and durations beside native totals as if they formed one additive breakdown. Values had different dimensions and evidence bases, while failed attribution disappeared during projection. - -## Decision - -Every displayed number carries dimension, basis, coverage, and provenance in the `CombatImpactEvent` ledger. - -- Additive breakdowns require the same dimension and basis; every non-zero remainder bucket stays in the internal ledger. Attribution gaps and accounting diagnostics are not player-facing tooltip copy. -- Native application-count controls stay internal, even when comparable. The tooltip shows the recorded effect count and gameplay amount or duration without appending a second count such as `cards affected` or `applications`. Native damage, healing, and shield amounts remain gameplay totals to display ([formatter](../../src/BazaarPlusPlus/Game/PostCombatImpact/Data/CombatImpactMetricFormatter.cs)). -- Conservation is per view. The received view intentionally omits hero/player targets, so no caused-versus-received grand total exists ([tests](../../tests/PostCombatImpact.Tests/CombatImpactAggregatorTests.cs)). -- `ObservedActivationBatchCount` is a distinct trigger-source/frame observation, never an exact trigger count or an application count ([models](../../src/BazaarPlusPlus/Game/PostCombatImpact/Data/CombatImpactModels.cs)). -- Producer-assigned `CombatImpactTriggerScope` distinguishes external, self, trigger-fallback, no-evidence, unattributed, and not-applicable provenance. Rejected trigger, target, source, and value evidence survives as typed residuals. -- `CombatImpactAmountLedger` keeps authoritative totals and observed amounts separate. A numeric residual exists only for comparable semantics, unit, and direction; a negative difference is an `OverObserved` diagnostic. -- Periodic attribution returns allocations and residuals with an `Exact` or `Proportional` proof. Presentation may hide a complete pure-self breakdown but never deletes its ledger entries. - -## Producer boundary - -Attribution follows the native ability graph, never card identity. [`CombatImpactAttributionRuleReader`](../../src/BazaarPlusPlus/Game/PostCombatImpact/Data/CombatImpactAttributionRuleReader.cs) reads structural rules, [`CombatImpactProjector`](../../src/BazaarPlusPlus/Game/PostCombatImpact/Data/CombatImpactProjector.cs) reconciles explicit executions with native metrics, and [`CombatImpactEntityTags`](../../src/BazaarPlusPlus/Game/PostCombatImpact/Data/CombatImpactEntityTags.cs) merges runtime, template, and enchantment tags needed after replay rehydration. Metrics stay attached to the instance that produced them. - -Critical attribution is evidence-bounded. A critical outcome requires a native critical health adjustment, an exact unambiguous doubled amount, or an executed `TTriggerOnCardCritted` ability whose source identifies the originating card. The listener path attaches one occurrence to a representative explicit effect and deduplicates stronger evidence. The listener execution is only evidence about the originating activation: its derived action is normalized as non-critical and cannot become the origin or an ambiguous-recovery candidate. Without one of those proofs, the outcome remains unknown. - -## Guardrails - -- Keep per-view conservation; never add a caused-versus-received equation. -- Keep authoritative and observed amounts separate, and preserve every typed residual. -- Present frame-derived activation batches as observations until the producer exposes stable activation identity. -- Extend attribution through ability-graph evidence, never template GUID constants or cross-source metric transfer. diff --git a/bazaarplusplus-mod/docs/adr/0009-tests-assert-behavior-or-compiled-artifacts.md b/bazaarplusplus-mod/docs/adr/0009-tests-assert-behavior-or-compiled-artifacts.md deleted file mode 100644 index 36ade18..0000000 --- a/bazaarplusplus-mod/docs/adr/0009-tests-assert-behavior-or-compiled-artifacts.md +++ /dev/null @@ -1,26 +0,0 @@ -# ADR-0009: Tests assert behavior or compiled artifacts, never source text - -Status: Accepted - -## Context - -Architecture and capsule tests read `.cs`, scripts, and headers as strings and asserted with `Contains`. Those checks broke on formatting, missed target-typed `new(...)`, and could not tell a real call from a comment. The replacement has to stay buildable under locked restore and `TreatWarningsAsErrors`. - -## Decision - -1. Prefer a behavior test. When the fact is structural, read the assemblies produced by the same build (metadata / IL / PDB). MSBuild and JSON are parsed as documents. Scripts and targets are executed. Native sources are checked with clang on a toolchain lane. S2 adds a Debug+Release IL scan so `#else` bodies in a Release build stay visible. Roslyn is not a test dependency. -2. Literal rules apply only to runtime data (SQL, header tokens, path segments) and match whole words. A rule's scope and its forbidden target must both resolve. -3. RS0030 (`tests/BannedSymbols.txt`) forbids test code from reading a file as text. The only exemptions are `{src,build}/**` Compile-Includes, `tests/Shared/TestFiles/**`, and `tests/CombatImpact.Corpus/**`. The debt list in `tests/.editorconfig` only shrinks. `File.OpenRead` plus `StreamReader(Stream)` stays open for loopback and zip; review those. - -Accepted gaps: IL does not show which parameter slot received a value; a field's declaring partial file is not a runtime fact (methods that touch it still map through the PDB); Windows native compiler flags and hosts without a native toolchain stay platform-gated. - -## Guardrails - -- Do not add `Microsoft.CodeAnalysis.CSharp` to satisfy an architecture rule. -- Do not grow the RS0030 debt list. A new file-to-text read fails the build. -- Enumerate architecture sweeps from `src/` and `tests/`, never the repo root. - -## Evidence - -- Ban and `TestInputs`: `tests/BannedSymbols.txt`, `tests/Shared/TestFiles/TestInputs.cs`, `tests/Architecture.Tests/SourceTextBanTests.cs` -- Debt list: `tests/.editorconfig` diff --git a/bazaarplusplus-mod/docs/adr/0010-compile-against-game-supplied-libraries.md b/bazaarplusplus-mod/docs/adr/0010-compile-against-game-supplied-libraries.md deleted file mode 100644 index d4131fb..0000000 --- a/bazaarplusplus-mod/docs/adr/0010-compile-against-game-supplied-libraries.md +++ /dev/null @@ -1,27 +0,0 @@ -# ADR-0010: Compile against game-supplied libraries - -Status: Accepted - -## Context - -The game's `Managed/` directory loads its own Newtonsoft.Json and MessagePack, and the mod binds to those at runtime. The mod used to compile against NuGet packages instead. 5.5.0 picked a Newtonsoft overload the game's copy lacks and failed at runtime with `MissingMethodException`. Pinning the package to the same version did not help: the game's Newtonsoft 13.0.2 is a different binary from NuGet's, and ModApi compiled against MessagePack 3.1.9 while the game has 3.1.4. A metadata validator (#92) compared the IL references with the game file, but it ran outside every gate and rebuilt part of the compiler's binding rules. `PublicizeAll` also publicized these libraries, so members the game keeps internal compiled cleanly. - -## Decision - -1. `build/GameLibraries.props` is the only list of game-supplied libraries. A project that sets `BppReferenceGameLibraries=true` references each one from `$(ManagedPath)` and excludes it from the publicizer. The Payload Inventory ships none of them. -2. The libraries have no central `PackageVersion`, so any future `PackageReference` fails restore (NU1010). -3. `ValidateBppGameLibraries` fails when a library is missing under `ManagedPath`. `VerifyBppGameLibraryCopies` fails when the copy in a build output is not the game's file. -4. The MessagePack source generator comes from `MessagePackAnalyzer`, pinned to the game's runtime version, 3.1.4. Dropping the NuGet `MessagePack` package would otherwise drop the generator, and the Run segment would silently fall back to runtime-built formatters. The generated code compiles against the game's MessagePack, so a generator that emits APIs missing from the game fails to build. - -The compiler is the compatibility check in every gate that already runs: `mod::check`, `mod::test`, `mod::matrix`, and the release `produce` build, which always takes an explicit `ManagedPath`. Windows, PTR, and archived snapshots are covered by building against their own Managed directory. - -## Guardrails - -- Add a library that the game loads for the mod to `BppGameLibraries`, never as a package. -- Not covered: reflection and runtime semantics, and any third-party Payload DLL built against a different Newtonsoft. None ships today. -- Deferred: `UnityEngine.Modules` 2022.3.40 still stands in for the game's Unity 6 modules. Switching needs the `FindObjectsOfType` call sites migrated first. - -## Evidence - -- Access: `tests/RuntimeIntegration.Tests/GameSuppliedLibraryAccessTests.cs` -- Generated formatters and Run goldens: `RunPayloadFormattersAreSourceGenerated` in `tests/BundleV6Codec.Tests/Program.cs` diff --git a/bazaarplusplus-mod/docs/adr/0011-schema-version-names-column-shape.md b/bazaarplusplus-mod/docs/adr/0011-schema-version-names-column-shape.md deleted file mode 100644 index 16c0439..0000000 --- a/bazaarplusplus-mod/docs/adr/0011-schema-version-names-column-shape.md +++ /dev/null @@ -1,30 +0,0 @@ -# ADR-0011: The local schema version names column shape - -Status: Accepted - -## Context - -The installer's History reads the mod's SQLite database and opens only the `user_version` values listed in `../bazaarplusplus-installer/src-tauri/history-database-compatibility.json`. The mod refuses a database newer than `RunLogSchema.LocalDatabaseSchemaVersion`. 5.6.0 bumped the version from 2 to 3 only to run a one-time queue repair of legacy JSON seal failures in `BundleQueueStore` (removed in V6), with no column change. As a result, a mod downgraded below 5.6.0 refuses the database and loses all storage, older installers report History unsupported, and the installer's compatibility list and tests changed with nothing new to read. The number was restated across `RunLogSchema`, tests, and both JSON files. The two files were compared only when a Payload was prepared. - -V6 moves the data root to `BazaarPlusPlusV6/` and starts a new database there instead of migrating the V5 one, so its numbering restarts. - -## Decision - -1. `user_version` names the column shape the installer reads. Bump it only for a column change. The bump lands in one pull request with its migration, `BazaarPlusPlus.history-database.json`, and the installer's compatibility list. Index and trigger DDL in `BootstrapSql` needs no bump. -2. A one-time data repair never bumps it. The first repair that must run once adds a mod-private ledger table through `BootstrapSql`, with one row per repair name written in the repair's own transaction. The repair checks that ledger, not the version. No ledger exists yet because no repair needs one. V5's version 3 repair was keyed on leaving version 2; V6 has no repair and no migration. -3. The mod's version is the newest one the installer supports. `assertHistoryDatabaseCompatibility` in root `release/history-database.mjs` checks the source files in `release::check` and the staged Payload in `release::prepare`. - -A mod-private table is invisible to the installer. History, cleanup, and the overlay query named tables only (installer `table_exists` in `src-tauri/src/history/queries.rs`), and Reset deletes the whole data root (installer ADR-0008). - -## Guardrails - -- V5 keeps version 3: it shipped in 5.6.0, and reverting it would strand databases already at 3. V6 starts at 1, and `EnsureInitialized` accepts only 0 (empty) and 1, so a V5 database at 3 is refused, not reinterpreted. V6 stores the seal input deadline as an integer column (`bundle_seal_jobs.input_deadline_at_ms`), so its format needs no repair. -- `RunLogSchemaColumnShapeTests` fails when columns change without a bump and when a bump records a shape an earlier version already had. -- `CREATE INDEX IF NOT EXISTS` never redefines an index, and History pages name theirs in `INDEXED BY`, which errors when the stored definition cannot serve the query. `EnsureInitialized` drops each index whose stored SQL differs from what `BootstrapSql` produces, in the init transaction, so `BootstrapSql` recreates it; `RunLogSchemaIndexTests` and `HistoryPaginationTests` pin this. -- Not covered: CHECK constraints and triggers are outside the fingerprint, a changed trigger or retired index name needs an explicit `DROP`, and a mod older than the database still refuses it. - -## Evidence - -- `LocalDatabaseSchemaVersion` and `EnsureInitialized` in `src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs` -- `tests/Storage.Tests/RunLogSchemaColumnShapeTests.cs`, `tests/Storage.Tests/RunLogSchemaReleaseContractTests.cs`, `tests/Storage.Tests/RunLogSchemaIndexTests.cs` -- Root `release/history-database.test.mjs` diff --git a/bazaarplusplus-mod/docs/architecture/capture.md b/bazaarplusplus-mod/docs/architecture/capture.md deleted file mode 100644 index 6bf44c1..0000000 --- a/bazaarplusplus-mod/docs/architecture/capture.md +++ /dev/null @@ -1,38 +0,0 @@ -# Combat Replay, Screenshots, Uploads, And Ghost Battles - -Replay recording and playback, optional video capture, end-of-run screenshot capture, bundle sealing, the single upload feed, and ghost battle import. - -Combat replay records local PvP battle replay payloads and lets HistoryPanel start playback when a local or downloaded ghost replay payload is available. Video recording is optional and supported on macOS and Windows through platform-native render plugins (Metal/VideoToolbox/AVFoundation; D3D11/Media Foundation); availability is gated by the native plugin and output directory configuration (`src/BazaarPlusPlus/Game/CombatReplay/Video/CombatReplayRecordingGate.cs`). - -Local replay payloads are a bounded cache, while battle facts and successful MP4 recordings are durable user artifacts. Startup maintenance runs off the constructor path behind the same operation gate as payload persistence and playback: one bulk SQLite inventory drives orphan cleanup and the `newest 200 ∪ last 30 days` retention policy, and a transactional `ready → delete_pending → evicted` lifecycle makes file failures retryable. Active runs, playback/persistence work, waiting or sealing Bundle seal jobs, Seal-Eligible Runs, and pending outbox rows are protected. History treats a replay as saved only while `local_payload_state` is `ready`. Video ownership and file health are orthogonal (`attachment_state` and `file_state`): run deletion detaches metadata in the run-delete transaction but keeps completed MP4s; reconcile marks missing/recovered files, reports unknown successful MP4s without deleting them, and removes only expired unprotected temporary/failed residue. Detached recording metadata remains in the store (`src/BazaarPlusPlus/Game/CombatReplay/ReplayPayloadMaintenanceService.cs`, `src/BazaarPlusPlus/Game/CombatReplay/Video/ReplayVideoArtifactMaintenanceService.cs`). - -To read a replay payload outside Unity, decode through `CombatReplayPayloadStore` plus `MessagePackSerializer.Deserialize` with `MessagePackConfig.Options`; `CombatReplayLoader` returns an Assembly-CSharp type, so it only works inside the game process. - -`tests/CombatImpact.Corpus/` is the offline acceptance module for the complete Combat Impact model. It stays out of `tests/BazaarPlusPlus.Tests.slnx` and runs as a child process: `ScenarioRunner.Tests` (`Combat_impact_corpus_matches_committed_evidence`) replays the committed pinned corpus in `tests/CombatImpact.Corpus/corpus/` on every `just mod::test` and compares its evidence with `tests/CombatImpact.Corpus/evidence/pinned-corpus.json`, while `just mod::test-corpus ` runs it over an external corpus. Its evidence records the corpus artifacts, `GameData.db`, and interpreting game assemblies so results reproduce against the same inputs; `tests/CombatImpact.Corpus/evidence/README.md` owns regeneration. - -Saved-replay playback state algebra lives in the pure `SavedReplayLifecycle` core; `CombatReplayRuntime` is its translation layer, which executes publishes, portrait cleanup, and menu dispatch but holds no transition logic (`src/BazaarPlusPlus/Game/CombatReplay/SavedReplayLifecycle.cs`; behavior tests in `tests/PureBehavior.Tests/SavedReplayLifecycleTests.cs`). The load-bearing states and windows (staged start commits, the shared 15-second exit-suppression latch, the two-phase exit decision, pending menu-return polling) are enumerated in ADR-0005. - -Saved-replay startup treats the native `ReplayState.SpawnCombatCards` task as the board-readiness boundary. Native state entry starts that task without awaiting it, so sampling active item setup or `BoardManager` flags alone can observe a false quiet frame before the first controller activates. The Harmony seam tracks both the complete board-spawn task and individual item setup tasks inside a scoped `ReplayPresentationTaskTracker`; startup waits until all tracked work completes and a render boundary passes without discovering new work, under the existing bounded failure rollback (`src/BazaarPlusPlus/Patches/Combat/CombatReplayItemPresentationReadinessPatch.cs`, `src/BazaarPlusPlus/Game/CombatReplay/Bootstrap/ReplayItemPresentationReadiness.cs`). Fixed delays and expected-controller counts are not substitutes for this native work boundary. - -`CombatReplayVideoRecorder` owns the video capture session (`src/BazaarPlusPlus/Game/CombatReplay/Video/CombatReplayVideoRecorder.cs`). Two contracts hold across it: audio capture is additive (tap failure never aborts video recording, and only usable sample-bearing WAVs are retained), and on playback end the finalization inputs are frozen into detached contexts with encoder drain/audio mux/metadata completion dispatched off the main thread, so a later replay cannot overwrite them (`src/BazaarPlusPlus/Game/CombatReplay/Audio/ReplayAudioTapStopper.cs`). - -BPP UI chrome suppression is centralized in `Game/OverlayPanels`: screenshot mode hides the CollectionPanel dock button and the combat status bar; replay recording mode hides only the dock button, intentionally leaving the combat status bar visible; there is no separate settings-dock suppression target (`src/BazaarPlusPlus/Game/OverlayPanels/BppUiChromeSuppression.cs`). Native tooltip suppression is a separate shared, owner-scoped adapter in `GameInterop/Tooltips`: replay presentation, replay video, and end-of-run capture hold independent leases; high- and low-level native show paths are gated while any lease is active, and cleanup unlocks and conceals primary, secondary, auxiliary, and locked tooltips. Controller discovery includes inactive objects so the native parent's current controller remains authoritative, but an inactive controller no longer owned by that parent cannot render while the show gates are held and is skipped as stale for that audit. Active or authoritative controllers still require their native visibility surface; unavailable surfaces retain the fail-open degraded-capture path. Debug sampling records both the stable native audit reason and the maximum skipped inactive-controller count (`src/BazaarPlusPlus/GameInterop/Tooltips/NativeTooltipSuppression.cs`, `src/BazaarPlusPlus/Patches/Tooltips/NativeTooltipSuppressionPatches.cs`). - -End-of-run capture is one run-scoped `EndOfRunCaptureWorkflow`: its core owns readiness, bounded attempts, deadlines, artifact validation, Continue blocking, and the single terminal outcome (`src/BazaarPlusPlus/Game/Screenshots/EndOfRunCaptureWorkflowCore.cs`), with the internal `EndOfRunCaptureDriver` as its Unity/native surface adapter (`src/BazaarPlusPlus/Game/Screenshots/EndOfRunCaptureDriver.cs`). The contracts that must hold: readiness requires native reveal start, a cleared screen transition, settled skills, and either 500 ms of structural card-pose stability after observed motion or the native `FaceUp` completion fallback (empty card boards retain their native settled path), and readiness starts capture automatically. Each attempt acquires BPP and native-tooltip suppression, clears hover/locked state, and passes a second bounded clean-frame barrier (native tooltip visibility audits clean and the post-clean card hierarchy stays structurally stable for a fresh 500 ms window) before `ScreenCapture` runs. The barrier is best-effort: missing native seams, unavailable visual audits, preparation exceptions, or the deadline degrade to an immediate capture with a terminal reason instead of dropping the artifact (`src/BazaarPlusPlus/Game/Screenshots/EndOfRunCleanFramePreparationCore.cs`). Suppression leases remain held until the captured frame's RGBA pixels have been copied out of Unity when preparation remains available; Run metadata (day, victories, hero, rank, rating, and placement) is copied into an immutable value immediately before frame capture; persistence reads only that value, never the later live run. Continue is released at that boundary, while PNG encoding, atomic file write, and metadata persistence continue in the background without consuming or replaying the native click. A verified PNG is never deleted or recaptured when metadata persistence fails or times out; a late artifact from a capture canceled before frame acquisition is deleted. Composition exposes the workflow's two-intent interface to patches before mounting the driver, so the Continue and raw reveal patches fail open during startup and teardown (`src/BazaarPlusPlus/BppComposition.cs`, `src/BazaarPlusPlus/Patches/EndOfRun/`). - -`BundleSealCoordinator` is the single background workflow owner of input convergence, payload composition, screenshot JPEG budgeting, deterministic bundle construction, self-open verification, atomic publication, and crash reconciliation; event-bus handlers only enqueue wakes (`src/BazaarPlusPlus/Game/BundlePipeline/BundleSealCoordinator.cs`). Stable bundle id/time are allocated before file creation, and startup recovery adopts a renamed file only when its durable allocation identity matches. The convergence/queue ownership split (pure `BundleSealConvergence` decisions, Storage-owned `BundleQueueStore` SQL) is recorded in ADR-0006. Every seal-path failure is decided by `BundleSealFailurePolicy` from the stage it happened in and its exception graph, then recorded through `BundleQueueStore.RecordSealFailure` (state, consecutive `attempts` for that code, time, bounded diagnostic) and logged with the original exception under a storm-limited category (`bundle_pipeline.seal.deferred`, `.environment_blocked`, `.degraded`, `.terminal`). Runtime failures (missing member, type load, assembly binding, type initializer) park the Run as waiting with `seal_environment_blocked`: it runs again once per launch, so a mod or game update retries it without a migration, and it ends as `seal_environment_blocked_expired` only after five parked launches and 60 days past its input deadline. Other failures retry with exponential backoff (5 s to 1 h) and end as `seal_retry_exhausted` only after eight consecutive failures with the same code and 14 days; codec failures in payload budgeting, encoding, or Bundle build are terminal at once. A job that fails again 90 days or more past its input deadline ends whatever its code, so alternating failures cannot pin its sources in History cleanup forever; a first failure never ends that way. Each Run is attempted in isolation and skipped while backing off, so one failing Run cannot abort a pass or starve later Runs. A replay that exists but cannot be used is reported by `RunPayloadComposer` with its load status and decode exception: bytes that do not decode omit that replay with a `replay_invalid` log even when the cause looks like IO (truncated MessagePack, corrupt gzip), a file that cannot be read retries the Run, and a runtime failure anywhere in the exception chain parks it. File recovery and pending-file validation are per file; a runtime that cannot open a Bundle neither deletes an orphan nor invalidates a pending outbox, and maintenance failures never stop waiting Runs from sealing (`BundleSealCoordinator.ReconcileAsync`). - -A reconcile pass arms uploads once after publishing its backlog, including partial progress before cancellation, so each recovered run cannot independently bypass the pump cadence. Pending-file invalidation checks the current outbox state in its transaction; a stale validation result cannot overwrite a completed upload (`BundleSealCoordinator.ReconcileAsync`, `BundleQueueStore.FailOutboxAndScheduleReseal`). `bundle_seal_jobs.input_deadline_at_ms` is a Unix-millisecond integer like every other stored instant, so `ListWaitingRunIds` and `idx_bundle_seal_jobs_state` order deadlines numerically and no write path can store a format that sorts wrongly. Only that explicit invalidation schedules a reseal: a server rejection or local retention expiry is final instead of sealing a replacement Bundle on every pass. The rule for which Runs get a new seal job is `BundleQueueStore.SealEligibleRunCondition`, composed by `EnsureEligibleJobs` and replay maintenance (`PvpBattleSqliteStore.ScheduleReplayPayloadDeletion`). It rejects a History-Only Run (`runs.upload_policy = 'history_only'`) before any other check, so imported history is never sealed and replay maintenance releases its replays. The mod never writes that policy, and `RunLogStore.ResumableRunCondition` also keeps such a Run from being resumed, reopened by `CreateRun`, or shown as the current Run in History, in case an import left one active. `tests/BundleQueueSqliteStore.Tests/fixtures/bundle-seal-eligibility.json` is its cross-project contract: both mod consumers and installer History cleanup evaluate its cases. - -There is exactly one upload feed and one `BackgroundUploadPump`: each `BundleUploadFeed.Session` owns a `ModApiSession`, sends immutable `.bundle` files to `POST /bundles` with `Content-Length` and `Content-Digest`, maps typed endpoint dispositions, persists retry time through `BundleQueueStore`, and commits success before deleting through the narrow `IBundleOutboxFiles` port (`src/BazaarPlusPlus/Game/BundlePipeline/`). Ghost discovery uses `GET /ghost-battles?limit=200`; replay download uses the plugin-owned History session, validates the bundle and run identities through `RunBundleV6Contract`, reconstructs only a complete target battle, saves it atomically, and persists `remote_available`, `local_ready`, `unavailable_payload`, or `expired` so permanent failures are not retried (`src/BazaarPlusPlus/Game/HistoryPanel/Ghost/`). Discovery restores legacy `ghost_bundle_invalid` failures for one new import attempt; new unexpected import failures use `ghost_bundle_import_failed` and remain terminal across syncs. The exact wire and payload contracts are documented in `docs/contracts/run-payload-v6.md`; transport/result/persistence ownership is recorded in ADR-0006. - -## Gotchas - -Traps and rules that bite only this feature; most failed silently at least once. - -- `CombatReplayPayloadStore`/`GhostBattlePayloadStore` stay thin named facades over `FileBackedPayloadStore`. Capsules construct `CombatReplayPayloadStore` directly, so renaming it breaks their build; `GhostBattlePayloadStore` and the `.mpack.gz` suffixes are not test-pinned. [`tests/BundlePipeline.Tests/Program.cs`] -- `tests/BundlePipeline.Tests` is the Bundle pipeline's end-to-end anchor: it seals and uploads through real SQLite stores and outbox files, writes every Bundle to `artifacts/bundle-pipeline/`, and fails unless its normalized summary matches `tests/BundlePipeline.Tests/fixtures/bundle-pipeline.golden.json` byte for byte. Its inputs must stay deterministic: game `NetMessage*` constructors draw a random `MessageId`, so the replay fixtures set it. Regenerate the golden only with `BPP_UPDATE_GOLDENS=1` and review the diff. [`tests/BundlePipeline.Tests/PipelineArtifacts.cs`] -- Dock-button lifecycle controllers must live on the always-active native button, never a `SetActive(false)` clone — inactive clones get no `LateUpdate` and miss later state transitions. The replay dock button's tooltip is the native cue activator's `defaultValue`, not a BPP-positioned auxiliary tooltip. [`src/BazaarPlusPlus/Game/CombatReplay/CurrentReplayRecordingButtonController.cs`] -- Clone the controller-free native donor first, then attach the BPP MonoBehaviour to the stable owner — cloning a GameObject that already carries a BPP controller duplicates the controller. [`src/BazaarPlusPlus/Game/CombatReplay/CurrentReplayRecordingButtonController.cs`] -- The native end-of-run reveal uses `CreateRawGraph`, whose delay roots have no `ScriptPlayableOutput` and therefore never complete — cards stay FaceDown and screenshot readiness never fires. `EndOfRunRawRevealCompletionPatch` injects a port-1 output per root; keep it. [`src/BazaarPlusPlus/Patches/EndOfRun/EndOfRunRawRevealCompletionPatch.cs`] -- `BackgroundUploadPump.OnDestroy` is a two-point dispose: release arm subscriptions first, dispose the session only after the drain callback. Merging them lets an in-flight `RunAttemptAsync` hit disposed resources. [`src/BazaarPlusPlus/Game/Upload/BackgroundUploadPump.cs` | ADR-0005] diff --git a/bazaarplusplus-mod/docs/architecture/collection.md b/bazaarplusplus-mod/docs/architecture/collection.md deleted file mode 100644 index 767f07e..0000000 --- a/bazaarplusplus-mod/docs/architecture/collection.md +++ /dev/null @@ -1,46 +0,0 @@ -# Collection Panel - -The full-screen Item/Skill catalog: filter state, the pure view-state reducer, grid virtualization and cell fit, filtering rules, the Day gate, the source catalog, and card view models. - -CollectionPanel is a full-screen Item/Skill catalog mounted by `CollectionPanelMount`, registered with the shared Overlay Panel Host (`src/BazaarPlusPlus/BppComposition.cs`). Its filter state is pure mutable data: active tab/card type, nullable concrete `SelectedHero` (`EffectiveHero` falls back to `Common`), tiers, tags, hidden keyword tags, Any/All facet modes, sizes, selected source key, run-day filter, and sort priority (`src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionFilterState.cs`). The tab model contains only `Items` and `Skills` (`src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionTabKind.cs`). - -All filter, search, and catalog state transitions are centralized in the pure `CollectionViewState` reducer: panel command methods are single-line forwards, each returning a `CollectionRenderOutcome?` (`null` = same-value no-op) that the panel consumes at its single `ApplyOutcome` point; grid read-back goes through the injected `ICollectionGridPort`, and hero normalization on catalog accept never writes the hero preference (`src/BazaarPlusPlus/Game/CollectionPanel/CollectionViewState.cs`; behavior tests in `tests/CollectionViewState.Tests/`; load-bearing contract points in ADR-0005). - -Collection creates one native-card-preview scope for each Unity runtime and gives its virtualizer only that scope. Realized cells retain opaque sessions, not native component/kind/setup-task tuples; stale acquisitions are disposed immediately (`src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanel.cs`, `src/BazaarPlusPlus/Game/CollectionPanel/Grid/CollectionGridVirtualizer.cs`). Runtime teardown waits for pending binds and scope disposal before destroying the overlay and Collection-owned art/material caches (`src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanel.cs`). Collection-specific tooltip registry, cache refcount, and shared-material cleanup remain in its owner adapter and destroy patch, outside the generic preview host. - -Collection cards open a modal inspection on left or right click; dragging or scrolling cancels a left click. `CollectionLockVariantPanelPatch` extends native tier/enchantment controls to registered Collection cards when the client supports them. `CollectionInspectionModule` owns an independent preview, suspends Collection input, and closes on Escape or clicks outside those controls. `CollectionInspectionState` rejects stale preview completions and prevents dismissal click-through; `NativeInspectionPresentation` restores borrowed native canvases and raycasters on release. The artwork rectangle stays fixed across tier, enchantment, and description changes until close or viewport resize. Activate the preview behind its alpha gate before measuring the exact native artwork; pooled frame descendants must never affect its fit (`src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionModule.cs`; `src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionLayout.cs`; `src/BazaarPlusPlus/GameInterop/CardPreview/NativeCardPreviewArtworkMeasurement.cs`; `src/BazaarPlusPlus/GameInterop/Tooltips/NativeInspectionPresentation.cs`; `src/BazaarPlusPlus/Patches/CollectionPanel/CollectionLockVariantPanelPatch.cs`). - -Cell measure/fit is split out of the virtualizer: `CollectionCardFitMath` is pure fit math (scale plus anchored position), `NativeCardCellFitter` is the Unity measurement adapter (frame-container → raw-image → aspect-fallback → rect chains), and `NativeCardCellBoundsCache` caches per-cell visual bounds with three invalidation hooks (rebind, scale-dirty, art-load completion) so the scroll path repositions with `allowMeasure: false` instead of remeasuring every realized cell each frame (`src/BazaarPlusPlus/Game/CollectionPanel/Grid/CollectionCardFitMath.cs`, `src/BazaarPlusPlus/Game/CollectionPanel/Grid/NativeCardCellFitter.cs`, `src/BazaarPlusPlus/Game/CollectionPanel/Grid/NativeCardCellBoundsCache.cs`, `src/BazaarPlusPlus/Game/CollectionPanel/Grid/CollectionGridVirtualizer.cs`). - -Filtering is code-owned and deterministic. `CollectionFilterEngine.Apply()` applies active card type, excludes package cards from normal results, applies source offer pool membership, hero, tier, day, tag, keyword, and size filters, then sorts by tier/size priority plus localized display name (`src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionFilterEngine.cs`). Tag and keyword facets support `Any` and `All` matching, and the UI exposes mode toggles in the tag and keyword headers (`src/BazaarPlusPlus/Game/CollectionPanel/Ui/CollectionPanelView.Tree.cs`). - -The Day gate consumes only the shared GameData result's `MaximumTier`; absent, not-ready, missing, invalid, and out-of-run results fail open. The manual Tier filter remains an independent AND condition, fixed-tier sources suppress only the Day gate, and Legendary starting tiers retain the game's Diamond compatibility alias (`src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionFilterEngine.cs`, `src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionFilterContext.cs`). - -Merchant and trainer source filtering is driven by an embedded `collection-sources.json` catalog. Mismatched `collection-sources.json` schema versions are rejected during build/parse (`src/BazaarPlusPlus/Game/CollectionPanel/Sources/CollectionSourceCatalog.cs`). Each source has `offerSegments`, and each segment parses a typed rule with hero mode, starting tier, sizes, tags, hidden tags and groups, enchantability, and enchantment facets (`src/BazaarPlusPlus/Game/CollectionPanel/Sources/CollectionSourceCatalog.cs`). - -Card VMs project base card tags and per-enchantment facets from game templates. Lifesteal is derived when an item has positive Lifesteal base value at any tier even if the template lacks the hidden tag (`src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionCardVm.From.cs`, `src/BazaarPlusPlus/Game/CollectionPanel/Data/CollectionDerivedKeywordFacts.cs`). - -Collection and EventPreview share `BppStaticCardMapProvider`, which normally uses the native `GetCardMap()`. `CardTemplateValueCompatibilityPatch` prepares the native thread-local card serializer for both bulk and point lookups. `CompatibleCardValueConverter` prefers native value implementations and supplies `TReferenceValueUniqueCardCount` only when the client cannot deserialize that discriminator. It counts distinct template IDs while inheriting native target selection, default values, modifiers, and rounding; it does not register a global discriminator or alter GameData on disk (`src/BazaarPlusPlus/GameInterop/StaticCards/`). - -Other unknown derived types remain unsupported. If native bulk loading encounters one, `CompatibleCardMapReader` reads the same database in read-only mode with the same value compatibility adapter and omits only unsupported templates. This partial snapshot does not replace the game's cache; malformed data and wholly unsupported catalogs still fail. `static_cards.catalog.unsupported_templates` records accepted and unsupported counts. - -## Art load degradation and retry - -A failed art bind reports `collection_panel.card_art.degraded` with `status=ArtUnavailable`, storm-keyed on `reason_code` (`src/BazaarPlusPlus/Game/CollectionPanel/Grid/CollectionCardArtCache.cs`). The family has one code per silent exit of `CollectionItemLoadArtPatch.LoadArtFromCache`: `CardDataMissing`, `ArtKeyMissing`, `ArtAssetMissing` (cache miss or failed Addressables load), `CardMaterialMissing` (SO without a material), `MaterialMissing` (material construction failed), `CardTextureMissing` (the SO's material has a null main texture), `CardImageMissing` (the card lost its RawImage slot, so neither texture nor material can reach the screen), and `CachedLoadFailed` for an exception on the path (`src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanelLogCodes.cs`). The event names the `art_key` whenever one is known. - -A failed artKey is suppressed for 60 s (`CollectionCardArtCache.FailureRetryDelay`), not permanently: the panel can stay open for hours and cells rebind on every scroll, so a permanent blacklist would turn one transient failure — the catalog still warming, a load cancelled by teardown, memory pressure during a fast scroll — into a blank card for the rest of the session. Suppression is per artKey, expires lazily on the next attempt, and a retry costs one Addressables request; the degraded event is storm-suppressed, so retrying cannot flood the log. The window uses `DateTime.UtcNow`, so a device time-zone change cannot move it. - -That window is per cache instance. Every `Open()` constructs a new `CollectionCardArtCache` and `DisposeAll()` clears the failed set, so it does not span panel open/close cycles. `CollectionCardArtCache.ClearFailedKeys()` is the in-session escape hatch: `CollectionPanel.InvalidateCatalog` calls it on locale change (through `NotifyLocaleChanged`) and on runtime dispose (where the caches are already gone, making it a no-op), so cards rebound after a catalog invalidation retry immediately instead of waiting out the TTL. It is never called per frame. - -Clearing the failure window is not enough on its own: every failure exit also calls `ClearCachedMaterialAssignment`, and pool release (`CollectionNativeCardPreviewOwner.ReleaseOwnedState`) clears `_cardImage.texture` and `_cardImage.material` before releasing the art refcount. Without that, a pooled card keeps drawing the previous item's art and would still point at a texture or shared Material the cache destroys on eviction. - -## Gotchas - -Traps and rules that bite only this feature; most failed silently at least once. - -- Android's mobile tray and its nested description canvas need distinct sorting orders: flattening both to one order composites the tray's dark background over otherwise fully opaque text. `NativeInspectionPresentation.PromoteDescriptionCanvas` leases only the description above the tray, without detaching its scaler or scroll mask, and restores it before its parent. [`src/BazaarPlusPlus/GameInterop/Tooltips/NativeInspectionPresentation.cs`] - -- UI Toolkit `Button` inherits `TextElement`, so `Q()` returns the button itself when no separate label exists — hiding that "label" hides the whole control (guard with `!ReferenceEquals`), and a refresh writing `Button.text` resurrects the native label beside a custom one. [`src/BazaarPlusPlus/Game/CollectionPanel/Ui/CollectionPanelView.Filters.cs`] -- The hardcoded `DayTierSchedule` was removed — do not restore it as a fallback. Day tiers resolve through `GameDataDayTierResolver`, whose success cache is keyed on `JsonGameDataManager` reference identity because the game swaps that reference after a GameData download. [`src/BazaarPlusPlus/GameInterop/DayTiers/GameDataDayTierResolver.cs`] -- Aspect-fallback collection cards (no measurable frame or raw-image bounds) hold size via a one-shot `SetSizeWithCurrentAnchors` plus the per-cell bounds cache. This path shipped without in-game smoke; on card-size drift, apply the fallback documented in the fitter header. [`src/BazaarPlusPlus/Game/CollectionPanel/Grid/NativeCardCellFitter.cs`] -- CollectionPanel source filtering runs off the embedded `collection-sources.json`, and the catalog size is pinned by the source/merchant/trainer count assertions in its test — adding a source means updating those expectations too. [`src/BazaarPlusPlus/Game/CollectionPanel/Sources/CollectionSourceCatalog.cs` | `tests/CollectionSourceFiltering.Tests/Program.cs`] diff --git a/bazaarplusplus-mod/docs/architecture/input-and-settings.md b/bazaarplusplus-mod/docs/architecture/input-and-settings.md deleted file mode 100644 index a37cd2e..0000000 --- a/bazaarplusplus-mod/docs/architecture/input-and-settings.md +++ /dev/null @@ -1,20 +0,0 @@ -# Hotkeys And The Settings Dock - -User-rebindable hotkeys and the settings dock: how a row is contributed, where its order comes from, and how binding paths are normalized. - -Settings-dock rows themselves are data: every cycling or boolean row is a `CyclingSettingsDockEntry` (with a `Toggle` factory for the bool case) built by a per-feature static factory supplying order, key, value ladder, read/write delegates, highlight predicate, status text, and an optional `onChanged` hook (`src/BazaarPlusPlus/Game/Settings/CyclingSettingsDockEntry.cs`). Only the history-panel action button and the force-lockable end-of-run screenshot toggle remain hand-built definitions. - -BPP hotkeys are user-rebindable and persisted in config per action. `BppHotkeyActionId` covers five actions: the two hold-preview hotkeys (Ctrl enchant / Shift upgrade defaults) plus toggles for CollectionPanel, LiveBuildPanel, and HistoryPanel (`src/BazaarPlusPlus/Game/Input/BppHotkeyActionId.cs`); rebinding rows are cloned from native settings rows (`src/BazaarPlusPlus/Game/Input/BppKeyBindRowController.cs`), and panel toggle presses are resolved per frame by the Overlay Panel Host. Binding-path normalization, ctrl/shift alias expansion, conflict detection, and the default/display data tables are the pure `HotkeyBindingPathCore` (`src/BazaarPlusPlus/Game/Input/HotkeyBindingPathCore.cs`, compile-linked into the zero-ManagedPath `tests/HotkeyBindingPath.Tests/`); `BppHotkeyService` remains the Unity/config facade. Binding paths in `BazaarPlusPlus.cfg` `[Hotkeys]` are untrusted input: junk normalizes to empty and falls back to the action default. - -The settings dock registers all feature rows through `SettingsDockEntryRegistry` with order constants centralized in `BppSettingsDockOrder` (`src/BazaarPlusPlus/Game/Settings/BppSettingsDockOrder.cs`); the roster spans history, name override, bilingual item names, cosmetic names, legendary position, enchant preview, event and quest previews, combat status bar, Chinese locale, supporter list, voice subtitles, end-of-run screenshot, BazaarDB upload, and the platform-gated graphics upscaling rows (`src/BazaarPlusPlus/BppComposition.cs`). There is no BPP font selector because all BPP-owned game UI follows the game's font assets. - -The combat status bar's settings-dock toggle controls visibility during runs and replays and persists through `BppConfig.EnableCombatStatusBarConfig`; hiding paused controls resumes playback without resetting the preferred speed (`src/BazaarPlusPlus/Game/CombatStatusBar/CombatStatusBarSettingsDockEntry.cs`, `Create`; `src/BazaarPlusPlus/Game/CombatStatusBar/CombatStatusBar.State.cs`, `OnVisibilitySettingChanged`). It keeps its plugin-owned mount and screen-space layout. Portrait bounds supply geometry only; rendering uses the native PvP transition canvas's camera and plane distance on `AboveBoard`, below the native transition backgrounds. This keeps scene decorations behind the controls while allowing the transition curtains to cover them (`src/BazaarPlusPlus/Game/CombatStatusBar/CombatStatusBar.Canvas.cs`, `RefreshLayout`; `src/BazaarPlusPlus/GameInterop/HeroPortraits/NativePlayerPortraitBounds.cs`, `TryRead`). - -Cosmetic Names is a default-off boolean in `[CosmeticNames] Enabled`. `CosmeticItemNamePatch` attaches one `CosmeticNameOverlay` to each individual loadout item at `CosmeticItem.SetData`; category buttons are separate native components. The overlay resolves the collectible template's name by item GUID, then tries the asset and sale-item names through the current game localization service, falling back to the English name when no translation exists. Default collectibles with authoring identifiers instead of translated names receive a localized default-item label, keyed by the native `IsDefault` flag. Game-font text uses glyph-geometry centering within the thumbnail's bottom shadow strip; both move upward by at least half a character height. The strip anchors to the image loader's visible viewport rather than its image rectangle, which is wider than the clipped thumbnail for carpets. It reacts to config, game-language, and Chinese locale-mode changes; complete Chinese labels pass through `L.ResolveChinese` before display (`src/BazaarPlusPlus/Game/CosmeticNames/`). - -## Gotchas - -Traps and rules that bite only this feature; most failed silently at least once. - -- The BPP hotkey conflict check compares BPP actions only against other BPP actions, never native `Gameplay/*` bindings. [`src/BazaarPlusPlus/Game/Input/BppHotkeyService.cs`] -- BPP settings dock buttons are clones of native dock buttons that must avoid native-button bounds and re-sync geometry for several frames after a screen-size change. [`src/BazaarPlusPlus/Game/Settings/BppDockButtonVisuals.cs`] diff --git a/bazaarplusplus-mod/docs/architecture/native-artifacts.md b/bazaarplusplus-mod/docs/architecture/native-artifacts.md deleted file mode 100644 index 4290785..0000000 --- a/bazaarplusplus-mod/docs/architecture/native-artifacts.md +++ /dev/null @@ -1,31 +0,0 @@ -# Desktop Native Artifact Publishing - -The mod project owns the macOS and Windows native recorder sources, build recipes, ABI declarations, and producer checks. The installer project owns the staged binaries and its native-recorder-input lock, which is the manifest consumed by installer prebuild verification. - -## Freshness contract - -`native/artifacts.json` is the catalog for the desktop artifacts. Each platform entry names its native sources, build scripts, platform policy, native headers, managed `DllImport` consumers, required exports, temporary build-output layout, and installer destination. Every policy field (architecture, deployment target, signing) is hashed into the input digest and recorded in the manifest; what a field additionally enforces is decided by whichever build or verify script reads it. The current-platform input digest is SHA-256 over a versioned canonical stream containing the normalized platform policy plus every declared input path, length, and exact worktree bytes in sorted path order. Consequently, uncommitted input changes invalidate an artifact immediately; unrelated repository changes do not. - -Git commit and dirty state are recorded only as producer provenance. They are never compared for freshness. - -The installer manifest records, per platform, the canonical input digest and input-file hashes alongside an exact file/tree inventory of the promoted artifact bytes. A platform is fresh only when its input digest matches the current catalog inputs and every staged artifact entry still matches the manifest. A platform record without an input digest remains integrity-checkable but is stale when that platform next publishes. - -## Product preparation - -`just release::prepare ` runs the workspace product coordinator on the native host. It prepares an isolated installer-shaped tree, ensures native inputs there, fetches and validates seeds, builds managed assemblies into private output directories, and checks assembly versions, native inventory and the unsigned archive before replacing any canonical Payload directory. - -The native coordinator computes the catalog input digest, reuses matching artifacts, or invokes the mod-owned build scripts into temporary output. Its local promotion is nested inside product preparation: a later managed build or final verification failure discards the entire temporary tree and leaves the previous canonical Payload unchanged. - -Switching the canonical Payload, locking, and journal recovery are owned by the [product release guide](../../../docs/release.md). - -## Producer checks - -Both macOS build scripts resolve Clang and the SDK through `xcrun`, pass the SDK explicitly with `-isysroot`, compile arm64 with `-mmacosx-version-min=12.0`, and turn unguarded-availability diagnostics into errors. Post-link checks require arm64, `LC_BUILD_VERSION` platform `MACOS` with `minos 12.0`, reviewed system-only dependencies, the catalog's exact exports, successful local load/symbol resolution, and a valid ad-hoc signature. The Core Audio dylib additionally requires `AudioHardwareCreateProcessTap` and `AudioHardwareDestroyProcessTap` to remain weak imports. - -The Windows build emits an x64 DLL through the local Visual Studio/MSVC environment, checks PE architecture, exact catalog exports, reviewed system dependencies, the explicit unsigned producer policy, and runs the native smoke program before promotion. - -These are producer checks on the machine running `publish`, not remote compatibility attestations. macOS 12.0 is the fixed binary deployment target; newer API use remains guarded by compiler availability enforcement and the Core Audio weak-import check. - -## Signing boundary - -Promoted macOS inputs are ad-hoc signed, and promoted Windows inputs are unsigned. The installer verifies those producer states before packaging. Its existing production path remains the release authority: nested macOS Mach-O code and bundles are signed inside-out with Developer ID, then the outer installer is signed and notarized. Those release signatures transform the producer bytes, so the installer artifact manifest continues to own final distribution hashes. diff --git a/bazaarplusplus-mod/docs/architecture/panels.md b/bazaarplusplus-mod/docs/architecture/panels.md deleted file mode 100644 index 401520f..0000000 --- a/bazaarplusplus-mod/docs/architecture/panels.md +++ /dev/null @@ -1,48 +0,0 @@ -# Overlay Panels, History, And Live Build - -Main-overlay-panel lifecycle, the native HistoryPanel surface, and the board adapters used by HistoryPanel and LiveBuildPanel. - -`LiveBuildRefreshState` owns Live Build Refresh acceptance, panel visibility, pending feedback, and the successful-pull allowance. The panel executes its download and view decisions; a status-only completion preserves the current recommendation and native boards. Reopening preserves a pending pull and clears completed feedback. Destroy prevents further view effects without cancelling the composition-owned Remote Embedded Catalog (`src/BazaarPlusPlus/Game/LiveBuildPanel/LiveBuildRefreshState.cs`, `LiveBuildPanel.RefreshFinalBuildsAsync`). - -`Game/OverlayPanels/OverlayPanelHost.cs` is the single Unity adapter that owns main-overlay-panel lifecycle: it reads per-frame input (escape, panel toggle hotkeys, combat state, scene changes), runs the pure `OverlayLifecycleCore` rules, and dispatches open/close/tick to registered panels (`src/BazaarPlusPlus/Game/OverlayPanels/OverlayPanelHost.cs`). It mounts before every panel mount, and CollectionPanel, HistoryPanel, and LiveBuildPanel all register through its accessor, enforcing at-most-one-open-panel (`src/BazaarPlusPlus/BppComposition.cs`). Lifecycle tests live in `tests/OverlayPanelLifecycle.Tests/`. - -Android panel text/control sizing uses `AndroidOverlayScale` through `AndroidOverlayViewport`, with a config-backed preference installed by `Plugin.InstallStaticUtilities` and cycled by the touch dock (`src/BazaarPlusPlus/Infrastructure/UiTokens/`, `src/BazaarPlusPlus/GameInterop/BppTouchEntry.cs`). Each panel scales its own renderer before converting safe-area pixels to layout units; native cards and tooltips keep their independent fitting. Collection resynchronizes its native title after Toolkit layout, and LiveBuild invalidates marker/footer geometry and compacts its sidebar when the canvas changes; attribution scrolls independently when the remaining height cannot hold the full list. The dock remains independently density-sized and reachable after closing a panel, including when the largest preference is selected. Pure scale/layout cases live in `tests/PureBehavior.Tests/AndroidOverlayScaleTests.cs`. - -On Android the combat status bar docks under the touch rail instead of under the player portrait, which reaches the bottom edge on phone layouts and leaves no room. The rail publishes the slot (`BppTouchEntry.StatusSlot`, placed by `AndroidOverlayGeometry.PlaceStatusSlot`), and the bar hides whenever the rail does. Android also draws a flat plaque, because the native skin's Addressable sprite load is skipped there (`CombatStatusBarNativeSkin.TryBeginLoad`). - -HistoryPanel is mounted through `HistoryPanelMount` with a single-constructor `HistoryPanelDependencies` (the `IRunContext`, data service, replay service, and the optional `ModApiSession` and account-link surfaces); the panel reads only `IsInGameRun` and `CurrentServerRunId`, and the server health check calls `ModApiSession.ProbeHealthAsync` directly (`src/BazaarPlusPlus/Game/HistoryPanel/HistoryPanelDependencies.cs`). Its owned uGUI view uses native artwork, portraits and trophies with scrolling run/battle lists (`src/BazaarPlusPlus/Game/HistoryPanel/Ui/HistoryPanelView.cs`). `HistoryPanel.NativeBoards.cs` projects a single normalized snapshot set into native cards and skills for `GameInterop/MonsterBoardPreview/OwnedMonsterBoardPreview.cs`. Each adapter owns a `MonsterBoardTooltip` clone, preserves native card pooling, and fits the carpet independently of its scrolling skills. Each board carries only a persistent ownership title directly above it; opponent identity, rank, rating and outcome stay in the battle list. Ownership wording is section-dependent: Runs shows the opponent above the local player, while Ghost drops the opponent rect entirely and the single surviving board is the CHALLENGER's, because ghost payloads stay in recorder perspective (ADR-0002) and `BuildPlayer` reads `Snapshots.PlayerHand`. Neither native history controllers nor the active monster tooltip are reused. - -`HistoryPanelLayout` is the panel's Unity-free geometry record, compiled directly into `tests/PureBehavior.Tests`. It owns the column spans, archive row heights, the board and title rects, and the day strip, and it is the single place top-down authoring flips into Unity's bottom-up anchors. Because the panel matches `.5`, a normalized value is worth a different number of canvas units at every aspect ratio, so its tests assert against aspect ratios rather than resolutions. The run archive uses compact rows with hero identity, mode, day, completed duration in whole minutes and timestamp; the rank and numeric Legendary rating precede the rightmost outcome trophy. A finished run shows the rank and rating it ended on, with its signed rating change beside a Legendary rating; an unfinished run falls back to the values it started on, and an unknown change (`final_player_rating_delta` is NULL) shows no sign. Ghost archive rows retain their taller layout. The battle timeline is a narrow vertical rail between the archive and the boards, one chip per battle with portrait, day and rank across the top, a numeric Legendary rating beneath the rank, the opponent's name below, and an outcome bar along the bottom. It keeps the page's newest-first order: the latest day appears at the top, matching the archive and the newer/older pager arrows. Row slots and battle indices are identical. It scrolls and pages because a run has no hard battle cap. The win target ends a run at ten wins, but losses only drain prestige. The boards are width-constrained (the carpet wants 2600:550), so the rail's width comes directly out of card size, and the two boards are always the same height because they are peers. - -`HistoryPanelCoordinator` owns page, selection and detail state. Each page owns its rows and cursors together; visible rows are read-only projections of that page, while the view takes a separate render snapshot. Summary records carry metadata only, and selected-detail state owns the loaded board snapshots. Run and battle pages use time/ID cursors and a maximum of 40 summaries; indexed SQL applies hero, outcome, day and account filters before the limit. The Runs and Ghost archives read counted pages and the battle timeline reads cursor pages (`src/BazaarPlusPlus/Game/HistoryPanel/Storage/HistoryPage.cs`). The page label shows a counted page's position and total under the current filters, plus the time range. `HistoryPageQuery` (`src/BazaarPlusPlus/Game/HistoryPanel/Storage/HistoryPageQuery.cs`) renders every page read's SQL from one filter (predicate, parameters, index hint), which the query-plan tests also use; a page's rows and counts share one read transaction. Ghost reads name the matching partial history index (`INDEXED BY`) so counts do not scan deleted table rows; opening the database rebuilds a drifted index first, since a hint the index cannot serve is an SQL error. Snapshot JSON and Ghost payloads are read only for the selected detail. Each read channel keeps one running operation and one replaceable pending request; session/account/selection checks prevent obsolete publication. Ghost sync runs when the Ghost section is entered and when the profile account arrives or changes while History is open in Ghost. `HistoryPanelCoordinator.ObserveAccount` owns every account change seen mid-session, including one first read by the account-link row: it restarts the session, then reloads the section. The persistent view reuses 40 archive rows and 40 battle rows. The archive retains record IDs and visible scroll anchors across refreshes. `HistoryTimelineScroll` preserves the timeline's exact offset on refresh and on clicks, including partly visible rows; a changed selection entirely outside the viewport is revealed at the nearest edge, without centering or row snapping. Temporary empty loading pages retain the previous offset and selection until rows return; subsequent detail or badge refreshes leave manual scrolling alone. - -Ghost empty-list and preview messages come from the pure `HistoryPanelDecisions.ArchiveStatus`: it reads one `HistoryArchiveFacts` observation (section, account, list read, Ghost sync phase, filters, row count, the selected battle's replay and detail, each native board's status) and returns the list message, one message per board, and the page label mode. An unavailable game profile explains account filtering and hides the Ghost page totals. An empty page reports loading, a read failure, a running sync, or active filters, in that order; after a failed sync it says the list may be incomplete rather than that nothing is saved, while the status bar keeps the failure detail. Undownloaded replays invite downloading before showing the board. Existing replay state distinguishes expired and unavailable data; download progress and failures appear only on the affected battle. Locally saved but unreadable or missing data suggests fetching it again. Native board callbacks store only their status, so every refresh re-derives the same copy and an unchanged board cannot retain a stale message. `TrySyncGhostBattlesAsync` alone writes a running, failed, or completed sync phase; `OnPanelHidden` and `ObserveAccount` reset it, because a sync its session cancelled returns without touching state. That cancelled request may still be unwinding when the next session syncs, so `GhostBattleSyncService.SyncRecentBattlesAsync` queues the new sync behind it instead of failing; a new account's sync therefore runs after an account change mid-sync. - -Downloaded Ghost facts remain visible regardless of discovery age. Maintenance traverses hidden `local_ready` rows in bounded batches and restores only payloads with matching battle/account identities; the conditional update also checks bundle identity. Undownloaded facts expire after the discovery window. `HistoryPanelDataService.MaintainGhosts` reports how many rows it expired and restored; it runs beside the page read, so the open Ghost page reloads when either count is non-zero, refreshing its rows and total. Ghost files are bounded to 16 MiB compressed and 64 MiB expanded; rejection preserves the file (`src/BazaarPlusPlus/Game/HistoryPanel/Storage/HistoryPanelDataService.cs`). Native Gameplay/MenuShortcuts input is suppressed by a manager-scoped lease while the account input is focused, reapplied after native context updates, and restored from the current context when focus ends (`src/BazaarPlusPlus/GameInterop/Input/NativeTextInputLease.cs`). - -Favorites is History's third section. A favorite is a snapshot, not a link: `favorite_battles` copies the battle's display columns and board snapshots with no foreign key, so deleting the run or expiring the Ghost row keeps it, and its list read never opens the snapshot columns. `HistoryFavoriteService` (`src/BazaarPlusPlus/Game/HistoryPanel/Favorites/HistoryFavoriteService.cs`) also writes the battle's replay to its own file under `FavoriteBattles/`, outside replay retention: a local battle loads through `CombatReplayRuntime.TryLoadSavedBattle` under the playback payload lease, a Ghost battle downloads and is identity-checked as a Ghost replay would be, and the copy is verified before its row is inserted (`favorite_payload_state` says whether it exists). One gate serializes saves, removals and the once-per-launch orphan sweep, which skips copies younger than an hour. Source loading happens before the gate; saving rechecks membership under the gate before writing a copy, so overlapping adds through one service preserve the first favorite. The factory supplies the game-dependent load, availability and playback callbacks; the service retains ownership of verification, persistence and cleanup. `tests/HistoryPanelRepository.Tests/HistoryFavoriteWorkflowTests.cs` exercises that lifecycle through the service with real SQLite and compressed files, including failure cleanup and replay after deleting the source Run. A favorite replays its copy as `CombatReplayPlaybackSource.Favorite`, so playback never touches the original payload. Rows keep their origin's layout: a Local-origin favorite shows both boards, a Ghost-origin favorite only the challenger's. The note is edited in a dialog and capped at `RunLogSchema.FavoriteNoteMaxLength`. - -HistoryPanel keeps replay, recording and deletion beside the archive. Its More dialog contains database status, remote health probing, supporter attribution and the BazaarDB account-link form (`src/BazaarPlusPlus/Game/HistoryPanel/Ui/HistoryPanelView.Actions.cs`). The dialog owns a foreground canvas above the native board canvases. The account-link card POSTs a one-time code to the bazaardb.gg redeem endpoint through `BazaarDbLinkClient`, built at startup on a dedicated 30s-timeout HttpClient independent of the mod-api base URL (`src/BazaarPlusPlus/Plugin.cs`), with only a local per-account hint persisted by `Game/HistoryPanel/AccountLink/BazaarDbAccountLinkStore.cs`. The binding itself belongs to the BazaarDB account and survives mod updates. The card stays visible when uploads are disabled or the game is PTR, explaining the reason without a form. `HistoryPanelMount` hands the panel one live `AccountLinkGate` from `HistoryPanelDecisions.ResolveAccountLinkGate` (upload setting plus build channel). When available, the linked row explains persistence even while the form is collapsed; `HistoryPanelDecisions.ResolveAccountLinkCard` owns every card field from that gate, the account and link-in-progress state. Server health display state is derived from the mod API health probe result without changing storage state (`src/BazaarPlusPlus/Game/HistoryPanel/HistoryPanelServerHealth.cs`). - -`HistoryPanelMenuEntry` appends an owned data row after merchandise in the native navigation menu. `HistoryPanelMenuPatches` reaches it through `BppPatchHost`. Accepted replay launches retain the history origin; when the replay session finishes and `SceneLoader.ActiveScene` is `HeroSelectScene`, the panel reopens with its selection and scroll positions preserved. - -`GameInterop/ItemBoardPreview` provides board planning shared by HistoryPanel and LiveBuildPanel. `BppItemBoardSlotPlanner` plans cards onto a 10-socket board, with special handling for selectable shop/container boards (`src/BazaarPlusPlus/GameInterop/ItemBoardPreview/BppItemBoardSlotPlanner.cs`). Both panels project planned items through `NativeMonsterBoardItemMapper` and render owned native `MonsterBoardTooltip` instances through `GameInterop/MonsterBoardPreview`; Collection retains the shared measured frame-height proportion for its independent card fitter. - -LiveBuildPanel owns an opaque full-screen uGUI view over the native Collection background. A right overview holds the title with a top-right close action, a compact corpus section with its refresh action in the heading and freshness/status underneath, a build navigation section with the page count and two large previous/next buttons, and a vertical supporter list. Four simultaneous peer sections on the left show recommendation, shop, stash, and current board; fine rules and spacing separate their contents over one consistently dimmed native backdrop, with a stronger rule for the recommendation. The overview uses a vertical rule rather than an opaque slab. Navigation chevrons use one closed mesh with shared vertices through the elbow. `LiveBuildPanelLayout` divides the height-scaled canvas between equal item-only carpet regions after reserving headers, metrics, and candidate tags; the carpet is height-constrained, so every unit given to the metrics row is taken from card size. Match evidence renders as one fixed cell per metric (an 11px label over a 16px value) because a single concatenated line ellipsized the last metric away on narrow panels, and the no-recommendation guidance owns a separate slot rather than sharing the metric styling. Native sockets and size spans determine placement. Titles, empty/loading status, and metrics align with the loaded carpet's horizontal bounds; those bounds position the overview and section decoration without resizing the preview region itself. Candidate state remains feature-owned and keyed by template id across selectable sources; the native adapter reports loaded frame geometry and template identity, and the view positions non-interactive native-art tags beneath those frames. Native hover stays on the prefab. Replacement and close synchronously end the tracked hover; close hides and detaches each owned root before waiting for native acquisition to finish and settling all rentals, including failed setup. No card setup is cancelled mid-acquisition. A weak identity gate rejects late native tooltip shows after the owning board retires, without hiding another owner’s tooltip. - -The board adapter uses `NativeCardPrefabLoader` to rent native prefabs, records ownership before Resize/SetUp, validates loaded art/frame state, and restores prefab layout before pool return. Missing templates are cached per static-data manager; partial failure preserves successful cards. Item and skill hover events register borrowed targets with `NativeCardPreviewHost`, which applies the existing tooltip refresh transaction without owning board rentals. Locked/secondary tooltips retain their existing skip policy. Geometry revisions drive LiveBuild marker updates; stable frames skip forced layout, recursive board fitting and marker rebuilds. - -## Gotchas - -Traps and rules that bite only this feature; most failed silently at least once. - -- Main-menu scene identity is `SceneID.HeroSelectScene`, but the loaded Unity scene is named `MainMenuScene` in current builds. Use `SceneLoader.ActiveScene` and `IsSceneLoaded` for replay return gates; comparing the scene name to `HeroSelectSceneName` silently prevents reopening history. [`src/BazaarPlusPlus/Game/HistoryPanel/HistoryPanel.cs`] -- Owned `MonsterBoardTooltip` clones must inherit the host canvas sorting: the donor has `overrideSorting=true` at order 0, hiding its opaque, correctly loaded cards behind history at order 26. Settle all rentals, restore prefab layout, and detach before returning to the native pool; pooling does not reparent. Fit the carpet from its own four corners: recursive bounds include card/gem overhang and shift opposing boards differently. [`src/BazaarPlusPlus/GameInterop/MonsterBoardPreview/OwnedMonsterBoardPreview.cs`] -- Android's native `LetterBoxOverlays/Canvas` can cover panel edges even while Unity reports a full-screen safe area. BPP-owned panel, preview and inspection layers must stay above it and below native system popups; changing layout margins cannot fix that occlusion. [`src/BazaarPlusPlus/Infrastructure/UiTokens/BppOverlaySorting.cs`] -- `LetterBoxManager.CurrentScreenRect` is normalized, not pixels: `BazaarCanvasScaler` multiplies it by screen dimensions. Fullscreen overrides must update both the returned crop and its cache to `(0,0,1,1)`; pixel dimensions inflate native tooltip scaling and push the mobile drawer off screen. [`src/BazaarPlusPlus/Patches/Android/AndroidLetterboxPatches.cs`, `AndroidLetterBoxCropPatch`] -- Android LiveBuild pixel-to-layout conversion uses its intended height baseline, not transient `Canvas.scaleFactor` values during hide/recreation. A temporary factor of 1 can turn a valid native rail into an oversized overview and move all sidebar controls off screen. [`src/BazaarPlusPlus/Game/LiveBuildPanel/Ui/LiveBuildPanelView.cs`, `CanvasScale`] -- Android has no hover, so item inspection is a long press everywhere except the Collection grid (tap). In-run items inspect after a native hold (`InRunItemLongPressInspectionPatch`); LiveBuild and History board cards use `BoardLongPress` and `CollectionInspectionModule.RequestPreviewInspection`, which keeps the card's native hover (suppressing its touch-release `OnHoverOut`) until the inspection closes, then hovers out. Both panels report the inspection as modal so Back closes it first. [`src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionModule.cs` | `GameInterop/MonsterBoardPreview/NativeBoardHoverPatch.cs`] -- Panel toggle hotkeys are filtered per registration by `HotkeyGuard`, where returning false swallows the press. HistoryPanel deliberately will not close while a text field is focused. [`src/BazaarPlusPlus/Game/OverlayPanels/OverlayPanelHost.cs` | `Game/HistoryPanel/HistoryPanel.cs`] -- HistoryPanel work cancelled by a session change (`_session` Begin/End) bails on `!IsCurrent` without resetting state, so each session boundary resets the in-progress flags and the Ghost sync phase; a flag left set turns the link row inert or blocks every later sync. [`src/BazaarPlusPlus/Game/HistoryPanel/HistoryPanelCoordinator.cs`] -- An MP4 recorded from a favorite is stored under the original battle id, so the installer's run cleanup, which deletes the videos of a cleaned run's battles, also deletes it; the favorite and its replay copy survive. [`bazaarplusplus-installer/src-tauri/src/history/cleanup.rs`] -- Scenario capsules construct HistoryPanel types positionally, so their ctor shape is pinned behavior: `HistoryPanelDependencies`' single ctor stays guard-free direct assignment (null guards break it at construction). [`src/BazaarPlusPlus/Game/HistoryPanel/HistoryPanelDependencies.cs` | ADR-0003] diff --git a/bazaarplusplus-mod/docs/architecture/previews.md b/bazaarplusplus-mod/docs/architecture/previews.md deleted file mode 100644 index 3c7027d..0000000 --- a/bazaarplusplus-mod/docs/architecture/previews.md +++ /dev/null @@ -1,27 +0,0 @@ -# Encounter Preview, Card Preview, And Tooltips - -The Encounter Preview query boundary, the native card preview owning module, and the tooltip presentation surfaces. `GameInterop/Tooltips` holds two adapters that must not be merged. - -`EncounterPreviewModule` is the single owner of event, encounter-step, and hero-level preview semantics, from cache identity and plan compilation through localization and final presentation; all three query kinds resolve to the single `EventPreviewResult` record (`src/BazaarPlusPlus/Game/EventPreview/EncounterPreviewModule.cs`). Its typed query interface accepts only stable template ids/current level plus native text already present at the patch boundary; game state (the current static-data source, hero, inventory, one generation-matched day-tier result, native keyword typography) is read through `IEncounterPreviewGameRuntime` (`src/BazaarPlusPlus/Game/EventPreview/EncounterPreviewGameRuntime.cs`). Beginning a source generation first removes the old snapshot; generation checks prevent a superseded load from publishing, while a successful compile remains published with degraded status if its cache write fails (`src/BazaarPlusPlus/Game/EventPreview/EncounterPreviewPlanRegistry.cs`). The disk cache stays because a cold start is slow: measured 2026-10-03 on macOS, game `1.0.12575-staging-macos-arm64-fecb8f8e` (Steam build 25661913), time-to-ready from the observed new source to `event_preview.plans.ready` was 6.1 s median cold (6106/5946/6256 ms; compile itself 0.55 s, the rest loading the card map the compiler needs, which a cache hit skips) against 0.17 s warm (181/164 ms), while the main thread saw 83–86 frames over 50 ms with a worst frame of 466 ms cold versus 4 slow frames and a worst of 200 ms warm — a temporary probe in `EventPreviewStaticDataObserver.Update` timed the window and summed `Time.unscaledDeltaTime` per frame (#161). - -`EventPreviewStaticDataObserver` is only the Unity frame adapter that reports a newly ready source to the module (`src/BazaarPlusPlus/Game/EventPreview/EventPreviewStaticDataObserver.cs`). Tooltip patches receive the module through the `BppPatchFeatures` bundle and consume semantic results; they do not read plans, static-data maps, inventory, or CollectionPanel formatters (`src/BazaarPlusPlus/Patches/BppPatchFeatures.cs`, `src/BazaarPlusPlus/Patches/Tooltips/`). `CardAbilityValueReader` centralizes the shared reflection seam over game-authored ability/aura action and attribute values; Event Preview and Collection keep their separate localization and typography policies (`src/BazaarPlusPlus/GameInterop/Cards/CardAbilityValueReader.cs`). `GameDataDayTierResolver` is the shared GameInterop day-tier owner for Collection's Day gate and Event Preview: it exposes typed unavailable states, retries transient readiness, and rejects an Event Preview query whose plan source is no longer the current manager; its generation-keyed caching and `MaximumTier` semantics are pinned in `docs/MEMORY.md` (`src/BazaarPlusPlus/GameInterop/DayTiers/`). - -`GameInterop/CardPreview` is the owning module for native card prefab selection, instantiation, setup/resize, reflection, hover state, tooltip replacement, pooling, and destruction. Production callers see only `INativeCardPreviewHost`, a per-owner `INativeCardPreviewScope`, and opaque `INativeCardPreviewSession` intent operations (`src/BazaarPlusPlus/GameInterop/CardPreview/NativeCardPreviewContracts.cs`). Each scope has its own pool: closing rejects new acquisitions, cancels and waits outstanding setup, invalidates/destroys active sessions, then destroys idle objects; a session released after closing cannot re-enter the pool (`src/BazaarPlusPlus/GameInterop/CardPreview/NativeCardPreviewScopeLifetime.cs`). Successful acquisition means the game template resolved, a synthetic instance was built, the owner prepared the inactive prefab, and native setup plus resize completed before the session was delivered (`src/BazaarPlusPlus/GameInterop/CardPreview/NativeCardPreviewFactory.cs`). Card prefab instantiation remains owned here, while `GameInterop/AssetLoading` owns cross-build `AssetLoader` signature adaptation; card previews request the native current scope rather than the `Global` lifetime used by process-static caches. The host also owns complete presentation visibility: the game's `CardPreviewBase.Show` covers only art/frame, so item gem groups remain concealed through setup and cancellation, are revealed only after a successful session `Show`, and are always concealed by `Hide` (`src/BazaarPlusPlus/GameInterop/CardPreview/NativeCardPreviewPresentation.cs`). Concrete pool/runtime/reflection/resource types are confined to this owning module by `NativeCardPreviewArchitectureTests`. - -Enchant preview visibility is a three-state setting controlled by `PreviewVisibilityMode`: `Off`, `AutoOnPedestalChoice`, and `Always` (default `Always`). `ItemEnchantPreviewSettingsDockEntry.Create()` supplies its cycle order (`Off → AutoOnPedestalChoice → Always`), and `BppSettingsDockCatalog.ResolvePreviewVisibilityModeStatus` its status labels (`src/BazaarPlusPlus/Game/ItemEnchantPreview/ItemEnchantPreviewSettingsDockEntry.cs`). Enchant text is useful always but can be noisy or irrelevant, hence the automatic pedestal-relevance mode between the explicit off/always choices; upgrade preview is an on-demand comparison, so it deliberately has no visibility mode, only `Hold` (default) or `Toggle` activation for its Shift key, persisted as `[Hotkeys] UpgradePreviewActivationMode` with no legacy boolean migration. `HotkeyActivationState` resets the latched toggle state when the activation mode or binding changes and processes at most one transition per frame (`src/BazaarPlusPlus/Game/Input/HotkeyActivationState.cs`). - -`TooltipPreviewModePolicy` owns preview priority: upgrade hotkey wins first, then enchant hotkey, then enchant `Always`, then enchant `AutoOnPedestalChoice` only when the current choice pedestal is an enchant pedestal (`src/BazaarPlusPlus/Game/Tooltips/TooltipPreviewModePolicy.cs`). A `TooltipModifierRefreshController` mountable re-resolves open preview tooltips when the Ctrl/Shift hold state changes: for both ordinary game cards and hovered synthetic previews, refresh verifies the visible primary tooltip belongs to the hovered session, keeps the existing native controller alive, replaces its `CardTooltipData`, and synchronously settles layout behind a temporary visibility gate; it never replays native hide/show positioning and fades (`src/BazaarPlusPlus/Game/Tooltips/TooltipModifierRefreshController.cs`, `src/BazaarPlusPlus/GameInterop/Tooltips/NativeCardTooltipContentRefresher.cs`). The tooltip patch surface also covers encounter/event tooltips (gated by the `Game/EventPreview` settings toggle), quest reward previews and aggregate-item missing types (separate implementations sharing the default-off `QuestPreview/Enabled` gate), and hero level rewards (`src/BazaarPlusPlus/Patches/Tooltips/`); disabling Quest Preview immediately restores tracked native quest text/layout and hides its pooled aggregate-item sections. Mod-appended text goes through the shared `BppTooltipSections` helper, which keeps the cloned native donor typography and attaches the game's own zh-CN fallback chain only when BPP-authored content contains CJK (`src/BazaarPlusPlus/Patches/Tooltips/BppTooltipSections.cs`). - -`GameInterop/Tooltips` holds two unrelated native-tooltip adapters that must not be merged. `NativeCardTooltipContentRefresher` replaces the `CardTooltipData` of an already-visible primary tooltip and settles its layout. `NativePairedTooltipHost` owns the separate "custom content inside the native auxiliary tooltip, pinned beside the native card tooltip" presentation: native state capture/restore, the `CanvasGroupGate` visibility gates, the cloned native background, the paired fade, side selection, and coordinate conversion (`src/BazaarPlusPlus/GameInterop/Tooltips/NativePairedTooltipHost.cs`). Composition creates one plugin-lifetime host; it is not `IDisposable`, and the releasable unit is the `NativePairedTooltipSession` a feature acquires from it. The host reports placement outcomes through `PlacementResult` and never logs: reason codes, their once-only latches, and native show/hide arbitration stay with the consuming feature, because that latch behavior decides how many records reach the log. It also does not arbitrate the native auxiliary singleton; other code drives it directly (`src/BazaarPlusPlus/Game/CombatReplay/CurrentReplayRecordingButtonController.cs`), so a single active session serializes only this host's own usage. Purely geometric decisions are the unit-tested `NativePairedTooltipPlacementMath`; the shared `NativePairedTooltipMetrics.Epsilon` deliberately serves both as a geometry tolerance and as the CanvasGroup alpha interactivity threshold. Combat Impact is currently the only consumer, supplying its own trim strategy through `IPairedContentBudget`; its `NativePostCombatImpactTooltipView` is a feature UI adapter rather than a Harmony patch, so by the layering rules it belongs under `Game/` and stays in `Patches/` as recorded debt. The host's generality is "multiple features sharing this paired shape", not "any native tooltip host". `NativePairedTooltipArchitectureTests` keeps this module free of feature and patch dependencies. - -## Gotchas - -Traps and rules that bite only this feature; most failed silently at least once. - -- Rendering the reused uGUI card prefab through an offscreen camera into a `RenderTexture` silently yields an empty texture under URP — native board previews stay on the `ScreenSpaceOverlay` canvas; do not re-propose the RT path. -- Pooled native tooltip clones share one root-canvas `sortingOrder`, and `overrideSorting` cannot be set on a root canvas. Layering a BPP preview above the other (locked) clone means raising this clone's root-canvas order while visible, refcounted per clone and `TooltipElevationReason`; sibling order inside the prefab is irrelevant. This bug class recurred four times: on Android any card tooltip shown while another clone is locked (a long-pressed monster board's cards) is raised as well, since pool reuse decides the tie from the second encounter on. [`src/BazaarPlusPlus/Patches/Tooltips/TooltipLayerOverride.cs` | `src/BazaarPlusPlus/Patches/Tooltips/LockedTooltipStackingPatch.cs`] -- The only working concealment seam for the native auxiliary tooltip is the `auxParent` CanvasGroup gate: `Tooltip_Aux_P`'s `auxParent` owns the complete visual tree, and a CanvasGroup on the controller root sits above the prefab's nested Canvas — silently inert. Teardown keeps the gate closed; owned gates `DestroyImmediate` on restore, since a deferred destroy leaves an end-of-frame corpse that `GetComponent` adopts and silently ungates. [`src/BazaarPlusPlus/GameInterop/Tooltips/NativePairedTooltipHost.cs` | `tests/NativePairedTooltipHost.Tests/`] -- Native `ShowAuxiliaryTooltipController` only `SetText`s — it never reactivates header/body, so a pooled controller handed back with inactive text nodes collapses to a tiny empty frame over the board. The show handoff force-reactivates requested nodes; a frame audit conceals `visible_without_text` leftovers. [`src/BazaarPlusPlus/GameInterop/Tooltips/NativePairedTooltipHost.cs`] -- Locking a native card tooltip (`SetLockedFlag(true)`) re-enables `blocksRaycasts` via `ToggleInteractabilityOnCanvas`; a tooltip overlapping the pointer then steals hover, and the synthetic `PointerExit` yields a show/hide flicker loop. Keep the lock but force raycasts off while BPP owns the controller. [`src/BazaarPlusPlus/Game/PostCombatImpact/PostCombatImpactController.cs` | `src/BazaarPlusPlus/Patches/PostCombatImpact/PostCombatImpactRecapPatch.cs`] -- Synthetic or unknown GUIDs must not repeatedly reach native-preview template lookup; the grid negative-caches `TemplateUnavailable` per catalog generation. [`src/BazaarPlusPlus/GameInterop/CardPreview/NativeCardPreviewFactory.cs`] -- Mod-appended tooltip text goes through `BppTooltipSections`, which clones the tooltip's own passive-text block at 0.75 font scale, keyed per controller and purpose. [`src/BazaarPlusPlus/Patches/Tooltips/BppTooltipSections.cs`] diff --git a/bazaarplusplus-mod/docs/architecture/text.md b/bazaarplusplus-mod/docs/architecture/text.md deleted file mode 100644 index fc365e6..0000000 --- a/bazaarplusplus-mod/docs/architecture/text.md +++ /dev/null @@ -1,23 +0,0 @@ -# Typography, Localization, Voice Subtitles, And Supporters - -Every BPP surface gets its text rendering from one adapter over the game's own font assets. Localization resolution, voice-over subtitles, and supporter attribution all sit on top of it. - -`BazaarPlusPlus.Localization` is the localization resolution engine. The `L` facade is installed at plugin startup with language and locale-mode providers, then resolves `LocalizedTextSet` values against current language and Chinese locale mode (`src/BazaarPlusPlus.Localization/L.cs`, `src/BazaarPlusPlus/Plugin.cs`). In Taiwan mode, text without an authored Traditional string is derived by `ChineseScriptConverter`: longest-match word overrides for one-to-many characters (头发→頭髮, 面包→麵包, with 里 kept in names), then the OpenCC-derived character table, then Taiwan vocabulary terms. The word list covers mod literals and the voice-line catalog, and `RuntimeIntegration.Tests` `TraditionalChineseConversionTests` fails when a Chinese literal compiled into the mod still carries a Simplified-only character after conversion (`src/BazaarPlusPlus.Localization/ChineseScriptConverter.cs`, `src/BazaarPlusPlus.Localization/OpenCcTraditionalCharacters.cs`). Chinese a feature shows without a `LocalizedTextSet`, such as voice-subtitle rows and Combat Impact's Chinese formatter branches, goes through `L.ResolveChinese` at display time, so stored and remote data stay Simplified. - -BPP does not embed, extract, select, or create an operating-system font. Every feature calls the single `NativeGameTypography` adapter and never receives a raw `Font`, `TMP_FontAsset`, fallback chain, or `PanelTextSettings`. The adapter keeps the renderer-specific implementation private: native TMP labels retain their donor primary font and material while a cloned primary receives the corresponding game fallback chain; BPP-created uGUI uses an opaque prepared binding over the game's loaded sans primary plus the complete ordered `zh-CN` Static → SecondSet → Dynamic chain; UI Toolkit uses a panel-local scope over the Dynamic asset's packaged `UnityEngine.Font` source because it cannot consume TMP assets directly (`src/BazaarPlusPlus/GameInterop/Fonts/NativeGameTypography.cs`). - -`PrepareOwnedText` preserves fail-before-create behavior for BPP TMP trees. Its binding establishes orthographic uGUI measurement before activation: TMP otherwise measures a hidden tree at one-tenth scale until `Awake`, causing eagerly cached supporter widths to collapse. Text rectangles must also fit the actual glyph height; an ellipsis overflow on the first glyph can clear the entire mesh. These behaviors require Unity runtime measurement rather than pure layout tests. `EnsureNativeTextCoverage` augments donor TMP without exposing how the chain is selected. `TryAttachPanel` atomically installs a panel-local `PanelTextSettings` bound to the game's sans body font; its scope is the only code that sets both `unityFont` and `unityFontDefinition`, checks external text against the actual selected font, and releases the panel settings. OS and emoji fallback remain disabled, global game settings are never mutated, and all Unity mutation is guarded to the initialization thread. The adapter restores donors, prunes destroyed donor bindings, invalidates outstanding scopes, and releases every owned handle/clone at teardown (`src/BazaarPlusPlus/GameInterop/Fonts/NativeGameTypography.cs`). - -`Game/VoiceSubtitles` renders in-game voice-over subtitles (the BazaarLine integration): `VoiceSubtitlesModule` plus a `GameInterop/VoiceSubtitles` bridge module observe game VO playback (`src/BazaarPlusPlus/BppComposition.cs`), and `VoiceLineDisplayDispatcher`/`VersionLabelScanner` mountables render cues. The line catalog is supplied under its stable manifest name by the shared remote-data build pipeline; `VoiceLinesCatalogFactory` contributes the parser and feature logging policy to `RemoteEmbeddedCatalog` (`src/BazaarPlusPlus/RemoteEmbeddedData.targets`, `src/BazaarPlusPlus/Game/VoiceSubtitles/VoiceLinesCatalogFactory.cs`). The feature module owns this catalog for its own lifetime and disposes it before clearing the static line catalog, so a late remote continuation cannot republish after `Stop()` (`src/BazaarPlusPlus/Game/VoiceSubtitles/VoiceSubtitlesModule.cs`). The feature is gated by a master toggle (default OFF) in `BazaarPlusPlus.cfg` `[VoiceSubtitles]` (`src/BazaarPlusPlus/Game/VoiceSubtitles/VoiceSubtitlesGate.cs`, `src/BazaarPlusPlus/Core/Config/BppConfig.cs`), with a four-state Subtitle Mode dock row registered via `VoiceSubtitlesSettingsDockEntry.RegisterAll`. Subtitle labels preserve the version-label donor font/material when it already covers Chinese. If it does not, mounting waits until the game's Chinese font configuration exists, then renders the Chinese row through `TextMeshProUGUI` using the game sans primary clone with its complete Chinese fallback chain and without synthetic bolding (`src/BazaarPlusPlus/Game/VoiceSubtitles/VersionLabelScanner.cs`, `src/BazaarPlusPlus/Game/VoiceSubtitles/VoiceLineDisplay.cs`). Because that font choice probes Simplified glyphs only, a Taiwan-mode row whose converted glyphs the renderer font and its fallbacks lack keeps its Simplified text and logs `traditional_glyphs_missing` once (`VoiceLineDisplay.DisplayChinese`, `FontDiagnostics.GlyphProbe`). - -Supporter attribution is a game-side display module, not a generic sampling utility. `BPPSupporters.SampleMany()` and `Sample()` delegate to `BPPSupporterCatalog.GetCurrentEntries()` and `BPPSupporterSampler` (`src/BazaarPlusPlus/Game/Supporters/BPPSupporters.cs`). `SupporterCatalogModule` is the composition-owned third consumer of `RemoteEmbeddedCatalog`; fixed-list mode bypasses factory/warm entirely, normal mode loads the game-root cache or embedded seed and queues the remote refresh, and a missing snapshot is latched for five minutes before access may schedule another warm (`src/BazaarPlusPlus/BppComposition.cs`, `src/BazaarPlusPlus/Game/Supporters/SupporterCatalogModule.cs`). The static `BPPSupporterCatalog` is only config, fixed-list policy, and the published snapshot projection; the module disposes the catalog before clearing that projection, so late callbacks cannot republish (`src/BazaarPlusPlus/Game/Supporters/BPPSupporterCatalog.cs`, `src/BazaarPlusPlus/Game/Supporters/SupporterCatalogModule.cs`). - -HistoryPanel, CollectionPanel, and LiveBuildPanel consume supporter samples. HistoryPanel and LiveBuildPanel share `BPPSupporterNativeAttributionRow`, which applies `NativeGameTypography` to fixed-size literal names, tier colors and gradients, localized attribution, and the support action; History uses an inline row and LiveBuild uses a vertical list that gives each name its own line (`src/BazaarPlusPlus/Game/Supporters/Ui/BPPSupporterNativeAttributionRow.cs`). Collection uses a UI Toolkit attribution row. In the UI Toolkit row, every prefix, name, separator, suffix, and action element pins both `unityFont` and `unityFontDefinition` to the same game source font so Latin and CJK names cannot diverge through a child theme font definition; supporter names use the font's normal weight rather than synthetic bold (`src/BazaarPlusPlus/Game/Supporters/Ui/BPPSupporterAttributionRow.cs`). This module should stay separate from feature-specific UI behavior. - -## Gotchas - -Traps and rules that bite only this feature; most failed silently at least once. - -- VoiceSubtitles labels clone the donor label's font and material and must keep `TextWrappingModes.Normal` + `TextOverflowModes.Overflow`. NoWrap+Ellipsis at a scaled font hits TMP's `m_characterCount == 0` branch and the whole subtitle block disappears. [`src/BazaarPlusPlus/Game/VoiceSubtitles/VoiceLineDisplay.cs`] -- CJK text that renders as tofu is routed through `NativeGameTypography`, which applies the game's native serif/sans and extends BPP-owned text with a CJK fallback chain. Fix the font route, not the copy. [`src/BazaarPlusPlus/GameInterop/Fonts/NativeGameTypography.cs`] -- `NotoFontFallbackRuntime` publishes its configuration before either primary finishes loading, so a null primary seconds after startup is that loading window, not a missing game font: `PrepareOwnedText` answers `Outcome.Waiting` instead of baking `TMP_Settings.defaultFontAsset` into a BPP tree, and `degraded` is reported only once one primary is published — its `role`, `sans_primary`, and `serif_primary` fields name the gap. [`src/BazaarPlusPlus/GameInterop/Fonts/NativeGameTypography.cs`] diff --git a/bazaarplusplus-mod/docs/contracts/run-payload-v6.md b/bazaarplusplus-mod/docs/contracts/run-payload-v6.md deleted file mode 100644 index e9cd756..0000000 --- a/bazaarplusplus-mod/docs/contracts/run-payload-v6.md +++ /dev/null @@ -1,81 +0,0 @@ -# Run payload V6 contract - -The Run segment inside a V6 Bundle uses media type `application/x-bpp-run-v6`. Its bytes are a -gzip stream containing one MessagePack `RunPayloadV6` object. Bundle validation, segment length, -and the compressed-segment SHA-256 are handled before this payload is decompressed. - -## Compatibility - -- `payload_format_version` is `6` (`RunPayloadV6.PayloadFormatVersion`, MessagePack key `0`). -- The serialized graph is public because it is decoded in the Unity/Mono runtime. -- Every DTO is encoded as a MessagePack array with the numeric keys declared by its `[Key]` - attributes. Existing keys are immutable. Additive fields must use new trailing keys. -- A decoder must reject a version other than `6`, a non-gzip input, malformed MessagePack, or a - decompressed payload larger than 64 MiB. -- `RunId` and `PlayerAccountId` must equal the enclosing Bundle manifest before any Battle replay is - consumed. - -## Root object - -| Key | Property | Type | Meaning | -|---:|---|---|---| -| 0 | `PayloadFormatVersion` | int | Always `6` | -| 1 | `RunId` | string | Stable local Run identity | -| 2 | `PlayerAccountId` | string | Frozen Run player identity | -| 3 | `Run` | `RunFactsV6` | Final Run facts | -| 4 | `Events` | `RunEventV6[]` | Run events ordered by sequence | -| 5 | `Battles` | `RunBattleV6[]` | Battle facts and optional replay inputs | -| 6 | `ReplayableBattleIds` | string[] | Battles retaining snapshots and all replay phases | -| 7 | `Degradation` | `PayloadDegradationV6` | Deterministic size/input degradation record | - -Every time is a Unix millisecond integer (MessagePack int): `RunFactsV6` keys `3` and `4` -(`StartedAtMs`, nullable `EndedAtMs`), `RunEventV6` key `1` (`TimestampMs`), and `BattleFactsV6` -key `0` (`RecordedAtMs`). - -## Nested objects - -`RunFactsV6` records hero, mode, seed, start/end time, terminal status, day/hour, wins/losses, -starting and final rank/rating, rating delta, final economy/build values, build channel, and mod -version. Its keys are `0..21` in property declaration order. - -`RunEventV6` uses keys `0..3` for sequence, timestamp, kind, and the structured event JSON. -`PayloadJson` does not repeat `run_id`, `seq`, `ts`, or `kind`: the Run root and the event's keys -`0..2` own them, and every consumer reads them from there. The JSON keeps the remaining fields of -the stored event in stored order, including `schema_version` (`RunLogEvent.PayloadSchemaVersion`); -`RunPayloadComposer.EventPayloadBody` does the stripping. The Bundle pipeline does not reinterpret it. - -`RunBattleV6` uses keys `0..4` for Battle ID, `BattleFactsV6`, `BattleParticipantsV6`, nullable -`BattleCardSnapshotsV6`, and nullable `BattleReplayV6`. A Battle is replayable only when both -nullable fields exist, Spawn, Combat, and Despawn replay byte arrays are non-empty, and snapshots -contain exactly one non-`Missing` set for each of `player_hand`, `player_skills`, `opponent_hand`, -and `opponent_skills`, with no duplicate or extra set. `RunBundleV6Contract` owns this predicate on -both composition and ghost-import paths. - -`BattleParticipantV6` carries account/display/hero/rank/rating/level/prestige/victories plus -payload-only income, gold, hand-item count, and skill count. The counts (keys `10` and `11`) are the -number of `Item`-type cards in that side's `*_hand` set and of `Skill`-type cards in its `*_skills` -set, and are `null` when that set is `Missing`. `RunPayloadComposer` counts them before the size -budget runs, so they remain when trimming drops a Battle's snapshots. Bundles sealed before the -composer wrote them carry `null` for both. Manifest projection normalization is a separate operation -and does not copy nullable payload values blindly. - -`BattleCardSnapshotsV6` contains the four captured card sets. `BattleCardV6` preserves stable -template and instance identity, type/size/location, display metadata, tags, and integer attributes. - -`BattleReplayV6` uses keys `0..3` for replay version and the native Spawn, Combat, and Despawn -MessagePack byte sequences. - -`PayloadDegradationV6` uses keys `0..3` for categories, replay-omitted Battle IDs, omitted event -count, and whether a requested Screenshot was omitted. It describes the final immutable payload; -it is not a retry state. - -## Golden - -The stable encoded sample is -`tests/BundleV6Codec.Tests/fixtures/run-payload-v6.fixture.b64`. The mod codec test decodes this gzip -fixture and pins its decompressed MessagePack bytes (`BPP_UPDATE_GOLDENS=1` rewrites it); gzip -headers and deflate output can vary by OS/runtime. The analyzer reads the same file and checks its -Run, Battle, card, and quality rows against its -[expected projection](../../../bazaarplusplus-analyzer/tests/fixtures/run-payload-v6.projection.json). -Bundle envelope goldens are owned by the [server contract fixtures](../../../bazaarplusplus-server/contracts/v6/fixtures/); -the mod test project links those files directly. diff --git a/bazaarplusplus-mod/global.json b/bazaarplusplus-mod/global.json deleted file mode 100644 index 1e05653..0000000 --- a/bazaarplusplus-mod/global.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "sdk": { - "version": "8.0.100", - "rollForward": "latestMajor", - "allowPrerelease": false - } -} diff --git a/bazaarplusplus-mod/mod.just b/bazaarplusplus-mod/mod.just deleted file mode 100644 index d583953..0000000 --- a/bazaarplusplus-mod/mod.just +++ /dev/null @@ -1,74 +0,0 @@ -set shell := ["bash", "-euo", "pipefail", "-c"] -set positional-arguments - -# Some VPN/tunnel configurations advertise an unusable IPv6 route; see scripts/lib.sh. -export DOTNET_SYSTEM_NET_DISABLEIPV6 := env('DOTNET_SYSTEM_NET_DISABLEIPV6', '1') - -# The four published assemblies; each keeps a committed NuGet lock file. -published_projects := "src/BazaarPlusPlus.Localization/BazaarPlusPlus.Localization.csproj src/BazaarPlusPlus.ModApi/BazaarPlusPlus.ModApi.csproj src/BazaarPlusPlus.Storage/BazaarPlusPlus.Storage.csproj src/BazaarPlusPlus/BazaarPlusPlus.csproj" - -# Check formatting, compile without deploying, and validate the NuGet and snapshot lock files. -check: fmt-check build locks-check lock-check - -# Compile; --deploy also repairs the macOS trampoline and copies into the installed game; [--deploy] [--fast] [-p:Name=Value ...]. -build *args: - bash scripts/build.sh build "$@" - -# Run the offline default xUnit suite; [-p:Name=Value ...]. -test *args: - bash scripts/test.sh test "$@" - -# Run the opt-in Combat Impact acceptance: [report-path] [--benchmark]. -test-corpus +args: - bash scripts/test.sh test-corpus "$@" - -# Format C# files with the repo-pinned CSharpier. -fmt: - dotnet tool restore - dotnet csharpier format . - -# Fail on C# files that the repo-pinned CSharpier would reformat. -fmt-check: - dotnet tool restore - dotnet csharpier check . - -# Rewrite the committed NuGet lock files; review every changed packages.lock.json. -locks: - for project in {{ published_projects }}; do dotnet restore "$project" --force-evaluate; done - -# Validate the committed NuGet lock files without rewriting them. -locks-check: - for project in {{ published_projects }}; do dotnet restore "$project" --locked-mode; done - -# Refresh the remote embedded seeds without building; [-p:Name=Value ...]. -fetch-data *args: - bash scripts/build.sh fetch-data "$@" - -# Decompile game DLLs (default Assembly-CSharp, or `all`) into decompiled/, decompiled-vstaging/ or decompiled-vptr/. -[arg('channel', pattern='online|staging|ptr')] -decompile channel *dlls: - bash scripts/game.sh decompile "$@" - -# Capture the mounted game's Managed dir under game-libs/ and record it in build/game-libs.lock.json. -snapshot: - bash scripts/game.sh snapshot - -# Upload a captured snapshot to the private store; needs the release credentials. -[arg('channel', pattern='online|staging|ptr')] -[arg('platform', pattern='macos|windows')] -publish platform channel: - node ../scripts/workspace.mjs run release -- bash scripts/game.sh publish "$@" - -# Make one lock entry's Managed dir available (snapshot, matching Steam install, or private store) and print it. -[arg('channel', pattern='online|staging|ptr')] -[arg('platform', pattern='macos|windows')] -fetch platform channel: - bash scripts/game.sh fetch "$@" - -# Validate build/game-libs.lock.json; empty or stale entries warn, a mismatched Managed dir fails. -lock-check: - bash scripts/game.sh lock-check - -# CompatCheck-compile against every captured lock entry, or against the host platform's named channels (an empty entry fails). -matrix *channels: - bash scripts/build.sh matrix "$@" diff --git a/bazaarplusplus-mod/native/artifacts.json b/bazaarplusplus-mod/native/artifacts.json deleted file mode 100644 index 63609ac..0000000 --- a/bazaarplusplus-mod/native/artifacts.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "schemaVersion": 1, - "platforms": { - "macos": { - "architecture": "arm64", - "deploymentTarget": "12.0", - "signing": "adhoc", - "inputs": [ - "native/mac-audio-tap/BppMacAudio.h", - "native/mac-audio-tap/BppMacAudio.m", - "native/mac-audio-tap/build.sh", - "native/macos/BppNativeLoadSmoke.c", - "native/macos/BppReplayAudioMuxer.mm", - "native/macos/BppReplayVideoToolbox.h", - "native/macos/BppReplayVideoToolbox.mm", - "native/macos/Info.plist", - "native/macos/build.sh", - "native/macos/verify.sh", - "src/BazaarPlusPlus/Game/CombatReplay/Audio/CoreAudioProcessTapCaptureTap.cs", - "src/BazaarPlusPlus/Game/CombatReplay/Audio/ReplayAudioCaptureFactory.cs", - "src/BazaarPlusPlus/Game/CombatReplay/Video/MacMetalVideoEncoder.cs", - "src/BazaarPlusPlus/Game/CombatReplay/Video/MacNativeReplayAudioMuxer.cs" - ], - "artifacts": [ - { - "id": "mac-audio", - "buildScript": "native/mac-audio-tap/build.sh", - "outputPath": "libBppMacAudio.dylib", - "binaryPath": "libBppMacAudio.dylib", - "kind": "file", - "destinationPath": "src-tauri/resources/SourceForBuild/macos/BepInEx/plugins/libBppMacAudio.dylib", - "requiredExports": [ - "BppMacAudio_IsSupported", - "BppMacAudio_Read", - "BppMacAudio_Start", - "BppMacAudio_Stop" - ], - "requiredWeakImports": [ - "AudioHardwareCreateProcessTap", - "AudioHardwareDestroyProcessTap" - ], - "allowedDependencyPrefixes": [ - "/System/Library/", - "/usr/lib/" - ] - }, - { - "id": "mac-replay", - "buildScript": "native/macos/build.sh", - "outputPath": "GfxPluginBppReplayVideoToolbox.bundle", - "binaryPath": "GfxPluginBppReplayVideoToolbox.bundle/Contents/MacOS/GfxPluginBppReplayVideoToolbox", - "kind": "directory", - "destinationPath": "src-tauri/resources/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle", - "requiredExports": [ - "BppVtAcquireSlot", - "BppVtCanMuxAudio", - "BppVtCancelRenderEvent", - "BppVtCommitRenderEvent", - "BppVtCopyError", - "BppVtCreate", - "BppVtDestroy", - "BppVtDiscardRenderEvent", - "BppVtFinish", - "BppVtGetRenderEventFunc", - "BppVtGetSlotCount", - "BppVtGetStats", - "BppVtHasUnityMetalInterface", - "BppVtIsFailed", - "BppVtMuxAudio", - "BppVtPrepareRenderEvent", - "BppVtReleaseSlot", - "UnityPluginLoad", - "UnityPluginUnload" - ], - "requiredWeakImports": [], - "allowedDependencyPrefixes": [ - "/System/Library/", - "/usr/lib/" - ] - } - ] - }, - "windows": { - "architecture": "x64", - "signing": "unsigned", - "inputs": [ - "native/windows/BppReplayMediaFoundation.cpp", - "native/windows/BppReplayMediaFoundation.h", - "native/windows/BppReplayMediaFoundationSmoke.cpp", - "native/windows/build.ps1", - "native/windows/test.ps1", - "src/BazaarPlusPlus/Game/CombatReplay/Video/WindowsMediaFoundationVideoEncoder.cs", - "src/BazaarPlusPlus/Game/CombatReplay/Video/WindowsNativeReplayAudioMuxer.cs" - ], - "artifacts": [ - { - "id": "windows-replay", - "buildScript": "native/windows/build.ps1", - "outputPath": "GfxPluginBppReplayMediaFoundation.dll", - "binaryPath": "GfxPluginBppReplayMediaFoundation.dll", - "kind": "file", - "destinationPath": "src-tauri/resources/SourceForBuild/windows/TheBazaar_Data/Plugins/x86_64/GfxPluginBppReplayMediaFoundation.dll", - "requiredExports": [ - "BppMfAcquireSlot", - "BppMfCanMuxAudio", - "BppMfCancelRenderEvent", - "BppMfCommitRenderEvent", - "BppMfCopyEncoderName", - "BppMfCopyError", - "BppMfCreate", - "BppMfDestroy", - "BppMfDiscardRenderEvent", - "BppMfFinish", - "BppMfGetRenderEventFunc", - "BppMfGetSlotCount", - "BppMfGetStats", - "BppMfHasUnityD3D11Interface", - "BppMfIsFailed", - "BppMfMuxAudio", - "BppMfPrepareRenderEvent", - "BppMfReleaseSlot", - "UnityPluginLoad", - "UnityPluginUnload" - ], - "allowedDependencies": [ - "ADVAPI32.dll", - "D3D11.dll", - "DXGI.dll", - "EVR.dll", - "KERNEL32.dll", - "MFPlat.dll", - "MFReadWrite.dll", - "OLE32.dll", - "SHLWAPI.dll", - "USER32.dll" - ] - } - ] - } - } -} diff --git a/bazaarplusplus-mod/native/mac-audio-tap/.gitignore b/bazaarplusplus-mod/native/mac-audio-tap/.gitignore deleted file mode 100644 index 6ab7575..0000000 --- a/bazaarplusplus-mod/native/mac-audio-tap/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Build output of build.sh. The consumed prebuilt lives in the installer repo at -# SourceForBuild/macos/BepInEx/plugins/ (alongside libe_sqlite3.dylib) and is referenced -# by BazaarPlusPlus.csproj via BPPInstallerSourcePath — the mod build never reads this copy. -*.dylib diff --git a/bazaarplusplus-mod/native/mac-audio-tap/BppMacAudio.h b/bazaarplusplus-mod/native/mac-audio-tap/BppMacAudio.h deleted file mode 100644 index 6382e76..0000000 --- a/bazaarplusplus-mod/native/mac-audio-tap/BppMacAudio.h +++ /dev/null @@ -1,44 +0,0 @@ -// BppMacAudio.h — C ABI for the BazaarPlusPlus macOS CoreAudio process-tap wrapper. -// -// The whole point of this dylib is to keep every CoreAudio interaction (the ObjC -// CATapDescription, the realtime IOProc, the planar->interleave fixup and a -// lock-free SPSC FIFO) on the native side, so the consumer degenerates into a -// plain pull loop and never drags the CoreAudio realtime thread into the -// managed runtime. -// -// All four entry points are plain C (extern "C", default visibility). The C# -// side binds them by name via [DllImport("BppMacAudio")], resolved on -// Unity-Mono through the lib{name}.dylib probe. - -#ifndef BPP_MAC_AUDIO_H -#define BPP_MAC_AUDIO_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// Safe to call on ANY macOS — touches only Foundation (NSProcessInfo), never a -// tap symbol. This IS the version gate: returns 1 on macOS >= 15, else 0. -int32_t BppMacAudio_IsSupported(void); - -// Starts a private self-tap of the current process and an aggregate device with -// an IOProc feeding the internal FIFO. On success returns an opaque handle and -// writes the actual mixed-down format (typically 48000 / 2). Returns NULL on any -// failure, after tearing down whatever was already created (no leaks). -void* BppMacAudio_Start(int32_t* outSampleRate, int32_t* outChannels); - -// Drains up to maxFloats interleaved floats from the FIFO into dst. Returns the -// number of floats actually copied (0 when empty). Non-blocking, wait-free. -int32_t BppMacAudio_Read(void* handle, float* dst, int32_t maxFloats); - -// Tears down the IOProc, aggregate device and tap (reverse of Start) and frees -// the handle. Idempotent-safe against NULL; the C# side guards double calls. -void BppMacAudio_Stop(void* handle); - -#ifdef __cplusplus -} -#endif - -#endif // BPP_MAC_AUDIO_H diff --git a/bazaarplusplus-mod/native/mac-audio-tap/BppMacAudio.m b/bazaarplusplus-mod/native/mac-audio-tap/BppMacAudio.m deleted file mode 100644 index a3f51e6..0000000 --- a/bazaarplusplus-mod/native/mac-audio-tap/BppMacAudio.m +++ /dev/null @@ -1,333 +0,0 @@ -// BppMacAudio.m — CoreAudio process-tap capture wrapper. -// -// The realtime IOProc, the lock-free SPSC FIFO and the planar->interleave -// fixup all live here in native code. The IOProc is a CoreAudio realtime -// thread; it must never malloc, lock, send an ObjC message, touch -// CF/Foundation, log, or make a blocking syscall. The consumer only calls -// Read on its own background thread, so no external realtime thread ever -// enters the managed runtime. - -#import -#import -#import -#import - -#include -#include -#include -#include - -#include "BppMacAudio.h" - -// --------------------------------------------------------------------------- -// Lock-free single-producer / single-consumer ring of float. Each cursor is -// strictly single-writer: the producer (IOProc) owns writePos and NEVER reads -// readPos; the consumer (Read) owns readPos and, on overrun, fast-forwards its -// OWN cursor past the clobbered region so the newest audio always wins. Cursors -// are 64-bit monotonic; the physical slot is pos & mask. -// --------------------------------------------------------------------------- - -#define BPP_FIFO_CAPACITY (1 << 18) // floats; power of two -#define BPP_FIFO_MASK (BPP_FIFO_CAPACITY - 1) -#define BPP_MAX_PLANES 64 // upper bound on non-interleaved channel planes per IOProc cycle - -typedef struct { - float *buf; // BPP_FIFO_CAPACITY floats, malloc'd in Start - _Atomic int64_t writePos; // producer-owned (IOProc) - _Atomic int64_t readPos; // consumer-owned (Read) -} BppFifo; - -typedef struct { - BppFifo fifo; - AudioObjectID tapID; - AudioObjectID aggDevID; - AudioDeviceIOProcID procID; - int channels; -} BppCtx; - -// PRODUCER: block-push one IOProc cycle. Loads writePos relaxed (sole writer), -// fills slots in place, then publishes the new cursor once with a release store -// so the consumer never observes data ahead of the published position. On -// overrun the oldest slots are simply overwritten; the consumer accounts the -// drop on its side. Wait-free, allocation-free. -static inline void bpp_fifo_push_block(BppFifo *f, const float *src, uint32_t count) { - int64_t w = atomic_load_explicit(&f->writePos, memory_order_relaxed); - for (uint32_t i = 0; i < count; i++) { - f->buf[w & BPP_FIFO_MASK] = src[i]; - w++; - } - atomic_store_explicit(&f->writePos, w, memory_order_release); -} - -// Planar push: interleave `frames` frames of `ch` non-interleaved planes -// (planes[c] is the c-th channel plane) into LRLR... order, single release at -// the end. -static inline void bpp_fifo_push_planar(BppFifo *f, const float *const *planes, - int ch, uint32_t frames) { - int64_t w = atomic_load_explicit(&f->writePos, memory_order_relaxed); - for (uint32_t fr = 0; fr < frames; fr++) { - for (int c = 0; c < ch; c++) { - f->buf[w & BPP_FIFO_MASK] = planes[c][fr]; - w++; - } - } - atomic_store_explicit(&f->writePos, w, memory_order_release); -} - -// CONSUMER: drain up to maxFloats into dst. Acquire-load writePos; relaxed-load -// our own readPos. On overrun (w - r > capacity) fast-forward our cursor to -// w - capacity. Copy n floats, publish readPos with a release store. -static int32_t bpp_fifo_read(BppFifo *f, float *dst, int32_t maxFloats) { - if (dst == NULL || maxFloats <= 0) - return 0; - - int64_t w = atomic_load_explicit(&f->writePos, memory_order_acquire); - int64_t r = atomic_load_explicit(&f->readPos, memory_order_relaxed); - - if (w - r > BPP_FIFO_CAPACITY) - r = w - BPP_FIFO_CAPACITY; - - int64_t avail = w - r; - int32_t n = (int32_t)(avail < maxFloats ? avail : maxFloats); - if (n <= 0) - return 0; - - for (int32_t i = 0; i < n; i++) - dst[i] = f->buf[(r + i) & BPP_FIFO_MASK]; - - atomic_store_explicit(&f->readPos, r + n, memory_order_release); - return n; -} - -// --------------------------------------------------------------------------- -// CoreAudio plumbing -// --------------------------------------------------------------------------- - -// REALTIME THREAD. No malloc/free, lock, ObjC message, CF/Foundation call, -// logging or blocking syscall in here. The tapped audio is the aggregate -// device INPUT. -static OSStatus BppIOProc(AudioObjectID inDevice, - const AudioTimeStamp *inNow, - const AudioBufferList *inInput, - const AudioTimeStamp *inInputTime, - AudioBufferList *outOutput, - const AudioTimeStamp *inOutputTime, - void *inClientData) { - (void)inDevice; - (void)inNow; - (void)inInputTime; - (void)outOutput; - (void)inOutputTime; - - BppCtx *ctx = (BppCtx *)inClientData; - if (ctx == NULL || inInput == NULL || inInput->mNumberBuffers == 0) - return noErr; - - int ch = ctx->channels; - if (ch <= 0) - return noErr; - - const AudioBufferList *abl = inInput; - uint32_t nbuf = abl->mNumberBuffers; - - // Decide the layout from the buffer list itself (authoritative for what the device - // actually delivers this cycle): - // non-interleaved -> one channel plane per buffer (mNumberBuffers == channels, - // each buffer carrying a single channel); - // interleaved -> a single buffer of LRLR... frames. - // Any other (nbuf, ch) shape is an unexpected layout: drop the cycle and leave the - // FIFO untouched rather than feed the interleaver one plane (which would corrupt - // channel order / pitch). A NULL plane (CoreAudio can hand these out for a silent or - // disabled stream) is skipped so the realtime path never dereferences NULL. - if ((int)nbuf == ch && ch <= BPP_MAX_PLANES && abl->mBuffers[0].mNumberChannels <= 1) { - const float *planes[BPP_MAX_PLANES]; - for (int c = 0; c < ch; c++) { - const float *p = (const float *)abl->mBuffers[c].mData; - if (p == NULL) - return noErr; - planes[c] = p; - } - uint32_t frames = abl->mBuffers[0].mDataByteSize / (uint32_t)sizeof(float); - bpp_fifo_push_planar(&ctx->fifo, planes, ch, frames); - } else if (nbuf == 1) { - const float *data = (const float *)abl->mBuffers[0].mData; - if (data == NULL) - return noErr; - uint32_t nf = abl->mBuffers[0].mDataByteSize / (uint32_t)sizeof(float); - bpp_fifo_push_block(&ctx->fifo, data, nf); - } - - return noErr; -} - -// Read a tap object property (UID / format) on the tap AudioObjectID. -static OSStatus bpp_get_tap_property(AudioObjectID tapID, AudioObjectPropertySelector sel, - void *outData, UInt32 *ioDataSize) { - AudioObjectPropertyAddress addr = { - sel, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; - return AudioObjectGetPropertyData(tapID, &addr, 0, NULL, ioDataSize, outData); -} - -int32_t BppMacAudio_IsSupported(void) { - // Version gate via NSProcessInfo (real product version), not - // kern.osproductversion and not Darwin kernel number. Safe on any macOS. - NSOperatingSystemVersion v = {15, 0, 0}; - return [[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:v] ? 1 : 0; -} - -// Reverse-order teardown of whatever a Start managed to create. ctx is calloc'd, so any -// stage never reached is 0/NULL and its guard skips it — the same helper therefore serves -// every Start error path AND Stop, keeping the teardown order in exactly one place. -// AudioDeviceStop on a created-but-never-started IOProc (an error path) is a harmless no-op. -// The tap-destroy is a weak macOS 14.2 symbol, hence the availability annotation; callers -// reach it only on macOS 15+ (the >=15 gate). -API_AVAILABLE(macos(15.0)) -static void bpp_destroy_ctx(BppCtx *ctx) { - if (ctx == NULL) - return; - if (ctx->procID != NULL && ctx->aggDevID != 0) { - AudioDeviceStop(ctx->aggDevID, ctx->procID); - AudioDeviceDestroyIOProcID(ctx->aggDevID, ctx->procID); - } - if (ctx->aggDevID != 0) - AudioHardwareDestroyAggregateDevice(ctx->aggDevID); - if (ctx->tapID != 0) - AudioHardwareDestroyProcessTap(ctx->tapID); - free(ctx->fifo.buf); - free(ctx); -} - -// All of the tap-touching setup lives here, annotated so clang statically knows -// CATapDescription (macOS 12) and the weak-imported process-tap functions -// (macOS 14.2) are only ever used on a new-enough OS. BppMacAudio_Start calls -// this solely from inside an `if (@available(macOS 15.0, *))` check, which -// matches the IsSupported gate and keeps the dylib self-defensive: on older -// systems the weak function symbols are NULL and must never be called. -API_AVAILABLE(macos(15.0)) -static void *bpp_start_tap(int32_t *outSampleRate, int32_t *outChannels) { - BppCtx *ctx = (BppCtx *)calloc(1, sizeof(BppCtx)); - if (ctx == NULL) - return NULL; - - // 1. Translate getpid() -> process AudioObjectID. - pid_t pid = getpid(); - AudioObjectID processObjID = 0; - UInt32 procSize = sizeof(processObjID); - AudioObjectPropertyAddress xlate = {kAudioHardwarePropertyTranslatePIDToProcessObject, - kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMain}; - OSStatus st = AudioObjectGetPropertyData(kAudioObjectSystemObject, &xlate, - sizeof(pid_t), &pid, &procSize, &processObjID); - if (st != noErr || processObjID == 0) { - bpp_destroy_ctx(ctx); - return NULL; - } - - // 2. Build the tap description (stereo mixdown of just this process) and tap. - CATapDescription *desc = - [[CATapDescription alloc] initStereoMixdownOfProcesses:@[ @(processObjID) ]]; - desc.muteBehavior = CATapUnmuted; - desc.privateTap = YES; - desc.name = @"BazaarPlusPlus Audio Tap"; - - // Each CoreAudio object is latched into ctx immediately after a successful create so a - // later failure routes through bpp_destroy_ctx, which tears down exactly what exists. - AudioObjectID tapID = 0; - st = AudioHardwareCreateProcessTap(desc, &tapID); - if (st != noErr || tapID == 0) { - bpp_destroy_ctx(ctx); - return NULL; - } - ctx->tapID = tapID; - - // 3. Read the tap UID and wrap the tap in an aggregate device. - CFStringRef tapUID = NULL; - UInt32 uidSize = sizeof(tapUID); - st = bpp_get_tap_property(tapID, kAudioTapPropertyUID, &tapUID, &uidSize); - if (st != noErr || tapUID == NULL) { - bpp_destroy_ctx(ctx); - return NULL; - } - - NSDictionary *aggDesc = @{ - @kAudioAggregateDeviceNameKey : @"BazaarPlusPlus Audio Tap", - @kAudioAggregateDeviceUIDKey : @"com.bazaarplusplus.audiotap", - @kAudioAggregateDeviceIsPrivateKey : @YES, - @kAudioAggregateDeviceTapAutoStartKey : @YES, - @kAudioAggregateDeviceTapListKey : @[ @{ - @kAudioSubTapUIDKey : (__bridge NSString *)tapUID, - @kAudioSubTapDriftCompensationKey : @NO - } ] - }; - - AudioObjectID aggDevID = 0; - st = AudioHardwareCreateAggregateDevice((__bridge CFDictionaryRef)aggDesc, &aggDevID); - CFRelease(tapUID); // the aggregate description has copied what it needs - if (st != noErr || aggDevID == 0) { - bpp_destroy_ctx(ctx); - return NULL; - } - ctx->aggDevID = aggDevID; - - // 4. Read the mixed-down stream format off the tap. - AudioStreamBasicDescription asbd; - memset(&asbd, 0, sizeof(asbd)); - UInt32 fmtSize = sizeof(asbd); - st = bpp_get_tap_property(tapID, kAudioTapPropertyFormat, &asbd, &fmtSize); - if (st != noErr || asbd.mChannelsPerFrame == 0) { - bpp_destroy_ctx(ctx); - return NULL; - } - ctx->channels = (int)asbd.mChannelsPerFrame; - if (outSampleRate) - *outSampleRate = (int32_t)asbd.mSampleRate; - if (outChannels) - *outChannels = (int32_t)asbd.mChannelsPerFrame; - - // 5. Allocate the FIFO buffer (pre-allocated; zero malloc on the RT path). - ctx->fifo.buf = (float *)malloc((size_t)BPP_FIFO_CAPACITY * sizeof(float)); - if (ctx->fifo.buf == NULL) { - bpp_destroy_ctx(ctx); - return NULL; - } - atomic_store_explicit(&ctx->fifo.writePos, 0, memory_order_relaxed); - atomic_store_explicit(&ctx->fifo.readPos, 0, memory_order_relaxed); - - // 6. Install the IOProc and start the device. - AudioDeviceIOProcID procID = NULL; - st = AudioDeviceCreateIOProcID(aggDevID, BppIOProc, ctx, &procID); - if (st != noErr || procID == NULL) { - bpp_destroy_ctx(ctx); - return NULL; - } - ctx->procID = procID; - - if (AudioDeviceStart(aggDevID, procID) != noErr) { - bpp_destroy_ctx(ctx); - return NULL; - } - - return (void *)ctx; // ARC manages desc / NSArray / NSDictionary -} - -void *BppMacAudio_Start(int32_t *outSampleRate, int32_t *outChannels) { - if (@available(macOS 15.0, *)) - return bpp_start_tap(outSampleRate, outChannels); - return NULL; -} - -int32_t BppMacAudio_Read(void *handle, float *dst, int32_t maxFloats) { - if (handle == NULL) - return 0; - return bpp_fifo_read(&((BppCtx *)handle)->fifo, dst, maxFloats); -} - -void BppMacAudio_Stop(void *handle) { - if (handle == NULL) - return; - // A non-NULL handle can only have come from a successful Start, which runs only on - // macOS 15+, so the same teardown helper applies. The @available guard re-states that - // for clang so the weak 14.2 tap-destroy symbol is never referenced unguarded. - if (@available(macOS 15.0, *)) - bpp_destroy_ctx((BppCtx *)handle); -} diff --git a/bazaarplusplus-mod/native/mac-audio-tap/README.md b/bazaarplusplus-mod/native/mac-audio-tap/README.md deleted file mode 100644 index 18d1739..0000000 --- a/bazaarplusplus-mod/native/mac-audio-tap/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# BppMacAudio — macOS CoreAudio process-tap capture (native) - -The native half of Combat Replay's macOS audio capture. All CoreAudio interaction lives -here so the C# side stays a plain pull loop identical to the Windows WASAPI path. - -C# consumer: [`src/BazaarPlusPlus/Game/CombatReplay/Audio/CoreAudioProcessTapCaptureTap.cs`](../../src/BazaarPlusPlus/Game/CombatReplay/Audio/CoreAudioProcessTapCaptureTap.cs) - -## How it works - -`BppMacAudio_Start` translates the current PID into a CoreAudio process object, creates a -private stereo-mixdown process tap on it, wraps the tap in a private aggregate device, and -installs an IOProc that pushes samples into a lock-free single-producer/single-consumer -FIFO (interleaving planar buffers on the fly). The consumer polls `BppMacAudio_Read` from -its own background thread; `BppMacAudio_Stop` tears everything down in reverse creation -order. The IOProc runs on a CoreAudio realtime thread and never allocates, locks, calls -ObjC/Foundation, logs, or blocks — and no CoreAudio realtime thread ever enters the Mono -runtime. - -The process-tap APIs are a macOS 14.2+ feature; this module gates itself at macOS 15 via -`BppMacAudio_IsSupported` (NSProcessInfo product version) and weak-imports the tap symbols -so the dylib still loads and degrades cleanly on older systems. - -## Build - -```bash -./build.sh -``` - -Requirements: macOS + Xcode / Command Line Tools SDK, Apple Silicon (arm64), and Node.js for -reading the shared native artifact catalog. The script builds into `build/` by default and runs -the architecture, deployment-target, weak-import, dependency, ABI export, load, and ad-hoc-signing -checks without writing the installer project. - -Every `clang` flag in `build.sh` is load-bearing, and the two whose reasons are not obvious from -the flag itself — the `lib` output prefix and `-mmacosx-version-min=12.0` — carry that reason in a -comment directly above the command. Read them there before changing the invocation. - -Those are producer checks. The final acceptance judgement is not one of them: it remains a -sample-bearing AAC track with audible in-game audio in the finished recording. - -## Where it ships - -The mod build **never reads the copy in this directory.** It reads the prebuilt from the -installer project, referenced by `BazaarPlusPlus.csproj` via `BPPInstallerSourcePath`, exactly -like `libe_sqlite3.dylib`: - -``` -bazaarplusplus-installer/src-tauri/resources/SourceForBuild/macos/BepInEx/plugins/libBppMacAudio.dylib -``` - -`just release::prepare ` reuses the staged copy while it matches the manifest and otherwise rebuilds through this script; see -[`docs/architecture/native-artifacts.md`](../../docs/architecture/native-artifacts.md). A direct -build may choose another side-effect-free output directory with its first argument: - -```bash -./build.sh /absolute/output/directory -``` - -## Naming + packaging - -- The artifact is **`libBppMacAudio.dylib`** (lib-prefixed) but C# binds - `[DllImport("BppMacAudio")]`; Unity-Mono resolves it via its `lib{name}.dylib` probe — the - same path that loads `libe_sqlite3.dylib` from `[DllImport("e_sqlite3")]`. -- The csproj mirrors sqlite: a **Debug-target** `` into the game's `BepInEx/plugins/`, - and **no Release-target native ``** — the promoted dylib is packed by the installer-owned - archive preparation step. diff --git a/bazaarplusplus-mod/native/mac-audio-tap/build.sh b/bazaarplusplus-mod/native/mac-audio-tap/build.sh deleted file mode 100644 index 8039fed..0000000 --- a/bazaarplusplus-mod/native/mac-audio-tap/build.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -output_dir="${1:-$script_dir/build}" -output="$output_dir/libBppMacAudio.dylib" - -if [[ "$(uname -s)" != "Darwin" ]]; then - echo "BppMacAudio can only be built on macOS." >&2 - exit 1 -fi - -mkdir -p "$output_dir" -sdk_path="$(xcrun --sdk macosx --show-sdk-path)" -clang_path="$(xcrun --sdk macosx --find clang)" - -# Output is lib-prefixed (libBppMacAudio.dylib) so [DllImport("BppMacAudio")] -# resolves on Unity-Mono via the lib{name}.dylib probe, exactly like -# libe_sqlite3.dylib. -# -# -mmacosx-version-min=12.0 (NOT 14.2) is required: CATapDescription exists on -# macOS 12, while the 14.2 tap functions are weak-imported. The dylib therefore -# loads on macOS 12-14 and IsSupported cleanly returns false there. The tap -# functions are only ever called after the >=15 gate passes. -"$clang_path" -isysroot "$sdk_path" -arch arm64 -fobjc-arc \ - -framework CoreAudio -framework Foundation \ - -mmacosx-version-min=12.0 \ - -Werror=unguarded-availability -Werror=unguarded-availability-new \ - -O2 -dynamiclib -install_name @rpath/libBppMacAudio.dylib \ - -o "$output" "$script_dir/BppMacAudio.m" - -codesign --force --sign - --timestamp=none "$output" -"$script_dir/../macos/verify.sh" mac-audio "$output" - -echo "built $output" diff --git a/bazaarplusplus-mod/native/macos/.gitignore b/bazaarplusplus-mod/native/macos/.gitignore deleted file mode 100644 index b54ab86..0000000 --- a/bazaarplusplus-mod/native/macos/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build/ -/GfxPluginBppReplayVideoToolbox.bundle/ diff --git a/bazaarplusplus-mod/native/macos/BppNativeLoadSmoke.c b/bazaarplusplus-mod/native/macos/BppNativeLoadSmoke.c deleted file mode 100644 index 277f11a..0000000 --- a/bazaarplusplus-mod/native/macos/BppNativeLoadSmoke.c +++ /dev/null @@ -1,37 +0,0 @@ -#include -#include - -int main(int argc, char **argv) -{ - if (argc < 3) - { - fprintf(stderr, "usage: %s [symbol...]\n", argv[0]); - return 2; - } - - void *image = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL); - if (image == NULL) - { - fprintf(stderr, "dlopen failed: %s\n", dlerror()); - return 1; - } - - for (int index = 2; index < argc; index++) - { - dlerror(); - if (dlsym(image, argv[index]) == NULL) - { - const char *error = dlerror(); - fprintf(stderr, "dlsym failed for %s: %s\n", argv[index], error == NULL ? "unknown" : error); - dlclose(image); - return 1; - } - } - - if (dlclose(image) != 0) - { - fprintf(stderr, "dlclose failed: %s\n", dlerror()); - return 1; - } - return 0; -} diff --git a/bazaarplusplus-mod/native/macos/BppReplayAudioMuxer.mm b/bazaarplusplus-mod/native/macos/BppReplayAudioMuxer.mm deleted file mode 100644 index 9c8e422..0000000 --- a/bazaarplusplus-mod/native/macos/BppReplayAudioMuxer.mm +++ /dev/null @@ -1,364 +0,0 @@ -#import - -#include "BppReplayVideoToolbox.h" - -#include -#include -#include -#include -#include - -namespace -{ -void CopyError(NSString *message, char *buffer, int capacity) -{ - if (buffer == nullptr || capacity <= 0) - return; - - buffer[0] = '\0'; - const char *utf8 = message.UTF8String; - if (utf8 == nullptr) - return; - - const int copied = std::min((int)std::strlen(utf8), capacity - 1); - if (copied > 0) - std::memcpy(buffer, utf8, (size_t)copied); - buffer[copied] = '\0'; -} - -int Fail(int code, NSString *message, char *buffer, int capacity) -{ - CopyError(message ?: @"Unknown AVFoundation mux failure.", buffer, capacity); - return code; -} - -NSString *ErrorMessage(NSString *prefix, NSError *error) -{ - NSString *detail = error.localizedDescription; - return detail.length == 0 ? prefix : [NSString stringWithFormat:@"%@: %@", prefix, detail]; -} - -bool IsReaderFailure(AVAssetReader *reader) -{ - return reader.status == AVAssetReaderStatusFailed || reader.status == AVAssetReaderStatusCancelled; -} - -void ReleaseSample(CMSampleBufferRef &sample) -{ - if (sample == nullptr) - return; - CFRelease(sample); - sample = nullptr; -} -} // namespace - -extern "C" -{ -__attribute__((visibility("default"))) int BppVtCanMuxAudio() -{ - return 1; -} - -// Copies the already-compressed H.264 samples without re-encoding and converts the captured PCM -// WAV tracks to stereo 48 kHz AAC. The caller runs this on its finalize worker, never on Unity's -// render thread. Return value 1 means success; negative values are stable failure categories. -__attribute__((visibility("default"))) int BppVtMuxAudio( - const char *silentVideoPath, - const char *const *wavPaths, - int wavPathCount, - const char *finalPath, - int audioBitrateBitsPerSecond, - int timeoutMs, - char *errorBuffer, - int errorCapacity) -{ - if (errorBuffer != nullptr && errorCapacity > 0) - errorBuffer[0] = '\0'; - if ( - silentVideoPath == nullptr || wavPaths == nullptr || wavPathCount <= 0 || - finalPath == nullptr || audioBitrateBitsPerSecond <= 0 || timeoutMs <= 0) - { - return Fail(-1, @"Invalid native audio mux arguments.", errorBuffer, errorCapacity); - } - - @autoreleasepool - { - @try - { - NSString *videoPath = [NSString stringWithUTF8String:silentVideoPath]; - NSString *outputPath = [NSString stringWithUTF8String:finalPath]; - if (videoPath.length == 0 || outputPath.length == 0) - return Fail(-1, @"A mux path is not valid UTF-8.", errorBuffer, errorCapacity); - - NSFileManager *files = NSFileManager.defaultManager; - if (![files fileExistsAtPath:videoPath]) - return Fail(-2, @"The silent video input does not exist.", errorBuffer, errorCapacity); - - AVURLAsset *videoAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:videoPath] - options:nil]; - NSArray *videoTracks = [videoAsset tracksWithMediaType:AVMediaTypeVideo]; - AVAssetTrack *videoTrack = videoTracks.firstObject; - if ( - videoTrack == nil || CMTIME_IS_INVALID(videoAsset.duration) || - CMTimeCompare(videoAsset.duration, kCMTimeZero) <= 0) - return Fail(-2, @"The silent video has no usable video track.", errorBuffer, errorCapacity); - - AVMutableComposition *audioComposition = [AVMutableComposition composition]; - NSMutableArray *compositionAudioTracks = - [NSMutableArray arrayWithCapacity:(NSUInteger)wavPathCount]; - for (int index = 0; index < wavPathCount; index++) - { - const char *rawPath = wavPaths[index]; - NSString *wavPath = rawPath == nullptr ? nil : [NSString stringWithUTF8String:rawPath]; - if (wavPath.length == 0 || ![files fileExistsAtPath:wavPath]) - return Fail(-2, @"A captured WAV input does not exist.", errorBuffer, errorCapacity); - - AVURLAsset *audioAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:wavPath] - options:nil]; - AVAssetTrack *sourceTrack = [audioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject; - if ( - sourceTrack == nil || CMTIME_IS_INVALID(audioAsset.duration) || - CMTimeCompare(audioAsset.duration, kCMTimeZero) <= 0) - return Fail(-2, @"A captured WAV has no usable audio track.", errorBuffer, errorCapacity); - - AVMutableCompositionTrack *compositionTrack = - [audioComposition addMutableTrackWithMediaType:AVMediaTypeAudio - preferredTrackID:kCMPersistentTrackID_Invalid]; - if (compositionTrack == nil) - return Fail(-3, @"AVFoundation could not create an audio composition track.", errorBuffer, errorCapacity); - - NSError *insertError = nil; - if (![compositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) - ofTrack:sourceTrack - atTime:kCMTimeZero - error:&insertError]) - { - return Fail( - -3, - ErrorMessage(@"AVFoundation could not add a WAV to the audio mix", insertError), - errorBuffer, - errorCapacity); - } - [compositionAudioTracks addObject:compositionTrack]; - } - - NSError *readerError = nil; - AVAssetReader *videoReader = [[AVAssetReader alloc] initWithAsset:videoAsset error:&readerError]; - if (videoReader == nil) - return Fail(-3, ErrorMessage(@"Could not create the video reader", readerError), errorBuffer, errorCapacity); - - AVAssetReaderTrackOutput *videoOutput = - [[AVAssetReaderTrackOutput alloc] initWithTrack:videoTrack outputSettings:nil]; - videoOutput.alwaysCopiesSampleData = NO; - if (![videoReader canAddOutput:videoOutput]) - return Fail(-3, @"AVAssetReader rejected the H.264 passthrough output.", errorBuffer, errorCapacity); - [videoReader addOutput:videoOutput]; - - readerError = nil; - AVAssetReader *audioReader = - [[AVAssetReader alloc] initWithAsset:audioComposition error:&readerError]; - if (audioReader == nil) - return Fail(-3, ErrorMessage(@"Could not create the audio reader", readerError), errorBuffer, errorCapacity); - - NSDictionary *pcmSettings = @{ - AVFormatIDKey : @(kAudioFormatLinearPCM), - AVSampleRateKey : @48000, - AVNumberOfChannelsKey : @2, - AVLinearPCMBitDepthKey : @32, - AVLinearPCMIsFloatKey : @YES, - AVLinearPCMIsBigEndianKey : @NO, - AVLinearPCMIsNonInterleaved : @NO, - }; - AVAssetReaderAudioMixOutput *audioOutput = - [[AVAssetReaderAudioMixOutput alloc] initWithAudioTracks:compositionAudioTracks - audioSettings:pcmSettings]; - audioOutput.alwaysCopiesSampleData = NO; - - NSMutableArray *mixParameters = - [NSMutableArray arrayWithCapacity:compositionAudioTracks.count]; - for (AVMutableCompositionTrack *track in compositionAudioTracks) - { - AVMutableAudioMixInputParameters *parameters = - [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track]; - [parameters setVolume:1.0f atTime:kCMTimeZero]; - [mixParameters addObject:parameters]; - } - AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix]; - audioMix.inputParameters = mixParameters; - audioOutput.audioMix = audioMix; - - if (![audioReader canAddOutput:audioOutput]) - return Fail(-3, @"AVAssetReader rejected the PCM audio mix output.", errorBuffer, errorCapacity); - [audioReader addOutput:audioOutput]; - - NSURL *outputUrl = [NSURL fileURLWithPath:outputPath]; - [files removeItemAtURL:outputUrl error:nil]; - NSError *writerError = nil; - AVAssetWriter *writer = [[AVAssetWriter alloc] initWithURL:outputUrl - fileType:AVFileTypeMPEG4 - error:&writerError]; - if (writer == nil) - return Fail(-3, ErrorMessage(@"Could not create the MP4 writer", writerError), errorBuffer, errorCapacity); - writer.shouldOptimizeForNetworkUse = YES; - - CMFormatDescriptionRef videoFormat = - (__bridge CMFormatDescriptionRef)videoTrack.formatDescriptions.firstObject; - if (videoFormat == nullptr) - return Fail(-2, @"The H.264 input has no format description.", errorBuffer, errorCapacity); - - AVAssetWriterInput *videoInput = - [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeVideo - outputSettings:nil - sourceFormatHint:videoFormat]; - videoInput.expectsMediaDataInRealTime = NO; - - NSDictionary *aacSettings = @{ - AVFormatIDKey : @(kAudioFormatMPEG4AAC), - AVSampleRateKey : @48000, - AVNumberOfChannelsKey : @2, - AVEncoderBitRateKey : @(audioBitrateBitsPerSecond), - }; - AVAssetWriterInput *audioInput = - [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeAudio - outputSettings:aacSettings]; - audioInput.expectsMediaDataInRealTime = NO; - - if (![writer canAddInput:videoInput] || ![writer canAddInput:audioInput]) - return Fail(-3, @"AVAssetWriter rejected the video or AAC input.", errorBuffer, errorCapacity); - [writer addInput:videoInput]; - [writer addInput:audioInput]; - - if (![videoReader startReading] || ![audioReader startReading] || ![writer startWriting]) - { - NSError *startError = writer.error ?: videoReader.error ?: audioReader.error; - return Fail(-4, ErrorMessage(@"AVFoundation could not start the native mux", startError), errorBuffer, errorCapacity); - } - [writer startSessionAtSourceTime:kCMTimeZero]; - - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::milliseconds(std::max(1, timeoutMs)); - CMSampleBufferRef pendingVideo = nullptr; - CMSampleBufferRef pendingAudio = nullptr; - bool videoFinished = false; - bool audioFinished = false; - int appendedAudioSamples = 0; - - while (!videoFinished || !audioFinished) - { - if (std::chrono::steady_clock::now() >= deadline) - { - ReleaseSample(pendingVideo); - ReleaseSample(pendingAudio); - [videoReader cancelReading]; - [audioReader cancelReading]; - [writer cancelWriting]; - return Fail(-8, @"AVFoundation timed out while muxing audio.", errorBuffer, errorCapacity); - } - - bool progressed = false; - if (!videoFinished && pendingVideo == nullptr) - { - pendingVideo = [videoOutput copyNextSampleBuffer]; - if (pendingVideo == nullptr && videoReader.status == AVAssetReaderStatusCompleted) - { - [videoInput markAsFinished]; - videoFinished = true; - progressed = true; - } - } - if (!audioFinished && pendingAudio == nullptr) - { - pendingAudio = [audioOutput copyNextSampleBuffer]; - if (pendingAudio == nullptr && audioReader.status == AVAssetReaderStatusCompleted) - { - [audioInput markAsFinished]; - audioFinished = true; - progressed = true; - } - } - - if (IsReaderFailure(videoReader) || IsReaderFailure(audioReader)) - { - NSError *failure = videoReader.error ?: audioReader.error; - ReleaseSample(pendingVideo); - ReleaseSample(pendingAudio); - [writer cancelWriting]; - return Fail(-6, ErrorMessage(@"AVAssetReader failed during the native mux", failure), errorBuffer, errorCapacity); - } - - if (pendingVideo != nullptr && videoInput.readyForMoreMediaData) - { - if (![videoInput appendSampleBuffer:pendingVideo]) - { - ReleaseSample(pendingVideo); - ReleaseSample(pendingAudio); - [writer cancelWriting]; - return Fail(-5, ErrorMessage(@"Could not append an H.264 sample", writer.error), errorBuffer, errorCapacity); - } - ReleaseSample(pendingVideo); - progressed = true; - } - - if (pendingAudio != nullptr && audioInput.readyForMoreMediaData) - { - CMTime presentationTime = CMSampleBufferGetPresentationTimeStamp(pendingAudio); - if (CMTIME_IS_VALID(presentationTime) && CMTimeCompare(presentationTime, videoAsset.duration) >= 0) - { - ReleaseSample(pendingAudio); - [audioInput markAsFinished]; - audioFinished = true; - } - else - { - if (![audioInput appendSampleBuffer:pendingAudio]) - { - ReleaseSample(pendingVideo); - ReleaseSample(pendingAudio); - [writer cancelWriting]; - return Fail(-5, ErrorMessage(@"Could not append an AAC source sample", writer.error), errorBuffer, errorCapacity); - } - appendedAudioSamples++; - ReleaseSample(pendingAudio); - } - progressed = true; - } - - if (!progressed) - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - - if (appendedAudioSamples == 0) - { - [writer cancelWriting]; - return Fail(-7, @"The captured WAV contained no audio samples.", errorBuffer, errorCapacity); - } - - dispatch_semaphore_t finished = dispatch_semaphore_create(0); - [writer finishWritingWithCompletionHandler:^{ - dispatch_semaphore_signal(finished); - }]; - - auto remaining = std::chrono::duration_cast( - deadline - std::chrono::steady_clock::now()).count(); - if ( - remaining <= 0 || - dispatch_semaphore_wait( - finished, - dispatch_time(DISPATCH_TIME_NOW, remaining * NSEC_PER_MSEC)) != 0) - { - [writer cancelWriting]; - return Fail(-8, @"AVAssetWriter timed out while finalizing the MP4.", errorBuffer, errorCapacity); - } - - if (writer.status != AVAssetWriterStatusCompleted) - return Fail(-9, ErrorMessage(@"AVAssetWriter did not complete the MP4", writer.error), errorBuffer, errorCapacity); - - return 1; - } - @catch (NSException *exception) - { - return Fail(-10, exception.reason ?: exception.name, errorBuffer, errorCapacity); - } - } -} -} diff --git a/bazaarplusplus-mod/native/macos/BppReplayVideoToolbox.h b/bazaarplusplus-mod/native/macos/BppReplayVideoToolbox.h deleted file mode 100644 index 510f4b1..0000000 --- a/bazaarplusplus-mod/native/macos/BppReplayVideoToolbox.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef BPP_REPLAY_VIDEO_TOOLBOX_H -#define BPP_REPLAY_VIDEO_TOOLBOX_H - -#include - -#if defined(__cplusplus) -extern "C" -{ -#endif - -typedef struct BppVtNativeStats -{ - int submittedFrames; - int appendedFrames; - int acquireMisses; - int notReadyDrops; - int encodeErrors; - int maxInFlight; -} BppVtNativeStats; - -int BppVtHasUnityMetalInterface(void); -int BppVtCanMuxAudio(void); -void *BppVtGetRenderEventFunc(void); -int BppVtCreate( - const char *outputPath, - int width, - int height, - int fps, - int bitrateBitsPerSecond, - void **handle); -int BppVtGetSlotCount(void *handle); -int BppVtAcquireSlot(void *handle, int *slotIndex); - -// Render-event packet ownership. BppVtPrepareRenderEvent returns a packet holding two -// references: one owned by the caller, one owned by the render-event callback the caller is -// about to queue. They are released independently and in no guaranteed order — the callback -// may run before, during, or after the call that releases the caller's reference. -// -// BppVtCommitRenderEvent releases the caller's reference. Use once the event is queued. -// BppVtCancelRenderEvent releases the caller's reference and marks the packet so a -// callback that has not run yet returns early. Use to abandon an -// event that WAS queued; the callback still releases its own. -// BppVtDiscardRenderEvent releases BOTH references. Use only for an event that was NEVER -// queued, because no callback will ever run to release the second. -// -// Swapping the last two is not benign: Discard on a queued event frees the packet while the -// render thread still holds it, and Cancel on an unqueued event leaks it. -void *BppVtPrepareRenderEvent( - void *handle, - int slotIndex, - int64_t firstFrameIndex, - int frameCount); -void BppVtCommitRenderEvent(void *eventData); -void BppVtCancelRenderEvent(void *eventData); -void BppVtDiscardRenderEvent(void *eventData); -void BppVtReleaseSlot(void *handle, int slotIndex); -int BppVtFinish(void *handle, int timeoutMs); -void BppVtDestroy(void *handle); -int BppVtIsFailed(void *handle); -void BppVtGetStats(void *handle, BppVtNativeStats *stats); -int BppVtCopyError(void *handle, char *buffer, int capacity); - -int BppVtMuxAudio( - const char *silentVideoPath, - const char *const *wavPaths, - int wavPathCount, - const char *finalPath, - int audioBitrateBitsPerSecond, - int timeoutMs, - char *errorBuffer, - int errorCapacity); - -#if defined(__cplusplus) -} -#endif - -#endif diff --git a/bazaarplusplus-mod/native/macos/BppReplayVideoToolbox.mm b/bazaarplusplus-mod/native/macos/BppReplayVideoToolbox.mm deleted file mode 100644 index 57fffe5..0000000 --- a/bazaarplusplus-mod/native/macos/BppReplayVideoToolbox.mm +++ /dev/null @@ -1,1377 +0,0 @@ -#import -#import -#import -#import - -#include "BppReplayVideoToolbox.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define UNITY_INTERFACE_API -#define UNITY_INTERFACE_EXPORT __attribute__((visibility("default"))) - -struct UnityInterfaceGUID -{ - unsigned long long high; - unsigned long long low; -}; - -struct IUnityInterface -{ -}; - -struct IUnityInterfaces -{ - IUnityInterface *(UNITY_INTERFACE_API *GetInterface)(UnityInterfaceGUID guid); - void(UNITY_INTERFACE_API *RegisterInterface)(UnityInterfaceGUID guid, IUnityInterface *value); - IUnityInterface *(UNITY_INTERFACE_API *GetInterfaceSplit)( - unsigned long long guidHigh, - unsigned long long guidLow); - void(UNITY_INTERFACE_API *RegisterInterfaceSplit)( - unsigned long long guidHigh, - unsigned long long guidLow, - IUnityInterface *value); -}; - -struct RenderSurfaceBase; -using UnityRenderBuffer = RenderSurfaceBase *; - -struct IUnityGraphicsMetal : IUnityInterface -{ - NSBundle *(UNITY_INTERFACE_API *MetalBundle)(); - id(UNITY_INTERFACE_API *MetalDevice)(); - id(UNITY_INTERFACE_API *CurrentCommandBuffer)(); - id(UNITY_INTERFACE_API *CurrentCommandEncoder)(); - void(UNITY_INTERFACE_API *EndCurrentCommandEncoder)(); - MTLRenderPassDescriptor *(UNITY_INTERFACE_API *CurrentRenderPassDescriptor)(); - UnityRenderBuffer(UNITY_INTERFACE_API *RenderBufferFromHandle)(void *bufferHandle); - id(UNITY_INTERFACE_API *TextureFromRenderBuffer)(UnityRenderBuffer buffer); - id(UNITY_INTERFACE_API *AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer); - id(UNITY_INTERFACE_API *StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer); -}; - -namespace -{ -constexpr int kSlotCount = 8; - -constexpr const char *kBgraToNv12MetalSource = R"METAL( -#include -using namespace metal; - -struct ConversionParameters -{ - uint width; - uint height; - uint sourceIsLinear; - uint reserved; -}; - -inline float encodeSrgb(float value) -{ - value = clamp(value, 0.0f, 1.0f); - return value <= 0.0031308f - ? 12.92f * value - : 1.055f * pow(value, 1.0f / 2.4f) - 0.055f; -} - -inline float3 videoRgb(float3 value, uint sourceIsLinear) -{ - if (sourceIsLinear == 0) - return clamp(value, 0.0f, 1.0f); - return float3(encodeSrgb(value.r), encodeSrgb(value.g), encodeSrgb(value.b)); -} - -inline float luma709(float3 rgb) -{ - return dot(rgb, float3(0.2126f, 0.7152f, 0.0722f)); -} - -inline float videoRangeLuma(float3 rgb) -{ - return clamp((16.0f + 219.0f * luma709(rgb)) / 255.0f, 0.0f, 1.0f); -} - -inline uint2 sourcePositionForOutput( - uint2 outputPosition, - uint2 outputSize, - uint2 sourceSize) -{ - if (all(outputSize == sourceSize)) - return outputPosition; - - return min((outputPosition * sourceSize) / outputSize, sourceSize - uint2(1)); -} - -kernel void bppBgraToNv12( - texture2d source [[texture(0)]], - texture2d lumaPlane [[texture(1)]], - texture2d chromaPlane [[texture(2)]], - constant ConversionParameters ¶meters [[buffer(0)]], - uint2 chromaPosition [[thread_position_in_grid]]) -{ - uint2 outputPosition = chromaPosition * 2; - uint2 outputSize = uint2(parameters.width, parameters.height); - if (outputPosition.x >= outputSize.x || outputPosition.y >= outputSize.y) - return; - - uint2 sourceSize = uint2(source.get_width(), source.get_height()); - uint2 source00 = sourcePositionForOutput(outputPosition, outputSize, sourceSize); - uint2 source10 = sourcePositionForOutput(outputPosition + uint2(1, 0), outputSize, sourceSize); - uint2 source01 = sourcePositionForOutput(outputPosition + uint2(0, 1), outputSize, sourceSize); - uint2 source11 = sourcePositionForOutput(outputPosition + uint2(1, 1), outputSize, sourceSize); - - float3 rgb00 = videoRgb(source.read(source00).rgb, parameters.sourceIsLinear); - float3 rgb10 = videoRgb(source.read(source10).rgb, parameters.sourceIsLinear); - float3 rgb01 = videoRgb(source.read(source01).rgb, parameters.sourceIsLinear); - float3 rgb11 = videoRgb(source.read(source11).rgb, parameters.sourceIsLinear); - - lumaPlane.write(float4(videoRangeLuma(rgb00), 0.0f, 0.0f, 1.0f), outputPosition); - lumaPlane.write(float4(videoRangeLuma(rgb10), 0.0f, 0.0f, 1.0f), outputPosition + uint2(1, 0)); - lumaPlane.write(float4(videoRangeLuma(rgb01), 0.0f, 0.0f, 1.0f), outputPosition + uint2(0, 1)); - lumaPlane.write(float4(videoRangeLuma(rgb11), 0.0f, 0.0f, 1.0f), outputPosition + uint2(1, 1)); - - float3 averageRgb = (rgb00 + rgb10 + rgb01 + rgb11) * 0.25f; - float averageLuma = luma709(averageRgb); - float cb = (128.0f + 224.0f * (averageRgb.b - averageLuma) / 1.8556f) / 255.0f; - float cr = (128.0f + 224.0f * (averageRgb.r - averageLuma) / 1.5748f) / 255.0f; - chromaPlane.write(float4(clamp(cb, 0.0f, 1.0f), clamp(cr, 0.0f, 1.0f), 0.0f, 1.0f), chromaPosition); -} -)METAL"; - -enum class SlotState : uint8_t -{ - Free, - GpuPending, - Encoding, -}; - -struct FrameSlot -{ - CVPixelBufferRef pixelBuffer = nullptr; - CVMetalTextureRef lumaTexture = nullptr; - CVMetalTextureRef chromaTexture = nullptr; - SlotState state = SlotState::Free; -}; - -struct Encoder -{ - std::mutex mutex; - std::string error; - bool failed = false; - bool acceptingFrames = true; - bool finished = false; - int fps = 60; - int inFlight = 0; - int renderEventsPending = 0; - int64_t lastFrameIndex = -1; - BppVtNativeStats stats{}; - std::condition_variable renderEventCondition; - std::condition_variable writerCondition; - std::vector slots; - - VTCompressionSessionRef compressionSession = nullptr; - CVPixelBufferPoolRef pixelBufferPool = nullptr; - CVMetalTextureCacheRef metalTextureCache = nullptr; - id __strong conversionPipeline = nil; - AVAssetWriter *__strong writer = nil; - AVAssetWriterInput *__strong writerInput = nil; - dispatch_queue_t encodeQueue = nullptr; - dispatch_queue_t writerQueue = nullptr; - bool writerStarted = false; - bool writerClosed = false; -}; - -struct RenderEventPacket -{ - Encoder *encoder; - int slotIndex; - int64_t firstFrameIndex; - int frameCount; - std::atomic references{2}; - std::atomic state{0}; -}; - -struct ConversionParameters -{ - uint32_t width; - uint32_t height; - uint32_t sourceIsLinear; - uint32_t reserved; -}; - -struct FrameSubmission -{ - Encoder *encoder; - int slotIndex; - std::atomic remainingFrames; -}; - -IUnityGraphicsMetal *gUnityMetal = nullptr; -std::mutex gConversionPipelineMutex; -NSMapTable, id> *__strong - gConversionPipelines = nil; - -void ReleaseRenderEventPacket(RenderEventPacket *packet) -{ - if (packet != nullptr && packet->references.fetch_sub(1, std::memory_order_acq_rel) == 1) - delete packet; -} - -struct ScopedRenderEventPacketReference -{ - RenderEventPacket *packet; - - ~ScopedRenderEventPacketReference() - { - ReleaseRenderEventPacket(packet); - } -}; - -void SetFailure(Encoder *encoder, const std::string &message) -{ - if (encoder == nullptr) - return; - - { - std::lock_guard guard(encoder->mutex); - encoder->failed = true; - if (encoder->error.empty()) - encoder->error = message; - } - encoder->writerCondition.notify_all(); -} - -std::string StatusMessage(const char *operation, OSStatus status) -{ - char buffer[160]; - std::snprintf(buffer, sizeof(buffer), "%s failed with OSStatus %d", operation, (int)status); - return std::string(buffer); -} - -void ReleaseSlot(Encoder *encoder, int slotIndex) -{ - if (encoder == nullptr) - return; - - std::lock_guard guard(encoder->mutex); - if (slotIndex >= 0 && slotIndex < (int)encoder->slots.size()) - encoder->slots[(size_t)slotIndex].state = SlotState::Free; - encoder->inFlight = std::max(0, encoder->inFlight - 1); -} - -void CompleteSubmissionFrame(FrameSubmission *submission) -{ - if (submission == nullptr) - return; - - if (submission->remainingFrames.fetch_sub(1, std::memory_order_acq_rel) != 1) - return; - - ReleaseSlot(submission->encoder, submission->slotIndex); - delete submission; -} - -bool StartWriterIfNeeded(Encoder *encoder, CMSampleBufferRef sampleBuffer) -{ - if (encoder->writerClosed) - return false; - if (encoder->writerStarted) - return true; - - CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer); - if (formatDescription == nullptr) - { - SetFailure(encoder, "VideoToolbox returned a sample without a format description."); - return false; - } - - AVAssetWriterInput *input = [[AVAssetWriterInput alloc] - initWithMediaType:AVMediaTypeVideo - outputSettings:nil - sourceFormatHint:formatDescription]; - input.expectsMediaDataInRealTime = YES; - - if (![encoder->writer canAddInput:input]) - { - SetFailure(encoder, "AVAssetWriter rejected the VideoToolbox passthrough input."); - return false; - } - [encoder->writer addInput:input]; - encoder->writerInput = input; - - if (![encoder->writer startWriting]) - { - NSString *message = encoder->writer.error.localizedDescription; - SetFailure( - encoder, - message == nil ? "AVAssetWriter failed to start." - : std::string(message.UTF8String)); - return false; - } - - [encoder->writer startSessionAtSourceTime:kCMTimeZero]; - encoder->writerStarted = true; - return true; -} - -void CompressionOutputCallback( - void *outputCallbackRefCon, - void *sourceFrameRefCon, - OSStatus status, - VTEncodeInfoFlags infoFlags, - CMSampleBufferRef sampleBuffer) -{ - auto *encoder = static_cast(outputCallbackRefCon); - auto *submission = static_cast(sourceFrameRefCon); - - if (encoder == nullptr || submission == nullptr) - return; - if (status != noErr || sampleBuffer == nullptr || (infoFlags & kVTEncodeInfo_FrameDropped) != 0) - { - { - std::lock_guard guard(encoder->mutex); - encoder->stats.encodeErrors++; - } - SetFailure( - encoder, - status == noErr ? "VideoToolbox dropped an encoded frame." - : StatusMessage("VTCompressionSession output", status)); - CompleteSubmissionFrame(submission); - return; - } - - CFRetain(sampleBuffer); - CompleteSubmissionFrame(submission); - dispatch_async(encoder->writerQueue, ^{ - @autoreleasepool - { - bool appended = false; - if (!encoder->writerClosed && StartWriterIfNeeded(encoder, sampleBuffer)) - { - if (encoder->writerInput.readyForMoreMediaData) - { - appended = [encoder->writerInput appendSampleBuffer:sampleBuffer]; - if (!appended) - { - NSString *message = encoder->writer.error.localizedDescription; - SetFailure( - encoder, - message == nil ? "AVAssetWriter failed to append an encoded frame." - : std::string(message.UTF8String)); - } - } - else - { - { - std::lock_guard guard(encoder->mutex); - encoder->stats.notReadyDrops++; - } - SetFailure( - encoder, - "AVAssetWriter input backpressure dropped an encoded video frame."); - } - } - - if (appended) - { - { - std::lock_guard guard(encoder->mutex); - encoder->stats.appendedFrames++; - } - encoder->writerCondition.notify_all(); - } - - CFRelease(sampleBuffer); - } - }); -} - -void ReleaseGpuPendingSlot(Encoder *encoder, int slotIndex) -{ - if (encoder == nullptr) - return; - - std::lock_guard guard(encoder->mutex); - if (slotIndex < 0 || slotIndex >= (int)encoder->slots.size()) - return; - auto &slot = encoder->slots[(size_t)slotIndex]; - if (slot.state == SlotState::GpuPending) - slot.state = SlotState::Free; -} - -int SubmitFramesInternal( - Encoder *encoder, - int slotIndex, - int64_t firstFrameIndex, - int frameCount) -{ - if ( - encoder == nullptr || slotIndex < 0 || slotIndex >= (int)encoder->slots.size() || - frameCount <= 0) - return 0; - - { - std::lock_guard guard(encoder->mutex); - auto &slot = encoder->slots[(size_t)slotIndex]; - if (encoder->failed || encoder->finished || slot.state != SlotState::GpuPending) - return 0; - slot.state = SlotState::Encoding; - encoder->inFlight++; - encoder->stats.maxInFlight = std::max(encoder->stats.maxInFlight, encoder->inFlight); - encoder->stats.submittedFrames += frameCount; - encoder->lastFrameIndex = std::max( - encoder->lastFrameIndex, - firstFrameIndex + frameCount - 1); - } - - auto *submission = new FrameSubmission{encoder, slotIndex, frameCount}; - CMTime duration = CMTimeMake(1, encoder->fps); - for (int offset = 0; offset < frameCount; offset++) - { - CMTime presentationTime = CMTimeMake(firstFrameIndex + offset, encoder->fps); - VTEncodeInfoFlags infoFlags = 0; - OSStatus status = VTCompressionSessionEncodeFrame( - encoder->compressionSession, - encoder->slots[(size_t)slotIndex].pixelBuffer, - presentationTime, - duration, - nullptr, - submission, - &infoFlags); - if (status == noErr) - continue; - - { - std::lock_guard guard(encoder->mutex); - encoder->stats.encodeErrors++; - } - SetFailure(encoder, StatusMessage("VTCompressionSessionEncodeFrame", status)); - for (int unsubmitted = offset; unsubmitted < frameCount; unsubmitted++) - CompleteSubmissionFrame(submission); - return 0; - } - - return 1; -} - -void CompleteRenderEvent(Encoder *encoder) -{ - if (encoder == nullptr) - return; - - { - std::lock_guard guard(encoder->mutex); - encoder->renderEventsPending = std::max(0, encoder->renderEventsPending - 1); - } - encoder->renderEventCondition.notify_all(); -} - -void UNITY_INTERFACE_API RenderEventCallback(int eventId, void *data) -{ - (void)eventId; - auto *packet = static_cast(data); - if (packet == nullptr) - return; - - ScopedRenderEventPacketReference callbackReference{packet}; - uint8_t expectedState = 0; - if (!packet->state.compare_exchange_strong( - expectedState, - 1, - std::memory_order_acq_rel)) - { - return; - } - - Encoder *encoder = packet->encoder; - const int slotIndex = packet->slotIndex; - const int64_t firstFrameIndex = packet->firstFrameIndex; - const int frameCount = packet->frameCount; - - IUnityGraphicsMetal *metal = gUnityMetal; - MTLRenderPassDescriptor *renderPass = - metal == nullptr ? nil : metal->CurrentRenderPassDescriptor(); - MTLRenderPassColorAttachmentDescriptor *colorAttachment = - renderPass == nil ? nil : renderPass.colorAttachments[0]; - id sourceTexture = colorAttachment.resolveTexture; - if (sourceTexture == nil) - sourceTexture = colorAttachment.texture; - id lumaTexture = CVMetalTextureGetTexture( - encoder->slots[(size_t)slotIndex].lumaTexture); - id chromaTexture = CVMetalTextureGetTexture( - encoder->slots[(size_t)slotIndex].chromaTexture); - id commandBuffer = - metal == nullptr ? nil : metal->CurrentCommandBuffer(); - if ( - commandBuffer == nil || sourceTexture == nil || lumaTexture == nil || - chromaTexture == nil || encoder->conversionPipeline == nil) - { - SetFailure( - encoder, - "Unity render event exposed no final Metal render target, NV12 plane, or command buffer."); - ReleaseGpuPendingSlot(encoder, slotIndex); - CompleteRenderEvent(encoder); - return; - } - if ( - chromaTexture.width * 2 != lumaTexture.width || - chromaTexture.height * 2 != lumaTexture.height || sourceTexture.sampleCount != 1) - { - char dimensions[260]; - std::snprintf( - dimensions, - sizeof(dimensions), - "Unity final Metal target is %lux%lu samples=%lu; NV12 planes are inconsistent at %lux%lu and %lux%lu.", - (unsigned long)sourceTexture.width, - (unsigned long)sourceTexture.height, - (unsigned long)sourceTexture.sampleCount, - (unsigned long)lumaTexture.width, - (unsigned long)lumaTexture.height, - (unsigned long)chromaTexture.width, - (unsigned long)chromaTexture.height); - SetFailure(encoder, dimensions); - ReleaseGpuPendingSlot(encoder, slotIndex); - CompleteRenderEvent(encoder); - return; - } - - bool sourceIsLinear = false; - switch (sourceTexture.pixelFormat) - { - case MTLPixelFormatBGRA8Unorm: - case MTLPixelFormatRGBA8Unorm: - sourceIsLinear = false; - break; - case MTLPixelFormatBGRA8Unorm_sRGB: - case MTLPixelFormatRGBA8Unorm_sRGB: - case MTLPixelFormatRGBA16Float: - case MTLPixelFormatRGBA32Float: - sourceIsLinear = true; - break; - default: - { - char format[160]; - std::snprintf( - format, - sizeof(format), - "Unsupported Unity final Metal pixel format %lu for NV12 conversion.", - (unsigned long)sourceTexture.pixelFormat); - SetFailure(encoder, format); - ReleaseGpuPendingSlot(encoder, slotIndex); - CompleteRenderEvent(encoder); - return; - } - } - - metal->EndCurrentCommandEncoder(); - id computeEncoder = [commandBuffer computeCommandEncoder]; - if (computeEncoder == nil) - { - SetFailure(encoder, "Metal could not create the NV12 conversion encoder."); - ReleaseGpuPendingSlot(encoder, slotIndex); - CompleteRenderEvent(encoder); - return; - } - - [computeEncoder setComputePipelineState:encoder->conversionPipeline]; - [computeEncoder setTexture:sourceTexture atIndex:0]; - [computeEncoder setTexture:lumaTexture atIndex:1]; - [computeEncoder setTexture:chromaTexture atIndex:2]; - ConversionParameters parameters{ - (uint32_t)lumaTexture.width, - (uint32_t)lumaTexture.height, - sourceIsLinear ? 1u : 0u, - 0u, - }; - [computeEncoder setBytes:¶meters length:sizeof(parameters) atIndex:0]; - - const NSUInteger threadWidth = encoder->conversionPipeline.threadExecutionWidth; - const NSUInteger threadHeight = std::max( - (NSUInteger)1, - encoder->conversionPipeline.maxTotalThreadsPerThreadgroup / threadWidth); - [computeEncoder - dispatchThreads:MTLSizeMake(chromaTexture.width, chromaTexture.height, 1) - threadsPerThreadgroup:MTLSizeMake(threadWidth, threadHeight, 1)]; - [computeEncoder endEncoding]; - - [commandBuffer addCompletedHandler:^(id completedCommandBuffer) { - @autoreleasepool - { - if (completedCommandBuffer.status == MTLCommandBufferStatusCompleted) - { - dispatch_async(encoder->encodeQueue, ^{ - @autoreleasepool - { - if (!SubmitFramesInternal( - encoder, - slotIndex, - firstFrameIndex, - frameCount)) - { - ReleaseGpuPendingSlot(encoder, slotIndex); - } - CompleteRenderEvent(encoder); - } - }); - return; - } - else - { - NSString *message = completedCommandBuffer.error.localizedDescription; - SetFailure( - encoder, - message == nil ? "Unity Metal command buffer did not complete." - : std::string(message.UTF8String)); - ReleaseGpuPendingSlot(encoder, slotIndex); - } - CompleteRenderEvent(encoder); - } - }]; -} - -bool SetCompressionProperty( - Encoder *encoder, - CFStringRef key, - CFTypeRef value, - const char *name) -{ - OSStatus status = VTSessionSetProperty(encoder->compressionSession, key, value); - if (status == noErr) - return true; - - SetFailure(encoder, StatusMessage(name, status)); - return false; -} - -bool InitializeConversionPipeline(Encoder *encoder, id device) -{ - std::lock_guard cacheGuard(gConversionPipelineMutex); - if (gConversionPipelines == nil) - { - gConversionPipelines = [NSMapTable - mapTableWithKeyOptions:NSPointerFunctionsWeakMemory | - NSPointerFunctionsObjectPointerPersonality - valueOptions:NSPointerFunctionsStrongMemory]; - } - id cachedPipeline = - [gConversionPipelines objectForKey:device]; - if (cachedPipeline != nil) - { - encoder->conversionPipeline = cachedPipeline; - return true; - } - - NSError *libraryError = nil; - NSString *source = [NSString stringWithUTF8String:kBgraToNv12MetalSource]; - id library = [device newLibraryWithSource:source options:nil error:&libraryError]; - if (library == nil) - { - NSString *message = libraryError.localizedDescription; - SetFailure( - encoder, - message == nil ? "Metal could not compile the NV12 conversion shader." - : std::string(message.UTF8String)); - return false; - } - - id function = [library newFunctionWithName:@"bppBgraToNv12"]; - if (function == nil) - { - SetFailure(encoder, "Metal library did not contain the NV12 conversion kernel."); - return false; - } - - NSError *pipelineError = nil; - encoder->conversionPipeline = [device - newComputePipelineStateWithFunction:function - error:&pipelineError]; - if (encoder->conversionPipeline == nil) - { - NSString *message = pipelineError.localizedDescription; - SetFailure( - encoder, - message == nil ? "Metal could not create the NV12 conversion pipeline." - : std::string(message.UTF8String)); - return false; - } - [gConversionPipelines setObject:encoder->conversionPipeline forKey:device]; - return true; -} - -void CancelWriterOnQueue(Encoder *encoder) -{ - if (encoder == nullptr || encoder->writerQueue == nullptr) - return; - dispatch_sync(encoder->writerQueue, ^{ - @autoreleasepool - { - encoder->writerClosed = true; - @try - { - if (encoder->writer.status == AVAssetWriterStatusWriting) - [encoder->writer cancelWriting]; - } - @catch (NSException *exception) - { - SetFailure( - encoder, - exception.reason == nil - ? "AVAssetWriter threw while cancelling." - : std::string(exception.reason.UTF8String)); - } - } - }); -} - -void DestroyEncoder(Encoder *encoder) -{ - if (encoder == nullptr) - return; - - if (encoder->compressionSession != nullptr) - { - VTCompressionSessionInvalidate(encoder->compressionSession); - CFRelease(encoder->compressionSession); - encoder->compressionSession = nullptr; - } - for (auto &slot : encoder->slots) - { - if (slot.lumaTexture != nullptr) - CFRelease(slot.lumaTexture); - if (slot.chromaTexture != nullptr) - CFRelease(slot.chromaTexture); - if (slot.pixelBuffer != nullptr) - CFRelease(slot.pixelBuffer); - slot.lumaTexture = nullptr; - slot.chromaTexture = nullptr; - slot.pixelBuffer = nullptr; - } - encoder->slots.clear(); - - if (encoder->metalTextureCache != nullptr) - CFRelease(encoder->metalTextureCache); - if (encoder->pixelBufferPool != nullptr) - CFRelease(encoder->pixelBufferPool); - encoder->metalTextureCache = nullptr; - encoder->pixelBufferPool = nullptr; - encoder->conversionPipeline = nil; - encoder->writerInput = nil; - encoder->writer = nil; -} -} // namespace - -extern "C" -{ -UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces *interfaces) -{ - if (interfaces == nullptr) - { - gUnityMetal = nullptr; - return; - } - gUnityMetal = reinterpret_cast( - interfaces->GetInterfaceSplit(0x992C8EAEA95811E5ULL, 0x9A62C4B5B9876117ULL)); -} - -UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API UnityPluginUnload() -{ - gUnityMetal = nullptr; -} - -__attribute__((visibility("default"))) int BppVtHasUnityMetalInterface() -{ - return gUnityMetal == nullptr ? 0 : 1; -} - -__attribute__((visibility("default"))) void *BppVtGetRenderEventFunc() -{ - return reinterpret_cast(&RenderEventCallback); -} - -__attribute__((visibility("default"))) int BppVtCreate( - const char *outputPath, - int width, - int height, - int fps, - int bitrateBitsPerSecond, - void **handle) -{ - if (handle == nullptr) - return -1; - *handle = nullptr; - if (outputPath == nullptr || width <= 0 || height <= 0 || fps <= 0 || bitrateBitsPerSecond <= 0) - return -2; - - @autoreleasepool - { - auto *encoder = new Encoder(); - encoder->fps = fps; - encoder->encodeQueue = dispatch_queue_create( - "com.bazaarplusplus.replay.videotoolbox.encode", - DISPATCH_QUEUE_SERIAL); - encoder->writerQueue = dispatch_queue_create( - "com.bazaarplusplus.replay.videotoolbox.writer", - DISPATCH_QUEUE_SERIAL); - - NSString *path = [NSString stringWithUTF8String:outputPath]; - if (path == nil) - { - delete encoder; - return -3; - } - - NSURL *url = [NSURL fileURLWithPath:path]; - [[NSFileManager defaultManager] removeItemAtURL:url error:nil]; - NSError *writerError = nil; - encoder->writer = [[AVAssetWriter alloc] - initWithURL:url - fileType:AVFileTypeMPEG4 - error:&writerError]; - if (encoder->writer == nil) - { - encoder->error = writerError == nil - ? "AVAssetWriter initialization failed." - : std::string(writerError.localizedDescription.UTF8String); - encoder->failed = true; - *handle = encoder; - return -4; - } - - NSDictionary *pixelBufferAttributes = @{ - (NSString *)kCVPixelBufferPixelFormatTypeKey : - @(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange), - (NSString *)kCVPixelBufferWidthKey : @(width), - (NSString *)kCVPixelBufferHeightKey : @(height), - (NSString *)kCVPixelBufferMetalCompatibilityKey : @YES, - (NSString *)kCVPixelBufferIOSurfacePropertiesKey : @{}, - }; - NSDictionary *poolAttributes = @{ - (NSString *)kCVPixelBufferPoolMinimumBufferCountKey : @(kSlotCount), - }; - - CVReturn cvStatus = CVPixelBufferPoolCreate( - kCFAllocatorDefault, - (__bridge CFDictionaryRef)poolAttributes, - (__bridge CFDictionaryRef)pixelBufferAttributes, - &encoder->pixelBufferPool); - if (cvStatus != kCVReturnSuccess || encoder->pixelBufferPool == nullptr) - { - SetFailure(encoder, StatusMessage("CVPixelBufferPoolCreate", cvStatus)); - *handle = encoder; - return -5; - } - - // Use Unity's device rather than the process default. The IOSurface-backed destination - // textures must belong to the same Metal device as Unity's render command buffer. - id device = gUnityMetal == nullptr ? nil : gUnityMetal->MetalDevice(); - if (device == nil) - { - SetFailure(encoder, "Unity returned no Metal device."); - *handle = encoder; - return -6; - } - if (!InitializeConversionPipeline(encoder, device)) - { - *handle = encoder; - return -7; - } - - cvStatus = CVMetalTextureCacheCreate( - kCFAllocatorDefault, - nullptr, - device, - nullptr, - &encoder->metalTextureCache); - if (cvStatus != kCVReturnSuccess || encoder->metalTextureCache == nullptr) - { - SetFailure(encoder, StatusMessage("CVMetalTextureCacheCreate", cvStatus)); - *handle = encoder; - return -7; - } - - encoder->slots.resize(kSlotCount); - for (int i = 0; i < kSlotCount; i++) - { - auto &slot = encoder->slots[(size_t)i]; - cvStatus = CVPixelBufferPoolCreatePixelBuffer( - kCFAllocatorDefault, - encoder->pixelBufferPool, - &slot.pixelBuffer); - if (cvStatus != kCVReturnSuccess || slot.pixelBuffer == nullptr) - { - SetFailure(encoder, StatusMessage("CVPixelBufferPoolCreatePixelBuffer", cvStatus)); - *handle = encoder; - return -8; - } - - CVBufferSetAttachment( - slot.pixelBuffer, - kCVImageBufferYCbCrMatrixKey, - kCVImageBufferYCbCrMatrix_ITU_R_709_2, - kCVAttachmentMode_ShouldPropagate); - CVBufferSetAttachment( - slot.pixelBuffer, - kCVImageBufferColorPrimariesKey, - kCVImageBufferColorPrimaries_ITU_R_709_2, - kCVAttachmentMode_ShouldPropagate); - CVBufferSetAttachment( - slot.pixelBuffer, - kCVImageBufferTransferFunctionKey, - kCVImageBufferTransferFunction_ITU_R_709_2, - kCVAttachmentMode_ShouldPropagate); - - if (CVPixelBufferGetPlaneCount(slot.pixelBuffer) != 2) - { - SetFailure(encoder, "VideoToolbox NV12 pixel buffer did not expose two planes."); - *handle = encoder; - return -9; - } - - cvStatus = CVMetalTextureCacheCreateTextureFromImage( - kCFAllocatorDefault, - encoder->metalTextureCache, - slot.pixelBuffer, - nullptr, - MTLPixelFormatR8Unorm, - width, - height, - 0, - &slot.lumaTexture); - if (cvStatus != kCVReturnSuccess || slot.lumaTexture == nullptr) - { - SetFailure(encoder, StatusMessage("CVMetalTextureCacheCreateTextureFromImage(Y)", cvStatus)); - *handle = encoder; - return -10; - } - - cvStatus = CVMetalTextureCacheCreateTextureFromImage( - kCFAllocatorDefault, - encoder->metalTextureCache, - slot.pixelBuffer, - nullptr, - MTLPixelFormatRG8Unorm, - width / 2, - height / 2, - 1, - &slot.chromaTexture); - if (cvStatus != kCVReturnSuccess || slot.chromaTexture == nullptr) - { - SetFailure(encoder, StatusMessage("CVMetalTextureCacheCreateTextureFromImage(UV)", cvStatus)); - *handle = encoder; - return -11; - } - } - - OSStatus status = VTCompressionSessionCreate( - kCFAllocatorDefault, - width, - height, - kCMVideoCodecType_H264, - nullptr, - (__bridge CFDictionaryRef)pixelBufferAttributes, - nullptr, - CompressionOutputCallback, - encoder, - &encoder->compressionSession); - if (status != noErr || encoder->compressionSession == nullptr) - { - SetFailure(encoder, StatusMessage("VTCompressionSessionCreate", status)); - *handle = encoder; - return -10; - } - - int expectedFrameRate = fps; - int maxFrameDelayCount = 2; - int keyFrameInterval = fps * 2; - int averageBitrate = bitrateBitsPerSecond; - CFNumberRef expectedFrameRateNumber = CFNumberCreate( - kCFAllocatorDefault, kCFNumberIntType, &expectedFrameRate); - CFNumberRef maxFrameDelayCountNumber = CFNumberCreate( - kCFAllocatorDefault, kCFNumberIntType, &maxFrameDelayCount); - CFNumberRef keyFrameIntervalNumber = CFNumberCreate( - kCFAllocatorDefault, kCFNumberIntType, &keyFrameInterval); - CFNumberRef bitrateNumber = CFNumberCreate( - kCFAllocatorDefault, kCFNumberIntType, &averageBitrate); - - bool configured = - SetCompressionProperty( - encoder, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue, "VideoToolbox realtime mode") && - SetCompressionProperty( - encoder, kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse, "VideoToolbox frame reordering") && - SetCompressionProperty( - encoder, kVTCompressionPropertyKey_ExpectedFrameRate, expectedFrameRateNumber, "VideoToolbox expected frame rate") && - SetCompressionProperty( - encoder, kVTCompressionPropertyKey_MaxKeyFrameInterval, keyFrameIntervalNumber, "VideoToolbox keyframe interval") && - SetCompressionProperty( - encoder, kVTCompressionPropertyKey_AverageBitRate, bitrateNumber, "VideoToolbox average bitrate") && - SetCompressionProperty( - encoder, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_High_AutoLevel, "VideoToolbox H.264 profile"); - - if (configured) - { - // Bounding VideoToolbox's compression window is what guarantees that the - // IOSurface slots return to Unity. This is best-effort because the managed - // path still degrades honestly on encoders that reject the optional key. - VTSessionSetProperty( - encoder->compressionSession, - kVTCompressionPropertyKey_MaxFrameDelayCount, - maxFrameDelayCountNumber); - configured = - SetCompressionProperty( - encoder, - kVTCompressionPropertyKey_ColorPrimaries, - kCVImageBufferColorPrimaries_ITU_R_709_2, - "VideoToolbox BT.709 color primaries") && - SetCompressionProperty( - encoder, - kVTCompressionPropertyKey_TransferFunction, - kCVImageBufferTransferFunction_ITU_R_709_2, - "VideoToolbox BT.709 transfer function") && - SetCompressionProperty( - encoder, - kVTCompressionPropertyKey_YCbCrMatrix, - kCVImageBufferYCbCrMatrix_ITU_R_709_2, - "VideoToolbox BT.709 YCbCr matrix"); - } - - CFRelease(expectedFrameRateNumber); - CFRelease(maxFrameDelayCountNumber); - CFRelease(keyFrameIntervalNumber); - CFRelease(bitrateNumber); - - if (!configured) - { - *handle = encoder; - return -11; - } - - status = VTCompressionSessionPrepareToEncodeFrames(encoder->compressionSession); - if (status != noErr) - { - SetFailure(encoder, StatusMessage("VTCompressionSessionPrepareToEncodeFrames", status)); - *handle = encoder; - return -12; - } - - *handle = encoder; - return 0; - } -} - -__attribute__((visibility("default"))) int BppVtGetSlotCount(void *handle) -{ - auto *encoder = static_cast(handle); - return encoder == nullptr ? 0 : (int)encoder->slots.size(); -} - -__attribute__((visibility("default"))) int BppVtAcquireSlot(void *handle, int *slotIndex) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr || slotIndex == nullptr) - return 0; - - std::lock_guard guard(encoder->mutex); - if (encoder->failed || !encoder->acceptingFrames || encoder->finished) - return 0; - for (int i = 0; i < (int)encoder->slots.size(); i++) - { - if (encoder->slots[(size_t)i].state != SlotState::Free) - continue; - encoder->slots[(size_t)i].state = SlotState::GpuPending; - *slotIndex = i; - return 1; - } - - encoder->stats.acquireMisses++; - return 0; -} - -__attribute__((visibility("default"))) void *BppVtPrepareRenderEvent( - void *handle, - int slotIndex, - int64_t firstFrameIndex, - int frameCount) -{ - auto *encoder = static_cast(handle); - if ( - encoder == nullptr || slotIndex < 0 || slotIndex >= (int)encoder->slots.size() || - frameCount <= 0) - return nullptr; - - { - std::lock_guard guard(encoder->mutex); - if ( - encoder->failed || !encoder->acceptingFrames || encoder->finished || - encoder->slots[(size_t)slotIndex].state != SlotState::GpuPending) - { - return nullptr; - } - encoder->renderEventsPending++; - } - - return new RenderEventPacket{encoder, slotIndex, firstFrameIndex, frameCount}; -} - -__attribute__((visibility("default"))) void BppVtCommitRenderEvent(void *data) -{ - ReleaseRenderEventPacket(static_cast(data)); -} - -__attribute__((visibility("default"))) void BppVtCancelRenderEvent(void *data) -{ - auto *packet = static_cast(data); - if (packet == nullptr) - return; - - uint8_t expectedState = 0; - if (packet->state.compare_exchange_strong( - expectedState, - 2, - std::memory_order_acq_rel)) - { - ReleaseGpuPendingSlot(packet->encoder, packet->slotIndex); - CompleteRenderEvent(packet->encoder); - } - ReleaseRenderEventPacket(packet); -} - -__attribute__((visibility("default"))) void BppVtDiscardRenderEvent(void *data) -{ - auto *packet = static_cast(data); - if (packet == nullptr) - return; - - uint8_t expectedState = 0; - if (packet->state.compare_exchange_strong( - expectedState, - 2, - std::memory_order_acq_rel)) - { - ReleaseGpuPendingSlot(packet->encoder, packet->slotIndex); - CompleteRenderEvent(packet->encoder); - ReleaseRenderEventPacket(packet); - } - ReleaseRenderEventPacket(packet); -} - -__attribute__((visibility("default"))) void BppVtReleaseSlot(void *handle, int slotIndex) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return; - - std::lock_guard guard(encoder->mutex); - if (slotIndex >= 0 && slotIndex < (int)encoder->slots.size()) - { - auto &slot = encoder->slots[(size_t)slotIndex]; - if (slot.state == SlotState::GpuPending) - slot.state = SlotState::Free; - } -} - -__attribute__((visibility("default"))) int BppVtFinish(void *handle, int timeoutMs) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return 0; - - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::milliseconds(std::max(1, timeoutMs)); - bool renderEventsDrained = false; - { - std::unique_lock guard(encoder->mutex); - if (encoder->finished) - return encoder->failed ? 0 : 1; - encoder->acceptingFrames = false; - renderEventsDrained = encoder->renderEventCondition.wait_until( - guard, - deadline, - [encoder] { return encoder->renderEventsPending == 0; }); - } - - if (!renderEventsDrained) - { - SetFailure(encoder, "Timed out waiting for Unity Metal render events to finish."); - CancelWriterOnQueue(encoder); - std::lock_guard guard(encoder->mutex); - encoder->finished = true; - return 0; - } - - OSStatus status = VTCompressionSessionCompleteFrames( - encoder->compressionSession, - kCMTimeInvalid); - if (status != noErr) - SetFailure(encoder, StatusMessage("VTCompressionSessionCompleteFrames", status)); - - bool writerCallbacksDrained = false; - { - std::unique_lock guard(encoder->mutex); - writerCallbacksDrained = encoder->writerCondition.wait_until( - guard, - deadline, - [encoder] { - return encoder->failed || - encoder->stats.appendedFrames == encoder->stats.submittedFrames; - }); - } - if (!writerCallbacksDrained) - SetFailure(encoder, "Timed out waiting for VideoToolbox output callbacks to append every frame."); - - dispatch_sync(encoder->writerQueue, ^{}); - - if (!encoder->writerStarted) - { - SetFailure(encoder, "VideoToolbox completed without producing an encoded frame."); - } - else - { - dispatch_semaphore_t completion = dispatch_semaphore_create(0); - dispatch_sync(encoder->writerQueue, ^{ - @autoreleasepool - { - encoder->writerClosed = true; - @try - { - [encoder->writerInput markAsFinished]; - [encoder->writer finishWritingWithCompletionHandler:^{ - dispatch_semaphore_signal(completion); - }]; - } - @catch (NSException *exception) - { - SetFailure( - encoder, - exception.reason == nil - ? "AVAssetWriter threw while finishing." - : std::string(exception.reason.UTF8String)); - dispatch_semaphore_signal(completion); - } - } - }); - - const auto remaining = std::chrono::duration_cast( - deadline - std::chrono::steady_clock::now()).count(); - if ( - remaining <= 0 || - dispatch_semaphore_wait( - completion, - dispatch_time(DISPATCH_TIME_NOW, remaining * NSEC_PER_MSEC)) != 0) - { - SetFailure(encoder, "AVAssetWriter timed out while finishing the MP4."); - CancelWriterOnQueue(encoder); - } - else if (encoder->writer.status != AVAssetWriterStatusCompleted) - { - NSString *message = encoder->writer.error.localizedDescription; - SetFailure( - encoder, - message == nil ? "AVAssetWriter did not complete the MP4." - : std::string(message.UTF8String)); - } - } - - { - std::lock_guard guard(encoder->mutex); - encoder->finished = true; - return encoder->failed ? 0 : 1; - } -} - -__attribute__((visibility("default"))) void BppVtDestroy(void *handle) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return; - - bool needsFinish = false; - { - std::lock_guard guard(encoder->mutex); - encoder->acceptingFrames = false; - needsFinish = - encoder->compressionSession != nullptr && !encoder->finished && - (encoder->stats.submittedFrames > 0 || encoder->renderEventsPending > 0); - } - if (needsFinish) - BppVtFinish(handle, 2000); - - bool renderEventsPending = false; - { - std::lock_guard guard(encoder->mutex); - renderEventsPending = encoder->renderEventsPending > 0; - needsFinish = - encoder->compressionSession != nullptr && !encoder->finished && - encoder->stats.submittedFrames > 0; - } - - // A timed-out Unity command buffer still owns a callback with this raw encoder pointer. - // Leaking the failed encoder is safer than freeing it underneath Metal; process teardown will - // reclaim it, and the normal completion path always reaches zero pending events. - if (renderEventsPending) - return; - - if (needsFinish) - BppVtFinish(handle, 2000); - - if (encoder->encodeQueue != nullptr) - dispatch_sync(encoder->encodeQueue, ^{}); - if (encoder->writerQueue != nullptr) - dispatch_sync(encoder->writerQueue, ^{}); - - DestroyEncoder(encoder); - delete encoder; -} - -__attribute__((visibility("default"))) int BppVtIsFailed(void *handle) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return 1; - std::lock_guard guard(encoder->mutex); - return encoder->failed ? 1 : 0; -} - -__attribute__((visibility("default"))) void BppVtGetStats( - void *handle, - BppVtNativeStats *stats) -{ - auto *encoder = static_cast(handle); - if (stats == nullptr) - return; - std::memset(stats, 0, sizeof(BppVtNativeStats)); - if (encoder == nullptr) - return; - - std::lock_guard guard(encoder->mutex); - *stats = encoder->stats; -} - -__attribute__((visibility("default"))) int BppVtCopyError( - void *handle, - char *buffer, - int capacity) -{ - auto *encoder = static_cast(handle); - if (buffer == nullptr || capacity <= 0) - return 0; - buffer[0] = '\0'; - if (encoder == nullptr) - return 0; - - std::lock_guard guard(encoder->mutex); - const int copied = std::min((int)encoder->error.size(), capacity - 1); - if (copied > 0) - std::memcpy(buffer, encoder->error.data(), (size_t)copied); - buffer[copied] = '\0'; - return copied; -} -} diff --git a/bazaarplusplus-mod/native/macos/Info.plist b/bazaarplusplus-mod/native/macos/Info.plist deleted file mode 100644 index 83864e8..0000000 --- a/bazaarplusplus-mod/native/macos/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - GfxPluginBppReplayVideoToolbox - CFBundleIdentifier - com.bazaarplusplus.replay.videotoolbox - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - GfxPluginBppReplayVideoToolbox - CFBundlePackageType - BNDL - CFBundleShortVersionString - 0.1 - CFBundleVersion - 1 - - diff --git a/bazaarplusplus-mod/native/macos/README.md b/bazaarplusplus-mod/native/macos/README.md deleted file mode 100644 index 9111817..0000000 --- a/bazaarplusplus-mod/native/macos/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# BppReplayVideoToolbox - -Native macOS backend for Combat Replay video recording. It keeps the real-time path inside the -Unity process and does not use ScreenCaptureKit or an external encoder process. - -## Data path - -1. `CommandBuffer.IssuePluginEventAndData` places a native callback after Unity's final render - commands. -2. The callback converts the final Metal texture to an IOSurface-backed NV12 `CVPixelBuffer` on - the GPU. -3. VideoToolbox encodes H.264 asynchronously and AVAssetWriter writes the silent first-pass MP4. -4. The existing CoreAudio process tap closes its PCM WAV at replay end. -5. `BppVtMuxAudio` copies the H.264 samples and uses AVFoundation to mix/resample the WAV input to - stereo 48 kHz AAC in the final MP4. - -No full-frame GPU readback, raw-video pipe, or Screen Recording permission is involved. Windows -uses the matching D3D11/Media Foundation native backend in `native/windows`. - -## Build - -```bash -./build.sh -``` - -The script requires macOS, Apple Silicon, Xcode Command Line Tools, and Node.js for the shared -native artifact catalog. It emits an ad-hoc signed and producer-verified bundle at: - -```text -build/GfxPluginBppReplayVideoToolbox.bundle -``` - -Ordinary C# contributors do not need the native toolchain: `just release::prepare ` reuses the staged copy while it matches the manifest and otherwise rebuilds through this script; see -[`docs/architecture/native-artifacts.md`](../../docs/architecture/native-artifacts.md). - -To build into an explicit side-effect-free output directory: - -```bash -./build.sh /absolute/output/directory -``` - -The bundle must be present under `TheBazaar.app/Contents/Plugins` before Unity starts so Unity calls -`UnityPluginLoad` and provides `IUnityGraphicsMetal`. This script signs ad hoc only; Developer ID -signing, notarization, and app re-signing belong to the installer's release build. - -## ABI - -[`BppReplayVideoToolbox.h`](./BppReplayVideoToolbox.h) is the stable C boundary consumed by -`MacMetalVideoEncoder` and `MacNativeReplayAudioMuxer`. The render callback packet and encoder -handles are opaque across that boundary. - -## Acceptance - -- output reports `avg_frame_rate=60/1`; -- `dropped_frames=0` and repeated frames are at most 3%; -- recorded replay p95 frame time is within 1 ms or 5% of the same replay without recording; -- audio finishes as `full`; -- the final MP4 has valid H.264 and AAC tracks and plays normally; -- the packaged mod contains only the platform-native recorder plugin. - -p99 remains diagnostic telemetry, not a release gate. diff --git a/bazaarplusplus-mod/native/macos/build.sh b/bazaarplusplus-mod/native/macos/build.sh deleted file mode 100644 index 544c699..0000000 --- a/bazaarplusplus-mod/native/macos/build.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -build_dir="${1:-$script_dir/build}" -bundle_name="GfxPluginBppReplayVideoToolbox.bundle" -bundle_dir="$build_dir/$bundle_name" -executable_dir="$bundle_dir/Contents/MacOS" -executable="$executable_dir/GfxPluginBppReplayVideoToolbox" - -if [[ "$(uname -s)" != "Darwin" ]]; then - echo "BppReplayVideoToolbox can only be built on macOS." >&2 - exit 1 -fi - -mkdir -p "$executable_dir" -cp "$script_dir/Info.plist" "$bundle_dir/Contents/Info.plist" -sdk_path="$(xcrun --sdk macosx --show-sdk-path)" -clang_path="$(xcrun --sdk macosx --find clang++)" - -"$clang_path" \ - -isysroot "$sdk_path" \ - -arch arm64 \ - -std=c++17 \ - -fobjc-arc \ - -fvisibility=hidden \ - -mmacosx-version-min=12.0 \ - -Werror=unguarded-availability -Werror=unguarded-availability-new \ - -O2 \ - -Wall -Wextra -Werror -Wno-deprecated-declarations \ - -bundle \ - -framework AVFoundation \ - -framework AudioToolbox \ - -framework CoreMedia \ - -framework CoreVideo \ - -framework Foundation \ - -framework Metal \ - -framework VideoToolbox \ - "$script_dir/BppReplayVideoToolbox.mm" \ - "$script_dir/BppReplayAudioMuxer.mm" \ - -o "$executable" - -# Development output is deliberately ad-hoc. The installer repository is the only production -# signing authority and must re-sign this bundle with the team named by OFFICIAL_APPLE_TEAM_ID in -# bazaarplusplus-installer/scripts/bundle.sh during release packaging. -codesign --force --sign - --timestamp=none "$bundle_dir" -codesign --verify --deep --strict "$bundle_dir" -"$script_dir/verify.sh" mac-replay "$executable" "$bundle_dir" - -echo "built $bundle_dir" diff --git a/bazaarplusplus-mod/native/macos/verify.sh b/bazaarplusplus-mod/native/macos/verify.sh deleted file mode 100644 index 0e27942..0000000 --- a/bazaarplusplus-mod/native/macos/verify.sh +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -kind="${1:?native artifact kind is required}" -binary="${2:?native binary path is required}" -signed_path="${3:-$binary}" -script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -catalog_path="$script_dir/../artifacts.json" - -catalog_values() { - local property="$1" - node -e ' -const fs = require("node:fs"); -const [catalogPath, artifactId, property] = process.argv.slice(1); -const catalog = JSON.parse(fs.readFileSync(catalogPath, "utf8")); -const artifact = catalog.platforms.macos.artifacts.find(({ id }) => id === artifactId); -if (!artifact) throw new Error(`missing catalog artifact ${artifactId}`); -process.stdout.write((artifact[property] ?? []).join("\n")); -' "$catalog_path" "$kind" "$property" -} - -catalog_platform_value() { - local property="$1" - node -e ' -const fs = require("node:fs"); -const [catalogPath, property] = process.argv.slice(1); -const catalog = JSON.parse(fs.readFileSync(catalogPath, "utf8")); -const value = catalog.platforms.macos[property]; -if (typeof value !== "string" || value === "") - throw new Error(`missing catalog macos.${property}`); -process.stdout.write(value); -' "$catalog_path" "$property" -} - -# The catalog owns the deployment target so this assertion cannot silently drift away from -# the value the installer hashes into the input digest. The build scripts still carry the -# literal -mmacosx-version-min flag, so a catalog edit alone fails the build loudly here -# instead of passing while producing the old minos. -deployment_target="$(catalog_platform_value deploymentTarget)" - -BPP_NATIVE_REQUIRED_EXPORTS="${BPP_NATIVE_REQUIRED_EXPORTS:-$(catalog_values requiredExports)}" -BPP_NATIVE_REQUIRED_WEAK_IMPORTS="${BPP_NATIVE_REQUIRED_WEAK_IMPORTS:-$(catalog_values requiredWeakImports)}" -BPP_NATIVE_ALLOWED_DEPENDENCY_PREFIXES="${BPP_NATIVE_ALLOWED_DEPENDENCY_PREFIXES:-$(catalog_values allowedDependencyPrefixes)}" - -[[ -f "$binary" ]] || { echo "missing native binary: $binary" >&2; exit 1; } -[[ -n "${BPP_NATIVE_REQUIRED_EXPORTS:-}" ]] || { - echo "BPP_NATIVE_REQUIRED_EXPORTS is required." >&2 - exit 1 -} - -sdk_path="$(xcrun --sdk macosx --show-sdk-path)" -clang_path="$(xcrun --sdk macosx --find clang)" - -archs="$(xcrun lipo -archs "$binary")" -[[ "$archs" == "arm64" ]] || { - echo "expected arm64 Mach-O, got: $archs" >&2 - exit 1 -} - -build_version="$(xcrun vtool -show-build "$binary")" -[[ "$build_version" == *"platform MACOS"* ]] || { - echo "Mach-O does not target platform MACOS." >&2 - exit 1 -} -[[ "$build_version" == *"minos $deployment_target"* ]] || { - echo "Mach-O deployment target is not $deployment_target." >&2 - exit 1 -} - -install_name="$(xcrun otool -D "$binary" 2>/dev/null | tail -n +2 | head -n 1 || true)" -while IFS= read -r dependency; do - [[ -n "$dependency" ]] || continue - [[ -n "$install_name" && "$dependency" == "$install_name" ]] && continue - allowed=false - while IFS= read -r prefix; do - [[ -n "$prefix" ]] || continue - if [[ "$dependency" == "$prefix"* ]]; then - allowed=true - break - fi - done <<<"${BPP_NATIVE_ALLOWED_DEPENDENCY_PREFIXES:-}" - [[ "$allowed" == "true" ]] || { - echo "unreviewed native dependency: $dependency" >&2 - exit 1 - } -done < <(xcrun otool -L "$binary" | tail -n +2 | sed -E 's/^[[:space:]]*([^[:space:]]+).*/\1/') - -actual_exports="$(xcrun nm -gUj "$binary" | sed 's/^_//' | LC_ALL=C sort)" -expected_exports="$(printf '%s\n' "$BPP_NATIVE_REQUIRED_EXPORTS" | sed '/^$/d' | LC_ALL=C sort)" -[[ "$actual_exports" == "$expected_exports" ]] || { - echo "native export set does not match the ABI contract." >&2 - diff -u <(printf '%s\n' "$expected_exports") <(printf '%s\n' "$actual_exports") >&2 || true - exit 1 -} - -# Driven entirely by the artifact's requiredWeakImports: an empty list is a natural no-op, -# so a new artifact that declares weak imports is checked without editing this script. -undefined_symbols="$(xcrun nm -m -u "$binary")" -while IFS= read -r symbol; do - [[ -n "$symbol" ]] || continue - line="$(printf '%s\n' "$undefined_symbols" | sed -n "/_$symbol[[:space:]]/p")" - [[ -n "$line" && ("$line" == *"weak import"* || "$line" == *"weak external"*) ]] || { - echo "required weak import is missing or strong: $symbol" >&2 - exit 1 - } -done <<<"${BPP_NATIVE_REQUIRED_WEAK_IMPORTS:-}" - -codesign --verify --strict "$binary" -signature_details="$(codesign -d --verbose=4 "$signed_path" 2>&1)" -[[ "$signature_details" == *"Signature=adhoc"* ]] || { - echo "producer output is not ad-hoc signed: $signed_path" >&2 - exit 1 -} - -smoke_dir="$(mktemp -d "${TMPDIR:-/tmp}/bpp-native-smoke.XXXXXX")" -trap 'rm -rf -- "$smoke_dir"' EXIT -"$clang_path" -isysroot "$sdk_path" -mmacosx-version-min="$deployment_target" \ - "$script_dir/BppNativeLoadSmoke.c" -o "$smoke_dir/bpp-native-load-smoke" -smoke_symbols=() -while IFS= read -r symbol; do - [[ -n "$symbol" ]] && smoke_symbols+=("$symbol") -done <<<"$BPP_NATIVE_REQUIRED_EXPORTS" -"$smoke_dir/bpp-native-load-smoke" "$binary" "${smoke_symbols[@]}" - -echo "verified $kind: arm64, minos $deployment_target, exports, dependencies, load, ad-hoc signature" diff --git a/bazaarplusplus-mod/native/windows/BppReplayMediaFoundation.cpp b/bazaarplusplus-mod/native/windows/BppReplayMediaFoundation.cpp deleted file mode 100644 index 740f89c..0000000 --- a/bazaarplusplus-mod/native/windows/BppReplayMediaFoundation.cpp +++ /dev/null @@ -1,1619 +0,0 @@ -#include "BppReplayMediaFoundation.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using Microsoft::WRL::ComPtr; - -#define UNITY_INTERFACE_API __stdcall -#define UNITY_INTERFACE_EXPORT __declspec(dllexport) - -struct UnityInterfaceGUID -{ - unsigned long long high; - unsigned long long low; -}; - -struct IUnityInterface -{ -}; - -struct IUnityInterfaces -{ - IUnityInterface *(UNITY_INTERFACE_API *GetInterface)(UnityInterfaceGUID guid); - void(UNITY_INTERFACE_API *RegisterInterface)(UnityInterfaceGUID guid, IUnityInterface *value); - IUnityInterface *(UNITY_INTERFACE_API *GetInterfaceSplit)( - unsigned long long guidHigh, - unsigned long long guidLow); - void(UNITY_INTERFACE_API *RegisterInterfaceSplit)( - unsigned long long guidHigh, - unsigned long long guidLow, - IUnityInterface *value); -}; - -struct RenderSurfaceBase; -using UnityRenderBuffer = RenderSurfaceBase *; -using UnityTextureID = unsigned int; - -struct IUnityGraphicsD3D11 : IUnityInterface -{ - ID3D11Device *(UNITY_INTERFACE_API *GetDevice)(); - ID3D11Resource *(UNITY_INTERFACE_API *TextureFromRenderBuffer)(UnityRenderBuffer buffer); - ID3D11Resource *(UNITY_INTERFACE_API *TextureFromNativeTexture)(UnityTextureID texture); - ID3D11RenderTargetView *(UNITY_INTERFACE_API *RTVFromRenderBuffer)(UnityRenderBuffer surface); - ID3D11ShaderResourceView *(UNITY_INTERFACE_API *SRVFromNativeTexture)(UnityTextureID texture); -}; - -namespace -{ -constexpr int kSlotCount = 8; -constexpr LONGLONG kTicksPerSecond = 10'000'000; -constexpr unsigned long long kD3D11GuidHigh = 0xAAB37EF87A87D748ULL; -constexpr unsigned long long kD3D11GuidLow = 0xBF76967F07EFB177ULL; - -IUnityGraphicsD3D11 *g_unityD3D11 = nullptr; -std::mutex g_mfMutex; -int g_mfReferences = 0; - -enum class SlotState : uint8_t -{ - Free, - GpuPending, - Encoding, -}; - -struct Encoder; - -struct FrameSlot -{ - ComPtr texture; - ComPtr outputView; - SlotState state = SlotState::Free; -}; - -struct Encoder -{ - std::mutex mutex; - std::condition_variable condition; - std::string error; - std::string encoderName; - bool failed = false; - bool acceptingFrames = true; - bool finished = false; - bool mfStarted = false; - bool destroyRequested = false; - bool destroyScheduled = false; - BOOL previousMultithreadProtection = FALSE; - int fps = 60; - int inFlight = 0; - int renderEventsPending = 0; - BppMfNativeStats stats{}; - - ComPtr device; - ComPtr context; - ComPtr multithread; - ComPtr videoDevice; - ComPtr videoContext; - ComPtr videoEnumerator; - ComPtr videoProcessor; - ComPtr sourceTexture; - ComPtr processorSourceTexture; - ComPtr sourceView; - std::vector slots; - - UINT resetToken = 0; - DWORD streamIndex = 0; - ComPtr deviceManager; - ComPtr sinkWriter; -}; - -struct RenderEventPacket -{ - Encoder *encoder; - int slotIndex; - int64_t firstFrameIndex; - int frameCount; - std::atomic state{0}; - std::atomic references{2}; -}; - -void MaybeScheduleDestroy(Encoder *encoder); - -class SlotReleaseCallback final : public IMFAsyncCallback -{ - public: - SlotReleaseCallback(Encoder *encoder, int slotIndex, int count) - : encoder_(encoder), slotIndex_(slotIndex), remaining_(count) - { - } - - STDMETHODIMP QueryInterface(REFIID iid, void **value) override - { - if (value == nullptr) - return E_POINTER; - if (iid == __uuidof(IUnknown) || iid == __uuidof(IMFAsyncCallback)) - { - *value = static_cast(this); - AddRef(); - return S_OK; - } - *value = nullptr; - return E_NOINTERFACE; - } - - STDMETHODIMP_(ULONG) AddRef() override - { - return static_cast(references_.fetch_add(1) + 1); - } - - STDMETHODIMP_(ULONG) Release() override - { - const ULONG remaining = static_cast(references_.fetch_sub(1) - 1); - if (remaining == 0) - delete this; - return remaining; - } - - STDMETHODIMP GetParameters(DWORD *, DWORD *) override - { - return E_NOTIMPL; - } - - STDMETHODIMP Invoke(IMFAsyncResult *) override - { - if (remaining_.fetch_sub(1) != 1) - return S_OK; - - { - std::lock_guard guard(encoder_->mutex); - if (slotIndex_ >= 0 && slotIndex_ < static_cast(encoder_->slots.size())) - encoder_->slots[static_cast(slotIndex_)].state = SlotState::Free; - encoder_->inFlight = std::max(0, encoder_->inFlight - 1); - encoder_->condition.notify_all(); - } - MaybeScheduleDestroy(encoder_); - return S_OK; - } - - private: - ~SlotReleaseCallback() = default; - std::atomic references_{1}; - Encoder *encoder_; - int slotIndex_; - std::atomic remaining_; -}; - -std::string HResultMessage(const char *operation, HRESULT result) -{ - char text[256]; - std::snprintf( - text, - sizeof(text), - "%s failed with HRESULT 0x%08lX.", - operation, - static_cast(result)); - return text; -} - -std::wstring Utf8ToWide(const char *value) -{ - if (value == nullptr || value[0] == '\0') - return {}; - const int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value, -1, nullptr, 0); - if (length <= 1) - return {}; - std::wstring result(static_cast(length), L'\0'); - MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value, -1, result.data(), length); - result.pop_back(); - return result; -} - -std::string WideToUtf8(const wchar_t *value) -{ - if (value == nullptr || value[0] == L'\0') - return {}; - const int length = WideCharToMultiByte(CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr); - if (length <= 1) - return {}; - std::string result(static_cast(length), '\0'); - WideCharToMultiByte(CP_UTF8, 0, value, -1, result.data(), length, nullptr, nullptr); - result.pop_back(); - return result; -} - -void SetFailure(Encoder *encoder, const std::string &message) -{ - if (encoder == nullptr) - return; - std::lock_guard guard(encoder->mutex); - if (encoder->error.empty()) - encoder->error = message; - encoder->failed = true; - encoder->acceptingFrames = false; - encoder->condition.notify_all(); -} - -bool StartMediaFoundation(std::string &error) -{ - std::lock_guard guard(g_mfMutex); - if (g_mfReferences == 0) - { - const HRESULT result = MFStartup(MF_VERSION, MFSTARTUP_FULL); - if (FAILED(result)) - { - error = HResultMessage("MFStartup", result); - return false; - } - } - ++g_mfReferences; - return true; -} - -void StopMediaFoundation() -{ - std::lock_guard guard(g_mfMutex); - if (g_mfReferences <= 0) - return; - --g_mfReferences; - if (g_mfReferences == 0) - MFShutdown(); -} - -DWORD WINAPI DestroyEncoderWorker(void *context) -{ - auto *encoder = static_cast(context); - if (encoder->multithread != nullptr) - encoder->multithread->SetMultithreadProtected( - encoder->previousMultithreadProtection); - encoder->sinkWriter.Reset(); - const bool stopMediaFoundation = encoder->mfStarted; - encoder->mfStarted = false; - delete encoder; - if (stopMediaFoundation) - StopMediaFoundation(); - return 0; -} - -void MaybeScheduleDestroy(Encoder *encoder) -{ - bool schedule = false; - { - std::lock_guard guard(encoder->mutex); - if (encoder->destroyRequested && !encoder->destroyScheduled && - encoder->renderEventsPending == 0 && encoder->inFlight == 0) - { - encoder->destroyScheduled = true; - schedule = true; - } - } - if (!schedule) - return; - if (!QueueUserWorkItem(&DestroyEncoderWorker, encoder, WT_EXECUTEDEFAULT)) - DestroyEncoderWorker(encoder); -} - -bool SetMediaTypeSize(IMFMediaType *type, REFGUID key, UINT32 width, UINT32 height) -{ - return SUCCEEDED(MFSetAttributeSize(type, key, width, height)); -} - -bool SetMediaTypeRatio(IMFMediaType *type, REFGUID key, UINT32 numerator, UINT32 denominator) -{ - return SUCCEEDED(MFSetAttributeRatio(type, key, numerator, denominator)); -} - -std::unordered_map EnumerateHardwareEncoders() -{ - std::unordered_map encoders; - MFT_REGISTER_TYPE_INFO input{MFMediaType_Video, MFVideoFormat_NV12}; - MFT_REGISTER_TYPE_INFO output{MFMediaType_Video, MFVideoFormat_H264}; - IMFActivate **activations = nullptr; - UINT32 count = 0; - const HRESULT result = MFTEnumEx( - MFT_CATEGORY_VIDEO_ENCODER, - MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER, - &input, - &output, - &activations, - &count); - if (FAILED(result)) - return encoders; - - for (UINT32 index = 0; index < count; ++index) - { - GUID clsid{}; - wchar_t *name = nullptr; - UINT32 nameLength = 0; - if (SUCCEEDED(activations[index]->GetGUID(MFT_TRANSFORM_CLSID_Attribute, &clsid))) - { - wchar_t clsidText[64]{}; - StringFromGUID2(clsid, clsidText, static_cast(std::size(clsidText))); - if (SUCCEEDED(activations[index]->GetAllocatedString( - MFT_FRIENDLY_NAME_Attribute, - &name, - &nameLength))) - { - encoders.emplace(WideToUtf8(clsidText), WideToUtf8(name)); - CoTaskMemFree(name); - } - else - { - encoders.emplace(WideToUtf8(clsidText), WideToUtf8(clsidText)); - } - } - activations[index]->Release(); - } - CoTaskMemFree(activations); - return encoders; -} - -bool TransformOutputsH264(IMFTransform *transform) -{ - DWORD inputCount = 0; - DWORD outputCount = 0; - if (FAILED(transform->GetStreamCount(&inputCount, &outputCount)) || outputCount == 0) - return false; - - std::vector inputIds(inputCount); - std::vector outputIds(outputCount); - const HRESULT idsResult = transform->GetStreamIDs( - inputCount, - inputIds.data(), - outputCount, - outputIds.data()); - if (idsResult == E_NOTIMPL) - { - for (DWORD index = 0; index < outputCount; ++index) - outputIds[index] = index; - } - else if (FAILED(idsResult)) - { - return false; - } - - for (const DWORD outputId : outputIds) - { - ComPtr type; - if (SUCCEEDED(transform->GetOutputCurrentType(outputId, &type))) - { - GUID major{}; - GUID subtype{}; - if (SUCCEEDED(type->GetGUID(MF_MT_MAJOR_TYPE, &major)) && - SUCCEEDED(type->GetGUID(MF_MT_SUBTYPE, &subtype)) && - major == MFMediaType_Video && subtype == MFVideoFormat_H264) - return true; - } - for (DWORD typeIndex = 0;; ++typeIndex) - { - type.Reset(); - if (FAILED(transform->GetOutputAvailableType(outputId, typeIndex, &type))) - break; - GUID major{}; - GUID subtype{}; - if (SUCCEEDED(type->GetGUID(MF_MT_MAJOR_TYPE, &major)) && - SUCCEEDED(type->GetGUID(MF_MT_SUBTYPE, &subtype)) && - major == MFMediaType_Video && subtype == MFVideoFormat_H264) - return true; - } - } - return false; -} - -bool VerifyHardwareEncoder(Encoder *encoder) -{ - const auto hardware = EnumerateHardwareEncoders(); - if (hardware.empty()) - { - SetFailure(encoder, "Media Foundation did not enumerate a hardware NV12 to H.264 encoder."); - return false; - } - - ComPtr writerEx; - HRESULT result = encoder->sinkWriter.As(&writerEx); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("IMFSinkWriterEx", result)); - return false; - } - - for (DWORD transformIndex = 0;; ++transformIndex) - { - GUID category{}; - ComPtr transform; - result = writerEx->GetTransformForStream( - encoder->streamIndex, - transformIndex, - &category, - &transform); - if (FAILED(result)) - break; - - if (category != MFT_CATEGORY_VIDEO_ENCODER) - continue; - - ComPtr attributes; - GUID clsid{}; - if (FAILED(transform->GetAttributes(&attributes))) - continue; - - if (SUCCEEDED(attributes->GetGUID(MFT_TRANSFORM_CLSID_Attribute, &clsid))) - { - wchar_t clsidText[64]{}; - StringFromGUID2(clsid, clsidText, static_cast(std::size(clsidText))); - const auto found = hardware.find(WideToUtf8(clsidText)); - if (found != hardware.end()) - { - encoder->encoderName = found->second; - return true; - } - } - - if (!TransformOutputsH264(transform.Get())) - continue; - - wchar_t *hardwareUrl = nullptr; - UINT32 hardwareUrlLength = 0; - if (SUCCEEDED(attributes->GetAllocatedString( - MFT_ENUM_HARDWARE_URL_Attribute, - &hardwareUrl, - &hardwareUrlLength)) && - hardwareUrl != nullptr && hardwareUrlLength > 0) - { - encoder->encoderName = WideToUtf8(hardwareUrl); - CoTaskMemFree(hardwareUrl); - return true; - } - } - - SetFailure( - encoder, - "Sink Writer selected a transform that is not in Media Foundation's hardware H.264 catalog."); - return false; -} - -bool InitializeVideoProcessor(Encoder *encoder, int width, int height) -{ - D3D11_TEXTURE2D_DESC sourceDescription{}; - encoder->sourceTexture->GetDesc(&sourceDescription); - if (sourceDescription.SampleDesc.Count != 1) - { - SetFailure(encoder, "The persistent Unity capture texture must not be multisampled."); - return false; - } - // Recording must hand the encoder Unity's final gamma-encoded bytes unchanged. A TYPELESS - // resource cannot be bound as a view at all, and an _SRGB view would be read with - // sRGB-to-linear semantics, so both are mapped onto the plain UNORM twin. When that changes - // the format, the block below allocates a typed texture of that format and each frame is - // bit-copied into it — the same bits reinterpreted, never a color conversion. - DXGI_FORMAT processorSourceFormat = sourceDescription.Format; - switch (sourceDescription.Format) - { - case DXGI_FORMAT_B8G8R8A8_TYPELESS: - case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: - processorSourceFormat = DXGI_FORMAT_B8G8R8A8_UNORM; - break; - case DXGI_FORMAT_B8G8R8A8_UNORM: - break; - case DXGI_FORMAT_R8G8B8A8_TYPELESS: - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - processorSourceFormat = DXGI_FORMAT_R8G8B8A8_UNORM; - break; - case DXGI_FORMAT_R8G8B8A8_UNORM: - break; - default: - { - char message[160]; - std::snprintf( - message, - sizeof(message), - "Unsupported Unity D3D11 capture texture DXGI format %u.", - static_cast(sourceDescription.Format)); - SetFailure(encoder, message); - return false; - } - } - - if (processorSourceFormat != sourceDescription.Format) - { - D3D11_TEXTURE2D_DESC processorSourceDescription = sourceDescription; - processorSourceDescription.MipLevels = 1; - processorSourceDescription.ArraySize = 1; - processorSourceDescription.Format = processorSourceFormat; - processorSourceDescription.Usage = D3D11_USAGE_DEFAULT; - processorSourceDescription.CPUAccessFlags = 0; - processorSourceDescription.MiscFlags = 0; - HRESULT result = encoder->device->CreateTexture2D( - &processorSourceDescription, - nullptr, - &encoder->processorSourceTexture); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("CreateTexture2D(typed RGB capture alias)", result)); - return false; - } - } - else - { - encoder->processorSourceTexture = encoder->sourceTexture; - } - - HRESULT result = encoder->device.As(&encoder->videoDevice); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("ID3D11VideoDevice", result)); - return false; - } - result = encoder->context.As(&encoder->videoContext); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("ID3D11VideoContext", result)); - return false; - } - - D3D11_VIDEO_PROCESSOR_CONTENT_DESC content{}; - content.InputFrameFormat = D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE; - content.InputFrameRate = {static_cast(encoder->fps), 1}; - content.InputWidth = sourceDescription.Width; - content.InputHeight = sourceDescription.Height; - content.OutputFrameRate = {static_cast(encoder->fps), 1}; - content.OutputWidth = static_cast(width); - content.OutputHeight = static_cast(height); - content.Usage = D3D11_VIDEO_USAGE_PLAYBACK_NORMAL; - result = encoder->videoDevice->CreateVideoProcessorEnumerator( - &content, - &encoder->videoEnumerator); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("CreateVideoProcessorEnumerator", result)); - return false; - } - result = encoder->videoDevice->CreateVideoProcessor( - encoder->videoEnumerator.Get(), - 0, - &encoder->videoProcessor); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("CreateVideoProcessor", result)); - return false; - } - - D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC inputDescription{}; - inputDescription.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D; - inputDescription.Texture2D.MipSlice = 0; - inputDescription.Texture2D.ArraySlice = 0; - result = encoder->videoDevice->CreateVideoProcessorInputView( - encoder->processorSourceTexture.Get(), - encoder->videoEnumerator.Get(), - &inputDescription, - &encoder->sourceView); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("CreateVideoProcessorInputView", result)); - return false; - } - - D3D11_TEXTURE2D_DESC slotDescription{}; - slotDescription.Width = static_cast(width); - slotDescription.Height = static_cast(height); - slotDescription.MipLevels = 1; - slotDescription.ArraySize = 1; - slotDescription.Format = DXGI_FORMAT_NV12; - slotDescription.SampleDesc.Count = 1; - slotDescription.Usage = D3D11_USAGE_DEFAULT; - slotDescription.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; - - encoder->slots.resize(kSlotCount); - for (auto &slot : encoder->slots) - { - result = encoder->device->CreateTexture2D(&slotDescription, nullptr, &slot.texture); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("CreateTexture2D(NV12)", result)); - return false; - } - D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC outputDescription{}; - outputDescription.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2D; - outputDescription.Texture2D.MipSlice = 0; - result = encoder->videoDevice->CreateVideoProcessorOutputView( - slot.texture.Get(), - encoder->videoEnumerator.Get(), - &outputDescription, - &slot.outputView); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("CreateVideoProcessorOutputView", result)); - return false; - } - } - - const RECT sourceRect{0, 0, static_cast(sourceDescription.Width), static_cast(sourceDescription.Height)}; - const RECT targetRect{0, 0, width, height}; - encoder->videoContext->VideoProcessorSetStreamSourceRect( - encoder->videoProcessor.Get(), 0, TRUE, &sourceRect); - encoder->videoContext->VideoProcessorSetStreamDestRect( - encoder->videoProcessor.Get(), 0, TRUE, &targetRect); - encoder->videoContext->VideoProcessorSetOutputTargetRect( - encoder->videoProcessor.Get(), TRUE, &targetRect); - // The two ends deliberately use different range fields. The input is RGB, whose range lives - // in RGB_Range (0 = full 0-255). The NV12 output is YCbCr, whose range must come from - // Nominal_Range: putting it in the RGB field on the output side leaves the YCbCr range - // unstated and lets the driver default it, which need not agree with the - // MFNominalRange_16_235 / BT.709 media type this encoder declares — that mismatch is what - // produced black-level and contrast drift on some drivers. YCbCr_Matrix = 1 is BT.709 on - // both ends. - D3D11_VIDEO_PROCESSOR_COLOR_SPACE inputColor{}; - inputColor.RGB_Range = 0; - inputColor.YCbCr_Matrix = 1; - encoder->videoContext->VideoProcessorSetStreamColorSpace( - encoder->videoProcessor.Get(), 0, &inputColor); - D3D11_VIDEO_PROCESSOR_COLOR_SPACE outputColor{}; - outputColor.Nominal_Range = D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_16_235; - outputColor.YCbCr_Matrix = 1; - encoder->videoContext->VideoProcessorSetOutputColorSpace( - encoder->videoProcessor.Get(), &outputColor); - return true; -} - -bool InitializeSinkWriter( - Encoder *encoder, - const std::wstring &path, - int width, - int height, - int bitrateBitsPerSecond) -{ - HRESULT result = MFCreateDXGIDeviceManager( - &encoder->resetToken, - &encoder->deviceManager); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("MFCreateDXGIDeviceManager", result)); - return false; - } - result = encoder->deviceManager->ResetDevice(encoder->device.Get(), encoder->resetToken); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("IMFDXGIDeviceManager::ResetDevice", result)); - return false; - } - - ComPtr attributes; - result = MFCreateAttributes(&attributes, 4); - if (SUCCEEDED(result)) - result = attributes->SetUnknown(MF_SINK_WRITER_D3D_MANAGER, encoder->deviceManager.Get()); - if (SUCCEEDED(result)) - result = attributes->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, TRUE); - if (SUCCEEDED(result)) - result = attributes->SetUINT32(MF_READWRITE_D3D_OPTIONAL, FALSE); - if (SUCCEEDED(result)) - result = attributes->SetUINT32(MF_SINK_WRITER_DISABLE_THROTTLING, TRUE); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("Media Foundation writer attributes", result)); - return false; - } - - result = MFCreateSinkWriterFromURL(path.c_str(), nullptr, attributes.Get(), &encoder->sinkWriter); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("MFCreateSinkWriterFromURL", result)); - return false; - } - - ComPtr outputType; - result = MFCreateMediaType(&outputType); - if (SUCCEEDED(result)) - result = outputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); - if (SUCCEEDED(result)) - result = outputType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264); - if (SUCCEEDED(result)) - result = outputType->SetUINT32(MF_MT_AVG_BITRATE, static_cast(bitrateBitsPerSecond)); - if (SUCCEEDED(result)) - result = outputType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive); - if (SUCCEEDED(result)) - result = outputType->SetUINT32(MF_MT_VIDEO_NOMINAL_RANGE, MFNominalRange_16_235); - if (SUCCEEDED(result)) - result = outputType->SetUINT32(MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT709); - if (SUCCEEDED(result)) - result = outputType->SetUINT32(MF_MT_VIDEO_PRIMARIES, MFVideoPrimaries_BT709); - if (SUCCEEDED(result)) - result = outputType->SetUINT32(MF_MT_TRANSFER_FUNCTION, MFVideoTransFunc_709); - if (SUCCEEDED(result) && !SetMediaTypeSize(outputType.Get(), MF_MT_FRAME_SIZE, width, height)) - result = E_FAIL; - if (SUCCEEDED(result) && !SetMediaTypeRatio(outputType.Get(), MF_MT_FRAME_RATE, encoder->fps, 1)) - result = E_FAIL; - if (SUCCEEDED(result) && !SetMediaTypeRatio(outputType.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1)) - result = E_FAIL; - if (SUCCEEDED(result)) - result = outputType->SetUINT32(MF_MT_MPEG2_PROFILE, 100); // H.264 High profile_idc. - if (SUCCEEDED(result)) - result = encoder->sinkWriter->AddStream(outputType.Get(), &encoder->streamIndex); - - ComPtr inputType; - if (SUCCEEDED(result)) - result = MFCreateMediaType(&inputType); - if (SUCCEEDED(result)) - result = inputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); - if (SUCCEEDED(result)) - result = inputType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_NV12); - if (SUCCEEDED(result)) - result = inputType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive); - if (SUCCEEDED(result)) - result = inputType->SetUINT32(MF_MT_VIDEO_NOMINAL_RANGE, MFNominalRange_16_235); - if (SUCCEEDED(result)) - result = inputType->SetUINT32(MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT709); - if (SUCCEEDED(result)) - result = inputType->SetUINT32(MF_MT_VIDEO_PRIMARIES, MFVideoPrimaries_BT709); - if (SUCCEEDED(result)) - result = inputType->SetUINT32(MF_MT_TRANSFER_FUNCTION, MFVideoTransFunc_709); - if (SUCCEEDED(result)) - result = inputType->SetUINT32( - MF_MT_SAMPLE_SIZE, - static_cast(width * height * 3 / 2)); - if (SUCCEEDED(result)) - result = inputType->SetUINT32(MF_MT_FIXED_SIZE_SAMPLES, TRUE); - if (SUCCEEDED(result)) - result = inputType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE); - if (SUCCEEDED(result) && !SetMediaTypeSize(inputType.Get(), MF_MT_FRAME_SIZE, width, height)) - result = E_FAIL; - if (SUCCEEDED(result) && !SetMediaTypeRatio(inputType.Get(), MF_MT_FRAME_RATE, encoder->fps, 1)) - result = E_FAIL; - if (SUCCEEDED(result) && !SetMediaTypeRatio(inputType.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1)) - result = E_FAIL; - if (SUCCEEDED(result)) - result = encoder->sinkWriter->SetInputMediaType(encoder->streamIndex, inputType.Get(), nullptr); - if (SUCCEEDED(result)) - result = encoder->sinkWriter->BeginWriting(); - if (FAILED(result)) - { - SetFailure(encoder, HResultMessage("Media Foundation H.264 writer initialization", result)); - return false; - } - return VerifyHardwareEncoder(encoder); -} - -void CompleteRenderEvent(Encoder *encoder) -{ - { - std::lock_guard guard(encoder->mutex); - encoder->renderEventsPending = std::max(0, encoder->renderEventsPending - 1); - encoder->condition.notify_all(); - } - MaybeScheduleDestroy(encoder); -} - -void ReleasePacket(RenderEventPacket *packet) -{ - if (packet != nullptr && packet->references.fetch_sub(1) == 1) - delete packet; -} - -void ReleasePendingSlot(Encoder *encoder, int slotIndex) -{ - std::lock_guard guard(encoder->mutex); - if (slotIndex >= 0 && slotIndex < static_cast(encoder->slots.size()) && - encoder->slots[static_cast(slotIndex)].state == SlotState::GpuPending) - encoder->slots[static_cast(slotIndex)].state = SlotState::Free; - encoder->condition.notify_all(); -} - -bool SubmitSlot(Encoder *encoder, int slotIndex, int64_t firstFrameIndex, int frameCount) -{ - auto *callback = new SlotReleaseCallback(encoder, slotIndex, frameCount); - const LONGLONG fps = std::max(1, encoder->fps); - - { - std::lock_guard guard(encoder->mutex); - encoder->slots[static_cast(slotIndex)].state = SlotState::Encoding; - ++encoder->inFlight; - encoder->stats.maxInFlight = std::max(encoder->stats.maxInFlight, encoder->inFlight); - } - - for (int index = 0; index < frameCount; ++index) - { - bool allocatorSet = false; - ComPtr buffer; - ComPtr sample; - HRESULT result = MFCreateDXGISurfaceBuffer( - __uuidof(ID3D11Texture2D), - encoder->slots[static_cast(slotIndex)].texture.Get(), - 0, - FALSE, - &buffer); - if (SUCCEEDED(result)) - { - D3D11_TEXTURE2D_DESC description{}; - encoder->slots[static_cast(slotIndex)].texture->GetDesc(&description); - result = buffer->SetCurrentLength(description.Width * description.Height * 3 / 2); - } - if (SUCCEEDED(result)) - result = MFCreateVideoSampleFromSurface(nullptr, &sample); - if (SUCCEEDED(result)) - result = sample->AddBuffer(buffer.Get()); - ComPtr tracked; - if (SUCCEEDED(result)) - result = sample.As(&tracked); - if (SUCCEEDED(result)) - result = tracked->SetAllocator(callback, nullptr); - if (SUCCEEDED(result)) - allocatorSet = true; - if (SUCCEEDED(result)) - { - const LONGLONG frameIndex = firstFrameIndex + index; - const LONGLONG sampleStart = frameIndex * kTicksPerSecond / fps; - const LONGLONG sampleEnd = (frameIndex + 1) * kTicksPerSecond / fps; - result = sample->SetSampleTime(sampleStart); - if (SUCCEEDED(result)) - result = sample->SetSampleDuration(sampleEnd - sampleStart); - } - if (SUCCEEDED(result)) - result = encoder->sinkWriter->WriteSample(encoder->streamIndex, sample.Get()); - if (FAILED(result)) - { - const int manualReleases = frameCount - index - (allocatorSet ? 1 : 0); - for (int release = 0; release < manualReleases; ++release) - callback->Invoke(nullptr); - callback->Release(); - SetFailure(encoder, HResultMessage("IMFSinkWriter::WriteSample", result)); - return false; - } - - std::lock_guard guard(encoder->mutex); - ++encoder->stats.submittedFrames; - ++encoder->stats.writtenFrames; - } - callback->Release(); - return true; -} - -void UNITY_INTERFACE_API RenderEventCallback(int eventId, void *data) -{ - if (eventId != 1 || data == nullptr) - return; - auto *packet = static_cast(data); - const uint8_t oldState = packet->state.exchange(1); - if (oldState != 0) - { - ReleasePacket(packet); - return; - } - - Encoder *encoder = packet->encoder; - const int slotIndex = packet->slotIndex; - const int64_t firstFrameIndex = packet->firstFrameIndex; - const int frameCount = packet->frameCount; - bool canSubmit = false; - { - std::lock_guard guard(encoder->mutex); - canSubmit = !encoder->failed && !encoder->finished && - slotIndex >= 0 && slotIndex < static_cast(encoder->slots.size()) && - encoder->slots[static_cast(slotIndex)].state == SlotState::GpuPending; - } - if (!canSubmit) - { - ReleasePendingSlot(encoder, slotIndex); - CompleteRenderEvent(encoder); - ReleasePacket(packet); - return; - } - - D3D11_VIDEO_PROCESSOR_STREAM stream{}; - stream.Enable = TRUE; - stream.pInputSurface = encoder->sourceView.Get(); - if (encoder->processorSourceTexture.Get() != encoder->sourceTexture.Get()) - { - encoder->context->CopySubresourceRegion( - encoder->processorSourceTexture.Get(), - 0, - 0, - 0, - 0, - encoder->sourceTexture.Get(), - 0, - nullptr); - } - const HRESULT result = encoder->videoContext->VideoProcessorBlt( - encoder->videoProcessor.Get(), - encoder->slots[static_cast(slotIndex)].outputView.Get(), - 0, - 1, - &stream); - if (FAILED(result)) - { - ReleasePendingSlot(encoder, slotIndex); - SetFailure(encoder, HResultMessage("ID3D11VideoContext::VideoProcessorBlt", result)); - } - else if (!SubmitSlot(encoder, slotIndex, firstFrameIndex, frameCount)) - { - std::lock_guard guard(encoder->mutex); - ++encoder->stats.encodeErrors; - } - - CompleteRenderEvent(encoder); - ReleasePacket(packet); -} - -int CopyText(const std::string &text, char *buffer, int capacity) -{ - if (buffer == nullptr || capacity <= 0) - return 0; - const int copied = std::min(static_cast(text.size()), capacity - 1); - if (copied > 0) - std::memcpy(buffer, text.data(), static_cast(copied)); - buffer[copied] = '\0'; - return copied; -} -} // namespace - -extern "C" UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API UnityPluginLoad( - IUnityInterfaces *interfaces) -{ - g_unityD3D11 = interfaces == nullptr - ? nullptr - : static_cast( - interfaces->GetInterfaceSplit(kD3D11GuidHigh, kD3D11GuidLow)); -} - -extern "C" UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API UnityPluginUnload() -{ - g_unityD3D11 = nullptr; -} - -extern "C" int __cdecl BppMfHasUnityD3D11Interface() -{ - return g_unityD3D11 != nullptr && g_unityD3D11->GetDevice() != nullptr ? 1 : 0; -} - -extern "C" int __cdecl BppMfCanMuxAudio() -{ - return 1; -} - -extern "C" void *__cdecl BppMfGetRenderEventFunc() -{ - return reinterpret_cast(&RenderEventCallback); -} - -extern "C" int __cdecl BppMfCreate( - const char *outputPath, - void *sourceTexture, - int width, - int height, - int fps, - int bitrateBitsPerSecond, - void **handle) -{ - if (handle == nullptr) - return -1; - *handle = nullptr; - auto *encoder = new Encoder(); - *handle = encoder; - encoder->fps = fps; - - if (g_unityD3D11 == nullptr || g_unityD3D11->GetDevice() == nullptr) - { - SetFailure(encoder, "Unity did not preload the replay plugin through D3D11."); - return -2; - } - if (sourceTexture == nullptr || width <= 0 || height <= 0 || - (width & 1) != 0 || (height & 1) != 0 || fps <= 0 || bitrateBitsPerSecond <= 0) - { - SetFailure(encoder, "Invalid Media Foundation encoder arguments."); - return -3; - } - const std::wstring path = Utf8ToWide(outputPath); - if (path.empty()) - { - SetFailure(encoder, "The output path is not valid UTF-8."); - return -4; - } - - std::string startupError; - if (!StartMediaFoundation(startupError)) - { - SetFailure(encoder, startupError); - return -5; - } - encoder->mfStarted = true; - - encoder->device = g_unityD3D11->GetDevice(); - encoder->device->GetImmediateContext(&encoder->context); - encoder->context.As(&encoder->multithread); - if (encoder->multithread != nullptr) - encoder->previousMultithreadProtection = - encoder->multithread->SetMultithreadProtected(TRUE); - static_cast(sourceTexture)->QueryInterface( - IID_PPV_ARGS(&encoder->sourceTexture)); - if (encoder->sourceTexture == nullptr) - { - SetFailure(encoder, "Unity native texture pointer is not an ID3D11Texture2D."); - return -6; - } - if (!InitializeVideoProcessor(encoder, width, height)) - return -7; - if (!InitializeSinkWriter(encoder, path, width, height, bitrateBitsPerSecond)) - return -8; - return 0; -} - -extern "C" int __cdecl BppMfGetSlotCount(void *handle) -{ - auto *encoder = static_cast(handle); - return encoder == nullptr ? 0 : static_cast(encoder->slots.size()); -} - -extern "C" int __cdecl BppMfAcquireSlot(void *handle, int *slotIndex) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr || slotIndex == nullptr) - return 0; - std::lock_guard guard(encoder->mutex); - if (encoder->failed || !encoder->acceptingFrames || encoder->finished) - return 0; - for (int index = 0; index < static_cast(encoder->slots.size()); ++index) - { - if (encoder->slots[static_cast(index)].state != SlotState::Free) - continue; - encoder->slots[static_cast(index)].state = SlotState::GpuPending; - *slotIndex = index; - return 1; - } - ++encoder->stats.acquireMisses; - return 0; -} - -extern "C" void *__cdecl BppMfPrepareRenderEvent( - void *handle, - int slotIndex, - int64_t firstFrameIndex, - int frameCount) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr || frameCount <= 0) - return nullptr; - { - std::lock_guard guard(encoder->mutex); - if (encoder->failed || !encoder->acceptingFrames || encoder->finished || - slotIndex < 0 || slotIndex >= static_cast(encoder->slots.size()) || - encoder->slots[static_cast(slotIndex)].state != SlotState::GpuPending) - return nullptr; - ++encoder->renderEventsPending; - } - return new RenderEventPacket{encoder, slotIndex, firstFrameIndex, frameCount}; -} - -extern "C" void __cdecl BppMfCommitRenderEvent(void *eventData) -{ - ReleasePacket(static_cast(eventData)); -} - -extern "C" void __cdecl BppMfCancelRenderEvent(void *eventData) -{ - auto *packet = static_cast(eventData); - if (packet == nullptr) - return; - uint8_t expected = 0; - if (packet->state.compare_exchange_strong(expected, 2)) - { - ReleasePendingSlot(packet->encoder, packet->slotIndex); - CompleteRenderEvent(packet->encoder); - } - ReleasePacket(packet); -} - -extern "C" void __cdecl BppMfDiscardRenderEvent(void *eventData) -{ - auto *packet = static_cast(eventData); - if (packet == nullptr) - return; - uint8_t expected = 0; - if (packet->state.compare_exchange_strong(expected, 2)) - { - ReleasePendingSlot(packet->encoder, packet->slotIndex); - CompleteRenderEvent(packet->encoder); - ReleasePacket(packet); - } - ReleasePacket(packet); -} - -extern "C" void __cdecl BppMfReleaseSlot(void *handle, int slotIndex) -{ - ReleasePendingSlot(static_cast(handle), slotIndex); -} - -extern "C" int __cdecl BppMfFinish(void *handle, int timeoutMs) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return 0; - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::milliseconds(std::max(1, timeoutMs)); - { - std::unique_lock guard(encoder->mutex); - if (encoder->finished) - return encoder->failed ? 0 : 1; - encoder->acceptingFrames = false; - if (!encoder->condition.wait_until( - guard, - deadline, - [encoder] { return encoder->renderEventsPending == 0; })) - { - encoder->failed = true; - encoder->finished = true; - if (encoder->error.empty()) - encoder->error = "Timed out waiting for Unity D3D11 render events."; - return 0; - } - } - - HRESULT result = encoder->sinkWriter == nullptr - ? E_POINTER - : encoder->sinkWriter->Finalize(); - if (FAILED(result)) - SetFailure(encoder, HResultMessage("IMFSinkWriter::Finalize", result)); - encoder->sinkWriter.Reset(); - - { - std::unique_lock guard(encoder->mutex); - if (!encoder->condition.wait_until( - guard, - deadline, - [encoder] { return encoder->inFlight == 0; })) - { - encoder->failed = true; - if (encoder->error.empty()) - encoder->error = "Timed out waiting for Media Foundation to release NV12 surfaces."; - } - encoder->finished = true; - return encoder->failed ? 0 : 1; - } -} - -extern "C" void __cdecl BppMfDestroy(void *handle) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return; - bool canFinish = false; - { - std::lock_guard guard(encoder->mutex); - encoder->acceptingFrames = false; - canFinish = encoder->renderEventsPending == 0; - } - if (canFinish && !encoder->finished && encoder->sinkWriter != nullptr) - BppMfFinish(encoder, 2000); - { - std::lock_guard guard(encoder->mutex); - encoder->destroyRequested = true; - } - MaybeScheduleDestroy(encoder); -} - -extern "C" int __cdecl BppMfIsFailed(void *handle) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return 1; - std::lock_guard guard(encoder->mutex); - return encoder->failed ? 1 : 0; -} - -extern "C" void __cdecl BppMfGetStats(void *handle, BppMfNativeStats *stats) -{ - if (stats == nullptr) - return; - std::memset(stats, 0, sizeof(*stats)); - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return; - std::lock_guard guard(encoder->mutex); - *stats = encoder->stats; -} - -extern "C" int __cdecl BppMfCopyError(void *handle, char *buffer, int capacity) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return CopyText("Native encoder handle is unavailable.", buffer, capacity); - std::lock_guard guard(encoder->mutex); - return CopyText(encoder->error, buffer, capacity); -} - -extern "C" int __cdecl BppMfCopyEncoderName(void *handle, char *buffer, int capacity) -{ - auto *encoder = static_cast(handle); - if (encoder == nullptr) - return CopyText({}, buffer, capacity); - std::lock_guard guard(encoder->mutex); - return CopyText(encoder->encoderName, buffer, capacity); -} - -namespace -{ -bool ConfigureAudioReader( - const std::wstring &path, - ComPtr &reader, - ComPtr &pcmType, - std::string &error) -{ - HRESULT result = MFCreateSourceReaderFromURL(path.c_str(), nullptr, &reader); - if (SUCCEEDED(result)) - result = reader->SetStreamSelection(static_cast(MF_SOURCE_READER_ALL_STREAMS), FALSE); - if (SUCCEEDED(result)) - result = reader->SetStreamSelection(static_cast(MF_SOURCE_READER_FIRST_AUDIO_STREAM), TRUE); - if (SUCCEEDED(result)) - result = MFCreateMediaType(&pcmType); - if (SUCCEEDED(result)) - result = pcmType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio); - if (SUCCEEDED(result)) - result = pcmType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM); - if (SUCCEEDED(result)) - result = pcmType->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS, 2); - if (SUCCEEDED(result)) - result = pcmType->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, 48'000); - if (SUCCEEDED(result)) - result = pcmType->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16); - if (SUCCEEDED(result)) - result = pcmType->SetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, 4); - if (SUCCEEDED(result)) - result = pcmType->SetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, 192'000); - if (SUCCEEDED(result)) - result = reader->SetCurrentMediaType( - static_cast(MF_SOURCE_READER_FIRST_AUDIO_STREAM), - nullptr, - pcmType.Get()); - if (FAILED(result)) - { - error = HResultMessage("Configure WAV source reader", result); - return false; - } - return true; -} - -bool ConfigureVideoReader( - const std::wstring &path, - ComPtr &reader, - ComPtr &videoType, - std::string &error) -{ - HRESULT result = MFCreateSourceReaderFromURL(path.c_str(), nullptr, &reader); - if (SUCCEEDED(result)) - result = reader->SetStreamSelection(static_cast(MF_SOURCE_READER_ALL_STREAMS), FALSE); - if (SUCCEEDED(result)) - result = reader->SetStreamSelection(static_cast(MF_SOURCE_READER_FIRST_VIDEO_STREAM), TRUE); - if (SUCCEEDED(result)) - result = reader->GetCurrentMediaType(static_cast(MF_SOURCE_READER_FIRST_VIDEO_STREAM), &videoType); - GUID major{}; - GUID subtype{}; - if (SUCCEEDED(result)) - result = videoType->GetGUID(MF_MT_MAJOR_TYPE, &major); - if (SUCCEEDED(result)) - result = videoType->GetGUID(MF_MT_SUBTYPE, &subtype); - if (SUCCEEDED(result) && (major != MFMediaType_Video || subtype != MFVideoFormat_H264)) - result = MF_E_INVALIDMEDIATYPE; - if (FAILED(result)) - { - error = HResultMessage("Open silent H.264 video", result); - return false; - } - return true; -} - -bool ConfigureMuxWriter( - const std::wstring &path, - IMFMediaType *videoType, - IMFMediaType *pcmType, - int audioBitrateBitsPerSecond, - ComPtr &writer, - DWORD &videoStream, - DWORD &audioStream, - std::string &error) -{ - ComPtr attributes; - HRESULT result = MFCreateAttributes(&attributes, 2); - if (SUCCEEDED(result)) - result = attributes->SetUINT32(MF_SINK_WRITER_DISABLE_THROTTLING, TRUE); - if (SUCCEEDED(result)) - result = attributes->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, TRUE); - if (SUCCEEDED(result)) - result = MFCreateSinkWriterFromURL(path.c_str(), nullptr, attributes.Get(), &writer); - if (SUCCEEDED(result)) - result = writer->AddStream(videoType, &videoStream); - if (SUCCEEDED(result)) - result = writer->SetInputMediaType(videoStream, videoType, nullptr); - - ComPtr aacType; - if (SUCCEEDED(result)) - result = MFCreateMediaType(&aacType); - if (SUCCEEDED(result)) - result = aacType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio); - if (SUCCEEDED(result)) - result = aacType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_AAC); - if (SUCCEEDED(result)) - result = aacType->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS, 2); - if (SUCCEEDED(result)) - result = aacType->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, 48'000); - if (SUCCEEDED(result)) - result = aacType->SetUINT32( - MF_MT_AUDIO_AVG_BYTES_PER_SECOND, - static_cast(std::max(1, audioBitrateBitsPerSecond) / 8)); - if (SUCCEEDED(result)) - result = aacType->SetUINT32(MF_MT_AAC_PAYLOAD_TYPE, 0); - if (SUCCEEDED(result)) - result = aacType->SetUINT32(MF_MT_AAC_AUDIO_PROFILE_LEVEL_INDICATION, 0x29); - if (SUCCEEDED(result)) - result = writer->AddStream(aacType.Get(), &audioStream); - if (SUCCEEDED(result)) - result = writer->SetInputMediaType(audioStream, pcmType, nullptr); - if (SUCCEEDED(result)) - result = writer->BeginWriting(); - if (FAILED(result)) - { - error = HResultMessage("Create Media Foundation AAC MP4 writer", result); - return false; - } - return true; -} - -bool HasTimedOut( - const std::chrono::steady_clock::time_point &deadline, - std::string &error) -{ - if (std::chrono::steady_clock::now() < deadline) - return false; - error = "Media Foundation audio mux timed out."; - return true; -} - -bool CopyVideoSamples( - IMFSourceReader *reader, - IMFSinkWriter *writer, - DWORD writerStream, - const std::chrono::steady_clock::time_point &deadline, - LONGLONG &videoDuration, - std::string &error) -{ - bool hasStart = false; - LONGLONG start = 0; - LONGLONG lastEnd = 0; - for (;;) - { - if (HasTimedOut(deadline, error)) - return false; - DWORD actualStream = 0; - DWORD flags = 0; - LONGLONG timestamp = 0; - ComPtr sample; - HRESULT result = reader->ReadSample( - static_cast(MF_SOURCE_READER_FIRST_VIDEO_STREAM), - 0, - &actualStream, - &flags, - ×tamp, - &sample); - if (FAILED(result)) - { - error = HResultMessage("Read H.264 sample", result); - return false; - } - if ((flags & MF_SOURCE_READERF_ENDOFSTREAM) != 0) - break; - if (sample == nullptr) - continue; - if (!hasStart) - { - start = timestamp; - hasStart = true; - } - const LONGLONG normalized = std::max(0, timestamp - start); - LONGLONG duration = 0; - if (FAILED(sample->GetSampleDuration(&duration)) || duration <= 0) - duration = 1; - sample->SetSampleTime(normalized); - result = writer->WriteSample(writerStream, sample.Get()); - if (FAILED(result)) - { - error = HResultMessage("Copy H.264 sample", result); - return false; - } - lastEnd = std::max(lastEnd, normalized + duration); - } - videoDuration = lastEnd; - if (!hasStart || videoDuration <= 0) - { - error = "The silent H.264 input did not contain a usable video sample."; - return false; - } - return true; -} - -bool CopyAudioSamples( - IMFSourceReader *reader, - IMFSinkWriter *writer, - DWORD writerStream, - LONGLONG videoDuration, - const std::chrono::steady_clock::time_point &deadline, - std::string &error) -{ - bool hasStart = false; - LONGLONG start = 0; - for (;;) - { - if (HasTimedOut(deadline, error)) - return false; - DWORD actualStream = 0; - DWORD flags = 0; - LONGLONG timestamp = 0; - ComPtr sample; - HRESULT result = reader->ReadSample( - static_cast(MF_SOURCE_READER_FIRST_AUDIO_STREAM), - 0, - &actualStream, - &flags, - ×tamp, - &sample); - if (FAILED(result)) - { - error = HResultMessage("Read WAV sample", result); - return false; - } - if ((flags & MF_SOURCE_READERF_ENDOFSTREAM) != 0) - break; - if (sample == nullptr) - continue; - if (!hasStart) - { - start = timestamp; - hasStart = true; - } - const LONGLONG normalized = std::max(0, timestamp - start); - if (normalized >= videoDuration) - break; - sample->SetSampleTime(normalized); - result = writer->WriteSample(writerStream, sample.Get()); - if (FAILED(result)) - { - error = HResultMessage("Encode AAC sample", result); - return false; - } - } - if (!hasStart) - { - error = "The WAV input did not contain a usable audio sample."; - return false; - } - return true; -} -} // namespace - -extern "C" int __cdecl BppMfMuxAudio( - const char *silentVideoPath, - const char *const *wavPaths, - int wavPathCount, - const char *finalPath, - int audioBitrateBitsPerSecond, - int timeoutMs, - char *errorBuffer, - int errorCapacity) -{ - std::string error; - if (silentVideoPath == nullptr || finalPath == nullptr || wavPaths == nullptr || - wavPathCount != 1 || wavPaths[0] == nullptr) - { - CopyText( - "The Windows native mux currently requires exactly one WASAPI WAV track.", - errorBuffer, - errorCapacity); - return -2; - } - - const std::wstring videoPath = Utf8ToWide(silentVideoPath); - const std::wstring wavPath = Utf8ToWide(wavPaths[0]); - const std::wstring outputPath = Utf8ToWide(finalPath); - if (videoPath.empty() || wavPath.empty() || outputPath.empty()) - { - CopyText("A mux input or output path is not valid UTF-8.", errorBuffer, errorCapacity); - return -3; - } - - const HRESULT comResult = CoInitializeEx(nullptr, COINIT_MULTITHREADED); - const bool uninitializeCom = SUCCEEDED(comResult); - if (FAILED(comResult) && comResult != RPC_E_CHANGED_MODE) - { - CopyText(HResultMessage("CoInitializeEx", comResult), errorBuffer, errorCapacity); - return -4; - } - if (!StartMediaFoundation(error)) - { - if (uninitializeCom) - CoUninitialize(); - CopyText(error, errorBuffer, errorCapacity); - return -5; - } - - int returnCode = -6; - { - ComPtr videoReader; - ComPtr audioReader; - ComPtr videoType; - ComPtr pcmType; - ComPtr writer; - DWORD videoStream = 0; - DWORD audioStream = 0; - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::milliseconds(std::max(1, timeoutMs)); - - if (ConfigureVideoReader(videoPath, videoReader, videoType, error) && - ConfigureAudioReader(wavPath, audioReader, pcmType, error) && - ConfigureMuxWriter( - outputPath, - videoType.Get(), - pcmType.Get(), - audioBitrateBitsPerSecond, - writer, - videoStream, - audioStream, - error)) - { - LONGLONG videoDuration = 0; - if (CopyVideoSamples( - videoReader.Get(), - writer.Get(), - videoStream, - deadline, - videoDuration, - error) && - CopyAudioSamples( - audioReader.Get(), - writer.Get(), - audioStream, - videoDuration, - deadline, - error)) - { - if (HasTimedOut(deadline, error)) - { - returnCode = -8; - } - else - { - const HRESULT result = writer->Finalize(); - if (SUCCEEDED(result)) - returnCode = 1; - else - error = HResultMessage("Finalize AAC MP4", result); - } - } - else if (error == "Media Foundation audio mux timed out.") - { - returnCode = -8; - } - } - } - - StopMediaFoundation(); - if (uninitializeCom) - CoUninitialize(); - CopyText(error, errorBuffer, errorCapacity); - return returnCode; -} diff --git a/bazaarplusplus-mod/native/windows/BppReplayMediaFoundation.h b/bazaarplusplus-mod/native/windows/BppReplayMediaFoundation.h deleted file mode 100644 index be95426..0000000 --- a/bazaarplusplus-mod/native/windows/BppReplayMediaFoundation.h +++ /dev/null @@ -1,79 +0,0 @@ -#pragma once - -#include - -#if defined(__cplusplus) -extern "C" -{ -#endif - -typedef struct BppMfNativeStats -{ - int submittedFrames; - int writtenFrames; - int acquireMisses; - int enqueueRejects; - int encodeErrors; - int maxInFlight; -} BppMfNativeStats; - -__declspec(dllexport) int __cdecl BppMfHasUnityD3D11Interface(void); -__declspec(dllexport) int __cdecl BppMfCanMuxAudio(void); -__declspec(dllexport) void *__cdecl BppMfGetRenderEventFunc(void); -__declspec(dllexport) int __cdecl BppMfCreate( - const char *outputPath, - void *sourceTexture, - int width, - int height, - int fps, - int bitrateBitsPerSecond, - void **handle); -__declspec(dllexport) int __cdecl BppMfGetSlotCount(void *handle); -__declspec(dllexport) int __cdecl BppMfAcquireSlot(void *handle, int *slotIndex); - -// Render-event packet ownership. BppMfPrepareRenderEvent returns a packet holding two -// references: one owned by the caller, one owned by the render-event callback the caller is -// about to queue. They are released independently and in no guaranteed order — the callback -// may run before, during, or after the call that releases the caller's reference. -// -// BppMfCommitRenderEvent releases the caller's reference. Use once the event is queued. -// BppMfCancelRenderEvent releases the caller's reference and marks the packet so a -// callback that has not run yet returns early. Use to abandon an -// event that WAS queued; the callback still releases its own. -// BppMfDiscardRenderEvent releases BOTH references. Use only for an event that was NEVER -// queued, because no callback will ever run to release the second. -// -// Swapping the last two is not benign: Discard on a queued event frees the packet while the -// render thread still holds it, and Cancel on an unqueued event leaks it. -__declspec(dllexport) void *__cdecl BppMfPrepareRenderEvent( - void *handle, - int slotIndex, - int64_t firstFrameIndex, - int frameCount); -__declspec(dllexport) void __cdecl BppMfCommitRenderEvent(void *eventData); -__declspec(dllexport) void __cdecl BppMfCancelRenderEvent(void *eventData); -__declspec(dllexport) void __cdecl BppMfDiscardRenderEvent(void *eventData); -__declspec(dllexport) void __cdecl BppMfReleaseSlot(void *handle, int slotIndex); -__declspec(dllexport) int __cdecl BppMfFinish(void *handle, int timeoutMs); -__declspec(dllexport) void __cdecl BppMfDestroy(void *handle); -__declspec(dllexport) int __cdecl BppMfIsFailed(void *handle); -__declspec(dllexport) void __cdecl BppMfGetStats(void *handle, BppMfNativeStats *stats); -__declspec(dllexport) int __cdecl BppMfCopyError(void *handle, char *buffer, int capacity); -__declspec(dllexport) int __cdecl BppMfCopyEncoderName( - void *handle, - char *buffer, - int capacity); - -__declspec(dllexport) int __cdecl BppMfMuxAudio( - const char *silentVideoPath, - const char *const *wavPaths, - int wavPathCount, - const char *finalPath, - int audioBitrateBitsPerSecond, - int timeoutMs, - char *errorBuffer, - int errorCapacity); - -#if defined(__cplusplus) -} -#endif diff --git a/bazaarplusplus-mod/native/windows/BppReplayMediaFoundationSmoke.cpp b/bazaarplusplus-mod/native/windows/BppReplayMediaFoundationSmoke.cpp deleted file mode 100644 index 5ddd2de..0000000 --- a/bazaarplusplus-mod/native/windows/BppReplayMediaFoundationSmoke.cpp +++ /dev/null @@ -1,282 +0,0 @@ -#include "BppReplayMediaFoundation.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -using Microsoft::WRL::ComPtr; - -#define UNITY_INTERFACE_API __stdcall - -struct UnityInterfaceGUID -{ - unsigned long long high; - unsigned long long low; -}; - -struct IUnityInterface -{ -}; - -struct IUnityInterfaces -{ - IUnityInterface *(UNITY_INTERFACE_API *GetInterface)(UnityInterfaceGUID guid); - void(UNITY_INTERFACE_API *RegisterInterface)(UnityInterfaceGUID guid, IUnityInterface *value); - IUnityInterface *(UNITY_INTERFACE_API *GetInterfaceSplit)( - unsigned long long guidHigh, - unsigned long long guidLow); - void(UNITY_INTERFACE_API *RegisterInterfaceSplit)( - unsigned long long guidHigh, - unsigned long long guidLow, - IUnityInterface *value); -}; - -struct IUnityGraphicsD3D11 : IUnityInterface -{ - ID3D11Device *(UNITY_INTERFACE_API *GetDevice)(); - ID3D11Resource *(UNITY_INTERFACE_API *TextureFromRenderBuffer)(void *buffer); - ID3D11Resource *(UNITY_INTERFACE_API *TextureFromNativeTexture)(unsigned int texture); - ID3D11RenderTargetView *(UNITY_INTERFACE_API *RTVFromRenderBuffer)(void *surface); - ID3D11ShaderResourceView *(UNITY_INTERFACE_API *SRVFromNativeTexture)(unsigned int texture); -}; - -extern "C" void __stdcall UnityPluginLoad(IUnityInterfaces *interfaces); -extern "C" void __stdcall UnityPluginUnload(); - -namespace -{ -ComPtr g_device; -IUnityGraphicsD3D11 g_d3dInterface{}; - -ID3D11Device *UNITY_INTERFACE_API GetDevice() -{ - return g_device.Get(); -} - -IUnityInterface *UNITY_INTERFACE_API GetInterface(UnityInterfaceGUID guid) -{ - if (guid.high == 0xAAB37EF87A87D748ULL && guid.low == 0xBF76967F07EFB177ULL) - return &g_d3dInterface; - return nullptr; -} - -IUnityInterface *UNITY_INTERFACE_API GetInterfaceSplit( - unsigned long long high, - unsigned long long low) -{ - return GetInterface({high, low}); -} - -void UNITY_INTERFACE_API RegisterInterface(UnityInterfaceGUID, IUnityInterface *) -{ -} - -void UNITY_INTERFACE_API RegisterInterfaceSplit( - unsigned long long, - unsigned long long, - IUnityInterface *) -{ -} - -bool WriteSilentWav(const std::filesystem::path &path, int seconds) -{ - constexpr uint32_t sampleRate = 48'000; - constexpr uint16_t channels = 2; - constexpr uint16_t bits = 16; - const uint32_t dataBytes = sampleRate * channels * (bits / 8) * seconds; - const uint32_t riffBytes = 36 + dataBytes; - const uint32_t byteRate = sampleRate * channels * (bits / 8); - const uint16_t blockAlign = channels * (bits / 8); - std::ofstream output(path, std::ios::binary); - if (!output) - return false; - output.write("RIFF", 4); - output.write(reinterpret_cast(&riffBytes), sizeof(riffBytes)); - output.write("WAVEfmt ", 8); - const uint32_t formatSize = 16; - const uint16_t pcm = 1; - output.write(reinterpret_cast(&formatSize), sizeof(formatSize)); - output.write(reinterpret_cast(&pcm), sizeof(pcm)); - output.write(reinterpret_cast(&channels), sizeof(channels)); - output.write(reinterpret_cast(&sampleRate), sizeof(sampleRate)); - output.write(reinterpret_cast(&byteRate), sizeof(byteRate)); - output.write(reinterpret_cast(&blockAlign), sizeof(blockAlign)); - output.write(reinterpret_cast(&bits), sizeof(bits)); - output.write("data", 4); - output.write(reinterpret_cast(&dataBytes), sizeof(dataBytes)); - std::vector silence(dataBytes, 0); - output.write(silence.data(), static_cast(silence.size())); - return output.good(); -} -} // namespace - -int main() -{ - ComPtr context; - D3D_FEATURE_LEVEL featureLevel{}; - HRESULT result = D3D11CreateDevice( - nullptr, - D3D_DRIVER_TYPE_HARDWARE, - nullptr, - D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT, - nullptr, - 0, - D3D11_SDK_VERSION, - &g_device, - &featureLevel, - &context); - if (FAILED(result)) - { - std::fprintf(stderr, "D3D11CreateDevice failed: 0x%08lX\n", static_cast(result)); - return 1; - } - - g_d3dInterface.GetDevice = &GetDevice; - IUnityInterfaces interfaces{ - &GetInterface, - &RegisterInterface, - &GetInterfaceSplit, - &RegisterInterfaceSplit, - }; - UnityPluginLoad(&interfaces); - - constexpr int width = 1280; - constexpr int height = 720; - constexpr int fps = 60; - D3D11_TEXTURE2D_DESC description{}; - description.Width = width; - description.Height = height; - description.MipLevels = 1; - description.ArraySize = 1; - // Typeless on purpose: it forces the typed-alias path in InitializeVideoProcessor, which is - // what Unity actually hands the plugin. - description.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS; - description.SampleDesc.Count = 1; - description.Usage = D3D11_USAGE_DEFAULT; - description.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; - ComPtr source; - result = g_device->CreateTexture2D(&description, nullptr, &source); - if (FAILED(result)) - return 2; - - ComPtr target; - D3D11_RENDER_TARGET_VIEW_DESC targetDescription{}; - targetDescription.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - targetDescription.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; - result = g_device->CreateRenderTargetView(source.Get(), &targetDescription, &target); - if (FAILED(result)) - return 3; - const float color[4]{0.15F, 0.35F, 0.75F, 1.0F}; - context->ClearRenderTargetView(target.Get(), color); - - const auto root = std::filesystem::temp_directory_path() / "bpp-mf-smoke"; - std::filesystem::create_directories(root); - const auto silentPath = root / "silent.mp4"; - const auto wavPath = root / "audio.wav"; - const auto finalPath = root / "final.mp4"; - std::filesystem::remove(silentPath); - std::filesystem::remove(finalPath); - - void *encoder = nullptr; - const std::string silentUtf8 = silentPath.u8string(); - int createResult = BppMfCreate( - silentUtf8.c_str(), - source.Get(), - width, - height, - fps, - 6'000'000, - &encoder); - char error[2048]{}; - BppMfCopyError(encoder, error, static_cast(sizeof(error))); - if (createResult != 0) - { - std::fprintf(stderr, "BppMfCreate failed (%d): %s\n", createResult, error); - BppMfDestroy(encoder); - return 4; - } - - auto renderEvent = reinterpret_cast(BppMfGetRenderEventFunc()); - for (int frame = 0; frame < fps * 2; ++frame) - { - int slot = -1; - for (int retry = 0; retry < 500 && BppMfAcquireSlot(encoder, &slot) == 0; ++retry) - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - if (slot < 0) - { - BppMfCopyError(encoder, error, static_cast(sizeof(error))); - std::fprintf(stderr, "No slot available at frame %d: %s\n", frame, error); - return 5; - } - void *packet = BppMfPrepareRenderEvent(encoder, slot, frame, 1); - if (packet == nullptr) - return 6; - renderEvent(1, packet); - BppMfCommitRenderEvent(packet); - } - - if (BppMfFinish(encoder, 30'000) == 0) - { - BppMfCopyError(encoder, error, static_cast(sizeof(error))); - std::fprintf(stderr, "BppMfFinish failed: %s\n", error); - return 7; - } - char encoderName[512]{}; - BppMfCopyEncoderName(encoder, encoderName, static_cast(sizeof(encoderName))); - BppMfNativeStats stats{}; - BppMfGetStats(encoder, &stats); - std::printf( - "encoder=%s submitted=%d written=%d max_in_flight=%d\n", - encoderName, - stats.submittedFrames, - stats.writtenFrames, - stats.maxInFlight); - BppMfDestroy(encoder); - - if (!WriteSilentWav(wavPath, 2)) - return 8; - const std::string wavUtf8 = wavPath.u8string(); - const std::string finalUtf8 = finalPath.u8string(); - const char *wavPaths[]{wavUtf8.c_str()}; - const auto muxStarted = std::chrono::steady_clock::now(); - const int muxResult = BppMfMuxAudio( - silentUtf8.c_str(), - wavPaths, - 1, - finalUtf8.c_str(), - 192'000, - 30'000, - error, - static_cast(sizeof(error))); - const auto muxElapsed = std::chrono::duration_cast( - std::chrono::steady_clock::now() - muxStarted); - if (muxResult != 1) - { - std::fprintf(stderr, "BppMfMuxAudio failed (%d): %s\n", muxResult, error); - return 9; - } - if (muxElapsed > std::chrono::seconds(3)) - { - std::fprintf( - stderr, - "BppMfMuxAudio was throttled (%lld ms).\n", - static_cast(muxElapsed.count())); - return 10; - } - std::printf( - "mux_ms=%lld\nsilent=%s\nfinal=%s\n", - static_cast(muxElapsed.count()), - silentUtf8.c_str(), - finalUtf8.c_str()); - UnityPluginUnload(); - return 0; -} diff --git a/bazaarplusplus-mod/native/windows/README.md b/bazaarplusplus-mod/native/windows/README.md deleted file mode 100644 index 6ae09b0..0000000 --- a/bazaarplusplus-mod/native/windows/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Windows native replay recorder - -`GfxPluginBppReplayMediaFoundation.dll` is a Unity D3D11 rendering plugin. It keeps the real-time -path inside the Unity process and does not use an external encoder process. macOS uses the matching -Metal/VideoToolbox/AVFoundation native backend in `native/macos`. - -## Data path - -1. `CommandBuffer.IssuePluginEventAndData` places a native callback after Unity's final render - commands. -2. The callback converts the persistent replay capture texture to NV12 with the D3D11 video - processor. -3. Media Foundation encodes H.264 and the sink writer produces the silent first-pass MP4. The active - encoder is checked against Media Foundation's hardware MFT catalog; software encoding is rejected - instead of being used as a hidden fallback. -4. The existing WASAPI loopback capture closes its PCM WAV at replay end. -5. `BppMfMuxAudio` copies the H.264 samples and uses Media Foundation to mix/resample the WAV input - to stereo 48 kHz AAC in the final MP4. - -## Build - -Build on Windows with Visual Studio 2022 and the Windows SDK: - -```powershell -./build.ps1 -``` - -The script builds into `build/` by default, verifies the x64 PE metadata, exact catalog ABI exports, -reviewed system dependencies, and unsigned producer policy, then runs the native smoke program. -Pass `-OutputDirectory` for a side-effect-free staging build. `test.ps1` runs the smoke program on -its own. - -`just release::prepare ` reuses the staged copy while it matches the manifest and otherwise rebuilds through this script; see -[`docs/architecture/native-artifacts.md`](../../docs/architecture/native-artifacts.md). - -## ABI - -[`BppReplayMediaFoundation.h`](./BppReplayMediaFoundation.h) is the stable C boundary consumed by -`WindowsMediaFoundationVideoEncoder` and `WindowsNativeReplayAudioMuxer`. The render callback packet -and encoder handles are opaque across that boundary. - -## Where it ships - -The DLL must be installed in `TheBazaar_Data/Plugins/x86_64` so Unity loads it before BepInEx -constructs the managed recording backend. diff --git a/bazaarplusplus-mod/native/windows/build.ps1 b/bazaarplusplus-mod/native/windows/build.ps1 deleted file mode 100644 index 1d84431..0000000 --- a/bazaarplusplus-mod/native/windows/build.ps1 +++ /dev/null @@ -1,101 +0,0 @@ -param( - [string]$OutputDirectory = (Join-Path $PSScriptRoot 'build'), - [switch]$SkipSmoke -) - -$ErrorActionPreference = 'Stop' - -$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -if (-not (Test-Path -LiteralPath $vswhere)) { - throw 'Visual Studio Installer vswhere.exe was not found.' -} - -$install = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath -if ([string]::IsNullOrWhiteSpace($install)) { - throw 'Visual Studio C++ build tools were not found.' -} - -$vcvars = Join-Path $install 'VC\Auxiliary\Build\vcvars64.bat' -$sourceDir = Split-Path -Parent $MyInvocation.MyCommand.Path -$buildDir = $OutputDirectory -New-Item -ItemType Directory -Force -Path $buildDir | Out-Null - -$command = 'call "{0}" && cl /nologo /std:c++17 /utf-8 /EHsc /W4 /WX /O2 /MT /LD /DNOMINMAX /DUNICODE /D_UNICODE "{1}\BppReplayMediaFoundation.cpp" /link /Brepro /OUT:"{2}\GfxPluginBppReplayMediaFoundation.dll" /IMPLIB:"{2}\BppReplayMediaFoundation.lib" d3d11.lib dxgi.lib evr.lib mfplat.lib mfreadwrite.lib mfuuid.lib ole32.lib shlwapi.lib' -f $vcvars, $sourceDir, $buildDir -cmd.exe /d /s /c $command -if ($LASTEXITCODE -ne 0) { - throw "Native Windows replay plugin build failed with exit code $LASTEXITCODE." -} - -$binary = Join-Path $buildDir 'GfxPluginBppReplayMediaFoundation.dll' -$headers = cmd.exe /d /s /c ('call "{0}" && dumpbin /headers "{1}"' -f $vcvars, $binary) -if ($LASTEXITCODE -ne 0 -or ($headers -join "`n") -notmatch 'machine \(x64\)') { - throw 'Native Windows replay plugin is not an x64 PE image.' -} - -$catalog = Get-Content -Raw -LiteralPath (Join-Path $sourceDir '..\artifacts.json') | ConvertFrom-Json -$artifactPolicy = $catalog.platforms.windows.artifacts | Where-Object { $_.id -eq 'windows-replay' } -$requiredExports = if ([string]::IsNullOrWhiteSpace($env:BPP_NATIVE_REQUIRED_EXPORTS)) { - @($artifactPolicy.requiredExports) -} else { - @($env:BPP_NATIVE_REQUIRED_EXPORTS -split '\r?\n' | Where-Object { $_ }) -} -if ($requiredExports.Count -eq 0) { - throw 'BPP_NATIVE_REQUIRED_EXPORTS is required.' -} -$exportOutput = cmd.exe /d /s /c ('call "{0}" && dumpbin /exports "{1}"' -f $vcvars, $binary) -if ($LASTEXITCODE -ne 0) { - throw 'Could not inspect native Windows exports.' -} -$actualExports = @( - $exportOutput | ForEach-Object { - if ($_ -match '^\s+\d+\s+[0-9A-Fa-f]+\s+[0-9A-Fa-f]+\s+(\S+)\s*$') { - $Matches[1] - } - } | Sort-Object -Unique -) -$exportDiff = @(Compare-Object ($requiredExports | Sort-Object -Unique) $actualExports) -if ($exportDiff.Count -ne 0) { - throw "Native Windows export set does not match the ABI contract:`n$($exportDiff | Out-String)" -} - -$allowedDependencies = if ([string]::IsNullOrWhiteSpace($env:BPP_NATIVE_ALLOWED_DEPENDENCIES)) { - @($artifactPolicy.allowedDependencies) -} else { - @($env:BPP_NATIVE_ALLOWED_DEPENDENCIES -split '\r?\n' | Where-Object { $_ }) -} -if ($allowedDependencies.Count -eq 0) { - throw 'BPP_NATIVE_ALLOWED_DEPENDENCIES is required.' -} -$dependencyOutput = cmd.exe /d /s /c ('call "{0}" && dumpbin /dependents "{1}"' -f $vcvars, $binary) -if ($LASTEXITCODE -ne 0) { - throw 'Could not inspect native Windows dependencies.' -} -$actualDependencies = @( - $dependencyOutput | ForEach-Object { - if ($_ -match '^\s+([A-Za-z0-9._-]+\.dll)\s*$') { - $Matches[1] - } - } | Sort-Object -Unique -) -$unexpectedDependencies = @( - $actualDependencies | Where-Object { - $dependency = $_ - -not ($allowedDependencies | Where-Object { $_ -ieq $dependency }) - } -) -if ($unexpectedDependencies.Count -ne 0) { - throw "Native Windows plugin has unreviewed dependencies: $($unexpectedDependencies -join ', ')" -} - -$securityModulePath = Join-Path $PSHOME 'Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1' -Import-Module -Name $securityModulePath -ErrorAction Stop -$signature = Get-AuthenticodeSignature -LiteralPath $binary -if ($signature.Status -ne [System.Management.Automation.SignatureStatus]::NotSigned) { - throw "Windows producer output must be unsigned, got $($signature.Status)." -} - -if (-not $SkipSmoke) { - & (Join-Path $sourceDir 'test.ps1') -OutputDirectory $buildDir -VcvarsPath $vcvars -SkipNativeBuild -} - -Write-Host "built and verified $binary" diff --git a/bazaarplusplus-mod/native/windows/test.ps1 b/bazaarplusplus-mod/native/windows/test.ps1 deleted file mode 100644 index 675adbb..0000000 --- a/bazaarplusplus-mod/native/windows/test.ps1 +++ /dev/null @@ -1,29 +0,0 @@ -param( - [string]$OutputDirectory = (Join-Path $PSScriptRoot 'build'), - [string]$VcvarsPath, - [switch]$SkipNativeBuild -) - -$ErrorActionPreference = 'Stop' - -if (-not $SkipNativeBuild) { - & (Join-Path $PSScriptRoot 'build.ps1') -OutputDirectory $OutputDirectory -SkipSmoke -} - -$vcvars = $VcvarsPath -if ([string]::IsNullOrWhiteSpace($vcvars)) { - $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" - $install = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath - $vcvars = Join-Path $install 'VC\Auxiliary\Build\vcvars64.bat' -} -$buildDir = $OutputDirectory -$command = 'call "{0}" && cl /nologo /std:c++17 /utf-8 /EHsc /W4 /WX /O2 /MT /DNOMINMAX /DUNICODE /D_UNICODE "{1}\BppReplayMediaFoundationSmoke.cpp" /link /OUT:"{2}\BppReplayMediaFoundationSmoke.exe" /LIBPATH:"{2}" BppReplayMediaFoundation.lib d3d11.lib' -f $vcvars, $PSScriptRoot, $buildDir -cmd.exe /d /s /c $command -if ($LASTEXITCODE -ne 0) { - throw "Native smoke test build failed with exit code $LASTEXITCODE." -} - -& (Join-Path $buildDir 'BppReplayMediaFoundationSmoke.exe') -if ($LASTEXITCODE -ne 0) { - throw "Native smoke test failed with exit code $LASTEXITCODE." -} diff --git a/bazaarplusplus-mod/scripts/build.sh b/bazaarplusplus-mod/scripts/build.sh deleted file mode 100644 index acaabdc..0000000 --- a/bazaarplusplus-mod/scripts/build.sh +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env bash -# Compile, deploy, seed refresh, and Payload production. Entry points: `just mod::*` -# and release/payload.mjs (`produce`). -# shellcheck source=scripts/lib.sh -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" - -MAIN_PROJECT=src/BazaarPlusPlus/BazaarPlusPlus.csproj - -# build [--deploy] [--fast] [-p:Name=Value ...]: compile; only --deploy touches the game install. -cmd_build() { - local deploy=false - local fast_args=() arg - local props=() - for arg in "$@"; do - case "$arg" in - # Inner-loop accelerator: skips NuGet restore. Run a normal build after - # editing any csproj or creating a fresh worktree. - --fast) fast_args=(--no-restore) ;; - --deploy) deploy=true ;; - -p:* | --property:*) props+=("$arg") ;; - *) die "Expected --deploy, --fast, or -p:Name=Value, got '$arg'" ;; - esac - done - while IFS= read -r arg; do props+=("$arg"); done < <(managed_props ${props[@]+"${props[@]}"}) - - local deploy_props=(-p:BppDeployToGame=false) - if [[ "$deploy" == "true" ]]; then - local root - root="$(game_root)" - [[ -n "$root" ]] || die "The Bazaar install was not found. Set BPP_GAME_ROOT=/path/to/The Bazaar." - # Deploy is gated on GamePath, which ManagedPath.props only sets for a - # discovered install, so pass it even when ManagedPath points elsewhere. - deploy_props=(-p:BppDeployToGame=true "-p:GamePath=$root") - if [[ "$(host_platform)" == "macos" ]]; then - repair_macos_trampoline "$root" ${props[@]+"${props[@]}"} - fi - fi - - dotnet build "$MAIN_PROJECT" \ - ${fast_args[@]+"${fast_args[@]}"} ${props[@]+"${props[@]}"} "${deploy_props[@]}" -} - -# A game update restores Steam's executable, so every deploy re-installs the trampoline first. -repair_macos_trampoline() { - local root="$1" - shift - local installer_source - installer_source="$(prop_value BPPInstallerSourcePath "$@")" - installer_source="${installer_source:-${BPP_INSTALLER_SOURCE_PATH:-$MOD_ROOT/../bazaarplusplus-installer/src-tauri/resources}}" - node "$MOD_ROOT/../bazaarplusplus-installer/scripts/headless.mjs" repair \ - --game "$root" \ - --stub "${BPP_TRAMPOLINE_STUB:-$installer_source/Trampoline/macos/bpp_launcher}" -} - -# matrix [channel ...]: compile against every captured lock entry, fetching each -# snapshot the way a normal build would; with channels, against exactly those entries -# of the host platform, so an empty one fails instead of being skipped (the CI lane -# names staging and ptr). The CompatCheck configuration fires neither the Debug -# deploy nor the Release installer copy. -cmd_matrix() { - local entries=() entry platform channel managed failed=() - if (($# > 0)); then - for channel in "$@"; do - case "$channel" in - online | staging | ptr) entries+=("$(host_platform) $channel") ;; - *) die "Expected a channel (online, staging or ptr), got '$channel'" ;; - esac - done - else - while IFS= read -r entry; do entries+=("$entry"); done < <(game_libs_cli entries) - ((${#entries[@]} > 0)) || die "The lock has no captured entries. Run 'just mod::snapshot' on a machine with the game, publish it, and commit build/game-libs.lock.json." - fi - for entry in "${entries[@]}"; do - platform="${entry% *}" channel="${entry#* }" - step "Matrix build against ${GREEN}${platform} ${channel}${CYAN}" - if ! managed="$(lock_managed_path "$platform" "$channel")"; then - failed+=("$platform $channel (snapshot unavailable)") - continue - fi - dotnet build "$MAIN_PROJECT" -c CompatCheck "-p:ManagedPath=$managed" || - failed+=("$platform $channel ($managed)") - done - if ((${#failed[@]} > 0)); then - err "Matrix build failed against:" - printf ' %s\n' "${failed[@]}" >&2 - exit 1 - fi - ok "Matrix build passed for every captured lock entry." -} - -# fetch-data [-p:Name=Value ...]: refresh the remote embedded seeds without building. -cmd_fetch_data() { - collect_props "$@" - fetch_remote_data ${PROPS[@]+"${PROPS[@]}"} -} - -# Fetches into a staging directory, gates it, then promotes it over the canonical set. -# The EXIT trap removes the staging directory when any step fails. -fetch_remote_data() { - local canonical_directory - canonical_directory="$(prop_value RemoteEmbeddedDataDirectory "$@")" - canonical_directory="${canonical_directory:-$MOD_ROOT/src/BazaarPlusPlus/obj/remote-data}" - local canonical_parent - canonical_parent="$(dirname "$canonical_directory")" - mkdir -p "$canonical_parent" - STAGING_DIRECTORY="$(mktemp -d "$canonical_parent/.remote-data-stage.XXXXXX")" - trap 'rm -rf -- "$STAGING_DIRECTORY"' EXIT - - dotnet msbuild "$MAIN_PROJECT" \ - -t:FetchRemoteEmbeddedData \ - "$@" \ - "-p:RemoteEmbeddedDataDirectory=$STAGING_DIRECTORY" \ - -p:ForceRemoteEmbeddedDataRefresh=true - run_seed_gates \ - "$@" \ - "-p:RemoteEmbeddedDataDirectory=$STAGING_DIRECTORY" \ - -p:RemoteEmbeddedDataPrepared=true - dotnet run \ - --project build/RemoteEmbeddedDataFetcher/RemoteEmbeddedDataFetcher.csproj \ - --no-launch-profile -- \ - promote "$STAGING_DIRECTORY" "$canonical_directory" \ - voice-lines.json builds.json - rm -rf -- "$STAGING_DIRECTORY" -} - -run_seed_gates() { - step "Validating ${GREEN}voice subtitle embedded seed${CYAN}" - dotnet test tests/RuntimeIntegration.Tests/RuntimeIntegration.Tests.csproj \ - -c Release \ - --filter "TestKind=EmbeddedSeed" \ - "$@" - step "Validating ${GREEN}live build recommendation embedded seed${CYAN}" - dotnet test tests/ScenarioRunner.Tests/ScenarioRunner.Tests.csproj \ - -c Release \ - --filter "TestKind=EmbeddedSeed" \ - -p:BppSeedGateOnly=true \ - "$@" -} - -# produce -p:ManagedPath=... -p:BPPInstallerSourcePath=... ...: internal to -# release/payload.mjs, which resolves and pins ManagedPath (game.sh managed-path). -cmd_produce() { - : "${BPP_RELEASE_ARTIFACTS:?Run node release.mjs prepare to build an isolated Payload}" - collect_props "$@" - local installer_source - installer_source="$(prop_value BPPInstallerSourcePath "$@")" - [[ -d "$installer_source" ]] || - die "Installer resources not found at '$installer_source'. Pass -p:BPPInstallerSourcePath=/absolute/path/to/resources." - [[ -n "$(prop_value ManagedPath "$@")" ]] || die "produce requires -p:ManagedPath." - - local common_args=("${PROPS[@]}" "-p:BppReleasePlatform=$(host_platform)") - fetch_remote_data "${common_args[@]}" - dotnet build "$MAIN_PROJECT" \ - -t:BuildAll \ - "${common_args[@]}" \ - -p:UseArtifactsOutput=true \ - "-p:ArtifactsPath=$BPP_RELEASE_ARTIFACTS" \ - -p:BuildProductionPackage=true \ - -p:RemoteEmbeddedDataPrepared=true -} - -dispatch "$@" diff --git a/bazaarplusplus-mod/scripts/game.sh b/bazaarplusplus-mod/scripts/game.sh deleted file mode 100644 index fbba057..0000000 --- a/bazaarplusplus-mod/scripts/game.sh +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env bash -# Which Game Assembly Snapshot is in use: decompile, snapshot, publish, fetch, lock -# check, release pin. Entry points: `just mod::decompile`, `mod::snapshot`, -# `mod::publish`, `mod::fetch`, `mod::lock-check`, and release/payload.mjs -# (`managed-path`). The lock itself is build/game-libs.lock.json (ADR 0004). -# shellcheck source=scripts/lib.sh -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" - -DECOMPILE_ALL=(Assembly-CSharp BazaarGameClient BazaarGameShared BazaarBattleService TheBazaarRuntime FMODUnity) - -# decompile [DllName ...]: online writes decompiled/, the others -# decompiled-v/. The channel's lock entry (or, while it is empty, the game -# version of the mounted install) decides which assemblies are read, so one channel's -# bits never land in another channel's reference tree. -cmd_decompile() { - local channel="${1:-}" - shift || true - local out_root - case "$channel" in - online) out_root=decompiled ;; - staging | ptr) out_root="decompiled-v$channel" ;; - *) die "Usage: just mod::decompile [DllName ...]" ;; - esac - local managed - managed="$(to_unix_path "$(lock_managed_path "$(host_platform)" "$channel" --allow-unlocked)")" - if ! command -v ilspycmd >/dev/null 2>&1; then - step "Installing ilspycmd" - dotnet tool install -g ilspycmd - fi - local dlls=("$@") dll - ((${#dlls[@]} > 0)) || dlls=(Assembly-CSharp) - [[ "${dlls[0]}" == "all" ]] && dlls=("${DECOMPILE_ALL[@]}") - for dll in "${dlls[@]}"; do - step "Decompiling ${GREEN}${dll}${CYAN} to ${out_root}/${dll}" - DOTNET_ROLL_FORWARD=Major ilspycmd -p -o "$out_root/$dll" "$managed/$dll.dll" - done -} - -# snapshot: archive the mounted install's Managed dir under game-libs/ keyed by -# platform, channel and game version, and record it in the lock. The game version -# comes from globalgamemanagers above Managed; buildid and branch from the appmanifest -# are the source record. Publish it with `just mod::publish`, then commit the lock. -cmd_snapshot() { - local managed acf branch buildid - managed="$(to_unix_path "${BPP_MANAGED_PATH:-$(steam_managed_path)}")" - [[ -f "${managed:-/nonexistent}/Assembly-CSharp.dll" ]] || - die "No mounted game install found. Install The Bazaar through Steam, or set BPP_MANAGED_PATH=/absolute/path/to/Managed." - acf="$(locate_appmanifest "$managed")" - [[ -n "$acf" ]] || die "Could not find appmanifest_1617400.acf above '$managed'; a snapshot is captured from a Steam install." - branch="$(installed_steam_branch "$managed")" - buildid="$(awk -F '"' '/"buildid"/ {print $4; exit}' "$acf")" - game_libs_cli snapshot --managed "$managed" --buildid "$buildid" --steam-branch "$branch" -} - -# publish : upload the captured snapshot of that -# lock entry to the private store. Needs the release credentials (`just mod::publish` -# loads them through the release profile). -cmd_publish() { - [[ $# -eq 2 ]] || die "Usage: just mod::publish " - game_libs_cli publish --platform "$1" --channel "$2" -} - -# fetch : make the lock entry's Managed dir -# available locally and print it. Pulling from the private store needs the release -# credentials: `just with-config release just mod::fetch `. -cmd_fetch() { - [[ $# -eq 2 ]] || die "Usage: just mod::fetch " - lock_managed_path "$1" "$2" -} - -# lock-check: a malformed lock fails; empty or stale entries warn; the Managed dir the -# build resolves must hash to the lock entry that names its game version. -cmd_lock_check() { - local managed - managed="$(to_unix_path "$(managed_path)")" - if [[ -n "$managed" ]]; then - game_libs_cli lock-check --managed "$managed" - else - game_libs_cli lock-check - fi -} - -# managed-path [-p:ManagedPath=...]: prints the Managed dir a production Payload -# compiles against, and nothing else on stdout. Production Payloads ship to online -# users, so this is the host platform's online lock entry unless overridden. -cmd_managed_path() { - collect_props "$@" - local pinned - pinned="$(prop_value ManagedPath "$@")" - [[ -n "$pinned" ]] || pinned="$(lock_managed_path "$(host_platform)" online)" - if command -v cygpath >/dev/null 2>&1; then - cygpath -am "$pinned" - else - (cd "$pinned" && pwd -P) - fi -} - -dispatch "$@" diff --git a/bazaarplusplus-mod/scripts/lib.sh b/bazaarplusplus-mod/scripts/lib.sh deleted file mode 100644 index bb3dad0..0000000 --- a/bazaarplusplus-mod/scripts/lib.sh +++ /dev/null @@ -1,169 +0,0 @@ -# shellcheck shell=bash -# Shared helpers for the mod command scripts. Sourced, never executed. -# Keep this Bash 3.2 compatible: macOS ships /bin/bash 3.2. - -set -euo pipefail - -MOD_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "$MOD_ROOT" - -# Some VPN/tunnel configurations advertise an unusable IPv6 route. Keep builds on -# the working IPv4 path by default while allowing callers to opt back into IPv6. -export DOTNET_SYSTEM_NET_DISABLEIPV6="${DOTNET_SYSTEM_NET_DISABLEIPV6:-1}" - -if [[ -t 2 && -z "${NO_COLOR:-}" ]]; then - CYAN=$'\033[0;36m' GREEN=$'\033[0;32m' RED=$'\033[0;31m' RESET=$'\033[0m' -else - CYAN='' GREEN='' RED='' RESET='' -fi - -# Progress goes to stderr so command substitutions (managed-path) keep stdout clean. -step() { printf '%s== %s ==%s\n' "$CYAN" "$*" "$RESET" >&2; } -ok() { printf '%s%s%s\n' "$GREEN" "$*" "$RESET" >&2; } -err() { printf '%s%s%s\n' "$RED" "$*" "$RESET" >&2; } -die() { - err "$*" - exit 1 -} - -host_platform() { - case "$(uname -s)" in - Darwin) echo macos ;; - MINGW* | MSYS* | CYGWIN*) echo windows ;; - *) die "Unsupported platform: $(uname -s)" ;; - esac -} - -# Collects MSBuild property arguments into PROPS; anything else is a usage error. -# Callers expand with ${PROPS[@]+"${PROPS[@]}"} because Bash 3.2 treats an empty -# array as unset under `set -u`. -collect_props() { - PROPS=() - local arg - for arg in "$@"; do - case "$arg" in - -p:* | --property:*) PROPS+=("$arg") ;; - *) die "Expected -p:Name=Value, got '$arg'" ;; - esac - done -} - -# Prints the last value given for property $1 in the remaining arguments. -prop_value() { - local name="$1" value="" arg - shift - for arg in "$@"; do - case "$arg" in - -p:"$name"=* | --property:"$name"=*) value="${arg#*=}" ;; - esac - done - printf '%s' "$value" -} - -to_unix_path() { - if [[ -n "$1" ]] && command -v cygpath >/dev/null 2>&1; then - cygpath -u "$1" - else - printf '%s' "$1" - fi -} - -# build/ManagedPath.props owns install discovery and lock resolution; ask it rather -# than restating paths. -discovered_prop() { - dotnet msbuild build/ManagedPath.props -nologo "-getProperty:$1" | tr -d '\r' -} - -# release/game-libs.mjs owns the Snapshot Lock, the Managed digest and the private store. -game_libs_cli() { - node "$MOD_ROOT/../release/game-libs.mjs" "$@" -} - -# The mounted Steam install's Managed dir, or empty; only snapshot and lock -# resolution read it. -steam_managed_path() { - discovered_prop BppSteamManagedPath -} - -# lock_managed_path [--allow-unlocked]: the Managed dir that -# satisfies the lock entry, printed on stdout: a verified game-libs/ snapshot, the -# mounted Steam install when its game version and sha256 match, or a fetch from the -# private store. The mounted install only counts for the host platform. -lock_managed_path() { - local platform="$1" channel="$2" - shift 2 - local steam=() - if [[ "$platform" == "$(host_platform)" ]]; then - steam=(--steam-managed "$(steam_managed_path)") - fi - game_libs_cli fetch --platform "$platform" --channel "$channel" \ - ${steam[@]+"${steam[@]}"} "$@" -} - -# Game assemblies: explicit -p:ManagedPath, then BPP_MANAGED_PATH, then the lock -# entry build/ManagedPath.props resolves (fetched snapshot or matching Steam install). -managed_path() { - local explicit - explicit="$(prop_value ManagedPath "$@")" - if [[ -n "$explicit" ]]; then - printf '%s' "$explicit" - elif [[ -n "${BPP_MANAGED_PATH:-}" ]]; then - printf '%s' "$BPP_MANAGED_PATH" - else - discovered_prop ManagedPath - fi -} - -# Forwards BPP_MANAGED_PATH to MSBuild when the caller did not pass ManagedPath. -managed_props() { - if [[ -n "${BPP_MANAGED_PATH:-}" && -z "$(prop_value ManagedPath "$@")" ]]; then - printf '%s\n' "-p:ManagedPath=$BPP_MANAGED_PATH" - fi -} - -game_root() { - if [[ -n "${BPP_GAME_ROOT:-}" ]]; then - printf '%s' "$BPP_GAME_ROOT" - else - discovered_prop GamePath - fi -} - -# Steam beta branches replace the single install in place, so a snapshot records -# the buildid and branch from the appmanifest as its source. The appmanifest is -# located by walking up from the Managed dir the DLLs are read from. -locate_appmanifest() { - local dir - dir="$(to_unix_path "$1")" - local _i - for _i in 1 2 3 4 5 6 7 8 9 10; do - dir="$(dirname "$dir")" - if [[ -f "$dir/appmanifest_1617400.acf" ]]; then - echo "$dir/appmanifest_1617400.acf" - return - fi - [[ "$dir" == "/" || "$dir" == "." ]] && break - done -} - -installed_steam_branch() { - local acf key - acf="$(locate_appmanifest "$1")" - [[ -n "$acf" ]] || { - echo unknown - return - } - key="$(awk '/"MountedConfig"/,/^\t\}/' "$acf" | awk -F '"' '/"BetaKey"/ {print $4}')" - echo "${key:-public}" -} - -# Dispatches `script args...` to the cmd_ function. -dispatch() { - local command="${1:-}" - local fn="cmd_${command//-/_}" - if [[ -z "$command" ]] || ! declare -F "$fn" >/dev/null; then - die "Usage: $0 [args...]; see 'just --list mod'." - fi - shift - "$fn" "$@" -} diff --git a/bazaarplusplus-mod/scripts/test.sh b/bazaarplusplus-mod/scripts/test.sh deleted file mode 100644 index 4785887..0000000 --- a/bazaarplusplus-mod/scripts/test.sh +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env bash -# Offline test suites. Entry points: `just mod::test`, `mod::test-corpus`. -# shellcheck source=scripts/lib.sh -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" - -# Tests never deploy or fetch; they embed the committed seed fixtures. -TEST_PROPS=( - -p:BppDeployToGame=false - -p:ForceRemoteEmbeddedDataRefresh=false - "-p:RemoteEmbeddedDataDirectory=$MOD_ROOT/tests/TestData/remote-data" -) - -# Collects -p arguments into PROPS plus BPP_MANAGED_PATH, and sets MANAGED to the -# game assembly directory the build will resolve. -resolve_test_inputs() { - collect_props "$@" - local arg - while IFS= read -r arg; do PROPS+=("$arg"); done < <(managed_props "$@") - MANAGED="$(to_unix_path "$(managed_path "$@")")" -} - -# test [-p:Name=Value ...]: the default xUnit suite. -cmd_test() { - resolve_test_inputs "$@" - [[ -f "$MANAGED/Assembly-CSharp.dll" ]] || - die "Game assemblies not found at '${MANAGED:-}'. Pass -p:ManagedPath=/absolute/path/to/Managed." - step "Test game assemblies: ${GREEN}${MANAGED}${CYAN}" - dotnet test tests/BazaarPlusPlus.Tests.slnx "${TEST_PROPS[@]}" ${PROPS[@]+"${PROPS[@]}"} -} - -# test-corpus [report-path] [--benchmark]: opt-in Combat Impact acceptance. -cmd_test_corpus() { - local usage="Usage: just mod::test-corpus [report-path] [--benchmark]" - local corpus_path="" report_path="" benchmark_arg=() arg - for arg in "$@"; do - case "$arg" in - --benchmark) benchmark_arg=(--benchmark) ;; - *) - if [[ -z "$corpus_path" ]]; then - corpus_path="$arg" - elif [[ -z "$report_path" ]]; then - report_path="$arg" - else - err "$usage" - exit 2 - fi - ;; - esac - done - if [[ -z "$corpus_path" ]]; then - err "$usage" - exit 2 - fi - if [[ ! -d "$corpus_path" ]]; then - err "Replay corpus directory not found: '$corpus_path'." - exit 2 - fi - report_path="${report_path:-$MOD_ROOT/artifacts/combat-impact-corpus/report.json}" - local props=() - while IFS= read -r arg; do props+=("$arg"); done < <(managed_props) - dotnet run --project tests/CombatImpact.Corpus/CombatImpact.Corpus.csproj \ - -p:BppDeployToGame=false ${props[@]+"${props[@]}"} \ - -- "$corpus_path" "$report_path" ${benchmark_arg[@]+"${benchmark_arg[@]}"} -} - -dispatch "$@" diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BazaarPlusPlus.Localization.csproj b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BazaarPlusPlus.Localization.csproj deleted file mode 100644 index a207a32..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BazaarPlusPlus.Localization.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - BazaarPlusPlus.Localization - BazaarPlusPlus.Localization - netstandard2.1 - 12 - enable - $(BppVersion) - true - - - - - - diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BppChineseLocaleMode.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BppChineseLocaleMode.cs deleted file mode 100644 index b7b0d87..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BppChineseLocaleMode.cs +++ /dev/null @@ -1,12 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Localization; - -internal enum BppChineseLocaleMode -{ - Mainland = 0, - Taiwan = 1, - - // Legacy persisted config value. Runtime code normalizes this to Taiwan. - [Obsolete("HongKong is kept only to migrate existing config values; use Taiwan.")] - HongKong = 2, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BppUiLanguage.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BppUiLanguage.cs deleted file mode 100644 index a207632..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/BppUiLanguage.cs +++ /dev/null @@ -1,16 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Localization; - -// Language for BazaarPlusPlus' own UI. Auto keeps the historical behaviour of following the -// game's language preference and only falls back to the OS language when the game stored none, -// which is what Android builds that never persist PreferencesData do. -internal enum BppUiLanguage -{ - Auto, - English, - Chinese, - German, - Portuguese, - Korean, - Italian, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/ChineseScriptConverter.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/ChineseScriptConverter.cs deleted file mode 100644 index 09d3f2c..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/ChineseScriptConverter.cs +++ /dev/null @@ -1,254 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Localization; - -internal static class ChineseScriptConverter -{ - // Words whose one-to-many characters the character table would convert wrongly, matched - // longest first before falling back to single characters: the OpenCC STPhrases entries that - // mod text and the voice-line catalog use, minus those wrong for that text (海里 where 里 - // means "inside", 上游 in 街上游荡), plus transliterated names that keep 里. - private static readonly Dictionary TraditionalPhraseMap = new( - StringComparer.Ordinal - ) - { - ["一只"] = "一隻", - ["一周"] = "一週", - ["一见钟情"] = "一見鍾情", - ["三只"] = "三隻", - ["上不了台面"] = "上不了檯面", - ["下周"] = "下週", - ["不了解"] = "不瞭解", - ["不划算"] = "不划算", - ["了解"] = "瞭解", - ["事迹"] = "事蹟", - ["佣金"] = "佣金", - ["借口"] = "藉口", - ["克制"] = "剋制", - ["关系"] = "關係", - ["养家糊口"] = "養家餬口", - ["准入"] = "准入", - ["准许"] = "准許", - ["划算"] = "划算", - ["制作"] = "製作", - ["制药"] = "製藥", - ["制造"] = "製造", - ["制造出"] = "製造出", - ["割舍"] = "割捨", - ["加里"] = "加里", - ["升华"] = "昇華", - ["卷入"] = "捲入", - ["卷土重来"] = "捲土重來", - ["反复"] = "反覆", - ["反复无常"] = "反覆無常", - ["发型"] = "髮型", - ["叮当"] = "叮噹", - ["叮当响"] = "叮噹響", - ["同流合污"] = "同流合汙", - ["向导"] = "嚮導", - ["吞并"] = "吞併", - ["命中注定"] = "命中註定", - ["喂养"] = "餵養", - ["喂给"] = "餵給", - ["回归"] = "迴歸", - ["坏家伙"] = "壞傢伙", - ["复制"] = "複製", - ["复合"] = "複合", - ["复杂"] = "複雜", - ["大只"] = "大隻", - ["头发"] = "頭髮", - ["夸克"] = "夸克", - ["奇迹"] = "奇蹟", - ["委托"] = "委託", - ["定制"] = "定製", - ["家伙"] = "傢伙", - ["小家伙"] = "小傢伙", - ["小杰"] = "小杰", - ["尝到"] = "嚐到", - ["尝尝"] = "嚐嚐", - ["尽可"] = "儘可", - ["尽管"] = "儘管", - ["尽量"] = "儘量", - ["巴里"] = "巴里", - ["布置"] = "佈置", - ["干净"] = "乾淨", - ["干干净净"] = "乾乾淨淨", - ["干扰"] = "干擾", - ["干涉"] = "干涉", - ["干站着"] = "乾站著", - ["干等"] = "乾等", - ["干草"] = "乾草", - ["幸免于难"] = "倖免於難", - ["幸存"] = "倖存", - ["弦断"] = "絃斷", - ["录制"] = "錄製", - ["征服"] = "征服", - ["恶心"] = "噁心", - ["惊叹"] = "驚歎", - ["想象"] = "想像", - ["扎实"] = "紮實", - ["托付"] = "託付", - ["拜托"] = "拜託", - ["拨弦"] = "撥絃", - ["挨饿"] = "捱餓", - ["操作台"] = "操作檯", - ["收获"] = "收穫", - ["放松"] = "放鬆", - ["放轻松"] = "放輕鬆", - ["日志"] = "日誌", - ["是只"] = "是隻", - ["是里格"] = "是里格", - ["杂志"] = "雜誌", - ["松了"] = "鬆了", - ["松开"] = "鬆開", - ["松懈"] = "鬆懈", - ["标签"] = "標籤", - ["榨干"] = "榨乾", - ["欲望"] = "慾望", - ["没关系"] = "沒關係", - ["治愈"] = "治癒", - ["注定"] = "註定", - ["洗干净"] = "洗乾淨", - ["淬炼"] = "淬鍊", - ["激荡"] = "激盪", - ["炼金"] = "鍊金", - ["炼金术"] = "鍊金術", - ["烟草"] = "菸草", - ["焚毁"] = "焚燬", - ["特里"] = "特里", - ["玛里"] = "瑪里", - ["痊愈"] = "痊癒", - ["精致"] = "精緻", - ["索里安"] = "索里安", - ["老板"] = "老闆", - ["老里格"] = "老里格", - ["联系"] = "聯繫", - ["背着"] = "揹著", - ["背负"] = "揹負", - ["舍不得"] = "捨不得", - ["舍弃"] = "捨棄", - ["英里"] = "英里", - ["蒙蔽"] = "矇蔽", - ["调制"] = "調製", - ["费纳里"] = "費納里", - ["轻松"] = "輕鬆", - ["这周"] = "這週", - ["遍布"] = "遍佈", - ["遗迹"] = "遺蹟", - ["那只"] = "那隻", - ["那只是"] = "那只是", - ["里亚"] = "里亞", - ["里欧"] = "里歐", - ["重复"] = "重複", - ["锻炼"] = "鍛鍊", - ["锻炼身体"] = "鍛鍊身體", - ["防御"] = "防禦", - ["雅致"] = "雅緻", - ["面包"] = "麵包", - ["面包师"] = "麵包師", - ["面包房"] = "麵包房", - ["预制"] = "預製", - ["风采"] = "風采", - ["饼干"] = "餅乾", - ["香蕉干"] = "香蕉乾", - }; - - private static readonly int MaxPhraseLength = TraditionalPhraseMap.Keys.Max(key => key.Length); - - private static readonly HashSet PhraseStarts = new( - TraditionalPhraseMap.Keys.Select(key => key[0]) - ); - - private static readonly Dictionary TraditionalCharacterMap = CreateCharacterMap(); - - internal static BppChineseLocaleMode NormalizeMode(BppChineseLocaleMode mode) - { - return mode == BppChineseLocaleMode.Mainland - ? BppChineseLocaleMode.Mainland - : BppChineseLocaleMode.Taiwan; - } - - internal static string Convert(string mainland, string? traditional, BppChineseLocaleMode mode) - { - if (string.IsNullOrEmpty(mainland)) - return mainland; - - var normalizedMode = NormalizeMode(mode); - if (normalizedMode == BppChineseLocaleMode.Mainland) - return mainland; - - if (!string.IsNullOrWhiteSpace(traditional)) - return traditional; - - var converted = ConvertToTraditional(mainland); - return normalizedMode switch - { - BppChineseLocaleMode.Taiwan => ApplyTraditionalChineseTerms(converted), - _ => mainland, - }; - } - - internal static string ResolveModeStatus(BppChineseLocaleMode mode) - { - return NormalizeMode(mode) switch - { - BppChineseLocaleMode.Mainland => "CN", - _ => "TW", - }; - } - - // Curated deviations from the OpenCC first candidate: 签 and 钟 take their common Taiwan - // forms, and 着, absent from STCharacters, becomes 著. - private static Dictionary CreateCharacterMap() - { - var map = OpenCcTraditionalCharacters.Create(); - map['签'] = "簽"; - map['钟'] = "鐘"; - map['着'] = "著"; - return map; - } - - private static string ConvertToTraditional(string text) - { - var buffer = new System.Text.StringBuilder(text.Length); - var index = 0; - while (index < text.Length) - { - if ( - PhraseStarts.Contains(text[index]) - && TryMatchPhrase(text, index, out var length, out var phrase) - ) - { - buffer.Append(phrase); - index += length; - continue; - } - - var character = text[index++]; - buffer.Append( - TraditionalCharacterMap.TryGetValue(character, out var mapped) ? mapped : character - ); - } - - return buffer.ToString(); - } - - private static bool TryMatchPhrase(string text, int index, out int length, out string phrase) - { - for (length = Math.Min(MaxPhraseLength, text.Length - index); length > 1; length--) - { - if (TraditionalPhraseMap.TryGetValue(text.Substring(index, length), out phrase!)) - return true; - } - - phrase = string.Empty; - return false; - } - - // Shared Traditional Chinese fallback terms for the single TW mode: Taiwan vocabulary, not - // script conversion, so they match the already converted text. - private static string ApplyTraditionalChineseTerms(string text) - { - return text.Replace("數據庫", "資料庫", StringComparison.Ordinal) - .Replace("查看", "檢視", StringComparison.Ordinal); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/L.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/L.cs deleted file mode 100644 index b8ff1a5..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/L.cs +++ /dev/null @@ -1,40 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Localization; - -internal static class L -{ - private static Func? _language; - private static Func? _mode; - - internal static void Install(Func language, Func mode) - { - _language = language ?? throw new ArgumentNullException(nameof(language)); - _mode = mode ?? throw new ArgumentNullException(nameof(mode)); - } - - internal static void Reset() - { - _language = null; - _mode = null; - } - - internal static string Resolve(LocalizedTextSet set) - { - return set.Resolve(Language(), Mode()); - } - - // Simplified text a feature shows as Chinese without a LocalizedTextSet (a Chinese-only - // subtitle row, a formatter's Chinese branch) still follows the Chinese locale mode. - internal static string ResolveChinese(string simplified) => - ChineseScriptConverter.Convert(simplified, null, Mode()); - - internal static string CurrentLanguageCode => Language(); - - internal static BppChineseLocaleMode CurrentMode => Mode(); - - private static Func Language => - _language ?? throw new InvalidOperationException("L.Install must be called at startup."); - - private static Func Mode => - _mode ?? throw new InvalidOperationException("L.Install must be called at startup."); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/LanguageCodeMatcher.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/LanguageCodeMatcher.cs deleted file mode 100644 index 09985de..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/LanguageCodeMatcher.cs +++ /dev/null @@ -1,49 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Localization; - -internal static class LanguageCodeMatcher -{ - internal static bool IsChinese(string languageCode) => - Matches( - languageCode, - "zh", - "zh-CN", - "zh-Hans", - "zh-SG", - "zh-TW", - "zh-Hant", - "zh-HK", - "zh-MO" - ); - - internal static bool IsGerman(string languageCode) => - Matches(languageCode, "de", "de-DE", "de-AT", "de-CH"); - - internal static bool IsPortuguese(string languageCode) => - Matches(languageCode, "pt", "pt-BR", "pt-PT"); - - internal static bool IsKorean(string languageCode) => Matches(languageCode, "ko", "ko-KR"); - - internal static bool IsItalian(string languageCode) => Matches(languageCode, "it", "it-IT"); - - private static bool Matches(string languageCode, params string[] candidates) - { - if (string.IsNullOrWhiteSpace(languageCode)) - return false; - - var normalized = languageCode.Replace('_', '-'); - foreach (var candidate in candidates) - { - if (string.IsNullOrWhiteSpace(candidate)) - continue; - - if (string.Equals(normalized, candidate, StringComparison.OrdinalIgnoreCase)) - return true; - - if (normalized.StartsWith(candidate + "-", StringComparison.OrdinalIgnoreCase)) - return true; - } - - return false; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/LocalizedTextSet.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/LocalizedTextSet.cs deleted file mode 100644 index 3ecc0a0..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/LocalizedTextSet.cs +++ /dev/null @@ -1,77 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Localization; - -internal readonly struct LocalizedTextSet -{ - internal LocalizedTextSet(string english, string chineseMainland) - : this(english, chineseMainland, null, english, english, english, english) { } - - internal LocalizedTextSet(string english, string chineseMainland, string? chineseTraditional) - : this(english, chineseMainland, chineseTraditional, english, english, english, english) { } - - internal LocalizedTextSet( - string english, - string chineseMainland, - string german, - string portuguese, - string korean, - string italian - ) - : this(english, chineseMainland, null, german, portuguese, korean, italian) { } - - internal LocalizedTextSet( - string english, - string chineseMainland, - string? chineseTraditional, - string german, - string portuguese, - string korean, - string italian - ) - { - English = english ?? throw new ArgumentNullException(nameof(english)); - ChineseMainland = - chineseMainland ?? throw new ArgumentNullException(nameof(chineseMainland)); - ChineseTraditional = chineseTraditional; - German = german ?? throw new ArgumentNullException(nameof(german)); - Portuguese = portuguese ?? throw new ArgumentNullException(nameof(portuguese)); - Korean = korean ?? throw new ArgumentNullException(nameof(korean)); - Italian = italian ?? throw new ArgumentNullException(nameof(italian)); - } - - internal string English { get; } - - internal string ChineseMainland { get; } - - internal string? ChineseTraditional { get; } - - internal string German { get; } - - internal string Portuguese { get; } - - internal string Korean { get; } - - internal string Italian { get; } - - internal string Resolve(string languageCode, BppChineseLocaleMode mode) - { - if (LanguageCodeMatcher.IsChinese(languageCode)) - { - return ChineseScriptConverter.Convert(ChineseMainland, ChineseTraditional, mode); - } - - if (LanguageCodeMatcher.IsGerman(languageCode)) - return German; - - if (LanguageCodeMatcher.IsPortuguese(languageCode)) - return Portuguese; - - if (LanguageCodeMatcher.IsKorean(languageCode)) - return Korean; - - if (LanguageCodeMatcher.IsItalian(languageCode)) - return Italian; - - return English; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/OpenCcTraditionalCharacters.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/OpenCcTraditionalCharacters.cs deleted file mode 100644 index 1df0c97..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/OpenCcTraditionalCharacters.cs +++ /dev/null @@ -1,158 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Localization; - -// Simplified-to-Traditional (Taiwan) character table: every BMP single-character key of OpenCC -// STCharacters.txt mapped to its first candidate, then through TWVariants.txt; identity -// mappings omitted. Derived from OpenCC (Apache-2.0), -// https://github.com/BYVoid/OpenCC/tree/2939943bd6f4d459b46d7fdcf07a885ab3f01761/data/dictionary -internal static class OpenCcTraditionalCharacters -{ - // Space-separated pairs: the Simplified character, then its Traditional form. - private const string Pairs = """ - 㐷傌 㐹㑶 㐽偑 㑇㑳 㑈倲 㑔㑯 㑩儸 㓆𠗣 㓥劏 㓰劃 㔉劚 㖊噚 㖞喎 㘎㘚 㚯㜄 㛀媰 㛟𡞵 㛠𡢃 㛣㜏 㛤孋 - 㛿𡠹 㟆㠏 㟜𡾱 㟥嵾 㡎幓 㤘㥮 㤽懤 㥪慺 㧏掆 㧐㩳 㧑撝 㧟擓 㧰擽 㨫㩜 㭎棡 㭏椲 㭣𣙎 㭤樢 㭴樫 㱩殰 - 㱮殨 㲿瀇 㳔濧 㳕灡 㳠澾 㳡濄 㳢𣾷 㳽瀰 㴋潚 㶉鸂 㶶燶 㶽煱 㺍獱 㻅璯 㻏𤫩 㻘𤪺 䀥䁻 䁖瞜 䂵碽 䃅磾 - 䅉稏 䅟穇 䅪𥢢 䇲筴 䉤籔 䌶䊷 䌷紬 䌸縳 䌹絅 䌺䋙 䌻䋚 䌼綐 䌽綵 䌾䋻 䌿䋹 䍀繿 䍁繸 䍠䍦 䎬䎱 䏝膞 - 䑽𦪙 䓓薵 䓕薳 䓖藭 䓨罃 䗖螮 䘛𧝞 䘞𧜗 䙊𧜵 䙌䙡 䙓襬 䜣訢 䜤鿁 䜥𧩙 䜧䜀 䜩讌 䝙貙 䞌𧵳 䞍䝼 䞎𧶧 - 䞐賰 䟢躎 䢀𨊰 䢁𨊸 䢂𨋢 䥺釾 䥽鏺 䥾䥱 䥿𨯅 䦀𨦫 䦁𨧜 䦂䥇 䦃鐯 䦅鐥 䦆钁 䦶䦛 䦷䦟 䩄靦 䭪𩞯 䯃𩣑 - 䯄騧 䯅䯀 䲝䱽 䲞𩶘 䲟鮣 䲠鰆 䲡鰌 䲢鰧 䲣䱷 䴓鳾 䴔鵁 䴕鴷 䴖鶄 䴗鶪 䴘鷉 䴙鸊 䶮龑 万萬 与與 丑醜 - 专專 业業 丛叢 东東 丝絲 丢丟 两兩 严嚴 丧喪 个個 丰豐 临臨 为為 丽麗 举舉 么麼 义義 乌烏 乐樂 乔喬 - 习習 乡鄉 书書 买買 乱亂 争爭 于於 亏虧 云雲 亘亙 亚亞 产產 亩畝 亲親 亵褻 亸嚲 亿億 仅僅 仆僕 从從 - 仑侖 仓倉 仪儀 们們 价價 众眾 优優 伙夥 会會 伛傴 伞傘 伟偉 传傳 伡俥 伣俔 伤傷 伥倀 伦倫 伧傖 伪偽 - 伫佇 体體 余餘 佣傭 佥僉 侠俠 侣侶 侥僥 侦偵 侧側 侨僑 侩儈 侪儕 侬儂 侭儘 俣俁 俦儔 俨儼 俩倆 俪儷 - 俫倈 俭儉 债債 倾傾 偬傯 偻僂 偾僨 偿償 傤儎 傥儻 傧儐 储儲 傩儺 儿兒 兑兌 兖兗 党黨 兰蘭 关關 兴興 - 兹茲 养養 兽獸 冁囅 内內 冈岡 册冊 写寫 军軍 农農 冯馮 冲衝 决決 况況 冻凍 净淨 凄悽 准準 凉涼 减減 - 凑湊 凛凜 几幾 凤鳳 凫鳧 凭憑 凯凱 凶兇 击擊 凿鑿 刍芻 划劃 刘劉 则則 刚剛 创創 删刪 别別 刬剗 刭剄 - 刹剎 刽劊 刾㓨 刿劌 剀剴 剂劑 剐剮 剑劍 剥剝 剧劇 劝勸 办辦 务務 劢勱 动動 励勵 劲勁 劳勞 势勢 勋勳 - 勚勩 匀勻 匦匭 匮匱 区區 医醫 华華 协協 单單 卖賣 占佔 卢盧 卤滷 卧臥 卫衛 却卻 卺巹 厂廠 厅廳 历歷 - 厉厲 压壓 厌厭 厍厙 厐龎 厕廁 厘釐 厢廂 厣厴 厦廈 厨廚 厩廄 厮廝 县縣 叁叄 参參 叆靉 叇靆 双雙 发發 - 变變 叙敘 叠疊 台臺 叶葉 号號 叹嘆 叽嘰 吁籲 后後 吓嚇 吕呂 吗嗎 吨噸 听聽 启啟 吴吳 呐吶 呒嘸 呓囈 - 呕嘔 呖嚦 呗唄 员員 呙咼 呛嗆 呜嗚 咏詠 咙嚨 咛嚀 咝噝 咤吒 咨諮 咸鹹 响響 哑啞 哒噠 哓嘵 哔嗶 哕噦 - 哗譁 哙噲 哜嚌 哝噥 哟喲 唛嘜 唝嗊 唠嘮 唡啢 唢嗩 唤喚 啧嘖 啬嗇 啭囀 啮齧 啯嘓 啰囉 啴嘽 啸嘯 喷噴 - 喽嘍 喾嚳 嗫囁 嗳噯 嘘噓 嘤嚶 嘱囑 噜嚕 嚣囂 团團 园園 囱囪 围圍 囵圇 国國 图圖 圆圓 圣聖 圹壙 场場 - 坏壞 块塊 坚堅 坛壇 坜壢 坝壩 坞塢 坟墳 坠墜 垄壟 垅壠 垆壚 垒壘 垦墾 垩堊 垫墊 垭埡 垯墶 垱壋 垲塏 - 垴堖 埘塒 埙壎 埚堝 堑塹 堕墮 塆壪 墙牆 壮壯 声聲 壳殼 壶壺 壸壼 处處 备備 复復 够夠 头頭 夸誇 夹夾 - 夺奪 奁奩 奂奐 奋奮 奖獎 奥奧 妆妝 妇婦 妈媽 妩嫵 妪嫗 妫媯 姗姍 姹奼 娄婁 娅婭 娆嬈 娇嬌 娈孌 娱娛 - 娲媧 娴嫻 婳嫿 婴嬰 婵嬋 婶嬸 媪媼 媭嬃 嫒嬡 嫔嬪 嫱嬙 嬷嬤 孙孫 学學 孪孿 宁寧 宝寶 实實 宠寵 审審 - 宪憲 宫宮 宽寬 宾賓 寝寢 对對 寻尋 导導 寿壽 将將 尔爾 尘塵 尝嘗 尧堯 尴尷 尸屍 尽盡 层層 屃屓 屉屜 - 届屆 属屬 屡屢 屦屨 屿嶼 岁歲 岂豈 岖嶇 岗崗 岘峴 岚嵐 岛島 岩巖 岭嶺 岳嶽 岽崬 岿巋 峃嶨 峄嶧 峡峽 - 峣嶢 峤嶠 峥崢 峦巒 崂嶗 崃崍 崄嶮 崭嶄 嵘嶸 嵚嶔 嵝嶁 巅巔 巩鞏 巯巰 币幣 帅帥 师師 帏幃 帐帳 帘簾 - 帜幟 带帶 帧幀 帮幫 帱幬 帻幘 帼幗 幂冪 干幹 并並 广廣 庄莊 庆慶 庐廬 庑廡 库庫 应應 庙廟 庞龐 废廢 - 庼廎 廪廩 开開 异異 弃棄 弑弒 张張 弥彌 弪弳 弯彎 弹彈 强強 归歸 当當 录錄 彟彠 彦彥 彨彲 彻徹 征徵 - 径徑 徕徠 忆憶 忏懺 忧憂 忾愾 怀懷 态態 怂慫 怃憮 怄慪 怅悵 怆愴 怜憐 总總 怼懟 怿懌 恋戀 恒恆 恳懇 - 恶惡 恸慟 恹懨 恺愷 恻惻 恼惱 恽惲 悦悅 悫愨 悬懸 悭慳 悮悞 悯憫 惊驚 惧懼 惨慘 惩懲 惫憊 惬愜 惭慚 - 惮憚 惯慣 愠慍 愤憤 愦憒 愿願 慑懾 慭憖 懑懣 懒懶 懔懍 戆戇 戋戔 戏戲 戗戧 战戰 戬戩 戯戱 户戶 扑撲 - 执執 扩擴 扪捫 扫掃 扬揚 扰擾 抚撫 抛拋 抟摶 抠摳 抡掄 抢搶 护護 报報 担擔 拟擬 拢攏 拣揀 拥擁 拦攔 - 拧擰 拨撥 择擇 挂掛 挚摯 挛攣 挜掗 挝撾 挞撻 挟挾 挠撓 挡擋 挢撟 挣掙 挤擠 挥揮 挦撏 捝挩 捞撈 损損 - 捡撿 换換 捣搗 据據 掳擄 掴摑 掷擲 掸撣 掺摻 掼摜 揽攬 揾搵 揿撳 搀攙 搁擱 搂摟 搄揯 搅攪 携攜 摄攝 - 摅攄 摆擺 摇搖 摈擯 摊攤 撄攖 撑撐 撵攆 撷擷 撸擼 撺攛 擜㩵 擞擻 攒攢 敌敵 敚敓 敛斂 敩斆 数數 斋齋 - 斓斕 斗鬥 斩斬 断斷 无無 旧舊 时時 旷曠 旸暘 昙曇 昵暱 昼晝 昽曨 显顯 晋晉 晒曬 晓曉 晔曄 晕暈 晖暉 - 暂暫 暅𣈶 暧曖 术術 朴樸 机機 杀殺 杂雜 权權 杠槓 条條 来來 杨楊 杩榪 杰傑 极極 构構 枞樅 枢樞 枣棗 - 枥櫪 枧梘 枨棖 枪槍 枫楓 枭梟 柜櫃 柠檸 柽檉 栀梔 栅柵 标標 栈棧 栉櫛 栊櫳 栋棟 栌櫨 栎櫟 栏欄 树樹 - 栖棲 样樣 栾欒 桠椏 桡橈 桢楨 档檔 桤榿 桥橋 桦樺 桧檜 桨槳 桩樁 桪樳 梦夢 梼檮 梾棶 梿槤 检檢 棁梲 - 棂欞 棱稜 椁槨 椝槼 椟櫝 椠槧 椢槶 椤欏 椫樿 椭橢 椮槮 楼樓 榄欖 榅榲 榇櫬 榈櫚 榉櫸 榝樧 槚檟 槛檻 - 槟檳 槠櫧 横橫 樯檣 樱櫻 橥櫫 橱櫥 橹櫓 橼櫞 檩檁 欢歡 欤歟 欧歐 歼殲 殁歿 殇殤 残殘 殒殞 殓殮 殚殫 - 殡殯 殴毆 毁毀 毂轂 毕畢 毙斃 毡氈 毵毿 毶𣯶 氇氌 气氣 氢氫 氩氬 氲氳 汇匯 汉漢 汤湯 汹洶 沄澐 沟溝 - 没沒 沣灃 沤漚 沥瀝 沦淪 沧滄 沨渢 沩溈 沪滬 泞濘 泪淚 泶澩 泷瀧 泸瀘 泺濼 泻瀉 泼潑 泽澤 泾涇 洁潔 - 洒灑 洼窪 浃浹 浅淺 浆漿 浇澆 浈湞 浉溮 浊濁 测測 浍澮 济濟 浏瀏 浐滻 浑渾 浒滸 浓濃 浔潯 浕濜 涂塗 - 涌湧 涚涗 涛濤 涝澇 涞淶 涟漣 涠潿 涡渦 涢溳 涣渙 涤滌 润潤 涧澗 涨漲 涩澀 淀澱 渊淵 渌淥 渍漬 渎瀆 - 渐漸 渑澠 渔漁 渖瀋 渗滲 温溫 游遊 湾灣 湿溼 溁濚 溃潰 溅濺 溆漵 溇漊 滗潷 滚滾 滞滯 滟灩 滠灄 满滿 - 滢瀅 滤濾 滥濫 滦灤 滨濱 滩灘 滪澦 潆瀠 潇瀟 潋瀲 潍濰 潜潛 潴瀦 澛瀂 澜瀾 濑瀨 濒瀕 灏灝 灭滅 灯燈 - 灵靈 灾災 灿燦 炀煬 炉爐 炖燉 炜煒 炝熗 点點 炼煉 炽熾 烁爍 烂爛 烃烴 烛燭 烟煙 烦煩 烧燒 烨燁 烩燴 - 烫燙 烬燼 热熱 焕煥 焖燜 焘燾 煴熅 熏燻 爱愛 爷爺 牍牘 牦犛 牵牽 牺犧 犊犢 状狀 犷獷 犸獁 犹猶 狈狽 - 狝獮 狞獰 独獨 狭狹 狮獅 狯獪 狰猙 狱獄 狲猻 猃獫 猎獵 猕獼 猡玀 猪豬 猫貓 猬蝟 献獻 獭獺 玑璣 玙璵 - 玚瑒 玛瑪 玮瑋 环環 现現 玱瑲 玺璽 珐琺 珑瓏 珰璫 珲琿 琎璡 琏璉 琐瑣 琼瓊 瑶瑤 瑷璦 瑸璸 璎瓔 瓒瓚 - 瓮甕 瓯甌 电電 画畫 畅暢 畴疇 疖癤 疗療 疟瘧 疠癘 疡瘍 疬癧 疭瘲 疮瘡 疯瘋 疱皰 疴痾 痈癰 痉痙 痒癢 - 痖瘂 痨癆 痪瘓 痫癇 瘅癉 瘆瘮 瘗瘞 瘘瘻 瘪癟 瘫癱 瘾癮 瘿癭 癞癩 癣癬 癫癲 皑皚 皱皺 皲皸 盏盞 盐鹽 - 监監 盖蓋 盗盜 盘盤 眍瞘 眦眥 眬矓 睁睜 睐睞 睑瞼 瞆瞶 瞒瞞 瞩矚 矫矯 矶磯 矾礬 矿礦 砀碭 码碼 砖磚 - 砗硨 砚硯 砜碸 砺礪 砻礱 砾礫 础礎 硁硜 硕碩 硖硤 硗磽 硙磑 硚礄 确確 硵磠 碍礙 碛磧 碜磣 碱鹼 礼禮 - 祃禡 祎禕 祢禰 祯禎 祷禱 祸禍 禀稟 禄祿 禅禪 离離 秃禿 秆稈 种種 秘祕 积積 称稱 秽穢 秾穠 稆穭 税稅 - 稣穌 稳穩 穑穡 穞穭 穷窮 窃竊 窍竅 窎窵 窑窯 窜竄 窝窩 窥窺 窦竇 窭窶 竖豎 竞競 笃篤 笋筍 笔筆 笕筧 - 笺箋 笼籠 笾籩 筑築 筚篳 筛篩 筜簹 筝箏 筹籌 筼篔 签籤 筿篠 简簡 箓籙 箦簀 箧篋 箨籜 箩籮 箪簞 箫簫 - 篑簣 篓簍 篮籃 篯籛 篱籬 簖籪 籁籟 籴糴 类類 籼秈 粜糶 粝糲 粤粵 粪糞 粮糧 糁糝 糇餱 糍餈 紧緊 絷縶 - 緼縕 縆緪 纟糹 纠糾 纡紆 红紅 纣紂 纤纖 纥紇 约約 级級 纨紈 纩纊 纪紀 纫紉 纬緯 纭紜 纮紘 纯純 纰紕 - 纱紗 纲綱 纳納 纴紝 纵縱 纶綸 纷紛 纸紙 纹紋 纺紡 纻紵 纼紖 纽紐 纾紓 线線 绀紺 绁紲 绂紱 练練 组組 - 绅紳 细細 织織 终終 绉縐 绊絆 绋紼 绌絀 绍紹 绎繹 经經 绐紿 绑綁 绒絨 结結 绔絝 绕繞 绖絰 绗絎 绘繪 - 给給 绚絢 绛絳 络絡 绝絕 绞絞 统統 绠綆 绡綃 绢絹 绣繡 绤綌 绥綏 绦絛 继繼 绨綈 绩績 绪緒 绫綾 绬緓 - 续續 绮綺 绯緋 绰綽 绱鞝 绲緄 绳繩 维維 绵綿 绶綬 绷繃 绸綢 绹綯 绺綹 绻綣 综綜 绽綻 绾綰 绿綠 缀綴 - 缁緇 缂緙 缃緗 缄緘 缅緬 缆纜 缇緹 缈緲 缉緝 缊縕 缋繢 缌緦 缍綞 缎緞 缏緶 缐線 缑緱 缒縋 缓緩 缔締 - 缕縷 编編 缗緡 缘緣 缙縉 缚縛 缛縟 缜縝 缝縫 缞縗 缟縞 缠纏 缡縭 缢縊 缣縑 缤繽 缥縹 缦縵 缧縲 缨纓 - 缩縮 缪繆 缫繅 缬纈 缭繚 缮繕 缯繒 缰韁 缱繾 缲繰 缳繯 缴繳 缵纘 罂罌 网網 罗羅 罚罰 罢罷 罴羆 羁羈 - 羟羥 羡羨 翘翹 翙翽 翚翬 耢耮 耧耬 耸聳 耻恥 聂聶 聋聾 职職 聍聹 联聯 聩聵 聪聰 肃肅 肠腸 肤膚 肮骯 - 肴餚 肾腎 肿腫 胀脹 胁脅 胆膽 胜勝 胧朧 胨腖 胪臚 胫脛 胶膠 脉脈 脍膾 脏髒 脐臍 脑腦 脓膿 脔臠 脚腳 - 脱脫 脶腡 脸臉 腊臘 腌醃 腘膕 腭顎 腻膩 腼靦 腽膃 腾騰 膑臏 膻羶 臜臢 舆輿 舣艤 舰艦 舱艙 舻艫 艰艱 - 艳豔 艺藝 节節 芈羋 芗薌 芜蕪 芦蘆 苁蓯 苇葦 苈藶 苋莧 苌萇 苍蒼 苎苧 苏蘇 苧薴 苹蘋 范範 茎莖 茏蘢 - 茑蔦 茔塋 茕煢 茧繭 荆荊 荐薦 荙薘 荚莢 荛蕘 荜蓽 荝萴 荞蕎 荟薈 荠薺 荡蕩 荣榮 荤葷 荥滎 荦犖 荧熒 - 荨蕁 荩藎 荪蓀 荫蔭 荬蕒 荭葒 荮葤 药藥 莅蒞 莱萊 莲蓮 莳蒔 莴萵 莶薟 获獲 莸蕕 莹瑩 莺鶯 莼蓴 萚蘀 - 萝蘿 萤螢 营營 萦縈 萧蕭 萨薩 葱蔥 蒀蒕 蒇蕆 蒉蕢 蒋蔣 蒌蔞 蒏醟 蓝藍 蓟薊 蓠蘺 蓣蕷 蓥鎣 蓦驀 蔂虆 - 蔷薔 蔹蘞 蔺藺 蔼藹 蕰薀 蕲蘄 蕴蘊 薮藪 藓蘚 藴蘊 蘖櫱 虏虜 虑慮 虚虛 虫蟲 虬虯 虮蟣 虱蝨 虽雖 虾蝦 - 虿蠆 蚀蝕 蚁蟻 蚂螞 蚃蠁 蚕蠶 蚝蠔 蚬蜆 蛊蠱 蛎蠣 蛏蟶 蛮蠻 蛰蟄 蛱蛺 蛲蟯 蛳螄 蛴蠐 蜕蛻 蜗蝸 蜡蠟 - 蝇蠅 蝈蟈 蝉蟬 蝎蠍 蝼螻 蝾蠑 螀螿 螨蟎 蟏蠨 衅釁 衔銜 补補 衬襯 衮袞 袄襖 袅嫋 袆褘 袜襪 袭襲 袯襏 - 装裝 裆襠 裈褌 裢褳 裣襝 裤褲 裥襉 褛褸 褴襤 襕襴 见見 观觀 觃覎 规規 觅覓 视視 觇覘 览覽 觉覺 觊覬 - 觋覡 觌覿 觍覥 觎覦 觏覯 觐覲 觑覷 觞觴 触觸 觯觶 訚誾 詟讋 誉譽 誊謄 讠訁 计計 订訂 讣訃 认認 讥譏 - 讦訐 讧訌 讨討 让讓 讪訕 讫訖 讬託 训訓 议議 讯訊 记記 讱訒 讲講 讳諱 讴謳 讵詎 讶訝 讷訥 许許 讹訛 - 论論 讻訩 讼訟 讽諷 设設 访訪 诀訣 证證 诂詁 诃訶 评評 诅詛 识識 诇詗 诈詐 诉訴 诊診 诋詆 诌謅 词詞 - 诎詘 诏詔 诐詖 译譯 诒詒 诓誆 诔誄 试試 诖詿 诗詩 诘詰 诙詼 诚誠 诛誅 诜詵 话話 诞誕 诟詬 诠詮 诡詭 - 询詢 诣詣 诤諍 该該 详詳 诧詫 诨諢 诩詡 诪譸 诫誡 诬誣 语語 诮誚 误誤 诰誥 诱誘 诲誨 诳誑 说說 诵誦 - 诶誒 请請 诸諸 诹諏 诺諾 读讀 诼諑 诽誹 课課 诿諉 谀諛 谁誰 谂諗 调調 谄諂 谅諒 谆諄 谇誶 谈談 谉讅 - 谊誼 谋謀 谌諶 谍諜 谎謊 谏諫 谐諧 谑謔 谒謁 谓謂 谔諤 谕諭 谖諼 谗讒 谘諮 谙諳 谚諺 谛諦 谜謎 谝諞 - 谞諝 谟謨 谠讜 谡謖 谢謝 谣謠 谤謗 谥諡 谦謙 谧謐 谨謹 谩謾 谪謫 谫譾 谬謬 谭譚 谮譖 谯譙 谰讕 谱譜 - 谲譎 谳讞 谴譴 谵譫 谶讖 豮豶 贝貝 贞貞 负負 贠貟 贡貢 财財 责責 贤賢 败敗 账賬 货貨 质質 贩販 贪貪 - 贫貧 贬貶 购購 贮貯 贯貫 贰貳 贱賤 贲賁 贳貰 贴貼 贵貴 贶貺 贷貸 贸貿 费費 贺賀 贻貽 贼賊 贽贄 贾賈 - 贿賄 赀貲 赁賃 赂賂 赃贓 资資 赅賅 赆贐 赇賕 赈賑 赉賚 赊賒 赋賦 赌賭 赍齎 赎贖 赏賞 赐賜 赑贔 赒賙 - 赓賡 赔賠 赕賧 赖賴 赗賵 赘贅 赙賻 赚賺 赛賽 赜賾 赝贗 赞贊 赟贇 赠贈 赡贍 赢贏 赣贛 赪赬 赵趙 赶趕 - 趋趨 趱趲 趸躉 跃躍 跄蹌 跖蹠 跞躒 践踐 跶躂 跷蹺 跸蹕 跹躚 跻躋 踌躊 踪蹤 踬躓 踯躑 蹑躡 蹒蹣 蹰躕 - 蹿躥 躏躪 躜躦 躯軀 輼轀 车車 轧軋 轨軌 轩軒 轪軑 轫軔 转轉 轭軛 轮輪 软軟 轰轟 轱軲 轲軻 轳轤 轴軸 - 轵軹 轶軼 轷軤 轸軫 轹轢 轺軺 轻輕 轼軾 载載 轾輊 轿轎 辀輈 辁輇 辂輅 较較 辄輒 辅輔 辆輛 辇輦 辈輩 - 辉輝 辊輥 辋輞 辌輬 辍輟 辎輜 辏輳 辐輻 辑輯 辒轀 输輸 辔轡 辕轅 辖轄 辗輾 辘轆 辙轍 辚轔 辞辭 辟闢 - 辩辯 辫辮 边邊 辽遼 达達 迁遷 过過 迈邁 运運 还還 这這 进進 远遠 违違 连連 迟遲 迩邇 迳逕 迹跡 适適 - 选選 逊遜 递遞 逦邐 逻邏 遗遺 遥遙 邓鄧 邝鄺 邬鄔 邮郵 邹鄒 邺鄴 邻鄰 郁鬱 郏郟 郐鄶 郑鄭 郓鄆 郦酈 - 郧鄖 郸鄲 酂酇 酝醞 酦醱 酱醬 酽釅 酾釃 酿釀 醖醞 采採 释釋 里裡 鉴鑑 銮鑾 錾鏨 钅釒 钆釓 钇釔 针針 - 钉釘 钊釗 钋釙 钌釕 钍釷 钎釺 钏釧 钐釤 钑鈒 钒釩 钓釣 钔鍆 钕釹 钖鍚 钗釵 钘鈃 钙鈣 钚鈈 钛鈦 钜鉅 - 钝鈍 钞鈔 钟鍾 钠鈉 钡鋇 钢鋼 钣鈑 钤鈐 钥鑰 钦欽 钧鈞 钨鎢 钩鉤 钪鈧 钫鈁 钬鈥 钭鈄 钮鈕 钯鈀 钰鈺 - 钱錢 钲鉦 钳鉗 钴鈷 钵缽 钶鈳 钷鉕 钸鈽 钹鈸 钺鉞 钻鑽 钼鉬 钽鉭 钾鉀 钿鈿 铀鈾 铁鐵 铂鉑 铃鈴 铄鑠 - 铅鉛 铆鉚 铇鉋 铈鈰 铉鉉 铊鉈 铋鉍 铌鈮 铍鈹 铎鐸 铏鉶 铐銬 铑銠 铒鉺 铓鋩 铔錏 铕銪 铖鋮 铗鋏 铘鋣 - 铙鐃 铚銍 铛鐺 铜銅 铝鋁 铞銱 铟銦 铠鎧 铡鍘 铢銖 铣銑 铤鋌 铥銩 铦銛 铧鏵 铨銓 铩鎩 铪鉿 铫銚 铬鉻 - 铭銘 铮錚 铯銫 铰鉸 铱銥 铲鏟 铳銃 铴鐋 铵銨 银銀 铷銣 铸鑄 铹鐒 铺鋪 铻鋙 铼錸 铽鋱 链鏈 铿鏗 销銷 - 锁鎖 锂鋰 锃鋥 锄鋤 锅鍋 锆鋯 锇鋨 锈鏽 锉銼 锊鋝 锋鋒 锌鋅 锍鋶 锎鐦 锏鐧 锐銳 锑銻 锒鋃 锓鋟 锔鋦 - 锕錒 锖錆 锗鍺 锘鍩 错錯 锚錨 锛錛 锜錡 锝鍀 锞錁 锟錕 锠錩 锡錫 锢錮 锣鑼 锤錘 锥錐 锦錦 锧鑕 锨鍁 - 锩錈 锪鍃 锫錇 锬錟 锭錠 键鍵 锯鋸 锰錳 锱錙 锲鍥 锳鍈 锴鍇 锵鏘 锶鍶 锷鍔 锸鍤 锹鍬 锺鍾 锻鍛 锼鎪 - 锽鍠 锾鍰 锿鎄 镀鍍 镁鎂 镂鏤 镃鎡 镄鐨 镅鎇 镆鏌 镇鎮 镈鎛 镉鎘 镊鑷 镋钂 镌鐫 镍鎳 镎鎿 镏鎦 镐鎬 - 镑鎊 镒鎰 镓鎵 镔鑌 镕鎔 镖鏢 镗鏜 镘鏝 镙鏍 镚鏰 镛鏞 镜鏡 镝鏑 镞鏃 镟鏇 镠鏐 镡鐔 镢钁 镣鐐 镤鏷 - 镥鑥 镦鐓 镧鑭 镨鐠 镩鑹 镪鏹 镫鐙 镬鑊 镭鐳 镮鐶 镯鐲 镰鐮 镱鐿 镲鑔 镳鑣 镴鑞 镵鑱 镶鑲 长長 门門 - 闩閂 闪閃 闫閆 闬閈 闭閉 问問 闯闖 闰閏 闱闈 闲閒 闳閎 间間 闵閔 闶閌 闷悶 闸閘 闹鬧 闺閨 闻聞 闼闥 - 闽閩 闾閭 闿闓 阀閥 阁閣 阂閡 阃閫 阄鬮 阅閱 阆閬 阇闍 阈閾 阉閹 阊閶 阋鬩 阌閿 阍閽 阎閻 阏閼 阐闡 - 阑闌 阒闃 阓闠 阔闊 阕闋 阖闔 阗闐 阘闒 阙闕 阚闞 阛闤 队隊 阳陽 阴陰 阵陣 阶階 际際 陆陸 陇隴 陈陳 - 陉陘 陕陝 陦隯 陧隉 陨隕 险險 随隨 隐隱 隶隸 隽雋 难難 雇僱 雏雛 雠讎 雳靂 雾霧 霁霽 霉黴 霡霢 霭靄 - 靓靚 靔靝 静靜 靥靨 鞑韃 鞒鞽 鞯韉 鞲韝 韦韋 韧韌 韨韍 韩韓 韪韙 韫韞 韬韜 韵韻 页頁 顶頂 顷頃 顸頇 - 项項 顺順 须須 顼頊 顽頑 顾顧 顿頓 颀頎 颁頒 颂頌 颃頏 预預 颅顱 领領 颇頗 颈頸 颉頡 颊頰 颋頲 颌頜 - 颍潁 颎熲 颏頦 颐頤 频頻 颒頮 颓頹 颔頷 颕頴 颖穎 颗顆 题題 颙顒 颚顎 颛顓 颜顏 额額 颞顳 颟顢 颠顛 - 颡顙 颢顥 颣纇 颤顫 颥顬 颦顰 颧顴 风風 飏颺 飐颭 飑颮 飒颯 飓颶 飔颸 飕颼 飖颻 飗飀 飘飄 飙飆 飚飈 - 飞飛 飨饗 餍饜 饣飠 饤飣 饥飢 饦飥 饧餳 饨飩 饩餼 饪飪 饫飫 饬飭 饭飯 饮飲 饯餞 饰飾 饱飽 饲飼 饳飿 - 饴飴 饵餌 饶饒 饷餉 饸餄 饹餎 饺餃 饻餏 饼餅 饽餑 饾餖 饿餓 馀餘 馁餒 馂餕 馃餜 馄餛 馅餡 馆館 馇餷 - 馈饋 馉餶 馊餿 馋饞 馌饁 馍饃 馎餺 馏餾 馐饈 馑饉 馒饅 馓饊 馔饌 馕饢 马馬 驭馭 驮馱 驯馴 驰馳 驱驅 - 驲馹 驳駁 驴驢 驵駔 驶駛 驷駟 驸駙 驹駒 驺騶 驻駐 驼駝 驽駑 驾駕 驿驛 骀駘 骁驍 骂罵 骃駰 骄驕 骅驊 - 骆駱 骇駭 骈駢 骉驫 骊驪 骋騁 验驗 骍騂 骎駸 骏駿 骐騏 骑騎 骒騍 骓騅 骔騌 骕驌 骖驂 骗騙 骘騭 骙騤 - 骚騷 骛騖 骜驁 骝騮 骞騫 骟騸 骠驃 骡騾 骢驄 骣驏 骤驟 骥驥 骦驦 骧驤 髅髏 髋髖 髌髕 鬓鬢 鬶鬹 魇魘 - 魉魎 鱼魚 鱽魛 鱾魢 鱿魷 鲀魨 鲁魯 鲂魴 鲃䰾 鲄魺 鲅鮁 鲆鮃 鲇鯰 鲈鱸 鲉鮋 鲊鮓 鲋鮒 鲌鮊 鲍鮑 鲎鱟 - 鲏鮍 鲐鮐 鲑鮭 鲒鮚 鲓鮳 鲔鮪 鲕鮞 鲖鮦 鲗鰂 鲘鮜 鲙鱠 鲚鱭 鲛鮫 鲜鮮 鲝鮺 鲞鯗 鲟鱘 鲠鯁 鲡鱺 鲢鰱 - 鲣鰹 鲤鯉 鲥鰣 鲦鰷 鲧鯀 鲨鯊 鲩鯇 鲪鮶 鲫鯽 鲬鯒 鲭鯖 鲮鯪 鲯鯕 鲰鯫 鲱鯡 鲲鯤 鲳鯧 鲴鯝 鲵鯢 鲶鯰 - 鲷鯛 鲸鯨 鲹鰺 鲺鯴 鲻鯔 鲼鱝 鲽鰈 鲾鰏 鲿鱨 鳀鯷 鳁鰮 鳂鰃 鳃鰓 鳄鱷 鳅鰍 鳆鰒 鳇鰉 鳈鰁 鳉鱂 鳊鯿 - 鳋鰠 鳌鰲 鳍鰭 鳎鰨 鳏鰥 鳐鰩 鳑鰟 鳒鰜 鳓鰳 鳔鰾 鳕鱈 鳖鱉 鳗鰻 鳘鰵 鳙鱅 鳚䲁 鳛鰼 鳜鱖 鳝鱔 鳞鱗 - 鳟鱒 鳠鱯 鳡鱤 鳢鱧 鳣鱣 鳤䲘 鸟鳥 鸠鳩 鸡雞 鸢鳶 鸣鳴 鸤鳲 鸥鷗 鸦鴉 鸧鶬 鸨鴇 鸩鴆 鸪鴣 鸫鶇 鸬鸕 - 鸭鴨 鸮鴞 鸯鴦 鸰鴒 鸱鴟 鸲鴝 鸳鴛 鸴鷽 鸵鴕 鸶鷥 鸷鷙 鸸鴯 鸹鴰 鸺鵂 鸻鴴 鸼鵃 鸽鴿 鸾鸞 鸿鴻 鹀鵐 - 鹁鵓 鹂鸝 鹃鵑 鹄鵠 鹅鵝 鹆鵒 鹇鷳 鹈鵜 鹉鵡 鹊鵲 鹋鶓 鹌鵪 鹍鵾 鹎鵯 鹏鵬 鹐鵮 鹑鶉 鹒鶊 鹓鵷 鹔鷫 - 鹕鶘 鹖鶡 鹗鶚 鹘鶻 鹙鶖 鹚鷀 鹛鶥 鹜鶩 鹝鷊 鹞鷂 鹟鶲 鹠鶹 鹡鶺 鹢鷁 鹣鶼 鹤鶴 鹥鷖 鹦鸚 鹧鷓 鹨鷚 - 鹩鷯 鹪鷦 鹫鷲 鹬鷸 鹭鷺 鹮䴉 鹯鸇 鹰鷹 鹱鸌 鹲鸏 鹳鸛 鹴鸘 鹾鹺 麦麥 麸麩 麹麴 麺麵 麽麼 黄黃 黉黌 - 黡黶 黩黷 黪黲 黾黽 鼋黿 鼌鼂 鼍鼉 鼹鼴 齐齊 齑齏 齿齒 龀齔 龁齕 龂齗 龃齟 龄齡 龅齙 龆齠 龇齜 龈齦 - 龉齬 龊齪 龋齲 龌齷 龙龍 龚龔 龛龕 龟龜 鿎䃮 鿏䥑 鿒鿓 鿔鎶 - """; - - internal static Dictionary Create() - { - var map = new Dictionary(); - foreach (var pair in Pairs.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)) - map[pair[0]] = pair.Substring(1); - return map; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/Properties/AssemblyInfo.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/Properties/AssemblyInfo.cs deleted file mode 100644 index 73b420a..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("BazaarPlusPlus")] -[assembly: InternalsVisibleTo("CombatImpact.Corpus")] -[assembly: InternalsVisibleTo("CombatStatusBarState.Tests")] -[assembly: InternalsVisibleTo("Supporters.Tests")] -[assembly: InternalsVisibleTo("GhostBattleSync.Tests")] -[assembly: InternalsVisibleTo("HistoryPanelDecisions.Tests")] -[assembly: InternalsVisibleTo("HistoryPanelRepository.Tests")] -[assembly: InternalsVisibleTo("HistoryPanelFiltering.Tests")] -[assembly: InternalsVisibleTo("LiveBuildRecommendations.Tests")] -[assembly: InternalsVisibleTo("PostCombatImpact.Tests")] -[assembly: InternalsVisibleTo("RuntimeIntegration.Tests")] -[assembly: InternalsVisibleTo("CollectionEncounterTooltip.Tests")] diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/packages.lock.json b/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/packages.lock.json deleted file mode 100644 index 735e6d2..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Localization/packages.lock.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "version": 2, - "dependencies": { - ".NETStandard,Version=v2.1": { - "NETStandard.Library": { - "type": "Direct", - "requested": "[2.0.3, )", - "resolved": "2.0.3", - "contentHash": "st47PosZSHrjECdjeIzZQbzivYBJFv6P2nv4cj2ypdI204DO+vZ7l5raGMiX4eXMJ53RfOIg+/s4DHVZ54Nu2A==", - "dependencies": { - "Microsoft.NETCore.Platforms": "1.1.0" - } - }, - "Microsoft.NETCore.Platforms": { - "type": "Transitive", - "resolved": "1.1.0", - "contentHash": "kz0PEW2lhqygehI/d6XsPCQzD7ff7gUJaVGPVETX611eadGsA3A877GdSlU0LRVMCTH/+P3o2iDTak+S08V2+A==" - } - } - } -} \ No newline at end of file diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/.gitkeep b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/BazaarPlusPlus.ModApi.csproj b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/BazaarPlusPlus.ModApi.csproj deleted file mode 100644 index 75b63db..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/BazaarPlusPlus.ModApi.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - BazaarPlusPlus.ModApi - BazaarPlusPlus.ModApi - netstandard2.1 - 12 - enable - $(BppVersion) - true - true - - - - - - - - diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleLimitsV6.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleLimitsV6.cs deleted file mode 100644 index 9eb57de..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleLimitsV6.cs +++ /dev/null @@ -1,22 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.ModApi.Bundle; - -internal static class BundleLimitsV6 -{ - public const int BundleVersion = 6; - public const int RunFormatVersion = 6; - public const int PrefixBytes = 16; - public const int MaxBundleBytes = 8_388_607; - public const int MaxManifestBytes = 2_097_152; - public const int MaxRunBytes = 2_097_151; - public const int MaxScreenshotBytes = 1_048_576; - public const int MaxProjectionBytes = 524_288; - public const int MaxBattlesPerBundle = 30; - public const long MaxSafeInteger = 9_007_199_254_740_991; - public const long MaxCreatedAtMs = 8_640_000_000_000_000; - - public const string BundleContentType = "application/x-bpp-bundle-v6"; - public const string RunContentType = "application/x-bpp-run-v6"; - public const string JpegContentType = "image/jpeg"; - public const string WebpContentType = "image/webp"; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleManifestV6.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleManifestV6.cs deleted file mode 100644 index b98de52..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleManifestV6.cs +++ /dev/null @@ -1,163 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.ModApi.Bundle; - -internal sealed class BundleManifestV6 -{ - public string BundleId { get; set; } = string.Empty; - public int BundleVersion { get; set; } = BundleLimitsV6.BundleVersion; - public long CreatedAtMs { get; set; } - public BundleRunManifestV6 Run { get; set; } = new(); - public BundleScreenshotManifestV6? Screenshot { get; set; } -} - -internal sealed class BundleRunManifestV6 -{ - public string RunId { get; set; } = string.Empty; - public string PlayerAccountId { get; set; } = string.Empty; - public int RunFormatVersion { get; set; } = BundleLimitsV6.RunFormatVersion; - public BundleProjectionV6 Projection { get; set; } = new(); - public BundleSegmentManifestV6 Payload { get; set; } = new(); -} - -internal sealed class BundleProjectionV6 -{ - public List Battles { get; set; } = new(); -} - -internal sealed class BundleBattleProjectionV6 -{ - public string BattleId { get; set; } = string.Empty; - public long RecordedAtMs { get; set; } - public long Day { get; set; } - public long Hour { get; set; } - public string? EncounterId { get; set; } - public string CombatKind { get; set; } = string.Empty; - public string Result { get; set; } = string.Empty; - public string WinnerCombatantId { get; set; } = string.Empty; - public string LoserCombatantId { get; set; } = string.Empty; - public bool IsFinalBattle { get; set; } - public BundleCombatantProjectionV6 Player { get; set; } = new(); - public BundleCombatantProjectionV6 Opponent { get; set; } = new(); -} - -internal sealed class BundleCombatantProjectionV6 -{ - public string AccountId { get; set; } = string.Empty; - public string DisplayName { get; set; } = string.Empty; - public string? HeroId { get; set; } - public string? HeroName { get; set; } - public string? Rank { get; set; } - public long? Rating { get; set; } - public long? Level { get; set; } - public long? Prestige { get; set; } - public long? Victories { get; set; } -} - -internal class BundleSegmentManifestV6 -{ - public long Offset { get; set; } - public long Length { get; set; } - public string Sha256 { get; set; } = string.Empty; - public string ContentType { get; set; } = string.Empty; -} - -internal sealed class BundleScreenshotManifestV6 : BundleSegmentManifestV6 -{ - public long Width { get; set; } - public long Height { get; set; } - public long Quality { get; set; } - public long CapturedAtMs { get; set; } -} - -internal sealed class BundleBuildInputV6 -{ - public string BundleId { get; set; } = string.Empty; - public long CreatedAtMs { get; set; } - public string RunId { get; set; } = string.Empty; - public string PlayerAccountId { get; set; } = string.Empty; - public IReadOnlyList Battles { get; set; } = - Array.Empty(); - public ReadOnlyMemory RunPayload { get; set; } - public BundleScreenshotBuildInputV6? Screenshot { get; set; } -} - -internal sealed class BundleScreenshotBuildInputV6 -{ - public ReadOnlyMemory Bytes { get; set; } - public string ContentType { get; set; } = BundleLimitsV6.JpegContentType; - public int Width { get; set; } - public int Height { get; set; } - public int Quality { get; set; } - public long CapturedAtMs { get; set; } -} - -internal sealed class BundleBuildResultV6 -{ - public BundleBuildResultV6( - byte[] bytes, - byte[] manifestBytes, - BundleManifestV6 manifest, - string sha256Hex, - string contentDigest - ) - { - Bytes = bytes; - ManifestBytes = manifestBytes; - Manifest = manifest; - Sha256Hex = sha256Hex; - ContentDigest = contentDigest; - } - - public byte[] Bytes { get; } - public byte[] ManifestBytes { get; } - public BundleManifestV6 Manifest { get; } - public string Sha256Hex { get; } - public string ContentDigest { get; } -} - -internal sealed class OpenedBundleV6 -{ - public OpenedBundleV6( - BundleManifestV6 manifest, - byte[] manifestBytes, - byte[] runPayload, - byte[]? screenshot, - string sha256Hex, - string contentDigest - ) - { - Manifest = manifest; - ManifestBytes = manifestBytes; - RunPayload = runPayload; - Screenshot = screenshot; - Sha256Hex = sha256Hex; - ContentDigest = contentDigest; - } - - public BundleManifestV6 Manifest { get; } - public byte[] ManifestBytes { get; } - public byte[] RunPayload { get; } - public byte[]? Screenshot { get; } - public string Sha256Hex { get; } - public string ContentDigest { get; } -} - -internal sealed class BundleV6Exception : Exception -{ - public BundleV6Exception(string code, string reason, string message) - : base(message) - { - Code = code; - Reason = reason; - } - - public BundleV6Exception(string code, string reason, string message, Exception innerException) - : base(message, innerException) - { - Code = code; - Reason = reason; - } - - public string Code { get; } - public string Reason { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleManifestV6Writer.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleManifestV6Writer.cs deleted file mode 100644 index 691b9e6..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleManifestV6Writer.cs +++ /dev/null @@ -1,156 +0,0 @@ -#nullable enable -using System.Globalization; -using System.Text; -using Newtonsoft.Json; - -namespace BazaarPlusPlus.ModApi.Bundle; - -internal static class BundleManifestV6Writer -{ - internal static byte[] Write(BundleManifestV6 manifest) - { - using var text = new StringWriter(CultureInfo.InvariantCulture); - using (var writer = new JsonTextWriter(text)) - { - writer.CloseOutput = false; - writer.Culture = CultureInfo.InvariantCulture; - writer.Formatting = Formatting.None; - writer.StringEscapeHandling = StringEscapeHandling.Default; - WriteManifest(writer, manifest); - } - return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(text.ToString()); - } - - private static void WriteManifest(JsonWriter writer, BundleManifestV6 manifest) - { - writer.WriteStartObject(); - Write(writer, "bundle_id", manifest.BundleId); - Write(writer, "bundle_version", manifest.BundleVersion); - Write(writer, "created_at_ms", manifest.CreatedAtMs); - writer.WritePropertyName("run"); - WriteRun(writer, manifest.Run); - if (manifest.Screenshot != null) - { - writer.WritePropertyName("screenshot"); - WriteScreenshot(writer, manifest.Screenshot); - } - writer.WriteEndObject(); - } - - private static void WriteRun(JsonWriter writer, BundleRunManifestV6 run) - { - writer.WriteStartObject(); - Write(writer, "run_id", run.RunId); - Write(writer, "player_account_id", run.PlayerAccountId); - Write(writer, "run_format_version", run.RunFormatVersion); - writer.WritePropertyName("projection"); - writer.WriteStartObject(); - writer.WritePropertyName("run"); - writer.WriteStartObject(); - writer.WriteEndObject(); - writer.WritePropertyName("battles"); - writer.WriteStartArray(); - foreach (var battle in run.Projection.Battles) - WriteBattle(writer, battle); - writer.WriteEndArray(); - writer.WriteEndObject(); - writer.WritePropertyName("payload"); - WriteSegment(writer, run.Payload); - writer.WriteEndObject(); - } - - private static void WriteBattle(JsonWriter writer, BundleBattleProjectionV6 battle) - { - writer.WriteStartObject(); - Write(writer, "battle_id", battle.BattleId); - Write(writer, "recorded_at_ms", battle.RecordedAtMs); - Write(writer, "day", battle.Day); - Write(writer, "hour", battle.Hour); - WriteNullable(writer, "encounter_id", battle.EncounterId); - Write(writer, "combat_kind", battle.CombatKind); - Write(writer, "result", battle.Result); - Write(writer, "winner_combatant_id", battle.WinnerCombatantId); - Write(writer, "loser_combatant_id", battle.LoserCombatantId); - Write(writer, "is_final_battle", battle.IsFinalBattle); - writer.WritePropertyName("player"); - WriteCombatant(writer, battle.Player); - writer.WritePropertyName("opponent"); - WriteCombatant(writer, battle.Opponent); - writer.WriteEndObject(); - } - - private static void WriteCombatant(JsonWriter writer, BundleCombatantProjectionV6 combatant) - { - writer.WriteStartObject(); - Write(writer, "account_id", combatant.AccountId); - Write(writer, "display_name", combatant.DisplayName); - WriteNullable(writer, "hero_id", combatant.HeroId); - WriteNullable(writer, "hero_name", combatant.HeroName); - WriteNullable(writer, "rank", combatant.Rank); - WriteNullable(writer, "rating", combatant.Rating); - WriteNullable(writer, "level", combatant.Level); - WriteNullable(writer, "prestige", combatant.Prestige); - WriteNullable(writer, "victories", combatant.Victories); - writer.WriteEndObject(); - } - - private static void WriteSegment(JsonWriter writer, BundleSegmentManifestV6 segment) - { - writer.WriteStartObject(); - Write(writer, "offset", segment.Offset); - Write(writer, "length", segment.Length); - Write(writer, "sha256", segment.Sha256); - Write(writer, "content_type", segment.ContentType); - writer.WriteEndObject(); - } - - private static void WriteScreenshot(JsonWriter writer, BundleScreenshotManifestV6 screenshot) - { - writer.WriteStartObject(); - Write(writer, "offset", screenshot.Offset); - Write(writer, "length", screenshot.Length); - Write(writer, "sha256", screenshot.Sha256); - Write(writer, "content_type", screenshot.ContentType); - Write(writer, "width", screenshot.Width); - Write(writer, "height", screenshot.Height); - Write(writer, "quality", screenshot.Quality); - Write(writer, "captured_at_ms", screenshot.CapturedAtMs); - writer.WriteEndObject(); - } - - private static void Write(JsonWriter writer, string name, string value) - { - writer.WritePropertyName(name); - writer.WriteValue(value); - } - - private static void Write(JsonWriter writer, string name, long value) - { - writer.WritePropertyName(name); - writer.WriteValue(value); - } - - private static void Write(JsonWriter writer, string name, bool value) - { - writer.WritePropertyName(name); - writer.WriteValue(value); - } - - private static void WriteNullable(JsonWriter writer, string name, string? value) - { - writer.WritePropertyName(name); - if (value == null) - writer.WriteNull(); - else - writer.WriteValue(value); - } - - private static void WriteNullable(JsonWriter writer, string name, long? value) - { - writer.WritePropertyName(name); - if (value.HasValue) - writer.WriteValue(value.Value); - else - writer.WriteNull(); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleV6Codec.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleV6Codec.cs deleted file mode 100644 index 5f89ae0..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/BundleV6Codec.cs +++ /dev/null @@ -1,751 +0,0 @@ -#nullable enable -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BazaarPlusPlus.ModApi.Bundle; - -internal static class BundleV6Codec -{ - private static readonly byte[] Magic = Encoding.ASCII.GetBytes("BPPBNDL6"); - private static readonly UTF8Encoding StrictUtf8 = new(false, true); - private static readonly Regex IdentifierPattern = new( - "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$", - RegexOptions.CultureInvariant - ); - private static readonly Regex Sha256Pattern = new( - "^[0-9a-f]{64}$", - RegexOptions.CultureInvariant - ); - - public static BundleBuildResultV6 Build(BundleBuildInputV6 input) - { - if (input == null) - throw new ArgumentNullException(nameof(input)); - ValidateBundleId(input.BundleId); - ValidateCreatedAt(input.CreatedAtMs); - ValidateIdentifier(input.RunId, "run.run_id"); - ValidateIdentifier(input.PlayerAccountId, "run.player_account_id"); - if (input.RunPayload.Length == 0) - Invalid("run_missing", "Run segment must be non-empty."); - if (input.RunPayload.Length > BundleLimitsV6.MaxRunBytes) - Invalid("run_too_large", "Run segment exceeds its byte limit."); - - var battles = input.Battles ?? throw new ArgumentNullException(nameof(input.Battles)); - ValidateBattles(battles, input.PlayerAccountId); - var runBytes = input.RunPayload.ToArray(); - var manifest = new BundleManifestV6 - { - BundleId = input.BundleId, - CreatedAtMs = input.CreatedAtMs, - Run = new BundleRunManifestV6 - { - RunId = input.RunId, - PlayerAccountId = input.PlayerAccountId, - Projection = new BundleProjectionV6 { Battles = battles.ToList() }, - Payload = new BundleSegmentManifestV6 - { - Offset = 0, - Length = runBytes.Length, - Sha256 = ComputeSha256Hex(runBytes), - ContentType = BundleLimitsV6.RunContentType, - }, - }, - }; - - byte[]? screenshotBytes = null; - if (input.Screenshot != null) - { - var screenshot = input.Screenshot; - screenshotBytes = screenshot.Bytes.ToArray(); - ValidateScreenshotInput(screenshot, screenshotBytes.Length); - manifest.Screenshot = new BundleScreenshotManifestV6 - { - Offset = runBytes.Length, - Length = screenshotBytes.Length, - Sha256 = ComputeSha256Hex(screenshotBytes), - ContentType = screenshot.ContentType, - Width = screenshot.Width, - Height = screenshot.Height, - Quality = screenshot.Quality, - CapturedAtMs = screenshot.CapturedAtMs, - }; - } - - var manifestBytes = BundleManifestV6Writer.Write(manifest); - if (manifestBytes.Length == 0 || manifestBytes.Length > BundleLimitsV6.MaxManifestBytes) - Invalid("manifest_too_large", "Manifest length is outside the accepted range."); - ValidateProjectionSize(manifest.Run.Projection); - - var totalBytes = checked( - BundleLimitsV6.PrefixBytes - + manifestBytes.Length - + runBytes.Length - + (screenshotBytes?.Length ?? 0) - ); - if (totalBytes > BundleLimitsV6.MaxBundleBytes) - throw new BundleV6Exception( - "bundle_too_large", - "bundle_too_large", - "Bundle exceeds its byte limit." - ); - - var bundle = new byte[totalBytes]; - Buffer.BlockCopy(Magic, 0, bundle, 0, Magic.Length); - WriteUInt32BigEndian(bundle, 8, BundleLimitsV6.BundleVersion); - WriteUInt32BigEndian(bundle, 12, manifestBytes.Length); - Buffer.BlockCopy( - manifestBytes, - 0, - bundle, - BundleLimitsV6.PrefixBytes, - manifestBytes.Length - ); - var payloadOffset = BundleLimitsV6.PrefixBytes + manifestBytes.Length; - Buffer.BlockCopy(runBytes, 0, bundle, payloadOffset, runBytes.Length); - if (screenshotBytes != null) - Buffer.BlockCopy( - screenshotBytes, - 0, - bundle, - payloadOffset + runBytes.Length, - screenshotBytes.Length - ); - - var digestBytes = ComputeSha256(bundle); - var result = new BundleBuildResultV6( - bundle, - manifestBytes, - manifest, - ToLowerHex(digestBytes), - FormatContentDigest(digestBytes) - ); - - // Build is the only writer; make its server-compatible reader the final local schema gate. - Open(bundle); - return result; - } - - public static OpenedBundleV6 Open(ReadOnlyMemory bytes) - { - if (bytes.Length > BundleLimitsV6.MaxBundleBytes) - throw new BundleV6Exception( - "bundle_too_large", - "bundle_too_large", - "Bundle exceeds its byte limit." - ); - if (bytes.Length < BundleLimitsV6.PrefixBytes) - Invalid("invalid_prefix", "Bundle prefix is incomplete."); - - var source = bytes.Span; - for (var index = 0; index < Magic.Length; index++) - { - if (source[index] != Magic[index]) - Invalid("invalid_prefix", "Bundle magic is invalid."); - } - - var version = ReadUInt32BigEndian(source, 8); - if (version != BundleLimitsV6.BundleVersion) - throw new BundleV6Exception( - "unsupported_bundle_version", - "unsupported_bundle_version", - "Bundle version is not supported." - ); - var manifestLength = ReadUInt32BigEndian(source, 12); - if (manifestLength == 0 || manifestLength > BundleLimitsV6.MaxManifestBytes) - Invalid("manifest_too_large", "Manifest length is outside the accepted range."); - if ((long)BundleLimitsV6.PrefixBytes + manifestLength >= bytes.Length) - Invalid("run_missing", "Bundle Run segment is missing."); - - var manifestBytes = bytes - .Slice(BundleLimitsV6.PrefixBytes, checked((int)manifestLength)) - .ToArray(); - var root = ParseManifest(manifestBytes); - var manifest = ReadManifest(root); - var payloadStart = checked(BundleLimitsV6.PrefixBytes + (int)manifestLength); - var describedBytes = checked( - (long)payloadStart + manifest.Run.Payload.Length + (manifest.Screenshot?.Length ?? 0) - ); - if (describedBytes < bytes.Length) - Invalid("undeclared_trailing_bytes", "Bundle has undeclared trailing bytes."); - if (describedBytes > bytes.Length) - Invalid("segment_out_of_bounds", "A segment extends beyond the Bundle body."); - - var runOffset = checked(payloadStart + (int)manifest.Run.Payload.Offset); - var runLength = checked((int)manifest.Run.Payload.Length); - var runBytes = bytes.Slice(runOffset, runLength).ToArray(); - ValidateDigest(runBytes, manifest.Run.Payload.Sha256); - - byte[]? screenshotBytes = null; - if (manifest.Screenshot != null) - { - var screenshotOffset = checked(payloadStart + (int)manifest.Screenshot.Offset); - var screenshotLength = checked((int)manifest.Screenshot.Length); - screenshotBytes = bytes.Slice(screenshotOffset, screenshotLength).ToArray(); - ValidateDigest(screenshotBytes, manifest.Screenshot.Sha256); - } - - var completeDigest = ComputeSha256(bytes.Span); - return new OpenedBundleV6( - manifest, - manifestBytes, - runBytes, - screenshotBytes, - ToLowerHex(completeDigest), - FormatContentDigest(completeDigest) - ); - } - - public static string ComputeSha256Hex(ReadOnlyMemory bytes) => - ToLowerHex(ComputeSha256(bytes.Span)); - - public static string FormatContentDigest(ReadOnlyMemory bundleBytes) => - FormatContentDigest(ComputeSha256(bundleBytes.Span)); - - private static JObject ParseManifest(byte[] manifestBytes) - { - string json; - try - { - json = StrictUtf8.GetString(manifestBytes); - } - catch (DecoderFallbackException ex) - { - throw new BundleV6Exception( - "invalid_bundle", - "manifest_not_json", - "Manifest is not valid UTF-8 JSON.", - ex - ); - } - - try - { - using var stringReader = new StringReader(json); - using var reader = new JsonTextReader(stringReader) - { - DateParseHandling = DateParseHandling.None, - FloatParseHandling = FloatParseHandling.Decimal, - MaxDepth = 64, - }; - var token = JToken.ReadFrom( - reader, - new JsonLoadSettings - { - DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Replace, - LineInfoHandling = LineInfoHandling.Ignore, - } - ); - if (reader.Read()) - Invalid("manifest_not_json", "Manifest contains trailing JSON tokens."); - return RequireObject(token, "Manifest root must be an object."); - } - catch (BundleV6Exception) - { - throw; - } - catch (Exception ex) when (ex is JsonException || ex is InvalidOperationException) - { - throw new BundleV6Exception( - "invalid_bundle", - "manifest_not_json", - "Manifest is not valid JSON.", - ex - ); - } - } - - private static BundleManifestV6 ReadManifest(JObject root) - { - var bundleVersion = ReadSafeInteger( - RequireProperty(root, "bundle_version"), - "bundle_version" - ); - if (bundleVersion != BundleLimitsV6.BundleVersion) - throw new BundleV6Exception( - "unsupported_bundle_version", - "unsupported_bundle_version", - "Manifest Bundle version is not supported." - ); - var bundleId = ReadString(RequireProperty(root, "bundle_id"), "bundle_id"); - ValidateBundleId(bundleId); - var createdAtMs = ReadSafeInteger(RequireProperty(root, "created_at_ms"), "created_at_ms"); - ValidateCreatedAt(createdAtMs); - - var run = RequireObject(RequireProperty(root, "run"), "run must be an object."); - var runFormatVersion = ReadSafeInteger( - RequireProperty(run, "run_format_version"), - "run.run_format_version" - ); - if (runFormatVersion != BundleLimitsV6.RunFormatVersion) - throw new BundleV6Exception( - "unsupported_run_format", - "unsupported_run_format", - "Run format is not supported." - ); - var runId = ReadIdentifier(RequireProperty(run, "run_id"), "run.run_id"); - var playerAccountId = ReadIdentifier( - RequireProperty(run, "player_account_id"), - "run.player_account_id" - ); - var payload = ReadRunSegment( - RequireObject(RequireProperty(run, "payload"), "run.payload must be an object.") - ); - var projectionToken = RequireProperty(run, "projection"); - var projectionObject = RequireObject(projectionToken, "run.projection must be an object."); - RequireObject( - RequireProperty(projectionObject, "run"), - "run.projection.run must be an object." - ); - ValidateProjectionTokenSize(projectionToken); - var battleTokens = RequireProperty(projectionObject, "battles") as JArray; - if (battleTokens == null) - Invalid("manifest_schema_invalid", "run.projection.battles must be an array."); - if (battleTokens!.Count > BundleLimitsV6.MaxBattlesPerBundle) - Invalid("too_many_battles", "Bundle contains too many Battle projections."); - var battles = battleTokens.Select(token => ReadBattle(token, playerAccountId)).ToList(); - if ( - battles.Select(battle => battle.BattleId).Distinct(StringComparer.Ordinal).Count() - != battles.Count - ) - Invalid("manifest_schema_invalid", "Battle IDs must be unique within a Bundle."); - - BundleScreenshotManifestV6? screenshot = null; - var screenshotProperty = root.Property("screenshot", StringComparison.Ordinal); - if (screenshotProperty != null) - screenshot = ReadScreenshot( - RequireObject(screenshotProperty.Value, "screenshot must be an object."), - payload.Length - ); - - return new BundleManifestV6 - { - BundleId = bundleId, - BundleVersion = BundleLimitsV6.BundleVersion, - CreatedAtMs = createdAtMs, - Run = new BundleRunManifestV6 - { - RunId = runId, - PlayerAccountId = playerAccountId, - RunFormatVersion = BundleLimitsV6.RunFormatVersion, - Projection = new BundleProjectionV6 { Battles = battles }, - Payload = payload, - }, - Screenshot = screenshot, - }; - } - - private static BundleSegmentManifestV6 ReadRunSegment(JObject payload) - { - var offset = ReadSafeInteger(RequireProperty(payload, "offset"), "run.payload.offset"); - var length = ReadSafeInteger(RequireProperty(payload, "length"), "run.payload.length"); - if (offset != 0 || length == 0) - Invalid( - "run_missing", - "Run segment must start at payload offset zero and be non-empty." - ); - if (length > BundleLimitsV6.MaxRunBytes) - Invalid("run_too_large", "Run segment exceeds its byte limit."); - var contentType = ReadString( - RequireProperty(payload, "content_type"), - "run.payload.content_type" - ); - if (!string.Equals(contentType, BundleLimitsV6.RunContentType, StringComparison.Ordinal)) - Invalid("manifest_schema_invalid", "Run content type is invalid."); - var sha256 = ReadSha256(RequireProperty(payload, "sha256"), "run.payload.sha256"); - return new BundleSegmentManifestV6 - { - Offset = offset, - Length = length, - Sha256 = sha256, - ContentType = contentType, - }; - } - - private static BundleScreenshotManifestV6 ReadScreenshot(JObject image, long runLength) - { - var offset = ReadSafeInteger(RequireProperty(image, "offset"), "screenshot.offset"); - var length = ReadSafeInteger(RequireProperty(image, "length"), "screenshot.length"); - if (length == 0 || length > BundleLimitsV6.MaxScreenshotBytes) - Invalid("screenshot_too_large", "Screenshot segment is empty or too large."); - var contentType = ReadString( - RequireProperty(image, "content_type"), - "screenshot.content_type" - ); - if ( - !string.Equals(contentType, BundleLimitsV6.JpegContentType, StringComparison.Ordinal) - && !string.Equals(contentType, BundleLimitsV6.WebpContentType, StringComparison.Ordinal) - ) - Invalid("screenshot_type_unsupported", "Screenshot content type is unsupported."); - var sha256 = ReadSha256(RequireProperty(image, "sha256"), "screenshot.sha256"); - var width = ReadSafeInteger(RequireProperty(image, "width"), "screenshot.width"); - var height = ReadSafeInteger(RequireProperty(image, "height"), "screenshot.height"); - var quality = ReadSafeInteger(RequireProperty(image, "quality"), "screenshot.quality"); - var capturedAtMs = ReadSafeInteger( - RequireProperty(image, "captured_at_ms"), - "screenshot.captured_at_ms" - ); - if (width < 1 || height < 1 || quality < 1 || quality > 100) - Invalid("manifest_schema_invalid", "Screenshot dimensions or quality are invalid."); - if (offset < runLength) - Invalid("segment_overlap", "Screenshot overlaps the Run segment."); - if (offset > runLength) - Invalid( - "segment_out_of_bounds", - "Screenshot does not immediately follow the Run segment." - ); - return new BundleScreenshotManifestV6 - { - Offset = offset, - Length = length, - Sha256 = sha256, - ContentType = contentType, - Width = width, - Height = height, - Quality = quality, - CapturedAtMs = capturedAtMs, - }; - } - - private static BundleBattleProjectionV6 ReadBattle(JToken token, string uploader) - { - var source = RequireObject(token, "Battle projection must be an object."); - var player = ReadCombatant(RequireProperty(source, "player"), "battle.player"); - var opponent = ReadCombatant(RequireProperty(source, "opponent"), "battle.opponent"); - if (!string.Equals(player.AccountId, uploader, StringComparison.Ordinal)) - Invalid("manifest_schema_invalid", "Battle player identity differs from uploader."); - var finalToken = RequireProperty(source, "is_final_battle"); - if (finalToken.Type != JTokenType.Boolean) - Invalid("manifest_schema_invalid", "battle.is_final_battle must be boolean."); - return new BundleBattleProjectionV6 - { - BattleId = ReadIdentifier(RequireProperty(source, "battle_id"), "battle.battle_id"), - RecordedAtMs = ReadSafeInteger( - RequireProperty(source, "recorded_at_ms"), - "battle.recorded_at_ms" - ), - Day = ReadSafeInteger(RequireProperty(source, "day"), "battle.day"), - Hour = ReadSafeInteger(RequireProperty(source, "hour"), "battle.hour"), - EncounterId = ReadNullableString( - RequireProperty(source, "encounter_id"), - "battle.encounter_id" - ), - CombatKind = ReadIdentifier( - RequireProperty(source, "combat_kind"), - "battle.combat_kind" - ), - Result = ReadIdentifier(RequireProperty(source, "result"), "battle.result"), - WinnerCombatantId = ReadIdentifier( - RequireProperty(source, "winner_combatant_id"), - "battle.winner_combatant_id" - ), - LoserCombatantId = ReadIdentifier( - RequireProperty(source, "loser_combatant_id"), - "battle.loser_combatant_id" - ), - IsFinalBattle = finalToken.Value(), - Player = player, - Opponent = opponent, - }; - } - - private static BundleCombatantProjectionV6 ReadCombatant(JToken token, string field) - { - var source = RequireObject(token, $"{field} must be an object."); - var displayName = ReadString( - RequireProperty(source, "display_name"), - $"{field}.display_name" - ); - if (displayName.Length > 256) - Invalid("manifest_schema_invalid", $"{field}.display_name is invalid."); - return new BundleCombatantProjectionV6 - { - AccountId = ReadIdentifier( - RequireProperty(source, "account_id"), - $"{field}.account_id" - ), - DisplayName = displayName, - HeroId = ReadNullableString(RequireProperty(source, "hero_id"), $"{field}.hero_id"), - HeroName = ReadNullableString( - RequireProperty(source, "hero_name"), - $"{field}.hero_name" - ), - Rank = ReadNullableString(RequireProperty(source, "rank"), $"{field}.rank"), - Rating = ReadNullableSafeInteger(RequireProperty(source, "rating"), $"{field}.rating"), - Level = ReadNullableSafeInteger(RequireProperty(source, "level"), $"{field}.level"), - Prestige = ReadNullableSafeInteger( - RequireProperty(source, "prestige"), - $"{field}.prestige" - ), - Victories = ReadNullableSafeInteger( - RequireProperty(source, "victories"), - $"{field}.victories" - ), - }; - } - - private static void ValidateBattles( - IReadOnlyList battles, - string uploader - ) - { - if (battles.Count > BundleLimitsV6.MaxBattlesPerBundle) - Invalid("too_many_battles", "Bundle contains too many Battle projections."); - var ids = new HashSet(StringComparer.Ordinal); - foreach (var battle in battles) - { - if (battle == null) - Invalid("manifest_schema_invalid", "Battle projection must be an object."); - ValidateIdentifier(battle.BattleId, "battle.battle_id"); - if (!ids.Add(battle.BattleId)) - Invalid("manifest_schema_invalid", "Battle IDs must be unique within a Bundle."); - ValidateSafeInteger(battle.RecordedAtMs, "battle.recorded_at_ms"); - ValidateSafeInteger(battle.Day, "battle.day"); - ValidateSafeInteger(battle.Hour, "battle.hour"); - ValidateNullableString(battle.EncounterId, "battle.encounter_id"); - ValidateIdentifier(battle.CombatKind, "battle.combat_kind"); - ValidateIdentifier(battle.Result, "battle.result"); - ValidateIdentifier(battle.WinnerCombatantId, "battle.winner_combatant_id"); - ValidateIdentifier(battle.LoserCombatantId, "battle.loser_combatant_id"); - ValidateCombatant(battle.Player, "battle.player"); - ValidateCombatant(battle.Opponent, "battle.opponent"); - if (!string.Equals(battle.Player.AccountId, uploader, StringComparison.Ordinal)) - Invalid("manifest_schema_invalid", "Battle player identity differs from uploader."); - } - } - - private static void ValidateCombatant(BundleCombatantProjectionV6 combatant, string field) - { - if (combatant == null) - Invalid("manifest_schema_invalid", $"{field} must be an object."); - ValidateIdentifier(combatant.AccountId, $"{field}.account_id"); - if (combatant.DisplayName == null || combatant.DisplayName.Length > 256) - Invalid("manifest_schema_invalid", $"{field}.display_name is invalid."); - ValidateNullableString(combatant.HeroId, $"{field}.hero_id"); - ValidateNullableString(combatant.HeroName, $"{field}.hero_name"); - ValidateNullableString(combatant.Rank, $"{field}.rank"); - ValidateNullableSafeInteger(combatant.Rating, $"{field}.rating"); - ValidateNullableSafeInteger(combatant.Level, $"{field}.level"); - ValidateNullableSafeInteger(combatant.Prestige, $"{field}.prestige"); - ValidateNullableSafeInteger(combatant.Victories, $"{field}.victories"); - } - - private static void ValidateProjectionSize(BundleProjectionV6 projection) - { - var bytes = BundleManifestV6Writer.Write( - new BundleManifestV6 - { - BundleId = "01J00000000000000000000000", - Run = new BundleRunManifestV6 { Projection = projection }, - } - ); - // Subtracting a fixed envelope is unnecessary: this conservative precheck can only reject - // a projection already beyond the server's limit. Open performs the exact token check. - if (bytes.Length > BundleLimitsV6.MaxProjectionBytes + 512) - Invalid("projection_too_large", "Run projection exceeds its byte limit."); - } - - private static void ValidateProjectionTokenSize(JToken projection) - { - var compact = projection.ToString(Formatting.None); - if (Encoding.UTF8.GetByteCount(compact) > BundleLimitsV6.MaxProjectionBytes) - Invalid("projection_too_large", "Run projection exceeds its byte limit."); - } - - private static void ValidateScreenshotInput(BundleScreenshotBuildInputV6 screenshot, int length) - { - if (length == 0 || length > BundleLimitsV6.MaxScreenshotBytes) - Invalid("screenshot_too_large", "Screenshot segment is empty or too large."); - if ( - !string.Equals( - screenshot.ContentType, - BundleLimitsV6.JpegContentType, - StringComparison.Ordinal - ) - && !string.Equals( - screenshot.ContentType, - BundleLimitsV6.WebpContentType, - StringComparison.Ordinal - ) - ) - Invalid("screenshot_type_unsupported", "Screenshot content type is unsupported."); - if ( - screenshot.Width < 1 - || screenshot.Height < 1 - || screenshot.Quality < 1 - || screenshot.Quality > 100 - ) - Invalid("manifest_schema_invalid", "Screenshot dimensions or quality are invalid."); - ValidateSafeInteger(screenshot.CapturedAtMs, "screenshot.captured_at_ms"); - } - - private static JObject RequireObject(JToken? token, string message) - { - if (token is JObject value) - return value; - Invalid("manifest_schema_invalid", message); - throw new InvalidOperationException(); - } - - private static JToken RequireProperty(JObject source, string name) - { - var property = source.Property(name, StringComparison.Ordinal); - if (property == null) - Invalid("manifest_schema_invalid", $"Manifest field {name} is required."); - return property!.Value; - } - - private static string ReadIdentifier(JToken token, string field) - { - var value = ReadString(token, field); - ValidateIdentifier(value, field); - return value; - } - - private static string ReadSha256(JToken token, string field) - { - var value = ReadString(token, field); - if (!Sha256Pattern.IsMatch(value)) - Invalid("manifest_schema_invalid", $"{field} is invalid."); - return value; - } - - private static string ReadString(JToken token, string field) - { - if (token.Type != JTokenType.String) - Invalid("manifest_schema_invalid", $"{field} must be a string."); - return token.Value()!; - } - - private static string? ReadNullableString(JToken token, string field) - { - if (token.Type == JTokenType.Null) - return null; - var value = ReadString(token, field); - if (value.Length > 256) - Invalid("manifest_schema_invalid", $"{field} must be a string or null."); - return value; - } - - private static long? ReadNullableSafeInteger(JToken token, string field) - { - if (token.Type == JTokenType.Null) - return null; - return ReadSafeInteger(token, field); - } - - private static long ReadSafeInteger(JToken token, string field) - { - if (token.Type != JTokenType.Integer && token.Type != JTokenType.Float) - Invalid("manifest_schema_invalid", $"{field} must be a non-negative safe integer."); - if ( - !decimal.TryParse( - token.ToString(Formatting.None), - NumberStyles.Float, - CultureInfo.InvariantCulture, - out var value - ) - || value != decimal.Truncate(value) - || value < 0 - || value > BundleLimitsV6.MaxSafeInteger - ) - Invalid("manifest_schema_invalid", $"{field} must be a non-negative safe integer."); - return decimal.ToInt64(value); - } - - private static void ValidateBundleId(string value) - { - if (!UlidV6Generator.IsCanonical(value)) - Invalid("manifest_schema_invalid", "bundle_id must be a canonical ULID."); - } - - private static void ValidateIdentifier(string? value, string field) - { - if (value == null || !IdentifierPattern.IsMatch(value)) - Invalid("manifest_schema_invalid", $"{field} is invalid."); - } - - private static void ValidateCreatedAt(long value) - { - ValidateSafeInteger(value, "created_at_ms"); - if (value > BundleLimitsV6.MaxCreatedAtMs) - Invalid( - "manifest_schema_invalid", - "created_at_ms is outside the supported date range." - ); - } - - private static void ValidateNullableString(string? value, string field) - { - if (value != null && value.Length > 256) - Invalid("manifest_schema_invalid", $"{field} must be a string or null."); - } - - private static void ValidateNullableSafeInteger(long? value, string field) - { - if (value.HasValue) - ValidateSafeInteger(value.Value, field); - } - - private static void ValidateSafeInteger(long value, string field) - { - if (value < 0 || value > BundleLimitsV6.MaxSafeInteger) - Invalid("manifest_schema_invalid", $"{field} must be a non-negative safe integer."); - } - - private static void ValidateDigest(byte[] bytes, string expected) - { - if (!string.Equals(ComputeSha256Hex(bytes), expected, StringComparison.Ordinal)) - throw new BundleV6Exception( - "segment_digest_mismatch", - "segment_digest_mismatch", - "A Bundle segment digest does not match its manifest." - ); - } - - private static byte[] ComputeSha256(ReadOnlySpan bytes) - { - using var sha256 = SHA256.Create(); - var digest = new byte[32]; - if (!sha256.TryComputeHash(bytes, digest, out var written) || written != digest.Length) - throw new InvalidOperationException("SHA-256 digest computation failed."); - return digest; - } - - private static string ToLowerHex(byte[] bytes) - { - var output = new char[bytes.Length * 2]; - const string alphabet = "0123456789abcdef"; - for (var index = 0; index < bytes.Length; index++) - { - output[index * 2] = alphabet[bytes[index] >> 4]; - output[index * 2 + 1] = alphabet[bytes[index] & 0x0F]; - } - return new string(output); - } - - private static string FormatContentDigest(byte[] digest) => - $"sha-256=:{Convert.ToBase64String(digest)}:"; - - private static uint ReadUInt32BigEndian(ReadOnlySpan bytes, int offset) => - ((uint)bytes[offset] << 24) - | ((uint)bytes[offset + 1] << 16) - | ((uint)bytes[offset + 2] << 8) - | bytes[offset + 3]; - - private static void WriteUInt32BigEndian(byte[] bytes, int offset, int value) - { - bytes[offset] = (byte)((uint)value >> 24); - bytes[offset + 1] = (byte)((uint)value >> 16); - bytes[offset + 2] = (byte)((uint)value >> 8); - bytes[offset + 3] = (byte)value; - } - - [DoesNotReturn] - private static void Invalid(string reason, string message) => - throw new BundleV6Exception("invalid_bundle", reason, message); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunBundleV6Contract.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunBundleV6Contract.cs deleted file mode 100644 index 70485c6..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunBundleV6Contract.cs +++ /dev/null @@ -1,179 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.ModApi.Bundle; - -internal enum RunBundleOpenFailureKind -{ - ContainerInvalid, - PayloadInvalid, - RunIdentityMismatch, -} - -internal sealed class RunBundleOpenResult -{ - private RunBundleOpenResult( - OpenedRunBundleV6? value, - RunBundleOpenFailureKind? failureKind, - string? reason, - Exception? exception - ) - { - Value = value; - FailureKind = failureKind; - Reason = reason; - Exception = exception; - } - - public OpenedRunBundleV6? Value { get; } - - public RunBundleOpenFailureKind? FailureKind { get; } - - public string? Reason { get; } - - public Exception? Exception { get; } - - public bool Succeeded => Value != null; - - internal static RunBundleOpenResult Success(OpenedRunBundleV6 value) => - new(value, null, null, null); - - internal static RunBundleOpenResult Failure( - RunBundleOpenFailureKind failureKind, - string reason, - Exception? exception = null - ) => new(null, failureKind, reason, exception); -} - -internal sealed class OpenedRunBundleV6 -{ - internal OpenedRunBundleV6(OpenedBundleV6 bundle, RunPayloadV6 payload) - { - Bundle = bundle; - Payload = payload; - } - - public OpenedBundleV6 Bundle { get; } - - public RunPayloadV6 Payload { get; } - - public bool TryGetReplayableBattle(string battleId, out RunBattleV6? battle) - { - battle = null; - if (string.IsNullOrWhiteSpace(battleId)) - return false; - if ( - Payload.ReplayableBattleIds == null - || Payload.Battles == null - || !Payload.ReplayableBattleIds.Contains(battleId, StringComparer.Ordinal) - ) - return false; - - RunBattleV6? matched = null; - foreach (var candidate in Payload.Battles) - { - if (!string.Equals(candidate.BattleId, battleId, StringComparison.Ordinal)) - continue; - if (matched != null) - return false; - matched = candidate; - } - - if (matched == null || !RunBundleV6Contract.IsReplayable(matched)) - return false; - battle = matched; - return true; - } -} - -internal static class RunBundleV6Contract -{ - private static readonly string[] RequiredCardSetLabels = - { - "player_hand", - "player_skills", - "opponent_hand", - "opponent_skills", - }; - - // Every collection reached here is checked for null even where the DTO declares a non-nullable - // collection with an initializer: well-formed MessagePack may encode `nil` for such a member, - // and the deserializer writes that null straight over the initializer. Decoded DTOs are - // untrusted input, so null-safe rejection is the contract, not defensive style. - public static bool IsReplayable(RunBattleV6? battle) - { - if ( - battle?.Replay - is not { - SpawnMessageBytes.Length: > 0, - CombatMessageBytes.Length: > 0, - DespawnMessageBytes.Length: > 0, - } - || battle.Snapshots?.CardSets == null - || battle.Snapshots.CardSets.Count != RequiredCardSetLabels.Length - ) - return false; - - foreach (var label in RequiredCardSetLabels) - { - BattleCardSetV6? matched = null; - foreach (var cardSet in battle.Snapshots.CardSets) - { - if (!string.Equals(cardSet.Label, label, StringComparison.Ordinal)) - continue; - if (matched != null) - return false; - matched = cardSet; - } - - if ( - matched == null - || string.Equals(matched.Status, "Missing", StringComparison.OrdinalIgnoreCase) - ) - return false; - } - - return true; - } - - public static RunBundleOpenResult Open(ReadOnlyMemory bundleBytes) - { - OpenedBundleV6 bundle; - try - { - bundle = BundleV6Codec.Open(bundleBytes); - } - catch (BundleV6Exception ex) - { - return RunBundleOpenResult.Failure( - RunBundleOpenFailureKind.ContainerInvalid, - ex.Reason, - ex - ); - } - - if (!RunPayloadV6Codec.TryDecode(bundle.RunPayload, out var payload, out var decodeReason)) - { - return RunBundleOpenResult.Failure( - RunBundleOpenFailureKind.PayloadInvalid, - decodeReason ?? "run_payload_invalid" - ); - } - - if ( - payload == null - || !string.Equals(payload.RunId, bundle.Manifest.Run.RunId, StringComparison.Ordinal) - || !string.Equals( - payload.PlayerAccountId, - bundle.Manifest.Run.PlayerAccountId, - StringComparison.Ordinal - ) - ) - { - return RunBundleOpenResult.Failure( - RunBundleOpenFailureKind.RunIdentityMismatch, - "run_identity_mismatch" - ); - } - - return RunBundleOpenResult.Success(new OpenedRunBundleV6(bundle, payload)); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunPayloadV6.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunPayloadV6.cs deleted file mode 100644 index b51b90d..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunPayloadV6.cs +++ /dev/null @@ -1,310 +0,0 @@ -#nullable enable -using MessagePack; - -namespace BazaarPlusPlus.ModApi.Bundle; - -[MessagePackObject] -public sealed class RunPayloadV6 -{ - [Key(0)] - public int PayloadFormatVersion { get; set; } = 6; - - [Key(1)] - public string RunId { get; set; } = string.Empty; - - [Key(2)] - public string PlayerAccountId { get; set; } = string.Empty; - - [Key(3)] - public RunFactsV6 Run { get; set; } = new(); - - [Key(4)] - public List Events { get; set; } = new(); - - [Key(5)] - public List Battles { get; set; } = new(); - - [Key(6)] - public List ReplayableBattleIds { get; set; } = new(); - - [Key(7)] - public PayloadDegradationV6 Degradation { get; set; } = new(); -} - -[MessagePackObject] -public sealed class RunFactsV6 -{ - [Key(0)] - public string Hero { get; set; } = string.Empty; - - [Key(1)] - public string GameMode { get; set; } = string.Empty; - - [Key(2)] - public int? Seed { get; set; } - - [Key(3)] - public long StartedAtMs { get; set; } - - [Key(4)] - public long? EndedAtMs { get; set; } - - [Key(5)] - public string Status { get; set; } = string.Empty; - - [Key(6)] - public int? Day { get; set; } - - [Key(7)] - public int? Hour { get; set; } - - [Key(8)] - public int? Victories { get; set; } - - [Key(9)] - public int? Losses { get; set; } - - [Key(10)] - public string? PlayerRank { get; set; } - - [Key(11)] - public int? PlayerRating { get; set; } - - [Key(12)] - public string? FinalPlayerRank { get; set; } - - [Key(13)] - public int? FinalPlayerRating { get; set; } - - [Key(14)] - public int? FinalPlayerRatingDelta { get; set; } - - [Key(15)] - public int? MaxHealth { get; set; } - - [Key(16)] - public int? Prestige { get; set; } - - [Key(17)] - public int? Level { get; set; } - - [Key(18)] - public int? Income { get; set; } - - [Key(19)] - public int? Gold { get; set; } - - [Key(20)] - public string? BuildChannel { get; set; } - - [Key(21)] - public string ModVersion { get; set; } = string.Empty; -} - -[MessagePackObject] -public sealed class RunEventV6 -{ - [Key(0)] - public long Seq { get; set; } - - [Key(1)] - public long TimestampMs { get; set; } - - [Key(2)] - public string Kind { get; set; } = string.Empty; - - [Key(3)] - public string PayloadJson { get; set; } = string.Empty; -} - -[MessagePackObject] -public sealed class RunBattleV6 -{ - [Key(0)] - public string BattleId { get; set; } = string.Empty; - - [Key(1)] - public BattleFactsV6 Facts { get; set; } = new(); - - [Key(2)] - public BattleParticipantsV6 Participants { get; set; } = new(); - - [Key(3)] - public BattleCardSnapshotsV6? Snapshots { get; set; } - - [Key(4)] - public BattleReplayV6? Replay { get; set; } -} - -[MessagePackObject] -public sealed class BattleFactsV6 -{ - [Key(0)] - public long RecordedAtMs { get; set; } - - [Key(1)] - public int? Day { get; set; } - - [Key(2)] - public int? Hour { get; set; } - - [Key(3)] - public string? EncounterId { get; set; } - - [Key(4)] - public string CombatKind { get; set; } = string.Empty; - - [Key(5)] - public string? Result { get; set; } - - [Key(6)] - public string? WinnerCombatantId { get; set; } - - [Key(7)] - public string? LoserCombatantId { get; set; } - - [Key(8)] - public bool IsFinalBattle { get; set; } -} - -[MessagePackObject] -public sealed class BattleParticipantsV6 -{ - [Key(0)] - public BattleParticipantV6 Player { get; set; } = new(); - - [Key(1)] - public BattleParticipantV6 Opponent { get; set; } = new(); -} - -[MessagePackObject] -public sealed class BattleParticipantV6 -{ - [Key(0)] - public string? AccountId { get; set; } - - [Key(1)] - public string? DisplayName { get; set; } - - [Key(2)] - public string? HeroName { get; set; } - - [Key(3)] - public string? Rank { get; set; } - - [Key(4)] - public int? Rating { get; set; } - - [Key(5)] - public int? Level { get; set; } - - [Key(6)] - public int? Prestige { get; set; } - - [Key(7)] - public int? Victories { get; set; } - - [Key(8)] - public int? Income { get; set; } - - [Key(9)] - public int? Gold { get; set; } - - [Key(10)] - public int? HandItemCount { get; set; } - - [Key(11)] - public int? SkillCount { get; set; } -} - -[MessagePackObject] -public sealed class BattleCardSnapshotsV6 -{ - [Key(0)] - public List CardSets { get; set; } = new(); -} - -[MessagePackObject] -public sealed class BattleCardSetV6 -{ - [Key(0)] - public string Label { get; set; } = string.Empty; - - [Key(1)] - public string? Status { get; set; } - - [Key(2)] - public string? Source { get; set; } - - [Key(3)] - public List Items { get; set; } = new(); -} - -[MessagePackObject] -public sealed class BattleCardV6 -{ - [Key(0)] - public string InstanceId { get; set; } = string.Empty; - - [Key(1)] - public string TemplateId { get; set; } = string.Empty; - - [Key(2)] - public int Type { get; set; } - - [Key(3)] - public int Size { get; set; } - - [Key(4)] - public int? Section { get; set; } - - [Key(5)] - public int? Socket { get; set; } - - [Key(6)] - public string? Name { get; set; } - - [Key(7)] - public string? Tier { get; set; } - - [Key(8)] - public string? Enchant { get; set; } - - [Key(9)] - public List Tags { get; set; } = new(); - - [Key(10)] - public Dictionary Attributes { get; set; } = new(); -} - -[MessagePackObject] -public sealed class BattleReplayV6 -{ - [Key(0)] - public int Version { get; set; } = 1; - - [Key(1)] - public byte[] SpawnMessageBytes { get; set; } = Array.Empty(); - - [Key(2)] - public byte[] CombatMessageBytes { get; set; } = Array.Empty(); - - [Key(3)] - public byte[] DespawnMessageBytes { get; set; } = Array.Empty(); -} - -[MessagePackObject] -public sealed class PayloadDegradationV6 -{ - [Key(0)] - public List Categories { get; set; } = new(); - - [Key(1)] - public List ReplayOmittedBattleIds { get; set; } = new(); - - [Key(2)] - public int EventsOmitted { get; set; } - - [Key(3)] - public bool ScreenshotOmitted { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunPayloadV6Codec.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunPayloadV6Codec.cs deleted file mode 100644 index 4eac648..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/RunPayloadV6Codec.cs +++ /dev/null @@ -1,80 +0,0 @@ -#nullable enable -using MessagePack; -using MessagePack.Resolvers; - -namespace BazaarPlusPlus.ModApi.Bundle; - -internal static class RunPayloadV6Codec -{ - public const int MaxDecompressedBytes = 64 * 1024 * 1024; - - private static readonly MessagePackSerializerOptions Options = MessagePackSerializerOptions - .Standard.WithResolver(ContractlessStandardResolverAllowPrivate.Instance) - .WithSecurity(MessagePackSecurity.UntrustedData); - - public static byte[] Encode(RunPayloadV6 payload) - { - if (payload == null) - throw new ArgumentNullException(nameof(payload)); - if (payload.PayloadFormatVersion != BundleLimitsV6.RunFormatVersion) - throw new ArgumentException("Run payload format version must be 6.", nameof(payload)); - - return MessagePackGzipFraming.Encode(payload, Options); - } - - public static RunPayloadV6 Decode(ReadOnlyMemory bytes) - { - if (!TryDecode(bytes, out var payload, out var reason)) - throw new InvalidDataException($"Run payload is invalid ({reason})."); - return payload!; - } - - public static bool TryDecode( - ReadOnlyMemory bytes, - out RunPayloadV6? payload, - out string? reason - ) - { - payload = null; - reason = null; - if (bytes.Length < 2) - { - reason = "run_payload_empty"; - return false; - } - var source = bytes.Span; - if (source[0] != 0x1F || source[1] != 0x8B) - { - reason = "run_payload_not_gzip"; - return false; - } - - var result = MessagePackGzipFraming.TryDecode( - bytes, - Options, - MaxDecompressedBytes - ); - if (!result.Succeeded) - { - reason = result.FailureKind switch - { - MessagePackGzipFailureKind.Empty => "run_payload_empty", - MessagePackGzipFailureKind.NotGzip => "run_payload_not_gzip", - MessagePackGzipFailureKind.DecompressedTooLarge => - "run_payload_decompressed_too_large", - MessagePackGzipFailureKind.DeserializedNull => "run_payload_deserialized_null", - _ => "run_payload_decode_failed", - }; - return false; - } - - payload = result.Value; - if (payload!.PayloadFormatVersion != BundleLimitsV6.RunFormatVersion) - { - payload = null; - reason = "unsupported_run_payload_version"; - return false; - } - return true; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/UlidV6Generator.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/UlidV6Generator.cs deleted file mode 100644 index 63f2f11..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Bundle/UlidV6Generator.cs +++ /dev/null @@ -1,118 +0,0 @@ -#nullable enable -using System.Security.Cryptography; - -namespace BazaarPlusPlus.ModApi.Bundle; - -internal sealed class UlidV6Generator -{ - private const long MaxTimestamp = 281_474_976_710_655; - private const string Alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; - private readonly Func _clock; - private readonly Action _fillRandom; - private readonly object _sync = new(); - private readonly byte[] _lastRandom = new byte[10]; - private long _lastTimestamp = -1; - - public UlidV6Generator() - : this( - () => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), - bytes => - { - using var random = RandomNumberGenerator.Create(); - random.GetBytes(bytes); - } - ) { } - - public UlidV6Generator(Func clock, Action fillRandom) - { - _clock = clock ?? throw new ArgumentNullException(nameof(clock)); - _fillRandom = fillRandom ?? throw new ArgumentNullException(nameof(fillRandom)); - } - - public string Next() - { - lock (_sync) - { - var timestamp = _clock(); - if (timestamp < 0 || timestamp > MaxTimestamp) - throw new ArgumentOutOfRangeException(nameof(timestamp)); - - if (timestamp > _lastTimestamp) - { - _fillRandom(_lastRandom); - _lastTimestamp = timestamp; - } - else - { - timestamp = _lastTimestamp; - if (!Increment(_lastRandom)) - { - if (timestamp == MaxTimestamp) - throw new InvalidOperationException( - "ULID timestamp and randomness overflowed." - ); - timestamp += 1; - Array.Clear(_lastRandom, 0, _lastRandom.Length); - _lastTimestamp = timestamp; - } - } - - return Encode(timestamp, _lastRandom); - } - } - - public static bool IsCanonical(string? value) - { - if (value == null || value.Length != 26 || value[0] > '7') - return false; - foreach (var character in value) - { - if (Alphabet.IndexOf(character) < 0) - return false; - } - return true; - } - - public static string Encode(long timestampMs, ReadOnlySpan randomness) - { - if (timestampMs < 0 || timestampMs > MaxTimestamp) - throw new ArgumentOutOfRangeException(nameof(timestampMs)); - if (randomness.Length != 10) - throw new ArgumentException( - "ULID randomness must contain exactly 10 bytes.", - nameof(randomness) - ); - - var output = new char[26]; - var timestamp = timestampMs; - for (var index = 9; index >= 0; index--) - { - output[index] = Alphabet[(int)(timestamp & 31)]; - timestamp >>= 5; - } - - for (var group = 0; group < 16; group++) - { - var value = 0; - for (var bit = 0; bit < 5; bit++) - { - var bitIndex = group * 5 + bit; - value = (value << 1) | ((randomness[bitIndex / 8] >> (7 - bitIndex % 8)) & 1); - } - output[10 + group] = Alphabet[value]; - } - - return new string(output); - } - - private static bool Increment(byte[] value) - { - for (var index = value.Length - 1; index >= 0; index--) - { - value[index]++; - if (value[index] != 0) - return true; - } - return false; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/BazaarDbLinkClient.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/BazaarDbLinkClient.cs deleted file mode 100644 index ff9c88a..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/BazaarDbLinkClient.cs +++ /dev/null @@ -1,168 +0,0 @@ -#nullable enable -using System.Text; -using BazaarPlusPlus.ModApi.Http; -using BazaarPlusPlus.ModApi.Models; -using Newtonsoft.Json; - -namespace BazaarPlusPlus.ModApi.Clients; - -internal enum BazaarDbLinkOutcome -{ - Linked, - InvalidOrExpired, - AlreadyLinked, - MissingFields, - ServerError, - Transport, -} - -internal readonly struct BazaarDbLinkResult -{ - private BazaarDbLinkResult(BazaarDbLinkOutcome outcome, int? statusCode, ModApiFailure? failure) - { - Outcome = outcome; - StatusCode = statusCode; - Failure = failure; - } - - public BazaarDbLinkOutcome Outcome { get; } - - public int? StatusCode { get; } - - public ModApiFailure? Failure { get; } - public string? Error => Failure?.UserCode; - public Exception? DiagnosticException => Failure?.DiagnosticException; - - public bool Succeeded => Outcome == BazaarDbLinkOutcome.Linked; - - public static BazaarDbLinkResult Linked(int statusCode) => - new(BazaarDbLinkOutcome.Linked, statusCode, null); - - public static BazaarDbLinkResult From(BazaarDbLinkOutcome o, int? status, string? error) => - new(o, status, error == null ? null : new ModApiFailure(error)); - - internal static BazaarDbLinkResult Failed( - BazaarDbLinkOutcome outcome, - int? statusCode, - ModApiFailure failure - ) => new(outcome, statusCode, failure); -} - -/// -/// Redeems a one-time BazaarDB profile-link code. Posts to a fixed full URI, no auth header. -/// Code is trimmed only (case-sensitive alphabet). 409 means already linked to a different -/// BazaarDB user and is permanent. -/// -internal sealed class BazaarDbLinkClient : IDisposable -{ - public const string DefaultRedeemEndpoint = "https://bazaardb.gg/api/profile/link/redeem"; - - private readonly HttpClient _httpClient; - private readonly Uri _redeemEndpoint; - - public BazaarDbLinkClient(HttpClient httpClient, Uri redeemEndpoint) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _redeemEndpoint = redeemEndpoint ?? throw new ArgumentNullException(nameof(redeemEndpoint)); - } - - public void Dispose() - { - _httpClient.Dispose(); - } - - public async Task RedeemAsync( - string code, - string accountId, - CancellationToken cancellationToken - ) - { - var trimmedCode = code?.Trim() ?? string.Empty; - if (trimmedCode.Length == 0 || string.IsNullOrWhiteSpace(accountId)) - return BazaarDbLinkResult.From(BazaarDbLinkOutcome.MissingFields, 400, "missing_field"); - - var payload = new BazaarDbProfileLinkRedeemRequest - { - Code = trimmedCode, - AccountId = accountId, - }; - try - { - var bodyBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload)); - using var request = new HttpRequestMessage(HttpMethod.Post, _redeemEndpoint) - { - Content = new ByteArrayContent(bodyBytes), - }; - request.Content.Headers.ContentType = new("application/json"); - using var response = await _httpClient - .SendAsync(request, cancellationToken) - .ConfigureAwait(false); - var result = await ModApiResponse - .ReadAsync(response, ModApiBodyReadPolicy.Json, cancellationToken) - .ConfigureAwait(false); - - if (result.IsSuccess) - return BazaarDbLinkResult.Linked(result.StatusCode); - - return Classify(result); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - return BazaarDbLinkResult.Failed( - BazaarDbLinkOutcome.Transport, - null, - new ModApiFailure("transport_error", diagnosticException: ex) - ); - } - } - - private static BazaarDbLinkResult Classify(ModApiResponse response) - { - var statusCode = response.StatusCode; - var error = response.Error.Code; - - if (error == "already_linked" || statusCode == 409) - return BazaarDbLinkResult.Failed( - BazaarDbLinkOutcome.AlreadyLinked, - statusCode, - new ModApiFailure("already_linked", response: response) - ); - if (error == "invalid_or_expired") - return BazaarDbLinkResult.Failed( - BazaarDbLinkOutcome.InvalidOrExpired, - statusCode, - new ModApiFailure("invalid_or_expired", response: response) - ); - if (IsMissingFieldError(error)) - return BazaarDbLinkResult.Failed( - BazaarDbLinkOutcome.MissingFields, - statusCode, - new ModApiFailure("missing_field", response: response) - ); - if (statusCode >= 500) - return BazaarDbLinkResult.Failed( - BazaarDbLinkOutcome.ServerError, - statusCode, - new ModApiFailure("server_error", response: response) - ); - - return BazaarDbLinkResult.Failed( - BazaarDbLinkOutcome.InvalidOrExpired, - statusCode, - new ModApiFailure("invalid_or_expired", response: response) - ); - } - - private static bool IsMissingFieldError(string? error) - { - if (error == null) - return false; - - return error.StartsWith("Missing", StringComparison.Ordinal) - || error.StartsWith("missing_", StringComparison.OrdinalIgnoreCase); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/BundleUploadClient.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/BundleUploadClient.cs deleted file mode 100644 index cdaac4e..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/BundleUploadClient.cs +++ /dev/null @@ -1,209 +0,0 @@ -#nullable enable -using System.Net.Http.Headers; -using BazaarPlusPlus.ModApi.Http; -using Newtonsoft.Json.Linq; - -namespace BazaarPlusPlus.ModApi.Clients; - -internal sealed class BundleUploadClient -{ - private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds( - ModApiUploadDefaults.RequestTimeoutSeconds - ); - private readonly HttpClient _httpClient; - private readonly ModApiRoutes _routes; - - public BundleUploadClient(HttpClient httpClient, ModApiRoutes routes) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _routes = routes ?? throw new ArgumentNullException(nameof(routes)); - } - - public async Task UploadAsync( - Stream sealedFile, - long contentLength, - string contentDigest, - string expectedBundleId, - string expectedRunId, - CancellationToken cancellationToken - ) - { - if (sealedFile == null) - throw new ArgumentNullException(nameof(sealedFile)); - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeout.CancelAfter(RequestTimeout); - try - { - using var request = new HttpRequestMessage(HttpMethod.Post, _routes.UploadBundle); - request.Content = new StreamContent(sealedFile); - request.Content.Headers.ContentType = new MediaTypeHeaderValue( - Bundle.BundleLimitsV6.BundleContentType - ); - request.Content.Headers.ContentLength = contentLength; - request.Headers.TryAddWithoutValidation("Content-Digest", contentDigest); - using var response = await _httpClient - .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token) - .ConfigureAwait(false); - var parsed = await ModApiResponse - .ReadAsync(response, ModApiBodyReadPolicy.Json, timeout.Token) - .ConfigureAwait(false); - return Classify(parsed, expectedBundleId, expectedRunId); - } - catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) - { - return BundleUploadResponse.Transient("request_timeout"); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - return BundleUploadResponse.Transient("transport_error", diagnosticException: ex); - } - } - - private static BundleUploadResponse Classify( - ModApiResponse response, - string expectedBundleId, - string expectedRunId - ) - { - var statusCode = response.StatusCode; - if (response.IsSuccess && statusCode is 200 or 201) - { - try - { - var receipt = JObject.Parse(response.Body); - var bundleId = receipt["bundle_id"]?.Value(); - var runId = receipt["run_id"]?.Value(); - var outcome = receipt["outcome"]?.Value(); - var delivery = receipt["bazaardb_delivery"]?.Value(); - var validOutcome = statusCode == 201 ? outcome == "stored" : outcome == "duplicate"; - var validDelivery = delivery is "created" or "existing" or "not_applicable"; - if ( - bundleId != expectedBundleId - || runId != expectedRunId - || !validOutcome - || !validDelivery - ) - return BundleUploadResponse.Transient( - "invalid_success_receipt", - requestId: response.RequestId - ); - return BundleUploadResponse.Uploaded(outcome!, response.RequestId); - } - catch - { - return BundleUploadResponse.Transient( - "invalid_success_receipt", - requestId: response.RequestId - ); - } - } - - var envelope = response.Error; - var code = response.UserCode; - var trustedConflict = envelope.Shape == ModApiEnvelopeShape.Nested; - if (statusCode == 409 && trustedConflict && envelope.Code == "run_already_bundled") - return BundleUploadResponse.Equivalent("run_already_bundled", response.RequestId); - if (statusCode == 409 && trustedConflict && envelope.Code == "bundle_id_conflict") - return BundleUploadResponse.Permanent( - "bundle_id_conflict", - envelope.Message, - response.RequestId - ); - if (statusCode == 409) - return BundleUploadResponse.Transient( - code, - requestId: response.RequestId, - retryAfterSeconds: response.RetryAfterSeconds - ); - if (statusCode is 400 or 411 or 413 or 415 or 422) - return BundleUploadResponse.Permanent(code, envelope.Message, response.RequestId); - if (statusCode is 408 or 429 || statusCode >= 500 || envelope.Retryable == true) - return BundleUploadResponse.Transient( - code, - envelope.Message, - response.RequestId, - response.RetryAfterSeconds - ); - if (envelope.Shape != ModApiEnvelopeShape.None) - return envelope.Retryable == false - ? BundleUploadResponse.Permanent(code, envelope.Message, response.RequestId) - : BundleUploadResponse.Transient( - code, - envelope.Message, - response.RequestId, - response.RetryAfterSeconds - ); - return BundleUploadResponse.Transient(code, requestId: response.RequestId); - } -} - -internal enum BundleUploadDisposition -{ - Uploaded, - Equivalent, - Permanent, - Transient, -} - -internal sealed class BundleUploadResponse -{ - private BundleUploadResponse( - BundleUploadDisposition disposition, - string code, - string? detail, - string? requestId, - string? outcome, - int? retryAfterSeconds, - Exception? diagnosticException - ) - { - Disposition = disposition; - Code = code; - Detail = detail; - RequestId = requestId; - Outcome = outcome; - RetryAfterSeconds = retryAfterSeconds; - DiagnosticException = diagnosticException; - } - - public BundleUploadDisposition Disposition { get; } - public string Code { get; } - public string? Detail { get; } - public string? RequestId { get; } - public string? Outcome { get; } - public int? RetryAfterSeconds { get; } - public Exception? DiagnosticException { get; } - - public static BundleUploadResponse Uploaded(string outcome, string? requestId) => - new(BundleUploadDisposition.Uploaded, outcome, null, requestId, outcome, null, null); - - public static BundleUploadResponse Equivalent(string code, string? requestId) => - new(BundleUploadDisposition.Equivalent, code, null, requestId, code, null, null); - - public static BundleUploadResponse Permanent( - string code, - string? detail = null, - string? requestId = null - ) => new(BundleUploadDisposition.Permanent, code, detail, requestId, null, null, null); - - public static BundleUploadResponse Transient( - string code, - string? detail = null, - string? requestId = null, - int? retryAfterSeconds = null, - Exception? diagnosticException = null - ) => - new( - BundleUploadDisposition.Transient, - code, - detail, - requestId, - null, - retryAfterSeconds, - diagnosticException - ); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/GhostBattleClient.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/GhostBattleClient.cs deleted file mode 100644 index c2f8bed..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/GhostBattleClient.cs +++ /dev/null @@ -1,348 +0,0 @@ -#nullable enable -using System.Globalization; -using BazaarPlusPlus.ModApi.Bundle; -using BazaarPlusPlus.ModApi.Http; -using BazaarPlusPlus.ModApi.Models; -using Newtonsoft.Json.Linq; - -namespace BazaarPlusPlus.ModApi.Clients; - -internal sealed class GhostBattleClient -{ - private readonly HttpClient _httpClient; - private readonly ModApiRoutes _routes; - - public GhostBattleClient(HttpClient httpClient, ModApiRoutes routes) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _routes = routes ?? throw new ArgumentNullException(nameof(routes)); - } - - public async Task QueryAgainstMeAsync( - string playerAccountId, - int limit, - CancellationToken cancellationToken - ) - { - if (string.IsNullOrWhiteSpace(playerAccountId)) - return GhostBattleQueryResult.Failure("player_account_id_required"); - - try - { - var endpoint = new UriBuilder(_routes.QueryGhostBattles) - { - Query = - $"player_account_id={Uri.EscapeDataString(playerAccountId.Trim())}&limit={Math.Clamp(limit, 1, 200)}", - }.Uri.ToString(); - using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); - using var response = await _httpClient - .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken) - .ConfigureAwait(false); - var parsed = await ModApiResponse - .ReadAsync(response, ModApiBodyReadPolicy.Json, cancellationToken) - .ConfigureAwait(false); - if (!parsed.IsSuccess) - { - return GhostBattleQueryResult.Failure( - new ModApiFailure(parsed.UserCode, response: parsed), - parsed.StatusCode, - parsed.RetryAfterSeconds - ); - } - - var battlesToken = JObject.Parse(parsed.Body)["battles"] as JArray; - var records = new List(); - if (battlesToken != null) - { - foreach (var child in battlesToken) - { - if (child is JObject battle && TryParseBattle(battle, out var record)) - records.Add(record); - } - } - - return GhostBattleQueryResult.Success(records); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - return GhostBattleQueryResult.Failure( - new ModApiFailure("transport_error", diagnosticException: ex) - ); - } - } - - public async Task DownloadBundleAsync( - string downloadUrl, - CancellationToken cancellationToken - ) - { - if (!Uri.TryCreate(downloadUrl, UriKind.Absolute, out var uri)) - return GhostBundleDownloadResult.Failure("download_url_invalid"); - - try - { - using var request = new HttpRequestMessage(HttpMethod.Get, uri); - using var response = await _httpClient - .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken) - .ConfigureAwait(false); - if (!response.IsSuccessStatusCode) - { - var parsed = await ModApiResponse - .ReadAsync( - response, - new ModApiBodyReadPolicy(16 * 1024, "bundle_too_large"), - cancellationToken - ) - .ConfigureAwait(false); - return GhostBundleDownloadResult.Failure( - new ModApiFailure(parsed.UserCode, response: parsed), - parsed.StatusCode - ); - } - - var declaredLength = response.Content.Headers.ContentLength; - if (declaredLength.HasValue && declaredLength.Value > BundleLimitsV6.MaxBundleBytes) - return GhostBundleDownloadResult.Failure("bundle_too_large"); - - var bytes = await ReadBoundedAsync( - response.Content, - BundleLimitsV6.MaxBundleBytes, - cancellationToken - ) - .ConfigureAwait(false); - return GhostBundleDownloadResult.Success(bytes); - } - catch (GhostDownloadLimitException) - { - return GhostBundleDownloadResult.Failure("bundle_too_large"); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - return GhostBundleDownloadResult.Failure( - new ModApiFailure("transport_error", diagnosticException: ex) - ); - } - } - - private static async Task ReadBoundedAsync( - HttpContent content, - int maxBytes, - CancellationToken cancellationToken - ) - { - using var stream = await content.ReadAsStreamAsync().ConfigureAwait(false); - using var output = new MemoryStream(); - var buffer = new byte[81920]; - while (true) - { - var read = await stream - .ReadAsync(buffer, 0, buffer.Length, cancellationToken) - .ConfigureAwait(false); - if (read == 0) - return output.ToArray(); - if (output.Length + read > maxBytes) - throw new GhostDownloadLimitException(); - output.Write(buffer, 0, read); - } - } - - private static bool TryParseBattle(JObject battle, out GhostBattleImportRecord record) - { - record = null!; - var battleId = ReadString(battle, "battle_id"); - var bundleId = ReadString(battle, "bundle_id"); - var downloadUrl = ReadString(battle, "download_url"); - if ( - string.IsNullOrEmpty(battleId) - || string.IsNullOrEmpty(bundleId) - || string.IsNullOrEmpty(downloadUrl) - || !TryReadUnixMilliseconds(battle["recorded_at_ms"], out var recordedAt) - || !TryReadUnixMilliseconds(battle["download_expires_at_ms"], out var expiresAt) - || battle["player"] is not JObject player - || battle["opponent"] is not JObject opponent - ) - return false; - - var uploaderAccountId = ReadString(player, "account_id"); - var opponentAccountId = ReadString(opponent, "account_id"); - if (string.IsNullOrEmpty(uploaderAccountId) || string.IsNullOrEmpty(opponentAccountId)) - return false; - - record = new GhostBattleImportRecord - { - BattleId = battleId, - BundleId = bundleId, - DownloadUrl = downloadUrl, - DownloadExpiresAtUtc = expiresAt, - RecordedAtUtc = recordedAt, - Day = ReadNonNegativeInt(battle, "day"), - Hour = ReadNonNegativeInt(battle, "hour"), - EncounterId = ReadString(battle, "encounter_id"), - PlayerName = ReadString(player, "display_name") ?? string.Empty, - PlayerAccountId = uploaderAccountId, - PlayerHero = ReadString(player, "hero_name"), - PlayerRank = ReadString(player, "rank"), - PlayerRating = ReadNonNegativeInt(player, "rating"), - PlayerLevel = ReadNonNegativeInt(player, "level"), - PlayerPrestige = ReadNonNegativeInt(player, "prestige"), - PlayerVictories = ReadNonNegativeInt(player, "victories"), - OpponentName = ReadString(opponent, "display_name") ?? string.Empty, - OpponentAccountId = opponentAccountId, - OpponentHero = ReadString(opponent, "hero_name"), - OpponentRank = ReadString(opponent, "rank"), - OpponentRating = ReadNonNegativeInt(opponent, "rating"), - OpponentLevel = ReadNonNegativeInt(opponent, "level"), - OpponentPrestige = ReadNonNegativeInt(opponent, "prestige"), - OpponentVictories = ReadNonNegativeInt(opponent, "victories"), - CombatKind = ReadString(battle, "combat_kind") ?? "pvp", - Result = NormalizeResult(ReadString(battle, "result")), - WinnerCombatantId = ReadString(battle, "winner_combatant_id"), - LoserCombatantId = ReadString(battle, "loser_combatant_id"), - IsFinalBattle = battle["is_final_battle"]?.Value() ?? false, - }; - return record.Day.HasValue && record.Hour.HasValue; - } - - private static string NormalizeResult(string? value) => - value != null - && ( - string.Equals(value, "win", StringComparison.OrdinalIgnoreCase) - || string.Equals(value, "loss", StringComparison.OrdinalIgnoreCase) - || string.Equals(value, "unknown", StringComparison.OrdinalIgnoreCase) - ) - ? value.ToLowerInvariant() - : "unknown"; - - private static string? ReadString(JObject source, string name) - { - var value = - source[name]?.Type == JTokenType.String ? source[name]?.Value()?.Trim() : null; - return string.IsNullOrEmpty(value) ? null : value; - } - - private static int? ReadNonNegativeInt(JObject source, string name) - { - var token = source[name]; - if (token == null || token.Type == JTokenType.Null) - return null; - if ( - !long.TryParse( - token.ToString(), - NumberStyles.Integer, - CultureInfo.InvariantCulture, - out var value - ) - ) - return null; - return value is >= 0 and <= int.MaxValue ? (int)value : null; - } - - private static bool TryReadUnixMilliseconds(JToken? token, out DateTimeOffset value) - { - value = default; - if ( - token == null - || !long.TryParse( - token.ToString(), - NumberStyles.Integer, - CultureInfo.InvariantCulture, - out var milliseconds - ) - || milliseconds < 0 - ) - return false; - try - { - value = DateTimeOffset.FromUnixTimeMilliseconds(milliseconds); - return true; - } - catch (ArgumentOutOfRangeException) - { - return false; - } - } - - private sealed class GhostDownloadLimitException : Exception { } -} - -internal readonly struct GhostBattleQueryResult -{ - private GhostBattleQueryResult( - bool succeeded, - IReadOnlyList? battles, - ModApiFailure? failure, - int? statusCode, - int? retryAfterSeconds - ) - { - Succeeded = succeeded; - Battles = battles ?? Array.Empty(); - FailureInfo = failure; - StatusCode = statusCode; - RetryAfterSeconds = retryAfterSeconds; - } - - public bool Succeeded { get; } - public IReadOnlyList Battles { get; } - public ModApiFailure? FailureInfo { get; } - public string? Error => FailureInfo?.UserCode; - public Exception? DiagnosticException => FailureInfo?.DiagnosticException; - public int? StatusCode { get; } - public int? RetryAfterSeconds { get; } - - public static GhostBattleQueryResult Success(IReadOnlyList battles) => - new(true, battles, null, null, null); - - public static GhostBattleQueryResult Failure( - ModApiFailure failure, - int? statusCode = null, - int? retryAfterSeconds = null - ) => new(false, null, failure, statusCode, retryAfterSeconds); - - public static GhostBattleQueryResult Failure( - string error, - int? statusCode = null, - int? retryAfterSeconds = null - ) => Failure(new ModApiFailure(error), statusCode, retryAfterSeconds); -} - -internal readonly struct GhostBundleDownloadResult -{ - private GhostBundleDownloadResult( - bool succeeded, - byte[]? bytes, - ModApiFailure? failure, - int? statusCode - ) - { - Succeeded = succeeded; - Bytes = bytes; - FailureInfo = failure; - StatusCode = statusCode; - } - - public bool Succeeded { get; } - public byte[]? Bytes { get; } - public ModApiFailure? FailureInfo { get; } - public string? Error => FailureInfo?.UserCode; - public Exception? DiagnosticException => FailureInfo?.DiagnosticException; - public int? StatusCode { get; } - - public static GhostBundleDownloadResult Success(byte[] bytes) => new(true, bytes, null, null); - - public static GhostBundleDownloadResult Failure( - ModApiFailure failure, - int? statusCode = null - ) => new(false, null, failure, statusCode); - - public static GhostBundleDownloadResult Failure(string error, int? statusCode = null) => - Failure(new ModApiFailure(error), statusCode); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/ModApiHealthClient.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/ModApiHealthClient.cs deleted file mode 100644 index 10fd38e..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/ModApiHealthClient.cs +++ /dev/null @@ -1,126 +0,0 @@ -#nullable enable -using System.Diagnostics; -using BazaarPlusPlus.ModApi.Http; -using BazaarPlusPlus.ModApi.Models; -using Newtonsoft.Json; - -namespace BazaarPlusPlus.ModApi.Clients; - -internal sealed class ModApiHealthClient -{ - private readonly HttpClient _httpClient; - private readonly ModApiRoutes _routes; - - public ModApiHealthClient(HttpClient httpClient, ModApiRoutes routes) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _routes = routes ?? throw new ArgumentNullException(nameof(routes)); - } - - public async Task ProbeAsync(CancellationToken cancellationToken) - { - var stopwatch = Stopwatch.StartNew(); - try - { - using var response = await _httpClient - .GetAsync(_routes.Health, cancellationToken) - .ConfigureAwait(false); - var parsedResponse = await ModApiResponse - .ReadAsync(response, ModApiBodyReadPolicy.Json, cancellationToken) - .ConfigureAwait(false); - stopwatch.Stop(); - - if (!parsedResponse.IsSuccess) - return ModApiHealthProbeResult.FailureFrom( - stopwatch.ElapsedMilliseconds, - new ModApiFailure(parsedResponse.UserCode, response: parsedResponse) - ); - - ModApiHealthResponse? parsed; - try - { - parsed = JsonConvert.DeserializeObject(parsedResponse.Body); - } - catch (JsonException) - { - return ModApiHealthProbeResult.Failure( - stopwatch.ElapsedMilliseconds, - "server_time_invalid" - ); - } - if ( - parsed == null - || !string.Equals(parsed.Status, "ok", StringComparison.OrdinalIgnoreCase) - ) - { - return ModApiHealthProbeResult.Failure( - stopwatch.ElapsedMilliseconds, - "health_status_not_ok" - ); - } - - if (!parsed.ServerTimeMs.HasValue) - return ModApiHealthProbeResult.Failure( - stopwatch.ElapsedMilliseconds, - "server_time_invalid" - ); - // server_time_ms is part of the health contract: reject an out-of-range value. - try - { - _ = DateTimeOffset.FromUnixTimeMilliseconds(parsed.ServerTimeMs.Value); - } - catch (ArgumentOutOfRangeException) - { - return ModApiHealthProbeResult.Failure( - stopwatch.ElapsedMilliseconds, - "server_time_invalid" - ); - } - - return ModApiHealthProbeResult.Success(stopwatch.ElapsedMilliseconds); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - stopwatch.Stop(); - return ModApiHealthProbeResult.FailureFrom( - stopwatch.ElapsedMilliseconds, - new ModApiFailure("transport_error", diagnosticException: ex) - ); - } - } -} - -internal readonly struct ModApiHealthProbeResult -{ - private ModApiHealthProbeResult( - bool succeeded, - long roundTripMilliseconds, - ModApiFailure? failure - ) - { - Succeeded = succeeded; - RoundTripMilliseconds = roundTripMilliseconds; - FailureInfo = failure; - } - - public bool Succeeded { get; } - public long RoundTripMilliseconds { get; } - public ModApiFailure? FailureInfo { get; } - public string? Error => FailureInfo?.UserCode; - public Exception? DiagnosticException => FailureInfo?.DiagnosticException; - - public static ModApiHealthProbeResult Success(long roundTripMilliseconds) => - new(true, roundTripMilliseconds, null); - - public static ModApiHealthProbeResult Failure(long roundTripMilliseconds, string error) => - FailureFrom(roundTripMilliseconds, new ModApiFailure(error)); - - internal static ModApiHealthProbeResult FailureFrom( - long roundTripMilliseconds, - ModApiFailure failure - ) => new(false, roundTripMilliseconds, failure); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/ModApiSession.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/ModApiSession.cs deleted file mode 100644 index 4bcf4ed..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Clients/ModApiSession.cs +++ /dev/null @@ -1,79 +0,0 @@ -#nullable enable -using BazaarPlusPlus.ModApi.Http; - -namespace BazaarPlusPlus.ModApi.Clients; - -internal sealed class ModApiSession : IDisposable -{ - private readonly HttpClient _httpClient; - private readonly BundleUploadClient _bundleUpload; - private readonly GhostBattleClient _ghostBattles; - private readonly ModApiHealthClient _health; - private int _disposed; - - private ModApiSession(HttpClient httpClient, ModApiRoutes routes) - { - _httpClient = httpClient; - _bundleUpload = new BundleUploadClient(httpClient, routes); - _ghostBattles = new GhostBattleClient(httpClient, routes); - _health = new ModApiHealthClient(httpClient, routes); - } - - public static ModApiSession? TryCreate( - string? apiBaseUrl, - string productVersion, - string userAgentSuffix, - TimeSpan timeout, - HttpMessageHandler? handler = null - ) - { - var routes = ModApiRoutes.TryCreate(apiBaseUrl); - if (routes == null) - return null; - var httpClient = BppHttpClientFactory.Create( - productVersion, - userAgentSuffix, - timeout, - handler - ); - return new ModApiSession(httpClient, routes); - } - - public Task UploadBundleAsync( - Stream sealedFile, - long contentLength, - string contentDigest, - string expectedBundleId, - string expectedRunId, - CancellationToken cancellationToken - ) => - _bundleUpload.UploadAsync( - sealedFile, - contentLength, - contentDigest, - expectedBundleId, - expectedRunId, - cancellationToken - ); - - public Task QueryGhostBattlesAgainstMeAsync( - string playerAccountId, - int limit, - CancellationToken cancellationToken - ) => _ghostBattles.QueryAgainstMeAsync(playerAccountId, limit, cancellationToken); - - public Task DownloadGhostBundleAsync( - string downloadUrl, - CancellationToken cancellationToken - ) => _ghostBattles.DownloadBundleAsync(downloadUrl, cancellationToken); - - public Task ProbeHealthAsync(CancellationToken cancellationToken) => - _health.ProbeAsync(cancellationToken); - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - _httpClient.Dispose(); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Http/BppHttpClientFactory.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Http/BppHttpClientFactory.cs deleted file mode 100644 index 43c4dec..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Http/BppHttpClientFactory.cs +++ /dev/null @@ -1,97 +0,0 @@ -#nullable enable -using System.Net.Http.Headers; - -namespace BazaarPlusPlus.ModApi.Http; - -internal static class BppHttpClientFactory -{ - private const string ProductName = "BazaarPlusPlus"; - - // Each consumer passes its own userAgentSuffix (BundleUpload, OnlineClient, ...). The backend - // groups its metrics and rate limits by that suffix, so keep the suffixes owner-specific: - // collapsing them into one shared token silently re-buckets server-side traffic. - - public static HttpClient Create( - string productVersion, - string? userAgentSuffix = null, - TimeSpan? timeout = null, - HttpMessageHandler? handler = null - ) - { - var client = handler == null ? new HttpClient() : new HttpClient(handler); - if (timeout.HasValue) - client.Timeout = timeout.Value; - - ApplyUserAgent(client, productVersion, userAgentSuffix); - return client; - } - - private static void ApplyUserAgent( - HttpClient client, - string productVersion, - string? userAgentSuffix - ) - { - var version = SanitizeUserAgentToken(productVersion) ?? "0.0.0"; - client.DefaultRequestHeaders.UserAgent.Add( - new ProductInfoHeaderValue(ProductName, version) - ); - - var sanitizedSuffix = SanitizeUserAgentToken(userAgentSuffix); - if (sanitizedSuffix != null) - { - client.DefaultRequestHeaders.UserAgent.Add( - new ProductInfoHeaderValue(sanitizedSuffix, version) - ); - } - } - - private static string? SanitizeUserAgentToken(string? value) - { - if (string.IsNullOrWhiteSpace(value)) - return null; - - // RFC 7230 token chars; replace anything else with '-' so a flaky version string never - // throws inside ProductInfoHeaderValue during plugin startup. - var trimmed = value.Trim(); - var buffer = new char[trimmed.Length]; - for (var i = 0; i < trimmed.Length; i++) - { - var c = trimmed[i]; - buffer[i] = IsTokenChar(c) ? c : '-'; - } - - return new string(buffer); - } - - private static bool IsTokenChar(char c) - { - if (c >= 'A' && c <= 'Z') - return true; - if (c >= 'a' && c <= 'z') - return true; - if (c >= '0' && c <= '9') - return true; - switch (c) - { - case '!': - case '#': - case '$': - case '%': - case '&': - case '\'': - case '*': - case '+': - case '-': - case '.': - case '^': - case '_': - case '`': - case '|': - case '~': - return true; - default: - return false; - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Http/ModApiResponse.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Http/ModApiResponse.cs deleted file mode 100644 index 9cc00dd..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Http/ModApiResponse.cs +++ /dev/null @@ -1,247 +0,0 @@ -#nullable enable -using System.Text; -using Newtonsoft.Json.Linq; - -namespace BazaarPlusPlus.ModApi.Http; - -internal enum ModApiEnvelopeShape -{ - None, - Nested, - LegacyTopLevel, -} - -internal readonly struct ModApiErrorEnvelope -{ - public ModApiErrorEnvelope( - ModApiEnvelopeShape shape, - string? code, - string? message, - bool? retryable, - string? requestId - ) - { - Shape = shape; - Code = code; - Message = message; - Retryable = retryable; - RequestId = requestId; - } - - public ModApiEnvelopeShape Shape { get; } - public string? Code { get; } - public string? Message { get; } - public bool? Retryable { get; } - public string? RequestId { get; } -} - -internal readonly struct ModApiBodyReadPolicy -{ - public ModApiBodyReadPolicy(int maxBytes, string overflowUserCode) - { - MaxBytes = maxBytes; - OverflowUserCode = overflowUserCode; - } - - public int MaxBytes { get; } - public string OverflowUserCode { get; } - - public static ModApiBodyReadPolicy Json { get; } = new(1024 * 1024, "response_too_large"); -} - -internal sealed class ModApiResponse -{ - private ModApiResponse( - int statusCode, - bool isSuccess, - string body, - ModApiErrorEnvelope error, - string? requestId, - int? retryAfterSeconds, - string userCode - ) - { - StatusCode = statusCode; - IsSuccess = isSuccess; - Body = body; - Error = error; - RequestId = requestId; - RetryAfterSeconds = retryAfterSeconds; - UserCode = userCode; - } - - public int StatusCode { get; } - public bool IsSuccess { get; } - public string Body { get; } - public ModApiErrorEnvelope Error { get; } - public string? RequestId { get; } - public int? RetryAfterSeconds { get; } - public string UserCode { get; } - - public static async Task ReadAsync( - HttpResponseMessage response, - ModApiBodyReadPolicy bodyPolicy, - CancellationToken cancellationToken = default - ) - { - if (response == null) - throw new ArgumentNullException(nameof(response)); - if (bodyPolicy.MaxBytes <= 0) - throw new ArgumentOutOfRangeException(nameof(bodyPolicy)); - if (string.IsNullOrWhiteSpace(bodyPolicy.OverflowUserCode)) - throw new ArgumentException("Overflow user code is required.", nameof(bodyPolicy)); - - var statusCode = (int)response.StatusCode; - var retryAfterSeconds = ReadRetryAfterSeconds(response); - var headerRequestId = response.Headers.TryGetValues("X-Request-Id", out var requestIds) - ? Normalize(requestIds.FirstOrDefault()) - : null; - - if ( - response.Content.Headers.ContentLength is { } declaredLength - && declaredLength > bodyPolicy.MaxBytes - ) - { - return new ModApiResponse( - statusCode, - false, - string.Empty, - default, - headerRequestId, - retryAfterSeconds, - bodyPolicy.OverflowUserCode - ); - } - - var body = await ReadBodyAsync(response.Content, bodyPolicy.MaxBytes, cancellationToken) - .ConfigureAwait(false); - if (body == null) - { - return new ModApiResponse( - statusCode, - false, - string.Empty, - default, - headerRequestId, - retryAfterSeconds, - bodyPolicy.OverflowUserCode - ); - } - - var error = ParseError(body); - var requestId = headerRequestId ?? error.RequestId; - var isSuccess = response.IsSuccessStatusCode; - // Remote codes remain protocol metadata. Endpoint clients may explicitly allow-list a - // code for product behavior, but arbitrary server text must never become user-facing. - var userCode = isSuccess ? "ok" : $"http_{statusCode}"; - return new ModApiResponse( - statusCode, - isSuccess, - body, - error, - requestId, - retryAfterSeconds, - userCode - ); - } - - private static async Task ReadBodyAsync( - HttpContent content, - int maxBytes, - CancellationToken cancellationToken - ) - { - using var stream = await content.ReadAsStreamAsync().ConfigureAwait(false); - using var output = new MemoryStream(); - var buffer = new byte[Math.Min(81920, maxBytes + 1)]; - while (true) - { - var read = await stream - .ReadAsync(buffer, 0, buffer.Length, cancellationToken) - .ConfigureAwait(false); - if (read == 0) - return Encoding.UTF8.GetString(output.ToArray()); - if (output.Length + read > maxBytes) - return null; - output.Write(buffer, 0, read); - } - } - - private static ModApiErrorEnvelope ParseError(string body) - { - if (string.IsNullOrWhiteSpace(body)) - return default; - try - { - var root = JObject.Parse(body); - if (root["error"] is JObject nested) - { - return new ModApiErrorEnvelope( - ModApiEnvelopeShape.Nested, - ReadString(nested, "code"), - ReadMessage(nested), - nested["retryable"]?.Value(), - ReadString(nested, "request_id") - ); - } - - var legacyCode = ReadString(root, "error") ?? ReadString(root, "code"); - if (legacyCode != null) - { - return new ModApiErrorEnvelope( - ModApiEnvelopeShape.LegacyTopLevel, - legacyCode, - ReadMessage(root), - root["retryable"]?.Value(), - ReadString(root, "request_id") - ); - } - } - catch - { - // Malformed and non-JSON bodies deliberately collapse to the status-derived user code. - } - return default; - } - - private static string? ReadMessage(JObject source) => - ReadString(source, "message") - ?? ReadString(source, "reason") - ?? ReadString(source, "detail"); - - private static string? ReadString(JObject source, string name) => - source[name]?.Type == JTokenType.String ? Normalize(source[name]?.Value()) : null; - - private static string? Normalize(string? value) => - string.IsNullOrWhiteSpace(value) ? null : value.Trim(); - - private static int? ReadRetryAfterSeconds(HttpResponseMessage response) - { - var retryAfter = response.Headers.RetryAfter; - if (retryAfter?.Delta is { } delta) - return Math.Max(0, (int)Math.Ceiling(delta.TotalSeconds)); - if (retryAfter?.Date is { } date) - return Math.Max(0, (int)Math.Ceiling((date - DateTimeOffset.UtcNow).TotalSeconds)); - return null; - } -} - -internal sealed class ModApiFailure -{ - public ModApiFailure( - string userCode, - Exception? diagnosticException = null, - ModApiResponse? response = null - ) - { - UserCode = string.IsNullOrWhiteSpace(userCode) - ? throw new ArgumentException("User code is required.", nameof(userCode)) - : userCode; - DiagnosticException = diagnosticException; - Response = response; - } - - public string UserCode { get; } - public Exception? DiagnosticException { get; } - public ModApiResponse? Response { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/MessagePackGzipCodec.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/MessagePackGzipCodec.cs deleted file mode 100644 index 39d07ed..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/MessagePackGzipCodec.cs +++ /dev/null @@ -1,73 +0,0 @@ -#nullable enable -using MessagePack; -using MessagePack.Resolvers; - -namespace BazaarPlusPlus.ModApi; - -/// -/// Compatibility wrapper for local BPP payloads that use contractless MessagePack inside gzip. -/// V6 Run payloads keep their untrusted-data options, size cap, version gate, and closed error codes -/// in RunPayloadV6Codec; only the framing loop is shared internally. -/// -internal static class MessagePackGzipCodec -{ - private static readonly MessagePackSerializerOptions Options = - MessagePackSerializerOptions.Standard.WithResolver( - ContractlessStandardResolverAllowPrivate.Instance - ); - - public static byte[] Serialize(T payload) - where T : class - { - if (payload == null) - throw new ArgumentNullException(nameof(payload)); - - return MessagePackGzipFraming.Encode(payload, Options); - } - - // The decode exception stays available so callers can tell a runtime binding failure - // (a missing member in a loaded assembly) from corrupt bytes. - public static bool TryDeserialize( - byte[]? payloadBytes, - out T? value, - out string? error, - out Exception? exception, - int? maxDecompressedBytes = null - ) - where T : class - { - value = null; - error = null; - exception = null; - - if (payloadBytes == null || payloadBytes.Length == 0) - { - error = "payload_empty"; - return false; - } - - var result = MessagePackGzipFraming.TryDecode( - payloadBytes, - Options, - maxDecompressedBytes - ); - if (result.Succeeded) - { - value = result.Value; - return true; - } - - exception = result.Exception; - error = result.FailureKind switch - { - MessagePackGzipFailureKind.Empty => "payload_empty", - MessagePackGzipFailureKind.DecompressedTooLarge => "payload_too_large", - MessagePackGzipFailureKind.NotGzip => "payload_not_gzip", - MessagePackGzipFailureKind.DeserializedNull => "payload_deserialized_null", - _ when result.Exception != null => - $"{result.Exception.GetType().Name}: {result.Exception.Message}", - _ => "payload_decode_failed", - }; - return false; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/MessagePackGzipFraming.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/MessagePackGzipFraming.cs deleted file mode 100644 index fc09cbb..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/MessagePackGzipFraming.cs +++ /dev/null @@ -1,110 +0,0 @@ -#nullable enable -using System.IO.Compression; -using MessagePack; - -namespace BazaarPlusPlus.ModApi; - -// This type shares only gzip framing, the bounded decompression loop, and failure classification. -// Each wrapper keeps its own size policy on purpose: V6 bundles arrive over the network and cap -// decompression at RunPayloadV6Codec.MaxDecompressedBytes, while locally recorded replays are -// written by this process and stay deliberately uncapped. Adding a cap to the local path would -// reject the mod's own large recordings. -internal enum MessagePackGzipFailureKind -{ - Empty, - NotGzip, - DecompressedTooLarge, - DeserializedNull, - DecodeFailed, -} - -internal readonly struct MessagePackGzipDecodeResult - where T : class -{ - private MessagePackGzipDecodeResult( - T? value, - MessagePackGzipFailureKind? failureKind, - Exception? exception - ) - { - Value = value; - FailureKind = failureKind; - Exception = exception; - } - - public T? Value { get; } - public MessagePackGzipFailureKind? FailureKind { get; } - public Exception? Exception { get; } - public bool Succeeded => Value != null; - - public static MessagePackGzipDecodeResult Success(T value) => new(value, null, null); - - public static MessagePackGzipDecodeResult Failure( - MessagePackGzipFailureKind failureKind, - Exception? exception = null - ) => new(null, failureKind, exception); -} - -internal static class MessagePackGzipFraming -{ - public static byte[] Encode(T payload, MessagePackSerializerOptions options) - where T : class - { - var packed = MessagePackSerializer.Serialize(payload, options); - using var output = new MemoryStream(); - using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true)) - gzip.Write(packed, 0, packed.Length); - return output.ToArray(); - } - - public static MessagePackGzipDecodeResult TryDecode( - ReadOnlyMemory bytes, - MessagePackSerializerOptions options, - int? maxDecompressedBytes = null - ) - where T : class - { - if (bytes.Length == 0) - return MessagePackGzipDecodeResult.Failure(MessagePackGzipFailureKind.Empty); - if (bytes.Length < 2 || bytes.Span[0] != 0x1F || bytes.Span[1] != 0x8B) - return MessagePackGzipDecodeResult.Failure(MessagePackGzipFailureKind.NotGzip); - - try - { - using var input = new MemoryStream(bytes.ToArray(), writable: false); - using var gzip = new GZipStream(input, CompressionMode.Decompress); - using var decompressed = new MemoryStream(); - var buffer = new byte[64 * 1024]; - while (true) - { - var read = gzip.Read(buffer, 0, buffer.Length); - if (read == 0) - break; - if ( - maxDecompressedBytes.HasValue - && decompressed.Length + read > maxDecompressedBytes.Value - ) - { - return MessagePackGzipDecodeResult.Failure( - MessagePackGzipFailureKind.DecompressedTooLarge - ); - } - decompressed.Write(buffer, 0, read); - } - - var value = MessagePackSerializer.Deserialize(decompressed.ToArray(), options); - return value == null - ? MessagePackGzipDecodeResult.Failure( - MessagePackGzipFailureKind.DeserializedNull - ) - : MessagePackGzipDecodeResult.Success(value); - } - catch (Exception ex) - { - return MessagePackGzipDecodeResult.Failure( - MessagePackGzipFailureKind.DecodeFailed, - ex - ); - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/ModApiRoutes.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/ModApiRoutes.cs deleted file mode 100644 index 6305ca9..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/ModApiRoutes.cs +++ /dev/null @@ -1,42 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.ModApi; - -internal sealed class ModApiRoutes -{ - private ModApiRoutes(Uri apiBaseUri) - { - ApiBaseUri = apiBaseUri; - UploadBundle = BuildAbsolute("/bundles"); - QueryGhostBattles = BuildAbsolute("/ghost-battles"); - Health = BuildAbsolute("/health"); - } - - public Uri ApiBaseUri { get; } - - public string UploadBundle { get; } - - public string QueryGhostBattles { get; } - - public string Health { get; } - - public static ModApiRoutes? TryCreate(string? apiBaseUrl) - { - if ( - string.IsNullOrWhiteSpace(apiBaseUrl) - || !Uri.TryCreate(apiBaseUrl, UriKind.Absolute, out var apiBaseUri) - || (apiBaseUri.Scheme != Uri.UriSchemeHttps && apiBaseUri.Scheme != Uri.UriSchemeHttp) - ) - { - return null; - } - - return new ModApiRoutes( - new UriBuilder(apiBaseUri) { Path = string.Empty, Query = string.Empty }.Uri - ); - } - - private string BuildAbsolute(string path) - { - return new Uri(ApiBaseUri, path).ToString(); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/ModApiUploadDefaults.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/ModApiUploadDefaults.cs deleted file mode 100644 index 38def13..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/ModApiUploadDefaults.cs +++ /dev/null @@ -1,11 +0,0 @@ -#nullable enable - -namespace BazaarPlusPlus.ModApi; - -internal static class ModApiUploadDefaults -{ - public const string ApiBaseUrl = "https://mod-api-v6.bazaarplusplus.com"; - public const int StartupDelaySeconds = 20; - public const int IntervalSeconds = 180; - public const int RequestTimeoutSeconds = 120; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/BazaarDbProfileLinkRedeemRequest.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/BazaarDbProfileLinkRedeemRequest.cs deleted file mode 100644 index 1140a3e..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/BazaarDbProfileLinkRedeemRequest.cs +++ /dev/null @@ -1,13 +0,0 @@ -#nullable enable -using Newtonsoft.Json; - -namespace BazaarPlusPlus.ModApi.Models; - -internal sealed class BazaarDbProfileLinkRedeemRequest -{ - [JsonProperty("code")] - public string Code { get; set; } = string.Empty; - - [JsonProperty("account_id")] - public string AccountId { get; set; } = string.Empty; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/GhostBattleImportRecord.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/GhostBattleImportRecord.cs deleted file mode 100644 index 443aad2..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/GhostBattleImportRecord.cs +++ /dev/null @@ -1,63 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.ModApi.Models; - -internal sealed class GhostBattleImportRecord -{ - public string BattleId { get; set; } = string.Empty; - - public string BundleId { get; set; } = string.Empty; - - public string DownloadUrl { get; set; } = string.Empty; - - public DateTimeOffset DownloadExpiresAtUtc { get; set; } - - public DateTimeOffset RecordedAtUtc { get; set; } - - public int? Day { get; set; } - - public int? Hour { get; set; } - - public string? EncounterId { get; set; } - - public string? PlayerName { get; set; } - - public string? PlayerAccountId { get; set; } - - public string? PlayerHero { get; set; } - - public string? PlayerRank { get; set; } - - public int? PlayerRating { get; set; } - - public int? PlayerLevel { get; set; } - - public int? PlayerPrestige { get; set; } - - public int? PlayerVictories { get; set; } - - public string? OpponentName { get; set; } - - public string? OpponentHero { get; set; } - - public string? OpponentRank { get; set; } - - public int? OpponentRating { get; set; } - - public int? OpponentLevel { get; set; } - - public int? OpponentPrestige { get; set; } - - public int? OpponentVictories { get; set; } - - public string? OpponentAccountId { get; set; } - - public string CombatKind { get; set; } = "PVPCombat"; - - public string? Result { get; set; } - - public string? WinnerCombatantId { get; set; } - - public string? LoserCombatantId { get; set; } - - public bool IsFinalBattle { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/ModApiHealthResponse.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/ModApiHealthResponse.cs deleted file mode 100644 index 0ce6e0a..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Models/ModApiHealthResponse.cs +++ /dev/null @@ -1,13 +0,0 @@ -#nullable enable -using Newtonsoft.Json; - -namespace BazaarPlusPlus.ModApi.Models; - -internal sealed class ModApiHealthResponse -{ - [JsonProperty("status")] - public string Status { get; set; } = string.Empty; - - [JsonProperty("server_time_ms")] - public long? ServerTimeMs { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Properties/AssemblyAttributes.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Properties/AssemblyAttributes.cs deleted file mode 100644 index c5ebfd6..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/Properties/AssemblyAttributes.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("BazaarPlusPlus")] -[assembly: InternalsVisibleTo("BppLog.Tests")] -[assembly: InternalsVisibleTo("BundlePipeline.Tests")] -[assembly: InternalsVisibleTo("BundleV6Codec.Tests")] -[assembly: InternalsVisibleTo("CombatImpact.Corpus")] -[assembly: InternalsVisibleTo("GhostBattleSync.Tests")] -[assembly: InternalsVisibleTo("HistoryPanelFiltering.Tests")] -[assembly: InternalsVisibleTo("HistoryPanelRepository.Tests")] -[assembly: InternalsVisibleTo("ModApi.Tests")] diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/packages.lock.json b/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/packages.lock.json deleted file mode 100644 index 9a3a8b5..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.ModApi/packages.lock.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "version": 2, - "dependencies": { - ".NETStandard,Version=v2.1": { - "MessagePack": { - "type": "Direct", - "requested": "[3.1.4, )", - "resolved": "3.1.4", - "contentHash": "BH0wlHWmVoZpbAPyyt2Awbq30C+ZsS3eHSkYdnyUAbqVJ22fAJDzn2xTieBeoT5QlcBzp61vHcv878YJGfi3mg==", - "dependencies": { - "MessagePack.Annotations": "3.1.4", - "MessagePackAnalyzer": "3.1.4", - "Microsoft.NET.StringTools": "17.11.4", - "System.Collections.Immutable": "8.0.0" - } - }, - "MessagePack.Annotations": { - "type": "Direct", - "requested": "[3.1.4, )", - "resolved": "3.1.4", - "contentHash": "aVWrDAkCdqxwQsz/q0ldPh2EFn48M99YUzE9OvZjMq2RNLKz4o2z88iGFvSvbMqOWRweRvKPHBJZe22PRqzslQ==" - }, - "MessagePackAnalyzer": { - "type": "Direct", - "requested": "[3.1.4, )", - "resolved": "3.1.4", - "contentHash": "CTaSsN/liJ7MhLCAB7Z4ZLBNuVGCq9lt2BT/cbrc9vzGv89yK3CqIA+z9T19a11eQYl9etZHL6MQJgCqECRVpg==" - }, - "NETStandard.Library": { - "type": "Direct", - "requested": "[2.0.3, )", - "resolved": "2.0.3", - "contentHash": "st47PosZSHrjECdjeIzZQbzivYBJFv6P2nv4cj2ypdI204DO+vZ7l5raGMiX4eXMJ53RfOIg+/s4DHVZ54Nu2A==", - "dependencies": { - "Microsoft.NETCore.Platforms": "1.1.0" - } - }, - "Newtonsoft.Json": { - "type": "Direct", - "requested": "[13.0.4, )", - "resolved": "13.0.4", - "contentHash": "pdgNNMai3zv51W5aq268sujXUyx7SNdE2bj1wZcWjAQrKMFZV260lbqYop1d2GM67JI1huLRwxo9ZqnfF/lC6A==" - }, - "Microsoft.NET.StringTools": { - "type": "Transitive", - "resolved": "17.11.4", - "contentHash": "mudqUHhNpeqIdJoUx2YDWZO/I9uEDYVowan89R6wsomfnUJQk6HteoQTlNjZDixhT2B4IXMkMtgZtoceIjLRmA==", - "dependencies": { - "System.Memory": "4.5.5", - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, - "Microsoft.NETCore.Platforms": { - "type": "Transitive", - "resolved": "1.1.0", - "contentHash": "kz0PEW2lhqygehI/d6XsPCQzD7ff7gUJaVGPVETX611eadGsA3A877GdSlU0LRVMCTH/+P3o2iDTak+S08V2+A==" - }, - "System.Buffers": { - "type": "Transitive", - "resolved": "4.5.1", - "contentHash": "Rw7ijyl1qqRS0YQD/WycNst8hUUMgrMH4FCn1nNm27M4VxchZ1js3fVjQaANHO5f3sN4isvP4a+Met9Y4YomAg==" - }, - "System.Collections.Immutable": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "AurL6Y5BA1WotzlEvVaIDpqzpIPvYnnldxru8oXJU2yFxFUy3+pNXjXd1ymO+RA0rq0+590Q8gaz2l3Sr7fmqg==", - "dependencies": { - "System.Memory": "4.5.5", - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.5.5", - "contentHash": "XIWiDvKPXaTveaB7HVganDlOCRoj03l+jrwNvcge/t8vhGYKvqV+dMv6G4SAX2NoNmN0wZfVPTAlFwZcZvVOUw==", - "dependencies": { - "System.Buffers": "4.5.1", - "System.Numerics.Vectors": "4.4.0", - "System.Runtime.CompilerServices.Unsafe": "4.5.3" - } - }, - "System.Numerics.Vectors": { - "type": "Transitive", - "resolved": "4.4.0", - "contentHash": "UiLzLW+Lw6HLed1Hcg+8jSRttrbuXv7DANVj0DkL9g6EnnzbL75EB7EWsw5uRbhxd/4YdG8li5XizGWepmG3PQ==" - }, - "System.Runtime.CompilerServices.Unsafe": { - "type": "CentralTransitive", - "requested": "[6.0.0, )", - "resolved": "6.0.0", - "contentHash": "/iUeP3tq1S0XdNNoMz5C9twLSrM/TH+qElHkXWaPvuNOt+99G75NrV0OS2EqHx5wMN7popYjpc8oTjC1y16DLg==" - } - } - } -} \ No newline at end of file diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.Storage.csproj b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.Storage.csproj deleted file mode 100644 index 9e5486b..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.Storage.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - BazaarPlusPlus.Storage - BazaarPlusPlus.Storage - netstandard2.1 - 12 - enable - $(BppVersion) - true - true - - - - - - - - - - - - - diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json deleted file mode 100644 index a8a1709..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "formatVersion": 1, - "dataRootDirectoryName": "BazaarPlusPlusV6", - "historyDatabaseUserVersion": 1, - "replayPayloadRetainedNewestCount": 200, - "replayPayloadRetainedAgeDays": 30 -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BundleQueue/BundleQueueRecords.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BundleQueue/BundleQueueRecords.cs deleted file mode 100644 index 8c34009..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BundleQueue/BundleQueueRecords.cs +++ /dev/null @@ -1,169 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.BundleQueue; - -public enum BundleSealJobState -{ - Waiting, - Sealing, - TerminalFailure, -} - -public enum BundleScreenshotState -{ - NotRequested, - Waiting, - Available, - Unavailable, - TimedOut, -} - -public sealed class BundleSealJobRecord -{ - public BundleSealJobRecord( - string runId, - BundleSealJobState state, - string? playerAccountId, - bool screenshotRequested, - BundleScreenshotState screenshotState, - DateTimeOffset inputDeadlineAtUtc, - string? bundleId, - long? createdAtMs, - int attempts, - DateTimeOffset? lastAttemptAtUtc, - string? lastErrorCode - ) - { - RunId = runId; - State = state; - PlayerAccountId = playerAccountId; - ScreenshotRequested = screenshotRequested; - ScreenshotState = screenshotState; - InputDeadlineAtUtc = inputDeadlineAtUtc; - BundleId = bundleId; - CreatedAtMs = createdAtMs; - Attempts = attempts; - LastAttemptAtUtc = lastAttemptAtUtc; - LastErrorCode = lastErrorCode; - } - - public string RunId { get; } - public BundleSealJobState State { get; } - public string? PlayerAccountId { get; } - public bool ScreenshotRequested { get; } - public BundleScreenshotState ScreenshotState { get; } - public DateTimeOffset InputDeadlineAtUtc { get; } - public string? BundleId { get; } - public long? CreatedAtMs { get; } - - // Consecutive failed seal attempts with LastErrorCode; the failure policy owns the count. - public int Attempts { get; } - public DateTimeOffset? LastAttemptAtUtc { get; } - public string? LastErrorCode { get; } -} - -public sealed class BundleAllocationRecord -{ - public BundleAllocationRecord(string bundleId, long createdAtMs) - { - BundleId = bundleId; - CreatedAtMs = createdAtMs; - } - - public string BundleId { get; } - public long CreatedAtMs { get; } -} - -public sealed class BundleOutboxPublishRecord -{ - public BundleOutboxPublishRecord( - string bundleId, - string runId, - string fileName, - string contentSha256Hex, - string contentDigest, - long totalBytes, - bool hasScreenshot - ) - { - BundleId = bundleId; - RunId = runId; - FileName = fileName; - ContentSha256Hex = contentSha256Hex; - ContentDigest = contentDigest; - TotalBytes = totalBytes; - HasScreenshot = hasScreenshot; - } - - public string BundleId { get; } - public string RunId { get; } - public string FileName { get; } - public string ContentSha256Hex { get; } - public string ContentDigest { get; } - public long TotalBytes { get; } - public bool HasScreenshot { get; } -} - -public sealed class BundleOutboxRecord -{ - public BundleOutboxRecord( - string bundleId, - string runId, - string fileName, - string contentSha256Hex, - string contentDigest, - long totalBytes - ) - { - BundleId = bundleId; - RunId = runId; - FileName = fileName; - ContentSha256Hex = contentSha256Hex; - ContentDigest = contentDigest; - TotalBytes = totalBytes; - } - - public string BundleId { get; } - public string RunId { get; } - public string FileName { get; } - public string ContentSha256Hex { get; } - public string ContentDigest { get; } - public long TotalBytes { get; } -} - -public sealed class BundleOutboxStateRecord -{ - public BundleOutboxStateRecord(string bundleId, string runId, string fileName) - { - BundleId = bundleId; - RunId = runId; - FileName = fileName; - } - - public string BundleId { get; } - public string RunId { get; } - public string FileName { get; } -} - -public sealed class BundleUploadOutcomeRecord -{ - public BundleUploadOutcomeRecord( - bool uploaded, - string code, - string? detail, - string? requestId, - string? outcome - ) - { - Uploaded = uploaded; - Code = code; - Detail = detail; - RequestId = requestId; - Outcome = outcome; - } - - public bool Uploaded { get; } - public string Code { get; } - public string? Detail { get; } - public string? RequestId { get; } - public string? Outcome { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BundleQueue/BundleQueueStore.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BundleQueue/BundleQueueStore.cs deleted file mode 100644 index 972d159..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/BundleQueue/BundleQueueStore.cs +++ /dev/null @@ -1,502 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Storage.RunLog; -using BazaarPlusPlus.Storage.Sqlite; -using Microsoft.Data.Sqlite; - -namespace BazaarPlusPlus.Storage.BundleQueue; - -public sealed class BundleQueueStore : SqliteStoreBase -{ - public BundleQueueStore(string databasePath) - : base(databasePath) { } - - public void ResetInterruptedSeals() - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = - $"UPDATE {RunLogSchema.BundleSealJobsTableName} SET state = 'waiting' WHERE state = 'sealing';"; - command.ExecuteNonQuery(); - } - - /// - /// The one rule for a Seal-Eligible Run, as a SQL condition over the runs row aliased - /// : not a History-Only Run, completed, Ranked, not PTR, and with - /// neither a seal job nor any outbox row. The upload policy is checked first: imported history - /// is never sealed, whatever its other columns say. Any outbox row ends eligibility: a reseal - /// after an invalid file is scheduled explicitly, and a server rejection or retention expiry is - /// final. - /// gives each such Run a job, and replay maintenance keeps its replays until then. The shared - /// cases in tests/BundleQueueSqliteStore.Tests/fixtures/bundle-seal-eligibility.json - /// pin this rule together with installer History cleanup. - /// - public static string SealEligibleRunCondition(string runAlias) => - $""" - ( - {runAlias}.upload_policy = 'bundle' - AND {runAlias}.status = 'completed' - AND lower({runAlias}.game_mode) = 'ranked' - AND lower(COALESCE({runAlias}.build_channel, 'unknown')) <> 'ptr' - AND NOT EXISTS ( - SELECT 1 FROM {RunLogSchema.BundleSealJobsTableName} AS {runAlias}_seal_job - WHERE {runAlias}_seal_job.run_id = {runAlias}.run_id - ) - AND NOT EXISTS ( - SELECT 1 FROM {RunLogSchema.BundleOutboxTableName} AS {runAlias}_outbox - WHERE {runAlias}_outbox.run_id = {runAlias}.run_id - ) - ) - """; - - public void EnsureEligibleJobs(TimeSpan inputConvergenceWindow) - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = $""" - INSERT OR IGNORE INTO {RunLogSchema.BundleSealJobsTableName} ( - run_id, state, player_account_id, screenshot_requested, screenshot_state, - input_deadline_at_ms - ) - SELECT r.run_id, 'waiting', r.player_account_id, r.bundle_screenshot_requested, - CASE WHEN r.bundle_screenshot_requested = 1 THEN 'waiting' ELSE 'not_requested' END, - COALESCE(r.ended_at_ms, r.last_seen_at_ms) + $windowMs - FROM {RunLogSchema.RunsTableName} AS r - WHERE {SealEligibleRunCondition("r")}; - """; - command.Parameters.AddWithValue( - "$windowMs", - (long)inputConvergenceWindow.TotalMilliseconds - ); - command.ExecuteNonQuery(); - } - - public IReadOnlyList ListWaitingRunIds() - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = - $"SELECT run_id FROM {RunLogSchema.BundleSealJobsTableName} WHERE state = 'waiting' ORDER BY input_deadline_at_ms, run_id;"; - using var reader = command.ExecuteReader(); - var ids = new List(); - while (reader.Read()) - ids.Add(reader.GetString(0)); - return ids; - } - - public BundleSealJobRecord? ReadJob(string runId) - { - using var connection = OpenConnection(); - return ReadJob(connection, runId); - } - - public BundleAllocationRecord EnsureAllocation( - string runId, - string proposedBundleId, - long proposedCreatedAtMs - ) - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = $""" - UPDATE {RunLogSchema.BundleSealJobsTableName} - SET bundle_id = COALESCE(bundle_id, $bundleId), - created_at_ms = COALESCE(created_at_ms, $createdAtMs), - state = 'sealing' - WHERE run_id = $runId; - SELECT bundle_id, created_at_ms - FROM {RunLogSchema.BundleSealJobsTableName} WHERE run_id = $runId; - """; - command.Parameters.AddWithValue("$runId", runId); - command.Parameters.AddWithValue("$bundleId", proposedBundleId); - command.Parameters.AddWithValue("$createdAtMs", proposedCreatedAtMs); - using var reader = command.ExecuteReader(); - if (!reader.Read()) - throw new InvalidOperationException("Seal job disappeared during allocation."); - return new BundleAllocationRecord(reader.GetString(0), reader.GetInt64(1)); - } - - public void FreezePlayerAccountId(string runId, string accountId) - { - using var connection = OpenConnection(); - using var transaction = connection.BeginTransaction(); - Execute( - connection, - transaction, - $"UPDATE {RunLogSchema.RunsTableName} SET player_account_id = COALESCE(player_account_id, $accountId) WHERE run_id = $runId;", - ("$runId", runId), - ("$accountId", accountId) - ); - Execute( - connection, - transaction, - $"UPDATE {RunLogSchema.BundleSealJobsTableName} SET player_account_id = COALESCE(player_account_id, $accountId) WHERE run_id = $runId;", - ("$runId", runId), - ("$accountId", accountId) - ); - transaction.Commit(); - } - - public void UpdateScreenshotState(string runId, BundleScreenshotState state) => - Execute( - $"UPDATE {RunLogSchema.BundleSealJobsTableName} SET screenshot_state = $state WHERE run_id = $runId;", - ("$runId", runId), - ("$state", ToStorage(state)) - ); - - // The one writer of a seal failure: state, consecutive-attempt count, time, and diagnostic - // change together so backoff and parking read one consistent row. - public void RecordSealFailure( - string runId, - BundleSealJobState state, - string code, - string? detail, - int attempts, - DateTimeOffset attemptedAt - ) - { - if (state == BundleSealJobState.Sealing) - throw new ArgumentOutOfRangeException(nameof(state)); - Execute( - $"UPDATE {RunLogSchema.BundleSealJobsTableName} SET state = $state, attempts = $attempts, last_attempt_at_ms = $attemptedAt, last_error_code = $code, last_error_detail = $detail WHERE run_id = $runId;", - ("$runId", runId), - ("$state", ToStorage(state)), - ("$attempts", attempts), - ("$attemptedAt", attemptedAt.ToUnixTimeMilliseconds()), - ("$code", code), - ("$detail", detail) - ); - } - - public bool ContainsOutbox(string bundleId) - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = - $"SELECT 1 FROM {RunLogSchema.BundleOutboxTableName} WHERE bundle_id = $bundleId LIMIT 1;"; - command.Parameters.AddWithValue("$bundleId", bundleId); - return command.ExecuteScalar() != null; - } - - public bool PublishOutbox( - BundleAllocationRecord allocation, - BundleOutboxPublishRecord outbox, - DateTimeOffset sealedAt - ) - { - using var connection = OpenConnection(); - using var transaction = connection.BeginTransaction(); - var job = ReadJob(connection, outbox.RunId, transaction); - if (job?.BundleId != allocation.BundleId || job.CreatedAtMs != allocation.CreatedAtMs) - return false; - InsertOutbox(connection, transaction, outbox, sealedAt); - DeleteJob(connection, transaction, outbox.RunId); - transaction.Commit(); - return true; - } - - public IReadOnlyList ListPendingForValidation() - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = - $"SELECT bundle_id, run_id, file_name FROM {RunLogSchema.BundleOutboxTableName} WHERE status = 'pending';"; - using var reader = command.ExecuteReader(); - var rows = new List(); - while (reader.Read()) - rows.Add(new(reader.GetString(0), reader.GetString(1), reader.GetString(2))); - return rows; - } - - public IReadOnlyList ListDue(DateTimeOffset now, int maximumCount) - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = $""" - SELECT bundle_id, run_id, file_name, content_sha256_hex, content_digest, total_bytes - FROM {RunLogSchema.BundleOutboxTableName} - WHERE status = 'pending' - AND (next_attempt_at_ms IS NULL OR next_attempt_at_ms <= $now) - ORDER BY attempts ASC, sealed_at_ms ASC - LIMIT $maximumCount; - """; - command.Parameters.AddWithValue("$now", now.ToUnixTimeMilliseconds()); - command.Parameters.AddWithValue("$maximumCount", maximumCount); - using var reader = command.ExecuteReader(); - var rows = new List(); - while (reader.Read()) - rows.Add(ReadOutbox(reader)); - return rows; - } - - public void RecordOutcome( - string bundleId, - BundleUploadOutcomeRecord outcome, - DateTimeOffset now - ) - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = $""" - UPDATE {RunLogSchema.BundleOutboxTableName} - SET status = $status, attempts = attempts + 1, last_attempt_at_ms = $now, - failed_at_ms = CASE WHEN $uploaded = 1 THEN NULL ELSE $now END, - last_error_code = CASE WHEN $uploaded = 1 THEN NULL ELSE $code END, - last_error_detail = CASE WHEN $uploaded = 1 THEN NULL ELSE $detail END, - server_request_id = $requestId, server_outcome = $outcome, - uploaded_at_ms = CASE WHEN $uploaded = 1 THEN $now ELSE NULL END - WHERE bundle_id = $bundleId AND status = 'pending'; - """; - command.Parameters.AddWithValue("$bundleId", bundleId); - command.Parameters.AddWithValue( - "$status", - outcome.Uploaded ? "uploaded" : "permanent_failure" - ); - command.Parameters.AddWithValue("$uploaded", outcome.Uploaded ? 1 : 0); - command.Parameters.AddWithValue("$now", now.ToUnixTimeMilliseconds()); - command.Parameters.AddWithValue("$code", outcome.Code); - AddNullableString(command, "$detail", outcome.Detail); - AddNullableString(command, "$requestId", outcome.RequestId); - AddNullableString(command, "$outcome", outcome.Outcome); - command.ExecuteNonQuery(); - } - - public void RecordTransient( - string bundleId, - string code, - string? detail, - DateTimeOffset now, - DateTimeOffset nextAttempt - ) => - Execute( - $"UPDATE {RunLogSchema.BundleOutboxTableName} SET attempts = attempts + 1, last_attempt_at_ms = $now, next_attempt_at_ms = $next, last_error_code = $code, last_error_detail = $detail WHERE bundle_id = $bundleId AND status = 'pending';", - ("$bundleId", bundleId), - ("$now", now.ToUnixTimeMilliseconds()), - ("$next", nextAttempt.ToUnixTimeMilliseconds()), - ("$code", code), - ("$detail", detail) - ); - - public void FailOutboxAndScheduleReseal( - string bundleId, - string runId, - string reason, - DateTimeOffset now - ) - { - using var connection = OpenConnection(); - using var transaction = connection.BeginTransaction(deferred: false); - using var invalidate = CreateCommand(connection, transaction); - invalidate.CommandText = - $"UPDATE {RunLogSchema.BundleOutboxTableName} SET status = 'permanent_failure', failed_at_ms = $now, last_error_code = $reason WHERE bundle_id = $bundleId AND run_id = $runId AND status = 'pending';"; - AddParameters( - invalidate, - [ - ("$bundleId", bundleId), - ("$runId", runId), - ("$now", now.ToUnixTimeMilliseconds()), - ("$reason", reason), - ] - ); - // File validation works from a snapshot; the upload may have completed since then. - if (invalidate.ExecuteNonQuery() == 0) - return; - Execute( - connection, - transaction, - $""" - INSERT OR IGNORE INTO {RunLogSchema.BundleSealJobsTableName} ( - run_id, state, player_account_id, screenshot_requested, screenshot_state, - input_deadline_at_ms - ) - SELECT run_id, 'waiting', player_account_id, bundle_screenshot_requested, - CASE WHEN bundle_screenshot_requested = 1 THEN 'waiting' ELSE 'not_requested' END, - $now - FROM {RunLogSchema.RunsTableName} WHERE run_id = $runId; - """, - ("$runId", runId), - ("$now", now.ToUnixTimeMilliseconds()) - ); - transaction.Commit(); - } - - public void ExpirePending(DateTimeOffset cutoff, DateTimeOffset now) => - Execute( - $"UPDATE {RunLogSchema.BundleOutboxTableName} SET status = 'permanent_failure', failed_at_ms = $now, last_error_code = 'local_retention_expired' WHERE status = 'pending' AND sealed_at_ms < $cutoff;", - ("$now", now.ToUnixTimeMilliseconds()), - ("$cutoff", cutoff.ToUnixTimeMilliseconds()) - ); - - public IReadOnlyList ListRetentionFileNames(DateTimeOffset permanentFailureCutoff) => - ListFileNames( - $"SELECT file_name FROM {RunLogSchema.BundleOutboxTableName} WHERE status = 'uploaded' OR (status = 'permanent_failure' AND failed_at_ms < $cutoff) ORDER BY COALESCE(failed_at_ms, uploaded_at_ms, sealed_at_ms);", - ("$cutoff", permanentFailureCutoff.ToUnixTimeMilliseconds()) - ); - - public IReadOnlyList ListReclaimFileNames(DateTimeOffset pendingCutoff) => - ListFileNames( - $"SELECT file_name FROM {RunLogSchema.BundleOutboxTableName} WHERE status = 'permanent_failure' OR (status = 'pending' AND sealed_at_ms < $pendingCutoff) ORDER BY sealed_at_ms ASC;", - ("$pendingCutoff", pendingCutoff.ToUnixTimeMilliseconds()) - ); - - private static BundleSealJobRecord? ReadJob( - SqliteConnection connection, - string runId, - SqliteTransaction? transaction = null - ) - { - using var command = CreateCommand(connection, transaction); - command.CommandText = - $"SELECT run_id, state, player_account_id, screenshot_requested, screenshot_state, input_deadline_at_ms, bundle_id, created_at_ms, attempts, last_attempt_at_ms, last_error_code FROM {RunLogSchema.BundleSealJobsTableName} WHERE run_id = $runId LIMIT 1;"; - command.Parameters.AddWithValue("$runId", runId); - using var reader = command.ExecuteReader(); - if (!reader.Read()) - return null; - return new BundleSealJobRecord( - reader.GetString(0), - ParseJobState(reader.GetString(1)), - reader.IsDBNull(2) ? null : reader.GetString(2), - reader.GetInt32(3) == 1, - ParseScreenshotState(reader.GetString(4)), - DateTimeOffset.FromUnixTimeMilliseconds(reader.GetInt64(5)), - reader.IsDBNull(6) ? null : reader.GetString(6), - reader.IsDBNull(7) ? null : reader.GetInt64(7), - reader.GetInt32(8), - reader.IsDBNull(9) ? null : DateTimeOffset.FromUnixTimeMilliseconds(reader.GetInt64(9)), - reader.IsDBNull(10) ? null : reader.GetString(10) - ); - } - - private static BundleOutboxRecord ReadOutbox(SqliteDataReader reader) => - new( - reader.GetString(0), - reader.GetString(1), - reader.GetString(2), - reader.GetString(3), - reader.GetString(4), - reader.GetInt64(5) - ); - - private static void InsertOutbox( - SqliteConnection connection, - SqliteTransaction transaction, - BundleOutboxPublishRecord outbox, - DateTimeOffset sealedAt - ) - { - using var command = CreateCommand(connection, transaction); - command.CommandText = $""" - INSERT OR IGNORE INTO {RunLogSchema.BundleOutboxTableName} ( - bundle_id, run_id, file_name, content_sha256_hex, content_digest, - total_bytes, has_screenshot, sealed_at_ms, status, next_attempt_at_ms - ) VALUES ( - $bundleId, $runId, $fileName, $sha256, $contentDigest, - $totalBytes, $hasScreenshot, $sealedAt, 'pending', $sealedAt - ); - """; - command.Parameters.AddWithValue("$bundleId", outbox.BundleId); - command.Parameters.AddWithValue("$runId", outbox.RunId); - command.Parameters.AddWithValue("$fileName", outbox.FileName); - command.Parameters.AddWithValue("$sha256", outbox.ContentSha256Hex); - command.Parameters.AddWithValue("$contentDigest", outbox.ContentDigest); - command.Parameters.AddWithValue("$totalBytes", outbox.TotalBytes); - command.Parameters.AddWithValue("$hasScreenshot", outbox.HasScreenshot ? 1 : 0); - command.Parameters.AddWithValue("$sealedAt", sealedAt.ToUnixTimeMilliseconds()); - command.ExecuteNonQuery(); - } - - private static void DeleteJob( - SqliteConnection connection, - SqliteTransaction transaction, - string runId - ) => - Execute( - connection, - transaction, - $"DELETE FROM {RunLogSchema.BundleSealJobsTableName} WHERE run_id = $runId;", - ("$runId", runId) - ); - - private static BundleSealJobState ParseJobState(string value) => - value switch - { - "waiting" => BundleSealJobState.Waiting, - "sealing" => BundleSealJobState.Sealing, - "terminal_failure" => BundleSealJobState.TerminalFailure, - _ => throw new InvalidDataException($"Unknown bundle seal job state '{value}'."), - }; - - private static BundleScreenshotState ParseScreenshotState(string value) => - value switch - { - "not_requested" => BundleScreenshotState.NotRequested, - "waiting" => BundleScreenshotState.Waiting, - "available" => BundleScreenshotState.Available, - "unavailable" => BundleScreenshotState.Unavailable, - "timed_out" => BundleScreenshotState.TimedOut, - _ => throw new InvalidDataException($"Unknown bundle screenshot state '{value}'."), - }; - - private static string ToStorage(BundleSealJobState state) => - state switch - { - BundleSealJobState.Waiting => "waiting", - BundleSealJobState.Sealing => "sealing", - BundleSealJobState.TerminalFailure => "terminal_failure", - _ => throw new ArgumentOutOfRangeException(nameof(state)), - }; - - private static string ToStorage(BundleScreenshotState state) => - state switch - { - BundleScreenshotState.NotRequested => "not_requested", - BundleScreenshotState.Waiting => "waiting", - BundleScreenshotState.Available => "available", - BundleScreenshotState.Unavailable => "unavailable", - BundleScreenshotState.TimedOut => "timed_out", - _ => throw new ArgumentOutOfRangeException(nameof(state)), - }; - - private IReadOnlyList ListFileNames( - string sql, - params (string Name, object? Value)[] parameters - ) - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = sql; - AddParameters(command, parameters); - using var reader = command.ExecuteReader(); - var names = new List(); - while (reader.Read()) - names.Add(reader.GetString(0)); - return names; - } - - private void Execute(string sql, params (string Name, object? Value)[] parameters) - { - using var connection = OpenConnection(); - Execute(connection, null, sql, parameters); - } - - private static void Execute( - SqliteConnection connection, - SqliteTransaction? transaction, - string sql, - params (string Name, object? Value)[] parameters - ) - { - using var command = CreateCommand(connection, transaction); - command.CommandText = sql; - AddParameters(command, parameters); - command.ExecuteNonQuery(); - } - - private static void AddParameters( - SqliteCommand command, - IEnumerable<(string Name, object? Value)> parameters - ) - { - foreach (var (name, value) in parameters) - command.Parameters.AddWithValue(name, value ?? DBNull.Value); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/IPathProvider.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/IPathProvider.cs deleted file mode 100644 index 37a081d..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/IPathProvider.cs +++ /dev/null @@ -1,7 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.Paths; - -public interface IPathProvider -{ - string? DataRootDirectoryPath { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/PathConstants.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/PathConstants.cs deleted file mode 100644 index e1122c7..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/PathConstants.cs +++ /dev/null @@ -1,39 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.Paths; - -public static class PathConstants -{ - public const string RunLogDatabaseFileName = "bazaarplusplus.db"; - public const string DataRootDirectoryName = "BazaarPlusPlusV6"; - private const string CombatReplayDirectoryName = "CombatReplays"; - private const string ScreenshotsDirectoryName = "Screenshots"; - private const string BundleOutboxDirectoryName = "BundleOutbox"; - private const string CombatReplayVideoDirectoryName = "CombatReplayVideos"; - private const string FavoriteBattlesDirectoryName = "FavoriteBattles"; - - public static string RunLogDatabase(string dataRoot) => - Combine(dataRoot, RunLogDatabaseFileName); - - public static string CombatReplays(string dataRoot) => - Combine(dataRoot, CombatReplayDirectoryName); - - public static string Screenshots(string dataRoot) => - Combine(dataRoot, ScreenshotsDirectoryName); - - public static string BundleOutbox(string dataRoot) => - Combine(dataRoot, BundleOutboxDirectoryName); - - public static string CombatReplayVideos(string dataRoot) => - Combine(dataRoot, CombatReplayVideoDirectoryName); - - // A favorite's own replay copy: never evicted by replay retention, removed only with the favorite. - public static string FavoriteBattles(string dataRoot) => - Combine(dataRoot, FavoriteBattlesDirectoryName); - - private static string Combine(string dataRoot, string child) - { - if (string.IsNullOrWhiteSpace(dataRoot)) - throw new ArgumentException("Data root is required.", nameof(dataRoot)); - return Path.Combine(dataRoot, child); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/PathProviderExtensions.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/PathProviderExtensions.cs deleted file mode 100644 index 3c9bce3..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Paths/PathProviderExtensions.cs +++ /dev/null @@ -1,13 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.Paths; - -public static class PathProviderExtensions -{ - public static string RequireDataRoot(this IPathProvider paths) - { - if (paths == null) - throw new ArgumentNullException(nameof(paths)); - return paths.DataRootDirectoryPath - ?? throw new InvalidOperationException("Data root directory path is not initialized."); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Properties/AssemblyAttributes.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Properties/AssemblyAttributes.cs deleted file mode 100644 index 20fede6..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Properties/AssemblyAttributes.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("BppLog.Tests")] diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/IRunLogStore.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/IRunLogStore.cs deleted file mode 100644 index e0781fe..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/IRunLogStore.cs +++ /dev/null @@ -1,19 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public interface IRunLogStore -{ - RunLogSessionState? TryResumeActiveRun(); - - RunLogSessionState CreateRun(RunLogCreateRequest request); - - void SetPlayerAccountIdOnce(string runId, string? playerAccountId); - - void AppendEvent(string runId, RunLogEvent entry); - - void SaveCheckpoint(string runId, RunLogCheckpoint checkpoint); - - void CompleteRun(string runId, RunLogCompletion completion); - - void MarkRunAbandoned(string runId, RunLogAbandonment abandonment); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/IRunLogStoreLogger.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/IRunLogStoreLogger.cs deleted file mode 100644 index 7a0f45e..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/IRunLogStoreLogger.cs +++ /dev/null @@ -1,7 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public interface IRunLogStoreLogger -{ - void Emit(RunLogStoreDiagnostic diagnostic); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/Replication/QueuedRunLogStore.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/Replication/QueuedRunLogStore.cs deleted file mode 100644 index 17bf490..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/Replication/QueuedRunLogStore.cs +++ /dev/null @@ -1,234 +0,0 @@ -#nullable enable -using System.Collections.Concurrent; - -namespace BazaarPlusPlus.Storage.RunLog.Replication; - -public sealed class QueuedRunLogStore : IRunLogStore, IDisposable -{ - private static readonly TimeSpan DefaultShutdownDrainTimeout = TimeSpan.FromMilliseconds(2500); - - private readonly IRunLogStore _innerStore; - private readonly IRunLogStoreLogger? _logger; - private readonly TimeSpan _shutdownDrainTimeout; - private readonly object _lifecycleGate = new(); - private readonly ConcurrentQueue _pending = new(); - private readonly SemaphoreSlim _signal = new(0); - private readonly Task _worker; - private int _stopRequested; - private int _stopAcceptingNewWork; - private int _disposeStarted; - private int _activeWrites; - private int _shutdownDrainTimedOut; - - public QueuedRunLogStore(IRunLogStore innerStore, IRunLogStoreLogger? logger = null) - : this(innerStore, DefaultShutdownDrainTimeout, logger) { } - - internal QueuedRunLogStore( - IRunLogStore innerStore, - TimeSpan shutdownDrainTimeout, - IRunLogStoreLogger? logger = null - ) - { - _innerStore = innerStore ?? throw new ArgumentNullException(nameof(innerStore)); - _logger = logger; - _shutdownDrainTimeout = - shutdownDrainTimeout <= TimeSpan.Zero - ? DefaultShutdownDrainTimeout - : shutdownDrainTimeout; - _worker = Task.Run(ProcessLoopAsync); - } - - internal Task WorkerCompletion => _worker; - - public RunLogSessionState? TryResumeActiveRun() - { - return _innerStore.TryResumeActiveRun(); - } - - public RunLogSessionState CreateRun(RunLogCreateRequest request) - { - return _innerStore.CreateRun(request); - } - - public void SetPlayerAccountIdOnce(string runId, string? playerAccountId) - { - _innerStore.SetPlayerAccountIdOnce(runId, playerAccountId); - } - - public void AppendEvent(string runId, RunLogEvent entry) - { - EnqueueWrite( - RunLogStoreWriteOperation.AppendEvent, - runId, - () => _innerStore.AppendEvent(runId, entry) - ); - } - - public void SaveCheckpoint(string runId, RunLogCheckpoint checkpoint) - { - EnqueueWrite( - RunLogStoreWriteOperation.SaveCheckpoint, - runId, - () => _innerStore.SaveCheckpoint(runId, checkpoint) - ); - } - - public void CompleteRun(string runId, RunLogCompletion completion) - { - DrainPendingWrites(runId); - _innerStore.CompleteRun(runId, completion); - } - - public void MarkRunAbandoned(string runId, RunLogAbandonment abandonment) - { - DrainPendingWrites(runId); - _innerStore.MarkRunAbandoned(runId, abandonment); - } - - public void Dispose() - { - lock (_lifecycleGate) - { - if (Interlocked.Exchange(ref _disposeStarted, 1) == 1) - return; - - Volatile.Write(ref _stopAcceptingNewWork, 1); - Volatile.Write(ref _stopRequested, 1); - _signal.Release(); - } - - var workerCompleted = false; - try - { - workerCompleted = _worker.Wait(_shutdownDrainTimeout); - } - catch (AggregateException) when (_worker.IsCompleted) - { - // ProcessLoopAsync already emitted the authoritative typed worker diagnostic. Dispose - // still owns the synchronization primitive and must finish cleanup without surfacing a - // second terminal failure to the feature teardown path. - workerCompleted = true; - } - - if (!workerCompleted) - { - // The timeout is the authoritative shutdown terminal. Any active write or worker - // exception that follows (Mono aborts background threads during process exit) is a - // consequence of this same episode and must not emit a second terminal record. - Volatile.Write(ref _shutdownDrainTimedOut, 1); - _logger?.Emit( - RunLogStoreDiagnostic.ShutdownDrainTimedOut( - _shutdownDrainTimeout, - PendingWriteCount() - ) - ); - _ = _worker.ContinueWith( - static (_, state) => ((SemaphoreSlim)state!).Dispose(), - _signal, - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default - ); - return; - } - - _signal.Dispose(); - } - - private void DrainPendingWrites(string runId) - { - using var drained = new ManualResetEventSlim(false); - EnqueueWrite(RunLogStoreWriteOperation.DrainBarrier, runId, drained.Set); - if (!drained.Wait(_shutdownDrainTimeout)) - { - throw new TimeoutException( - "Timed out while waiting for queued run logging writes to drain." - ); - } - } - - private void EnqueueWrite(RunLogStoreWriteOperation operation, string runId, Action action) - { - if (action == null) - throw new ArgumentNullException(nameof(action)); - - lock (_lifecycleGate) - { - if (Volatile.Read(ref _stopAcceptingNewWork) == 1) - { - throw new ObjectDisposedException( - nameof(QueuedRunLogStore), - $"Cannot queue {operation} after shutdown." - ); - } - - _pending.Enqueue(new QueuedWrite(operation, runId, action)); - _signal.Release(); - } - } - - private async Task ProcessLoopAsync() - { - try - { - while (true) - { - while (_pending.TryDequeue(out var write)) - { - Interlocked.Increment(ref _activeWrites); - try - { - write.Execute(); - } - catch (Exception ex) - { - if (Volatile.Read(ref _shutdownDrainTimedOut) == 0) - { - _logger?.Emit( - RunLogStoreDiagnostic.WriteFailed(write.Operation, write.RunId, ex) - ); - } - } - finally - { - Interlocked.Decrement(ref _activeWrites); - } - } - - if (Volatile.Read(ref _stopRequested) == 1 && _pending.IsEmpty) - return; - - await _signal.WaitAsync().ConfigureAwait(false); - } - } - catch (Exception ex) - { - if (Volatile.Read(ref _shutdownDrainTimedOut) == 0) - _logger?.Emit(RunLogStoreDiagnostic.WorkerFailed(PendingWriteCount(), ex)); - throw; - } - } - - private int PendingWriteCount() => _pending.Count + Volatile.Read(ref _activeWrites); - - private readonly struct QueuedWrite - { - public QueuedWrite(RunLogStoreWriteOperation operation, string runId, Action action) - { - Operation = operation; - RunId = runId; - Action = action; - } - - public RunLogStoreWriteOperation Operation { get; } - - public string RunId { get; } - - private Action Action { get; } - - public void Execute() - { - Action(); - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogAbandonment.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogAbandonment.cs deleted file mode 100644 index dba534d..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogAbandonment.cs +++ /dev/null @@ -1,15 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public sealed class RunLogAbandonment -{ - public string Status { get; set; } = "abandoned"; - - public DateTimeOffset EndedAtUtc { get; set; } - - public int? FinalDay { get; set; } - - public int? FinalHour { get; set; } - - public string? Reason { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCheckpoint.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCheckpoint.cs deleted file mode 100644 index 29006c8..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCheckpoint.cs +++ /dev/null @@ -1,23 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public sealed class RunLogCheckpoint -{ - public long LastSeq { get; set; } - - public DateTimeOffset LastSeenAtUtc { get; set; } - - public int? Day { get; set; } - - public int? Hour { get; set; } - - public int? MaxHealth { get; set; } - - public int? Prestige { get; set; } - - public int? Level { get; set; } - - public int? Income { get; set; } - - public int? Gold { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCompletion.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCompletion.cs deleted file mode 100644 index 8a1b3ca..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCompletion.cs +++ /dev/null @@ -1,35 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public sealed class RunLogCompletion -{ - public string Status { get; set; } = "completed"; - - public DateTimeOffset EndedAtUtc { get; set; } - - public int? FinalDay { get; set; } - - public int? FinalHour { get; set; } - - public int? MaxHealth { get; set; } - - public int? Prestige { get; set; } - - public int? Level { get; set; } - - public int? Income { get; set; } - - public int? Gold { get; set; } - - public int? Victories { get; set; } - - public int? Losses { get; set; } - - public string? FinalPlayerRank { get; set; } - - public int? FinalPlayerRating { get; set; } - - public int? FinalPlayerRatingDelta { get; set; } - - public string? Reason { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCreateRequest.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCreateRequest.cs deleted file mode 100644 index 12de375..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogCreateRequest.cs +++ /dev/null @@ -1,33 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public sealed class RunLogCreateRequest -{ - public string RunId { get; set; } = string.Empty; - - public DateTimeOffset StartedAtUtc { get; set; } - - public string Hero { get; set; } = string.Empty; - - public string GameMode { get; set; } = string.Empty; - - public string? PlayerRank { get; set; } - - public int? PlayerRating { get; set; } - - public int? Day { get; set; } - - public int? Hour { get; set; } - - public string Status { get; set; } = "active"; - - // Game build channel the run was recorded on ("Online" / "Ptr" / "Unknown"); - // rows tagged "Ptr" are permanently excluded from server uploads. - public string? BuildChannel { get; set; } - - public string? PlayerAccountId { get; set; } - - public bool BundleScreenshotRequested { get; set; } - - public string? ModVersion { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogEvent.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogEvent.cs deleted file mode 100644 index ddbcb33..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogEvent.cs +++ /dev/null @@ -1,41 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public sealed class RunLogEvent -{ - // The payload_json shape, copied verbatim into the Bundle run segment; independent of the - // database user_version. - public const int PayloadSchemaVersion = 3; - - public int SchemaVersion { get; set; } = PayloadSchemaVersion; - - public string RunId { get; set; } = string.Empty; - - public long Seq { get; set; } - - public DateTimeOffset Ts { get; set; } - - public string Kind { get; set; } = string.Empty; - - public int? Day { get; set; } - - public int? Hour { get; set; } - - public string? Hero { get; set; } - - public string? GameMode { get; set; } - - public int? Victories { get; set; } - - public int? Losses { get; set; } - - public string? State { get; set; } - - public string? EncounterId { get; set; } - - public string? CombatKind { get; set; } - - public string? BattleId { get; set; } - - public string? OpponentName { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogRunIdentity.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogRunIdentity.cs deleted file mode 100644 index f71402e..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogRunIdentity.cs +++ /dev/null @@ -1,31 +0,0 @@ -#nullable enable - -namespace BazaarPlusPlus.Storage.RunLog; - -public static class RunLogRunIdentity -{ - private const string CollisionSeparator = ":bpp:"; - - public static string CreateCollisionId(string serverRunId) - { - if (string.IsNullOrWhiteSpace(serverRunId)) - throw new ArgumentException("Server run ID is required.", nameof(serverRunId)); - - return $"{serverRunId}{CollisionSeparator}{Guid.NewGuid():N}"; - } - - public static bool MatchesServerRunId(string localRunId, string serverRunId) - { - if (string.IsNullOrWhiteSpace(localRunId) || string.IsNullOrWhiteSpace(serverRunId)) - return false; - - if (string.Equals(localRunId, serverRunId, StringComparison.Ordinal)) - return true; - - var collisionPrefix = serverRunId + CollisionSeparator; - if (!localRunId.StartsWith(collisionPrefix, StringComparison.Ordinal)) - return false; - - return Guid.TryParseExact(localRunId[collisionPrefix.Length..], "N", out _); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs deleted file mode 100644 index f54dfef..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSchema.cs +++ /dev/null @@ -1,459 +0,0 @@ -#nullable enable -using System.Globalization; -using Microsoft.Data.Sqlite; - -namespace BazaarPlusPlus.Storage.RunLog; - -public static class RunLogSchema -{ - // `PRAGMA user_version`: the column shape the installer reads. Bump it only with a column change - // and a migration; a one-time data repair does not bump it (ADR-0011). V6 starts at 1 in its own - // Data Root; a V5 database is imported, never opened here. - public const int LocalDatabaseSchemaVersion = 1; - - // A favorite note is plain text the player types in History; the table CHECK enforces it. - public const int FavoriteNoteMaxLength = 500; - - private static readonly object InitializationGate = new(); - - public const string RunsTableName = "runs"; - public const string RunEventsTableName = "run_events"; - public const string BattlesTableName = "battles"; - public const string BattleSnapshotsTableName = "battle_snapshots"; - public const string RunScreenshotsTableName = "run_screenshots"; - public const string CombatReplayVideosTableName = "combat_replay_videos"; - public const string BundleSealJobsTableName = "bundle_seal_jobs"; - public const string BundleOutboxTableName = "bundle_outbox"; - - // A favorite is a snapshot, not a link: no foreign key, so deleting the Run or expiring the - // Ghost row keeps it. Its display columns keep their battles names and meanings. - public const string FavoriteBattlesTableName = "favorite_battles"; - public const string CaptureSourceEndOfRunAuto = "end_of_run_auto"; - - // Stable SQL expressions shared by history queries and their expression indexes. - public const string HistoryRunTime = "COALESCE(ended_at_ms,last_seen_at_ms,started_at_ms)"; - public const string HistoryWhitespace = - " \t\n\v\f\r\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000"; - public const string HistoryHeroKey = "lower(trim(hero,'" + HistoryWhitespace + "'))"; - - // Writers store 'player'/'opponent' and 'win'/'loss' verbatim; a Ghost Battle value the server - // did not normalize reads as undecided. - public const string HistoryRecorderOutcome = - "CASE lower(winner_combatant_id) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 " - + "ELSE CASE lower(result) WHEN 'win' THEN 1 WHEN 'loss' THEN -1 ELSE 0 END END"; - - // Every *_at_ms column holds Unix epoch milliseconds (UTC). bundle_outbox.run_id, - // run_screenshots.run_id and combat_replay_videos.battle_id have no foreign key on purpose: - // outbox rows outlive their Run, and screenshots and videos survive a deleted Run or battle. - public static string BootstrapSql => - $""" - PRAGMA foreign_keys = ON; - - CREATE TABLE IF NOT EXISTS {RunsTableName} ( - run_id TEXT PRIMARY KEY, - started_at_ms INTEGER NOT NULL, - last_seen_at_ms INTEGER NOT NULL, - status TEXT NOT NULL, - hero TEXT NOT NULL, - game_mode TEXT NOT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - day INTEGER NULL, - hour INTEGER NULL, - max_health INTEGER NULL, - prestige INTEGER NULL, - level INTEGER NULL, - income INTEGER NULL, - gold INTEGER NULL, - last_seq INTEGER NOT NULL DEFAULT 0, - ended_at_ms INTEGER NULL, - final_day INTEGER NULL, - final_hour INTEGER NULL, - victories INTEGER NULL, - losses INTEGER NULL, - final_player_rank TEXT NULL, - final_player_rating INTEGER NULL, - final_player_rating_delta INTEGER NULL, - reason TEXT NULL, - build_channel TEXT NULL, - player_account_id TEXT NULL, - bundle_screenshot_requested INTEGER NOT NULL DEFAULT 0, - mod_version TEXT NULL, - upload_policy TEXT NOT NULL DEFAULT 'bundle', - CHECK (status IN ('active', 'completed', 'abandoned')), - CHECK (upload_policy IN ('bundle', 'history_only')) - ); - - CREATE TABLE IF NOT EXISTS {RunEventsTableName} ( - run_id TEXT NOT NULL, - seq INTEGER NOT NULL, - ts_at_ms INTEGER NOT NULL, - kind TEXT NOT NULL, - payload_json TEXT NOT NULL, - PRIMARY KEY (run_id, seq), - FOREIGN KEY (run_id) REFERENCES {RunsTableName}(run_id) ON DELETE CASCADE - ); - - CREATE TABLE IF NOT EXISTS {BattlesTableName} ( - battle_id TEXT PRIMARY KEY, - remote_battle_id TEXT NULL, - uploader_account_id TEXT NULL, - source TEXT NOT NULL, - run_id TEXT NULL, - local_player_account_id TEXT NULL, - recorded_at_ms INTEGER NOT NULL, - day INTEGER NULL, - hour INTEGER NULL, - encounter_id TEXT NULL, - combat_kind TEXT NOT NULL, - player_name TEXT NULL, - player_account_id TEXT NULL, - player_hero TEXT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_level INTEGER NULL, - player_prestige INTEGER NULL, - player_income INTEGER NULL, - player_gold INTEGER NULL, - player_victories INTEGER NULL, - player_hand_item_count INTEGER NULL, - player_skill_count INTEGER NULL, - opponent_name TEXT NULL, - opponent_account_id TEXT NULL, - opponent_hero TEXT NULL, - opponent_rank TEXT NULL, - opponent_rating INTEGER NULL, - opponent_level INTEGER NULL, - opponent_prestige INTEGER NULL, - opponent_victories INTEGER NULL, - opponent_hand_item_count INTEGER NULL, - opponent_skill_count INTEGER NULL, - result TEXT NULL, - winner_combatant_id TEXT NULL, - loser_combatant_id TEXT NULL, - is_final_battle INTEGER NOT NULL DEFAULT 0, - bundle_id TEXT NULL, - download_url TEXT NULL, - download_url_expires_at_ms INTEGER NULL, - ghost_replay_state TEXT NULL, - ghost_replay_unavailable_reason TEXT NULL, - deleted_at_ms INTEGER NULL, - local_payload_state TEXT NULL, - local_payload_maintenance_at_ms INTEGER NULL, - FOREIGN KEY (run_id) REFERENCES {RunsTableName}(run_id) ON DELETE CASCADE, - CHECK ( - (source = 'LOCAL' AND remote_battle_id IS NULL AND uploader_account_id IS NULL) - OR - (source = 'GHOST' AND run_id IS NULL AND remote_battle_id IS NOT NULL AND uploader_account_id IS NOT NULL) - ), - CHECK ( - ghost_replay_state IS NULL OR ghost_replay_state IN ( - 'remote_available', 'local_ready', 'unavailable_payload', 'expired' - ) - ), - CHECK ( - (source = 'LOCAL' AND local_payload_state IS NOT NULL - AND local_payload_state IN ('ready', 'delete_pending', 'evicted', 'missing')) - OR - (source <> 'LOCAL' AND local_payload_state IS NULL) - ) - ); - - CREATE TABLE IF NOT EXISTS {BattleSnapshotsTableName} ( - battle_id TEXT PRIMARY KEY, - player_hand_json TEXT NOT NULL, - player_skills_json TEXT NOT NULL, - opponent_hand_json TEXT NOT NULL, - opponent_skills_json TEXT NOT NULL, - FOREIGN KEY (battle_id) REFERENCES {BattlesTableName}(battle_id) ON DELETE CASCADE - ); - - CREATE TABLE IF NOT EXISTS {RunScreenshotsTableName} ( - screenshot_id TEXT PRIMARY KEY, - run_id TEXT NULL, - hero_name TEXT NULL, - capture_source TEXT NOT NULL, - is_primary INTEGER NOT NULL DEFAULT 0, - image_relative_path TEXT NOT NULL, - captured_at_ms INTEGER NOT NULL, - captured_utc_offset_minutes INTEGER NOT NULL, - day INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_position INTEGER NULL, - victories_at_capture INTEGER NULL - ); - - CREATE TABLE IF NOT EXISTS {CombatReplayVideosTableName} ( - video_id TEXT PRIMARY KEY, - battle_id TEXT NOT NULL, - source TEXT NOT NULL, - video_relative_path TEXT NOT NULL, - width INTEGER NOT NULL, - height INTEGER NOT NULL, - fps INTEGER NOT NULL, - codec TEXT NOT NULL, - crf INTEGER NULL, - preset TEXT NULL, - started_at_ms INTEGER NOT NULL, - ended_at_ms INTEGER NULL, - duration_ms INTEGER NULL, - captured_frames INTEGER NOT NULL DEFAULT 0, - dropped_frames INTEGER NOT NULL DEFAULT 0, - file_size_bytes INTEGER NULL, - status TEXT NOT NULL, - error TEXT NULL, - attachment_state TEXT NOT NULL DEFAULT 'attached', - file_state TEXT NOT NULL DEFAULT 'pending', - detached_at_ms INTEGER NULL, - missing_at_ms INTEGER NULL, - last_reconciled_at_ms INTEGER NULL, - CHECK (status IN ('RECORDING', 'COMPLETED', 'FAILED')), - CHECK (attachment_state IN ('attached', 'detached')), - CHECK (file_state IN ('pending', 'present', 'missing')) - ); - - CREATE TABLE IF NOT EXISTS {BundleSealJobsTableName} ( - run_id TEXT PRIMARY KEY, - state TEXT NOT NULL DEFAULT 'waiting', - player_account_id TEXT NULL, - screenshot_requested INTEGER NOT NULL, - screenshot_state TEXT NOT NULL DEFAULT 'waiting', - input_deadline_at_ms INTEGER NOT NULL, - bundle_id TEXT NULL UNIQUE, - created_at_ms INTEGER NULL, - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_ms INTEGER NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - FOREIGN KEY (run_id) REFERENCES {RunsTableName}(run_id) ON DELETE CASCADE, - CHECK (state IN ('waiting', 'sealing', 'terminal_failure')), - CHECK (screenshot_state IN ('not_requested', 'waiting', 'available', 'unavailable', 'timed_out')) - ); - - CREATE TABLE IF NOT EXISTS {BundleOutboxTableName} ( - bundle_id TEXT PRIMARY KEY, - run_id TEXT NOT NULL, - file_name TEXT NOT NULL UNIQUE, - content_sha256_hex TEXT NOT NULL, - content_digest TEXT NOT NULL, - total_bytes INTEGER NOT NULL, - has_screenshot INTEGER NOT NULL, - sealed_at_ms INTEGER NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_ms INTEGER NULL, - next_attempt_at_ms INTEGER NULL, - failed_at_ms INTEGER NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - server_request_id TEXT NULL, - server_outcome TEXT NULL, - uploaded_at_ms INTEGER NULL, - CHECK (status IN ('pending', 'uploaded', 'permanent_failure')) - ); - - CREATE TABLE IF NOT EXISTS {FavoriteBattlesTableName} ( - battle_id TEXT PRIMARY KEY, - source TEXT NOT NULL, - favorited_at_ms INTEGER NOT NULL, - note TEXT NOT NULL DEFAULT '', - note_updated_at_ms INTEGER NULL, - favorite_payload_state TEXT NOT NULL, - run_id TEXT NULL, - local_player_account_id TEXT NULL, - uploader_account_id TEXT NULL, - remote_battle_id TEXT NULL, - recorded_at_ms INTEGER NOT NULL, - day INTEGER NULL, - hour INTEGER NULL, - encounter_id TEXT NULL, - combat_kind TEXT NOT NULL, - player_name TEXT NULL, - player_account_id TEXT NULL, - player_hero TEXT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_level INTEGER NULL, - player_prestige INTEGER NULL, - player_victories INTEGER NULL, - player_hand_item_count INTEGER NULL, - player_skill_count INTEGER NULL, - opponent_name TEXT NULL, - opponent_account_id TEXT NULL, - opponent_hero TEXT NULL, - opponent_rank TEXT NULL, - opponent_rating INTEGER NULL, - opponent_level INTEGER NULL, - opponent_prestige INTEGER NULL, - opponent_victories INTEGER NULL, - opponent_hand_item_count INTEGER NULL, - opponent_skill_count INTEGER NULL, - result TEXT NULL, - winner_combatant_id TEXT NULL, - loser_combatant_id TEXT NULL, - is_final_battle INTEGER NOT NULL DEFAULT 0, - player_hand_json TEXT NULL, - player_skills_json TEXT NULL, - opponent_hand_json TEXT NULL, - opponent_skills_json TEXT NULL, - CHECK (source IN ('LOCAL', 'GHOST')), - CHECK (favorite_payload_state IN ('ready', 'missing')), - CHECK (length(note) <= {FavoriteNoteMaxLength}) - ); - - CREATE INDEX IF NOT EXISTS idx_runs_history_recent ON runs({HistoryRunTime} DESC, run_id DESC); - CREATE INDEX IF NOT EXISTS idx_runs_history_hero ON runs({HistoryHeroKey}, {HistoryRunTime} DESC, run_id DESC); - CREATE INDEX IF NOT EXISTS idx_battles_history_local ON battles(run_id, recorded_at_ms DESC, battle_id DESC) WHERE source = 'LOCAL'; - CREATE INDEX IF NOT EXISTS idx_battles_history_ghost ON battles(local_player_account_id, recorded_at_ms DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_ms IS NULL; - CREATE INDEX IF NOT EXISTS idx_battles_history_ghost_outcome ON battles(local_player_account_id, {HistoryRecorderOutcome}, recorded_at_ms DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_ms IS NULL; - CREATE INDEX IF NOT EXISTS idx_battles_history_ghost_day ON battles(local_player_account_id, recorded_at_ms DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_ms IS NULL AND day >= 10; - CREATE INDEX IF NOT EXISTS idx_battles_history_ghost_day_outcome ON battles(local_player_account_id, {HistoryRecorderOutcome}, recorded_at_ms DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_ms IS NULL AND day >= 10; - - CREATE INDEX IF NOT EXISTS idx_{RunsTableName}_status_last_seen - ON {RunsTableName}(status, last_seen_at_ms DESC); - CREATE INDEX IF NOT EXISTS idx_{BattlesTableName}_run_id_recorded - ON {BattlesTableName}(run_id, recorded_at_ms DESC); - CREATE INDEX IF NOT EXISTS idx_{BattlesTableName}_source_recorded - ON {BattlesTableName}(source, recorded_at_ms DESC); - CREATE INDEX IF NOT EXISTS idx_{BattlesTableName}_local_player_recent - ON {BattlesTableName}(local_player_account_id, recorded_at_ms DESC); - CREATE UNIQUE INDEX IF NOT EXISTS idx_battles_ghost_identity - ON {BattlesTableName}(uploader_account_id, remote_battle_id) - WHERE source = 'GHOST'; - CREATE INDEX IF NOT EXISTS idx_battles_ghost_discovery - ON {BattlesTableName}(local_player_account_id, source, recorded_at_ms DESC); - CREATE INDEX IF NOT EXISTS idx_{RunScreenshotsTableName}_run_id_captured - ON {RunScreenshotsTableName}(run_id, captured_at_ms DESC); - CREATE INDEX IF NOT EXISTS idx_run_screenshots_source_captured - ON {RunScreenshotsTableName}(capture_source, captured_at_ms ASC, screenshot_id ASC); - CREATE UNIQUE INDEX IF NOT EXISTS idx_run_screenshots_primary_run - ON {RunScreenshotsTableName}(run_id) - WHERE is_primary = 1 AND run_id IS NOT NULL; - CREATE INDEX IF NOT EXISTS idx_{CombatReplayVideosTableName}_battle - ON {CombatReplayVideosTableName}(battle_id, started_at_ms DESC); - CREATE INDEX IF NOT EXISTS idx_combat_replay_videos_attachment - ON {CombatReplayVideosTableName}( - attachment_state, started_at_ms DESC, video_id - ); - CREATE INDEX IF NOT EXISTS idx_bundle_seal_jobs_state - ON {BundleSealJobsTableName}(state, input_deadline_at_ms, run_id); - CREATE UNIQUE INDEX IF NOT EXISTS idx_bundle_outbox_active_run - ON {BundleOutboxTableName}(run_id) - WHERE status = 'pending'; - CREATE INDEX IF NOT EXISTS idx_bundle_outbox_due - ON {BundleOutboxTableName}(status, next_attempt_at_ms, attempts, sealed_at_ms); - CREATE INDEX IF NOT EXISTS idx_bundle_outbox_run - ON {BundleOutboxTableName}(run_id, status); - CREATE INDEX IF NOT EXISTS idx_favorite_battles_recent - ON {FavoriteBattlesTableName}(favorited_at_ms DESC, battle_id DESC); - - PRAGMA user_version = {LocalDatabaseSchemaVersion}; - """; - - public static void EnsureInitialized(SqliteConnection connection) - { - if (connection == null) - throw new ArgumentNullException(nameof(connection)); - - lock (InitializationGate) - { - var currentVersion = ReadUserVersion(connection); - if (currentVersion > LocalDatabaseSchemaVersion) - { - throw new InvalidOperationException( - $"Run log schema version {currentVersion} is newer than supported version {LocalDatabaseSchemaVersion}." - ); - } - - using var transaction = connection.BeginTransaction(deferred: false); - // Re-read under the write lock: another process may have initialized this DB meanwhile. - var versionInsideTransaction = ReadUserVersion(connection, transaction); - if ( - versionInsideTransaction != 0 - && versionInsideTransaction != LocalDatabaseSchemaVersion - ) - throw new InvalidOperationException( - $"Unsupported run log schema version {versionInsideTransaction}." - ); - DropDriftedIndexes(connection, transaction); - Execute(connection, transaction, BootstrapSql); - transaction.Commit(); - } - } - - // CREATE INDEX IF NOT EXISTS never redefines an existing index, and History pages name - // their index in INDEXED BY, which fails when the stored definition cannot serve the query. - // An index whose stored SQL differs from BootstrapSql's is dropped here so BootstrapSql - // recreates it. Retired index names still need an explicit DROP INDEX IF EXISTS. - private static void DropDriftedIndexes( - SqliteConnection connection, - SqliteTransaction transaction - ) - { - var drifted = new List(); - foreach (var (name, storedSql) in ReadIndexDefinitions(connection, transaction)) - { - if ( - ExpectedIndexDefinitions.Value.TryGetValue(name, out var expectedSql) - && !string.Equals(storedSql, expectedSql, StringComparison.Ordinal) - ) - drifted.Add(name); - } - foreach (var name in drifted) - Execute(connection, transaction, $"DROP INDEX \"{name}\";"); - } - - // SQLite stores an index's CREATE statement minus IF NOT EXISTS, so the definitions - // BootstrapSql produces on an empty database are the exact text a current index carries. - private static readonly Lazy> ExpectedIndexDefinitions = new(() => - { - using var scratch = new SqliteConnection("Data Source=:memory:"); - scratch.Open(); - using var transaction = scratch.BeginTransaction(); - Execute(scratch, transaction, BootstrapSql); - var definitions = new Dictionary(StringComparer.Ordinal); - foreach (var (name, sql) in ReadIndexDefinitions(scratch, transaction)) - definitions[name] = sql; - return definitions; - }); - - private static List<(string Name, string Sql)> ReadIndexDefinitions( - SqliteConnection connection, - SqliteTransaction transaction - ) - { - using var command = connection.CreateCommand(); - command.Transaction = transaction; - command.CommandText = - "SELECT name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL;"; - using var reader = command.ExecuteReader(); - var definitions = new List<(string, string)>(); - while (reader.Read()) - definitions.Add((reader.GetString(0), reader.GetString(1))); - return definitions; - } - - private static int ReadUserVersion( - SqliteConnection connection, - SqliteTransaction? transaction = null - ) - { - using var command = connection.CreateCommand(); - command.Transaction = transaction; - command.CommandText = "PRAGMA user_version;"; - return Convert.ToInt32(command.ExecuteScalar(), CultureInfo.InvariantCulture); - } - - private static void Execute( - SqliteConnection connection, - SqliteTransaction transaction, - string sql - ) - { - using var command = connection.CreateCommand(); - command.Transaction = transaction; - command.CommandText = sql; - command.ExecuteNonQuery(); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSessionState.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSessionState.cs deleted file mode 100644 index 123e0ff..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogSessionState.cs +++ /dev/null @@ -1,27 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public sealed class RunLogSessionState -{ - public string RunId { get; set; } = string.Empty; - - public DateTimeOffset StartedAtUtc { get; set; } - - public DateTimeOffset LastSeenAtUtc { get; set; } - - public long LastSeq { get; set; } - - public int? Day { get; set; } - - public int? Hour { get; set; } - - public int? MaxHealth { get; set; } - - public int? Prestige { get; set; } - - public int? Level { get; set; } - - public int? Income { get; set; } - - public int? Gold { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogStore.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogStore.cs deleted file mode 100644 index 2c9fd32..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogStore.cs +++ /dev/null @@ -1,455 +0,0 @@ -#nullable enable -using System.Globalization; -using BazaarPlusPlus.Storage.Paths; -using BazaarPlusPlus.Storage.Sqlite; -using Microsoft.Data.Sqlite; -using Newtonsoft.Json; - -namespace BazaarPlusPlus.Storage.RunLog; - -public sealed class RunLogStore : SqliteStoreBase, IRunLogStore -{ - private const string ActiveStatus = "active"; - - private static readonly JsonSerializerSettings SerializerSettings = - SerializerSettingsFactory.CreateSerializerSettings(includeStringEnumConverter: false); - - public RunLogStore(IPathProvider paths) - : base(PathConstants.RunLogDatabase(paths.RequireDataRoot())) { } - - public RunLogSessionState? TryResumeActiveRun() - { - using var connection = OpenConnection(); - return TryReadActiveRun(connection); - } - - public RunLogSessionState CreateRun(RunLogCreateRequest request) - { - using var connection = OpenConnection(); - using var transaction = connection.BeginTransaction(); - - var effectiveRunId = IsClosedToResume(connection, transaction, request.RunId) - ? RunLogRunIdentity.CreateCollisionId(request.RunId) - : request.RunId; - - using var command = CreateCommand(connection, transaction); - command.CommandText = $""" - INSERT INTO {RunLogSchema.RunsTableName} ( - run_id, - started_at_ms, - last_seen_at_ms, - status, - hero, - game_mode, - player_rank, - player_rating, - day, - hour, - last_seq, - build_channel, - player_account_id, - bundle_screenshot_requested, - mod_version - ) VALUES ( - $runId, - $startedAtMs, - $lastSeenAtMs, - $status, - $hero, - $gameMode, - $playerRank, - $playerRating, - $day, - $hour, - 0, - $buildChannel, - $playerAccountId, - $bundleScreenshotRequested, - $modVersion - ) - ON CONFLICT(run_id) DO UPDATE SET - hero = excluded.hero, - game_mode = excluded.game_mode, - player_rank = COALESCE(excluded.player_rank, {RunLogSchema.RunsTableName}.player_rank), - player_rating = COALESCE(excluded.player_rating, {RunLogSchema.RunsTableName}.player_rating), - day = COALESCE({RunLogSchema.RunsTableName}.day, excluded.day), - hour = COALESCE({RunLogSchema.RunsTableName}.hour, excluded.hour), - player_account_id = COALESCE({RunLogSchema.RunsTableName}.player_account_id, excluded.player_account_id), - status = excluded.status; - """; - command.Parameters.AddWithValue("$runId", effectiveRunId); - command.Parameters.AddWithValue( - "$startedAtMs", - request.StartedAtUtc.ToUnixTimeMilliseconds() - ); - command.Parameters.AddWithValue( - "$lastSeenAtMs", - request.StartedAtUtc.ToUnixTimeMilliseconds() - ); - command.Parameters.AddWithValue("$status", request.Status); - command.Parameters.AddWithValue("$hero", request.Hero); - command.Parameters.AddWithValue("$gameMode", request.GameMode); - AddNullableString(command, "$playerRank", request.PlayerRank); - AddNullableInt32(command, "$playerRating", request.PlayerRating); - AddNullableInt32(command, "$day", request.Day); - AddNullableInt32(command, "$hour", request.Hour); - AddNullableString(command, "$buildChannel", request.BuildChannel); - AddNullableString(command, "$playerAccountId", NormalizeAccountId(request.PlayerAccountId)); - command.Parameters.AddWithValue( - "$bundleScreenshotRequested", - request.BundleScreenshotRequested ? 1 : 0 - ); - AddNullableString(command, "$modVersion", request.ModVersion); - command.ExecuteNonQuery(); - - var session = - TryReadActiveRun(connection, transaction, effectiveRunId) - ?? throw new InvalidOperationException( - $"Run {effectiveRunId} could not be loaded after create." - ); - - transaction.Commit(); - return session; - } - - public void SetPlayerAccountIdOnce(string runId, string? playerAccountId) - { - var normalizedAccountId = NormalizeAccountId(playerAccountId); - if (normalizedAccountId == null) - return; - - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = $""" - UPDATE {RunLogSchema.RunsTableName} - SET player_account_id = COALESCE(player_account_id, $playerAccountId) - WHERE run_id = $runId; - """; - command.Parameters.AddWithValue("$runId", runId); - command.Parameters.AddWithValue("$playerAccountId", normalizedAccountId); - command.ExecuteNonQuery(); - } - - public void AppendEvent(string runId, RunLogEvent entry) - { - var payloadJson = JsonConvert.SerializeObject(entry, SerializerSettings); - using var connection = OpenConnection(); - using var transaction = connection.BeginTransaction(); - - using var command = CreateCommand(connection, transaction); - command.CommandText = $""" - INSERT INTO {RunLogSchema.RunEventsTableName} ( - run_id, - seq, - ts_at_ms, - kind, - payload_json - ) VALUES ( - $runId, - $seq, - $tsAtMs, - $kind, - $payloadJson - ); - """; - command.Parameters.AddWithValue("$runId", runId); - command.Parameters.AddWithValue("$seq", entry.Seq); - command.Parameters.AddWithValue("$tsAtMs", entry.Ts.ToUnixTimeMilliseconds()); - command.Parameters.AddWithValue("$kind", entry.Kind); - command.Parameters.AddWithValue("$payloadJson", payloadJson); - command.ExecuteNonQuery(); - - using var updateRun = CreateCommand(connection, transaction); - updateRun.CommandText = $""" - UPDATE {RunLogSchema.RunsTableName} - SET last_seq = MAX(last_seq, $seq), - last_seen_at_ms = MAX(last_seen_at_ms, $tsAtMs), - day = COALESCE($day, day), - hour = COALESCE($hour, hour) - WHERE run_id = $runId; - """; - updateRun.Parameters.AddWithValue("$runId", runId); - updateRun.Parameters.AddWithValue("$seq", entry.Seq); - updateRun.Parameters.AddWithValue("$tsAtMs", entry.Ts.ToUnixTimeMilliseconds()); - AddNullableInt32(updateRun, "$day", entry.Day); - AddNullableInt32(updateRun, "$hour", entry.Hour); - updateRun.ExecuteNonQuery(); - - transaction.Commit(); - } - - public void SaveCheckpoint(string runId, RunLogCheckpoint checkpoint) - { - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = $""" - UPDATE {RunLogSchema.RunsTableName} - SET last_seq = $lastSeq, - last_seen_at_ms = $lastSeenAtMs, - day = $day, - hour = $hour, - max_health = $maxHealth, - prestige = $prestige, - level = $level, - income = $income, - gold = $gold - WHERE run_id = $runId; - """; - command.Parameters.AddWithValue("$runId", runId); - command.Parameters.AddWithValue("$lastSeq", checkpoint.LastSeq); - command.Parameters.AddWithValue( - "$lastSeenAtMs", - checkpoint.LastSeenAtUtc.ToUnixTimeMilliseconds() - ); - AddNullableInt32(command, "$day", checkpoint.Day); - AddNullableInt32(command, "$hour", checkpoint.Hour); - AddNullableInt32(command, "$maxHealth", checkpoint.MaxHealth); - AddNullableInt32(command, "$prestige", checkpoint.Prestige); - AddNullableInt32(command, "$level", checkpoint.Level); - AddNullableInt32(command, "$income", checkpoint.Income); - AddNullableInt32(command, "$gold", checkpoint.Gold); - command.ExecuteNonQuery(); - } - - public void CompleteRun(string runId, RunLogCompletion completion) - { - WriteTerminalStatus( - runId, - completion.Status, - completion.EndedAtUtc, - completion.FinalDay, - completion.FinalHour, - completion.MaxHealth, - completion.Prestige, - completion.Level, - completion.Income, - completion.Gold, - completion.Victories, - completion.Losses, - completion.FinalPlayerRank, - completion.FinalPlayerRating, - completion.FinalPlayerRatingDelta, - completion.Reason - ); - } - - public void MarkRunAbandoned(string runId, RunLogAbandonment abandonment) - { - WriteTerminalStatus( - runId, - abandonment.Status, - abandonment.EndedAtUtc, - abandonment.FinalDay, - abandonment.FinalHour, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - abandonment.Reason - ); - } - - private void WriteTerminalStatus( - string runId, - string status, - DateTimeOffset endedAtUtc, - int? finalDay, - int? finalHour, - int? maxHealth, - int? prestige, - int? level, - int? income, - int? gold, - int? victories, - int? losses, - string? finalPlayerRank, - int? finalPlayerRating, - int? finalPlayerRatingDelta, - string? reason - ) - { - using var connection = OpenConnection(); - using var transaction = connection.BeginTransaction(); - - var resolvedFinalPlayerRatingDelta = - finalPlayerRatingDelta - ?? ResolvePlayerRatingDelta(connection, transaction, runId, finalPlayerRating); - - using var command = CreateCommand(connection, transaction); - command.CommandText = $""" - UPDATE {RunLogSchema.RunsTableName} - SET status = $status, - ended_at_ms = $endedAtMs, - final_day = $finalDay, - final_hour = $finalHour, - day = COALESCE($finalDay, day), - hour = COALESCE($finalHour, hour), - max_health = COALESCE($maxHealth, max_health), - prestige = COALESCE($prestige, prestige), - level = COALESCE($level, level), - income = COALESCE($income, income), - gold = COALESCE($gold, gold), - victories = $victories, - losses = $losses, - final_player_rank = $finalPlayerRank, - final_player_rating = $finalPlayerRating, - final_player_rating_delta = $finalPlayerRatingDelta, - reason = $reason - WHERE run_id = $runId; - """; - command.Parameters.AddWithValue("$runId", runId); - command.Parameters.AddWithValue("$status", status); - command.Parameters.AddWithValue("$endedAtMs", endedAtUtc.ToUnixTimeMilliseconds()); - AddNullableInt32(command, "$finalDay", finalDay); - AddNullableInt32(command, "$finalHour", finalHour); - AddNullableInt32(command, "$maxHealth", maxHealth); - AddNullableInt32(command, "$prestige", prestige); - AddNullableInt32(command, "$level", level); - AddNullableInt32(command, "$income", income); - AddNullableInt32(command, "$gold", gold); - AddNullableInt32(command, "$victories", victories); - AddNullableInt32(command, "$losses", losses); - AddNullableString(command, "$finalPlayerRank", finalPlayerRank); - AddNullableInt32(command, "$finalPlayerRating", finalPlayerRating); - AddNullableInt32(command, "$finalPlayerRatingDelta", resolvedFinalPlayerRatingDelta); - AddNullableString(command, "$reason", reason); - command.ExecuteNonQuery(); - - transaction.Commit(); - } - - private static int? ResolvePlayerRatingDelta( - SqliteConnection connection, - SqliteTransaction transaction, - string runId, - int? finalPlayerRating - ) - { - if (!finalPlayerRating.HasValue) - return null; - - using var command = CreateCommand(connection, transaction); - command.CommandText = $""" - SELECT player_rating - FROM {RunLogSchema.RunsTableName} - WHERE run_id = $runId; - """; - command.Parameters.AddWithValue("$runId", runId); - - // Without a starting rating the change is unknown, not zero: History renders NULL as "—". - var initialPlayerRating = command.ExecuteScalar(); - if (initialPlayerRating == null || initialPlayerRating is DBNull) - return null; - - return finalPlayerRating.Value - - Convert.ToInt32(initialPlayerRating, CultureInfo.InvariantCulture); - } - - // A Run id this session cannot continue gets a collision id instead of reopening the row: a - // terminal Run, or a History-Only Run (imported history the mod never writes into). - private static bool IsClosedToResume( - SqliteConnection connection, - SqliteTransaction transaction, - string runId - ) - { - using var command = CreateCommand(connection, transaction); - command.CommandText = $""" - SELECT 1 - FROM {RunLogSchema.RunsTableName} - WHERE run_id = $runId - AND NOT ({ResumableRunCondition(RunLogSchema.RunsTableName)}) - LIMIT 1; - """; - command.Parameters.AddWithValue("$runId", runId); - return command.ExecuteScalar() != null; - } - - /// - /// The SQL condition for a Run the mod may resume or show as the current Run, over the runs - /// row aliased : active and not History-Only. The mod never writes - /// history_only; this keeps an unfinished imported Run from being continued even if - /// the import left it active. - /// - public static string ResumableRunCondition(string runAlias) => - $"({runAlias}.status = '{ActiveStatus}' AND {runAlias}.upload_policy = 'bundle')"; - - private static RunLogSessionState? TryReadActiveRun( - SqliteConnection connection, - SqliteTransaction? transaction = null, - string? runId = null - ) - { - using var command = CreateCommand(connection, transaction); - command.CommandText = - runId == null - ? $""" - SELECT * - FROM {RunLogSchema.RunsTableName} - WHERE {ResumableRunCondition(RunLogSchema.RunsTableName)} - ORDER BY last_seen_at_ms DESC - LIMIT 1; - """ - : $""" - SELECT * - FROM {RunLogSchema.RunsTableName} - WHERE {ResumableRunCondition(RunLogSchema.RunsTableName)} - AND run_id = $runId - LIMIT 1; - """; - if (runId != null) - command.Parameters.AddWithValue("$runId", runId); - - using var reader = command.ExecuteReader(); - if (!reader.Read()) - return null; - - return ReadSessionState(reader); - } - - private static RunLogSessionState? ReadSessionState(SqliteDataReader reader) - { - if ( - !string.Equals( - reader.GetString(reader.GetOrdinal("status")), - ActiveStatus, - StringComparison.Ordinal - ) - ) - return null; - - var startedAtUtc = DateTimeOffset.FromUnixTimeMilliseconds( - reader.GetInt64(reader.GetOrdinal("started_at_ms")) - ); - var lastSeenAtUtc = DateTimeOffset.FromUnixTimeMilliseconds( - reader.GetInt64(reader.GetOrdinal("last_seen_at_ms")) - ); - - return new RunLogSessionState - { - RunId = reader.GetString(reader.GetOrdinal("run_id")), - StartedAtUtc = startedAtUtc, - LastSeenAtUtc = lastSeenAtUtc, - LastSeq = GetNullableInt64(reader, "last_seq") ?? 0, - Day = GetNullableInt32(reader, "day"), - Hour = GetNullableInt32(reader, "hour"), - MaxHealth = GetNullableInt32(reader, "max_health"), - Prestige = GetNullableInt32(reader, "prestige"), - Level = GetNullableInt32(reader, "level"), - Income = GetNullableInt32(reader, "income"), - Gold = GetNullableInt32(reader, "gold"), - }; - } - - private static string? NormalizeAccountId(string? playerAccountId) - { - var normalized = playerAccountId?.Trim(); - return string.IsNullOrEmpty(normalized) ? null : normalized; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogStoreDiagnostic.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogStoreDiagnostic.cs deleted file mode 100644 index 6384807..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunLog/RunLogStoreDiagnostic.cs +++ /dev/null @@ -1,80 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunLog; - -public enum RunLogStoreDiagnosticKind -{ - ShutdownDrainTimedOut, - WriteFailed, - WorkerFailed, -} - -public enum RunLogStoreWriteOperation -{ - AppendEvent, - SaveCheckpoint, - DrainBarrier, -} - -public sealed class RunLogStoreDiagnostic -{ - private RunLogStoreDiagnostic( - RunLogStoreDiagnosticKind kind, - long? timeoutMilliseconds, - int pendingCount, - RunLogStoreWriteOperation? operation, - string? runId, - Exception? exception - ) - { - Kind = kind; - TimeoutMilliseconds = timeoutMilliseconds; - PendingCount = pendingCount; - Operation = operation; - RunId = runId; - Exception = exception; - } - - public RunLogStoreDiagnosticKind Kind { get; } - - public long? TimeoutMilliseconds { get; } - - public int PendingCount { get; } - - public RunLogStoreWriteOperation? Operation { get; } - - public string? RunId { get; } - - public Exception? Exception { get; } - - internal static RunLogStoreDiagnostic ShutdownDrainTimedOut( - TimeSpan timeout, - int pendingCount - ) => - new( - RunLogStoreDiagnosticKind.ShutdownDrainTimedOut, - ToMilliseconds(timeout), - pendingCount, - null, - null, - null - ); - - internal static RunLogStoreDiagnostic WriteFailed( - RunLogStoreWriteOperation operation, - string runId, - Exception exception - ) => new(RunLogStoreDiagnosticKind.WriteFailed, null, 0, operation, runId, exception); - - internal static RunLogStoreDiagnostic WorkerFailed(int pendingCount, Exception exception) => - new(RunLogStoreDiagnosticKind.WorkerFailed, null, pendingCount, null, null, exception); - - private static long ToMilliseconds(TimeSpan timeout) - { - var milliseconds = timeout.TotalMilliseconds; - if (milliseconds >= long.MaxValue) - return long.MaxValue; - if (milliseconds <= 0) - return 0; - return (long)Math.Ceiling(milliseconds); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunScreenshot/RunScreenshotRecord.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunScreenshot/RunScreenshotRecord.cs deleted file mode 100644 index 35bc685..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunScreenshot/RunScreenshotRecord.cs +++ /dev/null @@ -1,42 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.RunScreenshot; - -public sealed class RunScreenshotRecord -{ - public string ScreenshotId { get; set; } = string.Empty; - - public string? RunId { get; set; } - - public string? HeroName { get; set; } - - public bool IsPrimary { get; set; } - - public string ImageRelativePath { get; set; } = string.Empty; - - // The capture instant in the player's local offset; only its offset is stored. - public DateTimeOffset CapturedAtLocal { get; set; } - - public DateTimeOffset CapturedAtUtc { get; set; } - - public int? Day { get; set; } - - public string? PlayerRank { get; set; } - - public int? PlayerRating { get; set; } - - public int? PlayerPosition { get; set; } - - public int? VictoriesAtCapture { get; set; } -} - -public sealed class RunScreenshotArtifact -{ - public RunScreenshotArtifact(string imageRelativePath, DateTimeOffset capturedAtUtc) - { - ImageRelativePath = imageRelativePath; - CapturedAtUtc = capturedAtUtc; - } - - public string ImageRelativePath { get; } - public DateTimeOffset CapturedAtUtc { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunScreenshot/RunScreenshotSqliteStore.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunScreenshot/RunScreenshotSqliteStore.cs deleted file mode 100644 index 0912e44..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/RunScreenshot/RunScreenshotSqliteStore.cs +++ /dev/null @@ -1,97 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Storage.RunLog; -using BazaarPlusPlus.Storage.Sqlite; - -namespace BazaarPlusPlus.Storage.RunScreenshot; - -public sealed class RunScreenshotSqliteStore : SqliteStoreBase -{ - public RunScreenshotSqliteStore(string databasePath) - : base(databasePath) { } - - public void Save(RunScreenshotRecord record) - { - if (record == null) - throw new ArgumentNullException(nameof(record)); - if (string.IsNullOrWhiteSpace(record.ScreenshotId)) - throw new ArgumentException("Screenshot id is required.", nameof(record)); - if (string.IsNullOrWhiteSpace(record.ImageRelativePath)) - throw new ArgumentException("Image path is required.", nameof(record)); - - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = $""" - INSERT INTO {RunLogSchema.RunScreenshotsTableName} ( - screenshot_id, - run_id, - hero_name, - capture_source, - is_primary, - image_relative_path, - captured_at_ms, - captured_utc_offset_minutes, - day, - player_rank, - player_rating, - player_position, - victories_at_capture - ) VALUES ( - $screenshotId, - $runId, - $heroName, - $captureSource, - $isPrimary, - $imageRelativePath, - $capturedAtMs, - $capturedUtcOffsetMinutes, - $day, - $playerRank, - $playerRating, - $playerPosition, - $victoriesAtCapture - ); - """; - command.Parameters.AddWithValue("$screenshotId", record.ScreenshotId); - command.Parameters.AddWithValue("$runId", (object?)record.RunId ?? DBNull.Value); - command.Parameters.AddWithValue("$heroName", (object?)record.HeroName ?? DBNull.Value); - command.Parameters.AddWithValue("$captureSource", RunLogSchema.CaptureSourceEndOfRunAuto); - command.Parameters.AddWithValue("$isPrimary", record.IsPrimary ? 1 : 0); - command.Parameters.AddWithValue("$imageRelativePath", record.ImageRelativePath); - command.Parameters.AddWithValue( - "$capturedAtMs", - record.CapturedAtUtc.ToUnixTimeMilliseconds() - ); - command.Parameters.AddWithValue( - "$capturedUtcOffsetMinutes", - (int)record.CapturedAtLocal.Offset.TotalMinutes - ); - AddNullableInt32(command, "$day", record.Day); - command.Parameters.AddWithValue("$playerRank", (object?)record.PlayerRank ?? DBNull.Value); - AddNullableInt32(command, "$playerRating", record.PlayerRating); - AddNullableInt32(command, "$playerPosition", record.PlayerPosition); - AddNullableInt32(command, "$victoriesAtCapture", record.VictoriesAtCapture); - command.ExecuteNonQuery(); - } - - public RunScreenshotArtifact? TryGetLatestPrimaryForRun(string runId) - { - if (string.IsNullOrWhiteSpace(runId)) - throw new ArgumentException("Run id is required.", nameof(runId)); - using var connection = OpenConnection(); - using var command = CreateCommand(connection); - command.CommandText = $""" - SELECT image_relative_path, captured_at_ms - FROM {RunLogSchema.RunScreenshotsTableName} - WHERE run_id = $runId AND is_primary = 1 - ORDER BY captured_at_ms DESC LIMIT 1; - """; - command.Parameters.AddWithValue("$runId", runId); - using var reader = command.ExecuteReader(); - return reader.Read() - ? new RunScreenshotArtifact( - reader.GetString(0), - DateTimeOffset.FromUnixTimeMilliseconds(reader.GetInt64(1)) - ) - : null; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/SerializerSettingsFactory.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/SerializerSettingsFactory.cs deleted file mode 100644 index ed7b7a0..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/SerializerSettingsFactory.cs +++ /dev/null @@ -1,28 +0,0 @@ -#nullable enable -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Serialization; - -namespace BazaarPlusPlus.Storage; - -public static class SerializerSettingsFactory -{ - public static JsonSerializerSettings CreateSerializerSettings(bool includeStringEnumConverter) - { - var settings = new JsonSerializerSettings - { - ContractResolver = new DefaultContractResolver - { - NamingStrategy = new SnakeCaseNamingStrategy(), - }, - NullValueHandling = NullValueHandling.Ignore, - Formatting = Formatting.None, - DateFormatString = "yyyy-MM-dd'T'HH:mm:ss.fffK", - }; - - if (includeStringEnumConverter) - settings.Converters.Add(new StringEnumConverter()); - - return settings; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteAvailability.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteAvailability.cs deleted file mode 100644 index 8d4f266..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteAvailability.cs +++ /dev/null @@ -1,39 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Storage.Sqlite; - -/// -/// One-shot probe for whether the SQLite native library can actually be loaded. -/// -/// On the Android port the bundled libe_sqlite3.so lives on shared storage, which the -/// Android linker refuses to dlopen from (namespace isolation). Probing once turns that into -/// a flag the stores can consult, instead of a that -/// aborts the whole plugin composition. -/// -public static class SqliteAvailability -{ - private static readonly Lazy Probe = new(ProbeCore); - - public static bool IsAvailable => Probe.Value; - - public static string UnavailableReason { get; private set; } = "unknown"; - - private static bool ProbeCore() - { - try - { - SQLitePCL.Batteries_V2.Init(); - using var connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source=:memory:"); - connection.Open(); - using var command = connection.CreateCommand(); - command.CommandText = "SELECT sqlite_version();"; - command.ExecuteScalar(); - UnavailableReason = string.Empty; - return true; - } - catch (Exception ex) - { - UnavailableReason = ex.Message; - return false; - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteShutdown.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteShutdown.cs deleted file mode 100644 index 7fee8b0..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteShutdown.cs +++ /dev/null @@ -1,48 +0,0 @@ -#nullable enable -using Microsoft.Data.Sqlite; - -namespace BazaarPlusPlus.Storage.Sqlite; - -/// -/// Hands the run-log database over to other processes on shutdown. -/// -/// -/// The installer opens this database directly while the game owns it. Two -/// details make an unmanaged exit hostile to that reader: Microsoft.Data.Sqlite -/// pools connections, so disposing a store's connection only returns the native -/// handle to the pool and the -wal/-shm files stay open for the -/// whole process lifetime; and nothing ever checkpoints, so the WAL that -/// survives the process holds committed data the main database file does not. -/// A reader that inherits that state has to recover the WAL before it can see -/// recent runs. Releasing the pool and truncating the WAL here leaves a -/// self-contained database file behind instead. -/// -public static class SqliteShutdown -{ - public static void ReleaseRunLogDatabase(string? databasePath) - { - // Drop pooled handles first: a checkpoint cannot reclaim WAL frames that - // idle pooled connections still hold read marks on. - SqliteConnection.ClearAllPools(); - - if (!string.IsNullOrWhiteSpace(databasePath) && File.Exists(databasePath)) - Checkpoint(databasePath!); - - // The checkpoint connection went back to the pool on dispose; clear again - // so the process leaves no sqlite3 handle, and no -shm mapping, behind. - SqliteConnection.ClearAllPools(); - } - - private static void Checkpoint(string databasePath) - { - using var connection = new SqliteConnection($"Data Source={databasePath}"); - connection.Open(); - using var command = connection.CreateCommand(); - command.CommandTimeout = 5; - command.CommandText = """ - PRAGMA busy_timeout = 2000; - PRAGMA wal_checkpoint(TRUNCATE); - """; - command.ExecuteNonQuery(); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteStoreBase.cs b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteStoreBase.cs deleted file mode 100644 index 704d76c..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/Sqlite/SqliteStoreBase.cs +++ /dev/null @@ -1,122 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Storage.RunLog; -using Microsoft.Data.Sqlite; - -namespace BazaarPlusPlus.Storage.Sqlite; - -public abstract class SqliteStoreBase -{ - private readonly string _databasePath; - private readonly string _connectionString; - - protected SqliteStoreBase(string databasePath) - { - if (string.IsNullOrWhiteSpace(databasePath)) - throw new ArgumentException("Database path is required.", nameof(databasePath)); - - _databasePath = databasePath; - _connectionString = new SqliteConnectionStringBuilder - { - DataSource = _databasePath, - ForeignKeys = true, - }.ConnectionString; - - // A platform without a loadable SQLite native library keeps the store object alive but - // unusable, so construction never aborts the caller's composition. - if (!SqliteAvailability.IsAvailable) - { - IsAvailable = false; - return; - } - - var directory = Path.GetDirectoryName(_databasePath); - if (!string.IsNullOrWhiteSpace(directory)) - Directory.CreateDirectory(directory); - - IsAvailable = true; - using var connection = OpenConnection(); - EnableWriteAheadLogging(connection); - RunLogSchema.EnsureInitialized(connection); - } - - /// False when the SQLite native library could not be loaded on this platform. - public bool IsAvailable { get; private set; } - - protected SqliteConnection OpenConnection() - { - if (!IsAvailable) - throw new InvalidOperationException( - $"SQLite is unavailable on this platform: {SqliteAvailability.UnavailableReason}" - ); - - // Foreign-key enforcement rides the connection string so it costs no extra round trip. - // busy_timeout stays a pragma: Microsoft.Data.Sqlite 8.0's "Default Timeout" only seeds - // SqliteCommand.CommandTimeout (a managed SQLITE_BUSY retry loop, and CreateCommand - // already sets it), never sqlite3_busy_timeout's native blocking wait. - var connection = new SqliteConnection(_connectionString); - try - { - connection.Open(); - using var command = CreateCommand(connection); - command.CommandText = "PRAGMA busy_timeout = 2000;"; - command.ExecuteNonQuery(); - return connection; - } - catch - { - connection.Dispose(); - throw; - } - } - - protected static SqliteCommand CreateCommand( - SqliteConnection connection, - SqliteTransaction? transaction = null - ) - { - var command = connection.CreateCommand(); - command.CommandTimeout = 2; - command.Transaction = transaction; - return command; - } - - protected static void EnableWriteAheadLogging(SqliteConnection connection) - { - using var command = CreateCommand(connection); - command.CommandText = "PRAGMA journal_mode = WAL;"; - command.ExecuteNonQuery(); - } - - protected static void AddNullableInt32(SqliteCommand command, string name, int? value) - { - command.Parameters.AddWithValue(name, value.HasValue ? value.Value : DBNull.Value); - } - - protected static void AddNullableInt64(SqliteCommand command, string name, long? value) - { - command.Parameters.AddWithValue(name, value.HasValue ? value.Value : DBNull.Value); - } - - protected static void AddNullableString(SqliteCommand command, string name, string? value) - { - command.Parameters.AddWithValue(name, value ?? (object)DBNull.Value); - } - - protected static int? GetNullableInt32(SqliteDataReader reader, string columnName) - { - var ordinal = reader.GetOrdinal(columnName); - return reader.IsDBNull(ordinal) ? null : reader.GetInt32(ordinal); - } - - protected static long? GetNullableInt64(SqliteDataReader reader, string columnName) - { - var ordinal = reader.GetOrdinal(columnName); - return reader.IsDBNull(ordinal) ? null : reader.GetInt64(ordinal); - } - - protected static string? GetNullableString(SqliteDataReader reader, string columnName) - { - var ordinal = reader.GetOrdinal(columnName); - return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/history-database-v6.schema.sql b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/history-database-v6.schema.sql deleted file mode 100644 index 56329e9..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/history-database-v6.schema.sql +++ /dev/null @@ -1,290 +0,0 @@ -PRAGMA user_version=1; -CREATE TABLE battle_snapshots ( - battle_id TEXT PRIMARY KEY, - player_hand_json TEXT NOT NULL, - player_skills_json TEXT NOT NULL, - opponent_hand_json TEXT NOT NULL, - opponent_skills_json TEXT NOT NULL, - FOREIGN KEY (battle_id) REFERENCES battles(battle_id) ON DELETE CASCADE -); -CREATE TABLE battles ( - battle_id TEXT PRIMARY KEY, - remote_battle_id TEXT NULL, - uploader_account_id TEXT NULL, - source TEXT NOT NULL, - run_id TEXT NULL, - local_player_account_id TEXT NULL, - recorded_at_ms INTEGER NOT NULL, - day INTEGER NULL, - hour INTEGER NULL, - encounter_id TEXT NULL, - combat_kind TEXT NOT NULL, - player_name TEXT NULL, - player_account_id TEXT NULL, - player_hero TEXT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_level INTEGER NULL, - player_prestige INTEGER NULL, - player_income INTEGER NULL, - player_gold INTEGER NULL, - player_victories INTEGER NULL, - player_hand_item_count INTEGER NULL, - player_skill_count INTEGER NULL, - opponent_name TEXT NULL, - opponent_account_id TEXT NULL, - opponent_hero TEXT NULL, - opponent_rank TEXT NULL, - opponent_rating INTEGER NULL, - opponent_level INTEGER NULL, - opponent_prestige INTEGER NULL, - opponent_victories INTEGER NULL, - opponent_hand_item_count INTEGER NULL, - opponent_skill_count INTEGER NULL, - result TEXT NULL, - winner_combatant_id TEXT NULL, - loser_combatant_id TEXT NULL, - is_final_battle INTEGER NOT NULL DEFAULT 0, - bundle_id TEXT NULL, - download_url TEXT NULL, - download_url_expires_at_ms INTEGER NULL, - ghost_replay_state TEXT NULL, - ghost_replay_unavailable_reason TEXT NULL, - deleted_at_ms INTEGER NULL, - local_payload_state TEXT NULL, - local_payload_maintenance_at_ms INTEGER NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK ( - (source = 'LOCAL' AND remote_battle_id IS NULL AND uploader_account_id IS NULL) - OR - (source = 'GHOST' AND run_id IS NULL AND remote_battle_id IS NOT NULL AND uploader_account_id IS NOT NULL) - ), - CHECK ( - ghost_replay_state IS NULL OR ghost_replay_state IN ( - 'remote_available', 'local_ready', 'unavailable_payload', 'expired' - ) - ), - CHECK ( - (source = 'LOCAL' AND local_payload_state IS NOT NULL - AND local_payload_state IN ('ready', 'delete_pending', 'evicted', 'missing')) - OR - (source <> 'LOCAL' AND local_payload_state IS NULL) - ) -); -CREATE TABLE bundle_outbox ( - bundle_id TEXT PRIMARY KEY, - run_id TEXT NOT NULL, - file_name TEXT NOT NULL UNIQUE, - content_sha256_hex TEXT NOT NULL, - content_digest TEXT NOT NULL, - total_bytes INTEGER NOT NULL, - has_screenshot INTEGER NOT NULL, - sealed_at_ms INTEGER NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_ms INTEGER NULL, - next_attempt_at_ms INTEGER NULL, - failed_at_ms INTEGER NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - server_request_id TEXT NULL, - server_outcome TEXT NULL, - uploaded_at_ms INTEGER NULL, - CHECK (status IN ('pending', 'uploaded', 'permanent_failure')) -); -CREATE TABLE bundle_seal_jobs ( - run_id TEXT PRIMARY KEY, - state TEXT NOT NULL DEFAULT 'waiting', - player_account_id TEXT NULL, - screenshot_requested INTEGER NOT NULL, - screenshot_state TEXT NOT NULL DEFAULT 'waiting', - input_deadline_at_ms INTEGER NOT NULL, - bundle_id TEXT NULL UNIQUE, - created_at_ms INTEGER NULL, - attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at_ms INTEGER NULL, - last_error_code TEXT NULL, - last_error_detail TEXT NULL, - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE, - CHECK (state IN ('waiting', 'sealing', 'terminal_failure')), - CHECK (screenshot_state IN ('not_requested', 'waiting', 'available', 'unavailable', 'timed_out')) -); -CREATE TABLE combat_replay_videos ( - video_id TEXT PRIMARY KEY, - battle_id TEXT NOT NULL, - source TEXT NOT NULL, - video_relative_path TEXT NOT NULL, - width INTEGER NOT NULL, - height INTEGER NOT NULL, - fps INTEGER NOT NULL, - codec TEXT NOT NULL, - crf INTEGER NULL, - preset TEXT NULL, - started_at_ms INTEGER NOT NULL, - ended_at_ms INTEGER NULL, - duration_ms INTEGER NULL, - captured_frames INTEGER NOT NULL DEFAULT 0, - dropped_frames INTEGER NOT NULL DEFAULT 0, - file_size_bytes INTEGER NULL, - status TEXT NOT NULL, - error TEXT NULL, - attachment_state TEXT NOT NULL DEFAULT 'attached', - file_state TEXT NOT NULL DEFAULT 'pending', - detached_at_ms INTEGER NULL, - missing_at_ms INTEGER NULL, - last_reconciled_at_ms INTEGER NULL, - CHECK (status IN ('RECORDING', 'COMPLETED', 'FAILED')), - CHECK (attachment_state IN ('attached', 'detached')), - CHECK (file_state IN ('pending', 'present', 'missing')) -); -CREATE TABLE favorite_battles ( - battle_id TEXT PRIMARY KEY, - source TEXT NOT NULL, - favorited_at_ms INTEGER NOT NULL, - note TEXT NOT NULL DEFAULT '', - note_updated_at_ms INTEGER NULL, - favorite_payload_state TEXT NOT NULL, - run_id TEXT NULL, - local_player_account_id TEXT NULL, - uploader_account_id TEXT NULL, - remote_battle_id TEXT NULL, - recorded_at_ms INTEGER NOT NULL, - day INTEGER NULL, - hour INTEGER NULL, - encounter_id TEXT NULL, - combat_kind TEXT NOT NULL, - player_name TEXT NULL, - player_account_id TEXT NULL, - player_hero TEXT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_level INTEGER NULL, - player_prestige INTEGER NULL, - player_victories INTEGER NULL, - player_hand_item_count INTEGER NULL, - player_skill_count INTEGER NULL, - opponent_name TEXT NULL, - opponent_account_id TEXT NULL, - opponent_hero TEXT NULL, - opponent_rank TEXT NULL, - opponent_rating INTEGER NULL, - opponent_level INTEGER NULL, - opponent_prestige INTEGER NULL, - opponent_victories INTEGER NULL, - opponent_hand_item_count INTEGER NULL, - opponent_skill_count INTEGER NULL, - result TEXT NULL, - winner_combatant_id TEXT NULL, - loser_combatant_id TEXT NULL, - is_final_battle INTEGER NOT NULL DEFAULT 0, - player_hand_json TEXT NULL, - player_skills_json TEXT NULL, - opponent_hand_json TEXT NULL, - opponent_skills_json TEXT NULL, - CHECK (source IN ('LOCAL', 'GHOST')), - CHECK (favorite_payload_state IN ('ready', 'missing')), - CHECK (length(note) <= 500) -); -CREATE TABLE run_events ( - run_id TEXT NOT NULL, - seq INTEGER NOT NULL, - ts_at_ms INTEGER NOT NULL, - kind TEXT NOT NULL, - payload_json TEXT NOT NULL, - PRIMARY KEY (run_id, seq), - FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE -); -CREATE TABLE run_screenshots ( - screenshot_id TEXT PRIMARY KEY, - run_id TEXT NULL, - hero_name TEXT NULL, - capture_source TEXT NOT NULL, - is_primary INTEGER NOT NULL DEFAULT 0, - image_relative_path TEXT NOT NULL, - captured_at_ms INTEGER NOT NULL, - captured_utc_offset_minutes INTEGER NOT NULL, - day INTEGER NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - player_position INTEGER NULL, - victories_at_capture INTEGER NULL -); -CREATE TABLE runs ( - run_id TEXT PRIMARY KEY, - started_at_ms INTEGER NOT NULL, - last_seen_at_ms INTEGER NOT NULL, - status TEXT NOT NULL, - hero TEXT NOT NULL, - game_mode TEXT NOT NULL, - player_rank TEXT NULL, - player_rating INTEGER NULL, - day INTEGER NULL, - hour INTEGER NULL, - max_health INTEGER NULL, - prestige INTEGER NULL, - level INTEGER NULL, - income INTEGER NULL, - gold INTEGER NULL, - last_seq INTEGER NOT NULL DEFAULT 0, - ended_at_ms INTEGER NULL, - final_day INTEGER NULL, - final_hour INTEGER NULL, - victories INTEGER NULL, - losses INTEGER NULL, - final_player_rank TEXT NULL, - final_player_rating INTEGER NULL, - final_player_rating_delta INTEGER NULL, - reason TEXT NULL, - build_channel TEXT NULL, - player_account_id TEXT NULL, - bundle_screenshot_requested INTEGER NOT NULL DEFAULT 0, - mod_version TEXT NULL, - upload_policy TEXT NOT NULL DEFAULT 'bundle', - CHECK (status IN ('active', 'completed', 'abandoned')), - CHECK (upload_policy IN ('bundle', 'history_only')) -); -CREATE INDEX idx_battles_ghost_discovery - ON battles(local_player_account_id, source, recorded_at_ms DESC); -CREATE UNIQUE INDEX idx_battles_ghost_identity - ON battles(uploader_account_id, remote_battle_id) - WHERE source = 'GHOST'; -CREATE INDEX idx_battles_history_ghost ON battles(local_player_account_id, recorded_at_ms DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_ms IS NULL; -CREATE INDEX idx_battles_history_ghost_day ON battles(local_player_account_id, recorded_at_ms DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_ms IS NULL AND day >= 10; -CREATE INDEX idx_battles_history_ghost_day_outcome ON battles(local_player_account_id, CASE lower(winner_combatant_id) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 ELSE CASE lower(result) WHEN 'win' THEN 1 WHEN 'loss' THEN -1 ELSE 0 END END, recorded_at_ms DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_ms IS NULL AND day >= 10; -CREATE INDEX idx_battles_history_ghost_outcome ON battles(local_player_account_id, CASE lower(winner_combatant_id) WHEN 'player' THEN 1 WHEN 'opponent' THEN -1 ELSE CASE lower(result) WHEN 'win' THEN 1 WHEN 'loss' THEN -1 ELSE 0 END END, recorded_at_ms DESC, battle_id DESC) WHERE source = 'GHOST' AND deleted_at_ms IS NULL; -CREATE INDEX idx_battles_history_local ON battles(run_id, recorded_at_ms DESC, battle_id DESC) WHERE source = 'LOCAL'; -CREATE INDEX idx_battles_local_player_recent - ON battles(local_player_account_id, recorded_at_ms DESC); -CREATE INDEX idx_battles_run_id_recorded - ON battles(run_id, recorded_at_ms DESC); -CREATE INDEX idx_battles_source_recorded - ON battles(source, recorded_at_ms DESC); -CREATE UNIQUE INDEX idx_bundle_outbox_active_run - ON bundle_outbox(run_id) - WHERE status = 'pending'; -CREATE INDEX idx_bundle_outbox_due - ON bundle_outbox(status, next_attempt_at_ms, attempts, sealed_at_ms); -CREATE INDEX idx_bundle_outbox_run - ON bundle_outbox(run_id, status); -CREATE INDEX idx_bundle_seal_jobs_state - ON bundle_seal_jobs(state, input_deadline_at_ms, run_id); -CREATE INDEX idx_combat_replay_videos_attachment - ON combat_replay_videos( - attachment_state, started_at_ms DESC, video_id - ); -CREATE INDEX idx_combat_replay_videos_battle - ON combat_replay_videos(battle_id, started_at_ms DESC); -CREATE INDEX idx_favorite_battles_recent - ON favorite_battles(favorited_at_ms DESC, battle_id DESC); -CREATE UNIQUE INDEX idx_run_screenshots_primary_run - ON run_screenshots(run_id) - WHERE is_primary = 1 AND run_id IS NOT NULL; -CREATE INDEX idx_run_screenshots_run_id_captured - ON run_screenshots(run_id, captured_at_ms DESC); -CREATE INDEX idx_run_screenshots_source_captured - ON run_screenshots(capture_source, captured_at_ms ASC, screenshot_id ASC); -CREATE INDEX idx_runs_history_hero ON runs(lower(trim(hero,' - …             

   ')), COALESCE(ended_at_ms,last_seen_at_ms,started_at_ms) DESC, run_id DESC); -CREATE INDEX idx_runs_history_recent ON runs(COALESCE(ended_at_ms,last_seen_at_ms,started_at_ms) DESC, run_id DESC); -CREATE INDEX idx_runs_status_last_seen - ON runs(status, last_seen_at_ms DESC); diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/packages.lock.json b/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/packages.lock.json deleted file mode 100644 index 548e587..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus.Storage/packages.lock.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "version": 2, - "dependencies": { - ".NETStandard,Version=v2.1": { - "MessagePack": { - "type": "Direct", - "requested": "[3.1.4, )", - "resolved": "3.1.4", - "contentHash": "BH0wlHWmVoZpbAPyyt2Awbq30C+ZsS3eHSkYdnyUAbqVJ22fAJDzn2xTieBeoT5QlcBzp61vHcv878YJGfi3mg==", - "dependencies": { - "MessagePack.Annotations": "3.1.4", - "MessagePackAnalyzer": "3.1.4", - "Microsoft.NET.StringTools": "17.11.4", - "System.Collections.Immutable": "8.0.0" - } - }, - "MessagePack.Annotations": { - "type": "Direct", - "requested": "[3.1.4, )", - "resolved": "3.1.4", - "contentHash": "aVWrDAkCdqxwQsz/q0ldPh2EFn48M99YUzE9OvZjMq2RNLKz4o2z88iGFvSvbMqOWRweRvKPHBJZe22PRqzslQ==" - }, - "Microsoft.Data.Sqlite": { - "type": "Direct", - "requested": "[10.0.12, )", - "resolved": "10.0.12", - "contentHash": "xUq9xUc653ue7ac2rMfCaf8UQN+U3zS8poWYlugycpvJllplMM0Mk7v/+MM0CTlu9zGvbGML4BPH8YWhrUOfGw==", - "dependencies": { - "Microsoft.Data.Sqlite.Core": "10.0.12", - "SQLitePCLRaw.bundle_e_sqlite3": "2.1.12", - "SQLitePCLRaw.core": "2.1.12" - } - }, - "NETStandard.Library": { - "type": "Direct", - "requested": "[2.0.3, )", - "resolved": "2.0.3", - "contentHash": "st47PosZSHrjECdjeIzZQbzivYBJFv6P2nv4cj2ypdI204DO+vZ7l5raGMiX4eXMJ53RfOIg+/s4DHVZ54Nu2A==", - "dependencies": { - "Microsoft.NETCore.Platforms": "1.1.0" - } - }, - "Newtonsoft.Json": { - "type": "Direct", - "requested": "[13.0.4, )", - "resolved": "13.0.4", - "contentHash": "pdgNNMai3zv51W5aq268sujXUyx7SNdE2bj1wZcWjAQrKMFZV260lbqYop1d2GM67JI1huLRwxo9ZqnfF/lC6A==" - }, - "SourceGear.sqlite3": { - "type": "Direct", - "requested": "[3.53.4, )", - "resolved": "3.53.4", - "contentHash": "aXPX39R0Vgivhi95Z82TRenG56bSOs+Hnt8h1GV0nmfuRaANObd3LC44eoZwszmQqALjaV3ZnBQRej8m5E0L4Q==" - }, - "SQLitePCLRaw.bundle_e_sqlite3": { - "type": "Direct", - "requested": "[3.0.5, )", - "resolved": "3.0.5", - "contentHash": "SW8iASIyWMrLzqabUHYQRvALhvD4ylSBsj4PgEVGwc36kQjc9xT5kSV/XQ9rU7nIpBWD+LPyX3Hlw5FzyUzGeQ==", - "dependencies": { - "SQLite": "3.53.4", - "SQLitePCLRaw.config.e_sqlite3": "3.0.5" - } - }, - "Microsoft.Data.Sqlite.Core": { - "type": "Transitive", - "resolved": "10.0.12", - "contentHash": "2aL9eL5HQr0V4b8V909SD+jQAx6qnTTl7sT/v3D8dIvmr2UGdpZIQxqm1pj2Js3e4EYTvpw0oMH7DjapJJuPPw==", - "dependencies": { - "SQLitePCLRaw.core": "2.1.12" - } - }, - "Microsoft.NET.StringTools": { - "type": "Transitive", - "resolved": "17.11.4", - "contentHash": "mudqUHhNpeqIdJoUx2YDWZO/I9uEDYVowan89R6wsomfnUJQk6HteoQTlNjZDixhT2B4IXMkMtgZtoceIjLRmA==", - "dependencies": { - "System.Memory": "4.5.5", - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, - "Microsoft.NETCore.Platforms": { - "type": "Transitive", - "resolved": "1.1.0", - "contentHash": "kz0PEW2lhqygehI/d6XsPCQzD7ff7gUJaVGPVETX611eadGsA3A877GdSlU0LRVMCTH/+P3o2iDTak+S08V2+A==" - }, - "SQLite": { - "type": "Transitive", - "resolved": "3.53.4", - "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" - }, - "SQLitePCLRaw.config.e_sqlite3": { - "type": "Transitive", - "resolved": "3.0.5", - "contentHash": "aSk8WE5tF2MybESMgtZAEyMVCAWA0nBqOMc48HFoa9UoSdtm3goDXVzNRnefeKIwE6bV9NaNXptn1F9ReMQI0Q==", - "dependencies": { - "SQLitePCLRaw.provider.e_sqlite3": "3.0.5" - } - }, - "SQLitePCLRaw.core": { - "type": "Transitive", - "resolved": "3.0.5", - "contentHash": "k81AYXXRCw3Zj8rOhyBoCsx/U97KYDFI2CSKr/ijl5BwpsW/hX/4kBiDmerFaoust8nxBwa0IHQFw8MmSHRtnQ==", - "dependencies": { - "System.Memory": "4.6.3" - } - }, - "SQLitePCLRaw.provider.e_sqlite3": { - "type": "Transitive", - "resolved": "3.0.5", - "contentHash": "um8YSWduhhuskTG2bHfZrBqMNQOydfU8pcseT+cu5RivOGyoUbCrGXxgoRNTmRYw2VbMWnEZVVFcneZT/5dsBg==", - "dependencies": { - "SQLitePCLRaw.core": "3.0.5" - } - }, - "System.Collections.Immutable": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "AurL6Y5BA1WotzlEvVaIDpqzpIPvYnnldxru8oXJU2yFxFUy3+pNXjXd1ymO+RA0rq0+590Q8gaz2l3Sr7fmqg==", - "dependencies": { - "System.Memory": "4.5.5", - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==" - }, - "MessagePackAnalyzer": { - "type": "CentralTransitive", - "requested": "[3.1.4, )", - "resolved": "3.1.4", - "contentHash": "CTaSsN/liJ7MhLCAB7Z4ZLBNuVGCq9lt2BT/cbrc9vzGv89yK3CqIA+z9T19a11eQYl9etZHL6MQJgCqECRVpg==" - }, - "System.Runtime.CompilerServices.Unsafe": { - "type": "CentralTransitive", - "requested": "[6.0.0, )", - "resolved": "6.0.0", - "contentHash": "/iUeP3tq1S0XdNNoMz5C9twLSrM/TH+qElHkXWaPvuNOt+99G75NrV0OS2EqHx5wMN7popYjpc8oTjC1y16DLg==" - } - } - } -} \ No newline at end of file diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/BazaarPlusPlus.csproj b/bazaarplusplus-mod/src/BazaarPlusPlus/BazaarPlusPlus.csproj deleted file mode 100644 index cf52e62..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/BazaarPlusPlus.csproj +++ /dev/null @@ -1,348 +0,0 @@ - - - - BazaarPlusPlus - BazaarPlusPlus - Game Enhancement Mod - BazaarPlusPlus - $(BppVersion) - 12 - enable - true - - false - netstandard2.1 - net6.0 - $(DefineConstants);BPP_ANDROID - true - true - - $(NoWarn);CS0436 - false - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(MSBuildThisFileDirectory) - $(ProjectRoot)/../../../bazaarplusplus-installer/src-tauri/resources - $(ProjectRoot)/../BazaarPlusPlus.Storage/BazaarPlusPlus.history-database.json - $([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()) - $([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX))) - $([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows))) - osx-arm64 - win-x64 - $(PkgSourceGear_sqlite3)/runtimes/$(MacSqliteRuntimeRid)/native/libe_sqlite3.dylib - $(BPPInstallerSourcePath)/SourceForBuild/macos/BepInEx/plugins/libBppMacAudio.dylib - $(PkgSourceGear_sqlite3)/runtimes/$(WindowsSqliteRuntimeRid)/native/e_sqlite3.dll - $(ProjectRoot)/../../native/macos/build/GfxPluginBppReplayVideoToolbox.bundle - $(BPPInstallerSourcePath)/SourceForBuild/macos/TheBazaar.app/Contents/Plugins/GfxPluginBppReplayVideoToolbox.bundle - $(LocalMacReplayPluginBundle) - $(InstallerMacReplayPluginBundle) - $(ProjectRoot)/../../native/windows/build/GfxPluginBppReplayMediaFoundation.dll - $(BPPInstallerSourcePath)/SourceForBuild/windows/TheBazaar_Data/Plugins/x86_64/GfxPluginBppReplayMediaFoundation.dll - $(LocalWindowsReplayPlugin) - $(InstallerWindowsReplayPlugin) - - - - - - - - - - - - - - - - - - - - - - - - - - - $(ManagedPath)\Assembly-CSharp.dll - - - $(ManagedPath)\BazaarBattleService.dll - - - $(ManagedPath)\BazaarGameClient.dll - - - $(ManagedPath)\BazaarGameShared.dll - - - $(ManagedPath)\TheBazaarRuntime.dll - - - $(ManagedPath)\Unity.Addressables.dll - - - $(ManagedPath)\Unity.ResourceManager.dll - - - $(ManagedPath)\Unity.InputSystem.dll - - - $(ManagedPath)\DOTween.dll - false - - - $(ManagedPath)\UnityEngine.UI.dll - - - $(ManagedPath)\UnityEngine.ImageConversionModule.dll - - - $(ManagedPath)\UnityEngine.UIElementsModule.dll - - - $(ManagedPath)\UnityEngine.TextCoreTextEngineModule.dll - - - $(ManagedPath)\UnityEngine.TextCoreFontEngineModule.dll - - - $(ManagedPath)\Unity.TextMeshPro.dll - - - $(ManagedPath)\FMODUnity.dll - - - - - - <_BppUnityEngineInterop Include="$(ManagedPath)\UnityEngine*.dll" /> - - false - - - - $(ManagedPath)\Il2Cppmscorlib.dll - false - - <_BppIl2CppBcl Include="$(ManagedPath)\Il2CppSystem*.dll" /> - - false - - - - - - - - - - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/BppComposition.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/BppComposition.cs deleted file mode 100644 index f550bac..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/BppComposition.cs +++ /dev/null @@ -1,325 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Core.Config; -using BazaarPlusPlus.Core.Events; -using BazaarPlusPlus.Core.Paths; -using BazaarPlusPlus.Core.Runtime; -using BazaarPlusPlus.Game.BilingualItemNames; -using BazaarPlusPlus.Game.BundlePipeline; -using BazaarPlusPlus.Game.CollectionPanel; -using BazaarPlusPlus.Game.CombatReplay; -using BazaarPlusPlus.Game.CombatReplay.Video; -using BazaarPlusPlus.Game.CombatStatusBar; -using BazaarPlusPlus.Game.CosmeticNames; -using BazaarPlusPlus.Game.EventPreview; -using BazaarPlusPlus.Game.GraphicsUpscaling; -using BazaarPlusPlus.Game.HistoryPanel; -using BazaarPlusPlus.Game.Input; -using BazaarPlusPlus.Game.ItemEnchantPreview; -using BazaarPlusPlus.Game.LegendaryPosition; -using BazaarPlusPlus.Game.LiveBuildPanel; -using BazaarPlusPlus.Game.LiveBuildPanel.Recommendations; -using BazaarPlusPlus.Game.Lobby; -using BazaarPlusPlus.Game.MusicNotes; -using BazaarPlusPlus.Game.NameOverride; -using BazaarPlusPlus.Game.OverlayPanels; -#if !BPP_ANDROID -using BazaarPlusPlus.Game.PostCombatImpact; -#endif -using BazaarPlusPlus.Game.PvpBattles.Persistence; -using BazaarPlusPlus.Game.QuestPreview; -using BazaarPlusPlus.Game.RunLifecycle; -using BazaarPlusPlus.Game.RunLogging; -using BazaarPlusPlus.Game.Screenshots; -using BazaarPlusPlus.Game.Settings; -using BazaarPlusPlus.Game.Supporters; -using BazaarPlusPlus.Game.Tooltips; -using BazaarPlusPlus.Game.VoiceSubtitles; -using BazaarPlusPlus.GameInterop; -using BazaarPlusPlus.GameInterop.CardPreview; -using BazaarPlusPlus.GameInterop.DayTiers; -using BazaarPlusPlus.GameInterop.Encounter; -using BazaarPlusPlus.GameInterop.RunSnapshot; -using BazaarPlusPlus.GameInterop.StaticCards; -using BazaarPlusPlus.GameInterop.Tooltips; -using BazaarPlusPlus.GameInterop.VoiceSubtitles; -using BazaarPlusPlus.Infrastructure.RemoteEmbeddedCatalog; -using BazaarPlusPlus.ModApi.Clients; -using BazaarPlusPlus.Patches; -#if !BPP_ANDROID -using BazaarPlusPlus.Patches.PostCombatImpact; -#endif -using BazaarPlusPlus.Patches.Tooltips; -using BazaarPlusPlus.Storage.Paths; -using BepInEx.Configuration; - -namespace BazaarPlusPlus; - -internal sealed class BppComposition : IDisposable -{ - private readonly InMemoryBppEventBus _eventBus = new(); - private readonly BppConfig _config; - private readonly BepInExPathProvider _paths = new(); - private readonly RunContextStore _runContext = new(); - private readonly GameStateProbe _gameStateProbe = new(); - private readonly EncounterStateProbe _encounterStateProbe = new(); - private readonly RunSnapshotProbe _runSnapshotProbe = new(); - private readonly BppStaticCardMapProvider _staticCardMapProvider = new(); - private readonly IGameDataDayTierResolver _dayTierResolver = new GameDataDayTierResolver( - new GameDataDayTierSource() - ); - private readonly BppRuntimeServices _services; - private readonly BppFeatureRegistry _featureRegistry = new(); - private readonly BppMountableRegistry _mountables = new(); - private readonly SettingsDockEntryRegistry _settingsDockRegistry = new(); - private readonly RunLifecycleModule _runLifecycle; - private readonly CombatReplayModule _combatReplayModule; - private readonly CombatStatusBarModule _combatStatusBarModule; -#if !BPP_ANDROID - private readonly PostCombatImpactModule _postCombatImpactModule; -#endif - private readonly RunLoggingModule _runLoggingModule; - private readonly BundleSealCoordinator _bundleSealCoordinator; - private readonly EncounterPreviewModule _encounterPreviewModule; - private readonly INativeCardPreviewHost _nativeCardPreviewHost; - private readonly EndOfRunCaptureWorkflow _endOfRunCaptureWorkflow; - private readonly BppPatchFeatures _patchFeatures; - private readonly VoiceSubtitlesModule _voiceSubtitlesModule; - private readonly VoiceSubtitlesInteropModule _voiceSubtitlesInteropModule; - private readonly SupporterCatalogModule _supporterCatalogModule; - private readonly IRemoteEmbeddedCatalog _buildRecommendationCatalog; - private readonly BuildRecommendationRepository _buildRecommendationRepository; - private ModApiSession? _modApiSessionRef; - private BazaarDbLinkClient? _accountLinkClientRef; - private PvpBattleSqliteStore? _pvpBattleCatalog; - - public IBppServices Services => _services; - public RunLifecycleModule RunLifecycle => _runLifecycle; - - public IPvpBattleCatalog PvpBattleCatalog => - _pvpBattleCatalog ??= new PvpBattleSqliteStore( - PathConstants.RunLogDatabase(_paths.RequireDataRoot()) - ); - - public BppMountableRegistry Mountables => _mountables; - public SettingsDockEntryRegistry SettingsDockRegistry => _settingsDockRegistry; - public BppPatchFeatures PatchFeatures => _patchFeatures; - - public BppComposition(ConfigFile configFile, IGameBuildInfo gameBuild) - { - if (configFile == null) - throw new ArgumentNullException(nameof(configFile)); - if (gameBuild == null) - throw new ArgumentNullException(nameof(gameBuild)); - - _config = new BppConfig(configFile); - _paths.Initialize(); - - _services = new BppRuntimeServices( - _eventBus, - _config, - _paths, - _runContext, - _gameStateProbe, - _encounterStateProbe, - _runSnapshotProbe, - gameBuild - ); - - _runLifecycle = new RunLifecycleModule(_eventBus, _gameStateProbe, _runContext); - _combatReplayModule = new CombatReplayModule(_eventBus); - _combatStatusBarModule = new CombatStatusBarModule(_eventBus); -#if !BPP_ANDROID - _postCombatImpactModule = new PostCombatImpactModule(_eventBus, _staticCardMapProvider); -#endif - _voiceSubtitlesModule = new VoiceSubtitlesModule(_paths.RequireDataRoot()); - _voiceSubtitlesInteropModule = new VoiceSubtitlesInteropModule(); - _supporterCatalogModule = new SupporterCatalogModule( - () => _config.UseFixedSupporterListConfig.Value, - _paths.RequireDataRoot() - ); - _nativeCardPreviewHost = new NativeCardPreviewHost(new NativeTooltipDataFactoryAdapter()); - _buildRecommendationCatalog = TenWinBuildCatalogFactory.Create(_paths.RequireDataRoot()); - _buildRecommendationRepository = new BuildRecommendationRepository( - _buildRecommendationCatalog - ); - var encounterPreviewCachePath = System.IO.Path.Combine( - _paths.RequireDataRoot(), - "EncounterPreview", - "preview-plans.json" - ); - _encounterPreviewModule = new EncounterPreviewModule( - _services, - _staticCardMapProvider, - _dayTierResolver, - encounterPreviewCachePath - ); - _endOfRunCaptureWorkflow = new EndOfRunCaptureWorkflow(_services); -#if BPP_ANDROID - _patchFeatures = new BppPatchFeatures(_encounterPreviewModule, _endOfRunCaptureWorkflow); -#else - _patchFeatures = new BppPatchFeatures( - _encounterPreviewModule, - _endOfRunCaptureWorkflow, - _postCombatImpactModule - ); -#endif - _patchFeatures.CollectionInspection.InitializeGlobalHost(_nativeCardPreviewHost); - _runLoggingModule = new RunLoggingModule( - _services, - PvpBattleCatalog, - () => _combatReplayModule.Runtime?.HasPendingPersistence == true - ); - _bundleSealCoordinator = new BundleSealCoordinator(_services); - - _featureRegistry.Register(_runLifecycle); - _featureRegistry.Register(_combatReplayModule); - _featureRegistry.Register(_combatStatusBarModule); -#if !BPP_ANDROID - _featureRegistry.Register(_postCombatImpactModule); -#endif - _featureRegistry.Register(_voiceSubtitlesInteropModule); - _featureRegistry.Register(_voiceSubtitlesModule); - _featureRegistry.Register(_supporterCatalogModule); - _featureRegistry.Register(_runLoggingModule); - _featureRegistry.Register(_bundleSealCoordinator); - - _settingsDockRegistry.Register(BazaarDbBundleSettingsDockEntry.Create()); - _settingsDockRegistry.Register(FixedSupporterListSettingsDockEntry.Create()); - VoiceSubtitlesSettingsDockEntry.RegisterAll(_settingsDockRegistry); - _settingsDockRegistry.Register(ChineseLocaleModeSettingsDockEntry.Create(_eventBus)); - _settingsDockRegistry.Register(BilingualItemNamesSettingsDockEntry.Create()); - _settingsDockRegistry.Register(CosmeticNamesSettingsDockEntry.Create()); - _settingsDockRegistry.Register(CombatStatusBarSettingsDockEntry.Create()); - _settingsDockRegistry.Register(new EndOfRunScreenshotSettingsDockEntry()); - _settingsDockRegistry.Register(new HistoryPanelSettingsDockEntry()); - _settingsDockRegistry.Register(ItemEnchantPreviewSettingsDockEntry.Create()); - _settingsDockRegistry.Register(UpgradePreviewActivationSettingsDockEntry.Create()); - _settingsDockRegistry.Register(EventPreviewSettingsDockEntry.Create()); - _settingsDockRegistry.Register( - QuestPreviewSettingsDockEntry.Create(() => - { - QuestRewardPreviewTooltipPatch.ClearPooledPresentation(); - AggregateItemMissingTypesTooltipPatch.ClearPooledPresentation(); - }) - ); - _settingsDockRegistry.Register(LegendaryPositionSettingsDockEntry.Create()); - _settingsDockRegistry.Register(NameOverrideSettingsDockEntry.Create()); - if ( - UnityEngine.Application.platform - is UnityEngine.RuntimePlatform.OSXPlayer - or UnityEngine.RuntimePlatform.WindowsPlayer - ) - GraphicsUpscalingSettingsDockEntry.RegisterAll(_settingsDockRegistry); - -#if !BPP_ANDROID - _mountables.Register(new UploadPumpMount()); -#endif - if ( - UnityEngine.Application.platform - is UnityEngine.RuntimePlatform.OSXPlayer - or UnityEngine.RuntimePlatform.WindowsPlayer - ) - { - _mountables.Register( - new ComponentMount( - (controller, services) => controller.Initialize(services.Config) - ) - ); - } -#if !BPP_ANDROID - // Mounting this observer aborts the process on the Android port: its first Update calls - // into the interop layer before the projections are ready. - _mountables.Register( - new ComponentMount( - (observer, _) => observer.Initialize(_encounterPreviewModule) - ) - ); -#endif - // The overlay host must mount before every Main Overlay Panel mount below: panels - // register their lifecycle with it through the accessor. - var overlayPanelHostMount = new OverlayPanelHostMount(); - _mountables.Register(overlayPanelHostMount); - _mountables.Register( - new CollectionPanelMount( - () => overlayPanelHostMount.Host, - _staticCardMapProvider, - _nativeCardPreviewHost, - _dayTierResolver, - _patchFeatures.CollectionInspection - ) - ); - _mountables.Register( - new ComponentMount((c, s) => c.Initialize(s)) - ); - _mountables.Register(new ComponentMount((c, s) => c.Initialize(s))); - _mountables.Register(new ComponentMount()); -#if !BPP_ANDROID - // Plugin-lifetime, like _nativeCardPreviewHost: composition does not dispose GameInterop - // hosts, and the releasable unit is the session the view acquires from it. - var pairedTooltipHost = new NativePairedTooltipHost(); - _mountables.Register( - new ComponentMount( - (c, _) => - c.Initialize( - _postCombatImpactModule, - new NativePostCombatImpactTooltipView( - _nativeCardPreviewHost, - pairedTooltipHost - ) - ) - ) - ); -#endif - _mountables.Register( - new ComponentMount( - (driver, services) => driver.Initialize(_endOfRunCaptureWorkflow, services) - ) - ); -#if !BPP_ANDROID - _mountables.Register( - new ComponentMount((c, _) => c.Initialize()) - ); -#endif - _mountables.Register( - new HistoryPanelMount( - combatReplayRuntime: () => _combatReplayModule.Runtime, - modApiSession: () => _modApiSessionRef, - accountLinkClient: () => _accountLinkClientRef, - overlayHost: () => overlayPanelHostMount.Host - ) - ); - _mountables.Register( - new LiveBuildPanelMount( - () => overlayPanelHostMount.Host, - _buildRecommendationRepository - ) - ); - _mountables.Register(new ComponentMount()); - _mountables.Register(new ComponentMount()); -#if !BPP_ANDROID - _mountables.Register( - new ComponentMount( - (c, s) => c.Initialize(s.Config, s.EncounterState, _nativeCardPreviewHost) - ) - ); -#endif - } - - public void AttachCombatReplayRuntime(CombatReplayRuntime runtime) => - _combatReplayModule.AttachRuntime(runtime); - - public void AttachModApiSession(ModApiSession? session) => _modApiSessionRef = session; - - public void AttachAccountLinkClient(BazaarDbLinkClient? client) => - _accountLinkClientRef = client; - - public void Start() => _featureRegistry.Start(); - - public void Dispose() - { - _featureRegistry.Stop(); - _endOfRunCaptureWorkflow.Dispose(); - _encounterPreviewModule.Dispose(); - _buildRecommendationCatalog.Dispose(); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/BppPluginMetadata.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/BppPluginMetadata.cs deleted file mode 100644 index 0aa19d1..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/BppPluginMetadata.cs +++ /dev/null @@ -1,13 +0,0 @@ -#pragma warning disable CS0436 -#nullable enable -namespace BazaarPlusPlus; - -/// -/// Re-exports the BazaarPlusPlus BepInEx plugin GUID as a public compile-time constant, so a -/// caller can name the plugin without reaching into the per-assembly, internal, build-generated -/// MyPluginInfo. -/// -public static class BppPluginMetadata -{ - public const string Guid = MyPluginInfo.PLUGIN_GUID; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/BppConfig.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/BppConfig.cs deleted file mode 100644 index 12d0295..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/BppConfig.cs +++ /dev/null @@ -1,290 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Localization; -using BepInEx.Configuration; - -namespace BazaarPlusPlus.Core.Config; - -internal sealed class BppConfig -{ - internal const PreviewVisibilityMode DefaultEnchantPreviewMode = PreviewVisibilityMode.Always; - internal const HotkeyActivationMode DefaultUpgradePreviewActivationMode = - HotkeyActivationMode.Hold; - internal const SubtitlePosition DefaultVoiceSubtitlesPosition = SubtitlePosition.TopCenter; - internal const float DefaultFsrSharpness = 0.92f; - - public ConfigEntry EnableNameOverrideConfig { get; } - - public ConfigEntry EnchantPreviewModeConfig { get; } - - public ConfigEntry EnableEventPreviewConfig { get; } - - public ConfigEntry EnableQuestPreviewConfig { get; } - - public ConfigEntry EnableBilingualItemNamesConfig { get; } - - public ConfigEntry EnableCosmeticNamesConfig { get; } - - public ConfigEntry EnableVoiceSubtitlesConfig { get; } - - public ConfigEntry VoiceSubtitlesPositionConfig { get; } - - public ConfigEntry VoiceSubtitlesLanguageModeConfig { get; } - - public ConfigEntry VoiceSubtitlesEnglishFontScaleConfig { get; } - - public ConfigEntry VoiceSubtitlesChineseFontScaleConfig { get; } - - public ConfigEntry EnableCombatStatusBarConfig { get; } - - public ConfigEntry CombatStatusBarSpeedMultiplierConfig { get; } - - public ConfigEntry EndOfRunScreenshotEnabledConfig { get; } - - public ConfigEntry EnchantPreviewHotkeyPathConfig { get; } - - public ConfigEntry UpgradePreviewHotkeyPathConfig { get; } - - public ConfigEntry UpgradePreviewActivationModeConfig { get; } - - public ConfigEntry ToggleCollectionPanelHotkeyPathConfig { get; } - - public ConfigEntry ToggleLiveBuildPanelHotkeyPathConfig { get; } - - public ConfigEntry ToggleHistoryPanelHotkeyPathConfig { get; } - - public ConfigEntry ChineseLocaleModeConfig { get; } - - public ConfigEntry UiLanguageConfig { get; } - - public ConfigEntry TouchDockAnchorXConfig { get; } - - public ConfigEntry TouchDockAnchorYConfig { get; } - - public ConfigEntry OverlayUiScalePercentConfig { get; } - - public ConfigEntry LegendaryPositionDisplayModeConfig { get; } - - public ConfigEntry GraphicsUpscalingModeConfig { get; } - - public ConfigEntry GraphicsUpscalingSharpnessConfig { get; } - - public ConfigEntry BazaarDbUploadEnabled { get; } - - public ConfigEntry UseFixedSupporterListConfig { get; } - - public BppConfig(ConfigFile config) - { - if (config == null) - throw new ArgumentNullException(nameof(config)); - - EnableNameOverrideConfig = config.Bind( - "StreamerMode", - "EnableNameOverride", - false, - "Whether to set the in-game display name to Anonymous" - ); - EnchantPreviewModeConfig = config.Bind( - "EnchantPreview", - "Mode", - DefaultEnchantPreviewMode, - "When to show enchant preview text in item tooltips. Off = hold Ctrl only. AutoOnPedestalChoice = auto-show while an enchant pedestal is offered on the choice screen, hold Ctrl otherwise. Always = append to every eligible tooltip." - ); - EnableEventPreviewConfig = config.Bind( - "EventPreview", - "Enabled", - true, - "Whether to append the event-choice breakdown and hero level-up reward sections to native tooltips." - ); - EnableQuestPreviewConfig = config.Bind( - "QuestPreview", - "Enabled", - false, - "Whether to show quest completion reward effects and aggregate-item missing-type hints in native tooltips." - ); - EnableBilingualItemNamesConfig = config.Bind( - "BilingualItemNames", - "Enabled", - false, - "Whether item, skill, monster, pedestal, reward, and event tooltips show the other English/Chinese name below the current-language name." - ); - EnableCosmeticNamesConfig = config.Bind( - "CosmeticNames", - "Enabled", - false, - "Whether to overlay localized names at the bottom center of individual cosmetic thumbnails in the loadout selection list." - ); - EnableVoiceSubtitlesConfig = config.Bind( - "VoiceSubtitles", - "Enabled", - false, - "Whether Subtitle Mode enables voice-over subtitles. The in-game dock writes this together with VoiceSubtitles.Language." - ); - VoiceSubtitlesPositionConfig = config.Bind( - "VoiceSubtitles", - "Position", - DefaultVoiceSubtitlesPosition, - "Where voice-over subtitles are anchored on screen." - ); - VoiceSubtitlesLanguageModeConfig = config.Bind( - "VoiceSubtitles", - "Language", - SubtitleLanguageMode.Both, - "Language used by Subtitle Mode when voice-over subtitles are enabled: Both, ChineseOnly, or EnglishOnly." - ); - VoiceSubtitlesEnglishFontScaleConfig = config.Bind( - "VoiceSubtitles", - "EnglishFontScale", - 1.0f, - new ConfigDescription( - "Font scale for the English subtitle line.", - new AcceptableValueRange(1.0f, 2.5f) - ) - ); - VoiceSubtitlesChineseFontScaleConfig = config.Bind( - "VoiceSubtitles", - "ChineseFontScale", - 1.0f, - new ConfigDescription( - "Font scale for the Chinese subtitle line.", - new AcceptableValueRange(1.0f, 2.5f) - ) - ); - EnableCombatStatusBarConfig = config.Bind( - "CombatStatusBar", - "Enabled", - true, - "Whether to show the combat status bar with elapsed time, speed controls, and pause controls." - ); - CombatStatusBarSpeedMultiplierConfig = config.Bind( - "CombatStatusBar", - "SpeedMultiplier", - 1.0f, - "Default combat playback speed multiplier. The speed button cycles between 0.50, 0.67, and 1.00." - ); - EndOfRunScreenshotEnabledConfig = config.Bind( - "Screenshots", - "EndOfRunEnabled", - true, - "Whether to capture the automatic end-of-run screenshot before continuing from the run summary." - ); - EnchantPreviewHotkeyPathConfig = config.Bind( - "Hotkeys", - "EnchantPreview", - "/ctrl", - "Binding path for enchant preview tooltip mode." - ); - UpgradePreviewHotkeyPathConfig = config.Bind( - "Hotkeys", - "UpgradePreview", - "/shift", - "Binding path for upgrade preview tooltip mode." - ); - UpgradePreviewActivationModeConfig = config.Bind( - "Hotkeys", - "UpgradePreviewActivationMode", - DefaultUpgradePreviewActivationMode, - "How Shift behaves across BazaarPlusPlus preview features. Hold = active only while Shift is held. Toggle = each Shift press switches the upgrade preview on or off." - ); - ToggleCollectionPanelHotkeyPathConfig = config.Bind( - "Hotkeys", - "ToggleCollectionPanel", - "/tab", - "Binding path for toggling the card collection panel." - ); - ToggleLiveBuildPanelHotkeyPathConfig = config.Bind( - "Hotkeys", - "ToggleLiveBuildPanel", - "/capsLock", - "Binding path for toggling the final build panel." - ); - ToggleHistoryPanelHotkeyPathConfig = config.Bind( - "Hotkeys", - "ToggleHistoryPanel", - "/f8", - "Binding path for toggling the game history panel." - ); - ChineseLocaleModeConfig = config.Bind( - "Localization", - "ChineseLocaleMode", - BppChineseLocaleMode.Mainland, - "Chinese locale variant for BazaarPlusPlus UI when the game language is Chinese. Cycles between Mainland and Taiwan." - ); - ChineseLocaleModeConfig.Value = ChineseScriptConverter.NormalizeMode( - ChineseLocaleModeConfig.Value - ); - UiLanguageConfig = config.Bind( - "Localization", - "UiLanguage", - BppUiLanguage.Auto, - "Language for the BazaarPlusPlus UI. Auto follows the game language and falls back to the " - + "system language when the game stored none. English, Chinese, German, Portuguese, " - + "Korean, and Italian force that language." - ); - OverlayUiScalePercentConfig = config.Bind( - "OverlayUI", - "ScalePercent", - 100, - new ConfigDescription( - "Android BPP panel text and control scale, in percent. Use the touch dock UI-size " - + "button to cycle sizes. Native game cards/tooltips are not scaled.", - new AcceptableValueRange(100, 250) - ) - ); - // The touch dock remembers where the user dragged it: a normalized anchor of the BPP - // toggle's centre inside the safe area. (1, 0.5) is the default right edge. - TouchDockAnchorXConfig = config.Bind( - "TouchDock", - "AnchorX", - 1f, - new ConfigDescription( - "Horizontal position of the touch dock, as a fraction of the safe area. 1 is the " - + "right edge. Long-press BPP on the device to move it.", - new AcceptableValueRange(0f, 1f) - ) - ); - TouchDockAnchorYConfig = config.Bind( - "TouchDock", - "AnchorY", - 0.5f, - new ConfigDescription( - "Vertical position of the touch dock, as a fraction of the safe area. 0.5 is the " - + "middle. Long-press BPP on the device to move it.", - new AcceptableValueRange(0f, 1f) - ) - ); - LegendaryPositionDisplayModeConfig = config.Bind( - "LegendaryPositionDisplay", - "Mode", - LegendaryPositionDisplayMode.Default, - "How BazaarPlusPlus should rewrite native Legendary leaderboard position labels. Default keeps the original value, Blank clears it, Fixed999999 forces 999999, and PositionWithRating shows '#position | rating'." - ); - GraphicsUpscalingModeConfig = config.Bind( - "Graphics", - "UpscalingMode", - GraphicsUpscalingMode.Native, - "Desktop FSR 1 render-resolution upscaling mode for macOS and Windows. Native preserves the game's original URP settings. Ultra Quality renders at 77%, Quality at 67%, Balanced at 59%, and Performance at 50% per axis." - ); - GraphicsUpscalingSharpnessConfig = config.Bind( - "Graphics", - "FsrSharpness", - DefaultFsrSharpness, - new ConfigDescription( - "FSR 1 RCAS sharpening strength. 0 is softest and 1 is sharpest.", - new AcceptableValueRange(0f, 1f) - ) - ); - // BazaarDB - BazaarDbUploadEnabled = config.Bind( - "BazaarDB", - "UploadScreenshots", - false, - "When enabled, end-of-run screenshot snapshots are uploaded to our server for BazaarDB delivery. Includes screenshots from past runs. You can turn this off at any time; we will stop uploading and never delete what was already sent." - ); - UseFixedSupporterListConfig = config.Bind( - "Supporters", - "UseFixedSupporterList", - false, - "Whether supporter attribution should use the bundled fixed supporter list instead of the remote supporter list." - ); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/GraphicsUpscalingMode.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/GraphicsUpscalingMode.cs deleted file mode 100644 index 3f4bb04..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/GraphicsUpscalingMode.cs +++ /dev/null @@ -1,12 +0,0 @@ -#nullable enable - -namespace BazaarPlusPlus.Core.Config; - -internal enum GraphicsUpscalingMode -{ - Native, - FsrUltraQuality, - FsrQuality, - FsrBalanced, - FsrPerformance, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/HotkeyActivationMode.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/HotkeyActivationMode.cs deleted file mode 100644 index 2e62921..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/HotkeyActivationMode.cs +++ /dev/null @@ -1,8 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Config; - -internal enum HotkeyActivationMode -{ - Hold = 0, - Toggle = 1, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/LegendaryPositionDisplayMode.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/LegendaryPositionDisplayMode.cs deleted file mode 100644 index 34e3f12..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/LegendaryPositionDisplayMode.cs +++ /dev/null @@ -1,10 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Config; - -internal enum LegendaryPositionDisplayMode -{ - Default = 0, - Blank = 1, - Fixed999999 = 2, - PositionWithRating = 3, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/PreviewVisibilityMode.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/PreviewVisibilityMode.cs deleted file mode 100644 index f91d94e..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/PreviewVisibilityMode.cs +++ /dev/null @@ -1,9 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Config; - -internal enum PreviewVisibilityMode -{ - Off = 0, - AutoOnPedestalChoice = 1, - Always = 2, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/SubtitleLanguageMode.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/SubtitleLanguageMode.cs deleted file mode 100644 index a668dd2..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/SubtitleLanguageMode.cs +++ /dev/null @@ -1,9 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Config; - -internal enum SubtitleLanguageMode -{ - Both, - ChineseOnly, - EnglishOnly, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/SubtitlePosition.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/SubtitlePosition.cs deleted file mode 100644 index 57d2e85..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Config/SubtitlePosition.cs +++ /dev/null @@ -1,9 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Config; - -internal enum SubtitlePosition -{ - TopLeft, - TopRight, - TopCenter, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/ChineseLocaleModeChanged.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/ChineseLocaleModeChanged.cs deleted file mode 100644 index a4edfaa..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/ChineseLocaleModeChanged.cs +++ /dev/null @@ -1,4 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Events; - -internal sealed class ChineseLocaleModeChanged { } diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/CombatFrameAdvanced.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/CombatFrameAdvanced.cs deleted file mode 100644 index c3c2d8b..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/CombatFrameAdvanced.cs +++ /dev/null @@ -1,11 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Events; - -// No-payload signal published once per combat frame. A single shared instance is reused so the -// hot per-frame publish path allocates nothing. -internal sealed class CombatFrameAdvanced -{ - public static readonly CombatFrameAdvanced Instance = new(); - - private CombatFrameAdvanced() { } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/CombatReplayPersistenceDrained.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/CombatReplayPersistenceDrained.cs deleted file mode 100644 index af0caec..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/CombatReplayPersistenceDrained.cs +++ /dev/null @@ -1,5 +0,0 @@ -#nullable enable - -namespace BazaarPlusPlus.Core.Events; - -internal sealed class CombatReplayPersistenceDrained { } diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/IBppEventBus.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/IBppEventBus.cs deleted file mode 100644 index 9c0dec9..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/IBppEventBus.cs +++ /dev/null @@ -1,11 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Events; - -internal interface IBppEventBus -{ - IDisposable Subscribe(Action handler) - where TEvent : class; - - void Publish(TEvent eventData) - where TEvent : class; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/InMemoryBppEventBus.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/InMemoryBppEventBus.cs deleted file mode 100644 index 65e30fc..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/InMemoryBppEventBus.cs +++ /dev/null @@ -1,120 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Infrastructure.Logging; - -namespace BazaarPlusPlus.Core.Events; - -internal sealed class InMemoryBppEventBus : IBppEventBus -{ - private readonly object _syncRoot = new(); - - // Copy-on-write: each event type maps to an immutable handler array that Subscribe/Unsubscribe - // replace wholesale. Publish can therefore grab the current array under a brief lock and iterate - // it without allocating a per-call snapshot, while a handler that subscribes/unsubscribes during - // dispatch still cannot mutate the array the in-flight Publish is walking. - private readonly Dictionary _handlers = new(); - - public IDisposable Subscribe(Action handler) - where TEvent : class - { - if (handler == null) - throw new ArgumentNullException(nameof(handler)); - - lock (_syncRoot) - { - if (_handlers.TryGetValue(typeof(TEvent), out var existing)) - { - var updated = new Delegate[existing.Length + 1]; - Array.Copy(existing, updated, existing.Length); - updated[existing.Length] = handler; - _handlers[typeof(TEvent)] = updated; - } - else - { - _handlers[typeof(TEvent)] = new Delegate[] { handler }; - } - } - - return new Subscription(() => Unsubscribe(handler)); - } - - public void Publish(TEvent eventData) - where TEvent : class - { - if (eventData == null) - throw new ArgumentNullException(nameof(eventData)); - - Delegate[]? snapshot; - lock (_syncRoot) - { - if (!_handlers.TryGetValue(typeof(TEvent), out snapshot) || snapshot.Length == 0) - return; - } - - // snapshot is immutable (copy-on-write), so iterating it outside the lock is safe. - foreach (var registration in snapshot) - { - try - { - ((Action)registration).Invoke(eventData); - } - catch (Exception ex) - { - global::BazaarPlusPlus.Infrastructure.BppLog.WarnEvent( - new BppLogEvent( - BppLogFeatureScope.Plugin, - "plugin.event_handler.degraded", - storm: ["event_id", "handler_id"] - ), - ex, - ("event_id", typeof(TEvent).FullName), - ("handler_id", registration.Method.DeclaringType?.FullName), - ("reason_code", global::BazaarPlusPlus.PluginLogReasonCode.HandlerException) - ); - } - } - } - - private void Unsubscribe(Action handler) - where TEvent : class - { - lock (_syncRoot) - { - if (!_handlers.TryGetValue(typeof(TEvent), out var existing)) - return; - - var index = Array.IndexOf(existing, (Delegate)handler); - if (index < 0) - return; - - if (existing.Length == 1) - { - _handlers.Remove(typeof(TEvent)); - return; - } - - var updated = new Delegate[existing.Length - 1]; - Array.Copy(existing, 0, updated, 0, index); - Array.Copy(existing, index + 1, updated, index, existing.Length - index - 1); - _handlers[typeof(TEvent)] = updated; - } - } - - private sealed class Subscription : IDisposable - { - private readonly Action _dispose; - private int _disposed; - - public Subscription(Action dispose) - { - _dispose = dispose; - } - - public void Dispose() - { - if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0) - return; - - _dispose(); - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunInitializedObserved.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunInitializedObserved.cs deleted file mode 100644 index 99ef66f..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunInitializedObserved.cs +++ /dev/null @@ -1,7 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Events; - -internal sealed class RunInitializedObserved -{ - public string RunId { get; set; } = string.Empty; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunLifecycleChanged.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunLifecycleChanged.cs deleted file mode 100644 index d4e7ed5..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunLifecycleChanged.cs +++ /dev/null @@ -1,13 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Core.RunContext; - -namespace BazaarPlusPlus.Core.Events; - -internal sealed class RunLifecycleChanged -{ - public bool IsInGameRun { get; set; } - - public RunExitKind LastRunExitKind { get; set; } - - public string Reason { get; set; } = string.Empty; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunLifecycleReasons.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunLifecycleReasons.cs deleted file mode 100644 index 39d0f89..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Events/RunLifecycleReasons.cs +++ /dev/null @@ -1,9 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Events; - -internal static class RunLifecycleReasons -{ - public const string RunEnded = "Run ended"; - - public const string RunInterrupted = "Run interrupted"; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/ChoicePedestalSnapshot.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/ChoicePedestalSnapshot.cs deleted file mode 100644 index 89a107c..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/ChoicePedestalSnapshot.cs +++ /dev/null @@ -1,16 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -internal readonly struct ChoicePedestalSnapshot -{ - public ChoiceScreenPedestalKind Kind { get; init; } - public IReadOnlyList EnchantmentTypeNames { get; init; } - public bool IsEnchantChoice => Kind == ChoiceScreenPedestalKind.Enchant; - - public static ChoicePedestalSnapshot Empty { get; } = - new() - { - Kind = ChoiceScreenPedestalKind.None, - EnchantmentTypeNames = Array.Empty(), - }; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/ChoiceScreenPedestalKind.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/ChoiceScreenPedestalKind.cs deleted file mode 100644 index 3558552..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/ChoiceScreenPedestalKind.cs +++ /dev/null @@ -1,9 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -internal enum ChoiceScreenPedestalKind -{ - None = 0, - Upgrade = 1, - Enchant = 2, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterIdsProbeOutcome.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterIdsProbeOutcome.cs deleted file mode 100644 index 28d4b61..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterIdsProbeOutcome.cs +++ /dev/null @@ -1,21 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -internal readonly record struct EncounterIdsProbeOutcome( - bool IsSuccess, - EncounterIdsSnapshot Snapshot, - EncounterProbeFailureReason FailureReason, - Exception? Exception -) -{ - internal static EncounterIdsProbeOutcome Success(EncounterIdsSnapshot snapshot) => - new(true, snapshot, EncounterProbeFailureReason.None, null); - - internal static EncounterIdsProbeOutcome Failure(Exception exception) => - new( - false, - EncounterIdsSnapshot.Empty, - EncounterProbeFailureReason.EncounterIdsReadException, - exception - ); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterIdsSnapshot.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterIdsSnapshot.cs deleted file mode 100644 index ac18a80..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterIdsSnapshot.cs +++ /dev/null @@ -1,24 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -/// Lightweight read of the currently available encounter ids. -public readonly struct EncounterIdsSnapshot -{ - public string? CurrentEncounterId { get; init; } - public Guid? CurrentEncounterTemplateId { get; init; } - public bool IsChoiceState { get; init; } - public bool IsSelectionState { get; init; } - public IReadOnlyList ChoiceSelectionEntryIds { get; init; } - public IReadOnlyList ChoiceSelectionTemplateIds { get; init; } - - public static EncounterIdsSnapshot Empty { get; } = - new() - { - CurrentEncounterId = null, - CurrentEncounterTemplateId = null, - IsChoiceState = false, - IsSelectionState = false, - ChoiceSelectionEntryIds = Array.Empty(), - ChoiceSelectionTemplateIds = Array.Empty(), - }; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterProbeOutcomes.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterProbeOutcomes.cs deleted file mode 100644 index 40ee5f4..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/EncounterProbeOutcomes.cs +++ /dev/null @@ -1,25 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -internal enum EncounterProbeFailureReason -{ - None, - EncounterIdsReadException, - ChoiceResolutionException, -} - -internal readonly record struct ChoicePedestalProbeOutcome( - bool IsSuccess, - ChoicePedestalSnapshot Snapshot, - EncounterProbeFailureReason FailureReason, - Exception? Exception -) -{ - internal static ChoicePedestalProbeOutcome Success(ChoicePedestalSnapshot snapshot) => - new(true, snapshot, EncounterProbeFailureReason.None, null); - - internal static ChoicePedestalProbeOutcome Failure( - EncounterProbeFailureReason reason, - Exception? exception - ) => new(false, ChoicePedestalSnapshot.Empty, reason, exception); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IEncounterStateProbe.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IEncounterStateProbe.cs deleted file mode 100644 index c54eea4..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IEncounterStateProbe.cs +++ /dev/null @@ -1,15 +0,0 @@ -#nullable enable - -namespace BazaarPlusPlus.Core.GameState; - -internal interface IEncounterStateProbe -{ - /// Main thread only. Lightweight read for current and choice-screen - /// encounter ids. Safe for high-frequency UI paths. A failed read carries its reason, so a - /// fallback empty snapshot cannot be mistaken for a complete selection read. - EncounterIdsProbeOutcome GetEncounterIdsOutcome(); - - /// Main thread only. Resolves the currently offered choice-screen - /// pedestal kind from the lightweight id snapshot. - ChoicePedestalProbeOutcome GetChoicePedestalOutcome(); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IGameStateProbe.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IGameStateProbe.cs deleted file mode 100644 index 5e429ec..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IGameStateProbe.cs +++ /dev/null @@ -1,7 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -internal interface IGameStateProbe -{ - bool ComputeIsInGameRun(); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IRunSnapshotProbe.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IRunSnapshotProbe.cs deleted file mode 100644 index aab0594..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/IRunSnapshotProbe.cs +++ /dev/null @@ -1,13 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -internal interface IRunSnapshotProbe -{ - bool TryGetRunBasics(out RunBasicsSnapshot basics); - - bool TryGetPlayerStats(out PlayerStatsSnapshot stats); - - bool TryGetRankSnapshot(out RankSnapshot rank); - - bool TryGetLeaderboardPosition(out int? position); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/PlayerStatsSnapshot.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/PlayerStatsSnapshot.cs deleted file mode 100644 index 3f18f12..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/PlayerStatsSnapshot.cs +++ /dev/null @@ -1,15 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -public sealed class PlayerStatsSnapshot -{ - public int? MaxHealth { get; set; } - - public int? Prestige { get; set; } - - public int? Level { get; set; } - - public int? Income { get; set; } - - public int? Gold { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/RankSnapshot.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/RankSnapshot.cs deleted file mode 100644 index 214b1e5..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/RankSnapshot.cs +++ /dev/null @@ -1,9 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -public sealed class RankSnapshot -{ - public string? Rank { get; set; } - - public int? Rating { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/RunBasicsSnapshot.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/RunBasicsSnapshot.cs deleted file mode 100644 index 458c222..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/GameState/RunBasicsSnapshot.cs +++ /dev/null @@ -1,17 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.GameState; - -internal sealed class RunBasicsSnapshot -{ - public int? Day { get; set; } - - public int? Hour { get; set; } - - public int? Victories { get; set; } - - public int? Losses { get; set; } - - public string? Hero { get; set; } - - public string? GameMode { get; set; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Paths/BepInExPathProvider.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Paths/BepInExPathProvider.cs deleted file mode 100644 index 517c0f2..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Paths/BepInExPathProvider.cs +++ /dev/null @@ -1,154 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Infrastructure; -using BazaarPlusPlus.Infrastructure.Logging; -using BazaarPlusPlus.Storage.Paths; - -namespace BazaarPlusPlus.Core.Paths; - -/// -/// Resolves the BPP data root under BepInEx's game root. -/// -/// On the Android port BepInEx points its game root at a writable external directory -/// (/sdcard/BepInEx_Android/<package>), but a read-only or misconfigured root would make -/// every history/config write fail at runtime rather than at startup. The probe below keeps that -/// failure local and falls back to Unity's per-app storage, which is always writable. -/// -/// On NextBep the game root is not the external directory but the per-launch code-cache directory -/// (/data/user/0/com.bepinex.android/app_bepinex_runtime/<package>), which is app-private -/// and therefore writable. That is a legitimate outcome, but the resulting root is invisible to a -/// search of shared storage, so the resolution is written once at startup: which candidate won, -/// the absolute path, and why the losing candidate was rejected. -/// -internal sealed class BepInExPathProvider : IPathProvider -{ - // Not a storm: this runs once per process, and a suppressed line would hide the answer. - private static readonly BppLogEvent DataRootResolved = new( - BppLogFeatureScope.Plugin, - "plugin.data_root.resolved" - ); - - public string? DataRootDirectoryPath { get; private set; } - - /// Why points where it does, for the log. - public string ResolutionSource { get; private set; } = "uninitialized"; - - public void Initialize() - { - var candidate = System.IO.Path.Combine( - BepInEx.Paths.GameRootPath, - PathConstants.DataRootDirectoryName - ); - - if (CanCreate(candidate, out var candidateFailure)) - { - Publish(candidate, "bepinex-game-root", probeFailure: null); - return; - } - - // NextBep keeps the game root in a per-launch runtime cache. A stable sibling under the - // same app-private data directory survives runtime-cache churn, so prefer it over Unity's - // persistent data path, which the launcher redirects to read-only external storage. - var stable = AppPrivateDataRoot(); - string? stableFailure = null; - if (stable != null && !string.Equals(stable, candidate, StringComparison.Ordinal)) - { - if (CanCreate(stable, out stableFailure)) - { - Publish(stable, "app-private-data", probeFailure: candidateFailure); - return; - } - } - - var fallback = System.IO.Path.Combine( - UnityEngine.Application.persistentDataPath, - PathConstants.DataRootDirectoryName - ); - - // Adopting the fallback even when its probe also fails is the pre-existing behaviour: the - // failure then surfaces at the writer instead of at startup. The probe result is reported - // so that path is not mistaken for a verified-writable root. - var fallbackWritable = CanCreate(fallback, out var fallbackFailure); - Publish( - fallback, - "unity-persistent-data", - fallbackWritable ? null : (fallbackFailure ?? stableFailure ?? candidateFailure) - ); - } - - /// - /// The app-private data directory for this game, or null when the game root is not the NextBep - /// runtime cache. Both live under the same /data/user/0/<launcher>/ parent, so only - /// the app_bepinex_runtime segment differs from files. - /// - private static string? AppPrivateDataRoot() - { - var gameRoot = BepInEx.Paths.GameRootPath; - if (string.IsNullOrWhiteSpace(gameRoot)) - return null; - - var runtimeDirectory = System.IO.Directory.GetParent(gameRoot.TrimEnd( - System.IO.Path.DirectorySeparatorChar, - System.IO.Path.AltDirectorySeparatorChar - )); - var appDirectory = runtimeDirectory?.Parent; - if ( - runtimeDirectory == null - || appDirectory == null - || !string.Equals( - runtimeDirectory.Name, - "app_bepinex_runtime", - StringComparison.Ordinal - ) - ) - return null; - - return System.IO.Path.Combine( - appDirectory.FullName, - "files", - System.IO.Path.GetFileName(gameRoot.TrimEnd( - System.IO.Path.DirectorySeparatorChar, - System.IO.Path.AltDirectorySeparatorChar - )), - PathConstants.DataRootDirectoryName - ); - } - - private void Publish(string dataRoot, string source, string? probeFailure) - { - DataRootDirectoryPath = dataRoot; - ResolutionSource = source; - - BppLog.InfoEvent( - DataRootResolved, - ("source", source), - ("data_root", dataRoot), - ("game_root", BepInEx.Paths.GameRootPath), - ("persistent_data_path", UnityEngine.Application.persistentDataPath), - ("probe_failure", probeFailure ?? "none") - ); - - // The BepInEx log writer buffers, so the same fact goes to the unbuffered startup trace. - BppStartupTrace.Write($"data-root:{source}:{dataRoot}"); - if (probeFailure != null) - BppStartupTrace.Write($"data-root:probe-failed:{probeFailure}"); - } - - private static bool CanCreate(string directoryPath, out string? failure) - { - try - { - System.IO.Directory.CreateDirectory(directoryPath); - var probe = System.IO.Path.Combine(directoryPath, ".bpp-write-probe"); - System.IO.File.WriteAllText(probe, string.Empty); - System.IO.File.Delete(probe); - failure = null; - return true; - } - catch (Exception ex) - { - // The type and message are what identify a storage-permission or read-only failure. - failure = ex.GetType().Name + ": " + ex.Message; - return false; - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/RunContext/RunExitKind.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/RunContext/RunExitKind.cs deleted file mode 100644 index 65eed2d..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/RunContext/RunExitKind.cs +++ /dev/null @@ -1,8 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.RunContext; - -internal enum RunExitKind -{ - Completed, - Interrupted, -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppBuild.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppBuild.cs deleted file mode 100644 index 705fb9a..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppBuild.cs +++ /dev/null @@ -1,11 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Runtime; - -internal static class BppBuild -{ -#if DEBUG - internal static bool IsDebug => true; -#else - internal static bool IsDebug => false; -#endif -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppFeatureRegistry.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppFeatureRegistry.cs deleted file mode 100644 index 223a689..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppFeatureRegistry.cs +++ /dev/null @@ -1,65 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Infrastructure.Logging; - -namespace BazaarPlusPlus.Core.Runtime; - -internal sealed class BppFeatureRegistry -{ - private readonly List _features = new(); - - public void Register(IBppFeature feature) - { - _features.Add(feature); - } - - public void Start() - { - for (var index = 0; index < _features.Count; index++) - { - try - { - // Traced by index: reflecting over the feature types resolves generated types that - // the interop layer may not have ready, and the abort that follows has no stack. - global::BazaarPlusPlus.Infrastructure.BppStartupTrace.Write("feature:" + index); - _features[index].Start(); - } - catch (Exception ex) - { - global::BazaarPlusPlus.Infrastructure.BppLog.WarnEvent( - new BppLogEvent( - BppLogFeatureScope.Plugin, - "plugin.feature_start.degraded", - storm: ["feature", "reason_code"] - ), - ex, - ("feature", _features[index].GetType().FullName), - ("reason_code", global::BazaarPlusPlus.PluginLogReasonCode.FeatureException) - ); - } - } - } - - public void Stop() - { - for (var i = _features.Count - 1; i >= 0; i--) - { - try - { - _features[i].Stop(); - } - catch (Exception ex) - { - global::BazaarPlusPlus.Infrastructure.BppLog.WarnEvent( - new BppLogEvent( - BppLogFeatureScope.Plugin, - "plugin.feature_stop.degraded", - storm: ["feature", "reason_code"] - ), - ex, - ("feature", _features[i].GetType().FullName), - ("reason_code", global::BazaarPlusPlus.PluginLogReasonCode.FeatureException) - ); - } - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppMountableRegistry.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppMountableRegistry.cs deleted file mode 100644 index c6d9054..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppMountableRegistry.cs +++ /dev/null @@ -1,33 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Infrastructure; -using BazaarPlusPlus.Infrastructure.Logging; -using UnityEngine; - -namespace BazaarPlusPlus.Core.Runtime; - -internal sealed class BppMountableRegistry -{ - private readonly List _mountables = new(); - - public void Register(IBppMountable mountable) => _mountables.Add(mountable); - - public void MountAll(GameObject host, IBppServices services) - { - for (var index = 0; index < _mountables.Count; index++) - { - // Traced by index, not by type name: reflecting over these generic mount types makes the - // interop layer resolve types it cannot represent, which aborts before the mount runs. - BppStartupTrace.Write("mount:" + index); - - _mountables[index].Mount(host, services); - } - - BppStartupTrace.Write("mount:done"); - } - - public void UnmountAll(GameObject host) - { - for (var i = _mountables.Count - 1; i >= 0; i--) - _mountables[i].Unmount(host); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppRuntimeServices.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppRuntimeServices.cs deleted file mode 100644 index 10e80de..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/BppRuntimeServices.cs +++ /dev/null @@ -1,41 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Core.Config; -using BazaarPlusPlus.Core.Events; -using BazaarPlusPlus.Core.GameState; -using BazaarPlusPlus.GameInterop; -using BazaarPlusPlus.Storage.Paths; - -namespace BazaarPlusPlus.Core.Runtime; - -internal sealed class BppRuntimeServices : IBppServices -{ - public BppRuntimeServices( - IBppEventBus eventBus, - BppConfig config, - IPathProvider paths, - IRunContext runContext, - IGameStateProbe gameStateProbe, - IEncounterStateProbe encounterState, - IRunSnapshotProbe runSnapshot, - IGameBuildInfo gameBuild - ) - { - EventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus)); - Config = config ?? throw new ArgumentNullException(nameof(config)); - Paths = paths ?? throw new ArgumentNullException(nameof(paths)); - RunContext = runContext ?? throw new ArgumentNullException(nameof(runContext)); - GameStateProbe = gameStateProbe ?? throw new ArgumentNullException(nameof(gameStateProbe)); - EncounterState = encounterState ?? throw new ArgumentNullException(nameof(encounterState)); - RunSnapshot = runSnapshot ?? throw new ArgumentNullException(nameof(runSnapshot)); - GameBuild = gameBuild ?? throw new ArgumentNullException(nameof(gameBuild)); - } - - public IBppEventBus EventBus { get; } - public BppConfig Config { get; } - public IPathProvider Paths { get; } - public IRunContext RunContext { get; } - public IGameStateProbe GameStateProbe { get; } - public IEncounterStateProbe EncounterState { get; } - public IRunSnapshotProbe RunSnapshot { get; } - public IGameBuildInfo GameBuild { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/ComponentMount.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/ComponentMount.cs deleted file mode 100644 index a9243b3..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/ComponentMount.cs +++ /dev/null @@ -1,33 +0,0 @@ -#nullable enable -using UnityEngine; - -namespace BazaarPlusPlus.Core.Runtime; - -/// -/// Generic for the common case: add one component to the host at -/// mount, run an optional initializer, and DestroyImmediate it on unmount. Replaces the -/// per-feature mount classes that differed only by component type and initializer call. -/// -internal sealed class ComponentMount : IBppMountable - where T : Component -{ - private readonly Action? _initialize; - - public ComponentMount(Action? initialize = null) - { - _initialize = initialize; - } - - public void Mount(GameObject host, IBppServices services) - { - var component = host.AddComponent(); - _initialize?.Invoke(component, services); - } - - public void Unmount(GameObject host) - { - var component = host.GetComponent(); - if (component != null) - UnityEngine.Object.DestroyImmediate(component); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppFeature.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppFeature.cs deleted file mode 100644 index 8251d46..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppFeature.cs +++ /dev/null @@ -1,10 +0,0 @@ -#nullable enable - -namespace BazaarPlusPlus.Core.Runtime; - -internal interface IBppFeature -{ - void Start(); - - void Stop(); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppMountable.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppMountable.cs deleted file mode 100644 index 2f56b18..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppMountable.cs +++ /dev/null @@ -1,12 +0,0 @@ -#nullable enable -using UnityEngine; - -namespace BazaarPlusPlus.Core.Runtime; - -/// Unity-aware counterpart of . Mount-time -/// receives the host GameObject so implementors can AddComponent. -internal interface IBppMountable -{ - void Mount(GameObject host, IBppServices services); - void Unmount(GameObject host); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppServices.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppServices.cs deleted file mode 100644 index 28d5346..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IBppServices.cs +++ /dev/null @@ -1,20 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Core.Config; -using BazaarPlusPlus.Core.Events; -using BazaarPlusPlus.Core.GameState; -using BazaarPlusPlus.GameInterop; -using BazaarPlusPlus.Storage.Paths; - -namespace BazaarPlusPlus.Core.Runtime; - -internal interface IBppServices -{ - IBppEventBus EventBus { get; } - BppConfig Config { get; } - IPathProvider Paths { get; } - IRunContext RunContext { get; } - IGameStateProbe GameStateProbe { get; } - IEncounterStateProbe EncounterState { get; } - IRunSnapshotProbe RunSnapshot { get; } - IGameBuildInfo GameBuild { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IGameBuildInfo.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IGameBuildInfo.cs deleted file mode 100644 index 6957b2d..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Core/Runtime/IGameBuildInfo.cs +++ /dev/null @@ -1,20 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Core.Runtime; - -internal enum GameBuildChannel -{ - Online, - - // Persisted isolation category for PTR and staging clients. - Ptr, - - // Detection failed (version string unreadable). Policy gates must treat Unknown - // like Online so a detection failure can never change online behavior. - Unknown, -} - -internal interface IGameBuildInfo -{ - string RawVersion { get; } - GameBuildChannel Channel { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Data/BuildRecommendations/builds.json b/bazaarplusplus-mod/src/BazaarPlusPlus/Data/BuildRecommendations/builds.json deleted file mode 100644 index 3eff295..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Data/BuildRecommendations/builds.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "schema_version": 2, - "kind": "ten_win_builds", - "generated_at": "2026-08-12T02:00:00Z", - "window": { "start": "2026-08-07", "end": "2026-08-11", "days": 5 }, - "cards": [ - "11111111-1111-1111-1111-111111111111", - "22222222-2222-2222-2222-222222222222", - "33333333-3333-3333-3333-333333333333", - "44444444-4444-4444-4444-444444444444", - "55555555-5555-5555-5555-555555555555" - ], - "enchantments": [null, "Burn", "Shielded"], - "schemas": { - "build": ["card_refs", "layout", "stats"], - "layout": ["card_ref", "slot", "tier", "enchant_ref", "size"], - "stats": [ - "completed_run_count", - "ten_win_run_count", - "ten_win_rate_bps", - "p75_ten_win_final_day", - "score" - ] - }, - "heroes": { - "Vanessa": { - "builds": [ - [ - [0, 1, 2, 3, 4], - [ - [0, 0, 4, 0, 2], - [1, 2, 3, 1, 2], - [2, 4, 4, 0, 2], - [3, 6, 3, 0, 2], - [4, 8, 4, 2, 2] - ], - [123, 45, 3659, 13, 421037] - ] - ], - "card_index": [ - [0, [0]], - [1, [0]], - [2, [0]], - [3, [0]], - [4, [0]] - ] - }, - "Pygmalien": { - "builds": [], - "card_index": [] - }, - "Dooley": { - "builds": [], - "card_index": [] - }, - "Mak": { - "builds": [], - "card_index": [] - }, - "Jules": { - "builds": [], - "card_index": [] - }, - "Karnok": { - "builds": [], - "card_index": [] - }, - "Stelle": { - "builds": [], - "card_index": [] - }, - "TheDragons": { - "builds": [], - "card_index": [] - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Data/CollectionSources/collection-sources.json b/bazaarplusplus-mod/src/BazaarPlusPlus/Data/CollectionSources/collection-sources.json deleted file mode 100644 index db4fc28..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Data/CollectionSources/collection-sources.json +++ /dev/null @@ -1,2105 +0,0 @@ -{ - "schemaVersion": 4, - "groups": [ - "generalist", - "tier-specialist", - "size-specialist", - "other-hero", - "all-hero", - "tag-type-specialist", - "trainer" - ], - "entries": [ - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 1, - "name": "Aero", - "availableHeroes": [ - "Stelle" - ], - "description": "Sells Vehicles or Drones", - "portraitTemplateId": "847b1294-649d-4f02-ab04-0ee9f838c462", - "sourceTemplateIds": [ - "847b1294-649d-4f02-ab04-0ee9f838c462" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Vehicle", - "Drone" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 0, - "name": "Aila", - "availableHeroes": [], - "description": "Sells Weapons", - "portraitTemplateId": "0cb20108-dcbb-48e2-8294-519d09c60b3e", - "sourceTemplateIds": [ - "0cb20108-dcbb-48e2-8294-519d09c60b3e", - "3155d09b-1440-4a95-a64e-68243735421d", - "3e22799f-87df-4c9f-bd45-769e14753caa", - "47a149e6-a8e2-4e33-aa88-e76246c45696", - "97b6aca1-f1f5-492b-afd8-fcab7752ef7c", - "9cac2384-2020-4ae9-8375-15c5d07da446", - "abf614d4-4700-41f3-a05a-68c7e843cb1a", - "dc12f4bd-6c33-41f0-b7ad-d62a0be09a47" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Weapon" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "all-hero", - "order": 2, - "name": "Aimbot", - "availableHeroes": [], - "description": "Sells Crit items from any Hero", - "portraitTemplateId": "f22fd14f-7e00-40cb-9e44-a46f34d64764", - "sourceTemplateIds": [ - "f22fd14f-7e00-40cb-9e44-a46f34d64764" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "AllHeroes", - "hiddenTagGroupsAny": [ - "Crit" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "size-specialist", - "order": 0, - "name": "Ande", - "availableHeroes": [], - "description": "Sells Small items", - "portraitTemplateId": "60e67364-7aab-4ffa-9751-db5ec0caf452", - "sourceTemplateIds": [ - "60e67364-7aab-4ffa-9751-db5ec0caf452", - "705c0d8e-8513-49ce-82e8-81782cdac316", - "70915950-ad96-47c8-a139-48b913b80750", - "b649cc9a-9ea4-46d3-9ee5-8d57626260cf", - "e3bbe96b-7108-4343-9584-3bade7f004a5" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "sizesAny": [ - "Small" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "size-specialist", - "order": 4, - "name": "Barkun", - "availableHeroes": [], - "description": "Sells Medium and Large items. Buys your Small items at +1 Value", - "portraitTemplateId": "8f0aea10-9894-4ded-a726-72b23142589c", - "sourceTemplateIds": [ - "8f0aea10-9894-4ded-a726-72b23142589c" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "sizesAny": [ - "Medium", - "Large" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 12, - "name": "Chronos", - "availableHeroes": [], - "description": "Sells Haste items", - "portraitTemplateId": "3346b0d5-20a0-4aa4-a7d4-b86ad0109e59", - "sourceTemplateIds": [ - "3346b0d5-20a0-4aa4-a7d4-b86ad0109e59", - "b1288f12-2cf9-4473-a43e-4dd521703990" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Haste" - ] - } - }, - { - "key": "rare-turbo", - "kind": "Enchanted", - "rarityLabel": "Rare", - "rule": { - "heroMode": "SelectedHero", - "enchantmentTypesAny": [ - "Turbo" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 13, - "name": "Cobweb", - "availableHeroes": [], - "description": "Sells Slow items", - "portraitTemplateId": "b10f79af-da26-4b27-88da-3e7fea49a3b9", - "sourceTemplateIds": [ - "b10f79af-da26-4b27-88da-3e7fea49a3b9", - "ef25f92c-484a-48de-b6de-8fc6429823ca" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Slow" - ] - } - }, - { - "key": "rare-heavy", - "kind": "Enchanted", - "rarityLabel": "Rare", - "rule": { - "heroMode": "SelectedHero", - "enchantmentTypesAny": [ - "Heavy" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 18, - "name": "Colt", - "availableHeroes": [ - "Vanessa" - ], - "description": "Sells Ammo items", - "portraitTemplateId": "816e6ba0-8f5f-412e-9756-8e1901dd9d49", - "sourceTemplateIds": [ - "816e6ba0-8f5f-412e-9756-8e1901dd9d49" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Ammo" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tier-specialist", - "order": 1, - "name": "Curio", - "availableHeroes": [], - "description": "Sells Bronze-tier Neutral items", - "portraitTemplateId": "c6cffe25-8e94-4a7b-a821-3e3c7093333b", - "sourceTemplateIds": [ - "c6cffe25-8e94-4a7b-a821-3e3c7093333b" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "NeutralOnly", - "startingTier": { - "mode": "AtMost", - "tier": "Bronze" - } - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 1, - "name": "Dooley", - "availableHeroes": [ - "Jules", - "Karnok", - "Mak", - "Pygmalien", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Sells items from this Hero", - "portraitTemplateId": "4580fb31-b2ea-4f9b-9ab9-2979602f83d8", - "sourceTemplateIds": [ - "4580fb31-b2ea-4f9b-9ab9-2979602f83d8" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Dooley" - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 5, - "name": "Eli", - "availableHeroes": [ - "Mak" - ], - "description": "Sells Potions", - "portraitTemplateId": "0ff275f7-60ef-4428-acb6-1a138d03152d", - "sourceTemplateIds": [ - "0ff275f7-60ef-4428-acb6-1a138d03152d" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Potion" - ] - } - }, - { - "key": "reference", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "PotionReference" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 10, - "name": "Flex", - "availableHeroes": [ - "Karnok", - "Pygmalien" - ], - "description": "Sells Max Health items", - "portraitTemplateId": "7bd967dd-4631-4252-bdff-ee0bd5e3ddb7", - "sourceTemplateIds": [ - "7bd967dd-4631-4252-bdff-ee0bd5e3ddb7" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Health" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 17, - "name": "Freiya", - "availableHeroes": [], - "description": "Sells Freeze items", - "portraitTemplateId": "c246ee53-51ea-40c1-ac2f-71435e179531", - "sourceTemplateIds": [ - "c246ee53-51ea-40c1-ac2f-71435e179531" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Freeze" - ] - } - }, - { - "key": "rare-icy", - "kind": "Enchanted", - "rarityLabel": "Rare", - "rule": { - "heroMode": "SelectedHero", - "enchantmentTypesAny": [ - "Icy" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "all-hero", - "order": 4, - "name": "Gaseo", - "availableHeroes": [], - "description": "Sells Apparel from any Hero", - "portraitTemplateId": "9fc8b5a3-f522-4999-b310-26a0fadc7708", - "sourceTemplateIds": [ - "9fc8b5a3-f522-4999-b310-26a0fadc7708" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "AllHeroes", - "tagsAny": [ - "Apparel" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 7, - "name": "Gastro", - "availableHeroes": [ - "Jules" - ], - "description": "Sells Foods", - "portraitTemplateId": "c3d9c329-0db6-478e-ad0f-ef2ae78834ce", - "sourceTemplateIds": [ - "c3d9c329-0db6-478e-ad0f-ef2ae78834ce" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Food" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tier-specialist", - "order": 3, - "name": "Goldie", - "availableHeroes": [], - "description": "Sells Gold-tier items", - "portraitTemplateId": "1f72700a-fe11-4792-8a47-9e52b9387f29", - "sourceTemplateIds": [ - "1f72700a-fe11-4792-8a47-9e52b9387f29", - "50292930-5e68-47a2-8cc5-fde69aadc5aa" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "startingTier": { - "mode": "AtMost", - "tier": "Gold" - } - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 15, - "name": "Hef", - "availableHeroes": [], - "description": "Sells Burn items", - "portraitTemplateId": "43dbd6ed-6989-4ae4-acdc-f8bfcb8a008f", - "sourceTemplateIds": [ - "43dbd6ed-6989-4ae4-acdc-f8bfcb8a008f", - "55e0f929-071a-4e51-b60e-51fcc792f0b9" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Burn" - ] - } - }, - { - "key": "rare-fiery", - "kind": "Enchanted", - "rarityLabel": "Rare", - "rule": { - "heroMode": "SelectedHero", - "enchantmentTypesAny": [ - "Fiery" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 11, - "name": "Herma", - "availableHeroes": [ - "Jules", - "Karnok", - "Mak", - "Pygmalien" - ], - "description": "Sells Heal and Regen items", - "portraitTemplateId": "2708055d-a8be-4c2f-a8d6-574e884a254e", - "sourceTemplateIds": [ - "2708055d-a8be-4c2f-a8d6-574e884a254e" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Heal", - "Regen" - ], - "hiddenTagsAny": [ - "HealthRegen" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "generalist", - "order": 0, - "name": "Jay Jay", - "availableHeroes": [], - "description": "Sells items", - "portraitTemplateId": "00b9bc97-b751-48c3-b3ae-6d96adf7a929", - "sourceTemplateIds": [ - "00b9bc97-b751-48c3-b3ae-6d96adf7a929", - "2f885e4a-bbb5-4233-8798-7224dd126f6e", - "5406f2e4-d22e-4aca-84c5-87fc81883d6e", - "74d81658-9f44-45e6-8f7c-fd6ced634e63", - "85db60ee-3619-4e39-bfb2-2f4ac56f172b", - "89d7bbcd-bf3e-48e5-a2ab-013d23452378", - "96cf61f6-9b9b-453c-9fc0-ea9268a0b71d", - "e25617c8-7366-428d-a3c2-b721fb9aa722", - "e34024e3-4380-4689-b9c6-b3db7faeaec5", - "eb1453e4-2307-4b6f-9a15-f8f30c849eb4", - "fa533c05-c89a-4849-8562-b560532f1431" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero" - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 6, - "name": "Jules", - "availableHeroes": [ - "Dooley", - "Karnok", - "Mak", - "Pygmalien", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Sells items from this Hero", - "portraitTemplateId": "7fdc233f-b81f-4216-a646-4c807c2240da", - "sourceTemplateIds": [ - "7fdc233f-b81f-4216-a646-4c807c2240da" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Jules" - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 7, - "name": "The Dragons", - "availableHeroes": [ - "Vanessa", - "Dooley", - "Pygmalien", - "Karnok", - "Mak", - "Stelle", - "Jules" - ], - "description": "Sells items from this Hero", - "portraitTemplateId": "85cdd52b-12c2-4b64-b308-a5788f791b81", - "sourceTemplateIds": [ - "85cdd52b-12c2-4b64-b308-a5788f791b81" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "TheDragons" - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 8, - "name": "Stickybeans", - "availableHeroes": [ - "Vanessa", - "Dooley", - "Pygmalien", - "Karnok", - "Mak", - "Stelle", - "Jules", - "TheDragons" - ], - "description": "Sells items from other Heroes", - "portraitTemplateId": "d0276b47-be8a-4bbc-ab55-9f92b352480a", - "sourceTemplateIds": [ - "d0276b47-be8a-4bbc-ab55-9f92b352480a" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "OtherHeroes" - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 3, - "name": "Karnok", - "availableHeroes": [ - "Dooley", - "Jules", - "Mak", - "Pygmalien", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Sells items from this Hero", - "portraitTemplateId": "379d881b-4524-4db9-a606-47bd35749f44", - "sourceTemplateIds": [ - "379d881b-4524-4db9-a606-47bd35749f44" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Karnok" - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 9, - "name": "Kev's Armory", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Pygmalien", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Sells Health and Shield items", - "portraitTemplateId": "a4fa13f8-6beb-4b6c-839b-60af167628d9", - "sourceTemplateIds": [ - "a4fa13f8-6beb-4b6c-839b-60af167628d9" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Health", - "Shield" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tier-specialist", - "order": 0, - "name": "Kina", - "availableHeroes": [], - "description": "Sells non-Weapon items", - "portraitTemplateId": "3ab184ce-bdb8-4dee-9169-8b383a25eae6", - "sourceTemplateIds": [ - "3ab184ce-bdb8-4dee-9169-8b383a25eae6", - "5b7c5fc4-c942-44fe-9ca8-726dc36a2ad6", - "79fe1693-1e6d-4ed6-b376-794baca19262", - "7b598c89-fdf2-4e83-bc4c-6f16d86fbe04" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsNone": [ - "Weapon" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 16, - "name": "Knightshade", - "availableHeroes": [], - "description": "Sells Poison items", - "portraitTemplateId": "2745a661-095c-44a5-bb6e-8dc76e07bda2", - "sourceTemplateIds": [ - "2745a661-095c-44a5-bb6e-8dc76e07bda2", - "d86e22d9-b54d-4be9-8b5b-f3fe93d4c133" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Poison" - ] - } - }, - { - "key": "rare-toxic", - "kind": "Enchanted", - "rarityLabel": "Rare", - "rule": { - "heroMode": "SelectedHero", - "enchantmentTypesAny": [ - "Toxic" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tier-specialist", - "order": 4, - "name": "Luxe", - "availableHeroes": [], - "description": "Sells Diamond-tier items", - "portraitTemplateId": "892de564-d894-4e07-ab21-959e16e8cdf8", - "sourceTemplateIds": [ - "892de564-d894-4e07-ab21-959e16e8cdf8" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "startingTier": { - "mode": "AtMost", - "tier": "Diamond" - } - } - } - ] - }, - { - "kind": "Merchant", - "group": "tier-specialist", - "order": 5, - "name": "Private Pitchfork", - "availableHeroes": [], - "description": "Sells Neutral items", - "portraitTemplateId": "15b88e74-024e-40a3-a811-aa5810e68ca2", - "sourceTemplateIds": [ - "15b88e74-024e-40a3-a811-aa5810e68ca2" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "NeutralOnly", - "tagsNone": [ - "Loot" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 4, - "name": "Mak", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Pygmalien", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Sells items from this Hero", - "portraitTemplateId": "4475cff5-6105-4f4a-978c-b282e36173eb", - "sourceTemplateIds": [ - "4475cff5-6105-4f4a-978c-b282e36173eb" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Mak" - } - } - ] - }, - { - "kind": "Merchant", - "group": "size-specialist", - "order": 3, - "name": "Midsworth", - "availableHeroes": [], - "description": "Sells Small and Large items. Buys your Medium items at +2 value", - "portraitTemplateId": "214fe1d5-c583-4766-99c5-c621598c83ce", - "sourceTemplateIds": [ - "214fe1d5-c583-4766-99c5-c621598c83ce", - "b8f55bb0-536e-4d5f-a328-d38f88c6d479" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "sizesAny": [ - "Small", - "Large" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "size-specialist", - "order": 1, - "name": "Mittel", - "availableHeroes": [], - "description": "Sells Medium items", - "portraitTemplateId": "912c8b09-3b76-4aa1-8e21-245e0dfb5046", - "sourceTemplateIds": [ - "912c8b09-3b76-4aa1-8e21-245e0dfb5046", - "ab14e395-2bef-42f1-a5ad-9947e56bb3f2", - "cca9281a-d259-4771-9747-ea7af6de8dcf", - "e1e3e229-9806-4d2d-99e7-d25592fe14b6" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "sizesAny": [ - "Medium" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 8, - "name": "Mr. Morland", - "availableHeroes": [ - "Pygmalien" - ], - "description": "Sells Property items", - "portraitTemplateId": "e30d8bef-5bea-4e95-b4c2-e29e17325a82", - "sourceTemplateIds": [ - "e30d8bef-5bea-4e95-b4c2-e29e17325a82" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Property" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 2, - "name": "Nautica", - "availableHeroes": [ - "Vanessa" - ], - "description": "Sells Aquatic items", - "portraitTemplateId": "1a21931f-6183-4251-914b-c8f83dc58a30", - "sourceTemplateIds": [ - "1a21931f-6183-4251-914b-c8f83dc58a30" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Aquatic" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 6, - "name": "Orion", - "availableHeroes": [], - "description": "Sells Tools", - "portraitTemplateId": "d3727a3a-3dd2-4ea7-a396-515e2c41c1b0", - "sourceTemplateIds": [ - "d3727a3a-3dd2-4ea7-a396-515e2c41c1b0", - "d61f942a-6da4-48bd-a4db-1bde45174aba" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Tool" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "all-hero", - "order": 5, - "name": "Pinfeather", - "availableHeroes": [ - "Dooley", - "Karnok", - "Mak", - "Pygmalien", - "Stelle", - "Vanessa" - ], - "description": "Sells Flying items from any Hero", - "portraitTemplateId": "7066e72e-40b7-4104-b521-159de457f2d0", - "sourceTemplateIds": [ - "7066e72e-40b7-4104-b521-159de457f2d0" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "AllHeroes", - "hiddenTagGroupsAny": [ - "Flying" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "size-specialist", - "order": 5, - "name": "Pol", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Pygmalien", - "Stelle", - "Vanessa" - ], - "description": "Sells Large items", - "portraitTemplateId": "065f6793-8607-4f02-abfe-db6afb221ab2", - "sourceTemplateIds": [ - "065f6793-8607-4f02-abfe-db6afb221ab2", - "bdf0a9ab-8bc2-4f1b-8f7d-614293ac2db2" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "sizesAny": [ - "Large" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "all-hero", - "order": 0, - "name": "Prospero", - "availableHeroes": [ - "Pygmalien" - ], - "description": "Sells Economic items from any hero", - "portraitTemplateId": "bcdaa6d4-9057-4ea1-8110-a2dae217c55f", - "sourceTemplateIds": [ - "bcdaa6d4-9057-4ea1-8110-a2dae217c55f" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "AllHeroes", - "hiddenTagsAny": [ - "EconomyReference", - "Gold", - "Income", - "Value", - "BuyPrice", - "SellPrice" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 2, - "name": "Pygmalien", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Sells items from this Hero", - "portraitTemplateId": "f9074804-1812-445a-8688-b8c86f9c7711", - "sourceTemplateIds": [ - "f9074804-1812-445a-8688-b8c86f9c7711" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Pygmalien" - } - } - ] - }, - { - "kind": "Merchant", - "group": "size-specialist", - "order": 2, - "name": "Quixel", - "availableHeroes": [], - "description": "Sells Small and Medium items. Buys your Large items at +3 value", - "portraitTemplateId": "323e2c05-f077-4774-84a5-9e89d8d1c9b9", - "sourceTemplateIds": [ - "323e2c05-f077-4774-84a5-9e89d8d1c9b9", - "e7cac33d-864c-45c9-8a3e-c3218aa0febe" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "sizesAny": [ - "Small", - "Medium" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "generalist", - "order": 2, - "name": "Serafina", - "availableHeroes": [], - "description": "Sells Enchanted items", - "portraitTemplateId": "b690812d-108b-49ce-82f3-e1a41379022c", - "sourceTemplateIds": [ - "b690812d-108b-49ce-82f3-e1a41379022c" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "enchantableOnly": true - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 3, - "name": "Shelter Shelby", - "availableHeroes": [ - "Karnok", - "Vanessa", - "TheDragons" - ], - "description": "Sells Friend items", - "portraitTemplateId": "9459a01b-edf5-432b-81cd-1fd2cacfadad", - "sourceTemplateIds": [ - "9459a01b-edf5-432b-81cd-1fd2cacfadad" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Friend" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tier-specialist", - "order": 2, - "name": "Silvia", - "availableHeroes": [], - "description": "Sells Silver-tier items", - "portraitTemplateId": "5fcd3081-0daa-4e50-b749-c884b405ef9c", - "sourceTemplateIds": [ - "5fcd3081-0daa-4e50-b749-c884b405ef9c", - "ec81a27c-590c-43a1-a353-804a23b5e5d9" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "startingTier": { - "mode": "AtMost", - "tier": "Silver" - } - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 5, - "name": "Stelle", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Pygmalien", - "Vanessa", - "TheDragons" - ], - "description": "Sells items from this Hero", - "portraitTemplateId": "e48b3243-1e7e-4a97-bf4f-0699fd0b4616", - "sourceTemplateIds": [ - "e48b3243-1e7e-4a97-bf4f-0699fd0b4616" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Stelle" - } - } - ] - }, - { - "kind": "Merchant", - "group": "all-hero", - "order": 6, - "name": "Tatiana", - "availableHeroes": [], - "description": "Sells Toys from any Hero", - "portraitTemplateId": "22bb0004-5131-4588-a567-03ee3c96003b", - "sourceTemplateIds": [ - "22bb0004-5131-4588-a567-03ee3c96003b" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "AllHeroes", - "tagsAny": [ - "Toy" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "all-hero", - "order": 3, - "name": "The Antiquarian", - "availableHeroes": [ - "Dooley", - "Karnok", - "Mak", - "Pygmalien", - "Vanessa" - ], - "description": "Sells Relics from any Hero", - "portraitTemplateId": "e840f7a3-0a04-455d-852c-286dc5011efc", - "sourceTemplateIds": [ - "e840f7a3-0a04-455d-852c-286dc5011efc" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "AllHeroes", - "tagsAny": [ - "Relic" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "all-hero", - "order": 1, - "name": "The Tester", - "availableHeroes": [ - "Dooley", - "Stelle", - "TheDragons" - ], - "description": "Sells your Hero's Tech items", - "portraitTemplateId": "41cdf4ee-7790-4da1-96f8-a46d3391a0d9", - "sourceTemplateIds": [ - "41cdf4ee-7790-4da1-96f8-a46d3391a0d9" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Tech" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 4, - "name": "Tinker", - "availableHeroes": [ - "Dooley" - ], - "description": "Sells Friend items", - "portraitTemplateId": "b1b1f445-e625-4397-b4e2-ee4feeb729fa", - "sourceTemplateIds": [ - "b1b1f445-e625-4397-b4e2-ee4feeb729fa" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Friend" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 14, - "name": "Tok's Clocks", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Sells Haste, Slow and Cooldown items", - "portraitTemplateId": "3e871bbb-fb25-417f-8643-cb43456c3fc7", - "sourceTemplateIds": [ - "3e871bbb-fb25-417f-8643-cb43456c3fc7" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagGroupsAny": [ - "Haste", - "Slow", - "Cooldown" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "tag-type-specialist", - "order": 19, - "name": "Uitar Center", - "availableHeroes": [ - "TheDragons" - ], - "description": "Sells Instruments", - "portraitTemplateId": "c5a68a92-9932-40bd-a45f-e1c902807814", - "sourceTemplateIds": [ - "c5a68a92-9932-40bd-a45f-e1c902807814" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Instrument" - ] - } - } - ] - }, - { - "kind": "Merchant", - "group": "generalist", - "order": 1, - "name": "Valpak", - "availableHeroes": [], - "description": "Sells items. Always sells discounted items", - "portraitTemplateId": "e3b894b0-a078-4b1d-8793-ac6459a8361a", - "sourceTemplateIds": [ - "e3b894b0-a078-4b1d-8793-ac6459a8361a" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero" - } - } - ] - }, - { - "kind": "Merchant", - "group": "other-hero", - "order": 0, - "name": "Vanessa", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Pygmalien", - "Stelle", - "TheDragons" - ], - "description": "Sells items from this Hero", - "portraitTemplateId": "580ba494-a852-4d80-a82d-5cd66fcfd2f3", - "sourceTemplateIds": [ - "580ba494-a852-4d80-a82d-5cd66fcfd2f3" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Vanessa" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 11, - "name": "Adira", - "availableHeroes": [], - "description": "Teaches Diamond-tier Skills", - "portraitTemplateId": "a7b60dc3-36a1-46e8-ba7e-c34f255513c8", - "sourceTemplateIds": [ - "a7b60dc3-36a1-46e8-ba7e-c34f255513c8" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "startingTier": { - "mode": "AtMost", - "tier": "Diamond" - } - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 9, - "name": "Argenta", - "availableHeroes": [], - "description": "Teaches Silver-tier Skills", - "portraitTemplateId": "4c3d4b9d-e5b7-469c-be91-67b213c5a975", - "sourceTemplateIds": [ - "4c3d4b9d-e5b7-469c-be91-67b213c5a975", - "8d5c8a08-45cf-43d2-b1ec-a37d3bd5542b" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "startingTier": { - "mode": "AtMost", - "tier": "Silver" - } - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 19, - "name": "Bjorn", - "availableHeroes": [ - "Dooley", - "Jules", - "Mak", - "Vanessa" - ], - "description": "Teaches Freeze skills", - "portraitTemplateId": "0417372b-77dc-4040-9f29-33d709c591a5", - "sourceTemplateIds": [ - "0417372b-77dc-4040-9f29-33d709c591a5" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Freeze", - "FreezeReference" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 20, - "name": "C4", - "availableHeroes": [ - "Vanessa" - ], - "description": "Teaches Ammo skills", - "portraitTemplateId": "54e27892-1eb3-4b1d-9824-51f9fa0bf51a", - "sourceTemplateIds": [ - "54e27892-1eb3-4b1d-9824-51f9fa0bf51a" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Ammo", - "AmmoReference" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 1, - "name": "Cymon", - "availableHeroes": [ - "Dooley" - ], - "description": "Teaches skills unique to Dooley", - "portraitTemplateId": "77cd5ccd-be81-49fb-a697-58da76571c0a", - "sourceTemplateIds": [ - "77cd5ccd-be81-49fb-a697-58da76571c0a" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Dooley" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 13, - "name": "Fortis", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Pygmalien", - "Stelle", - "TheDragons" - ], - "description": "Teaches Shield skills", - "portraitTemplateId": "d3a78867-fd60-4a67-b03a-4200ba58674c", - "sourceTemplateIds": [ - "d3a78867-fd60-4a67-b03a-4200ba58674c" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Shield", - "ShieldReference" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 3, - "name": "Kelsa", - "availableHeroes": [ - "Karnok" - ], - "description": "Teaches skills unique to Karnok", - "portraitTemplateId": "de175e34-df34-4581-a13a-46767e1c7c6b", - "sourceTemplateIds": [ - "de175e34-df34-4581-a13a-46767e1c7c6b" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Karnok" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 7, - "name": "Mama Bear", - "availableHeroes": [ - "TheDragons" - ], - "description": "Teaches skills unique to The Dragons", - "portraitTemplateId": "386dd351-d08e-49a5-9a38-52c4e73d45b2", - "sourceTemplateIds": [ - "386dd351-d08e-49a5-9a38-52c4e73d45b2" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "TheDragons" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 17, - "name": "Malafang", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Pygmalien", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Teaches Burn skills", - "portraitTemplateId": "294f81dd-eb9f-47a9-9b9c-fa9766291485", - "sourceTemplateIds": [ - "294f81dd-eb9f-47a9-9b9c-fa9766291485" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Burn", - "BurnReference" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 2, - "name": "Mr. Tuskari", - "availableHeroes": [ - "Pygmalien" - ], - "description": "Teaches skills unique to Pygmalien", - "portraitTemplateId": "35e74c18-1bd6-4c91-ab21-2fd64adf6cc6", - "sourceTemplateIds": [ - "35e74c18-1bd6-4c91-ab21-2fd64adf6cc6" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Pygmalien" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 6, - "name": "Nonna", - "availableHeroes": [ - "Jules" - ], - "description": "Teaches Jules Skills", - "portraitTemplateId": "c4e01347-bcbc-e164-c848-544774f80599", - "sourceTemplateIds": [ - "c4e01347-bcbc-e164-c848-544774f80599" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Jules" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 7, - "name": "Nufu", - "availableHeroes": [], - "description": "Sells Skills", - "portraitTemplateId": "210003fa-a20d-4ad1-9ada-d5fad5bf9f89", - "sourceTemplateIds": [ - "210003fa-a20d-4ad1-9ada-d5fad5bf9f89" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 0, - "name": "Old Zane", - "availableHeroes": [ - "Vanessa" - ], - "description": "Teaches skills unique to Vanessa", - "portraitTemplateId": "845d2051-cca0-4533-947a-aa290f364e0a", - "sourceTemplateIds": [ - "845d2051-cca0-4533-947a-aa290f364e0a" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Vanessa" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 10, - "name": "Orlin", - "availableHeroes": [], - "description": "Teaches Gold-tier Skills", - "portraitTemplateId": "a07fbe69-c1d0-41a3-af72-d517e7706718", - "sourceTemplateIds": [ - "a07fbe69-c1d0-41a3-af72-d517e7706718" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "startingTier": { - "mode": "AtMost", - "tier": "Gold" - } - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 8, - "name": "Pip", - "availableHeroes": [], - "description": "Gives you 2 Gold and teaches Bronze-tier Skills", - "portraitTemplateId": "61be3473-6546-427f-ac13-9dee4c43d23c", - "sourceTemplateIds": [ - "61be3473-6546-427f-ac13-9dee4c43d23c", - "bc75676c-032f-441a-a6a2-35b1ccc2eb80", - "e2fc8bd4-b97d-485b-8bb6-5c966d336c4a" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "startingTier": { - "mode": "AtMost", - "tier": "Bronze" - } - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 18, - "name": "Professor Riggle", - "availableHeroes": [ - "Dooley", - "Karnok", - "Mak", - "Vanessa" - ], - "description": "Teaches Poison skills", - "portraitTemplateId": "f1892cf4-3dcb-4d41-b137-d670f44a65f8", - "sourceTemplateIds": [ - "f1892cf4-3dcb-4d41-b137-d670f44a65f8" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Poison", - "PoisonReference" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 14, - "name": "Regenald", - "availableHeroes": [ - "Jules", - "Karnok", - "Mak", - "Pygmalien", - "TheDragons" - ], - "description": "Teaches Health, Heal and Regen skills", - "portraitTemplateId": "b46b862e-ba64-4e05-ad5e-b8dbc90517c9", - "sourceTemplateIds": [ - "b46b862e-ba64-4e05-ad5e-b8dbc90517c9" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Health", - "HealthReference", - "Heal", - "HealReference", - "Regen", - "RegenReference", - "HealthRegen" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 12, - "name": "Ryukon", - "availableHeroes": [], - "description": "Teaches Weapon Skills", - "portraitTemplateId": "bfe9db96-a189-4bdf-84e5-fc1743ff8569", - "sourceTemplateIds": [ - "bfe9db96-a189-4bdf-84e5-fc1743ff8569" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "tagsAny": [ - "Weapon" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 16, - "name": "Slohmor Lumbra", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Teaches Slow skills", - "portraitTemplateId": "18f8471a-3914-419a-9296-14e624e86ac6", - "sourceTemplateIds": [ - "18f8471a-3914-419a-9296-14e624e86ac6" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Slow", - "SlowReference" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 5, - "name": "Uncle Odi", - "availableHeroes": [ - "Stelle" - ], - "description": "Teaches skills unique to Stelle", - "portraitTemplateId": "3e0f0266-e92b-4a9a-b0b8-dba816e51647", - "sourceTemplateIds": [ - "3e0f0266-e92b-4a9a-b0b8-dba816e51647" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Stelle" - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 21, - "name": "Vermir", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Vanessa", - "TheDragons" - ], - "description": "Teaches Crit skills", - "portraitTemplateId": "922b9031-c859-479c-95c4-18234a366c63", - "sourceTemplateIds": [ - "922b9031-c859-479c-95c4-18234a366c63" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Crit", - "CritReference" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 15, - "name": "Zara", - "availableHeroes": [ - "Dooley", - "Jules", - "Karnok", - "Mak", - "Stelle", - "Vanessa", - "TheDragons" - ], - "description": "Teaches Haste and Charge skills", - "portraitTemplateId": "86907ad1-f67a-48db-ac30-e5afe2de237a", - "sourceTemplateIds": [ - "86907ad1-f67a-48db-ac30-e5afe2de237a" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "SelectedHero", - "hiddenTagsAny": [ - "Haste", - "HasteReference", - "Charge" - ] - } - } - ] - }, - { - "kind": "Trainer", - "group": "trainer", - "order": 4, - "name": "Zosima", - "availableHeroes": [ - "Mak" - ], - "description": "Teaches skills unique to Mak", - "portraitTemplateId": "054e937d-553e-41a5-951b-62550f870f93", - "sourceTemplateIds": [ - "054e937d-553e-41a5-951b-62550f870f93" - ], - "offerSegments": [ - { - "key": "normal", - "kind": "Normal", - "rule": { - "heroMode": "FixedHero", - "hero": "Mak" - } - } - ] - } - ] -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNamePresentation.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNamePresentation.cs deleted file mode 100644 index 5998b0b..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNamePresentation.cs +++ /dev/null @@ -1,17 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Game.BilingualItemNames; - -internal static class BilingualItemNamePresentation -{ - internal static string? TryBuildSubtitle(string? primaryTitle, string? secondaryTitle) - { - if ( - string.IsNullOrWhiteSpace(primaryTitle) - || string.IsNullOrWhiteSpace(secondaryTitle) - || string.Equals(primaryTitle.Trim(), secondaryTitle.Trim(), StringComparison.Ordinal) - ) - return null; - - return secondaryTitle.Trim(); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNameSubtitle.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNameSubtitle.cs deleted file mode 100644 index 7940658..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNameSubtitle.cs +++ /dev/null @@ -1,152 +0,0 @@ -#nullable enable -using BazaarPlusPlus.GameInterop; -using BazaarPlusPlus.GameInterop.Fonts; -using TheBazaar.UI.Tooltips; -using TMPro; -using UnityEngine; -using UnityEngine.UI; - -namespace BazaarPlusPlus.Game.BilingualItemNames; - -// The native title is a serif TMP label. Keep it intact and add the translated title as a -// separate label: Chinese uses the game's serif face, while English uses its sans face. -// The wrapper owns both rows and has no padding or spacing, avoiding the extra line box that the -// old rich-text newline/voffset markup left between the item name and its translation. -internal static class BilingualItemNameSubtitle -{ - private const string StackName = "BppBilingualItemNameStack"; - private const string LabelName = "BppBilingualItemNameSubtitle"; - private const float SubtitleScale = 0.42f; - private const float SubtitleGapScale = 0.6f; - private const float ChineseLocaleEnglishOffset = 2f; - - internal static bool TryShow( - CardTooltipController controller, - string subtitleText, - bool isEnglishSubtitle - ) - { - var header = controller?.headerText; - if (header == null || string.IsNullOrWhiteSpace(subtitleText)) - return false; - - var stack = EnsureStack(header); - if ( - stack == null - || NativeGameTypography.PrepareOwnedText( - isEnglishSubtitle - ? NativeGameTypography.OwnedTextRole.Body - : NativeGameTypography.OwnedTextRole.Heading, - out var typography - ) != NativeGameTypography.Outcome.Ready - || typography == null - ) - return false; - - var label = EnsureLabel(stack); - if (label == null || typography.Apply(label) != NativeGameTypography.Outcome.Applied) - return false; - - label.enableAutoSizing = false; - label.fontSize = header.fontSize * SubtitleScale; - label.fontStyle = FontStyles.Normal; - label.alignment = header.alignment; - label.color = header.color; - label.margin = new Vector4(isEnglishSubtitle ? ChineseLocaleEnglishOffset : 0f, 0f, 0f, 0f); - label.textWrappingMode = TextWrappingModes.NoWrap; - label.overflowMode = TextOverflowModes.Overflow; - label.richText = false; - label.lineSpacing = 0f; - label.paragraphSpacing = 0f; - label.text = subtitleText; - label.gameObject.SetActive(true); - - if (stack.GetComponent() is { } layout) - layout.spacing = -label.fontSize * (1f - SubtitleGapScale); - LayoutRebuilder.MarkLayoutForRebuild(stack); - return true; - } - - internal static void Hide(CardTooltipController controller) - { - var header = controller?.headerText; - var stack = header?.transform.parent as RectTransform; - var label = stack?.Find(LabelName)?.GetComponent(); - if (label == null) - return; - - label.text = string.Empty; - label.gameObject.SetActive(false); - LayoutRebuilder.MarkLayoutForRebuild(stack!); - } - - private static RectTransform? EnsureStack(TMP_Text header) - { - if (header.transform.parent is not RectTransform parent) - return null; - - if (parent.name == StackName && parent.GetComponent() is not null) - return parent; - - var headerRect = header.rectTransform; - var siblingIndex = header.transform.GetSiblingIndex(); - var stackObject = BppGameObjectFactory.Create(StackName, typeof(RectTransform)); - var stack = stackObject.GetComponent(); - stack.SetParent(parent, worldPositionStays: false); - stack.SetSiblingIndex(siblingIndex); - stack.anchorMin = headerRect.anchorMin; - stack.anchorMax = headerRect.anchorMax; - stack.pivot = headerRect.pivot; - stack.anchoredPosition = headerRect.anchoredPosition; - stack.sizeDelta = headerRect.sizeDelta; - stack.localScale = Vector3.one; - - var sourceLayout = header.GetComponent(); - if (sourceLayout != null) - { - var stackLayout = stackObject.AddComponent(); - stackLayout.ignoreLayout = sourceLayout.ignoreLayout; - stackLayout.minWidth = sourceLayout.minWidth; - stackLayout.preferredWidth = sourceLayout.preferredWidth; - stackLayout.flexibleWidth = sourceLayout.flexibleWidth; - } - - var layout = stackObject.AddComponent(); - layout.padding = new RectOffset(0, 0, 0, 0); - layout.spacing = 0f; - layout.childAlignment = TextAnchor.UpperLeft; - layout.childControlWidth = true; - layout.childControlHeight = true; - layout.childForceExpandWidth = false; - layout.childForceExpandHeight = false; - - if (parent.GetComponent() == null) - { - var fitter = stackObject.AddComponent(); - fitter.horizontalFit = ContentSizeFitter.FitMode.Unconstrained; - fitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize; - } - - header.transform.SetParent(stack, worldPositionStays: false); - return stack; - } - - private static TextMeshProUGUI? EnsureLabel(RectTransform stack) - { - var existing = stack.Find(LabelName)?.GetComponent(); - if (existing != null) - return existing; - - var labelObject = BppGameObjectFactory.Create(LabelName, typeof(RectTransform), typeof(CanvasRenderer)); - labelObject.transform.SetParent(stack, worldPositionStays: false); - var labelRect = labelObject.GetComponent(); - labelRect.anchorMin = new Vector2(0f, 0f); - labelRect.anchorMax = new Vector2(1f, 0f); - labelRect.pivot = new Vector2(0.5f, 1f); - labelRect.localScale = Vector3.one; - - var label = labelObject.AddComponent(); - label.raycastTarget = false; - return label; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNamesSettingsDockEntry.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNamesSettingsDockEntry.cs deleted file mode 100644 index 6377919..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualItemNamesSettingsDockEntry.cs +++ /dev/null @@ -1,30 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Game.Settings; -using BazaarPlusPlus.Localization; - -namespace BazaarPlusPlus.Game.BilingualItemNames; - -internal static class BilingualItemNamesSettingsDockEntry -{ - private static readonly LocalizedTextSet Labels = new( - "Bilingual Names", - "双语名称", - "雙語名稱", - "Zweisprachige Namen", - "Nomes Bilíngues", - "이중 언어 이름", - "Nomi Bilingue" - ); - - internal static CyclingSettingsDockEntry Create() => - CyclingSettingsDockEntry.Toggle( - BppSettingsDockOrder.BilingualItemNames, - "BilingualItemNames", - languageCode => Labels.Resolve(languageCode, L.CurrentMode), - config => config.EnableBilingualItemNamesConfig.Value, - (config, enabled) => - { - config.EnableBilingualItemNamesConfig.Value = enabled; - } - ); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualNameCardEligibility.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualNameCardEligibility.cs deleted file mode 100644 index b2b2980..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BilingualItemNames/BilingualNameCardEligibility.cs +++ /dev/null @@ -1,16 +0,0 @@ -#nullable enable -using BazaarGameShared.Domain.Core.Types; - -namespace BazaarPlusPlus.Game.BilingualItemNames; - -internal static class BilingualNameCardEligibility -{ - internal static bool IsSupported(ECardType cardType) => - cardType - is ECardType.Item - or ECardType.Skill - or ECardType.CombatEncounter - or ECardType.EncounterStep - or ECardType.EventEncounter - or ECardType.PedestalEncounter; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleOutboxFiles.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleOutboxFiles.cs deleted file mode 100644 index cd4ef5e..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleOutboxFiles.cs +++ /dev/null @@ -1,50 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Game.BundlePipeline; - -internal interface IBundleOutboxFiles -{ - Stream OpenRead(string fileName); - - bool Exists(string fileName); - - long GetLength(string fileName); - - void Delete(string fileName); - - IReadOnlyList EnumerateBundleFileNames(); -} - -internal sealed class SystemBundleOutboxFiles : IBundleOutboxFiles -{ - private readonly string _root; - - internal SystemBundleOutboxFiles(string root) - { - _root = Path.GetFullPath(root); - Directory.CreateDirectory(_root); - } - - public Stream OpenRead(string fileName) => - new FileStream(Resolve(fileName), FileMode.Open, FileAccess.Read, FileShare.Read); - - public bool Exists(string fileName) => File.Exists(Resolve(fileName)); - - public long GetLength(string fileName) => new FileInfo(Resolve(fileName)).Length; - - public void Delete(string fileName) => File.Delete(Resolve(fileName)); - - public IReadOnlyList EnumerateBundleFileNames() => - Directory - .EnumerateFiles(_root, "*.bundle") - .Select(Path.GetFileName) - .Where(name => name != null) - .Select(name => name!) - .ToArray(); - - private string Resolve(string fileName) - { - if (string.IsNullOrWhiteSpace(fileName) || Path.GetFileName(fileName) != fileName) - throw new InvalidDataException("bundle_file_name_invalid"); - return Path.Combine(_root, fileName); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundlePipelineLog.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundlePipelineLog.cs deleted file mode 100644 index 338b3e8..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundlePipelineLog.cs +++ /dev/null @@ -1,36 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Infrastructure; -using BazaarPlusPlus.Infrastructure.Logging; - -namespace BazaarPlusPlus.Game.BundlePipeline; - -internal static class BundlePipelineLog -{ - internal static void Info(BppLogEvent logEvent, string runId, string bundleId) => - BppLog.InfoEvent( - logEvent, - ("run_id", runId, BppLogCorrelationPolicy.Short), - ("bundle_id", bundleId, BppLogCorrelationPolicy.Short) - ); - - internal static void Warn( - BppLogEvent logEvent, - string category, - Exception? exception = null, - string? runId = null - ) - { - var values = - runId == null - ? new BppLogField[] { ("category", category) } - : new BppLogField[] - { - ("run_id", runId, BppLogCorrelationPolicy.Short), - ("category", category), - }; - if (exception == null) - BppLog.WarnEvent(logEvent, values); - else - BppLog.WarnEvent(logEvent, exception, values); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleScreenshotEncoder.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleScreenshotEncoder.cs deleted file mode 100644 index da8650b..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleScreenshotEncoder.cs +++ /dev/null @@ -1,105 +0,0 @@ -#nullable enable -using BazaarPlusPlus.ModApi.Bundle; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats.Jpeg; -using SixLabors.ImageSharp.Processing; - -namespace BazaarPlusPlus.Game.BundlePipeline; - -internal sealed class BundleScreenshotEncoder -{ - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); - private static readonly int[] LongestEdges = [1920, 1600, 1280, 1024, 768]; - private static readonly int[] Qualities = [90, 82, 74, 66, 58, 50]; - - internal async Task EncodeAsync( - string absolutePath, - long capturedAtMs, - CancellationToken cancellationToken - ) - { - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeout.CancelAfter(Timeout); - var task = Task.Run(() => Encode(absolutePath, capturedAtMs, timeout.Token), timeout.Token); - try - { - return await task.ConfigureAwait(false); - } - catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) - { - return null; - } - catch (UnknownImageFormatException) - { - return null; - } - catch (InvalidImageContentException) - { - return null; - } - catch (IOException) - { - return null; - } - catch (UnauthorizedAccessException) - { - return null; - } - } - - private static BundleScreenshotBuildInputV6? Encode( - string absolutePath, - long capturedAtMs, - CancellationToken cancellationToken - ) - { - cancellationToken.ThrowIfCancellationRequested(); - using var source = Image.Load(absolutePath); - var sourceEdge = Math.Max(source.Width, source.Height); - foreach (var edge in EnumerateEdges(sourceEdge)) - { - cancellationToken.ThrowIfCancellationRequested(); - using var image = Resize(source, edge); - foreach (var quality in Qualities) - { - cancellationToken.ThrowIfCancellationRequested(); - using var output = new MemoryStream(); - image.SaveAsJpeg(output, new JpegEncoder { Quality = quality }); - if (output.Length is <= 0 or > BundleLimitsV6.MaxScreenshotBytes) - continue; - return new BundleScreenshotBuildInputV6 - { - Bytes = output.ToArray(), - Width = image.Width, - Height = image.Height, - Quality = quality, - CapturedAtMs = capturedAtMs, - }; - } - } - return null; - } - - private static IEnumerable EnumerateEdges(int sourceEdge) - { - if (sourceEdge <= LongestEdges[0]) - yield return sourceEdge; - foreach (var edge in LongestEdges) - { - if (edge < sourceEdge) - yield return edge; - } - } - - private static Image Resize(Image source, int edge) => - source.Clone(context => - context.Resize( - new ResizeOptions - { - Size = new Size(edge, edge), - Mode = ResizeMode.Max, - Sampler = KnownResamplers.Bicubic, - } - ) - ); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleSealConvergence.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleSealConvergence.cs deleted file mode 100644 index 8ec0f79..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleSealConvergence.cs +++ /dev/null @@ -1,534 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Game.BundlePipeline; - -internal enum BundleSealInputGate -{ - ReplayPersistence, - PlayerAccount, - Screenshot, - ReplayPayload, - EncodedPayload, -} - -internal enum BundleSealConvergenceDecision -{ - Continue, - Wait, - MarkScreenshotTimedOutAndContinue, - MarkTerminal, -} - -internal readonly struct BundleSealJobFacts -{ - internal BundleSealJobFacts(bool screenshotRequested, bool screenshotUnavailable) - { - ScreenshotRequested = screenshotRequested; - ScreenshotUnavailable = screenshotUnavailable; - } - - internal bool ScreenshotRequested { get; } - internal bool ScreenshotUnavailable { get; } -} - -internal readonly struct BundleSealInputObservation -{ - private BundleSealInputObservation( - BundleSealInputGate gate, - bool inputAvailable, - int replayOmittedCount, - bool encodedPayloadTooLarge - ) - { - Gate = gate; - InputAvailable = inputAvailable; - ReplayOmittedCount = replayOmittedCount; - EncodedPayloadTooLarge = encodedPayloadTooLarge; - } - - internal BundleSealInputGate Gate { get; } - internal bool InputAvailable { get; } - internal int ReplayOmittedCount { get; } - internal bool EncodedPayloadTooLarge { get; } - - internal static BundleSealInputObservation Availability( - BundleSealInputGate gate, - bool available - ) => new(gate, available, 0, false); - - internal static BundleSealInputObservation ReplayPayload(int omittedCount) => - new(BundleSealInputGate.ReplayPayload, omittedCount == 0, omittedCount, false); - - internal static BundleSealInputObservation EncodedPayload(bool tooLarge) => - new(BundleSealInputGate.EncodedPayload, !tooLarge, 0, tooLarge); -} - -internal static class BundleSealConvergence -{ - internal static BundleSealConvergenceDecision Resolve( - BundleSealJobFacts job, - float secondsUntilInputDeadline, - BundleSealInputObservation observation - ) - { - var deadlineReached = secondsUntilInputDeadline <= 0f; - switch (observation.Gate) - { - case BundleSealInputGate.ReplayPersistence: - return !observation.InputAvailable && !deadlineReached - ? BundleSealConvergenceDecision.Wait - : BundleSealConvergenceDecision.Continue; - case BundleSealInputGate.PlayerAccount: - if (observation.InputAvailable) - return BundleSealConvergenceDecision.Continue; - return deadlineReached - ? BundleSealConvergenceDecision.MarkTerminal - : BundleSealConvergenceDecision.Wait; - case BundleSealInputGate.Screenshot: - if ( - !job.ScreenshotRequested - || job.ScreenshotUnavailable - || observation.InputAvailable - ) - return BundleSealConvergenceDecision.Continue; - return deadlineReached - ? BundleSealConvergenceDecision.MarkScreenshotTimedOutAndContinue - : BundleSealConvergenceDecision.Wait; - case BundleSealInputGate.ReplayPayload: - return observation.ReplayOmittedCount > 0 && !deadlineReached - ? BundleSealConvergenceDecision.Wait - : BundleSealConvergenceDecision.Continue; - case BundleSealInputGate.EncodedPayload: - return observation.EncodedPayloadTooLarge - ? BundleSealConvergenceDecision.MarkTerminal - : BundleSealConvergenceDecision.Continue; - default: - return BundleSealConvergenceDecision.MarkTerminal; - } - } -} - -// Failure half of the seal decision core: what a thrown or observed failure means for durable -// queue state. Input deadlines stay in BundleSealConvergence.Resolve; this type never waits on -// inputs, and Resolve never inspects exceptions. -internal enum BundleSealStage -{ - AccountResolution, - Screenshot, - Composition, - ReplayRead, - ReplayDecode, - PayloadEncode, - Allocation, - Build, - Publish, - Attempt, - PendingValidation, - OrphanAdoption, - FileRecovery, - JobDiscovery, - ScreenshotTerminal, -} - -internal enum BundleSealFailureCause -{ - Environment, - Transient, - Other, -} - -internal enum BundleSealFailureDisposition -{ - RetryLater, - ParkUntilNextLaunch, - Terminal, - Reseal, - Degrade, - Skip, -} - -internal enum BundleSealFailureLog -{ - Deferred, - EnvironmentBlocked, - Degraded, - Terminal, - MaintenanceFailed, -} - -internal readonly struct BundleSealRetryFacts -{ - internal BundleSealRetryFacts( - string? lastErrorCode, - int attempts, - float secondsSinceInputDeadline - ) - { - LastErrorCode = lastErrorCode; - Attempts = attempts; - SecondsSinceInputDeadline = secondsSinceInputDeadline; - } - - internal string? LastErrorCode { get; } - internal int Attempts { get; } - internal float SecondsSinceInputDeadline { get; } -} - -internal readonly struct BundleSealFailureDecision -{ - internal BundleSealFailureDecision( - BundleSealFailureDisposition disposition, - BundleSealFailureCause cause, - BundleSealFailureLog log, - string code, - string? detail, - int attempts - ) - { - Disposition = disposition; - Cause = cause; - Log = log; - Code = code; - Detail = detail; - Attempts = attempts; - } - - internal BundleSealFailureDisposition Disposition { get; } - internal BundleSealFailureCause Cause { get; } - internal BundleSealFailureLog Log { get; } - - // Bounded, stable: persisted as last_error_code and logged as the public category. - internal string Code { get; } - - // Bounded diagnostic persisted as last_error_detail; the full exception goes to the log. - internal string? Detail { get; } - - // Consecutive failures with this Code, including this one. - internal int Attempts { get; } -} - -internal static class BundleSealFailurePolicy -{ - internal const string EnvironmentBlockedCode = "seal_environment_blocked"; - internal const string EnvironmentBlockedExpiredCode = "seal_environment_blocked_expired"; - internal const string RetryExhaustedCode = "seal_retry_exhausted"; - internal const int RetryAttemptsBeforeExhaustion = 8; - internal const float RetryExhaustionSeconds = 14f * 24f * 3600f; - internal const int ParkedLaunchesBeforeExpiry = 5; - internal const float ParkedExpirySeconds = 60f * 24f * 3600f; - - // Any job that keeps failing ends here, whatever its code, so its sources are not held forever. - internal const float FailureAgeCeilingSeconds = 90f * 24f * 3600f; - internal const float InitialBackoffSeconds = 5f; - internal const float MaximumBackoffSeconds = 3600f; - private const int MaximumDetailLength = 512; - private const int MaximumVisitedExceptions = 64; - - // The runtime could not bind or initialize code: the same process cannot succeed by retrying. - internal static BundleSealFailureCause Classify(Exception? exception) => - Classify(exception, out _); - - internal static BundleSealFailureCause Classify(Exception? exception, out Exception? cause) - { - cause = exception; - if (exception == null) - return BundleSealFailureCause.Other; - Exception? transient = null; - var pending = new Stack(); - pending.Push(exception); - // Exception graphs are trees in practice; the visit budget only guards a malformed cycle. - for (var visits = 0; pending.Count > 0 && visits < MaximumVisitedExceptions; visits++) - { - var link = pending.Pop(); - if (IsEnvironment(link)) - { - cause = link; - return BundleSealFailureCause.Environment; - } - if (transient == null && IsTransient(link)) - transient = link; - if (link is AggregateException aggregate) - { - for (var index = aggregate.InnerExceptions.Count - 1; index >= 0; index--) - pending.Push(aggregate.InnerExceptions[index]); - } - else if (link.InnerException != null) - pending.Push(link.InnerException); - } - if (transient == null) - return BundleSealFailureCause.Other; - cause = transient; - return BundleSealFailureCause.Transient; - } - - internal static BundleSealFailureDecision Decide( - BundleSealStage stage, - Exception? exception, - BundleSealRetryFacts retry - ) - { - var cause = Classify(exception, out var link); - var detail = Describe(link); - switch (stage) - { - case BundleSealStage.PendingValidation: - return cause switch - { - BundleSealFailureCause.Environment => Maintenance( - BundleSealFailureDisposition.Skip, - cause, - BundleSealFailureLog.EnvironmentBlocked, - EnvironmentBlockedCode, - detail - ), - BundleSealFailureCause.Transient => Maintenance( - BundleSealFailureDisposition.Skip, - cause, - BundleSealFailureLog.Deferred, - "pending_file_unreadable", - detail - ), - _ => Maintenance( - BundleSealFailureDisposition.Reseal, - cause, - BundleSealFailureLog.Degraded, - "pending_file_invalid", - detail - ), - }; - case BundleSealStage.OrphanAdoption: - return cause switch - { - BundleSealFailureCause.Environment => Maintenance( - BundleSealFailureDisposition.Skip, - cause, - BundleSealFailureLog.EnvironmentBlocked, - EnvironmentBlockedCode, - detail - ), - BundleSealFailureCause.Transient => Maintenance( - BundleSealFailureDisposition.Skip, - cause, - BundleSealFailureLog.Deferred, - "orphan_file_unreadable", - detail - ), - _ => Maintenance( - BundleSealFailureDisposition.Degrade, - cause, - BundleSealFailureLog.Degraded, - "orphan_file_invalid", - detail - ), - }; - case BundleSealStage.FileRecovery: - case BundleSealStage.JobDiscovery: - case BundleSealStage.ScreenshotTerminal: - return Maintenance( - BundleSealFailureDisposition.Skip, - cause, - cause == BundleSealFailureCause.Environment - ? BundleSealFailureLog.EnvironmentBlocked - : BundleSealFailureLog.MaintenanceFailed, - stage switch - { - BundleSealStage.FileRecovery => "file_recovery_failed", - BundleSealStage.JobDiscovery => "job_discovery_failed", - _ => "screenshot_terminal_failed", - }, - detail - ); - } - - // A job that has already failed before cannot outlive the age ceiling; a first failure - // (including a revived legacy job's) always gets its normal retry or park. - var pastAgeCeiling = - retry.LastErrorCode != null - && retry.SecondsSinceInputDeadline >= FailureAgeCeilingSeconds; - if (cause == BundleSealFailureCause.Environment) - { - var parked = NextAttempts(retry, EnvironmentBlockedCode); - return ( - parked >= ParkedLaunchesBeforeExpiry - && retry.SecondsSinceInputDeadline >= ParkedExpirySeconds - || pastAgeCeiling - ) - ? new BundleSealFailureDecision( - BundleSealFailureDisposition.Terminal, - cause, - BundleSealFailureLog.Terminal, - EnvironmentBlockedExpiredCode, - detail, - parked - ) - : new BundleSealFailureDecision( - BundleSealFailureDisposition.ParkUntilNextLaunch, - cause, - BundleSealFailureLog.EnvironmentBlocked, - EnvironmentBlockedCode, - detail, - parked - ); - } - - var code = StageCode(stage); - // Bytes that exist but do not decode stay bad: omit that replay, whatever the inner cause - // (truncated MessagePack reports EndOfStreamException, corrupt gzip reports IOException). - if (stage == BundleSealStage.ReplayDecode) - return Job( - BundleSealFailureDisposition.Degrade, - cause, - BundleSealFailureLog.Degraded, - code, - detail, - retry - ); - if (cause == BundleSealFailureCause.Other) - { - // Codecs are deterministic over the same local inputs; retrying cannot change them. - if (stage is BundleSealStage.Build or BundleSealStage.PayloadEncode) - return Job( - BundleSealFailureDisposition.Terminal, - cause, - BundleSealFailureLog.Terminal, - code, - detail, - retry - ); - } - - var attempts = NextAttempts(retry, code); - var exhausted = - attempts >= RetryAttemptsBeforeExhaustion - && retry.SecondsSinceInputDeadline >= RetryExhaustionSeconds - || pastAgeCeiling; - if (!exhausted) - return new BundleSealFailureDecision( - BundleSealFailureDisposition.RetryLater, - cause, - BundleSealFailureLog.Deferred, - code, - detail, - attempts - ); - // An exhausted replay read degrades that one battle instead of losing the whole Run. - return stage == BundleSealStage.ReplayRead - ? Job( - BundleSealFailureDisposition.Degrade, - cause, - BundleSealFailureLog.Degraded, - code, - detail, - retry - ) - : new BundleSealFailureDecision( - BundleSealFailureDisposition.Terminal, - cause, - BundleSealFailureLog.Terminal, - RetryExhaustedCode, - detail, - attempts - ); - } - - // Whether a waiting job may run now. Parked jobs run once per launch; retrying jobs back off - // exponentially from their last recorded failure. - internal static bool IsDue( - string? lastErrorCode, - int attempts, - float? secondsSinceLastAttempt, - float secondsSinceLaunch - ) - { - if (lastErrorCode == null || attempts <= 0 || secondsSinceLastAttempt is not { } elapsed) - return true; - if (elapsed < 0f) - return true; - if (lastErrorCode == EnvironmentBlockedCode) - return elapsed > secondsSinceLaunch; - return elapsed >= BackoffSeconds(attempts); - } - - internal static float BackoffSeconds(int attempts) - { - if (attempts <= 0) - return 0f; - var exponent = Math.Min(attempts - 1, 30); - return Math.Min( - InitialBackoffSeconds * (float)Math.Pow(2, exponent), - MaximumBackoffSeconds - ); - } - - private static bool IsEnvironment(Exception exception) => - exception - is MissingMemberException - or TypeLoadException - or BadImageFormatException - or TypeInitializationException - or EntryPointNotFoundException - or InvalidProgramException - or System.Security.VerificationException - || exception is FileLoadException load && IsAssemblyIdentity(load.FileName) - || exception is FileNotFoundException missing && IsAssemblyIdentity(missing.FileName); - - private static bool IsTransient(Exception exception) => - exception - is IOException - or UnauthorizedAccessException - or TimeoutException - or OperationCanceledException - or System.Data.Common.DbException; - - // Assembly binding reports a display name ("Name, Version=..., PublicKeyToken=..."); file IO - // reports a path. Only the former is an environment failure. - private static bool IsAssemblyIdentity(string? fileName) => - fileName != null - && ( - fileName.Contains("Version=", StringComparison.Ordinal) - || fileName.Contains("PublicKeyToken=", StringComparison.Ordinal) - ); - - private static string StageCode(BundleSealStage stage) => - stage switch - { - BundleSealStage.AccountResolution => "account_resolve_failed", - BundleSealStage.Screenshot => "screenshot_encode_failed", - BundleSealStage.Composition => "payload_compose_failed", - BundleSealStage.ReplayRead => "replay_unreadable", - BundleSealStage.ReplayDecode => "replay_invalid", - BundleSealStage.PayloadEncode => "payload_encode_failed", - BundleSealStage.Allocation => "seal_allocation_failed", - BundleSealStage.Build => "bundle_build_failed", - BundleSealStage.Publish => "seal_publish_failed", - _ => "seal_attempt_failed", - }; - - private static int NextAttempts(BundleSealRetryFacts retry, string code) => - (string.Equals(retry.LastErrorCode, code, StringComparison.Ordinal) ? retry.Attempts : 0) - + 1; - - private static BundleSealFailureDecision Job( - BundleSealFailureDisposition disposition, - BundleSealFailureCause cause, - BundleSealFailureLog log, - string code, - string? detail, - BundleSealRetryFacts retry - ) => new(disposition, cause, log, code, detail, NextAttempts(retry, code)); - - private static BundleSealFailureDecision Maintenance( - BundleSealFailureDisposition disposition, - BundleSealFailureCause cause, - BundleSealFailureLog log, - string code, - string? detail - ) => new(disposition, cause, log, code, detail, 0); - - private static string? Describe(Exception? exception) - { - if (exception == null) - return null; - var text = exception.GetType().FullName + ": " + exception.Message; - return text.Length <= MaximumDetailLength ? text : text.Substring(0, MaximumDetailLength); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleSealCoordinator.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleSealCoordinator.cs deleted file mode 100644 index 5267825..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleSealCoordinator.cs +++ /dev/null @@ -1,761 +0,0 @@ -#nullable enable -using System.Collections.Concurrent; -using BazaarPlusPlus.Core.Events; -using BazaarPlusPlus.Core.Runtime; -using BazaarPlusPlus.Game.CombatReplay; -using BazaarPlusPlus.Game.Screenshots; -using BazaarPlusPlus.Game.Upload; -using BazaarPlusPlus.Infrastructure.Logging; -using BazaarPlusPlus.ModApi.Bundle; -using BazaarPlusPlus.Storage.BundleQueue; -using BazaarPlusPlus.Storage.Paths; -using BazaarPlusPlus.Storage.RunScreenshot; - -namespace BazaarPlusPlus.Game.BundlePipeline; - -internal sealed class BundleSealCoordinator : IBppFeature, IDisposable -{ - private static readonly TimeSpan InputConvergenceWindow = TimeSpan.FromMinutes(2); - private static readonly TimeSpan FallbackScanInterval = TimeSpan.FromSeconds(5); - private static readonly TimeSpan OrphanFileRetention = TimeSpan.FromHours(24); - private readonly IBppServices _services; - private readonly string _databasePath; - private readonly string _replayRoot; - private readonly string _screenshotRoot; - private readonly string _outboxRoot; - private readonly BundleQueueStore _queueStore; - private readonly RunScreenshotSqliteStore _screenshotStore; - private readonly RunPayloadComposer _composer; - private readonly BundleScreenshotEncoder _screenshotEncoder = new(); - private readonly UlidV6Generator _ulid = new(); - private readonly SemaphoreSlim _wake = new(0); - private readonly ConcurrentQueue _screenshotTerminals = new(); - private readonly CancellationTokenSource _shutdown = new(); - private readonly Action? _faultProbe; - - // Environment-blocked jobs become due once per launch (BundleSealFailurePolicy.IsDue). - private readonly DateTimeOffset _launchedAtUtc; - private IDisposable? _runInitialized; - private IDisposable? _runLifecycle; - private IDisposable? _replayDrained; - private IDisposable? _screenshotTerminal; - private Task? _worker; - private int _wakePending; - private bool _started; - - internal BundleSealCoordinator(IBppServices services) - : this(services, faultProbe: null) { } - - // Tests inject failures at named seal stages; production passes null. - internal BundleSealCoordinator( - IBppServices services, - Action? faultProbe - ) - { - _services = services ?? throw new ArgumentNullException(nameof(services)); - _faultProbe = faultProbe; - _launchedAtUtc = DateTimeOffset.UtcNow; - var dataRoot = services.Paths.RequireDataRoot(); - _databasePath = PathConstants.RunLogDatabase(dataRoot); - _replayRoot = PathConstants.CombatReplays(dataRoot); - _screenshotRoot = PathConstants.Screenshots(dataRoot); - _outboxRoot = PathConstants.BundleOutbox(dataRoot); - _queueStore = new BundleQueueStore(_databasePath); - _screenshotStore = new RunScreenshotSqliteStore(_databasePath); - _composer = new RunPayloadComposer(_databasePath, _replayRoot); - } - - public void Start() - { - if (_started) - return; - _started = true; - Directory.CreateDirectory(_outboxRoot); - _queueStore.ResetInterruptedSeals(); - _runInitialized = _services.EventBus.Subscribe(_ => Signal()); - _runLifecycle = _services.EventBus.Subscribe(_ => Signal()); - _replayDrained = _services.EventBus.Subscribe(_ => - Signal() - ); - _screenshotTerminal = _services.EventBus.Subscribe(terminal => - { - _screenshotTerminals.Enqueue(terminal); - Signal(); - }); -#if BPP_ANDROID - // The IL2CPP interop layer aborts the process when a worker thread resolves a projected - // type for the first time, so background workers stay off on the Android port. - _worker = null; -#else - _worker = Task.Run(() => WorkerAsync(_shutdown.Token)); -#endif - Signal(); - } - - public void Stop() => Dispose(); - - public void Dispose() - { - if (!_started) - return; - _started = false; - _runInitialized?.Dispose(); - _runLifecycle?.Dispose(); - _replayDrained?.Dispose(); - _screenshotTerminal?.Dispose(); - _shutdown.Cancel(); - _wake.Release(); - try - { - _worker?.Wait(TimeSpan.FromSeconds(3)); - } - catch - { - // Shutdown is best effort; jobs are durable and reconcile at next startup. - } - _shutdown.Dispose(); - _wake.Dispose(); - } - - internal void Signal() - { - if (Interlocked.Exchange(ref _wakePending, 1) == 0) - _wake.Release(); - } - - internal async Task ReconcileAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - // Maintenance failures are logged per step; they never keep waiting jobs from sealing. - Maintain(BundleSealStage.ScreenshotTerminal, ApplyScreenshotTerminals); - Maintain(BundleSealStage.FileRecovery, RecoverFiles); - Maintain(BundleSealStage.JobDiscovery, EnsureSealJobs); - var published = false; - try - { - foreach (var runId in _queueStore.ListWaitingRunIds()) - { - cancellationToken.ThrowIfCancellationRequested(); - // One Run's failure is recorded against that Run; it cannot abort the pass. - try - { - published |= await TrySealAsync(runId, cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) - { - RecordJobFailure(runId, null, BundleSealStage.Attempt, ex); - } - } - } - finally - { - // A recovered backlog arms one upload batch, not one immediate batch per run. - if (published) - _services.EventBus.Publish(new UploadArmRequested()); - } - } - - private async Task WorkerAsync(CancellationToken cancellationToken) - { - while (!cancellationToken.IsCancellationRequested) - { - try - { - await _wake - .WaitAsync(FallbackScanInterval, cancellationToken) - .ConfigureAwait(false); - Interlocked.Exchange(ref _wakePending, 0); - await ReconcileAsync(cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - return; - } - catch (Exception ex) - { - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.reconcile.failed", - storm: ["category"] - ), - "reconcile_exception", - ex - ); - } - } - } - - private async Task TrySealAsync(string runId, CancellationToken cancellationToken) - { - var job = _queueStore.ReadJob(runId); - if (job == null || job.State == BundleSealJobState.TerminalFailure) - return false; - var now = DateTimeOffset.UtcNow; - if ( - !BundleSealFailurePolicy.IsDue( - job.LastErrorCode, - job.Attempts, - job.LastAttemptAtUtc is { } lastAttempt - ? (float)(now - lastAttempt).TotalSeconds - : null, - (float)(now - _launchedAtUtc).TotalSeconds - ) - ) - return false; - var secondsUntilInputDeadline = (float)(job.InputDeadlineAtUtc - now).TotalSeconds; - var jobFacts = new BundleSealJobFacts( - job.ScreenshotRequested, - job.ScreenshotState == BundleScreenshotState.Unavailable - ); - if ( - BundleSealConvergence.Resolve( - jobFacts, - secondsUntilInputDeadline, - BundleSealInputObservation.Availability( - BundleSealInputGate.ReplayPersistence, - !ReplayPersistenceStateTracker.HasPending(runId) - ) - ) == BundleSealConvergenceDecision.Wait - ) - return false; - - var stage = BundleSealStage.AccountResolution; - try - { - Probe(stage, runId); - string playerAccountId; - try - { - playerAccountId = _composer.ResolvePlayerAccountId(runId, job.PlayerAccountId); - _queueStore.FreezePlayerAccountId(runId, playerAccountId); - } - catch (BundleCompositionException ex) - { - if (ex.Code == "player_account_id_missing") - { - var decision = BundleSealConvergence.Resolve( - jobFacts, - secondsUntilInputDeadline, - BundleSealInputObservation.Availability( - BundleSealInputGate.PlayerAccount, - false - ) - ); - if (decision == BundleSealConvergenceDecision.Wait) - return false; - } - MarkJobTerminal(runId, ex.Code, ex); - return false; - } - - stage = BundleSealStage.Screenshot; - Probe(stage, runId); - BundleScreenshotBuildInputV6? screenshot = null; - if (job.ScreenshotRequested && job.ScreenshotState != BundleScreenshotState.Unavailable) - { - var source = TryReadScreenshot(runId); - if (source == null) - { - var screenshotDecision = BundleSealConvergence.Resolve( - jobFacts, - secondsUntilInputDeadline, - BundleSealInputObservation.Availability( - BundleSealInputGate.Screenshot, - false - ) - ); - if (screenshotDecision == BundleSealConvergenceDecision.Wait) - return false; - if ( - screenshotDecision - == BundleSealConvergenceDecision.MarkScreenshotTimedOutAndContinue - ) - _queueStore.UpdateScreenshotState(runId, BundleScreenshotState.TimedOut); - } - else - { - screenshot = await _screenshotEncoder - .EncodeAsync(source.AbsolutePath, source.CapturedAtMs, cancellationToken) - .ConfigureAwait(false); - if (screenshot == null) - _queueStore.UpdateScreenshotState(runId, BundleScreenshotState.Unavailable); - else - _queueStore.UpdateScreenshotState(runId, BundleScreenshotState.Available); - } - } - - stage = BundleSealStage.Composition; - Probe(stage, runId); - RunPayloadComposition composition; - try - { - composition = _composer.Compose(runId, playerAccountId); - } - catch (BundleCompositionException ex) - { - MarkJobTerminal(runId, ex.Code, ex); - return false; - } - - stage = BundleSealStage.ReplayDecode; - Probe(stage, runId); - var retry = RetryFacts(job, now); - var replayDecisions = composition - .ReplayFailures.Select(failure => - ( - Decision: BundleSealFailurePolicy.Decide( - failure.Unreadable - ? BundleSealStage.ReplayRead - : BundleSealStage.ReplayDecode, - failure.Exception, - retry - ), - failure.Exception - ) - ) - .ToList(); - // A runtime failure on any replay decides the Run; an earlier transient must not mask it. - var holding = replayDecisions - .Where(item => item.Decision.Disposition != BundleSealFailureDisposition.Degrade) - .OrderBy(item => item.Decision.Cause == BundleSealFailureCause.Environment ? 0 : 1) - .ToList(); - if (holding.Count > 0) - { - ApplyJobFailure(runId, holding[0].Decision, holding[0].Exception); - return false; - } - - stage = BundleSealStage.PayloadEncode; - Probe(stage, runId); - _composer.FitToBudget(composition); - if ( - BundleSealConvergence.Resolve( - jobFacts, - secondsUntilInputDeadline, - BundleSealInputObservation.ReplayPayload( - composition.Payload.Degradation.ReplayOmittedBattleIds.Count - ) - ) == BundleSealConvergenceDecision.Wait - ) - return false; - foreach (var (decision, exception) in replayDecisions) - LogFailure(decision, exception, runId); - - composition.Payload.Degradation.ScreenshotOmitted = - job.ScreenshotRequested && screenshot == null; - var encodedPayload = RunPayloadV6Codec.Encode(composition.Payload); - if ( - BundleSealConvergence.Resolve( - jobFacts, - secondsUntilInputDeadline, - BundleSealInputObservation.EncodedPayload( - encodedPayload.Length > BundleLimitsV6.MaxRunBytes - ) - ) == BundleSealConvergenceDecision.MarkTerminal - ) - { - MarkJobTerminal(runId, "minimal_run_payload_too_large", null); - return false; - } - - stage = BundleSealStage.Allocation; - Probe(stage, runId); - var allocation = - job.BundleId != null && job.CreatedAtMs.HasValue - ? new BundleAllocationRecord(job.BundleId, job.CreatedAtMs.Value) - : _queueStore.EnsureAllocation( - job.RunId, - _ulid.Next(), - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - ); - - stage = BundleSealStage.Build; - Probe(stage, runId); - var built = BundleV6Codec.Build( - new BundleBuildInputV6 - { - BundleId = allocation.BundleId, - CreatedAtMs = allocation.CreatedAtMs, - RunId = runId, - PlayerAccountId = playerAccountId, - Battles = composition.Projections, - RunPayload = encodedPayload, - Screenshot = screenshot, - } - ); - _ = BundleV6Codec.Open(built.Bytes); - - stage = BundleSealStage.Publish; - Probe(stage, runId); - // Publication cannot depend on file recovery having run earlier in the pass. - Directory.CreateDirectory(_outboxRoot); - var fileName = allocation.BundleId + ".bundle"; - var finalPath = Path.Combine(_outboxRoot, fileName); - WriteAtomically(finalPath + ".tmp", finalPath, built.Bytes); - if ( - !_queueStore.PublishOutbox( - allocation, - new BundleOutboxPublishRecord( - allocation.BundleId, - job.RunId, - fileName, - built.Sha256Hex, - built.ContentDigest, - built.Bytes.Length, - screenshot != null - ), - DateTimeOffset.UtcNow - ) - ) - { - if (!_queueStore.ContainsOutbox(allocation.BundleId)) - File.Delete(finalPath); - return false; - } - BundlePipelineLog.Info( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.seal.succeeded" - ), - runId, - allocation.BundleId - ); - return true; - } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) - { - RecordJobFailure(runId, job, stage, ex); - return false; - } - } - - private void EnsureSealJobs() => _queueStore.EnsureEligibleJobs(InputConvergenceWindow); - - private void ApplyScreenshotTerminals() - { - while (_screenshotTerminals.TryDequeue(out var terminal)) - { - if (string.IsNullOrWhiteSpace(terminal.RunId)) - continue; - if (terminal.MetadataPersisted) - _queueStore.UpdateScreenshotState(terminal.RunId!, BundleScreenshotState.Available); - else if (terminal.ArtifactStatus == ScreenshotArtifactStatus.Unavailable) - _queueStore.UpdateScreenshotState( - terminal.RunId!, - BundleScreenshotState.Unavailable - ); - } - } - - private void RecoverFiles() - { - Directory.CreateDirectory(_outboxRoot); - foreach (var temp in Directory.EnumerateFiles(_outboxRoot, "*.bundle.tmp")) - { - Maintain( - BundleSealStage.FileRecovery, - () => - { - if (DateTime.UtcNow - File.GetLastWriteTimeUtc(temp) >= OrphanFileRetention) - File.Delete(temp); - } - ); - } - - foreach (var file in Directory.EnumerateFiles(_outboxRoot, "*.bundle")) - RecoverOrphan(file); - - foreach (var row in _queueStore.ListPendingForValidation()) - ValidatePending(row); - } - - private void RecoverOrphan(string file) - { - try - { - var bundleId = Path.GetFileNameWithoutExtension(file); - if (_queueStore.ContainsOutbox(bundleId)) - return; - Probe(BundleSealStage.OrphanAdoption, bundleId); - var bytes = File.ReadAllBytes(file); - var opened = BundleV6Codec.Open(bytes); - var job = _queueStore.ReadJob(opened.Manifest.Run.RunId); - if ( - job?.BundleId != opened.Manifest.BundleId - || job.CreatedAtMs != opened.Manifest.CreatedAtMs - || !string.Equals( - job.PlayerAccountId, - opened.Manifest.Run.PlayerAccountId, - StringComparison.Ordinal - ) - ) - { - DeleteExpiredOrphan(file); - return; - } - _queueStore.PublishOutbox( - new BundleAllocationRecord(job.BundleId!, job.CreatedAtMs!.Value), - new BundleOutboxPublishRecord( - opened.Manifest.BundleId, - opened.Manifest.Run.RunId, - Path.GetFileName(file), - opened.Sha256Hex, - opened.ContentDigest, - bytes.Length, - opened.Screenshot != null - ), - DateTimeOffset.UtcNow - ); - } - catch (Exception ex) - { - var decision = BundleSealFailurePolicy.Decide( - BundleSealStage.OrphanAdoption, - ex, - default - ); - LogFailure(decision, ex, null); - // Only an unreadable Bundle is an orphan; a runtime that cannot open it keeps it. - if (decision.Disposition == BundleSealFailureDisposition.Degrade) - Maintain(BundleSealStage.FileRecovery, () => DeleteExpiredOrphan(file)); - } - } - - private void ValidatePending(BundleOutboxStateRecord row) - { - Exception? failure = null; - try - { - Probe(BundleSealStage.PendingValidation, row.RunId); - var path = Path.Combine(_outboxRoot, row.FileName); - if ( - File.Exists(path) - && BundleV6Codec.Open(File.ReadAllBytes(path)).Manifest.BundleId == row.BundleId - ) - return; - } - catch (Exception ex) - { - failure = ex; - } - // A missing or mismatched file is an observed invalid artifact (no exception). - var decision = BundleSealFailurePolicy.Decide( - BundleSealStage.PendingValidation, - failure, - default - ); - LogFailure(decision, failure, row.RunId); - if (decision.Disposition != BundleSealFailureDisposition.Reseal) - return; - Maintain( - BundleSealStage.FileRecovery, - () => - _queueStore.FailOutboxAndScheduleReseal( - row.BundleId, - row.RunId, - decision.Code, - DateTimeOffset.UtcNow - ) - ); - } - - private static void DeleteExpiredOrphan(string path) - { - if (DateTime.UtcNow - File.GetLastWriteTimeUtc(path) >= OrphanFileRetention) - File.Delete(path); - } - - private ScreenshotSource? TryReadScreenshot(string runId) - { - var artifact = _screenshotStore.TryGetLatestPrimaryForRun(runId); - if (artifact == null) - return null; - var absolute = Path.GetFullPath(Path.Combine(_screenshotRoot, artifact.ImageRelativePath)); - var root = Path.GetFullPath(_screenshotRoot) + Path.DirectorySeparatorChar; - if (!absolute.StartsWith(root, StringComparison.Ordinal) || !File.Exists(absolute)) - return null; - return new ScreenshotSource(absolute, artifact.CapturedAtUtc.ToUnixTimeMilliseconds()); - } - - private void MarkJobTerminal(string runId, string code, Exception? exception) - { - try - { - _queueStore.RecordSealFailure( - runId, - BundleSealJobState.TerminalFailure, - code, - exception?.Message, - 1, - DateTimeOffset.UtcNow - ); - } - catch (Exception ex) - { - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.reconcile.failed", - storm: ["category"] - ), - "seal_failure_record_failed", - ex, - runId - ); - } - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.seal.terminal", - storm: ["category"] - ), - code, - exception, - runId - ); - } - - private void RecordJobFailure( - string runId, - BundleSealJobRecord? job, - BundleSealStage stage, - Exception exception - ) - { - try - { - job ??= _queueStore.ReadJob(runId); - } - catch (Exception readFailure) - { - // Without retry facts the original failure is still classified and recorded below. - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.reconcile.failed", - storm: ["category"] - ), - "seal_job_read_failed", - readFailure, - runId - ); - } - var decision = BundleSealFailurePolicy.Decide( - stage, - exception, - job == null ? default : RetryFacts(job, DateTimeOffset.UtcNow) - ); - ApplyJobFailure(runId, decision, exception); - } - - private void ApplyJobFailure( - string runId, - BundleSealFailureDecision decision, - Exception? exception - ) - { - var state = decision.Disposition switch - { - BundleSealFailureDisposition.Terminal => BundleSealJobState.TerminalFailure, - _ => BundleSealJobState.Waiting, - }; - try - { - _queueStore.RecordSealFailure( - runId, - state, - decision.Code, - decision.Detail, - decision.Attempts, - DateTimeOffset.UtcNow - ); - } - catch (Exception ex) - { - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.reconcile.failed", - storm: ["category"] - ), - "seal_failure_record_failed", - ex, - runId - ); - } - LogFailure(decision, exception, runId); - } - - private void Maintain(BundleSealStage stage, Action action) - { - try - { - Probe(stage, string.Empty); - action(); - } - catch (Exception ex) - { - LogFailure(BundleSealFailurePolicy.Decide(stage, ex, default), ex, null); - } - } - - private void Probe(BundleSealStage stage, string subject) => - _faultProbe?.Invoke(stage, subject); - - private static BundleSealRetryFacts RetryFacts(BundleSealJobRecord job, DateTimeOffset now) => - new(job.LastErrorCode, job.Attempts, (float)(now - job.InputDeadlineAtUtc).TotalSeconds); - - private static void LogFailure( - BundleSealFailureDecision decision, - Exception? exception, - string? runId - ) => - BundlePipelineLog.Warn( - decision.Log switch - { - BundleSealFailureLog.Deferred => new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.seal.deferred", - storm: ["category"] - ), - BundleSealFailureLog.EnvironmentBlocked => new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.seal.environment_blocked", - storm: ["category"] - ), - BundleSealFailureLog.Degraded => new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.seal.degraded", - storm: ["category"] - ), - BundleSealFailureLog.Terminal => new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.seal.terminal", - storm: ["category"] - ), - _ => new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.reconcile.failed", - storm: ["category"] - ), - }, - decision.Code, - exception, - runId - ); - - private static void WriteAtomically(string tempPath, string finalPath, byte[] bytes) - { - using ( - var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None) - ) - { - stream.Write(bytes, 0, bytes.Length); - stream.Flush(flushToDisk: true); - } - File.Move(tempPath, finalPath); - } - - private sealed record ScreenshotSource(string AbsolutePath, long CapturedAtMs); -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleUploadFeed.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleUploadFeed.cs deleted file mode 100644 index 99da8f0..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/BundleUploadFeed.cs +++ /dev/null @@ -1,339 +0,0 @@ -#nullable enable -using System.Security.Cryptography; -using BazaarPlusPlus.Core.Runtime; -using BazaarPlusPlus.Game.Upload; -using BazaarPlusPlus.Infrastructure; -using BazaarPlusPlus.Infrastructure.Logging; -using BazaarPlusPlus.ModApi; -using BazaarPlusPlus.ModApi.Clients; -using BazaarPlusPlus.Storage.BundleQueue; -using BazaarPlusPlus.Storage.Paths; - -namespace BazaarPlusPlus.Game.BundlePipeline; - -internal static class BundleUploadFeed -{ - internal const int MaximumAttemptBatch = 3; - - internal static Session Activate(IBppServices services, UploadPumpCadence cadence) => - new(services, cadence); - - /// - /// Feed-owned behavior for one pump lifetime: enablement, one attempt, feed-private arm - /// signals, and attempt-resource disposal. The pump owns Unity cadence, shared arms, and - /// shutdown drain. - /// - internal sealed class Session : IDisposable - { - private static readonly TimeSpan PendingRetention = TimeSpan.FromDays(14); - private static readonly TimeSpan PermanentFileRetention = TimeSpan.FromDays(7); - private const long SoftLimitBytes = 512L * 1024 * 1024; - private readonly IBppServices _services; - private readonly ModApiSession _modApiSession; - private readonly BundleQueueStore _queueStore; - private readonly IBundleOutboxFiles _files; - private readonly int _retryIntervalSeconds; - - internal Session(IBppServices services, UploadPumpCadence cadence) - { - _services = services; - var root = services.Paths.RequireDataRoot(); - _queueStore = new BundleQueueStore(PathConstants.RunLogDatabase(root)); - _files = new SystemBundleOutboxFiles(PathConstants.BundleOutbox(root)); - _modApiSession = - ModApiSession.TryCreate( - ModApiUploadDefaults.ApiBaseUrl, - BppPluginVersion.Current, - "BundleUpload", - TimeSpan.FromSeconds(ModApiUploadDefaults.RequestTimeoutSeconds) - ) ?? throw new InvalidOperationException("Mod API route is invalid."); - _retryIntervalSeconds = cadence.RetryIntervalSeconds; - } - - internal Session( - IBppServices services, - int retryIntervalSeconds, - ModApiSession modApiSession, - BundleQueueStore queueStore, - IBundleOutboxFiles files - ) - { - _services = services ?? throw new ArgumentNullException(nameof(services)); - _retryIntervalSeconds = retryIntervalSeconds; - _modApiSession = - modApiSession ?? throw new ArgumentNullException(nameof(modApiSession)); - _queueStore = queueStore ?? throw new ArgumentNullException(nameof(queueStore)); - _files = files ?? throw new ArgumentNullException(nameof(files)); - } - - public async Task RunAttemptAsync(CancellationToken cancellationToken) - { - Cleanup(); - var rows = _queueStore.ListDue(DateTimeOffset.UtcNow, MaximumAttemptBatch); - if (rows.Count == 0) - return UploadAttemptResult.NoWork(); - var observations = new List(); - foreach (var row in rows) - { - cancellationToken.ThrowIfCancellationRequested(); - try - { - using var stream = _files.OpenRead(row.FileName); - if (stream.Length != row.TotalBytes) - throw new InvalidDataException("bundle_length_mismatch"); - string digest; - using (var sha256 = SHA256.Create()) - digest = BitConverter - .ToString(sha256.ComputeHash(stream)) - .Replace("-", string.Empty) - .ToLowerInvariant(); - if (!string.Equals(digest, row.ContentSha256Hex, StringComparison.Ordinal)) - throw new InvalidDataException("bundle_digest_mismatch"); - stream.Seek(0, SeekOrigin.Begin); - var response = await _modApiSession - .UploadBundleAsync( - stream, - row.TotalBytes, - row.ContentDigest, - row.BundleId, - row.RunId, - cancellationToken - ) - .ConfigureAwait(false); - ApplyResponse(row, response); - if ( - response.Disposition - is BundleUploadDisposition.Uploaded - or BundleUploadDisposition.Equivalent - ) - { - _files.Delete(row.FileName); - BundlePipelineLog.Info( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.upload.succeeded" - ), - row.RunId, - row.BundleId - ); - observations.Add(UploadAttemptObservation.Succeeded(row.RunId)); - } - else if (response.Disposition == BundleUploadDisposition.Transient) - { - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.upload.degraded", - storm: ["category"] - ), - response.Code, - response.DiagnosticException, - runId: row.RunId - ); - observations.Add( - UploadAttemptObservation.Degraded( - row.RunId, - UploadLogReasonCode.RemoteUploadFailed, - response.DiagnosticException - ) - ); - _services.EventBus.Publish(new UploadArmRequested()); - } - else - { - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.upload.degraded", - storm: ["category"] - ), - response.Code, - response.DiagnosticException, - runId: row.RunId - ); - observations.Add( - UploadAttemptObservation.Degraded( - row.RunId, - UploadLogReasonCode.PayloadInvalid, - response.DiagnosticException - ) - ); - } - } - catch (FileNotFoundException) - { - _queueStore.FailOutboxAndScheduleReseal( - row.BundleId, - row.RunId, - "pending_file_missing", - DateTimeOffset.UtcNow - ); - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.upload.degraded", - storm: ["category"] - ), - "pending_file_missing", - runId: row.RunId - ); - observations.Add( - UploadAttemptObservation.Degraded( - row.RunId, - UploadLogReasonCode.PayloadUnreadable - ) - ); - } - catch (InvalidDataException ex) - { - _queueStore.FailOutboxAndScheduleReseal( - row.BundleId, - row.RunId, - ex.Message, - DateTimeOffset.UtcNow - ); - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.upload.degraded", - storm: ["category"] - ), - ex.Message, - ex, - row.RunId - ); - observations.Add( - UploadAttemptObservation.Degraded( - row.RunId, - UploadLogReasonCode.PayloadInvalid, - ex - ) - ); - } - catch (IOException ex) - { - RecordTransient(row, "file_io_error", ex.Message, null); - BundlePipelineLog.Warn( - new BppLogEvent( - BppLogFeatureScope.BundlePipeline, - "bundle_pipeline.upload.degraded", - storm: ["category"] - ), - "file_io_error", - ex, - row.RunId - ); - observations.Add( - UploadAttemptObservation.Degraded( - row.RunId, - UploadLogReasonCode.PayloadUnreadable, - ex - ) - ); - } - } - return UploadAttemptResult.From(observations); - } - - /// - /// Subscribe feed-private arm signals; null when the feed has none. The pump holds the - /// handle and disposes it first on shutdown; Dispose only owns attempt resources. - /// - public IDisposable? SubscribeArmSignals(Action arm) => null; - - public void Dispose() => _modApiSession.Dispose(); - - private void ApplyResponse(BundleOutboxRecord row, BundleUploadResponse response) - { - if (response.Disposition == BundleUploadDisposition.Transient) - { - RecordTransient(row, response.Code, response.Detail, response.RetryAfterSeconds); - return; - } - var uploaded = - response.Disposition - is BundleUploadDisposition.Uploaded - or BundleUploadDisposition.Equivalent; - _queueStore.RecordOutcome( - row.BundleId, - new BundleUploadOutcomeRecord( - uploaded, - response.Code, - response.Detail, - response.RequestId, - response.Outcome - ), - DateTimeOffset.UtcNow - ); - } - - private void RecordTransient( - BundleOutboxRecord row, - string code, - string? detail, - int? retryAfterSeconds - ) - { - var delay = Math.Max(_retryIntervalSeconds, retryAfterSeconds ?? 0); - var now = DateTimeOffset.UtcNow; - _queueStore.RecordTransient(row.BundleId, code, detail, now, now.AddSeconds(delay)); - } - - private void Cleanup() - { - var now = DateTimeOffset.UtcNow; - _queueStore.ExpirePending(now.Subtract(PendingRetention), now); - foreach ( - var fileName in _queueStore.ListRetentionFileNames( - now.Subtract(PermanentFileRetention) - ) - ) - { - if (_files.Exists(fileName)) - _files.Delete(fileName); - } - EnforceSoftLimit(now); - } - - private void EnforceSoftLimit(DateTimeOffset now) - { - var total = _files - .EnumerateBundleFileNames() - .Where(_files.Exists) - .Sum(_files.GetLength); - if (total <= SoftLimitBytes) - return; - foreach ( - var fileName in _queueStore.ListReclaimFileNames(now.Subtract(PendingRetention)) - ) - { - if (total <= SoftLimitBytes) - break; - if (!_files.Exists(fileName)) - continue; - var length = _files.GetLength(fileName); - _files.Delete(fileName); - total -= length; - } - } - } -} - -internal sealed class UploadPumpMount : IBppMountable -{ - private BackgroundUploadPump? _pump; - - public void Mount(UnityEngine.GameObject host, IBppServices services) - { - _pump = host.AddComponent(); - _pump.Initialize(services); - } - - public void Unmount(UnityEngine.GameObject host) - { - if (_pump == null) - return; - UnityEngine.Object.DestroyImmediate(_pump); - _pump = null; - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/RunPayloadComposer.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/RunPayloadComposer.cs deleted file mode 100644 index 2450a7a..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/BundlePipeline/RunPayloadComposer.cs +++ /dev/null @@ -1,497 +0,0 @@ -#nullable enable -using System.Text.RegularExpressions; -using BazaarGameShared.Domain.Core.Types; -using BazaarPlusPlus.Game.CombatReplay; -using BazaarPlusPlus.Game.PvpBattles; -using BazaarPlusPlus.Game.PvpBattles.Persistence; -using BazaarPlusPlus.Infrastructure; -using BazaarPlusPlus.ModApi.Bundle; -using BazaarPlusPlus.Storage.RunLog; -using Microsoft.Data.Sqlite; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BazaarPlusPlus.Game.BundlePipeline; - -internal sealed class RunPayloadComposer -{ - private static readonly Regex Identifier = new( - "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$", - RegexOptions.CultureInvariant - ); - private readonly string _databasePath; - private readonly PvpBattleSqliteStore _battleCatalog; - private readonly CombatReplayPayloadStore _replayStore; - - internal RunPayloadComposer(string databasePath, string replayRoot) - { - _databasePath = databasePath; - _battleCatalog = new PvpBattleSqliteStore(databasePath); - _replayStore = new CombatReplayPayloadStore(replayRoot); - } - - internal string ResolvePlayerAccountId(string runId, string? frozenAccountId) - { - var frozen = NormalizeIdentifier(frozenAccountId); - if (frozen != null) - return frozen; - var candidates = _battleCatalog - .ListByRunId(runId) - .Select(battle => NormalizeIdentifier(battle.Participants.PlayerAccountId)) - .Where(value => value != null) - .Distinct(StringComparer.Ordinal) - .ToList(); - return candidates.Count switch - { - 1 => candidates[0]!, - 0 => throw new BundleCompositionException("player_account_id_missing"), - _ => throw new BundleCompositionException("player_account_id_conflict"), - }; - } - - internal RunPayloadComposition Compose(string runId, string playerAccountId) - { - var payload = new RunPayloadV6 - { - RunId = runId, - PlayerAccountId = playerAccountId, - Run = ReadRunFacts(runId), - Events = ReadEvents(runId), - }; - var manifests = _battleCatalog - .ListByRunId(runId) - .OrderBy(battle => battle.RecordedAtUtc) - .ThenBy(battle => battle.BattleId, StringComparer.Ordinal) - .ToList(); - var finalBattleId = - payload.Run.Status == "completed" ? manifests.LastOrDefault()?.BattleId : null; - var replayFailures = new List(); - foreach (var manifest in manifests) - { - var battle = MapBattle(manifest, finalBattleId, replayFailures); - payload.Battles.Add(battle); - if (RunBundleV6Contract.IsReplayable(battle)) - payload.ReplayableBattleIds.Add(battle.BattleId); - else - payload.Degradation.ReplayOmittedBattleIds.Add(battle.BattleId); - } - - var projections = BuildProjections(payload, playerAccountId); - return new RunPayloadComposition(payload, projections, replayFailures); - } - - // Encoding belongs to the payload-encode seal stage: a codec failure here is deterministic, - // unlike a read failure while composing. The coordinator encodes the final payload itself. - internal void FitToBudget(RunPayloadComposition composition) => - ApplySizeBudget(composition.Payload, composition.Projections); - - private RunFactsV6 ReadRunFacts(string runId) - { - using var connection = Open(); - using var command = connection.CreateCommand(); - command.CommandText = $""" - SELECT hero, game_mode, started_at_ms, ended_at_ms, status, - COALESCE(final_day, day), COALESCE(final_hour, hour), victories, losses, - player_rank, player_rating, final_player_rank, final_player_rating, - final_player_rating_delta, max_health, prestige, level, income, gold, - build_channel, mod_version - FROM {RunLogSchema.RunsTableName} - WHERE run_id = $runId AND status <> 'active' - LIMIT 1; - """; - command.Parameters.AddWithValue("$runId", runId); - using var reader = command.ExecuteReader(); - if (!reader.Read()) - throw new BundleCompositionException("source_run_missing"); - return new RunFactsV6 - { - Hero = reader.GetString(0), - GameMode = reader.GetString(1), - Seed = null, - StartedAtMs = reader.GetInt64(2), - EndedAtMs = reader.IsDBNull(3) ? null : reader.GetInt64(3), - Status = reader.GetString(4), - Day = NonNegative(NullableInt(reader, 5)), - Hour = NonNegative(NullableInt(reader, 6)), - Victories = NonNegative(NullableInt(reader, 7)), - Losses = NonNegative(NullableInt(reader, 8)), - PlayerRank = Limit(NullableString(reader, 9)), - PlayerRating = NonNegative(NullableInt(reader, 10)), - FinalPlayerRank = Limit(NullableString(reader, 11)), - FinalPlayerRating = NonNegative(NullableInt(reader, 12)), - FinalPlayerRatingDelta = NullableInt(reader, 13), - MaxHealth = NonNegative(NullableInt(reader, 14)), - Prestige = NonNegative(NullableInt(reader, 15)), - Level = NonNegative(NullableInt(reader, 16)), - Income = NonNegative(NullableInt(reader, 17)), - Gold = NonNegative(NullableInt(reader, 18)), - BuildChannel = Limit(NullableString(reader, 19)), - ModVersion = Limit(NullableString(reader, 20)) ?? string.Empty, - }; - } - - private List ReadEvents(string runId) - { - using var connection = Open(); - using var command = connection.CreateCommand(); - command.CommandText = $""" - SELECT seq, ts_at_ms, kind, payload_json - FROM {RunLogSchema.RunEventsTableName} - WHERE run_id = $runId - ORDER BY seq ASC; - """; - command.Parameters.AddWithValue("$runId", runId); - using var reader = command.ExecuteReader(); - var events = new List(); - while (reader.Read()) - events.Add( - new RunEventV6 - { - Seq = reader.GetInt64(0), - TimestampMs = reader.GetInt64(1), - Kind = reader.GetString(2), - PayloadJson = EventPayloadBody(reader.GetString(3)), - } - ); - return events; - } - - // A replay that exists but cannot be used is reported, not decided: the seal coordinator asks - // BundleSealFailurePolicy whether it omits that replay or holds the whole Run. - private RunBattleV6 MapBattle( - PvpBattleManifest manifest, - string? finalBattleId, - List replayFailures - ) - { - BattleReplayV6? replay = null; - var loaded = _replayStore.LoadDetailed(manifest.BattleId); - if (loaded.Status == FileBackedPayloadLoadStatus.Unreadable) - replayFailures.Add(new(manifest.BattleId, Unreadable: true, loaded.Exception)); - else if (loaded.Status == FileBackedPayloadLoadStatus.Invalid) - replayFailures.Add(new(manifest.BattleId, Unreadable: false, loaded.Exception)); - else if (loaded.Status == FileBackedPayloadLoadStatus.Loaded && loaded.Payload != null) - { - try - { - _ = new CombatReplayLoader().Load(loaded.Payload); - replay = new BattleReplayV6 - { - Version = loaded.Payload.Version, - SpawnMessageBytes = loaded.Payload.SpawnMessageBytes.ToArray(), - CombatMessageBytes = loaded.Payload.CombatMessageBytes.ToArray(), - DespawnMessageBytes = loaded.Payload.DespawnMessageBytes.ToArray(), - }; - } - catch (Exception ex) - { - replayFailures.Add(new(manifest.BattleId, Unreadable: false, ex)); - } - } - - return new RunBattleV6 - { - BattleId = manifest.BattleId, - Facts = new BattleFactsV6 - { - RecordedAtMs = manifest.RecordedAtUtc.ToUnixTimeMilliseconds(), - Day = NonNegative(manifest.Day), - Hour = NonNegative(manifest.Hour), - EncounterId = Limit(manifest.EncounterId), - CombatKind = NormalizeIdentifier(manifest.CombatKind) ?? "pvp", - Result = NormalizeResult(manifest.Outcome.Result), - WinnerCombatantId = Limit(manifest.Outcome.WinnerCombatantId), - LoserCombatantId = Limit(manifest.Outcome.LoserCombatantId), - IsFinalBattle = string.Equals( - manifest.BattleId, - finalBattleId, - StringComparison.Ordinal - ), - }, - Participants = new BattleParticipantsV6 - { - Player = MapParticipant(manifest.Participants, manifest.Snapshots, player: true), - Opponent = MapParticipant(manifest.Participants, manifest.Snapshots, player: false), - }, - Snapshots = new BattleCardSnapshotsV6 - { - CardSets = - [ - MapCardSet("player_hand", manifest.Snapshots.PlayerHand), - MapCardSet("player_skills", manifest.Snapshots.PlayerSkills), - MapCardSet("opponent_hand", manifest.Snapshots.OpponentHand), - MapCardSet("opponent_skills", manifest.Snapshots.OpponentSkills), - ], - }, - Replay = replay, - }; - } - - private static BattleParticipantV6 MapParticipant( - PvpBattleParticipants participants, - PvpBattleSnapshots snapshots, - bool player - ) => - new() - { - AccountId = player ? participants.PlayerAccountId : participants.OpponentAccountId, - DisplayName = Limit(player ? participants.PlayerName : participants.OpponentName), - HeroName = Limit(player ? participants.PlayerHero : participants.OpponentHero), - Rank = Limit(player ? participants.PlayerRank : participants.OpponentRank), - Rating = NonNegative(player ? participants.PlayerRating : participants.OpponentRating), - Level = NonNegative(player ? participants.PlayerLevel : participants.OpponentLevel), - Prestige = NonNegative( - player ? participants.PlayerPrestige : participants.OpponentPrestige - ), - Victories = NonNegative( - player ? participants.PlayerVictories : participants.OpponentVictories - ), - Income = NonNegative(player ? participants.PlayerIncome : null), - Gold = NonNegative(player ? participants.PlayerGold : null), - HandItemCount = CountCards( - player ? snapshots.PlayerHand : snapshots.OpponentHand, - ECardType.Item - ), - SkillCount = CountCards( - player ? snapshots.PlayerSkills : snapshots.OpponentSkills, - ECardType.Skill - ), - }; - - // Counted from the captured set so they survive ApplySizeBudget dropping the card sets; a - // Missing set was never captured, so its count is unknown rather than zero. - private static int? CountCards(PvpBattleCardSetCapture source, ECardType type) => - source.Status == PvpBattleCaptureStatus.Missing - ? null - : source.Items.Count(card => card.Type == type); - - private static BattleCardSetV6 MapCardSet(string label, PvpBattleCardSetCapture source) => - new() - { - Label = label, - Status = source.Status.ToString(), - Source = source.Source.ToString(), - Items = source.Items.Select(MapCard).ToList(), - }; - - private static BattleCardV6 MapCard(PvpBattleCardSnapshot source) => - new() - { - InstanceId = source.InstanceId, - TemplateId = source.TemplateId, - Type = (int)source.Type, - Size = (int)source.Size, - Section = source.Section.HasValue ? (int)source.Section.Value : null, - Socket = source.Socket.HasValue ? (int)source.Socket.Value : null, - Name = Limit(source.Name), - Tier = Limit(source.Tier), - Enchant = Limit(source.Enchant), - Tags = source.Tags.Select(tag => Limit(tag) ?? string.Empty).ToList(), - Attributes = new Dictionary(source.Attributes), - }; - - private static List BuildProjections( - RunPayloadV6 payload, - string playerAccountId - ) => - payload - .Battles.Where(RunBundleV6Contract.IsReplayable) - .Where(battle => IsValidProjectionCandidate(battle, playerAccountId)) - .OrderByDescending(battle => battle.Facts.RecordedAtMs) - .ThenByDescending(battle => battle.BattleId, StringComparer.Ordinal) - .Take(BundleLimitsV6.MaxBattlesPerBundle) - .Select(battle => MapProjection(battle, playerAccountId)) - .OrderBy(projection => projection.RecordedAtMs) - .ThenBy(projection => projection.BattleId, StringComparer.Ordinal) - .ToList(); - - private static bool IsValidProjectionCandidate(RunBattleV6 battle, string playerAccountId) => - Identifier.IsMatch(battle.BattleId) - && battle.Facts.RecordedAtMs >= 0 - && battle.Facts.Day is >= 0 - && battle.Facts.Hour is >= 0 - && NormalizeIdentifier(battle.Participants.Player.AccountId) == playerAccountId - && NormalizeIdentifier(battle.Participants.Opponent.AccountId) != null - && NormalizeIdentifier(battle.Facts.WinnerCombatantId) != null - && NormalizeIdentifier(battle.Facts.LoserCombatantId) != null; - - private static BundleBattleProjectionV6 MapProjection( - RunBattleV6 battle, - string playerAccountId - ) => - new() - { - BattleId = battle.BattleId, - RecordedAtMs = battle.Facts.RecordedAtMs, - Day = battle.Facts.Day!.Value, - Hour = battle.Facts.Hour!.Value, - EncounterId = Limit(battle.Facts.EncounterId), - CombatKind = NormalizeIdentifier(battle.Facts.CombatKind) ?? "pvp", - Result = NormalizeIdentifier(battle.Facts.Result) ?? "unknown", - WinnerCombatantId = NormalizeIdentifier(battle.Facts.WinnerCombatantId)!, - LoserCombatantId = NormalizeIdentifier(battle.Facts.LoserCombatantId)!, - IsFinalBattle = battle.Facts.IsFinalBattle, - Player = MapCombatant(battle.Participants.Player, playerAccountId), - Opponent = MapCombatant( - battle.Participants.Opponent, - NormalizeIdentifier(battle.Participants.Opponent.AccountId)! - ), - }; - - private static BundleCombatantProjectionV6 MapCombatant( - BattleParticipantV6 participant, - string accountId - ) => - new() - { - AccountId = accountId, - DisplayName = Limit(participant.DisplayName) ?? string.Empty, - HeroId = null, - HeroName = Limit(participant.HeroName), - Rank = Limit(participant.Rank), - Rating = NonNegativeLong(participant.Rating), - Level = NonNegativeLong(participant.Level), - Prestige = NonNegativeLong(participant.Prestige), - Victories = NonNegativeLong(participant.Victories), - }; - - private static void ApplySizeBudget( - RunPayloadV6 payload, - List projections - ) - { - if (EncodedSize(payload) <= BundleLimitsV6.MaxRunBytes) - return; - var projected = projections - .Select(value => value.BattleId) - .ToHashSet(StringComparer.Ordinal); - foreach (var battle in payload.Battles.Where(value => !projected.Contains(value.BattleId))) - { - battle.Snapshots = null; - battle.Replay = null; - payload.ReplayableBattleIds.Remove(battle.BattleId); - AddDegradation(payload, "non_projection_replay_trimmed", battle.BattleId); - } - if (EncodedSize(payload) <= BundleLimitsV6.MaxRunBytes) - return; - - while (projections.Count > 0 && EncodedSize(payload) > BundleLimitsV6.MaxRunBytes) - { - var projection = projections[0]; - projections.RemoveAt(0); - var battle = payload.Battles.First(value => value.BattleId == projection.BattleId); - battle.Snapshots = null; - battle.Replay = null; - payload.ReplayableBattleIds.Remove(battle.BattleId); - AddDegradation(payload, "projection_battle_trimmed", battle.BattleId); - } - foreach ( - var battle in payload.Battles.Where(value => - value.Snapshots != null && value.Replay == null - ) - ) - battle.Snapshots = null; - if (EncodedSize(payload) <= BundleLimitsV6.MaxRunBytes) - return; - - for ( - var index = 0; - index < payload.Events.Count && EncodedSize(payload) > BundleLimitsV6.MaxRunBytes; - - ) - { - if (IsTerminalEvent(payload.Events[index].Kind)) - { - index++; - continue; - } - payload.Events.RemoveAt(index); - payload.Degradation.EventsOmitted++; - if (!payload.Degradation.Categories.Contains("events_trimmed")) - payload.Degradation.Categories.Add("events_trimmed"); - } - } - - private static void AddDegradation(RunPayloadV6 payload, string category, string battleId) - { - if (!payload.Degradation.Categories.Contains(category)) - payload.Degradation.Categories.Add(category); - if (!payload.Degradation.ReplayOmittedBattleIds.Contains(battleId)) - payload.Degradation.ReplayOmittedBattleIds.Add(battleId); - } - - private static bool IsTerminalEvent(string kind) => - kind is "run_started" or "run_completed" or "run_abandoned"; - - private static int EncodedSize(RunPayloadV6 payload) => - RunPayloadV6Codec.Encode(payload).Length; - - private SqliteConnection Open() - { - var connection = new SqliteConnection($"Data Source={_databasePath}"); - connection.Open(); - return connection; - } - - private static int? NullableInt(SqliteDataReader reader, int ordinal) => - reader.IsDBNull(ordinal) ? null : reader.GetInt32(ordinal); - - // The RunEventV6 envelope owns run_id, seq, ts, and kind; the stored payload_json repeats them - // (ts as text), so the Run segment carries only the remaining fields, in stored order. - private static readonly string[] EventEnvelopeKeys = ["run_id", "seq", "ts", "kind"]; - - internal static string EventPayloadBody(string payloadJson) - { - using var reader = new JsonTextReader(new StringReader(payloadJson)) - { - DateParseHandling = DateParseHandling.None, - FloatParseHandling = FloatParseHandling.Decimal, - }; - var body = JObject.Load(reader); - foreach (var key in EventEnvelopeKeys) - body.Remove(key); - return body.ToString(Formatting.None); - } - - private static string? NullableString(SqliteDataReader reader, int ordinal) => - reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal); - - private static int? NonNegative(int? value) => value is >= 0 ? value : null; - - private static long? NonNegativeLong(int? value) => value is >= 0 ? value.Value : null; - - private static string? Limit(string? value) - { - if (string.IsNullOrWhiteSpace(value)) - return null; - var normalized = value.Trim(); - return normalized.Length <= 256 ? normalized : normalized[..256]; - } - - private static string? NormalizeIdentifier(string? value) - { - var normalized = value?.Trim(); - return normalized != null && Identifier.IsMatch(normalized) ? normalized : null; - } - - private static string NormalizeResult(string? result) => - NormalizeIdentifier(result?.ToLowerInvariant()) ?? "unknown"; -} - -internal sealed record RunPayloadComposition( - RunPayloadV6 Payload, - List Projections, - IReadOnlyList ReplayFailures -); - -// Unreadable: the file could not be read. Otherwise its bytes did not decode; Exception is null -// when they were rejected without one (for example, not gzip). -internal sealed record ReplayLoadFailure(string BattleId, bool Unreadable, Exception? Exception); - -internal sealed class BundleCompositionException : Exception -{ - internal BundleCompositionException(string code) - : base(code) => Code = code; - - internal string Code { get; } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CardTags/PlayerFacingCardTags.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CardTags/PlayerFacingCardTags.cs deleted file mode 100644 index e5a7298..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CardTags/PlayerFacingCardTags.cs +++ /dev/null @@ -1,36 +0,0 @@ -#nullable enable -using BazaarGameShared.Domain.Core.Types; - -namespace BazaarPlusPlus.Game.CardTags; - -// Canonical ordering for card tags that are meaningful to players. Feature-specific -// consumers may filter this list further (for example aggregate item effects only -// count item types, so Merchant is excluded there). -internal static class PlayerFacingCardTags -{ - public static readonly IReadOnlyList Ordered = new[] - { - ECardTag.Weapon, - ECardTag.Friend, - ECardTag.Aquatic, - ECardTag.Tool, - ECardTag.Vehicle, - ECardTag.Food, - ECardTag.Trap, - ECardTag.Toy, - ECardTag.Potion, - ECardTag.Reagent, - ECardTag.Relic, - ECardTag.Dragon, - ECardTag.Core, - ECardTag.Tech, - ECardTag.Dinosaur, - ECardTag.Apparel, - ECardTag.Merchant, - ECardTag.Property, - ECardTag.Loot, - ECardTag.Instrument, - ECardTag.Drone, - ECardTag.Ray, - }; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionGridPortAdapter.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionGridPortAdapter.cs deleted file mode 100644 index 49ceb27..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionGridPortAdapter.cs +++ /dev/null @@ -1,46 +0,0 @@ -#nullable enable -using BazaarPlusPlus.Game.CollectionPanel.Data; -using BazaarPlusPlus.Game.CollectionPanel.Grid; - -namespace BazaarPlusPlus.Game.CollectionPanel; - -// Production adapter over CollectionGridVirtualizer. Bind(null) or Dispose clears the window so -// Current returns Empty rather than a stale ContentHeight with VisibleCount=0. -internal sealed class CollectionGridPortAdapter : ICollectionGridPort -{ - private CollectionGridVirtualizer? _virtualizer; - private bool _hasPublished; - - public void Bind(CollectionGridVirtualizer? virtualizer) - { - _virtualizer = virtualizer; - _hasPublished = false; - } - - public CollectionGridProjection? Publish( - IReadOnlyList cards, - CollectionTabKind activeTab - ) - { - if (_virtualizer == null) - return null; - - _virtualizer.SetVisible(cards, activeTab); - _hasPublished = true; - return new CollectionGridProjection(_virtualizer.VisibleCount, _virtualizer.ContentHeight); - } - - public CollectionGridProjection Current - { - get - { - if (_virtualizer == null || !_hasPublished) - return CollectionGridProjection.Empty; - - return new CollectionGridProjection( - _virtualizer.VisibleCount, - _virtualizer.ContentHeight - ); - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionClick.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionClick.cs deleted file mode 100644 index 4a3720f..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionClick.cs +++ /dev/null @@ -1,39 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Game.CollectionPanel; - -internal sealed class CollectionInspectionClick -{ - // Physical pixels. A finger routinely moves several pixels between down and up; the old - // 6px tolerance cancelled most real taps on a 640dpi phone. 32px is still well below a - // deliberate drag and keeps scrolling cancelled by the separate scroll check. - internal const float TapSlopPixels = 32f; - private Guid? _card; - private float _x, - _y, - _scroll; - - public bool Sample(bool pressed, bool released, Guid? card, float x, float y, float scroll) - { - if (pressed) - { - _card = card; - _x = x; - _y = y; - _scroll = scroll; - } - if ( - _card != card - || (x - _x) * (x - _x) + (y - _y) * (y - _y) - > TapSlopPixels * TapSlopPixels - || Math.Abs(scroll - _scroll) > .5f - ) - Reset(); - if (!released) - return false; - var open = _card.HasValue; - Reset(); - return open; - } - - public void Reset() => _card = null; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionLayout.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionLayout.cs deleted file mode 100644 index f4b8e1f..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionLayout.cs +++ /dev/null @@ -1,146 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Game.CollectionPanel; - -internal readonly record struct CollectionInspectionLayout( - float CardX, - float CardY, - float CardWidth, - float CardHeight, - float DetailCenterX, - float DetailCenterY, - float DetailWidth, - float DetailHeight, - float Scale, - float Gap -) -{ - // Available card lane in top-down screen pixels, with the measured selector below it. - public static CollectionInspectionLayout ForDrawer( - float left, - float top, - float laneWidth, - float laneHeight, - float visualWidth, - float visualHeight, - float selectorHeight, - float gap, - float uiScale = 1f - ) - { - laneWidth = Math.Max(1, laneWidth); - laneHeight = Math.Max(1, laneHeight); - visualWidth = Math.Max(1, visualWidth); - visualHeight = Math.Max(1, visualHeight); - var padding = Math.Min(laneWidth, laneHeight) * .025f; - var availableHeight = Math.Max(1, laneHeight - padding * 2 - selectorHeight - gap); - var maxScaleX = (laneWidth - padding * 2) * .92f / visualWidth; - var maxScaleY = availableHeight / visualHeight; - var maxFitScale = Math.Min(maxScaleX, maxScaleY); - var baseScale = Math.Min( - laneWidth * .72f / visualWidth, - availableHeight * .82f / visualHeight - ); - var scale = Math.Min(maxFitScale, baseScale * Math.Max(1f, uiScale)); - var width = visualWidth * scale; - var height = visualHeight * scale; - return new( - left + (laneWidth - width) / 2, - top + padding + (availableHeight - height) / 2, - width, - height, - 0, - 0, - 0, - 0, - scale, - gap - ); - } - - public static CollectionInspectionLayout ForContent( - float width, - float height, - float cardWidth, - float cardHeight, - float detailWidth, - float detailHeight - ) - { - width = Math.Max(1f, width); - height = Math.Max(1f, height); - cardWidth = Math.Max(1f, cardWidth); - cardHeight = Math.Max(1f, cardHeight); - detailWidth = Math.Max(1f, detailWidth); - detailHeight = Math.Max(1f, detailHeight); - var gap = Math.Min(width * .025f, Math.Clamp(height * .0175f, 12f, 36f)); - var scale = Math.Min( - 1f, - Math.Min( - (width * .92f - gap) / (cardWidth + detailWidth), - height * .74f / Math.Max(cardHeight, detailHeight) - ) - ); - cardWidth *= scale; - cardHeight *= scale; - detailWidth *= scale; - detailHeight *= scale; - var left = (width - cardWidth - detailWidth - gap) / 2f; - var cardOffset = width * .08f; - return new( - left + cardOffset, - (height - cardHeight) / 2f, - cardWidth, - cardHeight, - left + cardWidth + gap + detailWidth / 2f, - height / 2f, - detailWidth, - detailHeight, - scale, - gap - cardOffset - ); - } -} - -internal readonly record struct CollectionInspectionCardPlacement( - float X, - float Y, - float Width, - float Height -) -{ - public (float X, float Y) ScaleFor(float visualWidth, float visualHeight) => - (Width / Math.Max(1f, visualWidth), Height / Math.Max(1f, visualHeight)); -} - -// Selection changes replace native previews, but never reflow the card around new text. -internal sealed class CollectionInspectionCardAnchor -{ - private CollectionInspectionCardPlacement? _placement; - private float _width, - _height; - - public bool NeedsLayout(float width, float height) => - !_placement.HasValue || _width != width || _height != height; - - public CollectionInspectionCardPlacement Resolve( - float width, - float height, - CollectionInspectionLayout candidate - ) - { - if (NeedsLayout(width, height)) - { - _width = width; - _height = height; - _placement = new( - candidate.CardX, - candidate.CardY, - candidate.CardWidth, - candidate.CardHeight - ); - } - return _placement!.Value; - } - - public void Reset() => _placement = null; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionModule.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionModule.cs deleted file mode 100644 index cd1d4d1..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionModule.cs +++ /dev/null @@ -1,831 +0,0 @@ -#nullable enable -using BazaarGameClient.Domain.Models.Cards; -using BazaarGameShared.Domain.Core.Types; -using BazaarPlusPlus.Game.CollectionPanel.Grid; -using BazaarPlusPlus.Game.CollectionPanel.Tooltips; -using BazaarPlusPlus.GameInterop.CardPreview; -using BazaarPlusPlus.GameInterop.Tooltips; -using BazaarPlusPlus.Infrastructure; -using BazaarPlusPlus.Infrastructure.Logging; -using BazaarPlusPlus.Infrastructure.UiTokens; -using TheBazaar.Tooltips; -using TheBazaar.UI; -using TheBazaar.UI.Tooltips; -using UnityEngine; - -namespace BazaarPlusPlus.Game.CollectionPanel; - -internal sealed class CollectionInspectionModule -{ - private readonly CollectionInspectionState _state = new(); - private readonly CollectionInspectionCardAnchor _cardAnchor = new(); - private INativeCardPreviewHost? _host; - private INativeCardPreviewHost? _globalHost; - private Action? _blockInput; - private Func? _sourceBounds; - private CardTooltipController? _controller; - private NativeInspectionPresentation? _presentation; - private InspectionVariantPreviewState? _variants; - private InspectionVariantBar? _variantBar; - private CardTooltipData? _inspectionData; - private INativeCardPreviewScope? _scope; - private INativeCardPreviewSession? _card; - private InspectionPreviewOwner? _previewOwner; - private NativeCardCellBoundsCache _bounds = new(); - private Rect _origin; - private float _animation; - private bool _cardRevealed; - private bool _measurementPending; - private float _measurementDeadline; - - public bool BlocksInput => _state.BlocksInput(Time.frameCount); - public bool IsOpen => _state.IsOpen; - - internal void InitializeGlobalHost(INativeCardPreviewHost host) => _globalHost = host; - - public void OpenHovered(Guid templateId) - { - var controller = TheBazaar.Data.TooltipParentComponent?.CardTooltipController; - var data = controller?.CurrentTooltipData.TryCast(); - var rejection = - BlocksInput ? "input_blocked" - : controller == null ? "controller_missing" - : !controller.isActiveAndEnabled ? "controller_inactive" - : controller.IsLocked ? "already_locked" - : data == null ? "card_data_missing" - : data.CardInstance.TemplateId.ToSystemGuid() != templateId ? "card_mismatch" - : !CollectionTierTooltipRegistry.Contains(data.CardInstance) ? "card_unregistered" - : null; - if (rejection != null) - return; -#if BPP_ANDROID - // The mobile toggle can return without locking even with matching visible data. - // This is an explicit inspection intent, so use the native lock operation. - controller!.Lock(); -#else - controller!.LockTooltipToggle(); -#endif - } - -#if BPP_ANDROID - // The native tooltip spawns asynchronously after a hover, so allow it a moment to appear. - private const float PreviewRequestSeconds = 1f; - private CardPreviewBase? _previewCard; - private bool _previewPending; - private float _previewRequestDeadline; - private Rect _previewOrigin; - private IntPtr _acceptedPreview; - - public bool HasPendingPreview => _previewPending; - - // Touch lifts end a native hover. The long-pressed card keeps its hover until the request is - // dropped or its inspection closes, so that release cannot hide or unlock the tooltip. - public bool HoldsPreviewHover(CardPreviewBase card) => - _previewCard != null && card != null && card.Pointer == _previewCard.Pointer; - - // Live Build and History boards have no hover on touch. A long press asks the card for its - // native tooltip; the lock follows once the controller shows exactly that card's data. - public void RequestPreviewInspection(CardPreviewBase card, Rect origin) - { - if (BlocksInput || card == null || card._tooltipData == null) - return; - ReleasePreviewHover(); - _previewCard = card; - _previewPending = true; - _previewRequestDeadline = Time.unscaledTime + PreviewRequestSeconds; - _previewOrigin = origin; - try - { - card.OnHover(); - } - catch (Exception ex) - { - Report(ex); - ReleasePreviewHover(); - return; - } - PumpPreviewRequest(); - } - - // Idempotent: the Collection, Live Build and History ticks may all call it in one frame. - public void PumpPreviewRequest() - { - if (!_previewPending) - return; - var card = _previewCard; - if ( - card == null - || BlocksInput - || Time.unscaledTime > _previewRequestDeadline - || !card.gameObject.activeInHierarchy - || card._tooltipData == null - ) - { - ReleasePreviewHover(); - return; - } - var controller = TheBazaar.Data.TooltipParentComponent?.CardTooltipController; - // Read the card's data every frame: a hover may rebind it. - if ( - controller == null - || !controller.isActiveAndEnabled - || controller.IsLocked - || controller.CurrentTooltipData == null - || controller.CurrentTooltipData.Pointer != card._tooltipData.Pointer - ) - return; - _previewPending = false; - // Preview tooltip data is neither a registered Collection card nor an in-run ItemCard, - // so OnLocked accepts it only for this explicit request. - _acceptedPreview = card._tooltipData.Pointer; - try - { - controller.Lock(); - } - finally - { - _acceptedPreview = IntPtr.Zero; - } - if (!_state.IsOpen) - ReleasePreviewHover(); - } - - private void ReleasePreviewHover() - { - var card = _previewCard; - _previewCard = null; - _previewPending = false; - if (card == null) - return; - try - { - card.OnHoverOut(); - } - catch (Exception ex) - { - Report(ex); - } - } -#endif - - public void Attach( - INativeCardPreviewHost host, - Action blockInput, - Func sourceBounds - ) - { - _host = host; - _blockInput = blockInput; - _sourceBounds = sourceBounds; - } - - public void Detach() - { - Close(); - _host = null; - _blockInput = null; - _sourceBounds = null; - } - - public void OnLocked(CardTooltipController controller) - { - var host = _host ?? _globalHost; - if ( - host == null - || controller == null - || !controller.IsLocked - || controller.CurrentTooltipData.TryCast() is not { } data - || (!CollectionTierTooltipRegistry.Contains(data.CardInstance) - && data.CardInstance.TryCast() == null -#if BPP_ANDROID - && data.Pointer != _acceptedPreview -#endif - ) - ) - return; - Close(); - _controller = controller; - _inspectionData = data; - _origin = _sourceBounds?.Invoke() ?? default; -#if BPP_ANDROID - if (_acceptedPreview != IntPtr.Zero && data.Pointer == _acceptedPreview) - _origin = _previewOrigin; -#endif - _state.Open(); - _cardAnchor.Reset(); - _animation = 0f; - try - { - _blockInput?.Invoke(true); - _presentation = new NativeInspectionPresentation(controller); - _previewOwner = new InspectionPreviewOwner(_presentation.CardRoot); - _scope = host.OpenScope(_previewOwner); - CreateVariantControls(controller, data); - BppLog.InfoEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.inspection.opened" - ) - ); - OnPreviewChanged(controller, data); - RefreshLayout(0f); - } - catch (Exception ex) - { - Report(ex); - Close(); - } - } - - // The selector is optional: a card with one quality and no enchantments is still inspectable, - // and a failure while building chips must not abort an otherwise valid inspection. - private void CreateVariantControls(CardTooltipController controller, CardTooltipData data) - { - if (_presentation == null) - return; - var options = InspectionVariantOptions.Build(data); - if (options == null) - { - // Not every card has a second quality or a second enchantment; reporting keeps the - // difference between "nothing to choose" and "the selector failed to build" visible. - BppLog.InfoEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.inspection.variants.unavailable" - ), - ("registered", CollectionTierTooltipRegistry.Contains(data.CardInstance)) - ); - return; - } - try - { - _variants = new InspectionVariantPreviewState(data, options); - _variantBar = _presentation.CreateVariantBar( - options, - _variants.SelectedTier, - _variants.SelectedEnchantment - ); - if (_variantBar == null) - { - BppLog.WarnEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.inspection.variants.creation_failed" - ), - ("tiers", options.Tiers.Count), - ("enchantments", options.Enchantments.Count) - ); - return; - } - BppLog.InfoEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.inspection.variants.ready" - ), - ("tiers", options.Tiers.Count), - ("enchantments", options.Enchantments.Count) - ); - _variantBar.TierSelected += OnTierSelected; - _variantBar.EnchantmentSelected += OnEnchantmentSelected; - _variantBar.ResetRequested += OnResetSelected; - } - catch (Exception ex) - { - Report(ex); - DestroyVariantControls(); - } - } - - private void OnTierSelected(ETier tier) - { - if (_variants?.SelectTier(tier) != true) - return; - ApplyVariantSelection(); - } - - private void OnEnchantmentSelected(EEnchantmentType? enchantment) - { - if (_variants?.SelectEnchantment(enchantment) != true) - return; - ApplyVariantSelection(); - } - - private void OnResetSelected() - { - if (_variants?.Reset() != true) - return; - ApplyVariantSelection(); - } - - /// - /// Pushes the selected quality/enchantment into both inspection surfaces: the native tooltip - /// text and the 3D card preview. The native call also drives OnPreviewChanged, so the - /// card model and the description never disagree about the selected variant. - /// - private void ApplyVariantSelection() - { - if (_variants == null || _controller == null) - return; - // The description is about to change, so a popup describing the old copy must not linger. - _presentation?.HideNestedTooltip(); - var data = _variants.Data; - _inspectionData = data; - _variantBar?.SyncSelection(_variants.SelectedTier, _variants.SelectedEnchantment); - if (!NativeCardTooltipContentRefresher.TryApply(_controller, data)) - { - Report( - new InvalidOperationException( - "Native inspection tooltip rejected the selected quality/enchantment preview." - ) - ); - return; - } - _measurementPending = false; - _bounds = new NativeCardCellBoundsCache(); - RefreshLayout(0f); - } - - private void DestroyVariantControls() - { - if (_variantBar != null) - { - _variantBar.TierSelected -= OnTierSelected; - _variantBar.EnchantmentSelected -= OnEnchantmentSelected; - _variantBar.ResetRequested -= OnResetSelected; - _presentation?.ReleaseVariantBar(_variantBar); - _variantBar = null; - } - _variants?.Dispose(); - _variants = null; - } - - public void OnPreviewChanged(CardTooltipController controller, CardTooltipData data) - { - if (!ReferenceEquals(controller, _controller) || _scope == null) - return; - // The tooltip applies the preview data itself, so the 3D model must follow the same - // selection; otherwise switching quality would only change the text. - _inspectionData = data; - var card = data.CardInstance; - Dictionary attributes; - try - { - attributes = - card.Attributes != null - ? new Dictionary(card.Attributes.ToManagedDictionary()) - : new Dictionary(); - } - catch - { - attributes = new Dictionary(); - } - - var subject = new NativeCardPreviewSubject - { - TemplateId = card.TemplateId.ToSystemGuid(), - Tier = card.Tier, - EnchantmentType = BazaarPlusPlus.GameInterop.Cards.NativeCardOptionalFields.Enchantment( - card - ), - Attributes = attributes, - InstanceIdPrefix = "bpp-inspection", - }; - _ = AcquirePreviewAsync(_scope, subject, _state.Select()); - } - - public void OnNativeClosed(CardTooltipController controller, bool unlock = false) - { - if (ReferenceEquals(controller, _controller)) - Close(unlock); - } - - public void Close() => Close(unlock: true); - - private void Close(bool unlock) - { - if (!_state.IsOpen) - return; - _state.Close(Time.frameCount); - _cardAnchor.Reset(); - // The nested popup is a native sibling of the description, so it must go down with it. - _presentation?.HideNestedTooltip(); - var controller = _controller; - _controller = null; - // Stop native ownership synchronously before destroying anything its lock can reference. - try - { - if (unlock && controller != null && controller.IsLocked) - controller.Unlock(); - } - catch (Exception ex) - { - Report(ex); - } - finally - { - DestroyVariantControls(); - _inspectionData = null; -#if BPP_ANDROID - // After the unlock, so the held hover-out cannot race the lock it was protecting. - ReleasePreviewHover(); -#endif - _card?.Dispose(); - _card = null; - _previewOwner = null; - var scope = _scope; - var presentation = _presentation; - _scope = null; - _presentation = null; - presentation?.ReleaseNative(); - if (scope != null) - _ = DisposeScopeAsync(scope, presentation); - else - presentation?.Dispose(); - // Input remains blocked until a later frame, so dismissing cannot click through. - } - } - - public void Tick(float dt) - { -#if BPP_ANDROID - PumpPreviewRequest(); -#endif - if ( - _state.IsOpen - && (_controller == null || !_controller.isActiveAndEnabled || !_controller.IsLocked) - ) - Close(unlock: false); - _blockInput?.Invoke(BlocksInput); - RefreshLayout(dt); - // A tap that opens or closes a nested tooltip is consumed, so it must not also read as a - // background dismissal within the same frame. - if (_presentation?.PollTap() == true) - return; - if (_presentation?.PollDismiss() == true) - { - BppLog.InfoEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.inspection.background_dismissed" - ) - ); - Close(); - } - } - - private void PositionVariantBar() - { - if (_presentation == null || _variantBar == null) - return; - _presentation.PositionVariantBar(_variantBar, VariantBarGap); - } - -#if BPP_ANDROID - /// - /// Centers the BPP quality/enchantment band under the enlarged card in the left half. - /// - /// Android keeps the game's own drawer on the right, so the description is no longer the - /// anchor the band hangs under; the enlarged card is. - /// - private void PositionVariantBarUnderCard(Rect cardCell) - { - if (_variantBar == null) - return; - var size = _variantBar.Measure(); - var centerX = cardCell.x + cardCell.width * .5f; - // Cell rects run top-down from the screen top; the band is placed in screen coordinates (bottom-up). - var cardBottom = Screen.height - (cardCell.y + cardCell.height); - var safeBottom = Mathf.Max(0f, Screen.safeArea.yMin); - var minTop = safeBottom + size.y + 6f; - var top = Mathf.Max(minTop, cardBottom - VariantBarGap); - _variantBar.Root.position = new Vector3(centerX, top, 0f); - } - - // Use the native drawer's measured screen edge. Until it is measurable, split the - // current safe content evenly; no physical resolution identifies a device class. - private float AndroidDrawerLeft(Rect content) - { - if ( - _presentation != null - && _presentation.TryGetNativeTrayScreenRect(out var tray) - && tray.xMin > content.xMin + content.width * .2f - && tray.xMin < content.xMax - content.width * .1f - && tray.width > content.width * .2f - ) - return tray.xMin; - return content.center.x; - } - - private CollectionInspectionLayout AndroidInspectionLayout( - float visualWidth, - float visualHeight - ) - { - var content = AndroidOverlayViewport.ContentPixels; - var laneWidth = Mathf.Max(1f, AndroidDrawerLeft(content) - content.xMin); - _variantBar?.FitWidth(laneWidth * .95f); - var selectorHeight = _variantBar?.Measure().y ?? 0f; - return CollectionInspectionLayout.ForDrawer( - content.xMin, - Screen.height - content.yMax, - laneWidth, - content.height, - visualWidth, - visualHeight, - selectorHeight, - VariantBarGap, - AndroidOverlayViewport.UiScale - ); - } - - private Rect AndroidPlaceholderCard() - { - var layout = AndroidInspectionLayout(300f, 500f); - return new Rect(layout.CardX, layout.CardY, layout.CardWidth, layout.CardHeight); - } -#endif - - /// - /// Vertical gap between the description and the selector, scaled to the viewport so the band - /// stays tactile on a phone without drifting off a tablet's larger screen. - /// - private static float VariantBarGap => -#if BPP_ANDROID - AndroidOverlayViewport.Read().TouchScale * 8f; -#else - Mathf.Clamp(Screen.height * .014f, 10f, 26f); -#endif - - private void RefreshLayout(float dt) - { - if (_presentation == null) - return; -#if !BPP_ANDROID - if (_card != null && _cardAnchor.NeedsLayout(Screen.width, Screen.height)) - _bounds.InvalidateOnScaleDirty(); -#endif - if (_card != null && !_bounds.IsValid) - { - if (!_measurementPending) - { - _measurementPending = true; - _measurementDeadline = Time.unscaledTime + 1f; - } - NativeCardCellFitter.PrepareGridRect(_card.Rect); - NativeCardPreviewArtworkMeasurement.PrepareLayoutSize( - _card.Rect, - NativeCardCellFitter.FallbackNativeCardHeight - ); - Canvas.ForceUpdateCanvases(); - if (!NativeCardPreviewArtworkMeasurement.TryMeasure(_card.Rect, out var artwork)) - { - if (Time.unscaledTime >= _measurementDeadline) - { - Report( - new InvalidOperationException( - "Native inspection artwork did not become measurable. " - + NativeCardPreviewArtworkMeasurement.DescribeLayout(_card.Rect) - ) - ); - Close(); - } - return; - } - _measurementPending = false; - _bounds.Store( - new CardVisualBounds( - artwork.width, - artwork.height, - artwork.center.x, - artwork.center.y - ), - null - ); - } -#if BPP_ANDROID - _presentation.MeasureDescription(Screen.width * .92f, Screen.height * .74f); -#else - var detail = _presentation.MeasureDescription(Screen.width * .92f, Screen.height * .74f); -#endif - if (_card == null) - { -#if BPP_ANDROID - PositionVariantBarUnderCard(AndroidPlaceholderCard()); -#else - _presentation.PositionDescription(Screen.width / 2f, Screen.height / 2f, 1f); - _presentation.PositionVariantBar(_variantBar, VariantBarGap); -#endif - return; - } -#if !BPP_ANDROID - NativeCardCellFitter.ApplyScale( - _card.Rect, - new CollectionGridRect(0f, 0f, Screen.width * .50f, Screen.height * .72f), - 0f, - _bounds - ); -#endif - if (!_bounds.TryGet(out var visual, out _)) - return; -#if BPP_ANDROID - var layout = AndroidInspectionLayout(visual.Width, visual.Height); -#else - var baseScale = _card.Rect.localScale; - var layout = CollectionInspectionLayout.ForContent( - Screen.width, - Screen.height, - visual.Width * baseScale.x, - visual.Height * baseScale.y, - detail.x, - detail.y - ); - _presentation.PositionDescription(layout.DetailCenterX, layout.DetailCenterY, layout.Scale); - PositionVariantBar(); -#endif -#if BPP_ANDROID - var placement = new CollectionInspectionCardPlacement( - layout.CardX, - layout.CardY, - layout.CardWidth, - layout.CardHeight - ); -#else - var placement = _cardAnchor.Resolve(Screen.width, Screen.height, layout); -#endif - _animation = Mathf.Min(1f, _animation + dt / .25f); - var progress = 1f - Mathf.Pow(1f - _animation, 3f); - var target = new Rect(placement.X, placement.Y, placement.Width, placement.Height); - var origin = _origin.width > 0f ? _origin : target; - var rect = new Rect( - Vector2.Lerp(origin.position, target.position, progress), - Vector2.Lerp(origin.size, target.size, progress) - ); -#if BPP_ANDROID - PositionVariantBarUnderCard(rect); -#endif - var cell = new CollectionGridRect(rect.x, rect.y, rect.width, rect.height); - var animatedPlacement = new CollectionInspectionCardPlacement( - rect.x, - rect.y, - rect.width, - rect.height - ); - var scale = animatedPlacement.ScaleFor(visual.Width, visual.Height); - _card.Rect.localScale = new Vector3(scale.X, scale.Y, 1f); - NativeCardCellFitter.Reposition(_card.Rect, cell, 0f, _bounds, allowMeasure: false); - if (!_cardRevealed) - { - if (_previewOwner?.Reveal(_card.Root) != true) - { - Report( - new InvalidOperationException( - "Native inspection visibility lease was unavailable." - ) - ); - Close(); - return; - } - _cardRevealed = true; - } - } - - private async Task AcquirePreviewAsync( - INativeCardPreviewScope scope, - NativeCardPreviewSubject subject, - int revision - ) - { - try - { - var result = await scope.AcquireAsync(subject); - if (result.Session == null) - { - if (_state.CanPublish(revision)) - Close(); - return; - } - if (!_state.CanPublish(revision)) - { - result.Session.Dispose(); - return; - } - _card?.Dispose(); - _card = result.Session; - _bounds = new NativeCardCellBoundsCache(); - _cardRevealed = false; - _measurementPending = false; - var shown = _card.Show(); - if (shown.Status != NativePreviewActionStatus.Applied) - { - Report( - shown.Failure?.Exception - ?? new InvalidOperationException( - $"Native inspection preview activation failed: {shown.Status}." - ) - ); - Close(); - return; - } - RefreshLayout(0f); - } - catch (OperationCanceledException) { } - catch (Exception ex) - { - Report(ex); - if (_state.CanPublish(revision)) - Close(); - } - } - - private static async Task DisposeScopeAsync( - INativeCardPreviewScope scope, - NativeInspectionPresentation? presentation - ) - { - try - { - await scope.DisposeAsync(); - } - catch (Exception ex) - { - Report(ex); - } - finally - { - presentation?.Dispose(); - } - } - - private static void Report(Exception ex) => - BppLog.WarnEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.inspection.failed", - storm: ["reason_code"] - ), - ex, - ("reason_code", CollectionPanelLogReasonCode.NativePreviewRuntimeFailed) - ); - - private sealed class InspectionPreviewOwner(Transform parent) : INativeCardPreviewOwner - { - private readonly Dictionary _visibility = - new(); - public int Layer => CollectionGridOverlay.DefaultLayer; - public bool UsePremiumVisuals => true; - - public Transform ResolveParent(NativeCardPreviewSubject subject) => parent; - - public void PrepareWhileInactive(NativeCardPreviewOwnerContext context) - { - var cacheSession = CollectionCardCacheHost.ActiveSession; - if (cacheSession != null) - { - var marker = context.Root.GetComponent(); - if (marker == null) - marker = context.Root.AddComponent(); - marker.CacheOwner = cacheSession; - } - } - - public void OnAcquired(NativeCardPreviewOwnerContext context) - { - var group = - context.Root.GetComponent() - ?? context.Root.AddComponent(); - _visibility.Add(context.Root, (group, group.alpha)); - group.alpha = 0f; - foreach ( - var graphic in context.Root.GetComponentsInChildren(true) - ) - graphic.raycastTarget = false; - } - - public bool Reveal(GameObject root) - { - if (!_visibility.TryGetValue(root, out var state) || state.Group == null) - return false; - state.Group.alpha = 1f; - return true; - } - - public void BeforeRelease(NativeCardPreviewOwnerContext context) - { - if (_visibility.Remove(context.Root, out var state) && state.Group != null) - state.Group.alpha = state.Alpha; - var marker = context.Root.GetComponent(); - if (marker != null) - { - marker.ReleaseCachedArt(context.Root.GetComponent()); - } - // Keep the neutral component until the pooled root is destroyed. Deferred - // Destroy could remove a new lease's alpha gate after same-frame reuse. - } - - public void ReportFailure(NativeCardPreviewFailure failure) - { - if (failure.Exception != null) - Report(failure.Exception); - } - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionState.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionState.cs deleted file mode 100644 index 7679e0a..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionInspectionState.cs +++ /dev/null @@ -1,29 +0,0 @@ -#nullable enable -namespace BazaarPlusPlus.Game.CollectionPanel; - -// Generation and input-release decisions stay independent of Unity and async completion order. -internal sealed class CollectionInspectionState -{ - private int _revision; - private int _releasedFrame = -1; - public bool IsOpen { get; private set; } - - public int Open() - { - IsOpen = true; - return ++_revision; - } - - public int Select() => ++_revision; - - public bool CanPublish(int revision) => IsOpen && revision == _revision; - - public void Close(int frame) - { - IsOpen = false; - ++_revision; - _releasedFrame = frame; - } - - public bool BlocksInput(int frame) => IsOpen || frame <= _releasedFrame; -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanel.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanel.cs deleted file mode 100644 index 3559746..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanel.cs +++ /dev/null @@ -1,957 +0,0 @@ -#nullable enable -using System.Collections; -using BazaarGameShared.Domain.Core.Types; -using BazaarPlusPlus.Core.Config; -using BazaarPlusPlus.Core.GameState; -using BazaarPlusPlus.Core.Runtime; -using BazaarPlusPlus.Game.CollectionPanel.Data; -using BazaarPlusPlus.Game.CollectionPanel.Grid; -using BazaarPlusPlus.Game.CollectionPanel.Sources; -using BazaarPlusPlus.Game.CollectionPanel.Ui; -using BazaarPlusPlus.Game.Input; -using BazaarPlusPlus.Game.OverlayPanels; -using BazaarPlusPlus.Game.Supporters; -using BazaarPlusPlus.GameInterop; -using BazaarPlusPlus.GameInterop.CardPreview; -using BazaarPlusPlus.GameInterop.DayTiers; -using BazaarPlusPlus.GameInterop.StaticCards; -using BazaarPlusPlus.GameInterop.TagTypography; -using BazaarPlusPlus.Infrastructure; -using BazaarPlusPlus.Infrastructure.Logging; -using UnityEngine; -using UnityEngine.InputSystem; -using UnityEngine.InputSystem.LowLevel; - -namespace BazaarPlusPlus.Game.CollectionPanel; - -// Not a MonoBehaviour on purpose: ClassInjector cannot project a component whose methods take -// managed-only parameter types, and such a component fails to register as a whole. -internal sealed class CollectionPanel -{ - /// Host transform, supplied by the mount; the class is not a component. - internal Transform Root { get; set; } = null!; - - private const float CatalogBuildFrameBudgetMs = 4f; - private const float CatalogWarmupFrameBudgetMs = 1f; - private const string OverlayPanelId = "CollectionPanel"; - - private static CollectionPanel? _instance; - public static bool IsVisible => _instance != null && _instance._isVisible; - - /// Opens or closes this panel from the on-screen entry (no keyboard on Android). - internal static void ToggleFromUi() - { - var instance = _instance; - if (instance == null) - { - BppStartupTrace.Write("toggle:no-instance"); - return; - } - if (instance._overlayHandle == null) - { - BppStartupTrace.Write("toggle:no-handle"); - return; - } - - if (instance._overlayHandle.IsVisible) - { - var closed = instance._overlayHandle.RequestClose(); - BppStartupTrace.Write("toggle:close " + closed); - } - else - { - var opened = instance._overlayHandle.RequestOpen(); - BppStartupTrace.Write("toggle:open " + opened); - } - } - - internal static CollectionPanel? Instance => _instance; - - private CollectionCatalog _catalog = null!; - private Keyboard? _imeKeyboard; - private bool _isImeComposing; - private readonly ICollectionPanelHeroPreferenceStore _heroPreferenceStore = - new CollectionPanelHeroPreferenceStore(); - private readonly CollectionPanelSelectionLogState _selectionLogState = new(); - private readonly CollectionGridPortAdapter _gridPort = new(); - private CollectionViewState _viewState = null!; - - private BppConfig _config = null!; - private INativeCardPreviewHost _nativeCardPreviewHost = null!; - private CollectionInspectionModule _inspection = null!; - private readonly CollectionInspectionClick _inspectionClick = new(); - private IGameDataDayTierResolver _dayTierResolver = null!; - private CollectionPanelView? _view; - private CollectionGridOverlay? _overlay; - private INativeCardPreviewScope? _previewScope; - private CollectionGridVirtualizer? _virtualizer; - private CollectionCardArtCache? _artCache; - private CollectionCardMaterialCache? _materialCache; - private CollectionCardCacheSession? _cacheSession; - - private IBppServices _services = null!; - private IOverlayPanelHandle? _overlayHandle; - private bool _isVisible; - private bool _initialized; - private bool _viewportBoundsDirty; - private Rect _viewportBoundsPx; - private float _scrollY; - private Coroutine? _loadCoroutine; - private int _loadGeneration; - - // True when the last render ran before the game's async tooltip typography registration - // completed: tag chips rendered degraded (string-table labels, no accent color) and nothing - // else would re-render them without user interaction. Update polls for the typography - // instance and re-renders once, so the startup window self-heals. - private bool _viewMissedNativeTypography; - private bool _sourceCatalogWarmed; - private bool _stagingItemIdCopyEnabled; - - /// - /// Static, not an instance method: ClassInjector builds an IL2CPP trampoline for every instance - /// method and cannot convert a managed-only parameter type, which fails the whole component - /// registration. Static methods are not projected, so the dependencies travel here. - /// - internal static void InitializeInstance( - CollectionPanel panel, - IBppServices services, - BppStaticCardMapProvider cardMapProvider, - INativeCardPreviewHost nativeCardPreviewHost, - IGameDataDayTierResolver dayTierResolver, - CollectionInspectionModule inspection - ) - { - panel.InitializeCore( - services, - cardMapProvider, - nativeCardPreviewHost, - dayTierResolver, - inspection - ); - } - - private void InitializeCore( - IBppServices services, - BppStaticCardMapProvider cardMapProvider, - INativeCardPreviewHost nativeCardPreviewHost, - IGameDataDayTierResolver dayTierResolver, - CollectionInspectionModule inspection - ) - { - if (_initialized) - return; - if (services == null) - throw new ArgumentNullException(nameof(services)); - if (cardMapProvider == null) - throw new ArgumentNullException(nameof(cardMapProvider)); - if (nativeCardPreviewHost == null) - throw new ArgumentNullException(nameof(nativeCardPreviewHost)); - if (dayTierResolver == null) - throw new ArgumentNullException(nameof(dayTierResolver)); - - _initialized = true; - _instance = this; - _services = services; - _config = services.Config; - _stagingItemIdCopyEnabled = CollectionStagingTools.IsEnabled(services.GameBuild.RawVersion); - _nativeCardPreviewHost = nativeCardPreviewHost; - _inspection = inspection; - _inspection.Attach( - nativeCardPreviewHost, - SetInspectionBlocked, - () => _virtualizer?.HoveredScreenRect() ?? default - ); - _dayTierResolver = dayTierResolver; - _catalog = new CollectionCatalog(cardMapProvider); - _viewState = new CollectionViewState( - _gridPort, - new StaticCollectionSourceCatalog(), - dayTierResolver, - _heroPreferenceStore - ); - } - - internal void AttachToOverlayHost(OverlayPanelHost overlayHost) - { - if (_overlayHandle != null) - return; - - _overlayHandle = overlayHost.Register( - new OverlayPanelRegistration( - OverlayPanelId, - BppHotkeyActionId.ToggleCollectionPanel, - onOpen: Open, - onClose: Close, - tick: Tick - ) - { - OnSceneChanged = DisposeUnityRuntime, - HotkeyGuard = () => !IsVisible || !IsTextInputFocused(), - IsModalInputActive = () => _inspection.BlocksInput, - DismissModal = () => _inspection.Close(), - } - ); - } - - private bool IsTextInputFocused() => _view?.IsTextInputFocused() == true; - - private void SetInspectionBlocked(bool blocked) - { - _view?.SetInspectionBlocked(blocked); - _virtualizer?.SetInspectionBlocked(blocked); - if (blocked) - DetachImeKeyboard(); - } - - internal static void NotifyLocaleChanged() - { - if (_instance == null) - return; - _instance.InvalidateCatalog(CollectionPanelLogReasonCode.LocaleChange); - if (_instance._isVisible) - _instance.StartPanelLoad(); - } - - internal static void OpenFromDockButton() - { - if (_instance?._overlayHandle == null) - { - BppLog.ErrorEvent( - new BppLogEvent(BppLogFeatureScope.CollectionPanel, "collection_panel.open.failed"), - ("reason_code", CollectionPanelLogReasonCode.NotMounted) - ); - return; - } - - var outcome = _instance._overlayHandle.RequestOpen(); - switch (outcome) - { - case OverlayRequestOutcome.Executed: - case OverlayRequestOutcome.AlreadyInState: - return; - case OverlayRequestOutcome.SuppressedByCombat: - BppLog.DebugEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.open.skipped" - ), - static () => [("reason_code", CollectionPanelLogReasonCode.CombatActive)] - ); - return; - case OverlayRequestOutcome.UnknownPanel: - default: - BppLog.ErrorEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.open.failed" - ), - ("reason_code", CollectionPanelLogReasonCode.UnknownPanel) - ); - return; - } - } - - private void Open() - { - var resolved = ResolveOpenSelection(); - Open(resolved.Selection, resolved.CurrentRunDay, resolved.EncounteredMerchantSourceKeys); - } - - private ( - CollectionPanelSelectionState Selection, - int? CurrentRunDay, - IReadOnlyList EncounteredMerchantSourceKeys - ) ResolveOpenSelection() - { - PrepareCatalogReadinessForOpen(); - var failures = new List(4); - var isInGameRun = TryReadIsInGameRunForOpen(failures); - var rememberedPreference = isInGameRun - ? null - : _heroPreferenceStore.Load(_viewState.CatalogReadiness, _viewState.AvailableHeroes); - var hero = isInGameRun ? TryReadCurrentHero(failures) : null; - var encounterIds = isInGameRun ? TryReadEncounterIds(failures) : EncounterIdsSnapshot.Empty; - var currentRunDay = isInGameRun ? TryReadCurrentDay(failures) : null; - var sourceEntries = CollectionSourceCatalog.Entries; - var selection = CollectionPanelOpenSelectionResolver.Resolve( - isInGameRun, - hero, - encounterIds.CurrentEncounterTemplateId, - encounterIds.ChoiceSelectionTemplateIds, - sourceEntries, - rememberedPreference - ); - var encounteredMerchantSourceKeys = isInGameRun - ? CollectionPanelOpenSelectionResolver.ResolveEncounteredMerchantSourceKeys( - hero, - encounterIds.ChoiceSelectionTemplateIds, - sourceEntries - ) - : Array.Empty(); - - _selectionLogState.ObserveOpen( - failures.Count == 0 - ? CollectionPanelSelectionOpenObservation.Complete() - : CollectionPanelSelectionOpenObservation.Degraded(failures) - ); - BppLog.DebugEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.selection.resolved" - ), - () => - [ - ("source", selection.SelectedSourceKey), - ("hero", selection.SelectedHero), - ("day", currentRunDay), - ("encounter_id", encounterIds.CurrentEncounterTemplateId), - ] - ); - return (selection, currentRunDay, encounteredMerchantSourceKeys); - } - - private bool TryReadIsInGameRunForOpen(List failures) - { - try - { - return _services.RunContext.IsInGameRun - || _services.GameStateProbe.ComputeIsInGameRun(); - } - catch (Exception ex) - { - failures.Add(Failure(CollectionPanelSelectionProbe.RunState, ex)); - return _services.RunContext.IsInGameRun; - } - } - - private static EHero? TryReadCurrentHero(List failures) - { - try - { - var runHero = TheBazaar.Data.Run?.Player?.Hero; - if (CollectionPanelOpenSelectionResolver.IsConcreteHero(runHero)) - return runHero; - - var selectedHero = TheBazaar.Data.SelectedHero; - return CollectionPanelOpenSelectionResolver.IsConcreteHero(selectedHero) - ? selectedHero - : null; - } - catch (Exception ex) - { - failures.Add(Failure(CollectionPanelSelectionProbe.Hero, ex)); - return null; - } - } - - private static int? TryReadCurrentDay(List failures) - { - try - { - return (int?)TheBazaar.Data.Run?.Day; - } - catch (Exception ex) - { - failures.Add(Failure(CollectionPanelSelectionProbe.Day, ex)); - return null; - } - } - - private EncounterIdsSnapshot TryReadEncounterIds( - List failures - ) - { - try - { - var outcome = _services.EncounterState.GetEncounterIdsOutcome(); - if (outcome.IsSuccess) - return outcome.Snapshot; - - failures.Add( - Failure( - CollectionPanelSelectionProbe.Encounter, - outcome.Exception ?? new InvalidOperationException("Encounter ID probe failed.") - ) - ); - return outcome.Snapshot; - } - catch (Exception ex) - { - failures.Add(Failure(CollectionPanelSelectionProbe.Encounter, ex)); - return EncounterIdsSnapshot.Empty; - } - } - - private static CollectionPanelSelectionProbeFailure Failure( - CollectionPanelSelectionProbe probe, - Exception exception - ) => new(probe, CollectionPanelLogReasonCode.ProbeReadFailed, exception); - - private void Open( - CollectionPanelSelectionState selection, - int? currentRunDay, - IReadOnlyCollection encounteredMerchantSourceKeys - ) - { - _viewState.ResetSearchForLifecycle(); - // Temporary main-path probe: EnsureView() is heavy one-time UITK construction (visual - // tree + CJK glyph raster + cold OTF extract) that runs on the click frame BEFORE the - // panel is shown and is invisible to CollectionPanelLoadDiagnostics (created later in the - // coroutine). Time the first construction so its click-frame cost is attributable. - var firstViewConstruction = _view == null; - var openPrologueDiagnostics = firstViewConstruction - ? new CollectionPanelLoadDiagnostics() - : null; - EnsureView(); - _artCache?.ClearFailedKeys(); - if (firstViewConstruction) - openPrologueDiagnostics!.Complete( - CollectionPanelLoadPhase.OpenPrologue, - CollectionPanelLoadOutcome.Completed, - null - ); - ApplyOutcome( - _viewState.ApplyOpenSelection( - selection, - BPPSupporters.SampleMany(4), - currentRunDay, - encounteredMerchantSourceKeys - ) - ); - _isVisible = true; - // SetVisible starts the fade-in ramp; overlay activates so its CanvasGroup starts - // mirroring the view's opacity (Update pushes the live value each frame). - _view!.SetVisible(true); - _overlay?.SetVisible(true); - _overlay?.SetAlpha(_view!.CurrentOpacity); - StartPanelLoad(); - } - - private void PrepareCatalogReadinessForOpen() - { - if (_catalog.TryGetCached(out var cached)) - { - _viewState.PrepareCatalogForOpen(cached.Cards); - return; - } - - _viewState.PrepareCatalogForOpen(cachedCards: null); - } - - private void Close() - { - if (!_isVisible) - return; - _inspection.Close(); - _viewState.ResetSearchForLifecycle(); - // Cancel a deferred focus requested by the expanded presentation before the fading view - // remains alive for another frame. - ApplyOutcome(_viewState.Rebuild()); - // Drop composition state with the panel: a composition whose terminating Count==0 - // event never arrives would otherwise keep Advance() blocked after the next Open(). - DetachImeKeyboard(); - CancelPanelLoad(); - _isVisible = false; - HideNativeCardLayerImmediately(); - // Let the UITK chrome fade out, but do not keep the native card overlay alive during - // that animation. CardPreviewBase instances live on a sibling ScreenSpaceOverlay canvas, - // so delaying its teardown leaves visible card art after the panel has been dismissed. - _view?.SetVisible(false); - } - - private void RequestCloseFromUi() - { - if (_overlayHandle == null) - { - Close(); - return; - } - - // The visible close button is a lifecycle request, not just a local hide. If this - // bypasses the host, the dock button's later RequestOpen() sees the panel as still open. - var outcome = _overlayHandle.RequestClose(); - if (outcome == OverlayRequestOutcome.AlreadyInState && _isVisible) - Close(); - } - - // Lifecycle (scene change, combat gate, hotkey, escape) is owned by the Overlay Panel Host; - // this tick carries the panel's own per-frame content work, including closed-state work - // (fade-out completion, catalog warmup, deferred native cleanup). - private void Tick(float dt, bool isVisible) - { - _inspection.Tick(dt); - // Warm the shared card map and catalog while the panel is closed. Card-map acquisition - // runs on the provider's worker task; catalog projection stays on the main thread but is - // capped to a small closed-state budget. An open panel raises the budget and consumes the - // same build session, so the first click never starts a duplicate full-table walk. - _catalog.AdvanceBuild( - isVisible ? CatalogBuildFrameBudgetMs : CatalogWarmupFrameBudgetMs, - out _ - ); - if (!_sourceCatalogWarmed) - { - _ = CollectionSourceCatalog.Entries; - _sourceCatalogWarmed = true; - } - - // Drive the panel fade every frame regardless of _isVisible so a Close mid-frame - // can finish its fade-out animation before we tear runtime down. - _view?.TickOpacity(dt); - _view?.TickLoading(dt); - _view?.TickControlsScrollShadow(); - if (_view != null && _overlay != null) - _overlay.SetAlpha(_view.CurrentOpacity); - - if (!_isVisible) - { - _inspectionClick.Reset(); - // Close() already hides the native card layer synchronously. Keep this as an - // idempotent cleanup fallback once the remaining UITK fade-out has settled. - if (_view != null && !_view.IsFadingOrVisible) - { - _overlay?.SetVisible(false); - _virtualizer?.Dispose(); - } - return; - } - - if (_inspection.BlocksInput) - { - _inspectionClick.Reset(); - return; - } - - ApplyOutcome(_viewState.TickSearch(dt, isComposing: IsImeCompositionActive())); - - // Startup self-heal for tag typography: a refresh that ran inside the game's async - // typography registration window rendered degraded chips, and no further Refresh - // arrives without user interaction. Re-render once the instance appears (the check is - // a static null probe per frame; ApplyOutcome clears the flag). - if (_viewMissedNativeTypography && NativeTagTypography.IsNativeTypographyAvailable) - ApplyOutcome(_viewState.Rebuild()); - - if (_viewportBoundsDirty && _virtualizer != null && _overlay != null) - { - _viewportBoundsDirty = false; - _overlay.SetPosition(_viewportBoundsPx.position); - _overlay.SetClipSize(_viewportBoundsPx.size); - _virtualizer.SetViewport(_viewportBoundsPx.width, _viewportBoundsPx.height); - // The base unit (and therefore ContentHeight) is derived from the viewport width, - // so re-publish the scroll-spacer height once real bounds arrive — otherwise the - // first-open estimate computed at the placeholder width leaves the bottom rows - // unreachable. Viewport-driven projection drift stays panel-owned (grid port contract). - _view?.UpdateContentSpacerHeight(_virtualizer.ContentHeight); - } - - // UITK's default wheel handler updates scrollOffset directly; we just read the - // resulting position each frame and feed it to the virtualizer. (An earlier smooth- - // wheel intercept lived here but killed wheel scrolling entirely — see §16.6.) - if (_view != null) - _scrollY = _view.ReadScrollYPixels(); - _virtualizer?.SetScrollY(_scrollY); - _virtualizer?.Tick(); - _virtualizer?.TickFades(dt); - - if (CollectionGridConstants.UsePolledHover && _virtualizer != null) - { - // Pointer covers both the mouse and a touchscreen, so the same hover/click path runs - // on desktop and on the Android build. - var pointer = UnityEngine.InputSystem.Pointer.current; - if (pointer != null) - { - var pos = pointer.position.ReadValue(); - _virtualizer.PollHover(pos, _viewportBoundsPx); - TryCopyHoveredCardId(); - TryOpenHoveredInspection(pointer, pos); - } - else - _inspectionClick.Reset(); - } - _virtualizer?.TickHoverScale(dt); - } - - private void TryOpenHoveredInspection(UnityEngine.InputSystem.Pointer pointer, Vector2 position) - { - if (!Application.isFocused) - { - _inspectionClick.Reset(); - return; - } - Guid? id = - _virtualizer != null && _virtualizer.TryGetHoveredCard(out var card) ? card.Id : null; - if ( - _inspectionClick.Sample( - pointer.press.wasPressedThisFrame, - pointer.press.wasReleasedThisFrame, - id, - position.x, - position.y, - _scrollY - ) - && id.HasValue - ) - _inspection.OpenHovered(id.Value); - } - - private void TryCopyHoveredCardId() - { - if ( - !_stagingItemIdCopyEnabled - || IsTextInputFocused() - || _virtualizer == null - || !_virtualizer.TryGetHoveredCard(out var card) - ) - return; - - var keyboard = Keyboard.current; - if ( - keyboard?.cKey.wasPressedThisFrame != true - || (keyboard.leftCtrlKey.isPressed || keyboard.rightCtrlKey.isPressed) != true - ) - return; - - var templateId = card.Id.ToString("D"); - GUIUtility.systemCopyBuffer = templateId; - _view?.ShowStagingTemplateIdCopied(card.DisplayName, templateId); - } - - private void HideNativeCardLayerImmediately() - { - _virtualizer?.Dispose(); - _overlay?.SetAlpha(0f); - _overlay?.SetVisible(false); - } - - /// Called by the mount; the class is not a component so Unity does not do it. - internal void Dispose() - { - _inspection?.Detach(); - DetachImeKeyboard(); - if (ReferenceEquals(_instance, this)) - _instance = null; - _overlayHandle?.Dispose(); - _overlayHandle = null; - DisposeRuntime(); - } - - private bool IsImeCompositionActive() - { - var keyboard = Keyboard.current; - if (ReferenceEquals(_imeKeyboard, keyboard)) - return _isImeComposing; - - DetachImeKeyboard(); - _imeKeyboard = keyboard; -#if !BPP_ANDROID - if (_imeKeyboard != null) - _imeKeyboard.onIMECompositionChange += OnImeCompositionChange; -#endif - return false; - } - - private void OnImeCompositionChange(IMECompositionString composition) => - _isImeComposing = composition.Count > 0; - - private void DetachImeKeyboard() - { -#if !BPP_ANDROID - if (_imeKeyboard != null) - _imeKeyboard.onIMECompositionChange -= OnImeCompositionChange; -#endif - _imeKeyboard = null; - _isImeComposing = false; - } - - private void DisposeRuntime() - { - InvalidateCatalog(CollectionPanelLogReasonCode.RuntimeDispose); - DisposeUnityRuntime(); - } - - private void DisposeUnityRuntime() - { - _inspection?.Close(); - _viewState.ResetSearchForLifecycle(); - CancelPanelLoad(); - var virtualizer = _virtualizer; - var overlay = _overlay; - var previewScope = _previewScope; - var artCache = _artCache; - var materialCache = _materialCache; - var cacheSession = _cacheSession; - - virtualizer?.Dispose(); - overlay?.SetAlpha(0f); - overlay?.SetVisible(false); - - _virtualizer = null; - _gridPort.Bind(null); - _previewScope = null; - _overlay = null; - _view?.Dispose(); - _view = null; - _materialCache = null; - _artCache = null; - _cacheSession = null; - - var previewCleanup = previewScope?.DisposeAsync().AsTask() ?? Task.CompletedTask; - var cleanupBarrier = Task.WhenAll( - virtualizer?.WhenPendingBindsSettled ?? Task.CompletedTask, - previewCleanup - ); - if (cleanupBarrier.IsCompletedSuccessfully) - { - DestroyCollectionRuntimeObjects(overlay, cacheSession, artCache, materialCache); - return; - } - - _ = DestroyCollectionRuntimeObjectsWhenReadyAsync( - cleanupBarrier, - overlay, - cacheSession, - artCache, - materialCache - ); - } - - private static async Task DestroyCollectionRuntimeObjectsWhenReadyAsync( - Task cleanupBarrier, - CollectionGridOverlay? overlay, - CollectionCardCacheSession? cacheSession, - CollectionCardArtCache? artCache, - CollectionCardMaterialCache? materialCache - ) - { - try - { - await cleanupBarrier; - } - catch (Exception ex) - { - BppLog.WarnEvent( - new BppLogEvent( - BppLogFeatureScope.CollectionPanel, - "collection_panel.cleanup.degraded", - storm: ["reason_code"] - ), - ex, - ("reason_code", CollectionPanelLogReasonCode.PendingBindWaitFailed) - ); - } - - DestroyCollectionRuntimeObjects(overlay, cacheSession, artCache, materialCache); - } - - private static void DestroyCollectionRuntimeObjects( - CollectionGridOverlay? overlay, - CollectionCardCacheSession? cacheSession, - CollectionCardArtCache? artCache, - CollectionCardMaterialCache? materialCache - ) - { - // Scope disposal synchronously releases each card's feature-owned tooltip/art/material - // state before scheduling its GameObject destruction, so cache teardown is now safe. - overlay?.Dispose(); - CollectionCardCacheHost.Uninstall(cacheSession); - materialCache?.DisposeAll(); - artCache?.DisposeAll(); - } - - private void EnsureView() - { - if (_view != null) - { - _view.EnsureCreated(); - return; - } - - _view = new CollectionPanelView(Root, new PanelCommands(this), _stagingItemIdCopyEnabled); - - _view.GridViewportBoundsChanged += bounds => - { - _viewportBoundsPx = bounds; - _viewportBoundsDirty = true; - }; - - _view.EnsureCreated(); - - _overlay = new CollectionGridOverlay(); - _overlay.EnsureInitialized(); - - _artCache = new CollectionCardArtCache(); - _materialCache = new CollectionCardMaterialCache(); - _cacheSession = CollectionCardCacheHost.Install(_artCache, _materialCache); - - var previewOwner = new CollectionNativeCardPreviewOwner(_overlay.BoardRoot!, _cacheSession); - _previewScope = _nativeCardPreviewHost.OpenScope(previewOwner); - _virtualizer = new CollectionGridVirtualizer(_overlay, _previewScope); - _gridPort.Bind(_virtualizer); - } - - private sealed class PanelCommands(CollectionPanel panel) : ICollectionPanelCommands - { - public void Close() => panel.RequestCloseFromUi(); - - public void ToggleSearch() => panel.ApplyOutcome(panel._viewState.ToggleSearch()); - - public void SetActiveTab(CollectionTabKind tab) => - panel.ApplyOutcome(panel._viewState.SetActiveTab(tab)); - - public void ResetFilters() => panel.ApplyOutcome(panel._viewState.ResetFilters()); - - public void ToggleHero(EHero hero) => panel.ApplyOutcome(panel._viewState.ToggleHero(hero)); - - public void ToggleAllHeroes() => panel.ApplyOutcome(panel._viewState.ToggleAllHeroes()); - - public void ToggleTier(ETier tier) => panel.ApplyOutcome(panel._viewState.ToggleTier(tier)); - - public void ToggleRunDayFilter() => - panel.ApplyOutcome(panel._viewState.ToggleRunDayFilter()); - - public void ToggleSize(ECardSize size) => - panel.ApplyOutcome(panel._viewState.ToggleSize(size)); - - public void ToggleTag(ECardTag tag) => panel.ApplyOutcome(panel._viewState.ToggleTag(tag)); - - public void ToggleKeyword(CollectionKeywordFacetOption option) => - panel.ApplyOutcome(panel._viewState.ToggleKeyword(option)); - - public void SetKeywordMatchMode(CollectionFacetMatchMode mode) => - panel.ApplyOutcome(panel._viewState.SetKeywordMatchMode(mode)); - - public void SetTagMatchMode(CollectionFacetMatchMode mode) => - panel.ApplyOutcome(panel._viewState.SetTagMatchMode(mode)); - - public void ToggleSource(string sourceKey) => - panel.ApplyOutcome(panel._viewState.ToggleSource(sourceKey)); - - public void SetSortPriority(CollectionSortPriority priority) => - panel.ApplyOutcome(panel._viewState.SetSortPriority(priority)); - - public void SetSearchQuery(string query) => panel._viewState.SetSearchQuery(query); - } - - private void ApplyOutcome(object? outcomeObject) - { - // object, not the managed class: ClassInjector cannot convert a managed-only parameter - // to IL2CPP and fails the whole component registration. - if (outcomeObject is not CollectionRenderOutcome outcome) - return; - - if (outcome.ResetScroll) - { - _view?.ResetScroll(); - _scrollY = 0f; - } - - if (outcome.ResetControlsScroll) - _view?.ResetControlsScroll(); - - // Record whether this render has native typography; while it does not, Update polls for - // the late async registration and re-renders so the degraded chips self-heal. Written - // BEFORE the render: typography registration is a main-thread continuation that cannot - // interleave with the synchronous Refresh below, so the value is identical either way, - // and writing first keeps a throwing Refresh from leaving the flag armed (which would - // turn a one-shot failure into a per-frame retry). - _viewMissedNativeTypography = !NativeTagTypography.IsNativeTypographyAvailable; - _view?.Refresh(outcome.Model); - } - - private void StartPanelLoad() - { - CancelPanelLoad(); - var generation = ++_loadGeneration; - _loadCoroutine = BppCoroutines.Start(this, LoadPanelAsync(generation)); - } - - private void CancelPanelLoad() - { - _loadGeneration++; - if (_loadCoroutine != null) - { - BppCoroutines.Stop(this, _loadCoroutine); - _loadCoroutine = null; - } - _viewState?.NoteCatalogLoadCancelled(); - } - - private IEnumerator LoadPanelAsync(int generation) - { - var diagnostics = new CollectionPanelLoadDiagnostics(); - ApplyOutcome(_viewState.BeginCatalogLoad()); - - yield return null; - - if (!IsLoadGenerationCurrent(generation)) - yield break; - - var started = diagnostics.Now(); - CollectionCatalogBuildResult? catalogResult = null; - CollectionPanelLogReasonCode? unavailableReason = null; - CollectionRenderOutcome? acceptOutcome = null; - while (true) - { - if (_catalog.TryGetCached(out var cached)) - { - catalogResult = cached; - acceptOutcome = _viewState.AcceptCatalog(cached.Cards); - break; - } - - if (_catalog.WarmupStatus == CollectionCatalogWarmupStatus.Unavailable) - { - unavailableReason = _catalog.WarmupFailureReason; - acceptOutcome = _viewState.CatalogUnavailable(); - break; - } - - if (!IsLoadGenerationCurrent(generation)) - yield break; - yield return null; - } - diagnostics.AddSegment(CollectionPanelLoadSegment.Catalog, started); - if (catalogResult != null) - { - diagnostics.SetCatalogResult( - catalogResult.WasCacheHit, - catalogResult.SourceTemplateCount, - catalogResult.AcceptedCount, - catalogResult.RejectedCount - ); - } - - if (!IsLoadGenerationCurrent(generation)) - yield break; - - // AcceptCatalog/CatalogUnavailable fold the prior Filter + Refresh segments into one - // query-and-render (allowed measurement micro-shift; event schema unchanged). - started = diagnostics.Now(); - ApplyOutcome(acceptOutcome); - diagnostics.AddSegment(CollectionPanelLoadSegment.Filter, started); - diagnostics.AddSegment(CollectionPanelLoadSegment.Refresh, started); - diagnostics.SetFinalCounts(_viewState.CatalogCardCount, _gridPort.Current.VisibleCount); - diagnostics.Complete( - CollectionPanelLoadPhase.PanelLoad, - _viewState.CatalogCardCount > 0 - ? CollectionPanelLoadOutcome.Loaded - : CollectionPanelLoadOutcome.Unavailable, - unavailableReason - ); - _loadCoroutine = null; - } - - private bool IsLoadGenerationCurrent(int generation) => - generation == _loadGeneration && _isVisible; - - private void InvalidateCatalog(CollectionPanelLogReasonCode reasonCode) - { - // The cause behind a suppressed artKey may be exactly what changed (a locale swap changes - // which keys exist, a cold catalog may have warmed). Drop the suppression before the reset - // below so the cards rebound by the following load get a real attempt instead of staying - // blank for the TTL. Invalidation runs only on locale change and runtime dispose, never per - // frame; DisposeAll already clears the same map on teardown, so the null case is a no-op. - _artCache?.ClearFailedKeys(); - _viewState.ResetCatalog(); - _catalog.InvalidateCache(reasonCode); - } -} diff --git a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanelDockButtonController.cs b/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanelDockButtonController.cs deleted file mode 100644 index 999d685..0000000 --- a/bazaarplusplus-mod/src/BazaarPlusPlus/Game/CollectionPanel/CollectionPanelDockButtonController.cs +++ /dev/null @@ -1,236 +0,0 @@ -#nullable enable -using BazaarPlusPlus.GameInterop; -using BazaarPlusPlus.Game.Settings; -using BazaarPlusPlus.GameInterop.Scenes; -using BazaarPlusPlus.Infrastructure; -using BazaarPlusPlus.Infrastructure.Logging; -using UnityEngine; -using UnityEngine.UI; - -namespace BazaarPlusPlus.Game.CollectionPanel; - -internal sealed class CollectionPanelDockButtonController - : MonoBehaviour, - IBppNativeSettingsButtonCloneOwner -{ - private const int ScreenResizeSyncFrameCount = 6; - private const int LayoutImmediateSyncFrameCount = 2; - - private Button? _anchorButton; - private Button? _dockButton; - private RectTransform? _dockButtonRect; - private readonly BppScreenResizeSyncTracker _screenResizeSync = new(ScreenResizeSyncFrameCount); - private readonly BppDockLayoutSyncTracker _layoutSync = new(LayoutImmediateSyncFrameCount); - private readonly BppDockButtonScreenLayout _screenLayout = new(); - private readonly CollectionPanelDockLayoutLogState _layoutLogState = new(); - private bool _hasAvailableDockLayout; - private int _screenshotSuppressionCount; - - internal RectTransform? DockButtonRect => _dockButtonRect; - - internal void SetLayoutAvailable(bool available) - { - _hasAvailableDockLayout = available; - ApplyScreenshotSuppressionVisibility(); - } - - internal static void Attach(Button anchorButton, BppSettingsDockPlacement placement) - { - if (anchorButton == null) - return; - - var existingController = anchorButton.GetComponent(); - if (existingController != null && existingController._dockButtonRect != null) - { - existingController.SyncDockButtonPlacement(); - return; - } - - var dockButton = BppNativeSettingsButtonClone.FindOrCreate(anchorButton, placement); - if (dockButton == null) - return; - - var controller = - existingController - ?? anchorButton.gameObject.AddComponent(); - controller.Initialize(anchorButton, placement, dockButton); - } - - internal static IDisposable? BeginScreenshotSuppression() - { - var controllers = FindObjectsOfType( - includeInactive: true - ); - if (controllers.Length == 0) - return null; - - var suppressionActions = new Func[controllers.Length]; - for (var index = 0; index < controllers.Length; index++) - suppressionActions[index] = controllers[index].BeginInstanceScreenshotSuppression; - - return UiSuppressionScope.Begin(suppressionActions); - } - - private void Initialize( - Button anchorButton, - BppSettingsDockPlacement placement, - RectTransform dockButton - ) - { - _anchorButton = anchorButton; - _dockButtonRect = dockButton; - _dockButton = dockButton.GetComponent