Repository navigation
Expand file tree
/
Copy pathv1.ts
More file actions
46 lines (39 loc) · 1.46 KB
/
Copy pathv1.ts
File metadata and controls
46 lines (39 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
export type OpenAiErrorType = 'invalid_request_error' | 'server_error' | 'authentication_error';
export function extractBearerToken(request: NextRequest): string | null {
const header = request.headers.get('authorization') || request.headers.get('Authorization');
if (!header) return null;
const match = header.match(/^Bearer\s+(.+)$/i);
return match ? match[1].trim() : null;
}
export function isAuthorized(token: string | null): boolean {
if (!token) return false;
const required = process.env.V1_API_KEY || process.env.API_KEY;
if (!required) return true;
return token === required;
}
export function buildErrorResponse(message: string, status: number, type: OpenAiErrorType = 'invalid_request_error') {
return NextResponse.json(
{
error: {
message,
type,
},
},
{ status }
);
}
export function parseDataUrl(input: string): { mimeType: string; data: string } | null {
const match = input.match(/^data:([^;]+);base64,(.+)$/);
if (!match) return null;
return { mimeType: match[1], data: match[2] };
}
export function buildDataUrl(mimeType: string, data: string): string {
return `data:${mimeType};base64,${data}`;
}
export function stripDataUrl(input: string): { mimeType: string; data: string } {
const parsed = parseDataUrl(input);
if (parsed) return parsed;
return { mimeType: 'application/octet-stream', data: input };
}