feat(inventory): add external inventory, marketplace, and supply chests

Define external inventory items and support GJN purchases, recycling,
and supply chest drops.
This commit is contained in:
N0VAN0M4LY committed 2026-11-25 07:19:07 +08:00
1 parent 129d796095
commit 415f78e761
27 files changed
+2538 -15

No files matched your search

+7 -1
View File
@@ -10,12 +10,13 @@
* native/wto-net/build.ps1, and its settings wto_ws.cfg). The stock folder is only read.
* The launcher will run the same steps at every launch, with the port the player chose.
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { parseArgs } from 'node:util';
import { rebuildCharPack } from './char-pack.ts';
import { patchExecutable } from './executable.ts';
import { assertWritableCopy, GAME_FILES } from './game-copy.ts';
import { rebuildGuiPack } from './gui-pack.ts';
import { rebuildMainPack } from './main-pack.ts';
import { localEndpoint } from './network/local-endpoint.ts';
import { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts';
@@ -63,8 +64,12 @@ function main(): number {
console.log(`settings.blk: ${mainPack.addresses.length} address(es) now point to ${endpoint.host}:${endpoint.port}`);
for (const change of mainPack.addresses) console.log(` ${change.path}: ${change.before} -> ${change.after}`);
const guiPack = rebuildGuiPack(readFileSync(join(values.game, GAME_FILES.guiPack)), endpoint);
console.log('gui.vromfs.bin: local URLs bypass external SSO redirect');
writeOutput(values.out, GAME_FILES.charPack, charPack.pack);
writeOutput(values.out, GAME_FILES.mainPack, mainPack.pack);
writeOutput(values.out, GAME_FILES.guiPack, guiPack);
writeOutput(values.out, GAME_FILES.executable, executable.executable);
const executableFolder = dirname(GAME_FILES.executable);
writeOutput(values.out, join(executableFolder, NETWORK_HOOK_LIBRARY), readFileSync(hookLibraryPath));
@@ -76,6 +81,7 @@ function main(): number {
function writeOutput(folder: string, relativePath: string, content: Uint8Array): void {
const path = join(folder, relativePath);
mkdirSync(dirname(path), { recursive: true });
rmSync(path, { force: true });
writeFileSync(path, content);
console.log(`wrote ${path}`);
}
+1
View File
@@ -9,6 +9,7 @@ import { join, resolve, sep } from 'node:path';
export const GAME_FILES = {
charPack: 'char.vromfs.bin',
mainPack: 'aces.vromfs.bin',
guiPack: 'gui.vromfs.bin',
executable: join('win64', 'aces.exe'),
} as const;
+33
View File
@@ -0,0 +1,33 @@
/**
* Rebuild gui.vromfs.bin so local loopback URLs open directly in the player's browser
* instead of routing through Gaijin's external SSO login endpoint.
*
* Why a client pack edit is required:
* scripts/inventory/inventoryclient.nut getMarketplaceBaseUrl() prepends `auto_login` to
* marketplaceURL. In scripts/onlineshop/url.nut, `auto_login` invokes native SsoLoggedUrlAction
* (yu_sessionProc.cpp:951), which constructs a hardcoded `https://login.gaijin.net/sso/LoginByStoken`
* URL (no option override in YuSession::setOptionStringSync) and hands it to shell_launch().
* Because the external OS browser does not load wto_ws.dll, it connects to the real
* login.gaijin.net; and returning an error from getShortToken falls back to a base64-encoded
* notAuthUrl that shell_launch() cannot open. Skipping `auto_login` when the target URL is the
* local service endpoint lets every local web UI (/store, /trade.gaijin.net) open directly.
*/
import { getFile, putFile, readArchive, writeArchive } from '@wto/vromfs';
import type { LocalEndpoint } from './network/local-endpoint.ts';
export const URL_SCRIPT_PATH = 'scripts/onlineshop/url.nut';
const STOCK_AUTO_LOGIN_LINE = ' let shouldLogin = isInArray(URL_TAG_AUTO_LOGIN, urlTags)';
export function rebuildGuiPack(stockPack: Uint8Array, endpoint: LocalEndpoint): Uint8Array {
const archive = readArchive(stockPack);
const source = Buffer.from(getFile(archive, URL_SCRIPT_PATH)).toString('utf8');
if (!source.includes(STOCK_AUTO_LOGIN_LINE)) {
throw new Error(`${URL_SCRIPT_PATH} does not contain the expected auto_login check; this game build differs from the verified ones`);
}
const localPrefix = `://${endpoint.host}:${endpoint.port}`;
const replacement = `${STOCK_AUTO_LOGIN_LINE} && url.indexof("${localPrefix}") == null`;
const updated = source.replace(STOCK_AUTO_LOGIN_LINE, replacement);
putFile(archive, URL_SCRIPT_PATH, Buffer.from(updated, 'utf8'));
return writeArchive(archive);
}
+1
View File
@@ -6,6 +6,7 @@
export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts';
export { patchExecutable, type ExecutableResult } from './executable.ts';
export { assertWritableCopy, GAME_FILES } from './game-copy.ts';
export { URL_SCRIPT_PATH, rebuildGuiPack } from './gui-pack.ts';
export { ENGINE_SETTINGS_PATH, rebuildMainPack, type MainPackResult } from './main-pack.ts';
export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts';
@@ -17,15 +17,25 @@ 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 {
buyTrophyAction,
consumeInventoryItemAction,
inventoryExchangeAction,
multiConsumeInventoryItemsAction,
purchaseInventoryItemAction,
recycleItemsAction,
} from './inventory-actions.ts';
import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts';
export interface ActionDependencies {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly notifyInventoryChanged?: () => void;
}
export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharActionHandler> {
const notifyInventory = deps.notifyInventoryChanged ?? (() => {});
return new Map<string, CharActionHandler>([
['cln_get_initial_meta', initialMeta()],
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
@@ -65,5 +75,11 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharA
['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)],
['cln_consume_inventory_item', consumeInventoryItemAction(deps.profiles, deps.accounts, deps.research, notifyInventory)],
['cln_multi_consume_inventory_item_json', multiConsumeInventoryItemsAction(deps.profiles, deps.accounts, deps.research, notifyInventory)],
['cln_inventory_purchase_item', purchaseInventoryItemAction(deps.profiles, deps.accounts, deps.research, notifyInventory)],
['cln_recycle_items', recycleItemsAction(deps.profiles, deps.accounts, deps.research, notifyInventory)],
['cln_inventory_exchange_items', inventoryExchangeAction(deps.profiles, deps.accounts, deps.research)],
['cln_buy_trophy', buyTrophyAction(deps.profiles, deps.accounts, deps.research)],
]);
}
@@ -0,0 +1,207 @@
/**
* Char actions for external inventory, item recycling, and classic trophies
*:
* - cln_consume_inventory_item itemId:i quantity:i -> full profile
* - cln_multi_consume_inventory_item_json text BLK items{ item{ itemId:i quantity:i } } -> JSON {"revertedItems":[]}
* - cln_inventory_purchase_item key:t itemDefId:i wpCost:i goldCost:i [amount:i] -> full profile
* - cln_recycle_items items{ item{ itemId:t [count:i] } } -> full profile
* - cln_inventory_exchange_items JSON { outputitemdefid, quantity, materials } -> JSON item_json delta
* - cln_buy_trophy name:t index:i cost:i costGold:i -> full profile
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import {
consumeInventoryCoupon,
exchangeInventoryItems,
multiConsumeInventoryItems,
purchaseExternalInventoryItem,
recycleClassicItems,
type ExchangeMaterialInput,
} from '../../inventory/inventory-rules.ts';
import { buyTrophy } from '../../inventory/trophy-catalogue.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 type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
function profileRuleWithNotify(
profiles: PlayerProfiles,
accounts: AccountStore,
notifyInventoryChanged: () => void,
fromPayload: (payload: BlkBlock) => ((profile: BlkBlock) => RuleOutcome) | undefined,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const rule = context.payload && fromPayload(context.payload);
if (!rule) return { kind: 'error', code: 'BAD_PARAMS' };
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const saved = profiles.updateWhen(account.userId, (profile) => {
outcome = rule(profile);
return outcome.ok;
});
if (!saved) return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
notifyInventoryChanged();
return { kind: 'data', blk: clientProfile(saved, account) };
});
}
export function consumeInventoryItemAction(
profiles: PlayerProfiles,
accounts: AccountStore,
rules: ResearchRules,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemId = intParam(payload, 'itemId');
const quantity = intParam(payload, 'quantity') ?? 1;
if (itemId === undefined) return undefined;
return (profile) => consumeInventoryCoupon(profile, rules.inventory, rules.items, String(itemId), quantity, serverTimeNow());
});
}
export function purchaseInventoryItemAction(
profiles: PlayerProfiles,
accounts: AccountStore,
rules: ResearchRules,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemDefId = intParam(payload, 'itemDefId');
if (itemDefId === undefined) return undefined;
const amount = intParam(payload, 'amount') ?? 1;
const wpCost = intParam(payload, 'wpCost') ?? 0;
const goldCost = intParam(payload, 'goldCost') ?? 0;
return (profile) => purchaseExternalInventoryItem(profile, rules.inventory, itemDefId, amount, wpCost, goldCost);
});
}
export function recycleItemsAction(
profiles: PlayerProfiles,
accounts: AccountStore,
rules: ResearchRules,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemsBlock = payload.blocks.find((b) => b.name === 'items');
if (!itemsBlock) return undefined;
const requests = itemsBlock.blocks
.filter((b) => b.name === 'item')
.map((b) => ({
uid: stringParam(b, 'itemId') ?? '',
count: intParam(b, 'count') ?? 1,
}));
if (requests.length === 0) return undefined;
return (profile) => recycleClassicItems(profile, rules.items, requests);
});
}
export function multiConsumeInventoryItemsAction(
profiles: PlayerProfiles,
accounts: AccountStore,
rules: ResearchRules,
notifyInventoryChanged: () => void,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const requests = parseMultiConsumeItems(context.payload, context.rawText);
if (requests.length === 0) return { kind: 'json', data: { revertedItems: [] } };
let revertedItems: number[] = [];
profiles.update(account.userId, (saved) => {
const res = multiConsumeInventoryItems(saved, rules.inventory, rules.items, requests, serverTimeNow());
revertedItems = res.revertedItems;
});
notifyInventoryChanged();
return { kind: 'json', data: { revertedItems } };
});
}
export function inventoryExchangeAction(
profiles: PlayerProfiles,
accounts: AccountStore,
rules: ResearchRules,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(context.rawText) as Record<string, unknown>;
} catch {
return { kind: 'error', code: 'BAD_JSON' };
}
const outputItemDefId = Number(parsed.outputitemdefid ?? 0);
const quantity = Number(parsed.quantity ?? 1);
const rawMaterials = Array.isArray(parsed.materials) ? parsed.materials : [];
const materials: ExchangeMaterialInput[] = rawMaterials.flatMap((m) => {
if (typeof m !== 'object' || m === null) return [];
const rec = m as Record<string, unknown>;
return [{
itemid: String(rec.itemid ?? ''),
itemdefid: Number(rec.itemdefid ?? 0),
quantity: Number(rec.quantity ?? 0),
}];
});
let delta: unknown[] | undefined;
let errorCode = 'EXCHANGE_FAILED';
profiles.updateWhen(account.userId, (saved) => {
const res = exchangeInventoryItems(saved, account.userId, rules.inventory, outputItemDefId, quantity, materials);
if (!res.ok) {
errorCode = res.code;
return false;
}
delta = res.delta;
return true;
});
if (!delta) return { kind: 'error', code: errorCode };
return { kind: 'json', data: { response: { item_json: delta } } };
});
}
export function buyTrophyAction(
profiles: PlayerProfiles,
accounts: AccountStore,
rules: ResearchRules,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
if (!name) return undefined;
const cost = intParam(payload, 'cost') ?? 0;
const costGold = intParam(payload, 'costGold') ?? 0;
return (profile) => buyTrophy(profile, rules.trophies, rules.items, name, cost, costGold, serverTimeNow());
});
}
function parseMultiConsumeItems(
blk: BlkBlock | undefined,
rawText: string,
): Array<{ readonly itemId: number; readonly quantity: number }> {
const fromBlk = blk?.blocks.find((b) => b.name === 'items');
if (fromBlk) {
return fromBlk.blocks
.filter((b) => b.name === 'item')
.flatMap((b) => {
const itemId = intParam(b, 'itemId');
const quantity = intParam(b, 'quantity') ?? 1;
return itemId !== undefined && quantity > 0 ? [{ itemId, quantity }] : [];
});
}
// `DataBlock.formatAsString()` emits `item{\n itemId:i=1\n quantity:i=1\n}` text blocks.
const results: Array<{ readonly itemId: number; readonly quantity: number }> = [];
const blockRegex = /item\s*\{([^}]*)\}/g;
let match: RegExpExecArray | null;
while ((match = blockRegex.exec(rawText)) !== null) {
const body = match[1] ?? '';
const idMatch = /itemId:i\s*=\s*(\d+)/.exec(body);
const qtyMatch = /quantity:i\s*=\s*(\d+)/.exec(body);
if (idMatch) {
const itemId = Number(idMatch[1]);
const quantity = qtyMatch ? Number(qtyMatch[1]) : 1;
if (Number.isSafeInteger(itemId) && quantity > 0) results.push({ itemId, quantity });
}
}
return results;
}
@@ -7,6 +7,8 @@ export interface CharActionContext {
readonly userId: string | undefined;
/** The request's BLK parameters, when the body carried a BLK. */
readonly payload: BlkBlock | undefined;
/** Raw UTF-8 request body text, for EATT_JSON_REQUEST custom actions. */
readonly rawText: string;
/**
* A request parameter sent as an HTTP header: char_request_blk_from_server (scripts
* charRequestBlk) sends the top-level parameters of its BLK that way and no body (lab round
@@ -11,6 +11,7 @@ import { encodeDataAnswer } from './char-payload.ts';
export type CharAnswer =
| { readonly kind: 'data'; readonly blk: BlkBlock }
| { readonly kind: 'json'; readonly data: unknown }
| { readonly kind: 'done' }
| { readonly kind: 'error'; readonly code: string };
@@ -18,6 +19,10 @@ export function toResponse(answer: CharAnswer): ServiceResponse {
switch (answer.kind) {
case 'data':
return { status: 200, headers: BINARY, body: encodeDataAnswer(answer.blk), logNotes: { responseText: formatBlkText(answer.blk) } };
case 'json': {
const body = JSON.stringify(answer.data);
return { status: 200, headers: JSON_HEADERS, body, logNotes: { responseText: body } };
}
case 'done':
return { status: 200, headers: TEXT, body: '!OK' };
case 'error':
@@ -26,4 +31,5 @@ export function toResponse(answer: CharAnswer): ServiceResponse {
}
const BINARY = { 'content-type': 'application/octet-stream' };
const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' };
const TEXT = { 'content-type': 'text/plain' };
@@ -37,7 +37,12 @@ export class CharService implements Service {
const payload = decodeRequestPayload(request.body);
const handler = this.#actions.get(action);
const answer: CharAnswer = handler
? handler({ userId: header(request, 'uidhint'), payload: payload.blk, headerParam: (name) => header(request, name.toLowerCase()) })
? handler({
userId: header(request, 'uidhint'),
payload: payload.blk,
rawText: payload.text,
headerParam: (name) => header(request, name.toLowerCase()),
})
: { kind: 'data', blk: emptyBlock() };
const response = toResponse(answer);
return {
@@ -0,0 +1,157 @@
/**
* Dataset: stock game references to external inventory itemdef IDs outside shop.blk vehicles
*:
* - Decorator marketplace coupons in char.vromfs.bin config/{skins,decals,attachable}.blk;
* - Unlock/pilot-icon marketplace coupons in char.vromfs.bin config/unlocks.blk;
* - Workshop referenced itemdef IDs in aces.vromfs.bin config/workshop.blk.
*/
import type { BlkBlock } from '@wto/blk';
import { numberField, stringField } from './blk-fields.ts';
import type { Dataset, DatasetSource } from './dataset.ts';
import type { DecorKind } from './decor-catalogue.ts';
import type { LocalizedText } from './unit-names.ts';
export interface MarketplaceDecorCoupon {
readonly itemdefId: number;
readonly kind: DecorKind;
readonly resourceKey: string;
readonly rarityColor?: string;
readonly name: LocalizedText;
}
export interface MarketplaceUnlockCoupon {
readonly itemdefId: number;
readonly unlockId: string;
readonly unlockType: string;
readonly name: LocalizedText;
}
export interface ExternalItemSources {
readonly decorCoupons: readonly MarketplaceDecorCoupon[];
readonly unlockCoupons: readonly MarketplaceUnlockCoupon[];
readonly workshopItemdefIds: readonly number[];
}
const DECOR_FILES: readonly { kind: DecorKind; blkPath: string; csvPath: string }[] = [
{ kind: 'skin', blkPath: 'config/skins.blk', csvPath: 'lang/unlocks_skins.csv' },
{ kind: 'decal', blkPath: 'config/decals.blk', csvPath: 'lang/unlocks_decals.csv' },
{ kind: 'attachable', blkPath: 'config/attachable.blk', csvPath: 'lang/unlocks_attachables.csv' },
];
export const externalItemSources: Dataset<ExternalItemSources> = {
id: 'external-item-sources',
version: 1,
extract: (source) => {
const decorCoupons = DECOR_FILES.flatMap(({ kind, blkPath, csvPath }) => extractDecorCoupons(source, kind, blkPath, csvPath));
const unlockCoupons = extractUnlockCoupons(source);
const workshopItemdefIds = [...collectWorkshopIds(source.readBlk('aces.vromfs.bin', 'config/workshop.blk'))].sort((a, b) => a - b);
return { decorCoupons, unlockCoupons, workshopItemdefIds };
},
};
function extractDecorCoupons(
source: DatasetSource,
kind: DecorKind,
blkPath: string,
csvPath: string,
): MarketplaceDecorCoupon[] {
const locMap = parseCsvNames(source.readText('lang.vromfs.bin', csvPath));
const root = source.readBlk('char.vromfs.bin', blkPath);
const out: MarketplaceDecorCoupon[] = [];
for (const entry of root.blocks) {
const itemdefId = numberField(entry, 'marketplaceItemdefId');
if (!itemdefId || itemdefId <= 0) continue;
const key = entry.name;
const localized = locMap.get(key)
?? locMap.get(`decals/${key}`)
?? locMap.get(`attachables/${key}`)
?? { en: humanizeKey(key), zh: humanizeKey(key) };
const rarityColor = stringField(entry, 'userlogColoredText') ?? undefined;
out.push({ itemdefId, kind, resourceKey: key, ...(rarityColor ? { rarityColor } : {}), name: localized });
}
return out;
}
function extractUnlockCoupons(source: DatasetSource): MarketplaceUnlockCoupon[] {
const menuLoc = parseCsvNames(source.readText('lang.vromfs.bin', 'lang/menu.csv'));
const achieveLoc = parseCsvNames(source.readText('lang.vromfs.bin', 'lang/unlocks_achievements.csv'));
const root = source.readBlk('char.vromfs.bin', 'config/unlocks.blk');
const out: MarketplaceUnlockCoupon[] = [];
for (const entry of root.blocks) {
const itemdefId = numberField(entry, 'marketplaceItemdefId');
const unlockId = stringField(entry, 'id');
if (!itemdefId || itemdefId <= 0 || !unlockId) continue;
const unlockType = stringField(entry, 'type') ?? 'unlock';
const localized = achieveLoc.get(`${unlockId}/name`)
?? menuLoc.get(`${unlockId}/name`)
?? achieveLoc.get(unlockId)
?? menuLoc.get(unlockId)
?? { en: humanizeKey(unlockId), zh: humanizeKey(unlockId) };
out.push({ itemdefId, unlockId, unlockType, name: localized });
}
return out;
}
function collectWorkshopIds(block: BlkBlock, out = new Set<number>()): Set<number> {
for (const param of block.params) {
if (param.value.type === 'int' && param.value.value >= 1000) out.add(param.value.value);
else if (param.value.type === 'string' && /^\d{4,}$/.test(param.value.value)) out.add(Number(param.value.value));
}
if (/^\d{4,}$/.test(block.name)) out.add(Number(block.name));
for (const child of block.blocks) collectWorkshopIds(child, out);
return out;
}
function parseCsvNames(csvText: string): Map<string, LocalizedText> {
const lines = csvText.split(/\r?\n/);
const header = parseSemicolonRow(lines[0] ?? '');
const idIdx = 0;
const enIdx = Math.max(1, header.findIndex((col) => col.includes('<English>')));
const zhIdx = header.findIndex((col) => col.includes('<Chinese>'));
const hzhIdx = header.findIndex((col) => col.includes('<HChinese>'));
const map = new Map<string, LocalizedText>();
for (let i = 1; i < lines.length; i += 1) {
const line = lines[i];
if (!line) continue;
const cols = parseSemicolonRow(line);
const id = cols[idIdx];
if (!id) continue;
const en = cleanText(cols[enIdx] ?? '') || id;
const zh = cleanText((zhIdx >= 0 ? cols[zhIdx] : '') || (hzhIdx >= 0 ? cols[hzhIdx] : '') || '') || en;
map.set(id, { en, zh });
}
return map;
}
function parseSemicolonRow(line: string): string[] {
const fields: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i]!;
if (ch === '"') {
if (inQuotes && line[i + 1] === '"') {
current += '"';
i += 1;
} else {
inQuotes = !inQuotes;
}
} else if (ch === ';' && !inQuotes) {
fields.push(current);
current = '';
} else {
current += ch;
}
}
fields.push(current);
return fields;
}
function cleanText(text: string): string {
return text.replace(/\u200b/g, '').trim();
}
function humanizeKey(key: string): string {
const leaf = key.includes('/') ? key.slice(key.indexOf('/') + 1) : key;
return leaf.replace(/[_-]+/g, ' ').replace(/\b[a-z]/g, (ch) => ch.toUpperCase());
}
@@ -66,11 +66,13 @@ export interface ItemDefinition {
readonly spare?: SpareConditions;
readonly wager?: WagerLimits;
readonly discount?: DiscountDefinition;
/** External inventory craft-part itemdef id granted on recycling (299000..299004; implementation notes). */
readonly recycleItemResult?: number;
}
export const itemCatalogue: Dataset<readonly ItemDefinition[]> = {
id: 'item-catalogue',
version: 1,
version: 2,
extract: (source) => source.readBlk('char.vromfs.bin', ITEMS).blocks.flatMap(itemOf),
};
@@ -81,6 +83,7 @@ function itemOf(entry: BlkBlock): ItemDefinition[] {
const lifetimeHoursAfterActivation = positive(numberField(entry, 'expiredTimeHAfterActivation'));
const expiresAt = utcTime(stringField(entry, 'expiredAt'));
const purchaseFeature = stringField(entry, 'purchase_feature');
const recycleItemResult = positive(numberField(entry, 'recycleItemResult'));
const spare = spareOf(blockAt(entry, 'universalSpareParams'));
const wager = wagerOf(blockAt(entry, 'wagerParams'));
const discount = discountOf(blockAt(entry, 'personalDiscountsParams'));
@@ -95,6 +98,7 @@ function itemOf(entry: BlkBlock): ItemDefinition[] {
...(lifetimeHours !== undefined ? { lifetimeHours } : {}),
...(lifetimeHoursAfterActivation !== undefined ? { lifetimeHoursAfterActivation } : {}),
...(expiresAt !== undefined ? { expiresAt } : {}),
...(recycleItemResult !== undefined ? { recycleItemResult } : {}),
...(spare ? { spare } : {}),
...(wager ? { wager } : {}),
...(discount ? { discount } : {}),
@@ -0,0 +1,268 @@
/**
* Rules for external inventory consumption, item recycling, generator exchanges (chest
* opening and workshop/recycle crafting), and GJN marketplace coupon purchases
*.
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import { grantItem } from '../items/item-grants.ts';
import type { ItemCatalogue } from '../items/item-catalogue.ts';
import { balanceOf, canAfford, pay, payGjn } from '../profile/profile-currency.ts';
import {
consumeExternalItem,
externalInventoryItems,
externalItemByUid,
grantExternalItem,
type StoredExternalItem,
} from '../profile/profile-external-inventory.ts';
import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts';
import { ownedItem, removeItem, setItemCount } from '../profile/profile-items.ts';
import { addResource, ownsResource } from '../profile/profile-resources.ts';
import { appendUserLog, EULT_OPEN_TROPHY } from '../profile/profile-trophies-log.ts';
import { addUnlock, earnedUnlocks } from '../profile/profile-unlocks.ts';
import type { ServerTime } from '../profile/server-time.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
import type { GeneratorDrop, InventoryItemJson } from './itemdef-types.ts';
export function toInventoryJsonList(profile: BlkBlock, accountId: string): InventoryItemJson[] {
return externalInventoryItems(profile).map((item) => toInventoryJson(item, accountId));
}
export function toInventoryJson(item: StoredExternalItem, accountId: string): InventoryItemJson {
return {
itemid: item.itemId,
itemdef: item.itemDefId,
accountid: accountId,
quantity: item.quantity,
state: 'none',
timestamp: item.timestamp,
};
}
/** `cln_consume_inventory_item` (char_send_blk): consume coupon(s) into vehicles, decor, unlocks or items. */
export function consumeInventoryCoupon(
profile: BlkBlock,
catalogue: InventoryCatalogue,
classicItems: ItemCatalogue,
itemUid: string,
quantity: number,
now: ServerTime,
): RuleOutcome {
if (quantity < 1) return refused('BAD_PARAMS');
const held = externalItemByUid(profile, itemUid);
if (!held || held.quantity < quantity) return refused('NOT_AVAILABLE');
const action = catalogue.couponAction(held.itemDefId);
if (!action) return refused('NOT_AVAILABLE');
switch (action.kind) {
case 'vehicle': {
if (ownsVehicle(profile, action.unitName)) return refused('NOT_AVAILABLE');
if (!consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
addOwnedVehicle(profile, action.unitName);
for (const part of action.parts) addOwnedVehicle(profile, part);
return ACCEPTED;
}
case 'decor': {
if (ownsResource(profile, action.resourceKey)) return refused('NOT_AVAILABLE');
if (!consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
addResource(profile, action.resourceKey, { silverLions: 0, goldenEagles: 0 });
return ACCEPTED;
}
case 'unlock': {
if (earnedUnlocks(profile).has(action.unlockId)) return refused('NOT_AVAILABLE');
if (!consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
addUnlock(profile, action.unlockId);
return ACCEPTED;
}
case 'classic-item': {
const def = classicItems.item(action.itemName);
if (!def) return refused('BAD_PARAMS');
if (!consumeExternalItem(profile, itemUid, quantity)) return refused('NOT_AVAILABLE');
grantItem(profile, def, action.count * quantity, now);
return ACCEPTED;
}
}
}
/** `cln_multi_consume_inventory_item_json`: batch auto-consume of external items (such as classic-item wrappers). */
export function multiConsumeInventoryItems(
profile: BlkBlock,
catalogue: InventoryCatalogue,
classicItems: ItemCatalogue,
requests: ReadonlyArray<{ readonly itemId: number; readonly quantity: number }>,
now: ServerTime,
): { readonly revertedItems: number[] } {
const revertedItems: number[] = [];
for (const req of requests) {
const outcome = consumeInventoryCoupon(profile, catalogue, classicItems, String(req.itemId), req.quantity, now);
if (!outcome.ok) revertedItems.push(req.itemId);
}
return { revertedItems };
}
/** `cln_inventory_purchase_item`: buy external inventory chests/items priced in GetItemPrices. */
export function purchaseExternalInventoryItem(
profile: BlkBlock,
catalogue: InventoryCatalogue,
itemDefId: number,
amount: number,
offeredWp: number,
offeredGold: number,
): RuleOutcome {
if (amount < 1 || amount > 100) return refused('BAD_PARAMS');
const unitPrice = catalogue.priceOf(itemDefId);
if (!unitPrice) return refused('NOT_AVAILABLE');
if (offeredWp !== unitPrice.silverLions || offeredGold !== unitPrice.goldenEagles) return refused('PRICE_CHANGED');
const totalPrice = {
silverLions: unitPrice.silverLions * amount,
goldenEagles: unitPrice.goldenEagles * amount,
};
if (!canAfford(profile, totalPrice)) return refused('NOT_ENOUGH_MONEY');
pay(profile, totalPrice);
grantExternalItem(profile, itemDefId, amount);
return ACCEPTED;
}
/** `cln_recycle_items`: convert classic profile items into external craft_part items (299000..299004). */
export function recycleClassicItems(
profile: BlkBlock,
classicItems: ItemCatalogue,
requests: ReadonlyArray<{ readonly uid: string; readonly count: number }>,
): RuleOutcome {
if (requests.length === 0) return refused('BAD_PARAMS');
const validated: Array<{ readonly uid: string; readonly count: number; readonly remaining: number; readonly partId: number }> = [];
const countsByUid = new Map<string, number>();
for (const entry of requests) {
if (!entry.uid || entry.count < 1) return refused('BAD_PARAMS');
countsByUid.set(entry.uid, (countsByUid.get(entry.uid) ?? 0) + entry.count);
}
for (const [uid, count] of countsByUid) {
const owned = ownedItem(profile, uid);
if (!owned || owned.count < count) return refused('NOT_AVAILABLE');
const def = classicItems.item(owned.id);
const partId = def?.recycleItemResult;
if (!partId) return refused('NOT_AVAILABLE');
validated.push({ uid, count, remaining: owned.count - count, partId });
}
const nowIso = new Date().toISOString();
for (const item of validated) {
if (item.remaining <= 0) removeItem(profile, item.uid);
else setItemCount(profile, item.uid, item.remaining);
grantExternalItem(profile, item.partId, item.count, nowIso);
}
return ACCEPTED;
}
export interface ExchangeMaterialInput {
readonly itemid: string;
readonly itemdefid: number;
readonly quantity: number;
}
export type ExchangeOutcome =
| { readonly ok: true; readonly delta: InventoryItemJson[] }
| { readonly ok: false; readonly code: string };
/** `ExchangeItems` / `cln_inventory_exchange_items`: execute a generator recipe and roll drops. */
export function exchangeInventoryItems(
profile: BlkBlock,
accountId: string,
catalogue: InventoryCatalogue,
outputItemDefId: number,
quantity: number,
materials: readonly ExchangeMaterialInput[],
nowSec = Math.floor(Date.now() / 1000),
): ExchangeOutcome {
if (quantity < 1 || quantity > 100 || materials.length === 0) return { ok: false, code: 'BAD_PARAMS' };
const gen = catalogue.generator(outputItemDefId);
if (!gen || gen.drops.length === 0) return { ok: false, code: 'UNKNOWN_GENERATOR' };
// Verify materials match one of the generator's recipes scaled by quantity, and player holds them.
const providedByDef = new Map<number, number>();
for (const mat of materials) {
if (!mat.itemid || mat.quantity < 1) return { ok: false, code: 'BAD_MATERIALS' };
const held = externalItemByUid(profile, String(mat.itemid));
if (!held || held.itemDefId !== Number(mat.itemdefid) || held.quantity < mat.quantity) {
return { ok: false, code: 'NOT_ENOUGH_ITEMS' };
}
providedByDef.set(held.itemDefId, (providedByDef.get(held.itemDefId) ?? 0) + mat.quantity);
}
const matchesRecipe = gen.recipes.some((recipe) =>
recipe.components.length === providedByDef.size
&& recipe.components.every((comp) => providedByDef.get(comp.itemdefId) === comp.quantity * quantity));
if (!matchesRecipe) return { ok: false, code: 'RECIPE_MISMATCH' };
const nowIso = new Date(nowSec * 1000).toISOString();
const deltaByUid = new Map<string, InventoryItemJson>();
for (const mat of materials) {
const uid = String(mat.itemid);
const consumed = consumeExternalItem(profile, uid, mat.quantity, nowIso);
if (!consumed) return { ok: false, code: 'NOT_ENOUGH_ITEMS' };
deltaByUid.set(uid, {
itemid: uid,
itemdef: consumed.itemDefId,
accountid: accountId,
quantity: consumed.remaining,
state: 'none',
timestamp: nowIso,
});
}
for (let i = 0; i < quantity; i += 1) {
const dropDefId = rollWeightedDrop(gen.drops);
const granted = grantExternalItem(profile, dropDefId, 1, nowIso);
deltaByUid.set(granted.itemId, toInventoryJson(granted, accountId));
if (gen.isChestGenerator && gen.chestItemdefId !== undefined) {
const logParams: BlkParam[] = [
{ name: 'id', value: { type: 'string', value: 'trophyFromInventory' } },
{ name: 'fromInventory', value: { type: 'bool', value: true } },
{ name: 'itemDefId', value: { type: 'int', value: gen.chestItemdefId } },
{ name: 'itemId', value: { type: 'int', value: Number(granted.itemId) } },
{ name: 'item', value: { type: 'int', value: dropDefId } },
{ name: 'count', value: { type: 'int', value: 1 } },
];
appendUserLog(profile, { type: EULT_OPEN_TROPHY, timeSec: nowSec, bodyParams: logParams });
}
}
return { ok: true, delta: [...deltaByUid.values()] };
}
export type MarketBuyOutcome =
| { readonly ok: true; readonly item: StoredExternalItem }
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'NOT_ENOUGH_GJN' };
export function buyMarketplaceCoupon(
profile: BlkBlock,
catalogue: InventoryCatalogue,
itemdefId: number,
quantity = 1,
): MarketBuyOutcome {
const listing = catalogue.marketplaceListing(itemdefId);
if (!listing || quantity < 1 || quantity > 20) return { ok: false, reason: 'NOT_FOUND' };
const totalCost = listing.gjnCost * quantity;
if (balanceOf(profile).gjn < totalCost) return { ok: false, reason: 'NOT_ENOUGH_GJN' };
payGjn(profile, totalCost);
const item = grantExternalItem(profile, itemdefId, quantity);
return { ok: true, item };
}
function rollWeightedDrop(drops: readonly GeneratorDrop[]): number {
const total = drops.reduce((sum, entry) => sum + entry.weight, 0);
let roll = Math.random() * total;
for (const entry of drops) {
roll -= entry.weight;
if (roll <= 0) return entry.itemdefId;
}
return drops[drops.length - 1]!.itemdefId;
}
@@ -0,0 +1,154 @@
/**
* External inventory HTTP service (`inventory-proxy-0{1,2}.gaijin.net/char`; implementation notes).
*
* Unlike CharService (which prepends the `0x69` uncompressed marker to binary BLK answers),
* `charsq` (`0x459cac0 -> 0x459e020`) parses the raw HTTP body directly as UTF-8 JSON unless
* it equals `"!OK"` or starts with `"!ERROR:"`.
*/
import type { Account, AccountStore } from '../accounts/account-store.ts';
import { userIdFromToken } from '../login/session-credentials.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import { exchangeInventoryItems, toInventoryJsonList, type ExchangeMaterialInput } from './inventory-rules.ts';
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
const INVENTORY_HOST = /^inventory-proxy-[a-z0-9-]+\.gaijin\.net$/;
const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' };
const TEXT_HEADERS = { 'content-type': 'text/plain; charset=utf-8' };
export class InventoryService implements Service {
readonly name = 'inventory';
readonly #accounts: AccountStore;
readonly #profiles: PlayerProfiles;
readonly #catalogue: InventoryCatalogue;
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: InventoryCatalogue) {
this.#accounts = accounts;
this.#profiles = profiles;
this.#catalogue = catalogue;
}
accepts(request: ServiceRequest): boolean {
return request.originalHost !== undefined && INVENTORY_HOST.test(request.originalHost);
}
handle(request: ServiceRequest): ServiceResponse {
const action = headerOf(request, 'action') ?? '';
switch (action) {
case 'GetInventory':
return this.#getInventory(request);
case 'GetItemDefsClient':
return this.#getItemDefs(request);
case 'GetItemPrices':
return this.#getItemPrices(request);
case 'GetItemDefChances':
return this.#getItemDefChances(request);
case 'ExchangeItems':
return this.#exchangeItems(request);
case 'CancelDelayedExchange':
return jsonResponse({ response: { item_json: [] } }, 'CancelDelayedExchange -> 0 items');
default:
return jsonResponse({ response: {} }, `${action || '(no action)'} -> empty response`);
}
}
#getInventory(request: ServiceRequest): ServiceResponse {
const account = this.#resolveAccount(request);
if (!account) return errorResponse('UNAUTHORIZED', 'GetInventory: unknown account');
const items = toInventoryJsonList(this.#profiles.profileOf(account.userId), account.userId);
return jsonResponse({ response: { item_json: items } }, `GetInventory -> ${items.length} stack(s)`);
}
#getItemDefs(request: ServiceRequest): ServiceResponse {
const rawIds = headerOf(request, 'itemdefids') ?? '';
const language = headerOf(request, 'language') ?? 'english';
const ids = rawIds.split(',').map((part) => Number(part.trim())).filter((n) => Number.isSafeInteger(n) && n > 0);
const defs = this.#catalogue.itemDefs(ids, language);
return jsonResponse({ response: { itemdef_json: defs } }, `GetItemDefsClient (${defs.length} defs, lang=${language})`);
}
#getItemPrices(request: ServiceRequest): ServiceResponse {
const currency = headerOf(request, 'currency') === 'WTE' ? 'WTE' : 'WTS';
const itemPrices = this.#catalogue.pricesForCurrency(currency);
return jsonResponse({ response: { itemPrices } }, `GetItemPrices (${currency}) -> ${itemPrices.length} item(s)`);
}
#getItemDefChances(request: ServiceRequest): ServiceResponse {
const rawId = headerOf(request, 'itemdefs') ?? '';
const generatorId = Number(rawId.trim());
const chances = Number.isSafeInteger(generatorId) ? this.#catalogue.chancesForGenerator(generatorId) : undefined;
const response: Record<string, unknown> = chances ? { [String(generatorId)]: chances } : {};
return jsonResponse({ response }, `GetItemDefChances (${generatorId}) -> ${chances?.length ?? 0} drop(s)`);
}
#exchangeItems(request: ServiceRequest): ServiceResponse {
const account = this.#resolveAccount(request);
if (!account) return errorResponse('UNAUTHORIZED', 'ExchangeItems: unknown account');
let parsed: Record<string, unknown>;
try {
const raw = JSON.parse(request.body.toString('utf8')) as Record<string, unknown>;
parsed = typeof raw.data === 'object' && raw.data !== null ? raw.data as Record<string, unknown> : raw;
} catch {
return errorResponse('BAD_JSON', 'ExchangeItems: invalid JSON');
}
const outputItemDefId = Number(parsed.outputitemdefid ?? 0);
const quantity = Number(parsed.quantity ?? 1);
const rawMaterials = Array.isArray(parsed.materials) ? parsed.materials : [];
const materials: ExchangeMaterialInput[] = rawMaterials.flatMap((m) => {
if (typeof m !== 'object' || m === null) return [];
const rec = m as Record<string, unknown>;
return [{
itemid: String(rec.itemid ?? ''),
itemdefid: Number(rec.itemdefid ?? 0),
quantity: Number(rec.quantity ?? 0),
}];
});
let delta: unknown[] | undefined;
let errorCode = 'EXCHANGE_FAILED';
this.#profiles.updateWhen(account.userId, (saved) => {
const res = exchangeInventoryItems(saved, account.userId, this.#catalogue, outputItemDefId, quantity, materials);
if (!res.ok) {
errorCode = res.code;
return false;
}
delta = res.delta;
return true;
});
if (!delta) return errorResponse(errorCode, `ExchangeItems (${outputItemDefId}) -> ${errorCode}`);
return jsonResponse({ response: { item_json: delta } }, `ExchangeItems (${outputItemDefId} x${quantity}) -> ${delta.length} delta item(s)`);
}
#resolveAccount(request: ServiceRequest): Account | undefined {
const uidHint = headerOf(request, 'uidhint');
if (uidHint) {
const found = this.#accounts.byUserId(uidHint);
if (found) return found;
}
const token = headerOf(request, 'token');
const tokenUid = token ? userIdFromToken(token) : undefined;
if (tokenUid) {
const found = this.#accounts.byUserId(tokenUid);
if (found) return found;
}
return this.#accounts.activeAccount();
}
}
function headerOf(request: ServiceRequest, name: string): string | undefined {
const value = request.headers[name];
const text = Array.isArray(value) ? value[0] : value;
return text ? text : undefined;
}
function jsonResponse(payload: unknown, summary: string): ServiceResponse {
const body = JSON.stringify(payload);
return { status: 200, headers: JSON_HEADERS, body, logNotes: { summary, responseText: body.slice(0, 1200) } };
}
function errorResponse(code: string, summary: string): ServiceResponse {
return { status: 200, headers: TEXT_HEADERS, body: `!ERROR:${code}`, logNotes: { summary } };
}
@@ -0,0 +1,615 @@
/**
* Generated external inventory item definitions (`GetItemDefsClient`), item shop prices
* (`GetItemPrices`), generator drop tables (`GetItemDefChances` & `ExchangeItems`), and
* GJN marketplace listings.
*/
import type { ExternalItemSources, MarketplaceDecorCoupon, MarketplaceUnlockCoupon } from '../game-data/datasets/external-item-sources.ts';
import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts';
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import { vehicleTypeOfClass } from '../research/vehicle-types.ts';
import type { CouponAction, GeneratorDrop, ItemDefRecord, MarketplaceListing } from './itemdef-types.ts';
const DEFAULT_TIMESTAMP = '2026-01-01T00:00:00Z';
const RECYCLE_PART_IDS = [299000, 299001, 299002, 299003, 299004] as const;
const RECYCLE_SINGLE_OFFSET = 20;
const RECYCLE_GENERIC_GENERATOR_ID = 299030;
export const TACTICAL_CHEST_ID = 910001;
export const COLLECTOR_CHEST_ID = 910002;
const TACTICAL_CHEST_GEN_ID = 910101;
const COLLECTOR_CHEST_GEN_ID = 910102;
interface LocalizedItemDef {
readonly base: Omit<ItemDefRecord, 'name' | 'description'>;
readonly name: LocalizedText;
readonly description: LocalizedText;
}
export interface ExternalItemPrice {
readonly itemdefId: number;
readonly silverLions: number;
readonly goldenEagles: number;
}
export interface GeneratorRecipe {
readonly components: ReadonlyArray<{ readonly itemdefId: number; readonly quantity: number }>;
}
export interface GeneratorDefinition {
readonly itemdefId: number;
readonly isChestGenerator: boolean;
readonly chestItemdefId?: number;
readonly recipes: readonly GeneratorRecipe[];
readonly drops: readonly GeneratorDrop[];
}
const MARKET_VEHICLE_GJN_BY_RANK: Readonly<Record<number, number>> = {
1: 8,
2: 14,
3: 22,
4: 35,
5: 48,
6: 59,
7: 69,
8: 75,
};
const QUALITY_COLORS: Readonly<Record<number, string>> = {
1: '',
2: '45aacc',
3: '5599ff',
4: 'aa66ff',
5: 'dd8833',
};
export class InventoryCatalogue {
readonly #defs = new Map<number, LocalizedItemDef>();
readonly #coupons = new Map<number, CouponAction>();
readonly #prices = new Map<number, ExternalItemPrice>();
readonly #generators = new Map<number, GeneratorDefinition>();
readonly #marketListings: MarketplaceListing[] = [];
readonly #marketById = new Map<number, MarketplaceListing>();
constructor(
vehicles: readonly CatalogueVehicle[],
unitNames: Readonly<Record<string, LocalizedText>>,
sources: ExternalItemSources,
classicItems: readonly ItemDefinition[],
) {
const vehicleCouponIds: number[] = [];
const decorCouponIds: number[] = [];
// 1. 233 Marketplace vehicle coupons
for (const vehicle of vehicles) {
if (!vehicle.marketplaceItemdefId) continue;
const id = vehicle.marketplaceItemdefId;
const unitTitle = unitNames[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name };
const quality = vehicle.rank >= 6 ? 4 : vehicle.rank >= 4 ? 3 : 2;
const color = QUALITY_COLORS[quality] ?? '45aacc';
const gjnCost = MARKET_VEHICLE_GJN_BY_RANK[vehicle.rank] ?? 45;
const tagType = unitClassTag(vehicle.unitClass);
const marketUnitClass = marketUnitClassOf(vehicle.unitClass);
this.#addDef(id, {
type: 'item',
marketable: true,
market_hash_name: vehicle.name,
item_quality: quality,
name_color: color,
tags: `type:${tagType}`,
meta: `unit:t="${vehicle.name}"`,
icon_url: '!#ui/gameuiskin#item_type_blueprints.svg',
icon_url_large: '!#ui/gameuiskin#item_type_blueprints.svg',
}, unitTitle, {
en: `Exchangeable coupon for ${unitTitle.en} (Rank ${vehicle.rank}).`,
zh: `可兑换载具券:${unitTitle.zh}(${vehicle.rank} 级)。`,
});
this.#coupons.set(id, { kind: 'vehicle', unitName: vehicle.name, parts: vehicle.parts });
vehicleCouponIds.push(id);
this.#addMarketListing({
itemdefId: id,
marketHashName: vehicle.name,
category: 'vehicle',
gjnCost,
quality,
nameColor: color,
title: unitTitle,
subtitle: { en: `Rank ${vehicle.rank} ${tagType}`, zh: `${vehicle.rank} 级载具兑换券` },
country: vehicle.country,
unitClass: marketUnitClass,
rank: vehicle.rank,
targetKey: vehicle.name,
});
}
// 2. Decorator coupons (skins, decals, attachables)
for (const decor of sources.decorCoupons) {
this.#registerDecorCoupon(decor);
decorCouponIds.push(decor.itemdefId);
}
// 3. Unlock / pilot-icon coupons
for (const unlock of sources.unlockCoupons) {
this.#registerUnlockCoupon(unlock);
decorCouponIds.push(unlock.itemdefId);
}
// 4. Classic item wrappers (autoConsume internal_item) + recycle craft parts & generators
const classicWrapperIds = this.#registerClassicWrappers(classicItems);
this.#registerRecycleSystem(classicWrapperIds);
// 5. External Silver-Lion supply chests & open generators
this.#registerSupplyChests(classicWrapperIds, decorCouponIds, vehicleCouponIds);
// 6. Workshop config referenced IDs (hidden stubs so login itemdef requests succeed cleanly)
for (const workshopId of sources.workshopItemdefIds) {
if (this.#defs.has(workshopId)) continue;
this.#addDef(workshopId, {
type: 'item',
marketable: false,
item_quality: 1,
tags: 'type:craft_part;devItem:yes;hideDesc:yes',
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg',
}, { en: `Workshop Component #${workshopId}`, zh: `工坊组件 #${workshopId}` }, { en: '', zh: '' });
}
}
itemDef(itemdefId: number, language = 'english'): ItemDefRecord {
const entry = this.#defs.get(itemdefId);
if (!entry) return fallbackItemDef(itemdefId);
const useZh = isChineseLanguage(language);
return {
...entry.base,
name: useZh ? entry.name.zh : entry.name.en,
description: useZh ? entry.description.zh : entry.description.en,
};
}
itemDefs(ids: readonly number[], language = 'english'): ItemDefRecord[] {
const unique = [...new Set(ids.filter((id) => Number.isSafeInteger(id) && id > 0))];
return unique.map((id) => this.itemDef(id, language));
}
couponAction(itemdefId: number): CouponAction | undefined {
return this.#coupons.get(itemdefId);
}
priceOf(itemdefId: number): ExternalItemPrice | undefined {
return this.#prices.get(itemdefId);
}
pricesForCurrency(currency: 'WTE' | 'WTS'): Array<{ readonly itemdefid: number; readonly price: number }> {
const out: Array<{ readonly itemdefid: number; readonly price: number }> = [];
for (const entry of this.#prices.values()) {
const price = currency === 'WTE' ? entry.goldenEagles : entry.silverLions;
if (price > 0) out.push({ itemdefid: entry.itemdefId, price });
}
return out;
}
generator(generatorId: number): GeneratorDefinition | undefined {
return this.#generators.get(generatorId);
}
chancesForGenerator(generatorId: number): Array<{ readonly drop: number; readonly prob: number }> | undefined {
const gen = this.#generators.get(generatorId);
if (!gen || gen.drops.length === 0) return undefined;
const total = gen.drops.reduce((sum, d) => sum + d.weight, 0);
if (total <= 0) return undefined;
return gen.drops.map((d) => ({ drop: d.itemdefId, prob: Number((d.weight / total).toFixed(6)) }));
}
marketplaceListings(): readonly MarketplaceListing[] {
return this.#marketListings;
}
marketplaceListing(itemdefId: number): MarketplaceListing | undefined {
return this.#marketById.get(itemdefId);
}
hasItemDef(itemdefId: number): boolean {
return this.#defs.has(itemdefId);
}
#registerDecorCoupon(decor: MarketplaceDecorCoupon): void {
const quality = decor.kind === 'attachable' ? 3 : 2;
const color = QUALITY_COLORS[quality] ?? '45aacc';
const iconByKind = {
skin: '!#ui/gameuiskin#item_type_skin.svg',
decal: '!#ui/gameuiskin#item_type_decal.svg',
attachable: '!#ui/gameuiskin#item_type_attachable.svg',
} as const;
const gjnByKind = { skin: 5, decal: 3, attachable: 8 } as const;
const labelZh = { skin: '涂装兑换券', decal: '贴花兑换券', attachable: '3D 装饰挂件兑换券' } as const;
const hashName = `${decor.kind}_${decor.itemdefId}`;
this.#addDef(decor.itemdefId, {
type: 'item',
marketable: true,
market_hash_name: hashName,
item_quality: quality,
name_color: color,
tags: `type:${decor.kind}`,
meta: `resource:t="${decor.resourceKey}"\nresourceType:t="${decor.kind}"`,
icon_url: iconByKind[decor.kind],
icon_url_large: iconByKind[decor.kind],
}, decor.name, {
en: `Coupon for ${decor.kind}: ${decor.name.en}.`,
zh: `${labelZh[decor.kind]}:${decor.name.zh}。`,
});
this.#coupons.set(decor.itemdefId, { kind: 'decor', decorKind: decor.kind, resourceKey: decor.resourceKey });
this.#addMarketListing({
itemdefId: decor.itemdefId,
marketHashName: hashName,
category: decor.kind,
gjnCost: gjnByKind[decor.kind],
quality,
nameColor: color,
title: decor.name,
subtitle: { en: `${decor.kind} coupon`, zh: labelZh[decor.kind] },
targetKey: decor.resourceKey,
});
}
#registerUnlockCoupon(unlock: MarketplaceUnlockCoupon): void {
const quality = 3;
const color = QUALITY_COLORS[quality] ?? '5599ff';
const hashName = `unlock_${unlock.itemdefId}`;
this.#addDef(unlock.itemdefId, {
type: 'item',
marketable: true,
market_hash_name: hashName,
item_quality: quality,
name_color: color,
tags: 'type:unlock',
meta: `unlock:t="${unlock.unlockId}"`,
icon_url: '!#ui/gameuiskin#item_type_unlock.svg',
icon_url_large: '!#ui/gameuiskin#item_type_unlock.svg',
}, unlock.name, {
en: `Coupon for unlock: ${unlock.name.en}.`,
zh: `头像/收藏解锁兑换券:${unlock.name.zh}。`,
});
this.#coupons.set(unlock.itemdefId, { kind: 'unlock', unlockId: unlock.unlockId });
this.#addMarketListing({
itemdefId: unlock.itemdefId,
marketHashName: hashName,
category: 'unlock',
gjnCost: 6,
quality,
nameColor: color,
title: unlock.name,
subtitle: { en: 'Profile icon / unlock coupon', zh: '头像与解锁兑换券' },
targetKey: unlock.unlockId,
});
}
#registerClassicWrappers(classicItems: readonly ItemDefinition[]): ReadonlyMap<number, readonly number[]> {
// Group non-expired classic items by their recycleItemResult (299000..299004) so recycling
// and chest drops yield authentic boosters, universal spares, orders, and wagers.
const byRecyclePart = new Map<number, number[]>();
for (const partId of RECYCLE_PART_IDS) byRecyclePart.set(partId, []);
const preferredByPart = new Map<number, ItemDefinition[]>();
for (const item of classicItems) {
if (item.expiresAt !== undefined) continue;
if (item.type === 'personalDiscounts') continue;
const partId = item.recycleItemResult ?? 299001;
let bucket = preferredByPart.get(partId);
if (!bucket) preferredByPart.set(partId, bucket = []);
if (bucket.length < 8) bucket.push(item);
}
let nextWrapperId = 810001;
for (const [partId, defs] of preferredByPart) {
const targetList = byRecyclePart.get(partId) ?? [];
for (const def of defs) {
const wrapperId = nextWrapperId++;
const count = def.name === 'item_universal_spare' ? 3 : 1;
this.#addDef(wrapperId, {
type: 'item',
marketable: false,
item_quality: 1,
tags: 'type:internal_item;autoConsume:yes;showAsContentItem:yes;hideMarketablePropDesc:yes',
meta: `item:t="${def.name}"\ncount:i=${count}`,
icon_url: '!#ui/gameuiskin#item_type_trophies.svg',
icon_url_large: '!#ui/gameuiskin#item_type_trophies.svg',
}, { en: def.name, zh: def.name }, { en: '', zh: '' });
this.#coupons.set(wrapperId, { kind: 'classic-item', itemName: def.name, count });
targetList.push(wrapperId);
}
byRecyclePart.set(partId, targetList);
}
// Part 299002 corresponds to personalDiscounts: route its single-part generator to boosters + spares.
const fallbackPool = [
...(byRecyclePart.get(299000) ?? []),
...(byRecyclePart.get(299001) ?? []),
];
for (const partId of RECYCLE_PART_IDS) {
if ((byRecyclePart.get(partId)?.length ?? 0) === 0) {
byRecyclePart.set(partId, fallbackPool);
}
}
return byRecyclePart;
}
#registerRecycleSystem(wrappersByPart: ReadonlyMap<number, readonly number[]>): void {
const partNames: Readonly<Record<number, LocalizedText>> = {
299000: { en: 'Spare Supply Fragment', zh: '备用载具回收组件' },
299001: { en: 'Booster Fragment', zh: '加成卡回收组件' },
299002: { en: 'Coupon Fragment', zh: '折扣券回收组件' },
299003: { en: 'Order Fragment', zh: '任务令回收组件' },
299004: { en: 'Wager Fragment', zh: '合同回收组件' },
};
const allWrappers = [...new Set([...wrappersByPart.values()].flat())];
const pairRecipes: GeneratorRecipe[] = [];
const pairStrings: string[] = [];
for (let i = 0; i < RECYCLE_PART_IDS.length; i += 1) {
for (let j = i + 1; j < RECYCLE_PART_IDS.length; j += 1) {
const a = RECYCLE_PART_IDS[i]!;
const b = RECYCLE_PART_IDS[j]!;
pairRecipes.push({ components: [{ itemdefId: a, quantity: 1 }, { itemdefId: b, quantity: 1 }] });
pairStrings.push(`${a}x1,${b}x1`);
}
}
for (const partId of RECYCLE_PART_IDS) {
const singleGenId = partId + RECYCLE_SINGLE_OFFSET;
const title = partNames[partId] ?? { en: `Recycled Part #${partId}`, zh: `回收组件 #${partId}` };
this.#addDef(partId, {
type: 'item',
marketable: false,
item_quality: 1,
used_to_create: `${singleGenId}x1;${RECYCLE_GENERIC_GENERATOR_ID}x1`,
tags: 'type:craft_part;hideMarketablePropDesc:yes',
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg',
}, title, {
en: 'Obtained by recycling classic items; 2 fragments craft a new random tactical item.',
zh: '回收经典道具所得;每 2 个组件可重新合成 1 件随机道具。',
});
const pool = wrappersByPart.get(partId) ?? allWrappers;
const drops: GeneratorDrop[] = pool.map((id) => ({ itemdefId: id, weight: 10 }));
this.#addDef(singleGenId, {
type: 'generator',
marketable: false,
item_quality: 1,
exchange: `${partId}x2`,
bundle: pool.map((id) => `${id}x1`).join(';'),
tags: 'devItem:yes',
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg',
}, { en: 'Item Synthesizer', zh: '道具合成器' }, { en: '', zh: '' });
this.#generators.set(singleGenId, {
itemdefId: singleGenId,
isChestGenerator: false,
recipes: [{ components: [{ itemdefId: partId, quantity: 2 }] }],
drops,
});
}
const genericDrops: GeneratorDrop[] = allWrappers.map((id) => ({ itemdefId: id, weight: 10 }));
this.#addDef(RECYCLE_GENERIC_GENERATOR_ID, {
type: 'generator',
marketable: false,
item_quality: 1,
exchange: pairStrings.join(';'),
bundle: allWrappers.map((id) => `${id}x1`).join(';'),
tags: 'devItem:yes',
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg',
}, { en: 'Mixed Item Synthesizer', zh: '混搭道具合成器' }, { en: '', zh: '' });
this.#generators.set(RECYCLE_GENERIC_GENERATOR_ID, {
itemdefId: RECYCLE_GENERIC_GENERATOR_ID,
isChestGenerator: false,
recipes: pairRecipes,
drops: genericDrops,
});
}
#registerSupplyChests(
wrappersByPart: ReadonlyMap<number, readonly number[]>,
decorCouponIds: readonly number[],
vehicleCouponIds: readonly number[],
): void {
const commonWrappers = [
...(wrappersByPart.get(299000) ?? []).slice(0, 3),
...(wrappersByPart.get(299001) ?? []).slice(0, 5),
...(wrappersByPart.get(299003) ?? []).slice(0, 2),
];
const sampleDecors = decorCouponIds.slice(0, 8);
const sampleVehicles = vehicleCouponIds.slice(0, 6);
const collectorVehicles = vehicleCouponIds.slice(6, 16);
// Chest 1: Tactical Supply Chest (60,000 SL)
const tacticalDrops: GeneratorDrop[] = [
...commonWrappers.map((id) => ({ itemdefId: id, weight: 80 })),
...sampleDecors.map((id) => ({ itemdefId: id, weight: 18 })),
...sampleVehicles.map((id) => ({ itemdefId: id, weight: 4 })),
];
this.#registerChest(
TACTICAL_CHEST_ID,
TACTICAL_CHEST_GEN_ID,
60000,
2,
'!#ui/images/chests/items_box2.avif',
{ en: 'Tactical Supply Chest', zh: '战术物资补给箱' },
{
en: 'Silver-Lion supply chest containing boosters, universal backups, decorator coupons, and rare vehicle coupons.',
zh: '银狮物资补给箱:内含加成卡、通用备用载具、涂装/贴花/挂件券及稀有市场载具兑换券(点击可查看各项精确掉率)。',
},
tacticalDrops,
);
// Chest 2: Collector's Supply Chest (250,000 SL)
const collectorDrops: GeneratorDrop[] = [
...commonWrappers.slice(0, 5).map((id) => ({ itemdefId: id, weight: 45 })),
...decorCouponIds.slice(8, 20).map((id) => ({ itemdefId: id, weight: 22 })),
...(collectorVehicles.length ? collectorVehicles : sampleVehicles).map((id) => ({ itemdefId: id, weight: 12 })),
];
this.#registerChest(
COLLECTOR_CHEST_ID,
COLLECTOR_CHEST_GEN_ID,
250000,
4,
'!#ui/images/chests/items_box3.avif',
{ en: "Collector's Supply Chest", zh: '典藏收藏家补给箱' },
{
en: 'High-tier Silver-Lion supply chest with elevated drop rates for marketplace vehicle and decorator coupons.',
zh: '高阶银狮补给箱:大幅提升稀有市场载具兑换券与 3D 装饰挂件/涂装券的掉落概率。',
},
collectorDrops,
);
}
#registerChest(
chestId: number,
genId: number,
silverLions: number,
quality: number,
icon: string,
title: LocalizedText,
desc: LocalizedText,
drops: readonly GeneratorDrop[],
): void {
const color = QUALITY_COLORS[quality] ?? '45aacc';
this.#addDef(chestId, {
type: 'item',
marketable: false,
item_quality: quality,
name_color: color,
used_to_create: `${genId}x1`,
tags: 'type:chest;showChances:yes;allowToBuyAmount:10;isAllowSkipOpeningAnim:yes;hideMarketablePropDesc:yes',
icon_url: icon,
icon_url_large: icon,
}, title, desc);
this.#prices.set(chestId, { itemdefId: chestId, silverLions, goldenEagles: 0 });
const bundleStr = drops.map((d) => `${d.itemdefId}x1`).join(';');
this.#addDef(genId, {
type: 'generator',
marketable: false,
item_quality: quality,
name_color: color,
exchange: `${chestId}x1`,
bundle: bundleStr,
tags: 'devItem:yes',
icon_url: icon,
icon_url_large: icon,
}, title, { en: '', zh: '' });
this.#generators.set(genId, {
itemdefId: genId,
isChestGenerator: true,
chestItemdefId: chestId,
recipes: [{ components: [{ itemdefId: chestId, quantity: 1 }] }],
drops,
});
}
#addDef(
itemdefid: number,
partial: Partial<Omit<ItemDefRecord, 'itemdefid' | 'name' | 'name_english' | 'description' | 'description_english'>> & {
readonly type: ItemDefRecord['type'];
readonly tags: string;
readonly icon_url: string;
},
name: LocalizedText,
description: LocalizedText,
): void {
this.#defs.set(itemdefid, {
base: {
itemdefid,
type: partial.type,
Timestamp: partial.Timestamp ?? DEFAULT_TIMESTAMP,
marketable: partial.marketable ?? false,
exchange: partial.exchange ?? '',
used_to_create: partial.used_to_create ?? '',
market_hash_name: partial.market_hash_name ?? '',
background_color: partial.background_color ?? '',
name_color: partial.name_color ?? '',
item_quality: partial.item_quality ?? 1,
meta: partial.meta ?? '',
tags: partial.tags,
icon_url: partial.icon_url,
icon_url_large: partial.icon_url_large ?? partial.icon_url,
bundle: partial.bundle ?? '',
name_english: name.en,
description_english: description.en,
},
name,
description,
});
}
#addMarketListing(listing: MarketplaceListing): void {
this.#marketListings.push(listing);
this.#marketById.set(listing.itemdefId, listing);
}
}
function unitClassTag(unitClass: string): string {
switch (vehicleTypeOfClass(unitClass)) {
case 'Aircraft':
return 'aircraft';
case 'Helicopter':
return 'helicopter';
case 'Tank':
return 'tank';
case 'Ship':
case 'Boat':
return 'ship';
default:
return 'tank';
}
}
function marketUnitClassOf(unitClass: string): string {
switch (vehicleTypeOfClass(unitClass)) {
case 'Aircraft':
return 'aircraft';
case 'Helicopter':
return 'helicopter';
case 'Tank':
return 'tank';
case 'Ship':
return 'ship';
case 'Boat':
return 'boat';
default:
return 'tank';
}
}
function isChineseLanguage(lang: string): boolean {
const lower = lang.toLowerCase();
return lower.includes('chinese') || lower.includes('zh');
}
function fallbackItemDef(itemdefid: number): ItemDefRecord {
return {
itemdefid,
type: 'item',
Timestamp: DEFAULT_TIMESTAMP,
marketable: false,
exchange: '',
used_to_create: '',
market_hash_name: '',
background_color: '',
name_color: '',
item_quality: 1,
meta: '',
tags: 'type:craft_part;devItem:yes;hideDesc:yes',
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg',
bundle: '',
name: `Item #${itemdefid}`,
name_english: `Item #${itemdefid}`,
description: '',
description_english: '',
};
}
@@ -0,0 +1,67 @@
/**
* Types for the external inventory service (`inventory-proxy`), generated itemdefs,
* and the local GJN marketplace.
*/
import type { DecorKind } from '../game-data/datasets/decor-catalogue.ts';
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
/** Exact schema validated by scripts/inventory/inventoryClient.nut `validateResponseData.item_json`. */
export interface InventoryItemJson {
readonly itemid: string;
readonly itemdef: number;
readonly accountid: string;
readonly quantity: number;
readonly state: string;
readonly timestamp: string;
}
/** Exact schema validated by scripts/inventory/inventoryClient.nut `validateResponseData.itemdef_json`. */
export interface ItemDefRecord {
readonly itemdefid: number;
readonly type: 'item' | 'generator' | 'bundle' | 'delayedexchange';
readonly Timestamp: string;
readonly marketable: boolean;
readonly exchange: string;
readonly used_to_create: string;
readonly market_hash_name: string;
readonly background_color: string;
readonly name_color: string;
readonly item_quality: number;
readonly meta: string;
readonly tags: string;
readonly icon_url: string;
readonly icon_url_large: string;
readonly bundle: string;
readonly name: string;
readonly name_english: string;
readonly description: string;
readonly description_english: string;
}
export type CouponAction =
| { readonly kind: 'vehicle'; readonly unitName: string; readonly parts: readonly string[] }
| { readonly kind: 'decor'; readonly decorKind: DecorKind; readonly resourceKey: string }
| { readonly kind: 'unlock'; readonly unlockId: string }
| { readonly kind: 'classic-item'; readonly itemName: string; readonly count: number };
export type MarketplaceCategory = 'vehicle' | 'skin' | 'decal' | 'attachable' | 'unlock';
export interface MarketplaceListing {
readonly itemdefId: number;
readonly marketHashName: string;
readonly category: MarketplaceCategory;
readonly gjnCost: number;
readonly quality: number;
readonly nameColor: string;
readonly title: LocalizedText;
readonly subtitle: LocalizedText;
readonly country?: string;
readonly unitClass?: string;
readonly rank?: number;
readonly targetKey: string;
}
export interface GeneratorDrop {
readonly itemdefId: number;
readonly weight: number;
}
@@ -0,0 +1,300 @@
/**
* Single-page HTML UI for the local GJN Marketplace (`/trade.gaijin.net`), supporting
* vehicle coupons (233), skin coupons (74), attachable coupons (114), decal coupons (19),
* and unlock/profile-icon coupons (26), including deep links `?viewitem&n=<market_hash_name>`
* opened from in-game "Find on Marketplace" buttons.
*/
export function renderMarketplacePageHtml(): 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 — 本地 GJN 交易所</title>
<style>
:root {
--bg: #0f141b;
--panel: #17202b;
--panel-alt: #1e2a38;
--border: #2c3d52;
--text: #e6edf5;
--muted: #93a4b8;
--gjn: #4cd964;
--accent: #3b82f6;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
background: var(--bg);
color: var(--text);
}
header {
position: sticky;
top: 0;
z-index: 10;
background: rgba(15, 20, 27, 0.96);
border-bottom: 1px solid var(--border);
padding: 14px 24px;
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
justify-content: space-between;
}
.brand h1 { margin: 0; font-size: 19px; letter-spacing: 0.4px; }
.brand p { margin: 3px 0 0; font-size: 12px; color: var(--muted); }
.wallet {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
}
.pill {
background: var(--panel-alt);
border: 1px solid var(--border);
border-radius: 6px;
padding: 6px 12px;
font-size: 13px;
}
.pill strong.gjn { color: var(--gjn); font-size: 15px; }
select, input, button {
font-family: inherit;
font-size: 13px;
border-radius: 6px;
border: 1px solid var(--border);
background: var(--panel);
color: var(--text);
padding: 7px 11px;
}
button {
cursor: pointer;
background: var(--accent);
border-color: #2563eb;
font-weight: 600;
}
button:hover:not(:disabled) { filter: brightness(1.1); }
button:disabled { opacity: 0.45; cursor: not-allowed; }
main { max-width: 1320px; margin: 0 auto; padding: 20px 24px 60px; }
.tabs { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; }
.tab { background: var(--panel); border: 1px solid var(--border); color: var(--muted); }
.tab.active { background: var(--accent); border-color: #2563eb; color: #fff; }
.filters { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 16px; }
.filters input { min-width: 250px; }
#toast {
display: none;
margin-bottom: 14px;
padding: 10px 14px;
border-radius: 6px;
font-size: 13px;
border: 1px solid var(--border);
}
#toast.ok { display: block; background: rgba(22, 163, 74, 0.18); border-color: #16a34a; color: #86efac; }
#toast.err { display: block; background: rgba(239, 68, 68, 0.18); border-color: #ef4444; color: #fca5a5; }
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(275px, 1fr));
gap: 12px;
}
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
padding: 14px;
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 10px;
}
.card.highlight { border-color: var(--gjn); box-shadow: 0 0 0 1px var(--gjn); }
.card h3 { margin: 0 0 4px; font-size: 15px; }
.meta { font-size: 12px; color: var(--muted); }
.badges { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; }
.badge { font-size: 11px; padding: 2px 7px; border-radius: 4px; background: var(--panel-alt); color: var(--muted); }
.badge.owned { background: rgba(76, 217, 100, 0.16); color: var(--gjn); }
.card-foot {
display: flex;
align-items: center;
justify-content: space-between;
padding-top: 8px;
border-top: 1px solid rgba(255,255,255,0.06);
}
.price { font-weight: 700; font-size: 15px; color: var(--gjn); }
.link-btn { text-decoration: none; color: var(--muted); font-size: 13px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; }
</style>
</head>
<body>
<header>
<div class="brand">
<h1>War Thunder Offline 本地交易所 (GJN Market)</h1>
<p>购买的兑换券直接存入玩家外部库存并实时推送至游戏(机库 → 道具 → 库存中可直接使用兑换)</p>
</div>
<div class="wallet">
<a class="link-btn" href="/store">前往礼包与金鹰商店</a>
<select id="accountSelect" title="当前离线账号"></select>
<div class="pill">GJN 余额:<strong class="gjn" id="balGjn">0</strong> GJN</div>
<div class="pill">金鹰:<strong id="balGold">0</strong></div>
<div class="pill">银狮:<strong id="balSilver">0</strong></div>
</div>
</header>
<main>
<div id="toast"></div>
<div class="tabs" id="tabs">
<button class="tab active" data-cat="all">全部兑换券</button>
<button class="tab" data-cat="vehicle">市场载具券</button>
<button class="tab" data-cat="skin">涂装券</button>
<button class="tab" data-cat="attachable">3D 挂件券</button>
<button class="tab" data-cat="decal">贴花券</button>
<button class="tab" data-cat="unlock">头像与解锁券</button>
</div>
<div class="filters">
<select id="countryFilter"><option value="">全部国家</option></select>
<select id="classFilter">
<option value="">全部兵种</option>
<option value="aircraft">固定翼飞机</option>
<option value="helicopter">直升机</option>
<option value="tank">陆战载具</option>
<option value="ship">远洋舰艇</option>
<option value="boat">近岸舰艇</option>
</select>
<input id="searchInput" placeholder="搜索载具、涂装、挂件或编号..." />
</div>
<div class="grid" id="grid"></div>
</main>
<script>
const COUNTRY_LABELS = {
country_usa: '美国', country_germany: '德国', country_ussr: '苏联', country_britain: '英国',
country_japan: '日本', country_china: '中国', country_italy: '意大利', country_france: '法国',
country_sweden: '瑞典', country_israel: '以色列'
};
let state = { accounts: [], currentUserId: '', balance: { gjn: 0, goldenEagles: 0, silverLions: 0 }, listings: [] };
let activeCat = 'all';
const initialParams = new URLSearchParams(location.search);
const targetHash = initialParams.get('n') || '';
if (targetHash) {
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('searchInput').value = targetHash;
});
}
function showToast(msg, ok) {
const el = document.getElementById('toast');
el.textContent = msg;
el.className = ok ? 'ok' : 'err';
}
async function loadState(userId) {
const q = userId ? '?userId=' + encodeURIComponent(userId) : '';
const res = await fetch('/trade.gaijin.net/api/state' + q);
state = await res.json();
renderHeader();
populateCountries();
renderGrid();
}
function renderHeader() {
const sel = document.getElementById('accountSelect');
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.currentUserId) opt.selected = true;
sel.appendChild(opt);
}
document.getElementById('balGjn').textContent = state.balance.gjn.toLocaleString();
document.getElementById('balGold').textContent = state.balance.goldenEagles.toLocaleString();
document.getElementById('balSilver').textContent = state.balance.silverLions.toLocaleString();
}
function populateCountries() {
const sel = document.getElementById('countryFilter');
const prev = sel.value;
const countries = [...new Set(state.listings.map(l => l.country).filter(Boolean))];
sel.innerHTML = '<option value="">全部国家</option>';
for (const c of countries) {
const opt = document.createElement('option');
opt.value = c;
opt.textContent = COUNTRY_LABELS[c] || c;
if (c === prev) opt.selected = true;
sel.appendChild(opt);
}
}
function renderGrid() {
const grid = document.getElementById('grid');
const country = document.getElementById('countryFilter').value;
const unitClass = document.getElementById('classFilter').value;
const q = document.getElementById('searchInput').value.trim().toLowerCase();
const filtered = state.listings.filter(item => {
if (activeCat !== 'all' && item.category !== activeCat) return false;
if (country && item.country !== country) return false;
if (unitClass && item.unitClass !== unitClass) return false;
if (q) {
const hay = (item.title.zh + ' ' + item.title.en + ' ' + item.marketHashName + ' ' + item.itemdefId).toLowerCase();
if (!hay.includes(q)) return false;
}
return true;
});
grid.innerHTML = '';
for (const item of filtered) {
const card = document.createElement('div');
card.className = 'card' + (targetHash && item.marketHashName === targetHash ? ' highlight' : '');
const titleColor = item.nameColor ? '#' + item.nameColor : '#e6edf5';
const badges = [];
if (item.country) badges.push('<span class="badge">' + (COUNTRY_LABELS[item.country] || item.country) + '</span>');
if (item.rank) badges.push('<span class="badge">' + item.rank + ' 级</span>');
badges.push('<span class="badge">#' + item.itemdefId + '</span>');
if (item.couponCount > 0) badges.push('<span class="badge owned">库存持有 x' + item.couponCount + '</span>');
if (item.alreadyActivated) badges.push('<span class="badge owned">已激活拥有</span>');
card.innerHTML =
'<div>' +
'<h3 style="color:' + titleColor + '">' + escapeHtml(item.title.zh) + '</h3>' +
'<div class="meta">' + escapeHtml(item.title.en) + ' · ' + escapeHtml(item.subtitle.zh) + '</div>' +
'<div class="badges">' + badges.join('') + '</div>' +
'</div>' +
'<div class="card-foot">' +
'<span class="price">' + item.gjnCost + ' GJN</span>' +
'<button data-id="' + item.itemdefId + '">购买兑换券</button>' +
'</div>';
card.querySelector('button').addEventListener('click', () => buyCoupon(item.itemdefId));
grid.appendChild(card);
}
}
async function buyCoupon(itemdefId) {
const res = await fetch('/trade.gaijin.net/api/buy', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ userId: state.currentUserId, itemdefId, quantity: 1 })
});
const data = await res.json();
showToast(data.message, data.ok);
if (data.ok) await loadState(state.currentUserId);
}
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));
}
document.getElementById('tabs').addEventListener('click', e => {
const btn = e.target.closest('.tab');
if (!btn) return;
for (const el of document.querySelectorAll('.tab')) el.classList.remove('active');
btn.classList.add('active');
activeCat = btn.dataset.cat;
renderGrid();
});
document.getElementById('accountSelect').addEventListener('change', e => loadState(e.target.value));
document.getElementById('countryFilter').addEventListener('change', renderGrid);
document.getElementById('classFilter').addEventListener('change', renderGrid);
document.getElementById('searchInput').addEventListener('input', renderGrid);
loadState('');
</script>
</body>
</html>`;
}
@@ -0,0 +1,154 @@
/**
* Local GJN Marketplace web service (`/trade.gaijin.net` and `trade.gaijin.net` host;
* implementation notes). Lets players browse and buy all 466 stock marketplace coupons
* (vehicles, skins, decals, attachables, pilot/unlocks) with GJN, depositing coupons into
* `extInventory` and pushing `mrpc.generic_notify` (`inventory.changed`) to active game clients.
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../accounts/account-store.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { balanceOf } from '../profile/profile-currency.ts';
import { externalInventoryItems } from '../profile/profile-external-inventory.ts';
import { ownsVehicle } from '../profile/profile-hangar.ts';
import { ownsResource } from '../profile/profile-resources.ts';
import { earnedUnlocks } from '../profile/profile-unlocks.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import { buyMarketplaceCoupon } from './inventory-rules.ts';
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
import type { MarketplaceListing } from './itemdef-types.ts';
import { renderMarketplacePageHtml } from './marketplace-page.ts';
const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' };
export class MarketplaceService implements Service {
readonly name = 'marketplace';
readonly #accounts: AccountStore;
readonly #profiles: PlayerProfiles;
readonly #catalogue: InventoryCatalogue;
readonly #notifyInventoryChanged: () => void;
constructor(
accounts: AccountStore,
profiles: PlayerProfiles,
catalogue: InventoryCatalogue,
notifyInventoryChanged: () => void,
) {
this.#accounts = accounts;
this.#profiles = profiles;
this.#catalogue = catalogue;
this.#notifyInventoryChanged = notifyInventoryChanged;
}
accepts(request: ServiceRequest): boolean {
return request.originalHost === 'trade.gaijin.net'
|| request.path === '/trade.gaijin.net'
|| request.path.startsWith('/trade.gaijin.net/');
}
handle(request: ServiceRequest): ServiceResponse {
const subPath = request.path.startsWith('/trade.gaijin.net')
? (request.path.slice('/trade.gaijin.net'.length) || '/')
: request.path;
if (subPath === '/api/state' && request.method === 'GET') return this.#state(request);
if (subPath === '/api/buy' && request.method === 'POST') return this.#buy(request);
return {
status: 200,
headers: { 'content-type': 'text/html; charset=utf-8' },
body: renderMarketplacePageHtml(),
logNotes: { summary: `marketplace web page (${request.query.get('n') ?? 'index'})` },
};
}
#state(request: ServiceRequest): ServiceResponse {
const requestedId = request.query.get('userId') ?? '';
const account = (requestedId ? this.#accounts.byUserId(requestedId) : undefined) ?? this.#accounts.activeAccount();
const profile = account ? this.#profiles.profileOf(account.userId) : undefined;
const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjn: 0 };
const heldCounts = new Map<number, number>();
if (profile) {
for (const item of externalInventoryItems(profile)) {
heldCounts.set(item.itemDefId, (heldCounts.get(item.itemDefId) ?? 0) + item.quantity);
}
}
const unlockedSet = profile ? earnedUnlocks(profile) : new Set<string>();
const listings = this.#catalogue.marketplaceListings().map((listing) => ({
...listing,
couponCount: heldCounts.get(listing.itemdefId) ?? 0,
alreadyActivated: profile ? isListingAlreadyActivated(profile, listing, unlockedSet) : false,
}));
return {
status: 200,
headers: JSON_HEADERS,
body: JSON.stringify({
accounts: this.#accounts.all().map((a) => ({ userId: a.userId, login: a.login, nick: a.nick })),
currentUserId: account?.userId ?? '',
balance,
listings,
}),
logNotes: { summary: `marketplace state (${account?.userId ?? 'no-account'})` },
};
}
#buy(request: ServiceRequest): ServiceResponse {
let payload: { userId?: string; itemdefId?: number; quantity?: number };
try {
payload = JSON.parse(request.body.toString('utf8')) as { userId?: string; itemdefId?: number; quantity?: number };
} catch {
return jsonMessage(false, '请求格式无效', 'marketplace buy: bad json');
}
const account = (payload.userId ? this.#accounts.byUserId(payload.userId) : undefined) ?? this.#accounts.activeAccount();
if (!account) return jsonMessage(false, '请先在游戏客户端登录一次账号', 'marketplace buy: no account');
const itemdefId = Number(payload.itemdefId ?? 0);
const quantity = Math.max(1, Math.min(20, Number(payload.quantity ?? 1)));
const listing = this.#catalogue.marketplaceListing(itemdefId);
if (!listing) return jsonMessage(false, '未找到该兑换券商品', `marketplace buy: unknown ${itemdefId}`);
let errorReason: 'NOT_FOUND' | 'NOT_ENOUGH_GJN' | undefined;
this.#profiles.updateWhen(account.userId, (saved) => {
const res = buyMarketplaceCoupon(saved, this.#catalogue, itemdefId, quantity);
if (!res.ok) {
errorReason = res.reason;
return false;
}
return true;
});
if (errorReason === 'NOT_ENOUGH_GJN') {
return jsonMessage(false, 'GJN 余额不足(可通过存档修改器或商店兑换码补充 GJN)', `marketplace buy ${itemdefId}: NOMONEY`);
}
if (errorReason) {
return jsonMessage(false, '购买失败', `marketplace buy ${itemdefId}: ${errorReason}`);
}
this.#notifyInventoryChanged();
return jsonMessage(
true,
`已购买「${listing.title.zh}」兑换券 x${quantity}!已同步至游戏库存,可在机库【道具 → 库存】中使用兑换。`,
`marketplace buy ${itemdefId} x${quantity} (${listing.gjnCost * quantity} GJN)`,
);
}
}
function isListingAlreadyActivated(profile: BlkBlock, listing: MarketplaceListing, unlockedSet: ReadonlySet<string>): boolean {
switch (listing.category) {
case 'vehicle':
return ownsVehicle(profile, listing.targetKey);
case 'skin':
case 'decal':
case 'attachable':
return ownsResource(profile, listing.targetKey);
case 'unlock':
return unlockedSet.has(listing.targetKey);
}
}
function jsonMessage(ok: boolean, message: string, summary: string): ServiceResponse {
return { status: 200, headers: JSON_HEADERS, body: JSON.stringify({ ok, message }), logNotes: { summary } };
}
@@ -0,0 +1,273 @@
/**
* Classic trophies (`cln_get_price_ex` top-level `trophy{}` + `Common/trophy/<id>` prices)
* and `cln_buy_trophy` rules (implementation notes; scripts/items/itemsClasses/itemTrophy.nut):
* 1. Silver-Lion supply chests with native drop-chance display (`showChances:b=yes`, calculated
* by `calcTrophiesDropChance` at 0x1554dc0);
* 2. Golden-Eagle direct-purchase prize-pool vehicles (`numTotal:i=1`, single `i{ unit:t }` prize,
* disabled automatically by `isPrizeUnitBought()` once owned).
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { ItemCatalogue } from '../items/item-catalogue.ts';
import { grantItem } from '../items/item-grants.ts';
import { addGoldenEagles, addSilverLions, canAfford, pay } from '../profile/profile-currency.ts';
import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts';
import { appendUserLog, EULT_OPEN_TROPHY, incrementTrophyOpenCount, trophyOpenCount } from '../profile/profile-trophies-log.ts';
import type { ServerTime } from '../profile/server-time.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
export type TrophyPrize =
| { readonly kind: 'warpoints'; readonly amount: number; readonly weight: number }
| { readonly kind: 'gold'; readonly amount: number; readonly weight: number }
| { readonly kind: 'item'; readonly itemName: string; readonly count: number; readonly weight: number }
| { readonly kind: 'unit'; readonly unitName: string; readonly parts: readonly string[]; readonly weight: number };
export interface TrophyDefinition {
readonly id: string;
readonly locId?: string;
readonly iconStyle: string;
readonly silverLions: number;
readonly goldenEagles: number;
readonly showChances: boolean;
readonly repeatable: boolean;
readonly instantOpening: boolean;
readonly numTotal: number;
readonly countryFlag?: string;
readonly prizes: readonly TrophyPrize[];
}
const DIRECT_UNIT_GOLD_BY_RANK: Readonly<Record<number, number>> = {
1: 850,
2: 1450,
3: 2600,
4: 4880,
5: 6980,
6: 8380,
7: 9650,
8: 10900,
};
export class TrophyCatalogue {
readonly #trophies: readonly TrophyDefinition[];
readonly #byId = new Map<string, TrophyDefinition>();
constructor(vehicles: readonly CatalogueVehicle[], classicItems: readonly ItemDefinition[]) {
const trophies: TrophyDefinition[] = [];
const boosterIds = classicItems
.filter((item) => item.type === 'rateBooster' && item.expiresAt === undefined)
.slice(0, 6)
.map((item) => item.name);
const hasUniversalSpare = classicItems.some((item) => item.name === 'item_universal_spare');
const eventVehicles = vehicles.filter(
(v) => v.event && !v.marketplaceItemdefId && !v.onlyShownWhenOwned && v.inTechTree,
);
const rareChestUnits = eventVehicles.slice(0, 4);
// 1. Classic Silver-Lion Supply Chest (50,000 SL, repeatable, probability disclosure enabled)
trophies.push({
id: 'wto_silver_supply_trophy',
iconStyle: 'small_wooden_box',
silverLions: 50000,
goldenEagles: 0,
showChances: true,
repeatable: true,
instantOpening: false,
numTotal: 0,
prizes: [
...(rareChestUnits.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 2 }))),
{ kind: 'warpoints', amount: 250000, weight: 8 },
{ kind: 'warpoints', amount: 75000, weight: 20 },
{ kind: 'warpoints', amount: 25000, weight: 35 },
...(hasUniversalSpare ? [{ kind: 'item', itemName: 'item_universal_spare', count: 3, weight: 25 } as const] : []),
...boosterIds.map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: 1, weight: 20 })),
],
});
// 2. Classic Veteran Silver-Lion Supply Chest (150,000 SL, repeatable, higher rewards)
trophies.push({
id: 'wto_veteran_supply_trophy',
iconStyle: 'big_chest',
silverLions: 150000,
goldenEagles: 0,
showChances: true,
repeatable: true,
instantOpening: false,
numTotal: 0,
prizes: [
...(eventVehicles.slice(4, 10).map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 4 }))),
{ kind: 'gold', amount: 150, weight: 10 },
{ kind: 'warpoints', amount: 500000, weight: 12 },
{ kind: 'warpoints', amount: 120000, weight: 28 },
...(hasUniversalSpare ? [{ kind: 'item', itemName: 'item_universal_spare', count: 5, weight: 30 } as const] : []),
...boosterIds.slice(0, 4).map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: 1, weight: 22 })),
],
});
// 3. Golden-Eagle Vehicle Prize-Pool Direct Purchase Trophies (one per event/special vehicle)
for (const vehicle of eventVehicles) {
const gold = DIRECT_UNIT_GOLD_BY_RANK[vehicle.rank] ?? 6090;
trophies.push({
id: `wto_prize_unit_${vehicle.name}`,
iconStyle: 'ammo_box',
silverLions: 0,
goldenEagles: gold,
showChances: false,
repeatable: false,
instantOpening: true,
numTotal: 1,
countryFlag: vehicle.country,
prizes: [{ kind: 'unit', unitName: vehicle.name, parts: vehicle.parts, weight: 100 }],
});
}
this.#trophies = trophies;
for (const trophy of trophies) this.#byId.set(trophy.id, trophy);
}
all(): readonly TrophyDefinition[] {
return this.#trophies;
}
byId(id: string): TrophyDefinition | undefined {
return this.#byId.get(id);
}
/** Top-level `trophy{ ... }` definition block included in `cln_get_price_ex`. */
definitionsBlk(): BlkBlock {
return {
name: 'trophy',
params: [],
blocks: this.#trophies.map(toTrophyDefinitionBlk),
};
}
}
export function buyTrophy(
profile: BlkBlock,
trophies: TrophyCatalogue,
classicItems: ItemCatalogue,
trophyId: string,
offeredWp: number,
offeredGold: number,
now: ServerTime,
): RuleOutcome {
const trophy = trophies.byId(trophyId);
if (!trophy || trophy.prizes.length === 0) return refused('BAD_PARAMS');
if (offeredWp !== trophy.silverLions || offeredGold !== trophy.goldenEagles) return refused('PRICE_CHANGED');
if (trophy.numTotal > 0 && !trophy.repeatable && trophyOpenCount(profile, trophy.id) >= trophy.numTotal) {
return refused('NOT_AVAILABLE');
}
// Direct single-unit trophy: refuse duplicate purchase if the unit is already owned.
if (trophy.prizes.length === 1 && trophy.prizes[0]!.kind === 'unit' && ownsVehicle(profile, trophy.prizes[0]!.unitName)) {
return refused('NOT_AVAILABLE');
}
const price = { silverLions: trophy.silverLions, goldenEagles: trophy.goldenEagles };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
// Filter out already-owned vehicles when rolling a multi-prize chest; fall back to full list if all non-unit.
const eligible = trophy.prizes.filter((prize) => prize.kind !== 'unit' || !ownsVehicle(profile, prize.unitName));
const pool = eligible.length > 0 ? eligible : trophy.prizes;
const chosen = rollTrophyPrize(pool);
pay(profile, price);
const openSeq = incrementTrophyOpenCount(profile, trophy.id, 1);
const nowSec = Math.floor(Date.now() / 1000);
const logBody: BlkParam[] = [
{ name: 'id', value: { type: 'string', value: trophy.id } },
{ name: 'trophyItemId', value: { type: 'int', value: openSeq } },
];
switch (chosen.kind) {
case 'warpoints':
addSilverLions(profile, chosen.amount);
logBody.push({ name: 'warpoints', value: { type: 'int', value: chosen.amount } });
break;
case 'gold':
addGoldenEagles(profile, chosen.amount);
logBody.push({ name: 'gold', value: { type: 'int', value: chosen.amount } });
break;
case 'item': {
const def = classicItems.item(chosen.itemName);
if (def) grantItem(profile, def, chosen.count, now);
logBody.push(
{ name: 'item', value: { type: 'string', value: chosen.itemName } },
{ name: 'count', value: { type: 'int', value: chosen.count } },
);
break;
}
case 'unit':
addOwnedVehicle(profile, chosen.unitName);
for (const part of chosen.parts) addOwnedVehicle(profile, part);
logBody.push(
{ name: 'unit', value: { type: 'string', value: chosen.unitName } },
{ name: 'count', value: { type: 'int', value: 1 } },
);
break;
}
appendUserLog(profile, { type: EULT_OPEN_TROPHY, timeSec: nowSec, bodyParams: logBody });
return ACCEPTED;
}
function toTrophyDefinitionBlk(trophy: TrophyDefinition): BlkBlock {
const params: BlkParam[] = [
{ name: 'iconStyle', value: { type: 'string', value: trophy.iconStyle } },
{ name: 'showChances', value: { type: 'bool', value: trophy.showChances } },
{ name: 'repeatable', value: { type: 'bool', value: trophy.repeatable } },
{ name: 'instantOpening', value: { type: 'bool', value: trophy.instantOpening } },
];
if (trophy.numTotal > 0) params.push({ name: 'numTotal', value: { type: 'int', value: trophy.numTotal } });
if (trophy.countryFlag) params.push({ name: 'showCountryFlag', value: { type: 'string', value: trophy.countryFlag } });
if (trophy.prizes.length === 1 && trophy.prizes[0]!.kind === 'unit') {
params.push({ name: 'showTypeInName', value: { type: 'bool', value: true } });
}
const prizeBlocks: BlkBlock[] = [];
for (const prize of trophy.prizes) {
// Repeat `i` entries proportionally for coarse weight or emit `weight` string + `prob` float
// so calcTrophiesDropChance (0x95a510) and prizeChance.nut both display accurate weights.
const weightTag = prize.weight >= 25 ? 'high' : prize.weight >= 10 ? 'medium' : 'low';
const prizeParams: BlkParam[] = [
{ name: 'weight', value: { type: 'string', value: weightTag } },
];
switch (prize.kind) {
case 'warpoints':
prizeParams.push({ name: 'warpoints', value: { type: 'int', value: prize.amount } });
break;
case 'gold':
prizeParams.push({ name: 'gold', value: { type: 'int', value: prize.amount } });
break;
case 'item':
prizeParams.push(
{ name: 'item', value: { type: 'string', value: prize.itemName } },
{ name: 'count', value: { type: 'int', value: prize.count } },
);
break;
case 'unit':
prizeParams.push({ name: 'unit', value: { type: 'string', value: prize.unitName } });
break;
}
prizeBlocks.push({ name: 'i', params: prizeParams, blocks: [] });
}
return {
name: trophy.id,
params,
blocks: [{ name: 'prizes', params: [], blocks: prizeBlocks }],
};
}
function rollTrophyPrize(prizes: readonly TrophyPrize[]): TrophyPrize {
const total = prizes.reduce((sum, p) => sum + p.weight, 0);
let roll = Math.random() * total;
for (const prize of prizes) {
roll -= prize.weight;
if (roll <= 0) return prize;
}
return prizes[prizes.length - 1]!;
}
+10 -1
View File
@@ -12,8 +12,11 @@ import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.t
import { shopCountries } from './game-data/datasets/shop-countries.ts';
import { GameFiles } from './game-data/game-files.ts';
import { GameModes } from './game-modes/game-modes.ts';
import { InventoryService } from './inventory/inventory-service.ts';
import { MarketplaceService } from './inventory/marketplace-service.ts';
import { LoginService } from './login/login-service.ts';
import { matchingRequests } from './matching/matching-requests.ts';
import type { MatchingService } from './matching/matching-service.ts';
import { setUpProfiles } from './profiles-setup.ts';
import { createPortListener } from './server/port-listener.ts';
import { Router } from './server/router.ts';
@@ -49,14 +52,20 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
// One store for all services: accounts registered at sign-in must be visible everywhere.
const accounts = new AccountStore(options.dataFolder);
let matching: MatchingService | undefined;
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const router = new Router([
new StoreService(accounts, profiles, research.store),
new MarketplaceService(accounts, profiles, research.inventory, notifyInventoryChanged),
new InventoryService(accounts, profiles, research.inventory),
new LoginService(accounts),
new CharService(actionTable({ profiles, accounts, research })),
new CharService(actionTable({ profiles, accounts, research, notifyInventoryChanged })),
new DownloadableContentService(),
]);
const log = new TrafficLog(options.dataFolder);
const listener = createPortListener(router, matchingRequests({ gameModes }), log, loadOrCreateCredentials(options.dataFolder));
matching = listener.matching;
await listen(listener.server, options.port);
return {
logFolder: log.folder,
@@ -20,6 +20,8 @@ export const MessageKind = {
/** Value of "type" in the client's requests (0x44e9fcd). */
export const REQUEST_TYPE = 52;
/** Value of "type" in server push notifications (0x44eaba6 -> 0x44ec1ba). */
export const NOTIFY_TYPE = 49;
export interface MatchingMessage {
readonly kind: number;
@@ -94,3 +96,8 @@ export function asRequest(message: MatchingMessage): MatchingRequest | undefined
export function answerTo(request: MatchingRequest, result: Record<string, unknown>): MatchingMessage {
return { kind: MessageKind.Answer, json: { id: request.id, type: request.type, data: { data: result } } };
}
/** Server notification (any packet kind != 0x1b, type 49; aces.exe 0x44eaba6..0x44ec1d5). */
export function notifyMessage(name: string, data: Record<string, unknown>): MatchingMessage {
return { kind: MessageKind.Request, json: { type: NOTIFY_TYPE, data: { name, data } } };
}
@@ -14,7 +14,7 @@
import type { Socket } from 'node:net';
import type { TrafficLog } from '../traffic-log/traffic-log.ts';
import { encodePacket, PacketReader } from './matching-frame.ts';
import { answerTo, asPing, asRequest, decodeMessage, encodeMessage, pingAnswer, type MatchingMessage } from './matching-message.ts';
import { answerTo, asPing, asRequest, decodeMessage, encodeMessage, notifyMessage, pingAnswer, type MatchingMessage } from './matching-message.ts';
import type { MatchingRequestTable, MatchingSessionControl } from './matching-requests.ts';
import { messageLogText } from './message-redaction.ts';
import { EnvelopeReader, sealEnvelope } from './session-crypto/encrypted-envelope.ts';
@@ -22,6 +22,7 @@ import { EnvelopeReader, sealEnvelope } from './session-crypto/encrypted-envelop
export class MatchingService {
readonly #requests: MatchingRequestTable;
readonly #log: TrafficLog;
readonly #sessions = new Set<MatchingSession>();
constructor(requests: MatchingRequestTable, log: TrafficLog) {
this.#requests = requests;
@@ -30,6 +31,8 @@ export class MatchingService {
accept(socket: Socket, connectionId: number): void {
const session = new MatchingSession(socket, connectionId, this.#requests, this.#log);
this.#sessions.add(session);
socket.on('close', () => this.#sessions.delete(session));
socket.on('data', (chunk: Buffer) => {
try {
session.receive(chunk);
@@ -40,6 +43,12 @@ export class MatchingService {
});
socket.on('error', () => socket.destroy());
}
/** Push a matching notification (such as mrpc.generic_notify) to every active client session. */
broadcastNotify(name: string, data: Record<string, unknown>): void {
const message = notifyMessage(name, data);
for (const session of this.#sessions) session.pushNotify(message, name);
}
}
class MatchingSession {
@@ -114,6 +123,12 @@ class MatchingSession {
this.#socket.write(this.#sessionKey ? sealEnvelope(this.#sessionKey, packet) : packet);
}
pushNotify(message: MatchingMessage, summaryName: string): void {
if (!this.#sessionKey || this.#socket.destroyed) return;
this.#record('out', message, `notify ${summaryName} (encrypted)`, false);
this.#send(message);
}
#record(direction: 'in' | 'out', message: MatchingMessage, summary: string, unhandled: boolean): void {
this.#log.matchingMessage(this.#connectionId, { direction, kind: message.kind, summary, unhandled, text: messageLogText(message) });
}
@@ -0,0 +1,118 @@
/**
* External inventory items stored in the player's save.
*
* Stored under top-level block `extInventory` in `profile.blk` (ignored by aces.exe's profile
* reader 0x919060), keeping every player's save self-contained in a single directory:
*
* extInventory{
* nextItemId:i=4
* item{ itemId:t="1" itemDefId:i=50221 quantity:i=1 timestamp:t="2026-11-25T00:00:00Z" }
* }
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const EXT_INVENTORY = 'extInventory';
const NEXT_ID = 'nextItemId';
const ITEM_BLOCK = 'item';
export interface StoredExternalItem {
readonly itemId: string;
readonly itemDefId: number;
readonly quantity: number;
readonly timestamp: string;
}
export function externalInventoryItems(profile: BlkBlock): StoredExternalItem[] {
const root = findBlock(profile, EXT_INVENTORY);
if (!root) return [];
const items: StoredExternalItem[] = [];
for (const child of root.blocks) {
if (child.name !== ITEM_BLOCK) continue;
const itemId = stringOf(child, 'itemId');
const itemDefId = intOf(child, 'itemDefId');
const quantity = intOf(child, 'quantity');
const timestamp = stringOf(child, 'timestamp') || new Date().toISOString();
if (itemId && itemDefId > 0 && quantity > 0) {
items.push({ itemId, itemDefId, quantity, timestamp });
}
}
return items;
}
export function externalItemByUid(profile: BlkBlock, itemId: string): StoredExternalItem | undefined {
return externalInventoryItems(profile).find((item) => item.itemId === itemId);
}
/**
* Add quantity to an existing stack of the same itemDefId, or allocate a new itemId stack.
* Returns the updated or newly created item record.
*/
export function grantExternalItem(
profile: BlkBlock,
itemDefId: number,
quantity: number,
nowIso = new Date().toISOString(),
): StoredExternalItem {
const root = ensureBlock(profile, EXT_INVENTORY);
const existing = root.blocks.find((block) => block.name === ITEM_BLOCK && intOf(block, 'itemDefId') === itemDefId);
if (existing) {
const newQty = Math.max(0, intOf(existing, 'quantity')) + quantity;
setParam(existing, 'quantity', { type: 'int', value: newQty });
setParam(existing, 'timestamp', { type: 'string', value: nowIso });
return { itemId: stringOf(existing, 'itemId'), itemDefId, quantity: newQty, timestamp: nowIso };
}
const nextId = Math.max(1, intOf(root, NEXT_ID) + 1);
setParam(root, NEXT_ID, { type: 'int', value: nextId });
const itemId = String(nextId);
root.blocks.push({
name: ITEM_BLOCK,
params: [
{ name: 'itemId', value: { type: 'string', value: itemId } },
{ name: 'itemDefId', value: { type: 'int', value: itemDefId } },
{ name: 'quantity', value: { type: 'int', value: quantity } },
{ name: 'timestamp', value: { type: 'string', value: nowIso } },
],
blocks: [],
});
return { itemId, itemDefId, quantity, timestamp: nowIso };
}
/**
* Consume up to `quantity` from a specific `itemId` stack. Returns undefined if the player
* does not hold enough in that stack; otherwise returns the post-consumption quantity (0 when
* removed).
*/
export function consumeExternalItem(
profile: BlkBlock,
itemId: string,
quantity: number,
nowIso = new Date().toISOString(),
): { readonly itemDefId: number; readonly remaining: number; readonly timestamp: string } | undefined {
if (quantity <= 0) return undefined;
const root = findBlock(profile, EXT_INVENTORY);
if (!root) return undefined;
const idx = root.blocks.findIndex((block) => block.name === ITEM_BLOCK && stringOf(block, 'itemId') === itemId);
if (idx < 0) return undefined;
const target = root.blocks[idx]!;
const itemDefId = intOf(target, 'itemDefId');
const current = intOf(target, 'quantity');
if (current < quantity) return undefined;
const remaining = current - quantity;
if (remaining === 0) {
root.blocks.splice(idx, 1);
} else {
setParam(target, 'quantity', { type: 'int', value: remaining });
setParam(target, 'timestamp', { type: 'string', value: nowIso });
}
return { itemDefId, remaining, timestamp: nowIso };
}
function stringOf(block: BlkBlock, name: string): string {
const param = findParam(block, name)?.value;
return param?.type === 'string' ? param.value : '';
}
function intOf(block: BlkBlock, name: string): number {
const param = findParam(block, name)?.value;
return param?.type === 'int' ? param.value : param?.type === 'int64' ? Number(param.value) : 0;
}
@@ -0,0 +1,58 @@
/**
* Trophy open counts and UserLog entries in the profile:
* - `trophies{ <trophyId>{ count:i=<openCount> } }` (aces.exe 0x92d16b, 0x92d4df);
* - `userlogs{ <16-hex-id>{ type:i=<EULT> time:i=<unixSec> roomId:i64=0 body{ ... } } }`
* (UserLog::serialize 0x95f160, entry fields 0x95ec30; EULT_OPEN_TROPHY = 30 at 0x1a5599b).
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
const TROPHIES = 'trophies';
const USERLOGS = 'userlogs';
const MAX_USERLOGS = 80;
export const EULT_OPEN_TROPHY = 30;
export const EULT_BUY_TROPHY = 20;
export function trophyOpenCount(profile: BlkBlock, trophyId: string): number {
const trophies = findBlock(profile, TROPHIES);
const entry = trophies && findBlock(trophies, trophyId);
const param = entry && findParam(entry, 'count')?.value;
return param?.type === 'int' ? param.value : 0;
}
export function incrementTrophyOpenCount(profile: BlkBlock, trophyId: string, delta = 1): number {
const entry = ensureBlock(ensureBlock(profile, TROPHIES), trophyId);
const next = trophyOpenCount(profile, trophyId) + delta;
setParam(entry, 'count', { type: 'int', value: next });
return next;
}
export interface NewUserLogEntry {
readonly type: number;
readonly timeSec: number;
readonly bodyParams: readonly BlkParam[];
readonly bodyBlocks?: readonly BlkBlock[];
}
export function appendUserLog(profile: BlkBlock, entry: NewUserLogEntry): string {
const logs = ensureBlock(profile, USERLOGS);
const seq = logs.blocks.length + 1;
const idHex = ((BigInt(entry.timeSec) * 1000n) + BigInt(seq)).toString(16).padStart(16, '0');
logs.blocks.push({
name: idHex,
params: [
{ name: 'type', value: { type: 'int', value: entry.type } },
{ name: 'time', value: { type: 'int', value: entry.timeSec } },
{ name: 'roomId', value: { type: 'int64', value: 0n } },
],
blocks: [{
name: 'body',
params: [...entry.bodyParams],
blocks: [...(entry.bodyBlocks ?? [])],
}],
});
if (logs.blocks.length > MAX_USERLOGS) {
logs.blocks.splice(0, logs.blocks.length - MAX_USERLOGS);
}
return idHex;
}
@@ -37,6 +37,7 @@
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts';
import type { DecorShop } from '../decor/decor-purchase.ts';
import type { TrophyCatalogue } from '../inventory/trophy-catalogue.ts';
import type { ItemCatalogue } from '../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts';
import type { UnlockShop } from '../unlocks/unlock-purchase.ts';
@@ -50,12 +51,21 @@ export function priceTable(rules: ResearchRules): BlkBlock {
return {
name: '',
params: [],
blocks: [{
name: COMMON_SECTION,
params: [],
blocks: [vehicleSection(rules.techTree, rules.equipment), ...decorSections(rules.decor), skillPackSection(rules.crew),
unlockSection(rules.unlocks), itemSection(rules.items)],
}],
blocks: [
{
name: COMMON_SECTION,
params: [],
blocks: [
vehicleSection(rules.techTree, rules.equipment),
...decorSections(rules.decor),
skillPackSection(rules.crew),
unlockSection(rules.unlocks),
itemSection(rules.items),
trophyPriceSection(rules.trophies),
],
},
rules.trophies.definitionsBlk(),
],
};
}
@@ -118,3 +128,11 @@ function unlockSection(unlocks: UnlockShop): BlkBlock {
function itemSection(items: ItemCatalogue): BlkBlock {
return { name: 'items', params: [], blocks: items.forSale().map((item) => ({ name: item.name, params: priceParams(item.silverLions, item.goldenEagles), blocks: [] })) };
}
function trophyPriceSection(trophies: TrophyCatalogue): BlkBlock {
return {
name: 'trophy',
params: [],
blocks: trophies.all().map((trophy) => ({ name: trophy.id, params: priceParams(trophy.silverLions, trophy.goldenEagles), blocks: [] })),
};
}
@@ -16,8 +16,11 @@ 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 { externalItemSources } from '../game-data/datasets/external-item-sources.ts';
import { storeBundles } from '../game-data/datasets/store-bundles.ts';
import { unitNames } from '../game-data/datasets/unit-names.ts';
import { InventoryCatalogue } from '../inventory/itemdef-catalogue.ts';
import { TrophyCatalogue } from '../inventory/trophy-catalogue.ts';
import { ItemCatalogue } from '../items/item-catalogue.ts';
import { StoreCatalogue } from '../store/store-catalogue.ts';
import { TechTree } from './tech-tree.ts';
@@ -40,10 +43,16 @@ export interface ResearchRules {
readonly items: ItemCatalogue;
/** Paid store catalogue: GE packs, SL packs, Premium Account, vehicle packs. */
readonly store: StoreCatalogue;
/** External inventory itemdefs, supply chests, recycle recipes, and marketplace coupons. */
readonly inventory: InventoryCatalogue;
/** Classic trophies: SL supply chests and GE vehicle prize-pool direct purchases. */
readonly trophies: TrophyCatalogue;
}
export function loadResearchRules(datasets: DatasetCache): ResearchRules {
const vehicles = datasets.load(vehicleCatalogue);
const classicItemDefs = datasets.load(itemCatalogue);
const localizedUnitNames = datasets.load(unitNames);
return {
techTree: new TechTree(vehicles),
eraRequirements: datasets.load(eraRequirements),
@@ -54,7 +63,9 @@ export function loadResearchRules(datasets: DatasetCache): ResearchRules {
decor: new DecorShop(datasets.load(decorCatalogue)),
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)),
items: new ItemCatalogue(classicItemDefs),
store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames),
inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs),
trophies: new TrophyCatalogue(vehicles, classicItemDefs),
};
}
+18 -2
View File
@@ -19,13 +19,14 @@ import type { ItemDefinition } from './game-data/datasets/item-catalogue.ts';
import { grantItem } from './items/item-grants.ts';
import { balanceOf, setGjn, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts';
import { remainingPremiumDays } from './profile/profile-entitlements.ts';
import { externalInventoryItems, grantExternalItem } from './profile/profile-external-inventory.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>] [--gjn <n>] [--free-rp <n>] [--give-item <item>[:<pieces>]]...';
+ '[--silver <n>] [--gold <n>] [--gjn <n>] [--free-rp <n>] [--give-item <item>[:<pieces>]]... [--give-coupon <itemdefId>[:<qty>]]...';
function main(): number {
const { values } = parseArgs({
@@ -38,6 +39,7 @@ function main(): number {
gjn: { type: 'string' },
'free-rp': { type: 'string' },
'give-item': { type: 'string', multiple: true },
'give-coupon': { type: 'string', multiple: true },
},
});
if (!values.game || !values.data || !values.player) {
@@ -72,7 +74,18 @@ function main(): number {
}
gifts.push({ item, pieces });
}
const changes = silver !== undefined || gold !== undefined || gjn !== undefined || freeRp !== undefined || gifts.length > 0;
const coupons: { itemdefId: number; quantity: number }[] = [];
for (const request of values['give-coupon'] ?? []) {
const [idText = '', qtyText = '1'] = request.split(':');
const itemdefId = optionalAmount(idText);
const quantity = optionalAmount(qtyText);
if (!itemdefId || !quantity || !research.inventory.hasItemDef(itemdefId)) {
console.error(`--give-coupon: unknown itemdef id "${idText}", or quantity not a whole number of 1 or more`);
return 2;
}
coupons.push({ itemdefId, quantity });
}
const changes = silver !== undefined || gold !== undefined || gjn !== undefined || freeRp !== undefined || gifts.length > 0 || coupons.length > 0;
const now = serverTimeNow();
const profile = !changes
? profiles.profileOf(account.userId)
@@ -82,6 +95,7 @@ function main(): number {
if (gjn !== undefined) setGjn(saved, gjn);
if (freeRp !== undefined) setFreeResearchPoints(saved, freeRp);
for (const gift of gifts) grantItem(saved, gift.item, gift.pieces, now);
for (const coupon of coupons) grantExternalItem(saved, coupon.itemdefId, coupon.quantity);
});
const balance = balanceOf(profile);
const premiumDays = remainingPremiumDays(profile, now);
@@ -89,6 +103,8 @@ function main(): number {
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(', ')}`);
const extItems = externalInventoryItems(profile);
if (extItems.length) console.log(`extInventory: ${extItems.map((item) => `#${item.itemDefId} x${item.quantity}`).join(', ')}`);
return 0;
}
@@ -19,6 +19,7 @@ import type { Router } from './router.ts';
export interface PortListener {
readonly server: Server;
readonly matching: MatchingService;
/** Drop every open connection (on shutdown; the game keeps some open indefinitely). */
destroyConnections(): void;
}
@@ -62,6 +63,7 @@ export function createPortListener(router: Router, matchingRequests: MatchingReq
return {
server,
matching,
destroyConnections: () => {
for (const socket of open) socket.destroy();
},