/** * Slidev Generate Step * * API endpoint that generates a Slidev presentation from a template, * publishes it to GitHub Pages, and stores metadata in Supabase. * * Path: POST /api/slidev/generate */ export const config = { name: 'SlidevGenerate', type: 'api', path: '/api/slidev/generate', method: 'POST', description: 'Generate Slidev presentation and publish to GitHub Pages', emits: ['slidev.generated', 'slidev.failed'] }; interface GenerateInput { sessionId: string; templateId: string; data: Record; } interface GenerateOutput { deckId: string; deckUrl: string; message: string; } /** * Generate a unique 12-character deck ID * Format: xxxx-xxxx-xxxx */ function generateDeckId(): string { const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; const segments = [4, 4, 4]; return segments .map(length => { return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)] ).join(''); }) .join('-'); } /** * Replace placeholders in template content */ function _replacePlaceholders(content: string, data: Record): string { let result = content; for (const [key, value] of Object.entries(data)) { const placeholder = new RegExp(`{{\\s*${key}\\s*}}`, 'gi'); result = result.replace(placeholder, String(value)); } return result; } export const handler = async (req: MotiaRequest, { emit }: MotiaContext) => { try { const input: GenerateInput = req.body; // Validate required inputs if (!input.sessionId || !input.templateId || !input.data) { return { status: 400, body: { error: 'Validation failed', details: 'Missing required fields: sessionId, templateId, and data' } }; } console.log('[SlidevGenerate] Starting deck generation', { sessionId: input.sessionId, templateId: input.templateId }); // Step 1: Verify session exists in Supabase const supabaseUrl = process.env.SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY; if (!supabaseUrl || !supabaseServiceKey) { throw new Error('SUPABASE_URL or SUPABASE_SERVICE_KEY not configured'); } const sessionResponse = await fetch( `${supabaseUrl}/rest/v1/conversation_sessions?id=eq.${input.sessionId}&select=id`, { headers: { 'apikey': supabaseServiceKey, 'Authorization': `Bearer ${supabaseServiceKey}` } } ); if (!sessionResponse.ok) { throw new Error(`Failed to verify session: ${sessionResponse.statusText}`); } const sessions = await sessionResponse.json(); if (!sessions || sessions.length === 0) { return { status: 404, body: { error: 'Session not found', details: `No session exists with ID: ${input.sessionId}` } }; } // Step 2: Generate unique deck ID const deckId = generateDeckId(); console.log('[SlidevGenerate] Generated deck ID:', deckId); // Step 3: Prepare deck content (simplified for MVP - using basic template) // TODO: Load actual template from filesystem and replace placeholders const _slidesContent = `--- theme: default background: https://source.unsplash.com/collection/94734566/1920x1080 class: text-center highlighter: shiki lineNumbers: false info: | ## ${input.data.company || 'Company'} Presentation Generated by BuzzTrail AI drawings: persist: false transition: slide-left title: ${input.data.company || 'Company'} Presentation --- # ${input.data.company || 'Welcome'} ${input.data.tagline || 'Presentation created with Slidev'} --- # About Us ${input.data.description || 'Learn more about our company and services'} Industry: ${input.data.industry || 'N/A'} --- # Thank You Questions? `; // Step 4: Publish to GitHub Pages const githubToken = process.env.GITHUB_TOKEN; if (!githubToken) { throw new Error('GITHUB_TOKEN not configured'); } // For MVP, we'll create a simple HTML deck instead of full Slidev build // TODO: Implement actual Slidev build process const htmlContent = ` ${input.data.company || 'Presentation'}
1 / 3

${input.data.company || 'Welcome'}

${input.data.tagline || 'Presentation created with BuzzTrail AI'}

About Us

${input.data.description || 'Learn more about our company and services'}

Industry: ${input.data.industry || 'N/A'}

Thank You

Questions?

`; // Step 5: Publish to GitHub Pages const githubRepo = 'BuzzTrail/buzztrail-presentations'; const deckUrl = `https://buzztrail.github.io/buzztrail-presentations/${deckId}/`; console.log('[SlidevGenerate] Publishing to GitHub Pages:', deckUrl); // Create index.html file in GitHub repository (in /decks subdirectory) const createFileResponse = await fetch( `https://api.github.com/repos/${githubRepo}/contents/decks/${deckId}/index.html`, { method: 'PUT', headers: { 'Authorization': `Bearer ${githubToken}`, 'Accept': 'application/vnd.github+json', 'Content-Type': 'application/json', 'X-GitHub-Api-Version': '2022-11-28' }, body: JSON.stringify({ message: `Add deck ${deckId} - ${input.data.company || 'Generated presentation'}`, content: Buffer.from(htmlContent).toString('base64'), committer: { name: 'BuzzTrail Bot', email: 'bot@buzztrail.ai' } }) } ); if (!createFileResponse.ok) { const errorText = await createFileResponse.text(); throw new Error(`Failed to publish to GitHub: ${createFileResponse.status} ${errorText}`); } const githubResult = await createFileResponse.json(); console.log('[SlidevGenerate] Published to GitHub:', githubResult.content.html_url); console.log('[SlidevGenerate] Deck URL:', deckUrl); // Step 6: Store deck metadata in Supabase const deckMetadata = { deck_id: deckId, session_id: input.sessionId, template_id: input.templateId, generation_data: input.data, deck_url: deckUrl, html_content: htmlContent, created_at: new Date().toISOString() }; const insertResponse = await fetch( `${supabaseUrl}/rest/v1/slidev_decks`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'apikey': supabaseServiceKey, 'Authorization': `Bearer ${supabaseServiceKey}`, 'Prefer': 'return=representation' }, body: JSON.stringify(deckMetadata) } ); if (!insertResponse.ok) { const errorText = await insertResponse.text(); throw new Error(`Failed to store deck metadata: ${errorText}`); } console.log('[SlidevGenerate] Deck metadata stored in Supabase'); // Step 7: Update session with deck URL await fetch( `${supabaseUrl}/rest/v1/conversation_sessions?id=eq.${input.sessionId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', 'apikey': supabaseServiceKey, 'Authorization': `Bearer ${supabaseServiceKey}` }, body: JSON.stringify({ slidev_url: deckUrl }) } ); const output: GenerateOutput = { deckId, deckUrl, message: 'Deck generated successfully' }; // Emit success event emit({ topic: 'slidev.generated', data: output }); console.log('[SlidevGenerate] Generation complete:', output); return { status: 200, body: output }; } catch (error: unknown) { console.error('[SlidevGenerate] Error:', error); // Emit failure event emit({ topic: 'slidev.failed', data: { error: error.message, timestamp: new Date().toISOString() } }); return { status: 500, body: { error: 'Failed to generate deck', details: error.message } }; } };