mirror of
https://github.com/blitzkit/blitzkit.git
synced 2026-11-24 06:34:18 +01:00
add 7z in-memory streaming
This commit is contained in:
28 files changed
+930
-225
No files matched your search
+1
-1
Submodule packages/closed updated: 182fcdb273...c7ba70c33b.
@@ -7,6 +7,7 @@
|
||||
"@blitzkit/i18n": "workspace:*",
|
||||
"@blitzkit/protos": "workspace:*",
|
||||
"@bufbuild/protobuf": "^2.9.0",
|
||||
"@napi-rs/lzma": "^1.5.3",
|
||||
"@octokit/plugin-throttling": "^11.0.1",
|
||||
"@octokit/rest": "^22.0.0",
|
||||
"@types/adm-zip": "^0.5.7",
|
||||
|
||||
+14
-16
@@ -5,45 +5,45 @@ import {
|
||||
WGC_CLIENT_URL,
|
||||
WGC_METADATA_PROTOCOL_VERSION,
|
||||
WGC_PATCHES_CHAIN_PROTOCOL_VERSION,
|
||||
} from "../../config/wgcClient";
|
||||
import { downloadWgParts } from "../wgpkg";
|
||||
import { ClientMetadata, PatchesChain } from "./types";
|
||||
} from "../config/wgcClient";
|
||||
import type { WGCClientMetadata, WGCPatchesChain } from "../types/wgcClient";
|
||||
|
||||
const parser = new XMLParser();
|
||||
|
||||
export async function downloadWGCClient() {
|
||||
// Base url of the latest full client's 7z volumes, without the .001 suffix
|
||||
export async function fetchWGCClientSource() {
|
||||
const metadataUrl = new URL("api/v1/metadata", WGC_CLIENT_URL);
|
||||
|
||||
metadataUrl.searchParams.set("guid", WGC_CLIENT_GUID);
|
||||
metadataUrl.searchParams.set("chain_id", "unknown");
|
||||
metadataUrl.searchParams.set(
|
||||
"protocol_version",
|
||||
WGC_METADATA_PROTOCOL_VERSION,
|
||||
WGC_METADATA_PROTOCOL_VERSION
|
||||
);
|
||||
|
||||
const metadata = await fetch(`${metadataUrl}`)
|
||||
.then((response) => response.text())
|
||||
.then((text) => parser.parse(text) as Promise<ClientMetadata>);
|
||||
.then((text) => parser.parse(text) as WGCClientMetadata);
|
||||
|
||||
const patchesChainUrl = new URL("api/v1/patches_chain", WGC_CLIENT_URL);
|
||||
|
||||
patchesChainUrl.searchParams.set(
|
||||
"protocol_version",
|
||||
WGC_PATCHES_CHAIN_PROTOCOL_VERSION,
|
||||
WGC_PATCHES_CHAIN_PROTOCOL_VERSION
|
||||
);
|
||||
patchesChainUrl.searchParams.set("client_type", "full");
|
||||
patchesChainUrl.searchParams.set("lang", locales.default);
|
||||
patchesChainUrl.searchParams.set(
|
||||
"metadata_version",
|
||||
`${metadata.protocol.version}`,
|
||||
`${metadata.protocol.version}`
|
||||
);
|
||||
patchesChainUrl.searchParams.set(
|
||||
"metadata_protocol_version",
|
||||
WGC_METADATA_PROTOCOL_VERSION,
|
||||
WGC_METADATA_PROTOCOL_VERSION
|
||||
);
|
||||
patchesChainUrl.searchParams.set(
|
||||
"chain_id",
|
||||
metadata.protocol.predefined_section.chain_id,
|
||||
metadata.protocol.predefined_section.chain_id
|
||||
);
|
||||
patchesChainUrl.searchParams.set("game_installation", "true");
|
||||
patchesChainUrl.searchParams.set("game_id", WGC_CLIENT_GUID);
|
||||
@@ -51,12 +51,10 @@ export async function downloadWGCClient() {
|
||||
|
||||
const patchesChain = await fetch(`${patchesChainUrl}`)
|
||||
.then((response) => response.text())
|
||||
.then((text) => parser.parse(text) as Promise<PatchesChain>);
|
||||
.then((text) => parser.parse(text) as WGCPatchesChain);
|
||||
|
||||
const urls = patchesChain.protocol.patches_chain.patch.files.file.map(
|
||||
(file) =>
|
||||
new URL(file.name, patchesChain.protocol.web_seeds.url).toString(),
|
||||
);
|
||||
const firstVolume = patchesChain.protocol.patches_chain.patch.files.file[0];
|
||||
const url = new URL(firstVolume.name, patchesChain.protocol.web_seeds.url);
|
||||
|
||||
await downloadWgParts(urls);
|
||||
return `${url}`.replace(/\.001$/, "");
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export * from "./discoveredIdDefinitions";
|
||||
export * from "./emblemURL";
|
||||
export * from "./environment";
|
||||
export * from "./eventManager";
|
||||
export * from "./fetchWGCClientSource";
|
||||
export * from "./getTimeDaysAgo";
|
||||
export * from "./isExplosive";
|
||||
export * from "./metaSortTank";
|
||||
|
||||
@@ -1,18 +1,33 @@
|
||||
import { assertSecret } from "@blitzkit/core";
|
||||
import { fetchWGCClientSource } from "../fetchWGCClientSource";
|
||||
import { AbstractVFS } from "./abstract";
|
||||
import { LocalVFS } from "./local";
|
||||
import { MixedVFS } from "./mixed";
|
||||
import { SevenZipVFS } from "./sevenZip";
|
||||
import { ZipVFS } from "./zip";
|
||||
|
||||
export async function createClientVFS() {
|
||||
const provider = import.meta.env.CLIENT_PROVIDER;
|
||||
let vfs: AbstractVFS;
|
||||
|
||||
if (import.meta.env.CLIENT_PROVIDER === "zip") {
|
||||
if (provider === "zip") {
|
||||
vfs = new ZipVFS(assertSecret(import.meta.env.CLIENT_SOURCE));
|
||||
} else {
|
||||
} else if (provider === "7z") {
|
||||
vfs = new SevenZipVFS(assertSecret(import.meta.env.CLIENT_SOURCE));
|
||||
} else if (provider === "wgc") {
|
||||
vfs = new SevenZipVFS(await fetchWGCClientSource());
|
||||
} else if (provider === "local") {
|
||||
vfs = new LocalVFS(assertSecret(import.meta.env.CLIENT_DIR));
|
||||
} else {
|
||||
throw new Error(`Unknown client provider: ${provider}`);
|
||||
}
|
||||
|
||||
await vfs.init();
|
||||
// smart dlc patches take precedence over the client
|
||||
const smartDlcDir = import.meta.env.SMART_DLC_DIR;
|
||||
|
||||
return vfs;
|
||||
if (smartDlcDir) {
|
||||
vfs = new MixedVFS([new LocalVFS(smartDlcDir), vfs]);
|
||||
}
|
||||
|
||||
return await vfs.init();
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from "./abstract";
|
||||
export * from "./local";
|
||||
export * from "./mixed";
|
||||
export * from "./sevenZip";
|
||||
export * from "./steam";
|
||||
export * from "./zip";
|
||||
@@ -0,0 +1,228 @@
|
||||
import type { lzma, lzma2 } from "@napi-rs/lzma";
|
||||
import type { crc32 } from "node:zlib";
|
||||
import {
|
||||
SEVEN_ZIP_SIGNATURE_HEADER_SIZE,
|
||||
SevenZipReadStream,
|
||||
type SevenZipCoder,
|
||||
type SevenZipFileInfo,
|
||||
type SevenZipStreamsInfo,
|
||||
} from "../../../streams/sevenZip";
|
||||
import type { HTTPMultiRangeReader } from "./rangeReader";
|
||||
|
||||
const enum Method {
|
||||
LZMA2 = 0x21,
|
||||
LZMA = 0x030101,
|
||||
}
|
||||
|
||||
export interface SevenZipEntry {
|
||||
name: string;
|
||||
isDir: boolean;
|
||||
// -1 for entries without data (directories, empty files)
|
||||
folder: number;
|
||||
}
|
||||
|
||||
export class SevenZipArchive {
|
||||
entries: SevenZipEntry[] = [];
|
||||
private streams: SevenZipStreamsInfo = {
|
||||
packPos: 0,
|
||||
packSizes: [],
|
||||
folders: [],
|
||||
};
|
||||
private packOffsets: number[] = [];
|
||||
private lzma?: typeof lzma;
|
||||
private lzma2?: typeof lzma2;
|
||||
private crc32?: typeof crc32;
|
||||
|
||||
private constructor(private source: HTTPMultiRangeReader) {}
|
||||
|
||||
static async open(source: HTTPMultiRangeReader) {
|
||||
const archive = new SevenZipArchive(source);
|
||||
await archive.init();
|
||||
return archive;
|
||||
}
|
||||
|
||||
async read(entry: SevenZipEntry) {
|
||||
if (entry.folder === -1) return new Uint8Array(0);
|
||||
|
||||
return this.decodeFolder(this.streams, this.packOffsets, entry.folder);
|
||||
}
|
||||
|
||||
private async init() {
|
||||
const napiLzma = await import("@napi-rs/lzma");
|
||||
const zlib = await import("node:zlib");
|
||||
|
||||
this.lzma = napiLzma.lzma;
|
||||
this.lzma2 = napiLzma.lzma2;
|
||||
this.crc32 = zlib.crc32;
|
||||
|
||||
const signature = await this.source.read(
|
||||
0,
|
||||
SEVEN_ZIP_SIGNATURE_HEADER_SIZE,
|
||||
);
|
||||
const { startHeaderCrc, nextHeaderOffset, nextHeaderSize, nextHeaderCrc } =
|
||||
new SevenZipReadStream(signature.buffer).signatureHeader();
|
||||
|
||||
if (this.crc32!(signature.subarray(12)) !== startHeaderCrc) {
|
||||
throw new Error("7z: bad start header CRC");
|
||||
}
|
||||
|
||||
let header = await this.source.read(
|
||||
SEVEN_ZIP_SIGNATURE_HEADER_SIZE + nextHeaderOffset,
|
||||
nextHeaderSize,
|
||||
);
|
||||
|
||||
if (this.crc32!(header) !== nextHeaderCrc) {
|
||||
throw new Error("7z: bad header CRC");
|
||||
}
|
||||
|
||||
while (true) {
|
||||
const parsed = new SevenZipReadStream(header.buffer).header();
|
||||
|
||||
if (!parsed.encoded) {
|
||||
this.streams = parsed.streams;
|
||||
this.packOffsets = this.computePackOffsets(parsed.streams);
|
||||
this.indexEntries(parsed.files);
|
||||
return;
|
||||
}
|
||||
|
||||
header = await this.decodeFolder(
|
||||
parsed.streams,
|
||||
this.computePackOffsets(parsed.streams),
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// files with data fill each folder's unpack streams in order
|
||||
private indexEntries(files: SevenZipFileInfo[]) {
|
||||
const folders = this.streams.folders;
|
||||
let folderIndex = 0;
|
||||
let streamIndex = 0;
|
||||
|
||||
for (const file of files) {
|
||||
if (!file.hasStream) {
|
||||
this.entries.push({ name: file.name, isDir: file.isDir, folder: -1 });
|
||||
continue;
|
||||
}
|
||||
|
||||
while (
|
||||
folderIndex < folders.length &&
|
||||
streamIndex >= folders[folderIndex].numUnpackStreams
|
||||
) {
|
||||
folderIndex++;
|
||||
streamIndex = 0;
|
||||
}
|
||||
|
||||
if (folderIndex === folders.length) {
|
||||
throw new Error("7z: more files than streams");
|
||||
}
|
||||
|
||||
this.entries.push({ name: file.name, isDir: false, folder: folderIndex });
|
||||
streamIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
private computePackOffsets(streams: SevenZipStreamsInfo) {
|
||||
const offsets = [SEVEN_ZIP_SIGNATURE_HEADER_SIZE + streams.packPos];
|
||||
|
||||
for (const size of streams.packSizes) {
|
||||
offsets.push(offsets[offsets.length - 1] + size);
|
||||
}
|
||||
|
||||
return offsets;
|
||||
}
|
||||
|
||||
private async decodeFolder(
|
||||
streams: SevenZipStreamsInfo,
|
||||
packOffsets: number[],
|
||||
index: number,
|
||||
) {
|
||||
const folder = streams.folders[index];
|
||||
|
||||
if (folder.numUnpackStreams !== 1) {
|
||||
throw new Error("7z: solid folders are not supported");
|
||||
}
|
||||
|
||||
// filter chains like bcj only wrap the exes and dlls, which are never read
|
||||
if (folder.coders.length !== 1) {
|
||||
throw new Error(
|
||||
`7z: coder chain ${folder.coders.map((coder) =>
|
||||
coder.method.toString(16),
|
||||
)} is not supported`,
|
||||
);
|
||||
}
|
||||
|
||||
const start = packOffsets[folder.firstPackStream];
|
||||
const packed = await this.source.read(
|
||||
start,
|
||||
packOffsets[folder.firstPackStream + 1] - start,
|
||||
);
|
||||
const data = await this.runCoder(
|
||||
folder.coders[0],
|
||||
packed,
|
||||
folder.unpackSize,
|
||||
);
|
||||
|
||||
if (folder.crc !== undefined && this.crc32!(data) !== folder.crc) {
|
||||
throw new Error(`7z: CRC mismatch for folder ${index}`);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
private async runCoder(
|
||||
coder: SevenZipCoder,
|
||||
input: Uint8Array<ArrayBuffer>,
|
||||
size: number,
|
||||
) {
|
||||
let data: Uint8Array<ArrayBuffer>;
|
||||
|
||||
switch (coder.method) {
|
||||
case Method.LZMA2:
|
||||
data = await this.decodeLZMA2(input, coder.props);
|
||||
break;
|
||||
|
||||
case Method.LZMA:
|
||||
data = this.decodeLZMA(input, coder.props, size);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`7z: unsupported method ${coder.method.toString(16)}`);
|
||||
}
|
||||
|
||||
if (data.length !== size) throw new Error("7z: unpacked size mismatch");
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// 7z stores lzma props apart from the stream, so rebuild the .lzma header around it
|
||||
private decodeLZMA(
|
||||
input: Uint8Array<ArrayBuffer>,
|
||||
props: Uint8Array<ArrayBuffer>,
|
||||
size: number,
|
||||
) {
|
||||
const stream = new Uint8Array(13 + input.length);
|
||||
const view = new DataView(stream.buffer);
|
||||
|
||||
stream.set(props.subarray(0, 5));
|
||||
view.setBigUint64(5, BigInt(size), true);
|
||||
stream.set(input, 13);
|
||||
|
||||
return new Uint8Array(this.lzma!.decompressSync(stream));
|
||||
}
|
||||
|
||||
// raw lzma2 carries no dictionary size, so it comes from the coder's prop byte
|
||||
private async decodeLZMA2(
|
||||
input: Uint8Array<ArrayBuffer>,
|
||||
props: Uint8Array<ArrayBuffer>,
|
||||
) {
|
||||
const bits = props[0];
|
||||
const dictSize =
|
||||
bits === 40 ? 0xffffffff : (2 | (bits & 1)) * 2 ** ((bits >>> 1) + 11);
|
||||
const output = this.lzma2!.decompressStream(new Blob([input]).stream(), {
|
||||
dictSize,
|
||||
});
|
||||
|
||||
return new Uint8Array(await new Response(output).arrayBuffer());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { AbstractVFS } from "../abstract";
|
||||
import { SevenZipArchive, type SevenZipEntry } from "./archive";
|
||||
import { HTTPMultiRangeReader } from "./rangeReader";
|
||||
|
||||
/**
|
||||
* Reads a 7z archive straight from the CDN with HTTP range requests.
|
||||
* Split volumes (.001, .002, ...) are raw byte slices of one archive, so they
|
||||
* are stitched into a single virtual address space.
|
||||
*
|
||||
* Only non-solid archives (one block per file) are supported, so reading a file
|
||||
* costs exactly one range request of its packed size.
|
||||
*/
|
||||
export class SevenZipVFS extends AbstractVFS {
|
||||
entries = new Map<string, SevenZipEntry>();
|
||||
private archive!: SevenZipArchive;
|
||||
|
||||
constructor(private source: string) {
|
||||
super();
|
||||
}
|
||||
|
||||
async _init() {
|
||||
const urls: string[] = [];
|
||||
|
||||
// split volumes are suffixed .001, .002, ... until the cdn 404s
|
||||
for (let index = 1; ; index++) {
|
||||
const url = `${this.source}.${index.toString().padStart(3, "0")}`;
|
||||
const response = await fetch(url, { method: "HEAD" });
|
||||
|
||||
if (response.status === 404) break;
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Wargaming response error status: ${response.status}`);
|
||||
}
|
||||
|
||||
urls.push(url);
|
||||
}
|
||||
|
||||
if (urls.length === 0) throw new Error(`No volumes at ${this.source}`);
|
||||
|
||||
const reader = await new HTTPMultiRangeReader(urls).init();
|
||||
this.archive = await SevenZipArchive.open(reader);
|
||||
|
||||
for (const entry of this.archive.entries) {
|
||||
if (entry.isDir) continue;
|
||||
|
||||
this.entries.set(this.normalizePath!(entry.name), entry);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
async has(path: string) {
|
||||
return this.entries.has(path);
|
||||
}
|
||||
|
||||
async raw(path: string) {
|
||||
console.log(path);
|
||||
const entry = this.entries.get(path);
|
||||
if (!entry) throw new Error(`File not found in 7z: ${path}`);
|
||||
return this.archive.read(entry);
|
||||
}
|
||||
|
||||
async _dir(path: string) {
|
||||
const parentSegments = path.split("/").length;
|
||||
const children = new Set<string>();
|
||||
|
||||
for (const child of this.entries.keys()) {
|
||||
if (!child.startsWith(path) || child === path) continue;
|
||||
|
||||
const childSegments = child.split("/");
|
||||
const nextSegment = childSegments[parentSegments];
|
||||
|
||||
children.add(nextSegment);
|
||||
}
|
||||
|
||||
return Array.from(children);
|
||||
}
|
||||
|
||||
dispose() {}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
interface Volume {
|
||||
url: string;
|
||||
start: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
// Treats several URLs as one contiguous file
|
||||
export class HTTPMultiRangeReader {
|
||||
size = 0;
|
||||
private volumes: Volume[] = [];
|
||||
|
||||
constructor(private urls: string[]) {}
|
||||
|
||||
async init() {
|
||||
const sizes = await Promise.all(
|
||||
this.urls.map(async (url) => {
|
||||
const response = await fetch(url, { method: "HEAD" });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HEAD ${url} failed: ${response.status}`);
|
||||
}
|
||||
|
||||
const size = Number(response.headers.get("content-length"));
|
||||
|
||||
if (!Number.isFinite(size)) {
|
||||
throw new Error(`No content-length for ${url}`);
|
||||
}
|
||||
|
||||
return size;
|
||||
}),
|
||||
);
|
||||
|
||||
let start = 0;
|
||||
|
||||
this.volumes = this.urls.map((url, i) => {
|
||||
const volume = { url, start, size: sizes[i] };
|
||||
start += sizes[i];
|
||||
return volume;
|
||||
});
|
||||
|
||||
this.size = start;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
async read(offset: number, length: number) {
|
||||
const end = offset + length;
|
||||
|
||||
if (offset < 0 || end > this.size) {
|
||||
throw new Error(`Read out of bounds: ${offset}+${length}`);
|
||||
}
|
||||
|
||||
if (length === 0) return new Uint8Array(0);
|
||||
|
||||
const parts: Promise<Uint8Array<ArrayBuffer>>[] = [];
|
||||
|
||||
for (const volume of this.volumes) {
|
||||
const start = Math.max(offset, volume.start);
|
||||
const stop = Math.min(end, volume.start + volume.size);
|
||||
|
||||
if (start >= stop) continue;
|
||||
|
||||
parts.push(
|
||||
this.fetch(volume.url, start - volume.start, stop - volume.start),
|
||||
);
|
||||
}
|
||||
|
||||
const chunks = await Promise.all(parts);
|
||||
|
||||
if (chunks.length === 1) return chunks[0];
|
||||
|
||||
const result = new Uint8Array(length);
|
||||
let cursor = 0;
|
||||
|
||||
for (const chunk of chunks) {
|
||||
result.set(chunk, cursor);
|
||||
cursor += chunk.length;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async fetch(url: string, start: number, stop: number) {
|
||||
const response = await fetch(url, {
|
||||
headers: { Range: `bytes=${start}-${stop - 1}` },
|
||||
});
|
||||
|
||||
if (response.status !== 206) {
|
||||
throw new Error(
|
||||
`Expected 206 for ${url} [${start}, ${stop}), got ${response.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = new Uint8Array(await response.arrayBuffer());
|
||||
|
||||
if (data.length !== stop - start) {
|
||||
throw new Error(
|
||||
`Short read from ${url}: ${data.length} of ${stop - start} bytes`,
|
||||
);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -2,3 +2,4 @@ export * from "./gunTypeOrder";
|
||||
export * from "./skills";
|
||||
export * from "./tankClassOrder";
|
||||
export * from "./treeTypeOrder";
|
||||
export * from "./wgcClient";
|
||||
File renamed without changes.
@@ -6,4 +6,5 @@ export * from "./rts";
|
||||
export * from "./sc2";
|
||||
export * from "./scg";
|
||||
export * from "./scpg";
|
||||
export * from "./sevenZip";
|
||||
export * from "./windows";
|
||||
@@ -0,0 +1,411 @@
|
||||
import { ReadStream } from "./buffer";
|
||||
|
||||
export const SEVEN_ZIP_SIGNATURE_HEADER_SIZE = 32;
|
||||
|
||||
const SIGNATURE = [0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c];
|
||||
|
||||
const enum Id {
|
||||
End = 0x00,
|
||||
Header = 0x01,
|
||||
ArchiveProperties = 0x02,
|
||||
AdditionalStreamsInfo = 0x03,
|
||||
MainStreamsInfo = 0x04,
|
||||
FilesInfo = 0x05,
|
||||
PackInfo = 0x06,
|
||||
UnpackInfo = 0x07,
|
||||
SubStreamsInfo = 0x08,
|
||||
Size = 0x09,
|
||||
CRC = 0x0a,
|
||||
Folder = 0x0b,
|
||||
CodersUnpackSize = 0x0c,
|
||||
NumUnpackStream = 0x0d,
|
||||
EmptyStream = 0x0e,
|
||||
EmptyFile = 0x0f,
|
||||
Name = 0x11,
|
||||
EncodedHeader = 0x17,
|
||||
}
|
||||
|
||||
export interface SevenZipCoder {
|
||||
method: number;
|
||||
numIn: number;
|
||||
numOut: number;
|
||||
props: Uint8Array<ArrayBuffer>;
|
||||
}
|
||||
|
||||
// a folder is one compressed block; only single coder, single file folders are ever decoded
|
||||
export interface SevenZipFolder {
|
||||
coders: SevenZipCoder[];
|
||||
packedCount: number;
|
||||
firstPackStream: number;
|
||||
unpackSize: number;
|
||||
numUnpackStreams: number;
|
||||
crc?: number;
|
||||
}
|
||||
|
||||
export interface SevenZipStreamsInfo {
|
||||
packPos: number;
|
||||
packSizes: number[];
|
||||
folders: SevenZipFolder[];
|
||||
}
|
||||
|
||||
export interface SevenZipFileInfo {
|
||||
name: string;
|
||||
hasStream: boolean;
|
||||
isDir: boolean;
|
||||
}
|
||||
|
||||
export class SevenZipReadStream extends ReadStream {
|
||||
signatureHeader() {
|
||||
const signature = this.consumeUint8Array(SIGNATURE.length);
|
||||
|
||||
if (!SIGNATURE.every((byte, i) => signature[i] === byte)) {
|
||||
throw new Error("Not a 7z archive");
|
||||
}
|
||||
|
||||
// format version
|
||||
this.seek(2);
|
||||
|
||||
return {
|
||||
startHeaderCrc: this.uint32(),
|
||||
nextHeaderOffset: Number(this.uint64()),
|
||||
nextHeaderSize: Number(this.uint64()),
|
||||
nextHeaderCrc: this.uint32(),
|
||||
};
|
||||
}
|
||||
|
||||
header() {
|
||||
const id = this.number();
|
||||
|
||||
switch (id) {
|
||||
case Id.Header:
|
||||
return { encoded: false, ...this.mainHeader() } as const;
|
||||
|
||||
// the real header is itself compressed and stored as a packed stream
|
||||
case Id.EncodedHeader:
|
||||
return { encoded: true, streams: this.streamsInfo() } as const;
|
||||
|
||||
default:
|
||||
throw new Error(`7z: unexpected header id ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
private mainHeader() {
|
||||
let streams: SevenZipStreamsInfo = {
|
||||
packPos: 0,
|
||||
packSizes: [],
|
||||
folders: [],
|
||||
};
|
||||
let files: SevenZipFileInfo[] = [];
|
||||
|
||||
for (let id = this.number(); id !== Id.End; id = this.number()) {
|
||||
switch (id) {
|
||||
case Id.ArchiveProperties:
|
||||
while (this.number() !== Id.End) this.seek(this.number());
|
||||
break;
|
||||
|
||||
case Id.AdditionalStreamsInfo:
|
||||
throw new Error("7z: additional streams are not supported");
|
||||
|
||||
case Id.MainStreamsInfo:
|
||||
streams = this.streamsInfo();
|
||||
break;
|
||||
|
||||
case Id.FilesInfo:
|
||||
files = this.filesInfo();
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`7z: unexpected header id ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
return { streams, files };
|
||||
}
|
||||
|
||||
private streamsInfo() {
|
||||
const info: SevenZipStreamsInfo = {
|
||||
packPos: 0,
|
||||
packSizes: [],
|
||||
folders: [],
|
||||
};
|
||||
|
||||
for (let id = this.number(); id !== Id.End; id = this.number()) {
|
||||
switch (id) {
|
||||
case Id.PackInfo:
|
||||
this.packInfo(info);
|
||||
break;
|
||||
|
||||
case Id.UnpackInfo:
|
||||
info.folders = this.unpackInfo();
|
||||
break;
|
||||
|
||||
case Id.SubStreamsInfo:
|
||||
this.subStreamsInfo(info.folders);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`7z: unexpected StreamsInfo id ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
let packIndex = 0;
|
||||
|
||||
for (const folder of info.folders) {
|
||||
folder.firstPackStream = packIndex;
|
||||
packIndex += folder.packedCount;
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
private packInfo(info: SevenZipStreamsInfo) {
|
||||
info.packPos = this.number();
|
||||
const count = this.number();
|
||||
|
||||
for (let id = this.number(); id !== Id.End; id = this.number()) {
|
||||
switch (id) {
|
||||
case Id.Size:
|
||||
for (let i = 0; i < count; i++) info.packSizes.push(this.number());
|
||||
break;
|
||||
|
||||
case Id.CRC:
|
||||
this.digests(count);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`7z: unexpected PackInfo id ${id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private unpackInfo() {
|
||||
if (this.number() !== Id.Folder) throw new Error("7z: expected Folder");
|
||||
|
||||
const count = this.number();
|
||||
|
||||
if (this.uint8() !== 0) {
|
||||
throw new Error("7z: external folders are not supported");
|
||||
}
|
||||
|
||||
const folders: SevenZipFolder[] = [];
|
||||
for (let i = 0; i < count; i++) folders.push(this.folder());
|
||||
|
||||
if (this.number() !== Id.CodersUnpackSize) {
|
||||
throw new Error("7z: expected CodersUnpackSize");
|
||||
}
|
||||
|
||||
// every coder output has a size, but single coder folders only have the one
|
||||
for (const folder of folders) {
|
||||
const outputs = folder.coders.reduce(
|
||||
(sum, coder) => sum + coder.numOut,
|
||||
0,
|
||||
);
|
||||
|
||||
folder.unpackSize = this.number();
|
||||
for (let i = 1; i < outputs; i++) this.number();
|
||||
}
|
||||
|
||||
for (let id = this.number(); id !== Id.End; id = this.number()) {
|
||||
switch (id) {
|
||||
case Id.CRC:
|
||||
this.digests(count).forEach((crc, i) => (folders[i].crc = crc));
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`7z: unexpected UnpackInfo id ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
return folders;
|
||||
}
|
||||
|
||||
private folder() {
|
||||
const coderCount = this.number();
|
||||
const coders: SevenZipCoder[] = [];
|
||||
let totalIn = 0;
|
||||
let totalOut = 0;
|
||||
|
||||
for (let i = 0; i < coderCount; i++) {
|
||||
const flags = this.uint8();
|
||||
|
||||
if (flags & 0x80) {
|
||||
throw new Error("7z: alternative coder methods are not supported");
|
||||
}
|
||||
|
||||
// method ids are big endian
|
||||
const method = this.consumeUint8Array(flags & 0x0f).reduce(
|
||||
(value, byte) => value * 0x100 + byte,
|
||||
0,
|
||||
);
|
||||
let numIn = 1;
|
||||
let numOut = 1;
|
||||
|
||||
if (flags & 0x10) {
|
||||
numIn = this.number();
|
||||
numOut = this.number();
|
||||
}
|
||||
|
||||
const props =
|
||||
flags & 0x20
|
||||
? this.consumeUint8Array(this.number())
|
||||
: new Uint8Array(0);
|
||||
|
||||
coders.push({ method, numIn, numOut, props });
|
||||
totalIn += numIn;
|
||||
totalOut += numOut;
|
||||
}
|
||||
|
||||
// bind pairs and packed stream indices only matter for coder chains, so they're skipped
|
||||
const bindPairCount = totalOut - 1;
|
||||
const packedCount = totalIn - bindPairCount;
|
||||
|
||||
for (let i = 0; i < bindPairCount * 2; i++) this.number();
|
||||
if (packedCount > 1) for (let i = 0; i < packedCount; i++) this.number();
|
||||
|
||||
return {
|
||||
coders,
|
||||
packedCount,
|
||||
firstPackStream: 0,
|
||||
unpackSize: 0,
|
||||
numUnpackStreams: 1,
|
||||
} satisfies SevenZipFolder;
|
||||
}
|
||||
|
||||
private subStreamsInfo(folders: SevenZipFolder[]) {
|
||||
for (let id = this.number(); id !== Id.End; id = this.number()) {
|
||||
switch (id) {
|
||||
case Id.NumUnpackStream:
|
||||
for (const folder of folders) folder.numUnpackStreams = this.number();
|
||||
break;
|
||||
|
||||
// per file sizes only exist for solid folders, which are never read
|
||||
case Id.Size:
|
||||
for (const folder of folders) {
|
||||
for (let i = 1; i < folder.numUnpackStreams; i++) this.number();
|
||||
}
|
||||
break;
|
||||
|
||||
// folders holding one file with a known crc have no digest here
|
||||
case Id.CRC: {
|
||||
const undigested = folders.filter(
|
||||
(folder) =>
|
||||
!(folder.numUnpackStreams === 1 && folder.crc !== undefined),
|
||||
);
|
||||
const total = undigested.reduce(
|
||||
(sum, folder) => sum + folder.numUnpackStreams,
|
||||
0,
|
||||
);
|
||||
const digests = this.digests(total);
|
||||
let index = 0;
|
||||
|
||||
for (const folder of undigested) {
|
||||
if (folder.numUnpackStreams === 1) folder.crc = digests[index];
|
||||
index += folder.numUnpackStreams;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`7z: unexpected SubStreamsInfo id ${id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private filesInfo() {
|
||||
const count = this.number();
|
||||
const files: SevenZipFileInfo[] = Array.from({ length: count }, () => ({
|
||||
name: "",
|
||||
hasStream: true,
|
||||
isDir: false,
|
||||
}));
|
||||
let emptyStream: boolean[] | undefined;
|
||||
let emptyFile: boolean[] | undefined;
|
||||
|
||||
for (let type = this.number(); type !== Id.End; type = this.number()) {
|
||||
const data = new SevenZipReadStream(this.consume(this.number()));
|
||||
|
||||
switch (type) {
|
||||
case Id.EmptyStream:
|
||||
emptyStream = data.bits(count);
|
||||
break;
|
||||
|
||||
case Id.EmptyFile:
|
||||
emptyFile = data.bits(emptyStream?.filter(Boolean).length ?? 0);
|
||||
break;
|
||||
|
||||
// names are consecutive null terminated utf-16 strings
|
||||
case Id.Name: {
|
||||
if (data.uint8() !== 0) {
|
||||
throw new Error("7z: external names are not supported");
|
||||
}
|
||||
|
||||
const names = new TextDecoder("utf-16le")
|
||||
.decode(data.consumeRemaining())
|
||||
.split("\0");
|
||||
|
||||
files.forEach((file, i) => (file.name = names[i]));
|
||||
break;
|
||||
}
|
||||
|
||||
// times, attributes, padding etc. are not needed
|
||||
}
|
||||
}
|
||||
|
||||
let emptyIndex = 0;
|
||||
|
||||
files.forEach((file, i) => {
|
||||
if (!emptyStream?.[i]) return;
|
||||
|
||||
file.hasStream = false;
|
||||
file.isDir = !emptyFile?.[emptyIndex];
|
||||
emptyIndex++;
|
||||
});
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
// 7z variable-length number: leading 1-bits in the first byte count extra bytes
|
||||
private number() {
|
||||
const first = this.uint8();
|
||||
let mask = 0x80;
|
||||
let value = 0;
|
||||
|
||||
for (let i = 0; i < 8; i++) {
|
||||
if ((first & mask) === 0) {
|
||||
return value + (first & (mask - 1)) * 2 ** (8 * i);
|
||||
}
|
||||
|
||||
value += this.uint8() * 2 ** (8 * i);
|
||||
mask >>>= 1;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private bits(count: number) {
|
||||
const result: boolean[] = [];
|
||||
let current = 0;
|
||||
let mask = 0;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
if (mask === 0) {
|
||||
current = this.uint8();
|
||||
mask = 0x80;
|
||||
}
|
||||
|
||||
result.push((current & mask) !== 0);
|
||||
mask >>>= 1;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private digests(count: number) {
|
||||
const defined =
|
||||
this.uint8() !== 0
|
||||
? new Array<boolean>(count).fill(true)
|
||||
: this.bits(count);
|
||||
|
||||
return defined.map((isDefined) => (isDefined ? this.uint32() : undefined));
|
||||
}
|
||||
}
|
||||
@@ -32,3 +32,4 @@ export * from "./vehicleDefinitionArmor";
|
||||
export * from "./vehicleDefinitionList";
|
||||
export * from "./vehicleDefinitions";
|
||||
export * from "./vehicleFilter";
|
||||
export * from "./wgcClient";
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
export interface ClientMetadata {
|
||||
export interface WGCClientMetadata {
|
||||
protocol: {
|
||||
version: number;
|
||||
predefined_section: PredefinedSection;
|
||||
@@ -50,7 +50,7 @@ interface Instance {
|
||||
content_service_url: string;
|
||||
}
|
||||
|
||||
export interface PatchesChain {
|
||||
export interface WGCPatchesChain {
|
||||
protocol: {
|
||||
parts_info: { part: Part };
|
||||
patches_chain: { patch: Patch };
|
||||
@@ -1,9 +0,0 @@
|
||||
// dava engine has a lot of tiny files, this is faster
|
||||
export const DEPOT_DOWNLOADER_MAX_DOWNLOADS = 256;
|
||||
export const DEPOT_DOWNLOADER_OUTPUT = "../../temp/depotdownloader";
|
||||
export const DEPOT_DOWNLOADER_EXECUTABLE = `${DEPOT_DOWNLOADER_OUTPUT}/DepotDownloader`;
|
||||
|
||||
export const ARIA2_OUTPUT = "../../temp/aria2";
|
||||
export const ARIA2_EXECUTABLE = `${ARIA2_OUTPUT}/aria2c`;
|
||||
|
||||
export const WGPKG_DIR = "../../temp/wgpkgs";
|
||||
@@ -1,37 +0,0 @@
|
||||
import { assertSecret } from "@blitzkit/core";
|
||||
import { mkdir, rm } from "node:fs/promises";
|
||||
import { downloadSteamClient } from "./steam";
|
||||
import { downloadWGCClient } from "./wgc";
|
||||
import { downloadWGPKGClient } from "./wgpkg";
|
||||
|
||||
export const DEPOT_DOWNLOADER_RETRY_TIME = 30_000;
|
||||
|
||||
const provider = import.meta.env.CLIENT_PROVIDER;
|
||||
export const source = import.meta.env.CLIENT_SOURCE;
|
||||
export const dir = assertSecret(import.meta.env.CLIENT_DIR);
|
||||
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await mkdir(dir, { recursive: true });
|
||||
|
||||
switch (provider) {
|
||||
// steam, identical to wgc
|
||||
case "steam":
|
||||
await downloadSteamClient();
|
||||
break;
|
||||
|
||||
// from zip, read remotely by ZipVFS at build time; nothing to download
|
||||
case "zip":
|
||||
console.log("Zip client provider; skipping download in favor of ZipVFS");
|
||||
break;
|
||||
|
||||
// effectively the same as wgc, but direct for preview
|
||||
case "wgpkg":
|
||||
await downloadWGPKGClient();
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log("Unknown client provider specified, using latest wgc client");
|
||||
case "wgc":
|
||||
await downloadWGCClient();
|
||||
break;
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { assertSecret } from "@blitzkit/core";
|
||||
import { $ } from "bun";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { DEPOT_DOWNLOADER_RETRY_TIME, dir, source } from ".";
|
||||
import {
|
||||
DEPOT_DOWNLOADER_EXECUTABLE,
|
||||
DEPOT_DOWNLOADER_MAX_DOWNLOADS,
|
||||
DEPOT_DOWNLOADER_OUTPUT,
|
||||
} from "./constants";
|
||||
import { QuickGitHubRelease } from "./types";
|
||||
|
||||
export async function downloadSteamClient() {
|
||||
const [id, platform] = source.split("/");
|
||||
|
||||
console.log("Downloading Depot Downloader...");
|
||||
|
||||
const releases = await fetch(
|
||||
"https://api.github.com/repos/SteamRE/DepotDownloader/releases/latest",
|
||||
).then((response) => response.json() as Promise<QuickGitHubRelease>);
|
||||
const asset = releases.assets.find((asset) =>
|
||||
asset.name.includes("linux-x64"),
|
||||
);
|
||||
|
||||
if (!asset) {
|
||||
throw new Error("No linux-x64 asset found for Steam DepotDownloader");
|
||||
}
|
||||
|
||||
await rm(DEPOT_DOWNLOADER_OUTPUT, { recursive: true, force: true });
|
||||
|
||||
await $`curl -L "${asset.browser_download_url}" -o "${DEPOT_DOWNLOADER_OUTPUT}.zip"`;
|
||||
await $`unzip "${DEPOT_DOWNLOADER_OUTPUT}.zip" -d "${DEPOT_DOWNLOADER_OUTPUT}"`;
|
||||
await $`chmod +x "${DEPOT_DOWNLOADER_EXECUTABLE}"`;
|
||||
|
||||
console.log("Downloading client...");
|
||||
|
||||
const username = assertSecret(import.meta.env.STEAM_USERNAME);
|
||||
const password = assertSecret(import.meta.env.STEAM_PASSWORD);
|
||||
|
||||
while (true) {
|
||||
const result =
|
||||
await $`${DEPOT_DOWNLOADER_EXECUTABLE} -os ${platform} -app ${id} -username ${username} -password ${password} -dir ${dir} -max-downloads ${DEPOT_DOWNLOADER_MAX_DOWNLOADS}`.nothrow();
|
||||
|
||||
if (result.exitCode === 0) {
|
||||
console.log("Client downloaded successfully!");
|
||||
break;
|
||||
}
|
||||
|
||||
console.error(
|
||||
`DepotDownloader failed (exit ${result.exitCode}). Retrying in ${
|
||||
DEPOT_DOWNLOADER_RETRY_TIME / 1000
|
||||
} seconds...`,
|
||||
);
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, DEPOT_DOWNLOADER_RETRY_TIME),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
export interface QuickGitHubRelease {
|
||||
assets: Asset[];
|
||||
}
|
||||
|
||||
interface Asset {
|
||||
name: string;
|
||||
browser_download_url: string;
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { $ } from "bun";
|
||||
import { mkdir, rm } from "node:fs/promises";
|
||||
import { dir, source } from ".";
|
||||
import { WGPKG_DIR } from "./constants";
|
||||
|
||||
export async function downloadWGPKGClient() {
|
||||
let index = 1;
|
||||
const urls: string[] = [];
|
||||
|
||||
console.log("Discovering packages...");
|
||||
|
||||
while (true) {
|
||||
const url = `${source}.${index.toString().padStart(3, "0")}`;
|
||||
const response = await fetch(url);
|
||||
|
||||
if (response.status === 200) {
|
||||
urls.push(url);
|
||||
} else if (response.status === 404) {
|
||||
break;
|
||||
} else {
|
||||
throw new Error(`Wargaming response error status: ${response.status}`);
|
||||
}
|
||||
|
||||
index++;
|
||||
}
|
||||
|
||||
console.log(`Downloading ${urls.length} packages...`);
|
||||
|
||||
await downloadWgParts(urls);
|
||||
}
|
||||
|
||||
export async function downloadWgParts(urls: string[]) {
|
||||
await rm(WGPKG_DIR, { recursive: true, force: true });
|
||||
await mkdir(WGPKG_DIR, { recursive: true });
|
||||
|
||||
const inputContent = urls
|
||||
.map((url) => {
|
||||
const name = url.split("/").pop()!;
|
||||
return `${url}\n out=${name}\n dir=${WGPKG_DIR}`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
await $`echo ${inputContent} | aria2c -j ${urls.length} -x 2 -s 2 -i -`;
|
||||
|
||||
const firstChunk = `${WGPKG_DIR}/${urls[0].split("/").pop()!}`;
|
||||
await $`7z x "${firstChunk}" -o${dir} -y`;
|
||||
|
||||
await rm(WGPKG_DIR, { recursive: true });
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { assertSecret } from "@blitzkit/core";
|
||||
import { $ } from "bun";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { dir } from ".";
|
||||
|
||||
export async function downloadZipClient() {
|
||||
const url = assertSecret(import.meta.env.CLIENT_SOURCE);
|
||||
|
||||
console.log("Downloading and extracting zipped client...");
|
||||
|
||||
await mkdir(dir, { recursive: true });
|
||||
await $`curl -L "${url}" | bsdtar -xf- --strip-components=1 -C ${dir}`;
|
||||
}
|
||||
@@ -8,6 +8,11 @@ export default defineConfig({
|
||||
server: { allowedHosts: [] },
|
||||
esbuild: { target: "es2022" },
|
||||
build: { cssCodeSplit: false },
|
||||
|
||||
optimizeDeps: {
|
||||
exclude: ["@napi-rs/lzma"],
|
||||
},
|
||||
|
||||
css: {
|
||||
modules: {
|
||||
// Short hashed class names in production to shrink HTML; the leading _ keeps names that start with a digit valid
|
||||
|
||||
@@ -3,6 +3,12 @@
|
||||
# double quotation marks if your path has spaces
|
||||
CLIENT_DIR=
|
||||
|
||||
# Local reads CLIENT_DIR; zip, 7z, and wgc read the client remotely
|
||||
CLIENT_PROVIDER=local
|
||||
|
||||
# Optional; where downloaded SmartDLC patches live, read on top of the client
|
||||
SMART_DLC_DIR=
|
||||
|
||||
# Should be set to * for local development to build all chunks at once
|
||||
CHUNK=*
|
||||
|
||||
|
||||
Reference in new issue
Block a user