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, loadCampaignState } = await server.ssrLoadModule('/src/game/state/campaignState.ts'); storage.clear(); const empty = loadCampaignState(); assert(empty.version === 1 && empty.step === 'new', `Expected empty storage to create initial campaign state: ${JSON.stringify(empty)}`); 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', ''], completedCampVisits: 'visit-a', inventory: { bean: '3', wine: -2, empty: 0 }, selectedSortieUnitIds: { corrupted: true }, sortieFormationAssignments: 'front', sortieItemAssignments: { 'liu-bei': { bean: '2', wine: -1 }, '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 === 3 && malformed.inventory.wine === undefined && malformed.sortieItemAssignments['liu-bei']?.bean === 2 && 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-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, firstBattleReport: { battleId: 'first-battle-zhuo-commandery', outcome: 'victory', completedCampVisits: { corrupted: true } } }) ); const malformedReport = loadCampaignState(); assert( malformedReport.step === 'fourth-camp' && malformedReport.gold === 320, `Expected malformed report to be dropped without losing campaign progress: ${JSON.stringify(malformedReport)}` ); assert(malformedReport.firstBattleReport === undefined, `Expected malformed report to be discarded: ${JSON.stringify(malformedReport)}`); storage.clear(); storage.set( campaignStorageKey, JSON.stringify({ version: 1, updatedAt: '2026-07-04T01:00:00.000Z', step: 'fifth-camp', latestBattleId: 'missing-history-entry', battleHistory: { 'wrong-history-key': { battleId: 'first-battle-zhuo-commandery', battleTitle: 'Zhuo Commandery', 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 } }, objectives: [ { id: 'secure-village', label: 'Secure village', achieved: 'yes', status: 'lost', detail: 12, rewardGold: '80', targetTile: { x: '4', y: '5', radius: '2' } }, 'broken-objective' ], units: [ { unitId: 'liu-bei', name: 'Liu Bei', level: '4', exp: '33', hp: '28', maxHp: '30', equipment: 'broken' }, { unitId: '', name: 'Broken Unit', level: 99 } ], bonds: [ { id: 'oath-bond', title: 'Oath Bond', level: '2', exp: '22', battleExp: '4' }, { id: '', title: 'Broken Bond' } ], reserveTraining: [ { unitId: 'guan-yu', name: 'Guan Yu', expGained: '6', equipmentExpGained: '2', bondExpGained: '1', focusId: 'unknown-focus', focusLabel: 9, level: '5', exp: '44' }, 'broken-training' ], completedAt: '2026-07-04T01:00:00.000Z' }, corrupted: 'not-a-settlement' } }) ); const malformedHistory = loadCampaignState(); assert( Object.keys(malformedHistory.battleHistory).length === 1 && malformedHistory.battleHistory['first-battle-zhuo-commandery']?.rewardGold === 120 && 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, `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 === 1 && 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']?.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)}`); 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 }) ); const fallback = loadCampaignState(); assert(fallback.step === 'second-camp' && fallback.activeSaveSlot === 2, `Expected valid slotted save fallback: ${JSON.stringify(fallback)}`); console.log('Verified campaign save normalization, malformed-field/bond/sortie-item/latest-history/detail 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); } }