Unify Wiki and Studio and remove deployment scaffolding
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
const docs:Record<string,string>={
|
||||
'/studio/api/export/{slug}': `# Studio 封面工具 API
|
||||
|
||||
方法:GET, POST
|
||||
路径参数:slug 为 learning-skills-template(同一母版四张试版)或 layout-selection(三种不同构图);first-idea 仅提供 GET 内容导出。
|
||||
GET 参数:省略 format 返回方案 JSON;format=markdown 返回说明;format=svg 返回初始封面。四张试版用 slide=0..3(默认 0),多模板工具用 layoutId=ref-01|ref-07|ref-26(默认 ref-01)。
|
||||
JSON:普通方案 version:1;四张试版 version:2;多模板 version:3,layouts 包含源教程、画板、构件坐标及分层蒙版。文字、图位、装饰一一对应,图片位为色块占位。
|
||||
POST:Content-Type: application/json。format=svg(默认)返回独立 SVG;format=json 返回渲染参数及模板信息。请求最大 32KB,无存储副作用。
|
||||
learning-skills-template 参数:slide(整数 0–3,默认 0)、heading(1–6 字)、body(最多 360 字、3 行)、color、accent(#RRGGBB)、masthead(2 项数组,每项 1–8 个英文字母/空格);省略参数沿用初始值。
|
||||
layout-selection 参数:layoutId(必填,ref-01/ref-07/ref-26)、fields(可选,以对应模板 T 构件 ID 为键;每项 1–120 字、最多 4 行)、color、accent(#RRGGBB)。省略文字沿用初始值;拒绝未知参数或构件 ID。
|
||||
示例:POST /studio/api/export/learning-skills-template?format=svg
|
||||
{"slide":1,"heading":"笔记复习","color":"#7a8b7e"}
|
||||
POST /studio/api/export/layout-selection?format=svg
|
||||
{"layoutId":"ref-01","fields":{"T01":"STUDY","T02":"笔记复习\\n主题说明占位"},"color":"#83918a"}
|
||||
错误:400 参数/格式错误;404 方案不存在;405 方法不支持;413 请求过大。SVG 不含编辑辅助边界,文字经过 XML 转义;装饰位分层图片是按源构件重建的矢量;原始低分辨率分层保留在模板 JSON 中供核对。`,
|
||||
'/studio/api/health': '# 创作站健康检查\n\n方法:GET, HEAD\n无业务参数。GET 返回 200 JSON:{"status":"ok","service":"prompt-studio"};HEAD 无正文。\n示例:GET /studio/api/health\n错误:405 方法不支持。',
|
||||
};
|
||||
export function serveApiDocumentation(req:NextApiRequest,res:NextApiResponse,path:string){
|
||||
if(!['GET','HEAD'].includes(req.method||'')||typeof req.query.agent_mode!=='string'||req.query.agent_mode.toLowerCase()!=='true')return false;
|
||||
if(!docs[path])return false;
|
||||
res.setHeader('Content-Type','text/plain; charset=utf-8');res.setHeader('Cache-Control','no-store');res.status(200);
|
||||
if(req.method==='HEAD')res.end();else res.send(docs[path]+'\n\n使用 GET 或 HEAD,在原地址加 ?agent_mode=True;已有参数时加 &agent_mode=True。值不区分大小写。动态路径可保留占位符读取说明。业务调用请移除 agent_mode。\nAPI 目录:/api?agent_mode=True\n');return true;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from '../../lib/canvas-document.ts';
|
||||
@@ -0,0 +1,24 @@
|
||||
import type {IncomingMessage} from 'node:http';
|
||||
import {series} from './series';
|
||||
import {parameters,uuid} from './layout-parameters';
|
||||
import fixedLayouts from '../content/templates/layouts.json';
|
||||
import standardLayout from '../content/standard-layout.json';
|
||||
const layouts=[...fixedLayouts,standardLayout];
|
||||
import type {Design} from './native-layout';
|
||||
|
||||
/** Only forward the session to our fixed private Wiki service, never a request Host. */
|
||||
export async function readDesign(id:unknown,req:IncomingMessage):Promise<Design|null>{
|
||||
if(!uuid(id))return null;
|
||||
const origin=process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '3000'}`;
|
||||
const headers:Record<string,string>={};
|
||||
if(req.headers.cookie)headers.cookie=req.headers.cookie;
|
||||
if(req.headers.authorization)headers.authorization=req.headers.authorization;
|
||||
const response=await fetch(`${origin}/api/studio/designs/${id}`,{headers,redirect:'error',cache:'no-store',signal:AbortSignal.timeout(8000)});
|
||||
if(response.status===404||response.status===400)return null;
|
||||
if(!response.ok)throw new Error('Saved layout service unavailable');
|
||||
const {design}=await response.json() as {design:Design};
|
||||
const layout=layouts.find(l=>l.id===design.layoutId);
|
||||
if(!layout||design.id!==id)throw new Error('Invalid saved layout');
|
||||
if((design as Design&{archived?:boolean}).archived)return null;
|
||||
return {...design,...(design.document?{document:series(design.document,layouts)}:{}),parameters:parameters(layout,design.parameters)};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export type GraphicItem = {
|
||||
id:string;kind:'text'|'rect'|'ellipse'|'image';name:string;text:string;
|
||||
x:number;y:number;w:number;h:number;fill:string;size:number;hidden:boolean;locked:boolean;src?:string;
|
||||
};
|
||||
export type GraphicDocument = {name:string;background:string;items:GraphicItem[]};
|
||||
const color=(value:unknown)=>typeof value==='string'&&/^#[a-f0-9]{6}$/i.test(value);
|
||||
/** Accept only bounded editable documents; never execute or load external assets. */
|
||||
export function parseGraphicDocument(raw:string):GraphicDocument {
|
||||
if(raw.length>5*1024*1024)throw Error('设计文件不得超过 5MB');
|
||||
const d=JSON.parse(raw);
|
||||
if(!d||typeof d.name!=='string'||d.name.length>100||!color(d.background)||!Array.isArray(d.items)||d.items.length>500)throw Error('设计文件格式不正确');
|
||||
const ids=new Set<string>();
|
||||
for(const i of d.items){
|
||||
if(!i||typeof i.id!=='string'||i.id.length>100||ids.has(i.id)||!['text','rect','ellipse','image'].includes(i.kind)||typeof i.name!=='string'||i.name.length>200||typeof i.text!=='string'||i.text.length>4000||!color(i.fill)||typeof i.hidden!=='boolean'||typeof i.locked!=='boolean'||![i.x,i.y,i.w,i.h,i.size].every(Number.isFinite)||Math.abs(i.x)>4000||Math.abs(i.y)>4000||i.w<1||i.h<1||i.w>4000||i.h>4000||i.size<8||i.size>240)throw Error('设计图层格式不正确');
|
||||
if(i.kind==='image'&&(typeof i.src!=='string'||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(i.src)))throw Error('图片必须为嵌入式 PNG、JPEG 或 WebP');
|
||||
ids.add(i.id);
|
||||
}
|
||||
return {name:d.name,background:d.background,items:d.items.map((i:GraphicItem)=>({id:i.id,kind:i.kind,name:i.name,text:i.text,x:i.x,y:i.y,w:i.w,h:i.h,fill:i.fill,size:i.size,hidden:i.hidden,locked:i.locked,...(i.kind==='image'?{src:i.src}:{})}))};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/** References in the retained toolbox are internal Wiki media, displayed as derivatives. */
|
||||
export function referencePreview(source:string){
|
||||
const path=new URL(source,'http://wiki.internal').pathname;
|
||||
if(!/^\/api\/media\/[0-9a-f-]{36}$/.test(path))throw Error('Invalid reference media');
|
||||
return '/api/preview?'+new URLSearchParams({source:path,width:'960'});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type {NextApiRequest} from 'next';
|
||||
import type {Parameters} from './layout-parameters';
|
||||
/** Only fetch bounded previews from the authenticated Wiki service, never caller URLs. */
|
||||
export async function embedLayoutImages(req:NextApiRequest,params:Parameters){
|
||||
const ids=[...new Set(Object.values(params.images).flatMap(v=>v.assetId?[v.assetId]:[]))],sources:Record<string,string>={};let total=0;
|
||||
const headers:Record<string,string>={};if(req.headers.authorization)headers.authorization=req.headers.authorization;if(req.headers.cookie)headers.cookie=req.headers.cookie;
|
||||
for(const id of ids){const url=(process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '3000'}`)+'/api/preview?'+new URLSearchParams({source:'/api/media/'+id,width:'960'}),r=await fetch(url,{headers,signal:AbortSignal.timeout(15000),redirect:'error'});if(!r.ok||r.headers.get('content-type')?.split(';')[0]!=='image/webp')throw Error('图片预览不可访问,请检查图片 ID 与登录状态');const chunks:Buffer[]=[];const reader=r.body!.getReader();try{while(true){const {done,value}=await reader.read();if(done)break;total+=value.length;if(total>16*1024*1024)throw Error('图片预览总计超限');chunks.push(Buffer.from(value))}}finally{await reader.cancel()}sources[id]='data:image/webp;base64,'+Buffer.concat(chunks).toString('base64');}
|
||||
return sources;
|
||||
}
|
||||
|
||||
/** Export a self-contained SVG without storing image bytes in template JSON. */
|
||||
export async function embedSvgMedia(req:NextApiRequest,svg:string){
|
||||
const paths=[...new Set(svg.match(/\/api\/media\/[0-9a-f-]{36}/g)||[])];
|
||||
const headers:Record<string,string>={};if(req.headers.authorization)headers.authorization=req.headers.authorization;if(req.headers.cookie)headers.cookie=req.headers.cookie;
|
||||
let total=0;
|
||||
for(const path of paths){
|
||||
const response=await fetch((process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '3000'}`)+path,{headers,redirect:'error',signal:AbortSignal.timeout(15000)});
|
||||
const mime=response.headers.get('content-type')?.split(';')[0];
|
||||
if(!response.ok||!mime||!['image/png','image/jpeg','image/webp'].includes(mime))throw Error('模板图片不可访问');
|
||||
const chunks:Uint8Array[]=[];const reader=response.body!.getReader();
|
||||
try{while(true){const {done,value}=await reader.read();if(done)break;total+=value.length;if(total>16*1024*1024)throw Error('模板图片总计超限');chunks.push(value);}}finally{await reader.cancel();}
|
||||
svg=svg.replaceAll(path,'data:'+mime+';base64,'+Buffer.concat(chunks).toString('base64'));
|
||||
}
|
||||
return svg;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from '../../lib/layout-parameters.ts';
|
||||
@@ -0,0 +1,72 @@
|
||||
import type {CSSProperties} from 'react';
|
||||
import type {Layout,Parameters,Slot} from './layout-parameters';
|
||||
|
||||
export type Design={document?:import('./series').Series;id:string;name:string;layoutId:string;parameters:Parameters;revision:number;url:string};
|
||||
// getRandomValues is available on the deployment's HTTP origin; randomUUID is not.
|
||||
export const newElementId=()=> 'user-'+Array.from(globalThis.crypto.getRandomValues(new Uint32Array(4)),n=>n.toString(16).padStart(8,'0')).join('');
|
||||
export const emptyParameters=():Parameters=>({texts:{},images:{},decorations:{}});
|
||||
export const designUrl=(_layoutId:string,id:string)=>`/studio/template-layout?id=${id}`;
|
||||
export function nativeLayout(layout:Layout):Layout {
|
||||
return {id:layout.id,name:layout.name,width:layout.width,height:layout.height,elements:layout.elements.map(({id,kind,role,box,direction,text,reading})=>({id,kind,role,box,direction,text,reading}))};
|
||||
}
|
||||
// Each composition has its own paper and inks; layered artwork can add a middle tone.
|
||||
const palettes=[
|
||||
['#f3eee4','#293b42','#7c9a9e','#c4d5cb'],['#f5f2e9','#344335','#879782','#d7c39f'],['#efede7','#383d4a','#8996a6','#c5d0d7'],
|
||||
['#5e7472','#f5f0e5','#354e4a','#d9ded0'],['#f5eddf','#5c3b32','#b47d68','#d9bba0'],['#eceee8','#263d43','#688a94','#b4c7c7'],
|
||||
['#f3eddf','#4c4a36','#a1a185','#d8cba9'],['#edf0ef','#23424b','#73929a','#b6cbd2'],['#f5f1e9','#2f3e38','#7f9688','#d1d7ba'],
|
||||
['#eeece4','#344b57','#526e80','#afc4c9'],['#f4eee8','#4e393b','#a58a90','#d8bdb3'],['#f1f0e9','#424b36','#8c997b','#d1c7aa'],
|
||||
['#f3ebe5','#5b3e39','#b48e7e','#dec6ab'],['#eef0e7','#384c42','#789485','#c4d1b5'],['#e9edee','#2e4555','#839ba8','#c6d3d4'],
|
||||
['#f4f0e7','#50483a','#ada18a','#d9d1c0'],['#eeeee5','#394d42','#7e9785','#c8d5bc'],['#f2ede6','#3e424e','#8a92a3','#d0c7c0'],
|
||||
['#f5eede','#443d31','#a79b7a','#dbca9f'],['#eeefe8','#34463f','#809b89','#c5d3ba'],['#f0ebe5','#51413d','#a48b7f','#d5bfb3'],
|
||||
['#64797d','#142a2e','#b5c7c7','#3d565b','#7c9497'],['#f0efe9','#2f414d','#8199a7','#c5d2d6'],['#f4eee5','#5a443b','#ae927b','#dfc8ac'],
|
||||
['#ebeee8','#344b41','#829c8b','#c7d5bb'],['#edece8','#3c4354','#8b93aa','#c5cbd7'],['#f2ece2','#3b4e4b','#6f918c','#b8cdc3']
|
||||
];
|
||||
export function layoutPalette(id:string){return palettes[Number(id.slice(4))-1]||['#ffe5df','#303d43','#a9bec0','#f0bca6']}
|
||||
export function paperColor(id:string){return layoutPalette(id)[0]}
|
||||
export function textColor(id:string,slot:Slot){return (id==='ref-04'&&['T01','T02'].includes(slot.id))||(id==='ref-22'&&['T01','T03','T04'].includes(slot.id))||(id==='ref-27'&&slot.id==='T01')||(id==='ref-10'&&slot.id==='T03')?'#f9faf5':layoutPalette(id)[1]}
|
||||
// The screenshot's illegible small print is replaced with editable editorial copy.
|
||||
export function defaultText(layout:Layout,slot:Slot):string {
|
||||
if(slot.text)return slot.text;
|
||||
if(slot.direction==='curved')return 'BULUBLUE DESIGN · FORM AND SPACE · EDITORIAL DESIGN ·';
|
||||
if(slot.role.includes('日期'))return '2025 / 03 / 25';
|
||||
if(slot.role.includes('微字'))return slot.box[2]>60?'FORM / SPACE / DESIGN / 2026':'FORM / '+layout.id.slice(-2);
|
||||
if(slot.role.includes('英文')||slot.role.includes('品牌')||slot.role.includes('标识'))return 'BULUBLUE DESIGN';
|
||||
if(slot.role.includes('图注')||slot.role.includes('标签')||slot.box[3]<10)return slot.box[2]<25?'FORM / '+layout.id.slice(-2):'FORM / SPACE / DESIGN';
|
||||
if(slot.direction==='vertical')return '设计灵感 · 日常观察';
|
||||
return slot.box[2]<25?'留白之间\n观察日常\n记录灵感':'让文字与形状相遇。\n在留白之间,寻找新的秩序。';
|
||||
}
|
||||
export function slotPosition(layout:Layout,slot:Slot):CSSProperties {
|
||||
const [x,y,w,h]=slot.box;return {left:`${x/layout.width*100}%`,top:`${y/layout.height*100}%`,width:`${w/layout.width*100}%`,height:`${h/layout.height*100}%`};
|
||||
}
|
||||
export function textSize(layout:Layout,slot:Slot,text:string):number {
|
||||
const [, ,w,h]=slot.box,lines=text.split('\n');
|
||||
const length=(s:string)=>Array.from(s).reduce((n,c)=>n+(/[\u3400-\u9fff]/.test(c)?1:/[A-Z]/.test(c)?.8:.6),0);
|
||||
if(slot.direction==='vertical')return Math.min(w*.75,h/Math.max(1,Array.from(text.replaceAll('\n','')).length)*.88);
|
||||
if(slot.direction==='rotated')return Math.min(w*.85,h/Math.max(1,length(text)));
|
||||
if(slot.direction==='curved')return Math.min(2.2,Math.max(w,h)*1.1/Math.max(1,length(text)));
|
||||
const fitted=Math.min(h/(lines.length*1.15),w/Math.max(1,...lines.map(length)))*.92;
|
||||
return /微字|脚注|图注|标签/.test(slot.role)?Math.min(fitted,2.2):fitted;
|
||||
}
|
||||
export function imageShape(layout:Layout,slot:Slot):CSSProperties {
|
||||
const n=Number(layout.id.slice(4)),s:CSSProperties={backgroundColor:layoutPalette(layout.id)[slot.id==='I01'?2:3],backgroundImage:'linear-gradient(145deg,#ffffff12,transparent 65%)'};
|
||||
if([4,5,7,13,19,20].includes(n)||(n===17&&slot.id==='I02'))s.borderRadius='50%';
|
||||
if(n===4)s.transform='rotate(-9deg)';
|
||||
if(n===15&&slot.id==='I01')s.borderRadius='100% 0 0 0';
|
||||
if(n===22)s.backgroundColor=layoutPalette(layout.id)[slot.id==='I02'?3:slot.id==='I03'?4:2];
|
||||
if(n===22)s.clipPath=slot.id==='I01'?'polygon(0 0,100% 0,100% 48%,0 100%)':slot.id==='I02'?'polygon(0 30%,100% 0,100% 70%,0 100%)':'polygon(0 50%,100% 0,100% 100%,0 100%)';
|
||||
if(n===27)s.clipPath=slot.id==='I01'?'polygon(0 0,100% 35%,100% 100%,0 68%)':'polygon(0 40%,100% 0,100% 100%,0 100%)';
|
||||
if(n===10)s.backgroundColor=layoutPalette(layout.id)[2];
|
||||
if(n===16)s.backgroundColor=layoutPalette(layout.id)[slot.id==='I01'?3:2];
|
||||
if(n===20&&slot.id==='I02')s.backgroundColor=layoutPalette(layout.id)[3];
|
||||
return s;
|
||||
}
|
||||
export function decorationKind(slot:Slot){
|
||||
if(slot.role.includes('同心'))return 'rings';
|
||||
if(slot.role.includes('圆节点'))return 'node';
|
||||
if(slot.role.includes('椭圆'))return 'oval';
|
||||
if(slot.role.includes('曲线'))return 'curve';
|
||||
if(slot.role.includes('贴条')||slot.role.includes('浅带'))return 'band';
|
||||
if(slot.role.includes('斜'))return 'diagonal';
|
||||
if(slot.box[3]>slot.box[2]*2)return 'vertical-lines';
|
||||
return 'lines';
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import {createElement} from 'react';
|
||||
import {ideas} from '../content/ideas';
|
||||
import {Ref17Cover} from '../components/Ref17Cover';
|
||||
import {SourceCover,selections} from '../components/SourceCover';
|
||||
const record=(v:unknown):v is Record<string,unknown>=>!!v&&typeof v==='object'&&!Array.isArray(v);
|
||||
function color(value:unknown,fallback:string){if(value===undefined)return fallback;if(typeof value!=='string'||!/^#[0-9a-f]{6}$/i.test(value))throw Error('颜色必须为 #RRGGBB');return value;}
|
||||
function text(value:unknown,fallback:string,max:number,lines=1){if(value===undefined)return fallback;if(typeof value!=='string'||!value.trim()||Array.from(value).length>max||value.split('\n').length>lines)throw Error('文字长度或行数超限');return value;}
|
||||
function keys(input:Record<string,unknown>,allowed:string[]){if(Object.keys(input).some(k=>!allowed.includes(k)))throw Error('包含不支持的参数');}
|
||||
export function renderCover(slug:string,input:unknown){
|
||||
if(!record(input))throw Error('需要 JSON 对象');
|
||||
if(slug==='layout-selection'){
|
||||
keys(input,['layoutId','fields','color','accent']);const layout=selections.find(l=>l.id===input.layoutId);if(!layout)throw Error('layoutId 必须为 ref-01、ref-07 或 ref-26');
|
||||
if(input.fields!==undefined&&!record(input.fields))throw Error('fields 必须为对象');const supplied=(input.fields||{}) as Record<string,unknown>,defaults=Object.fromEntries(Object.entries(layout.fields).filter(([,v])=>v!==undefined)) as Record<string,string>;
|
||||
keys(supplied,Object.keys(defaults));const fields=Object.fromEntries(Object.entries(defaults).map(([key,value])=>[key,text(supplied[key],value,120,4)]));
|
||||
const values={fields,color:color(input.color,'#83918a'),accent:color(input.accent,'#c3cec5')};return {node:createElement(SourceCover,{layout,values}),data:{version:3,tool:slug,layoutId:layout.id,template:layout,...values}};
|
||||
}
|
||||
const idea=ideas.find(i=>i.slug===slug);if(!idea?.template)throw Error('这个方案不支持封面渲染');keys(input,['slide','heading','body','color','accent','masthead']);
|
||||
const index=input.slide??0;if(typeof index!=='number'||!Number.isInteger(index)||!idea.slides[index])throw Error('slide 必须是 0–3 的整数');const initial=idea.slides[index];
|
||||
const slide={...initial,heading:text(input.heading,initial.heading,6),body:text(input.body,initial.body,360,3),color:color(input.color,initial.color),accent:color(input.accent,initial.accent!)};
|
||||
const masthead=input.masthead??idea.template.masthead;if(!Array.isArray(masthead)||masthead.length!==2||!masthead.every(v=>typeof v==='string'&&/^[A-Za-z ]{1,8}$/.test(v)&&v.trim()))throw Error('masthead 为两行、每行 1–8 个英文字母或空格');
|
||||
return {node:createElement(Ref17Cover,{template:idea.template,slide,masthead}),data:{version:2,tool:slug,template:{...idea.template,masthead},slide}};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from '../../lib/series.ts';
|
||||
Reference in New Issue
Block a user