deckhearth/scripts/import-lorcana.js
Randall Stillwell ac8c998935 feat(brand): in-repo display + comment sweep for Deck Hearth (B1 of 2)
Mechanical sweep of 7 internal files — AGENTS.md branding note, two
Cursor rules (ui-and-theming, auth-and-permissions), scripts/README.md,
two pages/api/cards/import-* User-Agent strings, scripts/import-lorcana.js
comment block. Applies D1 (Deck Hearth) + D2 (deck-hearth) per operator
gate-1 ratification.

EXCLUDES (B2 owns): lib/rate-limit.js Redis prefix, package.json name,
package-lock.json regen, README.md, TESTING_GUIDE.md, three seed scripts,
pages/login.js demo-credential pre-fill, test/lib/permission-middleware
regression-lock literal (PRESERVED per Risk 4).

Verification:
- npm run lint: 128 problems (baseline preserved)
- npm run test:run: 21/21 pass
- Grep: 0 hits for `TCG Vault` in B1's seven files; expected B2 hits remain
- git diff --name-only matches B1 spec exactly

Architect brief: .convoys/pick-a-name/brief-1-display-and-comment-sweep.md
Architect commit: 50ce9ab
Operator gate-1: D1+D2 ratified.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 01:52:11 -05:00

160 lines
No EOL
4.9 KiB
JavaScript

import fetch from 'node-fetch';
import fs from 'fs';
// Lorcana sets to import
const LORCANA_SETS = [
{ code: 'tfc', name: 'The First Chapter', lorcastCode: '1' },
{ code: 'rotf', name: 'Rise of the Floodborn', lorcastCode: '2' },
{ code: 'ink', name: 'Into the Inklands', lorcastCode: '3' }
];
// Helper function to delay execution
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Helper function to fetch with retry logic
async function fetchWithRetry(url, maxRetries = 3, delayMs = 2000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, {
headers: {
'User-Agent': 'Deck-Hearth/1.0',
'Accept': 'application/json'
},
timeout: 30000 // 30 second timeout
});
if (response.ok) {
return response;
}
// If it's a 404, don't retry
if (response.status === 404) {
throw new Error(`Set not found: ${response.status}`);
}
// If it's a 504 or 503, wait longer before retry
if (response.status === 504 || response.status === 503) {
console.log(`Attempt ${attempt}: Got ${response.status}, waiting ${delayMs * attempt}ms before retry...`);
await delay(delayMs * attempt);
continue;
}
throw new Error(`Lorcana API error: ${response.status}`);
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.log(`Attempt ${attempt} failed:`, error.message);
await delay(delayMs * attempt);
}
}
}
async function importLorcanaSet(setCode, setName, lorcastCode) {
try {
console.log(`\n🎨 Importing Lorcana set: ${setName} (${setCode})`);
// Fetch cards directly from Lorcast API
const response = await fetchWithRetry(`https://api.lorcast.com/v0/cards/search?q=set:${lorcastCode}&unique=prints`);
const data = await response.json();
const cards = data.results || [];
if (cards.length === 0) {
console.log(`❌ No cards found for set ${setName}`);
return { success: false, error: 'No cards found', importedCount: 0 };
}
console.log(`📊 Found ${cards.length} cards for set ${setName}`);
let importedCount = 0;
let skippedCount = 0;
// Import all cards via our API in a single batch
const importResponse = await fetch('http://localhost:3000/api/cards/import-lorcana', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
setCode: setCode,
setName: setName
})
});
const importResult = await importResponse.json();
if (importResult.success) {
importedCount = importResult.imported || 0;
skippedCount = importResult.skipped || 0;
console.log(`✅ Import completed for ${setName}: ${importedCount} imported, ${skippedCount} skipped`);
} else {
console.log(`❌ Failed to import ${setName}: ${importResult.error}`);
return { success: false, error: importResult.error };
}
return { success: true, importedCount, skippedCount, total: cards.length };
} catch (error) {
console.log(`❌ Error importing ${setName}: ${error.message}`);
return { success: false, error: error.message };
}
}
async function importAllLorcana() {
console.log('🎨 Starting Lorcana card import...\n');
const results = {
total: 0,
successful: 0,
failed: 0,
sets: []
};
for (const set of LORCANA_SETS) {
const result = await importLorcanaSet(set.code, set.name, set.lorcastCode);
results.sets.push({ ...set, ...result });
if (result.success) {
results.successful++;
results.total += result.importedCount || 0;
} else {
results.failed++;
}
// Add a delay between sets
await delay(2000);
}
// Print summary
console.log('\n📊 Lorcana Import Summary:');
console.log('========================');
console.log(`Total sets: ${LORCANA_SETS.length}`);
console.log(`Successful: ${results.successful}`);
console.log(`Failed: ${results.failed}`);
console.log(`Total cards imported: ${results.total}`);
console.log(`Success rate: ${((results.successful / LORCANA_SETS.length) * 100).toFixed(1)}%`);
// Save detailed results
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `lorcana-import-results-${timestamp}.json`;
fs.writeFileSync(filename, JSON.stringify(results, null, 2));
console.log(`\n📄 Detailed results saved to: ${filename}`);
return results;
}
// Run the import if this script is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
importAllLorcana()
.then(() => {
console.log('\n🎉 Lorcana import completed!');
process.exit(0);
})
.catch((error) => {
console.error('❌ Import failed:', error);
process.exit(1);
});
}
export { importAllLorcana, importLorcanaSet };