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 | 1x 1x 1x 1x 1x 18x 16x 4x 12x 4x 8x 4x 4x 1x 9x 1x 8x 8x 8x 8x 3x 5x 5x 1x 11x 1x 10x 10x 10x 2x 2x 2x 2x 1x 1x 10x 10x 6x 4x 4x 1x 6x 1x 5x 5x 5x 5x 1x 4x 4x 1x 16x 1x 15x 15x 15x 15x 15x 15x 7x 7x 6x 1x 15x 2x 2x 1x 1x 15x 10x 5x 5x | // Quick AI helpers: single-shot blog draft / rewrite / SEO meta / topic
// suggestions. Sister file to blogs.routes.ts which mounts this sub-app and
// keeps the longer-running pipeline (generate-full / outline / from-outline)
// + jobs endpoints.
import { Hono } from "hono";
import { z } from "zod";
import { createDal } from "../../../dal";
import { getDb } from "../../../db";
import { logger } from "../../../lib/logger";
import { error, success } from "../../../lib/response";
import { zv } from "../../../lib/zv";
import {
aiDraftRateLimit,
aiMetaRateLimit,
aiRewriteRateLimit,
aiTopicRateLimit,
requirePlatformAdmin,
} from "../../../middleware";
import { createAIService, isAIEnabled } from "../../../services/ai/claude.service";
import {
formatResearchForPrompt,
gatherFullResearchContext,
} from "../../../services/ai/research";
type Variables = {
user: { id: string; email: string } | null;
};
const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>();
/**
* 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(),
});
// Map common AI provider failures onto user-facing copy. Anything we don't
// recognize falls back to the caller-supplied default.
function aiErrorMessage(err: unknown, fallback: string): string {
if (!(err instanceof Error)) return fallback;
if (err.message.includes("authentication")) {
return "AI service authentication error. Please contact support.";
}
if (err.message.includes("rate limit")) {
return "AI service rate limit reached. Please try again in a few minutes.";
}
if (err.message.includes("unavailable")) {
return "AI service temporarily unavailable. Please try again later.";
}
return fallback;
}
/**
* 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) => {
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);
return error(
c,
"AI_ERROR",
aiErrorMessage(err, "Failed to generate blog draft. Please try again."),
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) => {
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);
return error(
c,
"AI_ERROR",
aiErrorMessage(err, "Failed to rewrite section. Please try again."),
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) => {
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);
return error(
c,
"AI_ERROR",
aiErrorMessage(err, "Failed to generate metadata. Please try again."),
500,
);
}
},
);
/**
* POST /api/ai/blogs/suggest-topics
* Generate blog topic suggestions
*/
app.post(
"/suggest-topics",
aiTopicRateLimit,
zv("json", suggestTopicsSchema),
async (c) => {
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);
return error(
c,
"AI_ERROR",
aiErrorMessage(err, "Failed to suggest topics. Please try again."),
500,
);
}
},
);
export default app;
|