"""Prepare library-only copies without changing any original AVM2 code bytes.""" from __future__ import annotations from collections import Counter import hashlib import struct import zlib def digest(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def unpack_swf(data: bytes) -> bytes: if len(data) < 13 or data[:3] not in (b"FWS", b"CWS"): raise ValueError("Expected FWS/CWS SWF") result = data if data[:3] == b"FWS" else b"FWS" + data[3:8] + zlib.decompress(data[8:]) if len(result) != struct.unpack_from("> 3) + 7) // 8 + 4 position = start while position < len(data): if position + 2 > len(data): raise ValueError("Truncated SWF tag") header = struct.unpack_from("> 6, header & 63 position += 2 if size == 63: if position + 4 > len(data): raise ValueError("Truncated long SWF tag") size = struct.unpack_from(" len(data): raise ValueError("Truncated SWF tag payload") yield code, data[position:position + size] position += size if code == 0: if size != 0 or position != len(data): raise ValueError("Invalid SWF end tag") return raise ValueError("Missing SWF end tag") def encode_tag(code: int, data: bytes) -> bytes: size = len(data) return (struct.pack("= 63 else b"") + data) def symbols(data: bytes) -> list[tuple[int, bytes]]: if len(data) < 2: raise ValueError("Truncated SymbolClass tag") count = struct.unpack_from(" len(data): raise ValueError("Truncated SymbolClass entry") symbol_id = struct.unpack_from(" tuple[bytes, dict]: """Drop document bindings, make DoABC lazy, reject executable timelines. DoABC's flags/name are SWF metadata, outside the ABC payload. All ABC bytes (including checks, methods, skills, callbacks and static initializers) remain identical and ordered. Lazy loading prevents unrelated script initializers from running just because a library was loaded. """ raw = unpack_swf(original) start = 8 + (5 + 4 * (raw[8] >> 3) + 7) // 8 + 4 output = bytearray(raw[:start]) roots, code_hashes, lazy_changed = [], [], 0 counts = Counter() for code, payload in tags(raw): counts[code] += 1 if code in (12, 59, 72, 57, 71): raise ValueError(f"Unsupported executable/import SWF tag {code}") if code == 76: entries = symbols(payload) roots.extend(name.decode("utf-8") for sid, name in entries if sid == 0) entries = [(sid, name) for sid, name in entries if sid != 0] payload = struct.pack("