@@ -4,7 +4,7 @@ import type { RequestHandler } from './$types';
44import { db } from '$lib/db' ;
55import { modelPerformanceStats } from '$lib/db/schema' ;
66import { eq , and , sql } from 'drizzle-orm' ;
7- import { auth } from '$lib/auth' ;
7+ import { tryGetAuthenticatedUserId } from '$lib/backend/ auth-utils ' ;
88
99const COST_PER_1K_CHARS : Record < string , number > = {
1010 'gpt-4o-mini-tts' : 0.0125 ,
@@ -17,6 +17,18 @@ const COST_PER_1K_CHARS: Record<string, number> = {
1717// Default to standard price if unknown
1818const DEFAULT_COST = 0.015 ;
1919
20+ const getApiKey = ( request : Request ) : string | null => {
21+ const authHeader = request . headers . get ( 'Authorization' ) ;
22+ if ( authHeader ?. startsWith ( 'Bearer ' ) ) {
23+ const token = authHeader . slice ( 7 ) . trim ( ) ;
24+ if ( token . length > 0 ) {
25+ return token ;
26+ }
27+ }
28+
29+ return request . headers . get ( 'x-api-key' ) || env . NANOGPT_API_KEY || null ;
30+ } ;
31+
2032export const POST : RequestHandler = async ( { request, fetch } ) => {
2133 let textStr = '' ;
2234 let modelId = 'tts-1' ;
@@ -31,7 +43,7 @@ export const POST: RequestHandler = async ({ request, fetch }) => {
3143 return json ( { error : 'Text is required' } , { status : 400 } ) ;
3244 }
3345
34- const apiKey = request . headers . get ( 'x-api-key' ) || env . NANOGPT_API_KEY ;
46+ const apiKey = getApiKey ( request ) ;
3547
3648 if ( ! apiKey ) {
3749 return json ( { error : 'API key is required' } , { status : 401 } ) ;
@@ -61,6 +73,12 @@ export const POST: RequestHandler = async ({ request, fetch }) => {
6173 ) ;
6274 }
6375
76+ const contentType = response . headers . get ( 'Content-Type' ) || '' ;
77+ if ( response . status === 202 || contentType . includes ( 'application/json' ) ) {
78+ const data = await response . json ( ) ;
79+ return json ( data , { status : response . status } ) ;
80+ }
81+
6482 // Return the audio blob directly
6583 console . log (
6684 `[TTS] API response status: ${ response . status } , headers:` ,
@@ -71,9 +89,8 @@ export const POST: RequestHandler = async ({ request, fetch }) => {
7189 // Track analytics asynchronously
7290 ( async ( ) => {
7391 try {
74- const session = await auth . api . getSession ( { headers : request . headers } ) ;
75- if ( session ?. user ?. id ) {
76- const userId = session . user . id ;
92+ const userId = await tryGetAuthenticatedUserId ( request ) ;
93+ if ( userId ) {
7794 console . log ( `[TTS] Tracking analytics for user: ${ userId } , model: ${ model } ` ) ;
7895 const duration = Date . now ( ) - start ;
7996
0 commit comments