Files
vibemake/js/api.js
T
Jerry 1c837766cd feat: integrate robot assembly and simulation with resilient loading
Add backend-driven assembly and simulation experiences, MAKE branding, mobile rendering budgets and desktop-only CAD/PCB routes. Improve logo loading progress, document image recovery and URDF request handling; include dev packaging and regression coverage.
2026-10-30 18:38:39 +08:00

383 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Community 后端接口封装。字段与《Community 前端接口对接文档》一致。
// 所有请求走同域 /api(开发时由 scripts/dev-server.mjs 代理到后端,部署时由 nginx 反代)。
import { store } from './layout.js';
import { compressCoverImage } from './compress-cover.js';
import { normalizeUrdfEntries } from './urdf-paths.js';
// 后端地址按访问的域名选择(静态网站部署,浏览器直接请求后端,后端需要允许这些前端域名跨域):
// dev-vibemake.robotquan.com(及其他 dev-* 域名) → https://dev-vibemake-api.robotquan.com/api
// vibemake.robotquan.com → https://vibemake-api.robotquan.com/api
// localhost / 127.0.0.1 / 局域网 → /api(本地 node scripts/server.mjs 转发到 dev 后端)
export const API_HOSTS = {
'dev-vibemake.robotquan.com': 'https://dev-vibemake-api.robotquan.com/api',
'vibemake.robotquan.com': 'https://vibemake-api.robotquan.com/api',
};
// 打包脚本只替换部署产物中的值;本地源码继续按域名选择环境。
export const BUILD_ENV = 'auto';
function apiBase() {
if (BUILD_ENV === 'dev') return API_HOSTS['dev-vibemake.robotquan.com'];
const host = location.hostname;
if (API_HOSTS[host]) return API_HOSTS[host];
if (/^dev-/.test(host)) return 'https://dev-vibemake-api.robotquan.com/api';
return '/api';
}
export const API_BASE = apiBase();
// 封面图:放在我们 OSS 上的按显示宽度缩放并转 WebP(原图可能好几 MB);外部图片原样使用
export function imageUrl(url, width = 720) {
if (!url) return url;
try {
const u = new URL(url);
// YouTube 的 0.jpg / hqdefault 是 4:3 且上下自带黑边,换成 16:9 无黑边的 mqdefault
if (/(^|\.)(img\.youtube\.com|i\.ytimg\.com)$/.test(u.hostname)) return url.replace(/\/(0|hqdefault|default|sddefault)\.jpg$/, '/mqdefault.jpg');
if (!/\.aliyuncs\.com$/.test(u.hostname) || u.search) return url;
return `${url}?x-oss-process=image/resize,w_${width},m_lfit/format,webp/quality,q_80`;
} catch { return url; }
}
export class ApiError extends Error {
constructor(status, code, message, requestId = null, data = null) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
this.requestId = requestId;
this.data = data;
}
}
// ---------- 登录状态 ----------
const AUTH_KEY = 'vm.auth';
const listeners = new Set();
export const auth = {
get() {
const a = store.get(AUTH_KEY, null);
if (!a?.token) return null;
if (a.expiresAt && Date.now() > a.expiresAt) { store.set(AUTH_KEY, null); return null; }
return a;
},
get token() { return this.get()?.token || null; },
get user() { return this.get()?.user || null; },
set(login) {
store.set(AUTH_KEY, login ? { token: login.token, user: login.user, expiresAt: Date.now() + (login.expiresIn || 86400) * 1000 } : null);
listeners.forEach((fn) => fn(this.user));
},
setUser(user) {
const a = this.get();
if (a) { store.set(AUTH_KEY, { ...a, user }); listeners.forEach((fn) => fn(user)); }
},
clear() { this.set(null); },
onChange(fn) { listeners.add(fn); return () => listeners.delete(fn); },
};
// ---------- 请求封装(不自动重试写请求) ----------
// auth: 'required' 必须登录;'optional' 有 Token 就带,Token 失效时去掉后重读一次;'none' 不带
export async function request(path, { method = 'GET', body, query, auth: mode = 'none', signal } = {}) {
const url = API_BASE + path + (query ? `?${toQuery(query)}` : '');
const token = mode === 'none' ? null : auth.token;
if (mode === 'required' && !token) throw new ApiError(401, 'UNAUTHORIZED', '请先登录');
const headers = new Headers({ Accept: 'application/json' });
if (token) headers.set('Authorization', `Bearer ${token}`);
let payload;
if (body instanceof FormData) payload = body; // 浏览器自动设置 multipart boundary
else if (body !== undefined) { headers.set('Content-Type', 'application/json'); payload = JSON.stringify(body); }
const res = await fetch(url, { method, headers, body: payload, signal });
let result;
try {
result = await res.json();
} catch {
throw new ApiError(res.status, 'BAD_RESPONSE', res.status === 404 ? '接口不存在(检查 /api 代理)'
: res.status >= 502 && res.status <= 504 ? `后端服务暂时不可用(HTTP ${res.status}),请稍后再试`
: `接口未返回有效 JSON(HTTP ${res.status})`, res.headers.get('X-Request-Id'));
}
if (res.ok && result.code === 'OK') return result.data;
const err = new ApiError(res.status, result.code, result.message, result.requestId ?? res.headers.get('X-Request-Id'), result.data);
if (res.status === 401 && token) {
auth.clear();
// 公开接口带了失效 Token 也会 401:去掉 Token 再读一次(只对 GET)
if (mode === 'optional' && method === 'GET') return request(path, { method, query, auth: 'none', signal });
}
throw err;
}
function toQuery(q) {
const s = new URLSearchParams();
for (const [k, v] of Object.entries(q)) if (v !== undefined && v !== null && v !== '') s.set(k, String(v));
return s.toString();
}
const enc = encodeURIComponent;
// 项目、评论的时间没有时区后缀,按 UTC 解释;authorDate 自带时区时按原值
export function parseUtcTime(value) {
if (!value) return null;
return new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`);
}
export const utcIso = (v) => (v ? parseUtcTime(v).toISOString() : null);
// 文本按 UTF-8 字节计算大小
export const byteLength = (text) => new TextEncoder().encode(text).length;
export const LIMITS = {
textBytes: 1048576, // 在线编辑单个文本 1 MiB
fileBytes: 10485760, // 单文件 10 MiB
batchBytes: 52428800, // 单次上传 / 提交总量 50 MiB
batchCount: 500, // 单批文件数
coverBytes: 5242880, // 封面 5 MiB
coverTypes: ['image/jpeg', 'image/png', 'image/webp'],
};
// ---------- 登录和用户 ----------
export const getCaptcha = () => request('/auth/captcha');
export const login = (email, captchaCode, captchaAnswer) =>
request('/auth/login', { method: 'POST', body: { email: email.trim(), captchaCode, captchaAnswer } });
export const logout = () => request('/auth/logout', { method: 'POST', auth: 'required' });
export const getMe = () => request('/users/me', { auth: 'required' });
// ---------- 类型 ----------
let typesCache;
export function getProjectTypes() {
typesCache ??= request('/project-types').catch((e) => { typesCache = null; throw e; });
return typesCache;
}
// ---------- 社区(可匿名) ----------
export const listCommunityProjects = ({ page = 1, size = 20, type, keyword } = {}, signal) =>
request('/community/projects', { query: { page, size, type, keyword: keyword?.trim() }, auth: 'optional', signal });
export const getCommunityProject = (code) => request(`/community/projects/${enc(code)}`, { auth: 'optional' });
// 社区目录和文件固定读发布版本,不能传 commitSha
export const getCommunityTree = (code, path = '') => request(`/community/projects/${enc(code)}/tree`, { query: { path }, auth: 'optional' });
export const getCommunityFile = (code, path) => request(`/community/projects/${enc(code)}/files`, { query: { path }, auth: 'optional' });
// 匿名可访问,可以直接作为 <a href> 或加载器 URL
export const communityRawUrl = (code, path) => `${API_BASE}/community/projects/${enc(code)}/files?${toQuery({ path, download: 'true' })}`;
export const forkProject = (code, name, publishedCommitSha) =>
request(`/community/projects/${enc(code)}/forks`, { method: 'POST', body: { name, publishedCommitSha }, auth: 'required' });
export const listComments = (code, { page = 1, size = 20 } = {}) =>
request(`/community/projects/${enc(code)}/comments`, { query: { page, size }, auth: 'optional' });
export const postComment = (code, content) =>
request(`/community/projects/${enc(code)}/comments`, { method: 'POST', body: { content }, auth: 'required' });
export const deleteComment = (commentCode) => request(`/comments/${enc(commentCode)}`, { method: 'DELETE', auth: 'required' });
export const likeProject = (code) => request(`/community/projects/${enc(code)}/like`, { method: 'PUT', auth: 'required' });
export const unlikeProject = (code) => request(`/community/projects/${enc(code)}/like`, { method: 'DELETE', auth: 'required' });
// ---------- 我的工作区 ----------
export const listMyProjects = ({ page = 1, size = 20, type, keyword } = {}) =>
request('/workspace/projects', { query: { page, size, type, keyword: keyword?.trim() }, auth: 'required' });
export const createProject = ({ name, description = '', projectType, coverUrl }) =>
request('/workspace/projects', { method: 'POST', body: { name: name.trim(), description, projectType, coverUrl: coverUrl || undefined }, auth: 'required' });
export const getMyProject = (code) => request(`/workspace/projects/${enc(code)}`, { auth: 'required' });
// PATCH 实际要求完整的 name / description / projectType;coverUrl 不传表示保留
export const updateProject = (code, { name, description, projectType, coverUrl }) =>
request(`/workspace/projects/${enc(code)}`, { method: 'PATCH', body: { name, description, projectType, coverUrl }, auth: 'required' });
export const deleteProject = (code) => request(`/workspace/projects/${enc(code)}`, { method: 'DELETE', auth: 'required' });
export const getWorkspaceTree = (code, path = '', commitSha) =>
request(`/workspace/projects/${enc(code)}/tree`, { query: { path, commitSha }, auth: 'required' });
export const getWorkspaceFile = (code, path, commitSha) =>
request(`/workspace/projects/${enc(code)}/files`, { query: { path, commitSha }, auth: 'required' });
// 工作区下载要带 Token,只能 fetch 成 Blob
export async function downloadWorkspaceFile(code, path, commitSha) {
const res = await fetch(`${API_BASE}/workspace/projects/${enc(code)}/files?${toQuery({ path, commitSha, download: 'true' })}`, {
headers: { Authorization: `Bearer ${auth.token}` },
});
if (!res.ok) {
const r = await res.json().catch(() => ({}));
throw new ApiError(res.status, r.code || 'BAD_RESPONSE', r.message || `下载失败:${res.status}`, r.requestId ?? res.headers.get('X-Request-Id'), r.data);
}
return res.blob();
}
// changes: [{ action: 'CREATE_FILE'|'UPDATE_FILE'|'DELETE_FILE'|'CREATE_DIRECTORY', path, content? }]
export const commitChanges = (code, expectedCommitSha, message, changes) =>
request(`/workspace/projects/${enc(code)}/commits`, { method: 'POST', body: { expectedCommitSha, message, changes }, auth: 'required' });
export const listCommits = (code, { page = 1, size = 20 } = {}) =>
request(`/workspace/projects/${enc(code)}/commits`, { query: { page, size }, auth: 'required' });
// files: [{ file: File, path: '相对 directory 的路径' }]
export function uploadCommit(code, { expectedCommitSha, message, directory = '', files }) {
const form = new FormData();
form.append('expectedCommitSha', expectedCommitSha);
form.append('message', message);
form.append('directory', directory);
for (const f of files) {
form.append('files', f.file, f.file.name);
form.append('paths', f.path || f.file.name);
}
return request(`/workspace/projects/${enc(code)}/uploads/commit`, { method: 'POST', body: form, auth: 'required' });
}
export const publishProject = (code, commitSha) =>
request(`/workspace/projects/${enc(code)}/publication`, { method: 'PUT', body: { commitSha }, auth: 'required' });
export const unpublishProject = (code) => request(`/workspace/projects/${enc(code)}/publication`, { method: 'DELETE', auth: 'required' });
// ---------- 封面直传 OSS ----------
export async function uploadCover(file, signal) {
if (!LIMITS.coverTypes.includes(file.type)) throw new ApiError(400, 'BAD_REQUEST', '封面只支持 JPG / PNG / WebP');
if (file.size <= 0) throw new ApiError(400, 'BAD_REQUEST', '封面文件为空');
if (file.size > LIMITS.coverBytes) throw new ApiError(413, 'UPLOAD_TOO_LARGE', '封面不能超过 5 MB');
const uploadFile = await compressCoverImage(file);
const sig = await request('/uploads/project-covers/signature', {
method: 'POST', body: { contentType: uploadFile.type, fileSize: uploadFile.size }, auth: 'required', signal,
});
const form = new FormData();
for (const [k, v] of Object.entries(sig.formFields)) form.append(k, v);
form.append('file', uploadFile); // 必须是最后一个字段
const res = await fetch(sig.uploadUrl, { method: 'POST', body: form, credentials: 'omit', signal });
if (res.status !== 200) throw new ApiError(res.status, 'OSS_UPLOAD_FAILED', `封面上传失败:HTTP ${res.status}`);
return sig.coverUrl;
}
// ---------- 项目 URDF 文件夹(直传 OSS,不进仓库、不生成提交) ----------
// entries: [{ file, relativePath }],relativePath 以资源包根目录为基准(去掉所选文件夹本身的名字)
export const URDF_LIMITS = { fileBytes: 52428800, totalBytes: 209715200, files: 500 };
// 浏览器选的文件夹 → 资源包清单:去掉最外层文件夹名,跳过系统垃圾文件
export function urdfEntries(list) {
const items = list.map((x) => (x instanceof File ? { file: x, path: x.webkitRelativePath || x.name } : x))
.filter((x) => !/(^|\/)(\.DS_Store|Thumbs\.db|__MACOSX|\.git)(\/|$)/.test(x.path));
const tops = new Set(items.map((x) => (x.path.includes('/') ? x.path.split('/')[0] : '')));
const strip = tops.size === 1 && !tops.has('');
return items.map((x) => ({ file: x.file, relativePath: strip ? x.path.slice(x.path.indexOf('/') + 1) : x.path }));
}
// 上传前检查:恰好一个 .urdf、数量和大小不超限、路径合法。返回错误文字,没问题返回空串
export function checkUrdfEntries(entries) {
const mains = entries.filter((e) => /\.urdf$/i.test(e.relativePath));
if (!mains.length) return '文件夹中未找到 URDF 文件(.urdf 或 .xacro)';
if (mains.length > 1) return `文件夹中存在多个 URDF 文件(${mains.map((m) => m.relativePath).join('、')}),请仅保留一个后重新上传`;
if (entries.length > URDF_LIMITS.files) return `文件太多:${entries.length} 个,最多 ${URDF_LIMITS.files} 个`;
const big = entries.find((e) => e.file.size > URDF_LIMITS.fileBytes);
if (big) return `${big.relativePath} 超过 50 MB`;
const total = entries.reduce((n, e) => n + e.file.size, 0);
if (total > URDF_LIMITS.totalBytes) return `总大小 ${(total / 1048576).toFixed(0)} MB,最多 200 MB`;
const bad = entries.find((e) => /\\|:|[\x00-\x1f]/.test(e.relativePath) || e.relativePath.split('/').some((seg) => !seg || seg === '.' || seg === '..' || seg === '.git'));
if (bad) return `路径不合法:${bad.relativePath}`;
return '';
}
export async function uploadUrdf(code, entries, onProgress, signal) {
entries = await normalizeUrdfEntries(entries);
const problem = checkUrdfEntries(entries);
if (problem) throw new ApiError(400, 'URDF_MAIN_FILE_INVALID', problem);
const files = entries.map((e) => ({ relativePath: e.relativePath, sizeBytes: e.file.size }));
const base = `/workspace/projects/${enc(code)}/urdf`;
const sig = await request(`${base}/signature`, { method: 'POST', body: { files }, auth: 'required', signal });
const byPath = new Map(entries.map((e) => [e.relativePath, e.file]));
const total = entries.reduce((n, e) => n + e.file.size, 0) || 1;
let sent = 0;
const queue = [...sig.files];
// 同时传 4 个文件
const worker = async () => {
for (let item = queue.shift(); item; item = queue.shift()) {
const form = new FormData();
for (const [k, v] of Object.entries(item.formFields)) form.append(k, v);
const file = byPath.get(item.relativePath);
form.append('file', file); // 必须是最后一个字段
const res = await fetch(sig.uploadUrl, { method: 'POST', body: form, credentials: 'omit', signal });
if (res.status !== 200) throw new ApiError(res.status, 'OSS_UPLOAD_FAILED', `${item.relativePath} 上传失败:HTTP ${res.status}`);
sent += file.size;
onProgress?.(sent / total, item.relativePath);
}
};
await Promise.all(Array.from({ length: Math.min(4, queue.length) }, worker));
return request(base, { method: 'PUT', body: { batchCode: sig.batchCode, files }, auth: 'required', signal });
}
export const clearUrdf = (code) => request(`/workspace/projects/${enc(code)}/urdf`, { method: 'DELETE', auth: 'required' });
// ---------- AI 对话搜索(SSE) ----------
export async function chatAi(input, onProgress, signal) {
const res = await fetch(`${API_BASE}/community/ai/chat`, {
method: 'POST',
headers: { Authorization: `Bearer ${auth.token}`, 'Content-Type': 'application/json', Accept: 'text/event-stream' },
body: JSON.stringify(input),
signal,
});
const requestId = res.headers.get('X-Request-Id');
if (!res.ok) {
const f = await res.json().catch(() => ({}));
if (res.status === 401) auth.clear();
throw new ApiError(res.status, f.code || 'BAD_RESPONSE', f.message || `HTTP ${res.status}`, f.requestId ?? requestId);
}
if (!res.body || !res.headers.get('Content-Type')?.includes('text/event-stream')) {
throw new ApiError(res.status, 'BAD_RESPONSE', '接口未返回事件流', requestId);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let eventName = '';
let dataLines = [];
let result;
const dispatch = () => {
if (!dataLines.length) { eventName = ''; return; }
const ev = JSON.parse(dataLines.join('\n'));
dataLines = [];
// error 事件可能带 { projectCode }:创建 / Fork 初始化异常时用来核对工作区
if (eventName === 'error' || ev.code !== 'OK') throw new ApiError(res.status, ev.code, ev.message, ev.requestId ?? requestId, ev.data);
if (eventName === 'progress') onProgress?.(ev.data);
if (eventName === 'result') result = ev.data;
eventName = '';
};
try {
while (true) {
const { value, done } = await reader.read();
buffer += decoder.decode(value, { stream: !done });
let end;
while ((end = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, end).replace(/\r$/, '');
buffer = buffer.slice(end + 1);
if (!line) dispatch();
else if (line.startsWith('event:')) eventName = line.slice(6).trim();
else if (line.startsWith('data:')) dataLines.push(line.slice(5).trimStart());
}
if (result) return result;
if (done) break;
}
throw new ApiError(res.status, 'AI_STREAM_INCOMPLETE', '连接提前结束,未收到处理结果;如涉及创建或 Fork,请先核对工作区', requestId);
} finally {
await reader.cancel().catch(() => {});
reader.releaseLock();
}
}
// ---------- 错误提示 ----------
const FRIENDLY = {
UNAUTHORIZED: '登录已失效,请重新登录',
CAPTCHA_INVALID: '验证码错误或已过期',
ACCOUNT_DISABLED: '账号不可用',
FORBIDDEN: '没有权限',
NOT_FOUND: '内容不存在或已撤回',
CONFLICT: '版本已变化,请刷新后重试',
FILE_TOO_LARGE: '文件超出大小限制',
UPLOAD_TOO_LARGE: '上传内容超出大小限制',
AI_BUSY: 'Maker AI 繁忙,请稍后再试',
AI_RATE_LIMITED: '发送太频繁,请稍后再试',
AI_DISABLED: 'Maker AI 暂未开启',
AI_TIMEOUT: 'AI 处理超时',
AI_INVALID_RESPONSE: 'AI 返回的结果没有通过校验,本次未执行',
URDF_MAIN_FILE_INVALID: '文件夹中需要恰好有一个 URDF 文件',
URDF_FILE_MISSING: 'URDF 文件未上传完整,请重新上传',
URDF_FILE_SIZE_MISMATCH: 'URDF 文件大小不符,请重新上传',
URDF_UPLOAD_TOO_LARGE: 'URDF 文件数量或大小超过限制',
OSS_ERROR: '文件存储访问失败,请稍后再试',
OSS_UNAVAILABLE: '文件存储暂未开启',
FORK_UNAVAILABLE: 'Fork 服务暂不可用,请联系管理员',
FORK_BUSY: 'Fork 的人有点多,请稍后再试',
FORK_RESOURCE_LIMIT: '项目太大,超出 Fork 限制',
FORK_COPY_FAILED: 'Fork 复制失败',
FORK_TIMEOUT: 'Fork 超时,请先到「我的」里看看是否已经成功',
};
export function errorText(err) {
if (err?.name === 'AbortError') return '已取消';
if (!(err instanceof ApiError)) return '网络异常,请检查连接';
const msg = err.message || FRIENDLY[err.code] || err.code;
return err.requestId && err.status >= 500 ? `${msg}(${err.requestId.slice(0, 8)})` : msg;
}