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 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 | 1x 1x 1x 1x 1x 1x 1x 9x 1x 8x 8x 8x 8x 3x 5x 5x 5x 4x 1x 3x 1x 2x 1x 5x 1x 11x 1x 10x 10x 10x 2x 2x 2x 2x 1x 1x 10x 10x 6x 4x 4x 4x 1x 3x 1x 2x 1x 4x 1x 6x 1x 5x 5x 5x 5x 1x 4x 4x 4x 1x 3x 1x 2x 1x 4x 1x 16x 1x 15x 15x 15x 15x 15x 15x 7x 7x 6x 1x 15x 2x 2x 1x 1x 15x 10x 5x 5x 5x 4x 1x 3x 1x 2x 1x 5x 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 { Hono } from "hono";
import { z } from "zod";
import { error, success, handleError } from "../../lib/response";
import { zv } from "../../lib/zv";
import { ForbiddenError } from "../../lib/errors";
import { UserTenantRolesDal } from "../../dal/user-tenant-roles.dal";
import { createDualCache } from "../../lib/cache";
import {
getCachedUserRoles,
isPlatformAdminFromRoles,
getProRoleFromRoles,
} from "../../lib/role-cache";
import {
requireAuth,
requirePlatformAdmin,
aiDraftRateLimit,
aiRewriteRateLimit,
aiMetaRateLimit,
aiTopicRateLimit,
} from "../../middleware";
import { createAIService, isAIEnabled } from "../../services/ai/claude.service";
import {
gatherFullResearchContext,
formatResearchForPrompt,
} from "../../services/ai/research";
import { getDb } from "../../db";
import { createDal } from "../../dal";
import { logger } from "../../lib/logger";
type Variables = {
user: { id: string; email: string } | null;
};
const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>();
// All AI routes require authentication
app.use("*", requireAuth);
/**
* Validation schemas
*
* Each `.min(1, ...)` carries a user-friendly message so the `zv` wrapper can
* surface it in `error.fieldErrors[<field>]` — preventing raw Zod text like
* "Too small: expected string to have >=1 characters" from leaking to the UI
* (regression #588).
*
* `outline` and `primaryKeyword` are intentionally optional on the
* generate-draft endpoint: the Quick Draft (No Images) flow leaves them blank
* by design, and the AI service treats them as hints rather than requirements.
*/
const generateDraftSchema = z.object({
title: z.string().min(1, "Title is required").max(255),
primaryKeyword: z.string().max(100).optional(),
blogType: z.enum(["general", "project_spotlight", "hybrid"]),
outline: z.string().optional(),
proContext: z.string().optional(),
wordCount: z.number().int().min(500).max(5000).optional(),
});
const rewriteSectionSchema = z.object({
currentContent: z.string().min(1, "Current content is required"),
feedback: z.string().min(1, "Feedback is required"),
sectionToRewrite: z.string().optional(),
blogId: z.string().optional(),
});
const generateMetaSchema = z.object({
content: z.string().min(1, "Content is required"),
primaryKeyword: z.string().min(1, "Primary keyword is required").max(100),
});
const suggestTopicsSchema = z.object({
proId: z.string().optional(),
category: z.string().optional(),
recentBlogs: z.array(z.string()).optional(),
context: z.string().optional(),
count: z.number().int().min(1).max(10).optional(),
/** If true, gather research context (web trends, competitor articles, pro data) before generating suggestions */
useResearch: z.boolean().optional(),
});
/**
* POST /api/ai/blogs/generate-draft
* Generate a full blog draft from outline (Authenticated users - pros and admins)
*/
app.post(
"/generate-draft",
// Changed from requirePlatformAdmin to just requireAuth - pros can now generate drafts
aiDraftRateLimit,
zv("json", generateDraftSchema),
async (c) => {
// Check if AI features are enabled
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI-powered features are temporarily unavailable. Please try again later or contact support.",
503,
);
}
const params = c.req.valid("json");
try {
const aiService = createAIService(c.env);
const result = await aiService.generateDraft(params);
return success(c, {
content: result.content,
metadata: {
title: params.title,
primaryKeyword: params.primaryKeyword,
blogType: params.blogType,
wordCount: result.content.split(/\s+/).length,
},
});
} catch (err) {
logger.error("AI draft generation failed:", err);
// Provide specific user feedback based on error message
let userMessage = "Failed to generate blog draft. Please try again.";
if (err instanceof Error) {
if (err.message.includes("authentication")) {
userMessage =
"AI service authentication error. Please contact support.";
} else if (err.message.includes("rate limit")) {
userMessage =
"AI service rate limit reached. Please try again in a few minutes.";
} else if (err.message.includes("unavailable")) {
userMessage =
"AI service temporarily unavailable. Please try again later.";
}
}
return error(c, "AI_ERROR", userMessage, 500);
}
},
);
/**
* POST /api/ai/blogs/rewrite-section
* Rewrite a section based on feedback (Admin only)
*/
app.post(
"/rewrite-section",
requirePlatformAdmin,
aiRewriteRateLimit,
zv("json", rewriteSectionSchema),
async (c) => {
// Check if AI features are enabled
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI-powered features are temporarily unavailable. Please try again later or contact support.",
503,
);
}
const params = c.req.valid("json");
try {
// Save original content as a revision before rewriting
if (params.blogId) {
try {
const db = getDb(c.env.DB);
const dal = createDal(db);
const versionNumber = await dal.blogRevisions.getNextVersionNumber(params.blogId);
await dal.blogRevisions.create({
id: crypto.randomUUID(),
blogId: params.blogId,
versionNumber,
content: params.currentContent,
changeDescription: params.feedback,
createdBy: "ai_rewrite",
});
} catch (revErr) {
logger.warn("[rewrite-section] Failed to save revision, continuing:", revErr);
}
}
const aiService = createAIService(c.env);
const result = await aiService.rewriteSection(params);
return success(c, {
revisedContent: result.revisedContent,
metadata: {
originalWordCount: params.currentContent.split(/\s+/).length,
revisedWordCount: result.revisedContent.split(/\s+/).length,
},
});
} catch (err) {
logger.error("AI section rewrite failed:", err);
let userMessage = "Failed to rewrite section. Please try again.";
/* v8 ignore start -- V8 artifact: err is always an Error in tests */
if (err instanceof Error) {
/* v8 ignore stop */
if (err.message.includes("authentication")) {
userMessage =
"AI service authentication error. Please contact support.";
} else if (err.message.includes("rate limit")) {
userMessage =
"AI service rate limit reached. Please try again in a few minutes.";
} else if (err.message.includes("unavailable")) {
userMessage =
"AI service temporarily unavailable. Please try again later.";
}
}
return error(c, "AI_ERROR", userMessage, 500);
}
},
);
/**
* POST /api/ai/blogs/generate-meta
* Generate SEO metadata (title, description, slug) (Admin only)
*/
app.post(
"/generate-meta",
requirePlatformAdmin,
aiMetaRateLimit,
zv("json", generateMetaSchema),
async (c) => {
// Check if AI features are enabled
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI-powered features are temporarily unavailable. Please try again later or contact support.",
503,
);
}
const params = c.req.valid("json");
try {
const aiService = createAIService(c.env);
const result = await aiService.generateMeta(params);
return success(c, result);
} catch (err) {
logger.error("AI meta generation failed:", err);
let userMessage = "Failed to generate metadata. Please try again.";
/* v8 ignore start -- V8 artifact: err is always an Error in tests */
if (err instanceof Error) {
/* v8 ignore stop */
if (err.message.includes("authentication")) {
userMessage =
"AI service authentication error. Please contact support.";
} else if (err.message.includes("rate limit")) {
userMessage =
"AI service rate limit reached. Please try again in a few minutes.";
} else if (err.message.includes("unavailable")) {
userMessage =
"AI service temporarily unavailable. Please try again later.";
}
}
return error(c, "AI_ERROR", userMessage, 500);
}
},
);
/**
* POST /api/ai/blogs/suggest-topics
* Generate blog topic suggestions
*/
app.post(
"/suggest-topics",
aiTopicRateLimit,
zv("json", suggestTopicsSchema),
async (c) => {
// Check if AI features are enabled
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI-powered features are temporarily unavailable. Please try again later or contact support.",
503,
);
}
const params = c.req.valid("json");
try {
const aiService = createAIService(c.env);
const db = getDb(c.env.DB);
const dal = createDal(db);
// Look up the pro's city so suggestions are location-relevant
let proCity: string | undefined;
if (params.proId) {
try {
const pro = await dal.pros.findById(params.proId);
if (pro?.cityId) {
proCity = pro.cityId;
}
} catch {
// Non-critical — continue without city context
}
}
// Optionally enrich with research context
let researchContextStr: string | undefined;
if (params.useResearch && params.proId) {
try {
const research = await gatherFullResearchContext(
dal,
aiService,
c.env,
params.proId,
);
researchContextStr = formatResearchForPrompt(research);
} catch (researchErr) {
logger.warn(
"[suggest-topics] Research gathering failed, continuing without:",
researchErr,
);
}
}
const result = await aiService.suggestTopics({
...params,
proCity,
researchContext: researchContextStr,
});
return success(c, {
suggestions: result.suggestions,
count: result.suggestions.length,
});
} catch (err) {
logger.error("AI topic suggestion failed:", err);
let userMessage = "Failed to suggest topics. Please try again.";
if (err instanceof Error) {
if (err.message.includes("authentication")) {
userMessage =
"AI service authentication error. Please contact support.";
} else if (err.message.includes("rate limit")) {
userMessage =
"AI service rate limit reached. Please try again in a few minutes.";
} else if (err.message.includes("unavailable")) {
userMessage =
"AI service temporarily unavailable. Please try again later.";
}
}
return error(c, "AI_ERROR", userMessage, 500);
}
},
);
/**
* Verify the authenticated user has access to the given pro.
* Platform admins always have access.
*/
// biome-ignore lint/suspicious/noExplicitAny: Hono context type varies by route configuration
async function assertProAccess(c: any, 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;
|