/** * Debug utility for validating Date object preservation in Unity cloud saves * * This script helps verify that JavaScript Date objects are properly preserved * through the JSON serialization/deserialization cycle. * * Usage: * 1. Include this script in the browser console * 2. Call validateDatePreservation() after playing a Unity game * 3. Check the console output for validation results */ (function() { 'use strict'; /** * Test the JSON serialization/deserialization with Date objects */ function testDateSerialization() { console.group('๐Ÿงช Testing Date Object Serialization'); // Create test data similar to Unity save records const testData = [ { key: '/idbfs/PlayerPrefs', value: new Uint8Array([1, 2, 3, 4, 5]), timestamp: new Date('2025-11-13T10:30:00.000Z'), mode: 33206 }, { key: '/idbfs/data.unity3d', value: new Uint8Array([10, 20, 30]), timestamp: new Date('2025-11-13T10:31:15.500Z'), mode: 33188 } ]; console.log('Original data:', testData); console.log('First timestamp is Date:', testData[0].timestamp instanceof Date); console.log('Can call .getTime():', testData[0].timestamp.getTime()); // Test serialization with custom replacer const serialized = JSON.stringify(testData, (key, value) => { if (value instanceof Date) { console.log(' โ†’ Replacing Date object:', value.toISOString()); return { __date__: value.toISOString() }; } return value; }); console.log('Serialized:', serialized); // Test deserialization with custom reviver const deserialized = JSON.parse(serialized, (key, value) => { if (value && typeof value === 'object' && value.__date__) { console.log(' โ†’ Restoring Date object from:', value.__date__); return new Date(value.__date__); } return value; }); console.log('Deserialized data:', deserialized); console.log('First timestamp is Date:', deserialized[0].timestamp instanceof Date); if (deserialized[0].timestamp instanceof Date) { console.log('โœ… Date object successfully preserved!'); console.log('Can call .getTime():', deserialized[0].timestamp.getTime()); } else { console.error('โŒ Date object NOT preserved!'); console.error('Type:', typeof deserialized[0].timestamp); console.error('Value:', deserialized[0].timestamp); } console.groupEnd(); return deserialized[0].timestamp instanceof Date; } /** * Validate Date objects in actual Unity IndexedDB data */ async function validateUnityIndexedDB() { console.group('๐Ÿ” Validating Unity IndexedDB Data'); return new Promise((resolve) => { const request = indexedDB.open('/idbfs'); request.onerror = () => { console.error('โŒ Failed to open Unity database'); console.groupEnd(); resolve(false); }; request.onsuccess = (e) => { const db = e.target.result; if (!db.objectStoreNames.contains('FILE_DATA')) { console.warn('โš ๏ธ FILE_DATA store not found'); console.groupEnd(); resolve(false); return; } const tx = db.transaction('FILE_DATA', 'readonly'); const store = tx.objectStore('FILE_DATA'); const getAllRequest = store.getAll(); getAllRequest.onsuccess = (e2) => { const records = e2.target.result; console.log(`Found ${records.length} records in FILE_DATA`); let dateCount = 0; let validDates = 0; let invalidDates = 0; records.forEach((record, index) => { if (record.timestamp) { dateCount++; const isDate = record.timestamp instanceof Date; console.log(`Record ${index}:`, { key: record.key, hasTimestamp: true, isDate: isDate, type: typeof record.timestamp, value: record.timestamp }); if (isDate) { validDates++; try { const time = record.timestamp.getTime(); console.log(' โœ… .getTime() works:', time); } catch (err) { console.error(' โŒ .getTime() failed:', err); invalidDates++; } } else { invalidDates++; console.error(' โŒ timestamp is not a Date object'); } } }); console.log('\n๐Ÿ“Š Summary:'); console.log(` Total records: ${records.length}`); console.log(` Records with timestamp: ${dateCount}`); console.log(` Valid Date objects: ${validDates}`); console.log(` Invalid Date objects: ${invalidDates}`); if (invalidDates === 0 && dateCount > 0) { console.log(' โœ… ALL timestamp fields are valid Date objects!'); } else if (invalidDates > 0) { console.error(' โŒ Some timestamp fields are NOT Date objects!'); } console.groupEnd(); resolve(invalidDates === 0); }; getAllRequest.onerror = () => { console.error('โŒ Failed to read FILE_DATA'); console.groupEnd(); resolve(false); }; }; }); } /** * Check what's stored on the backend for the current game */ async function checkBackendData(gameId) { console.group('โ˜๏ธ Checking Backend Data'); const token = localStorage.getItem('edurocks_auth_token'); if (!token) { console.error('โŒ Not logged in - no auth token'); console.groupEnd(); return; } try { const response = await fetch( `https://backendapi.edurocks.org/userauth/game-api.php?action=getSaves&gameId=${gameId}&token=${token}`, { credentials: 'include' } ); const result = await response.json(); console.log('Backend response:', result); if (!result.success) { console.error('โŒ Failed to fetch saves:', result.message); console.groupEnd(); return; } const saves = result.saves || {}; const saveKeys = Object.keys(saves); console.log(`Found ${saveKeys.length} save keys`); for (const key of saveKeys) { console.log(`\nSave key: ${key}`); if (key.startsWith('indexedDB:')) { try { // Parse with custom reviver const data = JSON.parse(saves[key], (k, v) => { if (v && typeof v === 'object' && v.__date__) { return new Date(v.__date__); } return v; }); console.log(` Records: ${data.length}`); // Check first record if (data.length > 0 && data[0].timestamp) { const isDate = data[0].timestamp instanceof Date; console.log(` First record timestamp is Date: ${isDate}`); if (isDate) { console.log(' โœ… Date object properly restored from backend'); } else { console.error(' โŒ Date object NOT restored from backend'); console.error(' Type:', typeof data[0].timestamp); console.error(' Value:', data[0].timestamp); } } // Check for __date__ markers in raw JSON const rawData = saves[key]; if (rawData.includes('"__date__"')) { console.log(' โœ… Backend data contains __date__ markers (serialization working)'); } else { console.warn(' โš ๏ธ Backend data missing __date__ markers (may have Date issues)'); } } catch (err) { console.error(' โŒ Failed to parse save data:', err); } } } console.groupEnd(); } catch (err) { console.error('โŒ Network error:', err); console.groupEnd(); } } /** * Main validation function - runs all tests */ async function validateDatePreservation(gameId) { console.clear(); console.log('๐Ÿ”ฌ Date Object Preservation Validation\n'); // Test 1: Serialization/Deserialization const serializationWorks = testDateSerialization(); console.log('\n'); // Test 2: IndexedDB validation const indexedDBValid = await validateUnityIndexedDB(); console.log('\n'); // Test 3: Backend data validation if (gameId) { await checkBackendData(gameId); } else { console.warn('โš ๏ธ No gameId provided, skipping backend validation'); console.log(' Usage: validateDatePreservation("highway-racer-2")'); } // Final summary console.log('\n' + '='.repeat(60)); console.log('๐Ÿ“‹ VALIDATION SUMMARY'); console.log('='.repeat(60)); console.log(`Serialization test: ${serializationWorks ? 'โœ… PASS' : 'โŒ FAIL'}`); console.log(`IndexedDB validation: ${indexedDBValid ? 'โœ… PASS' : 'โŒ FAIL'}`); if (serializationWorks && indexedDBValid) { console.log('\n๐ŸŽ‰ ALL TESTS PASSED - Date preservation is working correctly!'); } else { console.log('\nโš ๏ธ SOME TESTS FAILED - Date preservation may have issues'); } console.log('='.repeat(60)); } /** * Quick check for current save sync status */ function checkSaveSyncStatus() { console.group('๐Ÿ“Š Save Sync Status'); if (window.EDUrocksSaveSync) { const info = window.EDUrocksSaveSync.debugInfo(); console.log('Save Sync Active: โœ…'); console.log('Game ID:', info.gameId); console.log('Logged In:', info.isLoggedIn); console.log('Open Databases:', info.openDatabases); if (info.savedIndexedDBData) { console.log('Queued IndexedDB saves:', info.savedIndexedDBData.size); } } else { console.error('Save Sync NOT Active: โŒ'); console.log('Make sure you are on a game page with cloud save enabled'); } console.groupEnd(); } // Expose functions to window for console access window.debugDatePreservation = { validate: validateDatePreservation, testSerialization: testDateSerialization, checkIndexedDB: validateUnityIndexedDB, checkBackend: checkBackendData, checkStatus: checkSaveSyncStatus }; console.log('๐Ÿ› ๏ธ Date Preservation Debug Tools Loaded'); console.log('Available commands:'); console.log(' debugDatePreservation.validate("game-id") - Run full validation'); console.log(' debugDatePreservation.testSerialization() - Test JSON serialization'); console.log(' debugDatePreservation.checkIndexedDB() - Check Unity IndexedDB'); console.log(' debugDatePreservation.checkBackend("game-id") - Check backend data'); console.log(' debugDatePreservation.checkStatus() - Check save sync status'); })();