Files
vibemake/js/project-resources.js

183 lines
10 KiB
JavaScript

// API resource bindings are authoritative. URLs come from each returned file entry,
// never from the assembly JSON's directory (the uploads use separate OSS batches).
import { assetPath, fetchPackageJson, loadPackage, validatePackage } from './experience-packages.js';
export function publicResourceUrl(value, base = globalThis.location?.href) {
if (typeof value !== 'string' || !value.trim()) return null;
try {
const url = new URL(value, base);
return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password ? url.href : null;
} catch { return null; }
}
function assemblyFileUrl(value, path) {
if (typeof value !== 'string' || !path.includes('#')) return publicResourceUrl(value);
// Recover literal # only if the resulting pathname matches the uploaded key.
const [base] = value.split('?');
const repaired = publicResourceUrl(base.replaceAll('#', '%23') + value.slice(base.length));
try {
if (repaired && decodeURIComponent(new URL(repaired).pathname).endsWith('/' + path)) return repaired;
} catch { /* Leave already-valid API URLs intact. */ }
return publicResourceUrl(value);
}
export function resourceIndex(entries, { assembly = false } = {}) {
if (!Array.isArray(entries) || !entries.length) throw new Error('资源文件清单为空');
if (!assembly && entries.length > 1000) throw new Error('行走资源文件清单超过 1000 个');
const files = new Map();
for (const entry of entries) {
const path = assetPath(entry.relativePath, { assembly });
const url = assembly ? assemblyFileUrl(entry.url, path) : publicResourceUrl(entry.url);
if (files.has(path) || !url || !Number.isSafeInteger(entry.sizeBytes) || entry.sizeBytes <= 0) throw new Error(`资源清单无效:${path}`);
files.set(path, { path, url, bytes: entry.sizeBytes });
}
return files;
}
export const assemblySource = (project) => publicResourceUrl(project?.assemblyJsonUrl || project?.assemblyManifestUrl);
export const hasProjectWalking = (project) => !!publicResourceUrl(project?.walkingManifestUrl)
|| (!!publicResourceUrl(project?.walkingResourcesBaseUrl) && Array.isArray(project?.walkingResourcesFiles) && project.walkingResourcesFiles.length > 0);
// Folder uploads may keep or remove the selected directory (parts/a.glb → a.glb).
// Resolve one consistent root change for the WHOLE manifest, never arbitrary
// basename matches. Preserve subdirectories, reject ambiguity and retain hashes.
export function bindAssemblyFiles(expected, uploaded) {
const paths = [...expected.keys()];
let bindings;
if (paths.every((path) => uploaded.has(path))) {
bindings = new Map(paths.map((path) => [path, uploaded.get(path)]));
} else {
const first = paths[0];
const roots = [''];
for (let i = first.indexOf('/'); i !== -1; i = first.indexOf('/', i + 1)) {
const root = first.slice(0, i + 1);
if (paths.every((path) => path.startsWith(root))) roots.push(root);
}
const candidates = new Map();
for (const root of roots) {
const relative = first.slice(root.length);
for (const actual of uploaded.keys()) {
if (actual !== relative && !actual.endsWith('/' + relative)) continue;
const targetRoot = actual.slice(0, -relative.length);
const targets = paths.map((path) => targetRoot + path.slice(root.length));
if (!targets.every((path) => uploaded.has(path))) continue;
candidates.set(JSON.stringify(targets), new Map(paths.map((path, i) => [path, uploaded.get(targets[i])])));
}
}
if (candidates.size > 1) throw new Error('零件目录匹配到多套文件,请保留一套与装配步骤对应的零件目录');
if (!candidates.size) {
const missing = paths.find((path) => !uploaded.has(path));
throw new Error(`装配步骤与零件目录不匹配:${missing},请检查文件是否齐全且子目录结构一致`);
}
bindings = candidates.values().next().value;
}
for (const [path, actual] of bindings) {
if (actual.bytes !== expected.get(path).bytes) throw new Error(`零件版本与步骤不一致:${path}`);
}
return bindings;
}
export async function loadProjectAssembly(project, signal) {
const url = assemblySource(project);
if (!url) throw new Error('此项目尚未配置拼装步骤');
const pkg = await loadPackage(url, 'assembly', signal);
if (project.assemblyJsonUrl) {
const bound = bindAssemblyFiles(pkg.files, resourceIndex(project.modelPartsFiles, { assembly: true }));
for (const [path, file] of pkg.files) {
const actual = bound.get(path);
file.url = actual.url;
}
}
return pkg;
}
export function resolveRobotResource(path, entryPath, files) {
assetPath(path);
const resolved = entryPath.includes('/') ? entryPath.slice(0, entryPath.lastIndexOf('/') + 1) + path : path;
const file = files.get(resolved);
if (!file) throw new Error(`运动资源缺少文件:${resolved}`);
return file;
}
export function validateRobotResources(config, entryPath, files) {
if (config?.schema === 1 && config.adapter === 'microduck') {
// The bundled duck adapter has its own observation/skill contract. It is
// never sent to the generic three-command controller.
if (!Array.isArray(config.skills) || !config.skills.some((s) => s.id === 'walk' && s.available !== false && s.controller?.type === 'onnx')) throw new Error('小鸭子配置缺少基础行走策略');
resolveRobotResource(config.model, entryPath, files);
for (const skill of config.skills.filter((s) => s.available !== false && s.controller?.type === 'onnx')) resolveRobotResource(skill.controller.policy, entryPath, files);
for (const path of ['robot/mjlab/microduck.glb', 'robot/mjlab/kinematics.json']) resolveRobotResource(path, entryPath, files);
return { format: 'microduck-package', config, entryPath, resources: [...files.values()] };
}
if (config?.schema !== 1 || config.adapter !== 'generic') throw new Error('当前文件夹需要尚未接入的运动运行器;请提供受支持的 Robot Package');
if (!Array.isArray(config.assets) || !Array.isArray(config.skills)) throw new Error('机器人配置缺少资源或动作声明');
const primary = config.skills.filter((s) => s.kind === 'primary');
if (primary.length !== 1 || primary[0].available === false || primary[0].controller?.type !== 'onnx') throw new Error('基础行走需要一个配套的 ONNX 控制器');
const required = new Set([resolveRobotResource(config.model, entryPath, files).path, entryPath]);
for (const asset of config.assets) {
assetPath(asset.vfs);
required.add(resolveRobotResource(asset.path, entryPath, files).path);
}
const ids = new Set(), supported = [], warnings = [];
for (const skill of config.skills) {
if (!skill.id || ids.has(skill.id)) throw new Error('运动技能编号重复或缺失');
ids.add(skill.id);
if (skill.kind === 'primary') {
required.add(resolveRobotResource(skill.controller.policy, entryPath, files).path);
supported.push(skill);
continue;
}
if (skill.available === false) continue;
try {
if (skill.kind === 'episodic' && skill.controller?.type === 'onnx') {
required.add(resolveRobotResource(skill.controller.policy, entryPath, files).path);
if (skill.reference) required.add(resolveRobotResource(skill.reference, entryPath, files).path);
} else if (skill.kind !== 'overlay' || skill.controller?.type !== 'oscillator') {
throw new Error('当前运行器暂不支持此控制器');
}
supported.push(skill);
} catch (error) { warnings.push({ skillId: skill.id, message: error.message }); }
}
for (const visual of config.render?.body_visuals ?? []) required.add(resolveRobotResource(visual.path, entryPath, files).path);
const enabled = new Set(supported.map((s) => s.id));
const normalized = { ...config, skills: supported, input: { ...config.input, bindings: (config.input?.bindings ?? []).filter((b) => {
const match = /^(?:skill|toggle):(.+)$/.exec(b.action);
return !match || enabled.has(match[1]);
}) } };
return {
format: 'robot-package', config: normalized, entryPath, warnings,
// Keep the explicit inventory for nested motion-reference data. Merely
// listing a file does not download it; runtime fetches are demand-driven.
resources: [...files.values()],
capabilities: supported.map((s) => ({ id: s.kind === 'primary' ? 'walk' : s.kind, skillId: s.id })),
};
}
export async function loadProjectWalking(project, signal) {
if (publicResourceUrl(project.walkingManifestUrl)) {
return { format: 'legacy', manifestUrl: publicResourceUrl(project.walkingManifestUrl), pkg: await loadPackage(project.walkingManifestUrl, 'walking', signal) };
}
const files = resourceIndex(project.walkingResourcesFiles);
const entries = [...files.keys()].filter((p) => /(^|\/)robot\.json$/.test(p));
if (entries.length !== 1) {
const manifests = [...files.values()].filter((f) => /(^|\/)manifest\.json$/.test(f.path));
if (!entries.length && manifests.length === 1) {
const raw = await fetchPackageJson(manifests[0].url, signal);
// Explicit legacy format is still served by the existing trusted runtime.
if (raw.kind === 'walking' && raw.schemaVersion === 1) {
const pkg = validatePackage(raw, 'walking', manifests[0].url);
for (const file of pkg.files.values()) {
const actual = resolveRobotResource(file.path, manifests[0].path, files);
if (file.bytes !== actual.bytes) throw new Error(`运动文件版本与清单不一致:${file.path}`);
file.url = actual.url;
}
return { format: 'legacy', manifestUrl: manifests[0].url, pkg, resources: [...pkg.files.values()] };
}
}
throw new Error(entries.length ? '运动目录存在多个 robot.json,请保留一个机器人入口' : '运动目录未找到受支持的 robot.json,上传文件夹本身不会自动生成行走配置');
}
const entryPath = entries[0];
const config = await fetchPackageJson(files.get(entryPath).url, signal);
return validateRobotResources(config, entryPath, files);
}