diff --git a/components/ui/ImportLogDialog.tsx b/components/ui/ImportLogDialog.tsx index 733f9ec..1708064 100644 --- a/components/ui/ImportLogDialog.tsx +++ b/components/ui/ImportLogDialog.tsx @@ -129,6 +129,8 @@ export function ImportLogDialog({ const [saveState, setSaveState] = useState("idle"); const [isParsing, startParseTransition] = useTransition(); const autoParseRequestIdRef = useRef(0); + const importSessionIdRef = useRef(0); + const saveInFlightRef = useRef(false); const shouldAutoParseImmediatelyRef = useRef(false); const closeTimerRef = useRef(null); const navigationTimerRef = useRef(null); @@ -222,6 +224,10 @@ export function ImportLogDialog({ }, [review, selectedDeckId, userDecks]); function resetImportState() { + autoParseRequestIdRef.current += 1; + importSessionIdRef.current += 1; + saveInFlightRef.current = false; + shouldAutoParseImmediatelyRef.current = false; setStage("raw"); setRawLog(""); setParseError(null); @@ -269,6 +275,8 @@ export function ImportLogDialog({ useEffect(() => { return () => { + autoParseRequestIdRef.current += 1; + importSessionIdRef.current += 1; clearCloseTimer(); clearNavigationTimer(); }; @@ -339,16 +347,25 @@ export function ImportLogDialog({ return; } + const sessionId = importSessionIdRef.current; + const requestId = ++autoParseRequestIdRef.current; try { setIsPasting(true); const clipboardText = await navigator.clipboard.readText(); + if (autoParseRequestIdRef.current !== requestId) { + return; + } shouldAutoParseImmediatelyRef.current = true; setRawLog(clipboardText); setParseError(null); } catch { - setParseError("Unable to read from the clipboard right now."); + if (autoParseRequestIdRef.current === requestId) { + setParseError("Unable to read from the clipboard right now."); + } } finally { - setIsPasting(false); + if (importSessionIdRef.current === sessionId) { + setIsPasting(false); + } } } @@ -418,6 +435,11 @@ export function ImportLogDialog({ } async function handleSubmit(formData: FormData) { + if (saveInFlightRef.current || !review) { + return; + } + saveInFlightRef.current = true; + const sessionId = importSessionIdRef.current; setSaveError(""); setSaveState("saving"); @@ -429,6 +451,9 @@ export function ImportLogDialog({ method: "POST" }); const result = (await response.json()) as SaveActionResult | { error?: string }; + if (importSessionIdRef.current !== sessionId) { + return; + } if (!response.ok || !("ok" in result)) { const message = "error" in result ? result.error : undefined; @@ -459,6 +484,10 @@ export function ImportLogDialog({ }, 50); }, SUCCESS_CLOSE_DELAY_MS); } catch (error) { + if (importSessionIdRef.current !== sessionId) { + return; + } + saveInFlightRef.current = false; setSaveError(error instanceof Error ? error.message : "Could not save this battle log."); setSaveState("idle"); } @@ -494,6 +523,7 @@ export function ImportLogDialog({ return () => { window.clearTimeout(timeoutId); + autoParseRequestIdRef.current += 1; }; }, [isOpen, isTrainingCourtUrl, requestParseReview, stage, trimmedRawLog]); @@ -833,6 +863,11 @@ export function ImportLogDialog({ }} onChange={(event) => { const nextRawLog = event.target.value; + // Only a change to the reviewed (trimmed) log supersedes a + // pending review; the auto-review effect reschedules on it. + if (nextRawLog.trim() !== trimmedRawLog) { + autoParseRequestIdRef.current += 1; + } if (nextRawLog.length - rawLog.length >= BULK_PASTE_CHARACTER_THRESHOLD) { shouldAutoParseImmediatelyRef.current = true; } diff --git a/lib/log-import/parser/players.ts b/lib/log-import/parser/players.ts index 6c43cbf..6b32e90 100644 --- a/lib/log-import/parser/players.ts +++ b/lib/log-import/parser/players.ts @@ -119,3 +119,18 @@ export function canonicalizeSelfPlayerSections( ) })); } + +/** Match the recorded actor, including names ending in punctuation. */ +export function getLeadingPlayerFromLine(line: string, playerNames: string[]) { + const normalized = String(line || "").replace(/^\s*(?:[-•]\s+)?/, ""); + return ( + playerNames + .toSorted((left, right) => right.length - left.length) + .find( + (player) => + normalized.startsWith(`${player} `) || + normalized.startsWith(`${player}'s `) || + normalized.startsWith(`${player}’s `) + ) ?? "" + ); +} diff --git a/lib/log-import/parser/pokemon-mentions.ts b/lib/log-import/parser/pokemon-mentions.ts index 1060dce..3a9f59f 100644 --- a/lib/log-import/parser/pokemon-mentions.ts +++ b/lib/log-import/parser/pokemon-mentions.ts @@ -3,17 +3,26 @@ import { normalizeText } from "@/lib/log-import/normalization"; import type { IdentificationCatalog, PlayerPokemonEvidence } from "@/lib/log-import/types"; import { stripLogCardIdentifiers } from "@/lib/battle-log/card-identifiers"; +// Effect-driven plays (e.g. Rare Candy) arrive as indented "- " / "• " detail +// lines; the acting player still leads the recorded sentence. +function stripDetailMarker(line: string) { + return line.replace(/^\s*(?:[-•]\s+)?/, ""); +} + function getRelevantIdentificationLines(lines: string[], playerName: string, language: Language) { if (language === "en") { - return lines.filter( - (line) => - line.includes(`${playerName} attached`) || - line.includes(`${playerName} played `) || - (line.includes(`${playerName} drew `) && line.includes("and played it to the Bench")) || - line.includes(`${playerName} evolved `) || - (line.includes(`${playerName}'s `) && - (line.includes("was Knocked Out") || (line.includes(" used") && !line.includes("damage")))) - ); + return lines + .map(stripDetailMarker) + .filter( + (line) => + line.startsWith(`${playerName} attached`) || + line.startsWith(`${playerName} played `) || + (line.startsWith(`${playerName} drew `) && line.includes("and played it to the Bench")) || + line.startsWith(`${playerName} evolved `) || + (line.startsWith(`${playerName}'s `) && + (line.includes("was Knocked Out") || + (line.includes(" used") && !line.includes("damage")))) + ); } if (language === "es") { @@ -25,7 +34,9 @@ function getRelevantIdentificationLines(lines: string[], playerName: string, lan if (language === "de") { return lines.filter( (line) => - (line.includes(playerName) && line.includes(" auf der Bank zu ") && line.includes("entwickelt")) || + (line.includes(playerName) && + line.includes(" auf der Bank zu ") && + line.includes("entwickelt")) || (line.includes(`${playerName} hat`) && line.includes(" auf die Bank gelegt.")) ); } @@ -40,7 +51,8 @@ function getRelevantIdentificationLines(lines: string[], playerName: string, lan if (language === "it") { return lines.filter( - (line) => line.includes(`${playerName} ha pescato e giocato`) && line.includes(" in panchina.") + (line) => + line.includes(`${playerName} ha pescato e giocato`) && line.includes(" in panchina.") ); } @@ -71,18 +83,19 @@ export function extractPlayerPokemonMentions(args: { catalog: IdentificationCatalog; }): PlayerPokemonEvidence { const relevantLines = getRelevantIdentificationLines(args.lines, args.playerName, args.language); + // Player identities are not card evidence, even when a username is a Pokémon name. + const cardLines = + args.language === "en" + ? relevantLines.map((line) => line.slice(args.playerName.length)) + : relevantLines; const mentionCounts = new Map(); const maxTokens = args.catalog.pokemon.maxNameTokens; - relevantLines.forEach((line) => { + cardLines.forEach((line) => { const tokens = tokenizeLine(line); for (let startIndex = 0; startIndex < tokens.length; startIndex += 1) { - for ( - let size = Math.min(maxTokens, tokens.length - startIndex); - size >= 1; - size -= 1 - ) { + for (let size = Math.min(maxTokens, tokens.length - startIndex); size >= 1; size -= 1) { const phrase = tokens.slice(startIndex, startIndex + size).join(" "); const slug = args.catalog.pokemon.normalizedNameToSlug.get(phrase); if (!slug) { @@ -98,7 +111,7 @@ export function extractPlayerPokemonMentions(args: { return { lines: relevantLines, - normalizedText: normalizeText(stripLogCardIdentifiers(relevantLines.join(" "))), + normalizedText: normalizeText(stripLogCardIdentifiers(cardLines.join(" "))), mentionCounts }; } diff --git a/lib/log-import/parser/stats.ts b/lib/log-import/parser/stats.ts index 0790bcf..a606c1c 100644 --- a/lib/log-import/parser/stats.ts +++ b/lib/log-import/parser/stats.ts @@ -1,15 +1,16 @@ import type { Language, LogSection, Result } from "@/types/index"; import { LANGUAGE_STRINGS } from "@/lib/log-import/parser/language"; +import { getLeadingPlayerFromLine } from "@/lib/log-import/parser/players"; import { ImportLogValidationError } from "@/lib/log-import/types"; import { compactMap } from "@/lib/array"; -const WINNER_PATTERNS: Record = { - en: /\. (.*) wins\./g, - es: /\. (.*) ganó\./, - de: /\. (.*) hat gewonnen\./, - fr: /\. (.*) gagne\./, - it: /\. (.*) ha vinto\./, - "pt-br": /\. (.*) venceu\./ +const WINNER_SUFFIXES: Record = { + en: " wins.", + es: " ganó.", + de: " hat gewonnen.", + fr: " gagne.", + it: " ha vinto.", + "pt-br": " venceu." }; const CONCEDE_PATTERNS: Record = { @@ -21,27 +22,12 @@ const CONCEDE_PATTERNS: Record = { "pt-br": [/concedeu/i, /desistiu/i] }; -function getLeadingPlayerFromLine(line: string, playerNames: string[]) { - const candidates = playerNames.toSorted((left, right) => right.length - left.length); - - return ( - candidates.find((player) => { - const escaped = player.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`^${escaped}(?:'s|\\b)`).test(String(line || "")); - }) ?? "" - ); -} - -function getPlayerFromLine(line: string, playerNames: string[]) { - return playerNames.find((player) => String(line || "").includes(player)) ?? ""; -} - function getCoinTossWinnerFromLine(line: string, playerNames: string[]) { if (!String(line || "").includes(" won the coin toss")) { return ""; } - return getLeadingPlayerFromLine(line, playerNames) || getPlayerFromLine(line, playerNames); + return getLeadingPlayerFromLine(line, playerNames); } function getMulligansTakenFromLine(line: string) { @@ -101,7 +87,10 @@ function getAttackDamageFromAction( // Ability actions such as Festival Lead contain a recorded attack in their // details. Read attack records, not the explanatory damage breakdown. const title = String(action.title || "").trim(); - const records = [title, ...action.details.map((detail) => detail.replace(/^\s*-\s*/, "").trim())]; + const records = [ + title, + ...action.details.map((detail) => detail.replace(/^\s*[-•]\s+/, "").trim()) + ]; const nestedAttacks = records.slice(1).filter((line) => getAttackDamageFromLine(line) > 0); // A title repeated in its details is one record. Repeated nested lines can // represent two real attacks (Festival Lead) and must each retain their damage. @@ -129,23 +118,27 @@ function getAttackDamageFromAction( }); } -function determineWinner(lines: string[], language: Language) { - const winner = lines - .map((line) => { - const match = WINNER_PATTERNS[language].exec(line)?.[1] ?? null; - WINNER_PATTERNS[language].lastIndex = 0; - return match; - }) - .find(Boolean); +function determineWinner(lines: string[], language: Language, playerNames: string[]) { + const candidates = playerNames.toSorted((left, right) => right.length - left.length); + const winners = Array.from( + new Set( + compactMap(lines, (line) => + candidates.find((player) => { + const ending = `${player}${WINNER_SUFFIXES[language]}`; + return line === ending || line.endsWith(`. ${ending}`); + }) + ) + ) + ); - if (!winner) { + if (winners.length !== 1) { throw new ImportLogValidationError( "UNKNOWN_LOG", - "Could not find a winner line in this PTCGL log." + "Could not resolve exactly one winner from the players in this PTCGL log." ); } - return winner; + return winners[0]; } export function getPrizesTakenFromLine(line: string, language: Language) { @@ -198,7 +191,7 @@ function calculateTotalTurns(sections: LogSection[]) { }) .filter((value) => Number.isFinite(value)); - return numberedTurns.length > 0 ? Math.max(...numberedTurns) : Math.ceil(nonSetupSections.length / 2); + return numberedTurns.length > 0 ? Math.max(...numberedTurns) : nonSetupSections.length; } function determineGoOrder( @@ -265,7 +258,7 @@ export function buildStats({ return; } - const leadingPlayer = getLeadingPlayerFromLine(line, playerNames) || getPlayerFromLine(line, playerNames); + const leadingPlayer = getLeadingPlayerFromLine(line, playerNames); const playerStats = leadingPlayer ? statsByName[leadingPlayer] : null; const actionLines = compactMap([line, ...action.details], (entry) => String(entry || "").trim()); @@ -275,12 +268,14 @@ export function buildStats({ coinTossWinner = coinTossPlayer; } - const mulliganPlayer = - getLeadingPlayerFromLine(actionLine, playerNames) || getPlayerFromLine(actionLine, playerNames); + const mulliganPlayer = getLeadingPlayerFromLine(actionLine, playerNames); const mulliganStats = mulliganPlayer ? statsByName[mulliganPlayer] : null; const mulligansTaken = getMulligansTakenFromLine(actionLine); if (mulliganStats && mulligansTaken > 0) { - mulliganStats.mulligans = Math.max(mulliganStats.mulligans, mulligansTaken); + // Each singular record is an event; numeric records summarize a count. + mulliganStats.mulligans = actionLine.includes("took a mulligan") + ? mulliganStats.mulligans + 1 + : Math.max(mulliganStats.mulligans, mulligansTaken); } }); @@ -296,7 +291,7 @@ export function buildStats({ }); }); - const winner = determineWinner(lines, language); + const winner = determineWinner(lines, language, playerNames); const result: Result = winner.toLowerCase() === selfPlayerName.toLowerCase() ? "Win" : "Loss"; const selfStats = statsByName[selfPlayerName]; const opponentStats = statsByName[opponentPlayerName]; diff --git a/lib/log-import/parser/turns.ts b/lib/log-import/parser/turns.ts index 9d8a10f..059bbb9 100644 --- a/lib/log-import/parser/turns.ts +++ b/lib/log-import/parser/turns.ts @@ -1,5 +1,6 @@ import type { Language, LogAction, LogSection } from "@/types/index"; import { LANGUAGE_STRINGS } from "@/lib/log-import/parser/language"; +import { getLeadingPlayerFromLine } from "@/lib/log-import/parser/players"; const SUBACTION_MARKERS = [ "A card was added", @@ -44,17 +45,6 @@ function isTurnBoundary(line: string, language: Language) { return getPlayerNameFromTurnLine(line, language) !== null; } -function getLeadingPlayerFromLine(line: string, playerNames: string[]) { - const candidates = playerNames.toSorted((left, right) => right.length - left.length); - - return ( - candidates.find((player) => { - const escaped = player.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`^${escaped}(?:'s|\\b)`).test(String(line || "")); - }) ?? "" - ); -} - function inferSectionPlayer( title: string, bodyLines: string[], @@ -103,7 +93,7 @@ function getTurnActions(bodyLines: string[]): LogAction[] { bodyLines.forEach((line) => { const trimmed = line.trim(); - const abilityActivationMatch = trimmed.match(/^[-•]?\s*(.+\s+was activated\.)$/i); + const abilityActivationMatch = trimmed.match(/^(?:[-•]\s+)?(.+\s+was activated\.)$/i); if (abilityActivationMatch?.[1]) { actions.push({ title: abilityActivationMatch[1], @@ -113,8 +103,7 @@ function getTurnActions(bodyLines: string[]): LogAction[] { } const isSubaction = - trimmed.startsWith("-") || - trimmed.startsWith("•") || + /^[-•]\s/.test(trimmed) || /\btook \d+ damage\b/i.test(trimmed) || SUBACTION_MARKERS.some((marker) => line.includes(marker)); diff --git a/tests/battle-replay-compiler.test.ts b/tests/battle-replay-compiler.test.ts index f94acfb..28fb370 100644 --- a/tests/battle-replay-compiler.test.ts +++ b/tests/battle-replay-compiler.test.ts @@ -179,7 +179,7 @@ test("real PTCGL exports replay through the importer with tokenized or name-only const identified = importAndReplay(identifiedBattleLog); assert.equal(identified.parsed.rawLog, identifiedBattleLog); assert.ok(identified.parsed.sections.some((section) => section.actions.some((action) => action.title.includes("(sv5_84) Relicanth")))); - assert.deepEqual(identified.parsed.stats, { winner: "tyDspen", result: "Loss", totalTurns: 2, coinTossWon: false, goOrder: "Second", selfPrizesTaken: 0, opponentPrizesTaken: 0, selfAttackDamage: 0, opponentAttackDamage: 30, selfMulligans: 0, opponentMulligans: 0, reason: "Concede" }); + assert.deepEqual(identified.parsed.stats, { winner: "tyDspen", result: "Loss", totalTurns: 4, coinTossWon: false, goOrder: "Second", selfPrizesTaken: 0, opponentPrizesTaken: 0, selfAttackDamage: 0, opponentAttackDamage: 30, selfMulligans: 0, opponentMulligans: 0, reason: "Concede" }); assert.deepEqual(identified.program.diagnostics.unresolvedActions, []); const final = identified.program.frames.at(-1)!; assert.deepEqual([final.self.handCount, final.self.deckCount, final.self.discardCount, final.self.inPlayCount], [4, 44, 4, 2]); diff --git a/tests/import-log-dialog.test.ts b/tests/import-log-dialog.test.ts new file mode 100644 index 0000000..4d7d108 --- /dev/null +++ b/tests/import-log-dialog.test.ts @@ -0,0 +1,173 @@ +import "./support/dom"; +import assert from "node:assert/strict"; +import test from "node:test"; +import { readFileSync } from "node:fs"; +import { createElement } from "react"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { AppRouterContext } from "next/dist/shared/lib/app-router-context.shared-runtime"; +import { PathnameContext } from "next/dist/shared/lib/hooks-client-context.shared-runtime"; +import { ImportLogDialog } from "@/components/ui/ImportLogDialog"; +import { ImportDialogDataProvider } from "@/components/ui/ImportDialogDataProvider"; +import { SiteFormatsProvider } from "@/components/ui/SiteFormatsProvider"; +import type { PersistedBattleLogImportReview } from "@/lib/db/battle-log-import-drafts"; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +test("Battle Log review discards abandoned requests and saves a draft once", async (t) => { + const originalFetch = globalThis.fetch; + const reviews: ReturnType>[] = []; + const save = deferred(); + let saves = 0; + const navigations: string[] = []; + globalThis.fetch = (async (input: RequestInfo | URL) => { + if (String(input) === "/api/log-import/review") { + const request = deferred(); + reviews.push(request); + return request.promise; + } + if (String(input) === "/api/log-import/save") { + saves += 1; + return save.promise; + } + return Response.json({ userDecks: [], deckLists: [] }); + }) as typeof fetch; + const review: PersistedBattleLogImportReview = { + draftId: "draft-1", + expiresAt: "2026-11-07T10:30:00Z", + date: "2026-11-07", + selfPlayerName: "E2ETrainer", + opponentPlayerName: "FixtureOpponent", + selfDeckName: "Dragapult", + opponentDeckName: "Charizard", + selfDeckSlug: "dragapult", + opponentDeckSlug: "charizard", + selfSprites: ["dragapult"], + opponentSprites: ["charizard"], + result: "Win", + goOrder: "First", + coinTossWon: true, + language: "en", + totalTurns: 2, + selfPrizesTaken: 1, + opponentPrizesTaken: 0, + selfAttackDamage: 200, + opponentAttackDamage: 180, + selfMulligans: 0, + opponentMulligans: 0, + reason: "Concede" + }; + try { + const formatsProps = { + initialSiteFormats: { + options: ["TEF-ASC"], + defaultFormat: "TEF-ASC", + source: "fallback" as const + }, + children: createElement(ImportDialogDataProvider, null, createElement(ImportLogDialog)) + }; + render( + createElement( + AppRouterContext.Provider, + { + value: { + bfcacheId: "import-test", + back() {}, + forward() {}, + refresh() {}, + prefetch() {}, + replace() {}, + push(url: string) { + navigations.push(url); + } + } + }, + createElement( + PathnameContext.Provider, + { value: "/logs" }, + createElement(SiteFormatsProvider, formatsProps) + ) + ) + ); + const rawLog = readFileSync("tests/e2e/fixtures/battle-log-valid.txt", "utf8"); + fireEvent.click(screen.getByRole("button", { name: "Import PTCGL Log" })); + const clipboard = deferred(); + t.mock.method(navigator.clipboard, "readText", () => clipboard.promise); + fireEvent.click(screen.getByRole("button", { name: "Paste From Clipboard" })); + fireEvent.click(screen.getByRole("button", { name: "Close dialog" })); + fireEvent.click(screen.getByRole("button", { name: "Import PTCGL Log" })); + await act(async () => { + clipboard.resolve(rawLog); + }); + assert.equal( + (screen.getByRole("textbox", { name: "Battle log" }) as HTMLTextAreaElement).value, + "", + "an abandoned clipboard read cannot paste into a later session" + ); + + fireEvent.change(screen.getByRole("textbox", { name: "Battle log" }), { + target: { value: rawLog } + }); + await waitFor(() => assert.equal(reviews.length, 1)); + fireEvent.change(screen.getByRole("textbox", { name: "Battle log" }), { + target: { value: "" } + }); + await act(async () => { + reviews[0].resolve(Response.json(review)); + }); + assert.ok( + screen.queryByRole("textbox", { name: "Battle log" }), + "clearing text invalidates the old response" + ); + + fireEvent.change(screen.getByRole("textbox", { name: "Battle log" }), { + target: { value: rawLog } + }); + await waitFor(() => assert.equal(reviews.length, 2)); + fireEvent.click(screen.getByRole("button", { name: "Close dialog" })); + await act(async () => { + reviews[1].resolve(Response.json(review)); + }); + fireEvent.click(screen.getByRole("button", { name: "Import PTCGL Log" })); + assert.ok( + screen.queryByRole("textbox", { name: "Battle log" }), + "reopening never restores an abandoned review" + ); + + fireEvent.change(screen.getByRole("textbox", { name: "Battle log" }), { + target: { value: rawLog } + }); + await waitFor(() => assert.equal(reviews.length, 3)); + // A whitespace-only edit leaves the reviewed log unchanged. + fireEvent.change(screen.getByRole("textbox", { name: "Battle log" }), { + target: { value: `${rawLog}\n ` } + }); + await act(async () => { + reviews[2].resolve(Response.json(review)); + }); + const form = screen.getByRole("textbox", { name: "Match notes" }).closest("form"); + assert.ok(form); + act(() => { + fireEvent.submit(form); + fireEvent.submit(form); + }); + assert.equal(saves, 1, "concurrent submits share one in-flight save"); + fireEvent.click(screen.getByRole("button", { name: "Close dialog" })); + fireEvent.click(screen.getByRole("button", { name: "Import PTCGL Log" })); + await act(async () => { + save.resolve(Response.json({ ok: true, redirectTo: "/logs/log-1" })); + }); + await act(async () => { + await new Promise((done) => setTimeout(done, 350)); + }); + assert.deepEqual(navigations, [], "an abandoned save cannot navigate a later dialog session"); + } finally { + cleanup(); + globalThis.fetch = originalFetch; + } +}); diff --git a/tests/local-e2e-battle-log-fixtures.test.ts b/tests/local-e2e-battle-log-fixtures.test.ts index 4a43ce4..5addc41 100644 --- a/tests/local-e2e-battle-log-fixtures.test.ts +++ b/tests/local-e2e-battle-log-fixtures.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import test from "node:test"; +import { identifiedBattleLog } from "./fixtures/battle-log-card-identifiers"; import { decodeLogSections } from "@/lib/battle-log/runtime-validation"; import { buildLocalE2EBattleLogFixture } from "@/scripts/local-e2e-battle-log-fixture"; @@ -21,6 +22,19 @@ test("local battle-log fixtures build renderable parsed sections and matching su }, ] as const; + const unnumbered = buildLocalE2EBattleLogFixture({ + rawLog: identifiedBattleLog, + ptcglUsername: "JammerUK1993" + }); + assert.equal( + unnumbered.totalTurns, + 4, + "unnumbered exports count the same player turns as numbered exports" + ); + assert.equal(unnumbered.goOrder, "Second"); + assert.equal(unnumbered.coinTossWon, false); + assert.equal(unnumbered.opponentAttackDamage, 30); + for (const expected of cases) { const fixture = buildLocalE2EBattleLogFixture({ rawLog: readFileSync( diff --git a/tests/log-import-player-identity.test.ts b/tests/log-import-player-identity.test.ts index ba49f4a..f7b1c9c 100644 --- a/tests/log-import-player-identity.test.ts +++ b/tests/log-import-player-identity.test.ts @@ -1,11 +1,96 @@ import assert from "node:assert/strict"; import test from "node:test"; +import { readFileSync } from "node:fs"; +import { parseBattleLog } from "@/lib/log-import/parser"; +import type { IdentificationCatalog } from "@/lib/log-import/types"; import { canonicalizeSelfPlayerSections, resolveSelfOpponent } from "@/lib/log-import/parser/players"; -test("an alternate PTCGL username identifies the importing player's side", () => { +test("player identities preserve outcomes, stats and card evidence", () => { + // Change only player identities in the committed export, never action wording. + const source = readFileSync("tests/e2e/fixtures/battle-log-valid.txt", "utf8"); + const catalog: IdentificationCatalog = { + pokemon: { + bySlug: new Map(), + normalizedNameToSlug: new Map([ + ["dreepy", "dreepy"], + ["charmander", "charmander"], + ["charizard", "charizard"] + ]), + slugToAncestors: new Map(), + slugToFamilyRoot: new Map(), + maxNameTokens: 1 + }, + archetypes: { + byId: new Map(), + normalizedLabelToIds: new Map(), + spriteToCandidateArchetypes: new Map(), + familyRootToCandidateArchetypes: new Map() + } + }; + for (const [self, opponent] of [ + ["Trainer", "OtherTrainer"], + ["Trainer[+]", "Opponent"], + ["Trainer", "Other. Trainer"], + ["Dreepy", "Charizard"], + ["Other. Trainer", "Trainer"], + ["-Trainer", "Opponent"] + ]) { + const parsed = parseBattleLog({ + rawLog: source.replaceAll("E2ETrainer", self).replaceAll("FixtureOpponent", opponent), + ptcglUsername: self, + catalog + }); + assert.equal(parsed.stats.result, "Win", `${opponent}: winner attribution`); + assert.equal(parsed.stats.selfAttackDamage, 200, `${self}: damage attribution`); + assert.equal(parsed.sections[1].prizesAfterTurn[self], 5, `${self}: prize attribution`); + assert.equal(parsed.stats.coinTossWon, true); + const opposite = parseBattleLog({ rawLog: parsed.rawLog, ptcglUsername: opponent, catalog }); + assert.equal(opposite.stats.result, "Loss"); + assert.equal(opposite.stats.coinTossWon, false); + + assert.deepEqual( + [...parsed.pokemonEvidence.self.mentionCounts], + [["dreepy", 1]], + `${self}: own card evidence only` + ); + assert.deepEqual( + [...parsed.pokemonEvidence.opponent.mentionCounts], + [["charmander", 1]], + `${opponent}: own card evidence only` + ); + } + + // Effect-driven plays (e.g. Rare Candy) are recorded as indented detail lines. + const detailEvolution = parseBattleLog({ + rawLog: source.replace( + "E2ETrainer played Dreepy to the Bench.\n", + "E2ETrainer played Dreepy to the Bench.\nE2ETrainer played Rare Candy.\n - E2ETrainer evolved Dreepy to Charizard on the Bench.\n" + ), + ptcglUsername: "E2ETrainer", + catalog + }); + assert.deepEqual( + [...detailEvolution.pokemonEvidence.self.mentionCounts], + [ + ["dreepy", 2], + ["charizard", 1] + ], + "detail-line plays remain card evidence" + ); + + assert.throws( + () => + parseBattleLog({ + rawLog: source.replace("E2ETrainer wins.", "UnknownTrainer wins."), + ptcglUsername: "E2ETrainer", + catalog + }), + /exactly one winner/, + "an unrelated winner must not silently become a loss" + ); assert.deepEqual( resolveSelfOpponent(["Opponent", "JJPokeMan2026"], "MainTrainer", [" jjpokeman2026 "]), { diff --git a/tests/log-import-stats.test.ts b/tests/log-import-stats.test.ts index 00848b4..2baba4c 100644 --- a/tests/log-import-stats.test.ts +++ b/tests/log-import-stats.test.ts @@ -3,6 +3,8 @@ import test from "node:test"; import { buildStats } from "@/lib/log-import/parser/stats"; import { divideIntoSections } from "@/lib/log-import/parser/turns"; import { getPrizesTakenFromLine, isPrizeTakenLine } from "@/lib/log-import/parser/stats"; +import { parseBattleLog } from "@/lib/log-import/parser"; +import { identifiedBattleLog } from "./fixtures/battle-log-card-identifiers"; import type { LogSection } from "@/types/index"; function buildSections(actions: LogSection["actions"][]): LogSection[] { @@ -28,7 +30,36 @@ function buildSections(actions: LogSection["actions"][]): LogSection[] { ]; } -test("buildStats counts Mirage Barrage damage listed in action details", () => { +test("buildStats counts recorded attack damage and setup mulligans", () => { + // Repeat the real appendix's mulligan event, retaining its bonus-draw wording. + const mulligans = parseBattleLog({ + rawLog: identifiedBattleLog.replace( + "Setup\n", + "Setup\nJammerUK1993 took a mulligan.\nJammerUK1993 took a mulligan.\ntyDspen drew 1 more card because JammerUK1993 took at least 1 mulligan.\n" + ), + ptcglUsername: "JammerUK1993", + catalog: { + pokemon: { + bySlug: new Map(), + normalizedNameToSlug: new Map(), + slugToAncestors: new Map(), + slugToFamilyRoot: new Map(), + maxNameTokens: 0 + }, + archetypes: { + byId: new Map(), + normalizedLabelToIds: new Map(), + spriteToCandidateArchetypes: new Map(), + familyRootToCandidateArchetypes: new Map() + } + } + }); + assert.equal(mulligans.stats.selfMulligans, 2); + assert.equal( + mulligans.stats.opponentMulligans, + 0, + "a bonus draw is not the drawing player's mulligan" + ); const stats = buildStats({ lines: [". Self wins."], language: "en", @@ -95,10 +126,7 @@ test("buildStats counts Mirage Barrage damage listed in action details", () => { sections: buildSections([[{ title: "Self's Dipplin used Festival Lead.", details: [`- ${attack}`, `- ${attack}`] }], []]) }); assert.equal(repeated.selfAttackDamage, 200, "two recorded Festival Lead attacks remain two attacks"); -}); - -test("buildStats adds Mirage Barrage title damage and benched damage details", () => { - const stats = buildStats({ + const titleAndDetails = buildStats({ lines: [". Self wins."], language: "en", selfPlayerName: "Self", @@ -117,8 +145,8 @@ test("buildStats adds Mirage Barrage title damage and benched damage details", ( ]) }); - assert.equal(stats.selfAttackDamage, 240); - assert.equal(stats.opponentAttackDamage, 0); + assert.equal(titleAndDetails.selfAttackDamage, 240); + assert.equal(titleAndDetails.opponentAttackDamage, 0); }); test("divideIntoSections groups unprefixed took-damage lines with the prior action", () => {