Restructure into Wiki, Studio and Python monorepo with scoped CI
python CI and deployment / verify-and-deploy (push) Successful in 7m23s
studio CI and deployment / verify-and-deploy (push) Failing after 5m28s
wiki CI and deployment / verify-and-deploy (push) Failing after 6m13s

This commit is contained in:
2026-10-25 21:13:43 +08:00
parent c898e41672
commit a2330b22e2
152 changed files with 3525 additions and 3287 deletions
+28
View File
@@ -0,0 +1,28 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { ZodError } from "zod";
export function sameOrigin(req: NextApiRequest) {
const origin=req.headers.origin;
if (origin && new URL(origin).host !== req.headers.host) throw new Error("Cross-origin request rejected");
}
export function apiError(res: NextApiResponse,error: unknown) {
if(error instanceof ZodError) return res.status(400).json({error:"请检查输入内容",issues:error.issues});
const message=error instanceof Error?error.message:"";
const clientMessages:Record<string,string>={
'Character PNG must have transparency':'请上传带真实透明背景的 PNG,透明区域 alpha 为 0,人物内部 alpha 至少为 250',
'Register the coded page before creating its post':'请先在代码中注册对应的作品页面',
'Referenced asset does not exist':'引用的素材不存在',
'A media post needs matching content':'素材包需要包含对应类型的素材',
'Cover must reference an image':'封面需要引用一张图片',
'Unsupported image format':'支持 JPG、PNG、WebP、GIF 和 AVIF 图片',
'File has no video stream':'文件中没有可用的画面',
'Select an audio file':'请选择独立的声音文件',
'Unsupported media MIME type':'文件类型不受支持',
};
if(clientMessages[message])return res.status(400).json({error:clientMessages[message]});
const code=(error as {code?:string})?.code;
if(code==='23505')return res.status(409).json({error:'这个网址标识已经存在,请换一个'});
if(code==='23503')return res.status(400).json({error:'引用的分类或素材不存在'});
if(["Invalid cursor","Tag not found","Cross-origin request rejected"].includes(message)) return res.status(400).json({error:message});
console.error("API failure",error instanceof Error?error.message:"Unknown error");
return res.status(500).json({error:"操作没有完成,请稍后重试"});
}
+11
View File
@@ -0,0 +1,11 @@
import sharp from "sharp";
import {streetPeople} from "./street-people";
export async function validateCharacter(path:string) {
try {
const input=sharp(path,{limitInputPixels:streetPeople.limits.pixels});
const meta=await input.metadata();
if(meta.format!=="png"||!meta.hasAlpha)throw new Error("Character PNG must have transparency");
const stats=await input.stats();const alpha=stats.channels.at(-1)!;
if(alpha.min!==0||alpha.max<250)throw new Error("Character PNG must have transparency");
}catch{throw new Error("Character PNG must have transparency");}
}
+13
View File
@@ -0,0 +1,13 @@
import { Pool, type PoolClient } from "pg";
const globalDb = globalThis as unknown as { promptPool?: Pool };
export function db() {
if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is required");
return globalDb.promptPool ??= new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
}
export async function transaction<T>(run: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await db().connect();
try { await client.query("BEGIN"); const result = await run(client); await client.query("COMMIT"); return result; }
catch (error) { await client.query("ROLLBACK"); throw error; }
finally { client.release(); }
}
+6
View File
@@ -0,0 +1,6 @@
export function healthResponse(method: string | undefined, release = "development") {
if (method !== "GET" && method !== "HEAD") {
return { statusCode: 405, body: { error: "Method not allowed" } };
}
return { statusCode: 200, body: { status: "ok", service: "prompt", release } };
}
+30
View File
@@ -0,0 +1,30 @@
import { db } from "./db";
import { decodeCursor, encodeCursor, type FeedData, type Post, type PostKind, type Tag } from "./model";
import { works } from "../content/registry";
const tagTree = `WITH RECURSIVE tree AS (SELECT *,slug::text AS path FROM tags WHERE parent_id IS NULL UNION ALL SELECT t.*,tree.path||'/'||t.slug FROM tags t JOIN tree ON t.parent_id=tree.id) SELECT * FROM tree`;
export async function tags(): Promise<Tag[]> { return (await db().query(`${tagTree} ORDER BY path`)).rows; }
const expand = `SELECT p.*,
COALESCE((SELECT jsonb_agg(ae ORDER BY ae.position) FROM (SELECT a.*,pa.position,pa.role,COALESCE((SELECT jsonb_agg(v.role) FROM asset_variants v WHERE v.asset_id=a.id),'[]') AS variants FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id) ae),'[]') AS assets,
COALESCE((SELECT jsonb_agg(t) FROM tags t JOIN post_tags pt ON pt.tag_id=t.id WHERE pt.post_id=p.id),'[]') AS tags FROM posts p`;
function serialize(posts: Post[], allTags: Tag[]): Post[] {
return posts.map(p => ({...p, created_at: new Date(p.created_at).toISOString(), updated_at:new Date(p.updated_at).toISOString(), tags:p.tags.map(t=>allTags.find(a=>a.id===t.id)!).filter(Boolean)}));
}
export async function getPost(slug: string): Promise<Post | null> {
const result = await db().query(`${expand} WHERE p.slug=$1`,[slug]);
return serialize(result.rows,await tags())[0] || null;
}
export async function feed(options: {kind?: PostKind; path?: string; cursor?: string; q?: string} = {}): Promise<FeedData> {
const allTags=await tags(); const target=options.path ? allTags.find(t=>t.path===options.path) : undefined;
if(options.path&&!target) throw new Error("Tag not found");
const cursor=decodeCursor(options.cursor); const values: unknown[]=[];
const where=[`((p.kind IN ('article','motion') AND p.page_key=ANY($1::text[])) OR EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role='content' AND a.kind=p.kind AND a.storage_key IS NOT NULL AND a.byte_size>0))`];
values.push(Object.keys(works));
if(options.kind){values.push(options.kind);where.push(`p.kind=$${values.length}`);}
if(target){values.push(allTags.filter(t=>t.path===target.path||t.path.startsWith(target.path+"/")).map(t=>t.id));where.push(`EXISTS(SELECT 1 FROM post_tags WHERE post_id=p.id AND tag_id=ANY($${values.length}::uuid[]))`);}
if(options.q){values.push(`%${options.q.replace(/[\\%_]/g,"\\$&")}%`);where.push(`p.title ILIKE $${values.length}`);}
if(cursor){values.push(...cursor);where.push(`(p.created_at,p.id)<($${values.length-1}::timestamptz,$${values.length}::uuid)`);}
const rows=(await db().query(`${expand} WHERE ${where.join(' AND ')} ORDER BY p.created_at DESC,p.id DESC LIMIT 25`,values)).rows as Post[];
const hasMore=rows.length>24; const posts=serialize(rows.slice(0,24),allTags); const last=posts.at(-1);
const contributions=(await db().query(`SELECT to_char(occurred_at AT TIME ZONE 'Asia/Shanghai','YYYY-MM-DD') AS day,sum(amount)::integer AS total FROM contribution_events WHERE occurred_at>=now()-interval '366 days' GROUP BY day ORDER BY day`)).rows;
return {posts,tags:allTags,contributions,nextCursor:hasMore&&last?encodeCursor(last.created_at,last.id):null};
}
+9
View File
@@ -0,0 +1,9 @@
import type {NextApiRequest,NextApiResponse} from 'next';
export function sendMarkdown(req:NextApiRequest,res:NextApiResponse,text:string|null){
res.setHeader('Allow','GET, HEAD');
if(req.method!=='GET'&&req.method!=='HEAD')return res.status(405).end();
if(text===null)return res.status(404).end();
res.setHeader('Content-Type','text/markdown; charset=utf-8');
res.setHeader('Cache-Control','no-cache');
return req.method==='HEAD'?res.status(200).end():res.status(200).send(text);
}
+22
View File
@@ -0,0 +1,22 @@
export const sections = [
{ path: "images", kind: "image", name: "图片素材", hint: "照片、插画与可以反复使用的画面" },
{ path: "videos", kind: "video", name: "视频素材", hint: "片段与镜头,声音随画面一起收好" },
{ path: "audio", kind: "audio", name: "声音素材", hint: "音乐、环境声与声音片段" },
{ path: "articles", kind: "article", name: "图文作品", hint: "用网页编写,慢慢打磨每一页" },
{ path: "motion", kind: "motion", name: "动态作品", hint: "让网页本身成为时间里的画面" },
] as const;
export type PostKind = typeof sections[number]["kind"];
export type Asset = { id: string; kind: "image" | "video" | "audio" | "text"; filename: string | null; body: string | null; width: number | null; height: number | null; duration: number | null; has_audio: boolean | null; processing_status: string; variants: string[] };
export type Tag = { id: string; parent_id: string | null; name: string; slug: string; path: string };
export type Post = { id: string; slug: string; kind: PostKind; title: string; created_at: string; updated_at: string; page_key: string | null; cover_asset_id: string | null; assets: Asset[]; tags: Tag[] };
export type FeedData = { posts: Post[]; tags: Tag[]; contributions: { day: string; total: number }[]; nextCursor: string | null; unavailable?: boolean };
export function validSection(path: string) { return sections.find(s => s.path === path); }
export const mediaUrl = (id: string, variant?: string) => `/api/media/${id}${variant ? `?variant=${variant}` : ""}`;
export function encodeCursor(date: string, id: string) { return Buffer.from(JSON.stringify([date,id])).toString("base64url"); }
export function decodeCursor(value?: string) {
if (!value) return null;
try { const [date,id] = JSON.parse(Buffer.from(value,"base64url").toString());
if (!Number.isNaN(Date.parse(date)) && /^[0-9a-f-]{36}$/.test(id)) return [date,id];
} catch { /* invalid pagination cursor */ }
throw new Error("Invalid cursor");
}
+7
View File
@@ -0,0 +1,7 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
export const run=promisify(execFile);
export async function probe(file:string) {
const {stdout}=await run(process.env.FFPROBE_PATH||'ffprobe',['-v','error','-protocol_whitelist','file,pipe','-show_streams','-show_format','-of','json',file],{timeout:30000,maxBuffer:2*1024*1024});
return JSON.parse(stdout) as {streams:{codec_type:string;width?:number;height?:number}[];format:{duration?:string;format_name?:string}};
}
@@ -0,0 +1,46 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { chapters } from "../content/learning-skills/data";
import { transaction } from "./db";
import { putFile } from "./storage";
function stableId(name: string) {
const bytes=createHash("sha256").update(`prompt:learning-series:${name}`).digest().subarray(0,16);
bytes[6]=(bytes[6]&15)|80;bytes[8]=(bytes[8]&63)|128;
const hex=bytes.toString("hex");return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;
}
// Explicit editorial publication, never part of the generic storage bootstrap.
// Re-running updates these three authored posts without duplicating posts or media.
export async function publishLearningSeries() {
const path="public/learning-skills/cover.png";
const cover=await readFile(path);const digest=createHash("sha256").update(cover).digest("hex");
const storageKey=`editorial/learning-skills/${digest}.png`;
const coverId=stableId("cover");
await putFile(storageKey,path,"image/png");
return transaction(async client=>{
await client.query("SELECT pg_advisory_xact_lock(18131002)");
await client.query(`INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,sha256,width,height)
VALUES($1,'image','学习资料自己做-系列共用封面.png',$2,'image/png',$3,$4,1080,1440)
ON CONFLICT(id) DO UPDATE SET storage_key=excluded.storage_key,byte_size=excluded.byte_size,sha256=excluded.sha256`,[coverId,storageKey,cover.length,digest]);
const root=(await client.query(`INSERT INTO tags(id,parent_id,slug,name) VALUES($1,NULL,'learning-skills','学习工具')
ON CONFLICT(parent_id,slug) DO UPDATE SET name=excluded.name RETURNING id`,[stableId("tag-root")])).rows[0].id;
const published:string[]=[];
for(const chapter of chapters){
const child=(await client.query(`INSERT INTO tags(id,parent_id,slug,name) VALUES($1,$2,$3,$4)
ON CONFLICT(parent_id,slug) DO UPDATE SET name=excluded.name RETURNING id`,[stableId(`tag-${chapter.key}`),root,chapter.number==="01"?"notes":chapter.number==="02"?"teaching":"english",chapter.number==="01"?"笔记复习":chapter.number==="02"?"教学资料":"英语学习"])).rows[0].id;
const result=await client.query(`INSERT INTO posts(id,slug,kind,title,page_key,cover_asset_id) VALUES($1,$2,'article',$3,$4,$5)
ON CONFLICT(slug) DO UPDATE SET title=excluded.title,cover_asset_id=COALESCE((SELECT asset_id FROM page_snapshots WHERE post_id=posts.id AND page_index=1),excluded.cover_asset_id),updated_at=now()
WHERE posts.page_key=excluded.page_key AND posts.kind='article' RETURNING id,cover_asset_id`,[stableId(chapter.key),chapter.slug,chapter.title,chapter.key,coverId]);
if(!result.rows[0])throw new Error(`Publication slug is already used by another post: ${chapter.slug}`);
const postId=result.rows[0].id;const captionId=stableId(`caption-${chapter.key}`);
const caption=`学习资料自己做 · 第 ${chapter.number} 辑\n${chapter.subtitle}。三篇共用系列封面,每篇 8 页,介绍 10 项工具。\n\n${chapter.skills.map((skill,i)=>`${String(i+1).padStart(2,"0")} ${skill.name} — ${skill.title}`).join("\n")}\n\n根据 GitHub 项目说明整理,尚未逐项安装实测。内页小样为排版示意;可在末页访问全部来源。`;
await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2) ON CONFLICT(id) DO UPDATE SET body=excluded.body",[captionId,caption]);
await client.query(`INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,0,'content'),($1,$3,1,'caption')
ON CONFLICT(post_id,position) DO UPDATE SET asset_id=excluded.asset_id,role=excluded.role`,[postId,result.rows[0].cover_asset_id,captionId]);
await client.query("INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2) ON CONFLICT DO NOTHING",[postId,child]);
await client.query(`INSERT INTO render_jobs(post_id,status,revision) VALUES($1,'pending',$2) ON CONFLICT(post_id) DO UPDATE SET status='pending',revision=excluded.revision,attempts=0,target_page=NULL,error=NULL WHERE render_jobs.revision IS DISTINCT FROM excluded.revision`,[postId,process.env.RELEASE_SHA||'development']);
published.push(chapter.slug);
}
return {published,coverId};
});
}
+57
View File
@@ -0,0 +1,57 @@
import {chromium} from "playwright-core";
import {createHash,randomUUID} from "node:crypto";
import {mkdtemp,rm} from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
import {db,transaction} from "./db";
import {putFile} from "./storage";
import {chapters} from "../content/learning-skills/data";
export async function snapshotState(slug:string){
const post=(await db().query('SELECT id,page_key FROM posts WHERE slug=$1',[slug])).rows[0];
if(!post||!chapters.some(c=>c.key===post.page_key))return null;
const pages=(await db().query('SELECT page_index,asset_id,rendered_at,revision FROM page_snapshots WHERE post_id=$1 ORDER BY page_index',[post.id])).rows;
const job=(await db().query('SELECT status,error,revision,attempts,target_page FROM render_jobs WHERE post_id=$1',[post.id])).rows[0]||null;
return {postId:post.id,pages,job};
}
export async function queueSnapshots(postId:string,pageIndex?:number){
await db().query(`INSERT INTO render_jobs(post_id,status,revision,target_page) VALUES($1,'pending',$2,$3) ON CONFLICT(post_id) DO UPDATE SET status='pending',revision=excluded.revision,target_page=excluded.target_page,attempts=0,error=NULL WHERE render_jobs.status NOT IN ('pending','processing')`,[postId,process.env.RELEASE_SHA||'development',pageIndex??null]);
}
export async function renderOne(){
const job=await transaction(async c=>(await c.query(`UPDATE render_jobs SET status='processing',attempts=attempts+1,locked_at=now() WHERE post_id=(SELECT post_id FROM render_jobs WHERE status='pending' OR (status='processing' AND locked_at<now()-interval '10 minutes') ORDER BY post_id FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING *`)).rows[0]);
if(!job)return false;
const dir=await mkdtemp(join(tmpdir(),'prompt-snapshots-'));let browser;
try{
const post=(await db().query('SELECT slug,page_key FROM posts WHERE id=$1',[job.post_id])).rows[0];
if(!chapters.some(c=>c.key===post.page_key&&c.slug===post.slug))throw Error('Unknown coded page');
browser=await chromium.launch({executablePath:process.env.CHROMIUM_PATH||'/usr/bin/chromium',args:['--no-sandbox','--disable-dev-shm-usage']});
const context=await browser.newContext({viewport:{width:1080,height:1440},deviceScaleFactor:1,locale:'zh-CN',timezoneId:'Asia/Shanghai',reducedMotion:'reduce'});
const origin=new URL(process.env.RENDER_ORIGIN||'http://web:3000').origin;
await context.route('**/*',route=>new URL(route.request().url()).origin===origin?route.continue():route.abort());
const page=await context.newPage();const output:{index:number;id:string}[]=[];
for(let index=job.target_page||1;index<=(job.target_page||8);index++){
console.log('Rendering canvas',post.slug,index);
const response=await page.goto(`${origin}/p/${post.slug}/pages/${index}`,{waitUntil:'networkidle',timeout:45000});
if(!response?.ok())throw Error('Canvas page unavailable');
await page.locator('[data-render-page]').waitFor();await page.evaluate(async()=>{await document.fonts.ready;});
console.log('Canvas loaded',post.slug,index);
const overflow=await page.evaluate(()=>{const sheet=document.querySelector('.learning-sheet');if(!sheet)return false;const footer=sheet.querySelector('footer')!;return Array.from(sheet.children).filter(c=>c!==footer).some(c=>c.getBoundingClientRect().bottom>footer.getBoundingClientRect().top-2)});
if(overflow)throw Error(`Canvas ${index} overlaps its footer`);
const path=join(dir,`${index}.png`);const bytes=await page.locator('[data-render-page]').screenshot({path,animations:'disabled'});
const hash=createHash('sha256').update(bytes).digest('hex');const key=`snapshots/${hash}.png`;const size=await putFile(key,path,'image/png');
const asset=(await db().query(`INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,sha256,width,height) VALUES($1,'image',$2,$3,'image/png',$4,$5,1080,1440) ON CONFLICT(storage_key) DO UPDATE SET storage_key=excluded.storage_key RETURNING id`,[randomUUID(),`图文-${index}.png`,key,size,hash])).rows[0];output.push({index,id:asset.id});console.log('Canvas stored',post.slug,index);
}
await transaction(async c=>{
const current=(await c.query('SELECT revision FROM render_jobs WHERE post_id=$1 FOR UPDATE',[job.post_id])).rows[0];
if(current.revision!==job.revision)return;
for(const result of output){
await c.query(`INSERT INTO page_snapshots(post_id,page_index,asset_id,revision) VALUES($1,$2,$3,$4) ON CONFLICT(post_id,page_index) DO UPDATE SET asset_id=excluded.asset_id,revision=excluded.revision,rendered_at=now()`,[job.post_id,result.index,result.id,job.revision]);
await c.query(`INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'content') ON CONFLICT(post_id,position) DO UPDATE SET asset_id=excluded.asset_id,role='content'`,[job.post_id,result.id,result.index===1?0:result.index+1]);
}
// Position zero remains the shared series cover reference; captions remain at one.
if(output[0].index===1)await c.query('UPDATE posts SET cover_asset_id=$2,updated_at=now() WHERE id=$1',[job.post_id,output[0].id]);
await c.query("UPDATE render_jobs SET status='ready',error=NULL WHERE post_id=$1",[job.post_id]);
});
}catch(e){await db().query("UPDATE render_jobs SET status=$2,error=$3 WHERE post_id=$1 AND revision=$4",[job.post_id,job.attempts<3?'pending':'failed',e instanceof Error?e.message:'Screenshot failed',job.revision]);console.error('Page screenshot job failed',job.post_id,e instanceof Error?e.message:'');await new Promise(r=>setTimeout(r,3000));}
finally{await browser?.close();await rm(dir,{recursive:true,force:true});}
return true;
}
+26
View File
@@ -0,0 +1,26 @@
import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand, HeadBucketCommand, CreateBucketCommand } from "@aws-sdk/client-s3";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
let instance: S3Client;
export function storage() {
return instance ??= new S3Client({
endpoint: process.env.S3_ENDPOINT, region: "us-east-1", forcePathStyle: true,
credentials: { accessKeyId: process.env.S3_ACCESS_KEY!, secretAccessKey: process.env.S3_SECRET_KEY! },
requestChecksumCalculation: "WHEN_REQUIRED", responseChecksumValidation: "WHEN_REQUIRED",
});
}
export const bucket = () => process.env.S3_BUCKET || "prompt";
export async function ensureBucket() {
try { await storage().send(new HeadBucketCommand({ Bucket: bucket() })); }
catch (e) {
if ((e as { $metadata?: { httpStatusCode: number } }).$metadata?.httpStatusCode !== 404) throw e;
await storage().send(new CreateBucketCommand({ Bucket: bucket() }));
}
}
export async function putFile(key: string, path: string, mime: string) {
const size = (await stat(path)).size;
await storage().send(new PutObjectCommand({ Bucket: bucket(), Key: key, Body: createReadStream(path), ContentLength: size, ContentType: mime }));
return size;
}
export const getObject = (key: string, range?: string) => storage().send(new GetObjectCommand({ Bucket: bucket(), Key: key, Range: range }));
export const removeObject = (key: string) => storage().send(new DeleteObjectCommand({ Bucket: bucket(), Key: key }));
+9
View File
@@ -0,0 +1,9 @@
export const streetPeople = {
id: "street-people", version: "1.0.0", name: "街头小人", description: "松散笔触、冬日衣着与奶油色剪纸边的街头人物。",
prompt: "Draw ONE original full-body street person: {{subject}}. Naive observational felt-tip pen sketch; loose irregular dark plum, cobalt blue OR coral red lines; sparse facial features; adult proportions; simple winter clothes; scribbled hatching on hair and trousers. Ivory cream paper inside the silhouette and a narrow uneven cut-paper border. Center the entire figure and accessories, with transparent padding. True RGBA transparency outside the cutout. Hard die-cut edge, zero glow, zero feathering. No cast shadow, no background, no text, no other people, no polished vector, no anime.",
workflow: ["从 /skills/street-people/SKILL.md 入口阅读文档与子文档,再读取风格规范,将 {{subject}} 替换为人物动作与衣着。", "使用 agent 自己的图片生成工具,明确启用 transparent background;每张只生成一个人物。", "检查人物完整、画风和 alpha 通道;最多 16 张 PNG 通过同一 POST 请求上传,组成一个素材包。", "使用返回的 url 查看 post,assets 为可复用的素材 ID。"],
generation: { executor: "coding-agent", serverSideModel: false, reference: "/skills/street-people/reference.png", transparentBackground: true },
upload: { method: "POST", endpoint: "/api/skills/street-people", encoding: "multipart/form-data", fields: { files: "1–16 张真实透明 PNG,每张一个完整人物;外部 alpha=0,内部 alpha≥250", title: "素材包标题(可选)", description: "提示词、生成来源和补充说明(可选)", tags: "分类 UUID 数组的 JSON(可选)", slug: "唯一小写英文网址标识(可选)" }, response: { id:"post UUID", slug:"稳定标识", url:"/p/<slug>", assets:["asset UUID"] } },
limits: { files:16, bytesPerFile:262144000, totalBytes:1073741824, pixels:40000000 },
errors: { 400:"PNG 格式、透明通道或表单不符合规范", 409:"slug 已存在,请查看已有 post 或更换 slug", 413:"文件数或体积超过限制", 500:"存储或服务器暂不可用" }
} as const;
+27
View File
@@ -0,0 +1,27 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import { transaction } from "./db";
import { works } from "../content/registry";
export const postInput=z.object({
slug:z.string().regex(/^[a-z0-9][a-z0-9-]{0,119}$/).optional(),
kind:z.enum(["image","video","audio","article","motion"]),title:z.string().trim().min(1).max(200),
assets:z.array(z.object({id:z.uuid(),role:z.enum(["content","caption"]).default("content")})).max(100).default([]),
text:z.string().trim().max(100000).optional(),tags:z.array(z.uuid()).max(50).default([]),
coverAssetId:z.uuid().optional(),pageKey:z.string().max(120).optional(),
});
export async function createPost(input:z.infer<typeof postInput>) {
const id=randomUUID(); const slug=input.slug||id;
if(["article","motion"].includes(input.kind)&&(!input.pageKey||works[input.pageKey]?.kind!==input.kind)) throw new Error("Register the coded page before creating its post");
return transaction(async client=>{
const ids=[...new Set(input.assets.map(a=>a.id))];
const assets=ids.length?(await client.query('SELECT id,kind FROM assets WHERE id=ANY($1::uuid[])',[ids])).rows:[];
if(assets.length!==ids.length) throw new Error("Referenced asset does not exist");
if(["image","video","audio"].includes(input.kind)&&!input.assets.some(link=>link.role==='content'&&assets.some(a=>a.id===link.id&&a.kind===input.kind))) throw new Error("A media post needs matching content");
if(input.coverAssetId && !(await client.query("SELECT 1 FROM assets WHERE id=$1 AND kind='image'",[input.coverAssetId])).rowCount) throw new Error("Cover must reference an image");
await client.query('INSERT INTO posts(id,slug,kind,title,page_key,cover_asset_id) VALUES($1,$2,$3,$4,$5,$6)',[id,slug,input.kind,input.title,input.pageKey||null,input.coverAssetId||null]);
for(const [position,a] of input.assets.entries()) await client.query('INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,$4)',[id,a.id,position,a.role]);
if(input.text){const textId=randomUUID();await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2)",[textId,input.text]);await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'caption')",[id,textId,input.assets.length]);}
for(const tag of new Set(input.tags)) await client.query('INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2)',[id,tag]);
return {id,slug};
});
}