Add GJN balances, the local store, and redemption codes

Support currency and entitlement purchases, including packs, from the
local store and the in-game payment flow. Expose the supported
redemption codes.
This commit is contained in:
N0VAN0M4LY committed 2026-11-25 06:33:41 +08:00
1 parent d95a5d8f0c
commit cfa6c04aa6
26 files changed
+1352 -29

No files matched your search

@@ -9,12 +9,16 @@
* offer (scripts/tutorials/nextTutorialHandler.nut) enables its skip and close buttons only
* with this feature (tutorialsData.nut canSkipByFeature). The offline version makes the
* tutorial optional (local verification).
*
* PaymentMethods: lets scripts/onlineShop/onlinePurchase.nut offer GJN payment directly
* inside the Golden Eagles and Premium Account windows (stock game_settings.blk restricts it
* with PS4Access; implementation notes).
*/
import { ensureBlock, setParam, type BlkBlock } from '@wto/blk';
export const GAME_SETTINGS_PATH = 'config/game_settings.blk';
export const OFFLINE_FEATURES: readonly string[] = ['AllowedToSkipBaseTutorials'];
export const OFFLINE_FEATURES: readonly string[] = ['AllowedToSkipBaseTutorials', 'PaymentMethods'];
/** Give every player the features; returns the ones that were not on for everyone before. */
export function enableFeaturesForEveryone(gameSettings: BlkBlock, names: readonly string[]): string[] {
+37 -8
View File
@@ -12,24 +12,53 @@
* Only the `network` block is touched: the rest of settings.blk is engine configuration, not
* server addresses.
*/
import { findBlock } from '@wto/blk';
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
import type { LocalEndpoint } from './network/local-endpoint.ts';
import { editPackBlk } from './pack-edit.ts';
import { editPackBlks } from './pack-edit.ts';
export const ENGINE_SETTINGS_PATH = 'config/settings.blk';
export const GUI_CONFIG_PATH = 'config/gui.blk';
const NETWORK_BLOCK = 'network';
/**
* GUIDs added to config/gui.blk bundles/guid so scripts/onlineShop/entitlementsInfo.nut
* requests GJN prices for GJN-priced Premium Account tiers alongside the stock eagles* packs
*.
*/
export const EXTRA_STORE_BUNDLE_GUIDS: ReadonlyArray<readonly [entitlement: string, guid: string]> = [
['wto_prem_20d', 'A1E00020-5754-4F46-8F00-000000000020'],
['wto_prem_60d', 'A1E00060-5754-4F46-8F00-000000000060'],
['wto_prem_180d', 'A1E00180-5754-4F46-8F00-000000000180'],
];
export interface MainPackResult {
readonly pack: Uint8Array;
readonly addresses: readonly AddressChange[];
}
export function rebuildMainPack(stockPack: Uint8Array, endpoint: LocalEndpoint): MainPackResult {
const { pack, report } = editPackBlk(stockPack, ENGINE_SETTINGS_PATH, (root) => {
const network = findBlock(root, NETWORK_BLOCK);
if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`);
return redirectAddresses(network, endpoint, [NETWORK_BLOCK]);
});
return { pack, addresses: report };
let addresses: AddressChange[] = [];
const pack = editPackBlks(stockPack, [
{
path: ENGINE_SETTINGS_PATH,
edit: (root) => {
const network = findBlock(root, NETWORK_BLOCK);
if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`);
addresses = redirectAddresses(network, endpoint, [NETWORK_BLOCK]);
},
},
{
path: GUI_CONFIG_PATH,
edit: (root) => registerStoreBundleGuids(root),
},
]);
return { pack, addresses };
}
function registerStoreBundleGuids(guiRoot: BlkBlock): void {
const guidBlock = ensureBlock(ensureBlock(guiRoot, 'bundles'), 'guid');
for (const [entitlement, guid] of EXTRA_STORE_BUNDLE_GUIDS) {
setParam(guidBlock, entitlement, { type: 'string', value: guid });
}
}
@@ -27,6 +27,8 @@ export function redirectNetworkConfig(root: BlkBlock, endpoint: LocalEndpoint):
function configureEnvironment(environment: BlkBlock, endpoint: LocalEndpoint): void {
setParam(environment, 'enableSslCertCheck', { type: 'bool', value: false });
// Open the local web store directly without SSO redirection to login.gaijin.net.
setParam(environment, 'webstoreURL', { type: 'string', value: `http://${endpoint.host}:${endpoint.port}/store` });
const login = ensureBlock(environment, 'yuplay');
for (const [key, value] of loginOverrides(endpoint)) setParam(login, key, { type: 'string', value });
}
@@ -35,6 +35,7 @@ const NICK_MAX_LENGTH = 16;
export class AccountStore {
readonly #path: string;
#file: AccountFile;
#lastSignedInUserId: string | undefined;
constructor(dataFolder: string) {
this.#path = join(dataFolder, 'accounts.json');
@@ -43,15 +44,33 @@ export class AccountStore {
signIn(login: string, password: string): SignInResult {
const existing = this.#find(login);
if (existing) return verifyPassword(password, existing.passwordHash) ? { kind: 'signed-in', account: existing, registered: false } : { kind: 'wrong-password' };
if (existing) {
if (!verifyPassword(password, existing.passwordHash)) return { kind: 'wrong-password' };
this.#lastSignedInUserId = existing.userId;
return { kind: 'signed-in', account: existing, registered: false };
}
const userId = String(this.#file.nextUserId);
const account: Account = { login, userId, nick: nickFromLogin(login, userId), passwordHash: hashPassword(password), created: new Date().toISOString() };
this.#file = { ...this.#file, nextUserId: this.#file.nextUserId + 1, accounts: [...this.#file.accounts, account] };
writeFileAtomic(this.#path, JSON.stringify(this.#file, null, 2));
this.#lastSignedInUserId = account.userId;
return { kind: 'signed-in', account, registered: true };
}
all(): readonly Account[] {
return this.#file.accounts;
}
/** User id of the account that signed in most recently, or the newest account when none signed in yet. */
activeAccount(): Account | undefined {
if (this.#lastSignedInUserId !== undefined) {
const active = this.byUserId(this.#lastSignedInUserId);
if (active) return active;
}
return this.#file.accounts[this.#file.accounts.length - 1];
}
byUserId(userId: string): Account | undefined {
return this.#file.accounts.find((account) => account.userId === userId);
}
@@ -17,6 +17,7 @@ import { buyAircraft, buySlot } from './purchase-actions.ts';
import { convertExp, resetResearchable, setResearchable } from './research-actions.ts';
import { setStartingInfo } from './starting-info-actions.ts';
import { activateBoosterAction, activateDiscountAction, applySpareItemAction, buyItemAction, startWagerAction } from './item-actions.ts';
import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts';
export interface ActionDependencies {
readonly profiles: PlayerProfiles;
@@ -61,5 +62,8 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharA
['cln_set_current_personal_discount', activateDiscountAction(deps.profiles, deps.accounts, deps.research)],
['cln_set_current_wager', startWagerAction(deps.profiles, deps.accounts, deps.research)],
['cln_apply_spare_item', applySpareItemAction(deps.profiles, deps.accounts, deps.research)],
['cln_get_entitlements_price_ex', entitlementsPriceEx(deps.research)],
['cln_buy_entitlement', buyEntitlementAction(deps.profiles, deps.accounts, deps.research)],
['cln_buy_entitlement_and_get_reward_for_day', buyEntitlementAction(deps.profiles, deps.accounts, deps.research)],
]);
}
@@ -0,0 +1,42 @@
/**
* Store char actions:
* - cln_get_entitlements_price_ex: returns the store catalogue BLK;
* - cln_buy_entitlement (and cln_buy_entitlement_and_get_reward_for_day): Golden-Eagle
* entitlement purchase (aces.exe 0x17a0f50 -> 0x2a1240 sends `entitlement` and `costGold`
* in the HTTP headers, job type 5, answer applied as a full profile update).
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import { buyGoldEntitlement } from '../../store/store-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { intParam, stringParam } from './payload-params.ts';
export function entitlementsPriceEx(rules: ResearchRules): CharActionHandler {
const table = rules.store.entitlementsPriceBlk();
return () => ({ kind: 'data', blk: table });
}
export function buyEntitlementAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const entitlement = context.headerParam('entitlement') ?? (context.payload ? stringParam(context.payload, 'entitlement') : undefined);
const headerGold = context.headerParam('costGold');
const offeredGold = headerGold !== undefined && /^\d+$/.test(headerGold)
? Number(headerGold)
: (context.payload ? intParam(context.payload, 'costGold') : undefined);
if (!entitlement) return { kind: 'error', code: 'BAD_PARAMS' };
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const now = serverTimeNow();
const updated = profiles.updateWhen(account.userId, (saved) => {
outcome = buyGoldEntitlement(saved, rules.store, entitlement, offeredGold, now);
return outcome.ok;
});
if (updated) return { kind: 'data', blk: clientProfile(updated, account) };
return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
});
}
@@ -119,6 +119,14 @@ class TrackedSource implements DatasetSource {
return gamePack.readBlk(path);
}
readText(pack: GamePackName, path: string): string {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readText(path);
}
listFiles(pack: GamePackName): readonly string[] {
const paths = this.#gameFiles.pack(pack).paths();
this.#listings.set(pack, { pack, sha1: listingDigest(paths) });
@@ -11,6 +11,7 @@ import type { GamePackName } from '../game-files.ts';
export interface DatasetSource {
readBlk(pack: GamePackName, path: string): BlkBlock;
readText(pack: GamePackName, path: string): string;
/** Every file path in a pack, sorted. */
listFiles(pack: GamePackName): readonly string[];
}
@@ -0,0 +1,27 @@
/**
* Dataset: entitlement-to-GUID mappings from aces.vromfs.bin config/gui.blk bundles/guid
* (gui.vromfs.bin scripts/onlineShop/onlineBundles.nut, implementation notes).
*/
import { findBlock } from '@wto/blk';
import type { Dataset } from './dataset.ts';
const GUI_CONFIG = 'config/gui.blk';
/** Entitlement name -> store item GUID (upper-case UUID string). */
export type StoreBundleGuids = Readonly<Record<string, string>>;
export const storeBundles: Dataset<StoreBundleGuids> = {
id: 'store-bundles',
version: 1,
extract: (source) => {
const gui = source.readBlk('aces.vromfs.bin', GUI_CONFIG);
const guidBlock = findBlock(findBlock(gui, 'bundles') ?? { name: '', params: [], blocks: [] }, 'guid');
const result: Record<string, string> = {};
for (const param of guidBlock?.params ?? []) {
if (param.value.type === 'string' && param.value.value) {
result[param.name] = param.value.value;
}
}
return result;
},
};
@@ -0,0 +1,96 @@
/**
* Dataset: localized vehicle names from lang.vromfs.bin lang/units.csv.
*
* Used by the local web store and generated inventory coupon definitions so players see the
* game's own English and Chinese vehicle names without shipping game text with the service.
*/
import type { Dataset } from './dataset.ts';
const UNITS_CSV = 'lang/units.csv';
export interface LocalizedText {
readonly en: string;
readonly zh: string;
}
export type UnitNamesMap = Readonly<Record<string, LocalizedText>>;
export const unitNames: Dataset<UnitNamesMap> = {
id: 'unit-names',
version: 1,
extract: (source) => {
const csv = source.readText('lang.vromfs.bin', UNITS_CSV);
const lines = csv.split(/\r?\n/);
const header = parseCsvRow(lines[0] ?? '');
const enCol = Math.max(1, header.indexOf('<English>'));
const zhCol = header.indexOf('<Chinese>');
const hzhCol = header.indexOf('<HChinese>');
const shopNames = new Map<string, LocalizedText>();
const fullNames = new Map<string, LocalizedText>();
for (let i = 1; i < lines.length; i++) {
const line = lines[i]!;
if (!line.startsWith('"')) continue;
const firstSemi = line.indexOf(';');
if (firstSemi <= 2) continue;
const key = line.slice(1, firstSemi - 1);
const isShop = key.endsWith('_shop');
const isFull = !isShop && key.endsWith('_0');
if (!isShop && !isFull) continue;
const cols = parseCsvRow(line);
const en = cleanText(cols[enCol] ?? '');
if (!en) continue;
const zh = cleanText((hzhCol >= 0 ? cols[hzhCol] : '') || (zhCol >= 0 ? cols[zhCol] : '') || en);
const unitId = key.slice(0, isShop ? -5 : -2);
if (isShop) shopNames.set(unitId, { en, zh });
else fullNames.set(unitId, { en, zh });
}
const result: Record<string, LocalizedText> = {};
for (const [unitId, text] of fullNames) result[unitId] = text;
for (const [unitId, text] of shopNames) result[unitId] = text;
return result;
},
};
function parseCsvRow(line: string): string[] {
const fields: string[] = [];
let i = 0;
while (i < line.length) {
if (line[i] === '"') {
i++;
let value = '';
while (i < line.length) {
if (line[i] === '"') {
if (line[i + 1] === '"') {
value += '"';
i += 2;
} else {
i++;
break;
}
} else {
value += line[i]!;
i++;
}
}
fields.push(value);
if (line[i] === ';') i++;
} else {
const next = line.indexOf(';', i);
if (next < 0) {
fields.push(line.slice(i));
break;
}
fields.push(line.slice(i, next));
i = next + 1;
}
}
return fields;
}
function cleanText(raw: string): string {
// Strip zero-width word-break spaces Gaijin inserts into CJK localization strings.
return raw.replace(/\u200b/g, '').trim();
}
@@ -52,11 +52,13 @@ export interface CatalogueVehicle {
readonly parts: readonly string[];
/** shop.blk showOnlyWhenBought. */
readonly onlyShownWhenOwned: boolean;
/** shop.blk marketplaceItemdefId (vehicles traded as coupons on the market, implementation notes). */
readonly marketplaceItemdefId?: number;
}
export const vehicleCatalogue: Dataset<readonly CatalogueVehicle[]> = {
id: 'vehicle-catalogue',
version: 2,
version: 3,
extract: (source) => {
const shopEntries = new Map<string, BlkBlock>();
for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) {
@@ -70,6 +72,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined): C
const requires = stringField(vehicle, 'reqAir');
const researchType = stringField(vehicle, 'researchType');
const requiredUnlock = stringField(shopEntry, 'reqUnlock');
const marketplaceItemdefId = numberField(shopEntry, 'marketplaceItemdefId') ?? numberField(vehicle, 'marketplaceItemdefId');
return {
name: vehicle.name,
country: stringField(vehicle, 'country') ?? '',
@@ -87,6 +90,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined): C
...(requiredUnlock ? { requiredUnlock } : {}),
parts: shopEntry ? shopEntry.params.flatMap((param) => (param.name === 'slaveUnit' && param.value.type === 'string' && param.value.value ? [param.value.value] : [])) : [],
onlyShownWhenOwned: boolField(shopEntry, 'showOnlyWhenBought') ?? false,
...(marketplaceItemdefId !== undefined ? { marketplaceItemdefId } : {}),
};
}
@@ -7,7 +7,7 @@ import type { BlkBlock } from '@wto/blk';
import { GamePack } from './game-pack.ts';
/** The data packs the local service reads (file names in the game folder). */
export type GamePackName = 'char.vromfs.bin' | 'mis.vromfs.bin';
export type GamePackName = 'char.vromfs.bin' | 'mis.vromfs.bin' | 'aces.vromfs.bin' | 'gui.vromfs.bin' | 'lang.vromfs.bin';
/** What identifies one version of a pack file cheaply (implementation notes, first check). */
export interface PackStamp {
@@ -26,6 +26,10 @@ export class GamePack {
return decodeBlk(getFile(this.#archive, pathInPack), this.#shared);
}
readText(pathInPack: string): string {
return Buffer.from(getFile(this.#archive, pathInPack)).toString('utf8');
}
/** Every file path in the pack, sorted. */
paths(): string[] {
return [...this.#archive.files.keys()].sort();
+3 -1
View File
@@ -18,6 +18,7 @@ import { setUpProfiles } from './profiles-setup.ts';
import { createPortListener } from './server/port-listener.ts';
import { Router } from './server/router.ts';
import { loadOrCreateCredentials } from './server/tls/tls-certificate.ts';
import { StoreService } from './store/store-service.ts';
import { TrafficLog } from './traffic-log/traffic-log.ts';
export interface LocalServiceOptions {
@@ -46,9 +47,10 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
const { profiles, research } = setUpProfiles(options.dataFolder, gameFiles, datasets);
gameFiles.releasePacks();
// One store for both services: accounts registered at sign-in must be visible to char.
// One store for all services: accounts registered at sign-in must be visible everywhere.
const accounts = new AccountStore(options.dataFolder);
const router = new Router([
new StoreService(accounts, profiles, research.store),
new LoginService(accounts),
new CharService(actionTable({ profiles, accounts, research })),
new DownloadableContentService(),
@@ -20,7 +20,29 @@ export interface SessionCredentials {
export function issueCredentials(account: Account): SessionCredentials {
const issued = Math.floor(Date.now() / 1000);
const expires = issued + SESSION_LIFETIME_SECONDS;
return { token: randomBytes(16).toString('hex'), jwt: jwt({ uid: account.userId, nick: account.nick, iat: issued, exp: expires }), expires };
const uidHex = BigInt(account.userId).toString(16).padStart(16, '0');
const token = `${uidHex}${randomBytes(8).toString('hex')}`;
return { token, jwt: jwt({ uid: account.userId, nick: account.nick, iat: issued, exp: expires }), expires };
}
/** Extract the user id encoded in a session token issued by issueCredentials. */
export function userIdFromToken(token: string | undefined): string | undefined {
if (!token || !/^[0-9a-f]{32}$/i.test(token)) return undefined;
const id = BigInt(`0x${token.slice(0, 16)}`);
return id > 0n ? id.toString(10) : undefined;
}
/** Extract the user id from a JWT issued by issueCredentials. */
export function userIdFromJwt(token: string | undefined): string | undefined {
if (!token) return undefined;
const parts = token.split('.');
if (parts.length !== 3 || !parts[1]) return undefined;
try {
const parsed = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as { uid?: unknown };
return typeof parsed.uid === 'string' && /^\d+$/.test(parsed.uid) ? parsed.uid : undefined;
} catch {
return undefined;
}
}
function jwt(claims: object): string {
@@ -5,7 +5,7 @@
*/
import type { ServiceResponse } from '../server/exchange.ts';
export type YuplayStatus = 'OK' | 'ERROR' | 'LOGINERROR';
export type YuplayStatus = 'OK' | 'ERROR' | 'LOGINERROR' | 'NOMONEY' | 'ALREADY' | 'NOTFOUND' | 'BADPAYMENT';
export function yuplayAnswer(status: YuplayStatus, fields: Readonly<Record<string, unknown>> = {}, summary?: string): ServiceResponse {
const body = JSON.stringify({ status, ...fields });
@@ -5,15 +5,16 @@
* eagles (local verification); the template has none.
*/
import type { BlkBlock } from '@wto/blk';
import { setGoldenEagles, setSilverLions, type Balance } from './profile-currency.ts';
import { setGjn, setGoldenEagles, setSilverLions, type Balance } from './profile-currency.ts';
import { applyStartingContent, type StartingContent } from './starting-content.ts';
export const STARTING_BALANCE: Balance = { silverLions: 150_000, goldenEagles: 500 };
export const STARTING_BALANCE: Balance = { silverLions: 150_000, goldenEagles: 500, gjn: 0 };
export function newProfile(template: BlkBlock, content: StartingContent): BlkBlock {
const profile = structuredClone(template);
applyStartingContent(profile, content);
setSilverLions(profile, STARTING_BALANCE.silverLions);
setGoldenEagles(profile, STARTING_BALANCE.goldenEagles);
setGjn(profile, STARTING_BALANCE.gjn);
return profile;
}
@@ -5,6 +5,8 @@
* warpointsPos:i64 silver lions earned in total
* warpointsNeg:i64 silver lions spent in total
* goldBalance:i golden eagles (read and written as a 32-bit integer, 0x91b570 / 0x91b5cb)
* gjnBalance:i64 GJN balance for the offline store and market (implementation notes;
* ignored by the client when loading a profile)
*
* The silver lion balance is warpointsPos - warpointsNeg; setting it keeps the amount spent
* and adjusts the amount earned.
@@ -14,15 +16,21 @@ import { findParam, setParam, type BlkBlock } from '@wto/blk';
const EARNED = 'warpointsPos';
const SPENT = 'warpointsNeg';
const GOLD = 'goldBalance';
const GJN = 'gjnBalance';
const MAX_GOLD = 0x7fffffff;
export interface Balance {
readonly silverLions: number;
readonly goldenEagles: number;
readonly gjn: number;
}
export function balanceOf(profile: BlkBlock): Balance {
return { silverLions: numberParam(profile, EARNED) - numberParam(profile, SPENT), goldenEagles: numberParam(profile, GOLD) };
return {
silverLions: numberParam(profile, EARNED) - numberParam(profile, SPENT),
goldenEagles: numberParam(profile, GOLD),
gjn: numberParam(profile, GJN),
};
}
export function setSilverLions(profile: BlkBlock, amount: number): void {
@@ -35,8 +43,34 @@ export function setGoldenEagles(profile: BlkBlock, amount: number): void {
setParam(profile, GOLD, { type: 'int', value: amount });
}
/** A price in both currencies. */
export type Price = Balance;
export function setGjn(profile: BlkBlock, amount: number): void {
requireAmount(amount, Number.MAX_SAFE_INTEGER);
setParam(profile, GJN, { type: 'int64', value: BigInt(amount) });
}
export function addGoldenEagles(profile: BlkBlock, amount: number): void {
requireAmount(amount, MAX_GOLD);
const next = Math.min(MAX_GOLD, numberParam(profile, GOLD) + amount);
setGoldenEagles(profile, next);
}
export function addSilverLions(profile: BlkBlock, amount: number): void {
requireAmount(amount, Number.MAX_SAFE_INTEGER);
setParam(profile, EARNED, { type: 'int64', value: BigInt(numberParam(profile, EARNED) + amount) });
}
export function payGjn(profile: BlkBlock, amount: number): void {
requireAmount(amount, Number.MAX_SAFE_INTEGER);
const current = numberParam(profile, GJN);
if (current < amount) throw new RangeError('the player cannot afford this GJN price');
setGjn(profile, current - amount);
}
/** A price in the two in-game currencies. */
export interface Price {
readonly silverLions: number;
readonly goldenEagles: number;
}
export function canAfford(profile: BlkBlock, price: Price): boolean {
const balance = balanceOf(profile);
@@ -0,0 +1,67 @@
/**
* Entitlements and Premium Account in the profile (implementation notes; read by aces.exe
* 2.61.0.37 0x91daf0..0x91e474, has_entitlement 0x179ec70, entitlement_expires_in 0x179ed60):
*
* entitlementsInfo{
* PremiumAccount{
* count:i=1
* expiredTime:i64=<Windows FILETIME>
* }
* wto_pack_f-5c{
* count:i=1
* }
* }
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const ENTITLEMENTS_INFO = 'entitlementsInfo';
export const PREMIUM_ACCOUNT_ENTITLEMENT = 'PremiumAccount';
const TICKS_PER_SECOND = 10_000_000n;
const TICKS_PER_DAY = 86_400n * TICKS_PER_SECOND;
export function hasEntitlement(profile: BlkBlock, name: string, nowFiletime: bigint): boolean {
const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? emptyRef, name);
if (!entry) return false;
const count = intField(entry, 'count');
if (count <= 0) return false;
const expires = int64Field(entry, 'expiredTime');
return expires === 0n || expires > nowFiletime;
}
export function recordEntitlementPurchase(profile: BlkBlock, name: string): void {
const entry = ensureBlock(ensureBlock(profile, ENTITLEMENTS_INFO), name);
const previous = intField(entry, 'count');
setParam(entry, 'count', { type: 'int', value: previous + 1 });
}
export function extendPremiumAccount(profile: BlkBlock, days: number, nowFiletime: bigint): void {
if (!Number.isSafeInteger(days) || days <= 0) throw new RangeError(`invalid premium days: ${days}`);
const entry = ensureBlock(ensureBlock(profile, ENTITLEMENTS_INFO), PREMIUM_ACCOUNT_ENTITLEMENT);
const previousCount = intField(entry, 'count');
const previousExpiry = int64Field(entry, 'expiredTime');
const base = previousExpiry > nowFiletime ? previousExpiry : nowFiletime;
setParam(entry, 'count', { type: 'int', value: previousCount + 1 });
setParam(entry, 'expiredTime', { type: 'int64', value: base + BigInt(days) * TICKS_PER_DAY });
}
/** Remaining whole days (rounded up) of Premium Account, or 0 when inactive. */
export function remainingPremiumDays(profile: BlkBlock, nowFiletime: bigint): number {
const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? emptyRef, PREMIUM_ACCOUNT_ENTITLEMENT);
if (!entry || intField(entry, 'count') <= 0) return 0;
const expires = int64Field(entry, 'expiredTime');
if (expires <= nowFiletime) return 0;
return Number((expires - nowFiletime + TICKS_PER_DAY - 1n) / TICKS_PER_DAY);
}
const emptyRef: BlkBlock = { name: '', params: [], blocks: [] };
function intField(block: BlkBlock, name: string): number {
const value = findParam(block, name)?.value;
return value?.type === 'int' ? value.value : 0;
}
function int64Field(block: BlkBlock, name: string): bigint {
const value = findParam(block, name)?.value;
if (value?.type === 'int64') return value.value;
return value?.type === 'int' ? BigInt(value.value) : 0n;
}
@@ -16,7 +16,10 @@ import { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts';
import { unlockPrices } from '../game-data/datasets/unlock-prices.ts';
import { UnlockShop } from '../unlocks/unlock-purchase.ts';
import { itemCatalogue } from '../game-data/datasets/item-catalogue.ts';
import { storeBundles } from '../game-data/datasets/store-bundles.ts';
import { unitNames } from '../game-data/datasets/unit-names.ts';
import { ItemCatalogue } from '../items/item-catalogue.ts';
import { StoreCatalogue } from '../store/store-catalogue.ts';
import { TechTree } from './tech-tree.ts';
export interface ResearchRules {
@@ -35,11 +38,14 @@ export interface ResearchRules {
readonly unlocks: UnlockShop;
/** Classic items: boosters, personal discounts, contracts, universal spares. */
readonly items: ItemCatalogue;
/** Paid store catalogue: GE packs, SL packs, Premium Account, vehicle packs. */
readonly store: StoreCatalogue;
}
export function loadResearchRules(datasets: DatasetCache): ResearchRules {
const vehicles = datasets.load(vehicleCatalogue);
return {
techTree: new TechTree(datasets.load(vehicleCatalogue)),
techTree: new TechTree(vehicles),
eraRequirements: datasets.load(eraRequirements),
vehicleUnlocks: datasets.load(vehicleUnlocks),
crewSlotPrices: datasets.load(crewSlotPrices),
@@ -49,5 +55,6 @@ export function loadResearchRules(datasets: DatasetCache): ResearchRules {
crew: new CrewSkillCatalogue(datasets.load(crewSkillData)),
unlocks: new UnlockShop(datasets.load(unlockPrices)),
items: new ItemCatalogue(datasets.load(itemCatalogue)),
store: new StoreCatalogue(vehicles, datasets.load(storeBundles), datasets.load(unitNames)),
};
}
+14 -8
View File
@@ -3,7 +3,7 @@
* section A; the launcher will call the same profile functions).
*
* node packages/local-service/src/save-cli.ts --game <game folder> --data <data folder>
* --player <login or user id> [--silver <n>] [--gold <n>] [--free-rp <n>]
* --player <login or user id> [--silver <n>] [--gold <n>] [--gjn <n>] [--free-rp <n>]
* [--give-item <item>[:<pieces>]]...
*
* --free-rp sets the free research points. --give-item gives classic
@@ -17,14 +17,15 @@ import { DatasetCache } from './game-data/datasets/dataset-cache.ts';
import { GameFiles } from './game-data/game-files.ts';
import type { ItemDefinition } from './game-data/datasets/item-catalogue.ts';
import { grantItem } from './items/item-grants.ts';
import { balanceOf, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts';
import { balanceOf, setGjn, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts';
import { remainingPremiumDays } from './profile/profile-entitlements.ts';
import { ownedItems } from './profile/profile-items.ts';
import { freeResearchPoints, setFreeResearchPoints } from './profile/profile-research-points.ts';
import { serverTimeNow } from './profile/server-time.ts';
import { setUpProfiles } from './profiles-setup.ts';
const USAGE = 'usage: save-cli.ts --game <game folder> --data <data folder> --player <login or user id> '
+ '[--silver <n>] [--gold <n>] [--free-rp <n>] [--give-item <item>[:<pieces>]]...';
+ '[--silver <n>] [--gold <n>] [--gjn <n>] [--free-rp <n>] [--give-item <item>[:<pieces>]]...';
function main(): number {
const { values } = parseArgs({
@@ -34,6 +35,7 @@ function main(): number {
player: { type: 'string' },
silver: { type: 'string' },
gold: { type: 'string' },
gjn: { type: 'string' },
'free-rp': { type: 'string' },
'give-item': { type: 'string', multiple: true },
},
@@ -44,9 +46,10 @@ function main(): number {
}
const silver = optionalAmount(values.silver);
const gold = optionalAmount(values.gold);
const gjn = optionalAmount(values.gjn);
const freeRp = optionalAmount(values['free-rp']);
if (silver === null || gold === null || freeRp === null) {
console.error('--silver, --gold and --free-rp take a whole number of 0 or more');
if (silver === null || gold === null || gjn === null || freeRp === null) {
console.error('--silver, --gold, --gjn and --free-rp take a whole number of 0 or more');
return 2;
}
const accounts = new AccountStore(values.data);
@@ -69,18 +72,21 @@ function main(): number {
}
gifts.push({ item, pieces });
}
const changes = silver !== undefined || gold !== undefined || freeRp !== undefined || gifts.length > 0;
const changes = silver !== undefined || gold !== undefined || gjn !== undefined || freeRp !== undefined || gifts.length > 0;
const now = serverTimeNow();
const profile = !changes
? profiles.profileOf(account.userId)
: profiles.update(account.userId, (saved) => {
if (silver !== undefined) setSilverLions(saved, silver);
if (gold !== undefined) setGoldenEagles(saved, gold);
if (gjn !== undefined) setGjn(saved, gjn);
if (freeRp !== undefined) setFreeResearchPoints(saved, freeRp);
const now = serverTimeNow();
for (const gift of gifts) grantItem(saved, gift.item, gift.pieces, now);
});
const balance = balanceOf(profile);
console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${freeResearchPoints(profile)} free research points`);
const premiumDays = remainingPremiumDays(profile, now);
const premiumNote = premiumDays > 0 ? `, premium: ${premiumDays}d` : '';
console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${balance.gjn} GJN, ${freeResearchPoints(profile)} free research points${premiumNote}`);
const items = ownedItems(profile);
if (items.length) console.log(`items: ${items.map((item) => `${item.id} x${item.count}`).join(', ')}`);
return 0;
@@ -0,0 +1,84 @@
/**
* Redeem codes (implementation notes section G; implementation notes):
* - PREMIUM-<N>D / VIP-<N>D (e.g. PREMIUM-7D, PREMIUM-30D, PREMIUM-365D): adds <N> days of
* Premium Account (1..3650 days);
* - WTO-GJN-<N> / GJN-<N> (e.g. WTO-GJN-100, WTO-GJN-1000): adds <N> GJN (1..100000);
* - WTO-STARTER (once per save): grants 7 days of Premium Account, 1,000 Golden Eagles and 100 GJN.
*/
import type { BlkBlock } from '@wto/blk';
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
import { addGoldenEagles, balanceOf, setGjn } from '../profile/profile-currency.ts';
import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts';
const STARTER_ENTITLEMENT = 'wto_redeem_starter';
export type RedeemOutcome =
| { readonly ok: true; readonly message: LocalizedText }
| { readonly ok: false; readonly reason: 'INVALID_CODE' | 'ALREADY_REDEEMED'; readonly message: LocalizedText };
export function redeemStoreCode(profile: BlkBlock, rawCode: string, nowFiletime: bigint): RedeemOutcome {
const code = rawCode.trim().toUpperCase();
if (!code) {
return { ok: false, reason: 'INVALID_CODE', message: { en: 'Enter a redeem code.', zh: '请输入兑换码。' } };
}
if (code === 'WTO-STARTER') {
if (hasEntitlement(profile, STARTER_ENTITLEMENT, nowFiletime)) {
return {
ok: false,
reason: 'ALREADY_REDEEMED',
message: { en: 'This starter code has already been redeemed on this save.', zh: '当前存档已使用过该新手礼包兑换码。' },
};
}
recordEntitlementPurchase(profile, STARTER_ENTITLEMENT);
extendPremiumAccount(profile, 7, nowFiletime);
addGoldenEagles(profile, 1_000);
setGjn(profile, balanceOf(profile).gjn + 100);
return {
ok: true,
message: {
en: 'Redeemed WTO-STARTER: +7d Premium Account, +1,000 Golden Eagles, +100 GJN.',
zh: '兑换成功:高级账户 +7 天、金鹰 +1,000、GJN +100。',
},
};
}
const premiumMatch = /^(?:PREMIUM|PREM|VIP)-(\d{1,4})D$/.exec(code);
if (premiumMatch) {
const days = Number(premiumMatch[1]);
if (days >= 1 && days <= 3_650) {
extendPremiumAccount(profile, days, nowFiletime);
return {
ok: true,
message: {
en: `Redeemed ${code}: +${days} days of Premium Account.`,
zh: `兑换成功:高级账户增加 ${days} 天。`,
},
};
}
}
const gjnMatch = /^(?:WTO-GJN|GJN)-(\d{1,6})$/.exec(code);
if (gjnMatch) {
const amount = Number(gjnMatch[1]);
if (amount >= 1 && amount <= 100_000) {
setGjn(profile, balanceOf(profile).gjn + amount);
return {
ok: true,
message: {
en: `Redeemed ${code}: +${amount.toLocaleString('en-US')} GJN.`,
zh: `兑换成功:GJN 增加 ${amount.toLocaleString('en-US')}。`,
},
};
}
}
return {
ok: false,
reason: 'INVALID_CODE',
message: {
en: 'Unknown redeem code. Examples: PREMIUM-7D, PREMIUM-30D, PREMIUM-365D, WTO-GJN-100, WTO-STARTER.',
zh: '无效的兑换码。可用示例:PREMIUM-7D、PREMIUM-30D、PREMIUM-365D、WTO-GJN-100、WTO-STARTER。',
},
};
}
@@ -0,0 +1,225 @@
/**
* Local store catalogue: Golden Eagles packs, Silver Lions packs,
* Premium Account durations (both Golden Eagles and GJN), and one vehicle pack per gift
* vehicle in the tech tree.
*/
import { emptyBlock, setParam, type BlkBlock } from '@wto/blk';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { StoreBundleGuids } from '../game-data/datasets/store-bundles.ts';
import type { LocalizedText, UnitNamesMap } from '../game-data/datasets/unit-names.ts';
export type StoreProductKind = 'eagles' | 'warpoints' | 'premium-gold' | 'premium-gjn' | 'vehicle-pack';
export interface StoreProduct {
readonly id: string;
readonly kind: StoreProductKind;
readonly chapter: string;
readonly title: LocalizedText;
/** Store item GUID when offered via item_info.php / item_purchase.php. */
readonly guid?: string;
/** Price in Golden Eagles (in-game purchase via cln_buy_entitlement). */
readonly goldCost?: number;
/** Price in GJN (onlinePurchase via item_purchase.php or the local web store). */
readonly gjnCost?: number;
/** Golden Eagles granted on purchase. */
readonly goldIncome?: number;
/** Silver Lions granted on purchase. */
readonly silverIncome?: number;
/** Premium Account days granted on purchase. */
readonly premiumDays?: number;
/** Gift vehicle granted on purchase, with any split-vehicle parts. */
readonly vehicle?: CatalogueVehicle;
}
const EAGLES_PACKS: ReadonlyArray<{ readonly id: string; readonly gold: number; readonly gjn: number }> = [
{ id: 'eagles150', gold: 150, gjn: 1 },
{ id: 'eagles500', gold: 500, gjn: 3 },
{ id: 'eagles1000', gold: 1_000, gjn: 6 },
{ id: 'eagles2500', gold: 2_500, gjn: 14 },
{ id: 'eagles5000', gold: 5_000, gjn: 25 },
{ id: 'eagles10000', gold: 10_000, gjn: 50 },
{ id: 'eagles15000', gold: 15_000, gjn: 72 },
{ id: 'eagles20000', gold: 20_000, gjn: 95 },
{ id: 'eagles25000', gold: 25_000, gjn: 115 },
];
const SILVER_LIONS_PACKS: ReadonlyArray<{ readonly id: string; readonly silver: number; readonly goldCost: number }> = [
{ id: 'warpoints1k', silver: 1_000, goldCost: 3 },
{ id: 'warpoints10k', silver: 10_000, goldCost: 30 },
{ id: 'warpoints50k', silver: 50_000, goldCost: 120 },
{ id: 'warpoints120k', silver: 120_000, goldCost: 300 },
{ id: 'warpoints630k', silver: 630_000, goldCost: 1_500 },
{ id: 'warpoints1300k', silver: 1_300_000, goldCost: 3_000 },
];
const PREMIUM_GOLD_TIERS: ReadonlyArray<{ readonly id: string; readonly days: number; readonly goldCost: number }> = [
{ id: 'prem_1d', days: 1, goldCost: 190 },
{ id: 'prem_7d', days: 7, goldCost: 690 },
{ id: 'prem_15d', days: 15, goldCost: 1_190 },
{ id: 'prem_30d', days: 30, goldCost: 1_900 },
{ id: 'prem_90d', days: 90, goldCost: 4_900 },
{ id: 'prem_365d', days: 365, goldCost: 14_900 },
];
const PREMIUM_GJN_TIERS: ReadonlyArray<{ readonly id: string; readonly fallbackGuid: string; readonly days: number; readonly gjn: number }> = [
{ id: 'wto_prem_20d', fallbackGuid: 'A1E00020-5754-4F46-8F00-000000000020', days: 20, gjn: 8 },
{ id: 'wto_prem_60d', fallbackGuid: 'A1E00060-5754-4F46-8F00-000000000060', days: 60, gjn: 20 },
{ id: 'wto_prem_180d', fallbackGuid: 'A1E00180-5754-4F46-8F00-000000000180', days: 180, gjn: 40 },
];
interface PackTier {
readonly gjn: number;
readonly bonusGold: number;
readonly bonusDays: number;
}
function packTierForRank(rank: number): PackTier {
if (rank <= 2) return { gjn: 15, bonusGold: 1_000, bonusDays: 7 };
if (rank === 3) return { gjn: 25, bonusGold: 1_000, bonusDays: 7 };
if (rank === 4) return { gjn: 35, bonusGold: 1_000, bonusDays: 7 };
if (rank === 5) return { gjn: 50, bonusGold: 2_000, bonusDays: 15 };
if (rank === 6) return { gjn: 60, bonusGold: 2_000, bonusDays: 15 };
if (rank === 7) return { gjn: 70, bonusGold: 2_500, bonusDays: 20 };
return { gjn: 75, bonusGold: 3_000, bonusDays: 30 };
}
export class StoreCatalogue {
readonly #byId = new Map<string, StoreProduct>();
readonly #byGuid = new Map<string, StoreProduct>();
readonly #priceBlk: BlkBlock;
constructor(vehicles: readonly CatalogueVehicle[], bundleGuids: StoreBundleGuids, names: UnitNamesMap) {
const products: StoreProduct[] = [];
for (const pack of EAGLES_PACKS) {
const guid = bundleGuids[pack.id];
products.push({
id: pack.id,
kind: 'eagles',
chapter: 'eagles',
title: { en: `${pack.gold.toLocaleString('en-US')} Golden Eagles`, zh: `${pack.gold.toLocaleString('en-US')} 金鹰` },
...(guid ? { guid } : {}),
gjnCost: pack.gjn,
goldIncome: pack.gold,
});
}
for (const pack of SILVER_LIONS_PACKS) {
products.push({
id: pack.id,
kind: 'warpoints',
chapter: 'warpoints',
title: { en: `${pack.silver.toLocaleString('en-US')} Silver Lions`, zh: `${pack.silver.toLocaleString('en-US')} 银狮` },
goldCost: pack.goldCost,
silverIncome: pack.silver,
});
}
for (const tier of PREMIUM_GOLD_TIERS) {
products.push({
id: tier.id,
kind: 'premium-gold',
chapter: 'premium',
title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` },
goldCost: tier.goldCost,
premiumDays: tier.days,
});
}
for (const tier of PREMIUM_GJN_TIERS) {
const guid = bundleGuids[tier.id] ?? tier.fallbackGuid;
products.push({
id: tier.id,
kind: 'premium-gjn',
chapter: 'premium',
title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` },
guid,
gjnCost: tier.gjn,
premiumDays: tier.days,
});
}
for (const vehicle of vehicles) {
if (!isPackVehicle(vehicle)) continue;
const tier = packTierForRank(vehicle.rank);
const unitLabel = names[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name };
products.push({
id: `wto_pack_${vehicle.name}`,
kind: 'vehicle-pack',
chapter: 'bonuses',
title: { en: `${unitLabel.en} Pack`, zh: `${unitLabel.zh} 礼包` },
gjnCost: tier.gjn,
goldIncome: tier.bonusGold,
premiumDays: tier.bonusDays,
vehicle,
});
}
for (const product of products) {
this.#byId.set(product.id, product);
if (product.guid) this.#byGuid.set(product.guid.toUpperCase(), product);
}
this.#priceBlk = buildEntitlementsPriceBlk(products);
}
allProducts(): readonly StoreProduct[] {
return [...this.#byId.values()];
}
byId(id: string): StoreProduct | undefined {
return this.#byId.get(id);
}
byGuid(guid: string): StoreProduct | undefined {
return this.#byGuid.get(guid.trim().toUpperCase());
}
entitlementsPriceBlk(): BlkBlock {
return this.#priceBlk;
}
}
function isPackVehicle(vehicle: CatalogueVehicle): boolean {
return vehicle.inTechTree
&& vehicle.gift
&& !vehicle.event
&& vehicle.marketplaceItemdefId === undefined
&& !vehicle.onlyShownWhenOwned;
}
function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock {
const root = emptyBlock();
for (const product of products) {
const block = emptyBlock(product.id);
setParam(block, 'chapter', { type: 'string', value: product.chapter });
if (product.kind === 'eagles') {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'group', { type: 'string', value: 'eagles100' });
setParam(block, 'useGroupAmount', { type: 'bool', value: true });
setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome! });
} else if (product.kind === 'warpoints') {
setParam(block, 'group', { type: 'string', value: '1KWP' });
setParam(block, 'useGroupAmount', { type: 'bool', value: true });
setParam(block, 'wpIncome', { type: 'int', value: product.silverIncome! });
setParam(block, 'goldCost', { type: 'int', value: product.goldCost! });
} else if (product.kind === 'premium-gold') {
setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'group', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'ttl', { type: 'int', value: product.premiumDays! });
setParam(block, 'goldCost', { type: 'int', value: product.goldCost! });
} else if (product.kind === 'premium-gjn') {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'group', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'ttl', { type: 'int', value: product.premiumDays! });
} else if (product.kind === 'vehicle-pack' && product.vehicle) {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'aircraftGift', { type: 'string', value: product.vehicle.name });
if (product.goldIncome) setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome });
}
root.blocks.push(block);
}
return root;
}
@@ -0,0 +1,326 @@
/**
* Single-page HTML interface for the local web store (/store, implementation notes;
* implementation notes section G). All dynamic data comes from /store/api/* as JSON.
*/
export function renderStorePageHtml(): string {
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>War Thunder Offline — 本地商店</title>
<style>
:root {
--bg: #11161c;
--panel: #19212b;
--panel-alt: #212b38;
--border: #2e3b4d;
--text: #e6edf5;
--muted: #93a3b5;
--accent: #e09f3e;
--accent-hover: #f0b354;
--ok: #3ea66b;
--err: #d9534f;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
background: var(--bg);
color: var(--text);
}
header {
background: var(--panel);
border-bottom: 1px solid var(--border);
padding: 14px 24px;
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
justify-content: space-between;
}
.brand { font-size: 18px; font-weight: 700; letter-spacing: 0.3px; }
.brand span { color: var(--accent); font-size: 13px; margin-left: 8px; font-weight: 500; }
.wallet {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
}
.pill {
background: var(--panel-alt);
border: 1px solid var(--border);
padding: 6px 12px;
border-radius: 6px;
font-size: 13px;
}
.pill strong { color: var(--accent); font-size: 15px; margin-left: 4px; }
select, input {
background: var(--panel-alt);
color: var(--text);
border: 1px solid var(--border);
border-radius: 6px;
padding: 7px 11px;
font-size: 14px;
}
main { max-width: 1240px; margin: 0 auto; padding: 20px 24px 48px; }
.tabs { display: flex; gap: 8px; margin-bottom: 18px; flex-wrap: wrap; }
.tab {
background: var(--panel);
color: var(--muted);
border: 1px solid var(--border);
padding: 9px 16px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
}
.tab.active { background: var(--accent); color: #11161c; border-color: var(--accent); }
.filters { display: flex; gap: 10px; margin-bottom: 16px; flex-wrap: wrap; }
.notice {
padding: 10px 14px;
border-radius: 6px;
margin-bottom: 16px;
font-size: 14px;
display: none;
}
.notice.ok { display: block; background: rgba(62, 166, 107, 0.18); border: 1px solid var(--ok); }
.notice.err { display: block; background: rgba(217, 83, 79, 0.18); border: 1px solid var(--err); }
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(265px, 1fr));
gap: 14px;
}
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
padding: 15px;
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 12px;
}
.card h3 { margin: 0 0 6px; font-size: 16px; }
.meta { color: var(--muted); font-size: 12.5px; line-height: 1.5; }
.card-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 4px; }
.price { font-size: 17px; font-weight: 700; color: var(--accent); }
button.buy {
background: var(--accent);
color: #11161c;
border: none;
border-radius: 6px;
padding: 8px 14px;
font-weight: 700;
cursor: pointer;
font-size: 13.5px;
}
button.buy:hover:not(:disabled) { background: var(--accent-hover); }
button.buy:disabled { background: var(--border); color: var(--muted); cursor: default; }
.redeem-box {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
padding: 20px;
max-width: 600px;
}
.redeem-row { display: flex; gap: 10px; margin: 12px 0 16px; }
.redeem-row input { flex: 1; }
.hint { color: var(--muted); font-size: 13px; line-height: 1.6; }
code { background: var(--panel-alt); padding: 2px 6px; border-radius: 4px; color: var(--accent); }
</style>
</head>
<body>
<header>
<div class="brand">WAR THUNDER OFFLINE <span>本地商店 · 切回游戏窗口自动同步档案</span></div>
<div class="wallet">
<select id="playerSelect" title="当前账号"></select>
<div class="pill">GJN 余额 <strong id="gjnVal">0</strong></div>
<div class="pill">金鹰 <strong id="goldVal">0</strong></div>
<div class="pill">银狮 <strong id="silverVal">0</strong></div>
<div class="pill">高级账户 <strong id="premVal">未激活</strong></div>
</div>
</header>
<main>
<div id="notice" class="notice"></div>
<div class="tabs">
<button class="tab active" data-tab="vehicle-pack">礼包载具</button>
<button class="tab" data-tab="premium-gjn">高级账户</button>
<button class="tab" data-tab="eagles">金鹰充值</button>
<button class="tab" data-tab="redeem">兑换码</button>
</div>
<div id="packFilters" class="filters">
<input id="searchInput" type="search" placeholder="搜索载具名称或代号…" style="min-width:220px">
<select id="countryFilter"><option value="">全部国家</option></select>
<select id="rankFilter"><option value="">全部等级</option></select>
</div>
<div id="grid" class="grid"></div>
<div id="redeemPanel" class="redeem-box" style="display:none">
<h3 style="margin-top:0">激活兑换码</h3>
<div class="redeem-row">
<input id="codeInput" type="text" placeholder="输入兑换码,例如 PREMIUM-30D">
<button id="redeemBtn" class="buy">立即兑换</button>
</div>
<div class="hint">
内置离线兑换码:<br>
· 高级账户天数:<code>PREMIUM-1D</code>、<code>PREMIUM-7D</code>、<code>PREMIUM-30D</code>、<code>PREMIUM-90D</code>、<code>PREMIUM-365D</code>(或任意 <code>PREMIUM-&lt;天数&gt;D</code>)<br>
· GJN 充值码:<code>WTO-GJN-100</code>、<code>WTO-GJN-1000</code>(或 <code>GJN-&lt;数量&gt;</code>)<br>
· 新手礼包(每存档一次):<code>WTO-STARTER</code>(7 天高级账户 + 1,000 金鹰 + 100 GJN)
</div>
</div>
</main>
<script>
const COUNTRY_NAMES = {
country_usa: '美国', country_germany: '德国', country_ussr: '苏联', country_britain: '英国',
country_japan: '日本', country_china: '中国', country_italy: '意大利', country_france: '法国',
country_sweden: '瑞典', country_israel: '以色列'
};
let state = { accounts: [], activeUserId: '', balance: { gjn: 0, goldenEagles: 0, silverLions: 0 }, premiumDays: 0, products: [] };
let currentTab = 'vehicle-pack';
function showNotice(text, ok) {
const el = document.getElementById('notice');
el.textContent = text;
el.className = 'notice ' + (ok ? 'ok' : 'err');
}
async function loadState(userId) {
const qs = userId ? '?userId=' + encodeURIComponent(userId) : '';
const res = await fetch('/store/api/state' + qs);
state = await res.json();
renderHeader();
populateFilters();
renderContent();
}
function renderHeader() {
const sel = document.getElementById('playerSelect');
sel.innerHTML = '';
for (const acc of state.accounts) {
const opt = document.createElement('option');
opt.value = acc.userId;
opt.textContent = acc.nick + ' (' + acc.login + ')';
if (acc.userId === state.activeUserId) opt.selected = true;
sel.appendChild(opt);
}
document.getElementById('gjnVal').textContent = state.balance.gjn.toLocaleString() + ' GJN';
document.getElementById('goldVal').textContent = state.balance.goldenEagles.toLocaleString();
document.getElementById('silverVal').textContent = state.balance.silverLions.toLocaleString();
document.getElementById('premVal').textContent = state.premiumDays > 0 ? ('剩余 ' + state.premiumDays + ' 天') : '未激活';
}
function populateFilters() {
const cSel = document.getElementById('countryFilter');
const prevC = cSel.value;
const countries = [...new Set(state.products.filter(p => p.country).map(p => p.country))];
cSel.innerHTML = '<option value="">全部国家</option>';
for (const c of countries) {
const opt = document.createElement('option');
opt.value = c;
opt.textContent = COUNTRY_NAMES[c] || c;
if (c === prevC) opt.selected = true;
cSel.appendChild(opt);
}
const rSel = document.getElementById('rankFilter');
const prevR = rSel.value;
const ranks = [...new Set(state.products.filter(p => p.rank).map(p => p.rank))].sort((a, b) => a - b);
rSel.innerHTML = '<option value="">全部等级</option>';
for (const r of ranks) {
const opt = document.createElement('option');
opt.value = String(r);
opt.textContent = '等级 ' + r;
if (String(r) === prevR) opt.selected = true;
rSel.appendChild(opt);
}
}
function renderContent() {
const isRedeem = currentTab === 'redeem';
document.getElementById('redeemPanel').style.display = isRedeem ? 'block' : 'none';
document.getElementById('grid').style.display = isRedeem ? 'none' : 'grid';
document.getElementById('packFilters').style.display = currentTab === 'vehicle-pack' ? 'flex' : 'none';
if (isRedeem) return;
const q = document.getElementById('searchInput').value.trim().toLowerCase();
const cFilter = document.getElementById('countryFilter').value;
const rFilter = document.getElementById('rankFilter').value;
const grid = document.getElementById('grid');
grid.innerHTML = '';
const items = state.products.filter(p => {
if (p.kind !== currentTab) return false;
if (currentTab === 'vehicle-pack') {
if (cFilter && p.country !== cFilter) return false;
if (rFilter && String(p.rank) !== rFilter) return false;
if (q && !(p.titleZh.toLowerCase().includes(q) || p.titleEn.toLowerCase().includes(q) || (p.unitName || '').toLowerCase().includes(q))) return false;
}
return true;
});
for (const item of items) {
const card = document.createElement('div');
card.className = 'card';
const details = [];
if (item.country) details.push((COUNTRY_NAMES[item.country] || item.country) + ' · 等级 ' + item.rank);
if (item.goldIncome) details.push('包含金鹰:' + item.goldIncome.toLocaleString());
if (item.premiumDays) details.push('包含高级账户:' + item.premiumDays + ' 天');
card.innerHTML = '<div><h3></h3><div class="meta"></div></div><div class="card-foot"><span class="price"></span><button class="buy"></button></div>';
card.querySelector('h3').textContent = item.titleZh;
card.querySelector('.meta').textContent = details.join(' | ');
card.querySelector('.price').textContent = item.gjnCost + ' GJN';
const btn = card.querySelector('button');
if (item.owned) {
btn.textContent = '已拥有';
btn.disabled = true;
} else if (!state.activeUserId) {
btn.textContent = '请先登录游戏';
btn.disabled = true;
} else {
btn.textContent = '购买';
btn.onclick = () => buyItem(item.id);
}
grid.appendChild(card);
}
}
async function buyItem(productId) {
const res = await fetch('/store/api/buy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: state.activeUserId, productId })
});
const data = await res.json();
showNotice(data.message, data.ok);
await loadState(state.activeUserId);
}
document.getElementById('playerSelect').onchange = (e) => loadState(e.target.value);
document.getElementById('searchInput').oninput = renderContent;
document.getElementById('countryFilter').onchange = renderContent;
document.getElementById('rankFilter').onchange = renderContent;
for (const tab of document.querySelectorAll('.tab')) {
tab.onclick = () => {
for (const t of document.querySelectorAll('.tab')) t.classList.remove('active');
tab.classList.add('active');
currentTab = tab.dataset.tab;
renderContent();
};
}
document.getElementById('redeemBtn').onclick = async () => {
const code = document.getElementById('codeInput').value;
const res = await fetch('/store/api/redeem', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: state.activeUserId, code })
});
const data = await res.json();
showNotice(data.message, data.ok);
if (data.ok) document.getElementById('codeInput').value = '';
await loadState(state.activeUserId);
};
loadState('');
</script>
</body>
</html>`;
}
@@ -0,0 +1,68 @@
/**
* Store purchase rules:
* - buyGoldEntitlement: Golden-Eagle-priced entitlements (Premium Account days, Silver Lions packs)
* bought through cln_buy_entitlement;
* - buyGjnProduct: GJN-priced products (Golden Eagles packs, GJN Premium Account, vehicle packs)
* bought through item_purchase.php or the local web store.
*/
import type { BlkBlock } from '@wto/blk';
import { addGoldenEagles, addSilverLions, balanceOf, canAfford, pay, payGjn } from '../profile/profile-currency.ts';
import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts';
import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts';
export function buyGoldEntitlement(
profile: BlkBlock,
catalogue: StoreCatalogue,
entitlementId: string,
offeredGoldCost: number | undefined,
nowFiletime: bigint,
): RuleOutcome {
const product = catalogue.byId(entitlementId);
if (!product || product.goldCost === undefined) return refused('BAD_PARAMS');
if (offeredGoldCost !== undefined && offeredGoldCost !== product.goldCost) return refused('PRICE_CHANGED');
const price = { silverLions: 0, goldenEagles: product.goldCost };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
grantProductRewards(profile, product, nowFiletime);
return ACCEPTED;
}
export type GjnPurchaseOutcome =
| { readonly ok: true }
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'ALREADY_BOUGHT' | 'NOT_ENOUGH_GJN' };
export function canBuyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): boolean {
if (product.gjnCost === undefined) return false;
if (product.kind === 'vehicle-pack' && product.vehicle) {
return !ownsVehicle(profile, product.vehicle.name) && !hasEntitlement(profile, product.id, nowFiletime);
}
return true;
}
export function buyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): GjnPurchaseOutcome {
if (product.gjnCost === undefined) return { ok: false, reason: 'NOT_FOUND' };
if (product.kind === 'vehicle-pack' && product.vehicle) {
if (ownsVehicle(profile, product.vehicle.name) || hasEntitlement(profile, product.id, nowFiletime)) {
return { ok: false, reason: 'ALREADY_BOUGHT' };
}
}
if (balanceOf(profile).gjn < product.gjnCost) return { ok: false, reason: 'NOT_ENOUGH_GJN' };
payGjn(profile, product.gjnCost);
grantProductRewards(profile, product, nowFiletime);
return { ok: true };
}
function grantProductRewards(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): void {
if (product.id !== 'PremiumAccount') recordEntitlementPurchase(profile, product.id);
if (product.goldIncome) addGoldenEagles(profile, product.goldIncome);
if (product.silverIncome) addSilverLions(profile, product.silverIncome);
if (product.premiumDays) extendPremiumAccount(profile, product.premiumDays, nowFiletime);
if (product.vehicle) {
addOwnedVehicle(profile, product.vehicle.name);
for (const part of product.vehicle.parts) addOwnedVehicle(profile, part);
}
}
@@ -0,0 +1,241 @@
/**
* Store service (implementation notes; implementation notes):
* 1. Native yuplay2 store API on api.gaijinent.com:
* - POST /item_info.php (multi-guid and single-guid item pricing in GJN)
* - POST /item_purchase.php (pay=gjn purchase from in-game modals)
* - POST /redeem_code.php (ActivateAction redeem code)
* 2. Local web store at /store and /store/api/* for browsing vehicle packs, viewing GJN
* balance, purchasing with GJN, and redeeming codes.
*/
import type { Account, AccountStore } from '../accounts/account-store.ts';
import { redactLoginForm } from '../login/form-redaction.ts';
import { userIdFromJwt, userIdFromToken } from '../login/session-credentials.ts';
import { yuplayAnswer } from '../login/yuplay-answer.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { balanceOf } from '../profile/profile-currency.ts';
import { remainingPremiumDays } from '../profile/profile-entitlements.ts';
import { serverTimeNow } from '../profile/server-time.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import { redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts';
import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts';
import { renderStorePageHtml } from './store-page.ts';
import { buyGjnProduct, canBuyGjnProduct, type GjnPurchaseOutcome } from './store-purchase.ts';
const STORE_API_PATHS = new Set(['/item_info.php', '/item_purchase.php', '/redeem_code.php']);
export class StoreService implements Service {
readonly name = 'store';
readonly #accounts: AccountStore;
readonly #profiles: PlayerProfiles;
readonly #catalogue: StoreCatalogue;
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue) {
this.#accounts = accounts;
this.#profiles = profiles;
this.#catalogue = catalogue;
}
accepts(request: ServiceRequest): boolean {
if (request.path === '/store' || request.path.startsWith('/store/')) return true;
if (!STORE_API_PATHS.has(request.path)) return false;
return request.originalHost === undefined || request.originalHost === 'api.gaijinent.com' || request.originalHost === 'store.gaijin.net';
}
handle(request: ServiceRequest): ServiceResponse {
if (request.path === '/store' || request.path === '/store/') return this.#storePage();
if (request.path === '/store/api/state' && request.method === 'GET') return this.#webState(request);
if (request.path === '/store/api/buy' && request.method === 'POST') return this.#webBuy(request);
if (request.path === '/store/api/redeem' && request.method === 'POST') return this.#webRedeem(request);
const redacted = redactLoginForm(request.body);
const apiResponse = request.method !== 'POST'
? yuplayAnswer('ERROR', {}, `${request.method} ${request.path} not supported`)
: request.path === '/item_info.php'
? this.#itemInfo(request)
: request.path === '/item_purchase.php'
? this.#itemPurchase(request)
: this.#redeemCode(request);
return { ...apiResponse, logNotes: { ...apiResponse.logNotes, redactedRequestBody: redacted, requestText: redacted } };
}
#itemInfo(request: ServiceRequest): ServiceResponse {
const form = new URLSearchParams(request.body.toString('utf8'));
const guids = [...form.getAll('guids[]'), ...form.getAll('guids'), ...form.getAll('guid')].filter(Boolean);
const account = this.#accountFromForm(form);
const profile = account ? this.#profiles.profileOf(account.userId) : undefined;
const now = serverTimeNow();
const items: Record<string, unknown> = {};
let numericId = 1;
for (const rawGuid of guids) {
const product = this.#catalogue.byGuid(rawGuid);
if (!product || product.gjnCost === undefined) continue;
const canBuy = profile ? canBuyGjnProduct(profile, product, now) : true;
items[rawGuid] = {
item_id: numericId++,
shop_price: product.gjnCost,
price_usd: product.gjnCost,
discount_mul: 1.0,
discount_till: 0,
title: product.title.en,
url: '',
short_desc: product.title.en,
shop_price_curr: 'gjn',
multi_purch: product.kind !== 'vehicle-pack',
can_be_bought: canBuy,
};
}
return yuplayAnswer('OK', { items }, `item_info (${Object.keys(items).length}/${guids.length} items)`);
}
#itemPurchase(request: ServiceRequest): ServiceResponse {
const form = new URLSearchParams(request.body.toString('utf8'));
const account = this.#accountFromForm(form);
if (!account) return yuplayAnswer('LOGINERROR', {}, 'item_purchase: unknown token');
const payMethod = (form.get('pay') ?? 'gjn').toLowerCase();
if (payMethod !== 'gjn') return yuplayAnswer('BADPAYMENT', {}, `item_purchase: unsupported pay=${payMethod}`);
const guid = form.get('guid') ?? '';
const product = this.#catalogue.byGuid(guid);
if (!product) return yuplayAnswer('NOTFOUND', {}, `item_purchase: unknown guid ${guid}`);
let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' };
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = buyGjnProduct(saved, product, now);
return outcome.ok;
});
if (outcome.ok) return yuplayAnswer('OK', {}, `item_purchase ${product.id} (${product.gjnCost} GJN)`);
if (outcome.reason === 'NOT_ENOUGH_GJN') return yuplayAnswer('NOMONEY', {}, `item_purchase ${product.id}: insufficient GJN`);
if (outcome.reason === 'ALREADY_BOUGHT') return yuplayAnswer('ALREADY', {}, `item_purchase ${product.id}: already owned`);
return yuplayAnswer('NOTFOUND', {}, `item_purchase ${product.id}: not available`);
}
#redeemCode(request: ServiceRequest): ServiceResponse {
const form = new URLSearchParams(request.body.toString('utf8'));
const account = this.#accountFromForm(form);
if (!account) return yuplayAnswer('LOGINERROR', {}, 'redeem_code: unknown token');
const code = form.get('code') ?? '';
let outcome: RedeemOutcome = { ok: false, reason: 'INVALID_CODE', message: { en: '', zh: '' } };
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = redeemStoreCode(saved, code, now);
return outcome.ok;
});
if (outcome.ok) return yuplayAnswer('OK', {}, `redeem_code ${code} -> OK`);
return yuplayAnswer(outcome.reason === 'ALREADY_REDEEMED' ? 'ALREADY' : 'NOTFOUND', {}, `redeem_code ${code} -> ${outcome.reason}`);
}
#storePage(): ServiceResponse {
return {
status: 200,
headers: { 'content-type': 'text/html; charset=utf-8' },
body: renderStorePageHtml(),
logNotes: { summary: 'store web page' },
};
}
#webState(request: ServiceRequest): ServiceResponse {
const requestedId = request.query.get('userId') ?? '';
const account = (requestedId ? this.#accounts.byUserId(requestedId) : undefined) ?? this.#accounts.activeAccount();
const now = serverTimeNow();
const profile = account ? this.#profiles.profileOf(account.userId) : undefined;
const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjn: 0 };
const premiumDays = profile ? remainingPremiumDays(profile, now) : 0;
const products = this.#catalogue.allProducts()
.filter((product) => product.gjnCost !== undefined)
.map((product) => toWebProduct(product, profile ? !canBuyGjnProduct(profile, product, now) : false));
return jsonResponse({
accounts: this.#accounts.all().map((entry) => ({ userId: entry.userId, login: entry.login, nick: entry.nick })),
activeUserId: account?.userId ?? '',
balance,
premiumDays,
products,
}, 'store web state');
}
#webBuy(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const userId = typeof body.userId === 'string' ? body.userId : '';
const productId = typeof body.productId === 'string' ? body.productId : '';
const account = this.#accounts.byUserId(userId);
const product = this.#catalogue.byId(productId);
if (!account || !product || product.gjnCost === undefined) {
return jsonResponse({ ok: false, message: '未找到账号或商品。' }, 'store web buy: invalid request');
}
let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' };
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = buyGjnProduct(saved, product, now);
return outcome.ok;
});
if (outcome.ok) {
return jsonResponse({ ok: true, message: `已购买「${product.title.zh}」(花费 ${product.gjnCost} GJN)。切回游戏窗口即可自动刷新。` }, `store web buy ${product.id}`);
}
const msg = outcome.reason === 'NOT_ENOUGH_GJN'
? `GJN 余额不足(需要 ${product.gjnCost} GJN,可在兑换码页使用 GJN 充值码或运行 save-cli --gjn)。`
: outcome.reason === 'ALREADY_BOUGHT'
? '已拥有该礼包载具。'
: '该商品当前不可购买。';
return jsonResponse({ ok: false, message: msg }, `store web buy ${product.id}: ${outcome.reason}`);
}
#webRedeem(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const userId = typeof body.userId === 'string' ? body.userId : '';
const code = typeof body.code === 'string' ? body.code : '';
const account = this.#accounts.byUserId(userId);
if (!account) return jsonResponse({ ok: false, message: '请先在游戏内登录一个本地账号。' }, 'store web redeem: no account');
let outcome: RedeemOutcome = { ok: false, reason: 'INVALID_CODE', message: { en: '', zh: '无效的兑换码。' } };
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = redeemStoreCode(saved, code, now);
return outcome.ok;
});
return jsonResponse({ ok: outcome.ok, message: outcome.message.zh }, `store web redeem ${code.trim() || '(empty)'}`);
}
#accountFromForm(form: URLSearchParams): Account | undefined {
const userId = userIdFromToken(form.get('token') ?? undefined) ?? userIdFromJwt(form.get('jwt') ?? undefined);
return (userId ? this.#accounts.byUserId(userId) : undefined) ?? this.#accounts.activeAccount();
}
}
function toWebProduct(product: StoreProduct, owned: boolean): Record<string, unknown> {
return {
id: product.id,
kind: product.kind,
titleZh: product.title.zh,
titleEn: product.title.en,
gjnCost: product.gjnCost,
...(product.goldIncome ? { goldIncome: product.goldIncome } : {}),
...(product.premiumDays ? { premiumDays: product.premiumDays } : {}),
...(product.vehicle ? { unitName: product.vehicle.name, country: product.vehicle.country, rank: product.vehicle.rank } : {}),
owned,
};
}
function parseJsonBody(raw: Buffer): Record<string, unknown> {
try {
const parsed = JSON.parse(raw.toString('utf8')) as unknown;
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};
} catch {
return {};
}
}
function jsonResponse(payload: unknown, summary: string): ServiceResponse {
const body = JSON.stringify(payload);
return {
status: 200,
headers: { 'content-type': 'application/json; charset=utf-8' },
body,
logNotes: { summary, responseText: body },
};
}