Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | 1x 1x 1x 24x 24x 23x 24x 24x 24x 23x 1x 1x 1x 9x 1x 8x 8x 8x 2x 6x 6x 6x 6x 1x 5x 5x 5x 1x 4x 3x 1x 3x 1x 1x 6x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 1x 5x 6x 4x 1x 1x 1x 1x 6x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 4x 3x 1x 3x 1x 1x 13x 1x 12x 12x 12x 12x 13x 13x 13x 11x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 6x 6x 6x 6x 6x 1x 5x 5x 3x 2x 2x 1x 4x | import { type Context, Hono } from "hono";
import { z } from "zod";
import { createDal } from "../../dal";
import { UserTenantRolesDal } from "../../dal/user-tenant-roles.dal";
import { getDb } from "../../db";
import { createDualCache } from "../../lib/cache";
import { ForbiddenError } from "../../lib/errors";
import { logger } from "../../lib/logger";
import { error, handleError, success } from "../../lib/response";
import {
getCachedUserRoles,
getProRoleFromRoles,
isPlatformAdminFromRoles,
} from "../../lib/role-cache";
import { zv } from "../../lib/zv";
import {
aiDraftRateLimit,
aiRewriteRateLimit,
aiTopicRateLimit,
requireAuth,
} from "../../middleware";
import type { ContextVariables } from "../../middleware/context.middleware";
import { createAIService, isAIEnabled } from "../../services/ai/claude.service";
import {
formatResearchForPrompt,
gatherFullResearchContext,
} from "../../services/ai/research";
import quickAiApp from "./blogs/quick-ai.routes";
type Variables = ContextVariables & {
user: { id: string; email: string } | null;
};
const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>();
// All AI routes require authentication
app.use("*", requireAuth);
// Quick AI endpoints (generate-draft, rewrite-section, generate-meta,
// suggest-topics) live in their own sub-file to keep this file focused on
// the longer-running blog-generation pipeline + jobs.
app.route("/", quickAiApp);
/**
* Verify the authenticated user has access to the given pro.
* Platform admins always have access.
*/
async function assertProAccess(
c: Context<{ Bindings: CloudflareBindings; Variables: Variables }>,
proId: string,
): Promise<void> {
const user = c.get("user");
if (!user) throw new ForbiddenError("Authentication required");
const db = c.get("db") || getDb(c.env.DB);
const rolesDal = new UserTenantRolesDal(db);
const cache = c.get("cache") || createDualCache(c.env.KV_CACHE);
const roles = await getCachedUserRoles(cache, rolesDal, user.id);
if (!isPlatformAdminFromRoles(roles) && !getProRoleFromRoles(roles, proId)) {
throw new ForbiddenError("You do not have access to this pro");
}
}
/**
* POST /api/ai/blogs/generate-full
* One-click full blog generation pipeline.
* Creates a job, enqueues the first pipeline phase, returns the job ID.
*/
const generateFullSchema = z.object({
title: z.string().min(1).max(255).optional(),
blogType: z.enum(["general", "project_spotlight", "hybrid"]).optional(),
primaryKeyword: z.string().min(1).max(100).optional(),
proId: z.string().min(1),
projectIds: z.array(z.string()).optional(),
});
app.post(
"/generate-full",
aiDraftRateLimit,
zv("json", generateFullSchema),
async (c) => {
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI-powered features are temporarily unavailable.",
503,
);
}
const params = c.req.valid("json");
try {
await assertProAccess(c, params.proId);
} catch (err) {
return handleError(c, err);
}
const db = getDb(c.env.DB);
const dal = createDal(db);
// Check for existing active jobs for this pro
const activeJobs = await dal.blogGenerationJobs.findActiveJobsForPro(
params.proId,
);
if (activeJobs.length >= 3) {
return error(
c,
"TOO_MANY_JOBS",
"You already have 3 active generation jobs. Please wait for them to complete.",
429,
);
}
// Create the generation job
const jobId = crypto.randomUUID();
const job = await dal.blogGenerationJobs.create({
id: jobId,
proId: params.proId,
mode: "one_click",
status: "research",
title: params.title || null,
blogType: params.blogType || "general",
primaryKeyword: params.primaryKeyword || null,
projectIds: params.projectIds || null,
currentStep: 0,
totalSteps: 5,
dateCreated: new Date(),
dateUpdated: new Date(),
});
if (!job) {
return error(c, "CREATE_FAILED", "Failed to create generation job", 500);
}
// Enqueue the first pipeline phase
if (c.env.BLOG_GENERATION_QUEUE) {
await c.env.BLOG_GENERATION_QUEUE.send({
jobId,
phase: "research",
});
} else {
return error(
c,
"QUEUE_UNAVAILABLE",
"Blog generation queue is not configured.",
503,
);
}
return success(c, {
jobId,
status: "research",
message:
"Blog generation started. Poll /api/ai/blogs/jobs/:jobId for progress.",
});
},
);
/**
* POST /api/ai/blogs/generate-outline
* Generate a structured outline from topic + research (for wizard mode).
*/
const generateOutlineSchema = z.object({
title: z.string().min(1).max(255),
blogType: z.enum(["general", "project_spotlight", "hybrid"]).optional(),
primaryKeyword: z.string().min(1).max(100).optional(),
proId: z.string().min(1),
});
app.post(
"/generate-outline",
aiTopicRateLimit,
zv("json", generateOutlineSchema),
async (c) => {
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI features are temporarily unavailable.",
503,
);
}
const params = c.req.valid("json");
try {
await assertProAccess(c, params.proId);
} catch (err) {
return handleError(c, err);
}
try {
const aiService = createAIService(c.env);
const db = getDb(c.env.DB);
const dal = createDal(db);
// Optionally gather research
let researchPrompt = "";
try {
const research = await gatherFullResearchContext(
dal,
aiService,
c.env,
params.proId,
);
researchPrompt = formatResearchForPrompt(research);
} catch (err) {
logger.warn("[generate-outline] Research failed, continuing:", err);
}
const outlinePrompt = `Create a structured blog outline for Interioring (Indian interior design marketplace).
**Topic:** ${params.title}
**Blog Type:** ${params.blogType || "general"}
**Primary Keyword:** ${params.primaryKeyword || params.title}
${researchPrompt ? `**Research Context:**\n${researchPrompt}\n` : ""}
Create 4-5 sections for a VISUAL GUIDE — image-heavy, Pinterest-style content.
Return ONLY valid JSON:
{
"sections": [
{
"title": "Section heading",
"contentHints": "2-3 bullet points of what to cover",
"imageHint": "Description of ideal image",
"wordTarget": 150
}
],
"estimatedReadTime": 5
}`;
const outline = await aiService.generateJSON(outlinePrompt, {
model: "haiku",
temperature: 0.5,
});
return success(c, { outline });
} catch (err) {
logger.error("Outline generation failed:", err);
return error(
c,
"AI_ERROR",
"Failed to generate outline. Please try again.",
500,
);
}
},
);
/**
* POST /api/ai/blogs/generate-from-outline
* Generate a full blog from an approved outline (wizard mode step 3).
* Creates a generation job using the pipeline.
*/
const generateFromOutlineSchema = z.object({
title: z.string().min(1).max(255),
blogType: z.enum(["general", "project_spotlight", "hybrid"]).optional(),
primaryKeyword: z.string().min(1).max(100).optional(),
proId: z.string().min(1),
outline: z.object({
sections: z.array(
z.object({
title: z.string(),
contentHints: z.string(),
imageHint: z.string(),
wordTarget: z.number(),
}),
),
estimatedReadTime: z.number(),
}),
});
app.post(
"/generate-from-outline",
aiDraftRateLimit,
zv("json", generateFromOutlineSchema),
async (c) => {
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI features are temporarily unavailable.",
503,
);
}
const params = c.req.valid("json");
try {
await assertProAccess(c, params.proId);
} catch (err) {
return handleError(c, err);
}
const db = getDb(c.env.DB);
const dal = createDal(db);
const jobId = crypto.randomUUID();
const job = await dal.blogGenerationJobs.create({
id: jobId,
proId: params.proId,
mode: "wizard",
status: "generating",
title: params.title,
blogType: params.blogType || "general",
primaryKeyword: params.primaryKeyword || null,
outline: params.outline as unknown as Record<string, unknown>,
currentStep: 2,
totalSteps: 5,
dateCreated: new Date(),
dateUpdated: new Date(),
});
if (!job) {
return error(c, "CREATE_FAILED", "Failed to create generation job", 500);
}
// Skip research + outline phases — start at content generation
if (c.env.BLOG_GENERATION_QUEUE) {
await c.env.BLOG_GENERATION_QUEUE.send({
jobId,
phase: "content",
sectionIndex: 0,
});
} else {
return error(
c,
"QUEUE_UNAVAILABLE",
"Blog generation queue not configured.",
503,
);
}
return success(c, {
jobId,
status: "generating",
message: "Blog generation from outline started.",
});
},
);
/**
* POST /api/ai/blogs/copilot
* AI co-pilot actions for in-editor assistance.
*/
const copilotSchema = z.object({
action: z.enum([
"expand",
"shorten",
"rewrite",
"indianize",
"suggest-next",
"cta",
]),
context: z.string().min(1),
selection: z.string().optional(),
blogId: z.string().optional(),
});
app.post(
"/copilot",
aiRewriteRateLimit,
zv("json", copilotSchema),
async (c) => {
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI features are temporarily unavailable.",
503,
);
}
const params = c.req.valid("json");
try {
const aiService = createAIService(c.env);
const text = params.selection || params.context;
const actionPrompts: Record<string, string> = {
expand: `Expand the following text to be more detailed and informative. Keep the same tone and style. Add specific examples, data points, or tips relevant to Indian interior design. Output ONLY the expanded text.\n\nText:\n${text}`,
shorten: `Make the following text more concise while keeping all key information. Remove filler words and unnecessary repetition. Output ONLY the shortened text.\n\nText:\n${text}`,
rewrite: `Rewrite the following text in a fresh way while preserving the meaning. Make it more engaging and reader-friendly. Output ONLY the rewritten text.\n\nText:\n${text}`,
indianize: `Rewrite the following text to add Indian context. Include: BHK apartment sizes, ₹ budget ranges, Indian materials/brands, festival references (Diwali, Navratri), Indian cities, climate considerations (monsoon, heat). Output ONLY the updated text.\n\nText:\n${text}`,
"suggest-next": `Based on the following blog content, suggest what the next section should cover. Write the actual section content (150-200 words) in markdown format. Use Indian interior design context.\n\nPrevious content:\n${text}`,
cta: `Write a compelling call-to-action paragraph for the end of an interior design blog on Interioring. The CTA should encourage readers to explore professionals on the platform. Keep it 2-3 sentences, warm and helpful, not pushy. Blog context:\n${text}`,
};
const prompt = actionPrompts[params.action];
const result = await aiService.generateText(prompt, {
model: "haiku",
maxTokens: 1024,
temperature: params.action === "expand" ? 0.7 : 0.5,
});
return success(c, {
result,
action: params.action,
});
} catch (err) {
logger.error("Copilot action failed:", err);
return error(
c,
"AI_ERROR",
"Copilot action failed. Please try again.",
500,
);
}
},
);
/**
* GET /api/ai/blogs/jobs
* List generation jobs for a pro (for resume-after-close UX)
*/
const jobsQuerySchema = z.object({
proId: z.string(),
status: z.string().optional(), // comma-separated statuses
});
app.get("/jobs", zv("query", jobsQuerySchema), async (c) => {
const { proId, status } = c.req.valid("query");
try {
await assertProAccess(c, proId);
} catch (err) {
return handleError(c, err);
}
const db = getDb(c.env.DB);
const dal = createDal(db);
const statusIn = status
? (status.split(",") as Array<
| "research"
| "outlining"
| "generating"
| "images"
| "seo"
| "review"
| "complete"
| "failed"
>)
: undefined;
const jobs = await dal.blogGenerationJobs.findJobs(
{ proId, statusIn },
0,
10,
);
return success(c, { jobs });
});
/**
* GET /api/ai/blogs/jobs/:jobId
* Poll a specific generation job status
*/
app.get("/jobs/:jobId", async (c) => {
const jobId = c.req.param("jobId");
const db = getDb(c.env.DB);
const dal = createDal(db);
const job = await dal.blogGenerationJobs.findById(jobId);
if (!job) {
return error(c, "NOT_FOUND", "Generation job not found", 404);
}
// Verify the authenticated user has access to this job
try {
if (job.proId) {
await assertProAccess(c, job.proId);
} else {
// Editorial job (no proId) — require authenticated user
const user = c.get("user");
if (!user) throw new ForbiddenError("Authentication required");
// Allow the job creator or platform admins to access editorial jobs
}
} catch (err) {
return handleError(c, err);
}
return success(c, {
id: job.id,
status: job.status,
currentStep: job.currentStep,
totalSteps: job.totalSteps,
blogId: job.blogId,
title: job.title,
errorLog: job.errorLog,
qualityScore: job.qualityScore,
dateCreated: job.dateCreated,
dateUpdated: job.dateUpdated,
});
});
export default app;
|