feat(tabletop): inject proxy handlers from web app
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* HTTP helpers for loading part assets. The only coupling to the host app's
|
||||
* HTTP surface: the asset proxy (`/asset`) and the trace endpoint (`/trace`).
|
||||
* Kept as plain functions so they're testable without react-three.
|
||||
*/
|
||||
import { deserialize } from 'bson';
|
||||
|
||||
/**
|
||||
* Resolve a part's asset URL. Absolute URLs (http/https, data:, blob:) pass
|
||||
* through unchanged; relative paths are resolved against `baseUrl` — the
|
||||
* directory of the part's source file (the json/yaml/markdown that defined
|
||||
* it). Without a `baseUrl`, a relative path is returned as-is.
|
||||
*/
|
||||
export function resolveAssetUrl(url: string, baseUrl?: string): string {
|
||||
if (/^(https?:|data:|blob:)/i.test(url)) return url;
|
||||
if (!baseUrl) return url;
|
||||
// `baseUrl` is a path relative to the games root (no scheme), so join rather
|
||||
// than resolve as a URL. A fake origin lets `new URL` normalize `./` and
|
||||
// `../`; the origin is stripped from the result.
|
||||
const resolved = new URL(url, `http://localhost/${baseUrl}`).pathname;
|
||||
return resolved.replace(/^\/+/, '');
|
||||
}
|
||||
|
||||
/** Route an external asset URL through the proxy so three.js can load it. */
|
||||
export function assetUrl(url: string): string {
|
||||
return `/asset?url=${encodeURIComponent(url)}`;
|
||||
}
|
||||
|
||||
export interface TraceResult {
|
||||
width: number;
|
||||
height: number;
|
||||
shape?: { outline: number[][]; holes?: number[][][] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Trace an image into a vector shape, BSON-deserializing the proxy response.
|
||||
* `mode` controls how the region is derived (`alpha`, `bw`, `color`); a
|
||||
* non-zero `offset` insets (negative) or outsets (positive) the shape.
|
||||
*/
|
||||
export async function traceImage(
|
||||
url: string,
|
||||
mode: 'alpha' | 'bw' | 'color' = 'alpha',
|
||||
offset?: number,
|
||||
): Promise<TraceResult> {
|
||||
const params = new URLSearchParams({ url, mode });
|
||||
if (offset !== undefined) params.set('offset', String(offset));
|
||||
const res = await fetch(`/trace?${params.toString()}`);
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => null)) as { error?: string } | null;
|
||||
throw new Error(body?.error ?? `Trace failed (${res.status})`);
|
||||
}
|
||||
return deserialize(new Uint8Array(await res.arrayBuffer())) as TraceResult;
|
||||
}
|
||||
Reference in New Issue
Block a user