MoooVeee
/** * ============================================================ * CNS CONTENT WORKER — Single File, Cloudflare Dashboard Deploy * Content Central Nervous System — AI Marketing Platform * ============================================================ * * HOW TO DEPLOY (no terminal, no Wrangler needed): * ───────────────────────────────────────────────── * 1. Go to dash.cloudflare.com → Workers & Pages → Create Worker * 2. Click "Edit Code" — delete everything in the editor * 3. Paste this entire file → click "Deploy" * 4. Name your Worker: hub (gives you hub.get100listings.workers.dev) * 5. Go to your Worker → Settings → Variables and Secrets * 6. Add each variable below using "Add variable" — mark as ENCRYPTED: * * Variable Name Value * ───────────────────────────────────────────── * KIE_API_KEY your-kie-api-key-here * KIE_BASE_URL https://api.kie.ai/v1 * FAL_API_KEY your-fal-api-key-here * FAL_BASE_URL https://fal.run * ALLOWED_ORIGIN https://your-brokerage-center.weebly.com * * 7. Click "Deploy" again after saving variables * 8. In your Step 1 frontend HTML, set: * const WORKER_URL = 'https://hub.get100listings.workers.dev'; * * HOW TO UPDATE LATER: * ───────────────────────────────────────────────── * - Edit code: Workers & Pages → your Worker → Edit Code → paste updated file → Deploy * - Update key: Workers & Pages → your Worker → Settings → Variables → Edit → Deploy * * ============================================================ * * ACTIONS THIS WORKER HANDLES: * ───────────────────────────────────────────────── * Action Step Status * ───────────────────────────────────────────────── * generate-post Step 1 ✅ Live — Claude Haiku via Kie → Fal backup * generate-image Step 2 ✅ Live — GPT Image-2 via Kie (async) → Fal backup * check-image Step 2 ✅ Live — Poll Kie image task status * check-video Step 3 ✅ Live — Poll Kie video task status * overlay-image Step 2 ✅ Live — GPT Image-2 image-to-image text overlay * upload-photo Step 2 ✅ Live — Upload user photo to R2 bucket * make-it-me Step 2 ✅ Live — Person swap + optional text overlay * image-to-video Step 3 □ Stubbed — ready to activate * * HOW KIE → FAL FAILOVER WORKS: * ───────────────────────────────────────────────── * Every action tries Kie first. If Kie fails for ANY reason * (down, timeout, bad response, out of business), the Worker * silently retries the exact same request on Fal. The frontend * never knows — it just gets { ok: true, result: "..." } either way. * The "provider" field in the response tells you which one ran. * * ============================================================ */ export default { async fetch(request, env) { // ── CORS preflight ────────────────────────────────────── if (request.method === 'OPTIONS') { return new Response(null, { status: 204, headers: buildCorsHeaders(env, request), }); } // ── Only accept POST ──────────────────────────────────── if (request.method !== 'POST') { return errResponse('Method not allowed — use POST.', 405, env, request); } // ── Parse body ────────────────────────────────────────── let body; try { body = await request.json(); } catch { return errResponse('Could not parse request body as JSON.', 400, env, request); } const { action } = body; // ── Route by action ───────────────────────────────────── switch (action) { case 'generate-post': return handleGeneratePost(body, env, request); case 'generate-image': // ── Step 2 — activate when ready ── return handleGenerateImage(body, env, request); case 'check-image': return handleCheckImage(body, env, request); case 'overlay-image': return handleOverlayImage(body, env, request); case 'enhance-image': return handleEnhanceImage(body, env, request); case 'upload-photo': return handleUploadPhoto(body, env, request); case 'make-it-me': return handleMakeItMe(body, env, request); case 'check-video': return handleCheckVideo(body, env, request); case 'image-to-video': // ── Step 3 — activate when ready ── return handleImageToVideo(body, env, request); default: return errResponse( `Unknown action "${action}". Valid: generate-post, generate-image, image-to-video.`, 400, env, request ); } }, }; // ============================================================ // ✅ STEP 1 — GENERATE POST // Claude Haiku via Kie. Falls back to Fal silently if Kie fails. // // Frontend sends: // { action: 'generate-post', prompt: string, biz: string, platform: string[] } // // Worker returns: // { ok: true, result: string, provider: 'kie' | 'fal' } // ============================================================ async function handleGeneratePost(body, env, request) { const { prompt } = body; if (!prompt || typeof prompt !== 'string' || prompt.trim().length < 10) { return errResponse('Missing or too-short prompt.', 400, env, request); } // Try Kie first let result = null; let provider = null; let kieError = null; try { result = await kieHaiku(prompt.trim(), env); provider = 'kie'; } catch (err) { kieError = err.message; console.error('[CNS] Kie generate-post failed:', kieError); } // Fal backup if Kie failed if (!result) { try { result = await falHaiku(prompt.trim(), env); provider = 'fal'; } catch (falErr) { console.error('[CNS] Fal generate-post also failed:', falErr.message); return errResponse( `Post generation failed on both providers. Kie: ${kieError} | Fal: ${falErr.message}`, 502, env, request ); } } return okResponse({ result, provider }, env, request); } // ── Kie: Claude Haiku text ─────────────────────────────────── // NOTE: If Kie uses a different alias for Haiku, update the // model string below. Check your Kie dashboard for their exact name. async function kieHaiku(prompt, env) { const url = baseUrl(env.KIE_BASE_URL, 'https://api.kie.ai') + '/claude/v1/messages'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${env.KIE_API_KEY}`, 'x-api-key': env.KIE_API_KEY, // Kie accepts both header formats }, body: JSON.stringify({ model: 'claude-haiku-4-5', // Kie alias -- confirmed from their docs max_tokens: prompt.length > 800 ? 2048 : 1024, // blog/article needs more tokens messages: [{ role: 'user', content: prompt }], }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Kie HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const text = data?.content?.[0]?.text; if (!text) throw new Error('Kie returned no text. Raw: ' + JSON.stringify(data).slice(0, 300)); return text.trim(); } // ── Fal: Claude Haiku text (backup) ───────────────────────── // Only runs if Kie fails. Key is in FAL_API_KEY env variable. async function falHaiku(prompt, env) { const url = baseUrl(env.FAL_BASE_URL, 'https://fal.run') + '/anthropic/claude-haiku'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Key ${env.FAL_API_KEY}`, }, body: JSON.stringify({ model: 'claude-haiku-4-5-20251001', max_tokens: prompt.length > 800 ? 2048 : 1024, messages: [{ role: 'user', content: prompt }], }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Fal HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); // Fal may return Anthropic-style OR their own envelope — handle both const text = data?.content?.[0]?.text || data?.output || data?.result || data?.choices?.[0]?.message?.content; if (!text) throw new Error('Fal returned no text. Raw: ' + JSON.stringify(data).slice(0, 300)); return text.trim(); } // ============================================================ // ✅ STEP 2 — GENERATE IMAGE // GPT Image-2 via Kie (task-based, async) → Fal Flux backup. // Supports: 1:1, 16:9, 9:16, 4:3, 3:4 natively — no mapping needed. // // Kie image generation is async — same pattern as video: // 1. POST to createTask → get taskId // 2. Frontend polls check-image until complete // // Frontend sends to start: // { action: 'generate-image', imagePrompt, aspectRatio, quality } // Worker returns: // { ok: true, taskId, provider: 'kie' | 'fal' } // // Frontend sends to poll: // { action: 'check-image', taskId, provider } // Worker returns: // { ok: true, status: 'processing'|'completed', imageUrl? } // ============================================================ async function handleGenerateImage(body, env, request) { const { imagePrompt, aspectRatio = '16:9' } = body; if (!imagePrompt || typeof imagePrompt !== 'string') { return errResponse('Missing imagePrompt.', 400, env, request); } let taskId = null; let provider = null; let kieError = null; // Try Kie GPT Image-1.5 first try { taskId = await kieImageCreate(imagePrompt.trim(), aspectRatio, env); provider = 'kie'; } catch (err) { kieError = err.message; console.error('[CNS] Kie image create failed:', kieError); } // Fal backup — Flux is synchronous so returns URL directly if (!taskId) { try { const imageUrl = await falImageGen(imagePrompt.trim(), aspectRatio, env); // Fal is sync — return URL directly, no polling needed return okResponse({ imageUrl, provider: 'fal', status: 'completed' }, env, request); } catch (falErr) { return errResponse( `Image generation failed on both providers. Kie: ${kieError} | Fal: ${falErr.message}`, 502, env, request ); } } return okResponse({ taskId, provider, status: 'processing' }, env, request); } // ── Kie: GPT Image-1.5 task create ─────────────────────────── async function kieImageCreate(prompt, aspectRatio, env) { const url = baseUrl(env.KIE_BASE_URL, 'https://api.kie.ai') + '/api/v1/jobs/createTask'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${env.KIE_API_KEY}`, }, body: JSON.stringify({ model: 'gpt-image-2-text-to-image', input: { prompt, aspect_ratio: aspectRatio, // 1:1, 16:9, 9:16, 4:3, 3:4 all supported natively resolution: '1K', // 1K is plenty for social media, faster and cheaper }, }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Kie image HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const id = data?.data?.taskId || data?.taskId || data?.id; if (!id) throw new Error('Kie image: no taskId. Raw: ' + JSON.stringify(data).slice(0, 300)); return id; } // ── Kie: poll image task status ─────────────────────────────── // GET /api/v1/jobs/recordInfo?taskId=xxx // States: waiting, queuing, generating, success, fail // Image URL is in data.resultJson (a JSON string) → { resultUrls: ["https://..."] } async function handleCheckImage(body, env, request) { const { taskId, provider } = body; if (!taskId) return errResponse('Missing taskId.', 400, env, request); if (provider === 'fal') { return errResponse('Fal image was synchronous — no polling needed.', 400, env, request); } try { const url = baseUrl(env.KIE_BASE_URL, 'https://api.kie.ai') + '/api/v1/jobs/recordInfo?taskId=' + encodeURIComponent(taskId); const res = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${env.KIE_API_KEY}`, }, }); if (!res.ok) { const txt = await res.text(); throw new Error(`Kie status HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const state = data?.data?.state || 'waiting'; if (state === 'fail') { return errResponse( 'Image generation failed: ' + (data?.data?.failMsg || 'unknown error'), 500, env, request ); } if (state === 'success') { // resultJson is a JSON string — parse it to get the URL array let imageUrl = null; try { const result = JSON.parse(data.data.resultJson); imageUrl = result?.resultUrls?.[0]; } catch { throw new Error('Could not parse resultJson: ' + data?.data?.resultJson); } if (!imageUrl) throw new Error('No image URL in resultJson. Raw: ' + JSON.stringify(data).slice(0, 400)); return okResponse({ status: 'completed', imageUrl, provider: 'kie' }, env, request); } // Still processing (waiting / queuing / generating) return okResponse({ status: 'processing', state, provider: 'kie' }, env, request); } catch (err) { return errResponse('Image status check failed: ' + err.message, 500, env, request); } } // ============================================================ // ✅ STEP 2 — IMAGE TO IMAGE (text overlay) // GPT Image-2 image-to-image via Kie. // Takes the generated image URL + overlay instructions and // produces a new image with text/branding applied. // // Frontend sends: // { // action: 'overlay-image', // imageUrl: string, — the generated image URL // overlayPrompt: string, — what to add e.g. "Add bold white text..." // aspectRatio: string, — same ratio as original // } // // Worker returns: // { ok: true, taskId, provider: 'kie' } // Poll with check-image action — same flow as text-to-image. // ============================================================ async function handleOverlayImage(body, env, request) { const { imageUrl, overlayPrompt, aspectRatio = 'auto' } = body; if (!imageUrl) return errResponse('Missing imageUrl.', 400, env, request); if (!overlayPrompt) return errResponse('Missing overlayPrompt.', 400, env, request); try { const url = baseUrl(env.KIE_BASE_URL, 'https://api.kie.ai') + '/api/v1/jobs/createTask'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${env.KIE_API_KEY}`, }, body: JSON.stringify({ model: 'gpt-image-2-image-to-image', input: { prompt: overlayPrompt, input_urls: [imageUrl], aspect_ratio: aspectRatio, resolution: '1K', }, }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Kie image-to-image HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const taskId = data?.data?.taskId || data?.taskId; if (!taskId) throw new Error('No taskId returned. Raw: ' + JSON.stringify(data).slice(0, 300)); return okResponse({ taskId, provider: 'kie', status: 'processing' }, env, request); } catch (err) { return errResponse('Overlay image failed: ' + err.message, 500, env, request); } } // ── Kie: poll video task status (same recordInfo endpoint) ── async function handleCheckVideo(body, env, request) { const { taskId } = body; if (!taskId) return errResponse('Missing taskId.', 400, env, request); try { const url = baseUrl(env.KIE_BASE_URL, 'https://api.kie.ai') + '/api/v1/jobs/recordInfo?taskId=' + encodeURIComponent(taskId); const res = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${env.KIE_API_KEY}` }, }); if (!res.ok) { const txt = await res.text(); throw new Error(`Kie video status HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const state = data?.data?.state || 'waiting'; if (state === 'fail') { return errResponse('Video generation failed: ' + (data?.data?.failMsg || 'unknown'), 500, env, request); } if (state === 'success') { let videoUrl = null; try { const result = JSON.parse(data.data.resultJson); videoUrl = result?.resultUrls?.[0]; } catch { throw new Error('Could not parse video resultJson'); } if (!videoUrl) throw new Error('No video URL in resultJson'); return okResponse({ status: 'completed', videoUrl, provider: 'kie' }, env, request); } return okResponse({ status: 'processing', state, provider: 'kie' }, env, request); } catch (err) { return errResponse('Video status check failed: ' + err.message, 500, env, request); } } // ── Fal: Flux image (backup, synchronous) ──────────────────── // Maps aspect ratio to Fal dimensions. Only runs if Kie fails. async function falImageGen(prompt, aspectRatio, env) { const url = baseUrl(env.FAL_BASE_URL, 'https://fal.run') + '/fal-ai/flux/schnell'; // Map UI aspect ratio to Fal pixel dimensions const sizeMap = { '1:1': { width: 1024, height: 1024 }, '16:9': { width: 1792, height: 1024 }, '9:16': { width: 1024, height: 1792 }, }; const size = sizeMap[aspectRatio] || sizeMap['16:9']; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Key ${env.FAL_API_KEY}`, }, body: JSON.stringify({ prompt, image_size: size, num_images: 1 }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Fal image HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const imgUrl = data?.images?.[0]?.url || data?.image?.url || data?.url; if (!imgUrl) throw new Error('Fal image: no URL. Raw: ' + JSON.stringify(data).slice(0, 300)); return imgUrl; } // ============================================================ // □ STEP 3 — IMAGE TO VIDEO // Wan 2.6 via Kie → Fal backup. // Mirrors your existing video studio Worker pattern exactly. // Activate when Step 3 frontend is built. // // Frontend will send: // { // action: 'image-to-video', // imageUrl: string, // duration: '5' | '10' | '15', // resolution: '720p' | '1080p', // motionPrompt: string (optional) // } // // Worker returns (task ID for polling): // { ok: true, taskId: string, provider: 'kie' | 'fal' } // // Then frontend polls with: // { action: 'check-video', taskId: string, provider: 'kie' | 'fal' } // ============================================================ async function handleImageToVideo(body, env, request) { const { imageUrl, duration = '5', resolution = '720p', motionPrompt = '' } = body; if (!imageUrl) { return errResponse('Missing imageUrl.', 400, env, request); } let taskId = null; let provider = null; let kieError = null; // Try Kie Wan 2.6 first try { taskId = await kieWan(imageUrl, duration, resolution, motionPrompt, env); provider = 'kie'; } catch (err) { kieError = err.message; console.error('[CNS] Kie image-to-video failed:', kieError); } // Fal backup if (!taskId) { try { taskId = await falVideo(imageUrl, duration, resolution, motionPrompt, env); provider = 'fal'; } catch (falErr) { return errResponse( `Video generation failed on both providers. Kie: ${kieError} | Fal: ${falErr.message}`, 502, env, request ); } } return okResponse({ taskId, provider }, env, request); } // ── Kie: Wan 2.6 video ─────────────────────────────────────── // Same pattern as your existing video studio Worker async function kieWan(imageUrl, duration, resolution, motionPrompt, env) { const url = baseUrl(env.KIE_BASE_URL, 'https://api.kie.ai/v1') + '/video/wan'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${env.KIE_API_KEY}`, 'x-api-key': env.KIE_API_KEY, }, body: JSON.stringify({ imageUrl, duration: parseInt(duration), resolution, prompt: motionPrompt || 'Cinematic smooth camera motion, professional marketing video', model: 'wan-2.6', }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Kie video HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const id = data?.data?.taskId || data?.taskId || data?.id; if (!id) throw new Error('Kie video: no taskId in response. Raw: ' + JSON.stringify(data).slice(0, 300)); return id; } // ── Fal: video generation (backup) ────────────────────────── async function falVideo(imageUrl, duration, resolution, motionPrompt, env) { const url = baseUrl(env.FAL_BASE_URL, 'https://fal.run') + '/fal-ai/wan/v2.2/i2v'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Key ${env.FAL_API_KEY}`, }, body: JSON.stringify({ image_url: imageUrl, num_frames: parseInt(duration) * 8, prompt: motionPrompt || 'Cinematic smooth camera motion professional marketing video', }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Fal video HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const id = data?.request_id || data?.id || data?.taskId; if (!id) throw new Error('Fal video: no taskId in response. Raw: ' + JSON.stringify(data).slice(0, 300)); return id; } // ============================================================ // UPLOAD PHOTO TO R2 // Accepts base64 image data, stores in R2, returns public URL. // R2 bucket bound as UPLOADS_BUCKET in Worker settings. // Public URL base: https://pub-f13e32650eb34af2a70c12755db32ff6.r2.dev // // Frontend sends: // { action: 'upload-photo', imageData: string (base64), fileName: string, mimeType: string } // // Worker returns: // { ok: true, photoUrl: string } // ============================================================ const R2_PUBLIC_URL = 'https://pub-f13e32650eb34af2a70c12755db32ff6.r2.dev'; async function handleUploadPhoto(body, env, request) { const { imageData, fileName, mimeType = 'image/jpeg' } = body; if (!imageData) return errResponse('Missing imageData.', 400, env, request); if (!env.UPLOADS_BUCKET) return errResponse('R2 bucket not bound. Add UPLOADS_BUCKET binding in Worker settings.', 500, env, request); try { // Convert base64 to binary const base64 = imageData.replace(/^data:image\/\w+;base64,/, ''); const binaryStr = atob(base64); const bytes = new Uint8Array(binaryStr.length); for (let i = 0; i < binaryStr.length; i++) { bytes[i] = binaryStr.charCodeAt(i); } // Generate unique filename const ext = mimeType.includes('png') ? 'png' : 'jpg'; const key = `uploads/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`; // Store in R2 await env.UPLOADS_BUCKET.put(key, bytes.buffer, { httpMetadata: { contentType: mimeType }, }); const photoUrl = `${R2_PUBLIC_URL}/${key}`; return okResponse({ photoUrl }, env, request); } catch (err) { return errResponse('Upload failed: ' + err.message, 500, env, request); } } // ============================================================ // MAKE IT ME -- person swap + optional text overlay // GPT Image-2 image-to-image via Kie. // Sends generated image + user's uploaded photo. // Single API call handles both person swap AND text overlay. // // Frontend sends: // { // action: 'make-it-me', // generatedImageUrl: string, -- the AI-generated marketing image // photoUrl: string, -- user's uploaded photo (R2 public URL) // aspectRatio: string, -- same as original image // overlayText: string, -- optional text to add // overlayPosition: string, -- top / bottom / left / right / center // overlayWeight: string, -- bold / medium / light // } // // Worker returns: // { ok: true, taskId: string, provider: 'kie' } // Poll with check-image action -- same flow as text-to-image. // ============================================================ async function handleMakeItMe(body, env, request) { const { generatedImageUrl, photoUrl, aspectRatio = 'auto', overlayText = '', adjusterText = '', overlayPosition = 'bottom', } = body; if (!generatedImageUrl) return errResponse('Missing generatedImageUrl.', 400, env, request); if (!photoUrl) return errResponse('Missing photoUrl.', 400, env, request); // Build the combined prompt let prompt = `Using the reference photo as the person's identity, replace the person in the marketing image with the person from the reference photo. Match their facial features, skin tone, hair, and overall likeness as closely as possible. Keep the background, lighting, composition, clothing style, and pose completely unchanged -- only swap the person's face and identity. The result should look natural and professional, as if the reference person was always in the original scene.`; // Add text overlay instruction if requested if (overlayText && overlayText.trim().length > 0) { prompt += ` Add text at the ${overlayPosition} of the image reading: "${overlayText.trim()}". Make it look like a professionally designed marketing image.`; } if (adjusterText && adjusterText.trim().length > 0) { prompt += ` Also apply these image edits: ${adjusterText.trim()}.`; } try { const url = baseUrl(env.KIE_BASE_URL, 'https://api.kie.ai') + '/api/v1/jobs/createTask'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${env.KIE_API_KEY}`, }, body: JSON.stringify({ model: 'gpt-image-2-image-to-image', input: { prompt, input_urls: [photoUrl, generatedImageUrl], // reference photo first, marketing image second aspect_ratio: aspectRatio, resolution: '1K', }, }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Kie make-it-me HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const taskId = data?.data?.taskId || data?.taskId; if (!taskId) throw new Error('No taskId returned. Raw: ' + JSON.stringify(data).slice(0, 300)); return okResponse({ taskId, provider: 'kie', status: 'processing' }, env, request); } catch (err) { return errResponse('Make It Me failed: ' + err.message, 500, env, request); } } // ============================================================ // ENHANCE IMAGE — image-to-image mode // User uploads an existing image and describes how to improve it. // Also handles aspect ratio changes (outpainting). // // Frontend sends: // { // action: 'enhance-image', // imageUrl: string, — R2 public URL of uploaded image // enhancePrompt: string, — user's description of changes // aspectRatio: string, — target ratio (may differ from original) // originalRatio: string, — original image ratio for outpaint detection // style: string, — style/mood selection // brandColor: string, — optional brand color // } // ============================================================ async function handleEnhanceImage(body, env, request) { const { imageUrl, enhancePrompt = '', aspectRatio = 'auto', originalRatio = 'auto', style = '', mood = '', brandColor = '', } = body; if (!imageUrl) return errResponse('Missing imageUrl.', 400, env, request); // Detect if ratio change is requested (outpainting) const isRatioChange = aspectRatio !== 'auto' && aspectRatio !== originalRatio; // Build the prompt let prompt = ''; if (isRatioChange) { prompt += `Reformat this image to a ${aspectRatio} aspect ratio. Intelligently extend and fill any new areas to match the existing scene, lighting, colors, and style naturally — as if the camera had captured a wider/taller frame. `; } if (enhancePrompt.trim()) { prompt += `Apply these specific changes: ${enhancePrompt.trim()}. `; } if (mood) { prompt += `The overall mood and feeling should be ${mood}. `; } if (style) { prompt += `The overall visual style should be ${style}. `; } if (brandColor) { prompt += `Incorporate ${brandColor} as an accent color where appropriate. `; } if (!isRatioChange && !enhancePrompt.trim()) { prompt = 'Enhance this image professionally — improve lighting, sharpness, color balance, and overall quality while preserving the original composition and subject.'; } prompt += ' Preserve the core subject and identity of the original image unless specifically instructed to change it.'; try { const url = baseUrl(env.KIE_BASE_URL, 'https://api.kie.ai') + '/api/v1/jobs/createTask'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${env.KIE_API_KEY}`, }, body: JSON.stringify({ model: 'gpt-image-2-image-to-image', input: { prompt, input_urls: [imageUrl], aspect_ratio: aspectRatio, resolution: '1K', }, }), }); if (!res.ok) { const txt = await res.text(); throw new Error(`Kie enhance-image HTTP ${res.status}: ${txt.slice(0, 200)}`); } const data = await res.json(); const taskId = data?.data?.taskId || data?.taskId; if (!taskId) throw new Error('No taskId returned: ' + JSON.stringify(data).slice(0, 300)); return okResponse({ taskId, provider: 'kie', status: 'processing' }, env, request); } catch (err) { return errResponse('Enhance image failed: ' + err.message, 500, env, request); } } // ============================================================ // SHARED UTILITIES // ============================================================ // Clean base URL — strips trailing slash function baseUrl(envVal, fallback) { return (envVal || fallback).replace(/\/$/, ''); } // CORS headers — locks to your Weebly domain in production function buildCorsHeaders(env, request) { const origin = request.headers.get('Origin') || ''; const allowed = env.ALLOWED_ORIGIN || '*'; const isAllowed = allowed === '*' || origin === allowed || origin === ''; return { 'Access-Control-Allow-Origin': isAllowed ? (origin || '*') : allowed, 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', 'Access-Control-Max-Age': '86400', }; } // Success response envelope function okResponse(data, env, request) { return new Response( JSON.stringify({ ok: true, ...data }), { status: 200, headers: { 'Content-Type': 'application/json', ...buildCorsHeaders(env, request), }, } ); } // Error response envelope function errResponse(message, status, env, request) { return new Response( JSON.stringify({ ok: false, error: message }), { status, headers: { 'Content-Type': 'application/json', ...buildCorsHeaders(env, request), }, } ); }
Ready to launch? Start Machine — Keys Please?
Need support? Open support ticket
Have questions? 678.425.8298
Email

© PCS, LLC  ·  MoooVeee  ·  All rights reserved
Home About Privacy Policy Terms of Use