|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { type NextRequest, NextResponse } from 'next/server' |
| 3 | +import { z } from 'zod' |
| 4 | +import { checkHybridAuth } from '@/lib/auth/hybrid' |
| 5 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 6 | +import { getBaseUrl } from '@/lib/core/utils/urls' |
| 7 | +import { StorageService } from '@/lib/uploads' |
| 8 | +import { extractStorageKey, inferContextFromKey } from '@/lib/uploads/utils/file-utils' |
| 9 | +import { verifyFileAccess } from '@/app/api/files/authorization' |
| 10 | + |
| 11 | +export const dynamic = 'force-dynamic' |
| 12 | + |
| 13 | +const logger = createLogger('PulseParseAPI') |
| 14 | + |
| 15 | +const PulseParseSchema = z.object({ |
| 16 | + apiKey: z.string().min(1, 'API key is required'), |
| 17 | + filePath: z.string().min(1, 'File path is required'), |
| 18 | + pages: z.string().optional(), |
| 19 | + extractFigure: z.boolean().optional(), |
| 20 | + figureDescription: z.boolean().optional(), |
| 21 | + returnHtml: z.boolean().optional(), |
| 22 | + chunking: z.string().optional(), |
| 23 | + chunkSize: z.number().optional(), |
| 24 | +}) |
| 25 | + |
| 26 | +export async function POST(request: NextRequest) { |
| 27 | + const requestId = generateRequestId() |
| 28 | + |
| 29 | + try { |
| 30 | + const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) |
| 31 | + |
| 32 | + if (!authResult.success || !authResult.userId) { |
| 33 | + logger.warn(`[${requestId}] Unauthorized Pulse parse attempt`, { |
| 34 | + error: authResult.error || 'Missing userId', |
| 35 | + }) |
| 36 | + return NextResponse.json( |
| 37 | + { |
| 38 | + success: false, |
| 39 | + error: authResult.error || 'Unauthorized', |
| 40 | + }, |
| 41 | + { status: 401 } |
| 42 | + ) |
| 43 | + } |
| 44 | + |
| 45 | + const userId = authResult.userId |
| 46 | + const body = await request.json() |
| 47 | + const validatedData = PulseParseSchema.parse(body) |
| 48 | + |
| 49 | + logger.info(`[${requestId}] Pulse parse request`, { |
| 50 | + filePath: validatedData.filePath, |
| 51 | + isWorkspaceFile: validatedData.filePath.includes('/api/files/serve/'), |
| 52 | + userId, |
| 53 | + }) |
| 54 | + |
| 55 | + let fileUrl = validatedData.filePath |
| 56 | + |
| 57 | + if (validatedData.filePath?.includes('/api/files/serve/')) { |
| 58 | + try { |
| 59 | + const storageKey = extractStorageKey(validatedData.filePath) |
| 60 | + const context = inferContextFromKey(storageKey) |
| 61 | + |
| 62 | + const hasAccess = await verifyFileAccess(storageKey, userId, undefined, context, false) |
| 63 | + |
| 64 | + if (!hasAccess) { |
| 65 | + logger.warn(`[${requestId}] Unauthorized presigned URL generation attempt`, { |
| 66 | + userId, |
| 67 | + key: storageKey, |
| 68 | + context, |
| 69 | + }) |
| 70 | + return NextResponse.json( |
| 71 | + { |
| 72 | + success: false, |
| 73 | + error: 'File not found', |
| 74 | + }, |
| 75 | + { status: 404 } |
| 76 | + ) |
| 77 | + } |
| 78 | + |
| 79 | + fileUrl = await StorageService.generatePresignedDownloadUrl(storageKey, context, 5 * 60) |
| 80 | + logger.info(`[${requestId}] Generated presigned URL for ${context} file`) |
| 81 | + } catch (error) { |
| 82 | + logger.error(`[${requestId}] Failed to generate presigned URL:`, error) |
| 83 | + return NextResponse.json( |
| 84 | + { |
| 85 | + success: false, |
| 86 | + error: 'Failed to generate file access URL', |
| 87 | + }, |
| 88 | + { status: 500 } |
| 89 | + ) |
| 90 | + } |
| 91 | + } else if (validatedData.filePath?.startsWith('/')) { |
| 92 | + const baseUrl = getBaseUrl() |
| 93 | + fileUrl = `${baseUrl}${validatedData.filePath}` |
| 94 | + } |
| 95 | + |
| 96 | + const formData = new FormData() |
| 97 | + formData.append('file_url', fileUrl) |
| 98 | + |
| 99 | + if (validatedData.pages) { |
| 100 | + formData.append('pages', validatedData.pages) |
| 101 | + } |
| 102 | + if (validatedData.extractFigure !== undefined) { |
| 103 | + formData.append('extract_figure', String(validatedData.extractFigure)) |
| 104 | + } |
| 105 | + if (validatedData.figureDescription !== undefined) { |
| 106 | + formData.append('figure_description', String(validatedData.figureDescription)) |
| 107 | + } |
| 108 | + if (validatedData.returnHtml !== undefined) { |
| 109 | + formData.append('return_html', String(validatedData.returnHtml)) |
| 110 | + } |
| 111 | + if (validatedData.chunking) { |
| 112 | + formData.append('chunking', validatedData.chunking) |
| 113 | + } |
| 114 | + if (validatedData.chunkSize !== undefined) { |
| 115 | + formData.append('chunk_size', String(validatedData.chunkSize)) |
| 116 | + } |
| 117 | + |
| 118 | + const pulseResponse = await fetch('https://api.runpulse.com/extract', { |
| 119 | + method: 'POST', |
| 120 | + headers: { |
| 121 | + 'x-api-key': validatedData.apiKey, |
| 122 | + }, |
| 123 | + body: formData, |
| 124 | + }) |
| 125 | + |
| 126 | + if (!pulseResponse.ok) { |
| 127 | + const errorText = await pulseResponse.text() |
| 128 | + logger.error(`[${requestId}] Pulse API error:`, errorText) |
| 129 | + return NextResponse.json( |
| 130 | + { |
| 131 | + success: false, |
| 132 | + error: `Pulse API error: ${pulseResponse.statusText}`, |
| 133 | + }, |
| 134 | + { status: pulseResponse.status } |
| 135 | + ) |
| 136 | + } |
| 137 | + |
| 138 | + const pulseData = await pulseResponse.json() |
| 139 | + |
| 140 | + logger.info(`[${requestId}] Pulse parse successful`) |
| 141 | + |
| 142 | + return NextResponse.json({ |
| 143 | + success: true, |
| 144 | + output: pulseData, |
| 145 | + }) |
| 146 | + } catch (error) { |
| 147 | + if (error instanceof z.ZodError) { |
| 148 | + logger.warn(`[${requestId}] Invalid request data`, { errors: error.errors }) |
| 149 | + return NextResponse.json( |
| 150 | + { |
| 151 | + success: false, |
| 152 | + error: 'Invalid request data', |
| 153 | + details: error.errors, |
| 154 | + }, |
| 155 | + { status: 400 } |
| 156 | + ) |
| 157 | + } |
| 158 | + |
| 159 | + logger.error(`[${requestId}] Error in Pulse parse:`, error) |
| 160 | + |
| 161 | + return NextResponse.json( |
| 162 | + { |
| 163 | + success: false, |
| 164 | + error: error instanceof Error ? error.message : 'Internal server error', |
| 165 | + }, |
| 166 | + { status: 500 } |
| 167 | + ) |
| 168 | + } |
| 169 | +} |
0 commit comments