import { promises as fs } from 'fs'; import { exec } from 'child_process'; import { promisify } from 'util'; import * as path from 'path'; import { generateDeckId } from './deck-id'; import { replaceTemplatePlaceholders } from './template-processor'; import { createSlidevSupabaseClient, checkDeckIdExists, insertDeckMetadata, } from './supabase-client'; import { publishDeckToGitHub, getGitHubPagesUrl } from './github-publisher'; const execAsync = promisify(exec); /** * Result of deck generation */ export interface GenerateDeckResult { deckId: string; deckUrl: string; } /** * Options for deck generation */ export interface GenerateDeckOptions { /** Template ID to use (e.g., 'starter') */ templateId: string; /** Data to replace placeholders in the template */ data: Record; /** Session ID for tracking (not used for now, reserved for Stream C) */ sessionId?: string; /** Build timeout in milliseconds (default: 60000) */ buildTimeout?: number; /** GitHub token for publishing (reads from GITHUB_TOKEN env var if not provided) */ githubToken?: string; } /** * Error thrown when template is not found */ export class TemplateNotFoundError extends Error { constructor(templateId: string) { super(`Template not found: ${templateId}`); this.name = 'TemplateNotFoundError'; } } /** * Error thrown when build times out */ export class BuildTimeoutError extends Error { constructor(timeout: number) { super(`Slidev build timed out after ${timeout}ms`); this.name = 'BuildTimeoutError'; } } /** * Error thrown when build fails */ export class BuildError extends Error { constructor(message: string, public originalError?: Error) { super(message); this.name = 'BuildError'; } } /** * Error thrown when deck ID collision occurs (max retries exceeded) */ export class DeckIdCollisionError extends Error { constructor(attempts: number) { super(`Failed to generate unique deck ID after ${attempts} attempts`); this.name = 'DeckIdCollisionError'; } } /** * Generate a Slidev deck from a template * * This function orchestrates the full pipeline: * 1. Initialize Supabase client (if configured) * 2. Generate unique deck ID with collision detection (max 3 attempts) * 3. Load template from apps/slidev-templates/src/default/{templateId}/slides.md * 4. Replace placeholders with provided data * 5. Create deck directory with processed template * 6. Push deck to buzztrail-presentations GitHub repo * 7. GitHub Actions builds and deploys to GitHub Pages (1-2 minutes) * 8. Save deck metadata to Supabase (if enabled) * 9. Clean up temp directory (even on errors) * * **Supabase Integration:** * - Checks for deck ID uniqueness before generation * - Tracks deck metadata in slidev_decks table * - Gracefully degrades if Supabase is not configured * - Database failures don't fail the generation (files still built) * * **Environment Variables (optional):** * - SUPABASE_URL: Your Supabase project URL * - SUPABASE_SERVICE_KEY: Service role key (or SUPABASE_ANON_KEY) * * @param options - Configuration for deck generation * @returns Promise with deckId and deckUrl * @throws {TemplateNotFoundError} If template doesn't exist * @throws {BuildTimeoutError} If build exceeds timeout * @throws {BuildError} If build fails for other reasons * @throws {DeckIdCollisionError} If unique deck ID cannot be generated * * @example * const result = await generateDeck({ * templateId: 'starter', * data: { * COMPANY_NAME: 'Acme Corp', * INDUSTRY: 'Technology' * }, * sessionId: 'session-123' * }); * console.log(result.deckUrl); // https://buzztrail.github.io/buzztrail-presentations/a3b2-c5d9-e7f1/ */ export async function generateDeck( options: GenerateDeckOptions ): Promise { const { templateId, data, sessionId, buildTimeout = 60000, githubToken = process.env.GITHUB_TOKEN, } = options; // Validate GitHub token if (!githubToken) { throw new Error('GitHub token is required. Set GITHUB_TOKEN environment variable or pass githubToken option.'); } // Initialize Supabase client (gracefully handle if env vars not set) let supabaseClient; let supabaseEnabled = false; try { supabaseClient = createSlidevSupabaseClient(); supabaseEnabled = true; } catch (error) { // Log warning but continue without Supabase console.warn( 'Supabase not configured, deck generation will proceed without database tracking:', error instanceof Error ? error.message : String(error) ); } // Generate unique deck ID with collision detection (max 3 attempts) let deckId: string; const maxAttempts = 3; let attempts = 0; while (attempts < maxAttempts) { attempts++; deckId = generateDeckId(); // Check for collision if Supabase is enabled if (supabaseEnabled && supabaseClient) { try { const exists = await checkDeckIdExists(supabaseClient, deckId); if (!exists) { break; // Found unique ID } console.log(`Deck ID collision detected: ${deckId}, retrying...`); } catch (error) { // If check fails, log but continue (assume ID is unique) console.error('Failed to check deck ID uniqueness:', error); break; } } else { // Without Supabase, assume first ID is unique break; } if (attempts >= maxAttempts) { throw new DeckIdCollisionError(maxAttempts); } } deckId = deckId!; // TypeScript assertion: deckId is definitely assigned // Get absolute paths - resolve relative to project root const projectRoot = path.resolve(__dirname, '../..'); const templatePath = path.join( projectRoot, 'apps/slidev-templates/src/default', templateId ); const slidesPath = path.join(templatePath, 'slides.md'); const tempDir = `/tmp/slidev-deck-${deckId}`; try { // 1. Validate template exists try { await fs.access(slidesPath); } catch (error) { throw new TemplateNotFoundError(templateId); } // 2. Load template const templateContent = await fs.readFile(slidesPath, 'utf-8'); // 3. Replace placeholders const processedContent = replaceTemplatePlaceholders(templateContent, data); // 4. Create temp deck directory await fs.mkdir(tempDir, { recursive: true }); // 5. Copy template files to temp directory (source files, not built) // GitHub Actions will build these files const packageJsonPath = path.join(templatePath, 'package.json'); try { await fs.access(packageJsonPath); await fs.copyFile( packageJsonPath, path.join(tempDir, 'package.json') ); } catch (error) { // If no package.json, create a minimal one const minimalPackageJson = { name: `slidev-deck-${deckId}`, type: 'module', scripts: { build: 'slidev build', }, dependencies: { '@slidev/cli': '^0.49.0', '@slidev/theme-default': '^0.25.0' } }; await fs.writeFile( path.join(tempDir, 'package.json'), JSON.stringify(minimalPackageJson, null, 2) ); } // Copy setup directory if it exists const setupDir = path.join(templatePath, 'setup'); try { await fs.access(setupDir); await execAsync(`cp -r "${setupDir}" "${tempDir}/setup"`); } catch (error) { // Setup directory is optional } // Write processed slides.md await fs.writeFile(path.join(tempDir, 'slides.md'), processedContent); // 6. Push deck to GitHub repository console.log(`Publishing deck ${deckId} to GitHub...`); const publishResult = await publishDeckToGitHub({ deckId, deckPath: tempDir, githubToken }); if (!publishResult.success) { throw new BuildError( `Failed to publish deck to GitHub: ${publishResult.error}`, new Error(publishResult.error) ); } console.log(`Deck published to GitHub. Commit: ${publishResult.commitSha}`); console.log(`GitHub Actions will build and deploy in 1-2 minutes.`); console.log(`Deck URL (will be live shortly): ${publishResult.deckUrl}`); // 7. Save metadata to Supabase (if enabled) if (supabaseEnabled && supabaseClient) { try { await insertDeckMetadata(supabaseClient, { deck_id: deckId, session_id: sessionId, template_id: templateId, generation_data: data, }); console.log(`Deck metadata saved to database: ${deckId}`); } catch (error) { // Log error but don't fail the generation // The deck files are already published successfully console.error( 'Failed to save deck metadata to database (deck generation succeeded):', error ); } } // 8. Return result with GitHub Pages URL return { deckId, deckUrl: publishResult.deckUrl, }; } finally { // 9. Cleanup temp directory (even on errors) try { await fs.rm(tempDir, { recursive: true, force: true }); } catch (error) { // Log but don't throw - cleanup errors shouldn't fail the operation console.error(`Failed to cleanup temp directory ${tempDir}:`, error); } } }