// Chat proxy - routes requests to n8n workflow // Path: /chat const handler = async (request) => { if (request.method === 'OPTIONS') { let response = new Response('') response.headers.set('Access-Control-Allow-Origin', '*') response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization') return response } if (request.method !== 'POST') { let response = new Response(JSON.stringify({ error: 'Method not allowed' })) response.headers.set('Content-Type', 'application/json') response.headers.set('Access-Control-Allow-Origin', '*') return response } try { // Use text() and parse manually - json() may not be available in wws const bodyText = await request.text() let body try { body = JSON.parse(bodyText) } catch (e) { let response = new Response(JSON.stringify({ error: 'Invalid JSON body' })) response.headers.set('Content-Type', 'application/json') response.headers.set('Access-Control-Allow-Origin', '*') return response } const message = body.message const project_id = body.project_id const user_id = body.user_id const provider = body.provider || 'zai' if (!message) { let response = new Response(JSON.stringify({ error: 'Message is required' })) response.headers.set('Content-Type', 'application/json') response.headers.set('Access-Control-Allow-Origin', '*') return response } // Forward to n8n webhook const n8nResponse = await fetch('https://n8n.mylder.io/webhook/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: message, project_id: project_id || null, user_id: user_id || null, provider: provider, source: 'wws-proxy', timestamp: new Date().toISOString() }) }) // Use text() and parse manually const responseText = await n8nResponse.text() let result try { result = JSON.parse(responseText) } catch (e) { result = { text: responseText } } let response = new Response(JSON.stringify({ success: true, response: result.response || result, provider: provider, timestamp: new Date().toISOString() })) response.headers.set('Content-Type', 'application/json') response.headers.set('Access-Control-Allow-Origin', '*') return response } catch (error) { let response = new Response(JSON.stringify({ success: false, error: error.message || 'Internal server error' })) response.headers.set('Content-Type', 'application/json') response.headers.set('Access-Control-Allow-Origin', '*') return response } } addEventListener('fetch', event => { return event.respondWith(handler(event.request)) })