Add website link to page profile so the AI can read the shop site

Adds PageProfile.website (with migration). Codex runs without network, so
the profile draft route fetches the site server-side (public hosts only,
redirect-checked, size-capped, cached) and passes its text as
<shop_website>. Other prompts receive the URL via the shop profile.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Loma Bot Ops
2026-11-23 21:20:35 +07:00
parent b592cd43f4
commit 5f8f0c9159
16 changed files with 184 additions and 35 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ export const JOB_SELECT = {
createdAt: true, startedAt: true, finishedAt: true,
} as const;
const Profile = z.object({ business: z.string(), audience: z.string(), tone: z.string(), visualStyle: z.string().default(""), avoid: z.string(), cta: z.string() });
const Profile = z.object({ business: z.string(), audience: z.string(), tone: z.string(), visualStyle: z.string().default(""), avoid: z.string(), cta: z.string(), website: z.string().default("") });
const Draft = z.object({
title: z.string().min(1).max(120),
caption: z.string().min(1).max(5000),
+18
View File
@@ -7,10 +7,12 @@ export interface ShopProfile {
visualStyle: string;
avoid: string;
cta: string;
website: string;
}
export const PROFILE_FIELDS: { key: keyof ShopProfile; label: string; hint: string; max: number; rows: number }[] = [
{ key: "business", label: "ขายอะไร / จุดเด่นของร้าน", hint: "สินค้าหรือบริการ ราคาโดยประมาณ ส่งที่ไหน ต่างจากร้านอื่นตรงไหน", max: 2000, rows: 4 },
{ key: "website", label: "เว็บไซต์ของร้าน", hint: "เช่น https://www.myshop.co.th — AI จะอ่านข้อความในหน้านี้ตอนร่างโปรไฟล์", max: 300, rows: 1 },
{ key: "audience", label: "ลูกค้าหลักคือใคร", hint: "เช่น ผู้หญิงวัยทำงาน 25–40 ซื้อเป็นของขวัญ", max: 1000, rows: 2 },
{ key: "tone", label: "น้ำเสียงของเพจ", hint: "เช่น เป็นกันเอง เรียกลูกค้าว่า “คุณลูกค้า” ใช้ emoji พอประมาณ", max: 500, rows: 2 },
{ key: "visualStyle", label: "สีและสไตล์ภาพของแบรนด์", hint: "เช่น ใช้กรมท่า ฟ้า และขาว ภาพทันสมัย เรียบมืออาชีพ แสงคม หลีกเลี่ยงสีชมพูและภาพการ์ตูน", max: 1000, rows: 3 },
@@ -18,6 +20,19 @@ export const PROFILE_FIELDS: { key: keyof ShopProfile; label: string; hint: stri
{ key: "cta", label: "ให้ลูกค้าติดต่อทางไหน", hint: "เช่น ทักแชทเพจ / โทร 08x-xxx-xxxx / LINE @shop", max: 500, rows: 2 },
];
/** Normalises a typed website to an absolute http(s) URL ("myshop.co.th" → "https://myshop.co.th/"). Empty string when blank, null when invalid. */
export function normalizeWebsite(input: string): string | null {
const text = input.trim();
if (!text) return "";
try {
const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`);
if ((url.protocol !== "https:" && url.protocol !== "http:") || !url.hostname.includes(".") || url.username || url.password) return null;
return url.href;
} catch {
return null;
}
}
export function parseProfile(body: Record<string, unknown>): { profile: ShopProfile } | { error: string } {
const profile = {} as ShopProfile;
for (const f of PROFILE_FIELDS) {
@@ -25,6 +40,9 @@ export function parseProfile(body: Record<string, unknown>): { profile: ShopProf
if (value.length > f.max) return { error: `“${f.label}” ยาวเกิน ${f.max.toLocaleString("th-TH")} ตัวอักษร` };
profile[f.key] = value;
}
const website = normalizeWebsite(profile.website);
if (website === null || website.length > 300) return { error: "ลิงก์เว็บไซต์ไม่ถูกต้อง ต้องขึ้นต้นด้วย http:// หรือ https://" };
profile.website = website;
if (!profile.business) return { error: "กรอกว่าร้านขายอะไรก่อน" };
return { profile };
}
+101
View File
@@ -0,0 +1,101 @@
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
const cache = new Map<string, { expiresAt: number; value: string }>();
const MAX_BYTES = 1_500_000;
const MAX_TEXT = 6_000;
const MAX_REDIRECTS = 3;
/** True for loopback, private, link-local, CGNAT and other non-public addresses (IPv4 and IPv6). */
function isPrivateAddress(address: string): boolean {
const mapped = address.toLowerCase().replace(/^::ffff:/, "");
if (isIP(mapped) === 4) {
const [a, b] = mapped.split(".").map(Number);
return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19));
}
const v6 = mapped;
return v6 === "::" || v6 === "::1" || v6.startsWith("fc") || v6.startsWith("fd") || /^fe[89ab]/.test(v6) || v6.startsWith("ff");
}
async function assertPublicHost(url: URL) {
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("scheme");
if (url.username || url.password) throw new Error("credentials");
if (url.port && url.port !== "80" && url.port !== "443") throw new Error("port");
const host = url.hostname.replace(/^\[|\]$/g, "");
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) throw new Error("host");
const addresses = isIP(host) ? [{ address: host }] : await lookup(host, { all: true });
if (!addresses.length || addresses.some((a) => isPrivateAddress(a.address))) throw new Error("private");
}
function decodeEntities(text: string): string {
return text
.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;|&apos;/gi, "'")
.replace(/&#(\d+);/g, (_, n: string) => String.fromCodePoint(Math.min(Number(n), 0x10ffff)));
}
function metaContent(html: string, name: string): string {
const tag = html.match(new RegExp(`<meta[^>]+(?:name|property)=["']${name}["'][^>]*>`, "i"))?.[0];
return decodeEntities(tag?.match(/content=["']([^"']*)["']/i)?.[1] ?? "").trim();
}
/** Reads a shop's public website into short plain text (title, description, visible copy). Empty string if it cannot be read. */
export async function websitePrompt(website: string): Promise<string> {
const cached = cache.get(website);
if (cached && cached.expiresAt > Date.now()) return cached.value;
let value = "";
try {
let url = new URL(website);
let response: Response | null = null;
// Follow redirects by hand so every hop is checked against the same public-host rule.
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
await assertPublicHost(url);
response = await fetch(url, {
redirect: "manual",
cache: "no-store",
signal: AbortSignal.timeout(10_000),
headers: { accept: "text/html,application/xhtml+xml", "user-agent": "Mozilla/5.0 (compatible; PageManagerBot/1.0)" },
});
const location = response.headers.get("location");
if (response.status >= 300 && response.status < 400 && location) {
url = new URL(location, url);
response = null;
continue;
}
break;
}
if (response?.ok && response.body && /text\/html|application\/xhtml/i.test(response.headers.get("content-type") ?? "")) {
const chunks: Uint8Array[] = [];
let size = 0;
const reader = response.body.getReader();
while (size < MAX_BYTES) {
const { done, value: chunk } = await reader.read();
if (done) break;
chunks.push(chunk);
size += chunk.length;
}
await reader.cancel().catch(() => {});
const html = Buffer.concat(chunks).toString("utf8");
const title = decodeEntities(html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] ?? "").replace(/\s+/g, " ").trim();
const description = metaContent(html, "description") || metaContent(html, "og:description");
const body = decodeEntities(
html
.replace(/<(script|style|noscript|svg|template|iframe)[\s\S]*?<\/\1>/gi, " ")
.replace(/<!--[\s\S]*?-->/g, " ")
.replace(/<\/(p|div|li|h[1-6]|section|article|tr|br)>|<br\s*\/?>/gi, "\n")
.replace(/<[^>]+>/g, " "),
)
.split("\n")
.map((line) => line.replace(/\s+/g, " ").trim())
.filter((line) => line.length > 1)
.join("\n")
.slice(0, MAX_TEXT);
if (title || description || body) {
value = `<shop_website url="${website}">\nTitle: ${title}\nDescription: ${description}\n\n${body}\n</shop_website>`;
}
}
} catch {
value = "";
}
cache.set(website, { expiresAt: Date.now() + 60 * 60_000, value });
return value;
}