Files
heros_web/scripts/verify-campaign-save-normalization.mjs

856 lines
34 KiB
JavaScript

import { createServer } from 'vite';
const storage = new Map();
globalThis.window = {
localStorage: {
getItem(key) {
return storage.has(key) ? storage.get(key) : null;
},
setItem(key, value) {
storage.set(key, String(value));
},
removeItem(key) {
storage.delete(key);
},
clear() {
storage.clear();
}
}
};
const server = await createServer({
logLevel: 'error',
server: { middlewareMode: true },
appType: 'custom'
});
try {
const {
campaignStorageKey,
applyCampBondExp,
applyCampVisitReward,
getCampaignState,
hasCampaignSave,
loadCampaignState,
normalizeCampaignSortieItemAssignments,
resetCampaignState,
setCampaignState,
setFirstBattleReport
} = await server.ssrLoadModule('/src/game/state/campaignState.ts');
const { battleScenarios } = await server.ssrLoadModule('/src/game/data/battles.ts');
storage.clear();
const empty = loadCampaignState();
assert(empty.version === 1 && empty.step === 'new', `Expected empty storage to create initial campaign state: ${JSON.stringify(empty)}`);
const normalizedLaunchSupplies = normalizeCampaignSortieItemAssignments(
{
'liu-bei': { bean: '9', salve: '2', stone: '4' },
'guan-yu': { wine: '3' },
'ghost-unit': { bean: '1' },
'': { bean: '1' }
},
new Set(['liu-bei', 'guan-yu'])
);
assert(
normalizedLaunchSupplies['liu-bei']?.bean === 2 &&
normalizedLaunchSupplies['liu-bei']?.salve === 1 &&
normalizedLaunchSupplies['liu-bei']?.stone === undefined &&
normalizedLaunchSupplies['guan-yu']?.wine === 1 &&
normalizedLaunchSupplies['ghost-unit'] === undefined,
`Expected launch sortie supplies to share save normalization rules: ${JSON.stringify(normalizedLaunchSupplies)}`
);
resetCampaignState();
const firstScenario = battleScenarios['first-battle-zhuo-commandery'];
const alliedFirstBattleUnits = firstScenario.units.filter((unit) => unit.faction === 'ally');
const firstBattleReport = {
battleId: firstScenario.id,
battleTitle: firstScenario.title,
outcome: 'victory',
turnNumber: 5,
rewardGold: 100,
defeatedEnemies: 2,
totalEnemies: 4,
objectives: [],
units: alliedFirstBattleUnits,
bonds: firstScenario.bonds.map((bond) => ({ ...bond, battleExp: 0 })),
itemRewards: ['Bean x2'],
campaignRewards: { supplies: ['Bean x2'], equipment: [], reputation: [], recruits: [], unlocks: [] },
completedCampDialogues: [],
completedCampVisits: [],
createdAt: '2026-07-03T09:00:00.000Z'
};
setFirstBattleReport(firstBattleReport);
setFirstBattleReport(firstBattleReport);
const repeatedSettlement = getCampaignState();
assert(
repeatedSettlement.gold === 100 &&
repeatedSettlement.inventory.Bean === 2 &&
repeatedSettlement.battleHistory[firstScenario.id]?.rewardGold === 100,
`Expected repeated battle report settlement to avoid duplicate gold/items: ${JSON.stringify(repeatedSettlement)}`
);
setFirstBattleReport({
...firstBattleReport,
rewardGold: 140,
itemRewards: ['Bean x3', 'Wine'],
campaignRewards: { supplies: ['Bean x3', 'Wine'], equipment: [], reputation: [], recruits: [], unlocks: [] }
});
const revisedSettlement = getCampaignState();
assert(
revisedSettlement.gold === 140 &&
revisedSettlement.inventory.Bean === 3 &&
revisedSettlement.inventory.Wine === 1,
`Expected revised battle report settlement to replace previous rewards instead of stacking: ${JSON.stringify(revisedSettlement)}`
);
applyCampVisitReward('repeat-visit', { gold: 10, itemRewards: ['Bean x2'] });
applyCampVisitReward('repeat-visit', { gold: 10, itemRewards: ['Bean x2'] });
const repeatedVisit = getCampaignState();
assert(
repeatedVisit.gold === 150 &&
repeatedVisit.inventory.Bean === 5 &&
repeatedVisit.completedCampVisits.includes('repeat-visit') &&
repeatedVisit.firstBattleReport?.completedCampVisits.includes('repeat-visit'),
`Expected repeated camp visit rewards to be applied once: ${JSON.stringify(repeatedVisit)}`
);
const visitDesynced = getCampaignState();
visitDesynced.completedCampVisits = [];
visitDesynced.firstBattleReport.completedCampVisits = ['repeat-visit'];
setCampaignState(visitDesynced);
applyCampVisitReward('repeat-visit', { gold: 10, itemRewards: ['Bean x2'] });
const visitResynced = getCampaignState();
assert(
visitResynced.gold === 150 &&
visitResynced.inventory.Bean === 5 &&
visitResynced.completedCampVisits.includes('repeat-visit') &&
visitResynced.firstBattleReport?.completedCampVisits.includes('repeat-visit'),
`Expected report-only camp visit completion to resync without duplicate rewards: ${JSON.stringify(visitResynced)}`
);
applyCampVisitReward('dirty-reward-visit', { itemRewards: ['', ' ', 'Bean -2', 'Bean +0', 'Bean x2'] });
const dirtyRewardVisit = getCampaignState();
assert(
dirtyRewardVisit.inventory.Bean === 7 &&
dirtyRewardVisit.inventory[''] === undefined &&
dirtyRewardVisit.inventory['Bean -'] === undefined &&
dirtyRewardVisit.completedCampVisits.includes('dirty-reward-visit'),
`Expected malformed reward labels to be ignored while valid rewards apply: ${JSON.stringify(dirtyRewardVisit)}`
);
const repeatBondId = firstScenario.bonds[0].id;
applyCampBondExp('repeat-dialogue', repeatBondId, 10);
const repeatedDialogueOnce = getCampaignState();
applyCampBondExp('repeat-dialogue', repeatBondId, 10);
const repeatedDialogueTwice = getCampaignState();
const onceBond = repeatedDialogueOnce.bonds.find((bond) => bond.id === repeatBondId);
const twiceBond = repeatedDialogueTwice.bonds.find((bond) => bond.id === repeatBondId);
assert(
onceBond?.exp === twiceBond?.exp &&
onceBond?.battleExp === twiceBond?.battleExp &&
repeatedDialogueTwice.completedCampDialogues.includes('repeat-dialogue') &&
repeatedDialogueTwice.firstBattleReport?.completedCampDialogues.includes('repeat-dialogue'),
`Expected repeated camp dialogue rewards to be applied once: ${JSON.stringify(repeatedDialogueTwice)}`
);
const dialogueDesynced = getCampaignState();
dialogueDesynced.completedCampDialogues = [];
dialogueDesynced.firstBattleReport.completedCampDialogues = ['repeat-dialogue'];
setCampaignState(dialogueDesynced);
applyCampBondExp('repeat-dialogue', repeatBondId, 10);
const dialogueResynced = getCampaignState();
const resyncedBond = dialogueResynced.bonds.find((bond) => bond.id === repeatBondId);
assert(
resyncedBond?.exp === twiceBond?.exp &&
resyncedBond?.battleExp === twiceBond?.battleExp &&
dialogueResynced.completedCampDialogues.includes('repeat-dialogue') &&
dialogueResynced.firstBattleReport?.completedCampDialogues.includes('repeat-dialogue'),
`Expected report-only camp dialogue completion to resync without duplicate bond exp: ${JSON.stringify(dialogueResynced)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
updatedAt: '2026-07-01T00:00:00.000Z',
step: 'first-camp',
activeSaveSlot: 1,
gold: 180,
inventory: { bean: 2 },
completedCampDialogues: ['bond-a', 'bond-a'],
completedCampVisits: ['visit-a', 'visit-a']
})
);
const legacy = loadCampaignState();
assert(legacy.version === 1, `Expected legacy save without version to normalize to v1: ${JSON.stringify(legacy)}`);
assert(legacy.step === 'first-camp' && legacy.gold === 180, `Expected legacy save progress to survive: ${JSON.stringify(legacy)}`);
assert(Array.isArray(legacy.roster) && Array.isArray(legacy.bonds), `Expected legacy save arrays to be restored: ${JSON.stringify(legacy)}`);
assert(
legacy.completedCampDialogues.length === 1 && legacy.completedCampVisits.length === 1,
`Expected legacy save duplicate completion flags to be deduped: ${JSON.stringify(legacy)}`
);
assert(
Array.isArray(legacy.selectedSortieUnitIds) &&
typeof legacy.sortieFormationAssignments === 'object' &&
typeof legacy.sortieItemAssignments === 'object',
`Expected modern sortie fields to be restored: ${JSON.stringify(legacy)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '',
step: 'third-camp',
activeSaveSlot: '2',
gold: '410',
roster: { corrupted: true },
bonds: [
{ id: 'broken-bond', title: 'Broken Bond', unitIds: { corrupted: true }, level: 3, exp: 12, battleExp: 2 },
{ id: 'oath-bond', title: 'Oath Bond', unitIds: ['liu-bei', 'guan-yu'], level: '2', exp: '14', battleExp: '5' },
9
],
completedCampDialogues: ['dialogue-a', 17, 'dialogue-a', '', 'x'.repeat(97)],
completedCampVisits: 'visit-a',
inventory: { bean: '3', ' bean ': '4', ['\uCF69']: '200', [' \uCF69 ']: '20', wine: -2, empty: 0 },
selectedSortieUnitIds: { corrupted: true },
sortieFormationAssignments: 'front',
sortieItemAssignments: {
'liu-bei': { bean: '5', wine: -1, salve: '1', stone: '9' },
'guan-yu': '2',
'zhang-fei': ['bean', '2'],
'': { bean: 4 }
},
battleHistory: []
})
);
const malformed = loadCampaignState();
assert(malformed.step === 'third-camp', `Expected malformed save progress to survive: ${JSON.stringify(malformed)}`);
assert(malformed.activeSaveSlot === 2 && malformed.gold === 410, `Expected malformed numeric fields to normalize: ${JSON.stringify(malformed)}`);
assert(Array.isArray(malformed.roster) && malformed.roster.length === 0, `Expected malformed roster to reset to an array: ${JSON.stringify(malformed)}`);
assert(
Array.isArray(malformed.bonds) &&
malformed.bonds.length === 1 &&
malformed.bonds[0].id === 'oath-bond' &&
malformed.bonds[0].level === 2 &&
malformed.bonds[0].unitIds.length === 2,
`Expected malformed bond entries to be filtered while valid bonds normalize: ${JSON.stringify(malformed)}`
);
assert(
malformed.completedCampDialogues.length === 1 &&
malformed.completedCampDialogues[0] === 'dialogue-a' &&
malformed.completedCampVisits.length === 0,
`Expected malformed completion lists to keep unique strings only: ${JSON.stringify(malformed)}`
);
assert(
malformed.inventory.bean === 7 &&
malformed.inventory['\uCF69'] === 120 &&
malformed.inventory[' bean '] === undefined &&
malformed.inventory[' \uCF69 '] === undefined &&
malformed.inventory.wine === undefined &&
malformed.sortieItemAssignments['liu-bei']?.bean === 2 &&
malformed.sortieItemAssignments['liu-bei']?.salve === 1 &&
malformed.sortieItemAssignments['liu-bei']?.stone === undefined &&
malformed.sortieItemAssignments['liu-bei']?.wine === undefined &&
malformed.sortieItemAssignments['guan-yu'] === undefined &&
malformed.sortieItemAssignments['zhang-fei'] === undefined &&
Object.keys(malformed.sortieItemAssignments).length === 1 &&
Object.keys(malformed.sortieFormationAssignments).length === 0,
`Expected malformed inventory and sortie assignments to normalize: ${JSON.stringify(malformed)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-03T12:30:00.000Z',
step: 'third-camp',
activeSaveSlot: 1,
completedCampDialogues: Array.from({ length: 140 }, (_, index) => `dialogue-${index}`),
completedCampVisits: ['visit-a', 'x'.repeat(97), 'visit-a']
})
);
const cappedStringLists = loadCampaignState();
assert(
cappedStringLists.completedCampDialogues.length === 128 &&
cappedStringLists.completedCampDialogues[0] === 'dialogue-0' &&
cappedStringLists.completedCampDialogues[127] === 'dialogue-127' &&
cappedStringLists.completedCampVisits.length === 1,
`Expected campaign string lists to filter long entries and cap excessive saves: ${JSON.stringify(cappedStringLists)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-03T12:00:00.000Z',
step: 'third-camp',
activeSaveSlot: 1,
roster: [{ id: 'liu-bei', name: 'Liu Bei', faction: 'ally' }],
selectedSortieUnitIds: ['liu-bei', 'ghost-unit', 'guan-yu', 'liu-bei'],
sortieFormationAssignments: {
'liu-bei': 'front',
'ghost-unit': 'flank',
'guan-yu': 'support',
broken: 'center'
},
sortieItemAssignments: {
'liu-bei': { bean: '2' },
'ghost-unit': { bean: '1' },
'guan-yu': { wine: '1' }
}
})
);
const staleSortie = loadCampaignState();
assert(
staleSortie.selectedSortieUnitIds.length === 1 &&
staleSortie.selectedSortieUnitIds[0] === 'liu-bei' &&
staleSortie.sortieFormationAssignments['liu-bei'] === 'front' &&
staleSortie.sortieFormationAssignments['ghost-unit'] === undefined &&
staleSortie.sortieItemAssignments['liu-bei']?.bean === 2 &&
staleSortie.sortieItemAssignments['ghost-unit'] === undefined &&
staleSortie.sortieItemAssignments['guan-yu'] === undefined,
`Expected stale sortie ids to be filtered against the recovered roster: ${JSON.stringify(staleSortie)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-03T13:00:00.000Z',
step: 'third-camp',
activeSaveSlot: 1,
roster: [
{ id: 'liu-bei', name: 'Liu Bei', faction: 'ally' },
{ id: 'guan-yu', name: 'Guan Yu', faction: 'ally' }
],
bonds: [
{ id: 'liu-bei__guan-yu', title: 'Oath Bond', unitIds: ['liu-bei', 'guan-yu'], level: '2', exp: '30', battleExp: '4' },
{ id: 'liu-bei__ghost', title: 'Ghost Bond', unitIds: ['liu-bei', 'ghost-unit'], level: '3', exp: '40', battleExp: '5' }
]
})
);
const staleBonds = loadCampaignState();
assert(
staleBonds.bonds.length === 1 &&
staleBonds.bonds[0].id === 'liu-bei__guan-yu' &&
staleBonds.bonds[0].level === 2 &&
staleBonds.bonds[0].battleExp === 4,
`Expected stale bonds to be filtered against the recovered roster while valid bonds survive: ${JSON.stringify(staleBonds)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-03T13:30:00.000Z',
step: 'third-camp',
activeSaveSlot: 1,
roster: [
{ id: 'liu-bei', name: 'Liu Bei', faction: 'ally' },
{ id: 'guan-yu', name: 'Guan Yu', faction: 'ally' }
],
firstBattleReport: {
battleId: 'first-battle-zhuo-commandery',
outcome: 'victory',
createdAt: '2026-07-03T13:30:00.000Z',
units: [{ id: 'rebel-a', name: 'Rebel', faction: 'enemy' }],
bonds: [
{ id: 'liu-bei__guan-yu', title: 'Oath Bond', unitIds: ['liu-bei', 'guan-yu'], level: 2, exp: 30, battleExp: 4 },
{ id: 'liu-bei__ghost', title: 'Ghost Bond', unitIds: ['liu-bei', 'ghost-unit'], level: 3, exp: 40, battleExp: 5 }
],
mvp: { unitId: 'ghost-unit', name: 'Ghost', damageDealt: 99, defeats: 4 }
}
})
);
const staleReportRefs = loadCampaignState();
assert(
staleReportRefs.firstBattleReport?.bonds.length === 1 &&
staleReportRefs.firstBattleReport.bonds[0].id === 'liu-bei__guan-yu' &&
staleReportRefs.firstBattleReport.mvp === undefined,
`Expected first battle report bonds and MVP to be filtered against the recovered roster: ${JSON.stringify(staleReportRefs)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-03T14:00:00.000Z',
step: 'third-camp',
activeSaveSlot: 1,
roster: [
{
id: 'liu-bei',
name: 'Liu Bei',
faction: 'ally',
className: 'Lord',
classKey: 'lost-class',
level: '6',
exp: '18',
hp: '42',
maxHp: '45',
attack: '22',
move: '5',
stats: { might: '19', intelligence: '17', leadership: '21', agility: '13', luck: '12' },
equipment: {
weapon: { itemId: 'short-bow', level: '3', exp: '14' },
armor: { itemId: 'short-bow', level: '2', exp: '9' },
accessory: { itemId: 'grain-pouch', level: '0', exp: '7' }
},
x: '2',
y: '3'
},
{ id: 'ghost-unit', name: 'Ghost', faction: 'neutral' }
]
})
);
const malformedRoster = loadCampaignState();
assert(
malformedRoster.roster.length === 1 &&
malformedRoster.roster[0].id === 'liu-bei' &&
malformedRoster.roster[0].classKey === 'infantry' &&
malformedRoster.roster[0].level === 6 &&
malformedRoster.roster[0].equipment.weapon.itemId === 'short-bow' &&
malformedRoster.roster[0].equipment.weapon.level === 3 &&
malformedRoster.roster[0].equipment.armor.itemId === 'cloth-armor' &&
malformedRoster.roster[0].equipment.accessory.itemId === 'grain-pouch' &&
malformedRoster.roster[0].equipment.accessory.level === 1,
`Expected malformed roster units and equipment to be normalized safely: ${JSON.stringify(malformedRoster)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-03T00:00:00.000Z',
step: 'lost-between-battles',
activeSaveSlot: 1,
gold: 90
})
);
const invalidStep = loadCampaignState();
assert(invalidStep.step === 'new', `Expected unknown campaign step to reset safely: ${JSON.stringify(invalidStep)}`);
assert(invalidStep.gold === 90, `Expected unknown-step save to keep harmless economy data: ${JSON.stringify(invalidStep)}`);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-04T00:00:00.000Z',
step: 'fourth-camp',
activeSaveSlot: 1,
gold: 320,
roster: alliedFirstBattleUnits,
firstBattleReport: {
battleId: 'first-battle-zhuo-commandery',
battleTitle: ' ',
outcome: 'victory',
turnNumber: '4',
rewardGold: '120',
defeatedEnemies: '3',
totalEnemies: '5',
objectives: [
{ id: 'village', label: 'Village', achieved: true, detail: 12, summary: 'x'.repeat(220), rewardGold: '80' },
{ id: '', label: 'Broken', achieved: true },
...Array.from({ length: 30 }, (_, index) => ({
id: `bonus-${index}`,
label: `Bonus ${index}`,
achieved: false,
detail: 'Hold the ridge',
rewardGold: 10
}))
],
units: [
{
id: 'liu-bei',
name: 'Liu Bei',
faction: 'ally',
className: 'Lord',
classKey: 'lord',
level: '5',
exp: '15',
hp: '41',
maxHp: '44',
attack: '21',
move: '5',
stats: { might: '18', intelligence: '17', leadership: '20', agility: '12', luck: '11' },
equipment: {},
x: '2',
y: '3'
},
{ id: 'broken-unit', name: 'Broken' },
...Array.from({ length: 120 }, (_, index) => ({
id: `enemy-${index}`,
name: `Enemy ${index}`,
faction: 'enemy',
className: 'Infantry',
classKey: 'infantry',
level: 1,
exp: 0,
hp: 20,
maxHp: 20,
attack: 12,
move: 4,
stats: { might: 8, intelligence: 5, leadership: 6, agility: 7, luck: 5 },
equipment: {},
x: index % 12,
y: Math.floor(index / 12)
}))
],
bonds: [
{ id: 'liu-bei__guan-yu', title: 'Oath Bond', unitIds: ['liu-bei', 'guan-yu'], level: '2', exp: '30', battleExp: '4' },
{ id: 'broken-bond', title: 'Broken Bond', unitIds: ['liu-bei'] },
...Array.from({ length: 120 }, (_, index) => ({
id: `bond-${index}`,
title: `Bond ${index}`,
unitIds: ['liu-bei', 'guan-yu'],
level: 1,
exp: 0,
battleExp: 1
}))
],
mvp: { unitId: 'liu-bei', name: 'Liu Bei', damageDealt: '88', defeats: '2' },
itemRewards: ['Bean', 'Bean', 10, 'x'.repeat(97)],
campaignRewards: {
supplies: [' Bean ', 'Bean', 20, 'x'.repeat(97)],
equipment: [' Iron Sword ', 'Iron Sword'],
reputation: ['Village Thanks', ' Village Thanks '],
recruits: [
{ unitId: ' guan-yu ', name: ' Guan Yu ' },
{ unitId: '', name: 'Broken' },
...Array.from({ length: 140 }, (_, index) => ({ unitId: `recruit-${index}`, name: `Recruit ${index}` }))
],
unlocks: [
{ battleId: ' second-battle-yellow-turban-pursuit ', title: ' Next ' },
{ battleId: '', title: 'Broken' },
...Array.from({ length: 140 }, (_, index) => ({ battleId: `battle-${index}`, title: `Battle ${index}` }))
],
note: ' Reward note '
},
completedCampDialogues: ['intro', 'intro', 7],
completedCampVisits: { corrupted: true },
createdAt: 42
}
})
);
const malformedReport = loadCampaignState();
assert(
malformedReport.step === 'fourth-camp' && malformedReport.gold === 320,
`Expected report recovery to keep campaign progress: ${JSON.stringify(malformedReport)}`
);
assert(
malformedReport.firstBattleReport?.battleId === 'first-battle-zhuo-commandery' &&
malformedReport.firstBattleReport.battleTitle === firstScenario.title &&
malformedReport.firstBattleReport.turnNumber === 4 &&
malformedReport.firstBattleReport.objectives.length === 24 &&
malformedReport.firstBattleReport.objectives[0].rewardGold === 80 &&
malformedReport.firstBattleReport.objectives[0].summary.length === 180 &&
malformedReport.firstBattleReport.units.length === 96 &&
malformedReport.firstBattleReport.units[0].level === 5 &&
malformedReport.firstBattleReport.bonds.length === 96 &&
malformedReport.firstBattleReport.bonds[0].battleExp === 4 &&
malformedReport.firstBattleReport.mvp?.damageDealt === 88 &&
malformedReport.firstBattleReport.itemRewards.length === 1 &&
malformedReport.firstBattleReport.campaignRewards?.supplies.length === 1 &&
malformedReport.firstBattleReport.campaignRewards?.supplies[0] === 'Bean' &&
malformedReport.firstBattleReport.campaignRewards?.equipment.length === 1 &&
malformedReport.firstBattleReport.campaignRewards?.reputation.length === 1 &&
malformedReport.firstBattleReport.campaignRewards?.recruits.length === 128 &&
malformedReport.firstBattleReport.campaignRewards?.recruits[0].unitId === 'guan-yu' &&
malformedReport.firstBattleReport.campaignRewards?.unlocks.length === 128 &&
malformedReport.firstBattleReport.campaignRewards?.unlocks[0].battleId === 'second-battle-yellow-turban-pursuit' &&
malformedReport.firstBattleReport.campaignRewards?.note === 'Reward note' &&
malformedReport.firstBattleReport.completedCampDialogues.length === 1 &&
malformedReport.firstBattleReport.completedCampVisits.length === 0,
`Expected malformed report fields to be normalized without discarding the report: ${JSON.stringify(malformedReport)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-04T00:30:00.000Z',
step: 'fourth-camp',
firstBattleReport: {
battleId: 'unknown-battle-id',
battleTitle: 'Unknown Battle',
outcome: 'victory',
turnNumber: 4,
rewardGold: 120,
defeatedEnemies: 3,
totalEnemies: 5,
objectives: [],
units: [],
bonds: [],
itemRewards: [],
completedCampDialogues: [],
completedCampVisits: [],
createdAt: '2026-07-04T00:30:00.000Z'
}
})
);
const unknownReport = loadCampaignState();
assert(
unknownReport.step === 'fourth-camp' && unknownReport.firstBattleReport === undefined,
`Expected first battle report with unknown battle id to be discarded safely: ${JSON.stringify(unknownReport)}`
);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-04T01:00:00.000Z',
step: 'fifth-camp',
latestBattleId: 'missing-history-entry',
roster: alliedFirstBattleUnits,
bonds: firstScenario.bonds,
battleHistory: {
'wrong-history-key': {
battleId: 'first-battle-zhuo-commandery',
battleTitle: ' ',
outcome: 'victory',
rewardGold: '120',
itemRewards: ['Bean', 12, 'Bean'],
campaignRewards: {
supplies: { corrupted: true },
equipment: ['Iron Sword'],
reputation: 'Fame',
recruits: [{ unitId: 'test-recruit', name: 'Test Recruit' }, { broken: true }],
unlocks: { corrupted: true },
note: 'x'.repeat(181)
},
objectives: [
{
id: 'secure-village',
label: 'Secure village',
achieved: 'yes',
status: 'lost',
detail: 12,
rewardGold: '80',
targetTile: { x: '4', y: '5', radius: '2' }
},
'broken-objective',
...Array.from({ length: 30 }, (_, index) => ({
id: `history-bonus-${index}`,
label: `History Bonus ${index}`,
achieved: false,
detail: 'Hold formation',
rewardGold: 5
}))
],
units: [
{ unitId: 'liu-bei', name: 'Liu Bei', level: '4', exp: '33', hp: '28', maxHp: '30', equipment: 'broken' },
{ unitId: '', name: 'Broken Unit', level: 99 },
...Array.from({ length: 120 }, (_, index) => ({
unitId: `history-unit-${index}`,
name: `History Unit ${index}`,
level: 1,
exp: 0,
hp: 12,
maxHp: 12,
equipment: {}
}))
],
bonds: [
{ id: firstScenario.bonds[0].id, title: firstScenario.bonds[0].title, level: '2', exp: '22', battleExp: '4' },
{ id: '', title: 'Broken Bond' },
...Array.from({ length: 120 }, (_, index) => ({
id: `history-bond-${index}`,
title: `History Bond ${index}`,
level: 1,
exp: 0,
battleExp: 1
}))
],
reserveTraining: [
{
unitId: 'guan-yu',
name: 'Guan Yu',
expGained: '6',
equipmentExpGained: '2',
bondExpGained: '1',
focusId: 'unknown-focus',
focusLabel: 9,
level: '5',
exp: '44'
},
'broken-training',
...Array.from({ length: 120 }, (_, index) => ({
unitId: `reserve-${index}`,
name: `Reserve ${index}`,
expGained: 3,
equipmentExpGained: 1,
focusId: 'balanced',
focusLabel: 'Balanced',
level: 1,
exp: 3
}))
],
completedAt: '2026-07-04T01:00:00.000Z'
},
'unknown-battle-key': {
battleId: 'unknown-battle-id',
battleTitle: 'Unknown Battle',
outcome: 'victory',
rewardGold: 999,
itemRewards: [],
campaignRewards: { supplies: [], equipment: [], reputation: [], recruits: [], unlocks: [] },
objectives: [],
units: [],
bonds: [],
reserveTraining: [],
completedAt: '2026-07-04T02:00:00.000Z'
},
'invalid-date-history-key': {
battleId: 'second-battle-yellow-turban-pursuit',
battleTitle: 'Invalid Date Battle',
outcome: 'victory',
rewardGold: 999,
itemRewards: [],
campaignRewards: { supplies: [], equipment: [], reputation: [], recruits: [], unlocks: [] },
objectives: [],
units: [],
bonds: [],
reserveTraining: [],
completedAt: 'not-a-date'
},
corrupted: 'not-a-settlement'
}
})
);
const malformedHistory = loadCampaignState();
assert(
Object.keys(malformedHistory.battleHistory).length === 1 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.rewardGold === 120 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.battleTitle === firstScenario.title &&
malformedHistory.battleHistory['wrong-history-key'] === undefined,
`Expected malformed battle history entries to be filtered while valid settlements are keyed by battleId: ${JSON.stringify(malformedHistory)}`
);
assert(
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.itemRewards.length === 1 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.campaignRewards?.equipment[0] === 'Iron Sword' &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.campaignRewards?.recruits.length === 1 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.campaignRewards?.note === undefined,
`Expected nested battle history rewards to normalize: ${JSON.stringify(malformedHistory)}`
);
assert(
malformedHistory.latestBattleId === 'first-battle-zhuo-commandery',
`Expected stale latestBattleId to recover to the latest valid settlement: ${JSON.stringify(malformedHistory)}`
);
assert(
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.objectives.length === 24 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.objectives[0].rewardGold === 80 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.objectives[0].targetTile?.x === 4 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.objectives[0].status === undefined &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.units.length === 1 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.units[0].level === 4 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.units[0].equipment.weapon.itemId === 'training-sword' &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.units[0].equipment.armor.itemId === 'cloth-armor' &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.units[0].equipment.accessory.itemId === 'grain-pouch' &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.bonds.length === 1 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.bonds[0].battleExp === 4 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.reserveTraining?.length === 1 &&
malformedHistory.battleHistory['first-battle-zhuo-commandery']?.reserveTraining?.[0].focusId === 'balanced',
`Expected nested battle history progress arrays to filter invalid entries and normalize numbers: ${JSON.stringify(malformedHistory)}`
);
storage.clear();
storage.set(campaignStorageKey, JSON.stringify({ version: 99, step: 'sixty-sixth-camp' }));
const unsupported = loadCampaignState();
assert(unsupported.step === 'new', `Expected unsupported future save version to be ignored: ${JSON.stringify(unsupported)}`);
assert(!hasCampaignSave(), 'Expected unsupported base save without valid slots to be ignored by hasCampaignSave');
storage.clear();
storage.set(campaignStorageKey, JSON.stringify({ version: 99, step: 'sixty-sixth-camp' }));
storage.set(
`${campaignStorageKey}:slot-2`,
JSON.stringify({
version: 1,
updatedAt: '2026-07-02T00:00:00.000Z',
step: 'second-camp',
activeSaveSlot: 2,
gold: 260
})
);
assert(hasCampaignSave(), 'Expected valid slotted save fallback to be visible to hasCampaignSave');
const fallback = loadCampaignState();
assert(fallback.step === 'second-camp' && fallback.activeSaveSlot === 2, `Expected valid slotted save fallback: ${JSON.stringify(fallback)}`);
storage.clear();
storage.set(
campaignStorageKey,
JSON.stringify({
version: 1,
updatedAt: '2026-07-01T00:00:00.000Z',
step: 'first-camp',
activeSaveSlot: 1,
gold: 100
})
);
storage.set(
`${campaignStorageKey}:slot-1`,
JSON.stringify({
version: 1,
updatedAt: '2026-07-02T00:00:00.000Z',
step: 'second-camp',
activeSaveSlot: 1,
gold: 200
})
);
const normalizedSlotFallback = loadCampaignState(0);
assert(
normalizedSlotFallback.step === 'second-camp' && normalizedSlotFallback.gold === 200,
`Expected explicit slot boundary values to normalize to slot 1 instead of base save: ${JSON.stringify(normalizedSlotFallback)}`
);
storage.clear();
storage.set(campaignStorageKey, JSON.stringify({ version: 99, step: 'sixty-sixth-camp' }));
storage.set(
`${campaignStorageKey}:slot-1`,
JSON.stringify({
version: 1,
updatedAt: 'zzzz-latest-looking-corruption',
step: 'sixty-sixth-camp',
activeSaveSlot: 1,
gold: 999
})
);
storage.set(
`${campaignStorageKey}:slot-2`,
JSON.stringify({
version: 1,
updatedAt: '2026-07-02T00:00:00.000Z',
step: 'second-camp',
activeSaveSlot: 2,
gold: 260
})
);
const timestampSafeFallback = loadCampaignState();
assert(
timestampSafeFallback.step === 'second-camp' && timestampSafeFallback.activeSaveSlot === 2,
`Expected latest slotted fallback to ignore invalid timestamp saves: ${JSON.stringify(timestampSafeFallback)}`
);
const corruptedSlot = loadCampaignState(1);
assert(
!Number.isNaN(Date.parse(corruptedSlot.updatedAt)) && corruptedSlot.updatedAt !== 'zzzz-latest-looking-corruption',
`Expected explicitly loaded corrupted slot timestamp to be normalized: ${JSON.stringify(corruptedSlot)}`
);
console.log('Verified campaign save normalization, reward resettlement, camp reward idempotence, malformed-field/roster-equipment/bond-roster/report-reference/sortie-roster/latest-history/detail recovery, timestamp-safe history/slot recovery, unknown-step/report/history recovery, unsupported-version rejection, and slotted fallback.');
} finally {
await server.close();
}
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}