refactor(repo)!: move apps, shared packages, and patch definitions

Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.

BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 03:20:54 +08:00
1 parent 9c813ccf7d
commit 930ea07630
476 files changed
+275 -251

No files matched your search

+253
View File
@@ -0,0 +1,253 @@
/**
* DataBlock serializers for squadron (clan) char actions:
* - `cln_clan_get` full clan info (`clanInfoTable.nut` + `0xeb9f60`)
* - `cln_clan_get_leaderboard` /
* `cln_clan_find_by_prefix` leaderboard / search rows (`clansModalHandler.nut`)
* - `cln_clans_list_get_short_info` short info blocks (`clanInfo.nut`)
* - `cln_clan_get_log` paginated clan event log (`clanRequests.nut`)
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { ClanTuning } from './clan-tuning.ts';
import {
totalPeriodActivityOf,
type ClanLogEntry,
type ClanMemberRecord,
type ClanRecord,
type ClanStats,
} from './clan-types.ts';
const CLAN_STAT_KEYS: ReadonlyArray<keyof ClanStats> = [
'dr_era5_arc', 'dr_era5_hist', 'dr_era5_sim',
'akills_arc', 'akills_hist', 'akills_sim',
'gkills_arc', 'gkills_hist', 'gkills_sim',
'deaths_arc', 'deaths_hist', 'deaths_sim',
'ftime_arc', 'ftime_hist', 'ftime_sim',
];
const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray<keyof Omit<ClanLogEntry, 'id' | 'ev' | 'timeSec' | 'uId' | 'uN'>> = [
'uid', 'nick', 'role', 'old', 'new', 'name', 'type', 'tag', 'desc', 'slogan', 'region', 'announcement', 'status', 'comments',
];
export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): BlkBlock {
const todayDay = Math.floor(nowSec / 86400);
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, historyDepthDays } = tuning.activity;
return {
name: '',
params: [
str('_id', clan.id),
str('name', clan.name),
str('tag', clan.tag),
str('lastPaidTag', clan.lastPaidTag),
str('slogan', clan.slogan),
str('desc', clan.desc),
str('region', clan.region),
str('announcement', clan.announcement),
int('cdate', clan.cdateSec),
str('status', clan.status),
int('mlimit', clan.mlimit),
str('changed_by_nick', clan.changedByNick),
str('changed_by_uid', clan.changedByUid),
int('changed_time', clan.changedTimeSec),
int('mspent', clan.mspent),
int('region_last_updated', clan.regionLastUpdatedSec),
str('type', clan.type),
bool('autoaccept', clan.autoaccept),
int('maxActivityPerPeriod', maxPerPeriod),
int('maxClanActivity', squadronRpPerFullPeriod),
int('rewardPeriodDays', rewardPeriodDays),
bool('expRewardEnabled', true),
int('historyDepth', historyDepthDays),
int('nextRewardDayId', todayDay + rewardPeriodDays),
],
blocks: [
buildAstatBlock(clan, tuning),
buildMembershipReqBlock(clan),
...clan.members.map(memberToBlk),
buildMemberRatingsBlock(clan),
{ name: 'activity', params: [], blocks: clan.members.map((m) => buildMemberActivityBlock(m, todayDay)) },
...clan.candidates.map((c) => ({
name: 'candidates',
params: [str('uid', c.uid), str('nick', c.nick), str('comment', c.comment), int('date', c.dateSec)],
blocks: [],
})),
...clan.blacklist.map((b) => ({
name: 'blacklist',
params: [
str('uid', b.uid), str('nick', b.nick),
str('initiator_uid', b.initiatorUid), str('initiator_nick', b.initiatorNick),
str('comments', b.comments), int('date', b.dateSec),
],
blocks: [],
})),
...clan.bestRewards.map((r) => ({
name: 'clanBestRewards',
params: [str('seasonName', r.seasonName), str('title', r.title)],
blocks: [],
})),
],
};
}
export function toClanLeaderboardRowBlk(clan: ClanRecord, pos: number, tuning: ClanTuning): BlkBlock {
const periodAct = totalPeriodActivityOf(clan, tuning);
return {
name: 'clan',
params: [
str('_id', clan.id),
str('name', clan.name),
str('tag', clan.tag),
str('slogan', clan.slogan),
str('desc', clan.desc),
str('region', clan.region),
str('type', clan.type),
str('status', clan.status),
bool('autoaccept', clan.autoaccept),
int('mlimit', clan.mlimit),
int('members_cnt', clan.members.length),
int('pos', pos),
int('activity', periodAct),
int('clan_activity_by_periods', periodAct),
...statParams(clan.stats),
],
blocks: [buildAstatBlock(clan, tuning), buildMembershipReqBlock(clan)],
};
}
export function toClanShortInfoBlk(clan: ClanRecord, tuning: ClanTuning): BlkBlock {
return {
name: clan.id,
params: [
str('_id', clan.id),
str('name', clan.name),
str('tag', clan.tag),
str('type', clan.type),
str('slogan', clan.slogan),
str('region', clan.region),
str('status', clan.status),
int('mlimit', clan.mlimit),
int('members_cnt', clan.members.length),
],
blocks: [buildAstatBlock(clan, tuning)],
};
}
export function toClanLogBlk(
clan: ClanRecord,
count: number,
eventsFilter?: string,
lastMark?: string,
): BlkBlock {
const allowedEvents = eventsFilter
? new Set(eventsFilter.split(';').map((s) => s.trim()).filter(Boolean))
: undefined;
const maxId = lastMark && /^\d+$/.test(lastMark) ? Number(lastMark) : Number.MAX_SAFE_INTEGER;
const sorted = [...clan.logs]
.filter((entry) => entry.id < maxId && (!allowedEvents || allowedEvents.has(entry.ev)))
.sort((a, b) => b.id - a.id);
const page = sorted.slice(0, Math.max(1, count));
const nextMark = sorted.length > page.length ? String(page[page.length - 1]!.id) : '';
return {
name: '',
params: nextMark ? [str('lastMark', nextMark)] : [],
blocks: page.map(logEntryToBlk),
};
}
function memberToBlk(m: ClanMemberRecord): BlkBlock {
return {
name: 'members',
params: [str('uid', m.uid), str('nick', m.nick), int('role', m.role), int('date', m.joinDateSec)],
blocks: [],
};
}
function buildMemberRatingsBlock(clan: ClanRecord): BlkBlock {
return {
name: 'member_ratings',
params: [],
blocks: clan.members.map((m) => ({
name: m.uid,
params: [int('dr_era5_arc', m.ratingArc), int('dr_era5_hist', m.ratingHist), int('dr_era5_sim', m.ratingSim)],
blocks: [],
})),
};
}
function buildMembershipReqBlock(clan: ClanRecord): BlkBlock {
return clan.membershipReqBlk
? { ...structuredClone(clan.membershipReqBlk), name: 'membership_req' }
: { name: 'membership_req', params: [], blocks: [] };
}
function logEntryToBlk(entry: ClanLogEntry): BlkBlock {
const params: BlkParam[] = [
str('ev', entry.ev),
int('time', entry.timeSec),
str('uId', entry.uId),
str('uN', entry.uN),
];
for (const key of OPTIONAL_LOG_STRING_KEYS) {
const val = entry[key];
if (val !== undefined) params.push(str(key, val));
}
return { name: 'log', params, blocks: [] };
}
function buildAstatBlock(clan: ClanRecord, tuning: ClanTuning): BlkBlock {
const periodAct = totalPeriodActivityOf(clan, tuning);
return {
name: 'astat',
params: [
int('activity', periodAct),
int('clan_activity_by_periods', periodAct),
...statParams(clan.stats),
],
blocks: [],
};
}
function statParams(stats: ClanStats): BlkParam[] {
return CLAN_STAT_KEYS.map((key) => int(key, stats[key]));
}
function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock {
const periods = member.periods.length > 0
? member.periods
: [{ day: todayDay, activity: member.curActivity, exp: 20000 }];
return {
name: member.uid,
params: [
int('cur', member.curActivity),
int('total', member.totalActivity),
int('activity', member.curActivity),
int('exp', member.earnedSquadronExp),
],
blocks: [
{ name: 'history', params: periods.map((p) => int(String(p.day), p.activity)), blocks: [] },
{
name: 'expActivity',
params: [],
blocks: periods.map((p) => ({
name: String(p.day),
params: [int('activity', p.activity), int('exp', p.exp), int('expRewardBase', p.exp), int('expBoost', 0)],
blocks: [],
})),
},
],
};
}
function str(name: string, value: string): BlkParam {
return { name, value: { type: 'string', value } };
}
function int(name: string, value: number): BlkParam {
return { name, value: { type: 'int', value: Math.trunc(value) } };
}
function bool(name: string, value: boolean): BlkParam {
return { name, value: { type: 'bool', value } };
}
+296
View File
@@ -0,0 +1,296 @@
/**
* Squadron lifecycle rules: creation, info editing, upgrading from training battalion to
* full squadron, member-limit expansion, requirements, and disbanding.
*/
import type { BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import type { ClanEconomy } from '../game-data/datasets/clan-economy.ts';
import type { ClanKind } from '../profile/profile-clan.ts';
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 type { ClanTuning } from './clan-tuning.ts';
import {
ClanRole,
type ClanMemberRecord,
type ClanRecord,
} from './clan-types.ts';
export interface StoredClansState {
nextClanId: number;
clans: ClanRecord[];
}
export interface CreateClanInput {
readonly name: string;
readonly tag: string;
readonly slogan: string;
readonly region: string;
readonly desc: string;
readonly announcement: string;
readonly type: ClanKind;
readonly offered: Price;
}
export interface ClanInfoChanges {
readonly name?: string | undefined;
readonly tag?: string | undefined;
readonly desc?: string | undefined;
readonly slogan?: string | undefined;
readonly announcement?: string | undefined;
readonly region?: string | undefined;
readonly status?: 'open' | 'closed' | undefined;
}
export function stripClanDecorators(tag: string): string {
return tag.replace(/^[^\p{L}\p{N}_]+|[^\p{L}\p{N}_]+$/gu, '');
}
export function createClanInState(
state: StoredClansState,
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
tuning: ClanTuning,
input: CreateClanInput,
nowSec: number,
): RuleOutcome {
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 || !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 }
: { silverLions: economy.normalCreateSilver, goldenEagles: economy.normalCreateGold };
if (input.offered.silverLions !== expectedPrice.silverLions || input.offered.goldenEagles !== expectedPrice.goldenEagles) {
return refused('PRICE_CHANGED');
}
if (!canAfford(profile, expectedPrice)) return refused('NOT_ENOUGH_MONEY');
clearCandidateEverywhere(state.clans, account.userId);
pay(profile, expectedPrice);
state.clans.unshift(buildCreatedClanRecord(String(state.nextClanId++), account, name, tag, input, nowSec, tuning));
return ACCEPTED;
}
export function editClanInfoInState(
clans: readonly ClanRecord[],
clan: ClanRecord | undefined,
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
changes: ClanInfoChanges,
nowSec: number,
): RuleOutcome {
if (!clan || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE');
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');
const editPrice = computeInfoEditPrice(clan, economy, nextName, nextTag, changes);
if (!canAfford(profile, editPrice)) return refused('NOT_ENOUGH_MONEY');
pay(profile, editPrice);
applyInfoFieldUpdates(clan, account, nextName, nextTag, changes, nowSec);
return ACCEPTED;
}
export function upgradeClanToNormalInState(
clans: readonly ClanRecord[],
clan: ClanRecord | undefined,
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
tuning: ClanTuning,
input: { readonly tag: string; readonly desc: string; readonly announcement: string },
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 };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
clan.type = 'normal';
clan.mlimit = tuning.memberLimits.normal;
clan.tag = nextTag;
clan.lastPaidTag = nextTag;
clan.desc = input.desc;
clan.announcement = input.announcement;
clan.changedByUid = account.userId;
clan.changedByNick = account.nick;
clan.changedTimeSec = nowSec;
appendClanLog(clan, {
ev: 'upgrade', timeSec: nowSec, uId: account.userId, uN: account.nick,
type: 'normal', tag: clan.tag, desc: clan.desc,
});
return ACCEPTED;
}
export function upgradeMembersLimitInState(
clan: ClanRecord | undefined,
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
nowSec: number,
): RuleOutcome {
if (!clan || clan.type !== 'battalion' || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE');
if (clan.mlimit >= economy.battalionMembersUpgradeLimit) return refused('NOT_AVAILABLE');
const price: Price = { silverLions: 0, goldenEagles: economy.battalionMembersUpgradeGold };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
const oldLimit = clan.mlimit;
pay(profile, price);
clan.mlimit = Math.min(economy.battalionMembersUpgradeLimit, clan.mlimit + economy.battalionMembersUpgradeStep);
clan.mspent += economy.battalionMembersUpgradeGold;
appendClanLog(clan, {
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,
name: string,
tag: string,
input: CreateClanInput,
nowSec: number,
tuning: ClanTuning,
): ClanRecord {
const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning);
const leader: ClanMemberRecord = {
uid: account.userId,
nick: account.nick,
role: ClanRole.LEADER,
joinDateSec: nowSec,
curActivity: tuning.activity.maxPerPeriod,
totalActivity: periods.reduce((s, p) => s + p.activity, 0),
earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0),
ratingArc: tuning.playerRating.founder.arc,
ratingHist: tuning.playerRating.founder.hist,
ratingSim: tuning.playerRating.founder.sim,
periods,
};
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' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal,
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,
akills_arc: 0, akills_hist: 0, akills_sim: 0,
gkills_arc: 0, gkills_hist: 0, gkills_sim: 0,
deaths_arc: 0, deaths_hist: 0, deaths_sim: 0,
ftime_arc: 0, ftime_hist: 0, ftime_sim: 0,
},
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,
}],
bestRewards: [],
};
}
+292
View File
@@ -0,0 +1,292 @@
/**
* Squadron membership, candidate moderation, role changes, blacklist, and event-log helpers
*.
*/
import type { ClanTuning } from './clan-tuning.ts';
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,
isAssignableClanRole,
roleNameOf,
type ClanLogEntry,
type ClanRecord,
} from './clan-types.ts';
export interface MembershipRequestQuery {
readonly clanId?: string | undefined;
readonly clanName?: string | undefined;
readonly clanTag?: string | undefined;
readonly cancel?: boolean | undefined;
readonly comment?: string | undefined;
}
export function hasClanManageRight(clan: ClanRecord, userId: string): boolean {
const role = clan.members.find((m) => m.uid === userId)?.role;
return role === ClanRole.LEADER || role === ClanRole.DEPUTY || role === ClanRole.CLANADMIN;
}
export function hasClanOfficerRight(clan: ClanRecord, userId: string): boolean {
const role = clan.members.find((m) => m.uid === userId)?.role;
return role === ClanRole.LEADER || role === ClanRole.DEPUTY || role === ClanRole.OFFICER || role === ClanRole.CLANADMIN;
}
export function appendClanLog(clan: ClanRecord, entry: Omit<ClanLogEntry, 'id'>): void {
const nextId = clan.logs.reduce((max, item) => Math.max(max, item.id), 0) + 1;
clan.logs.push({ id: nextId, ...entry });
}
export function clearCandidateEverywhere(clans: readonly ClanRecord[], userId: string): void {
for (const clan of clans) {
clan.candidates = clan.candidates.filter((c) => c.uid !== userId);
}
}
export function addMemberToClan(
clan: ClanRecord,
uid: string,
nick: string,
role: number,
initiatorUid: string,
initiatorNick: string,
nowSec: number,
tuning: ClanTuning,
): void {
if (clan.members.some((m) => m.uid === uid)) return;
const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning);
clan.members.push({
uid,
nick,
role,
joinDateSec: nowSec,
curActivity: tuning.activity.maxPerPeriod,
totalActivity: periods.reduce((s, p) => s + p.activity, 0),
earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0),
ratingArc: tuning.playerRating.joiner.arc,
ratingHist: tuning.playerRating.joiner.hist,
ratingSim: tuning.playerRating.joiner.sim,
periods,
});
appendClanLog(clan, {
ev: 'add',
timeSec: nowSec,
uId: initiatorUid,
uN: initiatorNick,
uid,
nick,
role: roleNameOf(role),
});
}
export function requestOrCancelMembershipInState(
clans: readonly ClanRecord[],
targetClan: ClanRecord | undefined,
alreadyInClan: boolean,
account: Account,
query: MembershipRequestQuery,
nowSec: number,
tuning: ClanTuning,
): { readonly outcome: RuleOutcome; readonly mutated: boolean } {
if (query.cancel || (!query.clanId && !query.clanName && !query.clanTag) || query.clanId === '-1') {
clearCandidateEverywhere(clans, account.userId);
return { outcome: ACCEPTED, mutated: true };
}
if (alreadyInClan) return { outcome: refused('NOT_AVAILABLE'), mutated: false };
if (!targetClan || targetClan.status === 'closed' || targetClan.members.length >= targetClan.mlimit) {
return { outcome: refused('NOT_AVAILABLE'), mutated: false };
}
if (targetClan.blacklist.some((b) => b.uid === account.userId)) {
return { outcome: refused('NOT_AVAILABLE'), mutated: false };
}
clearCandidateEverywhere(clans, account.userId);
if (targetClan.autoaccept) {
addMemberToClan(targetClan, account.userId, account.nick, ClanRole.REGULAR, account.userId, account.nick, nowSec, tuning);
} else {
targetClan.candidates.push({
uid: account.userId,
nick: account.nick,
comment: query.comment ?? '',
dateSec: nowSec,
});
}
return { outcome: ACCEPTED, mutated: true };
}
export function leaveClanInState(
clans: ClanRecord[],
clan: ClanRecord | undefined,
account: Account,
nowSec: number,
): { readonly outcome: RuleOutcome; readonly nextClans: ClanRecord[] } {
if (!clan) return { outcome: refused('NOT_AVAILABLE'), nextClans: clans };
clan.members = clan.members.filter((m) => m.uid !== account.userId);
if (clan.members.length === 0) {
return { outcome: ACCEPTED, nextClans: clans.filter((c) => c.id !== clan.id) };
}
if (!clan.members.some((m) => m.role === ClanRole.LEADER)) {
clan.members[0] = { ...clan.members[0]!, role: ClanRole.LEADER };
}
appendClanLog(clan, {
ev: 'rem',
timeSec: nowSec,
uId: account.userId,
uN: account.nick,
uid: account.userId,
nick: account.nick,
});
return { outcome: ACCEPTED, nextClans: clans };
}
export function acceptCandidateOnClan(
allClans: readonly ClanRecord[],
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
targetNick: string,
role: number,
nowSec: number,
tuning: ClanTuning,
): boolean {
if (!clan || !hasClanOfficerRight(clan, initiator.userId) || clan.members.length >= clan.mlimit) return false;
const cand = clan.candidates.find((c) => c.uid === targetUid);
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, tuning);
return true;
}
export function rejectCandidateOnClan(
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
comments: string,
nowSec: number,
): boolean {
if (!clan || !hasClanOfficerRight(clan, initiator.userId)) return false;
const cand = clan.candidates.find((c) => c.uid === targetUid);
if (!cand) return false;
clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid);
appendClanLog(clan, {
ev: 'reject_candidate',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: cand.uid,
nick: cand.nick,
comments,
});
return true;
}
export function dismissMemberOnClan(
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
comments: string,
nowSec: number,
): boolean {
if (!clan || !hasClanOfficerRight(clan, initiator.userId) || targetUid === initiator.userId) return false;
const member = clan.members.find((m) => m.uid === targetUid);
if (!member || member.role === ClanRole.LEADER) return false;
clan.members = clan.members.filter((m) => m.uid !== targetUid);
appendClanLog(clan, {
ev: 'rem',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: member.uid,
nick: member.nick,
comments,
});
return true;
}
export function changeMemberRoleOnClan(
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
newRole: number,
nowSec: number,
): boolean {
if (!clan || !hasClanManageRight(clan, initiator.userId) || targetUid === initiator.userId) return false;
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,
uId: initiator.userId,
uN: initiator.nick,
uid: prev.uid,
nick: prev.nick,
old: roleNameOf(prev.role),
new: roleNameOf(newRole),
});
return true;
}
export function editBlacklistOnClan(
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
targetNick: string,
add: boolean,
comments: string,
nowSec: number,
): boolean {
if (!clan || !hasClanOfficerRight(clan, initiator.userId)) return false;
if (add) {
clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid);
const resolvedNick = targetNick || `Pilot_${targetUid}`;
if (!clan.blacklist.some((b) => b.uid === targetUid)) {
clan.blacklist.push({
uid: targetUid,
nick: resolvedNick,
initiatorUid: initiator.userId,
initiatorNick: initiator.nick,
comments,
dateSec: nowSec,
});
}
appendClanLog(clan, {
ev: 'add_to_blacklist',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: targetUid,
nick: resolvedNick,
comments,
});
} else {
const existing = clan.blacklist.find((b) => b.uid === targetUid);
clan.blacklist = clan.blacklist.filter((b) => b.uid !== targetUid);
appendClanLog(clan, {
ev: 'remove_from_blacklist',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: targetUid,
nick: existing?.nick ?? targetNick,
comments,
});
}
return true;
}
+83
View File
@@ -0,0 +1,83 @@
/**
* Read-only search and leaderboard queries over the local squadron directory
*.
*/
import type { ClanTuning } from './clan-tuning.ts';
import { stripClanDecorators } from './clan-lifecycle.ts';
import { totalPeriodActivityOf, type ClanRecord } from './clan-types.ts';
export interface LeaderboardQuery {
readonly start: number;
readonly count: number;
readonly sortField: string;
readonly clanId?: string | undefined;
readonly prefix?: string | undefined;
readonly filterOpen?: boolean | undefined;
readonly filterNotFull?: boolean | undefined;
readonly filterAutoAccept?: boolean | undefined;
}
export function findClanInList(
clans: readonly ClanRecord[],
query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined },
): ClanRecord | undefined {
if (query.clanId && query.clanId !== '-1') {
const byId = clans.find((c) => c.id === query.clanId);
if (byId) return byId;
}
if (query.clanName) {
const lower = query.clanName.toLowerCase();
const byName = clans.find((c) => c.name.toLowerCase() === lower);
if (byName) return byName;
}
if (query.clanTag) {
const lower = query.clanTag.toLowerCase();
const byTag = clans.find((c) => c.tag.toLowerCase() === lower);
if (byTag) return byTag;
}
return undefined;
}
export function queryClanLeaderboard(
clans: readonly ClanRecord[],
query: LeaderboardQuery,
tuning: ClanTuning,
): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
const sorted = [...clans].sort((a, b) => metricOf(b, query.sortField, tuning) - metricOf(a, query.sortField, tuning));
const withPos = sorted.map((clan, index) => ({ clan, pos: index }));
if (query.clanId && query.clanId !== '-1') return withPos.filter((entry) => entry.clan.id === query.clanId);
const prefix = query.prefix?.trim().toLowerCase() ?? '';
const filtered = withPos.filter(({ clan }) => {
if (query.filterOpen && clan.status === 'closed') return false;
if (query.filterNotFull && clan.members.length >= clan.mlimit) return false;
if (query.filterAutoAccept && !clan.autoaccept) return false;
if (prefix) {
const strippedTag = stripClanDecorators(clan.tag).toLowerCase();
if (!clan.name.toLowerCase().includes(prefix) && !clan.tag.toLowerCase().includes(prefix) && !strippedTag.includes(prefix)) {
return false;
}
}
return true;
});
const start = Math.max(0, query.start);
const count = query.count > 0 ? query.count : 20;
return filtered.slice(start, start + count);
}
function metricOf(clan: ClanRecord, sortField: string, tuning: ClanTuning): number {
switch (sortField) {
case 'activity':
case 'clan_activity_by_periods':
return totalPeriodActivityOf(clan, tuning);
case 'members_cnt':
return clan.members.length;
case 'dr_era5_arc':
return clan.stats.dr_era5_arc;
case 'dr_era5_sim':
return clan.stats.dr_era5_sim;
case 'dr_era5_hist':
default:
return clan.stats.dr_era5_hist;
}
}
+80
View File
@@ -0,0 +1,80 @@
/**
* The preset squadron directory written on first creation of `<data>/clans.json`
* (implementation notes section I; implementation notes), and the activity periods a member
* starts with. Both are tuning (tuning/clans.jsonc).
*/
import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts';
import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts';
const SECONDS_PER_DAY = 86400;
export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY;
return tuning.presetClans.clans.map((spec) => buildSeededClan(spec, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning));
}
/** The activity periods a member starts with: startingPeriods periods, each with the given activity and the squadron RP it earns. */
export function buildDefaultPeriods(todayDay: number, tuning: ClanTuning, periodActivity = tuning.activity.maxPerPeriod): ClanActivityPeriodEntry[] {
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, startingPeriods } = tuning.activity;
const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod);
return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp }));
}
function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanRecord {
const members = spec.members.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning));
const leader = spec.members[0]!;
return {
id: spec.id,
name: spec.name,
tag: spec.tag,
lastPaidTag: spec.tag,
type: spec.type,
slogan: spec.slogan,
desc: spec.desc,
announcement: spec.announcement,
region: spec.region,
status: 'open',
autoaccept: spec.autoAccept,
mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal,
mspent: 0,
cdateSec,
changedByUid: leader.uid,
changedByNick: leader.nick,
changedTimeSec: cdateSec,
regionLastUpdatedSec: 0,
stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats },
members,
candidates: [],
blacklist: [],
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: [],
};
}
function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord {
const periods = buildDefaultPeriods(todayDay, tuning, npc.activity);
const { step, floor } = tuning.presetClans.memberRating;
return {
uid: npc.uid,
nick: npc.nick,
role: npc.role,
joinDateSec: cdateSec + idx * tuning.presetClans.memberJoinSpacingMinutes * 60,
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(floor.arc, spec.rating.arc - idx * step.arc),
ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist),
ratingSim: Math.max(floor.sim, spec.rating.sim - idx * step.sim),
periods,
};
}
+260
View File
@@ -0,0 +1,260 @@
/**
* Persistent local squadron (clan) directory & state store (`<data>/clans.json`),
* delegating queries, lifecycle, and membership rules to `clan-queries.ts`,
* `clan-lifecycle.ts`, and `clan-membership.ts` (implementation notes; implementation notes I).
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import type { ClanEconomy } from '../game-data/datasets/clan-economy.ts';
import {
clanMembershipOf,
clearClanMembership,
setClanMembership,
setPendingClanRequest,
syncStoredClanEarnedExp,
} from '../profile/profile-clan.ts';
import type { RuleOutcome } from '../research/rule-outcome.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import {
createClanInState,
disbandClanInState,
editClanInfoInState,
upgradeClanToNormalInState,
upgradeMembersLimitInState,
type ClanInfoChanges,
type CreateClanInput,
type StoredClansState,
} from './clan-lifecycle.ts';
import {
acceptCandidateOnClan,
changeMemberRoleOnClan,
dismissMemberOnClan,
editBlacklistOnClan,
hasClanManageRight,
leaveClanInState,
rejectCandidateOnClan,
requestOrCancelMembershipInState,
type MembershipRequestQuery,
} from './clan-membership.ts';
import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts';
import { createDefaultClans } from './clan-seeds.ts';
import type { ClanTuning } from './clan-tuning.ts';
import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts';
export type { LeaderboardQuery };
export class ClanStore {
readonly #filePath: string;
/** tuning/clans.jsonc; the clan actions serialize clan info with it too. */
readonly tuning: ClanTuning;
#state: StoredClansState;
constructor(dataFolder: string, tuning: ClanTuning) {
this.#filePath = join(dataFolder, 'clans.json');
this.tuning = tuning;
this.#state = this.#loadOrSeed();
}
#loadOrSeed(): StoredClansState {
if (existsSync(this.#filePath)) {
const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState;
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed;
}
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) };
this.#save(seeded);
return seeded;
}
#save(state: StoredClansState = this.#state): void {
writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2));
}
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan;
}
byId(clanId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.id === clanId);
}
findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined {
return findClanInList(this.#state.clans, query);
}
clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
for (const clan of this.#state.clans) {
const member = clan.members.find((m) => m.uid === userId);
if (member) return { clan, member };
}
return undefined;
}
pendingRequestOfUser(userId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId));
}
earnedSquadronExpOf(userId: string): number {
return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0;
}
npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
for (const clan of this.#state.clans) {
const member = clan.members.find((m) => m.uid === uid && m.isNpc);
if (member) return { clan, member };
}
return undefined;
}
syncProfile(profile: BlkBlock, account: Account): void {
const found = this.clanOfUser(account.userId);
if (found) {
const { clan, member } = found;
if (member.nick !== account.nick) {
const idx = clan.members.findIndex((m) => m.uid === account.userId);
if (idx >= 0) {
clan.members[idx] = { ...member, nick: account.nick };
this.#save();
}
}
setClanMembership(profile, { clanId: clan.id, clanTag: clan.tag, clanName: clan.name, clanType: clan.type, role: member.role });
syncStoredClanEarnedExp(profile, member.earnedSquadronExp);
return;
}
const pending = this.pendingRequestOfUser(account.userId);
if (pending) {
setPendingClanRequest(profile, { clanId: pending.id, clanTag: pending.tag, clanName: pending.name });
} else if (clanMembershipOf(profile).clanId !== '-1' || clanMembershipOf(profile).requestedClanId !== '-1') {
clearClanMembership(profile);
}
}
queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
return queryClanLeaderboard(this.#state.clans, query, this.tuning);
}
createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome {
const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
editClanInfo(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, changes: ClanInfoChanges, nowSec = nowSeconds()): RuleOutcome {
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);
}
return outcome;
}
upgradeClanToNormal(
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
clanId: string,
input: { readonly tag: string; readonly desc: string; readonly announcement: string },
nowSec = nowSeconds(),
): RuleOutcome {
const outcome = upgradeClanToNormalInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
upgradeMembersLimit(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, nowSec = nowSeconds()): RuleOutcome {
const outcome = upgradeMembersLimitInState(this.#resolveClan(clanId, account.userId), profile, account, economy, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
setMembershipRequirements(clanId: string, account: Account, reqBlk: BlkBlock | undefined, autoaccept: boolean): boolean {
const clan = this.#resolveClan(clanId, account.userId);
if (!clan || !hasClanManageRight(clan, account.userId)) return false;
clan.autoaccept = autoaccept;
if (reqBlk) clan.membershipReqBlk = structuredClone(reqBlk);
else delete clan.membershipReqBlk;
this.#save();
return true;
}
requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome {
const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning);
if (res.mutated) {
this.#save();
this.syncProfile(profile, account);
}
return res.outcome;
}
leaveClan(profile: BlkBlock, account: Account, nowSec = nowSeconds()): RuleOutcome {
const res = leaveClanInState(this.#state.clans, this.clanOfUser(account.userId)?.clan, account, nowSec);
if (res.outcome.ok) {
this.#state.clans = res.nextClans;
this.#save();
clearClanMembership(profile);
}
return res.outcome;
}
disbandClan(profile: BlkBlock, account: Account, clanId?: string): RuleOutcome {
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.#state.clans, this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, role, nowSec, this.tuning)) return false;
this.#save();
return true;
}
rejectCandidate(initiator: Account, clanId: string | undefined, targetUid: string, comments: string, nowSec = nowSeconds()): boolean {
if (!rejectCandidateOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, comments, nowSec)) return false;
this.#save();
return true;
}
dismissMember(initiator: Account, targetUid: string, comments: string, nowSec = nowSeconds()): boolean {
if (!dismissMemberOnClan(this.clanOfUser(initiator.userId)?.clan, initiator, targetUid, comments, nowSec)) return false;
this.#save();
return true;
}
changeMemberRole(initiator: Account, targetUid: string, newRole: number, nowSec = nowSeconds()): boolean {
if (!changeMemberRoleOnClan(this.clanOfUser(initiator.userId)?.clan, initiator, targetUid, newRole, nowSec)) return false;
this.#save();
return true;
}
editBlacklist(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, add: boolean, comments: string, nowSec = nowSeconds()): boolean {
if (!editBlacklistOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, add, comments, nowSec)) return false;
this.#save();
return true;
}
setBestRewards(clanId: string, initiatorUserId: string, rewards: readonly ClanBestReward[]): boolean {
const clan = this.byId(clanId);
if (!clan || !hasClanManageRight(clan, initiatorUserId)) return false;
clan.bestRewards = [...rewards];
this.#save();
return true;
}
}
function nowSeconds(): number {
return Math.floor(Date.now() / 1000);
}
+132
View File
@@ -0,0 +1,132 @@
/** Typed content of tuning/clans.jsonc. */
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
import { roleCodeFromString, type ClanStats } from './clan-types.ts';
/** The clan statistics a preset clan starts with; the per-mode ratings (dr_era5_*) come from each clan's rating. */
export type PresetClanStats = Omit<ClanStats, 'dr_era5_arc' | 'dr_era5_hist' | 'dr_era5_sim'>;
const STAT_KEYS: readonly (keyof PresetClanStats)[] = [
'akills_arc', 'akills_hist', 'akills_sim', 'gkills_arc', 'gkills_hist', 'gkills_sim',
'deaths_arc', 'deaths_hist', 'deaths_sim', 'ftime_arc', 'ftime_hist', 'ftime_sim',
];
export interface ModeTriple {
readonly arc: number;
readonly hist: number;
readonly sim: number;
}
export interface PresetMember {
readonly uid: string;
readonly nick: string;
readonly role: number;
readonly title: string;
readonly icon: string;
readonly unit: string;
readonly activity: number;
}
export interface PresetClan {
readonly id: string;
readonly tag: string;
readonly name: string;
readonly type: 'normal' | 'battalion';
readonly slogan: string;
readonly desc: string;
readonly announcement: string;
readonly region: string;
readonly autoAccept: boolean;
readonly createdAfterDays: number;
readonly rating: ModeTriple;
readonly members: readonly PresetMember[];
}
export interface ClanTuning {
readonly activity: {
readonly maxPerPeriod: number;
readonly squadronRpPerFullPeriod: number;
readonly rewardPeriodDays: number;
readonly historyDepthDays: number;
readonly startingPeriods: number;
};
readonly memberLimits: { readonly normal: number; readonly battalionInitial: number };
readonly leaderboard: { readonly activityMultiplier: number; readonly maxActivity: number };
readonly firstNewClanId: number;
readonly playerRating: { readonly founder: ModeTriple; readonly joiner: ModeTriple };
readonly presetClans: {
readonly createdDaysAgo: number;
readonly memberJoinSpacingMinutes: number;
readonly stats: PresetClanStats;
readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple };
readonly clans: readonly PresetClan[];
};
}
export function readClanTuning(file: TuningReader): ClanTuning {
const activity = file.object('activity');
const limits = file.object('memberLimits');
const leaderboard = file.object('leaderboard');
const preset = file.object('presetClans');
const stats = preset.object('stats');
const rating = preset.object('memberRating');
return {
activity: {
maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }),
squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }),
rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }),
historyDepthDays: activity.int('historyDepthDays', { min: 1 }),
startingPeriods: activity.int('startingPeriods', { min: 0 }),
},
memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) },
leaderboard: { activityMultiplier: leaderboard.number('activityMultiplier', { min: 0 }), maxActivity: leaderboard.int('maxActivity', { min: 0 }) },
firstNewClanId: file.int('firstNewClanId', { min: 1 }),
playerRating: { founder: triple(file.object('playerRating').object('founder')), joiner: triple(file.object('playerRating').object('joiner')) },
presetClans: {
createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }),
memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }),
stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats,
memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) },
clans: preset.list('clans', readPresetClan),
},
};
}
function readPresetClan(entry: TuningReader): PresetClan {
const type = entry.string('type');
if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`);
const members = entry.list('members', readPresetMember);
if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`);
return {
id: entry.string('id'),
tag: entry.string('tag'),
name: entry.string('name'),
type,
slogan: entry.string('slogan'),
desc: entry.string('desc'),
announcement: entry.string('announcement'),
region: entry.string('region'),
autoAccept: entry.bool('autoAccept'),
createdAfterDays: entry.int('createdAfterDays', { min: 0 }),
rating: triple(entry.object('rating')),
members,
};
}
function readPresetMember(member: TuningReader): PresetMember {
const roleName = member.string('role');
const role = roleCodeFromString(roleName);
if (role === undefined) throw new TuningError(`tuning file clans.jsonc: unknown member role "${roleName}"`);
return {
uid: member.string('uid'),
nick: member.string('nick'),
role,
title: member.string('title'),
icon: member.string('icon'),
unit: member.string('unit'),
activity: member.int('activity', { min: 0 }),
};
}
function triple(entry: TuningReader): ModeTriple {
return { arc: entry.int('arc'), hist: entry.int('hist'), sim: entry.int('sim') };
}
+182
View File
@@ -0,0 +1,182 @@
/**
* Types, binary enum constants, and shared squadron domain constants
*.
*/
import type { ClanTuning } from './clan-tuning.ts';
import type { BlkBlock } from '@wto/blk';
import type { ClanKind } from '../profile/profile-clan.ts';
/** Exact `ECMR_*` role codes registered at aces.exe 0x2986a0..0x298802 (table 0x7ba87e8). */
export const ClanRole = {
LEADER: 1,
OFFICER: 2,
REGULAR: 3,
CLANADMIN: 4,
DEPUTY: 5,
SERGEANT: 6,
} as const;
export type ClanRoleCode = (typeof ClanRole)[keyof typeof ClanRole];
export function roleNameOf(role: number): string {
switch (role) {
case ClanRole.LEADER:
return 'LEADER';
case ClanRole.DEPUTY:
return 'DEPUTY';
case ClanRole.OFFICER:
return 'OFFICER';
case ClanRole.SERGEANT:
return 'SERGEANT';
default:
return 'REGULAR';
}
}
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;
}
/** The period activity shown on the leaderboard (tuning/clans.jsonc leaderboard). */
export function totalPeriodActivityOf(clan: ClanRecord, tuning: ClanTuning): number {
const sum = clan.members.reduce((acc, m) => acc + m.curActivity, 0);
return Math.min(tuning.leaderboard.maxActivity, Math.round(sum * tuning.leaderboard.activityMultiplier));
}
export interface ClanStats {
readonly dr_era5_arc: number;
readonly dr_era5_hist: number;
readonly dr_era5_sim: number;
readonly akills_arc: number;
readonly akills_hist: number;
readonly akills_sim: number;
readonly gkills_arc: number;
readonly gkills_hist: number;
readonly gkills_sim: number;
readonly deaths_arc: number;
readonly deaths_hist: number;
readonly deaths_sim: number;
readonly ftime_arc: number;
readonly ftime_hist: number;
readonly ftime_sim: number;
}
export interface ClanActivityPeriodEntry {
readonly day: number;
readonly activity: number;
readonly exp: number;
}
export interface ClanMemberRecord {
readonly uid: string;
readonly nick: string;
readonly role: number;
readonly joinDateSec: number;
readonly isNpc?: boolean;
readonly npcTitle?: string;
readonly npcPilotIcon?: string;
readonly npcFrame?: string;
readonly npcShowcaseUnit?: string;
readonly curActivity: number;
readonly totalActivity: number;
readonly earnedSquadronExp: number;
readonly ratingArc: number;
readonly ratingHist: number;
readonly ratingSim: number;
readonly periods: readonly ClanActivityPeriodEntry[];
}
export interface ClanCandidateRecord {
readonly uid: string;
readonly nick: string;
readonly comment: string;
readonly dateSec: number;
}
export interface ClanBlacklistEntry {
readonly uid: string;
readonly nick: string;
readonly initiatorUid: string;
readonly initiatorNick: string;
readonly comments: string;
readonly dateSec: number;
}
export interface ClanLogEntry {
readonly id: number;
readonly ev: 'create' | 'info' | 'upgrade' | 'add' | 'rem' | 'role' | 'upgrade_members' | 'reject_candidate' | 'add_to_blacklist' | 'remove_from_blacklist';
readonly timeSec: number;
readonly uId: string;
readonly uN: string;
readonly uid?: string;
readonly nick?: string;
readonly role?: string;
readonly old?: string;
readonly new?: string;
readonly name?: string;
readonly type?: string;
readonly tag?: string;
readonly desc?: string;
readonly slogan?: string;
readonly region?: string;
readonly announcement?: string;
readonly status?: string;
readonly comments?: string;
}
export interface ClanBestReward {
readonly seasonName: string;
readonly title: string;
}
export interface ClanRecord {
id: string;
name: string;
tag: string;
lastPaidTag: string;
type: ClanKind;
slogan: string;
desc: string;
announcement: string;
region: string;
status: 'open' | 'closed';
autoaccept: boolean;
mlimit: number;
mspent: number;
cdateSec: number;
changedByUid: string;
changedByNick: string;
changedTimeSec: number;
regionLastUpdatedSec: number;
stats: ClanStats;
members: ClanMemberRecord[];
candidates: ClanCandidateRecord[];
blacklist: ClanBlacklistEntry[];
logs: ClanLogEntry[];
bestRewards: ClanBestReward[];
membershipReqBlk?: BlkBlock;
}