Compare commits

...
42 Commits
Author SHA1 Message Date
dahyeon ce00bc84b5 Rename mentor matching to similar players 2026-07-03 03:18:59 -07:00
dahyeon cfbc74d882 Show all metric insights with descriptions 2026-07-03 02:44:00 -07:00
dahyeon 741fce0adb Add mentor match dashboard section 2026-07-03 02:18:58 -07:00
dahyeon 1d8037adf1 Expose mentor match API 2026-07-03 02:04:11 -07:00
dahyeon 4f70e07cb7 Cache mentor match recommendations 2026-07-03 01:54:45 -07:00
dahyeon 1db1d1d1d6 Add mentor match ranking service 2026-07-03 01:51:31 -07:00
dahyeon 1df1cd54f8 Ensure Mongo collections on startup 2026-07-03 01:39:31 -07:00
dahyeon fafacec781 Denormalize profile tier fields 2026-07-03 01:31:22 -07:00
dahyeon 89eafb8770 Recompute registry-normalized features 2026-07-03 01:28:43 -07:00
dahyeon 9a17502d29 Apply population percentile normalization 2026-07-03 01:26:46 -07:00
dahyeon 2935a526c7 Wire baseline computation jobs 2026-07-03 01:19:45 -07:00
dahyeon 3ef86b0b66 Add metric baseline computation service 2026-07-03 01:15:20 -07:00
dahyeon d18e36e962 Process seed accounts through analysis pipeline 2026-07-03 01:11:21 -07:00
dahyeon 63a4aeace7 Wire seed collection queue 2026-07-03 01:04:45 -07:00
dahyeon a6c1acbc31 Add seed account collection service 2026-07-03 00:59:31 -07:00
dahyeon e24bb60627 Add Riot account lookup by PUUID 2026-07-03 00:50:36 -07:00
dahyeon 67b4032ff0 Add apex league Riot client methods 2026-07-03 00:48:59 -07:00
dahyeon 8668234065 Add feature recompute jobs 2026-07-03 00:45:04 -07:00
dahyeon 1a7a1cca68 Add timeline insight metrics 2026-07-03 00:29:51 -07:00
dahyeon a69e86f2bc Add timeline vector metrics 2026-07-03 00:12:13 -07:00
dahyeon 77ba93b94a Support sparse metric aggregation 2026-07-02 23:53:33 -07:00
dahyeon d4e7cb6e8b Add timeline roam frames 2026-07-02 23:50:10 -07:00
dahyeon df0e43d884 Add timeline death events 2026-07-02 23:43:09 -07:00
dahyeon d35843a8e2 Add timeline advantage events 2026-07-02 23:31:19 -07:00
dahyeon 1e2f1695ce Store timeline derived data 2026-07-02 23:13:27 -07:00
dahyeon 897e2092a3 Add timeline derived builders 2026-07-02 23:10:40 -07:00
dahyeon 3460a93eaf Support ratio profile metrics 2026-07-02 22:59:35 -07:00
dahyeon 02538ae300 Resolve lane opponents during extraction 2026-07-02 22:40:05 -07:00
dahyeon 43662a86d8 Collect match timelines during analysis 2026-07-02 22:38:24 -07:00
dahyeon 304f157b91 Accept League V4 entries without league ids 2026-07-02 22:32:17 -07:00
dahyeon bc36a8f0f0 Remove legacy Summoner fields 2026-07-02 22:27:24 -07:00
dahyeon 38cb97d86a Accept current Summoner V4 responses 2026-07-02 22:25:18 -07:00
dahyeon 9d43cc266c Log analysis job failures 2026-07-02 22:21:14 -07:00
dahyeon f447e0c6ab Keep API build info with dist 2026-07-02 22:11:45 -07:00
dahyeon ca7258d8d1 Update MVP implementation plan 2026-07-02 22:02:43 -07:00
dahyeon ad1a775bc1 Add web analysis screens 2026-07-02 22:00:01 -07:00
dahyeon 1ba87c0fe1 Fix API build output layout 2026-07-02 21:58:47 -07:00
dahyeon e1164e0b47 Add analysis REST API 2026-07-02 21:01:26 -07:00
dahyeon 770c198ccd Add analysis pipeline 2026-07-02 20:40:49 -07:00
dahyeon 256d776131 Add Riot API client 2026-07-02 14:18:26 -07:00
dahyeon 1f2805be23 Add shared feature registry 2026-07-02 14:04:28 -07:00
dahyeon 34ae20476f Wire API health endpoint 2026-07-02 13:56:01 -07:00
83 changed files with 19373 additions and 426 deletions

No files matched your search

+2
View File
@@ -20,11 +20,13 @@
},
"dependencies": {
"@infisical/sdk": "^5.0.2",
"@nestjs/bullmq": "^11.0.4",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@persona-lenz/shared": "workspace:*",
"bullmq": "^5.79.2",
"mongoose": "^9.7.3",
"redis": "^5.12.1",
"reflect-metadata": "^0.2.2",
+43
View File
@@ -0,0 +1,43 @@
import { NestFactory } from '@nestjs/core';
import { bootstrap } from './app.bootstrap';
import { configureApp } from './app.setup';
type ListenFunction = (port: string | number) => Promise<void>;
jest.mock('@nestjs/core', () => ({
NestFactory: {
create: jest.fn(),
},
}));
jest.mock('./app.setup', () => ({
API_GLOBAL_PREFIX: 'api',
configureApp: jest.fn(),
}));
describe('bootstrap', () => {
const originalPort = process.env.PORT;
afterEach(() => {
process.env.PORT = originalPort;
jest.clearAllMocks();
});
it('applies shared app setup before listening', async () => {
process.env.PORT = '3123';
const mockListen = jest
.fn<ReturnType<ListenFunction>, Parameters<ListenFunction>>()
.mockResolvedValue(undefined);
const mockApp = { listen: mockListen };
const mockedNestFactory = NestFactory as unknown as {
create: jest.MockedFunction<() => Promise<typeof mockApp>>;
};
mockedNestFactory.create.mockResolvedValue(mockApp);
await bootstrap();
expect(configureApp).toHaveBeenCalledWith(mockApp);
expect(mockListen).toHaveBeenCalledWith('3123');
});
});
+9
View File
@@ -0,0 +1,9 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { configureApp } from './app.setup';
export async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule);
configureApp(app);
await app.listen(process.env.PORT ?? 3000);
}
+3 -3
View File
@@ -14,9 +14,9 @@ describe('AppController', () => {
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
describe('health', () => {
it('returns the API health status', () => {
expect(appController.getHealth()).toEqual({ status: 'ok' });
});
});
});
+4 -4
View File
@@ -1,12 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { AppService, type HealthResponse } from './app.service';
@Controller()
@Controller('health')
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
getHealth(): HealthResponse {
return this.appService.getHealth();
}
}
+54
View File
@@ -0,0 +1,54 @@
import { getQueueToken } from '@nestjs/bullmq';
import { Test } from '@nestjs/testing';
import { AppModule } from './app.module';
import { AnalysisQueueService } from './modules/analysis/analysis-queue.service';
import {
ANALYSIS_QUEUE_NAME,
SEED_COLLECTION_QUEUE_NAME,
} from './modules/analysis/analysis.constants';
import { ConnectionService } from './modules/global/database/connection.service';
import { REDIS_CLIENT } from './modules/global/redis/redis.constants';
import { SecretService } from './modules/global/secret/secret.service';
function createSecretServiceStub() {
return {
get: jest.fn((key: string) => {
if (key === 'REDIS_URL')
return Promise.resolve('redis://localhost:6379/0');
return Promise.resolve('');
}),
ready: jest.fn().mockResolvedValue(undefined),
};
}
describe('AppModule', () => {
it('compiles with the analysis queue module wired', async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider(SecretService)
.useValue(createSecretServiceStub())
.overrideProvider(ConnectionService)
.useValue({})
.overrideProvider(REDIS_CLIENT)
.useValue({
destroy: jest.fn(),
quit: jest.fn().mockResolvedValue(undefined),
})
.overrideProvider(getQueueToken(ANALYSIS_QUEUE_NAME))
.useValue({
add: jest.fn(),
})
.overrideProvider(getQueueToken(SEED_COLLECTION_QUEUE_NAME))
.useValue({
add: jest.fn(),
})
.compile();
expect(moduleRef.get(AnalysisQueueService)).toBeInstanceOf(
AnalysisQueueService,
);
await moduleRef.close();
});
});
+2 -1
View File
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AnalysisModule } from './modules/analysis/analysis.module';
import { GlobalModule } from './modules/global/global.module';
@Module({
imports: [GlobalModule],
imports: [GlobalModule, AnalysisModule],
controllers: [AppController],
providers: [AppService],
})
+6 -2
View File
@@ -1,8 +1,12 @@
import { Injectable } from '@nestjs/common';
export interface HealthResponse {
status: 'ok';
}
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
getHealth(): HealthResponse {
return { status: 'ok' };
}
}
+7
View File
@@ -0,0 +1,7 @@
import type { INestApplication } from '@nestjs/common';
export const API_GLOBAL_PREFIX = 'api';
export function configureApp(app: INestApplication): void {
app.setGlobalPrefix(API_GLOBAL_PREFIX);
}
+12
View File
@@ -0,0 +1,12 @@
import { bootstrap } from './app.bootstrap';
import './main';
jest.mock('./app.bootstrap', () => ({
bootstrap: jest.fn().mockResolvedValue(undefined),
}));
describe('main', () => {
it('starts the Nest application bootstrap', () => {
expect(bootstrap).toHaveBeenCalledTimes(1);
});
});
+1 -6
View File
@@ -1,8 +1,3 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { bootstrap } from './app.bootstrap';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
void bootstrap();
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,455 @@
import type { AnalysisJob } from '../global/database/schemas';
import type { ConnectionService } from '../global/database/connection.service';
import type {
BaselineComputationJobData,
SeedCollectionJobData,
UserAnalysisJobData,
} from './analysis.types';
import {
BASELINE_COMPUTATION_JOB_NAME,
DEFAULT_SEED_COLLECTION_MATCH_COUNT,
FEATURE_RECOMPUTE_JOB_NAME,
SEED_COLLECTION_JOB_NAME,
USER_ANALYSIS_JOB_NAME,
} from './analysis.constants';
import { AnalysisQueueService } from './analysis-queue.service';
function createJobData(
overrides: Partial<UserAnalysisJobData> = {},
): UserAnalysisJobData {
return {
gameName: 'Hide on bush',
tagLine: 'KR1',
platformRoute: 'kr',
regionalRoute: 'asia',
queueId: 420,
requestedMatchCount: 20,
...overrides,
};
}
function createFindOneChain(
result: Pick<AnalysisJob, 'jobId' | 'status'> | null,
) {
const exec = jest
.fn<Promise<Pick<AnalysisJob, 'jobId' | 'status'> | null>, []>()
.mockResolvedValue(result);
const lean = jest.fn(() => ({ exec }));
const sort = jest.fn(() => ({ lean }));
return {
chain: { sort },
exec,
lean,
sort,
};
}
function createSeedCollectionJobData(
overrides: Partial<SeedCollectionJobData> = {},
): SeedCollectionJobData {
return {
platformRoute: 'kr',
queueId: 420,
sourceLimits: {
challenger: 50,
grandmaster: 50,
master: 50,
},
...overrides,
};
}
function createBaselineComputationJobData(
overrides: Partial<BaselineComputationJobData> = {},
): BaselineComputationJobData {
return {
platformRoute: 'kr',
queueId: 420,
cohort: 'MASTER_PLUS',
patch: 'ALL',
...overrides,
};
}
describe('AnalysisQueueService', () => {
it('creates an analysis job document and enqueues a BullMQ job', async () => {
const add = jest.fn().mockResolvedValue({ id: 'job-from-bull' });
const seedAdd = jest.fn();
const findOneChain = createFindOneChain(null);
const create = jest.fn().mockResolvedValue({});
const updateOne = jest.fn(() => ({
exec: jest.fn().mockResolvedValue({}),
}));
const analysisJobModel = {
create,
findOne: jest.fn(() => findOneChain.chain),
updateOne,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add } as never,
{ add: seedAdd } as never,
connectionService,
() => 'analysis-job-1',
);
const result = await service.enqueueUserAnalysis(createJobData());
expect(result).toEqual({ jobId: 'analysis-job-1', status: 'queued' });
expect(create).toHaveBeenCalledWith(
expect.objectContaining({
jobId: 'analysis-job-1',
jobType: USER_ANALYSIS_JOB_NAME,
gameName: 'Hide on bush',
tagLine: 'KR1',
status: 'queued',
}),
);
expect(add).toHaveBeenCalledWith(
USER_ANALYSIS_JOB_NAME,
createJobData(),
expect.objectContaining({
attempts: 2,
jobId: 'analysis-job-1',
}),
);
expect(seedAdd).not.toHaveBeenCalled();
});
it('creates a feature recompute job document and enqueues a BullMQ job', async () => {
const add = jest.fn().mockResolvedValue({ id: 'job-from-bull' });
const seedAdd = jest.fn();
const create = jest.fn().mockResolvedValue({});
const updateOne = jest.fn(() => ({
exec: jest.fn().mockResolvedValue({}),
}));
const analysisJobModel = {
create,
updateOne,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add } as never,
{ add: seedAdd } as never,
connectionService,
() => 'recompute-job-1',
);
const result = await service.enqueueFeatureRecompute({
platformRoute: 'kr',
queueId: 420,
batchSize: 25,
puuid: 'target-puuid',
});
expect(result).toEqual({ jobId: 'recompute-job-1', status: 'queued' });
expect(create).toHaveBeenCalledWith(
expect.objectContaining({
jobId: 'recompute-job-1',
jobType: FEATURE_RECOMPUTE_JOB_NAME,
platformRoute: 'kr',
queueId: 420,
requestedMatchCount: 0,
puuid: 'target-puuid',
status: 'queued',
}),
);
expect(add).toHaveBeenCalledWith(
FEATURE_RECOMPUTE_JOB_NAME,
{
platformRoute: 'kr',
queueId: 420,
batchSize: 25,
puuid: 'target-puuid',
},
expect.objectContaining({
attempts: 1,
jobId: 'recompute-job-1',
}),
);
expect(seedAdd).not.toHaveBeenCalled();
});
it('creates a seed collection job document and enqueues the seed queue', async () => {
const analysisAdd = jest.fn();
const seedAdd = jest.fn().mockResolvedValue({ id: 'job-from-bull' });
const create = jest.fn().mockResolvedValue({});
const updateOne = jest.fn(() => ({
exec: jest.fn().mockResolvedValue({}),
}));
const analysisJobModel = {
create,
updateOne,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add: analysisAdd } as never,
{ add: seedAdd } as never,
connectionService,
() => 'seed-job-1',
);
const result = await service.enqueueSeedCollection(
createSeedCollectionJobData(),
);
expect(result).toEqual({ jobId: 'seed-job-1', status: 'queued' });
expect(create).toHaveBeenCalledWith(
expect.objectContaining({
jobId: 'seed-job-1',
jobType: SEED_COLLECTION_JOB_NAME,
platformRoute: 'kr',
queueId: 420,
requestedMatchCount: DEFAULT_SEED_COLLECTION_MATCH_COUNT,
status: 'queued',
}),
);
expect(seedAdd).toHaveBeenCalledWith(
SEED_COLLECTION_JOB_NAME,
createSeedCollectionJobData(),
expect.objectContaining({
attempts: 1,
jobId: 'seed-job-1',
}),
);
expect(analysisAdd).not.toHaveBeenCalled();
});
it('creates a baseline computation job document and enqueues an analysis queue job', async () => {
const add = jest.fn().mockResolvedValue({ id: 'job-from-bull' });
const seedAdd = jest.fn();
const create = jest.fn().mockResolvedValue({});
const updateOne = jest.fn(() => ({
exec: jest.fn().mockResolvedValue({}),
}));
const analysisJobModel = {
create,
updateOne,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add } as never,
{ add: seedAdd } as never,
connectionService,
() => 'baseline-job-1',
);
const result = await service.enqueueBaselineComputation(
createBaselineComputationJobData(),
);
expect(result).toEqual({ jobId: 'baseline-job-1', status: 'queued' });
expect(create).toHaveBeenCalledWith(
expect.objectContaining({
jobId: 'baseline-job-1',
jobType: BASELINE_COMPUTATION_JOB_NAME,
platformRoute: 'kr',
queueId: 420,
requestedMatchCount: 0,
status: 'queued',
}),
);
expect(add).toHaveBeenCalledWith(
BASELINE_COMPUTATION_JOB_NAME,
createBaselineComputationJobData(),
expect.objectContaining({
attempts: 1,
jobId: 'baseline-job-1',
}),
);
expect(seedAdd).not.toHaveBeenCalled();
});
it('returns an existing active job instead of enqueueing a duplicate', async () => {
const add = jest.fn();
const findOneChain = createFindOneChain({
jobId: 'existing-job',
status: 'processing',
});
const analysisJobModel = {
create: jest.fn(),
findOne: jest.fn(() => findOneChain.chain),
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add } as never,
{ add: jest.fn() } as never,
connectionService,
() => 'new-job',
);
await expect(service.enqueueUserAnalysis(createJobData())).resolves.toEqual(
{
jobId: 'existing-job',
status: 'processing',
},
);
expect(add).not.toHaveBeenCalled();
expect(analysisJobModel.create).not.toHaveBeenCalled();
});
it('marks the pre-created job failed when BullMQ enqueue fails', async () => {
const add = jest.fn().mockRejectedValue(new Error('redis unavailable'));
const findOneChain = createFindOneChain(null);
const create = jest.fn().mockResolvedValue({});
const updateOne = jest.fn(() => ({
exec: jest.fn().mockResolvedValue({}),
}));
const analysisJobModel = {
create,
findOne: jest.fn(() => findOneChain.chain),
updateOne,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add } as never,
{ add: jest.fn() } as never,
connectionService,
() => 'analysis-job-1',
);
await expect(service.enqueueUserAnalysis(createJobData())).rejects.toThrow(
'redis unavailable',
);
expect(updateOne).toHaveBeenCalledWith(
{ jobId: 'analysis-job-1' },
{
$set: {
status: 'failed',
stage: 'enqueue',
error: 'Analysis could not be queued.',
},
},
);
});
it('marks a pre-created feature recompute job failed when BullMQ enqueue fails', async () => {
const add = jest.fn().mockRejectedValue(new Error('redis unavailable'));
const create = jest.fn().mockResolvedValue({});
const updateOne = jest.fn(() => ({
exec: jest.fn().mockResolvedValue({}),
}));
const analysisJobModel = {
create,
updateOne,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add } as never,
{ add: jest.fn() } as never,
connectionService,
() => 'recompute-job-1',
);
await expect(
service.enqueueFeatureRecompute({
platformRoute: 'kr',
queueId: 420,
batchSize: 25,
}),
).rejects.toThrow('redis unavailable');
expect(updateOne).toHaveBeenCalledWith(
{ jobId: 'recompute-job-1' },
{
$set: {
status: 'failed',
stage: 'enqueue',
error: 'Analysis could not be queued.',
},
},
);
});
it('marks a pre-created seed collection job failed when BullMQ enqueue fails', async () => {
const analysisAdd = jest.fn();
const seedAdd = jest.fn().mockRejectedValue(new Error('redis unavailable'));
const create = jest.fn().mockResolvedValue({});
const updateOne = jest.fn(() => ({
exec: jest.fn().mockResolvedValue({}),
}));
const analysisJobModel = {
create,
updateOne,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add: analysisAdd } as never,
{ add: seedAdd } as never,
connectionService,
() => 'seed-job-1',
);
await expect(
service.enqueueSeedCollection(createSeedCollectionJobData()),
).rejects.toThrow('redis unavailable');
expect(updateOne).toHaveBeenCalledWith(
{ jobId: 'seed-job-1' },
{
$set: {
status: 'failed',
stage: 'enqueue',
error: 'Analysis could not be queued.',
},
},
);
expect(analysisAdd).not.toHaveBeenCalled();
});
it('serializes identical in-process requests before creating a duplicate job', async () => {
const add = jest.fn().mockResolvedValue({ id: 'analysis-job-1' });
let activeJob: Pick<AnalysisJob, 'jobId' | 'status'> | null = null;
const findOne = jest.fn(() => ({
sort: jest.fn(() => ({
lean: jest.fn(() => ({
exec: jest
.fn<Promise<Pick<AnalysisJob, 'jobId' | 'status'> | null>, []>()
.mockImplementation(() => Promise.resolve(activeJob)),
})),
})),
}));
const create = jest.fn().mockImplementation(() => {
activeJob = { jobId: 'analysis-job-1', status: 'queued' };
return Promise.resolve({});
});
const analysisJobModel = {
create,
findOne,
updateOne: jest.fn(),
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(analysisJobModel),
} as unknown as ConnectionService;
const service = new AnalysisQueueService(
{ add } as never,
{ add: jest.fn() } as never,
connectionService,
() => (create.mock.calls.length === 0 ? 'analysis-job-1' : 'unexpected'),
);
const [firstResult, secondResult] = await Promise.all([
service.enqueueUserAnalysis(createJobData()),
service.enqueueUserAnalysis(createJobData()),
]);
expect(firstResult).toEqual({ jobId: 'analysis-job-1', status: 'queued' });
expect(secondResult).toEqual({ jobId: 'analysis-job-1', status: 'queued' });
expect(create).toHaveBeenCalledTimes(1);
expect(add).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,391 @@
import { InjectQueue } from '@nestjs/bullmq';
import { Inject, Injectable } from '@nestjs/common';
import type { AnalysisRequestAcceptedDto } from '@persona-lenz/shared';
import type { Queue } from 'bullmq';
import { randomUUID } from 'node:crypto';
import { ConnectionService } from '../global/database/connection.service';
import type { AnalysisJob, SeedSource } from '../global/database/schemas';
import {
ANALYSIS_JOB_ID_FACTORY,
ACTIVE_ANALYSIS_JOB_STATUSES,
ANALYSIS_QUEUE_NAME,
BASELINE_COMPUTATION_JOB_NAME,
DEFAULT_SEED_COLLECTION_MATCH_COUNT,
FEATURE_RECOMPUTE_JOB_NAME,
normalizeFeatureRecomputeBatchSize,
normalizeRequestedMatchCount,
SEED_COLLECTION_JOB_NAME,
SEED_COLLECTION_QUEUE_NAME,
USER_ANALYSIS_JOB_NAME,
} from './analysis.constants';
import type {
BaselineComputationJobData,
FeatureRecomputeJobData,
SeedCollectionJobData,
UserAnalysisJobData,
} from './analysis.types';
type JobIdFactory = () => string;
type AnalysisQueueJobData =
UserAnalysisJobData | FeatureRecomputeJobData | BaselineComputationJobData;
type AnalysisQueueJobName =
| typeof USER_ANALYSIS_JOB_NAME
| typeof FEATURE_RECOMPUTE_JOB_NAME
| typeof BASELINE_COMPUTATION_JOB_NAME;
type SeedCollectionQueueJobName = typeof SEED_COLLECTION_JOB_NAME;
type ActiveAnalysisJob = Pick<AnalysisJob, 'jobId'> & {
status: Extract<AnalysisJob['status'], 'queued' | 'processing'>;
};
@Injectable()
export class AnalysisQueueService {
constructor(
@InjectQueue(ANALYSIS_QUEUE_NAME)
private readonly analysisQueue: Queue<
AnalysisQueueJobData,
void,
AnalysisQueueJobName
>,
@InjectQueue(SEED_COLLECTION_QUEUE_NAME)
private readonly seedCollectionQueue: Queue<
SeedCollectionJobData,
void,
SeedCollectionQueueJobName
>,
private readonly connectionService: ConnectionService,
@Inject(ANALYSIS_JOB_ID_FACTORY)
private readonly jobIdFactory: JobIdFactory = randomUUID,
) {}
public async enqueueUserAnalysis(
data: UserAnalysisJobData,
): Promise<AnalysisRequestAcceptedDto> {
const normalizedData = {
...data,
requestedMatchCount: normalizeRequestedMatchCount(
data.requestedMatchCount,
),
};
const duplicateRequestKey = this.duplicateRequestKey(normalizedData);
while (this.pendingDuplicateRequestKeys.has(duplicateRequestKey)) {
await this.sleep(10);
}
this.pendingDuplicateRequestKeys.add(duplicateRequestKey);
try {
return await this.enqueueUserAnalysisWithoutDuplicateRequestRace(
normalizedData,
);
} finally {
this.pendingDuplicateRequestKeys.delete(duplicateRequestKey);
}
}
public async enqueueFeatureRecompute(
data: FeatureRecomputeJobData,
): Promise<AnalysisRequestAcceptedDto> {
const normalizedData = this.normalizeFeatureRecomputeData(data);
const analysisJobModel =
await this.connectionService.getModel('analysisJob');
const jobId = this.jobIdFactory();
await analysisJobModel.create({
jobId,
jobType: FEATURE_RECOMPUTE_JOB_NAME,
puuid: normalizedData.puuid,
platformRoute: normalizedData.platformRoute,
queueId: normalizedData.queueId,
requestedMatchCount: 0,
status: 'queued',
stage: 'queued',
progress: {
fetchedMatches: 0,
totalMatches: 0,
},
});
try {
await this.analysisQueue.add(FEATURE_RECOMPUTE_JOB_NAME, normalizedData, {
attempts: 1,
jobId,
});
} catch (error) {
await analysisJobModel
.updateOne(
{ jobId },
{
$set: {
status: 'failed',
stage: 'enqueue',
error: this.publicErrorMessage(),
},
},
)
.exec();
throw error;
}
return {
jobId,
status: 'queued',
};
}
public async enqueueSeedCollection(
data: SeedCollectionJobData,
): Promise<AnalysisRequestAcceptedDto> {
const normalizedData = this.normalizeSeedCollectionData(data);
const analysisJobModel =
await this.connectionService.getModel('analysisJob');
const jobId = this.jobIdFactory();
await analysisJobModel.create({
jobId,
jobType: SEED_COLLECTION_JOB_NAME,
platformRoute: normalizedData.platformRoute,
queueId: normalizedData.queueId,
requestedMatchCount: DEFAULT_SEED_COLLECTION_MATCH_COUNT,
status: 'queued',
stage: 'queued',
progress: {
fetchedMatches: 0,
totalMatches: 0,
},
});
try {
await this.seedCollectionQueue.add(
SEED_COLLECTION_JOB_NAME,
normalizedData,
{
attempts: 1,
jobId,
},
);
} catch (error) {
await analysisJobModel
.updateOne(
{ jobId },
{
$set: {
status: 'failed',
stage: 'enqueue',
error: this.publicErrorMessage(),
},
},
)
.exec();
throw error;
}
return {
jobId,
status: 'queued',
};
}
public async enqueueBaselineComputation(
data: BaselineComputationJobData,
): Promise<AnalysisRequestAcceptedDto> {
const normalizedData = this.normalizeBaselineComputationData(data);
const analysisJobModel =
await this.connectionService.getModel('analysisJob');
const jobId = this.jobIdFactory();
await analysisJobModel.create({
jobId,
jobType: BASELINE_COMPUTATION_JOB_NAME,
platformRoute: normalizedData.platformRoute,
queueId: normalizedData.queueId,
requestedMatchCount: 0,
status: 'queued',
stage: 'queued',
progress: {
fetchedMatches: 0,
totalMatches: 0,
},
});
try {
await this.analysisQueue.add(
BASELINE_COMPUTATION_JOB_NAME,
normalizedData,
{
attempts: 1,
jobId,
},
);
} catch (error) {
await analysisJobModel
.updateOne(
{ jobId },
{
$set: {
status: 'failed',
stage: 'enqueue',
error: this.publicErrorMessage(),
},
},
)
.exec();
throw error;
}
return {
jobId,
status: 'queued',
};
}
private readonly pendingDuplicateRequestKeys = new Set<string>();
private async enqueueUserAnalysisWithoutDuplicateRequestRace(
normalizedData: UserAnalysisJobData,
): Promise<AnalysisRequestAcceptedDto> {
const analysisJobModel =
await this.connectionService.getModel('analysisJob');
const existingJob = await this.findActiveJob(
analysisJobModel,
normalizedData,
);
if (existingJob) {
return {
jobId: existingJob.jobId,
status: existingJob.status,
};
}
const jobId = this.jobIdFactory();
await analysisJobModel.create({
jobId,
jobType: USER_ANALYSIS_JOB_NAME,
gameName: normalizedData.gameName,
tagLine: normalizedData.tagLine,
platformRoute: normalizedData.platformRoute,
queueId: normalizedData.queueId,
requestedMatchCount: normalizedData.requestedMatchCount,
status: 'queued',
stage: 'queued',
progress: {
fetchedMatches: 0,
totalMatches: 0,
},
});
try {
await this.analysisQueue.add(USER_ANALYSIS_JOB_NAME, normalizedData, {
attempts: 2,
backoff: {
type: 'exponential',
delay: 1_000,
},
jobId,
});
} catch (error) {
await analysisJobModel
.updateOne(
{ jobId },
{
$set: {
status: 'failed',
stage: 'enqueue',
error: this.publicErrorMessage(),
},
},
)
.exec();
throw error;
}
return {
jobId,
status: 'queued',
};
}
private async findActiveJob(
analysisJobModel: Awaited<ReturnType<ConnectionService['getModel']>>,
data: UserAnalysisJobData,
): Promise<ActiveAnalysisJob | null> {
return analysisJobModel
.findOne({
gameName: data.gameName,
tagLine: data.tagLine,
platformRoute: data.platformRoute,
queueId: data.queueId,
status: { $in: ACTIVE_ANALYSIS_JOB_STATUSES },
})
.sort({ createdAt: -1 })
.lean<ActiveAnalysisJob>()
.exec();
}
private errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
private publicErrorMessage(): string {
return 'Analysis could not be queued.';
}
private normalizeFeatureRecomputeData(
data: FeatureRecomputeJobData,
): FeatureRecomputeJobData {
const puuid = data.puuid?.trim();
return {
platformRoute: data.platformRoute,
queueId: data.queueId,
batchSize: normalizeFeatureRecomputeBatchSize(data.batchSize),
...(puuid ? { puuid } : {}),
};
}
private normalizeSeedCollectionData(
data: SeedCollectionJobData,
): SeedCollectionJobData {
return {
platformRoute: data.platformRoute,
queueId: data.queueId,
...(data.sourceLimits
? { sourceLimits: this.normalizeSeedSourceLimits(data.sourceLimits) }
: {}),
};
}
private normalizeBaselineComputationData(
data: BaselineComputationJobData,
): BaselineComputationJobData {
const patch = data.patch?.trim();
return {
platformRoute: data.platformRoute,
queueId: data.queueId,
cohort: data.cohort ?? 'MASTER_PLUS',
patch: patch && patch.length > 0 ? patch : 'ALL',
};
}
private normalizeSeedSourceLimits(
sourceLimits: NonNullable<SeedCollectionJobData['sourceLimits']>,
): NonNullable<SeedCollectionJobData['sourceLimits']> {
const normalizedSourceLimits: Partial<Record<SeedSource, number>> = {};
for (const [source, limit] of Object.entries(sourceLimits)) {
if (typeof limit === 'number' && Number.isFinite(limit) && limit >= 0) {
normalizedSourceLimits[source as SeedSource] = Math.trunc(limit);
}
}
return normalizedSourceLimits;
}
private duplicateRequestKey(data: UserAnalysisJobData): string {
return [
data.platformRoute,
data.queueId,
data.gameName.trim().toLocaleLowerCase(),
data.tagLine.trim().toLocaleLowerCase(),
].join(':');
}
private async sleep(durationMs: number): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, durationMs));
}
}
@@ -0,0 +1,168 @@
import { FEATURE_SCHEMA_VERSION } from '@persona-lenz/shared';
import type { ConnectionService } from '../global/database/connection.service';
import { AnalysisReadService } from './analysis-read.service';
function createLeanExec<T>(value: T) {
return {
lean: jest.fn(() => ({
exec: jest.fn().mockResolvedValue(value),
})),
};
}
describe('AnalysisReadService', () => {
it('queries analysis jobs by jobId and serializes public failed errors', async () => {
const findOne = jest.fn(() =>
createLeanExec({
error: 'internal host redis.local refused connection',
jobId: 'analysis-job-1',
progress: { fetchedMatches: 0, totalMatches: 20 },
status: 'failed',
}),
);
const service = new AnalysisReadService({
getModel: jest.fn().mockResolvedValue({ findOne }),
} as unknown as ConnectionService);
await expect(service.getJobStatus('analysis-job-1')).resolves.toEqual({
error: 'Analysis failed during processing.',
jobId: 'analysis-job-1',
progress: { fetchedMatches: 0, totalMatches: 20 },
status: 'failed',
});
expect(findOne).toHaveBeenCalledWith({ jobId: 'analysis-job-1' });
});
it('preserves public Riot account not-found job errors', async () => {
const findOne = jest.fn(() =>
createLeanExec({
error: 'Riot account was not found for the selected region.',
jobId: 'analysis-job-1',
progress: { fetchedMatches: 0, totalMatches: 0 },
stage: 'resolve-account',
status: 'failed',
}),
);
const service = new AnalysisReadService({
getModel: jest.fn().mockResolvedValue({ findOne }),
} as unknown as ConnectionService);
await expect(service.getJobStatus('analysis-job-1')).resolves.toEqual({
error: 'Riot account was not found for the selected region.',
jobId: 'analysis-job-1',
progress: { fetchedMatches: 0, totalMatches: 0 },
stage: 'resolve-account',
status: 'failed',
});
});
it('distinguishes analyzed accounts with no ranked games from missing accounts', async () => {
const accountFindOne = jest.fn(() =>
createLeanExec({
gameName: 'Hide on bush',
profileIconId: 1,
tagLine: 'KR1',
tiers: [],
}),
);
const profileFindOne = jest.fn(() => createLeanExec(null));
const service = new AnalysisReadService({
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'account'
? { findOne: accountFindOne }
: { findOne: profileFindOne },
),
),
} as unknown as ConnectionService);
await expect(
service.getLatestPlayerAnalysis('target-puuid', 420),
).rejects.toThrow('분석할 랭크 게임이 없음');
});
it('queries account and profile by puuid/queue and applies lower-is-better scoring', async () => {
const accountFindOne = jest.fn(() =>
createLeanExec({
gameName: 'Hide on bush',
profileIconId: 1,
tagLine: 'KR1',
tiers: [],
}),
);
const profileFindOne = jest.fn(() =>
createLeanExec({
championPool: [{ championId: 103, games: 4, wins: 3 }],
confidence: 0.9,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
mainRole: 'MIDDLE',
profile: {
kda: 0.8,
killParticipation: 0.7,
damageShare: 0.6,
damagePerMin: 0.5,
goldPerMin: 0.4,
csPerMin: 0.3,
visionScorePerMin: 0.2,
wardsKilledPerMin: 0.1,
controlWardsPlaced: 0.2,
deathsPerMin: 0.1,
objectiveParticipation: 0.6,
soloKills: 0.4,
},
queueId: 420,
sampleGameCount: 12,
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
}),
);
const service = new AnalysisReadService({
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'account'
? { findOne: accountFindOne }
: { findOne: profileFindOne },
),
),
} as unknown as ConnectionService);
const analysis = await service.getLatestPlayerAnalysis('target-puuid', 420);
expect(accountFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid' });
expect(profileFindOne).toHaveBeenCalledWith({
puuid: 'target-puuid',
queueId: 420,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
});
expect(analysis.profile.playstyle.kda).toBe(0.8);
expect(analysis.profile.playstyle.goldDiffAt10).toBeUndefined();
expect(analysis.profile.playstyle.objectivePreWardRate).toBeUndefined();
expect(
analysis.strengths.some((metric) => metric.metricId === 'goldDiffAt10'),
).toBe(false);
expect(
analysis.weaknesses.some(
(metric) => metric.metricId === 'deathWithShutdownBountyGivenRate',
),
).toBe(false);
expect(analysis.strengths).toHaveLength(12);
expect(analysis.weaknesses).toHaveLength(12);
expect(analysis.strengths.slice(0, 3)).toEqual([
{ metricId: 'deathsPerMin', value: 0.1 },
{ metricId: 'kda', value: 0.8 },
{ metricId: 'killParticipation', value: 0.7 },
]);
expect(analysis.strengths.at(-1)).toEqual({
metricId: 'wardsKilledPerMin',
value: 0.1,
});
expect(analysis.weaknesses.slice(0, 3)).toEqual([
{ metricId: 'wardsKilledPerMin', value: 0.1 },
{ metricId: 'visionScorePerMin', value: 0.2 },
{ metricId: 'controlWardsPlaced', value: 0.2 },
]);
expect(analysis.weaknesses.at(-1)).toEqual({
metricId: 'deathsPerMin',
value: 0.1,
});
});
});
@@ -0,0 +1,260 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import {
FEATURE_SCHEMA_VERSION,
METRICS,
type AnalysisJobStatusDto,
type MetricValueDto,
type PlayerAnalysisDto,
type SimilarPlayersDto,
} from '@persona-lenz/shared';
import { ConnectionService } from '../global/database/connection.service';
import type {
Account,
AnalysisJob,
PlayerProfile,
TierInfo,
} from '../global/database/schemas';
import { SimilarPlayerService } from './similar-player.service';
import type { SimilarPlayer } from './analysis.types';
type JobStatusRecord = Pick<
AnalysisJob,
'error' | 'jobId' | 'progress' | 'puuid' | 'stage' | 'status'
>;
type AccountSummaryRecord = Pick<
Account,
'gameName' | 'profileIconId' | 'tagLine' | 'tiers'
>;
type CounterpartAccountRecord = Pick<Account, 'gameName' | 'puuid' | 'tagLine'>;
type PlayerProfileRecord = Pick<
PlayerProfile,
| 'championPool'
| 'confidence'
| 'featureSchemaVersion'
| 'mainRole'
| 'profile'
| 'queueId'
| 'sampleGameCount'
| 'updatedAt'
>;
@Injectable()
export class AnalysisReadService {
constructor(
private readonly connectionService: ConnectionService,
private readonly similarPlayerService?: SimilarPlayerService,
) {}
public async getJobStatus(jobId: string): Promise<AnalysisJobStatusDto> {
const analysisJobModel =
await this.connectionService.getModel('analysisJob');
const job = await analysisJobModel
.findOne({ jobId })
.lean<JobStatusRecord>()
.exec();
if (!job) {
throw new NotFoundException('Analysis job not found.');
}
return {
jobId: job.jobId,
status: job.status,
stage: job.stage,
puuid: job.puuid,
progress: job.progress,
error: this.publicJobError(job.error),
};
}
public async getLatestPlayerAnalysis(
puuid: string,
queueId: number,
): Promise<PlayerAnalysisDto> {
const [account, profile] = await Promise.all([
this.findAccount(puuid),
this.findPlayerProfile(puuid, queueId),
]);
if (!account) {
throw new NotFoundException('Player account not found.');
}
if (!profile) {
throw new NotFoundException('분석할 랭크 게임이 없음');
}
return {
account: {
gameName: account.gameName,
tagLine: account.tagLine,
profileIconId: account.profileIconId,
tiers: account.tiers.map((tier) => this.toTierDto(tier)),
},
profile: {
mainRole: profile.mainRole,
queueId: profile.queueId,
sampleGameCount: profile.sampleGameCount,
championPool: profile.championPool,
playstyle: Object.fromEntries(
Object.entries(profile.profile).map(([metricId, value]) => [
metricId,
this.clampMetricValue(value),
]),
),
featureSchemaVersion: profile.featureSchemaVersion,
confidence: profile.confidence,
},
strengths: this.resolveMetricHighlights(profile.profile, 'strength'),
weaknesses: this.resolveMetricHighlights(profile.profile, 'weakness'),
updatedAt: profile.updatedAt.toISOString(),
};
}
public async getSimilarPlayers(
puuid: string,
queueId: number,
limit: number,
): Promise<SimilarPlayersDto> {
if (!this.similarPlayerService) {
throw new Error('SimilarPlayerService is not configured.');
}
const similarPlayersResult =
await this.similarPlayerService.findSimilarPlayers(puuid, queueId, limit);
const accountsByPuuid = await this.findCounterpartAccounts(
similarPlayersResult.matches.map((match) => match.puuid),
);
return {
puuid: similarPlayersResult.puuid,
queueId: similarPlayersResult.queueId,
profileUpdatedAt: similarPlayersResult.profileUpdatedAt.toISOString(),
matches: similarPlayersResult.matches.map((match, index) =>
this.toSimilarPlayerDto(match, accountsByPuuid.get(match.puuid), index),
),
};
}
private async findAccount(
puuid: string,
): Promise<AccountSummaryRecord | null> {
const accountModel = await this.connectionService.getModel('account');
return accountModel.findOne({ puuid }).lean<AccountSummaryRecord>().exec();
}
private async findCounterpartAccounts(
puuids: string[],
): Promise<Map<string, CounterpartAccountRecord>> {
const uniquePuuids = Array.from(new Set(puuids));
if (uniquePuuids.length === 0) return new Map();
const accountModel = await this.connectionService.getModel('account');
const accounts = await accountModel
.find({ puuid: { $in: uniquePuuids } })
.lean<CounterpartAccountRecord[]>()
.exec();
return new Map(accounts.map((account) => [account.puuid, account]));
}
private async findPlayerProfile(
puuid: string,
queueId: number,
): Promise<PlayerProfileRecord | null> {
const playerProfileModel =
await this.connectionService.getModel('playerProfile');
return playerProfileModel
.findOne({ puuid, queueId, featureSchemaVersion: FEATURE_SCHEMA_VERSION })
.lean<PlayerProfileRecord>()
.exec();
}
private resolveMetricHighlights(
profile: Record<string, number>,
direction: 'strength' | 'weakness',
): MetricValueDto[] {
return METRICS.flatMap((metric) => {
const rawValue = profile[metric.id];
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
return [];
}
const value = this.clampMetricValue(rawValue);
return {
metricId: metric.id,
score: metric.direction === 'lowerIsBetter' ? 1 - value : value,
value,
};
})
.sort((left, right) =>
direction === 'strength'
? right.score - left.score
: left.score - right.score,
)
.map(({ metricId, value }) => ({ metricId, value }));
}
private clampMetricValue(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value)
? Math.max(0, Math.min(1, value))
: 0;
}
private toTierDto(
tier: TierInfo,
): PlayerAnalysisDto['account']['tiers'][number] {
return {
queueType: tier.queueType,
tier: tier.tier,
rank: tier.rank,
leaguePoints: tier.leaguePoints,
wins: tier.wins,
losses: tier.losses,
fetchedAt: tier.fetchedAt?.toISOString(),
};
}
private toSimilarPlayerDto(
match: SimilarPlayer,
account: CounterpartAccountRecord | undefined,
index: number,
): SimilarPlayersDto['matches'][number] {
return {
displayId: `similar-${index + 1}`,
riotId: account
? {
gameName: account.gameName,
tagLine: account.tagLine,
}
: null,
similarityScore: match.similarityScore,
finalScore: match.finalScore,
tier: match.tier,
division: match.division,
leaguePoints: match.leaguePoints,
tierComparison: match.tierComparison,
mainRole: match.mainRole,
mainChampions: match.mainChampions,
sampleGameCount: match.sampleGameCount,
similarMetrics: match.similarMetrics,
strongerMetrics: match.strongerMetrics,
weakerMetrics: match.weakerMetrics,
};
}
private publicJobError(error: string | undefined): string | null {
if (!error) return null;
if (
error === 'Analysis failed during processing.' ||
error === 'Riot API key is invalid or expired.' ||
error === 'Riot account was not found for the selected region.' ||
error === 'Analysis could not be queued.'
) {
return error;
}
return 'Analysis failed during processing.';
}
}
@@ -0,0 +1,34 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
const REQUEST_WINDOW_MS = 60_000;
const MAX_REQUESTS_PER_WINDOW = 10;
interface RequestWindow {
count: number;
resetAt: number;
}
@Injectable()
export class AnalysisRequestThrottleService {
private readonly requestWindows = new Map<string, RequestWindow>();
public assertAllowed(clientKey: string, now = Date.now()): void {
const existingWindow = this.requestWindows.get(clientKey);
if (!existingWindow || existingWindow.resetAt <= now) {
this.requestWindows.set(clientKey, {
count: 1,
resetAt: now + REQUEST_WINDOW_MS,
});
return;
}
if (existingWindow.count >= MAX_REQUESTS_PER_WINDOW) {
throw new HttpException(
'Too many analysis requests.',
HttpStatus.TOO_MANY_REQUESTS,
);
}
existingWindow.count += 1;
}
}
@@ -0,0 +1,40 @@
export const ANALYSIS_QUEUE_NAME = 'analysis';
export const SEED_COLLECTION_QUEUE_NAME = 'seed-collection';
export const USER_ANALYSIS_JOB_NAME = 'user-analysis';
export const FEATURE_RECOMPUTE_JOB_NAME = 'feature-recompute';
export const SEED_COLLECTION_JOB_NAME = 'seed-collection';
export const BASELINE_COMPUTATION_JOB_NAME = 'baseline-computation';
export const ANALYSIS_JOB_ID_FACTORY = Symbol('ANALYSIS_JOB_ID_FACTORY');
export const DEFAULT_ANALYSIS_MATCH_COUNT = 20;
export const MAX_ANALYSIS_MATCH_COUNT = 50;
export const DEFAULT_SEED_COLLECTION_MATCH_COUNT = 30;
export const DEFAULT_SEED_COLLECTION_QUEUE_TYPE = 'RANKED_SOLO_5x5';
export const DEFAULT_SEED_COLLECTION_SOURCE_LIMIT = 50;
export const DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE = 100;
export const MAX_FEATURE_RECOMPUTE_BATCH_SIZE = 500;
export const ACTIVE_ANALYSIS_JOB_STATUSES = ['queued', 'processing'] as const;
export function normalizeRequestedMatchCount(
requestedMatchCount: number,
): number {
if (!Number.isFinite(requestedMatchCount) || requestedMatchCount <= 0) {
return DEFAULT_ANALYSIS_MATCH_COUNT;
}
return Math.min(Math.trunc(requestedMatchCount), MAX_ANALYSIS_MATCH_COUNT);
}
export function normalizeFeatureRecomputeBatchSize(batchSize: number): number {
if (!Number.isFinite(batchSize) || batchSize <= 0) {
return DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE;
}
const normalizedBatchSize = Math.trunc(batchSize);
if (normalizedBatchSize <= 0) {
return DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE;
}
return Math.min(normalizedBatchSize, MAX_FEATURE_RECOMPUTE_BATCH_SIZE);
}
@@ -0,0 +1,180 @@
import {
BadRequestException,
Body,
Controller,
Get,
HttpCode,
Param,
Post,
Query,
Req,
} from '@nestjs/common';
import type {
AnalysisJobStatusDto,
AnalysisRequestAcceptedDto,
PlayerAnalysisDto,
SimilarPlayersDto,
} from '@persona-lenz/shared';
import {
RIOT_PLATFORM_ROUTES,
toRegionalRoute,
type RiotPlatformRoute,
} from '../riot/riot.types';
import { AnalysisQueueService } from './analysis-queue.service';
import {
DEFAULT_ANALYSIS_MATCH_COUNT,
MAX_ANALYSIS_MATCH_COUNT,
normalizeRequestedMatchCount,
} from './analysis.constants';
import { AnalysisReadService } from './analysis-read.service';
import { AnalysisRequestThrottleService } from './analysis-request-throttle.service';
import type { UserAnalysisJobData } from './analysis.types';
import type { Request } from 'express';
@Controller()
export class AnalysisController {
constructor(
private readonly analysisQueueService: AnalysisQueueService,
private readonly analysisReadService: AnalysisReadService,
private readonly analysisRequestThrottleService: AnalysisRequestThrottleService,
) {}
@Post('analysis/request')
@HttpCode(202)
public async requestAnalysis(
@Body() body: unknown,
@Req() request: Request,
): Promise<AnalysisRequestAcceptedDto> {
const data = this.parseAnalysisRequest(body);
this.analysisRequestThrottleService.assertAllowed(
this.resolveClientKey(request),
);
return this.analysisQueueService.enqueueUserAnalysis(data);
}
@Get('analysis/jobs/:jobId')
public async getJobStatus(
@Param('jobId') jobId: string,
): Promise<AnalysisJobStatusDto> {
return this.analysisReadService.getJobStatus(jobId);
}
@Get('players/:puuid/analysis/latest')
public async getLatestPlayerAnalysis(
@Param('puuid') puuid: string,
@Query('queueId') rawQueueId?: string,
): Promise<PlayerAnalysisDto> {
return this.analysisReadService.getLatestPlayerAnalysis(
this.parsePuuid(puuid),
this.parseQueueId(rawQueueId),
);
}
@Get('players/:puuid/similar-players')
public async getSimilarPlayers(
@Param('puuid') puuid: string,
@Query('queueId') rawQueueId?: string,
@Query('limit') rawLimit?: string,
): Promise<SimilarPlayersDto> {
return this.analysisReadService.getSimilarPlayers(
this.parsePuuid(puuid),
this.parseQueueId(rawQueueId),
this.parseSimilarPlayersLimit(rawLimit),
);
}
private parseAnalysisRequest(body: unknown): UserAnalysisJobData {
const record = this.requireRecord(body);
const gameName = this.parseTrimmedString(
record.gameName,
'gameName',
3,
16,
);
const tagLine = this.parseTrimmedString(record.tagLine, 'tagLine', 3, 5);
const platformRoute = this.parsePlatformRoute(record.platform ?? 'kr');
const requestedMatchCount = this.parseMatchCount(record.matchCount);
return {
gameName,
tagLine,
platformRoute,
regionalRoute: toRegionalRoute(platformRoute),
queueId: 420,
requestedMatchCount,
};
}
private requireRecord(value: unknown): Record<string, unknown> {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new BadRequestException('Request body must be an object.');
}
return value as Record<string, unknown>;
}
private parseTrimmedString(
value: unknown,
fieldName: string,
minimumLength: number,
maximumLength: number,
): string {
if (typeof value !== 'string') {
throw new BadRequestException(`${fieldName} must be a string.`);
}
const trimmed = value.trim();
if (trimmed.length < minimumLength || trimmed.length > maximumLength) {
throw new BadRequestException(`${fieldName} is out of range.`);
}
return trimmed;
}
private parsePlatformRoute(value: unknown): RiotPlatformRoute {
if (
typeof value !== 'string' ||
!RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
) {
throw new BadRequestException('platform is unsupported.');
}
return value as RiotPlatformRoute;
}
private parseMatchCount(value: unknown): number {
if (value === undefined) return DEFAULT_ANALYSIS_MATCH_COUNT;
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new BadRequestException('matchCount must be a finite number.');
}
return normalizeRequestedMatchCount(
Math.min(Math.max(value, 1), MAX_ANALYSIS_MATCH_COUNT),
);
}
private parsePuuid(value: string): string {
const trimmed = value.trim();
if (trimmed.length === 0 || trimmed.length > 128) {
throw new BadRequestException('puuid is out of range.');
}
return trimmed;
}
private parseQueueId(value?: string): number {
if (value === undefined) return 420;
const queueId = Number(value);
if (!Number.isInteger(queueId) || queueId !== 420) {
throw new BadRequestException('queueId is unsupported.');
}
return queueId;
}
private parseSimilarPlayersLimit(value?: string): number {
if (value === undefined) return 10;
const limit = Number(value);
if (!Number.isInteger(limit) || limit < 1) {
throw new BadRequestException('limit is out of range.');
}
return Math.min(limit, 10);
}
private resolveClientKey(request: Request): string {
return request.ip || request.socket.remoteAddress || 'unknown-client';
}
}
@@ -0,0 +1,80 @@
import { BullModule } from '@nestjs/bullmq';
import { Module } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { DatabaseModule } from '../global/database/database.module';
import { SecretModule } from '../global/secret/secret.module';
import { SecretService } from '../global/secret/secret.service';
import { RiotModule } from '../riot/riot.module';
import { AnalysisController } from './analysis.controller';
import { AnalysisReadService } from './analysis-read.service';
import { AnalysisRequestThrottleService } from './analysis-request-throttle.service';
import { AnalysisQueueService } from './analysis-queue.service';
import {
ANALYSIS_JOB_ID_FACTORY,
ANALYSIS_QUEUE_NAME,
SEED_COLLECTION_QUEUE_NAME,
} from './analysis.constants';
import { AnalysisPipelineService } from './analysis-pipeline.service';
import { AnalysisProcessor } from './analysis.processor';
import { createBullMqOptions } from './bullmq.config';
import { FeatureExtractorService } from './feature-extractor.service';
import { MetricBaselineService } from './metric-baseline.service';
import { MetricNormalizationService } from './metric-normalization.service';
import { ProfileBuilderService } from './profile-builder.service';
import { SeedCollectionProcessor } from './seed-collection.processor';
import { SeedCollectionService } from './seed-collection.service';
import { SimilarPlayerService } from './similar-player.service';
import { TimelineDerivedService } from './timeline-derived.service';
import { TimelineMetricService } from './timeline-metric.service';
@Module({
imports: [
SecretModule,
DatabaseModule,
RiotModule,
BullModule.forRootAsync({
imports: [SecretModule],
inject: [SecretService],
useFactory: createBullMqOptions,
extraOptions: {
manualRegistration: process.env.NODE_ENV === 'test',
},
}),
BullModule.registerQueue({
name: ANALYSIS_QUEUE_NAME,
}),
BullModule.registerQueue({
name: SEED_COLLECTION_QUEUE_NAME,
}),
],
providers: [
{
provide: ANALYSIS_JOB_ID_FACTORY,
useValue: randomUUID,
},
AnalysisQueueService,
AnalysisReadService,
AnalysisRequestThrottleService,
AnalysisPipelineService,
AnalysisProcessor,
SeedCollectionProcessor,
FeatureExtractorService,
MetricBaselineService,
MetricNormalizationService,
ProfileBuilderService,
SeedCollectionService,
SimilarPlayerService,
TimelineDerivedService,
TimelineMetricService,
],
controllers: [AnalysisController],
exports: [
AnalysisQueueService,
AnalysisPipelineService,
MetricBaselineService,
MetricNormalizationService,
SeedCollectionService,
SimilarPlayerService,
],
})
export class AnalysisModule {}
@@ -0,0 +1,353 @@
import type { Job } from 'bullmq';
import {
BASELINE_COMPUTATION_JOB_NAME,
DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE,
FEATURE_RECOMPUTE_JOB_NAME,
MAX_FEATURE_RECOMPUTE_BATCH_SIZE,
USER_ANALYSIS_JOB_NAME,
} from './analysis.constants';
import type {
BaselineComputationJobData,
FeatureRecomputeJobData,
UserAnalysisJobData,
} from './analysis.types';
import { AnalysisPipelineService } from './analysis-pipeline.service';
import { AnalysisProcessor } from './analysis.processor';
function createJobData(
overrides: Partial<UserAnalysisJobData> = {},
): UserAnalysisJobData {
return {
gameName: 'Hide on bush',
tagLine: 'KR1',
platformRoute: 'kr',
regionalRoute: 'asia',
queueId: 420,
requestedMatchCount: 20,
...overrides,
};
}
function createFeatureRecomputeJobData(
overrides: Partial<FeatureRecomputeJobData> = {},
): FeatureRecomputeJobData {
return {
platformRoute: 'kr',
queueId: 420,
batchSize: 25,
puuid: 'target-puuid',
...overrides,
};
}
function createBaselineComputationJobData(
overrides: Partial<BaselineComputationJobData> = {},
): BaselineComputationJobData {
return {
platformRoute: 'kr',
queueId: 420,
cohort: 'MASTER_PLUS',
patch: 'ALL',
...overrides,
};
}
describe('AnalysisProcessor', () => {
it('delegates BullMQ jobs to the analysis pipeline', async () => {
const processUserAnalysisJob = jest
.fn<
Promise<void>,
[UserAnalysisJobData, string, { isFinalAttempt?: boolean }]
>()
.mockResolvedValue(undefined);
const processor = new AnalysisProcessor({
processUserAnalysisJob,
} as unknown as AnalysisPipelineService);
await processor.process({
attemptsMade: 1,
id: 'analysis-job-1',
name: USER_ANALYSIS_JOB_NAME,
opts: { attempts: 2 },
data: createJobData(),
} as Job<unknown>);
expect(processUserAnalysisJob).toHaveBeenCalledWith(
createJobData(),
'analysis-job-1',
{ isFinalAttempt: true },
);
});
it('delegates feature recompute jobs to the analysis pipeline', async () => {
const processFeatureRecomputeJob = jest
.fn<
Promise<void>,
[FeatureRecomputeJobData, string, { isFinalAttempt?: boolean }]
>()
.mockResolvedValue(undefined);
const processor = new AnalysisProcessor({
processFeatureRecomputeJob,
} as unknown as AnalysisPipelineService);
await processor.process({
attemptsMade: 0,
id: 'recompute-job-1',
name: FEATURE_RECOMPUTE_JOB_NAME,
opts: { attempts: 2 },
data: createFeatureRecomputeJobData(),
} as Job<unknown>);
expect(processFeatureRecomputeJob).toHaveBeenCalledWith(
createFeatureRecomputeJobData(),
'recompute-job-1',
{ isFinalAttempt: false },
);
});
it('delegates baseline computation jobs to the analysis pipeline', async () => {
const processBaselineComputationJob = jest
.fn<
Promise<void>,
[BaselineComputationJobData, string, { isFinalAttempt?: boolean }]
>()
.mockResolvedValue(undefined);
const processor = new AnalysisProcessor({
processBaselineComputationJob,
} as unknown as AnalysisPipelineService);
await processor.process({
attemptsMade: 0,
id: 'baseline-job-1',
name: BASELINE_COMPUTATION_JOB_NAME,
opts: { attempts: 1 },
data: createBaselineComputationJobData(),
} as Job<unknown>);
expect(processBaselineComputationJob).toHaveBeenCalledWith(
createBaselineComputationJobData(),
'baseline-job-1',
{ isFinalAttempt: true },
);
});
it('normalizes feature recompute batch size from valid queue payloads', async () => {
const processFeatureRecomputeJob = jest.fn().mockResolvedValue(undefined);
const processor = new AnalysisProcessor({
processFeatureRecomputeJob,
} as unknown as AnalysisPipelineService);
await processor.process({
attemptsMade: 0,
id: 'recompute-job-1',
name: FEATURE_RECOMPUTE_JOB_NAME,
opts: { attempts: 2 },
data: createFeatureRecomputeJobData({ batchSize: 999 }),
} as Job<unknown>);
expect(processFeatureRecomputeJob).toHaveBeenCalledWith(
createFeatureRecomputeJobData({
batchSize: MAX_FEATURE_RECOMPUTE_BATCH_SIZE,
}),
'recompute-job-1',
{ isFinalAttempt: false },
);
});
it('defaults fractional feature recompute batch sizes below one', async () => {
const processFeatureRecomputeJob = jest.fn().mockResolvedValue(undefined);
const processor = new AnalysisProcessor({
processFeatureRecomputeJob,
} as unknown as AnalysisPipelineService);
await processor.process({
attemptsMade: 0,
id: 'recompute-job-1',
name: FEATURE_RECOMPUTE_JOB_NAME,
opts: { attempts: 2 },
data: createFeatureRecomputeJobData({ batchSize: 0.5 }),
} as Job<unknown>);
expect(processFeatureRecomputeJob).toHaveBeenCalledWith(
createFeatureRecomputeJobData({
batchSize: DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE,
}),
'recompute-job-1',
{ isFinalAttempt: false },
);
});
it.each([
{
data: null,
expectedError: 'Feature recompute job data must be an object.',
},
{
data: {
...createFeatureRecomputeJobData(),
platformRoute: 'invalid',
},
expectedError: 'Analysis job platformRoute is unsupported.',
},
{
data: {
...createFeatureRecomputeJobData(),
queueId: 430,
},
expectedError: 'Analysis job queueId is unsupported.',
},
{
data: {
...createFeatureRecomputeJobData(),
batchSize: Number.NaN,
},
expectedError: 'Feature recompute job batchSize must be finite.',
},
{
data: {
...createFeatureRecomputeJobData(),
puuid: ' ',
},
expectedError: 'Analysis job puuid is out of range.',
},
{
data: {
...createFeatureRecomputeJobData(),
puuid: 'x'.repeat(129),
},
expectedError: 'Analysis job puuid is out of range.',
},
])(
'rejects malformed feature recompute payloads',
async ({ data, expectedError }) => {
const processFeatureRecomputeJob = jest.fn();
const processor = new AnalysisProcessor({
processFeatureRecomputeJob,
} as unknown as AnalysisPipelineService);
await expect(
processor.process({
attemptsMade: 0,
id: 'recompute-job-1',
name: FEATURE_RECOMPUTE_JOB_NAME,
opts: { attempts: 2 },
data,
} as Job<unknown>),
).rejects.toThrow(expectedError);
expect(processFeatureRecomputeJob).not.toHaveBeenCalled();
},
);
it.each([
{
data: null,
expectedError: 'Baseline computation job data must be an object.',
},
{
data: {
...createBaselineComputationJobData(),
cohort: 'INVALID',
},
expectedError: 'Baseline computation job cohort is unsupported.',
},
{
data: {
...createBaselineComputationJobData(),
patch: ' ',
},
expectedError: 'Analysis job patch is out of range.',
},
])(
'rejects malformed baseline computation payloads',
async ({ data, expectedError }) => {
const processBaselineComputationJob = jest.fn();
const processor = new AnalysisProcessor({
processBaselineComputationJob,
} as unknown as AnalysisPipelineService);
await expect(
processor.process({
attemptsMade: 0,
id: 'baseline-job-1',
name: BASELINE_COMPUTATION_JOB_NAME,
opts: { attempts: 1 },
data,
} as Job<unknown>),
).rejects.toThrow(expectedError);
expect(processBaselineComputationJob).not.toHaveBeenCalled();
},
);
it('rejects jobs without a BullMQ id', async () => {
const processor = new AnalysisProcessor({
processUserAnalysisJob: jest.fn(),
} as unknown as AnalysisPipelineService);
await expect(
processor.process({
data: createJobData(),
name: USER_ANALYSIS_JOB_NAME,
} as Job<unknown>),
).rejects.toThrow('Analysis job is missing a BullMQ job id.');
});
it('rejects unsupported job names before processing data', async () => {
const processUserAnalysisJob = jest.fn();
const processor = new AnalysisProcessor({
processUserAnalysisJob,
} as unknown as AnalysisPipelineService);
await expect(
processor.process({
id: 'analysis-job-1',
name: 'unexpected',
data: createJobData(),
} as Job<unknown>),
).rejects.toThrow('Unsupported analysis job name "unexpected".');
expect(processUserAnalysisJob).not.toHaveBeenCalled();
});
it('rejects malformed Redis payloads', async () => {
const processUserAnalysisJob = jest.fn();
const processor = new AnalysisProcessor({
processUserAnalysisJob,
} as unknown as AnalysisPipelineService);
await expect(
processor.process({
attemptsMade: 0,
id: 'analysis-job-1',
name: USER_ANALYSIS_JOB_NAME,
opts: { attempts: 2 },
data: {
...createJobData(),
regionalRoute: 'americas',
},
} as Job<unknown>),
).rejects.toThrow(
'Analysis job regionalRoute does not match platformRoute.',
);
expect(processUserAnalysisJob).not.toHaveBeenCalled();
});
it('normalizes requested match count from valid queue payloads', async () => {
const processUserAnalysisJob = jest.fn().mockResolvedValue(undefined);
const processor = new AnalysisProcessor({
processUserAnalysisJob,
} as unknown as AnalysisPipelineService);
await processor.process({
attemptsMade: 0,
id: 'analysis-job-1',
name: USER_ANALYSIS_JOB_NAME,
opts: { attempts: 2 },
data: createJobData({ requestedMatchCount: 999 }),
} as Job<unknown>);
expect(processUserAnalysisJob).toHaveBeenCalledWith(
createJobData({ requestedMatchCount: 50 }),
'analysis-job-1',
{ isFinalAttempt: false },
);
});
});
@@ -0,0 +1,232 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import type { Job } from 'bullmq';
import { BASELINE_COHORTS } from '../global/database/schemas';
import {
ANALYSIS_QUEUE_NAME,
BASELINE_COMPUTATION_JOB_NAME,
FEATURE_RECOMPUTE_JOB_NAME,
normalizeFeatureRecomputeBatchSize,
normalizeRequestedMatchCount,
USER_ANALYSIS_JOB_NAME,
} from './analysis.constants';
import { AnalysisPipelineService } from './analysis-pipeline.service';
import type {
BaselineComputationJobData,
FeatureRecomputeJobData,
UserAnalysisJobData,
} from './analysis.types';
import {
RIOT_PLATFORM_ROUTES,
RIOT_REGIONAL_ROUTES,
toRegionalRoute,
type RiotPlatformRoute,
type RiotRegionalRoute,
} from '../riot/riot.types';
@Processor(ANALYSIS_QUEUE_NAME)
export class AnalysisProcessor extends WorkerHost {
constructor(
private readonly analysisPipelineService: AnalysisPipelineService,
) {
super();
}
public async process(job: Job<unknown>): Promise<void> {
if (!job.id) {
throw new Error('Analysis job is missing a BullMQ job id.');
}
if (job.name === USER_ANALYSIS_JOB_NAME) {
const data = this.parseUserAnalysisJobData(job.data);
await this.analysisPipelineService.processUserAnalysisJob(data, job.id, {
isFinalAttempt: this.isFinalAttempt(job),
});
return;
}
if (job.name === FEATURE_RECOMPUTE_JOB_NAME) {
const data = this.parseFeatureRecomputeJobData(job.data);
await this.analysisPipelineService.processFeatureRecomputeJob(
data,
job.id,
{
isFinalAttempt: this.isFinalAttempt(job),
},
);
return;
}
if (job.name === BASELINE_COMPUTATION_JOB_NAME) {
const data = this.parseBaselineComputationJobData(job.data);
await this.analysisPipelineService.processBaselineComputationJob(
data,
job.id,
{
isFinalAttempt: this.isFinalAttempt(job),
},
);
return;
}
throw new Error(`Unsupported analysis job name "${job.name}".`);
}
private parseUserAnalysisJobData(value: unknown): UserAnalysisJobData {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error('Analysis job data must be an object.');
}
const record = value as Record<string, unknown>;
const gameName = this.parseBoundedString(record.gameName, 'gameName', 64);
const tagLine = this.parseBoundedString(record.tagLine, 'tagLine', 16);
const platformRoute = this.parsePlatformRoute(record.platformRoute);
const regionalRoute = this.parseRegionalRoute(record.regionalRoute);
if (regionalRoute !== toRegionalRoute(platformRoute)) {
throw new Error(
'Analysis job regionalRoute does not match platformRoute.',
);
}
const queueId = this.parseQueueId(record.queueId);
const requestedMatchCount = this.parseRequestedMatchCount(
record.requestedMatchCount,
);
return {
gameName,
tagLine,
platformRoute,
regionalRoute,
queueId,
requestedMatchCount,
};
}
private parseFeatureRecomputeJobData(
value: unknown,
): FeatureRecomputeJobData {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error('Feature recompute job data must be an object.');
}
const record = value as Record<string, unknown>;
const platformRoute = this.parsePlatformRoute(record.platformRoute);
const queueId = this.parseQueueId(record.queueId);
const batchSize = this.parseFeatureRecomputeBatchSize(record.batchSize);
const puuid =
record.puuid === undefined
? undefined
: this.parseBoundedString(record.puuid, 'puuid', 128);
return {
platformRoute,
queueId,
batchSize,
...(puuid ? { puuid } : {}),
};
}
private parseBaselineComputationJobData(
value: unknown,
): BaselineComputationJobData {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error('Baseline computation job data must be an object.');
}
const record = value as Record<string, unknown>;
const platformRoute = this.parsePlatformRoute(record.platformRoute);
const queueId = this.parseQueueId(record.queueId);
const cohort = this.parseBaselineCohort(record.cohort);
const patch =
record.patch === undefined
? 'ALL'
: this.parseBoundedString(record.patch, 'patch', 32);
return {
platformRoute,
queueId,
cohort,
patch,
};
}
private parseBoundedString(
value: unknown,
fieldName: string,
maximumLength: number,
): string {
if (typeof value !== 'string') {
throw new Error(`Analysis job ${fieldName} must be a string.`);
}
const trimmed = value.trim();
if (trimmed.length === 0 || trimmed.length > maximumLength) {
throw new Error(`Analysis job ${fieldName} is out of range.`);
}
return trimmed;
}
private parsePlatformRoute(value: unknown): RiotPlatformRoute {
if (
typeof value !== 'string' ||
!RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
) {
throw new Error('Analysis job platformRoute is unsupported.');
}
return value as RiotPlatformRoute;
}
private parseRegionalRoute(value: unknown): RiotRegionalRoute {
if (
typeof value !== 'string' ||
!RIOT_REGIONAL_ROUTES.includes(value as RiotRegionalRoute)
) {
throw new Error('Analysis job regionalRoute is unsupported.');
}
return value as RiotRegionalRoute;
}
private parseQueueId(value: unknown): number {
if (value !== 420) {
throw new Error('Analysis job queueId is unsupported.');
}
return value;
}
private parseRequestedMatchCount(value: unknown): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new Error('Analysis job requestedMatchCount must be finite.');
}
return normalizeRequestedMatchCount(value);
}
private parseBaselineCohort(
value: unknown,
): BaselineComputationJobData['cohort'] {
if (value === undefined) {
return 'MASTER_PLUS';
}
if (
typeof value !== 'string' ||
!BASELINE_COHORTS.includes(
value as NonNullable<BaselineComputationJobData['cohort']>,
)
) {
throw new Error('Baseline computation job cohort is unsupported.');
}
return value as NonNullable<BaselineComputationJobData['cohort']>;
}
private parseFeatureRecomputeBatchSize(value: unknown): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new Error('Feature recompute job batchSize must be finite.');
}
return normalizeFeatureRecomputeBatchSize(value);
}
private isFinalAttempt(job: Job<unknown>): boolean {
const attempts =
typeof job.opts?.attempts === 'number' && job.opts.attempts > 0
? job.opts.attempts
: 1;
return job.attemptsMade + 1 >= attempts;
}
}
@@ -0,0 +1,141 @@
import type { MetricId, Role, TierComparison } from '@persona-lenz/shared';
import type {
BaselineCohort,
LaneOpponentRef,
NormalizationMethod,
SeedSource,
TeamPositionOrUnknown,
} from '../global/database/schemas';
import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
export interface UserAnalysisJobData {
gameName: string;
tagLine: string;
platformRoute: RiotPlatformRoute;
regionalRoute: RiotRegionalRoute;
queueId: number;
requestedMatchCount: number;
}
export interface FeatureRecomputeJobData {
platformRoute: RiotPlatformRoute;
queueId: number;
batchSize: number;
puuid?: string;
}
export interface SeedCollectionJobData {
platformRoute: RiotPlatformRoute;
queueId: number;
sourceLimits?: Partial<Record<SeedSource, number>>;
}
export interface BaselineComputationJobData {
platformRoute: RiotPlatformRoute;
queueId: number;
cohort?: BaselineCohort;
patch?: string;
}
export interface SeedAccountPipelineData {
puuid: string;
platformRoute: RiotPlatformRoute;
regionalRoute: RiotRegionalRoute;
queueId: number;
requestedMatchCount: number;
}
export interface SeedAccountPipelineResult {
puuid: string;
fetchedMatches: number;
extractedFeatures: number;
profileBuilt: boolean;
}
export interface ExtractedPlayerMatchFeature {
matchId: string;
puuid: string;
queueId: number;
role: TeamPositionOrUnknown;
championId: number;
gameCreation: number;
gameDurationSec: number;
win: boolean;
patch: string;
features: Record<string, number>;
normalized: Record<string, number>;
vector: number[];
featureSchemaVersion: number;
normalizationMethod: NormalizationMethod;
confidence: number;
timelineProcessed: boolean;
laneOpponent?: LaneOpponentRef;
derived?: Record<string, unknown>;
}
export interface BuiltPlayerProfile {
puuid: string;
queueId: number;
mainRole: Role;
roleDistribution: Partial<Record<Role, number>>;
sampleGameCount: number;
championPool: Array<{
championId: number;
games: number;
wins: number;
}>;
profile: Record<string, number>;
vector: number[];
featureSchemaVersion: number;
normalizationMethod: NormalizationMethod;
confidence: number;
patches: string[];
lastMatchAt?: Date;
isSeed: boolean;
tier?: string;
division?: string;
leaguePoints?: number;
}
export interface ChampionPoolEntry {
championId: number;
games: number;
wins: number;
}
export interface SimilarMetric {
metricId: MetricId;
currentValue: number;
otherValue: number;
absoluteGap: number;
}
export interface LeadMetric {
metricId: MetricId;
currentValue: number;
otherValue: number;
lead: number;
}
export interface SimilarPlayer {
puuid: string;
similarityScore: number;
finalScore: number;
tier?: string;
division?: string;
leaguePoints?: number;
tierComparison: TierComparison;
mainRole: Role;
mainChampions: ChampionPoolEntry[];
sampleGameCount: number;
similarMetrics: SimilarMetric[];
strongerMetrics: LeadMetric[];
weakerMetrics: LeadMetric[];
}
export interface SimilarPlayersResult {
puuid: string;
queueId: number;
profileUpdatedAt: Date;
matches: SimilarPlayer[];
}
@@ -0,0 +1,54 @@
import {
createBullMqOptions,
resolveBullMqRedisConnection,
} from './bullmq.config';
describe('BullMQ config', () => {
it('parses redis URLs into BullMQ connection options', () => {
expect(
resolveBullMqRedisConnection('redis://worker:secret@redis.local:6380/2'),
).toMatchObject({
host: 'redis.local',
port: 6380,
username: 'worker',
password: 'secret',
db: 2,
maxRetriesPerRequest: null,
});
});
it('enables TLS for rediss URLs', () => {
expect(resolveBullMqRedisConnection('rediss://redis.local')).toMatchObject({
host: 'redis.local',
port: 6379,
tls: {},
});
});
it('rejects malformed Redis URLs without an explicit host', () => {
expect(() => resolveBullMqRedisConnection('redis:///0')).toThrow(
'REDIS_URL must include a hostname.',
);
});
it('creates root options from SecretService without exposing secrets', async () => {
const secretService = {
get: jest
.fn<Promise<string>, [string]>()
.mockResolvedValue('redis://localhost:6379/0'),
};
await expect(createBullMqOptions(secretService)).resolves.toMatchObject({
connection: {
host: 'localhost',
port: 6379,
db: 0,
maxRetriesPerRequest: null,
},
defaultJobOptions: {
attempts: 2,
},
});
expect(secretService.get).toHaveBeenCalledWith('REDIS_URL');
});
});
@@ -0,0 +1,73 @@
import type { BullRootModuleOptions } from '@nestjs/bullmq';
import type { QueueOptions } from 'bullmq';
import type { SecretService } from '../global/secret/secret.service';
export type BullMqConnectionOptions = NonNullable<QueueOptions['connection']>;
function parseRedisDatabase(pathname: string): number {
const trimmedPath = pathname.replace(/^\/+/u, '');
if (!trimmedPath) return 0;
const database = Number(trimmedPath);
if (!Number.isInteger(database) || database < 0) {
throw new Error('REDIS_URL must include a non-negative integer database.');
}
return database;
}
export function resolveBullMqRedisConnection(
redisUrl: string,
): BullMqConnectionOptions {
const parsedUrl = new URL(redisUrl);
if (parsedUrl.protocol !== 'redis:' && parsedUrl.protocol !== 'rediss:') {
throw new Error('REDIS_URL must use redis:// or rediss://.');
}
if (!parsedUrl.hostname) {
throw new Error('REDIS_URL must include a hostname.');
}
const connection: BullMqConnectionOptions = {
host: parsedUrl.hostname,
port: parsedUrl.port ? Number(parsedUrl.port) : 6379,
db: parseRedisDatabase(parsedUrl.pathname),
maxRetriesPerRequest: null,
};
if (parsedUrl.username) {
connection.username = decodeURIComponent(parsedUrl.username);
}
if (parsedUrl.password) {
connection.password = decodeURIComponent(parsedUrl.password);
}
if (parsedUrl.protocol === 'rediss:') {
connection.tls = {};
}
return connection;
}
export async function createBullMqOptions(
secretService: Pick<SecretService, 'get'>,
): Promise<BullRootModuleOptions> {
const redisUrl = await secretService.get<string>('REDIS_URL');
return {
connection: resolveBullMqRedisConnection(redisUrl),
defaultJobOptions: {
attempts: 2,
backoff: {
type: 'exponential',
delay: 1_000,
},
removeOnComplete: {
age: 86_400,
count: 1_000,
},
removeOnFail: {
age: 604_800,
count: 5_000,
},
},
};
}
@@ -0,0 +1,275 @@
import { FEATURE_SCHEMA_VERSION, VECTOR_METRICS } from '@persona-lenz/shared';
import { FeatureExtractorService } from './feature-extractor.service';
function createMatchPayload(overrides: Record<string, unknown> = {}) {
const currentPlayer = {
puuid: 'target-puuid',
teamId: 100,
teamPosition: 'MIDDLE',
championId: 103,
kills: 6,
deaths: 2,
assists: 8,
totalDamageDealtToChampions: 24_000,
goldEarned: 12_000,
totalMinionsKilled: 210,
neutralMinionsKilled: 12,
visionScore: 24,
wardsKilled: 4,
detectorWardsPlaced: 3,
win: true,
challenges: {
kda: 7,
killParticipation: 0.7,
teamDamagePercentage: 0.32,
damagePerMinute: 800,
goldPerMinute: 400,
visionScorePerMinute: 0.8,
controlWardsPlaced: 3,
dragonTakedowns: 1,
baronTakedowns: 1,
riftHeraldTakedowns: 0,
soloKills: 2,
},
};
return {
metadata: {
matchId: 'KR_1',
participants: ['target-puuid', 'ally-puuid', 'enemy-puuid'],
},
info: {
gameCreation: 1_700_000_000_000,
gameDuration: 1800,
gameVersion: '26.13.123.456',
queueId: 420,
participants: [
currentPlayer,
{
puuid: 'ally-puuid',
teamId: 100,
teamPosition: 'JUNGLE',
championId: 64,
kills: 10,
totalDamageDealtToChampions: 30_000,
},
{
puuid: 'enemy-puuid',
teamId: 200,
teamPosition: 'MIDDLE',
championId: 134,
kills: 4,
totalDamageDealtToChampions: 16_000,
},
],
...overrides,
},
};
}
describe('FeatureExtractorService', () => {
const service = new FeatureExtractorService();
it('extracts MVP 1 raw metrics and vector values in registry order', () => {
const feature = service.extractPlayerMatchFeature(
createMatchPayload(),
'target-puuid',
);
expect(feature.matchId).toBe('KR_1');
expect(feature.role).toBe('MIDDLE');
expect(feature.laneOpponent).toEqual({
puuid: 'enemy-puuid',
championId: 134,
});
expect(feature.patch).toBe('26.13');
expect(feature.features).toMatchObject({
kda: 7,
killParticipation: 0.7,
damageShare: 0.32,
damagePerMin: 800,
goldPerMin: 400,
csPerMin: 7.4,
visionScorePerMin: 0.8,
wardsKilledPerMin: 4 / 30,
controlWardsPlaced: 3,
deathsPerMin: 2 / 30,
objectiveParticipation: 2,
soloKills: 2,
});
expect(feature.vector).toEqual(
VECTOR_METRICS.map((metric) => feature.normalized[metric.id] ?? 0),
);
expect(feature.vector).toHaveLength(VECTOR_METRICS.length);
expect(feature.featureSchemaVersion).toBe(FEATURE_SCHEMA_VERSION);
expect(feature.confidence).toBe(1);
});
it('leaves registry metrics without raw observations out of normalized values', () => {
const actualShared = jest.requireActual<
typeof import('@persona-lenz/shared')
>('@persona-lenz/shared');
const metrics = [
...actualShared.METRICS,
{
id: 'futureTimelineMetric',
label: 'Future timeline metric',
direction: 'higherIsBetter' as const,
kind: 'scalar' as const,
includeInVector: true,
},
];
const vectorMetrics = metrics.filter((metric) => metric.includeInVector);
let feature:
| ReturnType<FeatureExtractorService['extractPlayerMatchFeature']>
| undefined;
jest.isolateModules(() => {
jest.doMock('@persona-lenz/shared', () => ({
...actualShared,
FEATURE_SCHEMA_VERSION: 99,
METRICS: metrics,
VECTOR_METRICS: vectorMetrics,
}));
const { FeatureExtractorService: MockedFeatureExtractorService } =
jest.requireActual<typeof import('./feature-extractor.service')>(
'./feature-extractor.service',
);
feature = new MockedFeatureExtractorService().extractPlayerMatchFeature(
createMatchPayload(),
'target-puuid',
);
});
jest.dontMock('@persona-lenz/shared');
expect(feature?.features.futureTimelineMetric).toBeUndefined();
expect(feature?.normalized.futureTimelineMetric).toBeUndefined();
expect(feature?.vector).toHaveLength(vectorMetrics.length);
expect(feature?.vector.at(-1)).toBe(0);
expect(feature?.featureSchemaVersion).toBe(99);
});
it('falls back to manual calculations when challenges are missing', () => {
const payload = createMatchPayload({
participants: [
{
puuid: 'target-puuid',
teamId: 100,
teamPosition: 'MIDDLE',
championId: 103,
kills: 6,
deaths: 2,
assists: 8,
totalDamageDealtToChampions: 24_000,
goldEarned: 12_000,
totalMinionsKilled: 210,
neutralMinionsKilled: 12,
visionScore: 24,
wardsKilled: 4,
detectorWardsPlaced: 3,
win: true,
},
{
puuid: 'ally-puuid',
teamId: 100,
teamPosition: 'JUNGLE',
championId: 64,
kills: 14,
totalDamageDealtToChampions: 36_000,
},
],
});
const feature = service.extractPlayerMatchFeature(payload, 'target-puuid');
expect(feature.features.kda).toBe(7);
expect(feature.features.killParticipation).toBe(0.7);
expect(feature.features.damageShare).toBe(0.4);
expect(feature.features.damagePerMin).toBe(800);
expect(feature.features.goldPerMin).toBe(400);
expect(feature.features.controlWardsPlaced).toBe(3);
expect(feature.features.objectiveParticipation).toBe(0);
expect(feature.features.soloKills).toBe(0);
});
it('marks unknown roles and short games with lower confidence', () => {
const payload = createMatchPayload({
gameDuration: 900,
participants: [
{
puuid: 'target-puuid',
teamId: 100,
teamPosition: '',
championId: 103,
kills: 1,
deaths: 2,
assists: 1,
totalDamageDealtToChampions: 5_000,
goldEarned: 6_000,
totalMinionsKilled: 100,
neutralMinionsKilled: 0,
visionScore: 10,
wardsKilled: 1,
detectorWardsPlaced: 0,
win: false,
},
],
});
const feature = service.extractPlayerMatchFeature(payload, 'target-puuid');
expect(feature.role).toBe('UNKNOWN');
expect(feature.confidence).toBe(0.5);
});
it('omits lane opponent and lowers confidence when same-position enemy is missing', () => {
const payload = createMatchPayload({
participants: [
{
puuid: 'target-puuid',
teamId: 100,
teamPosition: 'MIDDLE',
championId: 103,
kills: 6,
deaths: 2,
assists: 8,
totalDamageDealtToChampions: 24_000,
goldEarned: 12_000,
totalMinionsKilled: 210,
neutralMinionsKilled: 12,
visionScore: 24,
wardsKilled: 4,
detectorWardsPlaced: 3,
win: true,
},
{
puuid: 'enemy-puuid',
teamId: 200,
teamPosition: 'TOP',
championId: 266,
kills: 4,
totalDamageDealtToChampions: 16_000,
},
],
});
const feature = service.extractPlayerMatchFeature(payload, 'target-puuid');
expect(feature.laneOpponent).toBeUndefined();
expect(feature.confidence).toBe(0.7);
});
it('marks known-role short games with short-game confidence only', () => {
const payload = createMatchPayload({
gameDuration: 900,
});
const feature = service.extractPlayerMatchFeature(payload, 'target-puuid');
expect(feature.role).toBe('MIDDLE');
expect(feature.confidence).toBe(0.8);
});
});
@@ -0,0 +1,260 @@
import {
FEATURE_SCHEMA_VERSION,
METRICS,
VECTOR_METRICS,
type MetricDefinition,
type Role,
} from '@persona-lenz/shared';
import { Injectable } from '@nestjs/common';
import type {
LaneOpponentRef,
TeamPositionOrUnknown,
} from '../global/database/schemas';
import type { ExtractedPlayerMatchFeature } from './analysis.types';
interface MatchParticipant {
assists?: number;
challenges?: Record<string, unknown>;
championId?: number;
deaths?: number;
detectorWardsPlaced?: number;
goldEarned?: number;
kills?: number;
neutralMinionsKilled?: number;
puuid?: string;
teamId?: number;
teamPosition?: string;
totalDamageDealtToChampions?: number;
totalMinionsKilled?: number;
visionScore?: number;
wardsKilled?: number;
win?: boolean;
}
interface MatchInfo {
gameCreation?: number;
gameDuration?: number;
gameVersion?: string;
participants?: MatchParticipant[];
queueId?: number;
}
interface MatchPayload {
info?: MatchInfo;
metadata?: {
matchId?: string;
};
}
const TEAM_POSITIONS = new Set<Role>([
'TOP',
'JUNGLE',
'MIDDLE',
'BOTTOM',
'UTILITY',
]);
function asRecord(value: unknown): Record<string, unknown> {
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
function asNumber(value: unknown, fallback = 0): number {
return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
}
function asFiniteMetricValue(value: number | undefined): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
function fromChallenge(
challenges: Record<string, unknown>,
key: string,
): number | undefined {
const value = challenges[key];
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
function ratio(numerator: number, denominator: number): number {
if (denominator <= 0) return 0;
return numerator / denominator;
}
function normalizeMetric(
metric: MetricDefinition,
role: Role,
rawValue: number,
): number {
const baseline = metric.baseline?.[role];
if (!baseline) return Math.max(0, Math.min(1, rawValue));
return Math.max(
0,
Math.min(1, (rawValue - baseline.min) / (baseline.max - baseline.min)),
);
}
function resolveRole(teamPosition: string | undefined): TeamPositionOrUnknown {
return TEAM_POSITIONS.has(teamPosition as Role)
? (teamPosition as Role)
: 'UNKNOWN';
}
function resolveNormalizationRole(role: TeamPositionOrUnknown): Role {
return role === 'UNKNOWN' ? 'MIDDLE' : role;
}
function resolvePatch(gameVersion: string | undefined): string {
const [major, minor] = (gameVersion ?? 'unknown').split('.');
if (!major || !minor) return 'unknown';
return `${major}.${minor}`;
}
function resolveLaneOpponent(
participant: MatchParticipant,
participants: MatchParticipant[],
role: TeamPositionOrUnknown,
): LaneOpponentRef | undefined {
if (role === 'UNKNOWN' || participant.teamId === undefined) {
return undefined;
}
const opponent = participants.find(
(candidate) =>
candidate.teamId !== participant.teamId &&
candidate.teamPosition === role &&
typeof candidate.puuid === 'string',
);
if (!opponent?.puuid) {
return undefined;
}
return {
puuid: opponent.puuid,
championId: asNumber(opponent.championId),
};
}
@Injectable()
export class FeatureExtractorService {
public extractPlayerMatchFeature(
rawMatch: Record<string, unknown>,
puuid: string,
): ExtractedPlayerMatchFeature {
const payload = rawMatch as MatchPayload;
const info = payload.info ?? {};
const participants = info.participants ?? [];
const participant = participants.find(
(candidate) => candidate.puuid === puuid,
);
if (!participant) {
throw new Error(`Participant not found for puuid="${puuid}".`);
}
const gameDurationSec = asNumber(info.gameDuration);
const gameMinutes = Math.max(gameDurationSec / 60, 1);
const teamId = participant.teamId;
const teamParticipants = participants.filter(
(candidate) => candidate.teamId === teamId,
);
const teamKills = teamParticipants.reduce(
(sum, candidate) => sum + asNumber(candidate.kills),
0,
);
const teamDamage = teamParticipants.reduce(
(sum, candidate) => sum + asNumber(candidate.totalDamageDealtToChampions),
0,
);
const challenges = asRecord(participant.challenges);
const kills = asNumber(participant.kills);
const deaths = asNumber(participant.deaths);
const assists = asNumber(participant.assists);
const damage = asNumber(participant.totalDamageDealtToChampions);
const gold = asNumber(participant.goldEarned);
const minions =
asNumber(participant.totalMinionsKilled) +
asNumber(participant.neutralMinionsKilled);
const features: Record<string, number> = {
kda:
fromChallenge(challenges, 'kda') ??
(kills + assists) / Math.max(deaths, 1),
killParticipation:
fromChallenge(challenges, 'killParticipation') ??
ratio(kills + assists, teamKills),
damageShare:
fromChallenge(challenges, 'teamDamagePercentage') ??
ratio(damage, teamDamage),
damagePerMin:
fromChallenge(challenges, 'damagePerMinute') ?? damage / gameMinutes,
goldPerMin:
fromChallenge(challenges, 'goldPerMinute') ?? gold / gameMinutes,
csPerMin: minions / gameMinutes,
visionScorePerMin:
fromChallenge(challenges, 'visionScorePerMinute') ??
asNumber(participant.visionScore) / gameMinutes,
wardsKilledPerMin: asNumber(participant.wardsKilled) / gameMinutes,
controlWardsPlaced:
fromChallenge(challenges, 'controlWardsPlaced') ??
asNumber(participant.detectorWardsPlaced),
deathsPerMin: deaths / gameMinutes,
objectiveParticipation:
asNumber(challenges.dragonTakedowns) +
asNumber(challenges.baronTakedowns) +
asNumber(challenges.riftHeraldTakedowns),
soloKills: fromChallenge(challenges, 'soloKills') ?? 0,
};
const role = resolveRole(participant.teamPosition);
const laneOpponent = resolveLaneOpponent(participant, participants, role);
const normalizationRole = resolveNormalizationRole(role);
const normalized = Object.fromEntries(
METRICS.flatMap((metric) => {
const rawValue = asFiniteMetricValue(features[metric.id]);
return rawValue === undefined
? []
: [[metric.id, normalizeMetric(metric, normalizationRole, rawValue)]];
}),
);
return {
matchId: payload.metadata?.matchId ?? '',
puuid,
queueId: asNumber(info.queueId),
role,
championId: asNumber(participant.championId),
gameCreation: asNumber(info.gameCreation),
gameDurationSec,
win: participant.win === true,
patch: resolvePatch(info.gameVersion),
features,
normalized,
vector: VECTOR_METRICS.map((metric) => normalized[metric.id] ?? 0),
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
normalizationMethod: 'registry-baseline',
confidence: this.resolveConfidence(role, gameDurationSec, laneOpponent),
timelineProcessed: false,
...(laneOpponent ? { laneOpponent } : {}),
};
}
private resolveConfidence(
role: TeamPositionOrUnknown,
gameDurationSec: number,
laneOpponent: LaneOpponentRef | undefined,
): number {
let confidence = 1;
if (role === 'UNKNOWN') confidence = Math.min(confidence, 0.5);
if (role !== 'UNKNOWN' && !laneOpponent)
confidence = Math.min(confidence, 0.7);
if (gameDurationSec < 1200) confidence = Math.min(confidence, 0.8);
return confidence;
}
}
@@ -0,0 +1,218 @@
import { FEATURE_SCHEMA_VERSION } from '@persona-lenz/shared';
import type { ConnectionService } from '../global/database/connection.service';
import type { PlayerMatchFeature } from '../global/database/schemas';
import { MetricBaselineService } from './metric-baseline.service';
interface ExecQuery<T> {
exec: jest.Mock<Promise<T>, []>;
}
type AcknowledgedUpdate = { acknowledged: boolean };
type AggregateMock = jest.Mock<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>;
type UpdateOneMock = jest.Mock<
ExecQuery<AcknowledgedUpdate>,
[Record<string, unknown>, Record<string, unknown>, Record<string, unknown>?]
>;
function asRecord(value: unknown): Record<string, unknown> {
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
function execResolved<T>(value: T): ExecQuery<T> {
return { exec: jest.fn<Promise<T>, []>().mockResolvedValue(value) };
}
function createStoredFeature(
overrides: Partial<PlayerMatchFeature> = {},
): PlayerMatchFeature {
return {
createdAt: new Date('2026-07-01T00:00:00.000Z'),
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
matchId: 'KR_1',
puuid: 'seed-puuid',
queueId: 420,
role: 'MIDDLE',
championId: 103,
gameCreation: 1_700_000_000_000,
gameDurationSec: 1_800,
win: true,
patch: '26.13',
features: {
csPerMin: 8,
kda: 3,
},
normalized: {},
vector: [],
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
normalizationMethod: 'registry-baseline',
confidence: 1,
timelineProcessed: true,
...overrides,
};
}
describe('MetricBaselineService', () => {
it('computes p5-p95 breakpoints from seed raw feature values', async () => {
const seedFeatures = [10, 20, 30, 40, 50].map((kda, index) =>
createStoredFeature({
matchId: `KR_${index + 1}`,
features: {
kda,
},
}),
);
const aggregate: AggregateMock = jest
.fn<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>()
.mockReturnValue(execResolved(seedFeatures));
const updateOne: UpdateOneMock = jest
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
.mockReturnValue(execResolved({ acknowledged: true }));
const connectionService = {
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'playerMatchFeature'
? { aggregate }
: {
updateOne,
},
),
),
} as unknown as ConnectionService;
const service = new MetricBaselineService(connectionService);
const computedAt = new Date('2026-07-03T12:00:00.000Z');
const result = await service.computeMetricBaselines({
cohort: 'MASTER_PLUS',
computedAt,
patch: 'ALL',
});
expect(result).toEqual({
baselinesWritten: 1,
cohort: 'MASTER_PLUS',
computedAt,
patch: 'ALL',
samplesRead: 5,
});
const aggregatePipeline = aggregate.mock.calls[0]?.[0];
expect(aggregatePipeline).toContainEqual({
$match: {
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
role: {
$in: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'],
},
},
});
expect(aggregatePipeline).toContainEqual({
$lookup: {
as: 'account',
foreignField: 'puuid',
from: 'account',
localField: 'puuid',
},
});
expect(updateOne).toHaveBeenCalledTimes(1);
const [, update, options] = updateOne.mock.calls[0];
const updateSet = asRecord(asRecord(update).$set);
expect(updateSet).toMatchObject({
cohort: 'MASTER_PLUS',
computedAt,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
metricId: 'kda',
patch: 'ALL',
role: 'MIDDLE',
sampleCount: 5,
});
const breakpoints = updateSet.percentileBreakpoints;
expect(Array.isArray(breakpoints)).toBe(true);
const numericBreakpoints = (breakpoints as unknown[]).filter(
(value): value is number => typeof value === 'number',
);
expect(numericBreakpoints).toHaveLength(19);
expect(numericBreakpoints[0]).toBe(12);
expect(numericBreakpoints[9]).toBe(30);
expect(numericBreakpoints[18]).toBe(48);
expect(options).toEqual({ upsert: true });
});
it('groups baseline values by metric and role and skips unknown roles', async () => {
const seedFeatures = [
createStoredFeature({
role: 'MIDDLE',
features: {
csPerMin: 8,
kda: 3,
},
}),
createStoredFeature({
matchId: 'KR_2',
role: 'MIDDLE',
features: {
csPerMin: 9,
kda: 5,
},
}),
createStoredFeature({
matchId: 'KR_3',
role: 'TOP',
features: {
kda: 2,
},
}),
createStoredFeature({
matchId: 'KR_4',
role: 'UNKNOWN',
features: {
kda: 99,
},
}),
];
const aggregate: AggregateMock = jest
.fn<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>()
.mockReturnValue(execResolved(seedFeatures));
const updateOne: UpdateOneMock = jest
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
.mockReturnValue(execResolved({ acknowledged: true }));
const connectionService = {
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'playerMatchFeature'
? { aggregate }
: {
updateOne,
},
),
),
} as unknown as ConnectionService;
const service = new MetricBaselineService(connectionService);
await service.computeMetricBaselines({
cohort: 'MASTER_PLUS',
patch: '26.13',
});
const writtenBaselines = updateOne.mock.calls.map(([filter]) => filter);
expect(writtenBaselines).toEqual(
expect.arrayContaining([
expect.objectContaining({ metricId: 'kda', role: 'MIDDLE' }),
expect.objectContaining({ metricId: 'csPerMin', role: 'MIDDLE' }),
expect.objectContaining({ metricId: 'kda', role: 'TOP' }),
]),
);
expect(writtenBaselines).not.toContainEqual(
expect.objectContaining({ role: 'UNKNOWN' }),
);
expect(aggregate.mock.calls[0]?.[0]).toContainEqual({
$match: {
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
patch: '26.13',
role: {
$in: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'],
},
},
});
});
});
@@ -0,0 +1,216 @@
import { Injectable } from '@nestjs/common';
import { FEATURE_SCHEMA_VERSION, METRICS, ROLES } from '@persona-lenz/shared';
import type { PipelineStage } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
BaselineCohort,
PlayerMatchFeature,
TeamPosition,
} from '../global/database/schemas';
import { DEFAULT_SEED_COLLECTION_QUEUE_TYPE } from './analysis.constants';
export interface MetricBaselineComputationOptions {
cohort?: BaselineCohort;
computedAt?: Date;
patch?: string;
}
export interface MetricBaselineComputationResult {
baselinesWritten: number;
cohort: BaselineCohort;
computedAt: Date;
patch: string;
samplesRead: number;
}
type BaselineFeatureSample = Pick<
PlayerMatchFeature,
'features' | 'patch' | 'role'
>;
const BASELINE_PERCENTILES = Array.from(
{ length: 19 },
(_, index) => (index + 1) * 0.05,
);
const MASTER_PLUS_TIERS = ['MASTER', 'GRANDMASTER', 'CHALLENGER'];
function isTeamPosition(value: unknown): value is TeamPosition {
return typeof value === 'string' && ROLES.includes(value as TeamPosition);
}
function finiteNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
function baselineKey(metricId: string, role: TeamPosition): string {
return `${metricId}\u0000${role}`;
}
function percentile(sortedValues: number[], percentileRank: number): number {
if (sortedValues.length === 0) {
return 0;
}
if (sortedValues.length === 1) {
return sortedValues[0] ?? 0;
}
const rankIndex = (sortedValues.length - 1) * percentileRank;
const lowerIndex = Math.floor(rankIndex);
const upperIndex = Math.ceil(rankIndex);
const lowerValue = sortedValues[lowerIndex] ?? 0;
const upperValue = sortedValues[upperIndex] ?? lowerValue;
return lowerValue + (upperValue - lowerValue) * (rankIndex - lowerIndex);
}
@Injectable()
export class MetricBaselineService {
constructor(private readonly connectionService: ConnectionService) {}
public async computeMetricBaselines(
options: MetricBaselineComputationOptions = {},
): Promise<MetricBaselineComputationResult> {
const cohort = options.cohort ?? 'MASTER_PLUS';
const computedAt = options.computedAt ?? new Date();
const patch = options.patch ?? 'ALL';
const samples = await this.findBaselineFeatureSamples(cohort, patch);
const groupedMetricValues = this.groupMetricValues(samples);
const metricBaselineModel =
await this.connectionService.getModel('metricBaseline');
let baselinesWritten = 0;
for (const [key, values] of groupedMetricValues.entries()) {
const [metricId, role] = key.split('\u0000') as [string, TeamPosition];
const sortedValues = [...values].sort((left, right) => left - right);
const percentileBreakpoints = BASELINE_PERCENTILES.map((percentileRank) =>
percentile(sortedValues, percentileRank),
);
await metricBaselineModel
.updateOne(
{
metricId,
role,
cohort,
patch,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
},
{
$set: {
metricId,
role,
cohort,
patch,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
sampleCount: sortedValues.length,
percentileBreakpoints,
computedAt,
},
},
{ upsert: true },
)
.exec();
baselinesWritten += 1;
}
return {
baselinesWritten,
cohort,
computedAt,
patch,
samplesRead: samples.length,
};
}
private async findBaselineFeatureSamples(
cohort: BaselineCohort,
patch: string,
): Promise<BaselineFeatureSample[]> {
const playerMatchFeatureModel =
await this.connectionService.getModel('playerMatchFeature');
return playerMatchFeatureModel
.aggregate<BaselineFeatureSample>(this.baselineAggregation(cohort, patch))
.exec();
}
private baselineAggregation(
cohort: BaselineCohort,
patch: string,
): PipelineStage[] {
const matchStage: Record<string, unknown> = {
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
role: {
$in: [...ROLES],
},
...(patch === 'ALL' ? {} : { patch }),
};
const accountMatchStage: Record<string, unknown> = {
'account.isSeed': true,
...(cohort === 'MASTER_PLUS'
? {
'account.tiers': {
$elemMatch: {
queueType: DEFAULT_SEED_COLLECTION_QUEUE_TYPE,
tier: {
$in: MASTER_PLUS_TIERS,
},
},
},
}
: {}),
};
return [
{
$match: matchStage,
},
{
$lookup: {
from: 'account',
localField: 'puuid',
foreignField: 'puuid',
as: 'account',
},
},
{
$unwind: '$account',
},
{
$match: accountMatchStage,
},
{
$project: {
features: 1,
patch: 1,
role: 1,
},
},
];
}
private groupMetricValues(
samples: BaselineFeatureSample[],
): Map<string, number[]> {
const metricValuesByKey = new Map<string, number[]>();
for (const sample of samples) {
if (!isTeamPosition(sample.role)) {
continue;
}
for (const metric of METRICS) {
const value = finiteNumber(sample.features[metric.id]);
if (value === undefined) {
continue;
}
const key = baselineKey(metric.id, sample.role);
const values = metricValuesByKey.get(key) ?? [];
values.push(value);
metricValuesByKey.set(key, values);
}
}
return metricValuesByKey;
}
}
@@ -0,0 +1,148 @@
import { FEATURE_SCHEMA_VERSION, VECTOR_METRICS } from '@persona-lenz/shared';
import type { ConnectionService } from '../global/database/connection.service';
import type { MetricBaseline } from '../global/database/schemas';
import type { ExtractedPlayerMatchFeature } from './analysis.types';
import { MetricNormalizationService } from './metric-normalization.service';
interface ExecQuery<T> {
exec: jest.Mock<Promise<T>, []>;
}
function leanExecResolved<T>(value: T) {
return {
lean: jest.fn((): ExecQuery<T> => ({
exec: jest.fn<Promise<T>, []>().mockResolvedValue(value),
})),
};
}
function createFeature(
overrides: Partial<ExtractedPlayerMatchFeature> = {},
): ExtractedPlayerMatchFeature {
return {
matchId: 'KR_1',
puuid: 'target-puuid',
queueId: 420,
role: 'MIDDLE',
championId: 103,
gameCreation: 1_700_000_000_000,
gameDurationSec: 1_800,
win: true,
patch: '26.13',
features: {
csPerMin: 8,
kda: 30,
},
normalized: {
csPerMin: 0.5,
kda: 0.5,
},
vector: VECTOR_METRICS.map((metric) =>
metric.id === 'kda' || metric.id === 'csPerMin' ? 0.5 : 0,
),
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
normalizationMethod: 'registry-baseline',
confidence: 1,
timelineProcessed: true,
...overrides,
};
}
function createBaseline(
metricId: string,
overrides: Partial<MetricBaseline> = {},
): MetricBaseline {
return {
createdAt: new Date('2026-07-01T00:00:00.000Z'),
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
metricId,
role: 'MIDDLE',
cohort: 'MASTER_PLUS',
patch: 'ALL',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
sampleCount: 100,
percentileBreakpoints: [
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160,
170, 180, 190,
],
computedAt: new Date('2026-07-03T12:00:00.000Z'),
...overrides,
};
}
describe('MetricNormalizationService', () => {
it('normalizes observed metrics with population percentile baselines', async () => {
const find = jest.fn().mockReturnValue(
leanExecResolved([
createBaseline('kda'),
createBaseline('csPerMin', {
percentileBreakpoints: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
],
patch: '26.13',
}),
createBaseline('csPerMin', {
percentileBreakpoints: [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
],
}),
]),
);
const connectionService = {
getModel: jest.fn().mockResolvedValue({ find }),
} as unknown as ConnectionService;
const service = new MetricNormalizationService(connectionService);
const normalizedFeature = await service.normalizeFeature(createFeature());
expect(find).toHaveBeenCalledWith({
cohort: 'MASTER_PLUS',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
metricId: {
$in: ['csPerMin', 'kda'],
},
patch: {
$in: ['26.13', 'ALL'],
},
role: 'MIDDLE',
});
expect(normalizedFeature.normalizationMethod).toBe('population-percentile');
expect(normalizedFeature.normalized.kda).toBeCloseTo(0.15);
expect(normalizedFeature.normalized.csPerMin).toBeCloseTo(0.4);
expect(normalizedFeature.vector).toEqual(
VECTOR_METRICS.map(
(metric) => normalizedFeature.normalized[metric.id] ?? 0,
),
);
});
it('keeps registry normalization when a baseline is missing', async () => {
const find = jest
.fn()
.mockReturnValue(leanExecResolved([createBaseline('kda')]));
const connectionService = {
getModel: jest.fn().mockResolvedValue({ find }),
} as unknown as ConnectionService;
const service = new MetricNormalizationService(connectionService);
const feature = createFeature();
const normalizedFeature = await service.normalizeFeature(feature);
expect(normalizedFeature).toBe(feature);
expect(normalizedFeature.normalizationMethod).toBe('registry-baseline');
});
it('keeps registry normalization for unknown roles', async () => {
const find = jest.fn();
const connectionService = {
getModel: jest.fn().mockResolvedValue({ find }),
} as unknown as ConnectionService;
const service = new MetricNormalizationService(connectionService);
const feature = createFeature({ role: 'UNKNOWN' });
const normalizedFeature = await service.normalizeFeature(feature);
expect(normalizedFeature).toBe(feature);
expect(find).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,166 @@
import { Injectable } from '@nestjs/common';
import { FEATURE_SCHEMA_VERSION, VECTOR_METRICS } from '@persona-lenz/shared';
import { ConnectionService } from '../global/database/connection.service';
import type {
BaselineCohort,
MetricBaseline,
TeamPosition,
} from '../global/database/schemas';
import type { ExtractedPlayerMatchFeature } from './analysis.types';
interface NormalizeFeatureOptions {
cohort?: BaselineCohort;
}
const BASELINE_PERCENTILE_RANKS = Array.from(
{ length: 19 },
(_, index) => (index + 1) * 0.05,
);
const TEAM_POSITIONS = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'];
function isTeamPosition(value: unknown): value is TeamPosition {
return typeof value === 'string' && TEAM_POSITIONS.includes(value);
}
function finiteNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
function percentileRank(
rawValue: number,
percentileBreakpoints: number[],
): number {
const breakpoints = percentileBreakpoints.filter((value) =>
Number.isFinite(value),
);
if (breakpoints.length !== BASELINE_PERCENTILE_RANKS.length) {
return Number.NaN;
}
if (breakpoints[0] === breakpoints[breakpoints.length - 1]) {
return 0.5;
}
if (rawValue < (breakpoints[0] ?? 0)) {
return 0;
}
if (rawValue > (breakpoints[breakpoints.length - 1] ?? 0)) {
return 1;
}
for (let index = 0; index < breakpoints.length; index += 1) {
const currentBreakpoint = breakpoints[index] ?? 0;
const currentRank = BASELINE_PERCENTILE_RANKS[index] ?? 0;
if (rawValue === currentBreakpoint) {
return currentRank;
}
if (rawValue < currentBreakpoint) {
const previousBreakpoint = breakpoints[index - 1] ?? currentBreakpoint;
const previousRank = BASELINE_PERCENTILE_RANKS[index - 1] ?? 0;
if (currentBreakpoint === previousBreakpoint) {
return currentRank;
}
return (
previousRank +
((rawValue - previousBreakpoint) /
(currentBreakpoint - previousBreakpoint)) *
(currentRank - previousRank)
);
}
}
return 1;
}
@Injectable()
export class MetricNormalizationService {
constructor(private readonly connectionService: ConnectionService) {}
public async normalizeFeature(
feature: ExtractedPlayerMatchFeature,
options: NormalizeFeatureOptions = {},
): Promise<ExtractedPlayerMatchFeature> {
if (!isTeamPosition(feature.role)) {
return feature;
}
const observedMetricIds = Object.keys(feature.normalized).filter(
(metricId) => finiteNumber(feature.features[metricId]) !== undefined,
);
if (observedMetricIds.length === 0) {
return feature;
}
const baselinesByMetricId = await this.findBaselinesByMetricId({
cohort: options.cohort ?? 'MASTER_PLUS',
metricIds: observedMetricIds,
patch: feature.patch,
role: feature.role,
});
if (
observedMetricIds.some(
(metricId) => baselinesByMetricId.get(metricId) === undefined,
)
) {
return feature;
}
const normalized = { ...feature.normalized };
for (const metricId of observedMetricIds) {
const rawValue = finiteNumber(feature.features[metricId]);
const baseline = baselinesByMetricId.get(metricId);
if (rawValue === undefined || !baseline) {
return feature;
}
const normalizedValue = percentileRank(
rawValue,
baseline.percentileBreakpoints,
);
if (!Number.isFinite(normalizedValue)) {
return feature;
}
normalized[metricId] = Math.max(0, Math.min(1, normalizedValue));
}
return {
...feature,
normalized,
vector: VECTOR_METRICS.map((metric) => normalized[metric.id] ?? 0),
normalizationMethod: 'population-percentile',
};
}
private async findBaselinesByMetricId(params: {
cohort: BaselineCohort;
metricIds: string[];
patch: string;
role: TeamPosition;
}): Promise<Map<string, MetricBaseline>> {
const metricBaselineModel =
await this.connectionService.getModel('metricBaseline');
const baselines = await metricBaselineModel
.find({
metricId: {
$in: params.metricIds,
},
role: params.role,
cohort: params.cohort,
patch: {
$in: [params.patch, 'ALL'],
},
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
})
.lean<MetricBaseline[]>()
.exec();
const baselinesByMetricId = new Map<string, MetricBaseline>();
for (const baseline of baselines) {
const existingBaseline = baselinesByMetricId.get(baseline.metricId);
if (!existingBaseline || baseline.patch === params.patch) {
baselinesByMetricId.set(baseline.metricId, baseline);
}
}
return baselinesByMetricId;
}
}
@@ -0,0 +1,335 @@
import {
FEATURE_SCHEMA_VERSION,
METRICS,
VECTOR_METRICS,
type MetricDefinition,
} from '@persona-lenz/shared';
import type { PlayerMatchFeature } from '../global/database/schemas';
import {
buildProfileMetricValues,
ProfileBuilderService,
} from './profile-builder.service';
function createFeature(
overrides: Partial<PlayerMatchFeature> = {},
): PlayerMatchFeature {
const normalized = Object.fromEntries(
METRICS.map((metric) => [metric.id, 0.5]),
);
return {
createdAt: new Date('2026-07-01T00:00:00.000Z'),
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
matchId: 'KR_1',
puuid: 'target-puuid',
queueId: 420,
role: 'MIDDLE',
championId: 103,
gameCreation: 1_700_000_000_000,
gameDurationSec: 1800,
win: true,
patch: '26.13',
features: {},
normalized,
vector: METRICS.map((metric) => normalized[metric.id]),
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
normalizationMethod: 'registry-baseline',
confidence: 1,
timelineProcessed: true,
...overrides,
};
}
describe('ProfileBuilderService', () => {
const service = new ProfileBuilderService();
it('builds a confidence-weighted profile in registry vector order', () => {
const firstNormalized = Object.fromEntries(
METRICS.map((metric, index) => [metric.id, 0.8 - index * 0.01]),
);
const secondNormalized = Object.fromEntries(
METRICS.map((metric, index) => [metric.id, 0.2 + index * 0.01]),
);
const firstFeature = createFeature({
matchId: 'KR_1',
role: 'MIDDLE',
championId: 103,
win: true,
normalized: firstNormalized,
confidence: 1,
patch: '26.13',
gameCreation: 1_700_000_000_000,
});
firstFeature.vector = METRICS.map(
(metric) => firstFeature.normalized[metric.id],
);
const secondFeature = createFeature({
matchId: 'KR_2',
role: 'BOTTOM',
championId: 22,
win: false,
normalized: secondNormalized,
confidence: 0.5,
patch: '26.14',
gameCreation: 1_700_100_000_000,
});
secondFeature.vector = METRICS.map(
(metric) => secondFeature.normalized[metric.id],
);
const profile = service.buildProfile({
features: [firstFeature, secondFeature],
isSeed: false,
puuid: 'target-puuid',
queueId: 420,
});
expect(profile.mainRole).toBe('MIDDLE');
expect(profile.sampleGameCount).toBe(2);
for (const metric of METRICS.filter((metric) => metric.kind === 'scalar')) {
expect(profile.profile[metric.id]).toBeCloseTo(
(firstNormalized[metric.id] + secondNormalized[metric.id] * 0.5) / 1.5,
);
}
for (const metric of METRICS.filter((metric) => metric.kind === 'ratio')) {
expect(profile.profile[metric.id]).toBeUndefined();
}
expect(profile.vector).toEqual(
VECTOR_METRICS.map((metric) => profile.profile[metric.id] ?? 0),
);
expect(profile.championPool).toEqual([
{ championId: 103, games: 1, wins: 1 },
{ championId: 22, games: 1, wins: 0 },
]);
expect(profile.patches).toEqual(['26.13', '26.14']);
expect(profile.lastMatchAt).toEqual(new Date(1_700_100_000_000));
expect(profile.confidence).toBeCloseTo(0.3);
});
it('throws when no features are available', () => {
expect(() =>
service.buildProfile({
features: [],
isSeed: false,
puuid: 'target-puuid',
queueId: 420,
}),
).toThrow('Cannot build a profile without match features.');
});
it('discounts profile confidence when timeline metrics are missing', () => {
const profile = service.buildProfile({
features: [
createFeature({ timelineProcessed: true }),
createFeature({ matchId: 'KR_2', timelineProcessed: false }),
],
isSeed: false,
puuid: 'target-puuid',
queueId: 420,
});
expect(profile.confidence).toBeCloseTo(0.34);
});
it('marks profiles as population percentile only when every feature uses it', () => {
const populationProfile = service.buildProfile({
features: [
createFeature({ normalizationMethod: 'population-percentile' }),
createFeature({
matchId: 'KR_2',
normalizationMethod: 'population-percentile',
}),
],
isSeed: false,
puuid: 'target-puuid',
queueId: 420,
});
const mixedProfile = service.buildProfile({
features: [
createFeature({ normalizationMethod: 'population-percentile' }),
createFeature({ matchId: 'KR_2' }),
],
isSeed: false,
puuid: 'target-puuid',
queueId: 420,
});
expect(populationProfile.normalizationMethod).toBe('population-percentile');
expect(mixedProfile.normalizationMethod).toBe('registry-baseline');
});
it('denormalizes ranked solo tier fields into built profiles', () => {
const profile = service.buildProfile({
features: [createFeature()],
isSeed: true,
puuid: 'seed-puuid',
queueId: 420,
tier: 'CHALLENGER',
division: '',
leaguePoints: 987,
});
expect(profile).toMatchObject({
isSeed: true,
tier: 'CHALLENGER',
division: '',
leaguePoints: 987,
});
});
it('aggregates ratio metrics from raw numerator and denominator counts', () => {
const metrics: MetricDefinition[] = [
{
id: 'scalarMetric',
label: 'Scalar metric',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
},
{
id: 'rareEventRate',
label: 'Rare event rate',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
},
];
const firstFeature = createFeature({
features: {
rareEventRateNumerator: 1,
rareEventRateDenominator: 2,
},
normalized: { scalarMetric: 0.8 },
confidence: 1,
});
const secondFeature = createFeature({
features: {
rareEventRateNumerator: 2,
rareEventRateDenominator: 3,
},
normalized: { scalarMetric: 0.2 },
confidence: 0.5,
});
const profile = buildProfileMetricValues(
[firstFeature, secondFeature],
metrics,
);
expect(profile.scalarMetric).toBeCloseTo((0.8 + 0.2 * 0.5) / 1.5);
expect(profile.rareEventRate).toBeCloseTo(3 / 5);
});
it('aggregates scalar metrics only from features with observed normalized values', () => {
const metrics: MetricDefinition[] = [
{
id: 'observedScalar',
label: 'Observed scalar',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
},
];
const firstFeature = createFeature({
normalized: {},
confidence: 1,
});
const secondFeature = createFeature({
normalized: { observedScalar: 0.4 },
confidence: 0.5,
});
const profile = buildProfileMetricValues(
[firstFeature, secondFeature],
metrics,
);
expect(profile.observedScalar).toBe(0.4);
});
it('builds profile vectors from included metrics while retaining insight metrics', () => {
const actualShared = jest.requireActual<
typeof import('@persona-lenz/shared')
>('@persona-lenz/shared');
const metrics: MetricDefinition[] = [
{
id: 'scalarMetric',
label: 'Scalar metric',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
},
{
id: 'vectorRate',
label: 'Vector rate',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: true,
},
{
id: 'insightRate',
label: 'Insight rate',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
},
];
let profile: ReturnType<ProfileBuilderService['buildProfile']> | undefined;
jest.isolateModules(() => {
jest.doMock('@persona-lenz/shared', () => ({
...actualShared,
FEATURE_SCHEMA_VERSION: 99,
METRICS: metrics,
VECTOR_METRICS: metrics.filter((metric) => metric.includeInVector),
}));
const { ProfileBuilderService: MockedProfileBuilderService } =
jest.requireActual<typeof import('./profile-builder.service')>(
'./profile-builder.service',
);
const serviceWithMockedRegistry = new MockedProfileBuilderService();
const firstFeature = createFeature({
features: {
vectorRateNumerator: 1,
vectorRateDenominator: 2,
insightRateNumerator: 2,
insightRateDenominator: 4,
},
normalized: { scalarMetric: 0.8 },
confidence: 1,
});
const secondFeature = createFeature({
features: {
vectorRateNumerator: 3,
vectorRateDenominator: 4,
insightRateNumerator: 1,
insightRateDenominator: 1,
},
normalized: { scalarMetric: 0.2 },
confidence: 0.5,
});
profile = serviceWithMockedRegistry.buildProfile({
features: [firstFeature, secondFeature],
isSeed: false,
puuid: 'target-puuid',
queueId: 420,
});
});
jest.dontMock('@persona-lenz/shared');
expect(profile).toBeDefined();
expect(profile?.profile.scalarMetric).toBeCloseTo((0.8 + 0.2 * 0.5) / 1.5);
expect(profile?.profile.vectorRate).toBeCloseTo(4 / 6);
expect(profile?.profile.insightRate).toBeCloseTo(3 / 5);
expect(profile?.vector).toEqual([
profile?.profile.scalarMetric,
profile?.profile.vectorRate,
]);
expect(profile?.featureSchemaVersion).toBe(99);
});
});
@@ -0,0 +1,230 @@
import {
FEATURE_SCHEMA_VERSION,
METRICS,
VECTOR_METRICS,
type MetricDefinition,
type Role,
} from '@persona-lenz/shared';
import { Injectable } from '@nestjs/common';
import type {
NormalizationMethod,
PlayerMatchFeature,
} from '../global/database/schemas';
import type { BuiltPlayerProfile } from './analysis.types';
type ProfileSourceFeature = Pick<
PlayerMatchFeature,
| 'championId'
| 'confidence'
| 'features'
| 'gameCreation'
| 'normalized'
| 'normalizationMethod'
| 'patch'
| 'role'
| 'timelineProcessed'
| 'win'
>;
export interface BuildProfileParams {
division?: string;
features: ProfileSourceFeature[];
isSeed: boolean;
leaguePoints?: number;
puuid: string;
queueId: number;
tier?: string;
}
const ROLE_ORDER: Role[] = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'];
function toFiniteMetricValue(value: number | undefined): number {
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
function aggregateScalarMetric(
features: readonly ProfileSourceFeature[],
metricId: string,
): number | undefined {
let weightedSum = 0;
let confidenceSum = 0;
for (const feature of features) {
const metricValue = feature.normalized[metricId];
if (typeof metricValue !== 'number' || !Number.isFinite(metricValue)) {
continue;
}
weightedSum += metricValue * feature.confidence;
confidenceSum += feature.confidence;
}
if (confidenceSum <= 0) {
return undefined;
}
return weightedSum / confidenceSum;
}
function aggregateRatioMetric(
features: readonly ProfileSourceFeature[],
metricId: string,
): number | undefined {
const numeratorKey = `${metricId}Numerator`;
const denominatorKey = `${metricId}Denominator`;
const numerator = features.reduce(
(sum, feature) => sum + toFiniteMetricValue(feature.features[numeratorKey]),
0,
);
const denominator = features.reduce(
(sum, feature) =>
sum + toFiniteMetricValue(feature.features[denominatorKey]),
0,
);
if (denominator <= 0) {
return undefined;
}
return numerator / denominator;
}
export function buildProfileMetricValues(
features: readonly ProfileSourceFeature[],
metrics: readonly MetricDefinition[],
): Record<string, number> {
const profile: Record<string, number> = {};
for (const metric of metrics) {
const metricValue =
metric.kind === 'ratio'
? aggregateRatioMetric(features, metric.id)
: aggregateScalarMetric(features, metric.id);
if (metricValue !== undefined) {
profile[metric.id] = metricValue;
}
}
return profile;
}
function isRole(value: string): value is Role {
return ROLE_ORDER.includes(value as Role);
}
function resolveProfileNormalizationMethod(
features: readonly ProfileSourceFeature[],
): NormalizationMethod {
return features.every(
(feature) => feature.normalizationMethod === 'population-percentile',
)
? 'population-percentile'
: 'registry-baseline';
}
@Injectable()
export class ProfileBuilderService {
public buildProfile(params: BuildProfileParams): BuiltPlayerProfile {
if (params.features.length === 0) {
throw new Error('Cannot build a profile without match features.');
}
const totalConfidence = params.features.reduce(
(sum, feature) => sum + feature.confidence,
0,
);
const profile = buildProfileMetricValues(params.features, METRICS);
const roleCounts = new Map<Role, number>();
const championPool = new Map<
number,
{ championId: number; games: number; wins: number }
>();
for (const feature of params.features) {
if (isRole(feature.role)) {
roleCounts.set(feature.role, (roleCounts.get(feature.role) ?? 0) + 1);
}
const championEntry = championPool.get(feature.championId) ?? {
championId: feature.championId,
games: 0,
wins: 0,
};
championEntry.games += 1;
if (feature.win) championEntry.wins += 1;
championPool.set(feature.championId, championEntry);
}
const knownRoleGameCount = [...roleCounts.values()].reduce(
(sum, count) => sum + count,
0,
);
const roleDistribution = Object.fromEntries(
[...roleCounts.entries()].map(([role, count]) => [
role,
count / Math.max(knownRoleGameCount, 1),
]),
) as Partial<Record<Role, number>>;
const averageConfidence = totalConfidence / params.features.length;
const sampleSizeConfidenceMultiplier = Math.min(
params.features.length / 5,
1,
);
const timelineCoverageMultiplier =
0.7 +
0.3 *
(params.features.filter((feature) => feature.timelineProcessed).length /
params.features.length);
return {
puuid: params.puuid,
queueId: params.queueId,
mainRole: this.resolveMainRole(roleCounts),
roleDistribution,
sampleGameCount: params.features.length,
championPool: [...championPool.values()].sort(
(left, right) =>
right.games - left.games ||
right.wins - left.wins ||
left.championId - right.championId,
),
profile,
vector: VECTOR_METRICS.map((metric) => profile[metric.id] ?? 0),
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
normalizationMethod: resolveProfileNormalizationMethod(params.features),
confidence:
averageConfidence *
sampleSizeConfidenceMultiplier *
timelineCoverageMultiplier,
patches: [
...new Set(params.features.map((feature) => feature.patch)),
].sort(),
lastMatchAt: new Date(
Math.max(...params.features.map((feature) => feature.gameCreation)),
),
isSeed: params.isSeed,
...(params.tier ? { tier: params.tier } : {}),
...(params.division !== undefined ? { division: params.division } : {}),
...(params.leaguePoints !== undefined
? { leaguePoints: params.leaguePoints }
: {}),
};
}
private resolveMainRole(roleCounts: Map<Role, number>): Role {
let selectedRole: Role = 'MIDDLE';
let selectedCount = -1;
for (const role of ROLE_ORDER) {
const count = roleCounts.get(role) ?? 0;
if (count > selectedCount) {
selectedRole = role;
selectedCount = count;
}
}
return selectedRole;
}
}
@@ -0,0 +1,264 @@
import type { Job } from 'bullmq';
import type { ConnectionService } from '../global/database/connection.service';
import type { AnalysisPipelineService } from './analysis-pipeline.service';
import type { SeedCollectionService } from './seed-collection.service';
import {
DEFAULT_SEED_COLLECTION_MATCH_COUNT,
SEED_COLLECTION_JOB_NAME,
} from './analysis.constants';
import type { SeedCollectionJobData } from './analysis.types';
import { SeedCollectionProcessor } from './seed-collection.processor';
function createSeedCollectionJobData(
overrides: Partial<SeedCollectionJobData> = {},
): SeedCollectionJobData {
return {
platformRoute: 'kr',
queueId: 420,
sourceLimits: {
challenger: 50,
grandmaster: 50,
master: 50,
},
...overrides,
};
}
function createUpdateOneMock() {
return jest.fn(() => ({
exec: jest.fn().mockResolvedValue({ acknowledged: true }),
}));
}
function asRecord(value: unknown): Record<string, unknown> {
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
describe('SeedCollectionProcessor', () => {
it('delegates seed collection jobs and marks them completed', async () => {
const collectSeedAccounts = jest.fn().mockResolvedValue({
regionalRoute: 'asia',
selectedEntries: 150,
storedSeedAccounts: [
{
puuid: 'seed-puuid-1',
source: 'challenger',
},
],
storedAccounts: 149,
skippedAccounts: 1,
});
const processSeedAccountPipeline = jest.fn().mockResolvedValue({
puuid: 'seed-puuid-1',
fetchedMatches: 30,
extractedFeatures: 30,
profileBuilt: true,
});
const updateOne = createUpdateOneMock();
const connectionService = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const processor = new SeedCollectionProcessor(
{
collectSeedAccounts,
} as unknown as SeedCollectionService,
{
processSeedAccountPipeline,
} as unknown as AnalysisPipelineService,
connectionService,
);
await processor.process({
attemptsMade: 0,
id: 'seed-job-1',
name: SEED_COLLECTION_JOB_NAME,
opts: { attempts: 1 },
data: createSeedCollectionJobData(),
} as Job<unknown>);
expect(collectSeedAccounts).toHaveBeenCalledWith({
platformRoute: 'kr',
sourceLimits: {
challenger: 50,
grandmaster: 50,
master: 50,
},
});
expect(processSeedAccountPipeline).toHaveBeenCalledWith(
{
puuid: 'seed-puuid-1',
platformRoute: 'kr',
regionalRoute: 'asia',
queueId: 420,
requestedMatchCount: DEFAULT_SEED_COLLECTION_MATCH_COUNT,
},
'seed-job-1',
);
expect(updateOne).toHaveBeenCalledWith(
{ jobId: 'seed-job-1' },
{
$set: {
status: 'processing',
stage: 'collect-seed-accounts',
progress: {
fetchedMatches: 0,
totalMatches: 0,
},
},
},
);
const completedUpdate = updateOne.mock.calls.find(
([, update]) => asRecord(asRecord(update).$set).status === 'completed',
);
expect(completedUpdate).toBeDefined();
expect(asRecord(asRecord(completedUpdate?.[1]).$set)).toMatchObject({
status: 'completed',
stage: 'completed',
progress: {
fetchedMatches: 149,
totalMatches: 150,
},
});
expect(
asRecord(asRecord(completedUpdate?.[1]).$set).completedAt,
).toBeInstanceOf(Date);
});
it.each([
{
data: null,
expectedError: 'Seed collection job data must be an object.',
},
{
data: {
...createSeedCollectionJobData(),
platformRoute: 'invalid',
},
expectedError: 'Seed collection job platformRoute is unsupported.',
},
{
data: {
...createSeedCollectionJobData(),
queueId: 430,
},
expectedError: 'Seed collection job queueId is unsupported.',
},
{
data: {
...createSeedCollectionJobData(),
sourceLimits: {
challenger: Number.NaN,
},
},
expectedError:
'Seed collection job sourceLimits.challenger must be a non-negative finite number.',
},
{
data: {
...createSeedCollectionJobData(),
sourceLimits: {
diamond: 50,
},
},
expectedError: 'Seed collection job sourceLimits.diamond is unsupported.',
},
])(
'rejects malformed seed collection payloads',
async ({ data, expectedError }) => {
const collectSeedAccounts = jest.fn();
const processSeedAccountPipeline = jest.fn();
const updateOne = createUpdateOneMock();
const connectionService = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const processor = new SeedCollectionProcessor(
{
collectSeedAccounts,
} as unknown as SeedCollectionService,
{
processSeedAccountPipeline,
} as unknown as AnalysisPipelineService,
connectionService,
);
await expect(
processor.process({
attemptsMade: 0,
id: 'seed-job-1',
name: SEED_COLLECTION_JOB_NAME,
opts: { attempts: 1 },
data,
} as Job<unknown>),
).rejects.toThrow(expectedError);
expect(collectSeedAccounts).not.toHaveBeenCalled();
expect(processSeedAccountPipeline).not.toHaveBeenCalled();
expect(updateOne).not.toHaveBeenCalled();
},
);
it('marks final-attempt failures as failed', async () => {
const collectSeedAccounts = jest
.fn()
.mockRejectedValue(new Error('Riot unavailable'));
const processSeedAccountPipeline = jest.fn();
const updateOne = createUpdateOneMock();
const connectionService = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const processor = new SeedCollectionProcessor(
{
collectSeedAccounts,
} as unknown as SeedCollectionService,
{
processSeedAccountPipeline,
} as unknown as AnalysisPipelineService,
connectionService,
);
await expect(
processor.process({
attemptsMade: 0,
id: 'seed-job-1',
name: SEED_COLLECTION_JOB_NAME,
opts: { attempts: 1 },
data: createSeedCollectionJobData(),
} as Job<unknown>),
).rejects.toThrow('Riot unavailable');
expect(processSeedAccountPipeline).not.toHaveBeenCalled();
expect(updateOne).toHaveBeenCalledWith(
{ jobId: 'seed-job-1' },
{
$set: {
status: 'failed',
error: 'Seed collection failed during processing.',
},
},
);
});
it('rejects unsupported job names', async () => {
const processor = new SeedCollectionProcessor(
{
collectSeedAccounts: jest.fn(),
} as unknown as SeedCollectionService,
{
processSeedAccountPipeline: jest.fn(),
} as unknown as AnalysisPipelineService,
{
getModel: jest.fn(),
} as unknown as ConnectionService,
);
await expect(
processor.process({
id: 'seed-job-1',
name: 'unexpected',
data: createSeedCollectionJobData(),
} as Job<unknown>),
).rejects.toThrow('Unsupported seed collection job name "unexpected".');
});
});
@@ -0,0 +1,174 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import type { Job } from 'bullmq';
import { ConnectionService } from '../global/database/connection.service';
import { SEED_SOURCES, type SeedSource } from '../global/database/schemas';
import {
DEFAULT_SEED_COLLECTION_MATCH_COUNT,
SEED_COLLECTION_JOB_NAME,
SEED_COLLECTION_QUEUE_NAME,
} from './analysis.constants';
import type { SeedCollectionJobData } from './analysis.types';
import {
RIOT_PLATFORM_ROUTES,
type RiotPlatformRoute,
} from '../riot/riot.types';
import { AnalysisPipelineService } from './analysis-pipeline.service';
import { SeedCollectionService } from './seed-collection.service';
@Processor(SEED_COLLECTION_QUEUE_NAME, { concurrency: 1 })
export class SeedCollectionProcessor extends WorkerHost {
constructor(
private readonly seedCollectionService: SeedCollectionService,
private readonly analysisPipelineService: AnalysisPipelineService,
private readonly connectionService: ConnectionService,
) {
super();
}
public async process(job: Job<unknown>): Promise<void> {
if (!job.id) {
throw new Error('Seed collection job is missing a BullMQ job id.');
}
if (job.name !== SEED_COLLECTION_JOB_NAME) {
throw new Error(`Unsupported seed collection job name "${job.name}".`);
}
const data = this.parseSeedCollectionJobData(job.data);
try {
await this.updateJob(job.id, {
status: 'processing',
stage: 'collect-seed-accounts',
progress: {
fetchedMatches: 0,
totalMatches: 0,
},
});
const result = await this.seedCollectionService.collectSeedAccounts({
platformRoute: data.platformRoute,
...(data.sourceLimits ? { sourceLimits: data.sourceLimits } : {}),
});
for (const storedSeedAccount of result.storedSeedAccounts) {
await this.analysisPipelineService.processSeedAccountPipeline(
{
puuid: storedSeedAccount.puuid,
platformRoute: data.platformRoute,
regionalRoute: result.regionalRoute,
queueId: data.queueId,
requestedMatchCount: DEFAULT_SEED_COLLECTION_MATCH_COUNT,
},
job.id,
);
}
await this.updateJob(job.id, {
status: 'completed',
stage: 'completed',
progress: {
fetchedMatches: result.storedAccounts,
totalMatches: result.selectedEntries,
},
completedAt: new Date(),
});
} catch (error) {
if (this.isFinalAttempt(job)) {
await this.updateJob(job.id, {
status: 'failed',
error: this.publicErrorMessage(),
});
}
throw error;
}
}
private parseSeedCollectionJobData(value: unknown): SeedCollectionJobData {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error('Seed collection job data must be an object.');
}
const record = value as Record<string, unknown>;
const platformRoute = this.parsePlatformRoute(record.platformRoute);
const queueId = this.parseQueueId(record.queueId);
const sourceLimits = this.parseSourceLimits(record.sourceLimits);
return {
platformRoute,
queueId,
...(sourceLimits ? { sourceLimits } : {}),
};
}
private parsePlatformRoute(value: unknown): RiotPlatformRoute {
if (
typeof value !== 'string' ||
!RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
) {
throw new Error('Seed collection job platformRoute is unsupported.');
}
return value as RiotPlatformRoute;
}
private parseQueueId(value: unknown): number {
if (value !== 420) {
throw new Error('Seed collection job queueId is unsupported.');
}
return value;
}
private parseSourceLimits(
value: unknown,
): Partial<Record<SeedSource, number>> | undefined {
if (value === undefined) {
return undefined;
}
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error('Seed collection job sourceLimits must be an object.');
}
const sourceLimits = value as Record<string, unknown>;
const parsedSourceLimits: Partial<Record<SeedSource, number>> = {};
for (const [source, limit] of Object.entries(sourceLimits)) {
if (!SEED_SOURCES.includes(source as SeedSource)) {
throw new Error(
`Seed collection job sourceLimits.${source} is unsupported.`,
);
}
if (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0) {
throw new Error(
`Seed collection job sourceLimits.${source} must be a non-negative finite number.`,
);
}
parsedSourceLimits[source as SeedSource] = Math.trunc(limit);
}
return parsedSourceLimits;
}
private async updateJob(
jobId: string,
updates: Record<string, unknown>,
): Promise<void> {
const analysisJobModel =
await this.connectionService.getModel('analysisJob');
await analysisJobModel
.updateOne(
{ jobId },
{
$set: updates,
},
)
.exec();
}
private isFinalAttempt(job: Job<unknown>): boolean {
const attempts =
typeof job.opts?.attempts === 'number' && job.opts.attempts > 0
? job.opts.attempts
: 1;
return job.attemptsMade + 1 >= attempts;
}
private publicErrorMessage(): string {
return 'Seed collection failed during processing.';
}
}
@@ -0,0 +1,417 @@
import { Logger } from '@nestjs/common';
import type { ConnectionService } from '../global/database/connection.service';
import type { Account } from '../global/database/schemas';
import type {
RiotAccountDto,
RiotApexLeagueEntryDto,
RiotApexLeagueListDto,
RiotApiClient,
RiotLeagueEntryDto,
RiotSummonerDto,
} from '../riot/riot-api.client';
import { SeedCollectionService } from './seed-collection.service';
interface ExecQuery<T> {
exec: jest.Mock<Promise<T>, []>;
}
type FindOneAndUpdateAccountMock = jest.Mock<
LeanAccountQuery,
[Record<string, unknown>, Record<string, unknown>, Record<string, unknown>?]
>;
interface LeanAccountQuery {
lean: jest.Mock<ExecQuery<Account>, []>;
}
function asRecord(value: unknown): Record<string, unknown> {
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
function execResolved<T>(value: T): ExecQuery<T> {
return { exec: jest.fn<Promise<T>, []>().mockResolvedValue(value) };
}
function leanExecResolved<T>(value: T) {
return {
lean: jest.fn(() => execResolved(value)),
};
}
function selectLeanExecResolved<T>(value: T) {
const exec = jest.fn<Promise<T>, []>().mockResolvedValue(value);
const lean = jest.fn(() => ({ exec }));
const select = jest.fn(() => ({ lean }));
return {
chain: { select },
exec,
lean,
select,
};
}
function createApexEntry(
puuid: string,
overrides: Partial<RiotApexLeagueEntryDto> = {},
): RiotApexLeagueEntryDto {
return {
freshBlood: false,
hotStreak: false,
inactive: false,
leaguePoints: 100,
losses: 20,
puuid,
queueType: 'RANKED_SOLO_5x5',
rank: '',
tier: 'CHALLENGER',
veteran: false,
wins: 40,
...overrides,
};
}
function createAccount(puuid: string): RiotAccountDto {
return {
puuid,
gameName: `Game ${puuid}`,
tagLine: 'KR1',
};
}
function createSummoner(puuid: string): RiotSummonerDto {
return {
profileIconId: 5935,
puuid,
summonerLevel: 550,
};
}
function createLeagueEntry(
puuid: string,
overrides: Partial<RiotLeagueEntryDto> = {},
): RiotLeagueEntryDto {
return {
freshBlood: false,
hotStreak: false,
inactive: false,
leaguePoints: 123,
losses: 10,
queueType: 'RANKED_SOLO_5x5',
rank: '',
tier: 'CHALLENGER',
veteran: false,
wins: 20,
...overrides,
};
}
function createStoredAccount(overrides: Partial<Account> = {}): Account {
return {
createdAt: new Date('2026-07-01T00:00:00.000Z'),
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
puuid: 'seed-puuid',
gameName: 'Seed Player',
tagLine: 'KR1',
platformRoute: 'kr',
regionalRoute: 'asia',
profileIconId: 5935,
summonerLevel: 550,
tiers: [],
isSeed: true,
seedSource: 'challenger',
seedAddedAt: new Date('2026-07-03T00:00:00.000Z'),
lastSeedCollectedAt: new Date('2026-07-03T00:00:00.000Z'),
...overrides,
};
}
function createHarness(options: { existingSeedAddedAt?: Date } = {}) {
const findOneAccount = jest
.fn()
.mockReturnValue(
selectLeanExecResolved(
options.existingSeedAddedAt
? { seedAddedAt: options.existingSeedAddedAt }
: null,
).chain,
);
const findOneAndUpdateAccount: FindOneAndUpdateAccountMock = jest
.fn<LeanAccountQuery, Parameters<FindOneAndUpdateAccountMock>>()
.mockImplementation((query) => {
const puuid = asRecord(query).puuid;
return leanExecResolved(
createStoredAccount({
puuid: typeof puuid === 'string' ? puuid : 'seed-puuid',
}),
);
});
const accountModel = {
findOne: findOneAccount,
findOneAndUpdate: findOneAndUpdateAccount,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(accountModel),
} as unknown as ConnectionService;
const getAccountByPuuid = jest.fn<Promise<RiotAccountDto>, [string, string]>(
(puuid) => Promise.resolve(createAccount(puuid)),
);
const getChallengerLeagueByQueue = jest
.fn<Promise<RiotApexLeagueListDto>, [string, string]>()
.mockResolvedValue({
entries: [],
queueType: 'RANKED_SOLO_5x5',
tier: 'CHALLENGER',
});
const getGrandmasterLeagueByQueue = jest
.fn<Promise<RiotApexLeagueListDto>, [string, string]>()
.mockResolvedValue({
entries: [],
queueType: 'RANKED_SOLO_5x5',
tier: 'GRANDMASTER',
});
const getLeagueEntriesByPuuid = jest.fn<
Promise<RiotLeagueEntryDto[]>,
[string, string]
>((puuid) => Promise.resolve([createLeagueEntry(puuid)]));
const getMasterLeagueByQueue = jest
.fn<Promise<RiotApexLeagueListDto>, [string, string]>()
.mockResolvedValue({
entries: [],
queueType: 'RANKED_SOLO_5x5',
tier: 'MASTER',
});
const getSummonerByPuuid = jest.fn<
Promise<RiotSummonerDto>,
[string, string]
>((puuid) => Promise.resolve(createSummoner(puuid)));
const riotApiClient = {
getAccountByPuuid,
getChallengerLeagueByQueue,
getGrandmasterLeagueByQueue,
getLeagueEntriesByPuuid,
getMasterLeagueByQueue,
getSummonerByPuuid,
} as unknown as RiotApiClient;
return {
accountModel,
connectionService,
findOneAccount,
findOneAndUpdateAccount,
getAccountByPuuid,
getChallengerLeagueByQueue,
getGrandmasterLeagueByQueue,
getLeagueEntriesByPuuid,
getMasterLeagueByQueue,
getSummonerByPuuid,
riotApiClient,
service: new SeedCollectionService(connectionService, riotApiClient),
};
}
describe('SeedCollectionService', () => {
it('collects bounded high-tier seed account metadata', async () => {
const collectedAt = new Date('2026-07-03T12:00:00.000Z');
const harness = createHarness();
harness.getChallengerLeagueByQueue.mockResolvedValue({
entries: [
createApexEntry('challenger-low', { leaguePoints: 10, wins: 5 }),
createApexEntry('challenger-high', { leaguePoints: 500, wins: 50 }),
],
queueType: 'RANKED_SOLO_5x5',
tier: 'CHALLENGER',
});
harness.getGrandmasterLeagueByQueue.mockResolvedValue({
entries: [createApexEntry('grandmaster-one', { tier: 'GRANDMASTER' })],
queueType: 'RANKED_SOLO_5x5',
tier: 'GRANDMASTER',
});
harness.getMasterLeagueByQueue.mockResolvedValue({
entries: [createApexEntry('master-one', { tier: 'MASTER' })],
queueType: 'RANKED_SOLO_5x5',
tier: 'MASTER',
});
const result = await harness.service.collectSeedAccounts({
collectedAt,
platformRoute: 'kr',
sourceLimits: {
challenger: 1,
grandmaster: 1,
master: 1,
},
});
expect(result).toMatchObject({
platformRoute: 'kr',
regionalRoute: 'asia',
queueType: 'RANKED_SOLO_5x5',
storedAccounts: 3,
storedSeedAccounts: [
{
puuid: 'challenger-high',
source: 'challenger',
},
{
puuid: 'grandmaster-one',
source: 'grandmaster',
},
{
puuid: 'master-one',
source: 'master',
},
],
skippedAccounts: 0,
sourceResults: [
{
discoveredEntries: 2,
selectedEntries: 1,
source: 'challenger',
storedAccounts: 1,
},
{
discoveredEntries: 1,
selectedEntries: 1,
source: 'grandmaster',
storedAccounts: 1,
},
{
discoveredEntries: 1,
selectedEntries: 1,
source: 'master',
storedAccounts: 1,
},
],
});
expect(harness.getAccountByPuuid).toHaveBeenCalledWith(
'challenger-high',
'asia',
);
expect(harness.findOneAndUpdateAccount).toHaveBeenCalledTimes(3);
const challengerUpdate = harness.findOneAndUpdateAccount.mock.calls.find(
([query]) => asRecord(query).puuid === 'challenger-high',
);
expect(challengerUpdate).toBeDefined();
expect(challengerUpdate?.[1]).toMatchObject({
$set: {
gameName: 'Game challenger-high',
isSeed: true,
lastSeedCollectedAt: collectedAt,
platformRoute: 'kr',
puuid: 'challenger-high',
regionalRoute: 'asia',
seedAddedAt: collectedAt,
seedSource: 'challenger',
tagLine: 'KR1',
tiers: [
{
fetchedAt: collectedAt,
leaguePoints: 123,
losses: 10,
queueType: 'RANKED_SOLO_5x5',
rank: '',
tier: 'CHALLENGER',
wins: 20,
},
],
tiersFetchedAt: collectedAt,
},
});
expect(challengerUpdate?.[2]).toEqual({
new: true,
setDefaultsOnInsert: true,
upsert: true,
});
});
it('preserves the first seedAddedAt timestamp when refreshing a seed account', async () => {
const existingSeedAddedAt = new Date('2026-07-01T00:00:00.000Z');
const collectedAt = new Date('2026-07-03T12:00:00.000Z');
const harness = createHarness({ existingSeedAddedAt });
harness.getChallengerLeagueByQueue.mockResolvedValue({
entries: [createApexEntry('challenger-one')],
queueType: 'RANKED_SOLO_5x5',
tier: 'CHALLENGER',
});
await harness.service.collectSeedAccounts({
collectedAt,
platformRoute: 'kr',
sourceLimits: {
challenger: 1,
grandmaster: 0,
master: 0,
},
});
const challengerUpdate = harness.findOneAndUpdateAccount.mock.calls.find(
([query]) => asRecord(query).puuid === 'challenger-one',
);
expect(challengerUpdate).toBeDefined();
expect(challengerUpdate?.[1]).toMatchObject({
$set: {
lastSeedCollectedAt: collectedAt,
seedAddedAt: existingSeedAddedAt,
},
});
});
it('skips failed candidate accounts without aborting the collection pass', async () => {
const loggerWarn = jest
.spyOn(Logger.prototype, 'warn')
.mockImplementation(() => undefined);
const harness = createHarness();
harness.getChallengerLeagueByQueue.mockResolvedValue({
entries: [
createApexEntry('broken-puuid', { leaguePoints: 500 }),
createApexEntry('stored-puuid', { leaguePoints: 400 }),
],
queueType: 'RANKED_SOLO_5x5',
tier: 'CHALLENGER',
});
harness.getAccountByPuuid.mockImplementation((puuid) => {
if (puuid === 'broken-puuid') {
return Promise.reject(new Error('Riot account lookup failed'));
}
return Promise.resolve(createAccount(puuid));
});
const result = await harness.service.collectSeedAccounts({
platformRoute: 'kr',
sourceLimits: {
challenger: 2,
grandmaster: 0,
master: 0,
},
});
expect(result).toMatchObject({
storedAccounts: 1,
storedSeedAccounts: [
{
puuid: 'stored-puuid',
source: 'challenger',
},
],
skippedAccounts: 1,
sourceResults: [
expect.objectContaining({
skippedAccounts: 1,
storedAccounts: 1,
}),
expect.any(Object),
expect.any(Object),
],
});
expect(harness.findOneAndUpdateAccount).toHaveBeenCalledTimes(1);
expect(harness.findOneAndUpdateAccount.mock.calls[0]?.[0]).toEqual({
puuid: 'stored-puuid',
});
loggerWarn.mockRestore();
});
});
@@ -0,0 +1,351 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConnectionService } from '../global/database/connection.service';
import type { Account, SeedSource, TierInfo } from '../global/database/schemas';
import { SEED_SOURCES } from '../global/database/schemas';
import {
RiotApiClient,
type RiotApexLeagueEntryDto,
type RiotApexLeagueListDto,
type RiotLeagueEntryDto,
} from '../riot/riot-api.client';
import {
toRegionalRoute,
type RiotPlatformRoute,
type RiotRegionalRoute,
} from '../riot/riot.types';
import {
DEFAULT_SEED_COLLECTION_QUEUE_TYPE,
DEFAULT_SEED_COLLECTION_SOURCE_LIMIT,
} from './analysis.constants';
export interface SeedCollectionOptions {
collectedAt?: Date;
platformRoute: RiotPlatformRoute;
queueType?: string;
sourceLimits?: Partial<Record<SeedSource, number>>;
}
export interface SeedCollectionSourceResult {
source: SeedSource;
discoveredEntries: number;
selectedEntries: number;
storedAccounts: number;
skippedAccounts: number;
duplicateAccounts: number;
}
export interface SeedCollectionStoredAccount {
puuid: string;
source: SeedSource;
}
export interface SeedCollectionResult {
platformRoute: RiotPlatformRoute;
regionalRoute: RiotRegionalRoute;
queueType: string;
sourceResults: SeedCollectionSourceResult[];
discoveredEntries: number;
selectedEntries: number;
storedAccounts: number;
skippedAccounts: number;
duplicateAccounts: number;
storedSeedAccounts: SeedCollectionStoredAccount[];
}
@Injectable()
export class SeedCollectionService {
private readonly logger = new Logger(SeedCollectionService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly riotApiClient: RiotApiClient,
) {}
public async collectSeedAccounts(
options: SeedCollectionOptions,
): Promise<SeedCollectionResult> {
const collectedAt = options.collectedAt ?? new Date();
const platformRoute = options.platformRoute;
const regionalRoute = toRegionalRoute(platformRoute);
const queueType = options.queueType ?? DEFAULT_SEED_COLLECTION_QUEUE_TYPE;
const sourceResults: SeedCollectionSourceResult[] = [];
const storedSeedAccounts: SeedCollectionStoredAccount[] = [];
const seenPuuids = new Set<string>();
for (const source of SEED_SOURCES) {
const sourceLimit = this.normalizeSourceLimit(
options.sourceLimits?.[source],
);
const leagueList = await this.fetchSeedLeagueList(
source,
queueType,
platformRoute,
);
const selectedEntries = this.selectCandidateEntries(
source,
leagueList.entries,
sourceLimit,
);
const sourceResult: SeedCollectionSourceResult = {
source,
discoveredEntries: leagueList.entries.length,
selectedEntries: selectedEntries.length,
storedAccounts: 0,
skippedAccounts: 0,
duplicateAccounts: 0,
};
for (const selectedEntry of selectedEntries) {
if (seenPuuids.has(selectedEntry.puuid)) {
sourceResult.duplicateAccounts += 1;
continue;
}
seenPuuids.add(selectedEntry.puuid);
try {
const storedAccount = await this.storeSeedAccount({
collectedAt,
platformRoute,
puuid: selectedEntry.puuid,
regionalRoute,
source,
});
storedSeedAccounts.push({
puuid: storedAccount.puuid,
source,
});
sourceResult.storedAccounts += 1;
} catch (error) {
sourceResult.skippedAccounts += 1;
this.logger.warn(
`Skipping seed puuid="${this.safeLogText(selectedEntry.puuid)}" source="${source}" after collection failure: ${this.safeLogText(this.errorMessage(error))}`,
);
}
}
sourceResults.push(sourceResult);
}
return {
platformRoute,
regionalRoute,
queueType,
sourceResults,
discoveredEntries: this.sumSourceResults(
sourceResults,
'discoveredEntries',
),
selectedEntries: this.sumSourceResults(sourceResults, 'selectedEntries'),
storedAccounts: this.sumSourceResults(sourceResults, 'storedAccounts'),
skippedAccounts: this.sumSourceResults(sourceResults, 'skippedAccounts'),
duplicateAccounts: this.sumSourceResults(
sourceResults,
'duplicateAccounts',
),
storedSeedAccounts,
};
}
private async fetchSeedLeagueList(
source: SeedSource,
queueType: string,
platformRoute: RiotPlatformRoute,
): Promise<RiotApexLeagueListDto> {
if (source === 'challenger') {
return this.riotApiClient.getChallengerLeagueByQueue(
queueType,
platformRoute,
);
}
if (source === 'grandmaster') {
return this.riotApiClient.getGrandmasterLeagueByQueue(
queueType,
platformRoute,
);
}
return this.riotApiClient.getMasterLeagueByQueue(queueType, platformRoute);
}
private selectCandidateEntries(
source: SeedSource,
entries: RiotApexLeagueEntryDto[],
sourceLimit: number,
): RiotApexLeagueEntryDto[] {
if (sourceLimit <= 0) {
return [];
}
const sortedEntries = this.deduplicateEntries(entries).sort((left, right) =>
this.compareApexEntries(left, right),
);
if (source === 'master' && sortedEntries.length > sourceLimit) {
return this.shuffleEntries(sortedEntries).slice(0, sourceLimit);
}
return sortedEntries.slice(0, sourceLimit);
}
private deduplicateEntries(
entries: RiotApexLeagueEntryDto[],
): RiotApexLeagueEntryDto[] {
const bestEntriesByPuuid = new Map<string, RiotApexLeagueEntryDto>();
for (const entry of entries) {
const existingEntry = bestEntriesByPuuid.get(entry.puuid);
if (!existingEntry || this.compareApexEntries(entry, existingEntry) < 0) {
bestEntriesByPuuid.set(entry.puuid, entry);
}
}
return [...bestEntriesByPuuid.values()];
}
private compareApexEntries(
left: RiotApexLeagueEntryDto,
right: RiotApexLeagueEntryDto,
): number {
if (right.leaguePoints !== left.leaguePoints) {
return right.leaguePoints - left.leaguePoints;
}
if (right.wins !== left.wins) {
return right.wins - left.wins;
}
if (left.losses !== right.losses) {
return left.losses - right.losses;
}
return left.puuid.localeCompare(right.puuid);
}
private shuffleEntries(
entries: RiotApexLeagueEntryDto[],
): RiotApexLeagueEntryDto[] {
const shuffledEntries = [...entries];
for (
let currentIndex = shuffledEntries.length - 1;
currentIndex > 0;
currentIndex -= 1
) {
const swapIndex = Math.floor(Math.random() * (currentIndex + 1));
const currentEntry = shuffledEntries[currentIndex];
const swapEntry = shuffledEntries[swapIndex];
if (!currentEntry || !swapEntry) {
continue;
}
shuffledEntries[currentIndex] = swapEntry;
shuffledEntries[swapIndex] = currentEntry;
}
return shuffledEntries;
}
private async storeSeedAccount(params: {
collectedAt: Date;
platformRoute: RiotPlatformRoute;
puuid: string;
regionalRoute: RiotRegionalRoute;
source: SeedSource;
}): Promise<Account> {
const account = await this.riotApiClient.getAccountByPuuid(
params.puuid,
params.regionalRoute,
);
const [summoner, leagueEntries] = await Promise.all([
this.riotApiClient.getSummonerByPuuid(
account.puuid,
params.platformRoute,
),
this.riotApiClient.getLeagueEntriesByPuuid(
account.puuid,
params.platformRoute,
),
]);
const accountModel = await this.connectionService.getModel('account');
const existingAccount = await accountModel
.findOne({ puuid: account.puuid })
.select('seedAddedAt')
.lean<Pick<Account, 'seedAddedAt'> | null>()
.exec();
const seedAddedAt = existingAccount?.seedAddedAt ?? params.collectedAt;
const storedAccount = await accountModel
.findOneAndUpdate(
{ puuid: account.puuid },
{
$set: {
puuid: account.puuid,
gameName: account.gameName,
tagLine: account.tagLine,
platformRoute: params.platformRoute,
regionalRoute: params.regionalRoute,
profileIconId: summoner.profileIconId,
summonerLevel: summoner.summonerLevel,
tiers: this.toTierInfo(leagueEntries, params.collectedAt),
tiersFetchedAt: params.collectedAt,
isSeed: true,
seedSource: params.source,
seedAddedAt,
lastSeedCollectedAt: params.collectedAt,
},
},
{
new: true,
setDefaultsOnInsert: true,
upsert: true,
},
)
.lean<Account>()
.exec();
if (!storedAccount) {
throw new Error('Failed to store seed Riot account.');
}
return storedAccount;
}
private toTierInfo(
entries: RiotLeagueEntryDto[],
fetchedAt: Date,
): TierInfo[] {
return entries.map((entry) => ({
queueType: entry.queueType,
tier: entry.tier,
rank: entry.rank,
leaguePoints: entry.leaguePoints,
wins: entry.wins,
losses: entry.losses,
fetchedAt,
}));
}
private normalizeSourceLimit(limit: number | undefined): number {
if (limit === undefined) {
return DEFAULT_SEED_COLLECTION_SOURCE_LIMIT;
}
if (!Number.isFinite(limit) || limit < 0) {
return DEFAULT_SEED_COLLECTION_SOURCE_LIMIT;
}
return Math.trunc(limit);
}
private sumSourceResults(
sourceResults: SeedCollectionSourceResult[],
key: keyof Pick<
SeedCollectionSourceResult,
| 'discoveredEntries'
| 'selectedEntries'
| 'storedAccounts'
| 'skippedAccounts'
| 'duplicateAccounts'
>,
): number {
return sourceResults.reduce(
(total, sourceResult) => total + sourceResult[key],
0,
);
}
private errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
private safeLogText(value: string): string {
return value.replace(/[\n\r\t]/g, ' ').slice(0, 500);
}
}
@@ -0,0 +1,358 @@
import { FEATURE_SCHEMA_VERSION, VECTOR_DIMENSION } from '@persona-lenz/shared';
import type { ConnectionService } from '../global/database/connection.service';
import { SimilarPlayerService } from './similar-player.service';
function createLeanExec<T>(value: T) {
return {
lean: jest.fn(() => ({
exec: jest.fn().mockResolvedValue(value),
})),
};
}
function createAggregateExec<T>(value: T) {
return {
exec: jest.fn().mockResolvedValue(value),
};
}
function createSortedLeanExec<T>(value: T) {
return {
sort: jest.fn(() => ({
lean: jest.fn(() => ({
exec: jest.fn().mockResolvedValue(value),
})),
})),
};
}
function createUpdateExec<T>(value: T) {
return {
exec: jest.fn().mockResolvedValue(value),
};
}
function createVector(fillValue = 0.5): number[] {
return Array.from({ length: VECTOR_DIMENSION }, () => fillValue);
}
function createProfile(overrides: Record<string, unknown> = {}) {
return {
puuid: 'target-puuid',
queueId: 420,
mainRole: 'MIDDLE',
sampleGameCount: 35,
championPool: [
{ championId: 103, games: 8, wins: 5 },
{ championId: 84, games: 6, wins: 4 },
{ championId: 7, games: 5, wins: 2 },
],
profile: {
kda: 0.3,
killParticipation: 0.5,
goldPerMin: 0.5,
csPerMin: 0.5,
deathsPerMin: 0.7,
},
vector: createVector(),
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
lastMatchAt: new Date('2026-07-02T00:00:00.000Z'),
tier: 'DIAMOND',
isSeed: false,
...overrides,
};
}
describe('SimilarPlayerService', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2026-07-03T00:00:00.000Z'));
});
afterEach(() => {
jest.useRealTimers();
});
it('queries similar profiles without tier filters and ranks by style similarity', async () => {
const currentProfile = createProfile();
const findOne = jest.fn(() => createLeanExec(currentProfile));
const recommendationFindOne = jest.fn(() => createSortedLeanExec(null));
const updateOne = jest.fn(() => createUpdateExec({ acknowledged: true }));
const aggregate = jest.fn(() =>
createAggregateExec([
createProfile({
puuid: 'lower-style-better-context',
championPool: [
{ championId: 103, games: 12, wins: 8 },
{ championId: 84, games: 5, wins: 4 },
{ championId: 777, games: 5, wins: 3 },
],
profile: {
kda: 0.9,
killParticipation: 0.49,
goldPerMin: 0.8,
csPerMin: 0.51,
deathsPerMin: 0.2,
},
sampleGameCount: 20,
tier: 'CHALLENGER',
leaguePoints: 900,
lastMatchAt: new Date('2026-07-03T00:00:00.000Z'),
score: 0.8,
}),
createProfile({
puuid: 'higher-style-similar-player',
championPool: [{ championId: 222, games: 30, wins: 20 }],
profile: {
kda: 0.4,
killParticipation: 0.52,
goldPerMin: 0.55,
csPerMin: 0.7,
deathsPerMin: 0.6,
},
sampleGameCount: 30,
tier: 'PLATINUM',
lastMatchAt: new Date('2026-06-19T00:00:00.000Z'),
score: 0.9,
}),
]),
);
const service = new SimilarPlayerService({
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'playerProfile'
? { findOne, aggregate }
: { findOne: recommendationFindOne, updateOne },
),
),
} as unknown as ConnectionService);
const result = await service.findSimilarPlayers('target-puuid', 420, 2);
expect(findOne).toHaveBeenCalledWith({
puuid: 'target-puuid',
queueId: 420,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
});
expect(aggregate).toHaveBeenCalledWith([
{
$vectorSearch: {
index: 'player_profile_vector_index',
path: 'vector',
queryVector: currentProfile.vector,
numCandidates: 200,
limit: 50,
filter: {
mainRole: 'MIDDLE',
queueId: 420,
sampleGameCount: { $gte: 20 },
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
},
},
},
{ $match: { puuid: { $ne: 'target-puuid' } } },
{
$project: {
puuid: 1,
queueId: 1,
mainRole: 1,
sampleGameCount: 1,
championPool: 1,
profile: 1,
updatedAt: 1,
lastMatchAt: 1,
tier: 1,
division: 1,
leaguePoints: 1,
score: { $meta: 'vectorSearchScore' },
},
},
]);
expect(result.profileUpdatedAt).toEqual(
new Date('2026-07-02T00:00:00.000Z'),
);
// 스타일 유사도(0.9)가 컨텍스트(챔피언 풀·최근성)보다 랭킹을 지배한다.
expect(result.matches.map((match) => match.puuid)).toEqual([
'higher-style-similar-player',
'lower-style-better-context',
]);
expect(result.matches[0].finalScore).toBeCloseTo(0.69, 6);
expect(result.matches[1].finalScore).toBeCloseTo(0.67, 6);
expect(result.matches[0].tierComparison).toBe('lower');
expect(result.matches[1].tierComparison).toBe('higher');
expect(result.matches[0].similarMetrics).toEqual([
{
metricId: 'killParticipation',
currentValue: 0.5,
otherValue: 0.52,
absoluteGap: 0.02,
},
{
metricId: 'goldPerMin',
currentValue: 0.5,
otherValue: 0.55,
absoluteGap: 0.05,
},
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.4,
absoluteGap: 0.1,
},
]);
expect(result.matches[0].strongerMetrics).toEqual([
{
metricId: 'csPerMin',
currentValue: 0.5,
otherValue: 0.7,
lead: 0.2,
},
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.4,
lead: 0.1,
},
{
metricId: 'deathsPerMin',
currentValue: 0.7,
otherValue: 0.6,
lead: 0.1,
},
]);
expect(result.matches[0].weakerMetrics).toEqual([]);
expect(result.matches[1].strongerMetrics).toEqual([
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.9,
lead: 0.6,
},
{
metricId: 'deathsPerMin',
currentValue: 0.7,
otherValue: 0.2,
lead: 0.5,
},
{
metricId: 'goldPerMin',
currentValue: 0.5,
otherValue: 0.8,
lead: 0.3,
},
]);
expect(result.matches[1].weakerMetrics).toEqual([
{
metricId: 'killParticipation',
currentValue: 0.5,
otherValue: 0.49,
lead: 0.01,
},
]);
expect(updateOne).toHaveBeenCalledWith(
{
puuid: 'target-puuid',
queueId: 420,
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
},
{
$set: {
puuid: 'target-puuid',
queueId: 420,
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
result: { matches: result.matches },
evidence: {
candidateCount: 2,
vectorSearchIndex: 'player_profile_vector_index',
},
generatedAt: new Date('2026-07-03T00:00:00.000Z'),
},
},
{ upsert: true },
);
});
it('returns a fresh cached similar-player recommendation without running vector search', async () => {
const currentProfile = createProfile();
const cachedMatch = {
puuid: 'cached-similar-player',
similarityScore: 0.87,
finalScore: 0.81,
tier: 'CHALLENGER',
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
similarMetrics: [
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [],
};
const findOne = jest.fn(() => createLeanExec(currentProfile));
const aggregate = jest.fn();
const recommendationFindOne = jest.fn(() =>
createSortedLeanExec({
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
result: { matches: [cachedMatch] },
}),
);
const updateOne = jest.fn();
const service = new SimilarPlayerService({
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'playerProfile'
? { findOne, aggregate }
: { findOne: recommendationFindOne, updateOne },
),
),
} as unknown as ConnectionService);
const result = await service.findSimilarPlayers('target-puuid', 420, 10);
expect(recommendationFindOne).toHaveBeenCalledWith({
puuid: 'target-puuid',
queueId: 420,
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
});
expect(aggregate).not.toHaveBeenCalled();
expect(updateOne).not.toHaveBeenCalled();
expect(result).toEqual({
puuid: 'target-puuid',
queueId: 420,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
matches: [cachedMatch],
});
});
it('throws when the player profile has not been built yet', async () => {
const findOne = jest.fn(() => createLeanExec(null));
const aggregate = jest.fn();
const service = new SimilarPlayerService({
getModel: jest.fn().mockResolvedValue({ findOne, aggregate }),
} as unknown as ConnectionService);
await expect(
service.findSimilarPlayers('missing-puuid', 420),
).rejects.toThrow('Player profile not found.');
expect(aggregate).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,487 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import {
FEATURE_SCHEMA_VERSION,
METRICS,
ROLES,
VECTOR_DIMENSION,
type MetricDefinition,
type Role,
type TierComparison,
} from '@persona-lenz/shared';
import type { PipelineStage } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
ChampionPoolEntry,
LeadMetric,
SimilarMetric,
SimilarPlayer,
SimilarPlayersResult,
} from './analysis.types';
const SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME = 'player_profile_vector_index';
const SIMILAR_PLAYER_VECTOR_SEARCH_NUM_CANDIDATES = 200;
const SIMILAR_PLAYER_VECTOR_SEARCH_LIMIT = 50;
const DEFAULT_SIMILAR_PLAYER_LIMIT = 10;
const MINIMUM_SAMPLE_GAME_COUNT = 20;
const LOW_SAMPLE_GAME_COUNT_THRESHOLD = 30;
const LOW_SAMPLE_PENALTY = 0.1;
const RECENCY_HALF_LIFE_MS = 14 * 24 * 60 * 60 * 1000;
const TIER_ORDER = [
'IRON',
'BRONZE',
'SILVER',
'GOLD',
'PLATINUM',
'EMERALD',
'DIAMOND',
'MASTER',
'GRANDMASTER',
'CHALLENGER',
];
const TIER_COMPARISONS: TierComparison[] = [
'higher',
'same',
'lower',
'unknown',
];
interface PlayerProfileRecord {
puuid: string;
queueId: number;
mainRole: Role;
sampleGameCount: number;
championPool: ChampionPoolEntry[];
profile: Record<string, number>;
vector: number[];
updatedAt: Date;
lastMatchAt?: Date;
tier?: string;
division?: string;
leaguePoints?: number;
}
interface VectorSearchRecord extends Omit<PlayerProfileRecord, 'vector'> {
score?: number;
}
interface RecommendationCacheRecord {
result?: Record<string, unknown>;
}
/**
* 나와 플레이스타일 벡터가 가까운 유저를 찾는다. 목적은 "따라 할 멘토"가 아니라
* "스타일은 비슷한데 왜 점수(티어)가 다른가"라는 인사이트 제공이므로,
* 후보를 티어로 거르지 않고 유사도 중심으로 랭킹한 뒤 티어 관계와
* 지표 우위(양방향)를 함께 반환한다.
*/
@Injectable()
export class SimilarPlayerService {
constructor(private readonly connectionService: ConnectionService) {}
public async findSimilarPlayers(
puuid: string,
queueId: number,
requestedLimit = DEFAULT_SIMILAR_PLAYER_LIMIT,
): Promise<SimilarPlayersResult> {
const playerProfileModel =
await this.connectionService.getModel('playerProfile');
const recommendationModel =
await this.connectionService.getModel('recommendation');
const normalizedLimit = this.normalizeLimit(requestedLimit);
const currentProfile = await playerProfileModel
.findOne({ puuid, queueId, featureSchemaVersion: FEATURE_SCHEMA_VERSION })
.lean<PlayerProfileRecord>()
.exec();
if (!currentProfile) {
throw new NotFoundException('Player profile not found.');
}
const cacheFilter = this.createRecommendationFilter(
puuid,
queueId,
currentProfile.updatedAt,
);
const cachedRecommendation = await recommendationModel
.findOne(cacheFilter)
.sort({ generatedAt: -1 })
.lean<RecommendationCacheRecord>()
.exec();
const cachedMatches = this.extractCachedMatches(cachedRecommendation);
if (cachedMatches) {
return {
puuid,
queueId,
profileUpdatedAt: currentProfile.updatedAt,
matches: cachedMatches.slice(0, normalizedLimit),
};
}
if (currentProfile.vector.length !== VECTOR_DIMENSION) {
return {
puuid,
queueId,
profileUpdatedAt: currentProfile.updatedAt,
matches: [],
};
}
const candidates = await playerProfileModel
.aggregate<VectorSearchRecord>(
this.createCandidatePipeline(currentProfile, puuid, queueId),
)
.exec();
const matches = candidates
.map((candidate) => this.toSimilarPlayer(currentProfile, candidate))
.sort((left, right) => right.finalScore - left.finalScore)
.slice(0, normalizedLimit);
await recommendationModel
.updateOne(
cacheFilter,
{
$set: {
puuid,
queueId,
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: currentProfile.updatedAt,
result: { matches },
evidence: {
candidateCount: candidates.length,
vectorSearchIndex: SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME,
},
generatedAt: new Date(),
},
},
{ upsert: true },
)
.exec();
return {
puuid,
queueId,
profileUpdatedAt: currentProfile.updatedAt,
matches,
};
}
private createRecommendationFilter(
puuid: string,
queueId: number,
profileUpdatedAt: Date,
): {
puuid: string;
queueId: number;
type: 'similar-player';
featureSchemaVersion: number;
profileUpdatedAt: Date;
} {
return {
puuid,
queueId,
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt,
};
}
private createCandidatePipeline(
currentProfile: PlayerProfileRecord,
puuid: string,
queueId: number,
): PipelineStage[] {
return [
{
$vectorSearch: {
index: SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME,
path: 'vector',
queryVector: currentProfile.vector,
numCandidates: SIMILAR_PLAYER_VECTOR_SEARCH_NUM_CANDIDATES,
limit: SIMILAR_PLAYER_VECTOR_SEARCH_LIMIT,
filter: {
mainRole: currentProfile.mainRole,
queueId,
sampleGameCount: { $gte: MINIMUM_SAMPLE_GAME_COUNT },
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
},
},
},
{ $match: { puuid: { $ne: puuid } } },
{
$project: {
puuid: 1,
queueId: 1,
mainRole: 1,
sampleGameCount: 1,
championPool: 1,
profile: 1,
updatedAt: 1,
lastMatchAt: 1,
tier: 1,
division: 1,
leaguePoints: 1,
score: { $meta: 'vectorSearchScore' },
},
},
];
}
private toSimilarPlayer(
currentProfile: PlayerProfileRecord,
candidate: VectorSearchRecord,
): SimilarPlayer {
const similarityScore = this.clamp01(candidate.score ?? 0);
return {
puuid: candidate.puuid,
similarityScore,
finalScore: this.calculateFinalScore(
currentProfile,
candidate,
similarityScore,
),
tier: candidate.tier,
division: candidate.division,
leaguePoints: candidate.leaguePoints,
tierComparison: this.compareTier(currentProfile.tier, candidate.tier),
mainRole: candidate.mainRole,
mainChampions: candidate.championPool.slice(0, 3),
sampleGameCount: candidate.sampleGameCount,
similarMetrics: this.resolveSimilarMetrics(
currentProfile.profile,
candidate.profile,
),
strongerMetrics: this.resolveLeadMetrics(
currentProfile.profile,
candidate.profile,
'other',
),
weakerMetrics: this.resolveLeadMetrics(
currentProfile.profile,
candidate.profile,
'current',
),
};
}
private calculateFinalScore(
currentProfile: PlayerProfileRecord,
candidate: VectorSearchRecord,
similarityScore: number,
): number {
const championPoolSimilarity = this.calculateChampionPoolSimilarity(
currentProfile.championPool,
candidate.championPool,
);
const recencyScore = this.calculateRecencyScore(candidate.lastMatchAt);
const lowSamplePenalty =
candidate.sampleGameCount < LOW_SAMPLE_GAME_COUNT_THRESHOLD
? LOW_SAMPLE_PENALTY
: 0;
// 유사도가 랭킹을 지배해야 한다 — 티어는 랭킹 요소가 아니라 인사이트(tierComparison)로만 쓴다.
return this.clamp01(
0.7 * similarityScore +
0.18 * championPoolSimilarity +
0.12 * recencyScore -
lowSamplePenalty,
);
}
private compareTier(
currentTier: string | undefined,
otherTier: string | undefined,
): TierComparison {
const currentTierRank = TIER_ORDER.indexOf(currentTier ?? '');
const otherTierRank = TIER_ORDER.indexOf(otherTier ?? '');
if (currentTierRank < 0 || otherTierRank < 0) return 'unknown';
if (otherTierRank > currentTierRank) return 'higher';
if (otherTierRank < currentTierRank) return 'lower';
return 'same';
}
private calculateChampionPoolSimilarity(
currentChampionPool: ChampionPoolEntry[],
otherChampionPool: ChampionPoolEntry[],
): number {
const currentChampionIds = new Set(
currentChampionPool.slice(0, 5).map((entry) => entry.championId),
);
const otherChampionIds = new Set(
otherChampionPool.slice(0, 5).map((entry) => entry.championId),
);
const unionChampionIds = new Set([
...currentChampionIds,
...otherChampionIds,
]);
if (unionChampionIds.size === 0) return 0;
let sharedChampionCount = 0;
currentChampionIds.forEach((championId) => {
if (otherChampionIds.has(championId)) sharedChampionCount += 1;
});
return sharedChampionCount / unionChampionIds.size;
}
private calculateRecencyScore(lastMatchAt: Date | undefined): number {
if (!lastMatchAt) return 0;
const ageMs = Date.now() - lastMatchAt.getTime();
if (ageMs <= 0) return 1;
return this.clamp01(Math.pow(0.5, ageMs / RECENCY_HALF_LIFE_MS));
}
private resolveSimilarMetrics(
currentProfile: Record<string, number>,
otherProfile: Record<string, number>,
): SimilarMetric[] {
return METRICS.flatMap((metric) => {
const comparison = this.createMetricValues(
currentProfile,
otherProfile,
metric,
);
if (!comparison) return [];
return {
metricId: metric.id,
currentValue: comparison.currentValue,
otherValue: comparison.otherValue,
absoluteGap: this.roundMetricGap(
Math.abs(comparison.otherValue - comparison.currentValue),
),
};
})
.sort((left, right) => left.absoluteGap - right.absoluteGap)
.slice(0, 3);
}
private resolveLeadMetrics(
currentProfile: Record<string, number>,
otherProfile: Record<string, number>,
leader: 'current' | 'other',
): LeadMetric[] {
return METRICS.flatMap((metric) => {
const comparison = this.createMetricValues(
currentProfile,
otherProfile,
metric,
);
if (!comparison) return [];
const otherAdvantage =
metric.direction === 'lowerIsBetter'
? comparison.currentValue - comparison.otherValue
: comparison.otherValue - comparison.currentValue;
const lead = leader === 'other' ? otherAdvantage : -otherAdvantage;
if (lead <= 0) return [];
return {
metricId: metric.id,
currentValue: comparison.currentValue,
otherValue: comparison.otherValue,
lead: this.roundMetricGap(lead),
};
})
.sort((left, right) => right.lead - left.lead)
.slice(0, 3);
}
private createMetricValues(
currentProfile: Record<string, number>,
otherProfile: Record<string, number>,
metric: MetricDefinition,
): { currentValue: number; otherValue: number } | null {
const currentValue = currentProfile[metric.id];
const otherValue = otherProfile[metric.id];
if (!Number.isFinite(currentValue) || !Number.isFinite(otherValue)) {
return null;
}
return {
currentValue: this.clamp01(currentValue),
otherValue: this.clamp01(otherValue),
};
}
private normalizeLimit(requestedLimit: number): number {
if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
return DEFAULT_SIMILAR_PLAYER_LIMIT;
}
return Math.min(requestedLimit, DEFAULT_SIMILAR_PLAYER_LIMIT);
}
private roundMetricGap(value: number): number {
return Math.round(value * 1_000_000) / 1_000_000;
}
private clamp01(value: number): number {
if (!Number.isFinite(value)) return 0;
return Math.max(0, Math.min(1, value));
}
private extractCachedMatches(
recommendation: RecommendationCacheRecord | null,
): SimilarPlayer[] | null {
const matches = recommendation?.result?.matches;
if (!Array.isArray(matches)) return null;
if (!matches.every((match) => this.isCachedSimilarPlayer(match))) {
return null;
}
return matches;
}
private isCachedSimilarPlayer(value: unknown): value is SimilarPlayer {
const record = this.asRecord(value);
if (!record) return false;
return (
typeof record.puuid === 'string' &&
this.isFiniteNumber(record.similarityScore) &&
this.isFiniteNumber(record.finalScore) &&
typeof record.tierComparison === 'string' &&
TIER_COMPARISONS.includes(record.tierComparison as TierComparison) &&
typeof record.mainRole === 'string' &&
ROLES.includes(record.mainRole as Role) &&
Array.isArray(record.mainChampions) &&
this.isFiniteNumber(record.sampleGameCount) &&
this.isCachedMetricComparisonArray(
record.similarMetrics,
'absoluteGap',
) &&
this.isCachedMetricComparisonArray(record.strongerMetrics, 'lead') &&
this.isCachedMetricComparisonArray(record.weakerMetrics, 'lead')
);
}
private isCachedMetricComparisonArray(
value: unknown,
scoreFieldName: 'absoluteGap' | 'lead',
): boolean {
return (
Array.isArray(value) &&
value.every((entry) => {
const record = this.asRecord(entry);
return (
record !== null &&
typeof record.metricId === 'string' &&
this.isFiniteNumber(record.currentValue) &&
this.isFiniteNumber(record.otherValue) &&
this.isFiniteNumber(record[scoreFieldName])
);
})
);
}
private asRecord(value: unknown): Record<string, unknown> | null {
return typeof value === 'object' && value !== null && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
private isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
}
@@ -0,0 +1,676 @@
import { TimelineDerivedService } from './timeline-derived.service';
function createTimelinePayload(
eventsByFrame: Array<Record<string, unknown>[]>,
) {
return {
info: {
frames: eventsByFrame.map((events, index) => ({
timestamp: index * 60_000,
events,
})),
},
};
}
function createTimelinePayloadWithFrames(
frames: Array<{
timestamp?: number;
events?: Record<string, unknown>[];
participantFrames?: Record<string, unknown>;
}>,
) {
return {
info: {
frames: frames.map((frame, index) => ({
timestamp: frame.timestamp ?? index * 60_000,
events: frame.events ?? [],
participantFrames: frame.participantFrames ?? {},
})),
},
};
}
describe('TimelineDerivedService', () => {
const service = new TimelineDerivedService();
it('clusters champion kills transitively by time and distance', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
assistingParticipantIds: [2],
position: { x: 1_000, y: 1_000 },
victimDamageReceived: [
{
participantId: 3,
magicDamageDone: 100,
physicalDamageDone: 50,
trueDamageDone: 0,
},
{
participantId: 1,
magicDamageDone: 20,
physicalDamageDone: 30,
trueDamageDone: 0,
},
],
},
{
type: 'CHAMPION_KILL',
timestamp: 24_000,
killerId: 2,
victimId: 7,
assistingParticipantIds: null,
victimDamageReceived: null,
position: { x: 3_400, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 38_000,
killerId: 4,
victimId: 8,
assistingParticipantIds: [5],
position: { x: 5_800, y: 1_000 },
},
],
]),
);
expect(derived.fightClusters).toEqual([
{
startTimeMs: 10_000,
endTimeMs: 38_000,
killCount: 3,
participantIds: [1, 2, 3, 4, 5, 6, 7, 8],
openerParticipantIds: [1, 2, 3],
cleanupParticipantIds: [4, 5, 8],
isTeamfight: true,
},
]);
});
it('separates champion kills that are not connected by both time and distance', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
position: { x: 1_000, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 20_000,
killerId: 2,
victimId: 7,
position: { x: 7_000, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 40_000,
killerId: 3,
victimId: 8,
position: { x: 7_500, y: 1_000 },
},
],
]),
);
expect(derived.fightClusters).toHaveLength(3);
expect(derived.fightClusters.map((cluster) => cluster.killCount)).toEqual([
1, 1, 1,
]);
expect(
derived.fightClusters.every((cluster) => cluster.isTeamfight === false),
).toBe(true);
});
it('includes every kill within five seconds of the last kill as cleanup', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
position: { x: 1_000, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 20_000,
killerId: 2,
victimId: 7,
position: { x: 2_000, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 24_000,
killerId: 3,
victimId: 8,
position: { x: 2_500, y: 1_000 },
},
],
]),
);
expect(derived.fightClusters[0].cleanupParticipantIds).toEqual([
2, 3, 7, 8,
]);
});
it('uses explicit victim damage totals without adding component damage twice', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
position: { x: 1_000, y: 1_000 },
victimDamageReceived: [
{
participantId: 3,
totalDamageDone: 100,
magicDamageDone: 1_000,
},
{
participantId: 4,
magicDamageDone: 150,
},
],
},
],
]),
);
expect(derived.fightClusters[0].openerParticipantIds).toEqual([1, 4]);
});
it('aggregates duplicate victim damage rows before selecting the opener contributor', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
position: { x: 1_000, y: 1_000 },
victimDamageReceived: [
{
participantId: 3,
magicDamageDone: 80,
},
{
participantId: 3,
physicalDamageDone: 80,
},
{
participantId: 4,
magicDamageDone: 150,
},
],
},
],
]),
);
expect(derived.fightClusters[0].openerParticipantIds).toEqual([1, 3]);
});
it('builds objective windows around elite monster kill timestamps', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'ELITE_MONSTER_KILL',
timestamp: 900_000,
killerId: 4,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'HEXTECH_DRAGON',
position: { x: 9_800, y: 4_400 },
},
{
type: 'WARD_PLACED',
timestamp: 905_000,
},
],
]),
);
expect(derived.objectiveWindows).toEqual([
{
objectiveTimeMs: 900_000,
startTimeMs: 780_000,
endTimeMs: 930_000,
killerParticipantId: 4,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'HEXTECH_DRAGON',
position: { x: 9_800, y: 4_400 },
},
]);
});
it('ignores elite monster kills outside dragon, rift herald, and baron', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'ELITE_MONSTER_KILL',
timestamp: 900_000,
killerId: 4,
killerTeamId: 100,
monsterType: 'HORDE',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 1_200_000,
killerId: 5,
killerTeamId: 200,
monsterType: 'BARON_NASHOR',
},
],
]),
);
expect(derived.objectiveWindows).toHaveLength(1);
expect(derived.objectiveWindows[0].monsterType).toBe('BARON_NASHOR');
});
it('builds death events with shutdown bounty, zone, and nearest ally approximation', () => {
const derived = service.buildDerivedData(
createTimelinePayloadWithFrames([
{
timestamp: 0,
participantFrames: {
'1': { position: { x: 9_870, y: 4_414 } },
'7': { position: { x: 9_000, y: 4_000 } },
'8': { position: { x: 12_000, y: 4_000 } },
},
},
{
timestamp: 30_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 30_000,
killerId: 1,
victimId: 6,
shutdownBounty: 277,
position: { x: 9_866, y: 4_414 },
},
],
},
{
timestamp: 60_000,
participantFrames: {
'1': { position: { x: 9_870, y: 4_414 } },
'7': { position: { x: 10_000, y: 4_000 } },
'8': { position: { x: 12_000, y: 4_000 } },
},
},
]),
);
expect(derived.deathEvents).toEqual([
{
t: 30_000,
victimParticipantId: 6,
x: 9_866,
y: 4_414,
zone: 'dragonPit',
shutdownBountyGiven: 277,
nearestAllyDistanceApprox: 553,
},
]);
});
it('interpolates missing death positions from victim frames', () => {
const derived = service.buildDerivedData(
createTimelinePayloadWithFrames([
{
timestamp: 0,
participantFrames: {
'1': { position: { x: 4_020, y: 6_000 } },
'6': { position: { x: 3_000, y: 6_000 } },
'7': { position: { x: 8_000, y: 6_000 } },
},
},
{
timestamp: 30_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 30_000,
killerId: 1,
victimId: 6,
},
],
},
{
timestamp: 60_000,
participantFrames: {
'1': { position: { x: 4_020, y: 6_000 } },
'6': { position: { x: 5_000, y: 6_000 } },
'7': { position: { x: 10_000, y: 6_000 } },
},
},
]),
);
expect(derived.deathEvents).toEqual([
{
t: 30_000,
victimParticipantId: 6,
x: 4_000,
y: 6_000,
zone: 'southWestJungle',
shutdownBountyGiven: 0,
nearestAllyDistanceApprox: 5_000,
},
]);
});
it('classifies representative Summoner Rift death zones', () => {
const positions = [
{ x: 600, y: 600, zone: 'blueBase' },
{ x: 14_200, y: 14_200, zone: 'redBase' },
{ x: 1_000, y: 9_000, zone: 'topLane' },
{ x: 6_500, y: 6_500, zone: 'middleLane' },
{ x: 9_000, y: 1_000, zone: 'bottomLane' },
{ x: 8_000, y: 7_000, zone: 'river' },
{ x: 2_500, y: 8_500, zone: 'northWestJungle' },
{ x: 12_000, y: 9_000, zone: 'northEastJungle' },
{ x: 4_000, y: 6_000, zone: 'southWestJungle' },
{ x: 13_000, y: 5_000, zone: 'southEastJungle' },
{ x: 9_866, y: 4_414, zone: 'dragonPit' },
{ x: 5_007, y: 10_471, zone: 'baronPit' },
{ x: -1, y: 7_500, zone: 'unknown' },
];
const derived = service.buildDerivedData(
createTimelinePayload([
positions.map((position, index) => ({
type: 'CHAMPION_KILL',
timestamp: (index + 1) * 1_000,
killerId: 1,
victimId: 6,
position: { x: position.x, y: position.y },
})),
]),
);
expect(derived.deathEvents.map((deathEvent) => deathEvent.zone)).toEqual(
positions.map((position) => position.zone),
);
});
it('builds roam frames for non-jungle laners between 8 and 14 minutes', () => {
const rawMatch = {
info: {
participants: [
{ participantId: 1, teamId: 100, teamPosition: 'TOP' },
{ participantId: 2, teamId: 100, teamPosition: 'JUNGLE' },
{ participantId: 6, teamId: 200, teamPosition: 'MIDDLE' },
],
},
};
const derived = service.buildDerivedData(
createTimelinePayloadWithFrames([
{
timestamp: 7 * 60_000,
participantFrames: {
'1': { position: { x: 8_000, y: 7_000 } },
},
},
{
timestamp: 8 * 60_000,
participantFrames: {
'1': { position: { x: 8_000, y: 7_000 } },
'2': { position: { x: 8_000, y: 7_000 } },
'6': { position: { x: 14_200, y: 14_200 } },
},
},
{
timestamp: 9 * 60_000,
participantFrames: {
'1': { position: { x: 1_000, y: 9_000 } },
'6': { position: { x: 8_000, y: 7_000 } },
},
},
{
timestamp: 14 * 60_000,
participantFrames: {
'1': { position: { x: 9_000, y: 1_000 } },
},
},
{
timestamp: 15 * 60_000,
participantFrames: {
'1': { position: { x: 8_000, y: 7_000 } },
},
},
]),
rawMatch,
);
expect(derived.roamFrames).toEqual([
{
t: 8 * 60_000,
participantId: 1,
teamId: 100,
x: 8_000,
y: 7_000,
zone: 'river',
assignedLaneZone: 'topLane',
},
{
t: 9 * 60_000,
participantId: 6,
teamId: 200,
x: 8_000,
y: 7_000,
zone: 'river',
assignedLaneZone: 'middleLane',
},
{
t: 14 * 60_000,
participantId: 1,
teamId: 100,
x: 9_000,
y: 1_000,
zone: 'bottomLane',
assignedLaneZone: 'topLane',
},
]);
});
it('uses the participant own base only when filtering roam frames', () => {
const rawMatch = {
info: {
participants: [{ participantId: 1, teamId: 100, teamPosition: 'TOP' }],
},
};
const derived = service.buildDerivedData(
createTimelinePayloadWithFrames([
{
timestamp: 8 * 60_000,
participantFrames: {
'1': { position: { x: 600, y: 600 } },
},
},
{
timestamp: 9 * 60_000,
participantFrames: {
'1': { position: { x: 14_200, y: 14_200 } },
},
},
]),
rawMatch,
);
expect(derived.roamFrames).toEqual([
{
t: 9 * 60_000,
participantId: 1,
teamId: 100,
x: 14_200,
y: 14_200,
zone: 'redBase',
assignedLaneZone: 'topLane',
},
]);
});
it('omits roam frames when participant id or map zone is unknown', () => {
const rawMatch = {
info: {
participants: [
{ teamId: 100, teamPosition: 'TOP' },
{ participantId: 2, teamId: 100, teamPosition: 'MIDDLE' },
],
},
};
const derived = service.buildDerivedData(
createTimelinePayloadWithFrames([
{
timestamp: 8 * 60_000,
participantFrames: {
'1': { position: { x: 8_000, y: 7_000 } },
'2': { position: { x: -1, y: 7_500 } },
},
},
]),
rawMatch,
);
expect(derived.roamFrames).toEqual([]);
});
it('builds weighted advantage events for kills, plates, towers, and objectives', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
assistingParticipantIds: [2],
victimDamageReceived: [{ participantId: 3, magicDamageDone: 80 }],
},
{
type: 'TURRET_PLATE_DESTROYED',
timestamp: 20_000,
killerId: 0,
teamId: 200,
},
{
type: 'BUILDING_KILL',
timestamp: 30_000,
killerId: 2,
assistingParticipantIds: [3, 4],
buildingType: 'TOWER_BUILDING',
teamId: 200,
towerType: 'OUTER_TURRET',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 40_000,
killerId: 3,
killerTeamId: 100,
monsterType: 'RIFTHERALD',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 50_000,
killerId: 8,
killerTeamId: 200,
monsterType: 'BARON_NASHOR',
},
],
]),
);
expect(derived.advantageEvents).toEqual([
{
timestampMs: 10_000,
teamId: 100,
type: 'championKill',
score: 1,
participantIds: [1, 2, 3],
},
{
timestampMs: 20_000,
teamId: 100,
type: 'turretPlate',
score: 0.5,
participantIds: [],
},
{
timestampMs: 30_000,
teamId: 100,
type: 'tower',
score: 1.5,
participantIds: [2, 3, 4],
},
{
timestampMs: 40_000,
teamId: 100,
type: 'riftHerald',
score: 1.5,
participantIds: [3],
},
{
timestampMs: 50_000,
teamId: 200,
type: 'baron',
score: 3,
participantIds: [8],
},
]);
});
it('omits advantage events when the scoring team cannot be inferred', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 0,
victimId: 6,
},
{
type: 'TURRET_PLATE_DESTROYED',
timestamp: 20_000,
killerId: 0,
},
{
type: 'BUILDING_KILL',
timestamp: 30_000,
buildingType: 'TOWER_BUILDING',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 40_000,
killerId: 0,
monsterType: 'DRAGON',
},
],
]),
);
expect(derived.advantageEvents).toEqual([]);
});
});
@@ -0,0 +1,957 @@
import {
ADVANTAGE_EVENT_WEIGHTS,
SUMMONERS_RIFT_MAP,
type AdvantageEventType,
type SummonersRiftMapZone,
} from '@persona-lenz/shared';
import { Injectable } from '@nestjs/common';
interface TimelinePosition {
x: number;
y: number;
}
interface TimelineChampionKillEvent {
timestamp: number;
killerId?: number;
victimId?: number;
shutdownBounty?: number;
assistingParticipantIds: number[];
position?: TimelinePosition;
victimDamageReceived: Array<{
participantId: number;
damage: number;
}>;
}
interface TimelineEliteMonsterKillEvent {
timestamp: number;
killerParticipantId?: number;
killerTeamId?: number;
monsterType?: string;
monsterSubType?: string;
position?: TimelinePosition;
}
interface TimelineFrameSnapshot {
timestamp: number;
participantPositions: Map<number, TimelinePosition>;
}
interface TimelineRoamParticipant {
participantId: number;
teamId: 100 | 200;
assignedLaneZone: SummonersRiftMapZone;
baseZone: SummonersRiftMapZone;
}
export interface TimelineFightCluster {
startTimeMs: number;
endTimeMs: number;
killCount: number;
participantIds: number[];
openerParticipantIds: number[];
cleanupParticipantIds: number[];
isTeamfight: boolean;
}
export interface TimelineObjectiveWindow {
objectiveTimeMs: number;
startTimeMs: number;
endTimeMs: number;
killerParticipantId?: number;
killerTeamId?: number;
monsterType?: string;
monsterSubType?: string;
position?: TimelinePosition;
}
export interface TimelineAdvantageEvent {
timestampMs: number;
teamId: number;
type: AdvantageEventType;
score: number;
participantIds: number[];
}
export interface TimelineDeathEvent {
t: number;
victimParticipantId: number;
x: number;
y: number;
zone: SummonersRiftMapZone;
shutdownBountyGiven: number;
nearestAllyDistanceApprox: number | null;
}
export interface TimelineRoamFrame {
t: number;
participantId: number;
teamId: number;
x: number;
y: number;
zone: SummonersRiftMapZone;
assignedLaneZone: SummonersRiftMapZone;
}
export interface TimelineDerivedData {
fightClusters: TimelineFightCluster[];
advantageEvents: TimelineAdvantageEvent[];
deathEvents: TimelineDeathEvent[];
objectiveWindows: TimelineObjectiveWindow[];
roamFrames: TimelineRoamFrame[];
}
const FIGHT_CLUSTER_MAX_GAP_MS = 15_000;
const FIGHT_CLUSTER_MAX_DISTANCE = 3_000;
const CLEANUP_WINDOW_MS = 5_000;
const OBJECTIVE_WINDOW_BEFORE_MS = 120_000;
const OBJECTIVE_WINDOW_AFTER_MS = 30_000;
const ROAM_FRAME_START_MS = 8 * 60_000;
const ROAM_FRAME_END_MS = 14 * 60_000;
const OBJECTIVE_MONSTER_TYPES = new Set([
'DRAGON',
'RIFTHERALD',
'BARON_NASHOR',
]);
function asRecord(value: unknown): Record<string, unknown> {
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
function asArray(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
function asNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
function asString(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined;
}
function asParticipantId(value: unknown): number | undefined {
const participantId = asNumber(value);
return participantId !== undefined && participantId > 0
? participantId
: undefined;
}
function toSortedIds(values: Iterable<number>): number[] {
return [...new Set(values)].sort((left, right) => left - right);
}
function parsePosition(value: unknown): TimelinePosition | undefined {
const position = asRecord(value);
const x = asNumber(position.x);
const y = asNumber(position.y);
if (x === undefined || y === undefined) {
return undefined;
}
return { x, y };
}
function distance(
left: TimelinePosition | undefined,
right: TimelinePosition | undefined,
): number {
if (!left || !right) {
return Number.POSITIVE_INFINITY;
}
return Math.hypot(left.x - right.x, left.y - right.y);
}
function isWithinRadius(
position: TimelinePosition,
center: TimelinePosition,
radius: number,
): boolean {
return distance(position, center) <= radius;
}
function classifySummonersRiftPosition(
position: TimelinePosition | undefined,
): SummonersRiftMapZone {
if (!position) {
return 'unknown';
}
const {
baronPit,
baseRadius,
coordinateMax,
coordinateMin,
dragonPit,
jungleMidline,
laneAxisHalfWidth,
objectivePitRadius,
riverBandHalfWidth,
} = SUMMONERS_RIFT_MAP;
const { x, y } = position;
if (
x < coordinateMin ||
y < coordinateMin ||
x > coordinateMax ||
y > coordinateMax
) {
return 'unknown';
}
if (isWithinRadius(position, dragonPit, objectivePitRadius)) {
return 'dragonPit';
}
if (isWithinRadius(position, baronPit, objectivePitRadius)) {
return 'baronPit';
}
if (x <= baseRadius && y <= baseRadius) {
return 'blueBase';
}
if (x >= coordinateMax - baseRadius && y >= coordinateMax - baseRadius) {
return 'redBase';
}
if (Math.abs(x + y - coordinateMax) <= riverBandHalfWidth) {
return 'river';
}
if (x <= laneAxisHalfWidth || y >= coordinateMax - laneAxisHalfWidth) {
return 'topLane';
}
if (Math.abs(x - y) <= laneAxisHalfWidth) {
return 'middleLane';
}
if (y <= laneAxisHalfWidth || x >= coordinateMax - laneAxisHalfWidth) {
return 'bottomLane';
}
if (x < jungleMidline && y >= jungleMidline) {
return 'northWestJungle';
}
if (x >= jungleMidline && y >= jungleMidline) {
return 'northEastJungle';
}
if (x < jungleMidline && y < jungleMidline) {
return 'southWestJungle';
}
if (x >= jungleMidline && y < jungleMidline) {
return 'southEastJungle';
}
return 'unknown';
}
function isConnectedKill(
left: TimelineChampionKillEvent,
right: TimelineChampionKillEvent,
): boolean {
return (
Math.abs(left.timestamp - right.timestamp) <= FIGHT_CLUSTER_MAX_GAP_MS &&
distance(left.position, right.position) <= FIGHT_CLUSTER_MAX_DISTANCE
);
}
function eventParticipantIds(event: TimelineChampionKillEvent): number[] {
return toSortedIds(
[
event.killerId,
event.victimId,
...event.assistingParticipantIds,
...event.victimDamageReceived.map((damage) => damage.participantId),
].filter((id): id is number => id !== undefined),
);
}
function eventOpenerParticipantIds(event: TimelineChampionKillEvent): number[] {
const damageByParticipantId = new Map<number, number>();
for (const damage of event.victimDamageReceived) {
damageByParticipantId.set(
damage.participantId,
(damageByParticipantId.get(damage.participantId) ?? 0) + damage.damage,
);
}
const highestDamageContributor = [...damageByParticipantId.entries()].reduce<
{ participantId: number; damage: number } | undefined
>((selected, [participantId, damage]) => {
if (!selected || damage > selected.damage) {
return { participantId, damage };
}
return selected;
}, undefined);
return toSortedIds(
[
event.killerId,
...event.assistingParticipantIds,
highestDamageContributor?.participantId,
].filter((id): id is number => id !== undefined),
);
}
function isObjectiveMonsterType(monsterType: string | undefined): boolean {
return monsterType !== undefined && OBJECTIVE_MONSTER_TYPES.has(monsterType);
}
function objectiveAdvantageEventType(
monsterType: string | undefined,
): AdvantageEventType | undefined {
switch (monsterType) {
case 'DRAGON':
return 'dragon';
case 'RIFTHERALD':
return 'riftHerald';
case 'BARON_NASHOR':
return 'baron';
default:
return undefined;
}
}
function teamIdFromParticipantId(
participantId: number | undefined,
): 100 | 200 | undefined {
if (participantId === undefined) {
return undefined;
}
if (participantId >= 1 && participantId <= 5) {
return 100;
}
if (participantId >= 6 && participantId <= 10) {
return 200;
}
return undefined;
}
function toTeamId(value: unknown): 100 | 200 | undefined {
const teamId = asNumber(value);
return teamId === 100 || teamId === 200 ? teamId : undefined;
}
function opposingTeamId(teamId: 100 | 200 | undefined): 100 | 200 | undefined {
if (teamId === 100) {
return 200;
}
if (teamId === 200) {
return 100;
}
return undefined;
}
function assignedLaneZoneForRole(
teamPosition: string | undefined,
): SummonersRiftMapZone | undefined {
switch (teamPosition) {
case 'TOP':
return 'topLane';
case 'MIDDLE':
return 'middleLane';
case 'BOTTOM':
case 'UTILITY':
return 'bottomLane';
default:
return undefined;
}
}
function baseZoneForTeamId(
teamId: 100 | 200 | undefined,
): SummonersRiftMapZone | undefined {
switch (teamId) {
case 100:
return 'blueBase';
case 200:
return 'redBase';
default:
return undefined;
}
}
function parseRoamParticipants(
rawMatch: Record<string, unknown> | undefined,
): TimelineRoamParticipant[] {
const info = asRecord(rawMatch?.info);
return asArray(info.participants)
.map(asRecord)
.flatMap((participant) => {
const participantId = asParticipantId(participant.participantId);
const teamId = toTeamId(participant.teamId);
const assignedLaneZone = assignedLaneZoneForRole(
asString(participant.teamPosition),
);
const baseZone = baseZoneForTeamId(teamId);
if (
participantId === undefined ||
teamId === undefined ||
assignedLaneZone === undefined ||
baseZone === undefined
) {
return [];
}
return [
{
participantId,
teamId,
assignedLaneZone,
baseZone,
},
];
});
}
function scoringParticipantIds(event: TimelineChampionKillEvent): number[] {
return toSortedIds(
[
event.killerId,
...event.assistingParticipantIds,
...event.victimDamageReceived.map((damage) => damage.participantId),
].filter((id): id is number => id !== undefined),
);
}
function parseAssistingParticipantIds(value: unknown): number[] {
return toSortedIds(
asArray(value).flatMap((item) => {
const participantId = asParticipantId(item);
return participantId === undefined ? [] : [participantId];
}),
);
}
function parseVictimDamageReceived(
value: unknown,
): TimelineChampionKillEvent['victimDamageReceived'] {
return asArray(value).flatMap((item) => {
const damageRecord = asRecord(item);
const participantId = asParticipantId(damageRecord.participantId);
if (participantId === undefined) {
return [];
}
const explicitDamage =
asNumber(damageRecord.totalDamageDone) ?? asNumber(damageRecord.damage);
const componentDamage =
(asNumber(damageRecord.magicDamageDone) ?? 0) +
(asNumber(damageRecord.physicalDamageDone) ?? 0) +
(asNumber(damageRecord.trueDamageDone) ?? 0);
return [
{
participantId,
damage: explicitDamage ?? componentDamage,
},
];
});
}
function parseChampionKillEvent(
event: Record<string, unknown>,
): TimelineChampionKillEvent | undefined {
const timestamp = asNumber(event.timestamp);
if (timestamp === undefined) {
return undefined;
}
return {
timestamp,
killerId: asParticipantId(event.killerId),
victimId: asParticipantId(event.victimId),
shutdownBounty: asNumber(event.shutdownBounty),
assistingParticipantIds: parseAssistingParticipantIds(
event.assistingParticipantIds,
),
position: parsePosition(event.position),
victimDamageReceived: parseVictimDamageReceived(event.victimDamageReceived),
};
}
function parseTimelineFrame(
frame: Record<string, unknown>,
): TimelineFrameSnapshot | undefined {
const timestamp = asNumber(frame.timestamp);
if (timestamp === undefined) {
return undefined;
}
const participantFrames = asRecord(frame.participantFrames);
const participantPositions = new Map<number, TimelinePosition>();
for (const [participantIdValue, participantFrameValue] of Object.entries(
participantFrames,
)) {
const participantId = asParticipantId(Number(participantIdValue));
const participantFrame = asRecord(participantFrameValue);
const position = parsePosition(participantFrame.position);
if (participantId !== undefined && position) {
participantPositions.set(participantId, position);
}
}
return {
timestamp,
participantPositions,
};
}
function parseEliteMonsterKillEvent(
event: Record<string, unknown>,
): TimelineEliteMonsterKillEvent | undefined {
const timestamp = asNumber(event.timestamp);
if (timestamp === undefined) {
return undefined;
}
return {
timestamp,
killerParticipantId: asParticipantId(event.killerId),
killerTeamId: asNumber(event.killerTeamId),
monsterType: asString(event.monsterType),
monsterSubType: asString(event.monsterSubType),
position: parsePosition(event.position),
};
}
function structureParticipantIds(event: Record<string, unknown>): number[] {
return toSortedIds(
[
asParticipantId(event.killerId),
...parseAssistingParticipantIds(event.assistingParticipantIds),
].filter((id): id is number => id !== undefined),
);
}
function createStructureAdvantageEvent(
event: Record<string, unknown>,
type: AdvantageEventType,
): TimelineAdvantageEvent | undefined {
const timestamp = asNumber(event.timestamp);
const participantIds = structureParticipantIds(event);
const teamId =
teamIdFromParticipantId(participantIds[0]) ??
opposingTeamId(toTeamId(event.teamId));
if (timestamp === undefined || !teamId) {
return undefined;
}
return {
timestampMs: timestamp,
teamId,
type,
score: ADVANTAGE_EVENT_WEIGHTS[type],
participantIds,
};
}
function createChampionKillAdvantageEvent(
event: TimelineChampionKillEvent,
): TimelineAdvantageEvent | undefined {
const teamId = teamIdFromParticipantId(event.killerId);
if (event.killerId === undefined || !teamId) {
return undefined;
}
return {
timestampMs: event.timestamp,
teamId,
type: 'championKill',
score: ADVANTAGE_EVENT_WEIGHTS.championKill,
participantIds: scoringParticipantIds(event),
};
}
function createEliteMonsterAdvantageEvent(
event: TimelineEliteMonsterKillEvent,
): TimelineAdvantageEvent | undefined {
const type = objectiveAdvantageEventType(event.monsterType);
if (!type) {
return undefined;
}
const teamId =
toTeamId(event.killerTeamId) ??
teamIdFromParticipantId(event.killerParticipantId);
if (!teamId) {
return undefined;
}
return {
timestampMs: event.timestamp,
teamId,
type,
score: ADVANTAGE_EVENT_WEIGHTS[type],
participantIds:
event.killerParticipantId === undefined
? []
: [event.killerParticipantId],
};
}
function createBuildingAdvantageEvent(
event: Record<string, unknown>,
): TimelineAdvantageEvent | undefined {
const buildingType = asString(event.buildingType);
const towerType = asString(event.towerType);
if (buildingType !== 'TOWER_BUILDING' && towerType === undefined) {
return undefined;
}
return createStructureAdvantageEvent(event, 'tower');
}
function extractTimelineEvents(timeline: Record<string, unknown>) {
const info = asRecord(timeline.info);
const frames = asArray(info.frames).map(asRecord);
const championKills: TimelineChampionKillEvent[] = [];
const eliteMonsterKills: TimelineEliteMonsterKillEvent[] = [];
const advantageEvents: TimelineAdvantageEvent[] = [];
const frameSnapshots: TimelineFrameSnapshot[] = [];
for (const frame of frames) {
const frameSnapshot = parseTimelineFrame(frame);
if (frameSnapshot) {
frameSnapshots.push(frameSnapshot);
}
for (const rawEvent of asArray(frame.events)) {
const event = asRecord(rawEvent);
switch (asString(event.type)) {
case 'CHAMPION_KILL': {
const championKill = parseChampionKillEvent(event);
if (championKill) {
championKills.push(championKill);
const advantageEvent =
createChampionKillAdvantageEvent(championKill);
if (advantageEvent) {
advantageEvents.push(advantageEvent);
}
}
break;
}
case 'ELITE_MONSTER_KILL': {
const eliteMonsterKill = parseEliteMonsterKillEvent(event);
if (eliteMonsterKill) {
eliteMonsterKills.push(eliteMonsterKill);
const advantageEvent =
createEliteMonsterAdvantageEvent(eliteMonsterKill);
if (advantageEvent) {
advantageEvents.push(advantageEvent);
}
}
break;
}
case 'TURRET_PLATE_DESTROYED': {
const advantageEvent = createStructureAdvantageEvent(
event,
'turretPlate',
);
if (advantageEvent) {
advantageEvents.push(advantageEvent);
}
break;
}
case 'BUILDING_KILL': {
const advantageEvent = createBuildingAdvantageEvent(event);
if (advantageEvent) {
advantageEvents.push(advantageEvent);
}
break;
}
}
}
}
return {
championKills: championKills.sort(
(left, right) => left.timestamp - right.timestamp,
),
eliteMonsterKills: eliteMonsterKills.sort(
(left, right) => left.timestamp - right.timestamp,
),
advantageEvents: advantageEvents.sort(
(left, right) => left.timestampMs - right.timestampMs,
),
frameSnapshots: frameSnapshots.sort(
(left, right) => left.timestamp - right.timestamp,
),
};
}
function findRoot(parents: number[], index: number): number {
let root = index;
while (parents[root] !== root) {
root = parents[root];
}
while (parents[index] !== index) {
const parent = parents[index];
parents[index] = root;
index = parent;
}
return root;
}
function union(parents: number[], left: number, right: number): void {
const leftRoot = findRoot(parents, left);
const rightRoot = findRoot(parents, right);
if (leftRoot !== rightRoot) {
parents[rightRoot] = leftRoot;
}
}
function buildFightClusters(
kills: TimelineChampionKillEvent[],
): TimelineFightCluster[] {
const parents = kills.map((_, index) => index);
for (let leftIndex = 0; leftIndex < kills.length; leftIndex += 1) {
for (
let rightIndex = leftIndex + 1;
rightIndex < kills.length;
rightIndex += 1
) {
if (isConnectedKill(kills[leftIndex], kills[rightIndex])) {
union(parents, leftIndex, rightIndex);
}
}
}
const clusterGroups = new Map<number, TimelineChampionKillEvent[]>();
for (const [index, kill] of kills.entries()) {
const root = findRoot(parents, index);
clusterGroups.set(root, [...(clusterGroups.get(root) ?? []), kill]);
}
return [...clusterGroups.values()]
.map((clusterKills) => {
const sortedKills = [...clusterKills].sort(
(left, right) => left.timestamp - right.timestamp,
);
const firstKill = sortedKills[0];
const lastKill = sortedKills[sortedKills.length - 1];
const cleanupStartTimeMs = lastKill.timestamp - CLEANUP_WINDOW_MS;
const cleanupEndTimeMs = lastKill.timestamp + CLEANUP_WINDOW_MS;
const cleanupParticipantIds = sortedKills
.filter(
(kill) =>
kill.timestamp >= cleanupStartTimeMs &&
kill.timestamp <= cleanupEndTimeMs,
)
.flatMap(eventParticipantIds);
return {
startTimeMs: firstKill.timestamp,
endTimeMs: lastKill.timestamp,
killCount: sortedKills.length,
participantIds: toSortedIds(sortedKills.flatMap(eventParticipantIds)),
openerParticipantIds: eventOpenerParticipantIds(firstKill),
cleanupParticipantIds: toSortedIds(cleanupParticipantIds),
isTeamfight: sortedKills.length >= 3,
};
})
.sort((left, right) => left.startTimeMs - right.startTimeMs);
}
function buildObjectiveWindows(
eliteMonsterKills: TimelineEliteMonsterKillEvent[],
): TimelineObjectiveWindow[] {
return eliteMonsterKills
.filter((event) => isObjectiveMonsterType(event.monsterType))
.map((event) => ({
objectiveTimeMs: event.timestamp,
startTimeMs: event.timestamp - OBJECTIVE_WINDOW_BEFORE_MS,
endTimeMs: event.timestamp + OBJECTIVE_WINDOW_AFTER_MS,
...(event.killerParticipantId !== undefined
? { killerParticipantId: event.killerParticipantId }
: {}),
...(event.killerTeamId !== undefined
? { killerTeamId: event.killerTeamId }
: {}),
...(event.monsterType ? { monsterType: event.monsterType } : {}),
...(event.monsterSubType ? { monsterSubType: event.monsterSubType } : {}),
...(event.position ? { position: event.position } : {}),
}));
}
function interpolatePosition(
frameSnapshots: TimelineFrameSnapshot[],
participantId: number,
timestampMs: number,
): TimelinePosition | undefined {
let previous: { timestamp: number; position: TimelinePosition } | undefined;
let next: { timestamp: number; position: TimelinePosition } | undefined;
for (const frame of frameSnapshots) {
const position = frame.participantPositions.get(participantId);
if (!position) {
continue;
}
if (frame.timestamp <= timestampMs) {
previous = { timestamp: frame.timestamp, position };
}
if (frame.timestamp >= timestampMs) {
next = { timestamp: frame.timestamp, position };
break;
}
}
if (previous && next) {
if (previous.timestamp === next.timestamp) {
return previous.position;
}
const ratio =
(timestampMs - previous.timestamp) /
(next.timestamp - previous.timestamp);
return {
x: previous.position.x + (next.position.x - previous.position.x) * ratio,
y: previous.position.y + (next.position.y - previous.position.y) * ratio,
};
}
return previous?.position ?? next?.position;
}
function nearestAllyDistanceApprox(
frameSnapshots: TimelineFrameSnapshot[],
victimParticipantId: number,
deathPosition: TimelinePosition,
timestampMs: number,
): number | null {
const victimTeamId = teamIdFromParticipantId(victimParticipantId);
if (!victimTeamId) {
return null;
}
let nearestDistance = Number.POSITIVE_INFINITY;
for (let participantId = 1; participantId <= 10; participantId += 1) {
if (
participantId === victimParticipantId ||
teamIdFromParticipantId(participantId) !== victimTeamId
) {
continue;
}
const allyPosition = interpolatePosition(
frameSnapshots,
participantId,
timestampMs,
);
if (!allyPosition) {
continue;
}
nearestDistance = Math.min(
nearestDistance,
distance(deathPosition, allyPosition),
);
}
return Number.isFinite(nearestDistance) ? Math.round(nearestDistance) : null;
}
function buildDeathEvents(
championKills: TimelineChampionKillEvent[],
frameSnapshots: TimelineFrameSnapshot[],
): TimelineDeathEvent[] {
return championKills.flatMap((event) => {
if (event.victimId === undefined) {
return [];
}
const position =
event.position ??
interpolatePosition(frameSnapshots, event.victimId, event.timestamp);
if (!position) {
return [];
}
return [
{
t: event.timestamp,
victimParticipantId: event.victimId,
x: position.x,
y: position.y,
zone: classifySummonersRiftPosition(position),
shutdownBountyGiven: event.shutdownBounty ?? 0,
nearestAllyDistanceApprox: nearestAllyDistanceApprox(
frameSnapshots,
event.victimId,
position,
event.timestamp,
),
},
];
});
}
function buildRoamFrames(
frameSnapshots: TimelineFrameSnapshot[],
rawMatch: Record<string, unknown> | undefined,
): TimelineRoamFrame[] {
const roamParticipants = parseRoamParticipants(rawMatch);
if (roamParticipants.length === 0) {
return [];
}
return frameSnapshots.flatMap((frame) => {
if (
frame.timestamp < ROAM_FRAME_START_MS ||
frame.timestamp > ROAM_FRAME_END_MS
) {
return [];
}
return roamParticipants.flatMap((participant) => {
const position = frame.participantPositions.get(
participant.participantId,
);
if (!position) {
return [];
}
const zone = classifySummonersRiftPosition(position);
if (
zone === 'unknown' ||
zone === participant.assignedLaneZone ||
zone === participant.baseZone
) {
return [];
}
return [
{
t: frame.timestamp,
participantId: participant.participantId,
teamId: participant.teamId,
x: position.x,
y: position.y,
zone,
assignedLaneZone: participant.assignedLaneZone,
},
];
});
});
}
@Injectable()
export class TimelineDerivedService {
public buildDerivedData(
timeline: Record<string, unknown>,
rawMatch?: Record<string, unknown>,
): TimelineDerivedData {
const {
advantageEvents,
championKills,
eliteMonsterKills,
frameSnapshots,
} = extractTimelineEvents(timeline);
return {
fightClusters: buildFightClusters(championKills),
advantageEvents,
deathEvents: buildDeathEvents(championKills, frameSnapshots),
objectiveWindows: buildObjectiveWindows(eliteMonsterKills),
roamFrames: buildRoamFrames(frameSnapshots, rawMatch),
};
}
}
@@ -0,0 +1,718 @@
import { VECTOR_METRICS } from '@persona-lenz/shared';
import type { ExtractedPlayerMatchFeature } from './analysis.types';
import { TimelineMetricService } from './timeline-metric.service';
function createBaseFeature(): ExtractedPlayerMatchFeature {
return {
matchId: 'KR_1',
puuid: 'target-puuid',
queueId: 420,
role: 'MIDDLE',
championId: 103,
gameCreation: 1_700_000_000_000,
gameDurationSec: 1_800,
win: true,
patch: '26.13',
features: {
kda: 3,
},
normalized: {
kda: 0.5,
},
vector: [],
featureSchemaVersion: 2,
normalizationMethod: 'registry-baseline',
confidence: 1,
timelineProcessed: false,
laneOpponent: {
puuid: 'enemy-mid-puuid',
championId: 134,
},
};
}
function createRawMatch() {
return {
metadata: {
matchId: 'KR_1',
},
info: {
participants: [
{
participantId: 1,
puuid: 'target-puuid',
teamId: 100,
teamPosition: 'MIDDLE',
},
{
participantId: 2,
puuid: 'ally-jungle-puuid',
teamId: 100,
teamPosition: 'JUNGLE',
},
{
participantId: 3,
puuid: 'ally-top-puuid',
teamId: 100,
teamPosition: 'TOP',
},
{
participantId: 6,
puuid: 'enemy-mid-puuid',
teamId: 200,
teamPosition: 'MIDDLE',
},
{
participantId: 7,
puuid: 'enemy-jungle-puuid',
teamId: 200,
teamPosition: 'JUNGLE',
},
],
},
};
}
function participantFrame(overrides: Record<string, unknown>) {
return {
jungleMinionsKilled: 0,
minionsKilled: 0,
position: { x: 0, y: 0 },
timeEnemySpentControlled: 0,
totalGold: 0,
xp: 0,
...overrides,
};
}
function createTimeline() {
return {
info: {
frames: [
{
timestamp: 8 * 60_000,
events: [],
participantFrames: {
'1': participantFrame({ position: { x: 4_000, y: 4_000 } }),
'2': participantFrame({ position: { x: 5_000, y: 4_000 } }),
'3': participantFrame({ position: { x: 10_000, y: 4_000 } }),
},
},
{
timestamp: 10 * 60_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 100_000,
killerId: 1,
victimId: 6,
assistingParticipantIds: [2],
},
{
type: 'CHAMPION_KILL',
timestamp: 200_000,
killerId: 2,
victimId: 7,
assistingParticipantIds: [1],
},
{
type: 'CHAMPION_KILL',
timestamp: 300_000,
killerId: 2,
victimId: 7,
assistingParticipantIds: null,
victimDamageReceived: [{ participantId: 1 }],
},
{
type: 'CHAMPION_KILL',
timestamp: 400_000,
killerId: 6,
victimId: 1,
assistingParticipantIds: [],
},
{
type: 'WARD_PLACED',
timestamp: 500_000,
creatorId: 1,
},
],
participantFrames: {
'1': participantFrame({
jungleMinionsKilled: 5,
minionsKilled: 75,
position: { x: 4_000, y: 4_000 },
timeEnemySpentControlled: 10_000,
totalGold: 4_000,
xp: 5_000,
}),
'2': participantFrame({ position: { x: 4_800, y: 4_000 } }),
'3': participantFrame({ position: { x: 9_000, y: 4_000 } }),
'6': participantFrame({
jungleMinionsKilled: 0,
minionsKilled: 70,
totalGold: 3_500,
xp: 4_500,
}),
},
},
{
timestamp: 14 * 60_000,
events: [
{
type: 'WARD_PLACED',
timestamp: 830_000,
creatorId: 1,
},
],
participantFrames: {
'1': participantFrame({
position: { x: 4_000, y: 4_000 },
timeEnemySpentControlled: 30_000,
totalGold: 6_000,
}),
'2': participantFrame({ position: { x: 5_500, y: 4_000 } }),
'3': participantFrame({ position: { x: 11_000, y: 4_000 } }),
'6': participantFrame({
totalGold: 6_200,
}),
},
},
{
timestamp: 15 * 60_000,
events: [
{
type: 'WARD_PLACED',
timestamp: 850_000,
creatorId: 1,
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 900_000,
killerId: 2,
killerTeamId: 100,
monsterType: 'DRAGON',
assistingParticipantIds: [1],
},
],
participantFrames: {},
},
{
timestamp: 20 * 60_000,
events: [],
participantFrames: {
'1': participantFrame({
position: { x: 4_000, y: 4_000 },
timeEnemySpentControlled: 60_000,
}),
'2': participantFrame({ position: { x: 7_000, y: 4_000 } }),
'3': participantFrame({ position: { x: 12_000, y: 4_000 } }),
},
},
{
timestamp: 30 * 60_000,
events: [],
participantFrames: {
'1': participantFrame({
timeEnemySpentControlled: 90_000,
}),
},
},
],
},
};
}
function createInsightTimeline() {
return {
info: {
frames: [
{
timestamp: 10 * 60_000,
events: [
{
actualStartTime: 640_000,
type: 'OBJECTIVE_BOUNTY_PRESTART',
timestamp: 590_000,
teamId: 100,
},
],
participantFrames: {
'1': participantFrame({
minionsKilled: 80,
position: { x: 7_500, y: 7_500 },
totalGold: 4_000,
xp: 5_000,
}),
'6': participantFrame({
minionsKilled: 72,
totalGold: 3_400,
xp: 4_700,
}),
},
},
{
timestamp: 11 * 60_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 650_000,
killerId: 1,
victimId: 6,
shutdownBounty: 450,
assistingParticipantIds: [],
},
],
participantFrames: {
'1': participantFrame({ position: { x: 7_800, y: 9_000 } }),
},
},
{
timestamp: 12 * 60_000,
events: [
{
type: 'TURRET_PLATE_DESTROYED',
timestamp: 700_000,
teamId: 200,
laneType: 'MID_LANE',
},
{
type: 'OBJECTIVE_BOUNTY_FINISH',
timestamp: 700_000,
teamId: 100,
},
],
participantFrames: {
'1': participantFrame({ position: { x: 7_800, y: 7_800 } }),
},
},
{
timestamp: 800_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 800_000,
killerId: 1,
victimId: 7,
assistingParticipantIds: [],
},
],
participantFrames: {
'1': participantFrame({ position: { x: 9_866, y: 4_414 } }),
},
},
{
timestamp: 14 * 60_000,
events: [],
participantFrames: {
'1': participantFrame({
position: { x: 9_866, y: 4_414 },
totalGold: 5_800,
}),
'2': participantFrame({ position: { x: 8_800, y: 4_600 } }),
'3': participantFrame({ position: { x: 1_000, y: 13_000 } }),
'6': participantFrame({ totalGold: 5_500 }),
},
},
{
timestamp: 15 * 60_000,
events: [
{
type: 'ELITE_MONSTER_KILL',
timestamp: 900_000,
killerId: 2,
killerTeamId: 100,
monsterType: 'DRAGON',
assistingParticipantIds: [1],
position: { x: 9_866, y: 4_414 },
},
],
participantFrames: {
'1': participantFrame({ position: { x: 9_866, y: 4_414 } }),
},
},
{
timestamp: 20 * 60_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 1_030_000,
killerId: 6,
victimId: 1,
assistingParticipantIds: [],
},
{
type: 'CHAMPION_KILL',
timestamp: 1_215_000,
killerId: 2,
victimId: 7,
assistingParticipantIds: [],
},
],
participantFrames: {
'1': participantFrame({
position: { x: 7_500, y: 7_500 },
totalGold: 8_000,
}),
'6': participantFrame({ totalGold: 7_700 }),
},
},
],
},
};
}
function createDeficitRecoveryTimeline() {
return {
info: {
frames: [
{
timestamp: 10 * 60_000,
events: [],
participantFrames: {
'1': participantFrame({
minionsKilled: 65,
totalGold: 3_200,
xp: 4_200,
}),
'6': participantFrame({
minionsKilled: 75,
totalGold: 3_900,
xp: 4_600,
}),
},
},
{
timestamp: 20 * 60_000,
events: [],
participantFrames: {
'1': participantFrame({ totalGold: 7_500 }),
'6': participantFrame({ totalGold: 7_300 }),
},
},
],
},
};
}
describe('TimelineMetricService', () => {
const service = new TimelineMetricService();
it('extracts timeline vector metrics and ratio counts', () => {
const feature = createBaseFeature();
const result = service.extractTimelineMetrics(
feature,
createRawMatch(),
createTimeline(),
{
advantageEvents: [],
deathEvents: [
{
t: 400_000,
victimParticipantId: 1,
x: 4_000,
y: 4_000,
zone: 'middleLane',
shutdownBountyGiven: 300,
nearestAllyDistanceApprox: 1_500,
},
{
t: 1_000_000,
victimParticipantId: 1,
x: 4_000,
y: 4_000,
zone: 'middleLane',
shutdownBountyGiven: 0,
nearestAllyDistanceApprox: 1_500,
},
],
fightClusters: [
{
startTimeMs: 100_000,
endTimeMs: 130_000,
killCount: 3,
participantIds: [1, 2, 6, 7],
openerParticipantIds: [1],
cleanupParticipantIds: [2],
isTeamfight: true,
},
{
startTimeMs: 600_000,
endTimeMs: 640_000,
killCount: 3,
participantIds: [1, 2, 6, 7],
openerParticipantIds: [2],
cleanupParticipantIds: [1],
isTeamfight: true,
},
],
objectiveWindows: [
{
objectiveTimeMs: 900_000,
startTimeMs: 780_000,
endTimeMs: 930_000,
killerParticipantId: 2,
killerTeamId: 100,
monsterType: 'DRAGON',
},
],
roamFrames: [],
},
);
expect(result.features).toMatchObject({
goldDiffAt10: 500,
goldDiffAt14: -200,
csDiffAt10: 10,
xpDiffAt10: 500,
deathsBefore14: 1,
killParticipationBefore14: 1,
earlyWardsPerMin: 2 / 14,
objectivePreWardRateNumerator: 1,
objectivePreWardRateDenominator: 1,
eliteObjectiveParticipationRateNumerator: 1,
eliteObjectiveParticipationRateDenominator: 1,
teamfightFirstEngagementParticipationRateNumerator: 1,
teamfightFirstEngagementParticipationRateDenominator: 2,
teamfightCleanupKillParticipationRateNumerator: 1,
teamfightCleanupKillParticipationRateDenominator: 2,
deathWithShutdownBountyGivenRateNumerator: 1,
deathWithShutdownBountyGivenRateDenominator: 2,
ccTimePerMinute: 3,
});
expect(result.features.isolationTendency).toBeCloseTo(
(1_000 + 800 + 1_500 + 3_000) / 4,
);
expect(result.normalized.objectivePreWardRate).toBe(1);
expect(result.normalized.eliteObjectiveParticipationRate).toBe(1);
expect(result.normalized.teamfightFirstEngagementParticipationRate).toBe(
0.5,
);
expect(result.vector).toHaveLength(VECTOR_METRICS.length);
expect(
result.vector[
VECTOR_METRICS.findIndex((metric) => metric.id === 'goldDiffAt10')
],
).toBeCloseTo(result.normalized.goldDiffAt10);
expect(
result.vector[
VECTOR_METRICS.findIndex(
(metric) => metric.id === 'objectivePreWardRate',
)
],
).toBe(1);
expect(
result.vector[
VECTOR_METRICS.findIndex(
(metric) => metric.id === 'deathWithShutdownBountyGivenRate',
)
],
).toBe(0.5);
expect(result.vector[VECTOR_METRICS.length - 1]).toBe(
result.normalized.ccTimePerMinute,
);
});
it('extracts timeline insight metrics outside the vector', () => {
const feature = createBaseFeature();
const result = service.extractTimelineMetrics(
feature,
createRawMatch(),
createInsightTimeline(),
{
advantageEvents: [
{
timestampMs: 600_000,
teamId: 100,
type: 'championKill',
score: 1,
participantIds: [1],
},
{
timestampMs: 650_000,
teamId: 100,
type: 'championKill',
score: 1,
participantIds: [1],
},
{
timestampMs: 1_030_000,
teamId: 200,
type: 'championKill',
score: 1,
participantIds: [6],
},
{
timestampMs: 1_215_000,
teamId: 100,
type: 'championKill',
score: 1,
participantIds: [2],
},
],
deathEvents: [
{
t: 1_000_000,
victimParticipantId: 1,
x: 7_500,
y: 7_500,
zone: 'middleLane',
shutdownBountyGiven: 0,
nearestAllyDistanceApprox: 5_000,
},
{
t: 1_200_000,
victimParticipantId: 1,
x: 7_500,
y: 7_500,
zone: 'middleLane',
shutdownBountyGiven: 0,
nearestAllyDistanceApprox: 1_000,
},
],
fightClusters: [
{
startTimeMs: 850_000,
endTimeMs: 870_000,
killCount: 2,
participantIds: [1, 2, 6, 7],
openerParticipantIds: [1],
cleanupParticipantIds: [2],
isTeamfight: false,
},
],
objectiveWindows: [
{
objectiveTimeMs: 900_000,
startTimeMs: 780_000,
endTimeMs: 930_000,
killerParticipantId: 2,
killerTeamId: 100,
monsterType: 'DRAGON',
position: { x: 9_866, y: 4_414 },
},
],
roamFrames: [
{
t: 600_000,
participantId: 1,
teamId: 100,
x: 7_500,
y: 7_500,
zone: 'river',
assignedLaneZone: 'middleLane',
},
{
t: 660_000,
participantId: 1,
teamId: 100,
x: 8_000,
y: 7_000,
zone: 'river',
assignedLaneZone: 'middleLane',
},
],
},
);
expect(result.features).toMatchObject({
objectiveFightOpeningParticipationRateNumerator: 1,
objectiveFightOpeningParticipationRateDenominator: 1,
objectiveFightOpeningConvertedToObjectiveRateNumerator: 1,
objectiveFightOpeningConvertedToObjectiveRateDenominator: 1,
preObjectivePitPresenceRateNumerator: 1,
preObjectivePitPresenceRateDenominator: 1,
preObjectivePickParticipationRateNumerator: 1,
preObjectivePickParticipationRateDenominator: 1,
deathFollowedByTeamLossRateNumerator: 1,
deathFollowedByTeamLossRateDenominator: 2,
deathTradedForTeamAdvantageRateNumerator: 1,
deathTradedForTeamAdvantageRateDenominator: 2,
deathWhileIsolatedFromNearestAllyRateNumerator: 1,
deathWhileIsolatedFromNearestAllyRateDenominator: 2,
laneLeadConversionRateNumerator: 1,
laneLeadConversionRateDenominator: 1,
roamConvertedToTeamAdvantageRateNumerator: 1,
roamConvertedToTeamAdvantageRateDenominator: 1,
shutdownGoldCollectedPerGame: 450,
platePresenceParticipationRateNumerator: 1,
platePresenceParticipationRateDenominator: 1,
objectiveBountyComebackParticipationRateNumerator: 1,
objectiveBountyComebackParticipationRateDenominator: 1,
});
expect(result.normalized.objectiveFightOpeningParticipationRate).toBe(1);
expect(result.normalized.deathFollowedByTeamLossRate).toBe(0.5);
expect(result.normalized.deathTradedForTeamAdvantageRate).toBe(0.5);
expect(result.normalized.deathWhileIsolatedFromNearestAllyRate).toBe(0.5);
expect(result.vector).toHaveLength(VECTOR_METRICS.length);
expect(
VECTOR_METRICS.some(
(metric) => metric.id === 'shutdownGoldCollectedPerGame',
),
).toBe(false);
});
it('extracts early deficit recovery as a sparse ratio metric', () => {
const feature = createBaseFeature();
const result = service.extractTimelineMetrics(
feature,
createRawMatch(),
createDeficitRecoveryTimeline(),
{
advantageEvents: [],
deathEvents: [],
fightClusters: [],
objectiveWindows: [],
roamFrames: [],
},
);
expect(result.features).toMatchObject({
goldDiffAt10: -700,
earlyDeficitRecoveryRateNumerator: 1,
earlyDeficitRecoveryRateDenominator: 1,
laneLeadConversionRateNumerator: 0,
laneLeadConversionRateDenominator: 0,
});
expect(result.normalized.earlyDeficitRecoveryRate).toBe(1);
});
it('does not count the death kill event as a follow-up team loss', () => {
const feature = createBaseFeature();
const result = service.extractTimelineMetrics(
feature,
createRawMatch(),
createTimeline(),
{
advantageEvents: [
{
timestampMs: 400_000,
teamId: 200,
type: 'championKill',
score: 1,
participantIds: [6],
},
],
deathEvents: [
{
t: 400_000,
victimParticipantId: 1,
x: 4_000,
y: 4_000,
zone: 'middleLane',
shutdownBountyGiven: 0,
nearestAllyDistanceApprox: 1_500,
},
],
fightClusters: [],
objectiveWindows: [],
roamFrames: [],
},
);
expect(result.features).toMatchObject({
deathFollowedByTeamLossRateNumerator: 0,
deathFollowedByTeamLossRateDenominator: 1,
});
expect(result.normalized.deathFollowedByTeamLossRate).toBe(0);
});
});
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,10 @@
import {
ConnectionService,
resolveMongoAppName,
resolveMongoConnectionOptions,
resolveMongoDbName,
} from './connection.service';
import { modelDefinitions } from './schemas';
describe('resolveMongoDbName', () => {
it('uses production database only for prod', () => {
@@ -17,6 +19,57 @@ describe('resolveMongoDbName', () => {
});
});
describe('ConnectionService.ensureCollections', () => {
function createConnectionService() {
return new ConnectionService({
get: jest.fn(),
ready: jest.fn(),
} as never);
}
it('creates every registered collection that does not exist yet', async () => {
const connectionService = createConnectionService();
const hasNext = jest.fn().mockResolvedValue(false);
const listCollections = jest.fn(() => ({ hasNext }));
const createCollection = jest.fn().mockResolvedValue(undefined);
const getModel = jest.fn().mockResolvedValue({ createCollection });
connectionService.getConnection = jest.fn().mockResolvedValue({
db: { listCollections },
});
connectionService.getModel = getModel;
await connectionService.ensureCollections();
expect(listCollections).toHaveBeenCalledTimes(modelDefinitions.length);
expect(listCollections).toHaveBeenCalledWith(
{ name: 'account' },
{ nameOnly: true },
);
expect(getModel).toHaveBeenCalledTimes(modelDefinitions.length);
expect(createCollection).toHaveBeenCalledTimes(modelDefinitions.length);
});
it('skips collections that already exist', async () => {
const connectionService = createConnectionService();
const hasNext = jest.fn().mockResolvedValue(true);
const listCollections = jest.fn(() => ({ hasNext }));
const createCollection = jest.fn().mockResolvedValue(undefined);
const getModel = jest.fn().mockResolvedValue({ createCollection });
connectionService.getConnection = jest.fn().mockResolvedValue({
db: { listCollections },
});
connectionService.getModel = getModel;
await connectionService.ensureCollections();
expect(listCollections).toHaveBeenCalledTimes(modelDefinitions.length);
expect(getModel).not.toHaveBeenCalled();
expect(createCollection).not.toHaveBeenCalled();
});
});
describe('resolveMongoAppName', () => {
it('identifies api environment and process for MongoDB connection tracking', () => {
expect(resolveMongoAppName('staging', 1234)).toBe(
@@ -118,9 +118,32 @@ export class ConnectionService implements OnModuleInit {
}
}
public async ensureCollections(): Promise<void> {
const connection = await this.getConnection();
let createdCollectionCount = 0;
for (const modelDefinition of modelDefinitions) {
const collectionExists = await this.collectionExists(
connection,
modelDefinition.collectionName,
);
if (collectionExists) continue;
const model = await this.getModel(
modelDefinition.name as keyof ModelTypes,
);
await model.createCollection();
createdCollectionCount += 1;
}
this.logger.log(
`MongoDB collections ensured. registered=${modelDefinitions.length} created=${createdCollectionCount}`,
);
}
public async onModuleInit() {
await this.getConnection().catch((error: unknown) => {
this.logError('Failed to initialize MongoDB connection', error);
await this.ensureCollections().catch((error: unknown) => {
this.logError('Failed to initialize MongoDB collections', error);
});
}
@@ -134,4 +157,18 @@ export class ConnectionService implements OnModuleInit {
error instanceof Error ? error.stack : undefined,
);
}
private async collectionExists(
connection: mongoose.Connection,
collectionName: string,
): Promise<boolean> {
const database = connection.db;
if (!database) {
throw new Error('MongoDB database handle is unavailable.');
}
return database
.listCollections({ name: collectionName }, { nameOnly: true })
.hasNext();
}
}
@@ -107,7 +107,7 @@ export const PlayerProfileSchema = new Schema<PlayerProfile>(
);
PlayerProfileSchema.index({ puuid: 1, queueId: 1 }, { unique: true });
// 운영 조회용 (멘토 검색 자체는 Atlas Vector Search 인덱스 사용)
// 운영 조회용 (유사 유저 검색 자체는 Atlas Vector Search 인덱스 사용)
PlayerProfileSchema.index({ isSeed: 1, mainRole: 1, tier: 1 });
export type PlayerProfileDocument = HydratedDocument<PlayerProfile>;
@@ -2,14 +2,14 @@ import { HydratedDocument, Schema } from 'mongoose';
import { MongooseTimestamps } from './common';
/**
* - mentor-match: 유사 고티어 유저 Top-K (MVP 3)
* - similar-player: 플레이스타일이 비슷한 유저 Top-K (MVP 3)
* - champion-recommendation: Fit/Growth/Stretch 챔피언 추천 (MVP 4)
* - llm-feedback: LLM 생성 피드백 (MVP 5)
*/
export type RecommendationType =
'mentor-match' | 'champion-recommendation' | 'llm-feedback';
'similar-player' | 'champion-recommendation' | 'llm-feedback';
export const RECOMMENDATION_TYPES: RecommendationType[] = [
'mentor-match',
'similar-player',
'champion-recommendation',
'llm-feedback',
];
+3 -2
View File
@@ -1,11 +1,12 @@
import { Module, Global } from '@nestjs/common';
import { DatabaseModule } from './database/database.module';
import { RedisModule } from './redis/redis.module';
import { SecretModule } from './secret/secret.module';
@Global()
@Module({
imports: [SecretModule, DatabaseModule],
imports: [SecretModule, DatabaseModule, RedisModule],
providers: [],
exports: [SecretModule, DatabaseModule],
exports: [SecretModule, DatabaseModule, RedisModule],
})
export class GlobalModule {}
@@ -0,0 +1,386 @@
import { SecretService } from '../global/secret/secret.service';
import {
RiotApiClient,
RiotApiKeyError,
RiotApiTimeoutError,
type RiotApiClientOptions,
RiotNotFoundError,
} from './riot-api.client';
import { RiotRateLimiter } from './riot-rate-limiter';
type FetchMock = jest.Mock<ReturnType<typeof fetch>, Parameters<typeof fetch>>;
type SleepMock = jest.Mock<Promise<void>, [number]>;
function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
return new Response(JSON.stringify(body), {
headers: { 'content-type': 'application/json' },
status: 200,
...init,
});
}
function createFetchMock(): FetchMock {
return jest.fn<ReturnType<typeof fetch>, Parameters<typeof fetch>>();
}
function createClient(
fetchMock: FetchMock,
options?: {
clientOptions?: Partial<RiotApiClientOptions>;
sleep?: SleepMock;
},
) {
const getSecret = jest
.fn<Promise<string>, [string]>()
.mockResolvedValue('RGAPI-test-key');
const waitForSlot = jest
.fn<Promise<void>, [string]>()
.mockResolvedValue(undefined);
const sleep =
options?.sleep ??
jest.fn<Promise<void>, [number]>().mockResolvedValue(undefined);
const secretService = {
get: getSecret,
} as unknown as SecretService;
const rateLimiter = {
waitForSlot,
} as unknown as RiotRateLimiter;
const clientOptions: RiotApiClientOptions = {
fetchFn: fetchMock,
sleep,
...options?.clientOptions,
};
const client = new RiotApiClient(secretService, rateLimiter, clientOptions);
return { client, getSecret, sleep, waitForSlot };
}
describe('RiotApiClient', () => {
it('fetches account data through the regional Riot ID endpoint with an API key header', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({
puuid: 'puuid-1',
gameName: 'Hide on bush',
tagLine: 'KR1',
}),
);
const { client, getSecret, waitForSlot } = createClient(fetchMock);
await expect(
client.getAccountByRiotId('Hide on bush', 'KR1', 'asia'),
).resolves.toEqual({
puuid: 'puuid-1',
gameName: 'Hide on bush',
tagLine: 'KR1',
});
expect(getSecret).toHaveBeenCalledWith('RIOT_API_KEY');
expect(waitForSlot).toHaveBeenCalledWith('asia');
const [requestUrl, requestInit] = fetchMock.mock.calls[0];
expect(requestUrl).toBe(
'https://asia.api.riotgames.com/riot/account/v1/accounts/by-riot-id/Hide%20on%20bush/KR1',
);
expect(requestInit?.headers).toEqual(
expect.objectContaining({
'X-Riot-Token': 'RGAPI-test-key',
}),
);
});
it('fetches account data through the regional PUUID endpoint', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({
puuid: 'puuid/1',
gameName: 'Seed Player',
tagLine: 'KR1',
}),
);
const { client, waitForSlot } = createClient(fetchMock);
await expect(client.getAccountByPuuid('puuid/1', 'asia')).resolves.toEqual({
puuid: 'puuid/1',
gameName: 'Seed Player',
tagLine: 'KR1',
});
expect(waitForSlot).toHaveBeenCalledWith('asia');
expect(fetchMock).toHaveBeenCalledWith(
'https://asia.api.riotgames.com/riot/account/v1/accounts/by-puuid/puuid%2F1',
expect.any(Object),
);
});
it('fetches platform and regional League endpoints with encoded parameters and query filters', async () => {
const fetchMock = createFetchMock()
.mockResolvedValueOnce(
jsonResponse({
profileIconId: 7,
puuid: 'puuid/1',
summonerLevel: 30,
}),
)
.mockResolvedValueOnce(jsonResponse(['KR_1', 'KR_2']));
const { client } = createClient(fetchMock);
await client.getSummonerByPuuid('puuid/1', 'kr');
await expect(
client.getMatchIds('puuid/1', {
regionalRoute: 'asia',
queue: 420,
start: 0,
count: 20,
}),
).resolves.toEqual(['KR_1', 'KR_2']);
expect(fetchMock).toHaveBeenNthCalledWith(
1,
'https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-puuid/puuid%2F1',
expect.any(Object),
);
expect(fetchMock).toHaveBeenNthCalledWith(
2,
'https://asia.api.riotgames.com/lol/match/v5/matches/by-puuid/puuid%2F1/ids?queue=420&start=0&count=20',
expect.any(Object),
);
});
it('accepts current Summoner-V4 by-puuid responses', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({
profileIconId: 7,
puuid: 'puuid-1',
revisionDate: 1_783_056_144_000,
summonerLevel: 30,
}),
);
const { client } = createClient(fetchMock);
await expect(client.getSummonerByPuuid('puuid-1', 'kr')).resolves.toEqual({
profileIconId: 7,
puuid: 'puuid-1',
revisionDate: 1_783_056_144_000,
summonerLevel: 30,
});
});
it('accepts current League-V4 by-puuid entries without league ids', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse([
{
queueType: 'RANKED_SOLO_5x5',
tier: 'DIAMOND',
rank: 'IV',
puuid: 'puuid-1',
leaguePoints: 0,
wins: 164,
losses: 152,
veteran: false,
inactive: false,
freshBlood: false,
hotStreak: false,
},
]),
);
const { client } = createClient(fetchMock);
await expect(
client.getLeagueEntriesByPuuid('puuid-1', 'kr'),
).resolves.toEqual([
{
queueType: 'RANKED_SOLO_5x5',
tier: 'DIAMOND',
rank: 'IV',
leaguePoints: 0,
wins: 164,
losses: 152,
veteran: false,
inactive: false,
freshBlood: false,
hotStreak: false,
},
]);
});
it('fetches apex League-V4 lists by queue without legacy summoner ids', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({
tier: 'CHALLENGER',
queue: 'RANKED_SOLO_5x5',
entries: [
{
puuid: 'seed-puuid-1',
leaguePoints: 1200,
rank: 'I',
wins: 300,
losses: 210,
veteran: true,
inactive: false,
freshBlood: false,
hotStreak: true,
},
],
}),
);
const { client, waitForSlot } = createClient(fetchMock);
await expect(
client.getChallengerLeagueByQueue('RANKED_SOLO_5x5', 'kr'),
).resolves.toEqual({
tier: 'CHALLENGER',
queueType: 'RANKED_SOLO_5x5',
entries: [
{
puuid: 'seed-puuid-1',
tier: 'CHALLENGER',
queueType: 'RANKED_SOLO_5x5',
rank: 'I',
leaguePoints: 1200,
wins: 300,
losses: 210,
veteran: true,
inactive: false,
freshBlood: false,
hotStreak: true,
},
],
});
expect(waitForSlot).toHaveBeenCalledWith('kr');
expect(fetchMock).toHaveBeenCalledWith(
'https://kr.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5',
expect.any(Object),
);
});
it('rejects apex League-V4 list entries without puuid', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({
tier: 'MASTER',
queue: 'RANKED_SOLO_5x5',
entries: [
{
leaguePoints: 200,
rank: 'I',
wins: 120,
losses: 100,
},
],
}),
);
const { client } = createClient(fetchMock);
await expect(
client.getMasterLeagueByQueue('RANKED_SOLO_5x5', 'kr'),
).rejects.toThrow(
'Riot apex league entry response was missing string field "puuid".',
);
});
it('honors Retry-After for 429 responses and retries', async () => {
const sleep = jest
.fn<Promise<void>, [number]>()
.mockResolvedValue(undefined);
const fetchMock = createFetchMock()
.mockResolvedValueOnce(
jsonResponse(
{ status: { message: 'rate limited' } },
{
status: 429,
headers: { 'retry-after': '2' },
},
),
)
.mockResolvedValueOnce(jsonResponse(['KR_1']));
const { client } = createClient(fetchMock, { sleep });
await expect(client.getMatchIds('puuid-1')).resolves.toEqual(['KR_1']);
expect(sleep).toHaveBeenCalledWith(2000);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('caps oversized Retry-After waits before retrying', async () => {
const sleep = jest
.fn<Promise<void>, [number]>()
.mockResolvedValue(undefined);
const fetchMock = createFetchMock()
.mockResolvedValueOnce(
jsonResponse(
{ status: { message: 'rate limited' } },
{
status: 429,
headers: { 'retry-after': '9999' },
},
),
)
.mockResolvedValueOnce(jsonResponse(['KR_1']));
const { client } = createClient(fetchMock, { sleep });
await expect(client.getMatchIds('puuid-1')).resolves.toEqual(['KR_1']);
expect(sleep).toHaveBeenCalledWith(30_000);
});
it('fails 401 and 403 responses without retrying or leaking the API key', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({ status: { message: 'Forbidden' } }, { status: 403 }),
);
const { client } = createClient(fetchMock);
await expect(client.getMatch('KR_1')).rejects.toThrow(RiotApiKeyError);
await expect(client.getMatch('KR_1')).rejects.not.toThrow('RGAPI-test-key');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('maps 404 responses to a domain not-found error', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({ status: { message: 'not found' } }, { status: 404 }),
);
const { client } = createClient(fetchMock);
await expect(client.getAccountByRiotId('Missing', 'KR1')).rejects.toThrow(
RiotNotFoundError,
);
});
it('aborts a stalled Riot request with a domain timeout error', async () => {
const fetchMock: FetchMock = jest.fn(
(_input: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
reject(new DOMException('aborted', 'AbortError'));
});
}),
);
const { client } = createClient(fetchMock, {
clientOptions: { requestTimeoutMs: 1 },
});
await expect(client.getMatch('KR_1')).rejects.toThrow(RiotApiTimeoutError);
});
it('validates minimal match and timeline response invariants', async () => {
const fetchMock = createFetchMock()
.mockResolvedValueOnce(jsonResponse({ metadata: {}, info: {} }))
.mockResolvedValueOnce(jsonResponse({ metadata: {}, info: {} }));
const { client } = createClient(fetchMock);
await expect(client.getMatch('KR_1')).resolves.toEqual({
metadata: {},
info: {},
});
await expect(client.getMatchTimeline('KR_1')).resolves.toEqual({
metadata: {},
info: {},
});
});
it('rejects malformed match payloads before analytics can consume them', async () => {
const fetchMock = createFetchMock().mockResolvedValue(jsonResponse({}));
const { client } = createClient(fetchMock);
await expect(client.getMatch('KR_1')).rejects.toThrow(
'Riot match response was missing object field "metadata".',
);
});
});
@@ -0,0 +1,548 @@
import { Inject, Injectable, Optional } from '@nestjs/common';
import { SecretService } from '../global/secret/secret.service';
import {
RIOT_PLATFORM_ROUTES,
RIOT_REGIONAL_ROUTES,
type RiotPlatformRoute,
type RiotRegionalRoute,
} from './riot.types';
import { RiotRateLimiter } from './riot-rate-limiter';
export const RIOT_API_CLIENT_OPTIONS = Symbol('RIOT_API_CLIENT_OPTIONS');
type FetchFunction = typeof fetch;
export interface RiotApiClientOptions {
baseBackoffMs?: number;
maxRetryAfterMs?: number;
fetchFn?: FetchFunction;
requestTimeoutMs?: number;
maxRetries?: number;
sleep?: (durationMs: number) => Promise<void>;
}
export interface RiotAccountDto {
puuid: string;
gameName: string;
tagLine: string;
}
export interface RiotSummonerDto {
profileIconId: number;
puuid: string;
revisionDate?: number;
summonerLevel: number;
}
export interface RiotLeagueEntryDto {
freshBlood: boolean;
hotStreak: boolean;
inactive: boolean;
leaguePoints: number;
losses: number;
queueType: string;
rank: string;
tier: string;
veteran: boolean;
wins: number;
}
export interface RiotApexLeagueEntryDto extends RiotLeagueEntryDto {
puuid: string;
}
export interface RiotApexLeagueListDto {
entries: RiotApexLeagueEntryDto[];
queueType: string;
tier: string;
}
export interface RiotMatchIdsParams {
count?: number;
queue?: number;
regionalRoute?: RiotRegionalRoute;
start?: number;
}
export class RiotApiError extends Error {
constructor(
message: string,
public readonly statusCode?: number,
public readonly code = 'RIOT_API_ERROR',
) {
super(message);
this.name = new.target.name;
}
}
export class RiotApiKeyError extends RiotApiError {
constructor(statusCode: number) {
super(
'Riot API key is missing, expired, or invalid. Regenerate the key in the Riot Developer Portal and update Infisical RIOT_API_KEY.',
statusCode,
'RIOT_API_KEY_INVALID',
);
}
}
export class RiotNotFoundError extends RiotApiError {
constructor(statusCode: number) {
super('Riot API resource was not found.', statusCode, 'RIOT_NOT_FOUND');
}
}
export class RiotApiTimeoutError extends RiotApiError {
constructor() {
super('Riot API request timed out.', undefined, 'RIOT_API_TIMEOUT');
}
}
const DEFAULT_MAX_RETRIES = 3;
const DEFAULT_BASE_BACKOFF_MS = 250;
const DEFAULT_MAX_RETRY_AFTER_MS = 30_000;
const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
function defaultSleep(durationMs: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, durationMs));
}
function assertAllowedRoute(
route: RiotPlatformRoute | RiotRegionalRoute,
): void {
if (
!RIOT_PLATFORM_ROUTES.includes(route as RiotPlatformRoute) &&
!RIOT_REGIONAL_ROUTES.includes(route as RiotRegionalRoute)
) {
throw new RiotApiError('Unsupported Riot routing value.');
}
}
function regionalBaseUrl(regionalRoute: RiotRegionalRoute): string {
assertAllowedRoute(regionalRoute);
return `https://${regionalRoute}.api.riotgames.com`;
}
function platformBaseUrl(platformRoute: RiotPlatformRoute): string {
assertAllowedRoute(platformRoute);
return `https://${platformRoute}.api.riotgames.com`;
}
function encodePathValue(value: string): string {
return encodeURIComponent(value);
}
export function parseRetryAfterMs(
retryAfter: string | null,
now = Date.now(),
): number | undefined {
const trimmed = retryAfter?.trim();
if (!trimmed) return undefined;
const retryAfterSeconds = Number(trimmed);
if (Number.isFinite(retryAfterSeconds)) {
return Math.max(0, retryAfterSeconds * 1000);
}
const retryAt = Date.parse(trimmed);
if (Number.isNaN(retryAt)) return undefined;
return Math.max(0, retryAt - now);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function requireRecord(value: unknown, endpointName: string) {
if (!isRecord(value)) {
throw new RiotApiError(
`Riot ${endpointName} response had an unexpected shape.`,
);
}
return value;
}
function requireRecordField(
record: Record<string, unknown>,
key: string,
endpointName: string,
): Record<string, unknown> {
const value = record[key];
if (!isRecord(value)) {
throw new RiotApiError(
`Riot ${endpointName} response was missing object field "${key}".`,
);
}
return value;
}
function requireString(
record: Record<string, unknown>,
key: string,
endpointName: string,
): string {
const value = record[key];
if (typeof value !== 'string') {
throw new RiotApiError(
`Riot ${endpointName} response was missing string field "${key}".`,
);
}
return value;
}
function numberOrFallback(
record: Record<string, unknown>,
key: string,
fallback: number,
): number {
const value = record[key];
return typeof value === 'number' ? value : fallback;
}
function optionalNumber(
record: Record<string, unknown>,
key: string,
): number | undefined {
const value = record[key];
return typeof value === 'number' ? value : undefined;
}
function optionalBoolean(
record: Record<string, unknown>,
key: string,
fallback: boolean,
) {
const value = record[key];
return typeof value === 'boolean' ? value : fallback;
}
@Injectable()
export class RiotApiClient {
private readonly baseBackoffMs: number;
private readonly fetchFn: FetchFunction;
private readonly maxRetryAfterMs: number;
private readonly maxRetries: number;
private readonly requestTimeoutMs: number;
private readonly sleep: (durationMs: number) => Promise<void>;
constructor(
private readonly secretService: SecretService,
private readonly rateLimiter: RiotRateLimiter,
@Optional()
@Inject(RIOT_API_CLIENT_OPTIONS)
options: RiotApiClientOptions = {},
) {
this.baseBackoffMs = options.baseBackoffMs ?? DEFAULT_BASE_BACKOFF_MS;
this.fetchFn = options.fetchFn ?? fetch;
this.maxRetryAfterMs =
options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
this.requestTimeoutMs =
options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
this.sleep = options.sleep ?? defaultSleep;
}
public async getAccountByRiotId(
gameName: string,
tagLine: string,
regionalRoute: RiotRegionalRoute = 'asia',
): Promise<RiotAccountDto> {
const response = await this.requestJson(
regionalRoute,
`${regionalBaseUrl(regionalRoute)}/riot/account/v1/accounts/by-riot-id/${encodePathValue(gameName)}/${encodePathValue(tagLine)}`,
);
return this.parseAccount(response);
}
public async getAccountByPuuid(
puuid: string,
regionalRoute: RiotRegionalRoute = 'asia',
): Promise<RiotAccountDto> {
const response = await this.requestJson(
regionalRoute,
`${regionalBaseUrl(regionalRoute)}/riot/account/v1/accounts/by-puuid/${encodePathValue(puuid)}`,
);
return this.parseAccount(response);
}
public async getSummonerByPuuid(
puuid: string,
platformRoute: RiotPlatformRoute = 'kr',
): Promise<RiotSummonerDto> {
const response = await this.requestJson(
platformRoute,
`${platformBaseUrl(platformRoute)}/lol/summoner/v4/summoners/by-puuid/${encodePathValue(puuid)}`,
);
return this.parseSummoner(response);
}
public async getLeagueEntriesByPuuid(
puuid: string,
platformRoute: RiotPlatformRoute = 'kr',
): Promise<RiotLeagueEntryDto[]> {
const response = await this.requestJson(
platformRoute,
`${platformBaseUrl(platformRoute)}/lol/league/v4/entries/by-puuid/${encodePathValue(puuid)}`,
);
return this.parseLeagueEntries(response);
}
public async getChallengerLeagueByQueue(
queueType = 'RANKED_SOLO_5x5',
platformRoute: RiotPlatformRoute = 'kr',
): Promise<RiotApexLeagueListDto> {
return this.getApexLeagueByQueue(
'challengerleagues',
queueType,
platformRoute,
);
}
public async getGrandmasterLeagueByQueue(
queueType = 'RANKED_SOLO_5x5',
platformRoute: RiotPlatformRoute = 'kr',
): Promise<RiotApexLeagueListDto> {
return this.getApexLeagueByQueue(
'grandmasterleagues',
queueType,
platformRoute,
);
}
public async getMasterLeagueByQueue(
queueType = 'RANKED_SOLO_5x5',
platformRoute: RiotPlatformRoute = 'kr',
): Promise<RiotApexLeagueListDto> {
return this.getApexLeagueByQueue('masterleagues', queueType, platformRoute);
}
public async getMatchIds(
puuid: string,
params: RiotMatchIdsParams = {},
): Promise<string[]> {
const regionalRoute = params.regionalRoute ?? 'asia';
const searchParams = new URLSearchParams();
if (params.queue !== undefined)
searchParams.set('queue', String(params.queue));
if (params.start !== undefined)
searchParams.set('start', String(params.start));
if (params.count !== undefined)
searchParams.set('count', String(params.count));
const query = searchParams.size > 0 ? `?${searchParams.toString()}` : '';
const response = await this.requestJson(
regionalRoute,
`${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/by-puuid/${encodePathValue(puuid)}/ids${query}`,
);
return this.parseMatchIds(response);
}
public async getMatch(
matchId: string,
regionalRoute: RiotRegionalRoute = 'asia',
): Promise<Record<string, unknown>> {
const response = await this.requestJson(
regionalRoute,
`${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/${encodePathValue(matchId)}`,
);
return this.parseMatchPayload(response, 'match');
}
public async getMatchTimeline(
matchId: string,
regionalRoute: RiotRegionalRoute = 'asia',
): Promise<Record<string, unknown>> {
const response = await this.requestJson(
regionalRoute,
`${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/${encodePathValue(matchId)}/timeline`,
);
return this.parseMatchPayload(response, 'match timeline');
}
private async getApexLeagueByQueue(
endpointName: 'challengerleagues' | 'grandmasterleagues' | 'masterleagues',
queueType: string,
platformRoute: RiotPlatformRoute,
): Promise<RiotApexLeagueListDto> {
const response = await this.requestJson(
platformRoute,
`${platformBaseUrl(platformRoute)}/lol/league/v4/${endpointName}/by-queue/${encodePathValue(queueType)}`,
);
return this.parseApexLeagueList(response);
}
private async requestJson(
routingValue: RiotPlatformRoute | RiotRegionalRoute,
url: string,
): Promise<unknown> {
const apiKey = await this.secretService.get('RIOT_API_KEY');
for (let attemptIndex = 0; ; attemptIndex += 1) {
await this.rateLimiter.waitForSlot(routingValue);
const response = await this.fetchWithTimeout(url, apiKey);
if (response.status === 429 && attemptIndex < this.maxRetries) {
const rawRetryAfterMs =
parseRetryAfterMs(response.headers.get('retry-after')) ??
this.exponentialBackoffMs(attemptIndex);
const retryAfterMs = Math.min(rawRetryAfterMs, this.maxRetryAfterMs);
await this.sleep(retryAfterMs);
continue;
}
if (response.status >= 500 && attemptIndex < this.maxRetries) {
await this.sleep(this.exponentialBackoffMs(attemptIndex));
continue;
}
if (response.status === 401 || response.status === 403) {
throw new RiotApiKeyError(response.status);
}
if (response.status === 404) {
throw new RiotNotFoundError(response.status);
}
if (!response.ok) {
throw new RiotApiError(
`Riot API request failed with status ${response.status}.`,
response.status,
);
}
return response.json();
}
}
private exponentialBackoffMs(attemptIndex: number): number {
return this.baseBackoffMs * 2 ** attemptIndex;
}
private async fetchWithTimeout(
url: string,
apiKey: string,
): Promise<Response> {
const abortController = new AbortController();
const timeout = setTimeout(
() => abortController.abort(),
this.requestTimeoutMs,
);
try {
return await this.fetchFn(url, {
headers: {
Accept: 'application/json',
'X-Riot-Token': apiKey,
},
signal: abortController.signal,
});
} catch (error) {
if (
error instanceof DOMException &&
error.name.toLowerCase() === 'aborterror'
) {
throw new RiotApiTimeoutError();
}
throw error;
} finally {
clearTimeout(timeout);
}
}
private parseAccount(value: unknown): RiotAccountDto {
const record = requireRecord(value, 'account');
return {
puuid: requireString(record, 'puuid', 'account'),
gameName: requireString(record, 'gameName', 'account'),
tagLine: requireString(record, 'tagLine', 'account'),
};
}
private parseSummoner(value: unknown): RiotSummonerDto {
const record = requireRecord(value, 'summoner');
return {
puuid: requireString(record, 'puuid', 'summoner'),
profileIconId: numberOrFallback(record, 'profileIconId', 0),
revisionDate: optionalNumber(record, 'revisionDate'),
summonerLevel: numberOrFallback(record, 'summonerLevel', 0),
};
}
private parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] {
if (!Array.isArray(value)) {
throw new RiotApiError(
'Riot league entries response had an unexpected shape.',
);
}
return value.map((entry) => {
const record = requireRecord(entry, 'league entry');
return {
queueType: requireString(record, 'queueType', 'league entry'),
tier: requireString(record, 'tier', 'league entry'),
rank: requireString(record, 'rank', 'league entry'),
leaguePoints: numberOrFallback(record, 'leaguePoints', 0),
wins: numberOrFallback(record, 'wins', 0),
losses: numberOrFallback(record, 'losses', 0),
veteran: optionalBoolean(record, 'veteran', false),
inactive: optionalBoolean(record, 'inactive', false),
freshBlood: optionalBoolean(record, 'freshBlood', false),
hotStreak: optionalBoolean(record, 'hotStreak', false),
};
});
}
private parseApexLeagueList(value: unknown): RiotApexLeagueListDto {
const record = requireRecord(value, 'apex league list');
const tier = requireString(record, 'tier', 'apex league list');
const queueType = requireString(record, 'queue', 'apex league list');
const entries = record.entries;
if (!Array.isArray(entries)) {
throw new RiotApiError(
'Riot apex league list response was missing array field "entries".',
);
}
return {
tier,
queueType,
entries: entries.map((entry) => {
const entryRecord = requireRecord(entry, 'apex league entry');
return {
puuid: requireString(entryRecord, 'puuid', 'apex league entry'),
queueType,
tier,
rank: requireString(entryRecord, 'rank', 'apex league entry'),
leaguePoints: numberOrFallback(entryRecord, 'leaguePoints', 0),
wins: numberOrFallback(entryRecord, 'wins', 0),
losses: numberOrFallback(entryRecord, 'losses', 0),
veteran: optionalBoolean(entryRecord, 'veteran', false),
inactive: optionalBoolean(entryRecord, 'inactive', false),
freshBlood: optionalBoolean(entryRecord, 'freshBlood', false),
hotStreak: optionalBoolean(entryRecord, 'hotStreak', false),
};
}),
};
}
private parseMatchIds(value: unknown): string[] {
if (!Array.isArray(value)) {
throw new RiotApiError('Riot match id response had an unexpected shape.');
}
const matchIds = value.filter(
(matchId): matchId is string => typeof matchId === 'string',
);
if (matchIds.length !== value.length) {
throw new RiotApiError('Riot match id response had an unexpected shape.');
}
return matchIds;
}
private parseMatchPayload(
value: unknown,
endpointName: string,
): Record<string, unknown> {
const record = requireRecord(value, endpointName);
requireRecordField(record, 'metadata', endpointName);
requireRecordField(record, 'info', endpointName);
return record;
}
}
@@ -0,0 +1,59 @@
import { RiotRateLimiter } from './riot-rate-limiter';
class ManualClock {
public currentTimeMs = 0;
public sleeps: number[] = [];
now = () => this.currentTimeMs;
sleep = (durationMs: number): Promise<void> => {
this.sleeps.push(durationMs);
this.currentTimeMs += durationMs;
return Promise.resolve();
};
}
describe('RiotRateLimiter', () => {
it('waits when the one-second development key window is exhausted', async () => {
const clock = new ManualClock();
const limiter = new RiotRateLimiter({ clock });
for (let index = 0; index < 20; index += 1) {
await limiter.waitForSlot('asia');
}
await limiter.waitForSlot('asia');
expect(clock.sleeps).toEqual([1000]);
});
it('tracks windows independently per Riot routing value', async () => {
const clock = new ManualClock();
const limiter = new RiotRateLimiter({ clock });
for (let index = 0; index < 20; index += 1) {
await limiter.waitForSlot('asia');
}
await limiter.waitForSlot('kr');
expect(clock.sleeps).toEqual([]);
});
it('waits for the longest exhausted window before recording a new request', async () => {
const clock = new ManualClock();
const limiter = new RiotRateLimiter({
clock,
windows: [
{ limit: 2, durationMs: 1000 },
{ limit: 3, durationMs: 5000 },
],
});
await limiter.waitForSlot('asia');
await limiter.waitForSlot('asia');
clock.currentTimeMs = 1000;
await limiter.waitForSlot('asia');
await limiter.waitForSlot('asia');
expect(clock.sleeps).toEqual([4000]);
});
});
@@ -0,0 +1,111 @@
import { Inject, Injectable, Optional } from '@nestjs/common';
export const RIOT_RATE_LIMITER_OPTIONS = Symbol('RIOT_RATE_LIMITER_OPTIONS');
export interface RiotRateLimitWindow {
durationMs: number;
limit: number;
}
export interface RiotRateLimiterClock {
now(): number;
sleep(durationMs: number): Promise<void>;
}
export interface RiotRateLimiterOptions {
clock?: RiotRateLimiterClock;
windows?: RiotRateLimitWindow[];
}
const DEFAULT_RATE_LIMIT_WINDOWS: RiotRateLimitWindow[] = [
{ limit: 20, durationMs: 1000 },
{ limit: 100, durationMs: 120_000 },
];
// Single-process limiter for the MVP worker/API process. If workers split into
// multiple processes or hosts, replace this with Redis-backed coordination.
const DEFAULT_CLOCK: RiotRateLimiterClock = {
now: () => Date.now(),
sleep: (durationMs: number) =>
new Promise((resolve) => setTimeout(resolve, durationMs)),
};
@Injectable()
export class RiotRateLimiter {
private readonly clock: RiotRateLimiterClock;
private readonly windows: RiotRateLimitWindow[];
private readonly requestTimestampsByRoutingValue = new Map<
string,
number[]
>();
constructor(
@Optional()
@Inject(RIOT_RATE_LIMITER_OPTIONS)
options: RiotRateLimiterOptions = {},
) {
this.clock = options.clock ?? DEFAULT_CLOCK;
this.windows = options.windows ?? DEFAULT_RATE_LIMIT_WINDOWS;
}
public async waitForSlot(routingValue: string): Promise<void> {
const requestTimestamps =
this.requestTimestampsByRoutingValue.get(routingValue) ?? [];
this.requestTimestampsByRoutingValue.set(routingValue, requestTimestamps);
while (true) {
const now = this.clock.now();
this.pruneExpiredTimestamps(requestTimestamps, now);
const waitDurationMs = this.resolveWaitDurationMs(requestTimestamps, now);
if (waitDurationMs <= 0) {
requestTimestamps.push(now);
return;
}
await this.clock.sleep(waitDurationMs);
}
}
private pruneExpiredTimestamps(
requestTimestamps: number[],
now: number,
): void {
const longestWindowDurationMs = Math.max(
...this.windows.map((window) => window.durationMs),
);
const firstRetainedIndex = requestTimestamps.findIndex(
(timestamp) => timestamp > now - longestWindowDurationMs,
);
if (firstRetainedIndex === -1) {
requestTimestamps.splice(0, requestTimestamps.length);
return;
}
if (firstRetainedIndex > 0) {
requestTimestamps.splice(0, firstRetainedIndex);
}
}
private resolveWaitDurationMs(
requestTimestamps: number[],
now: number,
): number {
let waitDurationMs = 0;
for (const window of this.windows) {
const timestampsInWindow = requestTimestamps.filter(
(timestamp) => timestamp > now - window.durationMs,
);
if (timestampsInWindow.length < window.limit) continue;
const oldestTimestamp = timestampsInWindow[0];
waitDurationMs = Math.max(
waitDurationMs,
oldestTimestamp + window.durationMs - now,
);
}
return waitDurationMs;
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { SecretModule } from '../global/secret/secret.module';
import { RiotApiClient } from './riot-api.client';
import { RiotRateLimiter } from './riot-rate-limiter';
@Module({
imports: [SecretModule],
providers: [RiotApiClient, RiotRateLimiter],
exports: [RiotApiClient, RiotRateLimiter],
})
export class RiotModule {}
+31
View File
@@ -17,12 +17,41 @@ export type RiotPlatformRoute =
| 'ru'
| 'me1'
| 'oc1'
| 'ph2'
| 'sg2'
| 'th2'
| 'tw2'
| 'vn2';
export type RiotRegionalRoute = 'americas' | 'asia' | 'europe' | 'sea';
export const RIOT_PLATFORM_ROUTES: readonly RiotPlatformRoute[] = [
'kr',
'jp1',
'na1',
'br1',
'la1',
'la2',
'euw1',
'eun1',
'tr1',
'ru',
'me1',
'oc1',
'ph2',
'sg2',
'th2',
'tw2',
'vn2',
];
export const RIOT_REGIONAL_ROUTES: readonly RiotRegionalRoute[] = [
'americas',
'asia',
'europe',
'sea',
];
export const PLATFORM_TO_REGIONAL_ROUTE: Record<
RiotPlatformRoute,
RiotRegionalRoute
@@ -39,7 +68,9 @@ export const PLATFORM_TO_REGIONAL_ROUTE: Record<
ru: 'europe',
me1: 'europe',
oc1: 'sea',
ph2: 'sea',
sg2: 'sea',
th2: 'sea',
tw2: 'sea',
vn2: 'sea',
};
+343
View File
@@ -0,0 +1,343 @@
import {
ADVANTAGE_EVENT_WEIGHTS,
FEATURE_SCHEMA_VERSION,
METRICS,
SUMMONERS_RIFT_MAP,
SUMMONERS_RIFT_MAP_ZONES,
VECTOR_DIMENSION,
type AnalysisRequestAcceptedDto,
type AnalysisJobStatusDto,
type AnalysisRequestDto,
type PlayerAnalysisDto,
} from '@persona-lenz/shared';
const MVP_1_METRIC_IDS = [
'kda',
'killParticipation',
'damageShare',
'damagePerMin',
'goldPerMin',
'csPerMin',
'visionScorePerMin',
'wardsKilledPerMin',
'controlWardsPlaced',
'deathsPerMin',
'objectiveParticipation',
'soloKills',
];
const MVP_2_TIMELINE_METRIC_IDS = [
'goldDiffAt10',
'goldDiffAt14',
'csDiffAt10',
'xpDiffAt10',
'deathsBefore14',
'killParticipationBefore14',
'earlyWardsPerMin',
'objectivePreWardRate',
'eliteObjectiveParticipationRate',
'isolationTendency',
'teamfightFirstEngagementParticipationRate',
'teamfightCleanupKillParticipationRate',
'deathWithShutdownBountyGivenRate',
'ccTimePerMinute',
];
const MVP_2_INSIGHT_METRIC_IDS = [
'objectiveFightOpeningParticipationRate',
'objectiveFightOpeningConvertedToObjectiveRate',
'preObjectivePitPresenceRate',
'preObjectivePickParticipationRate',
'deathFollowedByTeamLossRate',
'deathTradedForTeamAdvantageRate',
'deathWhileIsolatedFromNearestAllyRate',
'earlyDeficitRecoveryRate',
'laneLeadConversionRate',
'roamConvertedToTeamAdvantageRate',
'shutdownGoldCollectedPerGame',
'platePresenceParticipationRate',
'objectiveBountyComebackParticipationRate',
];
const MVP_2_METRIC_IDS = [
...MVP_1_METRIC_IDS,
...MVP_2_TIMELINE_METRIC_IDS,
...MVP_2_INSIGHT_METRIC_IDS,
];
const MVP_2_TIMELINE_METRIC_CONTRACTS = [
{ id: 'goldDiffAt10', kind: 'scalar', direction: 'higherIsBetter' },
{ id: 'goldDiffAt14', kind: 'scalar', direction: 'higherIsBetter' },
{ id: 'csDiffAt10', kind: 'scalar', direction: 'higherIsBetter' },
{ id: 'xpDiffAt10', kind: 'scalar', direction: 'higherIsBetter' },
{ id: 'deathsBefore14', kind: 'scalar', direction: 'lowerIsBetter' },
{
id: 'killParticipationBefore14',
kind: 'scalar',
direction: 'higherIsBetter',
},
{ id: 'earlyWardsPerMin', kind: 'scalar', direction: 'higherIsBetter' },
{ id: 'objectivePreWardRate', kind: 'ratio', direction: 'higherIsBetter' },
{
id: 'eliteObjectiveParticipationRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{ id: 'isolationTendency', kind: 'scalar', direction: 'lowerIsBetter' },
{
id: 'teamfightFirstEngagementParticipationRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'teamfightCleanupKillParticipationRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'deathWithShutdownBountyGivenRate',
kind: 'ratio',
direction: 'lowerIsBetter',
},
{ id: 'ccTimePerMinute', kind: 'scalar', direction: 'higherIsBetter' },
] as const;
const MVP_2_INSIGHT_METRIC_CONTRACTS = [
{
id: 'objectiveFightOpeningParticipationRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'objectiveFightOpeningConvertedToObjectiveRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'preObjectivePitPresenceRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'preObjectivePickParticipationRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'deathFollowedByTeamLossRate',
kind: 'ratio',
direction: 'lowerIsBetter',
},
{
id: 'deathTradedForTeamAdvantageRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'deathWhileIsolatedFromNearestAllyRate',
kind: 'ratio',
direction: 'lowerIsBetter',
},
{
id: 'earlyDeficitRecoveryRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'laneLeadConversionRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'roamConvertedToTeamAdvantageRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'shutdownGoldCollectedPerGame',
kind: 'scalar',
direction: 'higherIsBetter',
},
{
id: 'platePresenceParticipationRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
{
id: 'objectiveBountyComebackParticipationRate',
kind: 'ratio',
direction: 'higherIsBetter',
},
] as const;
describe('shared feature registry', () => {
it('defines MVP 2 vector metrics in the documented order', () => {
expect(FEATURE_SCHEMA_VERSION).toBe(2);
expect(METRICS.map((metric) => metric.id)).toEqual(MVP_2_METRIC_IDS);
expect(VECTOR_DIMENSION).toBe(26);
expect(
METRICS.filter((metric) => metric.includeInVector).map(
(metric) => metric.id,
),
).toEqual([...MVP_1_METRIC_IDS, ...MVP_2_TIMELINE_METRIC_IDS]);
expect(METRICS.filter((metric) => metric.includeInVector)).toHaveLength(
VECTOR_DIMENSION,
);
});
it('keeps metric ids unique and every metric normalizable by role', () => {
const metricIds = METRICS.map((metric) => metric.id);
expect(new Set(metricIds).size).toBe(metricIds.length);
for (const metric of METRICS) {
expect(metric.label.trim()).toBeTruthy();
expect(metric.description.trim()).toBeTruthy();
expect(metric.baseline).toBeDefined();
expect(Object.keys(metric.baseline ?? {}).sort()).toEqual([
'BOTTOM',
'JUNGLE',
'MIDDLE',
'TOP',
'UTILITY',
]);
for (const range of Object.values(metric.baseline ?? {})) {
expect(range.min).toBeLessThan(range.max);
}
}
});
it('marks deaths per minute as lower-is-better for strength scoring', () => {
expect(
METRICS.find((metric) => metric.id === 'deathsPerMin')?.direction,
).toBe('lowerIsBetter');
expect(
METRICS.find((metric) => metric.id === 'deathWithShutdownBountyGivenRate')
?.direction,
).toBe('lowerIsBetter');
});
it('defines MVP 2 timeline metric aggregation contracts', () => {
expect(
MVP_2_TIMELINE_METRIC_IDS.map((metricId) => {
const metric = METRICS.find((candidate) => candidate.id === metricId);
return {
id: metric?.id,
kind: metric?.kind,
direction: metric?.direction,
includeInVector: metric?.includeInVector,
};
}),
).toEqual(
MVP_2_TIMELINE_METRIC_CONTRACTS.map((metric) => ({
...metric,
includeInVector: true,
})),
);
});
it('defines MVP 2 insight metric aggregation contracts outside the vector', () => {
expect(
MVP_2_INSIGHT_METRIC_IDS.map((metricId) => {
const metric = METRICS.find((candidate) => candidate.id === metricId);
return {
id: metric?.id,
kind: metric?.kind,
direction: metric?.direction,
includeInVector: metric?.includeInVector,
};
}),
).toEqual(
MVP_2_INSIGHT_METRIC_CONTRACTS.map((metric) => ({
...metric,
includeInVector: false,
})),
);
});
it('defines shared advantage event weights for timeline-derived metrics', () => {
expect(ADVANTAGE_EVENT_WEIGHTS).toEqual({
championKill: 1,
turretPlate: 0.5,
tower: 1.5,
dragon: 1.5,
riftHerald: 1.5,
baron: 3,
});
});
it('defines shared Summoner Rift map zones for timeline-derived metrics', () => {
expect(SUMMONERS_RIFT_MAP_ZONES).toEqual([
'blueBase',
'redBase',
'topLane',
'middleLane',
'bottomLane',
'river',
'northWestJungle',
'northEastJungle',
'southWestJungle',
'southEastJungle',
'dragonPit',
'baronPit',
'unknown',
]);
expect(SUMMONERS_RIFT_MAP).toEqual({
coordinateMin: 0,
coordinateMax: 15_000,
laneAxisHalfWidth: 1_500,
riverBandHalfWidth: 1_500,
jungleMidline: 7_500,
baseRadius: 2_200,
objectivePitRadius: 2_500,
dragonPit: { x: 9_866, y: 4_414 },
baronPit: { x: 5_007, y: 10_471 },
});
});
});
describe('shared DTO contracts', () => {
it('exports request, job status, and player analysis DTO shapes', () => {
const request: AnalysisRequestDto = {
gameName: 'Hide on bush',
tagLine: 'KR1',
platform: 'ph2',
matchCount: 20,
};
const jobStatus: AnalysisJobStatusDto = {
jobId: 'job-1',
status: 'processing',
stage: 'fetch-match-details',
puuid: 'puuid-1',
progress: { fetchedMatches: 3, totalMatches: 20 },
error: null,
};
const accepted: AnalysisRequestAcceptedDto = {
jobId: 'job-1',
status: 'queued',
};
const playstyle = Object.fromEntries(
MVP_2_METRIC_IDS.map((metricId) => [metricId, 0.5]),
) as PlayerAnalysisDto['profile']['playstyle'];
const analysis: PlayerAnalysisDto = {
account: {
gameName: 'Hide on bush',
tagLine: 'KR1',
profileIconId: 1,
tiers: [],
},
profile: {
mainRole: 'MIDDLE',
queueId: 420,
sampleGameCount: 12,
championPool: [{ championId: 103, games: 4, wins: 3 }],
playstyle,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
confidence: 0.9,
},
strengths: [{ metricId: 'kda', value: 0.6 }],
weaknesses: [{ metricId: 'deathsPerMin', value: 0.7 }],
updatedAt: '2026-07-02T00:00:00.000Z',
};
expect(request.platform).toBe('ph2');
expect(accepted.status).toBe('queued');
expect(jobStatus.progress.totalMatches).toBe(20);
expect(analysis.profile.mainRole).toBe('MIDDLE');
});
});
+545 -4
View File
@@ -1,26 +1,567 @@
import { getQueueToken } from '@nestjs/bullmq';
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import {
FEATURE_SCHEMA_VERSION,
type PlayerAnalysisDto,
type SimilarPlayersDto,
} from '@persona-lenz/shared';
import request from 'supertest';
import { App } from 'supertest/types';
import { configureApp } from './../src/app.setup';
import { AppModule } from './../src/app.module';
import { AnalysisQueueService } from './../src/modules/analysis/analysis-queue.service';
import {
ANALYSIS_QUEUE_NAME,
SEED_COLLECTION_QUEUE_NAME,
} from './../src/modules/analysis/analysis.constants';
import { SimilarPlayerService } from './../src/modules/analysis/similar-player.service';
import { ConnectionService } from './../src/modules/global/database/connection.service';
import { REDIS_CLIENT } from './../src/modules/global/redis/redis.constants';
import { SecretService } from './../src/modules/global/secret/secret.service';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
let analysisQueueService: {
enqueueUserAnalysis: jest.Mock;
};
let similarPlayerService: {
findSimilarPlayers: jest.Mock;
};
let connectionService: {
getModel: jest.Mock;
};
function createLeanExec<T>(value: T) {
return {
lean: jest.fn(() => ({
exec: jest.fn().mockResolvedValue(value),
})),
};
}
beforeEach(async () => {
analysisQueueService = {
enqueueUserAnalysis: jest.fn(),
};
similarPlayerService = {
findSimilarPlayers: jest.fn(),
};
connectionService = {
getModel: jest.fn(),
};
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
})
.overrideProvider(ConnectionService)
.useValue(connectionService)
.overrideProvider(AnalysisQueueService)
.useValue(analysisQueueService)
.overrideProvider(SimilarPlayerService)
.useValue(similarPlayerService)
.overrideProvider(SecretService)
.useValue({
get: jest.fn((key: string) => {
if (key === 'REDIS_URL') {
return Promise.resolve('redis://localhost:6379/0');
}
return Promise.resolve('');
}),
ready: jest.fn().mockResolvedValue(undefined),
})
.overrideProvider(REDIS_CLIENT)
.useValue({
destroy: jest.fn(),
quit: jest.fn().mockResolvedValue(undefined),
})
.overrideProvider(getQueueToken(ANALYSIS_QUEUE_NAME))
.useValue({
add: jest.fn(),
})
.overrideProvider(getQueueToken(SEED_COLLECTION_QUEUE_NAME))
.useValue({
add: jest.fn(),
})
.compile();
app = moduleFixture.createNestApplication();
configureApp(app);
await app.init();
});
it('/ (GET)', () => {
it('/api/health (GET)', () => {
return request(app.getHttpServer())
.get('/')
.get('/api/health')
.expect(200)
.expect('Hello World!');
.expect({ status: 'ok' });
});
it('/api/analysis/request (POST) validates and enqueues analysis requests', async () => {
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
jobId: 'analysis-job-1',
status: 'queued',
});
await request(app.getHttpServer())
.post('/api/analysis/request')
.send({
gameName: ' Hide on bush ',
ignored: 'field',
matchCount: 999,
tagLine: ' KR1 ',
})
.expect(202)
.expect({
jobId: 'analysis-job-1',
status: 'queued',
});
expect(analysisQueueService.enqueueUserAnalysis).toHaveBeenCalledWith({
gameName: 'Hide on bush',
tagLine: 'KR1',
platformRoute: 'kr',
regionalRoute: 'asia',
queueId: 420,
requestedMatchCount: 50,
});
});
it('/api/analysis/request (POST) maps non-default platforms to regional routes', async () => {
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
jobId: 'analysis-job-1',
status: 'queued',
});
await request(app.getHttpServer())
.post('/api/analysis/request')
.send({
gameName: 'Hide on bush',
matchCount: 0,
platform: 'ph2',
tagLine: 'KR1',
})
.expect(202);
expect(analysisQueueService.enqueueUserAnalysis).toHaveBeenCalledWith({
gameName: 'Hide on bush',
tagLine: 'KR1',
platformRoute: 'ph2',
regionalRoute: 'sea',
queueId: 420,
requestedMatchCount: 1,
});
});
it.each([
['short gameName', { gameName: 'x', tagLine: 'KR1' }],
['missing tagLine', { gameName: 'Hide on bush' }],
['long tagLine', { gameName: 'Hide on bush', tagLine: 'TOOLONG' }],
[
'unsupported platform',
{ gameName: 'Hide on bush', platform: 'bad', tagLine: 'KR1' },
],
[
'non-number matchCount',
{ gameName: 'Hide on bush', matchCount: '20', tagLine: 'KR1' },
],
])('/api/analysis/request (POST) rejects %s', async (_label, body) => {
await request(app.getHttpServer())
.post('/api/analysis/request')
.send(body)
.expect(400);
expect(analysisQueueService.enqueueUserAnalysis).not.toHaveBeenCalled();
});
it('/api/analysis/request (POST) throttles repeated accepted requests', async () => {
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
jobId: 'analysis-job-1',
status: 'queued',
});
for (let index = 0; index < 10; index += 1) {
await request(app.getHttpServer())
.post('/api/analysis/request')
.send({
gameName: 'Hide on bush',
tagLine: 'KR1',
})
.expect(202);
}
await request(app.getHttpServer())
.post('/api/analysis/request')
.send({
gameName: 'Hide on bush',
tagLine: 'KR1',
})
.expect(429);
});
it('/api/analysis/jobs/:jobId (GET) returns job statuses', async () => {
const records = new Map([
[
'queued-job',
{
error: undefined,
jobId: 'queued-job',
progress: { fetchedMatches: 0, totalMatches: 0 },
status: 'queued',
},
],
[
'completed-job',
{
error: undefined,
jobId: 'completed-job',
progress: { fetchedMatches: 20, totalMatches: 20 },
puuid: 'target-puuid',
stage: 'completed',
status: 'completed',
},
],
[
'failed-job',
{
error: 'internal redis hostname leaked',
jobId: 'failed-job',
progress: { fetchedMatches: 4, totalMatches: 20 },
stage: 'fetch-match-details',
status: 'failed',
},
],
]);
const findOne = jest.fn(({ jobId }: { jobId: string }) =>
createLeanExec(records.get(jobId) ?? null),
);
connectionService.getModel.mockResolvedValue({
findOne,
});
await request(app.getHttpServer())
.get('/api/analysis/jobs/queued-job')
.expect(200)
.expect({
error: null,
jobId: 'queued-job',
progress: { fetchedMatches: 0, totalMatches: 0 },
status: 'queued',
});
await request(app.getHttpServer())
.get('/api/analysis/jobs/completed-job')
.expect(200)
.expect({
error: null,
jobId: 'completed-job',
progress: { fetchedMatches: 20, totalMatches: 20 },
puuid: 'target-puuid',
stage: 'completed',
status: 'completed',
});
await request(app.getHttpServer())
.get('/api/analysis/jobs/failed-job')
.expect(200)
.expect({
error: 'Analysis failed during processing.',
jobId: 'failed-job',
progress: { fetchedMatches: 4, totalMatches: 20 },
stage: 'fetch-match-details',
status: 'failed',
});
expect(findOne).toHaveBeenCalledWith({ jobId: 'queued-job' });
expect(findOne).toHaveBeenCalledWith({ jobId: 'completed-job' });
expect(findOne).toHaveBeenCalledWith({ jobId: 'failed-job' });
});
it('/api/analysis/jobs/:jobId (GET) returns 404 for missing jobs', async () => {
connectionService.getModel.mockResolvedValue({
findOne: jest.fn(() => createLeanExec(null)),
});
await request(app.getHttpServer())
.get('/api/analysis/jobs/missing-job')
.expect(404);
});
it('/api/players/:puuid/analysis/latest (GET) returns latest analysis', async () => {
const accountFindOne = jest.fn(() =>
createLeanExec({
gameName: 'Hide on bush',
profileIconId: 1,
tagLine: 'KR1',
tiers: [
{
fetchedAt: new Date('2026-07-01T00:00:00.000Z'),
leaguePoints: 100,
losses: 5,
queueType: 'RANKED_SOLO_5x5',
rank: 'I',
tier: 'MASTER',
wins: 10,
},
],
}),
);
const profileFindOne = jest.fn(() =>
createLeanExec({
championPool: [{ championId: 103, games: 4, wins: 3 }],
confidence: 0.9,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
mainRole: 'MIDDLE',
profile: {
kda: 0.8,
killParticipation: 0.7,
damageShare: 0.6,
damagePerMin: 0.5,
goldPerMin: 0.4,
csPerMin: 0.3,
visionScorePerMin: 0.2,
wardsKilledPerMin: 0.1,
controlWardsPlaced: 0.2,
deathsPerMin: 0.1,
objectiveParticipation: 0.6,
soloKills: 0.4,
},
queueId: 420,
sampleGameCount: 12,
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
}),
);
connectionService.getModel.mockImplementation((modelKey: string) => {
if (modelKey === 'account') {
return Promise.resolve({
findOne: accountFindOne,
});
}
if (modelKey !== 'playerProfile') {
throw new Error(`Unexpected model ${modelKey}`);
}
return Promise.resolve({
findOne: profileFindOne,
});
});
const response = await request(app.getHttpServer())
.get('/api/players/target-puuid/analysis/latest')
.expect(200);
const responseBody = response.body as PlayerAnalysisDto;
expect(accountFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid' });
expect(profileFindOne).toHaveBeenCalledWith({
puuid: 'target-puuid',
queueId: 420,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
});
expect(responseBody).toMatchObject({
account: {
gameName: 'Hide on bush',
profileIconId: 1,
tagLine: 'KR1',
tiers: [
{
fetchedAt: '2026-07-01T00:00:00.000Z',
leaguePoints: 100,
losses: 5,
queueType: 'RANKED_SOLO_5x5',
rank: 'I',
tier: 'MASTER',
wins: 10,
},
],
},
profile: {
championPool: [{ championId: 103, games: 4, wins: 3 }],
confidence: 0.9,
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
mainRole: 'MIDDLE',
playstyle: {
kda: 0.8,
killParticipation: 0.7,
damageShare: 0.6,
damagePerMin: 0.5,
goldPerMin: 0.4,
csPerMin: 0.3,
visionScorePerMin: 0.2,
wardsKilledPerMin: 0.1,
controlWardsPlaced: 0.2,
deathsPerMin: 0.1,
objectiveParticipation: 0.6,
soloKills: 0.4,
},
queueId: 420,
sampleGameCount: 12,
},
updatedAt: '2026-07-02T00:00:00.000Z',
});
expect(responseBody.strengths).toHaveLength(12);
expect(responseBody.weaknesses).toHaveLength(12);
expect(responseBody.strengths).toEqual(
expect.arrayContaining([
{ metricId: 'deathsPerMin', value: 0.1 },
{ metricId: 'kda', value: 0.8 },
{ metricId: 'killParticipation', value: 0.7 },
{ metricId: 'wardsKilledPerMin', value: 0.1 },
]),
);
expect(responseBody.weaknesses).toEqual(
expect.arrayContaining([
{ metricId: 'wardsKilledPerMin', value: 0.1 },
{ metricId: 'visionScorePerMin', value: 0.2 },
{ metricId: 'controlWardsPlaced', value: 0.2 },
{ metricId: 'deathsPerMin', value: 0.1 },
]),
);
expect(responseBody.strengths.slice(0, 3)).toEqual([
{ metricId: 'deathsPerMin', value: 0.1 },
{ metricId: 'kda', value: 0.8 },
{ metricId: 'killParticipation', value: 0.7 },
]);
expect(responseBody.weaknesses.slice(0, 3)).toEqual([
{ metricId: 'wardsKilledPerMin', value: 0.1 },
{ metricId: 'visionScorePerMin', value: 0.2 },
{ metricId: 'controlWardsPlaced', value: 0.2 },
]);
});
it('/api/players/:puuid/analysis/latest (GET) returns 404 without a profile', async () => {
connectionService.getModel.mockImplementation((modelKey: string) => {
if (modelKey === 'playerProfile') {
return Promise.resolve({
findOne: jest.fn(() => createLeanExec(null)),
});
}
return Promise.resolve({
findOne: jest.fn(() => createLeanExec({})),
});
});
await request(app.getHttpServer())
.get('/api/players/target-puuid/analysis/latest')
.expect(404)
.expect((response) => {
expect(response.body).toMatchObject({
message: '분석할 랭크 게임이 없음',
});
});
});
it('/api/players/:puuid/similar-players (GET) returns similar players with display Riot IDs', async () => {
similarPlayerService.findSimilarPlayers.mockResolvedValue({
puuid: 'target-puuid',
queueId: 420,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
matches: [
{
puuid: 'similar-player-puuid',
similarityScore: 0.87,
finalScore: 0.81,
tier: 'CHALLENGER',
leaguePoints: 900,
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
similarMetrics: [
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [
{
metricId: 'visionScorePerMin',
currentValue: 0.6,
otherValue: 0.4,
lead: 0.2,
},
],
},
],
});
const accountFind = jest.fn(() =>
createLeanExec([
{
puuid: 'similar-player-puuid',
gameName: '프리리',
tagLine: 'KR1',
},
]),
);
connectionService.getModel.mockResolvedValue({
find: accountFind,
});
const response = await request(app.getHttpServer())
.get('/api/players/target-puuid/similar-players?limit=3')
.expect(200);
const responseBody = response.body as SimilarPlayersDto;
expect(similarPlayerService.findSimilarPlayers).toHaveBeenCalledWith(
'target-puuid',
420,
3,
);
expect(accountFind).toHaveBeenCalledWith({
puuid: { $in: ['similar-player-puuid'] },
});
expect(responseBody).toEqual({
puuid: 'target-puuid',
queueId: 420,
profileUpdatedAt: '2026-07-02T00:00:00.000Z',
matches: [
{
displayId: 'similar-1',
riotId: {
gameName: '프리리',
tagLine: 'KR1',
},
similarityScore: 0.87,
finalScore: 0.81,
tier: 'CHALLENGER',
leaguePoints: 900,
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
similarMetrics: [
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [
{
metricId: 'visionScorePerMin',
currentValue: 0.6,
otherValue: 0.4,
lead: 0.2,
},
],
},
],
});
expect(responseBody.matches[0]).not.toHaveProperty('puuid');
});
afterEach(async () => {
+5
View File
@@ -1,4 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"tsBuildInfoFile": "./dist/tsconfig.build.tsbuildinfo"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
+3 -2
View File
@@ -1,10 +1,11 @@
<!doctype html>
<html lang="en">
<html lang="ko">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="referrer" content="no-referrer" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web</title>
<title>persona-lenz</title>
</head>
<body>
<div id="root"></div>
+3 -1
View File
@@ -13,7 +13,9 @@
"dependencies": {
"@persona-lenz/shared": "workspace:*",
"react": "^19.2.7",
"react-dom": "^19.2.7"
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1",
"recharts": "^3.9.1"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
+4 -1
View File
@@ -1 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="12" fill="#0d1110"/>
<path d="M18 44V20h13c5 0 8 3 8 7s-3 7-8 7h-6v10h-7Zm7-16h5c2 0 3-1 3-2s-1-2-3-2h-5v4Zm19 16V20h7v18h9v6H44Z" fill="#4cc9a7"/>
</svg>

Before

Width:  |  Height:  |  Size: 9.3 KiB

After

Width:  |  Height:  |  Size: 253 B

-24
View File
@@ -1,24 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

Before

Width:  |  Height:  |  Size: 4.9 KiB

+697 -161
View File
@@ -1,184 +1,720 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
.app-shell {
min-height: 100svh;
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
}
.app-header {
min-height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 32px;
border-bottom: 1px solid var(--border);
background: color-mix(in srgb, var(--surface) 86%, transparent);
backdrop-filter: blur(14px);
position: sticky;
top: 0;
z-index: 10;
}
.brand {
min-width: 0;
display: inline-flex;
align-items: center;
gap: 12px;
color: var(--text-strong);
text-decoration: none;
}
.brand-mark {
width: 40px;
height: 40px;
display: inline-grid;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
border: 1px solid var(--accent);
border-radius: 8px;
color: var(--accent);
font-size: 13px;
font-weight: 800;
}
#next-steps {
display: flex;
.brand-copy {
min-width: 0;
display: grid;
gap: 2px;
}
.brand-copy strong,
.brand-copy span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.brand-copy strong {
font-size: 15px;
}
.brand-copy span {
color: var(--text-muted);
font-size: 12px;
}
.header-status,
.status-pill {
display: inline-flex;
align-items: center;
min-height: 28px;
max-width: 100%;
padding: 0 10px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text-muted);
font-size: 12px;
font-weight: 700;
line-height: 1;
text-transform: uppercase;
white-space: nowrap;
}
.app-main {
width: min(1180px, calc(100% - 32px));
flex: 1;
margin: 0 auto;
padding: 48px 0;
}
.riot-disclaimer {
padding: 18px 32px 24px;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
color: var(--text-subtle);
font-size: 12px;
line-height: 1.55;
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
.home-view {
display: grid;
grid-template-columns: minmax(0, 1.1fr) minmax(360px, 0.9fr);
gap: 32px;
align-items: start;
}
#next-steps ul {
list-style: none;
padding: 0;
.home-copy,
.analysis-form,
.progress-panel,
.chart-section,
.champion-section,
.insight-section,
.similar-section,
.dashboard-summary {
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
}
.home-copy {
min-height: 430px;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 36px;
}
.eyebrow {
margin: 0 0 12px;
color: var(--accent);
font-size: 12px;
font-weight: 800;
letter-spacing: 0;
text-transform: uppercase;
}
.lead-copy {
max-width: 740px;
margin: 0;
color: var(--text-muted);
font-size: 16px;
line-height: 1.7;
}
.home-facts {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
margin: 36px 0 0;
}
.home-facts div,
.summary-stat {
min-width: 0;
padding: 14px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface-soft);
}
.home-facts dt,
.summary-stat span,
.progress-meta span,
.champion-copy span {
display: block;
color: var(--text-subtle);
font-size: 12px;
font-weight: 700;
line-height: 1.4;
text-transform: uppercase;
}
.home-facts dd,
.summary-stat strong,
.progress-meta strong {
display: block;
margin: 6px 0 0;
color: var(--text-strong);
font-size: 15px;
line-height: 1.35;
}
.analysis-form {
display: grid;
gap: 18px;
padding: 24px;
}
.form-header,
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.field {
display: grid;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
.field span {
color: var(--text-muted);
font-size: 13px;
font-weight: 700;
}
.ticks {
position: relative;
.field input {
width: 100%;
min-height: 48px;
box-sizing: border-box;
border: 1px solid var(--border-strong);
border-radius: 8px;
background: var(--surface-soft);
color: var(--text-strong);
font: inherit;
outline: none;
padding: 0 14px;
}
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
.field input:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 24%, transparent);
}
.primary-action,
.secondary-action {
min-height: 44px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid transparent;
border-radius: 8px;
font-size: 14px;
font-weight: 800;
text-decoration: none;
white-space: nowrap;
cursor: pointer;
}
.primary-action {
background: var(--accent);
color: #07110e;
padding: 0 18px;
}
.primary-action:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.secondary-action {
border-color: var(--border-strong);
background: var(--surface-soft);
color: var(--text-strong);
padding: 0 16px;
}
.message {
margin: 0;
border-radius: 8px;
padding: 12px 14px;
font-size: 14px;
line-height: 1.55;
}
.message-error {
border: 1px solid color-mix(in srgb, var(--danger) 52%, var(--border));
background: color-mix(in srgb, var(--danger) 13%, var(--surface));
color: var(--danger-strong);
}
.message-warning {
border: 1px solid color-mix(in srgb, var(--warning) 52%, var(--border));
background: color-mix(in srgb, var(--warning) 13%, var(--surface));
color: var(--warning-strong);
}
.progress-view {
display: grid;
place-items: center;
min-height: calc(100svh - 240px);
}
.progress-panel {
width: min(760px, 100%);
padding: 32px;
}
.progress-meter {
height: 12px;
margin: 28px 0 18px;
overflow: hidden;
border-radius: 999px;
background: var(--surface-soft);
}
.progress-meter span {
display: block;
height: 100%;
border-radius: inherit;
background: var(--accent);
transition: width 200ms ease;
}
.progress-meta {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
margin-bottom: 18px;
}
.progress-meta div {
min-width: 0;
padding: 14px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface-soft);
}
.action-row {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 20px;
}
.dashboard-view {
display: grid;
gap: 20px;
}
.dashboard-summary {
display: grid;
grid-template-columns: minmax(0, 1.2fr) minmax(360px, 0.8fr);
gap: 28px;
align-items: end;
padding: 28px;
}
.summary-stat-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px;
}
.chart-section,
.champion-section,
.insight-section,
.similar-section {
padding: 24px;
}
.radar-frame {
min-height: 380px;
margin-top: 18px;
}
.insight-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
}
.metric-card-list {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
margin-top: 16px;
}
.metric-card {
min-width: 0;
display: grid;
gap: 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface-soft);
padding: 14px;
}
.metric-card-heading {
min-width: 0;
display: flex;
align-items: start;
justify-content: space-between;
gap: 12px;
}
.metric-card-heading h3 {
min-width: 0;
margin: 0;
font-size: 15px;
line-height: 1.35;
}
.metric-card-heading strong {
flex: 0 0 auto;
color: var(--text-strong);
font-size: 22px;
line-height: 1;
}
.metric-card p {
margin: 0;
color: var(--text-muted);
font-size: 13px;
line-height: 1.45;
}
.metric-card > span {
color: var(--text-muted);
font-size: 12px;
font-weight: 700;
line-height: 1.35;
text-transform: uppercase;
}
.champion-list {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
margin-top: 16px;
}
.champion-row {
min-width: 0;
display: flex;
align-items: center;
gap: 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface-soft);
padding: 12px;
}
.champion-icon {
width: 44px;
height: 44px;
flex: 0 0 44px;
border-radius: 8px;
background: var(--border);
object-fit: cover;
}
.champion-placeholder {
display: inline-block;
border: 1px solid var(--border-strong);
}
.champion-copy {
min-width: 0;
display: grid;
gap: 4px;
}
.champion-copy strong {
overflow: hidden;
color: var(--text-strong);
font-size: 15px;
text-overflow: ellipsis;
white-space: nowrap;
}
.section-copy {
margin: 8px 0 0;
color: var(--text-muted);
font-size: 14px;
line-height: 1.55;
}
.similar-message {
margin-top: 16px;
}
.similar-table-wrap {
margin-top: 18px;
overflow-x: auto;
}
.similar-table-wrap:focus-visible {
outline: 3px solid color-mix(in srgb, var(--accent) 42%, transparent);
outline-offset: 3px;
}
.similar-table {
width: 100%;
min-width: 780px;
border-collapse: separate;
border-spacing: 0 10px;
}
.similar-table th {
padding: 0 12px;
color: var(--text-subtle);
font-size: 12px;
font-weight: 800;
line-height: 1.3;
text-align: left;
text-transform: uppercase;
}
.similar-table td {
min-width: 0;
padding: 14px 12px;
border-block: 1px solid var(--border);
background: var(--surface-soft);
vertical-align: top;
}
.similar-table td:first-child {
border-left: 1px solid var(--border);
border-radius: 8px 0 0 8px;
}
.similar-table td:last-child {
border-right: 1px solid var(--border);
border-radius: 0 8px 8px 0;
}
.similar-player,
.similar-score,
.similar-metric-groups,
.similar-metric-group {
min-width: 0;
display: grid;
gap: 6px;
}
.similar-player strong,
.similar-score strong,
.similar-chip strong {
overflow: hidden;
color: var(--text-strong);
text-overflow: ellipsis;
white-space: nowrap;
}
.similar-player span,
.similar-score span,
.similar-chip span,
.similar-metric-group > span,
.similar-empty {
color: var(--text-subtle);
font-size: 12px;
font-weight: 700;
line-height: 1.35;
}
.similar-score strong {
font-size: 22px;
line-height: 1;
}
.similar-chip-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
}
.similar-chip {
max-width: 100%;
display: inline-flex;
align-items: center;
gap: 6px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--surface);
padding: 5px 8px;
}
.similar-chip strong {
min-width: 0;
}
.similar-chip span {
flex: 0 0 auto;
white-space: nowrap;
}
.similar-chip-accent {
border-color: color-mix(in srgb, var(--accent) 48%, var(--border));
}
.similar-chip-muted {
background: color-mix(in srgb, var(--surface) 74%, var(--surface-soft));
}
.similar-tier-badge {
justify-self: start;
border: 1px solid color-mix(in srgb, var(--accent) 48%, var(--border));
border-radius: 999px;
padding: 3px 8px;
color: var(--text-strong);
font-size: 11px;
font-weight: 700;
line-height: 1.2;
}
.empty-view {
min-height: calc(100svh - 240px);
display: grid;
place-content: center;
justify-items: start;
gap: 18px;
}
.empty-copy {
margin: 16px 0 0;
color: var(--text-muted);
}
.skeleton {
position: relative;
overflow: hidden;
border-radius: 8px;
background: var(--surface);
}
.skeleton::after {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(
90deg,
transparent,
color-mix(in srgb, var(--text-muted) 10%, transparent),
transparent
);
animation: skeleton-sheen 1.4s linear infinite;
}
.skeleton-title {
width: min(420px, 100%);
height: 92px;
}
.skeleton-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
}
.skeleton-panel {
min-height: 280px;
}
@keyframes skeleton-sheen {
from {
transform: translateX(-100%);
}
&::before {
left: 0;
border-left-color: var(--border);
to {
transform: translateX(100%);
}
&::after {
right: 0;
border-right-color: var(--border);
}
@media (max-width: 900px) {
.app-main {
width: min(100% - 24px, 720px);
padding: 32px 0;
}
.home-view,
.dashboard-summary,
.insight-grid,
.champion-list,
.skeleton-grid {
grid-template-columns: 1fr;
}
.home-copy {
min-height: auto;
}
.summary-stat-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 640px) {
.app-header {
min-height: auto;
align-items: flex-start;
flex-direction: column;
padding: 16px;
}
.header-status {
display: none;
}
.home-copy,
.analysis-form,
.progress-panel,
.chart-section,
.champion-section,
.insight-section,
.similar-section,
.dashboard-summary {
padding: 18px;
}
.home-facts,
.progress-meta,
.summary-stat-grid,
.metric-card-list {
grid-template-columns: 1fr;
}
.form-header,
.section-heading {
align-items: flex-start;
flex-direction: column;
}
.radar-frame {
margin-inline: -8px;
}
}
+55 -115
View File
@@ -1,122 +1,62 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from './assets/vite.svg'
import heroImg from './assets/hero.png'
import './App.css'
import { Suspense, lazy } from 'react';
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
import './App.css';
import { HomePage } from './pages/HomePage';
import { NotFoundPage } from './pages/NotFoundPage';
import { ProgressPage } from './pages/ProgressPage';
const DashboardPage = lazy(() =>
import('./pages/DashboardPage').then((module) => ({
default: module.DashboardPage,
})),
);
function App() {
const [count, setCount] = useState(0)
return (
<>
<section id="center">
<div className="hero">
<img src={heroImg} className="base" width="170" height="179" alt="" />
<img src={reactLogo} className="framework" alt="React logo" />
<img src={viteLogo} className="vite" alt="Vite logo" />
</div>
<div>
<h1>Get started</h1>
<p>
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
</p>
</div>
<button
type="button"
className="counter"
onClick={() => setCount((count) => count + 1)}
>
Count is {count}
</button>
</section>
<BrowserRouter>
<div className="app-shell">
<header className="app-header">
<Link className="brand" to="/" aria-label="persona-lenz 홈">
<span className="brand-mark" aria-hidden="true">
PL
</span>
<span className="brand-copy">
<strong>persona-lenz</strong>
<span>LoL 플레이스타일 분석</span>
</span>
</Link>
<span className="header-status">Ranked Solo MVP</span>
</header>
<div className="ticks"></div>
<main className="app-main">
<Suspense fallback={<RouteFallback />}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/analysis/:jobId" element={<ProgressPage />} />
<Route path="/players/:puuid" element={<DashboardPage />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</Suspense>
</main>
<section id="next-steps">
<div id="docs">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#documentation-icon"></use>
</svg>
<h2>Documentation</h2>
<p>Your questions, answered</p>
<ul>
<li>
<a href="https://vite.dev/" target="_blank">
<img className="logo" src={viteLogo} alt="" />
Explore Vite
</a>
</li>
<li>
<a href="https://react.dev/" target="_blank">
<img className="button-icon" src={reactLogo} alt="" />
Learn more
</a>
</li>
</ul>
</div>
<div id="social">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#social-icon"></use>
</svg>
<h2>Connect with us</h2>
<p>Join the Vite community</p>
<ul>
<li>
<a href="https://github.com/vitejs/vite" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#github-icon"></use>
</svg>
GitHub
</a>
</li>
<li>
<a href="https://chat.vite.dev/" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#discord-icon"></use>
</svg>
Discord
</a>
</li>
<li>
<a href="https://x.com/vite_js" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#x-icon"></use>
</svg>
X.com
</a>
</li>
<li>
<a href="https://bsky.app/profile/vite.dev" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#bluesky-icon"></use>
</svg>
Bluesky
</a>
</li>
</ul>
</div>
</section>
<div className="ticks"></div>
<section id="spacer"></section>
</>
)
<footer className="riot-disclaimer">
persona-lenz is not endorsed by Riot Games and does not reflect the
views or opinions of Riot Games or anyone officially involved in
producing or managing Riot Games properties. Riot Games and all
associated properties are trademarks or registered trademarks of Riot
Games, Inc.
</footer>
</div>
</BrowserRouter>
);
}
export default App
function RouteFallback() {
return (
<section className="empty-view" aria-busy="true" aria-label="화면 로딩 중">
<div className="skeleton skeleton-title" />
</section>
);
}
export default App;
+110
View File
@@ -0,0 +1,110 @@
import type {
AnalysisJobStatusDto,
AnalysisRequestAcceptedDto,
AnalysisRequestDto,
PlayerAnalysisDto,
SimilarPlayersDto,
} from '@persona-lenz/shared';
export class ApiClientError extends Error {
readonly status: number;
constructor(message: string, status: number) {
super(message);
this.name = 'ApiClientError';
this.status = status;
}
}
const JSON_HEADERS = {
'Content-Type': 'application/json',
} as const;
async function fetchJson<T>(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<T> {
const response = await fetch(input, init);
if (!response.ok) {
throw new ApiClientError(await readErrorMessage(response), response.status);
}
return (await response.json()) as T;
}
async function readErrorMessage(response: Response): Promise<string> {
const fallback = `요청 처리에 실패했습니다. (${response.status})`;
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.includes('application/json')) {
const text = await response.text().catch(() => '');
return text.trim() || fallback;
}
const payload = await response.json().catch(() => undefined);
if (!isRecord(payload) || !('message' in payload)) {
return fallback;
}
const { message } = payload;
if (Array.isArray(message)) {
return message.map(String).join(', ');
}
return typeof message === 'string' && message.trim() ? message : fallback;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
export function getReadableErrorMessage(error: unknown): string {
if (error instanceof ApiClientError) {
return error.message;
}
if (error instanceof Error) {
return error.message;
}
return '알 수 없는 오류가 발생했습니다.';
}
export async function requestAnalysis(
payload: AnalysisRequestDto,
): Promise<AnalysisRequestAcceptedDto> {
return fetchJson<AnalysisRequestAcceptedDto>('/api/analysis/request', {
method: 'POST',
headers: JSON_HEADERS,
body: JSON.stringify(payload),
});
}
export async function getAnalysisJob(
jobId: string,
): Promise<AnalysisJobStatusDto> {
return fetchJson<AnalysisJobStatusDto>(
`/api/analysis/jobs/${encodeURIComponent(jobId)}`,
);
}
export async function getLatestPlayerAnalysis(
puuid: string,
): Promise<PlayerAnalysisDto> {
return fetchJson<PlayerAnalysisDto>(
`/api/players/${encodeURIComponent(puuid)}/analysis/latest`,
);
}
export async function getSimilarPlayers(
puuid: string,
limit = 10,
): Promise<SimilarPlayersDto> {
const params = new URLSearchParams({ limit: String(limit) });
return fetchJson<SimilarPlayersDto>(
`/api/players/${encodeURIComponent(puuid)}/similar-players?${params}`,
);
}
+139
View File
@@ -0,0 +1,139 @@
const DATA_DRAGON_BASE_URL = 'https://ddragon.leagueoflegends.com';
const CACHE_KEY = 'persona-lenz:data-dragon:champions:v1';
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
export interface ChampionSummary {
id: number;
imageUrl: string;
name: string;
}
export interface ChampionCatalog {
champions: Record<number, ChampionSummary>;
version: string;
}
interface ChampionCatalogCache extends ChampionCatalog {
cachedAt: number;
}
interface DataDragonChampion {
image: {
full: string;
};
key: string;
name: string;
}
interface DataDragonChampionResponse {
data: Record<string, DataDragonChampion>;
}
export async function loadChampionCatalog(): Promise<ChampionCatalog> {
const cachedCatalog = readChampionCatalogCache();
if (cachedCatalog && Date.now() - cachedCatalog.cachedAt < CACHE_TTL_MS) {
return cachedCatalog;
}
try {
const [latestVersion] = await fetchJson<string[]>(
`${DATA_DRAGON_BASE_URL}/api/versions.json`,
);
if (!latestVersion) {
throw new Error('Data Dragon 버전 목록이 비어 있습니다.');
}
const championResponse = await fetchJson<DataDragonChampionResponse>(
`${DATA_DRAGON_BASE_URL}/cdn/${latestVersion}/data/ko_KR/champion.json`,
);
const champions = Object.values(championResponse.data).reduce<
Record<number, ChampionSummary>
>((catalog, champion) => {
const championId = Number(champion.key);
if (Number.isFinite(championId)) {
catalog[championId] = {
id: championId,
imageUrl: `${DATA_DRAGON_BASE_URL}/cdn/${latestVersion}/img/champion/${champion.image.full}`,
name: champion.name,
};
}
return catalog;
}, {});
const catalog: ChampionCatalogCache = {
cachedAt: Date.now(),
champions,
version: latestVersion,
};
writeChampionCatalogCache(catalog);
return catalog;
} catch (error) {
if (cachedCatalog) {
return cachedCatalog;
}
throw error;
}
}
function readChampionCatalogCache(): ChampionCatalogCache | null {
let rawCache: string | null;
try {
rawCache = window.localStorage.getItem(CACHE_KEY);
} catch {
return null;
}
if (!rawCache) {
return null;
}
try {
const parsedCache = JSON.parse(rawCache) as Partial<ChampionCatalogCache>;
if (
typeof parsedCache.cachedAt === 'number' &&
typeof parsedCache.version === 'string' &&
parsedCache.champions &&
typeof parsedCache.champions === 'object'
) {
return parsedCache as ChampionCatalogCache;
}
} catch {
removeChampionCatalogCache();
}
return null;
}
function writeChampionCatalogCache(catalog: ChampionCatalogCache): void {
try {
window.localStorage.setItem(CACHE_KEY, JSON.stringify(catalog));
} catch {
// Champion metadata remains usable even when browser storage is restricted.
}
}
function removeChampionCatalogCache(): void {
try {
window.localStorage.removeItem(CACHE_KEY);
} catch {
// Ignore storage failures.
}
}
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Data Dragon 요청에 실패했습니다. (${response.status})`);
}
return (await response.json()) as T;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="usLine truncated

Before

Width:  |  Height:  |  Size: 8.5 KiB

+72 -86
View File
@@ -1,111 +1,97 @@
:root {
--text: #6b6375;
--text-h: #08060d;
--bg: #fff;
--border: #e5e4e7;
--code-bg: #f4f3ec;
--accent: #aa3bff;
--accent-bg: rgba(170, 59, 255, 0.1);
--accent-border: rgba(170, 59, 255, 0.5);
--social-bg: rgba(244, 243, 236, 0.5);
--shadow:
rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;
--accent: #4cc9a7;
--background: #0d1110;
--border: #2d3834;
--border-strong: #46554f;
--danger: #d86666;
--danger-strong: #f2a3a3;
--surface: #151a18;
--surface-soft: #1c2420;
--text: #d9e1dc;
--text-muted: #a6b1ab;
--text-strong: #f4f7f5;
--text-subtle: #808b85;
--warning: #d4a944;
--warning-strong: #efd18a;
--sans: system-ui, 'Segoe UI', Roboto, sans-serif;
--heading: system-ui, 'Segoe UI', Roboto, sans-serif;
--mono: ui-monospace, Consolas, monospace;
font: 18px/145% var(--sans);
letter-spacing: 0.18px;
color-scheme: light dark;
color: var(--text);
background: var(--bg);
background: var(--background);
font: 16px/1.5 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
'Segoe UI', sans-serif;
font-synthesis: none;
letter-spacing: 0;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@media (max-width: 1024px) {
font-size: 16px;
}
}
@media (prefers-color-scheme: dark) {
:root {
--text: #9ca3af;
--text-h: #f3f4f6;
--bg: #16171d;
--border: #2e303a;
--code-bg: #1f2028;
--accent: #c084fc;
--accent-bg: rgba(192, 132, 252, 0.15);
--accent-border: rgba(192, 132, 252, 0.5);
--social-bg: rgba(47, 48, 58, 0.5);
--shadow:
rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;
}
#social .button-icon {
filter: invert(1) brightness(2);
}
}
#root {
width: 1126px;
max-width: 100%;
margin: 0 auto;
text-align: center;
border-inline: 1px solid var(--border);
min-height: 100svh;
display: flex;
flex-direction: column;
* {
box-sizing: border-box;
}
body {
min-width: 320px;
min-height: 100svh;
margin: 0;
}
button,
input {
font: inherit;
}
button,
a {
-webkit-tap-highlight-color: transparent;
}
button:focus-visible,
a:focus-visible,
input:focus-visible {
outline: 3px solid color-mix(in srgb, var(--accent) 42%, transparent);
outline-offset: 3px;
}
h1,
h2 {
font-family: var(--heading);
font-weight: 500;
color: var(--text-h);
h2,
h3,
p {
overflow-wrap: anywhere;
}
h1,
h2,
h3 {
margin: 0;
color: var(--text-strong);
font-weight: 800;
letter-spacing: 0;
}
h1 {
max-width: 860px;
font-size: 56px;
letter-spacing: -1.68px;
margin: 32px 0;
@media (max-width: 1024px) {
font-size: 36px;
margin: 20px 0;
}
line-height: 1.02;
}
h2 {
font-size: 24px;
line-height: 118%;
letter-spacing: -0.24px;
margin: 0 0 8px;
@media (max-width: 1024px) {
font-size: 20px;
font-size: 20px;
line-height: 1.25;
}
img,
svg {
display: block;
}
::selection {
background: color-mix(in srgb, var(--accent) 38%, transparent);
color: var(--text-strong);
}
@media (max-width: 640px) {
h1 {
font-size: 34px;
line-height: 1.08;
}
}
p {
margin: 0;
}
code,
.counter {
font-family: var(--mono);
display: inline-flex;
border-radius: 4px;
color: var(--text-h);
}
code {
font-size: 15px;
line-height: 135%;
padding: 4px 8px;
background: var(--code-bg);
}
@@ -0,0 +1,68 @@
import type { AnalysisPlatformRoute, AnalysisRequestDto } from '@persona-lenz/shared';
const CACHE_PREFIX = 'persona-lenz:analysis-request:';
export function saveAnalysisRequest(
jobId: string,
request: AnalysisRequestDto,
): void {
try {
window.sessionStorage.setItem(
getCacheKey(jobId),
JSON.stringify({
gameName: request.gameName,
matchCount: request.matchCount,
platform: request.platform,
tagLine: request.tagLine,
}),
);
} catch {
// Retry is a convenience path; analysis itself should not depend on storage.
}
}
export function loadAnalysisRequest(jobId: string): AnalysisRequestDto | null {
try {
const rawRequest = window.sessionStorage.getItem(getCacheKey(jobId));
if (!rawRequest) {
return null;
}
const parsedRequest = JSON.parse(rawRequest) as Partial<AnalysisRequestDto>;
if (
typeof parsedRequest.gameName === 'string' &&
typeof parsedRequest.tagLine === 'string'
) {
return {
gameName: parsedRequest.gameName,
matchCount:
typeof parsedRequest.matchCount === 'number'
? parsedRequest.matchCount
: undefined,
platform:
typeof parsedRequest.platform === 'string'
? (parsedRequest.platform as AnalysisPlatformRoute)
: undefined,
tagLine: parsedRequest.tagLine,
};
}
} catch {
clearAnalysisRequest(jobId);
}
return null;
}
export function clearAnalysisRequest(jobId: string): void {
try {
window.sessionStorage.removeItem(getCacheKey(jobId));
} catch {
// Ignore storage failures.
}
}
function getCacheKey(jobId: string): string {
return `${CACHE_PREFIX}${jobId}`;
}
+88
View File
@@ -0,0 +1,88 @@
import {
METRICS,
type MetricDefinition,
type MetricId,
type Role,
} from '@persona-lenz/shared';
export const ROLE_LABELS: Record<Role, string> = {
BOTTOM: '원딜',
JUNGLE: '정글',
MIDDLE: '미드',
TOP: '탑',
UTILITY: '서포터',
};
export const STAGE_LABELS: Record<string, string> = {
'build-profile': '플레이스타일 프로필 생성',
completed: '분석 완료',
enqueue: '분석 작업 등록',
'extract-features': '매치 지표 추출',
'fetch-match-details': '최근 랭크 게임 수집',
'fetch-match-ids': '랭크 게임 목록 조회',
queued: '대기열 등록',
'resolve-account': 'Riot ID 확인',
};
const metricLabelById = new Map<MetricId, string>(
METRICS.map((metric) => [metric.id, metric.label]),
);
const metricDefinitionById = new Map<MetricId, MetricDefinition>(
METRICS.map((metric) => [metric.id, metric]),
);
export function formatPercent(value: number): string {
return `${Math.round(value * 100)}%`;
}
export function getMetricLabel(metricId: MetricId): string {
return metricLabelById.get(metricId) ?? metricId;
}
export function getMetricDescription(metricId: MetricId): string {
return (
metricDefinitionById.get(metricId)?.description ??
'정규화된 플레이스타일 지표입니다.'
);
}
export function getMetricDirectionLabel(metricId: MetricId): string {
const direction = metricDefinitionById.get(metricId)?.direction;
if (direction === 'lowerIsBetter') {
return '낮을수록 좋음';
}
if (direction === 'higherIsBetter') {
return '높을수록 좋음';
}
return '참고 지표';
}
export function getStageLabel(stage?: string): string {
if (!stage) {
return '작업 상태 확인';
}
return STAGE_LABELS[stage] ?? stage;
}
export function formatTier({
leaguePoints,
losses,
queueType,
rank,
tier,
wins,
}: {
leaguePoints: number;
losses: number;
queueType: string;
rank: string;
tier: string;
wins: number;
}): string {
const queueLabel =
queueType === 'RANKED_SOLO_5x5' ? '솔로랭크' : queueType.replaceAll('_', ' ');
return `${queueLabel} ${tier} ${rank} ${leaguePoints}LP · ${wins}승 ${losses}패`;
}
+614
View File
@@ -0,0 +1,614 @@
import { useEffect, useMemo, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import {
METRICS,
type ChampionPoolEntryDto,
type LeadMetricDto,
type MetricId,
type MetricValueDto,
type PlayerAnalysisDto,
type SimilarMetricDto,
type SimilarPlayerDto,
type SimilarPlayersDto,
type TierComparison,
type TierInfoDto,
} from '@persona-lenz/shared';
import {
PolarAngleAxis,
PolarGrid,
PolarRadiusAxis,
Radar,
RadarChart,
ResponsiveContainer,
Tooltip,
} from 'recharts';
import {
getLatestPlayerAnalysis,
getReadableErrorMessage,
getSimilarPlayers,
} from '../api/analysis';
import {
loadChampionCatalog,
type ChampionCatalog,
} from '../api/data-dragon';
import {
formatPercent,
formatTier,
getMetricDescription,
getMetricDirectionLabel,
getMetricLabel,
ROLE_LABELS,
} from '../lib/format';
interface RadarMetricDatum {
metricId: MetricId;
metricLabel: string;
value: number;
}
const SIMILAR_PLAYER_LIMIT = 10;
export function DashboardPage() {
const { puuid } = useParams<{ puuid: string }>();
const [analysis, setAnalysis] = useState<PlayerAnalysisDto | null>(null);
const [championCatalog, setChampionCatalog] =
useState<ChampionCatalog | null>(null);
const [similarPlayers, setSimilarPlayers] =
useState<SimilarPlayersDto | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [similarPlayersErrorMessage, setSimilarPlayersErrorMessage] =
useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const missingPuuidMessage = puuid ? null : '플레이어 식별자가 없습니다.';
useEffect(() => {
if (!puuid) {
return;
}
const currentPuuid = puuid;
let isActive = true;
async function loadDashboard() {
setIsLoading(true);
setAnalysis(null);
setErrorMessage(null);
setSimilarPlayersErrorMessage(null);
setSimilarPlayers(null);
const similarPlayersResultPromise = getSimilarPlayers(
currentPuuid,
SIMILAR_PLAYER_LIMIT,
).then(
(value) => ({ status: 'fulfilled', value }) as const,
(reason: unknown) => ({ status: 'rejected', reason }) as const,
);
try {
const nextAnalysis = await getLatestPlayerAnalysis(currentPuuid);
if (!isActive) {
return;
}
setAnalysis(nextAnalysis);
} catch (error) {
if (isActive) {
setAnalysis(null);
setErrorMessage(getReadableErrorMessage(error));
setIsLoading(false);
}
return;
}
if (isActive) {
setIsLoading(false);
}
const similarPlayersResult = await similarPlayersResultPromise;
if (!isActive) {
return;
}
if (similarPlayersResult.status === 'fulfilled') {
setSimilarPlayers(similarPlayersResult.value);
} else {
setSimilarPlayersErrorMessage(
getReadableErrorMessage(similarPlayersResult.reason),
);
}
}
void loadDashboard();
return () => {
isActive = false;
};
}, [puuid]);
useEffect(() => {
let isActive = true;
async function loadChampions() {
try {
const catalog = await loadChampionCatalog();
if (isActive) {
setChampionCatalog(catalog);
}
} catch {
if (isActive) {
setChampionCatalog(null);
}
}
}
void loadChampions();
return () => {
isActive = false;
};
}, []);
const radarData = useMemo<RadarMetricDatum[]>(() => {
if (!analysis) {
return [];
}
return METRICS.filter((metric) => metric.includeInVector).map((metric) => ({
metricId: metric.id,
metricLabel: metric.label,
value: Math.round((analysis.profile.playstyle[metric.id] ?? 0) * 100),
}));
}, [analysis]);
if (!missingPuuidMessage && isLoading) {
return <DashboardSkeleton />;
}
if (missingPuuidMessage || errorMessage || !analysis) {
return (
<section className="empty-view" aria-labelledby="dashboard-error-title">
<p className="eyebrow">Analysis result</p>
<h1 id="dashboard-error-title">결과를 불러오지 못했습니다.</h1>
<p className="message message-error" role="alert">
{missingPuuidMessage ?? errorMessage ?? '분석 결과가 없습니다.'}
</p>
<Link className="primary-action" to="/">
새 분석 요청
</Link>
</section>
);
}
const soloTier = pickSoloTier(analysis.account.tiers);
const sampleIsLow = analysis.profile.sampleGameCount < 5;
return (
<article className="dashboard-view" aria-labelledby="dashboard-title">
<section className="dashboard-summary">
<div>
<p className="eyebrow">Player analysis</p>
<h1 id="dashboard-title">
{analysis.account.gameName}#{analysis.account.tagLine}
</h1>
<p className="lead-copy">
{soloTier ? formatTier(soloTier) : '랭크 정보 없음'}
</p>
</div>
<div className="summary-stat-grid" aria-label="요약 지표">
<SummaryStat label="주 포지션" value={ROLE_LABELS[analysis.profile.mainRole]} />
<SummaryStat
label="분석 게임"
value={`${analysis.profile.sampleGameCount}게임`}
/>
<SummaryStat
label="신뢰도"
value={formatPercent(analysis.profile.confidence)}
/>
</div>
</section>
{sampleIsLow ? (
<p className="message message-warning" role="status">
표본 부족: 유효 랭크 게임이 5게임 미만이라 지표 신뢰도가 낮습니다.
</p>
) : null}
<section className="chart-section" aria-labelledby="radar-title">
<div className="section-heading">
<h2 id="radar-title">플레이스타일 벡터</h2>
<span className="status-pill">
schema v{analysis.profile.featureSchemaVersion}
</span>
</div>
<div className="radar-frame">
<ResponsiveContainer height={380} width="100%">
<RadarChart data={radarData} outerRadius="72%">
<PolarGrid stroke="#31413b" />
<PolarAngleAxis
dataKey="metricLabel"
tick={{ fill: '#c7d3cc', fontSize: 11 }}
/>
<PolarRadiusAxis
angle={90}
domain={[0, 100]}
stroke="#748079"
tick={{ fill: '#9fa9a3', fontSize: 10 }}
tickCount={5}
/>
<Tooltip formatter={(value) => [`${value}%`, '정규화 값']} />
<Radar
dataKey="value"
fill="#4cc9a7"
fillOpacity={0.24}
name="플레이스타일"
stroke="#4cc9a7"
strokeWidth={2}
/>
</RadarChart>
</ResponsiveContainer>
</div>
</section>
<section className="insight-grid" aria-label="강점과 약점">
<MetricInsightList
description="방향성을 반영했을 때 현재 프로필에서 상대적으로 좋은 순서입니다."
title="강점 지표"
values={analysis.strengths}
/>
<MetricInsightList
description="방향성을 반영했을 때 개선 여지가 큰 순서입니다."
title="약점 지표"
values={analysis.weaknesses}
/>
</section>
<section className="champion-section" aria-labelledby="champion-title">
<div className="section-heading">
<h2 id="champion-title">챔피언 풀</h2>
{championCatalog ? (
<span className="status-pill">Data Dragon {championCatalog.version}</span>
) : (
<span className="status-pill">metadata unavailable</span>
)}
</div>
{analysis.profile.championPool.length > 0 ? (
<div className="champion-list">
{analysis.profile.championPool.map((entry) => (
<ChampionPoolRow
catalog={championCatalog}
entry={entry}
key={entry.championId}
/>
))}
</div>
) : (
<p className="empty-copy">분석 가능한 챔피언 기록이 없습니다.</p>
)}
</section>
<SimilarPlayerSection
catalog={championCatalog}
errorMessage={similarPlayersErrorMessage}
similarPlayers={similarPlayers}
/>
</article>
);
}
function DashboardSkeleton() {
return (
<section className="dashboard-view" aria-busy="true" aria-label="결과 로딩 중">
<div className="skeleton skeleton-title" />
<div className="skeleton-grid">
<div className="skeleton skeleton-panel" />
<div className="skeleton skeleton-panel" />
</div>
</section>
);
}
function SummaryStat({ label, value }: { label: string; value: string }) {
return (
<div className="summary-stat">
<span>{label}</span>
<strong>{value}</strong>
</div>
);
}
function MetricInsightList({
description,
title,
values,
}: {
description: string;
title: string;
values: MetricValueDto[];
}) {
return (
<section className="insight-section">
<div className="section-heading">
<div>
<h2>{title}</h2>
<p className="section-copy">{description}</p>
</div>
<span className="status-pill">{values.length} metrics</span>
</div>
<div className="metric-card-list">
{values.map((metricValue) => (
<article className="metric-card" key={metricValue.metricId}>
<div className="metric-card-heading">
<h3>{getMetricLabel(metricValue.metricId)}</h3>
<strong>{formatPercent(metricValue.value)}</strong>
</div>
<p>{getMetricDescription(metricValue.metricId)}</p>
<span>{getMetricDirectionLabel(metricValue.metricId)}</span>
</article>
))}
</div>
</section>
);
}
function ChampionPoolRow({
catalog,
entry,
}: {
catalog: ChampionCatalog | null;
entry: ChampionPoolEntryDto;
}) {
const champion = catalog?.champions[entry.championId];
const winRate = entry.games > 0 ? entry.wins / entry.games : 0;
return (
<article className="champion-row">
{champion ? (
<img alt="" className="champion-icon" height="44" src={champion.imageUrl} width="44" />
) : (
<span className="champion-icon champion-placeholder" aria-hidden="true" />
)}
<div className="champion-copy">
<strong>{champion?.name ?? `챔피언 ${entry.championId}`}</strong>
<span>
{entry.games}게임 · {entry.wins}승 · 승률 {formatPercent(winRate)}
</span>
</div>
</article>
);
}
function SimilarPlayerSection({
catalog,
errorMessage,
similarPlayers,
}: {
catalog: ChampionCatalog | null;
errorMessage: string | null;
similarPlayers: SimilarPlayersDto | null;
}) {
const matches = similarPlayers?.matches ?? [];
return (
<section className="similar-section" aria-labelledby="similar-title">
<div className="section-heading">
<div>
<h2 id="similar-title">나와 비슷한 플레이어</h2>
<p className="section-copy">
플레이스타일 벡터가 가장 가까운 유저들입니다. 티어가 다르다면 어떤
지표에서 차이가 나는지 확인해보세요.
</p>
</div>
<span className="status-pill">
{similarPlayers ? `${matches.length} players` : 'similar players'}
</span>
</div>
{errorMessage ? (
<p className="message message-warning similar-message" role="status">
비슷한 플레이어 목록을 불러오지 못했습니다. {errorMessage}
</p>
) : null}
{!errorMessage && similarPlayers && matches.length === 0 ? (
<p className="empty-copy">
비교 가능한 프로필이 아직 충분히 수집되지 않았습니다.
</p>
) : null}
{!errorMessage && !similarPlayers ? (
<p className="empty-copy">비슷한 플레이어를 찾는 중입니다.</p>
) : null}
{matches.length > 0 ? (
<div
aria-label="나와 비슷한 플레이어 테이블"
className="similar-table-wrap"
role="region"
tabIndex={0}
>
<table className="similar-table">
<thead>
<tr>
<th scope="col">플레이어</th>
<th scope="col">유사도</th>
<th scope="col">주요 챔피언</th>
<th scope="col">비교 지표</th>
</tr>
</thead>
<tbody>
{matches.map((match) => (
<tr key={match.displayId}>
<td>
<div className="similar-player">
<strong>{formatSimilarPlayerName(match)}</strong>
<span>
{formatSimilarPlayerTier(match)} ·{' '}
{ROLE_LABELS[match.mainRole]} ·{' '}
{match.sampleGameCount}게임
</span>
{formatTierComparison(match.tierComparison) ? (
<span className="similar-tier-badge">
{formatTierComparison(match.tierComparison)}
</span>
) : null}
</div>
</td>
<td>
<div className="similar-score">
<strong>{formatPercent(match.similarityScore)}</strong>
<span>종합 {formatPercent(match.finalScore)}</span>
</div>
</td>
<td>
<SimilarPlayerChampionList catalog={catalog} match={match} />
</td>
<td>
<div className="similar-metric-groups">
<LeadMetricChips
accent
emptyLabel="이 유저가 앞서는 지표 없음"
title="이 유저가 앞서는 지표"
values={match.strongerMetrics}
/>
<LeadMetricChips
emptyLabel={null}
title="내가 앞서는 지표"
values={match.weakerMetrics}
/>
<SimilarMetricChips values={match.similarMetrics} />
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : null}
</section>
);
}
function SimilarPlayerChampionList({
catalog,
match,
}: {
catalog: ChampionCatalog | null;
match: SimilarPlayerDto;
}) {
if (match.mainChampions.length === 0) {
return <span className="similar-empty">챔피언 기록 없음</span>;
}
return (
<ul className="similar-chip-list">
{match.mainChampions.map((entry) => (
<li className="similar-chip" key={entry.championId}>
<strong>{formatChampionName(catalog, entry.championId)}</strong>
<span>{entry.games}게임</span>
</li>
))}
</ul>
);
}
function LeadMetricChips({
accent = false,
emptyLabel,
title,
values,
}: {
accent?: boolean;
emptyLabel: string | null;
title: string;
values: LeadMetricDto[];
}) {
if (values.length === 0) {
return emptyLabel ? (
<span className="similar-empty">{emptyLabel}</span>
) : null;
}
return (
<div className="similar-metric-group">
<span>{title}</span>
<ul className="similar-chip-list">
{values.map((value) => (
<li
className={`similar-chip ${accent ? 'similar-chip-accent' : ''}`}
key={value.metricId}
>
<strong>{getMetricLabel(value.metricId)}</strong>
<span>+{formatPercent(value.lead)}</span>
</li>
))}
</ul>
</div>
);
}
function SimilarMetricChips({ values }: { values: SimilarMetricDto[] }) {
if (values.length === 0) {
return null;
}
return (
<div className="similar-metric-group">
<span>비슷한 지표</span>
<ul className="similar-chip-list">
{values.map((value) => (
<li className="similar-chip similar-chip-muted" key={value.metricId}>
<strong>{getMetricLabel(value.metricId)}</strong>
<span>차이 {formatPercent(value.absoluteGap)}</span>
</li>
))}
</ul>
</div>
);
}
function formatSimilarPlayerName(match: SimilarPlayerDto): string {
if (match.riotId) {
return `${match.riotId.gameName}#${match.riotId.tagLine}`;
}
return formatSimilarPlayerDisplayId(match.displayId);
}
function formatSimilarPlayerDisplayId(displayId: string): string {
const numericSuffix = displayId.match(/^similar-(\d+)$/)?.[1];
return numericSuffix ? `비슷한 플레이어 #${numericSuffix}` : '비슷한 플레이어';
}
function formatTierComparison(tierComparison: TierComparison): string | null {
if (tierComparison === 'higher') return '나보다 높은 티어';
if (tierComparison === 'lower') return '나보다 낮은 티어';
if (tierComparison === 'same') return '같은 티어';
return null;
}
function formatSimilarPlayerTier(match: SimilarPlayerDto): string {
const tier = [match.tier, match.division].filter(Boolean).join(' ');
if (!tier) {
return '랭크 정보 없음';
}
return typeof match.leaguePoints === 'number'
? `${tier} ${match.leaguePoints}LP`
: tier;
}
function formatChampionName(
catalog: ChampionCatalog | null,
championId: number,
): string {
return catalog?.champions[championId]?.name ?? `챔피언 ${championId}`;
}
function pickSoloTier(tiers: TierInfoDto[]): TierInfoDto | null {
return tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? tiers[0] ?? null;
}
+125
View File
@@ -0,0 +1,125 @@
import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { getReadableErrorMessage, requestAnalysis } from '../api/analysis';
import { saveAnalysisRequest } from '../lib/analysis-request-cache';
const DEFAULT_MATCH_COUNT = 20;
const GAME_NAME_MIN_LENGTH = 3;
const GAME_NAME_MAX_LENGTH = 16;
const TAG_LINE_MIN_LENGTH = 3;
const TAG_LINE_MAX_LENGTH = 5;
export function HomePage() {
const navigate = useNavigate();
const [gameName, setGameName] = useState('');
const [tagLine, setTagLine] = useState('');
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const trimmedGameName = gameName.trim();
const trimmedTagLine = tagLine.trim();
const canSubmit =
trimmedGameName.length >= GAME_NAME_MIN_LENGTH &&
trimmedGameName.length <= GAME_NAME_MAX_LENGTH &&
trimmedTagLine.length >= TAG_LINE_MIN_LENGTH &&
trimmedTagLine.length <= TAG_LINE_MAX_LENGTH &&
!isSubmitting;
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!canSubmit) {
return;
}
setErrorMessage(null);
setIsSubmitting(true);
try {
const requestPayload = {
gameName: trimmedGameName,
matchCount: DEFAULT_MATCH_COUNT,
platform: 'kr',
tagLine: trimmedTagLine,
} as const;
const response = await requestAnalysis(requestPayload);
saveAnalysisRequest(response.jobId, requestPayload);
navigate(`/analysis/${response.jobId}`);
} catch (error) {
setErrorMessage(getReadableErrorMessage(error));
} finally {
setIsSubmitting(false);
}
}
return (
<section className="home-view" aria-labelledby="home-title">
<div className="home-copy">
<p className="eyebrow">Riot ID 기반 스타일 벡터</p>
<h1 id="home-title">최근 솔로랭크에서 드러난 플레이 성향을 확인하세요.</h1>
<p className="lead-copy">
KR 서버 Riot ID를 입력하면 최근 랭크 게임을 분석해 지표별 강점,
취약점, 주 챔피언 풀을 한 화면에 정리합니다.
</p>
<dl className="home-facts" aria-label="분석 기준">
<div>
<dt>Queue</dt>
<dd>RANKED SOLO</dd>
</div>
<div>
<dt>Sample</dt>
<dd>최근 {DEFAULT_MATCH_COUNT}게임</dd>
</div>
<div>
<dt>Region</dt>
<dd>KR</dd>
</div>
</dl>
</div>
<form className="analysis-form" onSubmit={handleSubmit}>
<div className="form-header">
<h2>분석 요청</h2>
<span className="status-pill">API queued</span>
</div>
<label className="field">
<span>Game Name</span>
<input
autoComplete="off"
maxLength={GAME_NAME_MAX_LENGTH}
minLength={GAME_NAME_MIN_LENGTH}
onChange={(event) => setGameName(event.target.value)}
placeholder="Hide on bush"
required
value={gameName}
/>
</label>
<label className="field">
<span>Tag Line</span>
<input
autoComplete="off"
maxLength={TAG_LINE_MAX_LENGTH}
minLength={TAG_LINE_MIN_LENGTH}
onChange={(event) => setTagLine(event.target.value)}
placeholder="KR1"
required
value={tagLine}
/>
</label>
{errorMessage ? (
<p className="message message-error" role="alert">
{errorMessage}
</p>
) : null}
<button className="primary-action" disabled={!canSubmit} type="submit">
{isSubmitting ? '요청 중' : '분석 시작'}
</button>
</form>
</section>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { Link } from 'react-router-dom';
export function NotFoundPage() {
return (
<section className="empty-view" aria-labelledby="not-found-title">
<p className="eyebrow">404</p>
<h1 id="not-found-title">페이지를 찾을 수 없습니다.</h1>
<p className="lead-copy">분석 요청 화면에서 다시 시작해 주세요.</p>
<Link className="primary-action" to="/">
홈으로 이동
</Link>
</section>
);
}
+197
View File
@@ -0,0 +1,197 @@
import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import type { AnalysisJobStatusDto } from '@persona-lenz/shared';
import {
getAnalysisJob,
getReadableErrorMessage,
requestAnalysis,
} from '../api/analysis';
import {
clearAnalysisRequest,
loadAnalysisRequest,
saveAnalysisRequest,
} from '../lib/analysis-request-cache';
import { getStageLabel } from '../lib/format';
const POLLING_INTERVAL_MS = 2_000;
export function ProgressPage() {
const navigate = useNavigate();
const { jobId } = useParams<{ jobId: string }>();
const [job, setJob] = useState<AnalysisJobStatusDto | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [isRetrying, setIsRetrying] = useState(false);
const missingJobIdMessage = jobId ? null : '분석 작업 ID가 없습니다.';
useEffect(() => {
if (!jobId) {
return;
}
const currentJobId = jobId;
let isActive = true;
async function pollJob() {
try {
const nextJob = await getAnalysisJob(currentJobId);
if (!isActive) {
return;
}
setJob(nextJob);
setErrorMessage(null);
if (nextJob.status === 'completed') {
if (nextJob.puuid) {
clearAnalysisRequest(currentJobId);
navigate(`/players/${nextJob.puuid}`, { replace: true });
return;
}
setErrorMessage('분석은 완료됐지만 결과 식별자를 받지 못했습니다.');
window.clearInterval(intervalId);
}
if (nextJob.status === 'failed') {
window.clearInterval(intervalId);
}
} catch (error) {
if (isActive) {
setErrorMessage(getReadableErrorMessage(error));
}
}
}
const intervalId = window.setInterval(() => {
void pollJob();
}, POLLING_INTERVAL_MS);
void pollJob();
return () => {
isActive = false;
window.clearInterval(intervalId);
};
}, [jobId, navigate]);
async function handleRetry() {
if (!jobId) {
navigate('/');
return;
}
const previousRequest = loadAnalysisRequest(jobId);
if (!previousRequest) {
navigate('/');
return;
}
setIsRetrying(true);
setErrorMessage(null);
try {
const response = await requestAnalysis(previousRequest);
saveAnalysisRequest(response.jobId, previousRequest);
navigate(`/analysis/${response.jobId}`, { replace: true });
} catch (error) {
setErrorMessage(getReadableErrorMessage(error));
} finally {
setIsRetrying(false);
}
}
const progressPercent = useMemo(() => {
if (!job) {
return 0;
}
if (job.status === 'completed') {
return 100;
}
if (job.progress.totalMatches <= 0) {
return job.status === 'queued' ? 8 : 18;
}
return Math.min(
98,
Math.round(
(job.progress.fetchedMatches / job.progress.totalMatches) * 100,
),
);
}, [job]);
return (
<section className="progress-view" aria-labelledby="progress-title">
<div className="progress-panel" aria-live="polite">
<p className="eyebrow">Analysis job</p>
<h1 id="progress-title">분석을 진행 중입니다.</h1>
<p className="lead-copy">
Riot API 응답과 매치 수에 따라 몇 분 정도 걸릴 수 있습니다.
</p>
<div
className="progress-meter"
aria-label="분석 진행률"
aria-valuemax={100}
aria-valuemin={0}
aria-valuenow={progressPercent}
role="progressbar"
>
<span style={{ width: `${progressPercent}%` }} />
</div>
<div className="progress-meta">
<div>
<span>Stage</span>
<strong>{getStageLabel(job?.stage)}</strong>
</div>
<div>
<span>Progress</span>
<strong>{progressPercent}%</strong>
</div>
<div>
<span>Matches</span>
<strong>
{job
? `${job.progress.fetchedMatches}/${job.progress.totalMatches}`
: '-'}
</strong>
</div>
</div>
{job?.status === 'failed' ? (
<p className="message message-error" role="alert">
{job.error ?? '분석 작업이 실패했습니다.'}
</p>
) : null}
{missingJobIdMessage || errorMessage ? (
<p className="message message-error" role="alert">
{missingJobIdMessage ?? errorMessage}
</p>
) : null}
<div className="action-row">
{job?.status === 'failed' ? (
<button
className="primary-action"
disabled={isRetrying}
onClick={() => {
void handleRetry();
}}
type="button"
>
{isRetrying ? '재시도 중' : '다시 시도'}
</button>
) : null}
<Link className="secondary-action" to="/">
새 요청 입력
</Link>
</div>
</div>
</section>
);
}
+8
View File
@@ -3,5 +3,13 @@ import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
optimizeDeps: {
include: ['@persona-lenz/shared'],
},
plugins: [react()],
server: {
proxy: {
'/api': 'http://localhost:3000',
},
},
})
+861
View File
@@ -0,0 +1,861 @@
# persona-lenz — 플레이스타일 벡터 기반 LoL 개인 분석 앱 실행 플랜
작성일: 2026-07-02
이 문서는 Codex(또는 다른 코딩 에이전트)가 추가 질문 없이 구현에 착수할 수 있도록 작성된 실행 플랜이다.
아이디어 원본은 `docs/archive/lol_playstyle_mentor_app_codex_context.md`에 보존되어 있으며, **스택·아키텍처가 원본과 다른 부분은 항상 이 문서가 우선한다** (원본: pgvector/Python worker/Next.js → 확정: MongoDB Atlas/BullMQ/Vite-React).
---
## 1. 프로젝트 개요와 제약
### 1.1 한 줄 설명
> Riot API의 Match History / Timeline 데이터로 유저의 플레이스타일을 벡터화하고, 나와 비슷하게 플레이하지만 더 높은 티어인 유저를 찾아 비교해주며, 스타일에 맞는 챔피언 추천과 개선 피드백을 제공하는 LoL 학습 도구.
단순 전적 검색 사이트가 아니다. 핵심은 **데이터 정제 + feature engineering + vector search + 근거 기반 설명 생성**이다.
### 1.2 앱이 답해야 하는 질문
- 나는 어떤 스타일의 플레이어인가? 강점/약점은 무엇인가?
- 나와 비슷한데 더 높은 티어인 유저는 누구이고, 어떤 지표에서 차이가 나는가?
- 내 스타일에 맞는 챔피언은 무엇인가?
- 다음 게임에서 바로 시도할 수 있는 개선 행동은 무엇인가?
### 1.3 만들지 말아야 할 것 (금지 사항)
- 단순 KDA/승률 전적 검색 사이트
- MMR/ELO 계산기 ("당신의 숨겨진 MMR은 X입니다" 류 — Riot 정책 위반)
- 실시간 게임 중 정보 제공/의사결정 강제 오버레이
- Raw match JSON을 LLM에 통째로 던져 그럴듯한 코칭 문장을 생성하는 앱
### 1.4 Riot 정책 제약 (구현 시 상시 준수)
- Riot API key는 **서버 전용**. 코드/클라이언트 번들/git에 절대 포함하지 않는다. `SecretService`(Infisical) 경유로만 접근.
- 구조는 반드시 `Frontend → Backend → Riot API`.
- 실시간 게임 중 숨겨진 정보 제공 금지, 플레이어 의사결정 강제 표현 지양.
- Riot과 공식 제휴/승인된 것처럼 보이지 않게 하고, 법적 고지 문구를 서비스에 표시 (§9.4).
- 공식 문서 참조: https://developer.riotgames.com/apis , https://developer.riotgames.com/policies/general
### 1.5 LLM 사용 원칙 (MVP 5)
LLM은 **분석 엔진이 아니라 설명 엔진**이다. 백엔드가 계산한 metric/evidence JSON만 입력으로 받아 사람이 읽기 쉬운 피드백을 생성한다. 없는 지표를 만들어내면 안 되고, 모든 피드백은 metricId와 연결되어야 한다.
---
## 2. 확정 기술 스택과 아키텍처
| 레이어 | 기술 |
| ----------- | --------------------------------------------------------------------------------------------------- |
| Runtime | Node.js 26 |
| Backend | NestJS 11 (`apps/api`) — HTTP API + BullMQ 프로세서 동거 (단일 프로세스) |
| Frontend | Vite + React (`apps/web`) |
| DB | **MongoDB Atlas** (환경별 dbName 분리 — T0.2 참조). 벡터 검색은 Atlas Vector Search `$vectorSearch` |
| Queue/Cache | Redis + BullMQ |
| 공유 코드 | `packages/shared` (DTO, feature registry) |
| Secret | Infisical (`SECRET_SOURCE=infisical`, `project.yaml`에 projectId 있음) |
| 패키지 관리 | pnpm workspace 모노레포 |
### 2.1 데이터 흐름
```text
web (Riot ID 입력)
→ api: POST /api/analysis/request
→ BullMQ 큐 'analysis' (Redis)
→ 프로세서: Riot API 수집 → Atlas 저장 → feature 추출 → profile 생성
→ web: 잡 폴링 → 완료 시 GET /api/players/:puuid/analysis/latest → 대시보드
```
### 2.2 필요한 시크릿 (Infisical dev 환경에 등록 — 사용자가 수행)
- `RIOT_API_KEY` — Riot 개발자 포털 development key
- `MONGODB_CONNECTION_STRING` — Atlas 클러스터 SRV 연결 문자열
- `REDIS_URL` (또는 기존 `REDIS_ENDPOINT`/`REDIS_PASSWORD / REDIS_USERID` 조합 — `RedisModule`이 둘 다 지원)
- `MONGODB_AUTO_INDEX=true` (dev만 — 스키마 선언 인덱스 자동 생성. prod는 인덱스 수동 생성)
로컬 인프라: MongoDB는 Atlas를 그대로 사용하므로 로컬 컨테이너 불필요. Redis가 로컬에 없으면 `compose.dev.yaml`(redis 단일 서비스)을 추가해 사용한다.
### 2.3 확장 시 분리 지점 (지금은 하지 않음)
- BullMQ 프로세서를 `apps/worker`로 분리 (큐 이름/잡 계약은 그대로 유지되도록 설계)
- rate limiter를 인메모리 → Redis 기반으로 전환 (§6.3)
---
## 3. Phase 0 — 선행 정리 작업
`apps/api/src/modules/global/database/`는 타 프로젝트(lolympus)에서 **스타일 참고용**으로 복사된 상태였다. 스타일(패턴)은 계승하고 도메인 내용물은 교체한다.
> **상태: T0.1~T0.3은 Claude가 구현 완료** (lolympus 파일 삭제, ConnectionService 수정, §4 스키마 8종 + 레지스트리 + 테스트). Codex는 **T0.4부터** 시작한다.
### T0.1 lolympus 도메인 파일 삭제 — 완료
- 삭제: `database/schema.ts`, `database/migrations/` 전체, `database/dev-seeds/` 전체, `database/auction-redis-schema.spec.ts`
- `database/connection.service.spec.ts`는 새 스키마 레지스트리에 맞게 재작성하거나 일단 삭제 후 T0.3에서 재작성
- 유지: `database/connection.service.ts`, `database/database.module.ts`, `database/types.d.ts`(ModelDefinition 타입 — 새 구조에 맞게 조정)
### T0.2 ConnectionService 수정 — 완료
`connection.service.ts`에서:
- `resolveMongoDbName`: `lolympus` → `persona-lenz`, `lolympus-staging` → `persona-lenz-staging`, `lolympus-dev` → `persona-lenz-dev`
- `resolveMongoAppName`: `lolympus-api:*` → `persona-lenz-api:*`
- `applyMongoosePerformancePlugin` import 제거 (observability 모듈은 이 레포에 없음. 필요해지면 나중에 도입)
- `tournamentModelDefinitions`/`TournamentModelTypes` 네이밍을 `modelDefinitions`/`ModelTypes`로 일반화
### T0.3 스키마 파일 구조 (agent-friendly 개선) — 완료
lolympus는 2,400줄 단일 `schema.ts`였다. 에이전트가 작은 단위로 안전하게 편집할 수 있도록 **컬렉션별 파일로 분리**했다:
```text
apps/api/src/modules/global/database/
connection.service.ts # 유지·수정 (T0.2)
database.module.ts # 유지
types.ts # ModelDefinition 타입
schemas/
common.ts # MongooseTimestamps, TeamPosition, TierInfo, NormalizationMethod
account.schema.ts
riot-match.schema.ts
player-match-feature.schema.ts
player-profile.schema.ts
analysis-job.schema.ts
metric-baseline.schema.ts
recommendation.schema.ts
champion-style-profile.schema.ts
index.ts # modelDefinitions 배열 + ModelTypes 맵 조립
```
파일당 규칙 (lolympus 스타일 계승):
- interface 정의 → SubSchema → 메인 `Schema` → `schema.index(...)` 선언을 한 파일에 콜로케이션
- 컬렉션명은 snake_case 단수 (`collection: 'riot_match'` 등), timestamps: true
- `HydratedDocument<T>` 타입 export
- `index.ts`의 `modelDefinitions`에 등록하면 `ConnectionService.getModel('riotMatch')`처럼 typed로 꺼내 쓸 수 있어야 한다
**완료 기준**: `pnpm --filter api build` 통과, `connection.service` 단위 테스트(레지스트리에 모든 모델이 등록되는지) 통과.
### T0.4 AppModule 배선
- `GlobalModule`에 `DatabaseModule`, `RedisModule` 등록 (현재 SecretModule만 등록되어 있음)
- 기본 NestJS 보일러플레이트(`app.controller/service`)는 헬스체크(`GET /api/health`)로 교체
- `main.ts`: global prefix `/api`, CORS는 사용하지 않고 web의 vite proxy로 처리 (§9.1)
---
## 4. MongoDB 스키마 설계 (MVP 1~4를 견디는 설계 — **구현 완료**)
> 이 섹션의 스키마는 Claude가 `apps/api/src/modules/global/database/schemas/`에 이미 구현했다. MVP 2(§11)·MVP 3(§12)의 요구사항 — timeline 파생물, `$vectorSearch` filter용 비정규화, percentile baseline, seed 계정 구분 — 을 미리 반영해 **이후 단계에서 스키마 마이그레이션 없이 필드가 채워지기만** 하도록 설계했다. Codex는 이 스키마를 수정하지 말고 사용한다 (변경이 필요하면 이유를 명시하고 사용자 확인).
모든 벡터 필드는 `number[]`이며 길이/순서는 `packages/shared`의 feature registry(§5)가 결정한다. 저장 시 `featureSchemaVersion`을 함께 기록해 registry 변경 시 재계산 대상을 식별한다.
공용 타입은 `schemas/common.ts`: `MongooseTimestamps`, `TeamPosition`(TOP/JUNGLE/MIDDLE/BOTTOM/UTILITY), `TierInfo`(+SubSchema), `NormalizationMethod`. Riot 라우팅 타입은 `modules/riot/riot.types.ts`(이미 생성됨 — T3에서 client가 여기에 추가된다).
인덱스는 mongoose 스키마에 선언되어 있고 `MONGODB_AUTO_INDEX=true`일 때만 자동 생성된다(ConnectionService 기본 autoIndex=false). **dev 환경 Infisical에 `MONGODB_AUTO_INDEX=true`를 넣고, prod는 인덱스 확정 후 수동 생성**한다.
### 4.1 `account`
```ts
interface Account extends MongooseTimestamps {
puuid: string; // unique index
gameName: string;
tagLine: string;
platformRoute: RiotPlatformRoute; // 'kr' 등
regionalRoute: RiotRegionalRoute; // 'asia' 등
profileIconId: number;
summonerLevel: number;
tiers: TierInfo[]; // league-v4 결과. queueType별 최신 스냅샷
tiersFetchedAt?: Date;
matchIdsFetchedAt?: Date;
lastAnalyzedAt?: Date;
// ---- MVP 3: 고티어 seed pool ----
isSeed: boolean; // default false. league-v4 리그 목록에서 수집된 계정
seedSource?: "challenger" | "grandmaster" | "master";
seedAddedAt?: Date;
lastSeedCollectedAt?: Date; // seed 수집 스케줄러가 다음 대상 선정에 사용
}
```
- index: `{ puuid: 1 }` unique, `{ gameName: 1, tagLine: 1 }`, `{ isSeed: 1, lastSeedCollectedAt: 1 }`
### 4.2 `riot_match` — lolympus 설계 계승 (검증된 구조)
```ts
interface RiotMatch extends MongooseTimestamps {
matchId: string; // unique index. 예: KR_7123456789
gameCreation: number;
gameDuration: number;
gameVersion?: string;
queueId?: number;
participantPuuids: string[];
raw: Record<string, unknown>; // Match-V5 원본 전체
timeline?: Record<string, unknown>; // MVP 2에서 채움
timelineFetchedAt?: Date;
fetchedAt: Date;
}
```
- index: `{ matchId: 1 }` unique, `{ participantPuuids: 1, gameCreation: -1 }`, `{ participantPuuids: 1, queueId: 1, gameCreation: -1 }`
### 4.3 `player_match_feature`
```ts
interface LaneOpponentRef {
puuid: string;
championId: number;
}
interface PlayerMatchFeature extends MongooseTimestamps {
matchId: string;
puuid: string;
queueId: number;
role: TeamPosition | "UNKNOWN"; // participant.teamPosition. 빈 값이면 'UNKNOWN' + confidence 감점
championId: number;
gameCreation: number;
gameDurationSec: number;
win: boolean;
patch: string; // gameVersion 앞 두 마디. 예: '26.13'
features: Record<string, number>; // metricId → 정규화 전 raw 값
normalized: Record<string, number>; // metricId → 0~1 정규화 값
vector: number[]; // registry 순서대로 normalized 값
featureSchemaVersion: number;
normalizationMethod: NormalizationMethod; // 'registry-baseline' | 'population-percentile'
confidence: number; // 0~1. remake/짧은 게임/role 불명 시 감점
// ---- MVP 2: timeline ----
timelineProcessed: boolean; // default false. timeline 지표 반영 여부 (재계산 대상 식별)
laneOpponent?: LaneOpponentRef; // diff 지표의 비교 대상
derived?: Record<string, unknown>; // 스칼라가 아닌 파생물: deathEvents[{t,x,y,zone}] 등
}
```
- index: `{ matchId: 1, puuid: 1 }` unique, `{ puuid: 1, queueId: 1, gameCreation: -1 }`, `{ featureSchemaVersion: 1, timelineProcessed: 1 }`(재계산 스캔), `{ role: 1, patch: 1, gameCreation: -1 }`(baseline 집계)
### 4.4 `player_profile`
`$vectorSearch`는 같은 컬렉션의 필드로만 filter할 수 있으므로, 검색 필터에 필요한 값(tier, isSeed 등)을 profile build 시점에 `account`에서 **비정규화**해 저장한다 (§12.3).
```ts
interface ChampionPoolEntry {
championId: number;
games: number;
wins: number;
}
interface PlayerProfile extends MongooseTimestamps {
puuid: string;
queueId: number; // MVP 1은 420 고정
mainRole: TeamPosition;
roleDistribution: Partial<Record<TeamPosition, number>>; // 게임 수 비율 0~1
sampleGameCount: number;
championPool: ChampionPoolEntry[]; // games 내림차순. re-rank의 championPoolSim에 사용
profile: Record<string, number>; // metricId → 집계된 0~1 값
vector: number[];
featureSchemaVersion: number;
normalizationMethod: NormalizationMethod;
confidence: number;
patches: string[]; // 집계에 포함된 패치 목록
lastMatchAt?: Date; // 집계에 포함된 가장 최근 게임 시각. recency re-rank용
// ---- MVP 3: $vectorSearch filter용 비정규화 (build 시점 account.tiers에서 복사) ----
tier?: string; // RANKED_SOLO_5x5 기준. 'MASTER' 등
division?: string; // 'I'~'IV'
leaguePoints?: number;
isSeed: boolean; // default false
}
```
- index: `{ puuid: 1, queueId: 1 }` unique, `{ isSeed: 1, mainRole: 1, tier: 1 }`(운영 조회용)
- **Atlas Vector Search 인덱스는 MVP 3에서 생성** (§12.3에 정의 JSON). MVP 1~2는 필드 저장만.
### 4.5 `analysis_job`
유저 분석뿐 아니라 MVP 2~3의 백그라운드 잡(재계산·seed 수집·baseline 계산)도 같은 컬렉션으로 추적한다.
```ts
type AnalysisJobType =
| "user-analysis" // MVP 1
| "feature-recompute" // MVP 2 (§11.4)
| "seed-collection" // MVP 3 (§12.1)
| "baseline-computation"; // MVP 3 (§12.2)
type AnalysisJobStatus = "queued" | "processing" | "completed" | "failed";
interface AnalysisJob extends MongooseTimestamps {
jobId: string; // unique. BullMQ job id와 동일하게
jobType: AnalysisJobType; // default 'user-analysis'
puuid?: string; // user-analysis는 resolve-account 후 채움. seed-collection은 처음부터
gameName?: string; // user-analysis에서만 사용
tagLine?: string;
platformRoute: RiotPlatformRoute;
queueId: number;
requestedMatchCount: number;
status: AnalysisJobStatus;
stage?: string; // 'resolve-account' | 'fetch-match-ids' | ...
progress: { fetchedMatches: number; totalMatches: number };
error?: string;
completedAt?: Date;
}
```
- index: `{ jobId: 1 }` unique, `{ puuid: 1, status: 1 }`, `{ jobType: 1, status: 1, createdAt: -1 }`
### 4.6 `metric_baseline` (MVP 3 — §12.2)
metricId × role × cohort × patch 조합별 인구 분위값. 정규화 v2(percentile rank)의 근거 데이터.
```ts
interface MetricBaseline extends MongooseTimestamps {
metricId: string;
role: TeamPosition;
cohort: "MASTER_PLUS" | "ALL";
patch: string; // '26.13' 또는 'ALL'
featureSchemaVersion: number;
sampleCount: number;
percentileBreakpoints: number[]; // p5~p95, 5% 간격 19개. 정규화 = 선형 보간 percentile rank
computedAt: Date;
}
```
- index: `{ metricId: 1, role: 1, cohort: 1, patch: 1, featureSchemaVersion: 1 }` unique
### 4.7 `recommendation` (MVP 3~5 공용 결과 캐시)
```ts
type RecommendationType =
| "similar-player" // MVP 3
| "champion-recommendation" // MVP 4
| "llm-feedback"; // MVP 5
interface Recommendation extends MongooseTimestamps {
puuid: string;
queueId: number;
type: RecommendationType;
featureSchemaVersion: number;
profileUpdatedAt: Date; // 어떤 프로필 기준으로 생성됐는지 — 프로필 갱신 시 stale 판정
result: Record<string, unknown>; // type별 결과 구조 (DTO는 shared에 정의)
evidence: Record<string, unknown>; // 근거 지표 스냅샷 (LLM 입력·UI 근거 표시)
generatedAt: Date;
}
```
- index: `{ puuid: 1, queueId: 1, type: 1, generatedAt: -1 }`
### 4.8 `champion_style_profile` (MVP 4)
```ts
interface ChampionStyleProfile extends MongooseTimestamps {
championId: number;
role: TeamPosition;
patch: string; // '26.13' 또는 'ALL'
source: "manual-taxonomy" | "derived-from-matches";
style: Record<string, number>; // metricId → 0~1
vector: number[];
featureSchemaVersion: number;
sampleGameCount?: number; // derived일 때만
}
```
- index: `{ championId: 1, role: 1, patch: 1, featureSchemaVersion: 1 }` unique
---
## 5. Feature Registry (`packages/shared`)
api(추출/집계)와 web(레이더 차트 축 라벨/순서)이 **같은 정의를 import**한다. 벡터 차원의 단일 진실 공급원.
### 5.1 구조
```ts
// packages/shared/src/feature-registry.ts
export const FEATURE_SCHEMA_VERSION = 1; // MVP 2에서 2로 bump (§11)
export type MetricDirection = "higherIsBetter" | "lowerIsBetter" | "neutral";
export type Role = "TOP" | "JUNGLE" | "MIDDLE" | "BOTTOM" | "UTILITY";
// 주의: DB 스키마의 TeamPosition(apps/api .../schemas/common.ts)과 값이 같아야 한다
export interface MetricDefinition {
id: string; // 예: 'killParticipation'
label: string; // UI 표시용 한국어 라벨
direction: MetricDirection; // 강점/약점 판정용. 벡터 값 자체는 반전하지 않는다
// scalar: 매치당 값 하나. ratio: 매치엔 {id}Numerator/{id}Denominator 저장,
// rate는 profile builder가 Σ분자/Σ분모로 계산 (§11.3)
kind: "scalar" | "ratio";
// 유사도 벡터·레이더 차트 포함 여부. insight 지표(§11.6~7)는 false
includeInVector: boolean;
// role별 min-max clipping baseline. 정규화: clamp((raw - min) / (max - min), 0, 1)
// ratio 지표는 rate가 이미 0~1이므로 baseline 생략 가능
baseline?: Record<Role, { min: number; max: number }>;
}
export const METRICS: MetricDefinition[] = [
/* 아래 5.2 순서대로. MVP 1은 전부 kind: 'scalar', includeInVector: true */
];
export const VECTOR_DIMENSION = METRICS.filter(
(metric) => metric.includeInVector,
).length;
```
### 5.2 MVP 1 지표 (12차원, match detail만으로 계산)
Match-V5 응답의 `info.participants[]`에는 `challenges` 객체(사전 계산 지표)가 포함된다. **challenges 필드가 있으면 우선 사용하고, 없으면 수동 계산으로 fallback**한다 (오래된 매치엔 일부 필드가 없을 수 있음).
| # | metricId | 계산식 (participant p, 분 = gameDuration/60) | challenges 대응 필드 |
| --- | ------------------------ | ------------------------------------------------ | ------------------------------------ |
| 1 | `kda` | (kills + assists) / max(deaths, 1) | `challenges.kda` |
| 2 | `killParticipation` | (kills + assists) / max(teamKills, 1) | `challenges.killParticipation` |
| 3 | `damageShare` | totalDamageDealtToChampions / 팀 합계 | `challenges.teamDamagePercentage` |
| 4 | `damagePerMin` | totalDamageDealtToChampions / 분 | `challenges.damagePerMinute` |
| 5 | `goldPerMin` | goldEarned / 분 | `challenges.goldPerMinute` |
| 6 | `csPerMin` | (totalMinionsKilled + neutralMinionsKilled) / 분 | — |
| 7 | `visionScorePerMin` | visionScore / 분 | `challenges.visionScorePerMinute` |
| 8 | `wardsKilledPerMin` | wardsKilled / 분 | — |
| 9 | `controlWardsPlaced` | 게임당 제어 와드 설치 수 | `challenges.controlWardsPlaced` |
| 10 | `deathsPerMin` | deaths / 분 (direction: lowerIsBetter) | — |
| 11 | `objectiveParticipation` | (dragon + baron + riftHerald takedown) / 게임 | `challenges.dragonTakedowns` 등 합산 |
| 12 | `soloKills` | 게임당 솔로킬 수 (공격성 proxy) | `challenges.soloKills` |
### 5.3 정규화와 그 한계 (문서화 필수)
- MVP 1: role별 baseline min-max clipping → 0~1. baseline 상수는 registry에 하드코딩하며 초기값은 대략적인 상식값으로 시작한다 (예: MIDDLE `csPerMin` min 4.0 / max 9.5, UTILITY `csPerMin` min 0 / max 2.5). 각 baseline에 `// TODO: MVP 3에서 인구 percentile로 교체` 주석을 남긴다.
- 원본 아이디어 문서 §6.4의 "role-specific percentile" 정규화는 비교 인구 데이터가 필요하므로 **MVP 3(고티어 pool 수집)에서 교체**한다.
- direction이 `lowerIsBetter`인 지표도 벡터에는 정규화 값을 그대로 저장한다 (플레이스타일 벡터는 "좋음"이 아니라 "성향 강도"를 표현). 강점/약점 판정 시에만 direction을 사용한다.
### 5.4 DTO
`packages/shared/src/dto/`에 API 요청/응답 타입 정의: `AnalysisRequestDto`, `AnalysisJobStatusDto`, `PlayerAnalysisDto` (§8의 스펙과 1:1). web은 이 타입으로 fetch 응답을 다룬다.
---
## 6. Riot 모듈 (`apps/api/src/modules/riot`)
### 6.1 `riot.types.ts`
```ts
export type RiotPlatformRoute = 'kr' | 'jp1' | 'na1' | 'euw1' | /* 필요 시 확장 */;
export type RiotRegionalRoute = 'asia' | 'americas' | 'europe' | 'sea';
export function toRegionalRoute(platform: RiotPlatformRoute): RiotRegionalRoute;
```
MVP 1은 `kr`/`asia`만 실사용하지만 타입은 위처럼 잡는다.
### 6.2 `riot-api.client.ts`
fetch 기반, API key는 `SecretService.get('RIOT_API_KEY')`. 메서드:
| 메서드 | endpoint | route |
| --------------------------------------------- | ----------------------------------------------------------- | -------- |
| `getAccountByRiotId(gameName, tagLine)` | `/riot/account/v1/accounts/by-riot-id/{gameName}/{tagLine}` | regional |
| `getSummonerByPuuid(puuid)` | `/lol/summoner/v4/summoners/by-puuid/{puuid}` | platform |
| `getLeagueEntriesByPuuid(puuid)` | `/lol/league/v4/entries/by-puuid/{puuid}` | platform |
| `getMatchIds(puuid, { queue, start, count })` | `/lol/match/v5/matches/by-puuid/{puuid}/ids` | regional |
| `getMatch(matchId)` | `/lol/match/v5/matches/{matchId}` | regional |
| `getMatchTimeline(matchId)` | `/lol/match/v5/matches/{matchId}/timeline` (MVP 2) | regional |
구현 시 실제 endpoint 경로는 Riot Developer Portal API Reference에서 재확인한다. 404(계정 없음)는 도메인 에러로 매핑해 API 응답에서 사용자 친화적으로 처리.
**Development key는 24시간마다 만료된다.** 401/403 응답은 재시도하지 말고 "API key 만료/무효" 도메인 에러로 매핑해 잡을 즉시 실패시키고, 에러 메시지에 키 갱신(개발자 포털 → Infisical `RIOT_API_KEY` 업데이트) 안내를 담는다.
### 6.3 Rate limiter
- development key 기준: 20 req/1s, 100 req/2min — 두 윈도우를 모두 지키는 인메모리 토큰버킷/슬라이딩 윈도우를 클라이언트 내부에 내장
- 429 응답 시 `Retry-After` 헤더를 존중해 대기 후 재시도 (최대 3회, exponential backoff)
- 5xx는 짧은 backoff 후 재시도, 4xx(429 제외)는 즉시 실패
- 단일 프로세스 전제의 인메모리 구현. **worker 분리 시 Redis 기반(기존 `RedisService` 활용)으로 교체해야 함을 주석으로 명시**
### 6.4 수집 캐시 규칙
- 이미 `riot_match`에 존재하는 matchId는 **재호출 금지** (저장 전 `exists` 확인)
- account/summoner/league는 `account` 문서의 `*FetchedAt`이 일정 시간(예: 1시간) 이내면 재호출 생략
---
## 7. Analysis 파이프라인 (`apps/api/src/modules/analysis`)
### 7.1 의존성 추가
- `bullmq`, `@nestjs/bullmq` 를 `apps/api`에 추가
- BullMQ는 자체 Redis 연결(ioredis)을 관리한다 — 기존 `RedisModule`(node-redis)과 **별개 연결**로 공존시킨다. 연결 옵션은 SecretService의 `REDIS_URL`에서 파싱해 BullMQ `connection`에 전달하는 factory를 만든다.
### 7.2 큐와 잡
큐 이름 `analysis`, 잡 하나가 전체 파이프라인을 순차 실행한다 (스테이지별 잡 분리는 하지 않는다 — MVP에선 단순함 우선). 각 스테이지 진입/진행 시 `analysis_job` 문서를 갱신한다.
```text
stage 1. resolve-account : account-v1 → puuid, summoner-v4, league-v4 → account upsert, job.puuid 기록
stage 2. fetch-match-ids : match-v5 ids (queue=420, count=요청값[기본 20, 최대 50])
stage 3. fetch-match-details: 미보유 matchId만 상세 조회 → riot_match 저장
제외: gameDuration < 300초(remake), queueId ≠ 420
진행률 progress.fetchedMatches/totalMatches 갱신
stage 4. extract-features : 각 매치에서 해당 puuid participant 추출 → §5 registry 기반 계산
→ player_match_feature upsert (featureSchemaVersion 포함)
confidence: 기본 1.0, teamPosition 빈 값이면 0.5, 20분 미만 게임 0.8
stage 5. build-profile : 최근 N게임 feature를 confidence 가중 평균으로 집계
mainRole = teamPosition 최빈값, championPool 집계
→ player_profile upsert, account.lastAnalyzedAt 갱신
완료: status=completed / 실패: status=failed + error 기록 (스테이지 단위 try/catch)
```
### 7.3 중복 요청 처리
동일 (gameName, tagLine)에 대해 `queued`/`processing` 상태의 잡이 이미 있으면 새 잡을 만들지 않고 기존 jobId를 반환한다.
### 7.4 멱등성과 엣지 케이스
- 모든 스테이지는 **재실행해도 안전**해야 한다 (BullMQ 재시도 대비): riot_match는 존재 확인 후 스킵, feature/profile은 upsert. BullMQ `attempts`는 2로 시작
- **랭크 게임이 없는 계정**: stage 2에서 matchId 0건이면 잡을 `failed`가 아니라 `completed`로 끝내되 profile을 만들지 않고, 결과 API가 "분석할 랭크 게임이 없음"을 반환하도록 한다
- **표본 부족** (유효 게임 5건 미만): profile은 생성하되 confidence를 크게 감점 (예: `sampleGameCount / 5` 상한 1.0)하고, 프론트에 "표본 부족" 경고를 표시한다
- 개별 매치 조회 실패는 잡 전체를 실패시키지 않는다 — 해당 matchId만 건너뛰고 progress에 반영, 마지막에 성공 매치 수 기준으로 진행
---
## 8. REST API (`apps/api`)
전역 prefix `/api`. DTO는 `packages/shared`에서 import.
### 8.1 `POST /api/analysis/request`
```jsonc
// 요청
{ "gameName": "Hide on bush", "tagLine": "KR1", "platform": "kr", "matchCount": 20 }
// 응답 202
{ "jobId": "...", "status": "queued" }
```
검증: gameName/tagLine 필수(공백 트림, 길이 제한 — Riot ID 규격 gameName 3~16자·tagLine 3~5자 안팎), matchCount 1~50 clamp, platform 기본 `kr`. NestJS 전역 `ValidationPipe` + class-validator DTO로 처리하고, 알 수 없는 필드는 strip한다.
### 8.2 `GET /api/analysis/jobs/:jobId`
```jsonc
{
"jobId": "...",
"status": "processing",
"stage": "fetch-match-details",
"puuid": "...", // resolve 후부터 포함 — web이 완료 시 이 값으로 결과 조회
"progress": { "fetchedMatches": 12, "totalMatches": 20 },
"error": null,
}
```
### 8.3 `GET /api/players/:puuid/analysis/latest`
```jsonc
{
"account": { "gameName": "...", "tagLine": "...", "profileIconId": 1234, "tiers": [ ... ] },
"profile": {
"mainRole": "MIDDLE",
"queueId": 420,
"sampleGameCount": 18,
"championPool": [ { "championId": 103, "games": 6, "wins": 4 } ],
"playstyle": { "kda": 0.62, "killParticipation": 0.71, ... }, // metricId → 0~1
"featureSchemaVersion": 1,
"confidence": 0.93
},
"strengths": [ { "metricId": "killParticipation", "value": 0.71 } ], // direction 반영 전체 지표, 강점 순 정렬
"weaknesses": [ { "metricId": "visionScorePerMin", "value": 0.22 } ], // direction 반영 전체 지표, 약점 순 정렬
"updatedAt": "..."
}
```
강점/약점 판정: direction이 `lowerIsBetter`인 지표는 (1 - value)로 뒤집어 정렬에 사용. 응답은 계산 가능한 모든 registry 지표를 포함하며, 대시보드는 label/description과 함께 표시한다. profile이 없으면 404.
---
## 9. Frontend (`apps/web`)
### 9.1 셋업
- Vite React 템플릿 잔재(hero.png, 데모 App.tsx 등) 정리
- 의존성 추가: `react-router-dom`, `recharts`, `@persona-lenz/shared`(workspace)
- `vite.config.ts`에 dev proxy: `/api` → `http://localhost:3000` (API에 CORS 설정 불필요)
- `@persona-lenz/shared`는 dist 소비 원칙을 유지한다. 현재 shared dist가 CommonJS로 빌드되므로 Vite dev 환경에서는 `optimizeDeps.include: ['@persona-lenz/shared']`로 사전 번들링해 브라우저 ESM named import 오류를 피한다.
### 9.2 화면 (3개)
1. **홈 `/`**: gameName + tagLine 입력 폼 → `POST /api/analysis/request` → `/analysis/:jobId`로 이동
2. **진행 `/analysis/:jobId`**: 2초 간격 폴링. stage/진행률 표시. `completed`가 되면 응답의 puuid로 `/players/:puuid`로 이동. `failed`면 에러와 재시도 버튼. 재시도는 홈에서 저장한 직전 `AnalysisRequestDto`를 `sessionStorage`에서 찾아 새 `POST /api/analysis/request`를 보낸다. 저장값이 없으면 홈으로 이동해 다시 입력하게 한다.
3. **대시보드 `/players/:puuid`**:
- 계정 요약 (Riot ID, 티어, mainRole, 분석 게임 수. 표본 부족 시 경고 배지 — §7.4)
- **레이더 차트** (recharts `RadarChart`): 축 순서/라벨은 shared feature registry의 `METRICS` 순서·`label` 사용, 값은 `profile.playstyle`
- 강점/약점 Top 3 카드 (metricId → registry label로 표시)
- championPool 요약 — championId → 이름/이미지는 **Data Dragon 정적 CDN**(`ddragon.leagueoflegends.com`)에서 web이 직접 fetch (API key 불필요·정책상 허용). 버전 목록 → 최신 버전 champion.json을 로드해 매핑, localStorage 캐시. 캐시는 best-effort로만 사용하며 storage 제한/쿼터 오류가 나도 CDN fetch 자체는 계속 시도한다.
### 9.3 스타일
MVP 1은 기능 검증이 목적이므로 과한 디자인 시스템 도입 없이 단정한 다크 테마 CSS 정도로 유지한다.
### 9.4 Riot 법적 고지 (푸터에 상시 표시)
> persona-lenz is not endorsed by Riot Games and does not reflect the views or opinions of Riot Games or anyone officially involved in producing or managing Riot Games properties. Riot Games and all associated properties are trademarks or registered trademarks of Riot Games, Inc.
외부 Data Dragon 이미지 요청에 `/players/:puuid` 경로가 referrer로 전달되지 않도록 web HTML에 `Referrer-Policy: no-referrer`에 해당하는 `<meta name="referrer" content="no-referrer" />`를 둔다.
### 9.5 MVP 1 구현 상태
- T0.4~T6 구현은 완료됐다. 각 작업은 커밋 단위로 분리되어 있으며 주요 커밋은 §10 표에 기록한다.
- T6 web 수동 E2E는 Codex 환경에서 임시 mock API + headless Chrome CDP로 검증했다: 홈, 진행, 실패 재시도 버튼, 대시보드 데스크톱, 대시보드 모바일, 콘솔 에러 없음. 실 Riot 계정 E2E는 §10.0의 MongoDB/Redis/Infisical 시크릿 체크리스트가 완료된 환경에서 §10.2 순서로 별도 실행해야 한다.
- MVP 1 결과 URL은 현재 스펙대로 `/players/:puuid`를 사용한다. PUUID는 안정적인 식별자이므로 공개 공유 URL/분석 로그/외부 referrer 정책을 바꾸는 단계에서는 opaque analysis id 또는 share token으로 교체할지 별도 제품 결정을 해야 한다.
---
## 10. 작업 순서와 검증
각 작업은 "빌드 통과 + 테스트 통과 + 커밋" 단위로 마무리한다. 커밋 메시지는 영어 명령형 한 줄.
### 10.0 시작 전 체크리스트
**사용자(사람)가 먼저 해야 하는 것** — 이것 없이는 E2E가 안 되지만, T0.4~T5 구현·단위 테스트는 진행 가능:
- [ ] MongoDB Atlas dev 클러스터 생성 (M0 가능)
- [ ] Infisical dev 환경에 등록: `RIOT_API_KEY`, `MONGODB_CONNECTION_STRING`, `REDIS_URL`, `MONGODB_AUTO_INDEX=true`
- [ ] 현재 작업 트리를 베이스 커밋으로 고정 (스키마·문서·의존성이 미커밋 상태)
**Codex 개발 환경 노트**:
- Infisical에 접근할 수 없는 환경에서는 `SECRET_SOURCE=env`로 실행하면 `SecretService`가 process.env를 그대로 사용한다 (`NODE_ENV=dev SECRET_SOURCE=env nest start` + 로컬 env 주입). 단위 테스트는 시크릿 불필요
- `@persona-lenz/shared`는 **dist를 통해 소비**된다 (`main: ./dist/index.js`). shared 수정 후 api/web에 반영하려면 `pnpm --filter @persona-lenz/shared build` 필요. 워치 개발 시 shared에 `tsc --watch`를 병행하거나 매 변경 후 재빌드
- shared에는 테스트 러너가 없다. registry 단위 테스트는 shared에 jest를 추가하거나, 간단히 **api의 jest에서 shared를 import한 spec**으로 작성해도 된다 (후자 권장 — 셋업 최소화)
| 순서 | 작업 | 완료 기준 |
| -------- | ----------------------------------------------- | -------------------------------------------------------------------------- |
| ~~T0.1~3~~ | ~~Phase 0 정리 (§3)~~ + ~~DB 스키마 8종 (§4)~~ | **완료 — Claude가 구현** (스키마·레지스트리·테스트 포함) |
| ~~T0.4~~ | ~~AppModule 배선 (§3)~~ | **완료 — `34ae204`**. `pnpm build` 전체 통과, `GET /api/health` 200 |
| ~~T1~~ | ~~shared: feature registry + DTO (§5)~~ | **완료 — `1f2805b`**. shared 빌드 통과, registry 단위 테스트 |
| ~~T3~~ | ~~riot 모듈: client + rate limiter (§6)~~ | **완료 — `256d776`**. rate limiter/client fetch mock 테스트 |
| ~~T4~~ | ~~analysis 파이프라인 + BullMQ 배선 (§7)~~ | **완료 — `770c198`**. feature extraction/profile aggregation 테스트 |
| ~~T5~~ | ~~REST API 3종 (§8)~~ | **완료 — `e1164e0`**. e2e(supertest): 요청 검증, 404 케이스, Riot mock |
| ~~T6~~ | ~~web 3화면 (§9)~~ | **완료 — `ad1a775`**. `pnpm --filter web build` 통과, mock API 수동 E2E |
| ~~T7~~ | ~~문서 갱신~~ | **완료 — 본 문서 갱신**. MVP 1 실제 구현 상태와 차이점 반영 |
### 10.1 Feature extraction 테스트 fixture
- 개발 중 실제 Match-V5 응답 1건을 `apps/api/test/fixtures/match-v5-sample.json`으로 저장 (dev key로 1회 조회. **응답에 API key는 포함되지 않지만 puuid 등이 있으므로 fixture는 커밋 전 내용 확인**)
- fixture 기반으로 12개 지표 계산값을 스냅샷/명시값으로 검증. challenges 필드가 없는 케이스(필드 삭제한 사본)도 fallback 경로 테스트
### 10.2 수동 E2E 시나리오 (최종 검증)
1. §10.0 체크리스트(Infisical 시크릿 4종 포함) 완료 확인 → `pnpm start:api:dev` + `pnpm start:web:dev`
2. 실계정 Riot ID 입력 → 진행 화면에서 스테이지 전환 확인
3. 완료 후 대시보드: 레이더 차트 12축 렌더, 강점/약점 카드, championPool 표시
4. 같은 계정 재요청 시: 기존 잡 재사용(진행 중일 때) 또는 riot_match 재호출 없이 빠르게 완료(캐시 확인)
---
## 11. MVP 2 상세 — Timeline 기반 지표
DB 스키마가 이 단계를 미리 견디도록 상세화한 스펙이다. 구현은 MVP 1 완료 후 착수한다.
### 11.0 실데이터 검증 결과 (2026-07-02, `docs/archive/timeline-data.json`)
실제 KR 랭크 게임 타임라인 1건으로 필드를 검증했다. **이 파일을 `apps/api/test/fixtures/`로 복사해 timeline feature 테스트 fixture로 사용한다.**
확인된 것 (지표 설계에 사용 가능):
- `info.frames[]` 60초 간격. `participantFrames`: `position`, `totalGold`, `currentGold`, `xp`, `level`, `minionsKilled`, `jungleMinionsKilled`, **`timeEnemySpentControlled`**(누적 CC 시간), `damageStats`(누적 딜/탱), `championStats`
- `CHAMPION_KILL`: `position`, `bounty`, **`shutdownBounty`**, `killStreakLength`, `assistingParticipantIds`(**null 가능**), **`victimDamageReceived[]`**(가해자 `participantId`별 피해 내역 → killer/assist가 아니어도 damage contributor 판정 가능), `victimTeamfightDamageDealt/Received`
- `ELITE_MONSTER_KILL`: `position`, `killerId`, `killerTeamId`, `monsterType/SubType`, `bounty`
- `BUILDING_KILL`(position/laneType/towerType), `TURRET_PLATE_DESTROYED`(position/laneType, killerId 0 가능), `CHAMPION_SPECIAL_KILL`(KILL_FIRST_BLOOD 등), `DRAGON_SOUL_GIVEN`, **`OBJECTIVE_BOUNTY_PRESTART/FINISH`**(teamId — 열세 신호), `ITEM_PURCHASED/SOLD/DESTROYED/UNDO`, `SKILL_LEVEL_UP`, `GAME_END`
- `info.participants[]`에서 participantId(1~10) ↔ puuid 매핑
제약 (모든 지표 설계가 따라야 함):
1. **프레임이 60초 간격**이라 위치 기반 "presence/roam" 지표는 게임당 표본이 1~2 프레임 수준 → 매치 단위 값은 노이즈. 비율(rate) 지표는 반드시 §11.3의 분자/분모 누적 방식을 쓴다
2. **WARD_PLACED/WARD_KILL에 좌표가 없다** → 와드 위치 기반 지표 불가, 시간 창 근사만 가능
3. **리스폰/생존 인원 추적 데이터가 없다** → "인원 수 우위/열세" 판정은 부활 시간 추정이 필요해 부정확. 인원 조건이 들어간 지표는 채택하지 않는다 (골드 diff로 대체)
4. 임의 시점의 타 플레이어 위치는 앞뒤 프레임 선형 보간 근사
5. `assistingParticipantIds`가 null인 킬 존재 → 관여 판정은 항상 killer ∪ assists ∪ damage contributor(victimDamageReceived) 순으로 폭넓게
### 11.1 Timeline 수집
- `getMatchTimeline(matchId)` 결과를 `riot_match.timeline`에 저장 (`timelineFetchedAt` 기록, 미보유분만 호출)
- 분석 잡의 stage 3(fetch-match-details)에 timeline 조회를 추가 — 매치당 호출이 2배가 되므로 rate limit 예산에 반영
### 11.2 라인 상대(lane opponent) 매칭
- 상대 팀에서 같은 `teamPosition`인 participant를 라인 상대로 지정 → `player_match_feature.laneOpponent`에 저장
- 상대를 특정할 수 없으면(teamPosition 비정상) laneOpponent 없이 diff 지표를 결측 처리하고 confidence 0.7 이하로 감점
### 11.3 지표 2계층 구조: vector 지표 vs insight 지표
지표를 전부 유사도 벡터에 넣으면 희귀 이벤트 기반의 노이즈 축이 코사인 유사도를 오염시킨다. 두 계층으로 나눈다:
- **vector 지표** (`includeInVector: true`): 게임마다 안정적으로 관측되는 핵심 스타일 축. 벡터·레이더 차트·유사 유저 탐색에 사용
- **insight 지표** (`includeInVector: false`): 희귀 이벤트 기반 비율. 강점/약점 분석, 유사 유저와의 gap 비교, LLM evidence에 사용. 벡터에는 미포함
**ratio 지표 저장 규칙**: 게임당 발생 횟수가 적은 비율 지표는 매치 단위 rate가 0/1로 튄다. 매치의 `features`에는 `{metricId}Numerator` / `{metricId}Denominator`로 **횟수만** 저장하고, rate는 profile builder가 `Σ분자/Σ분모`로 계산해 `profile`에 저장한다. registry의 `kind: 'scalar' | 'ratio'`가 이를 결정한다 (§5.1).
### 11.4 공통 빌딩 블록 (구현 순서상 지표보다 먼저)
지표들이 공유하는 파생 구조. `derived`에 저장해 재사용·검증·MVP 5 evidence에 쓴다.
- **fightCluster**: CHAMPION_KILL 이벤트를 시간 ≤15초, 거리 ≤3000 기준으로 연결(transitive)해 묶은 교전. 참여자 = killer ∪ assists ∪ victim ∪ victimDamageReceived의 챔피언 participantId. opener = 첫 킬의 killer/assists/최대 피해 기여자. cleanup = 마지막 킬 ±5초 관여자. 3킬 이상이면 teamfight로 분류
- **objectiveWindow**: 드래곤/전령/바론 `ELITE_MONSTER_KILL` 시각 t 기준 `[t-120s, t+30s]`. 스폰 시각 계산(패치 의존)이 필요 없도록 처치 시각 기준으로 정의
- **advantageEvent 점수**: 창 내 팀 이득 비교용 가중치 상수 `ADVANTAGE_EVENT_WEIGHTS` — 킬 1.0, 플레이트 0.5, 타워 1.5, 드래곤/전령 1.5, 바론 3.0 (registry 옆에 정의, 튜닝 대상)
- **맵 존 상수**: SR 좌표 (0,0)~(약 15000,15000). 존: 양 팀 base, 라인 축 3개(축 ±1500), 강가 밴드, 정글 사분면 4개, 오브젝트 pit(드래곤/바론 반경 ~2500). 데스 위치 분류·roam 판정·pit presence에 공용
- **roamFrame**: 8~14분 프레임 중 내 위치가 (배정 라인 존 ∪ 우리 base) 밖인 프레임. **JUNGLE role은 roam 지표 전체를 결측 처리** (정글은 원래 전맵이 활동 영역)
- **derived 저장물**: `deathEvents: [{t, x, y, zone, shutdownBountyGiven, nearestAllyDistanceApprox}]`, `fightClusters` 요약, `objectiveWindows` 요약
### 11.5 vector 지표 (timeline 14개, MVP 1의 12개와 합쳐 `FEATURE_SCHEMA_VERSION = 2`, 총 26차원)
| # | metricId | kind | 계산 |
| --- | --------------------------------------- | ------ | -------------------------------------------------------------------------------------------- |
| 13 | `goldDiffAt10` | scalar | 10분 프레임에서 라인 상대와 totalGold 차이 |
| 14 | `goldDiffAt14` | scalar | 14분 프레임 동일 |
| 15 | `csDiffAt10` | scalar | (minionsKilled + jungleMinionsKilled) 차이 @10분 |
| 16 | `xpDiffAt10` | scalar | xp 차이 @10분 |
| 17 | `deathsBefore14` | scalar | t < 14분 CHAMPION_KILL 중 victimId == 나 |
| 18 | `killParticipationBefore14` | scalar | 14분 이전 (킬+어시) / 팀 킬 |
| 19 | `earlyWardsPerMin` | scalar | 14분 이전 WARD_PLACED(creatorId == 나) / 14 |
| 20 | `objectivePreWardRate` | ratio | objectiveWindow(우리 팀 처치) 중 `[t-60s, t]`에 내 와드 설치가 있었던 비율 (시간 근사) |
| 21 | `eliteObjectiveParticipationRate` | ratio | 우리 팀 ELITE_MONSTER_KILL 중 내가 killer/assist인 비율 |
| 22 | `isolationTendency` | scalar | 8~20분 프레임에서 가장 가까운 아군과의 평균 거리 (스플릿 성향) |
| 23 | `teamfightFirstEngagementParticipationRate` | ratio | teamfight fightCluster 중 내가 opener에 포함된 비율 — 교전을 여는 성향 |
| 24 | `teamfightCleanupKillParticipationRate` | ratio | teamfight fightCluster 중 내가 cleanup에 포함된 비율 — 마무리/추격 성향 |
| 25 | `deathWithShutdownBountyGivenRate` | ratio | 내 사망 중 `shutdownBounty > 0`으로 상대에게 현상금을 준 비율 — 리드 상태 리스크 관리 |
| 26 | `ccTimePerMinute` | scalar | `timeEnemySpentControlled` 최종 누적값 / 게임 분 — CC/유틸리티 기여 |
23~26은 원안 검토에서 승격한 것: 매 게임 안정적으로 관측되고(교전은 게임당 수 회, 사망·CC는 상시), 스타일 축으로서 해석이 명확하다. 특히 25는 `shutdownBounty` 필드가 실데이터에 확인되어 정확·단순하게 계산된다.
### 11.6 insight 지표 1차 (MVP 2에서 함께 구현, 벡터 미포함 — 별도 표기 없으면 kind: ratio)
| metricId | 분모 / 분자 | 해석 · 비고 |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `objectiveFightOpeningParticipationRate` | objectiveWindow 내 첫 fightCluster 수 / 그중 내가 opener인 수 | 오브젝트 타이밍에 물꼬를 트는 성향 (원안 2·6 통합) |
| `objectiveFightOpeningConvertedToObjectiveRate` | 내가 opener였던 objectiveWindow 교전 수 / 그중 이후 90초 내 우리 팀이 해당 오브젝트를 획득한 수 | 싸움을 열어 오브젝트로 연결 (원안 3) |
| `preObjectivePitPresenceRate` | 우리 팀 objectiveWindow 수 / 그중 처치 전 90초 프레임에서 내 위치가 pit·강가 반경 내였던 수 | 오브젝트 선점 포지셔닝 (원안 10). 프레임 1~2개 근사 |
| `preObjectivePickParticipationRate` | 우리 팀 objectiveWindow 수 / 그중 처치 전 120초 내 적 처형에 내가 관여한 수 | 오브젝트 전에 숫자 우위 창출 (원안 7 재정의 — 스폰 시각 불필요) |
| `deathFollowedByTeamLossRate` | 내 사망 수 / 그중 이후 60초 내 상대 advantageEvent 점수 > 우리 점수인 수 | 내 죽음이 팀 손해로 번지는 정도 (원안 11 단순화 — 가중합 Index 대신 비율) |
| `deathTradedForTeamAdvantageRate` | 내 사망 수 / 그중 ±30초 내 우리 advantageEvent 점수 > 상대 점수인 수 | 죽었지만 팀 이득을 만든 사망 (원안 16) |
| `deathWhileIsolatedFromNearestAllyRate` | 내 사망 수 / 그중 사망 시점(프레임 보간) 최근접 아군 거리 > 4000인 수 | 고립사 비율 (원안 17). 보간 근사 명시 |
| `earlyDeficitRecoveryRate` | goldDiffAt10 < -500인 게임 수 / 그중 20분 diff ≥ 0으로 복구한 게임 수 | 초반 열세 복구 (원안 13 단순화 — 게임당 0/1, 프로필 합산) |
| `laneLeadConversionRate` | goldDiffAt10 > +500인 게임 수 / 그중 10~20분 우리 팀 첫 타워 또는 첫 오브젝트에 내가 관여한 게임 수 | 라인 리드를 팀 이득으로 전환 (원안 8 단순화) |
| `roamConvertedToTeamAdvantageRate` | roamFrame 에피소드 수 / 그중 이후 90초 내 내가 관여한 advantageEvent 발생 수 | 로밍의 실효성 (원안 9). 60초 프레임 해상도 한계 명시 |
| `shutdownGoldCollectedPerGame` | 게임당 내가 killer인 킬의 shutdownBounty 합 (**kind: scalar**) | 현상금 사냥 성향 — vector 지표 25(`deathWithShutdownBountyGivenRate`)의 쌍 |
| `platePresenceParticipationRate` | 우리 팀 TURRET_PLATE_DESTROYED 수 / 그중 직전 프레임 내 위치가 해당 라인 존 내였던 수 | 플레이트 관여 — killerId가 0인 플레이트가 있어 위치 근사가 유일한 방법 |
| `objectiveBountyComebackParticipationRate` | OBJECTIVE_BOUNTY 활성(우리 팀 열세 공식 신호) 구간의 우리 팀 advantageEvent 수 / 그중 내 관여 수 | comeback_resilience 축 — Riot 공식 열세 신호를 데이터 근거로 사용 |
### 11.7 insight 지표 2차 (백로그 — 1차 안정화 후)
| metricId | 요약 | 비고 |
| -------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| `lateCarryPickoffParticipationRate` | 20분 이후 적 딜러 상위 2명(프레임 damageStats 기준) 사망 중 내가 killer/assist/damage contributor | 원안 4 수정 — "고립" 조건은 보간 근사라 제외 |
| `pickoffConvertedToMajorObjectiveRate` | 위 pickoff 후 90초 내 우리 팀 바론/드래곤/타워 획득 비율 | 원안 5 |
| `deficitFightInitiationWinRate` | 직전 프레임 팀 골드 diff < -1000에서 내가 opener인 fightCluster 중 킬 교환 우위로 끝난 비율 | 원안 1 단순화 — 인원/오브젝트 압박 판정 제외(§11.0 제약 3) |
| `crossMapTradeAnswerRate` | 상대 오브젝트/타워 획득 후 90초 내 우리 팀 반대편 이득에 내가 관여한 비율 | 원안 15 |
| `sidePressureConvertedToMapAdvantageRate` | 14~25분 사이드 고립 프레임 묶음 중 90초 내 팀 이득으로 연결된 비율 | 원안 12 단순화 — "적 2명 근접"은 보간 근사로만 |
| `preObjectiveGroupingRate` | objectiveWindow 전 90초 프레임에서 팀 중심(아군 평균 위치)과 거리 < 2500인 비율 | 원안 19 — pitPresence(선점)와 구분되는 합류 타이밍 |
| `roamLaneResourceLossIndex` | roam 에피소드 전후 2분 내 CS/XP 증가량을 라인 상대와 비교한 손실 평균 | 원안 14 — roam 판정 위 이중 근사라 2차 |
| `visionActionConvertedToTeamAdvantageRate` | 내 WARD_PLACED/WARD_KILL 후 90초 내 우리 팀 advantageEvent 발생 비율 | 원안 22 — 와드 좌표 없음, 시간 근사 |
### 11.8 원안 대비 조정 내역 (검토 근거 기록)
- **기각: `postRecallTempoReturnToMapScore`** — 귀환 proxy(ITEM_PURCHASED 묶음)가 사망 후 구매와 구분되지 않고, 합성 가중합이라 설명 곤란. 필요해지면 "사망이 아닌데 base 존에서 구매" 조건으로 재설계
- **기각: 인원 우위/열세 조건 전반** — 리스폰 추적 데이터가 없어 부활 시간 추정이 필요 (§11.0 제약 3). 골드 diff 조건으로 대체
- **합성 Score/Index → 단순 비율로 분해** (`earlyLaneLeadConvertedToMidGameAdvantageScore`, `earlyDeficitRecoveredByMidGameScore`, `deathCausedFollowUpTeamLossIndex`, `sideLanePressureConvertedToMapAdvantageScore`): 임의 가중합은 percentile 정규화·근거 제시(§14)와 충돌한다. 가중치가 필요한 부분은 `ADVANTAGE_EVENT_WEIGHTS` 상수 하나로 수렴
- **통합**: 원안 2+6 → `objectiveFightOpeningParticipationRate`, 원안 7 → 처치 시각 기준 재정의(스폰 시각은 패치 의존이라 회피)
- **승격**: 교전 opener/cleanup, shutdown 사망, CC 시간은 vector 지표로 (관측 빈도·해석 명확성 기준)
### 11.9 버전 bump와 재계산
- registry에 지표 추가 → `FEATURE_SCHEMA_VERSION` 2로 bump. 레이더 차트는 vector 지표 26축이 아니라 **UI 그룹(라인전/교전/오브젝트/시야/리스크) 단위로 묶어 표시**하는 것을 권장
- `analysis_job.jobType = 'feature-recompute'` 잡: `player_match_feature` 중 `featureSchemaVersion < 2` 또는 `timelineProcessed = false`인 문서를 대상으로 재계산 → 이후 해당 puuid들의 `player_profile` 재빌드
- timeline이 없는 오래된 매치는 MVP 2 지표를 결측으로 두고 confidence로 반영 (수집 불가능한 과거 데이터를 억지로 채우지 않는다)
---
## 12. MVP 3 상세 — 고티어 pool · percentile 정규화 · 유사 유저 탐색
> **컨셉 (2026-07-03 재정의)**: 이 기능은 "멘토 매칭"이 아니라 **나와 플레이스타일이 비슷한 유저 찾기**다. 목적은 따라 할 상위 티어 유저를 지정해주는 것이 아니라, "스타일은 비슷한데 왜 저 유저는 점수(티어)가 더 높거나/낮은가"라는 인사이트를 주는 것. 따라서 후보를 티어로 거르지 않고 유사도 중심으로 랭킹하며, 티어 관계(tierComparison)와 지표 우위(양방향)를 함께 제공한다. seed pool(§12.1)은 필터 조건이 아니라 **비교 후보군의 주 공급원**이다.
### 12.1 고티어 seed pool 수집
- league-v4 `challengerleagues|grandmasterleagues|masterleagues /by-queue/RANKED_SOLO_5x5`(platform route)로 엔트리 확보
- 초기 목표 pool: **150명** (Challenger 50 / GM 50 / Master 무작위 50), 각 최근 **30게임**
- rate limit 예산 (dev key 100req/2min): 유저당 약 1(ids) + 30×2(detail+timeline) ≈ 61 호출 → 150명 ≈ 9,150 호출 ≈ 3~4시간. 단 **고티어끼리는 같은 매치에 자주 등장하므로 `riot_match` 중복 제거로 실호출이 크게 줄어든다.** 백그라운드로 하룻밤 돌리는 전제. production key 승인 시 확대
- `account`에 `isSeed: true`, `seedSource`(challenger/grandmaster/master), `seedAddedAt`, `lastSeedCollectedAt` 기록
- 별도 저우선순위 BullMQ 큐 `seed-collection`(concurrency 1)로 수집. 유저 분석 잡(`analysis`)이 항상 우선하도록 rate limiter를 공유
- seed 유저도 **동일한 파이프라인**(stage 3~5)으로 `player_match_feature`/`player_profile` 생성 — 별도 코드 경로를 만들지 않는다
- **스토리지 예산 주의**: timeline 원본은 경기당 약 2MB(실측 2.3MB)라 seed 수집(중복 제거 후 수천 경기)이면 수 GB로 Atlas M0(512MB)를 초과한다. MVP 1~2(개인 계정 수십 경기)는 M0로 충분하지만, **MVP 3 착수 전에 ① 클러스터 상향 또는 ② feature 추출 완료 후 `riot_match.timeline` 원본 삭제(derived만 보존) 정책을 결정**해야 한다. ②를 대비해 재계산 잡은 timeline 부재를 결측으로 처리하도록 이미 설계되어 있다(§11.9)
### 12.2 Percentile 정규화 도입 (§5.3 TODO 해소)
- `metric_baseline` 컬렉션(§4.6)에 metricId × role × cohort × patch별 **분위값 19개**(p5~p95, 5% 간격)를 저장
- 계산: `jobType = 'baseline-computation'` 잡이 seed 유저들의 `player_match_feature.features`(raw 값)를 집계해 생성. cohort는 `MASTER_PLUS`부터, 데이터가 쌓이면 `ALL` 추가
- 정규화 v2: raw 값 → breakpoints 선형 보간으로 percentile rank(0~1). registry의 min-max baseline은 **cold start fallback**으로 유지
- 적용 결과는 `normalizationMethod: 'population-percentile'`로 기록. 유저 프로필과 seed 프로필이 **같은 baseline으로 정규화됐을 때만** 벡터 비교가 유효하므로, baseline 전환 시 전체 `player_match_feature` 재정규화 + `player_profile` 재빌드 잡을 돌린다
### 12.3 Atlas Vector Search 인덱스
`player_profile` 컬렉션에 생성 (Atlas UI 또는 Admin API). **numDimensions는 생성 시점의 `VECTOR_DIMENSION`(MVP 2 완료 기준 26 — vector 지표만, insight 지표 제외)과 일치**시키고, 차원이 바뀌면 인덱스를 재생성한다:
```json
{
"name": "player_profile_vector_index",
"type": "vectorSearch",
"fields": [
{ "type": "vector", "path": "vector", "numDimensions": 26, "similarity": "cosine" },
{ "type": "filter", "path": "mainRole" },
{ "type": "filter", "path": "queueId" },
{ "type": "filter", "path": "tier" },
{ "type": "filter", "path": "isSeed" },
{ "type": "filter", "path": "sampleGameCount" },
{ "type": "filter", "path": "featureSchemaVersion" }
]
}
```
filter로 쓰는 필드(tier, isSeed 등)가 `player_profile`에 **비정규화되어 있어야** `$vectorSearch` 단계에서 join 없이 거를 수 있다 — §4.4 스키마가 이를 전제한다.
### 12.4 유사 유저 탐색 파이프라인
```text
1. 내 player_profile 조회 (없으면 404)
2. $vectorSearch:
queryVector = 내 vector, numCandidates = 200, limit = 50
filter: { mainRole: eq 내 mainRole, queueId: eq 420,
sampleGameCount: gte 20, featureSchemaVersion: eq 현재 버전 }
※ tier/isSeed 필터 없음 — "비슷한 유저"가 목적이므로 어느 티어든 후보.
(인덱스의 tier/isSeed filter 필드는 유지 — 추후 옵션 필터용)
3. 앱 레벨 re-rank (Top 50 → Top K):
final = 0.70 * styleSim # $vectorSearch score (cosine) — 유사도가 랭킹을 지배
+ 0.18 * championPoolSim # 양쪽 championPool 상위 5개 Jaccard
+ 0.12 * recencyScore # lastMatchAt 지수 감쇠 (half-life 14일)
- lowSamplePenalty # sampleGameCount < 30이면 0.1
(tierScore 없음 — 티어는 랭킹 요소가 아니라 인사이트. mainRole은 filter로 보장)
4. 각 유사 유저에 대해 비교 계산:
- tierComparison: 내 tier 대비 higher | same | lower | unknown
- 비슷한 지표 Top 3: |내 profile[m] - 상대 profile[m]| 최소
- 상대가 앞서는 지표 Top 3 (strongerMetrics): direction 반영 gap 최대 (lowerIsBetter는 반전)
- 내가 앞서는 지표 Top 3 (weakerMetrics): 위와 대칭 — 상대가 나보다 낮은 티어일 때의 인사이트
5. recommendation 컬렉션에 캐시 (type: 'similar-player', profileUpdatedAt 기록)
→ 내 프로필이 갱신되면 stale로 보고 재계산
```
### 12.5 API / UI
- `GET /api/players/:puuid/similar-players?limit=10` — 캐시 있으면 캐시, stale이면 재계산
- 응답 항목: similarityScore, finalScore, Riot ID(표시용), tier, tierComparison, mainRole, mainChampions(top 3), sampleGameCount, similarMetrics[3], strongerMetrics[3], weakerMetrics[3]
- 대시보드에 "나와 비슷한 플레이어" 테이블 추가. 화법: "따라 하라"가 아니라 "나와 비슷한 이 유저는 이런 지표에서 차이가 난다" 유지 (§1.3, §14). 상대가 높은 티어면 strongerMetrics가, 낮은 티어면 weakerMetrics가 인사이트의 중심
- 유저 Riot ID 표시는 공개 데이터이지만, 표시 형식은 전적 사이트 관례 수준으로 유지
---
## 13. MVP 4~5 로드맵 (개요 — 착수 시 상세화)
### MVP 4: 챔피언 추천
- 챔피언 스타일 벡터: 초기엔 수동 taxonomy(주요 챔피언 ~60개), 이후 seed 유저 match data 기반 자동화. **스키마는 `champion_style_profile`(§4.8)로 이미 준비됨**
- Fit(현 스타일 유사) / Growth(약점 보완) / Stretch(폭 확장) 3종 추천 + 근거(유사도, 유사 유저 pool 등장 빈도) 표시. 결과는 `recommendation`(type: 'champion-recommendation')에 캐시
- Data Dragon 연동 (챔피언 이름/이미지, 패치별 static data)
### MVP 5: LLM 피드백
- `FeedbackGenerator` 인터페이스로 provider 추상화 (provider는 이 시점에 결정)
- 입력: 백엔드가 만든 evidence JSON만 (user profile 지표, 유사 유저와의 gap Top-N, `derived`의 데스 위치 요약). raw match JSON 입력 금지
- 출력: strict JSON schema 검증. 모든 피드백 항목은 metricId 참조 필수, 검증 실패/LLM 장애 시 rule-based fallback 문장 사용. 결과는 `recommendation`(type: 'llm-feedback')에 캐시
- 화법 규칙: 비난 금지, "다음 5게임에서 실험할 행동" 형태, 실시간 지시·MMR 추정 표현 금지
---
## 14. 부록: 원본 문서에서 계승하는 판단 기준
- **데이터 품질이 AI보다 중요하다.** feature extraction이 틀리면 앱 전체 신뢰가 무너진다. 파이프라인 안정화가 항상 우선.
- **비교군 설계가 핵심이다.** 전체 평균이 아니라 같은 포지션·유사 챔피언·비슷한 패치·충분한 sample size 기준으로 비교한다.
- **결과는 항상 근거와 함께.** "운영이 약합니다"(X) → "10분 골드 리드 게임에서 첫 전령 관여율이 유사 유저 그룹보다 낮습니다"(O).
- **추천은 단정하지 않는다.** "이 챔피언을 해야 티어가 오릅니다"(X) → "현재 스타일과 잘 맞을 가능성이 높은 후보입니다. 다음 10게임에서 비교해보세요"(O).
+147
View File
@@ -0,0 +1,147 @@
import type { MetricId, Role } from '../feature-registry';
export type AnalysisPlatformRoute =
| 'kr'
| 'jp1'
| 'na1'
| 'br1'
| 'la1'
| 'la2'
| 'euw1'
| 'eun1'
| 'tr1'
| 'ru'
| 'me1'
| 'oc1'
| 'ph2'
| 'sg2'
| 'th2'
| 'tw2'
| 'vn2';
export type AnalysisJobStatus =
| 'queued'
| 'processing'
| 'completed'
| 'failed';
export interface AnalysisRequestDto {
gameName: string;
tagLine: string;
platform?: AnalysisPlatformRoute;
matchCount?: number;
}
export interface AnalysisRequestAcceptedDto {
jobId: string;
status: Extract<AnalysisJobStatus, 'queued' | 'processing'>;
}
export interface AnalysisJobProgressDto {
fetchedMatches: number;
totalMatches: number;
}
export interface AnalysisJobStatusDto {
jobId: string;
status: AnalysisJobStatus;
stage?: string;
puuid?: string;
progress: AnalysisJobProgressDto;
error: string | null;
}
export interface TierInfoDto {
queueType: string;
tier: string;
rank: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt?: string;
}
export interface AccountSummaryDto {
gameName: string;
tagLine: string;
profileIconId: number;
tiers: TierInfoDto[];
}
export interface ChampionPoolEntryDto {
championId: number;
games: number;
wins: number;
}
export interface PlayerProfileSummaryDto {
mainRole: Role;
queueId: number;
sampleGameCount: number;
championPool: ChampionPoolEntryDto[];
playstyle: Partial<Record<MetricId, number>>;
featureSchemaVersion: number;
confidence: number;
}
export interface MetricValueDto {
metricId: MetricId;
value: number;
}
export interface PlayerAnalysisDto {
account: AccountSummaryDto;
profile: PlayerProfileSummaryDto;
strengths: MetricValueDto[];
weaknesses: MetricValueDto[];
updatedAt: string;
}
export interface SimilarPlayerRiotIdDto {
gameName: string;
tagLine: string;
}
/** 상대 유저의 티어가 내 티어 대비 어느 쪽인지. 티어 정보가 없으면 unknown. */
export type TierComparison = 'higher' | 'same' | 'lower' | 'unknown';
export interface SimilarMetricDto {
metricId: MetricId;
currentValue: number;
otherValue: number;
absoluteGap: number;
}
export interface LeadMetricDto {
metricId: MetricId;
currentValue: number;
otherValue: number;
/** direction 반영 우위 폭. 항상 양수. */
lead: number;
}
export interface SimilarPlayerDto {
displayId: string;
riotId: SimilarPlayerRiotIdDto | null;
similarityScore: number;
finalScore: number;
tier?: string;
division?: string;
leaguePoints?: number;
tierComparison: TierComparison;
mainRole: Role;
mainChampions: ChampionPoolEntryDto[];
sampleGameCount: number;
similarMetrics: SimilarMetricDto[];
/** 이 유저가 나보다 앞서는 지표 Top 3 */
strongerMetrics: LeadMetricDto[];
/** 내가 이 유저보다 앞서는 지표 Top 3 */
weakerMetrics: LeadMetricDto[];
}
export interface SimilarPlayersDto {
puuid: string;
queueId: number;
profileUpdatedAt: string;
matches: SimilarPlayerDto[];
}
+627
View File
@@ -0,0 +1,627 @@
export const FEATURE_SCHEMA_VERSION = 2;
export type MetricDirection = 'higherIsBetter' | 'lowerIsBetter' | 'neutral';
export type Role = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
export const ROLES: readonly Role[] = [
'TOP',
'JUNGLE',
'MIDDLE',
'BOTTOM',
'UTILITY',
];
export interface MetricBaselineRange {
min: number;
max: number;
}
export interface MetricDefinition {
id: string;
label: string;
description: string;
direction: MetricDirection;
kind: 'scalar' | 'ratio';
includeInVector: boolean;
baseline?: Record<Role, MetricBaselineRange>;
}
const allRoles = (
baseline: Record<Role, MetricBaselineRange>,
): Record<Role, MetricBaselineRange> => baseline;
const rateBaseline = allRoles({
TOP: { min: 0, max: 1 },
JUNGLE: { min: 0, max: 1 },
MIDDLE: { min: 0, max: 1 },
BOTTOM: { min: 0, max: 1 },
UTILITY: { min: 0, max: 1 },
});
export const METRICS = [
{
id: 'kda',
label: 'KDA',
description: '킬과 어시스트를 사망 대비 얼마나 안정적으로 만들었는지 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0.8, max: 5.0 },
JUNGLE: { min: 1.0, max: 6.0 },
MIDDLE: { min: 0.8, max: 6.0 },
BOTTOM: { min: 0.9, max: 6.5 },
UTILITY: { min: 1.0, max: 6.0 },
}),
},
{
id: 'killParticipation',
label: '킬 관여율',
description: '팀 킬 중 직접 관여한 비율로, 교전 합류와 영향력을 나타냅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0.25, max: 0.75 },
JUNGLE: { min: 0.45, max: 0.85 },
MIDDLE: { min: 0.35, max: 0.8 },
BOTTOM: { min: 0.35, max: 0.8 },
UTILITY: { min: 0.45, max: 0.85 },
}),
},
{
id: 'damageShare',
label: '팀 딜 비중',
description: '팀 전체 챔피언 피해량 중 본인이 차지한 비중입니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0.12, max: 0.32 },
JUNGLE: { min: 0.08, max: 0.25 },
MIDDLE: { min: 0.18, max: 0.38 },
BOTTOM: { min: 0.2, max: 0.42 },
UTILITY: { min: 0.03, max: 0.18 },
}),
},
{
id: 'damagePerMin',
label: '분당 챔피언 피해량',
description: '게임 시간 대비 적 챔피언에게 넣은 피해량입니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 350, max: 900 },
JUNGLE: { min: 250, max: 750 },
MIDDLE: { min: 450, max: 1000 },
BOTTOM: { min: 450, max: 1050 },
UTILITY: { min: 100, max: 450 },
}),
},
{
id: 'goldPerMin',
label: '분당 골드',
description: '분당 획득 골드로 성장 속도와 자원 확보 능력을 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 300, max: 520 },
JUNGLE: { min: 300, max: 500 },
MIDDLE: { min: 330, max: 550 },
BOTTOM: { min: 340, max: 580 },
UTILITY: { min: 180, max: 380 },
}),
},
{
id: 'csPerMin',
label: '분당 CS',
description: '분당 미니언과 몬스터 처치량으로 기본 성장 안정성을 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 4.0, max: 9.0 },
JUNGLE: { min: 4.0, max: 7.8 },
MIDDLE: { min: 4.0, max: 9.5 },
BOTTOM: { min: 4.5, max: 10.0 },
UTILITY: { min: 0.0, max: 2.5 },
}),
},
{
id: 'visionScorePerMin',
label: '분당 시야 점수',
description: '게임 시간 대비 시야 확보와 시야 기여도를 나타냅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0.3, max: 1.5 },
JUNGLE: { min: 0.5, max: 2.0 },
MIDDLE: { min: 0.3, max: 1.6 },
BOTTOM: { min: 0.3, max: 1.5 },
UTILITY: { min: 1.0, max: 4.0 },
}),
},
{
id: 'wardsKilledPerMin',
label: '분당 와드 제거',
description: '상대 시야를 얼마나 꾸준히 지웠는지 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0.0, max: 0.2 },
JUNGLE: { min: 0.02, max: 0.35 },
MIDDLE: { min: 0.01, max: 0.25 },
BOTTOM: { min: 0.01, max: 0.22 },
UTILITY: { min: 0.03, max: 0.45 },
}),
},
{
id: 'controlWardsPlaced',
label: '제어 와드 설치',
description: '제어 와드를 통한 주요 지역 시야 장악 기여도입니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 6 },
JUNGLE: { min: 0, max: 8 },
MIDDLE: { min: 0, max: 6 },
BOTTOM: { min: 0, max: 5 },
UTILITY: { min: 0, max: 10 },
}),
},
{
id: 'deathsPerMin',
label: '분당 사망',
description: '게임 시간 대비 사망 빈도입니다. 낮을수록 안정적인 지표입니다.',
direction: 'lowerIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0.0, max: 0.35 },
JUNGLE: { min: 0.0, max: 0.32 },
MIDDLE: { min: 0.0, max: 0.35 },
BOTTOM: { min: 0.0, max: 0.38 },
UTILITY: { min: 0.0, max: 0.45 },
}),
},
{
id: 'objectiveParticipation',
label: '오브젝트 관여',
description: '드래곤, 전령, 바론, 포탑 등 주요 오브젝트 관여도를 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 3 },
JUNGLE: { min: 0, max: 5 },
MIDDLE: { min: 0, max: 4 },
BOTTOM: { min: 0, max: 4 },
UTILITY: { min: 0, max: 4 },
}),
},
{
id: 'soloKills',
label: '솔로킬',
description: '아군 도움 없이 만든 킬로 라인전 압박과 개인 교전력을 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 4 },
JUNGLE: { min: 0, max: 3 },
MIDDLE: { min: 0, max: 4 },
BOTTOM: { min: 0, max: 3 },
UTILITY: { min: 0, max: 1.5 },
}),
},
{
id: 'goldDiffAt10',
label: '10분 골드 차이',
description: '10분 시점 상대 라이너와의 골드 격차입니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: -3_000, max: 3_000 },
JUNGLE: { min: -3_000, max: 3_000 },
MIDDLE: { min: -3_000, max: 3_000 },
BOTTOM: { min: -3_000, max: 3_000 },
UTILITY: { min: -2_000, max: 2_000 },
}),
},
{
id: 'goldDiffAt14',
label: '14분 골드 차이',
description: '14분 시점 상대 라이너와의 골드 격차입니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: -4_000, max: 4_000 },
JUNGLE: { min: -4_000, max: 4_000 },
MIDDLE: { min: -4_000, max: 4_000 },
BOTTOM: { min: -4_000, max: 4_000 },
UTILITY: { min: -2_500, max: 2_500 },
}),
},
{
id: 'csDiffAt10',
label: '10분 CS 차이',
description: '10분 시점 상대 라이너와의 CS 격차입니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: -60, max: 60 },
JUNGLE: { min: -50, max: 50 },
MIDDLE: { min: -60, max: 60 },
BOTTOM: { min: -60, max: 60 },
UTILITY: { min: -20, max: 20 },
}),
},
{
id: 'xpDiffAt10',
label: '10분 경험치 차이',
description: '10분 시점 상대 라이너와의 경험치 격차입니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: -2_000, max: 2_000 },
JUNGLE: { min: -2_000, max: 2_000 },
MIDDLE: { min: -2_000, max: 2_000 },
BOTTOM: { min: -2_000, max: 2_000 },
UTILITY: { min: -1_500, max: 1_500 },
}),
},
{
id: 'deathsBefore14',
label: '14분 전 사망',
description: '라인전 구간인 14분 전 사망 횟수입니다. 낮을수록 안정적입니다.',
direction: 'lowerIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 6 },
JUNGLE: { min: 0, max: 5 },
MIDDLE: { min: 0, max: 6 },
BOTTOM: { min: 0, max: 6 },
UTILITY: { min: 0, max: 7 },
}),
},
{
id: 'killParticipationBefore14',
label: '14분 전 킬 관여율',
description: '14분 전 팀 킬에 얼마나 관여했는지 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 1 },
JUNGLE: { min: 0, max: 1 },
MIDDLE: { min: 0, max: 1 },
BOTTOM: { min: 0, max: 1 },
UTILITY: { min: 0, max: 1 },
}),
},
{
id: 'earlyWardsPerMin',
label: '초반 분당 와드',
description: '초반 구간의 분당 와드 설치량으로 라인전 시야 습관을 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 1 },
JUNGLE: { min: 0, max: 1.2 },
MIDDLE: { min: 0, max: 1 },
BOTTOM: { min: 0, max: 1 },
UTILITY: { min: 0, max: 2 },
}),
},
{
id: 'objectivePreWardRate',
label: '오브젝트 전 와드율',
description: '주요 오브젝트 전 사전 시야를 준비한 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: true,
baseline: allRoles({
TOP: { min: 0, max: 1 },
JUNGLE: { min: 0, max: 1 },
MIDDLE: { min: 0, max: 1 },
BOTTOM: { min: 0, max: 1 },
UTILITY: { min: 0, max: 1 },
}),
},
{
id: 'eliteObjectiveParticipationRate',
label: '에픽 오브젝트 관여율',
description: '드래곤, 전령, 바론 등 에픽 오브젝트에 관여한 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: true,
baseline: allRoles({
TOP: { min: 0, max: 1 },
JUNGLE: { min: 0, max: 1 },
MIDDLE: { min: 0, max: 1 },
BOTTOM: { min: 0, max: 1 },
UTILITY: { min: 0, max: 1 },
}),
},
{
id: 'isolationTendency',
label: '고립 성향',
description: '아군과 떨어진 위치에서 플레이한 정도입니다. 낮을수록 팀과 가깝습니다.',
direction: 'lowerIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 8_000 },
JUNGLE: { min: 0, max: 8_000 },
MIDDLE: { min: 0, max: 8_000 },
BOTTOM: { min: 0, max: 8_000 },
UTILITY: { min: 0, max: 8_000 },
}),
},
{
id: 'teamfightFirstEngagementParticipationRate',
label: '한타 첫 교전 관여율',
description: '한타가 열리는 첫 구간에 얼마나 빠르게 관여했는지 봅니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: true,
baseline: allRoles({
TOP: { min: 0, max: 1 },
JUNGLE: { min: 0, max: 1 },
MIDDLE: { min: 0, max: 1 },
BOTTOM: { min: 0, max: 1 },
UTILITY: { min: 0, max: 1 },
}),
},
{
id: 'teamfightCleanupKillParticipationRate',
label: '한타 마무리 관여율',
description: '한타 후반 추격, 정리 킬, 마무리 과정의 관여율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: true,
baseline: allRoles({
TOP: { min: 0, max: 1 },
JUNGLE: { min: 0, max: 1 },
MIDDLE: { min: 0, max: 1 },
BOTTOM: { min: 0, max: 1 },
UTILITY: { min: 0, max: 1 },
}),
},
{
id: 'deathWithShutdownBountyGivenRate',
label: '현상금 사망률',
description: '현상금을 가진 상태에서 사망한 비율입니다. 낮을수록 좋습니다.',
direction: 'lowerIsBetter',
kind: 'ratio',
includeInVector: true,
baseline: allRoles({
TOP: { min: 0, max: 1 },
JUNGLE: { min: 0, max: 1 },
MIDDLE: { min: 0, max: 1 },
BOTTOM: { min: 0, max: 1 },
UTILITY: { min: 0, max: 1 },
}),
},
{
id: 'ccTimePerMinute',
label: '분당 군중제어 시간',
description: '분당 적에게 제공한 군중제어 시간으로 교전 제어력을 봅니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: true,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 10 },
JUNGLE: { min: 0, max: 12 },
MIDDLE: { min: 0, max: 10 },
BOTTOM: { min: 0, max: 8 },
UTILITY: { min: 0, max: 15 },
}),
},
{
id: 'objectiveFightOpeningParticipationRate',
label: '오브젝트 교전 개시 관여율',
description: '오브젝트 주변 교전이 시작될 때 관여한 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'objectiveFightOpeningConvertedToObjectiveRate',
label: '오브젝트 교전 개시 전환율',
description: '오브젝트 교전 개시가 실제 오브젝트 획득으로 이어진 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'preObjectivePitPresenceRate',
label: '오브젝트 전 강가 선점률',
description: '오브젝트 등장 전 강가와 둥지 주변에 먼저 자리 잡은 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'preObjectivePickParticipationRate',
label: '오브젝트 전 픽 관여율',
description: '오브젝트 직전 상대를 먼저 끊어낸 상황에 관여한 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'deathFollowedByTeamLossRate',
label: '사망 후 팀 손실률',
description: '본인 사망 뒤 팀이 오브젝트나 구조물을 잃은 비율입니다. 낮을수록 좋습니다.',
direction: 'lowerIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'deathTradedForTeamAdvantageRate',
label: '이득 교환 사망률',
description: '사망했지만 팀이 킬, 오브젝트, 구조물 이득을 얻은 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'deathWhileIsolatedFromNearestAllyRate',
label: '고립 사망률',
description: '가장 가까운 아군과 멀리 떨어진 상태에서 사망한 비율입니다. 낮을수록 좋습니다.',
direction: 'lowerIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'earlyDeficitRecoveryRate',
label: '초반 열세 복구율',
description: '초반 불리함 이후 골드나 오브젝트 흐름을 회복한 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'laneLeadConversionRate',
label: '라인 리드 전환율',
description: '라인전 우위를 오브젝트, 포탑, 팀 이득으로 전환한 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'roamConvertedToTeamAdvantageRate',
label: '로밍 이득 전환율',
description: '로밍이 킬, 오브젝트, 구조물 이득으로 이어진 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'shutdownGoldCollectedPerGame',
label: '게임당 현상금 획득 골드',
description: '게임당 상대 현상금을 회수해 얻은 평균 골드입니다.',
direction: 'higherIsBetter',
kind: 'scalar',
includeInVector: false,
// TODO: MVP 3에서 인구 percentile baseline으로 교체.
baseline: allRoles({
TOP: { min: 0, max: 1_500 },
JUNGLE: { min: 0, max: 1_500 },
MIDDLE: { min: 0, max: 1_500 },
BOTTOM: { min: 0, max: 1_500 },
UTILITY: { min: 0, max: 1_000 },
}),
},
{
id: 'platePresenceParticipationRate',
label: '플레이트 위치 관여율',
description: '포탑 플레이트 압박이나 방어 상황에 위치해 관여한 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
{
id: 'objectiveBountyComebackParticipationRate',
label: '오브젝트 현상금 역전 관여율',
description: '오브젝트 현상금을 활용한 역전 흐름에 관여한 비율입니다.',
direction: 'higherIsBetter',
kind: 'ratio',
includeInVector: false,
baseline: rateBaseline,
},
] as const satisfies readonly MetricDefinition[];
export type MetricId = (typeof METRICS)[number]['id'];
export const VECTOR_METRICS = METRICS.filter(
(metric) => metric.includeInVector,
);
export const VECTOR_DIMENSION = VECTOR_METRICS.length;
export const ADVANTAGE_EVENT_WEIGHTS = {
championKill: 1,
turretPlate: 0.5,
tower: 1.5,
dragon: 1.5,
riftHerald: 1.5,
baron: 3,
} as const;
export type AdvantageEventType = keyof typeof ADVANTAGE_EVENT_WEIGHTS;
export const SUMMONERS_RIFT_MAP_ZONES = [
'blueBase',
'redBase',
'topLane',
'middleLane',
'bottomLane',
'river',
'northWestJungle',
'northEastJungle',
'southWestJungle',
'southEastJungle',
'dragonPit',
'baronPit',
'unknown',
] as const;
export type SummonersRiftMapZone =
(typeof SUMMONERS_RIFT_MAP_ZONES)[number];
export const SUMMONERS_RIFT_MAP = {
coordinateMin: 0,
coordinateMax: 15_000,
laneAxisHalfWidth: 1_500,
riverBandHalfWidth: 1_500,
jungleMidline: 7_500,
baseRadius: 2_200,
objectivePitRadius: 2_500,
dragonPit: { x: 9_866, y: 4_414 },
baronPit: { x: 5_007, y: 10_471 },
} as const;
+2 -1
View File
@@ -1 +1,2 @@
export {};
export * from './feature-registry';
export * from './dto/analysis.dto';
+555
View File
@@ -17,6 +17,9 @@ importers:
'@infisical/sdk':
specifier: ^5.0.2
version: 5.0.2
'@nestjs/bullmq':
specifier: ^11.0.4
version: 11.0.4(@nestjs/common@11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.27)(bullmq@5.79.2(redis@5.12.1))
'@nestjs/common':
specifier: ^11.0.1
version: 11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2)
@@ -32,6 +35,9 @@ importers:
'@persona-lenz/shared':
specifier: workspace:*
version: link:../../packages/shared
bullmq:
specifier: ^5.79.2
version: 5.79.2(redis@5.12.1)
mongoose:
specifier: ^9.7.3
version: 9.7.3(@aws-sdk/credential-providers@3.993.0)
@@ -129,6 +135,12 @@ importers:
react-dom:
specifier: ^19.2.7
version: 19.2.7(react@19.2.7)
react-router-dom:
specifier: ^7.18.1
version: 7.18.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
recharts:
specifier: ^3.9.1
version: 3.9.1(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react-is@19.2.7)(react@19.2.7)(redux@5.0.1)
devDependencies:
'@eslint/js':
specifier: ^10.0.1
@@ -758,6 +770,9 @@ packages:
'@types/node':
optional: true
'@ioredis/commands@1.5.1':
resolution: {integrity: sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==}
'@isaacs/cliui@8.0.2':
resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
engines: {node: '>=12'}
@@ -881,12 +896,55 @@ packages:
'@mongodb-js/saslprep@1.4.12':
resolution: {integrity: sha512-QAfAMwNgnYxZ2C6D1HgeP7Gc4i/uvJRim415PCIL9ptRxWMNbWeLBYb2/9R4pGKny/s1FVu2JA2cxCUBUOggrA==}
'@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4':
resolution: {integrity: sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==}
cpu: [arm64]
os: [darwin]
'@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4':
resolution: {integrity: sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==}
cpu: [x64]
os: [darwin]
'@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4':
resolution: {integrity: sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==}
cpu: [arm64]
os: [linux]
'@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4':
resolution: {integrity: sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==}
cpu: [arm]
os: [linux]
'@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4':
resolution: {integrity: sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==}
cpu: [x64]
os: [linux]
'@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4':
resolution: {integrity: sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==}
cpu: [x64]
os: [win32]
'@napi-rs/wasm-runtime@1.1.6':
resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==}
peerDependencies:
'@emnapi/core': ^1.7.1
'@emnapi/runtime': ^1.7.1
'@nestjs/bull-shared@11.0.4':
resolution: {integrity: sha512-VBJcDHSAzxQnpcDfA0kt9MTGUD1XZzfByV70su0W0eDCQ9aqIEBlzWRW21tv9FG9dIut22ysgDidshdjlnczLw==}
peerDependencies:
'@nestjs/common': ^10.0.0 || ^11.0.0
'@nestjs/core': ^10.0.0 || ^11.0.0
'@nestjs/bullmq@11.0.4':
resolution: {integrity: sha512-wBzK9raAVG0/6NTMdvLGM4/FQ1lsB35/pYS8L6a0SDgkTiLpd7mAjQ8R692oMx5s7IjvgntaZOuTUrKYLNfIkA==}
peerDependencies:
'@nestjs/common': ^10.0.0 || ^11.0.0
'@nestjs/core': ^10.0.0 || ^11.0.0
bullmq: ^3.0.0 || ^4.0.0 || ^5.0.0
'@nestjs/cli@11.0.23':
resolution: {integrity: sha512-2V0Bf5jz0KXhUZk3eJi9GljIyqH04otwsE/mYLbqJR+X0iiYx+6bkNJ2Qz28uHNFj1cpHgimf9xDzHkqarie0g==}
engines: {node: '>= 20.11'}
@@ -1019,6 +1077,17 @@ packages:
peerDependencies:
'@redis/client': ^5.12.1
'@reduxjs/toolkit@2.12.0':
resolution: {integrity: sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw==}
peerDependencies:
react: ^16.9.0 || ^17.0.0 || ^18 || ^19
react-redux: ^7.2.1 || ^8.1.3 || ^9.0.0
peerDependenciesMeta:
react:
optional: true
react-redux:
optional: true
'@rolldown/binding-android-arm64@1.1.4':
resolution: {integrity: sha512-EZLpf/8y7GXkkra90ML47kzik/GMP3EMcE9bPyHmRfxLC6z9+aW5A8poCsoxjrT5GfEcNAAvWwUHjvP1pUQkfw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -1253,6 +1322,9 @@ packages:
'@standard-schema/spec@1.1.0':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
'@standard-schema/utils@0.3.0':
resolution: {integrity: sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==}
'@tokenizer/inflate@0.4.1':
resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}
engines: {node: '>=18'}
@@ -1296,6 +1368,33 @@ packages:
'@types/cookiejar@2.1.5':
resolution: {integrity: sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==}
'@types/d3-array@3.2.2':
resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==}
'@types/d3-color@3.1.3':
resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==}
'@types/d3-ease@3.0.2':
resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==}
'@types/d3-interpolate@3.0.4':
resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==}
'@types/d3-path@3.1.1':
resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==}
'@types/d3-scale@4.0.9':
resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==}
'@types/d3-shape@3.1.8':
resolution: {integrity: sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==}
'@types/d3-time@3.0.4':
resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==}
'@types/d3-timer@3.0.2':
resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==}
'@types/eslint-scope@3.7.7':
resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==}
@@ -1367,6 +1466,9 @@ packages:
'@types/supertest@7.2.0':
resolution: {integrity: sha512-uh2Lv57xvggst6lCqNdFAmDSvoMG7M/HDtX4iUCquxQ5EGPtaPM5PL5Hmi7LCvOG8db7YaCPNJEeoI8s/WzIQw==}
'@types/use-sync-external-store@0.0.6':
resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}
'@types/webidl-conversions@7.0.3':
resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==}
@@ -1823,6 +1925,15 @@ packages:
buffer@5.7.1:
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
bullmq@5.79.2:
resolution: {integrity: sha512-FebD+8XCZl/hnS1R4to24L4EAN70XSndKZO0776M36vGRk5MKVhKlNFM8/34zXLXKyYB4QaeIPFhVXSYYGTHpQ==}
engines: {node: '>=12.22.0'}
peerDependencies:
redis: '>=5.0.0'
peerDependenciesMeta:
redis:
optional: true
busboy@1.6.0:
resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==}
engines: {node: '>=10.16.0'}
@@ -1904,6 +2015,10 @@ packages:
resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==}
engines: {node: '>=0.8'}
clsx@2.1.1:
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
engines: {node: '>=6'}
cluster-key-slot@1.1.2:
resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==}
engines: {node: '>=0.10.0'}
@@ -1970,6 +2085,10 @@ packages:
resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
engines: {node: '>= 0.6'}
cookie@1.1.1:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
cookiejar@2.1.4:
resolution: {integrity: sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==}
@@ -1989,6 +2108,10 @@ packages:
create-require@1.1.1:
resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==}
cron-parser@4.9.0:
resolution: {integrity: sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==}
engines: {node: '>=12.0.0'}
cross-spawn@7.0.6:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
@@ -1996,6 +2119,50 @@ packages:
csstype@3.2.3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
d3-array@3.2.4:
resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==}
engines: {node: '>=12'}
d3-color@3.1.0:
resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}
engines: {node: '>=12'}
d3-ease@3.0.1:
resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==}
engines: {node: '>=12'}
d3-format@3.1.2:
resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==}
engines: {node: '>=12'}
d3-interpolate@3.0.1:
resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==}
engines: {node: '>=12'}
d3-path@3.1.0:
resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==}
engines: {node: '>=12'}
d3-scale@4.0.2:
resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==}
engines: {node: '>=12'}
d3-shape@3.2.0:
resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}
engines: {node: '>=12'}
d3-time-format@4.1.0:
resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==}
engines: {node: '>=12'}
d3-time@3.1.0:
resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==}
engines: {node: '>=12'}
d3-timer@3.0.1:
resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==}
engines: {node: '>=12'}
debug@4.4.3:
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
@@ -2005,6 +2172,9 @@ packages:
supports-color:
optional: true
decimal.js-light@2.5.1:
resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==}
dedent@1.7.2:
resolution: {integrity: sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==}
peerDependencies:
@@ -2027,6 +2197,10 @@ packages:
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
engines: {node: '>=0.4.0'}
denque@2.1.0:
resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==}
engines: {node: '>=0.10'}
depd@2.0.0:
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
@@ -2111,6 +2285,9 @@ packages:
resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}
engines: {node: '>= 0.4'}
es-toolkit@1.49.0:
resolution: {integrity: sha512-G5iZ6Pc/FNRY/soKZHC+TxGDD83rHUDXxzaWhGCX44vAv/tMs56WMusnm/KMNK+luUPsgA9U28cGr4RDlSzL2g==}
escalade@3.2.0:
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
engines: {node: '>=6'}
@@ -2238,6 +2415,9 @@ packages:
resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}
engines: {node: '>= 0.6'}
eventemitter3@5.0.4:
resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}
events@3.3.0:
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
@@ -2472,6 +2652,9 @@ packages:
resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==}
engines: {node: '>= 4'}
immer@11.1.9:
resolution: {integrity: sha512-sc/z0Cyti70bZa0ZU4sWfAElfovFb9Ni8tArJZLuklYWxegPiK3pDOql1Rq5H0FIRAW9LSQRG6OX4KqBldbhBA==}
import-fresh@3.3.1:
resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==}
engines: {node: '>=6'}
@@ -2492,6 +2675,14 @@ packages:
inherits@2.0.4:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
internmap@2.0.3:
resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}
engines: {node: '>=12'}
ioredis@5.10.1:
resolution: {integrity: sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==}
engines: {node: '>=12.22.0'}
ipaddr.js@1.9.1:
resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}
engines: {node: '>= 0.10'}
@@ -2842,6 +3033,12 @@ packages:
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
engines: {node: '>=10'}
lodash.defaults@4.2.0:
resolution: {integrity: sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==}
lodash.isarguments@3.1.0:
resolution: {integrity: sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==}
lodash.memoize@4.1.2:
resolution: {integrity: sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==}
@@ -2865,6 +3062,10 @@ packages:
lru-cache@5.1.1:
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
luxon@3.7.2:
resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==}
engines: {node: '>=12'}
magic-string@0.30.17:
resolution: {integrity: sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==}
@@ -2997,6 +3198,13 @@ packages:
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
msgpackr-extract@3.0.4:
resolution: {integrity: sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==}
hasBin: true
msgpackr@2.0.4:
resolution: {integrity: sha512-o1C5KRmuRt+apqMr1HuGSqWStZoRBUpEsCsl15uM9VdAF1qHLtvMOU2En747EnTyEl6c4pzPewRMFF31s1CNbA==}
multer@2.1.1:
resolution: {integrity: sha512-mo+QTzKlx8R7E5ylSXxWzGoXoZbOsRMpyitcht8By2KHvMbf3tjwosZ/Mu/XYU6UuJ3VZnODIrak5ZrPiPyB6A==}
engines: {node: '>= 10.16.0'}
@@ -3031,6 +3239,10 @@ packages:
node-emoji@1.11.0:
resolution: {integrity: sha512-wo2DpQkQp7Sjm2A0cq+sN7EHKO6Sl0ctXeBdFZrL9T9+UywORbufTcTZxom8YqpLQt/FqNMUkOpkZrJVYSKD3A==}
node-gyp-build-optional-packages@5.2.2:
resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==}
hasBin: true
node-int64@0.4.0:
resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}
@@ -3217,6 +3429,35 @@ packages:
react-is@19.2.7:
resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==}
react-redux@9.3.0:
resolution: {integrity: sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==}
peerDependencies:
'@types/react': ^18.2.25 || ^19
react: ^18.0 || ^19
redux: ^5.0.0
peerDependenciesMeta:
'@types/react':
optional: true
redux:
optional: true
react-router-dom@7.18.1:
resolution: {integrity: sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==}
engines: {node: '>=20.0.0'}
peerDependencies:
react: '>=18'
react-dom: '>=18'
react-router@7.18.1:
resolution: {integrity: sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg==}
engines: {node: '>=20.0.0'}
peerDependencies:
react: '>=18'
react-dom: '>=18'
peerDependenciesMeta:
react-dom:
optional: true
react@19.2.7:
resolution: {integrity: sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==}
engines: {node: '>=0.10.0'}
@@ -3229,10 +3470,34 @@ packages:
resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==}
engines: {node: '>= 14.18.0'}
recharts@3.9.1:
resolution: {integrity: sha512-WMcwlXcB7l+BbxiEdyClkG+1sxrMHNZpzT577LEvU4+rXPd8oTAy1wXk72hnk2KOOmxuLvw3z5DtXT7HEAydtg==}
engines: {node: '>=18'}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-is: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
redis-errors@1.2.0:
resolution: {integrity: sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==}
engines: {node: '>=4'}
redis-parser@3.0.0:
resolution: {integrity: sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==}
engines: {node: '>=4'}
redis@5.12.1:
resolution: {integrity: sha512-LDsoVvb/CpoV9EN3FXvgvSHNJWuCIzl9MiO3ppOevuGLpSGJhwfQjpEwfFJcQvNSddHADDdZaWx0HnmMxRXG7g==}
engines: {node: '>= 18.19.0'}
redux-thunk@3.1.0:
resolution: {integrity: sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==}
peerDependencies:
redux: ^5.0.0
redux@5.0.1:
resolution: {integrity: sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==}
reflect-metadata@0.2.2:
resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==}
@@ -3244,6 +3509,9 @@ packages:
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
reselect@5.2.0:
resolution: {integrity: sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==}
resolve-cwd@3.0.0:
resolution: {integrity: sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==}
engines: {node: '>=8'}
@@ -3309,6 +3577,9 @@ packages:
resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}
engines: {node: '>= 18'}
set-cookie-parser@2.7.2:
resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==}
setprototypeof@1.2.0:
resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}
@@ -3382,6 +3653,9 @@ packages:
resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==}
engines: {node: '>=10'}
standard-as-callback@2.1.0:
resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
statuses@2.0.2:
resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}
engines: {node: '>= 0.8'}
@@ -3513,6 +3787,9 @@ packages:
resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==}
engines: {node: '>=8'}
tiny-invariant@1.3.3:
resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}
tinyglobby@0.2.17:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'}
@@ -3681,6 +3958,11 @@ packages:
uri-js@4.4.1:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
use-sync-external-store@1.6.0:
resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
util-deprecate@1.0.2:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
@@ -3695,6 +3977,9 @@ packages:
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
engines: {node: '>= 0.8'}
victory-vendor@37.3.6:
resolution: {integrity: sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==}
vite@8.1.3:
resolution: {integrity: sha512-Ds+gBRbj0lwRO2Y5hwnUBdxSwlAve9LeRyU4sNnAr0ewW0gWF0n5bgXgUzbgZ49MV9BVUAQUFYVcDUcilUExMA==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4699,6 +4984,8 @@ snapshots:
optionalDependencies:
'@types/node': 24.13.2
'@ioredis/commands@1.5.1': {}
'@isaacs/cliui@8.0.2':
dependencies:
string-width: 5.1.2
@@ -4931,6 +5218,24 @@ snapshots:
dependencies:
sparse-bitfield: 3.0.3
'@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4':
optional: true
'@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4':
optional: true
'@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4':
optional: true
'@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4':
optional: true
'@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4':
optional: true
'@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4':
optional: true
'@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
dependencies:
'@emnapi/core': 1.10.0
@@ -4945,6 +5250,20 @@ snapshots:
'@tybys/wasm-util': 0.10.3
optional: true
'@nestjs/bull-shared@11.0.4(@nestjs/common@11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.27)':
dependencies:
'@nestjs/common': 11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2)
'@nestjs/core': 11.1.27(@nestjs/common@11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.27)(reflect-metadata@0.2.2)(rxjs@7.8.2)
tslib: 2.8.1
'@nestjs/bullmq@11.0.4(@nestjs/common@11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.27)(bullmq@5.79.2(redis@5.12.1))':
dependencies:
'@nestjs/bull-shared': 11.0.4(@nestjs/common@11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.27)
'@nestjs/common': 11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2)
'@nestjs/core': 11.1.27(@nestjs/common@11.1.27(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.27)(reflect-metadata@0.2.2)(rxjs@7.8.2)
bullmq: 5.79.2(redis@5.12.1)
tslib: 2.8.1
'@nestjs/cli@11.0.23(@types/node@24.13.2)(prettier@3.9.4)':
dependencies:
'@angular-devkit/core': 19.2.27(chokidar@4.0.3)
@@ -5080,6 +5399,18 @@ snapshots:
dependencies:
'@redis/client': 5.12.1
'@reduxjs/toolkit@2.12.0(react-redux@9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1))(react@19.2.7)':
dependencies:
'@standard-schema/spec': 1.1.0
'@standard-schema/utils': 0.3.0
immer: 11.1.9
redux: 5.0.1
redux-thunk: 3.1.0(redux@5.0.1)
reselect: 5.2.0
optionalDependencies:
react: 19.2.7
react-redux: 9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1)
'@rolldown/binding-android-arm64@1.1.4':
optional: true
@@ -5301,6 +5632,8 @@ snapshots:
'@standard-schema/spec@1.1.0': {}
'@standard-schema/utils@0.3.0': {}
'@tokenizer/inflate@0.4.1':
dependencies:
debug: 4.4.3
@@ -5355,6 +5688,30 @@ snapshots:
'@types/cookiejar@2.1.5': {}
'@types/d3-array@3.2.2': {}
'@types/d3-color@3.1.3': {}
'@types/d3-ease@3.0.2': {}
'@types/d3-interpolate@3.0.4':
dependencies:
'@types/d3-color': 3.1.3
'@types/d3-path@3.1.1': {}
'@types/d3-scale@4.0.9':
dependencies:
'@types/d3-time': 3.0.4
'@types/d3-shape@3.1.8':
dependencies:
'@types/d3-path': 3.1.1
'@types/d3-time@3.0.4': {}
'@types/d3-timer@3.0.2': {}
'@types/eslint-scope@3.7.7':
dependencies:
'@types/eslint': 9.6.1
@@ -5442,6 +5799,8 @@ snapshots:
'@types/methods': 1.1.4
'@types/superagent': 8.1.10
'@types/use-sync-external-store@0.0.6': {}
'@types/webidl-conversions@7.0.3': {}
'@types/whatwg-url@13.0.0':
@@ -5999,6 +6358,19 @@ snapshots:
base64-js: 1.5.1
ieee754: 1.2.1
bullmq@5.79.2(redis@5.12.1):
dependencies:
cron-parser: 4.9.0
ioredis: 5.10.1
msgpackr: 2.0.4
node-abort-controller: 3.1.1
semver: 7.8.5
tslib: 2.8.1
optionalDependencies:
redis: 5.12.1
transitivePeerDependencies:
- supports-color
busboy@1.6.0:
dependencies:
streamsearch: 1.1.0
@@ -6064,6 +6436,8 @@ snapshots:
clone@1.0.4: {}
clsx@2.1.1: {}
cluster-key-slot@1.1.2: {}
co@4.6.0: {}
@@ -6112,6 +6486,8 @@ snapshots:
cookie@0.7.2: {}
cookie@1.1.1: {}
cookiejar@2.1.4: {}
cors@2.8.6:
@@ -6130,6 +6506,10 @@ snapshots:
create-require@1.1.1: {}
cron-parser@4.9.0:
dependencies:
luxon: 3.7.2
cross-spawn@7.0.6:
dependencies:
path-key: 3.1.1
@@ -6138,10 +6518,50 @@ snapshots:
csstype@3.2.3: {}
d3-array@3.2.4:
dependencies:
internmap: 2.0.3
d3-color@3.1.0: {}
d3-ease@3.0.1: {}
d3-format@3.1.2: {}
d3-interpolate@3.0.1:
dependencies:
d3-color: 3.1.0
d3-path@3.1.0: {}
d3-scale@4.0.2:
dependencies:
d3-array: 3.2.4
d3-format: 3.1.2
d3-interpolate: 3.0.1
d3-time: 3.1.0
d3-time-format: 4.1.0
d3-shape@3.2.0:
dependencies:
d3-path: 3.1.0
d3-time-format@4.1.0:
dependencies:
d3-time: 3.1.0
d3-time@3.1.0:
dependencies:
d3-array: 3.2.4
d3-timer@3.0.1: {}
debug@4.4.3:
dependencies:
ms: 2.1.3
decimal.js-light@2.5.1: {}
dedent@1.7.2: {}
deep-is@0.1.4: {}
@@ -6154,6 +6574,8 @@ snapshots:
delayed-stream@1.0.0: {}
denque@2.1.0: {}
depd@2.0.0: {}
detect-libc@2.1.2: {}
@@ -6221,6 +6643,8 @@ snapshots:
has-tostringtag: 1.0.2
hasown: 2.0.4
es-toolkit@1.49.0: {}
escalade@3.2.0: {}
escape-html@1.0.3: {}
@@ -6385,6 +6809,8 @@ snapshots:
etag@1.8.1: {}
eventemitter3@5.0.4: {}
events@3.3.0: {}
execa@5.1.1:
@@ -6672,6 +7098,8 @@ snapshots:
ignore@7.0.5: {}
immer@11.1.9: {}
import-fresh@3.3.1:
dependencies:
parent-module: 1.0.1
@@ -6691,6 +7119,22 @@ snapshots:
inherits@2.0.4: {}
internmap@2.0.3: {}
ioredis@5.10.1:
dependencies:
'@ioredis/commands': 1.5.1
cluster-key-slot: 1.1.2
debug: 4.4.3
denque: 2.1.0
lodash.defaults: 4.2.0
lodash.isarguments: 3.1.0
redis-errors: 1.2.0
redis-parser: 3.0.0
standard-as-callback: 2.1.0
transitivePeerDependencies:
- supports-color
ipaddr.js@1.9.1: {}
is-arrayish@0.2.1: {}
@@ -7181,6 +7625,10 @@ snapshots:
dependencies:
p-locate: 5.0.0
lodash.defaults@4.2.0: {}
lodash.isarguments@3.1.0: {}
lodash.memoize@4.1.2: {}
lodash.merge@4.6.2: {}
@@ -7200,6 +7648,8 @@ snapshots:
dependencies:
yallist: 3.1.1
luxon@3.7.2: {}
magic-string@0.30.17:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -7301,6 +7751,22 @@ snapshots:
ms@2.1.3: {}
msgpackr-extract@3.0.4:
dependencies:
node-gyp-build-optional-packages: 5.2.2
optionalDependencies:
'@msgpackr-extract/msgpackr-extract-darwin-arm64': 3.0.4
'@msgpackr-extract/msgpackr-extract-darwin-x64': 3.0.4
'@msgpackr-extract/msgpackr-extract-linux-arm': 3.0.4
'@msgpackr-extract/msgpackr-extract-linux-arm64': 3.0.4
'@msgpackr-extract/msgpackr-extract-linux-x64': 3.0.4
'@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.4
optional: true
msgpackr@2.0.4:
optionalDependencies:
msgpackr-extract: 3.0.4
multer@2.1.1:
dependencies:
append-field: 1.0.0
@@ -7326,6 +7792,11 @@ snapshots:
dependencies:
lodash: 4.18.1
node-gyp-build-optional-packages@5.2.2:
dependencies:
detect-libc: 2.1.2
optional: true
node-int64@0.4.0: {}
node-releases@2.0.50: {}
@@ -7495,6 +7966,29 @@ snapshots:
react-is@19.2.7: {}
react-redux@9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1):
dependencies:
'@types/use-sync-external-store': 0.0.6
react: 19.2.7
use-sync-external-store: 1.6.0(react@19.2.7)
optionalDependencies:
'@types/react': 19.2.17
redux: 5.0.1
react-router-dom@7.18.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
dependencies:
react: 19.2.7
react-dom: 19.2.7(react@19.2.7)
react-router: 7.18.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
react-router@7.18.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
dependencies:
cookie: 1.1.1
react: 19.2.7
set-cookie-parser: 2.7.2
optionalDependencies:
react-dom: 19.2.7(react@19.2.7)
react@19.2.7: {}
readable-stream@3.6.2:
@@ -7505,6 +7999,32 @@ snapshots:
readdirp@4.1.2: {}
recharts@3.9.1(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react-is@19.2.7)(react@19.2.7)(redux@5.0.1):
dependencies:
'@reduxjs/toolkit': 2.12.0(react-redux@9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1))(react@19.2.7)
clsx: 2.1.1
decimal.js-light: 2.5.1
es-toolkit: 1.49.0
eventemitter3: 5.0.4
immer: 11.1.9
react: 19.2.7
react-dom: 19.2.7(react@19.2.7)
react-is: 19.2.7
react-redux: 9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1)
reselect: 5.2.0
tiny-invariant: 1.3.3
use-sync-external-store: 1.6.0(react@19.2.7)
victory-vendor: 37.3.6
transitivePeerDependencies:
- '@types/react'
- redux
redis-errors@1.2.0: {}
redis-parser@3.0.0:
dependencies:
redis-errors: 1.2.0
redis@5.12.1:
dependencies:
'@redis/bloom': 5.12.1(@redis/client@5.12.1)
@@ -7516,12 +8036,20 @@ snapshots:
- '@node-rs/xxhash'
- '@opentelemetry/api'
redux-thunk@3.1.0(redux@5.0.1):
dependencies:
redux: 5.0.1
redux@5.0.1: {}
reflect-metadata@0.2.2: {}
require-directory@2.1.1: {}
require-from-string@2.0.2: {}
reselect@5.2.0: {}
resolve-cwd@3.0.0:
dependencies:
resolve-from: 5.0.0
@@ -7622,6 +8150,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
set-cookie-parser@2.7.2: {}
setprototypeof@1.2.0: {}
shebang-command@2.0.0:
@@ -7694,6 +8224,8 @@ snapshots:
dependencies:
escape-string-regexp: 2.0.0
standard-as-callback@2.1.0: {}
statuses@2.0.2: {}
streamsearch@1.1.0: {}
@@ -7798,6 +8330,8 @@ snapshots:
glob: 7.2.3
minimatch: 3.1.5
tiny-invariant@1.3.3: {}
tinyglobby@0.2.17:
dependencies:
fdir: 6.5.0(picomatch@4.0.5)
@@ -7987,6 +8521,10 @@ snapshots:
dependencies:
punycode: 2.3.1
use-sync-external-store@1.6.0(react@19.2.7):
dependencies:
react: 19.2.7
util-deprecate@1.0.2: {}
v8-compile-cache-lib@3.0.1: {}
@@ -7999,6 +8537,23 @@ snapshots:
vary@1.1.2: {}
victory-vendor@37.3.6:
dependencies:
'@types/d3-array': 3.2.2
'@types/d3-ease': 3.0.2
'@types/d3-interpolate': 3.0.4
'@types/d3-scale': 4.0.9
'@types/d3-shape': 3.1.8
'@types/d3-time': 3.0.4
'@types/d3-timer': 3.0.2
d3-array: 3.2.4
d3-ease: 3.0.1
d3-interpolate: 3.0.1
d3-scale: 4.0.2
d3-shape: 3.2.0
d3-time: 3.1.0
d3-timer: 3.0.1
vite@8.1.3(@types/node@24.13.2)(terser@5.48.0)(yaml@2.9.0):
dependencies:
lightningcss: 1.32.0
+1 -5
View File
@@ -4,10 +4,6 @@
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true,
"paths": {
"@persona-lenz/shared": ["./packages/shared/src/index.ts"],
"@persona-lenz/shared/*": ["./packages/shared/src/*"]
}
"skipLibCheck": true
}
}