EDUrocks-3.0-frontend-source-code / assets /js /debug-date-preservation.js
EDUrocks's picture
Add files using upload-large-folder tool
77bd40d verified
Raw History Blame Contribute Delete
12.9 kB
/**
* 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');
})();