Files
WT-Offline/packages/local-service/src/saves/save-store.ts
T
N0VAN0M4LY 7f482ae530 feat(accounts): implement local login
Route login and character requests by their original host names on one
loopback port. Add local accounts, saves, and credential redaction.
2026-11-24 05:01:26 +08:00

63 lines
2.3 KiB
TypeScript

/**
* Save layer: one save per account, holding the profile in Gaijin's
* profile structure.
*
* <data>/saves/<userId>/save.json format version and bookkeeping
* <data>/saves/<userId>/profile.blk the profile, binary BLK with every value's type kept
*
* Every write reaches the disk before the caller replies to the game. A save written by an
* older format version is upgraded step by step when it is opened (save-upgrades.ts).
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import { CURRENT_SAVE_FORMAT, upgradeSave } from './save-upgrades.ts';
interface SaveInfo {
formatVersion: number;
created: string;
updated: string;
}
export class SaveStore {
readonly #folder: string;
constructor(dataFolder: string) {
this.#folder = join(dataFolder, 'saves');
}
/** The account's profile, or undefined when the account has no save yet. */
loadProfile(userId: string): BlkBlock | undefined {
const infoPath = this.#infoPath(userId);
if (!existsSync(infoPath)) return undefined;
const info = JSON.parse(readFileSync(infoPath, 'utf8')) as SaveInfo;
const profile = decodeBlk(readFileSync(this.#profilePath(userId)));
if (info.formatVersion === CURRENT_SAVE_FORMAT) return profile;
const upgraded = upgradeSave(profile, info.formatVersion);
this.saveProfile(userId, upgraded);
return upgraded;
}
saveProfile(userId: string, profile: BlkBlock): void {
const now = new Date().toISOString();
const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined;
writeFileAtomic(this.#profilePath(userId), encodeBlk(profile));
const info: SaveInfo = { formatVersion: CURRENT_SAVE_FORMAT, created: previous?.created ?? now, updated: now };
writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2));
}
#infoPath(userId: string): string {
return join(this.#folder, safeId(userId), 'save.json');
}
#profilePath(userId: string): string {
return join(this.#folder, safeId(userId), 'profile.blk');
}
}
function safeId(userId: string): string {
if (!/^\d+$/.test(userId)) throw new Error(`invalid user id: ${userId}`);
return userId;
}