Fix squadron persistence and align inventory wire formats

Read squadron action parameters from the request headers and persist
squadron state on profile refresh. Use floating-point trophy weights
to match the client probability display and assign unique log IDs
when opening multiple chests.

Tighten shop, marketplace, squadron, and cloud settings validation.
Move PBBD and inventory encoding into the protocol modules and share
CSV reading. Update the research and acceptance instructions.

Type checking and all eight executable patch checks passed.
In-game acceptance is pending.
This commit is contained in:
N0VAN0M4LY committed 2026-11-25 09:10:09 +08:00
1 parent 0b604c76f1
commit 8012cf7954
40 files changed
+1347 -1248

No files matched your search

@@ -39,28 +39,21 @@ export function buildSupplyChests(sources: SupplyChestSources): SupplyChestBuild
...(sources.wrappersByPart.get(299001) ?? []).slice(0, 5),
...(sources.wrappersByPart.get(299003) ?? []).slice(0, 2),
];
const midTierVehicles = pickAcrossCountries(sources.sortedMarketVehicles.filter((v) => v.rank <= 4), 6).map((v) => v.marketplaceItemdefId!);
const highTierVehicles = pickAcrossCountries(sources.sortedMarketVehicles.filter((v) => v.rank >= 5), 10).map((v) => v.marketplaceItemdefId!);
const tacticalDecors = [
...sources.skinCouponIds.slice(0, 3),
...sources.decalCouponIds.slice(0, 2),
...sources.attachableCouponIds.slice(0, 3),
];
const collectorDecors = [
...sources.skinCouponIds.slice(3, 8),
...sources.decalCouponIds.slice(2, 4),
...sources.attachableCouponIds.slice(3, 8),
];
const tactical = buildTacticalChest(commonWrappers, sources, midTierVehicles);
const collector = buildCollectorChest(commonWrappers, sources, highTierVehicles.length ? highTierVehicles : midTierVehicles);
return {
defs: [...tactical.defs, ...collector.defs],
prices: [tactical.price, collector.price],
generators: [tactical.generator, collector.generator],
};
}
const midTierVehicles = pickAcrossCountries(
sources.sortedMarketVehicles.filter((v) => v.rank <= 4),
6,
).map((v) => v.marketplaceItemdefId!);
const highTierVehicles = pickAcrossCountries(
sources.sortedMarketVehicles.filter((v) => v.rank >= 5),
10,
).map((v) => v.marketplaceItemdefId!);
const tactical = createChestPair({
function buildTacticalChest(commonWrappers: readonly number[], sources: SupplyChestSources, vehicleIds: readonly number[]) {
const decors = [...sources.skinCouponIds.slice(0, 3), ...sources.decalCouponIds.slice(0, 2), ...sources.attachableCouponIds.slice(0, 3)];
return createChestPair({
chestId: TACTICAL_CHEST_ID,
genId: TACTICAL_CHEST_GEN_ID,
silverLions: 60_000,
@@ -73,12 +66,15 @@ export function buildSupplyChests(sources: SupplyChestSources): SupplyChestBuild
},
drops: [
...commonWrappers.map((itemdefId) => ({ itemdefId, weight: 80 })),
...tacticalDecors.map((itemdefId) => ({ itemdefId, weight: 18 })),
...midTierVehicles.map((itemdefId) => ({ itemdefId, weight: 4 })),
...decors.map((itemdefId) => ({ itemdefId, weight: 18 })),
...vehicleIds.map((itemdefId) => ({ itemdefId, weight: 4 })),
],
});
}
const collector = createChestPair({
function buildCollectorChest(commonWrappers: readonly number[], sources: SupplyChestSources, vehicleIds: readonly number[]) {
const decors = [...sources.skinCouponIds.slice(3, 8), ...sources.decalCouponIds.slice(2, 4), ...sources.attachableCouponIds.slice(3, 8)];
return createChestPair({
chestId: COLLECTOR_CHEST_ID,
genId: COLLECTOR_CHEST_GEN_ID,
silverLions: 250_000,
@@ -91,16 +87,10 @@ export function buildSupplyChests(sources: SupplyChestSources): SupplyChestBuild
},
drops: [
...commonWrappers.slice(0, 5).map((itemdefId) => ({ itemdefId, weight: 45 })),
...collectorDecors.map((itemdefId) => ({ itemdefId, weight: 22 })),
...(highTierVehicles.length ? highTierVehicles : midTierVehicles).map((itemdefId) => ({ itemdefId, weight: 12 })),
...decors.map((itemdefId) => ({ itemdefId, weight: 22 })),
...vehicleIds.map((itemdefId) => ({ itemdefId, weight: 12 })),
],
});
return {
defs: [...tactical.defs, ...collector.defs],
prices: [tactical.price, collector.price],
generators: [tactical.generator, collector.generator],
};
}
/**
@@ -1,15 +1,14 @@
/**
* Rules for external inventory consumption, item recycling, generator exchanges (chest
* opening and workshop/recycle crafting), and GJN marketplace coupon purchases
*.
* Pure domain rules for external inventory coupon consumption, item recycling, generator
* exchanges (chest opening and workshop/recycle crafting), and GJN marketplace coupon purchases
*. Wire JSON formatting lives in `inventory-wire.ts`.
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import { grantItem } from '../items/item-grants.ts';
import type { ItemCatalogue } from '../items/item-catalogue.ts';
import { grantItem } from '../items/item-grants.ts';
import { balanceOf, canAfford, pay, payGjn } from '../profile/profile-currency.ts';
import {
consumeExternalItem,
externalInventoryItems,
externalItemByUid,
grantExternalItem,
type StoredExternalItem,
@@ -17,26 +16,22 @@ import {
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 { appendUserLog, EULT_OPEN_TROPHY, incrementTrophyOpenCount } 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 { ExchangeMaterialInput } from './inventory-wire.ts';
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
import type { GeneratorDrop, InventoryItemJson } from './itemdef-types.ts';
import type { GeneratorDefinition, GeneratorDrop } 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,
};
export function pickWeighted<T extends { readonly weight: number }>(entries: readonly T[]): T {
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
let roll = Math.random() * total;
for (const entry of entries) {
roll -= entry.weight;
if (roll <= 0) return entry;
}
return entries[entries.length - 1]!;
}
/** `cln_consume_inventory_item` (char_send_blk): consume coupon(s) into vehicles, decor, unlocks or items. */
@@ -48,7 +43,7 @@ export function consumeInventoryCoupon(
quantity: number,
now: ServerTime,
): RuleOutcome {
if (quantity < 1) return refused('BAD_PARAMS');
if (!Number.isSafeInteger(quantity) || quantity < 1) return refused('BAD_PARAMS');
const held = externalItemByUid(profile, itemUid);
if (!held || held.quantity < quantity) return refused('NOT_AVAILABLE');
@@ -57,21 +52,18 @@ export function consumeInventoryCoupon(
switch (action.kind) {
case 'vehicle': {
if (ownsVehicle(profile, action.unitName)) return refused('NOT_AVAILABLE');
if (!consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
if (ownsVehicle(profile, action.unitName) || !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');
if (ownsResource(profile, action.resourceKey) || !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');
if (earnedUnlocks(profile).has(action.unlockId) || !consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
addUnlock(profile, action.unlockId);
return ACCEPTED;
}
@@ -85,7 +77,7 @@ export function consumeInventoryCoupon(
}
}
/** `cln_multi_consume_inventory_item_json`: batch auto-consume of external items (such as classic-item wrappers). */
/** `cln_multi_consume_inventory_item_json`: batch auto-consume of external items. */
export function multiConsumeInventoryItems(
profile: BlkBlock,
catalogue: InventoryCatalogue,
@@ -110,15 +102,12 @@ export function purchaseExternalInventoryItem(
offeredWp: number,
offeredGold: number,
): RuleOutcome {
if (amount < 1 || amount > 100) return refused('BAD_PARAMS');
if (!Number.isSafeInteger(amount) || 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,
};
const totalPrice = { silverLions: unitPrice.silverLions * amount, goldenEagles: unitPrice.goldenEagles * amount };
if (!canAfford(profile, totalPrice)) return refused('NOT_ENOUGH_MONEY');
pay(profile, totalPrice);
@@ -133,19 +122,17 @@ export function recycleClassicItems(
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');
if (!entry.uid || !Number.isSafeInteger(entry.count) || entry.count < 1) return refused('BAD_PARAMS');
countsByUid.set(entry.uid, (countsByUid.get(entry.uid) ?? 0) + entry.count);
}
const validated: Array<{ readonly uid: string; readonly count: number; readonly remaining: number; readonly partId: number }> = [];
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;
const partId = classicItems.item(owned.id)?.recycleItemResult;
if (!partId) return refused('NOT_AVAILABLE');
validated.push({ uid, count, remaining: owned.count - count, partId });
}
@@ -159,121 +146,96 @@ export function recycleClassicItems(
return ACCEPTED;
}
export interface ExchangeMaterialInput {
readonly itemid: string;
readonly itemdefid: number;
export interface ExchangeItemDelta {
readonly itemId: string;
readonly itemDefId: number;
readonly quantity: number;
}
export interface ParsedExchangeRequest {
readonly outputItemDefId: number;
readonly quantity: number;
readonly materials: readonly ExchangeMaterialInput[];
}
export function parseExchangeItemsRequest(rawText: string): ParsedExchangeRequest | undefined {
let parsed: Record<string, unknown>;
try {
const raw = JSON.parse(rawText) as Record<string, unknown>;
parsed = typeof raw.data === 'object' && raw.data !== null ? (raw.data as Record<string, unknown>) : raw;
} catch {
return undefined;
}
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),
}];
});
return { outputItemDefId, quantity, materials };
}
export function pickWeighted<T extends { readonly weight: number }>(entries: readonly T[]): T {
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
let roll = Math.random() * total;
for (const entry of entries) {
roll -= entry.weight;
if (roll <= 0) return entry;
}
return entries[entries.length - 1]!;
readonly timestamp: string;
}
export type ExchangeOutcome =
| { readonly ok: true; readonly delta: InventoryItemJson[] }
| { readonly ok: true; readonly delta: ExchangeItemDelta[] }
| { 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' };
if (!Number.isSafeInteger(quantity) || 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 validationError = validateRecipeMaterials(profile, gen, quantity, materials);
if (validationError) return { ok: false, code: validationError };
const nowIso = new Date(nowSec * 1000).toISOString();
const deltaByUid = new Map<string, InventoryItemJson>();
const deltaByUid = new Map<string, ExchangeItemDelta>();
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,
});
deltaByUid.set(uid, { itemId: uid, itemDefId: consumed.itemDefId, quantity: consumed.remaining, timestamp: nowIso });
}
rollGeneratorOutputs(profile, gen, quantity, nowSec, nowIso, deltaByUid);
return { ok: true, delta: [...deltaByUid.values()] };
}
function validateRecipeMaterials(
profile: BlkBlock,
gen: GeneratorDefinition,
quantity: number,
materials: readonly ExchangeMaterialInput[],
): string | undefined {
const providedByDef = new Map<number, number>();
for (const mat of materials) {
if (!mat.itemid || !Number.isSafeInteger(mat.quantity) || mat.quantity < 1) return 'BAD_MATERIALS';
const held = externalItemByUid(profile, String(mat.itemid));
if (!held || held.itemDefId !== Number(mat.itemdefid) || held.quantity < mat.quantity) return 'NOT_ENOUGH_ITEMS';
providedByDef.set(held.itemDefId, (providedByDef.get(held.itemDefId) ?? 0) + mat.quantity);
}
const matches = gen.recipes.some((recipe) =>
recipe.components.length === providedByDef.size
&& recipe.components.every((comp) => providedByDef.get(comp.itemdefId) === comp.quantity * quantity));
return matches ? undefined : 'RECIPE_MISMATCH';
}
function rollGeneratorOutputs(
profile: BlkBlock,
gen: GeneratorDefinition,
quantity: number,
nowSec: number,
nowIso: string,
deltaByUid: Map<string, ExchangeItemDelta>,
): void {
for (let i = 0; i < quantity; i += 1) {
const dropDefId = pickWeighted<GeneratorDrop>(gen.drops).itemdefId;
const granted = grantExternalItem(profile, dropDefId, 1, nowIso);
deltaByUid.set(granted.itemId, toInventoryJson(granted, accountId));
deltaByUid.set(granted.itemId, granted);
if (gen.isChestGenerator && gen.chestItemdefId !== undefined) {
// Allocate a unique monotonically increasing open sequence ID so opening multiple chests
// in one batch never overwrites same-itemDefId entries in buyAndOpenChestWnd.nut.
const uniqueOpenId = incrementTrophyOpenCount(profile, 'trophyFromInventory', 1);
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: 'itemId', value: { type: 'int', value: uniqueOpenId } },
{ 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 =
@@ -284,10 +246,12 @@ export function buyMarketplaceCoupon(
profile: BlkBlock,
catalogue: InventoryCatalogue,
itemdefId: number,
quantity = 1,
quantity: number,
): MarketBuyOutcome {
const listing = catalogue.marketplaceListing(itemdefId);
if (!listing || quantity < 1 || quantity > 20) return { ok: false, reason: 'NOT_FOUND' };
if (!listing || !Number.isSafeInteger(quantity) || 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' };
@@ -9,11 +9,12 @@ 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, parseExchangeItemsRequest, toInventoryJsonList } from './inventory-rules.ts';
import { jsonResponse } from '../web-ui/web-helpers.ts';
import { exchangeInventoryItems, type ExchangeItemDelta } from './inventory-rules.ts';
import { deltaToInventoryJson, parseExchangeItemsRequest, toInventoryJsonList } from './inventory-wire.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 {
@@ -88,17 +89,10 @@ export class InventoryService implements Service {
const parsed = parseExchangeItemsRequest(request.body.toString('utf8'));
if (!parsed) return errorResponse('BAD_JSON', 'ExchangeItems: invalid JSON');
let delta: unknown[] | undefined;
let delta: ExchangeItemDelta[] | undefined;
let errorCode = 'EXCHANGE_FAILED';
this.#profiles.updateWhen(account.userId, (saved) => {
const res = exchangeInventoryItems(
saved,
account.userId,
this.#catalogue,
parsed.outputItemDefId,
parsed.quantity,
parsed.materials,
);
const res = exchangeInventoryItems(saved, this.#catalogue, parsed.outputItemDefId, parsed.quantity, parsed.materials);
if (!res.ok) {
errorCode = res.code;
return false;
@@ -108,7 +102,8 @@ export class InventoryService implements Service {
});
if (!delta) return errorResponse(errorCode, `ExchangeItems (${parsed.outputItemDefId}) -> ${errorCode}`);
return jsonResponse({ response: { item_json: delta } }, `ExchangeItems (${parsed.outputItemDefId} x${parsed.quantity}) -> ${delta.length} delta item(s)`);
const jsonDelta = deltaToInventoryJson(delta, account.userId);
return jsonResponse({ response: { item_json: jsonDelta } }, `ExchangeItems (${parsed.outputItemDefId} x${parsed.quantity}) -> ${jsonDelta.length} delta item(s)`);
}
#resolveAccount(request: ServiceRequest): Account | undefined {
@@ -126,11 +121,6 @@ function headerOf(request: ServiceRequest, name: string): string | undefined {
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,70 @@
/**
* Protocol-layer JSON encoders and parsers for `inventory-proxy` (`GetInventory`,
* `ExchangeItems`) and `cln_inventory_exchange_items`.
*/
import type { BlkBlock } from '@wto/blk';
import { externalInventoryItems, type StoredExternalItem } from '../profile/profile-external-inventory.ts';
import type { ExchangeItemDelta } from './inventory-rules.ts';
import type { InventoryItemJson } from './itemdef-types.ts';
export interface ExchangeMaterialInput {
readonly itemid: string;
readonly itemdefid: number;
readonly quantity: number;
}
export interface ParsedExchangeRequest {
readonly outputItemDefId: number;
readonly quantity: number;
readonly materials: readonly ExchangeMaterialInput[];
}
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,
};
}
export function deltaToInventoryJson(deltas: readonly ExchangeItemDelta[], accountId: string): InventoryItemJson[] {
return deltas.map((d) => ({
itemid: d.itemId,
itemdef: d.itemDefId,
accountid: accountId,
quantity: d.quantity,
state: 'none',
timestamp: d.timestamp,
}));
}
export function parseExchangeItemsRequest(rawText: string): ParsedExchangeRequest | undefined {
let parsed: Record<string, unknown>;
try {
const raw = JSON.parse(rawText) as Record<string, unknown>;
parsed = typeof raw.data === 'object' && raw.data !== null ? (raw.data as Record<string, unknown>) : raw;
} catch {
return undefined;
}
const outputItemDefId = Number(parsed.outputitemdefid ?? 0);
const quantity = Number(parsed.quantity ?? 1);
if (!Number.isSafeInteger(outputItemDefId) || !Number.isSafeInteger(quantity)) return undefined;
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),
}];
});
return { outputItemDefId, quantity, materials };
}
@@ -60,7 +60,7 @@ export class MarketplaceService implements Service {
if (subPath === '/api/buy' && request.method === 'POST') return this.#buy(request);
return MARKET_WEB.serve(subPath, `marketplace web (${request.query.get('n') ?? 'index'})`)
?? MARKET_WEB.serve('/', `marketplace web (${request.query.get('n') ?? 'index'})`)!;
?? { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: 'Not found', logNotes: { summary: `marketplace 404: ${subPath}` } };
}
#state(request: ServiceRequest): ServiceResponse {
@@ -98,7 +98,11 @@ export class MarketplaceService implements Service {
}
const itemdefId = Number(body.itemdefId ?? 0);
const quantity = Math.max(1, Math.min(20, Math.trunc(Number(body.quantity ?? 1))));
const rawQuantity = body.quantity === undefined ? 1 : Number(body.quantity);
if (!Number.isSafeInteger(itemdefId) || itemdefId <= 0 || !Number.isSafeInteger(rawQuantity) || rawQuantity < 1 || rawQuantity > 20) {
return jsonResponse({ ok: false, message: '请求参数无效(每次购买数量需为 1~20 的整数)。' }, 'marketplace buy: bad params');
}
const quantity = rawQuantity;
const listing = this.#catalogue.marketplaceListing(itemdefId);
if (!listing) return jsonResponse({ ok: false, message: '未找到该兑换券商品。' }, `marketplace buy: unknown ${itemdefId}`);
@@ -39,42 +39,55 @@ export function buildRecyclingDefs(classicItems: readonly ItemDefinition[]): Rec
const wrappersByPart = buildClassicWrappers(classicItems, defs, coupons);
const allWrappers = [...new Set([...wrappersByPart.values()].flat())];
const { pairRecipes, pairStrings } = buildPairRecipes();
for (const partId of RECYCLE_PART_IDS) {
const singleGenId = partId + RECYCLE_SINGLE_OFFSET;
const title = PART_NAMES[partId] ?? { en: `Recycled Part #${partId}`, zh: `回收组件 #${partId}` };
defs.push(makeLocalizedItemDef(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',
}, 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 }));
defs.push(makeLocalizedItemDef(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',
}, { en: 'Item Synthesizer', zh: '道具合成器' }, { en: '', zh: '' }));
generators.push({
itemdefId: singleGenId,
isChestGenerator: false,
recipes: [{ components: [{ itemdefId: partId, quantity: 2 }] }],
drops,
});
registerSinglePartSynthesizer(partId, wrappersByPart.get(partId) ?? allWrappers, defs, generators);
}
registerMixedSynthesizer(allWrappers, defs, generators);
return { defs, coupons, generators, wrappersByPart };
}
function registerSinglePartSynthesizer(
partId: number,
pool: readonly number[],
defs: LocalizedItemDef[],
generators: GeneratorDefinition[],
): void {
const singleGenId = partId + RECYCLE_SINGLE_OFFSET;
const title = PART_NAMES[partId] ?? { en: `Recycled Part #${partId}`, zh: `回收组件 #${partId}` };
defs.push(makeLocalizedItemDef(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',
}, title, {
en: 'Obtained by recycling classic items; 2 fragments craft a new random tactical item.',
zh: '回收经典道具所得;每 2 个组件可重新合成 1 件随机道具。',
}));
defs.push(makeLocalizedItemDef(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',
}, { en: 'Item Synthesizer', zh: '道具合成器' }, { en: '', zh: '' }));
generators.push({
itemdefId: singleGenId,
isChestGenerator: false,
recipes: [{ components: [{ itemdefId: partId, quantity: 2 }] }],
drops: pool.map((id): GeneratorDrop => ({ itemdefId: id, weight: 10 })),
});
}
function registerMixedSynthesizer(
allWrappers: readonly number[],
defs: LocalizedItemDef[],
generators: GeneratorDefinition[],
): void {
const { pairRecipes, pairStrings } = buildPairRecipes();
defs.push(makeLocalizedItemDef(RECYCLE_GENERIC_GENERATOR_ID, {
type: 'generator',
marketable: false,
@@ -88,10 +101,8 @@ export function buildRecyclingDefs(classicItems: readonly ItemDefinition[]): Rec
itemdefId: RECYCLE_GENERIC_GENERATOR_ID,
isChestGenerator: false,
recipes: pairRecipes,
drops: allWrappers.map((id) => ({ itemdefId: id, weight: 10 })),
drops: allWrappers.map((id): GeneratorDrop => ({ itemdefId: id, weight: 10 })),
});
return { defs, coupons, generators, wrappersByPart };
}
function buildClassicWrappers(
@@ -27,7 +27,6 @@ export type TrophyPrize =
export interface TrophyDefinition {
readonly id: string;
readonly locId?: string;
readonly iconStyle: string;
readonly silverLions: number;
readonly goldenEagles: number;
@@ -55,8 +54,6 @@ export class TrophyCatalogue {
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)
.map((item) => item.name)
@@ -68,66 +65,15 @@ export class TrophyCatalogue {
.filter((v) => v.event && !v.marketplaceItemdefId && !v.onlyShownWhenOwned && v.inTechTree)
.sort((a, b) => (a.rank - b.rank) || a.country.localeCompare(b.country) || a.name.localeCompare(b.name));
const silverChestUnits = pickAcrossCountries(sortedEventVehicles.filter((v) => v.rank <= 3), 4);
const veteranChestUnits = pickAcrossCountries(sortedEventVehicles.filter((v) => v.rank >= 4), 6);
const silverUnits = pickAcrossCountries(sortedEventVehicles.filter((v) => v.rank <= 3), 4);
const veteranUnits = pickAcrossCountries(sortedEventVehicles.filter((v) => v.rank >= 4), 6);
trophies.push({
id: 'wto_silver_supply_trophy',
iconStyle: 'small_wooden_box',
silverLions: 50_000,
goldenEagles: 0,
showChances: true,
repeatable: true,
instantOpening: false,
numTotal: 0,
prizes: [
...silverChestUnits.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 2 })),
{ kind: 'warpoints', amount: 250_000, weight: 8 },
{ kind: 'warpoints', amount: 75_000, weight: 20 },
{ kind: 'warpoints', amount: 25_000, 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 })),
],
});
trophies.push({
id: 'wto_veteran_supply_trophy',
iconStyle: 'big_chest',
silverLions: 150_000,
goldenEagles: 0,
showChances: true,
repeatable: true,
instantOpening: false,
numTotal: 0,
prizes: [
...(veteranChestUnits.length ? veteranChestUnits : silverChestUnits)
.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 4 })),
{ kind: 'gold', amount: 150, weight: 10 },
{ kind: 'warpoints', amount: 500_000, weight: 12 },
{ kind: 'warpoints', amount: 120_000, 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 })),
],
});
for (const vehicle of sortedEventVehicles) {
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);
this.#trophies = [
buildSilverSupplyTrophy(silverUnits, boosterIds, hasUniversalSpare),
buildVeteranSupplyTrophy(veteranUnits.length ? veteranUnits : silverUnits, boosterIds, hasUniversalSpare),
...sortedEventVehicles.map(buildDirectUnitTrophy),
];
for (const trophy of this.#trophies) this.#byId.set(trophy.id, trophy);
}
all(): readonly TrophyDefinition[] {
@@ -139,6 +85,63 @@ export class TrophyCatalogue {
}
}
function buildSilverSupplyTrophy(units: readonly CatalogueVehicle[], boosterIds: readonly string[], hasSpare: boolean): TrophyDefinition {
return {
id: 'wto_silver_supply_trophy',
iconStyle: 'small_wooden_box',
silverLions: 50_000,
goldenEagles: 0,
showChances: true,
repeatable: true,
instantOpening: false,
numTotal: 0,
prizes: [
...units.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 2 })),
{ kind: 'warpoints', amount: 250_000, weight: 8 },
{ kind: 'warpoints', amount: 75_000, weight: 20 },
{ kind: 'warpoints', amount: 25_000, weight: 35 },
...(hasSpare ? [{ kind: 'item', itemName: 'item_universal_spare', count: 3, weight: 25 } as const] : []),
...boosterIds.map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: 1, weight: 20 })),
],
};
}
function buildVeteranSupplyTrophy(units: readonly CatalogueVehicle[], boosterIds: readonly string[], hasSpare: boolean): TrophyDefinition {
return {
id: 'wto_veteran_supply_trophy',
iconStyle: 'big_chest',
silverLions: 150_000,
goldenEagles: 0,
showChances: true,
repeatable: true,
instantOpening: false,
numTotal: 0,
prizes: [
...units.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 4 })),
{ kind: 'gold', amount: 150, weight: 10 },
{ kind: 'warpoints', amount: 500_000, weight: 12 },
{ kind: 'warpoints', amount: 120_000, weight: 28 },
...(hasSpare ? [{ 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 })),
],
};
}
function buildDirectUnitTrophy(vehicle: CatalogueVehicle): TrophyDefinition {
return {
id: `wto_prize_unit_${vehicle.name}`,
iconStyle: 'ammo_box',
silverLions: 0,
goldenEagles: DIRECT_UNIT_GOLD_BY_RANK[vehicle.rank] ?? 6090,
showChances: false,
repeatable: false,
instantOpening: true,
numTotal: 1,
countryFlag: vehicle.country,
prizes: [{ kind: 'unit', unitName: vehicle.name, parts: vehicle.parts, weight: 100 }],
};
}
export function buyTrophy(
profile: BlkBlock,
trophies: TrophyCatalogue,