diff --git a/packages/local-service/package.json b/packages/local-service/package.json index 1eaa753..44ba112 100644 --- a/packages/local-service/package.json +++ b/packages/local-service/package.json @@ -5,5 +5,9 @@ "type": "module", "exports": { ".": "./src/index.ts" + }, + "dependencies": { + "@wto/blk": "*", + "@wto/vromfs": "*" } } diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index 04eb6ee..4e93ea4 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -30,25 +30,11 @@ import { clanRejectCandidateAction, setClanBestRewardsAction, } from './clan-moderation-actions.ts'; -import { - buyNotResearchedClanUnitAction, - flushClanExpToUnitAction, - setResearchClanUnitAction, -} from './squadron-research-actions.ts'; import { bulkSetGblkAction, getGeneralBlkAction, getMetaBlkAction, setGeneralBlkAction } from './cloud-settings-actions.ts'; import { bulkTrainCrews, trainCrew } from './crew-actions.ts'; -import { buyUnlockAction } from './unlock-actions.ts'; -import { buyAllModificationsAction, buyModificationAction, buySparesAction, buyWeaponsAction, enableModificationsAction } from './modification-actions.ts'; import { purchaseSkillPointsAction, specializeCrewAction, upgradeCrewAction } from './crew-skill-actions.ts'; -import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts'; import { buyResourceAction } from './decor-actions.ts'; import { saveDecorLayoutsAction } from './decor-layout-actions.ts'; -import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; -import { priceEx } from './price-actions.ts'; -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, @@ -57,7 +43,17 @@ import { purchaseInventoryItemAction, recycleItemsAction, } from './inventory-actions.ts'; +import { activateBoosterAction, activateDiscountAction, applySpareItemAction, buyItemAction, startWagerAction } from './item-actions.ts'; +import { buyAllModificationsAction, buyModificationAction, buySparesAction, buyWeaponsAction, enableModificationsAction } from './modification-actions.ts'; +import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; +import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts'; +import { priceEx } from './price-actions.ts'; +import { buyAircraft, buySlot } from './purchase-actions.ts'; +import { convertExp, resetResearchable, setResearchable } from './research-actions.ts'; +import { buyNotResearchedClanUnitAction, flushClanExpToUnitAction, setResearchClanUnitAction } from './squadron-research-actions.ts'; +import { setStartingInfo } from './starting-info-actions.ts'; import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts'; +import { buyUnlockAction } from './unlock-actions.ts'; export interface ActionDependencies { readonly profiles: PlayerProfiles; @@ -69,11 +65,20 @@ export interface ActionDependencies { } export function actionTable(deps: ActionDependencies): ReadonlyMap { - const notifyInventory = deps.notifyInventoryChanged ?? (() => {}); const entries: Array<[string, CharActionHandler]> = [ + ...coreActionEntries(deps), + ...(deps.clans ? clanActionEntries(deps, deps.clans) : []), + ...(deps.cloudSettings ? cloudActionEntries(deps.accounts, deps.cloudSettings) : []), + ]; + return new Map(entries); +} + +function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionHandler]> { + const notifyInventory = deps.notifyInventoryChanged ?? (() => {}); + return [ ['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)], - ['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts, deps.clans)], - ['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts, deps.clans)], + ['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)], + ['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)], ['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)], ['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)], ['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.research)], @@ -115,46 +120,41 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap { + return [ + ['cln_clan_get', clanGetAction(deps.accounts, clans)], + ['cln_clan_get_leaderboard', clanGetLeaderboardAction(clans)], + ['cln_clan_find_by_prefix', clanFindByPrefixAction(clans)], + ['cln_clans_list_get_short_info', clansListShortInfoAction(clans)], + ['cln_clan_get_log', clanGetLogAction(deps.accounts, clans)], + ['cln_clan_create', clanCreateAction(deps.profiles, deps.accounts, clans, deps.research)], + ['cln_clan_change_info', clanChangeInfoAction(deps.profiles, deps.accounts, clans, deps.research)], + ['cln_clan_upgrade', clanUpgradeAction(deps.profiles, deps.accounts, clans, deps.research)], + ['cln_clan_members_upgrade', clanMembersUpgradeAction(deps.profiles, deps.accounts, clans, deps.research)], + ['cln_clan_set_membership_requirements', clanSetMembershipReqAction(deps.accounts, clans)], + ['cln_clan_membership_request', clanMembershipRequestAction(deps.profiles, deps.accounts, clans)], + ['cln_clan_leave', clanLeaveAction(deps.profiles, deps.accounts, clans)], + ['cln_clan_disband', clanDisbandAction(deps.profiles, deps.accounts, clans)], + ['cln_clan_sync_profile_and_clan', clanSyncProfileAction(deps.profiles, deps.accounts, clans)], + ['ano_clan_accept_membership_request', clanAcceptCandidateAction(deps.profiles, deps.accounts, clans)], + ['ano_clan_reject_membership_request', clanRejectCandidateAction(deps.profiles, deps.accounts, clans)], + ['ano_clan_dismiss_member', clanDismissMemberAction(deps.profiles, deps.accounts, clans)], + ['ano_clan_change_member_role', clanChangeMemberRoleAction(deps.profiles, deps.accounts, clans)], + ['ano_clan_edit_blacklist', clanEditBlacklistAction(deps.accounts, clans)], + ['cln_set_clan_best_rewards', setClanBestRewardsAction(deps.accounts, clans)], + ['cln_set_research_clan_unit', setResearchClanUnitAction(deps.profiles, deps.accounts, clans, deps.research)], + ['cln_flush_clan_exp_to_unit', flushClanExpToUnitAction(deps.profiles, deps.accounts, clans, deps.research)], + ['cln_buy_not_researched_clans_unit', buyNotResearchedClanUnitAction(deps.profiles, deps.accounts, clans, deps.research)], + ]; +} - if (deps.cloudSettings) { - const cloudSettings = deps.cloudSettings; - entries.push( - ['cln_get_meta_blk', getMetaBlkAction(deps.accounts, cloudSettings)], - ['cln_get_general_blk', getGeneralBlkAction(deps.accounts, cloudSettings)], - ['cln_set_general_blk', setGeneralBlkAction(deps.accounts, cloudSettings)], - ['cln_bulk_set_gblk', bulkSetGblkAction(deps.accounts, cloudSettings)], - ); - } - - return new Map(entries); +function cloudActionEntries(accounts: AccountStore, cloudSettings: CloudSettingsStore): Array<[string, CharActionHandler]> { + return [ + ['cln_get_meta_blk', getMetaBlkAction(accounts, cloudSettings)], + ['cln_get_general_blk', getGeneralBlkAction(accounts, cloudSettings)], + ['cln_set_general_blk', setGeneralBlkAction(accounts, cloudSettings)], + ['cln_bulk_set_gblk', bulkSetGblkAction(accounts, cloudSettings)], + ]; } diff --git a/packages/local-service/src/char/actions/clan-actions.ts b/packages/local-service/src/char/actions/clan-actions.ts index dde6a1f..defefa9 100644 --- a/packages/local-service/src/char/actions/clan-actions.ts +++ b/packages/local-service/src/char/actions/clan-actions.ts @@ -3,7 +3,7 @@ * membership requests. Officer moderation and squadron vehicle * research live in `clan-moderation-actions.ts` and `squadron-research-actions.ts`. */ -import { emptyBlock, findBlock, findParam, type BlkBlock } from '@wto/blk'; +import { emptyBlock, findBlock, type BlkBlock } from '@wto/blk'; import type { Account, AccountStore } from '../../accounts/account-store.ts'; import { toClanInfoBlk, @@ -19,7 +19,15 @@ import type { ResearchRules } from '../../research/research-rules.ts'; import type { RuleOutcome } from '../../research/rule-outcome.ts'; import type { CharActionContext, CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; -import { boolParam, intParam, stringParam } from './payload-params.ts'; +import { + boolParam, + headerOrPayloadBool, + headerOrPayloadId, + headerOrPayloadInt, + headerOrPayloadString, + intParam, + stringParam, +} from './payload-params.ts'; export function priceFromClanPayload(payload: BlkBlock): Price { return { @@ -31,41 +39,25 @@ export function priceFromClanPayload(payload: BlkBlock): Price { export function clanProfileRuleAction( profiles: PlayerProfiles, accounts: AccountStore, - clans: ClanStore, + _clans: ClanStore, run: (context: CharActionContext, profile: BlkBlock, account: Account) => RuleOutcome, ): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' }; const updated = profiles.updateWhen(account.userId, (saved) => { - clans.syncProfile(saved, account); outcome = run(context, saved, account); return outcome.ok; }); if (!updated) return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal }; - return { kind: 'data', blk: clientProfile(updated, account, clans) }; + return { kind: 'data', blk: clientProfile(updated, account) }; }); } -export function clanParamOrHeader(context: CharActionContext, name: string): string | undefined { - return (context.payload ? stringParam(context.payload, name) : undefined) ?? context.headerParam(name); -} - -export function clanStrOrIntId(context: CharActionContext, name: string): string | undefined { - if (context.payload) { - const param = findParam(context.payload, name)?.value; - if (param?.type === 'string' && param.value !== '') return param.value; - if (param?.type === 'int64') return param.value.toString(); - if (param?.type === 'int') return String(param.value); - } - const hdr = context.headerParam(name); - return hdr && hdr !== '' ? hdr : undefined; -} - export function clanGetAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const clanId = clanStrOrIntId(context, 'clanId') ?? clanStrOrIntId(context, '_id'); - const clanName = clanParamOrHeader(context, 'clanName'); - const clanTag = clanParamOrHeader(context, 'clanTag'); + const clanId = headerOrPayloadId(context, 'clanId') ?? headerOrPayloadId(context, '_id'); + const clanName = headerOrPayloadString(context, 'clanName'); + const clanTag = headerOrPayloadString(context, 'clanTag'); const clan = (!clanId && !clanName && !clanTag) ? clans.clanOfUser(account.userId)?.clan : clans.findClan({ clanId, clanName, clanTag }); @@ -76,15 +68,14 @@ export function clanGetAction(accounts: AccountStore, clans: ClanStore): CharAct export function clanGetLeaderboardAction(clans: ClanStore): CharActionHandler { return (context) => { - const payload = context.payload; const rows = clans.queryLeaderboard({ - start: (payload && intParam(payload, 'start')) ?? 0, - count: (payload && intParam(payload, 'count')) ?? 20, - sortField: (payload && stringParam(payload, 'sortField')) ?? 'dr_era5_hist', - clanId: payload ? stringParam(payload, 'clanId') : undefined, - filterOpen: payload ? stringParam(payload, 'filterOpen') === 'on' : false, - filterNotFull: payload ? stringParam(payload, 'filterNotFull') === 'on' : false, - filterAutoAccept: payload ? stringParam(payload, 'filterAutoAccept') === 'on' : false, + start: headerOrPayloadInt(context, 'start') ?? 0, + count: headerOrPayloadInt(context, 'count') ?? 20, + sortField: headerOrPayloadString(context, 'sortField') ?? 'dr_era5_hist', + clanId: headerOrPayloadId(context, 'clanId'), + filterOpen: headerOrPayloadBool(context, 'filterOpen') ?? false, + filterNotFull: headerOrPayloadBool(context, 'filterNotFull') ?? false, + filterAutoAccept: headerOrPayloadBool(context, 'filterAutoAccept') ?? false, }); return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos)) } }; }; @@ -92,16 +83,15 @@ export function clanGetLeaderboardAction(clans: ClanStore): CharActionHandler { export function clanFindByPrefixAction(clans: ClanStore): CharActionHandler { return (context) => { - const payload = context.payload; - const prefix = (payload && (stringParam(payload, 'namePrefix') ?? stringParam(payload, 'tagPrefix'))) ?? ''; + const prefix = headerOrPayloadString(context, 'namePrefix') ?? headerOrPayloadString(context, 'tagPrefix') ?? ''; const rows = clans.queryLeaderboard({ - start: (payload && intParam(payload, 'start')) ?? 0, - count: (payload && intParam(payload, 'count')) ?? 20, + start: headerOrPayloadInt(context, 'start') ?? 0, + count: headerOrPayloadInt(context, 'count') ?? 20, sortField: 'activity', prefix, - filterOpen: payload ? stringParam(payload, 'filterOpen') === 'on' : false, - filterNotFull: payload ? stringParam(payload, 'filterNotFull') === 'on' : false, - filterAutoAccept: payload ? stringParam(payload, 'filterAutoAccept') === 'on' : false, + filterOpen: headerOrPayloadBool(context, 'filterOpen') ?? false, + filterNotFull: headerOrPayloadBool(context, 'filterNotFull') ?? false, + filterAutoAccept: headerOrPayloadBool(context, 'filterAutoAccept') ?? false, }); return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos)) } }; }; @@ -123,12 +113,12 @@ export function clansListShortInfoAction(clans: ClanStore): CharActionHandler { export function clanGetLogAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const clanId = clanStrOrIntId(context, '_id') ?? clanStrOrIntId(context, 'clanId'); + const clanId = headerOrPayloadId(context, '_id') ?? headerOrPayloadId(context, 'clanId'); const clan = clanId && clanId !== '-1' ? clans.byId(clanId) : clans.clanOfUser(account.userId)?.clan; if (!clan) return { kind: 'data', blk: emptyBlock() }; - const count = (context.payload && intParam(context.payload, 'count')) ?? 20; - const events = context.payload ? stringParam(context.payload, 'events') : undefined; - const last = context.payload ? stringParam(context.payload, 'last') : undefined; + const count = headerOrPayloadInt(context, 'count') ?? 20; + const events = headerOrPayloadString(context, 'events'); + const last = headerOrPayloadString(context, 'last'); return { kind: 'data', blk: toClanLogBlk(clan, count, events, last) }; }); } @@ -137,8 +127,10 @@ export function clanCreateAction(profiles: PlayerProfiles, accounts: AccountStor return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { const payload = context.payload; const offered = payload && priceFromClanPayload(payload); - if (!payload || !offered) return { ok: false, refusal: 'BAD_PARAMS' }; - const rawType = stringParam(payload, 'type'); + const rawType = payload && stringParam(payload, 'type'); + if (!payload || !offered || (rawType !== 'normal' && rawType !== 'battalion')) { + return { ok: false, refusal: 'BAD_PARAMS' }; + } return clans.createClan(profile, account, rules.clanEconomy, { name: stringParam(payload, 'name') ?? '', tag: stringParam(payload, 'tag') ?? '', @@ -146,7 +138,7 @@ export function clanCreateAction(profiles: PlayerProfiles, accounts: AccountStor region: stringParam(payload, 'region') ?? '', desc: stringParam(payload, 'desc') ?? '', announcement: stringParam(payload, 'announcement') ?? '', - type: rawType === 'battalion' ? 'battalion' : 'normal', + type: rawType, offered, }); }); @@ -156,7 +148,7 @@ export function clanChangeInfoAction(profiles: PlayerProfiles, accounts: Account return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { const payload = context.payload; if (!payload) return { ok: false, refusal: 'BAD_PARAMS' }; - const clanId = clanStrOrIntId(context, '_id') ?? '-1'; + const clanId = headerOrPayloadId(context, '_id') ?? '-1'; const rawStatus = stringParam(payload, 'status'); return clans.editClanInfo(profile, account, rules.clanEconomy, clanId, { name: stringParam(payload, 'name'), @@ -174,7 +166,7 @@ export function clanUpgradeAction(profiles: PlayerProfiles, accounts: AccountSto return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { const payload = context.payload; if (!payload) return { ok: false, refusal: 'BAD_PARAMS' }; - const clanId = clanStrOrIntId(context, '_id') ?? '-1'; + const clanId = headerOrPayloadId(context, '_id') ?? '-1'; return clans.upgradeClanToNormal(profile, account, rules.clanEconomy, clanId, { tag: stringParam(payload, 'tag') ?? '', desc: stringParam(payload, 'desc') ?? '', @@ -185,7 +177,7 @@ export function clanUpgradeAction(profiles: PlayerProfiles, accounts: AccountSto export function clanMembersUpgradeAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, rules: ResearchRules): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { - const clanId = clanStrOrIntId(context, '_id') ?? '-1'; + const clanId = headerOrPayloadId(context, '_id') ?? '-1'; return clans.upgradeMembersLimit(profile, account, rules.clanEconomy, clanId); }); } @@ -193,7 +185,7 @@ export function clanMembersUpgradeAction(profiles: PlayerProfiles, accounts: Acc export function clanSetMembershipReqAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { const payload = context.payload; - const clanId = clanStrOrIntId(context, '_id') ?? '-1'; + const clanId = headerOrPayloadId(context, '_id') ?? '-1'; const reqBlk = payload && findBlock(payload, 'membership_req'); const autoaccept = (payload && boolParam(payload, 'autoaccept')) ?? false; if (!clans.setMembershipRequirements(clanId, account, reqBlk, autoaccept)) { @@ -205,11 +197,11 @@ export function clanSetMembershipReqAction(accounts: AccountStore, clans: ClanSt export function clanMembershipRequestAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { - const clanId = clanStrOrIntId(context, '_id') ?? clanStrOrIntId(context, 'requestedClanId'); - const clanName = clanParamOrHeader(context, 'name'); - const clanTag = clanParamOrHeader(context, 'tag'); - const cancel = (context.payload && boolParam(context.payload, 'cancelRequest')) ?? false; - const comment = clanParamOrHeader(context, 'comments'); + const clanId = headerOrPayloadId(context, '_id') ?? headerOrPayloadId(context, 'requestedClanId'); + const clanName = headerOrPayloadString(context, 'name'); + const clanTag = headerOrPayloadString(context, 'tag'); + const cancel = headerOrPayloadBool(context, 'cancelRequest') ?? false; + const comment = headerOrPayloadString(context, 'comments'); return clans.requestOrCancelMembership(profile, account, { clanId, clanName, clanTag, cancel, comment }); }); } @@ -221,12 +213,12 @@ export function clanLeaveAction(profiles: PlayerProfiles, accounts: AccountStore export function clanDisbandAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => - clans.disbandClan(profile, account, clanStrOrIntId(context, 'requestedClanId') ?? clanStrOrIntId(context, '_id'))); + clans.disbandClan(profile, account, headerOrPayloadId(context, 'requestedClanId') ?? headerOrPayloadId(context, '_id'))); } -export function clanSyncProfileAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler { +export function clanSyncProfileAction(profiles: PlayerProfiles, accounts: AccountStore, _clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const updated = profiles.update(account.userId, (saved) => clans.syncProfile(saved, account)); - return { kind: 'data', blk: clientProfile(updated, account, clans) }; + const updated = profiles.profileOf(account.userId); + return { kind: 'data', blk: clientProfile(updated, account) }; }); } diff --git a/packages/local-service/src/char/actions/clan-moderation-actions.ts b/packages/local-service/src/char/actions/clan-moderation-actions.ts index b59ef37..d6e52b6 100644 --- a/packages/local-service/src/char/actions/clan-moderation-actions.ts +++ b/packages/local-service/src/char/actions/clan-moderation-actions.ts @@ -1,15 +1,14 @@ /** * Char action handlers for squadron officer moderation, blacklist, and best-rewards metadata - * (`ano_clan_*`, `cln_set_clan_best_rewards`; implementation notes). + * (`ano_clan_*`, `cln_set_clan_best_rewards`; implementation notes; aces.exe 0x29d150, 0x29d540). */ import type { AccountStore } from '../../accounts/account-store.ts'; import type { ClanStore } from '../../clans/clan-store.ts'; -import type { ClanBestReward } from '../../clans/clan-types.ts'; +import { ClanRole, roleCodeFromString, type ClanBestReward } from '../../clans/clan-types.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; -import type { CharActionHandler } from '../char-action.ts'; +import type { CharActionContext, CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; -import { clanParamOrHeader, clanStrOrIntId } from './clan-actions.ts'; -import { intParam } from './payload-params.ts'; +import { headerOrPayloadId, headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts'; export function clanAcceptCandidateAction( profiles: PlayerProfiles, @@ -17,16 +16,14 @@ export function clanAcceptCandidateAction( clans: ClanStore, ): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const targetUid = clanStrOrIntId(context, 'userid') ?? ''; - const clanId = clanStrOrIntId(context, '_id'); - const role = (context.payload && intParam(context.payload, 'role')) ?? 3; + const targetUid = headerOrPayloadId(context, 'userid') ?? ''; + const clanId = headerOrPayloadId(context, '_id'); + const role = parseRoleParam(context) ?? ClanRole.REGULAR; const targetAccount = accounts.byUserId(targetUid); if (!targetUid || !clans.acceptCandidate(account, clanId, targetUid, targetAccount?.nick ?? `Pilot_${targetUid}`, role)) { return { kind: 'error', code: 'NOT_AVAILABLE' }; } - if (targetAccount) { - profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); - } + if (targetAccount) profiles.profileOf(targetAccount.userId); return { kind: 'done' }; }); } @@ -37,16 +34,14 @@ export function clanRejectCandidateAction( clans: ClanStore, ): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const targetUid = clanStrOrIntId(context, 'userid') ?? ''; - const clanId = clanStrOrIntId(context, '_id'); - const comments = clanParamOrHeader(context, 'comments') ?? ''; + const targetUid = headerOrPayloadId(context, 'userid') ?? ''; + const clanId = headerOrPayloadId(context, '_id'); + const comments = headerOrPayloadString(context, 'comments') ?? ''; if (!targetUid || !clans.rejectCandidate(account, clanId, targetUid, comments)) { return { kind: 'error', code: 'NOT_AVAILABLE' }; } const targetAccount = accounts.byUserId(targetUid); - if (targetAccount) { - profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); - } + if (targetAccount) profiles.profileOf(targetAccount.userId); return { kind: 'done' }; }); } @@ -57,15 +52,13 @@ export function clanDismissMemberAction( clans: ClanStore, ): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const targetUid = clanStrOrIntId(context, 'userid') ?? ''; - const comments = clanParamOrHeader(context, 'comments') ?? ''; + const targetUid = headerOrPayloadId(context, 'userid') ?? ''; + const comments = headerOrPayloadString(context, 'comments') ?? ''; if (!targetUid || !clans.dismissMember(account, targetUid, comments)) { return { kind: 'error', code: 'NOT_AVAILABLE' }; } const targetAccount = accounts.byUserId(targetUid); - if (targetAccount) { - profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); - } + if (targetAccount) profiles.profileOf(targetAccount.userId); return { kind: 'done' }; }); } @@ -76,25 +69,26 @@ export function clanChangeMemberRoleAction( clans: ClanStore, ): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const targetUid = clanStrOrIntId(context, 'userid') ?? ''; - const newRole = (context.payload && intParam(context.payload, 'role')) ?? 0; - if (!targetUid || !newRole || !clans.changeMemberRole(account, targetUid, newRole)) { + const targetUid = headerOrPayloadId(context, 'userid') ?? ''; + const newRole = parseRoleParam(context); + if (!targetUid || newRole === undefined || !clans.changeMemberRole(account, targetUid, newRole)) { return { kind: 'error', code: 'NOT_AVAILABLE' }; } const targetAccount = accounts.byUserId(targetUid); - if (targetAccount) { - profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); - } + if (targetAccount) profiles.profileOf(targetAccount.userId); return { kind: 'done' }; }); } export function clanEditBlacklistAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const targetUid = clanStrOrIntId(context, 'userid') ?? ''; - const clanId = clanStrOrIntId(context, '_id'); - const mode = clanParamOrHeader(context, 'mode') ?? 'addToBlackList'; - const comments = clanParamOrHeader(context, 'comments') ?? ''; + const targetUid = headerOrPayloadId(context, 'userid') ?? ''; + const clanId = headerOrPayloadId(context, '_id'); + const mode = headerOrPayloadString(context, 'mode'); + if (mode !== 'addToBlackList' && mode !== 'delFromBlackList') { + return { kind: 'error', code: 'BAD_PARAMS' }; + } + const comments = headerOrPayloadString(context, 'comments') ?? ''; const targetNick = accounts.byUserId(targetUid)?.nick ?? ''; if (!targetUid || !clans.editBlacklist(account, clanId, targetUid, targetNick, mode === 'addToBlackList', comments)) { return { kind: 'error', code: 'NOT_AVAILABLE' }; @@ -118,3 +112,14 @@ export function setClanBestRewardsAction(accounts: AccountStore, clans: ClanStor return { kind: 'done' }; }); } + +/** + * Native `0x29d150` and `0x29d540` write `role:i=` into the request DataBlock; also + * accept role name strings in case a script caller passes `"REGULAR"` / `"OFFICER"` in headers. + */ +function parseRoleParam(context: CharActionContext): number | undefined { + const intRole = headerOrPayloadInt(context, 'role'); + if (intRole !== undefined && intRole >= 1 && intRole <= 6) return intRole; + const strRole = headerOrPayloadString(context, 'role'); + return strRole ? roleCodeFromString(strRole) : undefined; +} diff --git a/packages/local-service/src/char/actions/cloud-settings-actions.ts b/packages/local-service/src/char/actions/cloud-settings-actions.ts index d3c9381..9fe22a2 100644 --- a/packages/local-service/src/char/actions/cloud-settings-actions.ts +++ b/packages/local-service/src/char/actions/cloud-settings-actions.ts @@ -3,19 +3,20 @@ * aces.exe 2.61.0.37: `cln_get_meta_blk` 0x4662b3f, `cln_get_general_blk` 0x46677df, * `cln_set_general_blk` 0x4666c51, `cln_bulk_set_gblk` 0x4663cfd). */ +import { emptyBlock } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; +import { isSupportedGeneralBlkType, type CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts'; +import type { CharActionHandler } from '../char-action.ts'; import { buildContainerBlk, computeContentHash, + isPbbdStream, normalizeContainerBlk, parsePbbdBulkUploads, unpackCloudBlk, -} from '../../cloud-settings/cloud-settings-codec.ts'; -import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts'; -import { emptyBlock } from '@wto/blk'; -import type { CharActionHandler } from '../char-action.ts'; +} from '../pbbd-stream.ts'; import { withAccount } from './account-context.ts'; -import { intParam, stringParam } from './payload-params.ts'; +import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts'; /** `cln_get_meta_blk`: returns schema, compression negotiation, and saved block versions/hashes. */ export function getMetaBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler { @@ -25,12 +26,11 @@ export function getMetaBlkAction(accounts: AccountStore, cloudSettings: CloudSet })); } -/** `cln_get_general_blk`: returns `ContainerBlk` (`version:i`, `content { ... }`) for `blkType`. */ +/** `cln_get_general_blk`: returns `ContainerBlk` (`version:i`, `content { ... }`) for a valid `blkType`. */ export function getGeneralBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const payload = context.payload; - const blkType = context.headerParam('blkType') ?? (payload ? stringParam(payload, 'blkType') : undefined); - if (!blkType) return { kind: 'error', code: 'BAD_PARAM' }; + const blkType = headerOrPayloadString(context, 'blkType'); + if (!blkType || !isSupportedGeneralBlkType(blkType)) return { kind: 'error', code: 'BAD_PARAM' }; const stored = cloudSettings.loadContainer(account.userId, blkType) ?? buildContainerBlk(1, emptyBlock('content')); return { kind: 'data', blk: stored }; }); @@ -39,25 +39,17 @@ export function getGeneralBlkAction(accounts: AccountStore, cloudSettings: Cloud /** `cln_set_general_blk`: stores a single `ContainerBlk` uploaded by the client and answers `!OK`. */ export function setGeneralBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const payload = context.payload; - const blkType = context.headerParam('type') - ?? context.headerParam('blkType') - ?? (payload ? stringParam(payload, 'type') : undefined) - ?? (payload ? stringParam(payload, 'blkType') : undefined); - if (!blkType) return { kind: 'error', code: 'BAD_PARAM' }; + const blkType = headerOrPayloadString(context, 'type') ?? headerOrPayloadString(context, 'blkType'); + if (!blkType || !isSupportedGeneralBlkType(blkType)) return { kind: 'error', code: 'BAD_PARAM' }; - const headerVersion = parsePositiveInt(context.headerParam('version')) - ?? (payload ? intParam(payload, 'version') : undefined) - ?? 1; - const compr = context.headerParam('compr'); + const rawVer = headerOrPayloadInt(context, 'version'); + const headerVersion = rawVer !== undefined && rawVer > 0 ? rawVer : 1; const rawBody = context.rawBody ?? new Uint8Array(0); - const decoded = unpackCloudBlk(rawBody, compr) ?? payload; + const decoded = unpackCloudBlk(rawBody, context.headerParam('compr')) ?? context.payload; if (!decoded) return { kind: 'error', code: 'BAD_PARAM' }; const normalized = normalizeContainerBlk(decoded, headerVersion); - const contentHash = context.headerParam('contentHash') - ?? (payload ? stringParam(payload, 'contentHash') : undefined) - ?? computeContentHash(normalized.content); + const contentHash = headerOrPayloadString(context, 'contentHash') ?? computeContentHash(normalized.content); const ok = cloudSettings.saveUpload(account.userId, { blkType, @@ -73,18 +65,9 @@ export function setGeneralBlkAction(accounts: AccountStore, cloudSettings: Cloud export function bulkSetGblkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { const rawBody = context.rawBody ?? new Uint8Array(0); - if (rawBody.byteLength > 0) { - const uploads = parsePbbdBulkUploads(rawBody); - if (uploads.length > 0) { - cloudSettings.saveBulkUploads(account.userId, uploads); - } - } + if (rawBody.byteLength === 0 || !isPbbdStream(rawBody)) return { kind: 'error', code: 'BAD_PARAM' }; + const uploads = parsePbbdBulkUploads(rawBody); + if (uploads.length > 0) cloudSettings.saveBulkUploads(account.userId, uploads); return { kind: 'done' }; }); } - -function parsePositiveInt(raw: string | undefined): number | undefined { - if (!raw || !/^\d+$/.test(raw.trim())) return undefined; - const parsed = Number.parseInt(raw.trim(), 10); - return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined; -} diff --git a/packages/local-service/src/char/actions/inventory-actions.ts b/packages/local-service/src/char/actions/inventory-actions.ts index 6ec3fdb..1517e13 100644 --- a/packages/local-service/src/char/actions/inventory-actions.ts +++ b/packages/local-service/src/char/actions/inventory-actions.ts @@ -14,10 +14,11 @@ import { consumeInventoryCoupon, exchangeInventoryItems, multiConsumeInventoryItems, - parseExchangeItemsRequest, purchaseExternalInventoryItem, recycleClassicItems, + type ExchangeItemDelta, } from '../../inventory/inventory-rules.ts'; +import { deltaToInventoryJson, parseExchangeItemsRequest } from '../../inventory/inventory-wire.ts'; import { buyTrophy } from '../../inventory/trophy-catalogue.ts'; import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; @@ -128,12 +129,11 @@ export function inventoryExchangeAction( const parsed = parseExchangeItemsRequest(context.rawText); if (!parsed) return { kind: 'error', code: 'BAD_JSON' }; - let delta: unknown[] | undefined; + let delta: ExchangeItemDelta[] | undefined; let errorCode = 'EXCHANGE_FAILED'; profiles.updateWhen(account.userId, (saved) => { const res = exchangeInventoryItems( saved, - account.userId, rules.inventory, parsed.outputItemDefId, parsed.quantity, @@ -147,7 +147,7 @@ export function inventoryExchangeAction( return true; }); if (!delta) return { kind: 'error', code: errorCode }; - return { kind: 'json', data: { response: { item_json: delta } } }; + return { kind: 'json', data: { response: { item_json: deltaToInventoryJson(delta, account.userId) } } }; }); } diff --git a/packages/local-service/src/char/actions/online-init-actions.ts b/packages/local-service/src/char/actions/online-init-actions.ts index 379f796..0e52a85 100644 --- a/packages/local-service/src/char/actions/online-init-actions.ts +++ b/packages/local-service/src/char/actions/online-init-actions.ts @@ -4,7 +4,6 @@ */ import { emptyBlock, setParam } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; -import type { ClanStore } from '../../clans/clan-store.ts'; import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts'; import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; @@ -40,19 +39,19 @@ export function initialMeta(accounts?: AccountStore, cloudSettings?: CloudSettin * performAction (0x295ef0) reads it into the client's profile with the profile serializer * (0x917740) when it is not empty. */ -export function entitlementsFull(profiles: PlayerProfiles, accounts: AccountStore, clans?: ClanStore): CharActionHandler { - return profileAnswer(profiles, accounts, clans); +export function entitlementsFull(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return profileAnswer(profiles, accounts); } /** cln_legacy_get_userdata: the whole profile (ClientEconomicState::loadOnline, aces.exe 0x2a23b0). */ -export function legacyUserData(profiles: PlayerProfiles, accounts: AccountStore, clans?: ClanStore): CharActionHandler { - return profileAnswer(profiles, accounts, clans); +export function legacyUserData(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return profileAnswer(profiles, accounts); } -function profileAnswer(profiles: PlayerProfiles, accounts: AccountStore, clans?: ClanStore): CharActionHandler { +function profileAnswer(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => ({ kind: 'data', - blk: clientProfile(profiles.profileOf(account.userId), account, clans), + blk: clientProfile(profiles.profileOf(account.userId), account), })); } diff --git a/packages/local-service/src/char/actions/payload-params.ts b/packages/local-service/src/char/actions/payload-params.ts index 24b7f6a..631c382 100644 --- a/packages/local-service/src/char/actions/payload-params.ts +++ b/packages/local-service/src/char/actions/payload-params.ts @@ -1,17 +1,63 @@ -/** Typed reads of a char request's BLK parameters; a missing or differently typed parameter reads as undefined. */ +/** Read typed parameters from a char action's BLK payload or HTTP request headers. */ import { findParam, type BlkBlock } from '@wto/blk'; +import type { CharActionContext } from '../char-action.ts'; export function stringParam(payload: BlkBlock, name: string): string | undefined { - const value = findParam(payload, name)?.value; - return value?.type === 'string' ? value.value : undefined; + const param = findParam(payload, name)?.value; + return param?.type === 'string' ? param.value : undefined; } export function intParam(payload: BlkBlock, name: string): number | undefined { - const value = findParam(payload, name)?.value; - return value?.type === 'int' ? value.value : undefined; + const param = findParam(payload, name)?.value; + return param?.type === 'int' ? param.value : undefined; } export function boolParam(payload: BlkBlock, name: string): boolean | undefined { - const value = findParam(payload, name)?.value; - return value?.type === 'bool' ? value.value : undefined; + const param = findParam(payload, name)?.value; + return param?.type === 'bool' ? param.value : undefined; +} + +export function headerOrPayloadString(context: CharActionContext, name: string): string | undefined { + const fromPayload = context.payload ? stringParam(context.payload, name) : undefined; + return fromPayload ?? context.headerParam(name); +} + +export function headerOrPayloadInt(context: CharActionContext, name: string): number | undefined { + if (context.payload) { + const fromPayload = intParam(context.payload, name); + if (fromPayload !== undefined) return fromPayload; + } + const hdr = context.headerParam(name)?.trim(); + if (hdr !== undefined && /^-?\d+$/.test(hdr)) { + const parsed = Number(hdr); + if (Number.isSafeInteger(parsed)) return parsed; + } + return undefined; +} + +export function headerOrPayloadBool(context: CharActionContext, name: string): boolean | undefined { + if (context.payload) { + const fromBool = boolParam(context.payload, name); + if (fromBool !== undefined) return fromBool; + const fromStr = stringParam(context.payload, name); + if (fromStr !== undefined) return parseTruthyFlag(fromStr); + } + const hdr = context.headerParam(name); + return hdr !== undefined ? parseTruthyFlag(hdr) : undefined; +} + +export function headerOrPayloadId(context: CharActionContext, name: string): string | undefined { + if (context.payload) { + const param = findParam(context.payload, name)?.value; + if (param?.type === 'string' && param.value !== '') return param.value; + if (param?.type === 'int64') return param.value.toString(); + if (param?.type === 'int') return String(param.value); + } + const hdr = context.headerParam(name); + return hdr && hdr !== '' ? hdr : undefined; +} + +function parseTruthyFlag(raw: string): boolean { + const lower = raw.trim().toLowerCase(); + return lower === 'yes' || lower === 'true' || lower === 'on' || lower === '1'; } diff --git a/packages/local-service/src/char/actions/store-actions.ts b/packages/local-service/src/char/actions/store-actions.ts index 33089e6..f58da8f 100644 --- a/packages/local-service/src/char/actions/store-actions.ts +++ b/packages/local-service/src/char/actions/store-actions.ts @@ -17,7 +17,7 @@ import type { StoreProduct } from '../../store/store-catalogue.ts'; import { buyGoldEntitlement } from '../../store/store-purchase.ts'; import type { CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; -import { intParam, stringParam } from './payload-params.ts'; +import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts'; export function entitlementsPriceEx(rules: ResearchRules): CharActionHandler { const table = buildEntitlementsPriceBlk(rules.store.allProducts()); @@ -26,12 +26,11 @@ export function entitlementsPriceEx(rules: ResearchRules): CharActionHandler { export function buyEntitlementAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const entitlement = context.headerParam('entitlement') ?? (context.payload ? stringParam(context.payload, 'entitlement') : undefined); - const headerGold = context.headerParam('costGold'); - const offeredGold = headerGold !== undefined && /^\d+$/.test(headerGold) - ? Number(headerGold) - : (context.payload ? intParam(context.payload, 'costGold') : undefined); - if (!entitlement) return { kind: 'error', code: 'BAD_PARAMS' }; + const entitlement = headerOrPayloadString(context, 'entitlement'); + const offeredGold = headerOrPayloadInt(context, 'costGold'); + if (!entitlement || offeredGold === undefined || offeredGold < 0) { + return { kind: 'error', code: 'BAD_PARAMS' }; + } let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' }; const now = serverTimeNow(); diff --git a/packages/local-service/src/char/char-payload.ts b/packages/local-service/src/char/char-payload.ts index 2984e17..fbd2d46 100644 --- a/packages/local-service/src/char/char-payload.ts +++ b/packages/local-service/src/char/char-payload.ts @@ -9,8 +9,8 @@ * text) and the traffic log records which form it was. */ import { decodeBlk, encodeBlk, formatBlkText, type BlkBlock } from '@wto/blk'; -import { describePbbdForLog, isPbbdStream } from '../cloud-settings/cloud-settings-codec.ts'; import { markUncompressed, unpackMarked } from './compression-marker.ts'; +import { describePbbdForLog, isPbbdStream } from './pbbd-stream.ts'; export function encodeDataAnswer(blk: BlkBlock): Uint8Array { return markUncompressed(encodeBlk(blk)); diff --git a/packages/local-service/src/char/pbbd-stream.ts b/packages/local-service/src/char/pbbd-stream.ts new file mode 100644 index 0000000..677db11 --- /dev/null +++ b/packages/local-service/src/char/pbbd-stream.ts @@ -0,0 +1,136 @@ +/** + * Protocol-layer wire codecs for `online_storage` (`cln_set_general_blk` and `PBBD` batch + * streams on `cln_bulk_set_gblk`; implementation notes; aces.exe 0x4662a70..0x466b2ec, + * 0x41537d0..0x4154020). + */ +import { createHash } from 'node:crypto'; +import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib'; +import { decodeBlk, emptyBlock, encodeBlk, findBlock, setParam, type BlkBlock } from '@wto/blk'; +import type { ParsedGblkUpload } from '../cloud-settings/cloud-settings-store.ts'; +import { intField, stringField } from '../profile/blk-fields.ts'; +import { unpackMarked } from './compression-marker.ts'; + +export const PBBD_MAGIC = 0x44424250; // "PBBD" little-endian (0x4663427: 0x144424250) + +export function isPbbdStream(bytes: Uint8Array): boolean { + if (bytes.byteLength < 8) return false; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + return view.getUint32(0, true) === PBBD_MAGIC && view.getUint16(4, true) === 1; +} + +export function unpackCloudBlk(bytes: Uint8Array, comprHeader: string | undefined): BlkBlock | undefined { + if (bytes.byteLength === 0) return undefined; + const raw = decompressCloudBytes(bytes, comprHeader); + if (!raw || raw.byteLength === 0) return undefined; + try { + return decodeBlk(raw); + } catch { + return undefined; + } +} + +export function parsePbbdBulkUploads(bytes: Uint8Array): ReadonlyArray { + if (!isPbbdStream(bytes)) return []; + const chunks = readPbbdChunks(bytes); + const uploads: ParsedGblkUpload[] = []; + + for (let i = 0; i < chunks.length; i++) { + const meta = chunks[i]; + if (!meta) continue; + const desc = stringField(meta, 'desc'); + if (desc === 'store_gblk') { + const containerCandidate = chunks[i + 1]; + i += 1; + const blkType = stringField(meta, 'blkType'); + if (!blkType || !containerCandidate) continue; + const fallbackVersion = intField(meta, 'version', 1) || 1; + const extracted = normalizeContainerBlk(containerCandidate, fallbackVersion); + const contentHash = stringField(meta, 'contentHash') || computeContentHash(extracted.content); + uploads.push({ blkType, version: extracted.version, contentHash, container: extracted.container }); + } else if (desc === 'bigquery' || desc === 'logout') { + i += 1; + } + } + return uploads; +} + +export function normalizeContainerBlk( + incoming: BlkBlock, + fallbackVersion: number, +): { readonly version: number; readonly content: BlkBlock; readonly container: BlkBlock } { + const existingContent = findBlock(incoming, 'content'); + const rawVersion = intField(incoming, 'version', fallbackVersion); + const version = rawVersion > 0 ? rawVersion : Math.max(1, fallbackVersion); + const content = cloneAsContent(existingContent ?? incoming); + return { version, content, container: buildContainerBlk(version, content) }; +} + +export function buildContainerBlk(version: number, content: BlkBlock): BlkBlock { + const container = emptyBlock(); + setParam(container, 'version', { type: 'int', value: Math.max(1, Math.trunc(version)) }); + container.blocks.push(cloneAsContent(content)); + return container; +} + +export function computeContentHash(content: BlkBlock): string { + const rootCopy = emptyBlock(); + rootCopy.params.push(...content.params); + rootCopy.blocks.push(...content.blocks); + return createHash('md5').update(encodeBlk(rootCopy)).digest('hex'); +} + +export function describePbbdForLog(bytes: Uint8Array): string { + const uploads = parsePbbdBulkUploads(bytes); + if (uploads.length === 0) return 'PBBD stream (0 store_gblk items)'; + return uploads.map((u) => `${u.blkType} v${u.version} (${u.contentHash})`).join(', '); +} + +function readPbbdChunks(bytes: Uint8Array): Array { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const chunkCount = view.getUint16(6, true); + const chunks: Array = []; + let offset = 8; + + for (let i = 0; i < chunkCount; i++) { + if (offset + 5 > bytes.byteLength) break; + const payloadLen = view.getUint32(offset, true); + const marker = bytes[offset + 4]!; + offset += 5; + if (offset + payloadLen > bytes.byteLength) break; + const slice = bytes.subarray(offset, offset + payloadLen); + offset += payloadLen; + chunks.push(decodeMarkedChunk(marker, slice)); + } + return chunks; +} + +function cloneAsContent(source: BlkBlock): BlkBlock { + return { name: 'content', params: [...source.params], blocks: [...source.blocks] }; +} + +function decompressCloudBytes(bytes: Uint8Array, comprHeader: string | undefined): Uint8Array | undefined { + const method = comprHeader?.trim().toLowerCase(); + try { + if (method === 'zstd') return zstdDecompressSync(bytes); + if (method === 'zlib') return bytes.byteLength > 4 ? inflateSync(bytes.subarray(4)) : undefined; + if (method === 'gzip') return gunzipSync(bytes); + if (!method || method === 'none') return unpackMarked(bytes)?.data ?? bytes; + return unpackMarked(bytes)?.data; + } catch { + return unpackMarked(bytes)?.data; + } +} + +function decodeMarkedChunk(marker: number, payload: Uint8Array): BlkBlock | undefined { + if (payload.byteLength === 0) return emptyBlock(); + try { + let raw: Uint8Array | undefined; + if (marker === 0x69) raw = payload; + else if (marker === 0x5a) raw = zstdDecompressSync(payload); + else if (marker === 0x7a) raw = payload.byteLength > 4 ? inflateSync(payload.subarray(4)) : undefined; + else if (marker === 0x1f) raw = gunzipSync(payload); + return raw ? decodeBlk(raw) : undefined; + } catch { + return undefined; + } +} diff --git a/packages/local-service/src/clans/clan-blk.ts b/packages/local-service/src/clans/clan-blk.ts index 3130d8f..4bc6102 100644 --- a/packages/local-service/src/clans/clan-blk.ts +++ b/packages/local-service/src/clans/clan-blk.ts @@ -7,12 +7,17 @@ * - `cln_clan_get_log` paginated clan event log (`clanRequests.nut`) */ import type { BlkBlock, BlkParam } from '@wto/blk'; -import type { ClanLogEntry, ClanMemberRecord, ClanRecord, ClanStats } from './clan-types.ts'; - -export const MAX_ACTIVITY_PER_PERIOD = 360; -export const MAX_CLAN_ACTIVITY = 20000; -export const REWARD_PERIOD_DAYS = 3; -export const HISTORY_DEPTH_DAYS = 14; +import { + HISTORY_DEPTH_DAYS, + MAX_ACTIVITY_PER_PERIOD, + MAX_CLAN_ACTIVITY, + REWARD_PERIOD_DAYS, + totalPeriodActivityOf, + type ClanLogEntry, + type ClanMemberRecord, + type ClanRecord, + type ClanStats, +} from './clan-types.ts'; const CLAN_STAT_KEYS: ReadonlyArray = [ 'dr_era5_arc', 'dr_era5_hist', 'dr_era5_sim', @@ -26,11 +31,6 @@ const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray acc + m.curActivity, 0); - return Math.min(MAX_CLAN_ACTIVITY * 5, sum * 10); -} - export function toClanInfoBlk(clan: ClanRecord, nowSec = Math.floor(Date.now() / 1000)): BlkBlock { const todayDay = Math.floor(nowSec / 86400); return { diff --git a/packages/local-service/src/clans/clan-lifecycle.ts b/packages/local-service/src/clans/clan-lifecycle.ts index 3110b1c..fb6e987 100644 --- a/packages/local-service/src/clans/clan-lifecycle.ts +++ b/packages/local-service/src/clans/clan-lifecycle.ts @@ -1,6 +1,6 @@ /** * Squadron lifecycle rules: creation, info editing, upgrading from training battalion to - * full squadron, member-limit expansion, and disbanding. + * full squadron, member-limit expansion, requirements, and disbanding. */ import type { BlkBlock } from '@wto/blk'; import type { Account } from '../accounts/account-store.ts'; @@ -10,7 +10,14 @@ import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import { appendClanLog, clearCandidateEverywhere, hasClanManageRight } from './clan-membership.ts'; import { buildDefaultPeriods } from './clan-seeds.ts'; -import { ClanRole, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; +import { + BATTALION_INITIAL_MEMBER_LIMIT, + ClanRole, + MAX_ACTIVITY_PER_PERIOD, + NORMAL_CLAN_MEMBER_LIMIT, + type ClanMemberRecord, + type ClanRecord, +} from './clan-types.ts'; export interface StoredClansState { nextClanId: number; @@ -39,7 +46,7 @@ export interface ClanInfoChanges { } export function stripClanDecorators(tag: string): string { - return tag.replace(/^[\[\-\.\=\^\*]+|[\]\-\.\=\^\*]+$/g, ''); + return tag.replace(/^[^\p{L}\p{N}_]+|[^\p{L}\p{N}_]+$/gu, ''); } export function createClanInState( @@ -53,12 +60,8 @@ export function createClanInState( if (state.clans.some((c) => c.members.some((m) => m.uid === account.userId))) return refused('NOT_AVAILABLE'); const name = input.name.trim(); const tag = input.tag.trim(); - if (!name || !tag) return refused('BAD_PARAMS'); - - const coreTag = stripClanDecorators(tag).toLowerCase(); - if (state.clans.some((c) => c.name.toLowerCase() === name.toLowerCase() || stripClanDecorators(c.tag).toLowerCase() === coreTag)) { - return refused('NOT_AVAILABLE'); - } + if (!name || !tag || !stripClanDecorators(tag)) return refused('BAD_PARAMS'); + if (hasConflictingClan(state.clans, undefined, name, tag)) return refused('NOT_AVAILABLE'); const expectedPrice: Price = input.type === 'battalion' ? { silverLions: economy.battalionCreateSilver, goldenEagles: economy.battalionCreateGold } @@ -71,14 +74,12 @@ export function createClanInState( clearCandidateEverywhere(state.clans, account.userId); pay(profile, expectedPrice); - - const id = String(state.nextClanId++); - const created = buildCreatedClanRecord(id, account, name, tag, input, nowSec); - state.clans.unshift(created); + state.clans.unshift(buildCreatedClanRecord(String(state.nextClanId++), account, name, tag, input, nowSec)); return ACCEPTED; } export function editClanInfoInState( + clans: readonly ClanRecord[], clan: ClanRecord | undefined, profile: BlkBlock, account: Account, @@ -88,50 +89,21 @@ export function editClanInfoInState( ): RuleOutcome { if (!clan || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE'); - if (clan.type === 'battalion') { - const isNameChanged = changes.name !== undefined && changes.name !== clan.name; - const isCoreTagChanged = changes.tag !== undefined && stripClanDecorators(changes.tag) !== stripClanDecorators(clan.tag); - if (isNameChanged || isCoreTagChanged) { - const editCost: Price = { silverLions: economy.battalionPrimaryEditSilver, goldenEagles: economy.battalionPrimaryEditGold }; - if (!canAfford(profile, editCost)) return refused('NOT_ENOUGH_MONEY'); - pay(profile, editCost); - } - } + const nextName = changes.name !== undefined && changes.name.trim() ? changes.name.trim() : clan.name; + const nextTag = changes.tag !== undefined && changes.tag.trim() ? changes.tag.trim() : clan.tag; + if (!stripClanDecorators(nextTag)) return refused('BAD_PARAMS'); + if (hasConflictingClan(clans, clan.id, nextName, nextTag)) return refused('NOT_AVAILABLE'); - if (changes.name !== undefined && changes.name.trim()) clan.name = changes.name.trim(); - if (changes.tag !== undefined && changes.tag.trim()) { - clan.tag = changes.tag.trim(); - clan.lastPaidTag = clan.tag; - } - if (changes.desc !== undefined) clan.desc = changes.desc; - if (changes.slogan !== undefined) clan.slogan = changes.slogan; - if (changes.announcement !== undefined) clan.announcement = changes.announcement; - if (changes.region !== undefined && changes.region !== clan.region) { - clan.region = changes.region; - clan.regionLastUpdatedSec = nowSec; - } - if (changes.status !== undefined) clan.status = changes.status; + const editPrice = computeInfoEditPrice(clan, economy, nextName, nextTag, changes); + if (!canAfford(profile, editPrice)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, editPrice); - clan.changedByUid = account.userId; - clan.changedByNick = account.nick; - clan.changedTimeSec = nowSec; - appendClanLog(clan, { - ev: 'info', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - name: clan.name, - tag: clan.tag, - desc: clan.desc, - slogan: clan.slogan, - region: clan.region, - announcement: clan.announcement, - status: clan.status, - }); + applyInfoFieldUpdates(clan, account, nextName, nextTag, changes, nowSec); return ACCEPTED; } export function upgradeClanToNormalInState( + clans: readonly ClanRecord[], clan: ClanRecord | undefined, profile: BlkBlock, account: Account, @@ -140,6 +112,10 @@ export function upgradeClanToNormalInState( nowSec: number, ): RuleOutcome { if (!clan || clan.type !== 'battalion' || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE'); + const nextTag = input.tag.trim() || clan.tag; + if (!stripClanDecorators(nextTag) || hasConflictingClan(clans, clan.id, clan.name, nextTag)) { + return refused('NOT_AVAILABLE'); + } const goldCost = Math.max(0, economy.upgradeBattalionToNormalGold - clan.mspent); const price: Price = { silverLions: economy.upgradeBattalionToNormalSilver, goldenEagles: goldCost }; @@ -147,11 +123,9 @@ export function upgradeClanToNormalInState( pay(profile, price); clan.type = 'normal'; - clan.mlimit = 128; - if (input.tag.trim()) { - clan.tag = input.tag.trim(); - clan.lastPaidTag = clan.tag; - } + clan.mlimit = NORMAL_CLAN_MEMBER_LIMIT; + clan.tag = nextTag; + clan.lastPaidTag = nextTag; clan.desc = input.desc; clan.announcement = input.announcement; clan.changedByUid = account.userId; @@ -159,13 +133,8 @@ export function upgradeClanToNormalInState( clan.changedTimeSec = nowSec; appendClanLog(clan, { - ev: 'upgrade', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - type: 'normal', - tag: clan.tag, - desc: clan.desc, + ev: 'upgrade', timeSec: nowSec, uId: account.userId, uN: account.nick, + type: 'normal', tag: clan.tag, desc: clan.desc, }); return ACCEPTED; } @@ -189,16 +158,93 @@ export function upgradeMembersLimitInState( clan.mspent += economy.battalionMembersUpgradeGold; appendClanLog(clan, { - ev: 'upgrade_members', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - old: String(oldLimit), - new: String(clan.mlimit), + ev: 'upgrade_members', timeSec: nowSec, uId: account.userId, uN: account.nick, + old: String(oldLimit), new: String(clan.mlimit), }); return ACCEPTED; } +export function disbandClanInState(state: StoredClansState, clan: ClanRecord | undefined, account: Account): RuleOutcome { + const role = clan?.members.find((m) => m.uid === account.userId)?.role; + if (!clan || (role !== ClanRole.LEADER && role !== ClanRole.CLANADMIN)) return refused('NOT_AVAILABLE'); + state.clans = state.clans.filter((c) => c.id !== clan.id); + return ACCEPTED; +} + +function hasConflictingClan(clans: readonly ClanRecord[], excludeId: string | undefined, name: string, tag: string): boolean { + const lowerName = name.toLowerCase(); + const coreTag = stripClanDecorators(tag).toLowerCase(); + return clans.some((c) => c.id !== excludeId && (c.name.toLowerCase() === lowerName || stripClanDecorators(c.tag).toLowerCase() === coreTag)); +} + +function computeInfoEditPrice( + clan: ClanRecord, + economy: ClanEconomy, + nextName: string, + nextTag: string, + changes: ClanInfoChanges, +): Price { + const nameChanged = nextName !== clan.name; + const coreTagChanged = stripClanDecorators(nextTag) !== stripClanDecorators(clan.tag); + const paidDecorChanged = nextTag !== clan.tag && nextTag !== clan.lastPaidTag && !isFreeDecorator(clan.type, nextTag, economy); + const primaryChanged = nameChanged || coreTagChanged || paidDecorChanged; + const secondaryChanged = (changes.desc !== undefined && changes.desc !== clan.desc) + || (changes.slogan !== undefined && changes.slogan !== clan.slogan) + || (changes.announcement !== undefined && changes.announcement !== clan.announcement) + || (changes.region !== undefined && changes.region !== clan.region); + + const primaryGold = clan.type === 'battalion' ? economy.battalionPrimaryEditGold : economy.normalPrimaryEditGold; + const primarySilver = clan.type === 'battalion' ? economy.battalionPrimaryEditSilver : economy.normalPrimaryEditSilver; + const secondaryGold = clan.type === 'battalion' ? economy.battalionSecondaryEditGold : economy.normalSecondaryEditGold; + const secondarySilver = clan.type === 'battalion' ? economy.battalionSecondaryEditSilver : economy.normalSecondaryEditSilver; + + return { + silverLions: (primaryChanged ? primarySilver : 0) + (!primaryChanged && secondaryChanged ? secondarySilver : 0), + goldenEagles: (primaryChanged ? primaryGold : 0) + (!primaryChanged && secondaryChanged ? secondaryGold : 0), + }; +} + +function isFreeDecorator(clanType: ClanKind, tag: string, economy: ClanEconomy): boolean { + const freeList = clanType === 'battalion' ? economy.battalionFreeDecorators : economy.normalFreeDecorators; + return freeList.some((decor) => { + const half = Math.floor(decor.length / 2); + const start = decor.slice(0, half); + const end = decor.slice(half); + return tag.startsWith(start) && tag.endsWith(end); + }); +} + +function applyInfoFieldUpdates( + clan: ClanRecord, + account: Account, + nextName: string, + nextTag: string, + changes: ClanInfoChanges, + nowSec: number, +): void { + clan.name = nextName; + if (nextTag !== clan.tag) { + clan.tag = nextTag; + clan.lastPaidTag = nextTag; + } + if (changes.desc !== undefined) clan.desc = changes.desc; + if (changes.slogan !== undefined) clan.slogan = changes.slogan; + if (changes.announcement !== undefined) clan.announcement = changes.announcement; + if (changes.region !== undefined && changes.region !== clan.region) { + clan.region = changes.region; + clan.regionLastUpdatedSec = nowSec; + } + if (changes.status !== undefined) clan.status = changes.status; + clan.changedByUid = account.userId; + clan.changedByNick = account.nick; + clan.changedTimeSec = nowSec; + appendClanLog(clan, { + ev: 'info', timeSec: nowSec, uId: account.userId, uN: account.nick, + name: clan.name, tag: clan.tag, desc: clan.desc, slogan: clan.slogan, + region: clan.region, announcement: clan.announcement, status: clan.status, + }); +} + function buildCreatedClanRecord( id: string, account: Account, @@ -207,13 +253,13 @@ function buildCreatedClanRecord( input: CreateClanInput, nowSec: number, ): ClanRecord { - const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), 360); - const leaderMember: ClanMemberRecord = { + const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), MAX_ACTIVITY_PER_PERIOD); + const leader: ClanMemberRecord = { uid: account.userId, nick: account.nick, role: ClanRole.LEADER, joinDateSec: nowSec, - curActivity: 360, + curActivity: MAX_ACTIVITY_PER_PERIOD, totalActivity: periods.reduce((s, p) => s + p.activity, 0), earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), ratingArc: 1500, @@ -223,23 +269,12 @@ function buildCreatedClanRecord( }; const desc = input.type === 'normal' ? input.desc : ''; return { - id, - name, - tag, - lastPaidTag: tag, - type: input.type, - slogan: input.slogan, - desc, - announcement: input.announcement, - region: input.region, - status: 'open', - autoaccept: true, - mlimit: input.type === 'battalion' ? 10 : 128, - mspent: 0, - cdateSec: nowSec, - changedByUid: account.userId, - changedByNick: account.nick, - changedTimeSec: nowSec, + id, name, tag, lastPaidTag: tag, type: input.type, + slogan: input.slogan, desc, announcement: input.announcement, region: input.region, + status: 'open', autoaccept: true, + mlimit: input.type === 'battalion' ? BATTALION_INITIAL_MEMBER_LIMIT : NORMAL_CLAN_MEMBER_LIMIT, + mspent: 0, cdateSec: nowSec, + changedByUid: account.userId, changedByNick: account.nick, changedTimeSec: nowSec, regionLastUpdatedSec: input.region ? nowSec : 0, stats: { dr_era5_arc: 1500, dr_era5_hist: 1500, dr_era5_sim: 1500, @@ -248,22 +283,12 @@ function buildCreatedClanRecord( deaths_arc: 0, deaths_hist: 0, deaths_sim: 0, ftime_arc: 0, ftime_hist: 0, ftime_sim: 0, }, - members: [leaderMember], + members: [leader], candidates: [], blacklist: [], logs: [{ - id: 1, - ev: 'create', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - name, - type: input.type, - tag, - desc, - slogan: input.slogan, - region: input.region, - announcement: input.announcement, + id: 1, ev: 'create', timeSec: nowSec, uId: account.userId, uN: account.nick, + name, type: input.type, tag, desc, slogan: input.slogan, region: input.region, announcement: input.announcement, }], bestRewards: [], }; diff --git a/packages/local-service/src/clans/clan-membership.ts b/packages/local-service/src/clans/clan-membership.ts index b06d2b4..ff8a1fd 100644 --- a/packages/local-service/src/clans/clan-membership.ts +++ b/packages/local-service/src/clans/clan-membership.ts @@ -5,7 +5,14 @@ import type { Account } from '../accounts/account-store.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import { buildDefaultPeriods } from './clan-seeds.ts'; -import { ClanRole, roleNameOf, type ClanLogEntry, type ClanRecord } from './clan-types.ts'; +import { + ClanRole, + isAssignableClanRole, + MAX_ACTIVITY_PER_PERIOD, + roleNameOf, + type ClanLogEntry, + type ClanRecord, +} from './clan-types.ts'; export interface MembershipRequestQuery { readonly clanId?: string | undefined; @@ -46,13 +53,13 @@ export function addMemberToClan( nowSec: number, ): void { if (clan.members.some((m) => m.uid === uid)) return; - const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), 360); + const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), MAX_ACTIVITY_PER_PERIOD); clan.members.push({ uid, nick, role, joinDateSec: nowSec, - curActivity: 360, + curActivity: MAX_ACTIVITY_PER_PERIOD, totalActivity: periods.reduce((s, p) => s + p.activity, 0), earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), ratingArc: 1450, @@ -131,6 +138,7 @@ export function leaveClanInState( } export function acceptCandidateOnClan( + allClans: readonly ClanRecord[], clan: ClanRecord | undefined, initiator: Account, targetUid: string, @@ -140,8 +148,11 @@ export function acceptCandidateOnClan( ): boolean { if (!clan || !hasClanOfficerRight(clan, initiator.userId) || clan.members.length >= clan.mlimit) return false; const cand = clan.candidates.find((c) => c.uid === targetUid); - clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid); - addMemberToClan(clan, targetUid, cand?.nick ?? targetNick, role || ClanRole.REGULAR, initiator.userId, initiator.nick, nowSec); + if (!cand) return false; + if (allClans.some((c) => c.members.some((m) => m.uid === targetUid))) return false; + const assignedRole = isAssignableClanRole(clan.type, role) ? role : ClanRole.REGULAR; + clearCandidateEverywhere(allClans, targetUid); + addMemberToClan(clan, targetUid, cand.nick || targetNick, assignedRole, initiator.userId, initiator.nick, nowSec); return true; } @@ -199,10 +210,23 @@ export function changeMemberRoleOnClan( nowSec: number, ): boolean { if (!clan || !hasClanManageRight(clan, initiator.userId) || targetUid === initiator.userId) return false; - const idx = clan.members.findIndex((m) => m.uid === targetUid); - if (idx < 0) return false; - const prev = clan.members[idx]!; - clan.members[idx] = { ...prev, role: newRole }; + const initiatorIdx = clan.members.findIndex((m) => m.uid === initiator.userId); + const targetIdx = clan.members.findIndex((m) => m.uid === targetUid); + if (initiatorIdx < 0 || targetIdx < 0) return false; + + const initiatorMember = clan.members[initiatorIdx]!; + const prev = clan.members[targetIdx]!; + + if (newRole === ClanRole.LEADER) { + if (initiatorMember.role !== ClanRole.LEADER) return false; + const demotedRole = clan.type === 'battalion' ? ClanRole.OFFICER : ClanRole.DEPUTY; + clan.members[initiatorIdx] = { ...initiatorMember, role: demotedRole }; + clan.members[targetIdx] = { ...prev, role: ClanRole.LEADER }; + } else { + if (prev.role === ClanRole.LEADER || !isAssignableClanRole(clan.type, newRole)) return false; + clan.members[targetIdx] = { ...prev, role: newRole }; + } + appendClanLog(clan, { ev: 'role', timeSec: nowSec, diff --git a/packages/local-service/src/clans/clan-queries.ts b/packages/local-service/src/clans/clan-queries.ts index c1aece6..f6f14ad 100644 --- a/packages/local-service/src/clans/clan-queries.ts +++ b/packages/local-service/src/clans/clan-queries.ts @@ -2,9 +2,8 @@ * Read-only search and leaderboard queries over the local squadron directory *. */ -import { totalPeriodActivityOf } from './clan-blk.ts'; import { stripClanDecorators } from './clan-lifecycle.ts'; -import type { ClanRecord } from './clan-types.ts'; +import { totalPeriodActivityOf, type ClanRecord } from './clan-types.ts'; export interface LeaderboardQuery { readonly start: number; diff --git a/packages/local-service/src/clans/clan-seeds.ts b/packages/local-service/src/clans/clan-seeds.ts index 04444ef..6cdd521 100644 --- a/packages/local-service/src/clans/clan-seeds.ts +++ b/packages/local-service/src/clans/clan-seeds.ts @@ -1,129 +1,27 @@ /** * Default offline squadron directory seeded on first creation of `/clans.json` - * (implementation notes section I). Includes open auto-accept squadrons for instant offline - * joining, a manual-review squadron for testing candidate requests, a battalion squadron, - * and rich NPC member profiles so player cards work for every member. + * (implementation notes section I; implementation notes). */ -import { ClanRole, type ClanActivityPeriodEntry, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; +import { + BATTALION_INITIAL_MEMBER_LIMIT, + ClanRole, + MAX_ACTIVITY_PER_PERIOD, + MAX_CLAN_ACTIVITY, + NORMAL_CLAN_MEMBER_LIMIT, + REWARD_PERIOD_DAYS, + type ClanActivityPeriodEntry, + type ClanMemberRecord, + type ClanRecord, +} from './clan-types.ts'; -export function createDefaultClans(nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] { - const todayDay = Math.floor(nowSec / 86400); - const createdBase = nowSec - 180 * 86400; - - return [ - buildSeededClan({ - id: '500001', - tag: '[WTOF]', - name: 'War Thunder Offline Guard', - type: 'normal', - slogan: '离线天空与钢铁防线 · 自由研发全部联队载具', - desc: 'War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。', - announcement: '欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。', - region: 'CN / Global', - autoaccept: true, - mlimit: 128, - cdateSec: createdBase, - todayDay, - eloArc: 1840, - eloHist: 2150, - eloSim: 1620, - npcs: [ - { uid: '900001001', nick: 'Lin_Wei', role: ClanRole.LEADER, title: 'title_marshall', icon: 'cardicon_28', unit: 'cn_ztz_99a', activity: 360 }, - { uid: '900001002', nick: 'Elena_Valkyrie', role: ClanRole.DEPUTY, title: 'title_ace', icon: 'cardicon_fem_01', unit: 'su_27sm', activity: 360 }, - { uid: '900001003', nick: 'iron_tiger_88', role: ClanRole.OFFICER, title: 'title_tank_destroyer', icon: 'cardicon_14', unit: 'germ_leopard_2a7v', activity: 360 }, - { uid: '900001004', nick: 'Tomcat_Actual', role: ClanRole.OFFICER, title: 'title_jet_powered', icon: 'cardicon_07', unit: 'f_14b', activity: 345 }, - { uid: '900001005', nick: 'Kuroshio_DD', role: ClanRole.SERGEANT, title: 'title_sea_wolf', icon: 'cardicon_19', unit: 'jp_destroyer_shimakaze', activity: 330 }, - { uid: '900001006', nick: 'Northern_Fox', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_11', unit: 'sw_strv_122b_plus', activity: 310 }, - ], - }), - buildSeededClan({ - id: '500002', - tag: '=PLAF=', - name: 'Red Falcon Aviation Wing', - type: 'normal', - slogan: '鹰击长空 · 现代喷气空战与陆空协同联队', - desc: '专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。', - announcement: '本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。', - region: 'Asia', - autoaccept: true, - mlimit: 128, - cdateSec: createdBase + 86400 * 12, - todayDay, - eloArc: 1690, - eloHist: 2040, - eloSim: 1780, - npcs: [ - { uid: '900002001', nick: 'SkyDragon_J20', role: ClanRole.LEADER, title: 'title_ace', icon: 'cardicon_25', unit: 'j_11a', activity: 360 }, - { uid: '900002002', nick: 'Thunderbolt_CN', role: ClanRole.DEPUTY, title: 'title_pilot', icon: 'cardicon_09', unit: 'jh_7a', activity: 360 }, - { uid: '900002003', nick: 'SteelWall_99', role: ClanRole.OFFICER, title: 'title_unstoppable', icon: 'cardicon_16', unit: 'cn_vt_4a1', activity: 350 }, - { uid: '900002004', nick: 'NightHawk_04', role: ClanRole.REGULAR, title: 'title_eagle', icon: 'cardicon_05', unit: 'f_15j_kai', activity: 300 }, - ], - }), - buildSeededClan({ - id: '500003', - tag: '-1STG-', - name: '1st Armored Guards Division', - type: 'normal', - slogan: 'Steel & Fire — Heavy Armor Historical Squadron', - desc: 'Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.', - announcement: 'Squadron vehicles ready for research at full 20,000 RP per period.', - region: 'EU / Global', - autoaccept: true, - mlimit: 128, - cdateSec: createdBase + 86400 * 24, - todayDay, - eloArc: 1920, - eloHist: 1980, - eloSim: 1510, - npcs: [ - { uid: '900003001', nick: 'Kommissar_KVs', role: ClanRole.LEADER, title: 'title_hero', icon: 'cardicon_22', unit: 'ussr_t_90m', activity: 360 }, - { uid: '900003002', nick: 'PanzerMeyer_IV', role: ClanRole.OFFICER, title: 'title_tankman', icon: 'cardicon_12', unit: 'germ_pzkpfw_VI_ausf_h1_tiger', activity: 340 }, - { uid: '900003003', nick: 'DesertRat_UK', role: ClanRole.REGULAR, title: 'title_conqueror', icon: 'cardicon_18', unit: 'uk_challenger_2_black_night', activity: 290 }, - ], - }), - buildSeededClan({ - id: '500004', - tag: '^82AB^', - name: '82nd Combined Task Force', - type: 'normal', - slogan: 'All The Way — Air, Ground & Naval Task Force', - desc: '需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。', - announcement: 'Manual application review enabled for testing request/cancel workflow.', - region: 'NA', - autoaccept: false, - mlimit: 128, - cdateSec: createdBase + 86400 * 35, - todayDay, - eloArc: 1550, - eloHist: 1760, - eloSim: 1490, - npcs: [ - { uid: '900004001', nick: 'Major_Winters', role: ClanRole.LEADER, title: 'title_brother_in_arms', icon: 'cardicon_03', unit: 'us_m1a2_sep2_abrams', activity: 360 }, - { uid: '900004002', nick: 'Mustang_Lead', role: ClanRole.OFFICER, title: 'title_ace', icon: 'cardicon_08', unit: 'p-51d-30_usaaf_korea', activity: 315 }, - ], - }), - buildSeededClan({ - id: '500005', - tag: '**RCON**', - name: 'Reconnaissance Battalion Alpha', - type: 'battalion', - slogan: '轻量级战术分队 · 侦察与快速反应', - desc: '战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。', - announcement: '轻装侦察分队常驻开放。', - region: 'Global', - autoaccept: true, - mlimit: 10, - cdateSec: createdBase + 86400 * 48, - todayDay, - eloArc: 1410, - eloHist: 1610, - eloSim: 1320, - npcs: [ - { uid: '900005001', nick: 'Ghost_Scout', role: ClanRole.LEADER, title: 'title_scout', icon: 'cardicon_15', unit: 'us_hstvl', activity: 360 }, - { uid: '900005002', nick: 'Lynx_Spotter', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_20', unit: 'it_centauro_rgo_120', activity: 280 }, - ], - }), - ]; +interface NpcSpec { + readonly uid: string; + readonly nick: string; + readonly role: number; + readonly title: string; + readonly icon: string; + readonly unit: string; + readonly activity: number; } interface SeedSpec { @@ -137,45 +35,140 @@ interface SeedSpec { readonly region: string; readonly autoaccept: boolean; readonly mlimit: number; - readonly cdateSec: number; - readonly todayDay: number; + readonly dayOffset: number; readonly eloArc: number; readonly eloHist: number; readonly eloSim: number; - readonly npcs: ReadonlyArray<{ - readonly uid: string; - readonly nick: string; - readonly role: number; - readonly title: string; - readonly icon: string; - readonly unit: string; - readonly activity: number; - }>; + readonly npcs: readonly NpcSpec[]; } -function buildSeededClan(spec: SeedSpec): ClanRecord { - const members: ClanMemberRecord[] = spec.npcs.map((npc, idx) => { - const periods = buildDefaultPeriods(spec.todayDay, npc.activity); - return { - uid: npc.uid, - nick: npc.nick, - role: npc.role, - joinDateSec: spec.cdateSec + idx * 3600, - isNpc: true, - npcTitle: npc.title, - npcPilotIcon: npc.icon, - npcFrame: '', - npcShowcaseUnit: npc.unit, - curActivity: npc.activity, - totalActivity: periods.reduce((sum, p) => sum + p.activity, 0), - earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0), - ratingArc: Math.max(800, spec.eloArc - idx * 45), - ratingHist: Math.max(850, spec.eloHist - idx * 50), - ratingSim: Math.max(700, spec.eloSim - idx * 40), - periods, - }; - }); +const SEED_SPECS: readonly SeedSpec[] = [ + { + id: '500001', + tag: '[WTOF]', + name: 'War Thunder Offline Guard', + type: 'normal', + slogan: '离线天空与钢铁防线 · 自由研发全部联队载具', + desc: 'War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。', + announcement: '欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。', + region: 'CN / Global', + autoaccept: true, + mlimit: NORMAL_CLAN_MEMBER_LIMIT, + dayOffset: 0, + eloArc: 1840, + eloHist: 2150, + eloSim: 1620, + npcs: [ + { uid: '900001001', nick: 'Lin_Wei', role: ClanRole.LEADER, title: 'title_marshall', icon: 'cardicon_28', unit: 'cn_ztz_99a', activity: MAX_ACTIVITY_PER_PERIOD }, + { uid: '900001002', nick: 'Elena_Valkyrie', role: ClanRole.DEPUTY, title: 'title_ace', icon: 'cardicon_fem_01', unit: 'su_27sm', activity: MAX_ACTIVITY_PER_PERIOD }, + { uid: '900001003', nick: 'iron_tiger_88', role: ClanRole.OFFICER, title: 'title_tank_destroyer', icon: 'cardicon_14', unit: 'germ_leopard_2a7v', activity: MAX_ACTIVITY_PER_PERIOD }, + { uid: '900001004', nick: 'Tomcat_Actual', role: ClanRole.OFFICER, title: 'title_jet_powered', icon: 'cardicon_07', unit: 'f_14b', activity: 345 }, + { uid: '900001005', nick: 'Kuroshio_DD', role: ClanRole.SERGEANT, title: 'title_sea_wolf', icon: 'cardicon_19', unit: 'jp_destroyer_shimakaze', activity: 330 }, + { uid: '900001006', nick: 'Northern_Fox', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_11', unit: 'sw_strv_122b_plus', activity: 310 }, + ], + }, + { + id: '500002', + tag: '=PLAF=', + name: 'Red Falcon Aviation Wing', + type: 'normal', + slogan: '鹰击长空 · 现代喷气空战与陆空协同联队', + desc: '专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。', + announcement: '本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。', + region: 'Asia', + autoaccept: true, + mlimit: NORMAL_CLAN_MEMBER_LIMIT, + dayOffset: 12, + eloArc: 1690, + eloHist: 2040, + eloSim: 1780, + npcs: [ + { uid: '900002001', nick: 'SkyDragon_J20', role: ClanRole.LEADER, title: 'title_ace', icon: 'cardicon_25', unit: 'j_11a', activity: MAX_ACTIVITY_PER_PERIOD }, + { uid: '900002002', nick: 'Thunderbolt_CN', role: ClanRole.DEPUTY, title: 'title_pilot', icon: 'cardicon_09', unit: 'jh_7a', activity: MAX_ACTIVITY_PER_PERIOD }, + { uid: '900002003', nick: 'SteelWall_99', role: ClanRole.OFFICER, title: 'title_unstoppable', icon: 'cardicon_16', unit: 'cn_vt_4a1', activity: 350 }, + { uid: '900002004', nick: 'NightHawk_04', role: ClanRole.REGULAR, title: 'title_eagle', icon: 'cardicon_05', unit: 'f_15j_kai', activity: 300 }, + ], + }, + { + id: '500003', + tag: '-1STG-', + name: '1st Armored Guards Division', + type: 'normal', + slogan: 'Steel & Fire — Heavy Armor Historical Squadron', + desc: 'Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.', + announcement: 'Squadron vehicles ready for research at full 20,000 RP per period.', + region: 'EU / Global', + autoaccept: true, + mlimit: NORMAL_CLAN_MEMBER_LIMIT, + dayOffset: 24, + eloArc: 1920, + eloHist: 1980, + eloSim: 1510, + npcs: [ + { uid: '900003001', nick: 'Kommissar_KVs', role: ClanRole.LEADER, title: 'title_hero', icon: 'cardicon_22', unit: 'ussr_t_90m', activity: MAX_ACTIVITY_PER_PERIOD }, + { uid: '900003002', nick: 'PanzerMeyer_IV', role: ClanRole.OFFICER, title: 'title_tankman', icon: 'cardicon_12', unit: 'germ_pzkpfw_VI_ausf_h1_tiger', activity: 340 }, + { uid: '900003003', nick: 'DesertRat_UK', role: ClanRole.REGULAR, title: 'title_conqueror', icon: 'cardicon_18', unit: 'uk_challenger_2_black_night', activity: 290 }, + ], + }, + { + id: '500004', + tag: '^82AB^', + name: '82nd Combined Task Force', + type: 'normal', + slogan: 'All The Way — Air, Ground & Naval Task Force', + desc: '需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。', + announcement: 'Manual application review enabled for testing request/cancel workflow.', + region: 'NA', + autoaccept: false, + mlimit: NORMAL_CLAN_MEMBER_LIMIT, + dayOffset: 35, + eloArc: 1550, + eloHist: 1760, + eloSim: 1490, + npcs: [ + { uid: '900004001', nick: 'Major_Winters', role: ClanRole.LEADER, title: 'title_brother_in_arms', icon: 'cardicon_03', unit: 'us_m1a2_sep2_abrams', activity: MAX_ACTIVITY_PER_PERIOD }, + { uid: '900004002', nick: 'Mustang_Lead', role: ClanRole.OFFICER, title: 'title_ace', icon: 'cardicon_08', unit: 'p-51d-30_usaaf_korea', activity: 315 }, + ], + }, + { + id: '500005', + tag: '**RCON**', + name: 'Reconnaissance Battalion Alpha', + type: 'battalion', + slogan: '轻量级战术分队 · 侦察与快速反应', + desc: '战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。', + announcement: '轻装侦察分队常驻开放。', + region: 'Global', + autoaccept: true, + mlimit: BATTALION_INITIAL_MEMBER_LIMIT, + dayOffset: 48, + eloArc: 1410, + eloHist: 1610, + eloSim: 1320, + npcs: [ + { uid: '900005001', nick: 'Ghost_Scout', role: ClanRole.LEADER, title: 'title_scout', icon: 'cardicon_15', unit: 'us_hstvl', activity: MAX_ACTIVITY_PER_PERIOD }, + { uid: '900005002', nick: 'Lynx_Spotter', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_20', unit: 'it_centauro_rgo_120', activity: 280 }, + ], + }, +]; +export function createDefaultClans(nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] { + const todayDay = Math.floor(nowSec / 86400); + const createdBase = nowSec - 180 * 86400; + return SEED_SPECS.map((spec) => buildSeededClan(spec, createdBase + spec.dayOffset * 86400, todayDay)); +} + +export function buildDefaultPeriods(todayDay: number, periodActivity = MAX_ACTIVITY_PER_PERIOD): ClanActivityPeriodEntry[] { + const expPerPeriod = Math.round((periodActivity / MAX_ACTIVITY_PER_PERIOD) * MAX_CLAN_ACTIVITY); + return [0, 1, 2].map((idx) => ({ + day: todayDay - idx * REWARD_PERIOD_DAYS, + activity: periodActivity, + exp: expPerPeriod, + })); +} + +function buildSeededClan(spec: SeedSpec, cdateSec: number, todayDay: number): ClanRecord { + const members = spec.npcs.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay)); const leader = spec.npcs[0]!; return { id: spec.id, @@ -191,56 +184,48 @@ function buildSeededClan(spec: SeedSpec): ClanRecord { autoaccept: spec.autoaccept, mlimit: spec.mlimit, mspent: 0, - cdateSec: spec.cdateSec, + cdateSec, changedByUid: leader.uid, changedByNick: leader.nick, - changedTimeSec: spec.cdateSec, + changedTimeSec: cdateSec, regionLastUpdatedSec: 0, stats: { - dr_era5_arc: spec.eloArc, - dr_era5_hist: spec.eloHist, - dr_era5_sim: spec.eloSim, - akills_arc: 4280, - akills_hist: 6150, - akills_sim: 1420, - gkills_arc: 7890, - gkills_hist: 11240, - gkills_sim: 2680, - deaths_arc: 5120, - deaths_hist: 6890, - deaths_sim: 1950, - ftime_arc: 18400, - ftime_hist: 32600, - ftime_sim: 8900, + dr_era5_arc: spec.eloArc, dr_era5_hist: spec.eloHist, dr_era5_sim: spec.eloSim, + akills_arc: 4280, akills_hist: 6150, akills_sim: 1420, + gkills_arc: 7890, gkills_hist: 11240, gkills_sim: 2680, + deaths_arc: 5120, deaths_hist: 6890, deaths_sim: 1950, + ftime_arc: 18400, ftime_hist: 32600, ftime_sim: 8900, }, members, candidates: [], blacklist: [], - logs: [ - { - id: 1, - ev: 'create', - timeSec: spec.cdateSec, - uId: leader.uid, - uN: leader.nick, - name: spec.name, - type: spec.type, - tag: spec.tag, - desc: spec.desc, - slogan: spec.slogan, - region: spec.region, - announcement: spec.announcement, - }, - ], + logs: [{ + id: 1, ev: 'create', timeSec: cdateSec, uId: leader.uid, uN: leader.nick, + name: spec.name, type: spec.type, tag: spec.tag, desc: spec.desc, + slogan: spec.slogan, region: spec.region, announcement: spec.announcement, + }], bestRewards: [], }; } -export function buildDefaultPeriods(todayDay: number, periodActivity = 360): ClanActivityPeriodEntry[] { - const expPerPeriod = Math.round((periodActivity / 360) * 20000); - return [ - { day: todayDay, activity: periodActivity, exp: expPerPeriod }, - { day: todayDay - 3, activity: periodActivity, exp: expPerPeriod }, - { day: todayDay - 6, activity: Math.max(180, periodActivity - 30), exp: Math.round((Math.max(180, periodActivity - 30) / 360) * 20000) }, - ]; +function buildSeededMember(spec: SeedSpec, npc: NpcSpec, idx: number, cdateSec: number, todayDay: number): ClanMemberRecord { + const periods = buildDefaultPeriods(todayDay, npc.activity); + return { + uid: npc.uid, + nick: npc.nick, + role: npc.role, + joinDateSec: cdateSec + idx * 3600, + isNpc: true, + npcTitle: npc.title, + npcPilotIcon: npc.icon, + npcFrame: '', + npcShowcaseUnit: npc.unit, + curActivity: npc.activity, + totalActivity: periods.reduce((sum, p) => sum + p.activity, 0), + earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0), + ratingArc: Math.max(800, spec.eloArc - idx * 45), + ratingHist: Math.max(850, spec.eloHist - idx * 50), + ratingSim: Math.max(700, spec.eloSim - idx * 40), + periods, + }; } diff --git a/packages/local-service/src/clans/clan-store.ts b/packages/local-service/src/clans/clan-store.ts index cfd64d7..3fec216 100644 --- a/packages/local-service/src/clans/clan-store.ts +++ b/packages/local-service/src/clans/clan-store.ts @@ -15,10 +15,11 @@ import { setPendingClanRequest, syncStoredClanEarnedExp, } from '../profile/profile-clan.ts'; -import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { RuleOutcome } from '../research/rule-outcome.ts'; import { writeFileAtomic } from '../storage/atomic-file.ts'; import { createClanInState, + disbandClanInState, editClanInfoInState, upgradeClanToNormalInState, upgradeMembersLimitInState, @@ -39,7 +40,7 @@ import { } from './clan-membership.ts'; import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts'; import { createDefaultClans } from './clan-seeds.ts'; -import { ClanRole, type ClanBestReward, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; +import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts'; export type { LeaderboardQuery }; @@ -140,7 +141,7 @@ export class ClanStore { } editClanInfo(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, changes: ClanInfoChanges, nowSec = nowSeconds()): RuleOutcome { - const outcome = editClanInfoInState(this.#resolveClan(clanId, account.userId), profile, account, economy, changes, nowSec); + const outcome = editClanInfoInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, changes, nowSec); if (outcome.ok) { this.#save(); this.syncProfile(profile, account); @@ -156,7 +157,7 @@ export class ClanStore { input: { readonly tag: string; readonly desc: string; readonly announcement: string }, nowSec = nowSeconds(), ): RuleOutcome { - const outcome = upgradeClanToNormalInState(this.#resolveClan(clanId, account.userId), profile, account, economy, input, nowSec); + const outcome = upgradeClanToNormalInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, input, nowSec); if (outcome.ok) { this.#save(); this.syncProfile(profile, account); @@ -203,17 +204,16 @@ export class ClanStore { } disbandClan(profile: BlkBlock, account: Account, clanId?: string): RuleOutcome { - const clan = this.#resolveClan(clanId, account.userId); - const role = clan?.members.find((m) => m.uid === account.userId)?.role; - if (!clan || (role !== ClanRole.LEADER && role !== ClanRole.CLANADMIN)) return refused('NOT_AVAILABLE'); - this.#state.clans = this.#state.clans.filter((c) => c.id !== clan.id); - this.#save(); - this.syncProfile(profile, account); - return ACCEPTED; + const outcome = disbandClanInState(this.#state, this.#resolveClan(clanId, account.userId), account); + if (outcome.ok) { + this.#save(); + this.syncProfile(profile, account); + } + return outcome; } acceptCandidate(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, role: number, nowSec = nowSeconds()): boolean { - if (!acceptCandidateOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, role, nowSec)) return false; + if (!acceptCandidateOnClan(this.#state.clans, this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, role, nowSec)) return false; this.#save(); return true; } diff --git a/packages/local-service/src/clans/clan-types.ts b/packages/local-service/src/clans/clan-types.ts index eeb1d8a..aa66ceb 100644 --- a/packages/local-service/src/clans/clan-types.ts +++ b/packages/local-service/src/clans/clan-types.ts @@ -1,10 +1,17 @@ /** - * Types and binary enum constants for the local squadron (clan) system + * Types, binary enum constants, and shared squadron domain constants *. */ import type { BlkBlock } from '@wto/blk'; import type { ClanKind } from '../profile/profile-clan.ts'; +export const MAX_ACTIVITY_PER_PERIOD = 360; +export const MAX_CLAN_ACTIVITY = 20_000; +export const REWARD_PERIOD_DAYS = 3; +export const HISTORY_DEPTH_DAYS = 14; +export const NORMAL_CLAN_MEMBER_LIMIT = 128; +export const BATTALION_INITIAL_MEMBER_LIMIT = 10; + /** Exact `ECMR_*` role codes registered at aces.exe 0x2986a0..0x298802 (table 0x7ba87e8). */ export const ClanRole = { LEADER: 1, @@ -32,6 +39,39 @@ export function roleNameOf(role: number): string { } } +export function roleCodeFromString(name: string): number | undefined { + switch (name.trim().toUpperCase()) { + case 'LEADER': + return ClanRole.LEADER; + case 'DEPUTY': + return ClanRole.DEPUTY; + case 'OFFICER': + return ClanRole.OFFICER; + case 'SERGEANT': + return ClanRole.SERGEANT; + case 'REGULAR': + return ClanRole.REGULAR; + default: + return undefined; + } +} + +/** Whether a non-leader member role is valid for the given squadron type (0x2986a0 table). */ +export function isAssignableClanRole(clanType: ClanKind, role: number): boolean { + if (clanType === 'battalion') { + return role === ClanRole.OFFICER || role === ClanRole.REGULAR; + } + return role === ClanRole.DEPUTY + || role === ClanRole.OFFICER + || role === ClanRole.SERGEANT + || role === ClanRole.REGULAR; +} + +export function totalPeriodActivityOf(clan: ClanRecord): number { + const sum = clan.members.reduce((acc, m) => acc + m.curActivity, 0); + return Math.min(MAX_CLAN_ACTIVITY * 5, sum * 10); +} + export interface ClanStats { readonly dr_era5_arc: number; readonly dr_era5_hist: number; diff --git a/packages/local-service/src/cloud-settings/cloud-settings-codec.ts b/packages/local-service/src/cloud-settings/cloud-settings-codec.ts deleted file mode 100644 index 972aa14..0000000 --- a/packages/local-service/src/cloud-settings/cloud-settings-codec.ts +++ /dev/null @@ -1,212 +0,0 @@ -/** - * Wire codecs for War Thunder's cloud settings subsystem (`online_storage` / `generalBlk`, - * implementation notes; aces.exe 2.61.0.37 at 0x4662a70..0x466b2ec and 0x41537d0..0x4154020). - */ -import { createHash } from 'node:crypto'; -import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib'; -import { - decodeBlk, - emptyBlock, - encodeBlk, - findBlock, - findParam, - setParam, - type BlkBlock, -} from '@wto/blk'; -import { unpackMarked } from '../char/compression-marker.ts'; - -/** - * The three GeneralBlk types accepted by `PlayerProfile::applyGeneralBlk` (0xf5afb0) and - * `PlayerProfile::storeGeneralBlk` (0xf5b080). - */ -export const GENERAL_BLK_TYPES = [ - 'GBT_GENERAL_STORAGE', - 'GBT_GENERAL_SETTINGS', - 'GBT_GENERAL_MACHINE_SETTINGS', -] as const; - -/** - * Compression methods advertised in `cln_get_meta_blk`'s `compressionSupported`. Put `zstd` - * first so `online_storage::Context::selectCompression` (0x4665de1) selects pure Zstandard - * frames (0x3372ca0), which Node's built-in `node:zlib` unpacks directly. - */ -export const SUPPORTED_CLOUD_COMPRESSIONS = 'zstd;zlib;gzip'; - -export const PBBD_MAGIC = 0x44424250; // "PBBD" little-endian (0x4663427: 0x144424250) - -export interface ParsedGblkUpload { - readonly blkType: string; - readonly version: number; - readonly contentHash: string; - readonly container: BlkBlock; -} - -export function isPbbdStream(bytes: Uint8Array): boolean { - if (bytes.byteLength < 8) return false; - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - return view.getUint32(0, true) === PBBD_MAGIC && view.getUint16(4, true) === 1; -} - -/** - * Unpack a single `cln_set_general_blk` request body (0x4666ee7 -> 0x3371f30 -> 0x3371cc0). - * Unlike CharServer answers, `0x3371cc0` omits the 1-byte marker and names the compressor in - * the HTTP `compr` header (`zstd`: pure Zstd frame; `zlib`: 4-byte BE size + zlib stream; - * `gzip`: standard gzip; omitted/`none`: raw binary BLK). - */ -export function unpackCloudBlk(bytes: Uint8Array, comprHeader: string | undefined): BlkBlock | undefined { - if (bytes.byteLength === 0) return undefined; - const raw = decompressCloudBytes(bytes, comprHeader); - if (!raw || raw.byteLength === 0) return undefined; - try { - return decodeBlk(raw); - } catch { - return undefined; - } -} - -/** - * Parse a `cln_bulk_set_gblk` `PBBD` stream (0x4663080..0x4663f1c, 0x41537d0..0x4154020). - * Header is 8 bytes: `"PBBD"` + `uint16_le(1)` + `uint16_le(chunkCount)`. - * Each chunk is `uint32_le(payloadLen)` + `uint8(marker)` + `payload`. - * Each `desc:t="store_gblk"` descriptor chunk is immediately followed by its `ContainerBlk` chunk. - */ -export function parsePbbdBulkUploads(bytes: Uint8Array): ReadonlyArray { - if (!isPbbdStream(bytes)) return []; - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const chunkCount = view.getUint16(6, true); - const chunks: Array = []; - let offset = 8; - - for (let i = 0; i < chunkCount; i++) { - if (offset + 5 > bytes.byteLength) break; - const payloadLen = view.getUint32(offset, true); - const marker = bytes[offset + 4]!; - offset += 5; - if (offset + payloadLen > bytes.byteLength) break; - const slice = bytes.subarray(offset, offset + payloadLen); - offset += payloadLen; - chunks.push(decodeMarkedChunk(marker, slice)); - } - - const uploads: ParsedGblkUpload[] = []; - for (let i = 0; i < chunks.length; i++) { - const meta = chunks[i]; - if (!meta) continue; - const desc = stringOf(meta, 'desc'); - if (desc === 'store_gblk') { - const containerCandidate = chunks[i + 1]; - i += 1; - const blkType = stringOf(meta, 'blkType'); - if (!blkType || !containerCandidate) continue; - const fallbackVersion = intOf(meta, 'version') ?? 1; - const extracted = normalizeContainerBlk(containerCandidate, fallbackVersion); - const contentHash = stringOf(meta, 'contentHash') || computeContentHash(extracted.content); - uploads.push({ - blkType, - version: extracted.version, - contentHash, - container: extracted.container, - }); - } else if (desc === 'bigquery' || desc === 'logout') { - // Both `bigquery` (0x4663916) and `logout` (0x4663b66) append one companion payload chunk. - i += 1; - } - } - return uploads; -} - -/** - * Normalize an uploaded `ContainerBlk` (`version:i` + `content { ... }`, 0x4664b55 / 0x466a810) - * so stored `.blk` files always carry an authoritative positive `version:i` and a `content` block. - */ -export function normalizeContainerBlk( - incoming: BlkBlock, - fallbackVersion: number, -): { readonly version: number; readonly content: BlkBlock; readonly container: BlkBlock } { - const existingContent = findBlock(incoming, 'content'); - const rawVersion = intOf(incoming, 'version') ?? fallbackVersion; - const version = rawVersion > 0 ? rawVersion : Math.max(1, fallbackVersion); - - const content = existingContent - ? cloneAsContent(existingContent) - : cloneAsContent(incoming); - - const container = buildContainerBlk(version, content); - return { version, content, container }; -} - -export function buildContainerBlk(version: number, content: BlkBlock): BlkBlock { - const container = emptyBlock(); - setParam(container, 'version', { type: 'int', value: Math.max(1, Math.trunc(version)) }); - container.blocks.push(cloneAsContent(content)); - return container; -} - -/** MD5 hex of the serialized `content` DataBlock (`ContainerBlk::calcHash` at 0x466af40 -> 0x4661840). */ -export function computeContentHash(content: BlkBlock): string { - const rootCopy = emptyBlock(); - rootCopy.params.push(...content.params); - rootCopy.blocks.push(...content.blocks); - return createHash('md5').update(encodeBlk(rootCopy)).digest('hex'); -} - -export function describePbbdForLog(bytes: Uint8Array): string { - const uploads = parsePbbdBulkUploads(bytes); - if (uploads.length === 0) return 'PBBD stream (0 store_gblk items)'; - return uploads.map((u) => `${u.blkType} v${u.version} (${u.contentHash})`).join(', '); -} - -function cloneAsContent(source: BlkBlock): BlkBlock { - return { - name: 'content', - params: [...source.params], - blocks: [...source.blocks], - }; -} - -function decompressCloudBytes(bytes: Uint8Array, comprHeader: string | undefined): Uint8Array | undefined { - const method = comprHeader?.trim().toLowerCase(); - try { - if (method === 'zstd') return zstdDecompressSync(bytes); - if (method === 'zlib') return bytes.byteLength > 4 ? inflateSync(bytes.subarray(4)) : undefined; - if (method === 'gzip') return gunzipSync(bytes); - if (!method || method === 'none') { - const marked = unpackMarked(bytes); - return marked?.data ?? bytes; - } - const marked = unpackMarked(bytes); - return marked?.data; - } catch { - const marked = unpackMarked(bytes); - return marked?.data; - } -} - -function decodeMarkedChunk(marker: number, payload: Uint8Array): BlkBlock | undefined { - if (payload.byteLength === 0) return emptyBlock(); - try { - let raw: Uint8Array | undefined; - if (marker === 0x69) { - raw = payload; // 'i' uncompressed - } else if (marker === 0x5a) { - raw = zstdDecompressSync(payload); // 'Z' zstd (0-byte header) - } else if (marker === 0x7a) { - raw = payload.byteLength > 4 ? inflateSync(payload.subarray(4)) : undefined; // 'z' 4B BE size + zlib - } else if (marker === 0x1f) { - raw = gunzipSync(payload); // gzip - } - return raw ? decodeBlk(raw) : undefined; - } catch { - return undefined; - } -} - -function stringOf(block: BlkBlock, name: string): string | undefined { - const param = findParam(block, name); - return param?.value.type === 'string' ? param.value.value : undefined; -} - -function intOf(block: BlkBlock, name: string): number | undefined { - const param = findParam(block, name); - return param?.value.type === 'int' ? param.value.value : undefined; -} diff --git a/packages/local-service/src/cloud-settings/cloud-settings-store.ts b/packages/local-service/src/cloud-settings/cloud-settings-store.ts index 0d26e84..45f7c12 100644 --- a/packages/local-service/src/cloud-settings/cloud-settings-store.ts +++ b/packages/local-service/src/cloud-settings/cloud-settings-store.ts @@ -8,11 +8,32 @@ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, setParam, type BlkBlock } from '@wto/blk'; import { writeFileAtomic } from '../storage/atomic-file.ts'; -import { - GENERAL_BLK_TYPES, - SUPPORTED_CLOUD_COMPRESSIONS, - type ParsedGblkUpload, -} from './cloud-settings-codec.ts'; + +/** + * The three GeneralBlk types accepted by `PlayerProfile::applyGeneralBlk` (0xf5afb0) and + * `PlayerProfile::storeGeneralBlk` (0xf5b080). + */ +export const GENERAL_BLK_TYPES = [ + 'GBT_GENERAL_STORAGE', + 'GBT_GENERAL_SETTINGS', + 'GBT_GENERAL_MACHINE_SETTINGS', +] as const; + +/** + * Compression methods advertised in `cln_get_meta_blk`'s `compressionSupported`. Put `zstd` + * first so `online_storage::Context::selectCompression` (0x4665de1) selects pure Zstandard + * frames (0x3372ca0), which Node's built-in `node:zlib` unpacks directly. + */ +export const SUPPORTED_CLOUD_COMPRESSIONS = 'zstd;zlib;gzip'; + +const SUPPORTED_BLK_TYPE_SET: ReadonlySet = new Set(GENERAL_BLK_TYPES); + +export interface ParsedGblkUpload { + readonly blkType: string; + readonly version: number; + readonly contentHash: string; + readonly container: BlkBlock; +} interface StoredBlockMeta { version: number; @@ -32,11 +53,6 @@ export class CloudSettingsStore { this.#savesRoot = join(dataFolder, 'saves'); } - /** - * Build the `generalBlkMeta` / `cln_get_meta_blk` DataBlock (aces.exe 0x4665cf4..0x4666900). - * Every registered `blkType` is marked `perMachine:b=no` in `__schema` so settings travel - * with the player's save across machines without hardware-ID partitioning. - */ buildMetaBlk(userId?: string, blockName?: string): BlkBlock { const meta = blockName ? emptyBlock(blockName) : emptyBlock(); setParam(meta, 'machineHash', { type: 'string', value: `hhh${userId ?? '0'}` }); @@ -44,7 +60,7 @@ export class CloudSettingsStore { const schema = ensureBlock(meta, '__schema'); const saved = userId && isValidUserId(userId) ? this.#loadMeta(userId).blocks : {}; - const allTypes = new Set([...GENERAL_BLK_TYPES, ...Object.keys(saved)]); + const allTypes = new Set([...GENERAL_BLK_TYPES, ...Object.keys(saved).filter(isSupportedGeneralBlkType)]); for (const blkType of allTypes) { const schemaEntry = ensureBlock(schema, blkType); @@ -57,11 +73,9 @@ export class CloudSettingsStore { setParam(typeBlock, 'contentHash', { type: 'string', value: entry.contentHash }); } } - return meta; } - /** Load a stored `ContainerBlk` (`version:i` + `content { ... }`) for `cln_get_general_blk`. */ loadContainer(userId: string, blkType: string): BlkBlock | undefined { if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined; const blkPath = this.#blkPath(userId, blkType); @@ -73,7 +87,6 @@ export class CloudSettingsStore { } } - /** Persist a single uploaded `ContainerBlk` and update `meta.json` atomically. */ saveUpload(userId: string, upload: ParsedGblkUpload): boolean { if (!isValidUserId(userId) || !isSupportedGeneralBlkType(upload.blkType)) return false; const meta = this.#loadMeta(userId); @@ -90,7 +103,6 @@ export class CloudSettingsStore { return true; } - /** Persist a batch of uploads from `cln_bulk_set_gblk`. */ saveBulkUploads(userId: string, uploads: ReadonlyArray): number { let savedCount = 0; for (const upload of uploads) { @@ -126,8 +138,6 @@ export class CloudSettingsStore { } } -const SUPPORTED_BLK_TYPE_SET: ReadonlySet = new Set(GENERAL_BLK_TYPES); - function isValidUserId(userId: string): boolean { return /^\d+$/.test(userId); } diff --git a/packages/local-service/src/game-data/datasets/clan-economy.ts b/packages/local-service/src/game-data/datasets/clan-economy.ts index 769a1d1..29b48d7 100644 --- a/packages/local-service/src/game-data/datasets/clan-economy.ts +++ b/packages/local-service/src/game-data/datasets/clan-economy.ts @@ -1,7 +1,9 @@ /** - * Dataset: squadron creation, edit, member-limit upgrade, and battalion-to-normal upgrade - * prices from char.vromfs.bin config/warpoints.blk (implementation notes; scripts/clans/clanType.nut). + * Dataset: squadron creation, edit, member-limit upgrade, battalion-to-normal upgrade prices, + * and free tag decorators from char.vromfs.bin config/warpoints.blk (implementation notes; + * aces.exe 0x906fe0..0x907070; scripts/clans/clanType.nut). */ +import { findBlock, type BlkBlock } from '@wto/blk'; import { numberField } from './blk-fields.ts'; import type { Dataset } from './dataset.ts'; @@ -10,34 +12,58 @@ const WARPOINTS = 'config/warpoints.blk'; export interface ClanEconomy { readonly normalCreateGold: number; readonly normalCreateSilver: number; + readonly normalPrimaryEditGold: number; + readonly normalPrimaryEditSilver: number; + readonly normalSecondaryEditGold: number; + readonly normalSecondaryEditSilver: number; readonly battalionCreateGold: number; readonly battalionCreateSilver: number; readonly battalionPrimaryEditGold: number; readonly battalionPrimaryEditSilver: number; + readonly battalionSecondaryEditGold: number; + readonly battalionSecondaryEditSilver: number; readonly battalionMembersUpgradeGold: number; readonly battalionMembersUpgradeStep: number; readonly battalionMembersUpgradeLimit: number; readonly upgradeBattalionToNormalGold: number; readonly upgradeBattalionToNormalSilver: number; + readonly normalFreeDecorators: readonly string[]; + readonly battalionFreeDecorators: readonly string[]; } export const clanEconomy: Dataset = { id: 'clan-economy', - version: 1, + version: 2, extract: (source) => { const wp = source.readBlk('char.vromfs.bin', WARPOINTS); return { normalCreateGold: numberField(wp, 'clanCreateGoldCost') ?? 2500, normalCreateSilver: numberField(wp, 'clanCreateWPCost') ?? 0, + normalPrimaryEditGold: numberField(wp, 'costGoldPrimaryInfo') ?? 2500, + normalPrimaryEditSilver: numberField(wp, 'costWPPrimaryInfo') ?? 0, + normalSecondaryEditGold: numberField(wp, 'costGoldSecondaryInfo') ?? 0, + normalSecondaryEditSilver: numberField(wp, 'costWPSecondaryInfo') ?? 0, battalionCreateGold: numberField(wp, 'battalionCreateGoldCost') ?? 0, battalionCreateSilver: numberField(wp, 'battalionCreateWPCost') ?? 1_000_000, battalionPrimaryEditGold: numberField(wp, 'battalionCostGoldPrimaryInfo') ?? 0, battalionPrimaryEditSilver: numberField(wp, 'battalionCostWPPrimaryInfo') ?? 1_000_000, + battalionSecondaryEditGold: numberField(wp, 'battalionCostGoldSecondaryInfo') ?? 0, + battalionSecondaryEditSilver: numberField(wp, 'battalionCostWPSecondaryInfo') ?? 0, battalionMembersUpgradeGold: numberField(wp, 'battalionMembersUpgradeCost') ?? 225, battalionMembersUpgradeStep: numberField(wp, 'battalionMembersUpgradeStep') ?? 10, battalionMembersUpgradeLimit: numberField(wp, 'battalionMembersUpgradeLimit') ?? 110, upgradeBattalionToNormalGold: numberField(wp, 'clanUpgradeCostGoldBattalionToNormal') ?? 2500, upgradeBattalionToNormalSilver: numberField(wp, 'clanUpgradeCostWPBattalionToNormal') ?? 0, + normalFreeDecorators: readDecorList(findBlock(wp, 'clanTagDecorators'), ['--', '..', '==', '^^', '[]']), + battalionFreeDecorators: readDecorList(findBlock(wp, 'battalionTagDecorators'), ['**']), }; }, }; + +function readDecorList(block: BlkBlock | undefined, fallback: readonly string[]): readonly string[] { + if (!block) return fallback; + const values = block.params + .filter((p) => p.name === 'decor' && p.value.type === 'string') + .map((p) => (p.value as { type: 'string'; value: string }).value); + return values.length > 0 ? values : fallback; +} diff --git a/packages/local-service/src/game-data/datasets/external-item-sources.ts b/packages/local-service/src/game-data/datasets/external-item-sources.ts index 2ebc9e1..b75d8ba 100644 --- a/packages/local-service/src/game-data/datasets/external-item-sources.ts +++ b/packages/local-service/src/game-data/datasets/external-item-sources.ts @@ -9,6 +9,7 @@ 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 { parseLocalizedCsvMap } from './lang-csv.ts'; import type { LocalizedText } from './unit-names.ts'; export interface MarketplaceDecorCoupon { @@ -41,12 +42,11 @@ const DECOR_FILES: readonly { kind: DecorKind; blkPath: string; csvPath: string export const externalItemSources: Dataset = { 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 }; - }, + extract: (source) => ({ + decorCoupons: DECOR_FILES.flatMap(({ kind, blkPath, csvPath }) => extractDecorCoupons(source, kind, blkPath, csvPath)), + unlockCoupons: extractUnlockCoupons(source), + workshopItemdefIds: [...collectWorkshopIds(source.readBlk('aces.vromfs.bin', 'config/workshop.blk'))].sort((a, b) => a - b), + }), }; function extractDecorCoupons( @@ -55,7 +55,7 @@ function extractDecorCoupons( blkPath: string, csvPath: string, ): MarketplaceDecorCoupon[] { - const locMap = parseCsvNames(source.readText('lang.vromfs.bin', csvPath)); + const locMap = parseLocalizedCsvMap(source.readText('lang.vromfs.bin', csvPath)); const root = source.readBlk('char.vromfs.bin', blkPath); const out: MarketplaceDecorCoupon[] = []; for (const entry of root.blocks) { @@ -73,8 +73,8 @@ function extractDecorCoupons( } 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 menuLoc = parseLocalizedCsvMap(source.readText('lang.vromfs.bin', 'lang/menu.csv')); + const achieveLoc = parseLocalizedCsvMap(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) { @@ -102,55 +102,6 @@ function collectWorkshopIds(block: BlkBlock, out = new Set()): Set { - const lines = csvText.split(/\r?\n/); - const header = parseSemicolonRow(lines[0] ?? ''); - const idIdx = 0; - const enIdx = Math.max(1, header.findIndex((col) => col.includes(''))); - const zhIdx = header.findIndex((col) => col.includes('')); - const hzhIdx = header.findIndex((col) => col.includes('')); - const map = new Map(); - 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()); diff --git a/packages/local-service/src/game-data/datasets/lang-csv.ts b/packages/local-service/src/game-data/datasets/lang-csv.ts new file mode 100644 index 0000000..0709575 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/lang-csv.ts @@ -0,0 +1,57 @@ +/** + * Shared semicolon-separated localization CSV parser for files in `lang.vromfs.bin`. + */ +export interface LocalizedCsvText { + readonly en: string; + readonly zh: string; +} + +export function parseSemicolonCsvRow(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; +} + +/** Strip zero-width word-break spaces Gaijin inserts into CJK localization strings. */ +export function cleanLangText(raw: string): string { + return raw.replace(/\u200b/g, '').trim(); +} + +export function parseLocalizedCsvMap(csvText: string): Map { + const lines = csvText.split(/\r?\n/); + const header = parseSemicolonCsvRow(lines[0] ?? ''); + const enIdx = Math.max(1, header.findIndex((col) => col.includes(''))); + const zhIdx = header.findIndex((col) => col.includes('')); + const hzhIdx = header.findIndex((col) => col.includes('')); + const map = new Map(); + + for (let i = 1; i < lines.length; i += 1) { + const line = lines[i]; + if (!line) continue; + const cols = parseSemicolonCsvRow(line); + const id = cols[0]; + if (!id) continue; + const en = cleanLangText(cols[enIdx] ?? '') || id; + const zh = cleanLangText((zhIdx >= 0 ? cols[zhIdx] : '') || (hzhIdx >= 0 ? cols[hzhIdx] : '') || '') || en; + map.set(id, { en, zh }); + } + return map; +} diff --git a/packages/local-service/src/game-data/datasets/unit-names.ts b/packages/local-service/src/game-data/datasets/unit-names.ts index 4e99bdf..cecf5b6 100644 --- a/packages/local-service/src/game-data/datasets/unit-names.ts +++ b/packages/local-service/src/game-data/datasets/unit-names.ts @@ -5,23 +5,19 @@ * game's own English and Chinese vehicle names without shipping game text with the service. */ import type { Dataset } from './dataset.ts'; +import { cleanLangText, parseSemicolonCsvRow, type LocalizedCsvText } from './lang-csv.ts'; const UNITS_CSV = 'lang/units.csv'; -export interface LocalizedText { - readonly en: string; - readonly zh: string; -} - +export type LocalizedText = LocalizedCsvText; export type UnitNamesMap = Readonly>; export const unitNames: Dataset = { id: 'unit-names', version: 1, extract: (source) => { - const csv = source.readText('lang.vromfs.bin', UNITS_CSV); - const lines = csv.split(/\r?\n/); - const header = parseCsvRow(lines[0] ?? ''); + const lines = source.readText('lang.vromfs.bin', UNITS_CSV).split(/\r?\n/); + const header = parseSemicolonCsvRow(lines[0] ?? ''); const enCol = Math.max(1, header.indexOf('')); const zhCol = header.indexOf(''); const hzhCol = header.indexOf(''); @@ -38,10 +34,10 @@ export const unitNames: Dataset = { const isFull = !isShop && key.endsWith('_0'); if (!isShop && !isFull) continue; - const cols = parseCsvRow(line); - const en = cleanText(cols[enCol] ?? ''); + const cols = parseSemicolonCsvRow(line); + const en = cleanLangText(cols[enCol] ?? ''); if (!en) continue; - const zh = cleanText((hzhCol >= 0 ? cols[hzhCol] : '') || (zhCol >= 0 ? cols[zhCol] : '') || en); + const zh = cleanLangText((hzhCol >= 0 ? cols[hzhCol] : '') || (zhCol >= 0 ? cols[zhCol] : '') || en); const unitId = key.slice(0, isShop ? -5 : -2); if (isShop) shopNames.set(unitId, { en, zh }); else fullNames.set(unitId, { en, zh }); @@ -53,44 +49,3 @@ export const unitNames: Dataset = { return result; }, }; - -function parseCsvRow(line: string): string[] { - const fields: string[] = []; - let i = 0; - while (i < line.length) { - if (line[i] === '"') { - i++; - let value = ''; - while (i < line.length) { - if (line[i] === '"') { - if (line[i + 1] === '"') { - value += '"'; - i += 2; - } else { - i++; - break; - } - } else { - value += line[i]!; - i++; - } - } - fields.push(value); - if (line[i] === ';') i++; - } else { - const next = line.indexOf(';', i); - if (next < 0) { - fields.push(line.slice(i)); - break; - } - fields.push(line.slice(i, next)); - i = next + 1; - } - } - return fields; -} - -function cleanText(raw: string): string { - // Strip zero-width word-break spaces Gaijin inserts into CJK localization strings. - return raw.replace(/\u200b/g, '').trim(); -} diff --git a/packages/local-service/src/inventory/chest-defs.ts b/packages/local-service/src/inventory/chest-defs.ts index c68bab9..114df28 100644 --- a/packages/local-service/src/inventory/chest-defs.ts +++ b/packages/local-service/src/inventory/chest-defs.ts @@ -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], - }; } /** diff --git a/packages/local-service/src/inventory/inventory-rules.ts b/packages/local-service/src/inventory/inventory-rules.ts index 0a7c202..20da8d5 100644 --- a/packages/local-service/src/inventory/inventory-rules.ts +++ b/packages/local-service/src/inventory/inventory-rules.ts @@ -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(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(); - 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; - try { - const raw = JSON.parse(rawText) as Record; - parsed = typeof raw.data === 'object' && raw.data !== null ? (raw.data as Record) : 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; - return [{ - itemid: String(rec.itemid ?? ''), - itemdefid: Number(rec.itemdefid ?? 0), - quantity: Number(rec.quantity ?? 0), - }]; - }); - return { outputItemDefId, quantity, materials }; -} - -export function pickWeighted(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(); - 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(); + const deltaByUid = new Map(); 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(); + 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, +): void { for (let i = 0; i < quantity; i += 1) { const dropDefId = pickWeighted(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' }; diff --git a/packages/local-service/src/inventory/inventory-service.ts b/packages/local-service/src/inventory/inventory-service.ts index ee3c520..d9ac304 100644 --- a/packages/local-service/src/inventory/inventory-service.ts +++ b/packages/local-service/src/inventory/inventory-service.ts @@ -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 } }; } diff --git a/packages/local-service/src/inventory/inventory-wire.ts b/packages/local-service/src/inventory/inventory-wire.ts new file mode 100644 index 0000000..2cacae9 --- /dev/null +++ b/packages/local-service/src/inventory/inventory-wire.ts @@ -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; + try { + const raw = JSON.parse(rawText) as Record; + parsed = typeof raw.data === 'object' && raw.data !== null ? (raw.data as Record) : 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; + return [{ + itemid: String(rec.itemid ?? ''), + itemdefid: Number(rec.itemdefid ?? 0), + quantity: Number(rec.quantity ?? 0), + }]; + }); + return { outputItemDefId, quantity, materials }; +} diff --git a/packages/local-service/src/inventory/marketplace-service.ts b/packages/local-service/src/inventory/marketplace-service.ts index caa2729..926317c 100644 --- a/packages/local-service/src/inventory/marketplace-service.ts +++ b/packages/local-service/src/inventory/marketplace-service.ts @@ -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}`); diff --git a/packages/local-service/src/inventory/recycling-defs.ts b/packages/local-service/src/inventory/recycling-defs.ts index 0b3009c..43bc571 100644 --- a/packages/local-service/src/inventory/recycling-defs.ts +++ b/packages/local-service/src/inventory/recycling-defs.ts @@ -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( diff --git a/packages/local-service/src/inventory/trophy-catalogue.ts b/packages/local-service/src/inventory/trophy-catalogue.ts index 0f2cc48..3e589d1 100644 --- a/packages/local-service/src/inventory/trophy-catalogue.ts +++ b/packages/local-service/src/inventory/trophy-catalogue.ts @@ -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(); 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, diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index 19c312c..63e3088 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -46,16 +46,15 @@ export interface RunningLocalService { export async function startLocalService(options: LocalServiceOptions): Promise { const report = options.report ?? (() => {}); const gameFiles = new GameFiles(options.gameFolder); - // Static data first, before the port opens. + // Static data and stores first, before the port opens. const datasets = new DatasetCache(options.dataFolder, gameFiles, report); const gameModes = new GameModes(datasets.load(multiplayerMissions), datasets.load(shopCountries), report); - const { profiles, research } = setUpProfiles(options.dataFolder, gameFiles, datasets); - gameFiles.releasePacks(); - - // One store for all services: accounts registered at sign-in must be visible everywhere. const accounts = new AccountStore(options.dataFolder); const clans = new ClanStore(options.dataFolder); const cloudSettings = new CloudSettingsStore(options.dataFolder); + const { profiles, research } = setUpProfiles(options.dataFolder, gameFiles, datasets, { accounts, clans }); + gameFiles.releasePacks(); + let matching: MatchingService | undefined; const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' }); diff --git a/packages/local-service/src/profile/client-profile.ts b/packages/local-service/src/profile/client-profile.ts index b64d320..4b84ef5 100644 --- a/packages/local-service/src/profile/client-profile.ts +++ b/packages/local-service/src/profile/client-profile.ts @@ -1,24 +1,19 @@ /** * The profile as the char service hands it to the client: the saved profile plus the - * account data and state the char server keeps outside the profile. + * account data and server clock the char server attaches on the wire. * * charDrivenNick: the client reads the player's nick from this top-level string when it * loads a profile (name looked up at aces.exe 2.61.0.37 0x8fe0aa, value stored at 0x91874d). - * A profile without it clears the nick, and the online initialisation then fails with - * "[CONNECT] nick is empty" and error 0x81110017 (0x164e5cf), as seen in the lab runs. - * The nick belongs to the account, so it is added here rather than kept in the save. * * serverTime:i64: the char server's clock; without it the client * takes the server time as 0 and every expiry and time limit is wrong. */ import { setParam, type BlkBlock } from '@wto/blk'; import type { Account } from '../accounts/account-store.ts'; -import type { ClanStore } from '../clans/clan-store.ts'; import { serverTimeNow } from './server-time.ts'; -export function clientProfile(saved: BlkBlock, account: Account, clans?: ClanStore): BlkBlock { +export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { const profile = structuredClone(saved); - clans?.syncProfile(profile, account); setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick }); setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() }); return profile; diff --git a/packages/local-service/src/profile/player-profiles.ts b/packages/local-service/src/profile/player-profiles.ts index a677e45..f804343 100644 --- a/packages/local-service/src/profile/player-profiles.ts +++ b/packages/local-service/src/profile/player-profiles.ts @@ -2,9 +2,9 @@ * The one way services get a player's profile: the saved one, or a new one that is written * to the save before it is handed out. * - * State that follows from the rest of the profile (statuses, open ranks, earned unlocks: - * research/research-state.ts) is brought up to date every time a profile is handed out or - * changed, and saved with it, so it also follows a game update that changed the data. + * State that follows from the rest of the profile (clan sync, statuses, open ranks, earned + * unlocks: research/research-state.ts) is brought up to date every time a profile is handed + * out or changed, and saved with it, so every action returns a consistent persisted profile. */ import type { BlkBlock } from '@wto/blk'; import type { GameFiles } from '../game-data/game-files.ts'; @@ -13,7 +13,7 @@ import { newProfile } from './new-profile.ts'; import type { StartingContent } from './starting-content.ts'; /** Brings the derived state of a profile up to date, in place. */ -export type ProfileRefresh = (profile: BlkBlock) => void; +export type ProfileRefresh = (profile: BlkBlock, userId: string) => void; export class PlayerProfiles { readonly #saves: SaveStore; @@ -30,7 +30,7 @@ export class PlayerProfiles { profileOf(userId: string): BlkBlock { const profile = this.#saves.loadProfile(userId) ?? newProfile(this.#gameFiles.newAccountTemplate(), this.#startingContent); - this.#refresh(profile); + this.#refresh(profile, userId); this.#saves.saveProfile(userId, profile); return profile; } @@ -50,7 +50,7 @@ export class PlayerProfiles { updateWhen(userId: string, change: (profile: BlkBlock) => boolean): BlkBlock | undefined { const profile = this.profileOf(userId); if (!change(profile)) return undefined; - this.#refresh(profile); + this.#refresh(profile, userId); this.#saves.saveProfile(userId, profile); return profile; } diff --git a/packages/local-service/src/profiles-setup.ts b/packages/local-service/src/profiles-setup.ts index 16a2ede..a260285 100644 --- a/packages/local-service/src/profiles-setup.ts +++ b/packages/local-service/src/profiles-setup.ts @@ -1,21 +1,23 @@ /** * Assemble the players' profiles with the rules they depend on, the same way for the local * service and for the save editor (save-cli.ts): static data from the dataset cache, the - * save store with its format upgrades, and the research and modification state kept up to date - * (expired classic items removed). + * save store with its format upgrades, and clan membership, research, and modification state + * kept up to date and persisted on every read or write. */ +import type { AccountStore } from './accounts/account-store.ts'; +import type { ClanStore } from './clans/clan-store.ts'; import type { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { reserveVehicles } from './game-data/datasets/reserve-vehicles.ts'; import { shopBranches } from './game-data/datasets/shop-branches.ts'; import type { GameFiles } from './game-data/game-files.ts'; +import { removeExpiredItems } from './items/item-expiry.ts'; +import { refreshModuleState } from './modifications/module-state.ts'; import { PlayerProfiles } from './profile/player-profiles.ts'; import { profileUpgrades } from './profile/profile-upgrades.ts'; -import type { StartingContent } from './profile/starting-content.ts'; -import { refreshModuleState } from './modifications/module-state.ts'; -import { removeExpiredItems } from './items/item-expiry.ts'; import { serverTimeNow } from './profile/server-time.ts'; -import { refreshResearchState } from './research/research-state.ts'; +import type { StartingContent } from './profile/starting-content.ts'; import { loadResearchRules, type ResearchRules } from './research/research-rules.ts'; +import { refreshResearchState } from './research/research-state.ts'; import { SaveStore } from './saves/save-store.ts'; export interface ProfileServices { @@ -23,11 +25,26 @@ export interface ProfileServices { readonly research: ResearchRules; } -export function setUpProfiles(dataFolder: string, gameFiles: GameFiles, datasets: DatasetCache): ProfileServices { - const startingContent: StartingContent = { reserveVehicles: datasets.load(reserveVehicles), branches: datasets.load(shopBranches) }; +export interface ProfileSyncContext { + readonly accounts: AccountStore; + readonly clans: ClanStore; +} + +export function setUpProfiles( + dataFolder: string, + gameFiles: GameFiles, + datasets: DatasetCache, + sync?: ProfileSyncContext, +): ProfileServices { + const startingContent: StartingContent = { + reserveVehicles: datasets.load(reserveVehicles), + branches: datasets.load(shopBranches), + }; const research = loadResearchRules(datasets); const saves = new SaveStore(dataFolder, profileUpgrades(startingContent)); - const profiles = new PlayerProfiles(saves, gameFiles, startingContent, (profile) => { + const profiles = new PlayerProfiles(saves, gameFiles, startingContent, (profile, userId) => { + const account = sync?.accounts.byUserId(userId); + if (account && sync) sync.clans.syncProfile(profile, account); refreshResearchState(profile, research); refreshModuleState(profile, research.equipment); removeExpiredItems(profile, serverTimeNow()); diff --git a/packages/local-service/src/research/price-table.ts b/packages/local-service/src/research/price-table.ts index 8b2426c..118e11f 100644 --- a/packages/local-service/src/research/price-table.ts +++ b/packages/local-service/src/research/price-table.ts @@ -165,8 +165,9 @@ function toTrophyDefinitionBlk(trophy: TrophyDefinition): BlkBlock { } function prizeToBlk(prize: TrophyPrize): BlkBlock { - const weightTag = prize.weight >= 25 ? 'high' : prize.weight >= 10 ? 'medium' : 'low'; - const params: BlkParam[] = [{ name: 'weight', value: { type: 'string', value: weightTag } }]; + // calculate_drop_chances (aces.exe 0x95a510 -> 0x95c27c..0x95c28f) checks paramType == TYPE_REAL (3) + // on `weight` (defaulting to 1.0f when non-real) and writes normalized `percent:i` (0..10000). + const params: BlkParam[] = [{ name: 'weight', value: { type: 'real', value: prize.weight } }]; if (prize.kind === 'warpoints') params.push(intParam('warpoints', prize.amount)); else if (prize.kind === 'gold') params.push(intParam('gold', prize.amount)); else if (prize.kind === 'item') { diff --git a/packages/local-service/src/save-cli.ts b/packages/local-service/src/save-cli.ts index 9315150..d77bcb1 100644 --- a/packages/local-service/src/save-cli.ts +++ b/packages/local-service/src/save-cli.ts @@ -4,19 +4,14 @@ * * node packages/local-service/src/save-cli.ts --game --data * --player [--silver ] [--gold ] [--gjn ] [--free-rp ] - * [--give-item [:]]... - * - * --free-rp sets the free research points. --give-item gives classic - * items from config/items.blk, as a reward would; it can be repeated. - * Without any change it only prints the balance. The edit is written to the save; the game - * shows it after its next profile update (any action, or signing in again). + * [--squadron-rp ] [--give-item [:]]... [--give-coupon [:]]... */ import { parseArgs } from 'node:util'; -import { AccountStore } from './accounts/account-store.ts'; +import { AccountStore, type Account } from './accounts/account-store.ts'; import { ClanStore } from './clans/clan-store.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; -import { GameFiles } from './game-data/game-files.ts'; import type { ItemDefinition } from './game-data/datasets/item-catalogue.ts'; +import { GameFiles } from './game-data/game-files.ts'; import { grantItem } from './items/item-grants.ts'; import { availableSquadronRp, clanMembershipOf, setAvailableSquadronRp } from './profile/profile-clan.ts'; import { balanceOf, setGjn, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts'; @@ -26,11 +21,24 @@ 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'; +import type { ResearchRules } from './research/research-rules.ts'; +import type { BlkBlock } from '@wto/blk'; const USAGE = 'usage: save-cli.ts --game --data --player ' + '[--silver ] [--gold ] [--gjn ] [--free-rp ] [--squadron-rp ] ' + '[--give-item [:]]... [--give-coupon [:]]...'; +interface ParsedEdits { + readonly silver: number | undefined; + readonly gold: number | undefined; + readonly gjn: number | undefined; + readonly freeRp: number | undefined; + readonly squadronRp: number | undefined; + readonly gifts: ReadonlyArray<{ readonly item: ItemDefinition; readonly pieces: number }>; + readonly coupons: ReadonlyArray<{ readonly itemdefId: number; readonly quantity: number }>; + readonly hasChanges: boolean; +} + function main(): number { const { values } = parseArgs({ options: { @@ -50,63 +58,85 @@ function main(): number { console.error(USAGE); return 2; } - const silver = optionalAmount(values.silver); - const gold = optionalAmount(values.gold); - const gjn = optionalAmount(values.gjn); - const freeRp = optionalAmount(values['free-rp']); - const squadronRp = optionalAmount(values['squadron-rp']); - if (silver === null || gold === null || gjn === null || freeRp === null || squadronRp === null) { - console.error('--silver, --gold, --gjn, --free-rp and --squadron-rp take a whole number of 0 or more'); - return 2; - } + const accounts = new AccountStore(values.data); const account = accounts.byLogin(values.player) ?? accounts.byUserId(values.player); if (!account) { console.error(`no player "${values.player}" in ${values.data}`); return 1; } + const clans = new ClanStore(values.data); const gameFiles = new GameFiles(values.game); const datasets = new DatasetCache(values.data, gameFiles, () => {}); - const { profiles, research } = setUpProfiles(values.data, gameFiles, datasets); - const gifts: { item: ItemDefinition; pieces: number }[] = []; - for (const request of values['give-item'] ?? []) { + const { profiles, research } = setUpProfiles(values.data, gameFiles, datasets, { accounts, clans }); + + const edits = parseRequestedEdits(values, research); + if (!edits) return 2; + + const now = serverTimeNow(); + const clanEarned = clans.earnedSquadronExpOf(account.userId); + const profile = !edits.hasChanges + ? profiles.profileOf(account.userId) + : profiles.update(account.userId, (saved) => applyEdits(saved, edits, clanEarned, now)); + + printSaveSummary(account, profile, clanEarned, now); + return 0; +} + +function parseRequestedEdits( + values: Record, + research: ResearchRules, +): ParsedEdits | undefined { + const silver = optionalAmount(values.silver as string | undefined); + const gold = optionalAmount(values.gold as string | undefined); + const gjn = optionalAmount(values.gjn as string | undefined); + const freeRp = optionalAmount(values['free-rp'] as string | undefined); + const squadronRp = optionalAmount(values['squadron-rp'] as string | undefined); + if (silver === null || gold === null || gjn === null || freeRp === null || squadronRp === null) { + console.error('--silver, --gold, --gjn, --free-rp and --squadron-rp take a whole number of 0 or more'); + return undefined; + } + + const gifts: Array<{ item: ItemDefinition; pieces: number }> = []; + for (const request of (values['give-item'] as string[] | undefined) ?? []) { const [name = '', piecesText = '1'] = request.split(':'); const item = research.items.item(name); const pieces = optionalAmount(piecesText); if (!item || !pieces) { console.error(`--give-item: no classic item "${name}", or pieces not a whole number of 1 or more`); - return 2; + return undefined; } gifts.push({ item, pieces }); } - const coupons: { itemdefId: number; quantity: number }[] = []; - for (const request of values['give-coupon'] ?? []) { + + const coupons: Array<{ itemdefId: number; quantity: number }> = []; + for (const request of (values['give-coupon'] as string[] | undefined) ?? []) { 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; + return undefined; } coupons.push({ itemdefId, quantity }); } - const changes = silver !== undefined || gold !== undefined || gjn !== undefined || freeRp !== undefined || squadronRp !== undefined || gifts.length > 0 || coupons.length > 0; - const now = serverTimeNow(); - const clanEarned = clans.earnedSquadronExpOf(account.userId); - const profile = !changes - ? profiles.profileOf(account.userId) - : profiles.update(account.userId, (saved) => { - clans.syncProfile(saved, account); - if (silver !== undefined) setSilverLions(saved, silver); - if (gold !== undefined) setGoldenEagles(saved, gold); - if (gjn !== undefined) setGjn(saved, gjn); - if (freeRp !== undefined) setFreeResearchPoints(saved, freeRp); - if (squadronRp !== undefined) setAvailableSquadronRp(saved, squadronRp, clanEarned); - for (const gift of gifts) grantItem(saved, gift.item, gift.pieces, now); - for (const coupon of coupons) grantExternalItem(saved, coupon.itemdefId, coupon.quantity); - }); - clans.syncProfile(profile, account); + + const hasChanges = silver !== undefined || gold !== undefined || gjn !== undefined || freeRp !== undefined || squadronRp !== undefined || gifts.length > 0 || coupons.length > 0; + return { silver, gold, gjn, freeRp, squadronRp, gifts, coupons, hasChanges }; +} + +function applyEdits(saved: BlkBlock, edits: ParsedEdits, clanEarned: number, now: bigint): void { + if (edits.silver !== undefined) setSilverLions(saved, edits.silver); + if (edits.gold !== undefined) setGoldenEagles(saved, edits.gold); + if (edits.gjn !== undefined) setGjn(saved, edits.gjn); + if (edits.freeRp !== undefined) setFreeResearchPoints(saved, edits.freeRp); + if (edits.squadronRp !== undefined) setAvailableSquadronRp(saved, edits.squadronRp, clanEarned); + for (const gift of edits.gifts) grantItem(saved, gift.item, gift.pieces, now); + for (const coupon of edits.coupons) grantExternalItem(saved, coupon.itemdefId, coupon.quantity); +} + +function printSaveSummary(account: Account, profile: BlkBlock, clanEarned: number, now: bigint): void { const balance = balanceOf(profile); const premiumDays = remainingPremiumDays(profile, now); const premiumNote = premiumDays > 0 ? `, premium: ${premiumDays}d` : ''; @@ -118,10 +148,8 @@ function main(): number { 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; } -/** undefined when not given, null when not a valid amount. */ function optionalAmount(text: string | undefined): number | undefined | null { if (text === undefined) return undefined; return /^\d+$/.test(text) && Number.isSafeInteger(Number(text)) ? Number(text) : null; diff --git a/packages/local-service/src/store/redeem-codes.ts b/packages/local-service/src/store/redeem-codes.ts index a979917..cbe3918 100644 --- a/packages/local-service/src/store/redeem-codes.ts +++ b/packages/local-service/src/store/redeem-codes.ts @@ -1,8 +1,8 @@ /** - * Redeem codes (implementation notes section G; implementation notes): - * - PREMIUM-D / VIP-D (e.g. PREMIUM-7D, PREMIUM-30D, PREMIUM-365D): adds days of - * Premium Account (1..3650 days); - * - WTO-GJN- / GJN- (e.g. WTO-GJN-100, WTO-GJN-1000): adds GJN (1..100000); + * Redeem & offline cheat codes (implementation notes section G; implementation notes; + * local verification): + * - PREMIUM-D / WTO-PREM-D / PREM-D / VIP-D (1..3650 days): adds days of Premium Account; + * - WTO-GJN- / GJN- (1..1000000): offline player cheat code adding GJN; * - WTO-STARTER (once per save): grants 7 days of Premium Account, 1,000 Golden Eagles and 100 GJN. */ import type { BlkBlock } from '@wto/blk'; @@ -22,28 +22,9 @@ export function redeemStoreCode(profile: BlkBlock, rawCode: string, nowFiletime: return { ok: false, reason: 'INVALID_CODE', message: { en: 'Enter a redeem code.', zh: '请输入兑换码。' } }; } - if (code === 'WTO-STARTER') { - if (hasEntitlement(profile, STARTER_ENTITLEMENT, nowFiletime)) { - return { - ok: false, - reason: 'ALREADY_REDEEMED', - message: { en: 'This starter code has already been redeemed on this save.', zh: '当前存档已使用过该新手礼包兑换码。' }, - }; - } - recordEntitlementPurchase(profile, STARTER_ENTITLEMENT); - extendPremiumAccount(profile, 7, nowFiletime); - addGoldenEagles(profile, 1_000); - setGjn(profile, balanceOf(profile).gjn + 100); - return { - ok: true, - message: { - en: 'Redeemed WTO-STARTER: +7d Premium Account, +1,000 Golden Eagles, +100 GJN.', - zh: '兑换成功:高级账户 +7 天、金鹰 +1,000、GJN +100。', - }, - }; - } + if (code === 'WTO-STARTER') return redeemStarterCode(profile, nowFiletime); - const premiumMatch = /^(?:PREMIUM|PREM|VIP)-(\d{1,4})D$/.exec(code); + const premiumMatch = /^(?:PREMIUM|WTO-PREM|PREM|VIP)-(\d{1,4})D$/.exec(code); if (premiumMatch) { const days = Number(premiumMatch[1]); if (days >= 1 && days <= 3_650) { @@ -58,10 +39,10 @@ export function redeemStoreCode(profile: BlkBlock, rawCode: string, nowFiletime: } } - const gjnMatch = /^(?:WTO-GJN|GJN)-(\d{1,6})$/.exec(code); + const gjnMatch = /^(?:WTO-GJN|GJN)-(\d{1,7})$/.exec(code); if (gjnMatch) { const amount = Number(gjnMatch[1]); - if (amount >= 1 && amount <= 100_000) { + if (amount >= 1 && amount <= 1_000_000) { setGjn(profile, balanceOf(profile).gjn + amount); return { ok: true, @@ -77,8 +58,29 @@ export function redeemStoreCode(profile: BlkBlock, rawCode: string, nowFiletime: ok: false, reason: 'INVALID_CODE', message: { - en: 'Unknown redeem code. Examples: PREMIUM-7D, PREMIUM-30D, PREMIUM-365D, WTO-GJN-100, WTO-STARTER.', - zh: '无效的兑换码。可用示例:PREMIUM-7D、PREMIUM-30D、PREMIUM-365D、WTO-GJN-100、WTO-STARTER。', + en: 'Unknown redeem code. Examples: PREMIUM-7D, PREMIUM-30D, WTO-PREM-90D, WTO-GJN-100, WTO-STARTER.', + zh: '无效的兑换码。可用示例:PREMIUM-7D、PREMIUM-30D、WTO-PREM-90D、WTO-GJN-100、WTO-STARTER。', + }, + }; +} + +function redeemStarterCode(profile: BlkBlock, nowFiletime: bigint): RedeemOutcome { + if (hasEntitlement(profile, STARTER_ENTITLEMENT, nowFiletime)) { + return { + ok: false, + reason: 'ALREADY_REDEEMED', + message: { en: 'This starter code has already been redeemed on this save.', zh: '当前存档已使用过该新手礼包兑换码。' }, + }; + } + recordEntitlementPurchase(profile, STARTER_ENTITLEMENT); + extendPremiumAccount(profile, 7, nowFiletime); + addGoldenEagles(profile, 1_000); + setGjn(profile, balanceOf(profile).gjn + 100); + return { + ok: true, + message: { + en: 'Redeemed WTO-STARTER: +7d Premium Account, +1,000 Golden Eagles, +100 GJN.', + zh: '兑换成功:高级账户 +7 天、金鹰 +1,000、GJN +100。', }, }; } diff --git a/packages/local-service/src/store/store-catalogue.ts b/packages/local-service/src/store/store-catalogue.ts index 4ed50a0..a70928e 100644 --- a/packages/local-service/src/store/store-catalogue.ts +++ b/packages/local-service/src/store/store-catalogue.ts @@ -6,7 +6,6 @@ * Pure domain catalogue: protocol-layer DataBlock serialization for `cln_get_entitlements_price_ex` * lives in `char/actions/store-actions.ts`. */ -import { EXTRA_STORE_BUNDLE_GUID_MAP } from '@wto/build'; import type { StoreBundleGuids } from '../game-data/datasets/store-bundles.ts'; import type { LocalizedText, UnitNamesMap } from '../game-data/datasets/unit-names.ts'; import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; @@ -157,7 +156,7 @@ function buildPremiumGoldProducts(): StoreProduct[] { function buildPremiumGjnProducts(bundleGuids: StoreBundleGuids): StoreProduct[] { return PREMIUM_GJN_TIERS.map((tier) => { - const guid = bundleGuids[tier.id] ?? EXTRA_STORE_BUNDLE_GUID_MAP[tier.id]; + const guid = bundleGuids[tier.id]; return { id: tier.id, kind: 'premium-gjn', diff --git a/packages/local-service/src/store/store-purchase.ts b/packages/local-service/src/store/store-purchase.ts index b5d0757..20db566 100644 --- a/packages/local-service/src/store/store-purchase.ts +++ b/packages/local-service/src/store/store-purchase.ts @@ -16,12 +16,14 @@ export function buyGoldEntitlement( profile: BlkBlock, catalogue: StoreCatalogue, entitlementId: string, - offeredGoldCost: number | undefined, + offeredGoldCost: number, nowFiletime: bigint, ): RuleOutcome { const product = catalogue.byId(entitlementId); - if (!product || product.goldCost === undefined) return refused('BAD_PARAMS'); - if (offeredGoldCost !== undefined && offeredGoldCost !== product.goldCost) return refused('PRICE_CHANGED'); + if (!product || product.goldCost === undefined || !Number.isSafeInteger(offeredGoldCost) || offeredGoldCost < 0) { + return refused('BAD_PARAMS'); + } + if (offeredGoldCost !== product.goldCost) return refused('PRICE_CHANGED'); const price = { silverLions: 0, goldenEagles: product.goldCost }; if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');