fix(desk): convert api/desk.js to ES module with native fetch
This commit is contained in:
1 parent
b9378f18ef
commit
aa27c62094
1 file changed
+51
-85
+51
-85
@@ -1,56 +1,12 @@
|
||||
/**
|
||||
* 🚀 Sovereign AIRA Founder Desk Gateway (Vercel Serverless)
|
||||
* 🚀 Sovereign AIRA Founder Desk Gateway (Vercel Serverless - ES Module)
|
||||
* Connects airaaigroup.in visitors directly to Founder Er. Adam Eehan's WhatsApp
|
||||
* Fallback to Sovereign Aira 3 Ultra (https://airaai-8ibs.onrender.com)
|
||||
*/
|
||||
|
||||
const https = require('https');
|
||||
|
||||
const RENDER_BRIDGE_URL = process.env.RENDER_BRIDGE_URL || 'https://aira-whatsapp-bridge.onrender.com';
|
||||
const AIRA_ENDPOINT = process.env.AIRA_API_URL || 'https://airaai-8ibs.onrender.com/v1/chat/completions';
|
||||
const FOUNDER_PHONE = '918921584368';
|
||||
|
||||
// Helper: HTTP Request Promise
|
||||
function fetchJson(url, options = {}, postData = null) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsedUrl = new URL(url);
|
||||
const reqOptions = {
|
||||
hostname: parsedUrl.hostname,
|
||||
port: parsedUrl.port || 443,
|
||||
path: parsedUrl.pathname + parsedUrl.search,
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers || {})
|
||||
},
|
||||
timeout: options.timeout || 8000
|
||||
};
|
||||
|
||||
const req = https.request(reqOptions, (res) => {
|
||||
let body = '';
|
||||
res.on('data', chunk => body += chunk);
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const parsed = JSON.parse(body);
|
||||
resolve({ status: res.statusCode, data: parsed });
|
||||
} catch (e) {
|
||||
resolve({ status: res.statusCode, text: body });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', reject);
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
reject(new Error('Request timeout'));
|
||||
});
|
||||
|
||||
if (postData) {
|
||||
req.write(typeof postData === 'string' ? postData : JSON.stringify(postData));
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
const RENDER_BRIDGE_URL = process.env.RENDER_BRIDGE_URL || "https://aira-whatsapp-bridge.onrender.com";
|
||||
const AIRA_ENDPOINT = process.env.AIRA_API_URL || "https://airaai-8ibs.onrender.com/v1/chat/completions";
|
||||
const FOUNDER_PHONE = "918921584368";
|
||||
|
||||
// Fallback Aira 3 Ultra AI Query
|
||||
async function queryAiraUltraDirect(userName, message) {
|
||||
@@ -69,45 +25,53 @@ Language Directives:
|
||||
- Keep it concise, helpful, and professional with zero robotic fluff.`;
|
||||
|
||||
try {
|
||||
const res = await fetchJson(AIRA_ENDPOINT, { method: 'POST', timeout: 15000 }, {
|
||||
model: 'aira-3-ultra',
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: message }
|
||||
],
|
||||
max_tokens: 500,
|
||||
temperature: 0.7
|
||||
const res = await fetch(AIRA_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
model: "aira-3-ultra",
|
||||
messages: [
|
||||
{ role: "system", content: systemPrompt },
|
||||
{ role: "user", content: message }
|
||||
],
|
||||
max_tokens: 500,
|
||||
temperature: 0.7
|
||||
}),
|
||||
signal: AbortSignal.timeout(12000)
|
||||
});
|
||||
|
||||
const content = res.data?.choices?.[0]?.message?.content;
|
||||
if (content) return content.trim();
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const content = data?.choices?.[0]?.message?.content;
|
||||
if (content) return content.trim();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Aira Ultra Direct error:', err.message);
|
||||
console.warn("Aira Ultra Direct fetch error:", err.message);
|
||||
}
|
||||
|
||||
return `Hello ${userName}! Er. Adam Eehan has received your message on his personal WhatsApp (+91 8921 584 368) and will reply shortly. Thank you for connecting with Aira Group!`;
|
||||
}
|
||||
|
||||
module.exports = async (req, res) => {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
||||
export default async function handler(req, res) {
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
if (req.method === "OPTIONS") {
|
||||
return res.status(200).end();
|
||||
}
|
||||
|
||||
// GET: Poll for messages or check status
|
||||
if (req.method === 'GET') {
|
||||
const { userId, after } = req.query;
|
||||
if (req.method === "GET") {
|
||||
const { userId, after } = req.query || {};
|
||||
|
||||
// Try forwarding to Render WhatsApp bridge if available
|
||||
try {
|
||||
const bridgeRes = await fetchJson(`${RENDER_BRIDGE_URL}/api/desk/poll?userId=${encodeURIComponent(userId || '')}&after=${encodeURIComponent(after || 0)}`, {
|
||||
timeout: 4000
|
||||
});
|
||||
if (bridgeRes.status === 200 && bridgeRes.data) {
|
||||
return res.status(200).json(bridgeRes.data);
|
||||
const bridgeUrl = `${RENDER_BRIDGE_URL}/api/desk/poll?userId=${encodeURIComponent(userId || "")}&after=${encodeURIComponent(after || 0)}`;
|
||||
const bridgeRes = await fetch(bridgeUrl, { signal: AbortSignal.timeout(3500) });
|
||||
if (bridgeRes.ok) {
|
||||
const data = await bridgeRes.json();
|
||||
return res.status(200).json(data);
|
||||
}
|
||||
} catch (e) {
|
||||
// Bridge sleeping or not yet reachable
|
||||
@@ -116,17 +80,17 @@ module.exports = async (req, res) => {
|
||||
return res.status(200).json({
|
||||
online: true,
|
||||
messages: [],
|
||||
founder: 'Er. Adam Eehan',
|
||||
founder: "Er. Adam Eehan",
|
||||
phone: `+${FOUNDER_PHONE}`
|
||||
});
|
||||
}
|
||||
|
||||
// POST: Send visitor message
|
||||
if (req.method === 'POST') {
|
||||
if (req.method === "POST") {
|
||||
const { userId, userName, userEmail, userAvatar, message } = req.body || {};
|
||||
|
||||
if (!userId || !message || !message.trim()) {
|
||||
return res.status(400).json({ error: 'Missing userId or message' });
|
||||
return res.status(400).json({ error: "Missing userId or message" });
|
||||
}
|
||||
|
||||
let bridgeSuccess = false;
|
||||
@@ -134,21 +98,23 @@ module.exports = async (req, res) => {
|
||||
|
||||
// 1. Try sending to Render WhatsApp Bridge
|
||||
try {
|
||||
const bridgeRes = await fetchJson(`${RENDER_BRIDGE_URL}/api/desk/send`, {
|
||||
method: 'POST',
|
||||
timeout: 6000
|
||||
}, { userId, userName, userEmail, userAvatar, message });
|
||||
const bridgeRes = await fetch(`${RENDER_BRIDGE_URL}/api/desk/send`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ userId, userName, userEmail, userAvatar, message }),
|
||||
signal: AbortSignal.timeout(5000)
|
||||
});
|
||||
|
||||
if (bridgeRes.status === 200) {
|
||||
if (bridgeRes.ok) {
|
||||
bridgeSuccess = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Render Bridge unreachable, generating direct Aira 3 Ultra response...');
|
||||
console.warn("Render Bridge unreachable, generating direct Aira 3 Ultra response...");
|
||||
}
|
||||
|
||||
// 2. If Render Bridge is still connecting/pairing, provide instant Aira 3 Ultra response
|
||||
if (!bridgeSuccess) {
|
||||
aiResponse = await queryAiraUltraDirect(userName || 'Visitor', message);
|
||||
aiResponse = await queryAiraUltraDirect(userName || "Visitor", message);
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
@@ -156,13 +122,13 @@ module.exports = async (req, res) => {
|
||||
deliveredToBridge: bridgeSuccess,
|
||||
aiReply: aiResponse ? {
|
||||
id: `ai_${Date.now()}`,
|
||||
sender: 'aira_ultra',
|
||||
senderName: 'Aira 3 Ultra (Co-Pilot)',
|
||||
sender: "aira_ultra",
|
||||
senderName: "Aira 3 Ultra (Co-Pilot)",
|
||||
text: aiResponse,
|
||||
timestamp: Date.now()
|
||||
} : null
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(405).json({ error: 'Method Not Allowed' });
|
||||
};
|
||||
return res.status(405).json({ error: "Method Not Allowed" });
|
||||
}
|
||||
Reference in new issue
Block a user