Merge branch 'main' into feature/ingame-message-parity

This commit is contained in:
2026-07-26 05:38:17 +00:00
42 changed files with 2094 additions and 336 deletions
@@ -0,0 +1,237 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { chromium } from '@playwright/test';
const baseUrl = process.env.REF_NATION_BETTING_URL ?? 'https://dev-sam-ref.hided.net/sam/';
const staticBaseUrl = process.env.REF_NATION_BETTING_STATIC_BASE_URL;
const username = process.env.REF_NATION_BETTING_USER ?? 'refuser1';
const passwordFile = process.env.REF_NATION_BETTING_PASSWORD_FILE;
const artifactRoot = resolve(process.env.REF_NATION_BETTING_ARTIFACT_DIR ?? 'test-results/reference-nation-betting');
if (!staticBaseUrl && !passwordFile) {
throw new Error('REF_NATION_BETTING_PASSWORD_FILE is required.');
}
const password = passwordFile ? (await readFile(passwordFile, 'utf8')).trim() : '';
const bettingList = {
result: true,
bettingList: {
7: {
id: 7,
type: 'bettingNation',
name: '천통국 예상',
finished: false,
selectCnt: 2,
isExclusive: false,
reqInheritancePoint: true,
openYearMonth: 2316,
closeYearMonth: 2340,
winner: null,
totalAmount: 800,
},
},
year: 193,
month: 1,
};
const bettingDetail = {
result: true,
bettingInfo: {
id: 7,
type: 'bettingNation',
name: '천통국 예상',
finished: false,
selectCnt: 2,
isExclusive: false,
reqInheritancePoint: true,
openYearMonth: 2316,
closeYearMonth: 2340,
candidates: [
{ title: '촉', info: '국력: 1200<br>장수 수: 8<br>도시 수: 5', isHtml: true },
{ title: '위', info: '국력: 1100<br>장수 수: 7<br>도시 수: 4', isHtml: true },
{ title: '오', info: '국력: 900<br>장수 수: 6<br>도시 수: 3', isHtml: true },
{ title: '연', info: '국력: 700<br>장수 수: 5<br>도시 수: 2', isHtml: true },
{ title: '양', info: '국력: 650<br>장수 수: 4<br>도시 수: 2', isHtml: true },
{ title: '형', info: '국력: 600<br>장수 수: 3<br>도시 수: 1', isHtml: true },
],
winner: null,
},
bettingDetail: [
['[-1]', 500],
['[0,1]', 200],
['[1,2]', 100],
],
myBetting: [['[0,1]', 50]],
remainPoint: 1200,
year: 193,
month: 1,
};
const login = async (context, page) => {
await page.goto(baseUrl, { waitUntil: 'networkidle', timeout: 60_000 });
const globalSalt = await page.locator('#global_salt').inputValue();
// The reference entrance polls install status and can keep the PHP session
// occupied. Leave it before the login request so the session lock is free.
await page.goto('about:blank');
await context.clearCookies();
const passwordHash = createHash('sha512')
.update(globalSalt + password + globalSalt)
.digest('hex');
const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), {
data: { username, password: passwordHash },
timeout: 60_000,
});
const result = await response.json();
if (!response.ok() || result.result !== true) {
throw new Error('Reference login failed.');
}
};
const installBettingFixture = async (page) => {
await page.route('**/api.php*', async (route) => {
const path = new URL(route.request().url()).searchParams.get('path');
if (path === 'Betting/GetBettingList') {
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(bettingList) });
return;
}
if (path === 'Betting/GetBettingDetail') {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(bettingDetail),
});
return;
}
await route.continue();
});
};
const mountStaticReference = async (page) => {
const hweUrl = new URL('hwe/', staticBaseUrl);
const assetUrl = new URL('dist_js/hwe_dynamic/vue/', staticBaseUrl);
await page.setContent(
`<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=500">
<base href="${hweUrl}">
<link rel="stylesheet" href="${new URL('d_shared/common.css', hweUrl)}">
<link rel="stylesheet" href="${new URL('vendors.css', assetUrl)}">
<link rel="stylesheet" href="${new URL('common_ts.css', assetUrl)}">
<link rel="stylesheet" href="${new URL('bootstrap.css', assetUrl)}">
<link rel="stylesheet" href="${new URL('v_nationBetting.css', assetUrl)}">
</head>
<body>
<div id="app"></div>
<script src="${new URL('d_shared/common_path.js', hweUrl)}"></script>
<script src="${new URL('vendors.js', assetUrl)}"></script>
<script src="${new URL('common_ts.js', assetUrl)}"></script>
<script src="${new URL('bootstrap.js', assetUrl)}"></script>
<script src="${new URL('v_nationBetting.js', assetUrl)}"></script>
</body>
</html>`,
{ waitUntil: 'networkidle' }
);
};
const measure = async (browser, viewport) => {
const context = await browser.newContext({
viewport: { width: viewport.width, height: viewport.height },
deviceScaleFactor: 1,
colorScheme: 'dark',
locale: 'ko-KR',
timezoneId: 'UTC',
ignoreHTTPSErrors: true,
});
try {
const page = await context.newPage();
await installBettingFixture(page);
if (staticBaseUrl) {
await mountStaticReference(page);
} else {
await login(context, page);
await page.goto(new URL('hwe/v_nationBetting.php', baseUrl).toString(), {
waitUntil: 'networkidle',
timeout: 60_000,
});
}
await page.locator('.bettingItem').click();
await page.locator('.bettingCandidate').first().waitFor({ state: 'visible' });
const geometry = await page.locator('#container').evaluate((container) => {
const rect = (element) => {
const value = element.getBoundingClientRect();
return { x: value.x, y: value.y, width: value.width, height: value.height };
};
const cards = Array.from(container.querySelectorAll('.bettingCandidate'));
const firstCard = cards[0];
const cardStyle = getComputedStyle(firstCard);
const titleStyle = getComputedStyle(firstCard.querySelector('.title'));
const optionalRect = (selector) => {
const element = container.querySelector(selector);
return element ? rect(element) : null;
};
return {
container: rect(container),
topBar: rect(container.querySelector('.back_bar')),
candidateCells: Array.from(container.querySelectorAll('.bettingCandidates > div')).map(rect),
candidates: cards.map(rect),
bettingForm: optionalRect('.bettingCandidates + .row'),
payoutTable: optionalRect('.bettingCandidates + .row + div'),
bettingList: optionalRect('.bettingList'),
bottomBar: optionalRect('.bottom_bar, .bg0[style]'),
cardStyle: {
borderWidth: cardStyle.borderWidth,
borderRadius: cardStyle.borderRadius,
cursor: cardStyle.cursor,
fontSize: cardStyle.fontSize,
lineHeight: cardStyle.lineHeight,
},
titleStyle: {
fontWeight: titleStyle.fontWeight,
textAlign: titleStyle.textAlign,
},
};
});
await page.locator('.bettingCandidate').first().click();
const pickedStyle = await page
.locator('.bettingCandidate')
.first()
.evaluate((candidate) => {
const style = getComputedStyle(candidate);
return {
borderColor: style.borderColor,
outlineWidth: style.outlineWidth,
titleWeight: getComputedStyle(candidate.querySelector('.title')).fontWeight,
};
});
const screenshotPath = resolve(artifactRoot, `nation-betting-ref-${viewport.name}.png`);
await page.screenshot({ path: screenshotPath, fullPage: true, animations: 'disabled' });
return { geometry, pickedStyle, screenshotPath };
} finally {
await context.close();
}
};
await mkdir(artifactRoot, { recursive: true });
const browser = await chromium.launch({ headless: true });
try {
const result = {};
for (const viewport of [
{ name: 'desktop', width: 1280, height: 900 },
{ name: 'mobile', width: 500, height: 900 },
]) {
result[viewport.name] = await measure(browser, viewport);
}
const outputPath = resolve(artifactRoot, 'computed-dom.json');
await writeFile(outputPath, `${JSON.stringify(result, null, 2)}\n`);
process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, outputPath })}\n`);
} finally {
await browser.close();
}
@@ -4,10 +4,7 @@ import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const imageRoots = [
resolve(repositoryRoot, '../image/game'),
resolve(repositoryRoot, '../../image/game'),
];
const imageRoots = [resolve(repositoryRoot, '../image/game'), resolve(repositoryRoot, '../../image/game')];
const artifactRoot = process.env.FRONTEND_PARITY_ARTIFACT_DIR;
const response = (data: unknown) => ({ result: { data } });
@@ -214,12 +211,39 @@ test('nation betting matches the legacy desktop geometry and preserves a failed
const geometry = await page.locator('#nation-betting-container').evaluate((container) => {
const containerRect = container.getBoundingClientRect();
const bar = container.querySelector<HTMLElement>('.legacy-top-bar')!.getBoundingClientRect();
const detail = container.querySelector<HTMLElement>('.betting-detail')!;
const detailRect = detail.getBoundingClientRect();
const candidateRowElement = container.querySelector<HTMLElement>('.betting-candidates')!;
const candidateRow = candidateRowElement.getBoundingClientRect();
const candidateCells = Array.from(container.querySelectorAll<HTMLElement>('.betting-candidate-cell'));
const cards = Array.from(container.querySelectorAll<HTMLElement>('.betting-candidate'));
const cardStyle = getComputedStyle(cards[0]!);
const optionalRect = (selector: string) => {
const element = container.querySelector<HTMLElement>(selector);
if (!element) return null;
const rect = element.getBoundingClientRect();
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
};
return {
container: { x: containerRect.x, width: containerRect.width },
container: { x: containerRect.x, width: containerRect.width, height: containerRect.height },
bar: { width: bar.width, height: bar.height },
cardWidths: cards.map((card) => card.getBoundingClientRect().width),
detail: { x: detailRect.x, width: detailRect.width },
candidateRow: {
x: candidateRow.x,
width: candidateRow.width,
},
candidateCells: candidateCells.map((cell) => {
const rect = cell.getBoundingClientRect();
return { x: rect.x, width: rect.width };
}),
cards: cards.map((card) => {
const rect = card.getBoundingClientRect();
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
}),
bettingForm: optionalRect('.betting-form'),
payoutTable: optionalRect('.payout-table'),
bettingList: optionalRect('.betting-list'),
bottomBar: optionalRect('.betting-footer'),
cardStyle: {
borderWidth: cardStyle.borderWidth,
borderRadius: cardStyle.borderRadius,
@@ -229,24 +253,43 @@ test('nation betting matches the legacy desktop geometry and preserves a failed
},
};
});
expect(geometry.container).toEqual({ x: 140, width: 1000 });
expect(geometry.container).toEqual({ x: 140, width: 1000, height: 435 });
expect(geometry.bar).toEqual({ width: 1000, height: 32 });
expect(geometry.cardWidths.every((width) => Math.abs(width - 162) < 1)).toBe(true);
expect(geometry.detail).toEqual({ x: 140, width: 1000 });
expect(geometry.candidateRow).toEqual({ x: 138.25, width: 1003.5 });
expect(geometry.candidateCells.map(({ width }) => width)).toEqual(Array(6).fill(167.25));
expect(geometry.cards.map(({ width }) => width)).toEqual(Array(6).fill(163.75));
expect(geometry.cards.map(({ height }) => height)).toEqual(Array(6).fill(143));
expect(geometry.cards.map(({ y }) => y)).toEqual(Array(6).fill(53));
expect(geometry.bettingForm).toEqual({ x: 140, y: 196, width: 1000, height: 35.5 });
expect(geometry.payoutTable).toEqual({ x: 140, y: 231.5, width: 1000, height: 85 });
expect(geometry.bettingList).toEqual({ x: 140, y: 330.5, width: 1000, height: 45.5 });
expect(geometry.bottomBar).toEqual({ x: 140, y: 379.5, width: 1000, height: 55.5 });
expect(geometry.cardStyle).toEqual({
borderWidth: '1px',
borderRadius: '7px',
cursor: 'pointer',
fontSize: '14px',
lineHeight: '18.2px',
lineHeight: '21px',
});
await expect(page.locator('.legacy-top-bar .legacy-nav-button')).toHaveCount(1);
await expect(page.locator('.payout-row:not(.payout-head)').first().locator('div').nth(2)).toHaveText(
'(50 -> 100.0)'
);
await page.locator('.betting-candidate').nth(0).click();
await page.locator('.betting-candidate').nth(1).click();
const pickedStyle = await page.locator('.betting-candidate').first().evaluate((candidate) => {
const style = getComputedStyle(candidate);
return { borderColor: style.borderColor, outlineWidth: style.outlineWidth, titleWeight: getComputedStyle(candidate.querySelector('.candidate-title')!).fontWeight };
});
const pickedStyle = await page
.locator('.betting-candidate')
.first()
.evaluate((candidate) => {
const style = getComputedStyle(candidate);
return {
borderColor: style.borderColor,
outlineWidth: style.outlineWidth,
titleWeight: getComputedStyle(candidate.querySelector('.candidate-title')!).fontWeight,
};
});
expect(pickedStyle.borderColor).toBe('rgb(255, 255, 255)');
// Chromium snaps the legacy 1.5px CSS outline to one device pixel at DSF 1.
expect(pickedStyle.outlineWidth).toBe('1px');
@@ -281,6 +324,7 @@ test('nation betting keeps the legacy 500px three-column mobile contract', async
return {
x: rect.x,
width: rect.width,
firstX: cards[0]!.getBoundingClientRect().x,
firstWidth: cards[0]!.getBoundingClientRect().width,
fourthY: cards[3]!.getBoundingClientRect().y,
firstY: cards[0]!.getBoundingClientRect().y,
@@ -288,7 +332,8 @@ test('nation betting keeps the legacy 500px three-column mobile contract', async
});
expect(geometry.x).toBe(0);
expect(geometry.width).toBe(500);
expect(geometry.firstWidth).toBeCloseTo(161.328125, 3);
expect(geometry.firstX).toBe(0);
expect(geometry.firstWidth).toBe(164.328125);
expect(geometry.fourthY).toBeGreaterThan(geometry.firstY);
if (artifactRoot) {
@@ -325,17 +370,7 @@ test('NPC list matches the legacy table geometry, sorting and error retention',
expect(geometry.tableWidth).toBe(1000);
// The legacy width attributes total 974px; Chromium proportionally expands them into the 1000px table.
expect(geometry.headerWidths).toEqual([
104.609375,
104.609375,
69.734375,
121.015625,
69.734375,
90.25,
69.734375,
69.734375,
69.734375,
69.734375,
80,
104.609375, 104.609375, 69.734375, 121.015625, 69.734375, 90.25, 69.734375, 69.734375, 69.734375, 69.734375, 80,
80.109375,
]);
expect(geometry.headerStyle).toEqual({
@@ -346,7 +381,10 @@ test('NPC list matches the legacy table geometry, sorting and error retention',
lineHeight: '18.2px',
});
await expect(page.locator('.npc-table tbody tr').first()).toContainText('관우');
await expect(page.locator('.npc-table tbody tr').first().locator('td').first()).toHaveCSS('color', 'rgb(135, 206, 235)');
await expect(page.locator('.npc-table tbody tr').first().locator('td').first()).toHaveCSS(
'color',
'rgb(135, 206, 235)'
);
const personality = page.locator('.npc-table tbody tr').first().locator('.trait-tooltip').first();
await personality.hover();
await expect(personality.getByRole('tooltip')).toBeVisible();
@@ -348,6 +348,8 @@ const buildWorldInput = (
maxGeneral: 500,
baseGold: 0,
baseRice: 2_000,
generalMinimumGold: 0,
generalMinimumRice: 500,
maxResourceActionAmount: 10_000,
maxTechLevel: 12,
maxLevel: 255,
@@ -1109,6 +1109,194 @@ integration('general command missing-target fallback matrix', () => {
);
});
const resourceAmountCases: Array<{
name: string;
action: string;
args: Record<string, unknown>;
expectedAmount: number;
}> = [
{
name: 'gift rounds a half unit up',
action: 'che_증여',
args: { isGold: true, amount: 150, destGeneralID: 3 },
expectedAmount: 200,
},
{
name: 'gift clamps below the minimum',
action: 'che_증여',
args: { isGold: true, amount: 1, destGeneralID: 3 },
expectedAmount: 100,
},
{
name: 'gift clamps above the maximum',
action: 'che_증여',
args: { isGold: true, amount: 10_050, destGeneralID: 3 },
expectedAmount: 10_000,
},
{
name: 'donation rounds a half unit up',
action: 'che_헌납',
args: { isGold: true, amount: 150 },
expectedAmount: 200,
},
{
name: 'donation clamps below the minimum',
action: 'che_헌납',
args: { isGold: true, amount: 1 },
expectedAmount: 100,
},
{
name: 'donation clamps above the maximum',
action: 'che_헌납',
args: { isGold: true, amount: 10_050 },
expectedAmount: 10_000,
},
{
name: 'trade rounds a half unit up',
action: 'che_군량매매',
args: { buyRice: true, amount: 150 },
expectedAmount: 200,
},
{
name: 'trade clamps below the minimum',
action: 'che_군량매매',
args: { buyRice: true, amount: 1 },
expectedAmount: 100,
},
{
name: 'trade clamps above the maximum',
action: 'che_군량매매',
args: { buyRice: true, amount: 10_050 },
expectedAmount: 10_000,
},
];
integration('general command resource amount normalization matrix', () => {
it.each(resourceAmountCases)(
'$name matches legacy rounding and clamp semantics',
async ({ action, args, expectedAmount }) => {
const request = buildRequest(action, args);
const reference = runReferenceTurnCommandTraceRequest(
workspaceRoot!,
request as unknown as Record<string, unknown>
);
const core = await runCoreTurnCommandTrace(request, reference.before);
const referenceActor = reference.after.generals.find((entry) => entry.id === 1);
const coreActor = core.after.generals.find((entry) => entry.id === 1);
const referenceLastTurn = referenceActor?.lastTurn as { arg?: Record<string, unknown> } | null | undefined;
const coreLastTurn = coreActor?.lastTurn as { arg?: Record<string, unknown> } | null | undefined;
expect(reference.execution.outcome).toMatchObject({ completed: true });
expect(core.execution.outcome).toMatchObject({
requestedAction: action,
actionKey: action,
usedFallback: false,
});
expect(referenceLastTurn?.arg).toMatchObject({ amount: expectedAmount });
expect(coreLastTurn?.arg).toMatchObject({ amount: expectedAmount });
expect(core.rng).toEqual(reference.rng);
expect(
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
ignoredPathPatterns: ignoredLifecyclePaths,
})
).toEqual([]);
},
120_000
);
});
integration('general command donation resource boundaries', () => {
it('donates the available resource when the normalized request exceeds the current amount', async () => {
const request = buildRequest('che_헌납', { isGold: true, amount: 10_000 }, { gold: 5_000 });
const reference = runReferenceTurnCommandTraceRequest(
workspaceRoot!,
request as unknown as Record<string, unknown>
);
const core = await runCoreTurnCommandTrace(request, reference.before);
expect(reference.execution.outcome).toMatchObject({ completed: true });
expect(core.execution.outcome).toMatchObject({
requestedAction: 'che_헌납',
actionKey: 'che_헌납',
usedFallback: false,
});
expect(core.rng).toEqual(reference.rng);
expect(
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
ignoredPathPatterns: ignoredLifecyclePaths,
})
).toEqual([]);
}, 120_000);
it('falls back when current rice is below the legacy minimum even for a small request', async () => {
const request = buildRequest('che_헌납', { isGold: false, amount: 100 }, { rice: 499 });
const reference = runReferenceTurnCommandTraceRequest(
workspaceRoot!,
request as unknown as Record<string, unknown>
);
const core = await runCoreTurnCommandTrace(request, reference.before);
expect(reference.execution.outcome).toMatchObject({ completed: false });
expect(core.execution.outcome).toMatchObject({
requestedAction: 'che_헌납',
actionKey: '휴식',
usedFallback: true,
});
expect(core.rng).toEqual(reference.rng);
expect(
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
ignoredPathPatterns: ignoredLifecyclePaths,
})
).toEqual([]);
}, 120_000);
});
integration('general command gift resource and target boundaries', () => {
it('keeps the legacy minimum rice reserve while gifting the available amount', async () => {
const request = buildRequest('che_증여', { isGold: false, amount: 10_000, destGeneralID: 3 }, { rice: 600 });
const reference = runReferenceTurnCommandTraceRequest(
workspaceRoot!,
request as unknown as Record<string, unknown>
);
const core = await runCoreTurnCommandTrace(request, reference.before);
expect(reference.execution.outcome).toMatchObject({ completed: true });
expect(core.execution.outcome).toMatchObject({
requestedAction: 'che_증여',
actionKey: 'che_증여',
usedFallback: false,
});
expect(core.rng).toEqual(reference.rng);
expect(
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
ignoredPathPatterns: ignoredLifecyclePaths,
})
).toEqual([]);
}, 120_000);
it('rejects gifting to the actor and falls back without command RNG', async () => {
const request = buildRequest('che_증여', { isGold: true, amount: 100, destGeneralID: 1 });
const reference = runReferenceTurnCommandTraceRequest(
workspaceRoot!,
request as unknown as Record<string, unknown>
);
const core = await runCoreTurnCommandTrace(request, reference.before);
expect(reference.execution.outcome).toMatchObject({ completed: false });
expect(core.execution.outcome).toMatchObject({
requestedAction: 'che_증여',
actionKey: '휴식',
usedFallback: true,
});
expect(core.rng).toEqual(reference.rng);
expect(
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
ignoredPathPatterns: ignoredLifecyclePaths,
})
).toEqual([]);
}, 120_000);
});
type GeneralConstraintCase = {
name: string;
action: string;