Files
2026-11-12 11:05:55 +08:00

149 lines
6.8 KiB
JavaScript

const dirname = (path) => path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
function normalize(path, clamp = false) {
const out = [];
for (const seg of path.split('/')) {
if (!seg || seg === '.') continue;
if (seg === '..') {
if (!out.length) { if (clamp) continue; return null; }
out.pop();
} else out.push(seg);
}
return out.join('/');
}
function relative(fromDir, to) {
const a = fromDir ? fromDir.split('/') : [];
const b = to.split('/');
while (a.length && b.length > 1 && a[0] === b[0]) { a.shift(); b.shift(); }
return [...a.map(() => '..'), ...b].join('/') || '.';
}
function localPath(filename, mainPath) {
const value = String(filename).trim().replace(/\\/g, '/');
const pkg = value.match(/^package:\/\/[^/]*\/(.*)$/i);
if (pkg) return normalize(pkg[1], true);
if (/^https?:\/\//i.test(value) || /^(data|blob):/i.test(value)) return null;
if (/^file:\/\//i.test(value)) return normalize(value.replace(/^file:\/+/i, ''), true);
if (/^[a-z]:\//i.test(value)) return normalize(value.slice(3), true);
return normalize(value.startsWith('/') ? value.slice(1) : `${dirname(mainPath)}/${value}`, true);
}
export function meshUrlCandidates(base, url) {
const value = String(url);
const root = String(base).replace(/\/+$/, '');
const prefix = `${root}/`;
if (!value.startsWith(prefix)) return [value];
const rawPath = value.slice(prefix.length);
const suffix = rawPath.match(/[?#].*$/)?.[0] || '';
// Keep legacy references inside their upload batch, including ../ paths and
// Windows exporter paths, before trying shorter uploaded directory prefixes.
const path = normalize(rawPath.split(/[?#]/, 1)[0].replace(/\\/g, '/'), true);
if (!path) return [value];
const canonical = `${root}/${path}${suffix}`;
const parts = path.split('/');
const resourceIndex = parts.findIndex((part, index) => index > 1 && (part === 'meshes' || part === 'qb_meshes'));
const rootResource = parts[0] === 'robots' && resourceIndex > 1
? `${root}/${parts.slice(resourceIndex).join('/')}${suffix}`
: null;
// Older uploads can retain source directories that are absent from the OSS batch.
const fallbacks = parts.slice(1, 9).map((_, i) => `${root}/${parts.slice(i + 1).join('/')}${suffix}`);
return [...new Set([rootResource, canonical, ...fallbacks].filter(Boolean))];
}
// URDFLoader keeps the package URI intact until this step so different ROS
// packages can resolve to different directories within the same upload batch.
export function urdfResourceUrlCandidates(base, url, mainUrl) {
const root = String(base).replace(/\/+$/, '');
const value = String(url);
const pkg = value.match(/^package:\/\/([^/]*)(?:\/(.*))?$/i);
let candidates;
if (pkg) {
const [, name, path = ''] = pkg;
const roots = [root];
const main = String(mainUrl || '').split(/[?#]/, 1)[0];
const dirs = main.startsWith(`${root}/`) ? main.slice(root.length + 1).split('/').slice(0, -1) : [];
const index = dirs.lastIndexOf(name);
if (name && index >= 0) roots.unshift(`${root}/${dirs.slice(0, index + 1).join('/')}`);
if (name && name !== '.' && name !== '..') roots.push(`${root}/${name}`);
const paths = [...new Set(roots)].map((dir) => `${dir}/${path}`);
const first = meshUrlCandidates(root, paths[0]);
candidates = [first[0], ...paths.slice(1), ...first.slice(1), ...paths.slice(1).flatMap((p) => meshUrlCandidates(root, p))];
} else {
const file = value.match(/(?:^|\/)file:\/+(.*)$/i);
candidates = meshUrlCandidates(root, file ? `${root}/${file[1]}` : value);
}
candidates = [...new Set(candidates)];
// Some older exports use .STL while the uploaded object ends in .stl.
const lowerExtensions = candidates.map((p) => p.replace(/\.[A-Z\d]+(?=[?#]|$)/, (ext) => ext.toLowerCase()));
return [...new Set([...candidates, ...lowerExtensions])];
}
// Resolve references against the uploaded file manifest. A unique suffix match
// handles URDFs that retain their source workspace prefix after upload.
export function resolveUrdfResourcePath(filename, mainPath, availablePaths) {
const target = localPath(filename, mainPath);
if (!target) return null;
const available = [...new Set(availablePaths.map((path) => normalize(path)).filter(Boolean))];
const pkg = String(filename).trim().replace(/\\/g, '/').match(/^package:\/\/([^/]+)\/(.*)$/i);
const qualified = pkg && pkg[1] !== '..' ? normalize(`${pkg[1]}/${pkg[2]}`) : null;
const packageMatches = qualified ? available.filter((path) => path === qualified || path.endsWith(`/${qualified}`)) : [];
let match = packageMatches.length === 1 ? packageMatches[0] : available.includes(target) ? target : null;
if (!match) {
const targetParts = target.split('/');
let bestScore = 1;
let best = [];
for (const path of available) {
const parts = path.split('/');
let score = 0;
while (score < targetParts.length && score < parts.length
&& targetParts[targetParts.length - score - 1] === parts[parts.length - score - 1]) score++;
if (score > bestScore) { bestScore = score; best = [path]; }
else if (score === bestScore && score > 1) best.push(path);
}
if (bestScore > 1 && best.length === 1) match = best[0];
else if (bestScore <= 1) {
const basename = targetParts.at(-1);
const sameName = available.filter((path) => path.split('/').at(-1) === basename);
if (sameName.length === 1) match = sameName[0];
}
}
if (!match) {
const lowerTarget = target.toLowerCase();
const caseMatches = available.filter((path) => path.toLowerCase() === lowerTarget
|| path.toLowerCase().endsWith(`/${lowerTarget}`));
if (caseMatches.length === 1) match = caseMatches[0];
}
return match ? relative(dirname(mainPath), match) : null;
}
export async function normalizeUrdfEntries(entries) {
const main = entries.find((entry) => /\.urdf$/i.test(entry.relativePath));
if (!main || typeof DOMParser === 'undefined' || typeof XMLSerializer === 'undefined' || typeof File === 'undefined') return entries;
const source = await main.file.text();
const doc = new DOMParser().parseFromString(source, 'application/xml');
if (doc.getElementsByTagName('parsererror').length) return entries;
const paths = entries.map((entry) => entry.relativePath);
let changed = false;
doc.querySelectorAll('mesh[filename], texture[filename]').forEach((node) => {
const filename = node.getAttribute('filename');
const resolved = resolveUrdfResourcePath(filename, main.relativePath, paths);
if (resolved && resolved !== filename) {
node.setAttribute('filename', resolved);
changed = true;
}
});
if (!changed) return entries;
const file = new File([new XMLSerializer().serializeToString(doc)], main.file.name, {
type: main.file.type || 'application/xml',
lastModified: main.file.lastModified,
});
return entries.map((entry) => entry === main ? { ...entry, file } : entry);
}