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
|
* Connects airaaigroup.in visitors directly to Founder Er. Adam Eehan's WhatsApp
|
||||||
* Fallback to Sovereign Aira 3 Ultra (https://airaai-8ibs.onrender.com)
|
* 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 RENDER_BRIDGE_URL = process.env.RENDER_BRIDGE_URL || 'https://aira-whatsapp-bridge.onrender.com';
|
const FOUNDER_PHONE = "918921584368";
|
||||||
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();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback Aira 3 Ultra AI Query
|
// Fallback Aira 3 Ultra AI Query
|
||||||
async function queryAiraUltraDirect(userName, message) {
|
async function queryAiraUltraDirect(userName, message) {
|
||||||
@@ -69,45 +25,53 @@ Language Directives:
|
|||||||
- Keep it concise, helpful, and professional with zero robotic fluff.`;
|
- Keep it concise, helpful, and professional with zero robotic fluff.`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetchJson(AIRA_ENDPOINT, { method: 'POST', timeout: 15000 }, {
|
const res = await fetch(AIRA_ENDPOINT, {
|
||||||
model: 'aira-3-ultra',
|
method: "POST",
|
||||||
messages: [
|
headers: { "Content-Type": "application/json" },
|
||||||
{ role: 'system', content: systemPrompt },
|
body: JSON.stringify({
|
||||||
{ role: 'user', content: message }
|
model: "aira-3-ultra",
|
||||||
],
|
messages: [
|
||||||
max_tokens: 500,
|
{ role: "system", content: systemPrompt },
|
||||||
temperature: 0.7
|
{ role: "user", content: message }
|
||||||
|
],
|
||||||
|
max_tokens: 500,
|
||||||
|
temperature: 0.7
|
||||||
|
}),
|
||||||
|
signal: AbortSignal.timeout(12000)
|
||||||
});
|
});
|
||||||
|
|
||||||
const content = res.data?.choices?.[0]?.message?.content;
|
if (res.ok) {
|
||||||
if (content) return content.trim();
|
const data = await res.json();
|
||||||
|
const content = data?.choices?.[0]?.message?.content;
|
||||||
|
if (content) return content.trim();
|
||||||
|
}
|
||||||
} catch (err) {
|
} 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!`;
|
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) => {
|
export default async function handler(req, res) {
|
||||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
if (req.method === "OPTIONS") {
|
||||||
return res.status(200).end();
|
return res.status(200).end();
|
||||||
}
|
}
|
||||||
|
|
||||||
// GET: Poll for messages or check status
|
// GET: Poll for messages or check status
|
||||||
if (req.method === 'GET') {
|
if (req.method === "GET") {
|
||||||
const { userId, after } = req.query;
|
const { userId, after } = req.query || {};
|
||||||
|
|
||||||
// Try forwarding to Render WhatsApp bridge if available
|
// Try forwarding to Render WhatsApp bridge if available
|
||||||
try {
|
try {
|
||||||
const bridgeRes = await fetchJson(`${RENDER_BRIDGE_URL}/api/desk/poll?userId=${encodeURIComponent(userId || '')}&after=${encodeURIComponent(after || 0)}`, {
|
const bridgeUrl = `${RENDER_BRIDGE_URL}/api/desk/poll?userId=${encodeURIComponent(userId || "")}&after=${encodeURIComponent(after || 0)}`;
|
||||||
timeout: 4000
|
const bridgeRes = await fetch(bridgeUrl, { signal: AbortSignal.timeout(3500) });
|
||||||
});
|
if (bridgeRes.ok) {
|
||||||
if (bridgeRes.status === 200 && bridgeRes.data) {
|
const data = await bridgeRes.json();
|
||||||
return res.status(200).json(bridgeRes.data);
|
return res.status(200).json(data);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Bridge sleeping or not yet reachable
|
// Bridge sleeping or not yet reachable
|
||||||
@@ -116,17 +80,17 @@ module.exports = async (req, res) => {
|
|||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
online: true,
|
online: true,
|
||||||
messages: [],
|
messages: [],
|
||||||
founder: 'Er. Adam Eehan',
|
founder: "Er. Adam Eehan",
|
||||||
phone: `+${FOUNDER_PHONE}`
|
phone: `+${FOUNDER_PHONE}`
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST: Send visitor message
|
// POST: Send visitor message
|
||||||
if (req.method === 'POST') {
|
if (req.method === "POST") {
|
||||||
const { userId, userName, userEmail, userAvatar, message } = req.body || {};
|
const { userId, userName, userEmail, userAvatar, message } = req.body || {};
|
||||||
|
|
||||||
if (!userId || !message || !message.trim()) {
|
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;
|
let bridgeSuccess = false;
|
||||||
@@ -134,21 +98,23 @@ module.exports = async (req, res) => {
|
|||||||
|
|
||||||
// 1. Try sending to Render WhatsApp Bridge
|
// 1. Try sending to Render WhatsApp Bridge
|
||||||
try {
|
try {
|
||||||
const bridgeRes = await fetchJson(`${RENDER_BRIDGE_URL}/api/desk/send`, {
|
const bridgeRes = await fetch(`${RENDER_BRIDGE_URL}/api/desk/send`, {
|
||||||
method: 'POST',
|
method: "POST",
|
||||||
timeout: 6000
|
headers: { "Content-Type": "application/json" },
|
||||||
}, { userId, userName, userEmail, userAvatar, message });
|
body: JSON.stringify({ userId, userName, userEmail, userAvatar, message }),
|
||||||
|
signal: AbortSignal.timeout(5000)
|
||||||
|
});
|
||||||
|
|
||||||
if (bridgeRes.status === 200) {
|
if (bridgeRes.ok) {
|
||||||
bridgeSuccess = true;
|
bridgeSuccess = true;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} 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
|
// 2. If Render Bridge is still connecting/pairing, provide instant Aira 3 Ultra response
|
||||||
if (!bridgeSuccess) {
|
if (!bridgeSuccess) {
|
||||||
aiResponse = await queryAiraUltraDirect(userName || 'Visitor', message);
|
aiResponse = await queryAiraUltraDirect(userName || "Visitor", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -156,13 +122,13 @@ module.exports = async (req, res) => {
|
|||||||
deliveredToBridge: bridgeSuccess,
|
deliveredToBridge: bridgeSuccess,
|
||||||
aiReply: aiResponse ? {
|
aiReply: aiResponse ? {
|
||||||
id: `ai_${Date.now()}`,
|
id: `ai_${Date.now()}`,
|
||||||
sender: 'aira_ultra',
|
sender: "aira_ultra",
|
||||||
senderName: 'Aira 3 Ultra (Co-Pilot)',
|
senderName: "Aira 3 Ultra (Co-Pilot)",
|
||||||
text: aiResponse,
|
text: aiResponse,
|
||||||
timestamp: Date.now()
|
timestamp: Date.now()
|
||||||
} : null
|
} : 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