fix: types

This commit is contained in:
TrèsAbhi committed 2024-09-07 21:45:00 -05:00
1 parent 9ae8b0ac49
commit 3c80a43435
255 files changed
+797 -838

No files matched your search

@@ -1,3 +1,5 @@
import { ShellDefinition, ShellType } from '@blitzkit/core';
export function canSplash(type: ShellDefinition['type']): type is ShellType.HE {
return type === ShellType.HE;
}
@@ -1,13 +1,16 @@
import {
Hierarchy,
Sc2ReadStream,
ScgReadStream,
VertexAttribute,
} from '@blitzkit/core';
import { Accessor, Document, Node, Scene } from '@gltf-transform/core';
import { times } from 'lodash';
import { Hierarchy, Sc2ReadStream } from '../streams/sc2';
import { ScgReadStream } from '../streams/scg';
import { VertexAttribute } from '../streams/scpg';
import { readDVPLFile } from '../../../../scripts/src/core/blitz/readDVPLFile';
import {
vertexAttributeGLTFName,
vertexAttributeGltfVectorSizes,
} from './extractModel/constants';
import { readDVPLFile } from './readDVPLFile';
export async function extractArmor(data: string, fileName: string) {
const sc2Path = `${data}/3d/Tanks/CollisionMeshes/${fileName}.sc2.dvpl`;
@@ -1,5 +1,4 @@
import { vertexAttributeVectorSizes } from '../../streams/scg';
import { VertexAttribute } from '../../streams/scpg';
import { VertexAttribute, vertexAttributeVectorSizes } from '@blitzkit/core';
export const vertexAttributeGLTFName: Partial<Record<VertexAttribute, string>> =
{
@@ -1,13 +1,17 @@
import {
Hierarchy,
Sc2ReadStream,
ScgReadStream,
Textures,
VertexAttribute,
} from '@blitzkit/core';
import { Document, Material, Node, Scene } from '@gltf-transform/core';
import { times } from 'lodash';
import { dirname } from 'path';
import { Matrix4, Quaternion, Vector3, Vector4Tuple } from 'three';
import { readDVPLFile } from '../../../../../scripts/src/core/blitz/readDVPLFile';
import { readTexture } from '../../blitzkit/readTexture';
import { TextureMutation } from '../../blitzkit/readTexture/constants';
import { Hierarchy, Sc2ReadStream, Textures } from '../../streams/sc2';
import { ScgReadStream } from '../../streams/scg';
import { VertexAttribute } from '../../streams/scpg';
import { readDVPLFile } from '../readDVPLFile';
import {
vertexAttributeGLTFName,
vertexAttributeGltfVectorSizes,
@@ -1,6 +1,5 @@
import { assertSecret } from '@blitzkit/core';
import { assertSecret, Region } from '@blitzkit/core';
import { EventManager } from '@blitzkit/core/src/blitzkit/eventManager';
import { Region } from '../../constants/regions';
import { patientFetch } from '../blitzkit/patientFetch';
const RETRY_ERRORS = ['REQUEST_LIMIT_EXCEEDED', 'SOURCE_NOT_AVAILABLE'];
@@ -73,7 +72,9 @@ export default function fetchBlitz<Data extends object>(
return new Promise<Data>((resolve) => {
queue.push({
url: `https://api.wotblitz.${region}/wotb/${path}/?${Object.entries({
application_id: assertSecret(process.env.WARGAMING_APPLICATION_ID),
application_id: assertSecret(
process.env.NEXT_PUBLIC_WARGAMING_APPLICATION_ID,
),
...params,
})
.filter(([_, value]) => value !== undefined)
@@ -1,5 +1,5 @@
import calculateWN8 from '../statistics/calculateWN8';
import { BlitzStats } from '../statistics/compositeStats/constants';
import { BlitzStats } from '@blitzkit/core';
import calculateWN8 from '@blitzkit/core/src/statistics/calculateWN8';
export type Stat = keyof ReturnType<typeof generateStats>;
@@ -1,4 +1,4 @@
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
import fetchBlitz from './fetchBlitz';
import { normalizeIds } from './normalizeIds';
@@ -1,5 +1,4 @@
import { Region } from '../../constants/regions';
import { BlitzStats } from '../statistics/compositeStats/constants';
import { BlitzStats, Region } from '@blitzkit/core';
import fetchBlitz, { FetchBlitzParams } from './fetchBlitz';
import { normalizeIds } from './normalizeIds';
@@ -1,4 +1,4 @@
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
import fetchBlitz from './fetchBlitz';
import { normalizeIds } from './normalizeIds';
@@ -1,4 +1,4 @@
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
import fetchBlitz from './fetchBlitz';
import { normalizeIds } from './normalizeIds';
@@ -1,4 +1,4 @@
import { LEAGUES } from '../../constants/leagues';
import { LEAGUES } from '@blitzkit/core';
export function getLeagueFromScore(score: number) {
return LEAGUES.find(({ minScore }) => score >= minScore)!;
@@ -1,5 +1,5 @@
import { RatingInfo } from '../../commands/ratingLeaderboard';
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
import { RatingInfo } from '../../../../bot/src/commands/ratingLeaderboard';
import { context } from '../blitzkit/context';
import { patientFetch } from '../blitzkit/patientFetch';
import regionToRegionSubdomain from './regionToRegionSubdomain';
@@ -1,5 +1,8 @@
import { LeagueTop, RatingPlayer } from '../../commands/ratingLeaderboard';
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
import {
LeagueTop,
RatingPlayer,
} from '../../../../bot/src/commands/ratingLeaderboard';
import { context } from '../blitzkit/context';
import { patientFetch } from '../blitzkit/patientFetch';
import regionToRegionSubdomain from './regionToRegionSubdomain';
@@ -1,5 +1,5 @@
import { RatingNeighbors } from '../../commands/ratingLeaderboard';
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
import { RatingNeighbors } from '../../../../bot/src/commands/ratingLeaderboard';
import { patientFetch } from '../blitzkit/patientFetch';
import { withCORSProxy } from '../blitzkit/withCORSProxy';
import regionToRegionSubdomain from './regionToRegionSubdomain';
@@ -1,5 +1,4 @@
import { Region } from '../../constants/regions';
import { TanksStats } from '../../types/tanksStats';
import { Region, TanksStats } from '@blitzkit/core';
import fetchBlitz, { FetchBlitzParams } from './fetchBlitz';
export default async function getTankStats(
@@ -1,6 +1,4 @@
import { Region } from '../../constants/regions';
import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID';
import { idToRegion } from './idToRegion';
import { Region, assertSecret, idToRegion } from '@blitzkit/core';
export async function isValidBlitzId(id: number, token?: string) {
let region: Region;
@@ -12,9 +10,9 @@ export async function isValidBlitzId(id: number, token?: string) {
}
const json = await fetch(
`https://api.wotblitz.${region}/wotb/account/info/?account_id=${
id
}&application_id=${WARGAMING_APPLICATION_ID}${
`https://api.wotblitz.${region}/wotb/account/info/?account_id=${id}&application_id=${assertSecret(
process.env.NEXT_PUBLIC_WARGAMING_APPLICATION_ID,
)}${
token === undefined ? '' : `&access_token=${token}`
}&fields=account_id%2C-account_id`,
).then(
@@ -1,6 +0,0 @@
import { readDVPLFile } from './readDVPLFile';
export async function readBase64DVPL(file: string) {
const buffer = await readDVPLFile(file);
return buffer.toString('base64');
}
@@ -1,60 +0,0 @@
import { crc32 } from 'crc';
import { decompressBlock } from 'lz4js';
/**
* Thanks Maddoxkkm! Modified heavily to be modern.
* https://github.com/Maddoxkkm/dvpl_converter/
*/
export function readDVPL(buffer: Buffer) {
const footerBuffer = buffer.subarray(buffer.length - 20, buffer.length);
if (
footerBuffer.toString('utf8', 16, 20) !== 'DVPL' ||
footerBuffer.length !== 20
) {
throw new SyntaxError('Invalid DVPL footer');
}
const footerData = {
oSize: footerBuffer.readUInt32LE(0),
cSize: footerBuffer.readUInt32LE(4),
crc32: footerBuffer.readUInt32LE(8),
type: footerBuffer.readUInt32LE(12),
};
const targetBlock = buffer.subarray(0, buffer.length - 20);
if (targetBlock.length !== footerData.cSize) {
throw new RangeError('DVPL size mismatch');
}
if (crc32(targetBlock) !== footerData.crc32) {
throw new TypeError('DVPL CRC32 mismatch');
}
if (footerData.type === 0) {
if (!(footerData.oSize === footerData.cSize && footerData.type === 0)) {
throw new RangeError('DVPL type and size mismatch');
}
return targetBlock;
} else if (footerData.type === 1 || footerData.type === 2) {
const source = new Uint8Array(targetBlock);
const destination = new Uint8Array(footerData.oSize);
const decompressedSize = decompressBlock(
source,
destination,
0,
source.length,
0,
);
if (decompressedSize !== footerData.oSize) {
throw new RangeError(
`Decompressed DVPL size mismatch (${decompressedSize} vs ${footerData.oSize})`,
);
}
return Buffer.from(destination);
} else {
throw new SyntaxError('Unknown DVPL format');
}
}
@@ -1,6 +0,0 @@
import { readFile } from 'fs/promises';
import { readDVPL } from './readDVPL';
export async function readDVPLFile(file: string) {
return readDVPL(await readFile(file));
}
@@ -1,6 +0,0 @@
import { readDVPLFile } from './readDVPLFile';
export async function readStringDVPL(file: string) {
const buffer = await readDVPLFile(file);
return buffer.toString();
}
@@ -1,9 +0,0 @@
import { XMLParser } from 'fast-xml-parser';
import { readStringDVPL } from './readStringDVPL';
export async function readXMLDVPL<Type>(file: string) {
const parser = new XMLParser();
const xml = await readStringDVPL(file);
return parser.parse(xml) as Type;
}
@@ -1,7 +0,0 @@
import { readFile } from 'fs/promises';
import { parse } from 'yaml';
export async function readYAML<Type>(file: string) {
const yaml = (await readFile(file)).toString();
return parse(yaml) as Type;
}
@@ -1,8 +0,0 @@
import { parse } from 'yaml';
import { readStringDVPL } from './readStringDVPL';
export async function readYAMLDVPL<Type>(file: string) {
const yaml = await readStringDVPL(file);
return parse(yaml) as Type;
}
@@ -1,7 +1,7 @@
import { Region, RegionSubdomain } from '../../constants/regions';
import { Region, RegionSubdomain } from "@blitzkit/core";
export default function regionSubdomainToRegion(
regionDomain: RegionSubdomain,
): Region {
return regionDomain === 'na' ? 'com' : regionDomain;
return regionDomain === 'na' ? 'com' : regionDomain;
}
@@ -1,4 +1,4 @@
import { Region, RegionSubdomain } from '../../constants/regions';
import { Region, RegionSubdomain } from "@blitzkit/core";
export default function regionToRegionSubdomain(
regionDomain: Region,
@@ -1,11 +1,10 @@
import { tankDefinitions, tankNames } from '@blitzkit/core';
import { Locale } from 'discord.js';
import { go } from 'fuzzysort';
import markdownEscape from 'markdown-escape';
import { tankNamesTechTreeOnly } from '../../../../bot/src/core/discord/autocompleteTanks';
import { translator } from '../../../../bot/src/core/localization/translator';
import { UserError } from '../../hooks/userError';
import { tankDefinitions } from '../blitzkit/tankDefinitions';
import { tankNames } from '../blitzkit/tankDefinitions/tankNames';
import { tankNamesTechTreeOnly } from '../discord/autocompleteTanks';
import { translator } from '../localization/translator';
export default async function resolveTankId(
tank: string | number,
@@ -1,5 +1,5 @@
import { Region } from '../../constants/regions';
import { ClanList } from '../../types/clanList';
import { Region } from '@blitzkit/core';
import { ClanList } from '../../../../bot/src/types/clanList';
import fetchBlitz from './fetchBlitz';
export default async function searchClansAcrossRegions(
@@ -1,4 +1,4 @@
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
import { context } from '../blitzkit/context';
import regionToRegionSubdomain from './regionToRegionSubdomain';
@@ -1,4 +1,4 @@
import { Region } from '../../../constants/regions';
import { Region } from '@blitzkit/core';
import fetchBlitz from '../fetchBlitz';
import { usernamePattern } from './constants';
@@ -1,4 +1,4 @@
import { NATION_IDS } from '../../constants/nations';
import { NATION_IDS } from "@blitzkit/core";
export function toUniqueId(nation: string, id: number) {
return (id << 8) + (NATION_IDS[nation] << 4) + 1;
@@ -1,5 +1,5 @@
import { tankDefinitions } from '@blitzkit/core';
import { resolveAncestry } from './resolveAncestry';
import { tankDefinitions } from './tankDefinitions';
export async function buildTechTreeLine(start: number, end: number) {
const awaitedTankDefinitions = await tankDefinitions;
@@ -1,17 +0,0 @@
import { assertSecret } from '../../../packages/core/src/blitzkit/assertSecret';
import { ASSETS_REPO } from '../../constants/assets';
import commitMultipleFiles, { FileChange } from './commitMultipleFiles';
export async function commitAssets(message: string, changes: FileChange[]) {
console.log(`Committing ${message}...`);
if (changes.length === 0) return;
await commitMultipleFiles(
'tresabhi',
ASSETS_REPO,
assertSecret(process.env.NEXT_PUBLIC_ASSET_BRANCH),
`${message} - ${new Date().toDateString()}`,
changes,
);
}
@@ -1,63 +0,0 @@
import ProgressBar from 'progress';
import { GithubChangeBlob, createBlob } from './createBlob';
import { octokit } from './octokit';
export interface FileChange {
path: string;
content: string;
encoding: 'utf-8' | 'base64';
}
export default async function commitMultipleFiles(
owner: string,
repo: string,
branch: string,
message: string,
changes: FileChange[],
) {
const latestCommitSha = (
await octokit.git.getRef({
owner,
repo,
ref: `heads/${branch}`,
})
).data.object.sha;
const treeSha = (
await octokit.git.getCommit({
owner,
repo,
commit_sha: latestCommitSha,
})
).data.tree.sha;
const blobs: GithubChangeBlob[] = [];
const bar = new ProgressBar('Blobs :bar', changes.length);
for (const changeIndexString in changes) {
const changeIndex = parseInt(changeIndexString);
const change = changes[changeIndex];
const createdBlob = await createBlob(owner, repo, change);
blobs.push(createdBlob!);
bar.tick();
}
const { data: treeData } = await octokit.git.createTree({
owner,
repo,
base_tree: treeSha,
tree: blobs,
});
const { data: newCommitData } = await octokit.git.createCommit({
owner,
repo,
message,
tree: treeData.sha,
parents: [latestCommitSha],
});
await octokit.git.updateRef({
owner,
repo,
ref: `heads/${branch}`,
sha: newCommitData.sha,
force: true,
});
}
@@ -1,5 +1,5 @@
import { throttle } from 'lodash';
import { FileChange } from './commitMultipleFiles';
import { FileChange } from '../../../../scripts/src/core/github/commitMultipleFiles';
import { octokit } from './octokit';
export interface GithubChangeBlob {
@@ -1,35 +0,0 @@
import { times } from 'lodash';
import { decompress } from 'lz4js';
import ProgressBar from 'progress';
import { DidsReadStream } from '../streams/dids';
import { asset } from './asset';
import { DiscoveredIdsDefinitions } from './discoveredIdDefinitions';
export async function fetchPreDiscoveredIds() {
const idChunks: number[][] = [];
const manifest = (await fetch(asset('ids/manifest.json')).then((response) =>
response.json(),
)) as DiscoveredIdsDefinitions;
const bar = new ProgressBar(
`Fetching ${manifest.count.toLocaleString()} ids in ${manifest.chunks} chunks :bar`,
manifest.chunks,
);
bar.render();
await Promise.all(
times(manifest.chunks, async (chunkIndex) => {
const preDiscovered = await fetch(
asset(`ids/${chunkIndex}.dids.lz4`),
).then(async (response) => {
const buffer = await response.arrayBuffer();
const decompressed = decompress(new Uint8Array(buffer)).buffer;
return new DidsReadStream(decompressed as ArrayBuffer).dids();
});
idChunks.push(preDiscovered);
bar.tick();
}),
);
return idChunks.sort((a, b) => a[0] - b[0]).flat();
}
@@ -1,8 +1,11 @@
import {
StatFilters,
tankDefinitions,
Tier,
TIER_ROMAN_NUMERALS,
} from '@blitzkit/core';
import { Locale } from 'discord.js';
import { translator } from '../localization/translator';
import { StatFilters } from '../statistics/filterStats';
import { Tier, tankDefinitions } from './tankDefinitions';
import { TIER_ROMAN_NUMERALS } from './tankDefinitions/constants';
import { translator } from '../../../../bot/src/core/localization/translator';
export async function filtersToDescription(
{ nation, tier, tankType, treeType, tank }: StatFilters,
@@ -1,4 +1,4 @@
import { usersDatabase } from '../../databases/users';
import { usersDatabase } from '@blitzkit/core';
export async function flagUserActivity(blitzId: number) {
await usersDatabase.user.upsert({
@@ -1,4 +1,4 @@
import { ASSETS_REPO } from '../../constants/assets';
import { assertSecret } from '@blitzkit/core';
import getRatingInfo from '../blitz/getRatingInfo';
interface GitHubTrees {
@@ -17,7 +17,9 @@ export async function getArchivedLatestSeasonNumber() {
if (ratingInfo.detail) {
const regionsURL = (
(await fetch(
`https://api.github.com/repos/tresabhi/${ASSETS_REPO}/git/trees/main`,
`https://api.github.com/repos/tresabhi/${assertSecret(
process.env.NEXT_PUBLIC_ASSET_REPO,
)}/git/trees/main`,
).then((response) => response.json())) as GitHubTrees
).tree.find(({ path }) => path === 'regions')!.url;
const comURL = (
@@ -1,7 +1,6 @@
import { Region, asset } from '@blitzkit/core';
import { superDecompress } from '@blitzkit/core/src/blitzkit/superDecompress';
import { RatingInfo } from '../../commands/ratingLeaderboard';
import { Region } from '../../constants/regions';
import { asset } from './asset';
import { RatingInfo } from '../../../../bot/src/commands/ratingLeaderboard';
const cache: Record<
Region,
@@ -1,6 +1,9 @@
import { Region } from '../../constants/regions';
import { BkrlDiscriminatedEntries, BkrlReadStream } from '../streams/bkrl';
import { asset } from './asset';
import {
asset,
BkrlDiscriminatedEntries,
BkrlReadStream,
Region,
} from '@blitzkit/core';
const cache: Record<Region, Record<number, BkrlDiscriminatedEntries>> = {
asia: {},
@@ -1,6 +1,9 @@
import { Region } from '../../constants/regions';
import { BkrlDiscriminatedEntries, BkrlReadStream } from '../streams/bkrl';
import { asset } from './asset';
import {
asset,
BkrlDiscriminatedEntries,
BkrlReadStream,
Region,
} from '@blitzkit/core';
const cache: Record<Region, Record<number, BkrlDiscriminatedEntries | null>> = {
com: {},
@@ -1,14 +0,0 @@
import { usersDatabase } from '../../databases/users';
import { idToRegion } from '../blitz/idToRegion';
import { flagUserActivity } from './flagUserActivity';
export async function getBlitzFromDiscord(discordId: bigint) {
const unique = await usersDatabase.discordUser.findUnique({
where: { discord_id: discordId },
});
if (unique === null) return null;
await flagUserActivity(unique.blitz_id);
return { id: unique.blitz_id, region: idToRegion(unique.blitz_id) };
}
@@ -1,3 +0,0 @@
export default function getPeriodNow() {
return Date.now() / 1000;
}
@@ -1,9 +0,0 @@
import { Region } from '../../constants/regions';
import { PeriodSize } from '../discord/addPeriodSubCommands';
import getTimeDaysAgo from './getTimeDaysAgo';
export default function getPeriodStart(region: Region, period: PeriodSize) {
if (period === 'career') return 0;
if (period === 'today') return getTimeDaysAgo(region, 1);
return getTimeDaysAgo(region, parseInt(period));
}
@@ -1,122 +0,0 @@
import { emptyAllStats } from '@blitzkit/core/src/blitzstars/getStatsInPeriod/constants';
import { Region } from '../../constants/regions';
import {
GetHistoriesOptions,
Histories,
History,
getHistoriesDefaultOptions,
} from '../../types/histories';
import getTankStats from '../blitz/getTankStats';
import { translator } from '../localization/translator';
export interface TankHistory extends History {
tank_id: number;
}
export type TankHistories = TankHistory[];
export interface TankHistoryRaw extends TankHistory {
mark_of_mastery: number;
battle_life_time: number;
account_id: number;
}
export type TankHistoriesRaw = TankHistoryRaw[];
export interface GetTankHistoriesOptions extends GetHistoriesOptions {
tankId?: number;
}
const getTankHistoriesDefaultOptions: GetTankHistoriesOptions = {
...getHistoriesDefaultOptions,
tankId: undefined,
};
export default async function getTankHistories(
server: Region,
id: number,
locale: Locale,
options?: Partial<GetTankHistoriesOptions>,
) {
const { t } = translator(locale);
const mergedOptions = { ...getTankHistoriesDefaultOptions, ...options };
const tankHistoriesResponse = await fetch(
`https://www.blitzstars.com/api/tankhistories/for/${id}/`,
);
const tankHistories = (
(await tankHistoriesResponse.json()) as TankHistoriesRaw
).map(
(history) =>
({
all: history.all,
last_battle_time: history.last_battle_time,
tank_id: history.tank_id,
} satisfies TankHistory),
);
const compliantTanks: number[] = [];
const lastBattles: Record<number, number> = {};
const lastNonCompliantIndex: Record<number, number> = {};
const hasCompliedOnce: Record<number, boolean> = {};
const filtered = tankHistories.filter(
({ last_battle_time, tank_id, all: { battles } }, index) => {
const complies =
last_battle_time >= mergedOptions.start &&
last_battle_time <= mergedOptions.end &&
(mergedOptions.tankId === undefined ||
tank_id === mergedOptions.tankId);
if (complies && !hasCompliedOnce[tank_id]) {
hasCompliedOnce[tank_id] = true;
compliantTanks.push(tank_id);
}
if (!hasCompliedOnce[tank_id]) lastNonCompliantIndex[tank_id] = index;
lastBattles[tank_id] = battles;
return complies;
},
);
const latestNodes: TankHistories = [];
if (mergedOptions.includeLatestHistories) {
const tankStats = await getTankStats(server, id);
if (tankStats === null) {
throw new UserError(t`bot.common.errors.no_tank_stats`);
}
tankStats.forEach((tankHistory) => {
if (
tankHistory.all.battles > (lastBattles[tankHistory.tank_id] ?? 0) &&
(mergedOptions.tankId === undefined ||
tankHistory.tank_id === mergedOptions.tankId)
) {
if (!hasCompliedOnce[tankHistory.tank_id]) {
// was played today for the first time... I think???
hasCompliedOnce[tankHistory.tank_id] = true;
compliantTanks.push(tankHistory.tank_id);
}
latestNodes.push(tankHistory);
}
});
}
const previousNodes: TankHistories = [];
if (mergedOptions.includePreviousHistories) {
compliantTanks.forEach((tankId) => {
if (tankId in lastNonCompliantIndex) {
previousNodes.push(
tankHistories[lastNonCompliantIndex[tankId]] ??
({
all: emptyAllStats,
last_battle_time: -Infinity,
tank_id: tankId,
} satisfies TankHistory),
);
}
});
}
return [...previousNodes, ...filtered, ...latestNodes] satisfies Histories;
}
@@ -1,4 +1,4 @@
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
const TIME_ZONE_MAPPINGS: Record<Region, number> = {
com: -5, // Central North American Time
@@ -1,5 +1,5 @@
import { equipmentDefinitions } from '@blitzkit/core/src/blitzkit/equipmentDefinitions';
import { EquipmentMatrix } from '../../../packages/website/src/stores/duel';
import { EquipmentMatrix } from '../../stores/duel';
export async function hasEquipment(
id: number,
@@ -1,9 +0,0 @@
import jsxToSvg from './jsxToSvg';
import svgToPng from './svgToPng';
export default async function jsxToPng(jsx: JSX.Element) {
const svg = await jsxToSvg(jsx);
const png = svgToPng(svg);
return png;
}
@@ -1,12 +0,0 @@
import jsxToSvg from './jsxToSvg';
import { RenderConfiguration } from './renderConfiguration';
import { svgToPngThreaded } from './svgToPngThreaded';
export default async function jsxToPngThreaded(
jsx: JSX.Element,
renderConfiguration: RenderConfiguration,
) {
const svg = await jsxToSvg(jsx, renderConfiguration);
const png = await svgToPngThreaded(svg);
return png;
}
@@ -1,23 +0,0 @@
import { readFile } from 'fs/promises';
import satori from 'satori';
import { RenderConfiguration } from '../renderConfiguration';
import robotoBlack from './Roboto-Black.ttf';
import robotoBold from './Roboto-Bold.ttf';
import roboto from './Roboto.ttf';
const fontsPromise = [
{ file: roboto, weight: 400 as const },
{ file: robotoBold, weight: 700 as const },
{ file: robotoBlack, weight: 900 as const },
].map(async ({ file, weight }) => {
const data = await readFile(`dist/bot/workers/${file}`);
return { name: 'Roboto', weight, data };
});
export default async function jsxToSvg(
jsx: JSX.Element,
renderConfiguration = new RenderConfiguration(),
) {
const fonts = await Promise.all(fontsPromise);
return await satori(jsx, { width: renderConfiguration.width, fonts });
}
@@ -1,4 +1,4 @@
import { usersDatabase } from '../../databases/users';
import { usersDatabase } from '@blitzkit/core';
import { flagUserActivity } from './flagUserActivity';
export async function linkBlitzAndDiscord(discordId: bigint, blitzId: number) {
@@ -1,6 +1,6 @@
import { assertSecret } from '@blitzkit/core';
import { throttling } from '@octokit/plugin-throttling';
import { Octokit } from '@octokit/rest';
import { assertSecret } from '../../../packages/core/src/blitzkit/assertSecret';
Octokit.plugin(throttling);
@@ -1,7 +1,5 @@
import getBkniPercentile, {
BKNI_COLORS,
BkniPercentile,
} from '../statistics/getBkniPercentile';
import { BKNI_COLORS, BkniPercentile } from '@blitzkit/core';
import getBkniPercentile from '@blitzkit/core/src/statistics/getBkniPercentile';
export function parseBkni(bkni: number) {
const bkniFraction = (bkni + 1) / 2;
@@ -1,5 +1,5 @@
import { usersDatabase } from '../../databases/users';
import { client } from '../discord/client';
import { usersDatabase } from '@blitzkit/core';
import { client } from '../../../../bot/src/core/discord/client';
const EXIT_EVENTS = [
'beforeExit',
@@ -1,8 +1,7 @@
import { DdsReadStream, PvrReadStream } from '@blitzkit/core';
import { existsSync } from 'fs';
import sharp from 'sharp';
import { readDVPLFile } from '../../blitz/readDVPLFile';
import { DdsReadStream } from '../../streams/dds';
import { PvrReadStream } from '../../streams/pvr';
import { readDVPLFile } from '../../../../../scripts/src/core/blitz/readDVPLFile';
import { TextureMutation } from './constants';
export async function readTexture(path: string, mutation?: TextureMutation) {
@@ -1,4 +1,4 @@
import { tankDefinitions } from './tankDefinitions';
import { tankDefinitions } from '@blitzkit/core';
export async function resolveAncestry(id: number) {
const awaitedTankDefinitions = await tankDefinitions;
@@ -1,4 +1,4 @@
import { GunDefinition } from './tankDefinitions';
import { GunDefinition } from '@blitzkit/core';
export function resolveReload(gun: GunDefinition) {
if (gun.type === 'regular') {
@@ -1,5 +0,0 @@
import { Resvg } from '@resvg/resvg-js';
export default function svgToPng(svg: string) {
return new Resvg(svg).render().asPng();
}
@@ -1,46 +0,0 @@
import { Worker } from 'worker_threads';
const RENDER_WORKERS = 1;
const workers = [...Array(RENDER_WORKERS)].map(() => {
const worker = new Worker('dist/bot/workers/render.js');
console.log(`🟡 Launching render worker ${worker.threadId}`);
return worker;
});
const queue: {
svg: string;
resolve: (png: Buffer) => void;
}[] = [];
function manageQueue() {
if (queue.length > 0 && workers.length > 0) {
const { svg, resolve } = queue.shift()!;
const worker = workers.shift()!;
function cleanup() {
workers.push(worker);
worker.off('message', handleMessage);
worker.off('error', handleError);
manageQueue();
}
function handleMessage(png: Uint8Array) {
cleanup();
resolve(Buffer.from(png));
}
function handleError(error: Error) {
cleanup();
throw error;
}
worker.postMessage(svg);
worker.on('message', handleMessage);
worker.on('error', handleError);
}
}
export function svgToPngThreaded(svg: string) {
return new Promise<Buffer>((resolve) => {
queue.push({ svg, resolve });
manageQueue();
});
}
@@ -1,7 +1,7 @@
import { TankDefinition } from '@blitzkit/core';
import { ProvisionDefinitions } from '@blitzkit/core/src/blitzkit/provisionDefinitions';
import { uniqueId } from 'lodash';
import { CompareMember } from '../../../packages/website/src/stores/compareEphemeral';
import { TankDefinition } from './tankDefinitions';
import { CompareMember } from '../../stores/compareEphemeral';
import { tankToDuelMember } from './tankToDuelMember';
export function tankToCompareMember(
@@ -1,6 +1,6 @@
import { Region } from '../../constants/regions';
import { Region } from '@blitzkit/core';
import buttonLink from '../../../../bot/src/core/discord/buttonLink';
import { getAccountInfo } from '../blitz/getAccountInfo';
import buttonLink from '../discord/buttonLink';
export async function getBlitzStarsLinkButton(
region: Region,
@@ -1,11 +1,10 @@
import { emptyAllStats } from '@blitzkit/core/src/blitzstars/getStatsInPeriod/constants';
import { Region } from '../../constants/regions';
import { Region, emptyAllStats } from '@blitzkit/core';
import {
GetHistoriesOptions,
Histories,
History,
getHistoriesDefaultOptions,
} from '../../types/histories';
} from '../../../../bot/src/types/histories';
import { getAccountInfo } from '../blitz/getAccountInfo';
import { PlayerStats } from './getPlayerStats';
@@ -1,5 +1,4 @@
import { Region } from '../../constants/regions';
import { BlitzStats } from '../statistics/compositeStats/constants';
import { BlitzStats, Region } from '@blitzkit/core';
interface IndividualPlayerStats {
clan: { clan_id: number; name: string; tag: string };
@@ -1,6 +1,5 @@
import { BlitzStats, tankDefinitions } from '@blitzkit/core';
import { context } from '../blitzkit/context';
import { tankDefinitions } from '../blitzkit/tankDefinitions';
import { BlitzStats } from '../statistics/compositeStats/constants';
interface SpecialStats {
winrate: number;
@@ -1,18 +0,0 @@
import { Locale, SlashCommandStringOption } from 'discord.js';
import { translator } from '../localization/translator';
import { localizationObject } from './localizationObject';
export default function addClanChoices(option: SlashCommandStringOption) {
const { translate } = translator(Locale.EnglishUS);
return option
.setName('clan')
.setNameLocalizations(localizationObject('bot.common.options.clan'))
.setDescription(translate('bot.common.options.clan.description'))
.setDescriptionLocalizations(
localizationObject('bot.common.options.clan.description'),
)
.setAutocomplete(true)
.setMinLength(2)
.setRequired(true);
}
@@ -1,111 +0,0 @@
import {
APIApplicationCommandOptionChoice,
Locale,
SlashCommandBuilder,
SlashCommandSubcommandBuilder,
} from 'discord.js';
import {
TANK_CLASSES,
TREE_TYPES,
} from '../../components/Tanks/components/Item/constants';
import { translator } from '../localization/translator';
import addTankChoices from './addTankChoices';
import addTierChoices from './addTierChoices';
import { localizationObject } from './localizationObject';
export function addFilterOptions<
Option extends SlashCommandBuilder | SlashCommandSubcommandBuilder,
>(option: Option, nations: string[]) {
const { translate } = translator(Locale.EnglishUS);
return (
option
.addStringOption((option) =>
option
.setName(translate('bot.common.options.filters.nation'))
.setNameLocalizations(
localizationObject('bot.common.options.filters.nation'),
)
.setDescription(
translate('bot.common.options.filters.nation.description'),
)
.setDescriptionLocalizations(
localizationObject('bot.common.options.filters.nation.description'),
)
.addChoices(
...nations.map(
(nation) =>
({
value: nation,
name: translate(`common.nations.${nation}`),
name_localizations: localizationObject(
`common.nations.${nation}`,
),
}) satisfies APIApplicationCommandOptionChoice,
),
)
.setRequired(false),
)
.addStringOption((option) => addTierChoices(option).setRequired(false))
.addStringOption((option) =>
option
.setName(translate('bot.common.options.filters.tank_class'))
.setNameLocalizations(
localizationObject('bot.common.options.filters.tank_class'),
)
.setDescription(
translate('bot.common.options.filters.tank_class.description'),
)
.setDescriptionLocalizations(
localizationObject(
'bot.common.options.filters.tank_class.description',
),
)
.addChoices(
...TANK_CLASSES.map(
(tankType) =>
({
value: tankType,
name: translate(`common.tank_class_short.${tankType}`),
name_localizations: localizationObject(
`common.tank_class_short.${tankType}`,
),
}) satisfies APIApplicationCommandOptionChoice,
),
)
.setRequired(false),
)
.addStringOption((option) =>
option
.setName(translate('bot.common.options.filters.tree_type'))
.setNameLocalizations(
localizationObject('bot.common.options.filters.tree_type'),
)
.setDescription(
translate('bot.common.options.filters.tree_type.description'),
)
.setDescriptionLocalizations(
localizationObject(
'bot.common.options.filters.tree_type.description',
),
)
.addChoices(
...TREE_TYPES.map(
(treeType) =>
({
value: treeType,
name: translate(`common.tree_type.${treeType}`),
name_localizations: localizationObject(
`common.tree_type.${treeType}`,
),
}) satisfies APIApplicationCommandOptionChoice,
),
)
.setRequired(false),
)
// TODO: somehow localize this?
.addStringOption((option) =>
addTankChoices(option).setRequired(false),
) as Option
);
}
@@ -1,122 +0,0 @@
import {
Locale,
SlashCommandBuilder,
SlashCommandSubcommandBuilder,
SlashCommandSubcommandGroupBuilder,
} from 'discord.js';
import { translator } from '../localization/translator';
import { localizationObject } from './localizationObject';
export type PeriodType = 'today' | '30' | '60' | '90' | 'career' | 'custom';
export type PeriodSize = 'today' | `${number}` | 'career';
export function addPeriodSubCommands(
option: SlashCommandBuilder | SlashCommandSubcommandGroupBuilder,
extra: (
option: SlashCommandSubcommandBuilder,
) => SlashCommandSubcommandBuilder = (option) => option,
) {
const { translate } = translator(Locale.EnglishUS);
const subcommandNameLocalizations = {
today: localizationObject('bot.common.subcommands.today'),
30: localizationObject('bot.common.subcommands.30'),
60: localizationObject('bot.common.subcommands.60'),
90: localizationObject('bot.common.subcommands.90'),
career: localizationObject('bot.common.subcommands.career'),
custom: localizationObject('bot.common.subcommands.custom'),
};
const subcommandDescriptionLocalizations = {
today: localizationObject('bot.common.subcommands.today.description'),
30: localizationObject('bot.common.subcommands.30.description'),
60: localizationObject('bot.common.subcommands.60.description'),
90: localizationObject('bot.common.subcommands.90.description'),
career: localizationObject('bot.common.subcommands.career.description'),
custom: localizationObject('bot.common.subcommands.custom.description'),
};
option
.addSubcommand((option) =>
extra(
option
.setName(translate('bot.common.subcommands.today'))
.setNameLocalizations(subcommandNameLocalizations.today)
.setDescription(translate('bot.common.subcommands.today.description'))
.setDescriptionLocalizations(
subcommandDescriptionLocalizations.today,
),
),
)
.addSubcommand((option) =>
extra(
option
.setName(translate('bot.common.subcommands.30'))
.setNameLocalizations(subcommandNameLocalizations[30])
.setDescription(translate('bot.common.subcommands.30.description'))
.setDescriptionLocalizations(subcommandDescriptionLocalizations[30]),
),
)
.addSubcommand((option) =>
extra(
option
.setName(translate('bot.common.subcommands.60'))
.setNameLocalizations(subcommandNameLocalizations[60])
.setDescription(translate('bot.common.subcommands.60.description'))
.setDescriptionLocalizations(subcommandDescriptionLocalizations[60]),
),
)
.addSubcommand((option) =>
extra(
option
.setName(translate('bot.common.subcommands.90'))
.setNameLocalizations(subcommandNameLocalizations[90])
.setDescription(translate('bot.common.subcommands.90.description'))
.setDescriptionLocalizations(subcommandDescriptionLocalizations[90]),
),
)
.addSubcommand((option) =>
extra(
option
.setName(translate('bot.common.subcommands.career'))
.setNameLocalizations(subcommandNameLocalizations.career)
.setDescription(
translate('bot.common.subcommands.career.description'),
)
.setDescriptionLocalizations(
subcommandDescriptionLocalizations.career,
),
),
)
.addSubcommand((option) =>
extra(
option
.setName(translate('bot.common.subcommands.custom'))
.setNameLocalizations(subcommandNameLocalizations.custom)
.setDescription(
translate('bot.common.subcommands.custom.description'),
)
.setDescriptionLocalizations(
subcommandDescriptionLocalizations.custom,
)
.addIntegerOption((option) =>
option
.setName(translate('bot.common.subcommands.custom.options.start'))
.setDescription(
translate(
'bot.common.subcommands.custom.options.start.description',
),
)
.setRequired(true),
)
.addIntegerOption((option) =>
option
.setName(translate('bot.common.subcommands.custom.options.end'))
.setDescription(
translate(
'bot.common.subcommands.custom.options.end.description',
),
)
.setRequired(true),
),
),
);
}
@@ -1,25 +0,0 @@
import { gameDefinitions } from '@blitzkit/core/src/blitzkit/gameDefinitions';
import {
SlashCommandBuilder,
SlashCommandSubcommandBuilder,
SlashCommandSubcommandGroupBuilder,
} from 'discord.js';
import { addFilterOptions } from './addFilterOptions';
import { addPeriodSubCommands } from './addPeriodSubCommands';
export default async function addPeriodicFilterOptions<
OptionType extends SlashCommandBuilder | SlashCommandSubcommandGroupBuilder,
>(
option: OptionType,
extra: (
option: SlashCommandSubcommandBuilder,
) => SlashCommandSubcommandBuilder = (option) => option,
): Promise<OptionType> {
const awaitedGameDefinitions = await gameDefinitions;
addPeriodSubCommands(option, (option) =>
addFilterOptions(extra(option), awaitedGameDefinitions.nations),
);
return option;
}
@@ -1,33 +0,0 @@
import {
APIApplicationCommandOptionChoice,
Locale,
SlashCommandStringOption,
} from 'discord.js';
import { REGIONS } from '../../constants/regions';
import { translator } from '../localization/translator';
import { localizationObject } from './localizationObject';
export default function addRegionChoices(option: SlashCommandStringOption) {
const { t, translate } = translator(Locale.EnglishUS);
return option
.setName(t`bot.common.options.region`)
.setNameLocalizations(localizationObject('bot.common.options.region'))
.setDescription(t`bot.common.options.region.description`)
.setDescriptionLocalizations(
localizationObject('bot.common.options.region.description'),
)
.addChoices(
...REGIONS.map(
(region) =>
({
value: region,
name: translate(`common.regions.normal.${region}`),
name_localizations: localizationObject(
`common.regions.normal.${region}`,
),
}) satisfies APIApplicationCommandOptionChoice,
),
)
.setRequired(true);
}
@@ -1,17 +0,0 @@
import { Locale, SlashCommandStringOption } from 'discord.js';
import { translator } from '../localization/translator';
import { localizationObject } from './localizationObject';
export default function addTankChoices(option: SlashCommandStringOption) {
const { translate } = translator(Locale.EnglishUS);
return option
.setName(translate('bot.common.options.tank'))
.setNameLocalizations(localizationObject('bot.common.options.tank'))
.setDescription(translate('bot.common.options.tank.description'))
.setDescriptionLocalizations(
localizationObject('bot.common.options.tank.description'),
)
.setAutocomplete(true)
.setRequired(true);
}
@@ -1,38 +0,0 @@
import numberToRomanNumeral from '@blitzkit/core/src/math/numberToRomanNumeral';
import {
APIApplicationCommandOptionChoice,
Locale,
SlashCommandStringOption,
} from 'discord.js';
import { range } from 'lodash';
import { translator } from '../localization/translator';
import { localizationObject } from './localizationObject';
export default function addTierChoices(option: SlashCommandStringOption) {
const { t, translate } = translator(Locale.EnglishUS);
return option
.setName(t`bot.common.options.tier`)
.setNameLocalizations(localizationObject('bot.common.options.tier'))
.setDescription(t`bot.common.options.tier.description`)
.setDescriptionLocalizations(
localizationObject('bot.common.options.tier.description'),
)
.setChoices(
...range(10, 0).map(
(tier) =>
({
name: translate('bot.common.options.tier.choices.tier', [
`${tier}`,
numberToRomanNumeral(tier),
]),
value: `${tier}`,
name_localizations: localizationObject(
'bot.common.options.tier.choices.tier',
[`${tier}`, numberToRomanNumeral(tier)],
),
} satisfies APIApplicationCommandOptionChoice),
),
)
.setRequired(true);
}
@@ -1,16 +0,0 @@
import { Locale, SlashCommandStringOption } from 'discord.js';
import { translator } from '../localization/translator';
import { localizationObject } from './localizationObject';
export default function addUsernameChoices(option: SlashCommandStringOption) {
const { t } = translator(Locale.EnglishUS);
return option
.setName(t`bot.common.options.username`)
.setNameLocalizations(localizationObject('bot.common.options.username'))
.setDescription(t`bot.common.options.username.description`)
.setDescriptionLocalizations(
localizationObject('bot.common.options.username.description'),
)
.setAutocomplete(true);
}
@@ -1,2 +0,0 @@
export const DISCORD_CHOICES_MAX_NAME_SIZE = 25;
export const OVERFLOW_SUFFIX = '…';
@@ -1,44 +0,0 @@
import {
ApplicationCommandOptionChoiceData,
AutocompleteInteraction,
CacheType,
} from 'discord.js';
import searchClansAcrossRegions from '../../blitz/searchClansAcrossRegions';
import { translator } from '../../localization/translator';
import { DISCORD_CHOICES_MAX_NAME_SIZE, OVERFLOW_SUFFIX } from './constants';
export default async function autocompleteClan(
interaction: AutocompleteInteraction<CacheType>,
) {
const { translate } = translator(interaction.locale);
const focusedOption = interaction.options.getFocused(true);
if (focusedOption.name !== 'clan') return;
if (focusedOption.value.length < 2) return interaction.respond([]);
const clans = await searchClansAcrossRegions(focusedOption.value);
await interaction.respond(
clans
? clans.map((clan) => {
let name = `${clan.name} (${translate(
`common.regions.short.${clan.region}`,
)})`;
if (name.length > DISCORD_CHOICES_MAX_NAME_SIZE) {
const overSize = name.length - DISCORD_CHOICES_MAX_NAME_SIZE;
name = `${clan.name.slice(
0,
clan.name.length - overSize - OVERFLOW_SUFFIX.length,
)}${OVERFLOW_SUFFIX} (${translate(
`common.regions.short.${clan.region}`,
)})`;
}
return {
name,
value: `${clan.region}/${clan.clan_id}`,
} satisfies ApplicationCommandOptionChoiceData<string>;
})
: [],
);
}
@@ -1,57 +0,0 @@
import {
ApplicationCommandOptionChoiceData,
AutocompleteInteraction,
CacheType,
} from 'discord.js';
import { go } from 'fuzzysort';
import { tankNames } from '../blitzkit/tankDefinitions/tankNames';
import {
DISCORD_CHOICES_MAX_NAME_SIZE,
OVERFLOW_SUFFIX,
} from './autocompleteClan/constants';
export const tankNamesTechTreeOnly = tankNames.then((names) =>
names.filter((tank) => tank.treeType === 'researchable'),
);
export default async function autocompleteTanks(
interaction: AutocompleteInteraction<CacheType>,
techTreeOnly = false,
fields = ['tank'],
) {
const focusedOption = interaction.options.getFocused(true);
if (!fields.includes(focusedOption.name)) return;
await interaction.respond(
focusedOption.value
? await Promise.all(
go(
focusedOption.value,
await (techTreeOnly ? tankNamesTechTreeOnly : tankNames),
{
keys: ['searchableName', 'searchableNameDeburr', 'camouflages'],
limit: 10,
},
).map(async (item) => {
let name = item.obj.searchableName;
if (name.length > DISCORD_CHOICES_MAX_NAME_SIZE) {
const overSize = name.length - DISCORD_CHOICES_MAX_NAME_SIZE;
name = `${item.obj.searchableName.slice(
0,
item.obj.searchableName.length -
overSize -
OVERFLOW_SUFFIX.length,
)}${OVERFLOW_SUFFIX}`;
}
return {
name,
value: `${item.obj.id}`,
} satisfies ApplicationCommandOptionChoiceData<string>;
}),
)
: [],
);
}
@@ -1,48 +0,0 @@
import {
ApplicationCommandOptionChoiceData,
AutocompleteInteraction,
CacheType,
} from 'discord.js';
import searchPlayersAcrossRegions from '../blitz/searchPlayersAcrossRegions';
import { translator } from '../localization/translator';
import {
DISCORD_CHOICES_MAX_NAME_SIZE,
OVERFLOW_SUFFIX,
} from './autocompleteClan/constants';
export default async function autocompleteUsername(
interaction: AutocompleteInteraction<CacheType>,
) {
const { translate } = translator(interaction.locale);
const focusedOption = interaction.options.getFocused(true);
if (focusedOption.name !== 'username') return;
const players = await searchPlayersAcrossRegions(focusedOption.value);
try {
await interaction.respond(
players
? players.map((player) => {
let name = `${player.nickname} (${translate(
`common.regions.short.${player.region}`,
)})`;
if (name.length > DISCORD_CHOICES_MAX_NAME_SIZE) {
const overSize = name.length - DISCORD_CHOICES_MAX_NAME_SIZE;
name = `${player.nickname.slice(
0,
player.nickname.length - overSize - OVERFLOW_SUFFIX.length,
)}${OVERFLOW_SUFFIX} (${translate(
`common.regions.short.${player.region}`,
)})`;
}
return {
name,
value: `${player.region}/${player.account_id}`,
} satisfies ApplicationCommandOptionChoiceData<string>;
})
: [],
);
} catch (error) {}
}
@@ -1,20 +0,0 @@
import {
ButtonBuilder,
ButtonStyle,
ComponentEmojiResolvable,
} from 'discord.js';
export default function buttonLink(
url: string,
label: string,
emoji?: ComponentEmojiResolvable,
) {
const button = new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setURL(url)
.setLabel(label);
if (emoji) button.setEmoji(emoji);
return button;
}
@@ -1,20 +0,0 @@
import {
ButtonBuilder,
ButtonStyle,
ComponentEmojiResolvable,
} from 'discord.js';
export default function buttonPrimary(
id: string,
label: string,
emoji?: ComponentEmojiResolvable,
) {
const button = new ButtonBuilder()
.setCustomId(id)
.setStyle(ButtonStyle.Primary)
.setLabel(label);
if (emoji) button.setEmoji(emoji);
return button;
}
@@ -1,19 +0,0 @@
import { ChatInputCommandInteraction } from 'discord.js';
import { translator } from '../localization/translator';
import buttonPrimary from './buttonPrimary';
export function buttonRefresh(
interaction: ChatInputCommandInteraction,
path: string,
) {
const { t } = translator(interaction.locale);
if (
interaction.appPermissions?.has('ReadMessageHistory') &&
interaction.appPermissions?.has('ViewChannel')
) {
return buttonPrimary(path, t`bot.common.buttons.refresh`);
}
return null;
}
@@ -1,9 +0,0 @@
import { Client, GatewayIntentBits } from 'discord.js';
import interactionCreate from '../../events/interactionCreate';
import ready from '../../events/ready';
export const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
})
.on('ready', ready)
.on('interactionCreate', interactionCreate);
@@ -1,27 +0,0 @@
import { CacheType, ChatInputCommandInteraction } from 'discord.js';
export interface Parameters {
[key: string]: string | number | boolean | undefined | null;
}
// TODO: automatically infer command options???
// but how would that work with the region and id options?
export default function commandToURL(
interaction: ChatInputCommandInteraction<CacheType>,
parameters?: Parameters,
) {
const pathname = [
interaction.commandName,
interaction.options.getSubcommandGroup(false),
interaction.options.getSubcommand(false),
]
.filter(Boolean)
.join('/');
const params = (parameters ? Object.entries(parameters) : [])
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${key}=${value}`)
.join('&');
return `${pathname}${params.length > 0 ? `?${params}` : ''}`;
}
@@ -1,85 +0,0 @@
import {
Locale,
SlashCommandBuilder,
SlashCommandSubcommandBuilder,
SlashCommandSubcommandGroupBuilder,
} from 'discord.js';
import { translator } from '../localization/translator';
import { localizationObject } from './localizationObject';
interface CreateLocalizedCommandSubcommand {
subcommand: string;
modify?: (option: SlashCommandSubcommandBuilder) => void;
}
interface CreateLocalizedCommandSubcommandGroup {
group: string;
modify?: (option: SlashCommandSubcommandGroupBuilder) => void;
}
export function createLocalizedCommand(
command: string,
sub?:
| CreateLocalizedCommandSubcommand[]
| CreateLocalizedCommandSubcommandGroup[],
) {
const commandPathItem = command.replaceAll('-', '_');
const { translate } = translator(Locale.EnglishUS);
const slashCommand = new SlashCommandBuilder()
.setName(command)
.setNameLocalizations(localizationObject(`bot.commands.${commandPathItem}`))
.setDescription(translate(`bot.commands.${commandPathItem}.description`))
.setDescriptionLocalizations(
localizationObject(`bot.commands.${commandPathItem}.description`),
);
if (sub) {
sub.map((subItem) => {
if ('subcommand' in subItem) {
const subcommandNameLocalizations = localizationObject(
`bot.commands.${commandPathItem}.subcommands.${subItem.subcommand}`,
);
const subcommandDescriptionLocalizations = localizationObject(
`bot.commands.${commandPathItem}.subcommands.${subItem.subcommand}.description`,
);
slashCommand.addSubcommand((option) => {
if (subItem.modify) subItem.modify(option);
return option
.setName(subItem.subcommand)
.setNameLocalizations(subcommandNameLocalizations)
.setDescription(
translate(
`bot.commands.${commandPathItem}.subcommands.${subItem.subcommand}.description`,
),
)
.setDescriptionLocalizations(subcommandDescriptionLocalizations);
});
} else {
const subcommandNameLocalizations = localizationObject(
`bot.commands.${commandPathItem}.groups.${subItem.group}`,
);
const subcommandDescriptionLocalizations = localizationObject(
`bot.commands.${commandPathItem}.groups.${subItem.group}.description`,
);
slashCommand.addSubcommandGroup((option) => {
if (subItem.modify) subItem.modify(option);
return option
.setName(subItem.group)
.setNameLocalizations(subcommandNameLocalizations)
.setDescription(
translate(
`bot.commands.${commandPathItem}.groups.${subItem.group}.description`,
),
)
.setDescriptionLocalizations(subcommandDescriptionLocalizations);
});
}
});
}
return slashCommand;
}
@@ -1,12 +0,0 @@
import { EmbedBuilder } from 'discord.js';
import { ACCENT_COLOR } from '../../constants/colors';
export default function embedInfo(title: string, description: string) {
const embed = new EmbedBuilder()
.setColor(ACCENT_COLOR)
.setDescription(description);
if (title) embed.setTitle(title);
return embed;
}
@@ -1,9 +0,0 @@
import { EmbedBuilder } from 'discord.js';
import { NEGATIVE_COLOR } from '../../constants/colors';
export default function embedNegative(title: string, description: string) {
return new EmbedBuilder()
.setColor(NEGATIVE_COLOR)
.setTitle(title)
.setDescription(description);
}
@@ -1,9 +0,0 @@
import { EmbedBuilder } from 'discord.js';
import { POSITIVE_COLOR } from '../../constants/colors';
export default function embedPositive(title: string, description: string) {
return new EmbedBuilder()
.setColor(POSITIVE_COLOR)
.setTitle(title)
.setDescription(description);
}
@@ -1,9 +0,0 @@
import { EmbedBuilder } from 'discord.js';
import { WARNING_COLOR } from '../../constants/colors';
export default function embedWarning(title: string, description: string) {
return new EmbedBuilder()
.setColor(WARNING_COLOR)
.setTitle(title)
.setDescription(description);
}
@@ -1,19 +0,0 @@
import { ChatInputCommandInteraction } from 'discord.js';
import { PeriodType } from './addPeriodSubCommands';
export function getCustomPeriodParams(
interaction: ChatInputCommandInteraction,
forcedNonCustomPeriod = false,
) {
if (
!forcedNonCustomPeriod &&
(interaction.options.getSubcommand() as PeriodType) === 'custom'
) {
return {
start: interaction.options.getInteger('start', true),
end: interaction.options.getInteger('end', true),
};
}
return undefined;
}
@@ -1,16 +0,0 @@
import { ButtonInteraction } from 'discord.js';
import { TreeType } from '../../components/Tanks';
import { StatFilters } from '../statistics/filterStats';
export function getFiltersFromButton(interaction: ButtonInteraction) {
const url = new URL(`https://example.com/${interaction.customId}`);
return {
nation: url.searchParams.get('nation') ?? undefined,
tank: parseInt(url.searchParams.get('tank') ?? '0') || undefined,
tankType: url.searchParams.get('tank-class') ?? undefined,
treeType:
(url.searchParams.get('tree-type') as TreeType | undefined) ?? undefined,
tier: parseInt(url.searchParams.get('tier') ?? '0') || undefined,
} satisfies StatFilters;
}
@@ -1,23 +0,0 @@
import { ChatInputCommandInteraction } from 'discord.js';
import { TreeType } from '../../components/Tanks';
import resolveTankId from '../blitz/resolveTankId';
import { StatFilters } from '../statistics/filterStats';
export async function getFiltersFromCommand(
interaction: ChatInputCommandInteraction,
) {
const tankRaw = interaction.options.getString('tank');
return {
nation: interaction.options.getString('nation') ?? undefined,
tier: parseInt(interaction.options.getString('tier') ?? '0') || undefined,
tankType: interaction.options.getString('tank-class') ?? undefined,
treeType:
(interaction.options.getString('tree-type') as TreeType | undefined) ??
undefined,
tank:
tankRaw === null
? undefined
: await resolveTankId(tankRaw, interaction.locale),
} satisfies StatFilters;
}
@@ -1,10 +0,0 @@
import { Locale } from 'discord.js';
import { translator } from '../localization/translator';
import { PeriodSize } from './addPeriodSubCommands';
export function getPeriodOptionName(period: PeriodSize, locale: Locale) {
const { translate } = translator(locale);
if (period === 'career') return translate('bot.common.periods.career');
if (period === 'today') return translate('bot.common.periods.today');
return translate('bot.common.periods.days', [period]);
}
@@ -1,16 +0,0 @@
import { Locale } from 'discord.js';
import { SUPPORTED_LOCALES } from '../localization/strings/constants';
import { translator } from '../localization/translator';
export function localizationObject(path: string, literals?: string[]) {
return SUPPORTED_LOCALES.reduce<Partial<Record<Locale, string>>>(
(localizations, locale) => {
const { translate } = translator(locale);
return {
...localizations,
[locale]: translate(path, literals),
};
},
{},
);
}
@@ -1,6 +0,0 @@
import { ShardingManager } from 'discord.js';
import { assertSecret } from '../../../packages/core/src/blitzkit/assertSecret';
export const manager = new ShardingManager('dist/bot/workers/bot.js', {
token: assertSecret(process.env.DISCORD_TOKEN),
});
@@ -1,9 +0,0 @@
export type TableInputEntry = [string, string | number] | [];
export type TableInput = TableInputEntry[];
export default function markdownTable(input: TableInput) {
return input
.filter((array) => array[1] !== undefined)
.map((array) => (array.length === 0 ? '' : `**${array[0]}**: ${array[1]}`))
.join('\n');
}
@@ -1,64 +0,0 @@
import {
ActionRowBuilder,
AttachmentBuilder,
ButtonBuilder,
EmbedBuilder,
InteractionEditReplyOptions,
InteractionReplyOptions,
MessageEditOptions,
} from 'discord.js';
import { InteractionReturnable } from '../../events/interactionCreate';
import { Writeable } from '../../types/writable';
import jsxToPngThreaded from '../blitzkit/jsxToPngThreaded';
import { RenderConfiguration } from '../blitzkit/renderConfiguration';
export default async function normalizeInteractionReturnable(
returnable: InteractionReturnable,
) {
const images: [number, Buffer][] = [];
const reply: InteractionEditReplyOptions &
InteractionReplyOptions &
MessageEditOptions = {};
const awaitedReturnable = await returnable;
const normalizedReturnable = Array.isArray(awaitedReturnable)
? awaitedReturnable
: [awaitedReturnable];
let renderConfiguration = new RenderConfiguration();
await Promise.all(
normalizedReturnable.map(async (item, index) => {
if (typeof item === 'string') {
reply.content = item;
} else if (item instanceof EmbedBuilder) {
if (!reply.embeds) reply.embeds = [];
(reply.embeds as Writeable<typeof reply.embeds>).push(item);
} else if (item instanceof ButtonBuilder) {
if (!reply.components)
reply.components = [new ActionRowBuilder<ButtonBuilder>()];
(reply.components[0] as ActionRowBuilder<ButtonBuilder>).addComponents(
item,
);
} else if (item instanceof AttachmentBuilder) {
if (!reply.files) reply.files = [];
(reply.files as Writeable<typeof reply.files>).push(item);
} else if (item instanceof RenderConfiguration) {
renderConfiguration = item;
} else if (item === null) {
return;
} else {
const image = await jsxToPngThreaded(item, renderConfiguration);
images.push([index, image]);
}
}),
);
if (images.length > 0) {
images.sort(([a], [b]) => b - a);
if (!reply.files) reply.files = [];
images.forEach(([, image]) =>
(reply.files as Writeable<typeof reply.files>)?.push(image),
);
}
return reply;
}
-36
View File
@@ -1,36 +0,0 @@
export type PSAData = {
secret?: boolean;
links?: {
title: string;
url: string;
}[];
commands?: string[];
} & (
| {
type?: 'embed';
title: string;
description: string;
image?: string;
}
| {
type: 'image';
image: string;
title?: string;
}
);
export interface PSA {
data: PSAData | null;
}
export const psa: PSA = {
data: null,
};
fetch(
'https://gist.githubusercontent.com/tresabhi/ed4b136f08856e615212e573aabe1968/raw',
)
.then((response) => response.json())
.then((data) => {
psa.data = data as PSAData;
});
@@ -1,29 +0,0 @@
import { ChatInputCommandInteraction } from 'discord.js';
import markdownEscape from 'markdown-escape';
import { Region } from '../../constants/regions';
import { UserError } from '../../hooks/userError';
import searchClansAcrossRegions from '../blitz/searchClansAcrossRegions';
import { translator } from '../localization/translator';
import { serverAndIdPattern } from './resolvePlayerFromCommand/constants';
export default async function resolveClanFromCommand(
interaction: ChatInputCommandInteraction,
) {
const { translate } = translator(interaction.locale);
const clan = interaction.options.getString('clan', true);
if (serverAndIdPattern.test(clan)) {
const [server, accountId] = clan.split('/');
return { region: server as Region, id: Number(accountId) };
} else {
const accounts = await searchClansAcrossRegions(clan);
if (accounts[0]) {
return { region: accounts[0].region, id: accounts[0].clan_id };
} else {
throw new UserError(
translate('bot.common.errors.clan_not_found', [markdownEscape(clan)]),
);
}
}
}
@@ -1,41 +0,0 @@
import { ButtonInteraction } from 'discord.js';
import { Region } from '../../constants/regions';
import getPeriodNow from '../blitzkit/getPeriodNow';
import getPeriodStart from '../blitzkit/getPeriodStart';
import getTimeDaysAgo from '../blitzkit/getTimeDaysAgo';
import { PeriodType } from './addPeriodSubCommands';
import { getPeriodOptionName } from './getPeriodOptionName';
import { ResolvedPeriod } from './resolvePeriodFromCommand';
export default function resolvePeriodFromButton(
region: Region,
interaction: ButtonInteraction,
) {
let name: string;
let start: number;
let end: number;
const url = new URL(`https://example.com/${interaction.customId}`);
const path = url.pathname.split('/');
const periodSubcommand = path.at(-1) as PeriodType;
if (periodSubcommand === 'custom') {
const startRaw = parseInt(url!.searchParams.get('start')!);
const endRaw = parseInt(url!.searchParams.get('end')!);
const startDaysAgoMin = Math.min(startRaw, endRaw);
const endDaysAgoMax = Math.max(startRaw, endRaw);
name = `${startDaysAgoMin} - ${endDaysAgoMax} days`;
start = getTimeDaysAgo(region, endDaysAgoMax);
end = getTimeDaysAgo(region, startDaysAgoMin);
} else {
name = getPeriodOptionName(periodSubcommand, interaction.locale);
start = getPeriodStart(region, periodSubcommand);
end = getPeriodNow();
}
return {
name,
start,
end,
} satisfies ResolvedPeriod;
}
Loaded 100 of 255 files, more files were not shown because too many files have changed in this diff. Show more