Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Export and import .mavatar files from the editor

shinshin86af8ed71f3346
diff --git a/README.ja.md b/README.ja.md
index e6484e2..f3e6db2 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -68,6 +68,12 @@ npm run dev
![口の描き分けの依頼](docs/images/ja/05-variants.png)
+## アバターを共有する
+
+エディタの「.mavatar を書き出す」で、保存済みの設定・レイヤー画像・目と口の差分画像・アバターの情報を1つのファイルにまとめてダウンロードできます。「元画像を含める」は初期状態でオンです。受け取った人がStudioで編集する場合は、そのまま書き出してください。未保存の編集は「保存して書き出す」で反映できます。輪郭を変更した場合は、先にレイヤーを作り直してください。読み取り専用の画面では元のファイルを書き出します。
+
+受け取ったファイルは「プロジェクトを開く」の「.mavatar を取り込む」から選ぶか、その欄にドロップします。`projects/` の中に新しいフォルダが作られ、同名のフォルダがある場合は別の名前になります。取り込みには `npm run dev` が必要で、上限は128 MiBです。元画像を含めなかった場合は再生専用となり、編集やレイヤーの作り直しはできません。元画像を除いても、レイヤー画像はファイルに残ります。詳しくは[アバターの形式](docs/format.md)(英語)を参照してください。
+
## カメラで動かして配信する
![配信の操作画面](docs/images/ja/07-live.png)
diff --git a/README.md b/README.md
index 27dabee..788b688 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,19 @@ the masks and prompts for you to hand to an image generator.)
![Requesting drawn mouths](docs/images/en/05-variants.png)
+## Share your avatar
+
+Choose **Export .mavatar** in the editor to download one file containing the saved rig,
+built layers, drawn expressions and avatar metadata. **Include source image** is on by
+default so the recipient can edit it in Studio. If you have unsaved edits, use **Save and
+export**; changed outlines need a layer rebuild first. Read-only views export the original files.
+
+In **Open project**, choose **Import .mavatar** or drop the file there. Studio creates a new
+folder under `projects/`, using a new name if one already exists. Import requires `npm run dev`
+and accepts archives up to 128 MiB. Without the source image, the imported avatar can play but
+cannot be edited or rebuilt. Omitting the source does not remove the built images.
+See the [avatar format](docs/format.md) for the file contents.
+
## Live and streaming
![The Live page](docs/images/en/07-live.png)
diff --git a/docs/format.md b/docs/format.md
index b94cb17..efc9b81 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -55,6 +55,8 @@ source variants, masks and review images; these are not required for playback.
| `thumbnail` | Optional preview-image filename relative to the root, normally `thumbnail.png`. |
| `studio.version` | Optional version string identifying the Studio that prepared the avatar. |
+On import, Studio saves the original image as `source.png` and updates `avatar.json.source` when its filename differs.
+
An existing folder without `avatar.json` has the effective manifest
`{ "format": "mesh-avatar", "version": 1, "name": "<folder name>" }`.
Archives must contain an explicit manifest. `parseManifest` validates known fields,
diff --git a/docs/reference.md b/docs/reference.md
index 97d2130..b0d5a81 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -174,6 +174,7 @@ Two pages served by the development server (`npm run dev`):
| Parameter | Values | Default |
|---|---|---|
| `project` | A project name from the local list, or `sample-miko-qipao` | the sample |
+| `avatar` | A folder or `.mavatar` URL on the same origin as the local development server; an explicit `project` takes precedence | unset |
| `bg` | `transparent`, `green`, `blue` or a hex colour such as `#336699` | `transparent` |
| `fit` | `contain` (whole avatar) or `cover` (fill the frame) | `contain` |
| `idle` | `1` (idle motion, blinking, breathing, hair sway) or `0` | `1` |
@@ -194,6 +195,10 @@ Live page's current lighting settings. In OBS, add the URL as a **Browser Source
(for example 1080 × 1080); the transparent background needs no chroma key. Use green or blue
for software without transparency support.
+`avatar` accepts relative URLs or HTTP(S) URLs with the same origin (scheme, host and port)
+as Studio. External or invalid URLs are ignored and the sample loads instead; they do not
+trigger external requests. If `project` is present, `avatar` is ignored.
+
### How motion reaches the stream view
- The Live page sends numeric pose values (head angles, eyes, gaze, brows, mouth) over the
diff --git a/e2e/avatar-archive.spec.ts b/e2e/avatar-archive.spec.ts
index 63b4f36..70969d3 100644
--- a/e2e/avatar-archive.spec.ts
+++ b/e2e/avatar-archive.spec.ts
@@ -36,7 +36,7 @@ test('stored archive renders the same stream as its folder, with local requests
} });
});
const hashes: string[] = [];
- for (const query of ['', `&avatar=${encodeURIComponent(`/__studio/projects/${name}`)}`, '&project=sample-miko-qipao&avatar=/must-not-load.mavatar']) {
+ for (const query of ['', `&avatar=${encodeURIComponent(`/__studio/projects/${name}`)}`, '&project=sample-miko-qipao&avatar=/must-not-load.mavatar', '&avatar=https%3A%2F%2Fexample.com%2Fexternal.mavatar']) {
await page.goto(`/stream.html?idle=0${query}`);
await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');
await page.evaluate(() => (window as unknown as { stepFrames: (count: number) => void }).stepFrames(120));
diff --git a/e2e/avatar-sharing.spec.ts b/e2e/avatar-sharing.spec.ts
new file mode 100644
index 0000000..7d36a81
--- /dev/null
+++ b/e2e/avatar-sharing.spec.ts
@@ -0,0 +1,88 @@
+import { expect, test, type Page } from '@playwright/test';
+import { readFile, rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { zipSync, unzipSync } from 'fflate';
+import { dismissGuide, samplePresent, sampleSkipReason } from './sample';
+
+const imported: string[] = [];
+test.beforeEach(async ({ page }) => {
+ test.skip(!samplePresent, sampleSkipReason);
+ await page.goto('/'); await dismissGuide(page);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+});
+test.afterEach(async () => { for (const name of imported.splice(0)) await rm(resolve('projects', name), { recursive: true, force: true }); });
+
+async function download(page: Page, includeSource = true, button = 'Download .mavatar') {
+ const menu = page.getByTestId('export-menu');
+ if (await menu.getAttribute('open') === null) await menu.locator('summary').click();
+ await menu.getByRole('checkbox').setChecked(includeSource);
+ const result = page.waitForEvent('download');
+ await menu.getByRole('button', { name: button, exact: true }).click();
+ const file = await result;
+ return readFile((await file.path())!);
+}
+async function importFile(page: Page, bytes: Buffer) {
+ await page.locator('.open-menu > summary').click();
+ const response = page.waitForResponse(response => response.url().endsWith('/__studio/import'));
+ await page.getByLabel('Avatar archive file').setInputFiles({ name: 'avatar.mavatar', mimeType: 'application/octet-stream', buffer: bytes });
+ const result = await response; expect(result.ok()).toBe(true);
+ const entry = await result.json(); imported.push(entry.name);
+ await expect(page.getByTestId('project-location')).toContainText(entry.name);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ return entry.name as string;
+}
+
+test('sample export imports as a listed, rendered project and reexports the same files', async ({ page, baseURL }) => {
+ const outside: string[] = [];
+ await page.route('**/*', route => {
+ if (new URL(route.request().url()).origin !== baseURL) { outside.push(route.request().url()); return route.abort(); }
+ return route.continue();
+ });
+ await page.getByTestId('export-menu').locator('summary').click();
+ await expect(page.getByRole('checkbox', { name: 'Include source image' })).toBeChecked();
+ const first = await download(page), name = await importFile(page, first);
+ await expect(page.getByTestId('preview')).toBeVisible();
+ const image = await page.getByTestId('preview').evaluate(canvas => (canvas as HTMLCanvasElement).toDataURL());
+ expect(image.length).toBeGreaterThan(10000);
+ await page.locator('.open-menu > summary').click();
+ await expect(page.getByTestId(`project-${name}`)).toBeVisible();
+ await page.locator('.open-menu > summary').click();
+ const before = unzipSync(first), after = unzipSync(await download(page));
+ expect(Object.keys(after).sort()).toEqual(Object.keys(before).sort());
+ for (const name of Object.keys(before)) expect(Buffer.from(after[name]).equals(Buffer.from(before[name])), name).toBe(true);
+ expect(outside).toEqual([]);
+});
+
+test('source-free import renders in playback-only mode and a bad path dropped in the import area shows the ZIP error', async ({ page }) => {
+ const bytes = await download(page, false);
+ const name = await importFile(page, bytes);
+ await expect(page.getByText('Source image missing: playback only. Editing and rebuilding are unavailable.')).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Save rig', exact: true })).toBeDisabled();
+ await expect(page.locator('.editor-panel')).toHaveCount(0);
+ await expect(page.getByTestId('preview')).toBeVisible();
+ await page.locator('.open-menu > summary').click();
+ await expect(page.getByTestId(`project-${name}`)).toContainText('Playback only');
+ const bad = zipSync({ ...unzipSync(bytes), '../escape.txt': new Uint8Array([1]) }, { level: 0 });
+ const transfer = await page.evaluateHandle(values => {
+ const data = new DataTransfer(); data.items.add(new File([new Uint8Array(values)], 'bad.mavatar', { type: 'application/octet-stream' })); return data;
+ }, Array.from(bad));
+ await page.getByTestId('archive-import').dispatchEvent('drop', { dataTransfer: transfer });
+ await expect(page.getByRole('alert')).toContainText('ZIP entry "../escape.txt": path must be relative');
+ await expect(page.getByTestId('project-location')).toContainText(name);
+});
+
+test('browser-picked folders export in memory, and writable projects save current edits before exporting', async ({ page }) => {
+ let exports = 0;
+ page.on('request', request => { if (request.url().endsWith('/__studio/export')) exports++; });
+ await page.getByLabel('Open project folder files', { exact: true }).setInputFiles(resolve('samples/miko-qipao'));
+ await expect(page.getByTestId('project-location')).toContainText('miko-qipao');
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ const bytes = await download(page); expect(exports).toBe(0);
+ const name = await importFile(page, bytes);
+ await page.getByTestId('part-mouth').click();
+ const field = page.getByRole('spinbutton', { name: 'mouth.area.cx', exact: true });
+ const next = Number(await field.inputValue()) + 1; await field.fill(String(next)); await field.blur();
+ const edited = unzipSync(await download(page, true, 'Save and export'));
+ const rig = JSON.parse(new TextDecoder().decode(edited['rig.json'])); expect(rig.mouth.area.cx).toBe(next);
+ expect(JSON.parse(await readFile(resolve('projects', name, 'rig.json'), 'utf8'))).toEqual(rig);
+});
diff --git a/e2e/usability.spec.ts b/e2e/usability.spec.ts
index 7e66590..ad4e97b 100644
--- a/e2e/usability.spec.ts
+++ b/e2e/usability.spec.ts
@@ -172,7 +172,8 @@ for (const [width, height] of [[1440, 900], [1280, 800]]) for (const language of
const parent = node.parentElement!;
if (!parent.checkVisibility() || parent.closest('select, .field-path, .point-field > small')) continue;
const text = node.textContent!.trim();
- if (/[a-z]{2}/i.test(text) && text !== 'Mesh Avatar Studio') found.push(text);
+ // The archive filename extension is identical in every language.
+ if (/[a-z]{2}/i.test(text.replace(/\.mavatar\b/g, '')) && text !== 'Mesh Avatar Studio') found.push(text);
}
return found;
});
diff --git a/packages/runtime/src/format/project-archive.ts b/packages/runtime/src/format/project-archive.ts
new file mode 100644
index 0000000..0ec39ea
--- /dev/null
+++ b/packages/runtime/src/format/project-archive.ts
@@ -0,0 +1,33 @@
+import { parseManifest, type AvatarManifest } from './manifest.ts';
+import { checkEntryName, packAvatar } from './zip.ts';
+
+type Files = Record<string, Uint8Array>;
+
+// Shared by Studio and the CLI; this is not part of the runtime's public API.
+export async function packProjectAvatar(
+ read: (paths: Set<string>) => Promise<Files>,
+ { name, includeSource = true }: { name: string; includeSource?: boolean },
+): Promise<Uint8Array> {
+ const wanted = new Set(['avatar.json', 'rig.json', 'built/layers.json', 'built/sprites/sprites.json']);
+ const metadata = await read(wanted);
+ const json = (path: string) => {
+ try { return JSON.parse(new TextDecoder().decode(metadata[path])); }
+ catch { throw new Error(`${path}: invalid JSON`); }
+ };
+ const manifest = metadata['avatar.json'] ? parseManifest(json('avatar.json')) : undefined;
+ const source = manifest?.source ?? 'source.png', thumbnail = manifest?.thumbnail ?? 'thumbnail.png';
+ checkEntryName(source); checkEntryName(thumbnail);
+ wanted.add('built/base.png'); wanted.add('built/hairmask.png'); wanted.add(thumbnail);
+ if (includeSource) wanted.add(source);
+ for (const [path, prefix] of [['built/layers.json', 'built/'], ['built/sprites/sprites.json', 'built/sprites/']]) {
+ if (!metadata[path]) continue;
+ for (const layer of Object.keys(json(path)?.layers ?? {})) {
+ if (!/^[A-Za-z0-9_-]+$/.test(layer)) throw new Error(`${path}.layers.${layer}: invalid layer name`);
+ wanted.add(`${prefix}${layer}.png`);
+ }
+ }
+ const files = await read(wanted);
+ let override: Partial<AvatarManifest> | undefined = manifest ? undefined : { name };
+ if (!includeSource && manifest?.source) override = { ...manifest, source: undefined };
+ return packAvatar(files, { manifest: override });
+}
diff --git a/src/editor/App.tsx b/src/editor/App.tsx
index 1a01ce8..d05579f 100644
--- a/src/editor/App.tsx
+++ b/src/editor/App.tsx
@@ -5,7 +5,9 @@ import { setAt } from './model';
import { type Rig, parseRig, validateRig } from 'mesh-avatar';
import { Preview } from './Preview';
import { RigHistory, downloadRig } from './history';
-import { openProjectFolder, openLocalProject, copySample, localProjects, projectAction, sampleImagesAvailable, sampleSourceUrl, repositoryContext, runProjectJob, ProjectJobError, type ProjectJob, type LocalProject, type LocalProjectEntry } from './project';
+import { openProjectFolder, openLocalProject, copySample, localProjects, projectAction, sampleImagesAvailable, sampleSourceUrl, repositoryContext, runProjectJob, ProjectJobError, importAvatar, exportAvatar, type ProjectJob, type LocalProject, type LocalProjectEntry } from './project';
+import { ExportAvatar, ImportAvatar } from './AvatarTransfer';
+import { archiveText } from './archive-i18n';
import { folderOpenError } from './folder-errors';
import { layerSignature } from './stale';
import { RigFields } from './RigFields';
@@ -35,6 +37,11 @@ function Workspace() {
const [help, setHelp] = useState(false);
const [history] = useState(() => new RigHistory(parseRig(fixture)));
const [rig, setRig] = useState(history.present);
+ const [savedRig, setSavedRig] = useState(() => JSON.stringify(history.present));
+ const pickedFiles = useRef<File[] | undefined>(undefined);
+ const [archiveBusy, setArchiveBusy] = useState(false);
+ const [archiveFeedback, setArchiveFeedback] = useState<{ error?: string; name?: string } | null>(null);
+ const sharing = archiveText[language];
const [builtSignature, setBuiltSignature] = useState(() => layerSignature(history.present));
const fileInput = useRef<HTMLInputElement>(null);
const folderInput = useRef<HTMLInputElement>(null);
@@ -121,7 +128,7 @@ function Workspace() {
setRig(history.present);
};
const openFile = async (file?: File) => {
- if (!file || jobRef.current) return;
+ if (!file || jobRef.current || localProject?.hasSource === false) return;
try {
update(parseRig(JSON.parse(await file.text())));
setSelected(null);
@@ -130,11 +137,13 @@ function Workspace() {
};
const openFolder = async (files: File[], handle?: ProjectDirectory) => {
if (jobRef.current) return false;
+ setOpening(true);
try {
const project = await openProjectFolder(files);
projectOpened.current = true;
if (project.rig) {
history.load(project.rig); setRig(history.present); setDragStale(null);
+ setSavedRig(JSON.stringify(project.rig));
setBuiltSignature(layerSignature(project.rig));
}
setSelected(null);
@@ -143,6 +152,7 @@ function Workspace() {
setSourceUrl(project.sourceUrl);
setAssets(project.assets);
setLocalProject(null);
+ pickedFiles.current = files;
setPickedName(files[0]?.webkitRelativePath.split('/')[0] || t.openProject);
setChecking(false);
setError(null);
@@ -162,6 +172,7 @@ function Workspace() {
if (openMenu.current) openMenu.current.open = false;
return true;
} catch (error) { setError(folderOpenError(error)); return false; }
+ finally { setOpening(false); }
};
const openLocal = async (entry: LocalProjectEntry, automatic = false) => {
if (jobRef.current) return;
@@ -171,6 +182,7 @@ function Workspace() {
const project = await openLocalProject(entry);
projectOpened.current = true;
history.load(project.rig!); setRig(history.present); setDragStale(null); setBuiltSignature(layerSignature(project.rig!));
+ setSavedRig(JSON.stringify(project.rig)); pickedFiles.current = undefined;
setSelected(null); setLocalProject(entry); setPickedName('');
objectUrls.current.forEach(url => URL.revokeObjectURL(url)); objectUrls.current = [];
setSourceUrl(project.sourceUrl); setAssets(project.assets); setChecking(false); setError(null);
@@ -188,10 +200,12 @@ function Workspace() {
const saveRef = useRef<() => void>(() => undefined);
const save = async () => {
if (jobRef.current) return;
+ if (localProject?.hasSource === false) return;
if (!localProject || localProject.readOnly) { downloadRig(history.present); return; }
if (saving) return;
setSaving(true);
- try { const result = await projectAction(localProject, 'rig', history.present); setNotice({ key: 'savedTo', path: result.path }); setError(null); }
+ const snapshot = JSON.stringify(history.present);
+ try { const result = await projectAction(localProject, 'rig', history.present); setSavedRig(snapshot); setNotice({ key: 'savedTo', path: result.path }); setError(null); }
catch { setError({ kind: 'saveError', paths: [] }); }
finally { setSaving(false); }
};
@@ -264,6 +278,7 @@ function Workspace() {
const loaded = await openLocalProject(fresh);
// Keep the canvas mounted, its view, selection and the existing undo/redo stack.
history.replacePresent(loaded.rig!); setRig(history.present); setDragStale(null);
+ setSavedRig(JSON.stringify(loaded.rig));
setBuiltSignature(layerSignature(loaded.rig!)); setAssets(loaded.assets); setLocalProject(fresh); setProjects(list); setRebuildError(null);
};
useEffect(() => {
@@ -324,12 +339,48 @@ function Workspace() {
objectUrls.current.forEach(url => URL.revokeObjectURL(url)); objectUrls.current = [];
projectOpened.current = true; setSourceUrl(loaded.sourceUrl); setAssets(loaded.assets);
setLocalProject(entry); setPickedName(''); setChecking(false); setRebuildError(null);
+ setSavedRig(JSON.stringify(loaded.rig)); pickedFiles.current = undefined;
setProjects(await localProjects());
remember({ id: `server:${entry.name}`, kind: 'server', name: entry.name, serverName: entry.name, relativePath: entry.relativePath, lastOpened: new Date().toISOString() });
} catch { setError({ kind: 'continueError', paths: [] }); }
finally { jobRef.current = null; setOpening(false); }
};
- return <main onDragOver={event => event.preventDefault()} onDrop={event => { event.preventDefault(); void openFile(event.dataTransfer.files[0]); }}>
+ const playbackOnly = localProject?.hasSource === false;
+ const busy = job !== null || opening || archiveBusy;
+ const dirty = JSON.stringify(rig) !== savedRig;
+ const writable = !!localProject && !localProject.readOnly && !playbackOnly;
+ const importFile = async (file: File) => {
+ if (jobRef.current || saving || opening) return;
+ if (!rootPath) { setArchiveFeedback({ error: sharing.importUnavailable }); return; }
+ if (openMenu.current) openMenu.current.open = false;
+ jobRef.current = 'transfer'; setArchiveBusy(true); setArchiveFeedback(null);
+ try {
+ const entry = await importAvatar(file);
+ setProjects(await localProjects());
+ jobRef.current = null;
+ await openLocal(entry);
+ setArchiveFeedback({ name: entry.name });
+ } catch (error) { setArchiveFeedback({ error: error instanceof Error ? error.message : sharing.failed }); }
+ finally { jobRef.current = null; setArchiveBusy(false); }
+ };
+ const exportFile = async (includeSource: boolean) => {
+ if (jobRef.current || saving || opening) return;
+ jobRef.current = 'transfer'; setArchiveBusy(true); setArchiveFeedback(null);
+ try {
+ if (writable && dirty) {
+ const snapshot = JSON.stringify(history.present);
+ await projectAction(localProject!, 'rig', history.present); setSavedRig(snapshot);
+ }
+ const name = localProject?.name ?? (pickedName || 'sample-miko-qipao');
+ const blob = await exportAvatar(name, includeSource, pickedFiles.current);
+ const url = URL.createObjectURL(blob), link = document.createElement('a');
+ link.href = url; link.download = `${name}.mavatar`; link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ } catch (error) { setArchiveFeedback({ error: error instanceof Error ? error.message : sharing.failed }); throw error; }
+ finally { jobRef.current = null; setArchiveBusy(false); }
+ };
+ const importControl = <ImportAvatar busy={busy || saving} available={!!rootPath} onImport={file => { void importFile(file); }} />;
+ return <main onDragOver={event => event.preventDefault()} onDrop={event => { event.preventDefault(); const file = event.dataTransfer.files[0]; if (file?.name.toLowerCase().endsWith('.mavatar')) void importFile(file); else void openFile(file); }}>
<header className="toolbar">
<div className="brand"><h1>{t.product}</h1><p>{t.subtitle}</p></div>
<nav aria-label={t.tools}>
@@ -337,25 +388,26 @@ function Workspace() {
onChange={event => { void openFile(event.target.files?.[0]); event.target.value = ''; }} />
<input ref={folderInput} type="file" multiple hidden aria-label={t.folderFiles} {...{ webkitdirectory: '' }}
onChange={event => { void openFolder(Array.from(event.target.files ?? [])); event.target.value = ''; }} />
- <details ref={openMenu} className="open-menu" inert={job !== null || opening} onToggle={event => {
+ <details ref={openMenu} className="open-menu" inert={busy} onToggle={event => {
if (event.currentTarget.open) void localProjects().then(setProjects);
}}><summary>{t.openProject}<Icon name="chevron" /></summary>
- <div className="project-menu">{recentControl}<p className="project-help">{t.projectHelp}</p>
+ <div className="project-menu">{importControl}{recentControl}<p className="project-help">{t.projectHelp}</p>
{projects && <div className="project-list" aria-label={t.localProjects}>
{projects.length === 0 && <p>{t.noProjects}</p>}
{projects.map(project => <button key={project.name} className={project.error ? 'unreadable-project' : undefined} disabled={opening || !!project.error} data-testid={`project-${project.name}`} onClick={() => { void openLocal(project); }}>
<strong>{project.readOnly ? t.sampleProject : project.name}</strong><small>{project.relativePath}</small>
<small>{project.error ? <>{t.unreadableProject} ({project.error.code}) · {project.error.path}</> : <>{t.updated}: {new Date(project.updatedAt).toLocaleString(locale)}
- {project.hasSprites && <span className="badge">{t.drawnVariants}</span>}{project.readOnly && <span className="badge">{t.readOnly}</span>}</>}</small>
+ {project.hasSprites && <span className="badge">{t.drawnVariants}</span>}{project.readOnly && <span className="badge">{t.readOnly}</span>}{project.hasSource === false && <span className="badge">{sharing.playbackBadge}</span>}</>}</small>
</button>)}
</div>}
- <button onClick={() => { void chooseFile(true); }}>{t.openFolder}</button><button onClick={() => { void chooseFile(false); }}>{t.openRig}</button>
+ <button onClick={() => { void chooseFile(true); }}>{t.openFolder}</button><button disabled={playbackOnly} onClick={() => { void chooseFile(false); }}>{t.openRig}</button>
</div>
</details>
- <button className="icon-button" aria-label={t.save} disabled={saving || job !== null || opening} title={`${t.save} · ⌘S`} onClick={() => { void save(); }}><Icon name="save" /></button>
+ <ExportAvatar busy={busy || saving} available={!!rootPath || !!pickedFiles.current} writable={writable} dirty={dirty} stale={changed.length > 0} onExport={exportFile} />
+ <button className="icon-button" aria-label={t.save} disabled={saving || busy || playbackOnly} title={`${t.save} · ⌘S`} onClick={() => { void save(); }}><Icon name="save" /></button>
<span className="toolbar-divider" />
- <button className="icon-button" aria-label={t.undo} title={`${t.undo} · ⌘Z`} disabled={!history.canUndo || job !== null || opening} onClick={() => setRig(history.undo())}><Icon name="undo" /></button>
- <button className="icon-button" aria-label={t.redo} title={`${t.redo} · ⇧⌘Z`} disabled={!history.canRedo || job !== null || opening} onClick={() => setRig(history.redo())}><Icon name="redo" /></button>
+ <button className="icon-button" aria-label={t.undo} title={`${t.undo} · ⌘Z`} disabled={!history.canUndo || busy || playbackOnly} onClick={() => setRig(history.undo())}><Icon name="undo" /></button>
+ <button className="icon-button" aria-label={t.redo} title={`${t.redo} · ⇧⌘Z`} disabled={!history.canRedo || busy || playbackOnly} onClick={() => setRig(history.redo())}><Icon name="redo" /></button>
<span className="toolbar-divider" />
<a className="live-link" href={localProject || listedProject || !pickedName ? `/live.html?project=${encodeURIComponent(localProject?.name ?? listedProject?.name ?? 'sample-miko-qipao')}` : undefined}
target="_blank" rel="noreferrer" aria-disabled={!!pickedName && !localProject && !listedProject}
@@ -375,16 +427,20 @@ function Workspace() {
{localProject.readOnly && <span className="badge">{t.readOnly}</span>}</>}
</div>}
{notice && <div role="status" className="save-notice">{t[notice.key]}{notice.path && ` ${notice.path}`}</div>}
+ {archiveFeedback && <div className={`archive-feedback${archiveFeedback.error ? ' error' : ''}`} role={archiveFeedback.error ? 'alert' : 'status'}>
+ <span>{archiveFeedback.error ?? `${sharing.imported} ${archiveFeedback.name}`}</span><button onClick={() => setArchiveFeedback(null)}>{sharing.dismiss}</button>
+ </div>}
+ {playbackOnly && <p className="playback-notice" role="status">{sharing.playbackOnly}</p>}
{help && <Help onClose={() => setHelp(false)} onGuide={() => { setGuide(true); setHelp(false); }} />}
{(dragStale ?? changed.length > 0) && <div className="stale" data-testid="stale-banner"><p role="status">{localProject && !localProject.readOnly ? t.staleLocal : sampleEditing ? t.staleSample : listedProject ? t.staleListed : t.stale}</p><small>{t.changedParts}: {changed.map(key => parts[key as PartGroup]?.[0] ?? title(key)).join(' · ')}</small>
{localProject && !localProject.readOnly ? <button className="primary" disabled={job !== null || saving} onClick={() => { setRebuildError(null); void runJob('rebuild').catch(error => setRebuildError(error instanceof ProjectJobError ? error : new ProjectJobError('toolFailed'))); }}>{job === 'rebuild' ? t.rebuilding : t.rebuild}</button> : <><small>{sampleEditing ? t.sampleRebuildReason : t.folderRebuildReason}</small>{sampleEditing || listedProject ? <button className="primary" disabled={opening || saving || job !== null || (sampleEditing && !rootPath)} onClick={() => { void continueEditing(); }}>{opening ? t.operationBusy : sampleEditing ? t.copyContinue : t.reopenListed}</button> : <p>{t.rebuildUnavailable}</p>}</>}
{rebuildError && <JobFeedback error={rebuildError} rig={rig} />}
{error?.kind === 'continueError' && errorNotice}
</div>}
- {!sourceUrl && <section className="panel empty-project"><h2>{checking ? t.checking : t.emptyTitle}</h2><p>{t.projectHelp}</p><p>{t.emptyHelp}</p>{recentControl}<AskAgent newProject rootPath={rootPath} />{errorNotice}</section>}
- {sourceUrl && <div className="workspace">
- <div className="parts-container" inert={job !== null || opening}><PartList rig={rig} visible={visible} selected={selected} onSelect={selectPart} onFocus={group => { selectPart(group); setFocusRequest(current => ({ group, id: (current?.id ?? 0) + 1 })); }} onVisible={setVisible} /></div>
- <section className="panel editor-panel" inert={job !== null || opening}>
+ {!sourceUrl && !assets && <section className="panel empty-project"><h2>{checking ? t.checking : t.emptyTitle}</h2><p>{t.projectHelp}</p><p>{t.emptyHelp}</p>{recentControl}<AskAgent newProject rootPath={rootPath} />{errorNotice}</section>}
+ {(sourceUrl || assets) && <div className={`workspace${playbackOnly ? ' playback-only' : ''}`}>
+ {!playbackOnly && <div className="parts-container" inert={busy}><PartList rig={rig} visible={visible} selected={selected} onSelect={selectPart} onFocus={group => { selectPart(group); setFocusRequest(current => ({ group, id: (current?.id ?? 0) + 1 })); }} onVisible={setVisible} /></div>}
+ {!playbackOnly && <section className="panel editor-panel" inert={busy}>
<div className="panel-title"><h2>{t.source}</h2><span>{rig.image.width} × {rig.image.height} {t.px}</span></div>
<div className="canvas-stage">
<EditorCanvas sourceUrl={sourceUrl} rig={rig} visible={visible} selected={selected} onSelect={setSelected} onChange={update} focusRequest={focusRequest}
@@ -392,18 +448,18 @@ function Workspace() {
onEnd={() => { history.end(); setRig(structuredClone(history.present)); setDragStale(null); }} />
{guide && <FirstGuide onDismiss={dismissGuide} />}
</div>
- </section>
+ </section>}
<div className="right-column">
- <Preview key={localProject?.name ?? (pickedName || 'sample-miko-qipao')} projectKey={localProject?.name ?? (pickedName || 'sample-miko-qipao')} rig={rig} assets={assets} hasMouthSprites={mouthSprites} onDrawMouth={() => setMouthRequest(value => value + 1)} />
- <VariantsPanel project={localProject} projectPath={localProject?.relativePath ?? (pickedName ? `<${pickedName}>` : 'samples/miko-qipao')} assets={assets} rootPath={rootPath} busy={job !== null || saving} stale={changed.length > 0} onRun={runJob} mouthRequest={mouthRequest} onMouthPresence={setMouthSprites} />
+ <Preview key={localProject?.name ?? (pickedName || 'sample-miko-qipao')} projectKey={localProject?.name ?? (pickedName || 'sample-miko-qipao')} rig={rig} assets={assets} hasMouthSprites={mouthSprites} onDrawMouth={playbackOnly ? undefined : () => setMouthRequest(value => value + 1)} />
+ {!playbackOnly && <VariantsPanel project={localProject} projectPath={localProject?.relativePath ?? (pickedName ? `<${pickedName}>` : 'samples/miko-qipao')} assets={assets} rootPath={rootPath} busy={busy || saving} stale={changed.length > 0} onRun={runJob} mouthRequest={mouthRequest} onMouthPresence={setMouthSprites} />}
{!localProject && !pickedName && <details className="panel new-illustration"><summary>{t.newIllustration}</summary><AskAgent newProject rootPath={rootPath} /></details>}
- <aside className="panel inspector" inert={job !== null || opening}>
+ {!playbackOnly && <aside className="panel inspector" inert={busy}>
<div className="selection-heading"><h2>{selectedPart?.[0] ?? t.selection}</h2></div>
{errorNotice}
{selectedPart ? <><p className="part-description">{selectedPart[1]}</p><p className="part-tip"><strong>{t.tip}</strong> {selectedPart[2]}</p>
<div className="fields">{selected && <RigFields rig={rig} path={selected} onChange={(path, value) => update(setAt(rig, path, value))} />}</div></>
: <div className="selection-empty"><p>{t.selectPart}</p><GuideSteps /></div>}
- </aside>
+ </aside>}
</div>
</div>}
</main>;
diff --git a/src/editor/AvatarTransfer.tsx b/src/editor/AvatarTransfer.tsx
new file mode 100644
index 0000000..568d521
--- /dev/null
+++ b/src/editor/AvatarTransfer.tsx
@@ -0,0 +1,40 @@
+import { useRef, useState } from 'react';
+import { useI18n } from './i18n';
+import { archiveText } from './archive-i18n';
+import { Icon } from './Icon';
+
+export function ExportAvatar({ busy, available, writable, dirty, stale, onExport }: {
+ busy: boolean; available: boolean; writable: boolean; dirty: boolean; stale: boolean;
+ onExport: (includeSource: boolean) => Promise<void>;
+}) {
+ const { language } = useI18n(), text = archiveText[language];
+ const [includeSource, setIncludeSource] = useState(true);
+ const menu = useRef<HTMLDetailsElement>(null);
+ return <details ref={menu} className="archive-menu" data-testid="export-menu" onKeyDown={event => { if (event.key === 'Escape' && menu.current) menu.current.open = false; }}>
+ <summary>{text.exportTitle}<Icon name="chevron" /></summary>
+ <div className="archive-options">
+ <p>{text.savedHelp}</p>
+ <label><input type="checkbox" checked={includeSource} disabled={busy} onChange={event => setIncludeSource(event.target.checked)} />{text.includeSource}</label>
+ <p>{text.sourceHelp}</p><small>{text.noSourceHelp}</small>
+ {(dirty || (writable && stale)) && <p>{writable ? stale ? text.rebuildHelp : text.saveHelp : text.originalHelp}</p>}
+ {!available && <p>{text.exportUnavailable}</p>}
+ <button className="primary" disabled={busy || !available || (writable && stale)} onClick={() => { void onExport(includeSource).finally(() => { if (menu.current) menu.current.open = false; }).catch(() => undefined); }}>{busy ? text.busy : writable && dirty ? text.saveExport : text.exportButton}</button>
+ </div>
+ </details>;
+}
+
+export function ImportAvatar({ busy, available, onImport }: { busy: boolean; available: boolean; onImport: (file: File) => void }) {
+ const { language } = useI18n(), text = archiveText[language];
+ const input = useRef<HTMLInputElement>(null);
+ const [dragging, setDragging] = useState(false);
+ return <div className={`archive-import${dragging ? ' dragging' : ''}`} data-testid="archive-import"
+ onDragOver={event => { event.preventDefault(); event.stopPropagation(); if (!busy && available) setDragging(true); }}
+ onDragLeave={() => setDragging(false)} onDrop={event => {
+ event.preventDefault(); event.stopPropagation(); setDragging(false);
+ const file = event.dataTransfer.files[0]; if (file && !busy && available) onImport(file);
+ }}>
+ <input ref={input} type="file" accept=".mavatar" hidden aria-label={text.archiveFile} onChange={event => { const file = event.target.files?.[0]; if (file) onImport(file); event.target.value = ''; }} />
+ <button disabled={busy || !available} onClick={() => input.current?.click()}>{busy ? text.busy : text.importTitle}</button>
+ <p>{available ? text.importHelp : text.importUnavailable}</p>
+ </div>;
+}
diff --git a/src/editor/Preview.tsx b/src/editor/Preview.tsx
index 1534f4f..90fc87d 100644
--- a/src/editor/Preview.tsx
+++ b/src/editor/Preview.tsx
@@ -18,7 +18,7 @@ const sliders = [
] as const;
type Vowel = 'a' | 'i' | 'u' | 'e' | 'o' | 'n';
type Lip = { kind: 'hold'; vowel: Vowel } | { kind: 'text'; text: string; speed: number; loop: boolean } | null;
-export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth }: { projectKey: string; rig: Rig; assets?: Record<string, string>; hasMouthSprites: boolean; onDrawMouth: () => void }) {
+export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth }: { projectKey: string; rig: Rig; assets?: Record<string, string>; hasMouthSprites: boolean; onDrawMouth?: () => void }) {
const { t, language } = useI18n();
const [lighting, setLighting] = useState(() => loadLighting(projectKey));
const lightRef = useRef(lighting); lightRef.current = lighting;
@@ -156,7 +156,7 @@ export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth
onChange={event => { const value = Number(event.target.value); setSpeed(value); setLip(current => current?.kind === 'text' ? { ...current, speed: value } : current); }} /><output>{speed}</output></label>
<label><input type="checkbox" checked={loop} onChange={event => { const value = event.target.checked; setLoop(value); setLip(current => current?.kind === 'text' ? { ...current, loop: value } : current); }} />{t.lipLoop}</label>
</div>
- {!hasMouthSprites && <p className="mouth-fallback">{t.mouthFallback} <button type="button" onClick={onDrawMouth}>{t.drawMouth}</button></p>}
+ {!hasMouthSprites && <p className="mouth-fallback">{t.mouthFallback} {onDrawMouth && <button type="button" onClick={onDrawMouth}>{t.drawMouth}</button>}</p>}
<p className="lip-help">{t.lipHelp}</p>{skipped && <p className="lip-skipped">{t.skippedKana} {skipped}</p>}
<div className="sliders lip-live"><label>{t.mouthOpen}<input type="range" aria-label={t.mouthOpen} min="0" max="1" step="0.01" disabled={lip !== null}
value={lip ? liveMouth : parameters.mouthOpen ?? 0} onChange={event => setParameters(current => ({ ...current, mouthOpen: Number(event.target.value) }))} /><output>{(lip ? liveMouth : parameters.mouthOpen ?? 0).toFixed(2)}</output></label></div>
diff --git a/src/editor/archive-i18n.ts b/src/editor/archive-i18n.ts
new file mode 100644
index 0000000..1f571c8
--- /dev/null
+++ b/src/editor/archive-i18n.ts
@@ -0,0 +1,43 @@
+const en = {
+ exportTitle: 'Export .mavatar', exportButton: 'Download .mavatar', saveExport: 'Save and export',
+ includeSource: 'Include source image', sourceHelp: 'Include the original illustration to edit this avatar in Studio later.',
+ savedHelp: 'Exports the saved rig, built layers and drawn expressions.',
+ originalHelp: 'Exports the original files. Edits in this read-only view are not included.',
+ saveHelp: 'Your current edits will be saved before exporting.',
+ rebuildHelp: 'Outlines changed. Rebuild the layers before exporting your edits.',
+ exportUnavailable: 'Export requires the local development server or a folder opened in the browser.',
+ importTitle: 'Import .mavatar', importHelp: 'Choose a file or drop it here. A new local project will be created.',
+ importUnavailable: 'Import requires the local development server (npm run dev).',
+ archiveFile: 'Avatar archive file', busy: 'Working…', failed: 'Could not transfer the avatar.', dismiss: 'Dismiss',
+ playbackOnly: 'Source image missing: playback only. Editing and rebuilding are unavailable.',
+ playbackBadge: 'Playback only', imported: 'Imported:', noSourceHelp: 'Built images remain in the file even when the source image is omitted.',
+};
+const ja: typeof en = {
+ exportTitle: '.mavatar を書き出す', exportButton: '.mavatar をダウンロード', saveExport: '保存して書き出す',
+ includeSource: '元画像を含める', sourceHelp: 'あとでStudioで編集する場合は、元のイラストを含めてください。',
+ savedHelp: '保存済みの設定・レイヤー画像・目と口の差分画像を書き出します。',
+ originalHelp: '元のファイルを書き出します。読み取り専用の画面で加えた編集は含まれません。',
+ saveHelp: '現在の編集内容を保存してから書き出します。',
+ rebuildHelp: '輪郭が変更されています。編集内容を書き出す前にレイヤーを作り直してください。',
+ exportUnavailable: '書き出すには、ローカルの開発サーバーか、ブラウザで開いたフォルダが必要です。',
+ importTitle: '.mavatar を取り込む', importHelp: 'ファイルを選ぶか、ここにドロップしてください。新しいプロジェクトを作成します。',
+ importUnavailable: '取り込むには、ローカルの開発サーバー (npm run dev) が必要です。',
+ archiveFile: 'アバターのアーカイブファイル', busy: '処理中…', failed: 'アバターを転送できませんでした。', dismiss: '閉じる',
+ playbackOnly: '元画像がないため再生専用です。編集・レイヤーの作り直しはできません。',
+ playbackBadge: '再生専用', imported: '取り込みました:', noSourceHelp: '元画像を含めなくても、レイヤー画像はファイルに残ります。',
+};
+const zh: typeof en = {
+ exportTitle: '导出 .mavatar', exportButton: '下载 .mavatar', saveExport: '保存并导出',
+ includeSource: '包含原图', sourceHelp: '如需日后在 Studio 中编辑,请包含原始插画。',
+ savedHelp: '导出已保存的设置、图层和眼睛、嘴部的差分图像。',
+ originalHelp: '导出原始文件,不包含在只读视图中的修改。',
+ saveHelp: '先保存当前修改,再导出。',
+ rebuildHelp: '轮廓已更改。导出修改前,请重新生成图层。',
+ exportUnavailable: '导出需要本地开发服务器或在浏览器中打开的文件夹。',
+ importTitle: '导入 .mavatar', importHelp: '选择文件或拖放到此处,将创建一个新的本地项目。',
+ importUnavailable: '导入需要本地开发服务器 (npm run dev)。',
+ archiveFile: '虚拟形象归档文件', busy: '处理中…', failed: '无法传输虚拟形象。', dismiss: '关闭',
+ playbackOnly: '缺少原图:仅支持播放,无法编辑或重新生成图层。',
+ playbackBadge: '仅播放', imported: '已导入:', noSourceHelp: '即使不包含原图,文件仍保留图层图像。',
+};
+export const archiveText = { en, ja, zh };
diff --git a/src/editor/project.ts b/src/editor/project.ts
index 4b11dfe..d9a0a9c 100644
--- a/src/editor/project.ts
+++ b/src/editor/project.ts
@@ -1,6 +1,7 @@
import { openAvatar, parseRig, type Rig, type AvatarPackage } from 'mesh-avatar';
import type { LocalProject, LocalProjectEntry } from '../project-types';
import { FolderOpenError } from './folder-errors';
+import { packProjectAvatar } from '../../packages/runtime/src/format/project-archive';
export type { LocalProject, LocalProjectEntry } from '../project-types';
const sampleBase = '/miko-qipao/';
@@ -72,6 +73,30 @@ export async function copySample(rig: Rig): Promise<LocalProject> {
if (!response.ok) throw new Error('Could not copy the sample.');
return response.json();
}
+export async function importAvatar(file: File): Promise<LocalProject> {
+ if (file.size > 128 * 1024 * 1024) throw new Error('Archive exceeds 128 MiB.');
+ const response = await fetch('/__studio/import', { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file });
+ const result = await response.json();
+ if (!response.ok) throw new Error(result.error);
+ return result;
+}
+export async function exportAvatar(name: string, includeSource: boolean, pickedFiles?: File[]): Promise<Blob> {
+ if (pickedFiles) {
+ const entries = new Map(pickedFiles.map(file => [file.webkitRelativePath.replace(/^[^/]+\//, '') || file.name, file]));
+ const bytes = await packProjectAvatar(async paths => {
+ const files: Record<string, Uint8Array> = Object.create(null);
+ for (const path of paths) {
+ const file = entries.get(path);
+ if (file) files[path] = new Uint8Array(await file.arrayBuffer());
+ }
+ return files;
+ }, { name, includeSource });
+ return new Blob([new Uint8Array(bytes)], { type: 'application/octet-stream' });
+ }
+ const response = await fetch('/__studio/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ project: name, includeSource }) });
+ if (!response.ok) throw new Error((await response.json()).error);
+ return response.blob();
+}
export async function revealRepository() {
const response = await fetch('/__studio/reveal', { method: 'POST' });
if (!response.ok) throw new Error('Could not open repository.');
@@ -108,9 +133,9 @@ async function jsonFile(url: string) {
export async function openLocalProject(project: LocalProject): Promise<ProjectAssets> {
const base = baseUrl(project), version = Date.now();
const { rig, assets } = await openAvatar(base, { version, rigFile: project.rigFile });
- const sourceUrl = `${base}source.png?v=${version}`;
+ const sourceUrl = project.hasSource === false ? '' : `${base}source.png?v=${version}`;
// Check images before replacing the editor's current project.
- const urls = [sourceUrl, ...Object.entries(assets).filter(([name]) => name.endsWith('.png')).map(([, url]) => url)];
+ const urls = [sourceUrl, ...Object.entries(assets).filter(([name]) => name.endsWith('.png')).map(([, url]) => url)].filter(Boolean);
await Promise.all(urls.map(url => new Promise<void>((done, reject) => {
const image = new Image(); image.onload = () => done(); image.onerror = () => reject(new Error('Missing project image.')); image.src = url;
})));
diff --git a/src/editor/style.css b/src/editor/style.css
index 9720dec..ee94e9c 100644
--- a/src/editor/style.css
+++ b/src/editor/style.css
@@ -13,11 +13,11 @@ h2 { font-size: 14px; margin: 0; }
h3 { font-size: 12px; margin: 0; }
p { line-height: 1.5; margin: 8px 0; }
button, input, select { font: inherit; }
-button, .open-menu > summary {
+button, .open-menu > summary, .archive-menu > summary {
color: var(--ink); background: var(--surface); border: 1px solid var(--line);
border-radius: 8px; padding: 8px 12px; cursor: pointer;
}
-button:hover:not(:disabled), .open-menu > summary:hover { border-color: var(--accent); color: var(--accent); }
+button:hover:not(:disabled), .open-menu > summary:hover, .archive-menu > summary:hover { border-color: var(--accent); color: var(--accent); }
button:disabled { opacity: .45; cursor: default; }
button:focus-visible, summary:focus-visible, select:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
button.primary { color: white; background: var(--accent); border-color: var(--accent); }
@@ -33,11 +33,25 @@ button.primary:hover { color: white; background: #1d4ed8; }
.language-toggle { display: flex; border: 1px solid var(--line); border-radius: 8px; padding: 2px; background: var(--surface); }
.language-toggle button { border: 0; padding: 6px 10px; border-radius: 6px; font-size: 12px; }
.language-toggle button[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
-.open-menu { position: relative; }
-.open-menu > summary { display: flex; align-items: center; gap: 12px; list-style: none; }
+.open-menu, .archive-menu { position: relative; }
+.open-menu > summary, .archive-menu > summary { display: flex; align-items: center; gap: 12px; list-style: none; }
summary::-webkit-details-marker { display: none; }
-.project-menu { position: absolute; right: 0; top: calc(100% + 8px); z-index: 5; width: min(420px, calc(100vw - 32px)); max-height: calc(100dvh - 100px); overflow: auto; padding: 8px; border: 1px solid var(--line); border-radius: var(--radius); background: white; box-shadow: 0 8px 24px #24334818; }
-.project-menu button { display: block; width: 100%; border: 0; text-align: left; }
+.project-menu, .archive-options { position: absolute; right: 0; top: calc(100% + 8px); z-index: 5; width: min(420px, calc(100vw - 32px)); max-height: calc(100dvh - 100px); overflow: auto; padding: 8px; border: 1px solid var(--line); border-radius: var(--radius); background: white; box-shadow: 0 8px 24px #24334818; }
+.project-menu button, .archive-options button { display: block; width: 100%; border: 0; text-align: left; }
+.archive-options { padding: 16px; }
+.archive-options p, .archive-import p { margin: 8px 0; color: var(--muted); line-height: 1.6; }
+.archive-options label { display: flex; align-items: center; gap: 8px; margin: 16px 0 8px; }
+.archive-options small { display: block; color: var(--muted); line-height: 1.6; }
+.archive-options button { margin-top: 16px; text-align: center; }
+.archive-import { border: 1px dashed var(--accent); background: var(--accent-soft); border-radius: 8px; padding: 8px; margin-bottom: 8px; }
+.archive-import.dragging { outline: 2px solid var(--accent); }
+.archive-import p { padding: 0 8px; font-size: 12px; }
+.archive-feedback { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin: 12px 0; padding: 12px 16px; background: white; border: 1px solid var(--line); border-radius: 8px; }
+.archive-feedback span { white-space: pre-wrap; overflow-wrap: anywhere; }
+.archive-feedback button { flex-shrink: 0; }
+.workspace.playback-only { display: block; max-width: 640px; margin: 0 auto; }
+.workspace.playback-only .right-column { display: block; }
+.playback-notice { padding: 12px 16px; border-radius: 8px; background: var(--accent-soft); color: var(--ink); }
.project-help { padding: 0 8px; font-size: 12px; color: var(--muted); }
.project-list { max-height: 320px; overflow: auto; border-bottom: 1px solid var(--line); margin-bottom: 6px; }
.project-list button { margin: 4px 0; background: #f5f7fb; }
diff --git a/src/live/settings.ts b/src/live/settings.ts
index 59025a0..0ad234a 100644
--- a/src/live/settings.ts
+++ b/src/live/settings.ts
@@ -15,10 +15,18 @@ export function backgroundColor(value: string | null): string {
if (value && /^#?(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(value)) return `#${value.replace('#', '')}`;
return 'transparent';
}
-export function viewSettings(search: string): ViewSettings {
+export function viewSettings(search: string, origin = globalThis.location?.origin ?? 'http://localhost'): ViewSettings {
const query = new URLSearchParams(search), project = query.get('project');
+ let avatar: string | undefined;
+ try {
+ const value = query.get('avatar');
+ if (!query.has('project') && value) {
+ const url = new URL(value, origin);
+ if (url.origin === origin && /^https?:$/.test(url.protocol) && !url.username && !url.password) avatar = value;
+ }
+ } catch { /* Invalid or external URLs fall back to the sample. */ }
return { project: project && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(project) ? project : SAMPLE_PROJECT,
- ...(!query.has('project') && query.get('avatar') ? { avatar: query.get('avatar')! } : {}),
+ ...(avatar ? { avatar } : {}),
background: backgroundColor(query.get('bg')), fit: query.get('fit') === 'cover' ? 'cover' : 'contain', idle: query.get('idle') !== '0', ...(query.has('light') ? { lighting: lightingFromQuery(query) } : {}) };
}
export function streamUrl(settings: ViewSettings, origin: string): string {
diff --git a/src/project-types.ts b/src/project-types.ts
index 2e1a4d6..57f8d34 100644
--- a/src/project-types.ts
+++ b/src/project-types.ts
@@ -13,6 +13,7 @@ export interface LocalProject extends ProjectIdentity {
updatedAt: string;
hasSprites: boolean;
hasVariants: boolean;
+ hasSource?: boolean;
rigFile?: 'rig.json' | 'rig.draft.json';
}
diff --git a/src/server/local-projects.ts b/src/server/local-projects.ts
index 630e853..9854e1a 100644
--- a/src/server/local-projects.ts
+++ b/src/server/local-projects.ts
@@ -2,11 +2,13 @@ import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { homedir } from 'node:os';
import { readFile, readdir, realpath, stat, writeFile, rename, unlink, mkdir, cp, lstat, rm } from 'node:fs/promises';
-import { resolve, relative, extname, sep, isAbsolute } from 'node:path';
+import { resolve, relative, extname, sep, isAbsolute, dirname } from 'node:path';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Plugin } from 'vite';
// Vite bundles its config before applying aliases, so use the public source entry here.
-import { validateRig } from '../../packages/runtime/src/index';
+import { validateRig, unpackAvatar, validateAvatarFiles, parseManifest } from '../../packages/runtime/src/index';
+import { packProjectAvatar } from '../../packages/runtime/src/format/project-archive';
+import { checkEntryName } from '../../packages/runtime/src/format/zip';
import type { LocalProject, LocalProjectEntry } from '../project-types';
import { decodeVariants, JobError, projectJob, runTool, variantState, VARIANTS, type Runner } from './project-jobs';
@@ -38,11 +40,102 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
root = resolve(root);
const base = resolve(root, 'projects'), sample = resolve(root, 'samples/miko-qipao');
const saving = new Set<string>();
- async function readBody(req: IncomingMessage, limit = 1024 * 1024) {
- if (req.headers['content-type']?.split(';')[0] !== 'application/json') throw new HttpError(400, 'Send application/json.');
+ async function readBytes(req: IncomingMessage, limit: number) {
+ if (Number(req.headers['content-length']) > limit) throw new HttpError(413, 'Request is too large.');
const chunks: Buffer[] = []; let size = 0;
for await (const chunk of req) { size += chunk.length; if (size > limit) throw new HttpError(413, 'Request is too large.'); chunks.push(chunk); }
- try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new HttpError(400, 'Invalid JSON.'); }
+ return Buffer.concat(chunks);
+ }
+ async function readBody(req: IncomingMessage, limit = 1024 * 1024) {
+ if (req.headers['content-type']?.split(';')[0] !== 'application/json') throw new HttpError(400, 'Send application/json.');
+ const bytes = await readBytes(req, limit);
+ try { return JSON.parse(bytes.toString('utf8')); } catch { throw new HttpError(400, 'Invalid JSON.'); }
+ }
+ async function readSelected(path: string, names: Set<string>) {
+ const files: Record<string, Uint8Array> = Object.create(null);
+ for (const name of names) {
+ checkEntryName(name);
+ const file = resolve(path, name);
+ if (!inside(path, file)) throw new HttpError(400, 'Path must stay inside the project.');
+ try {
+ await checked(path, file);
+ if (!(await stat(file)).isFile()) throw new HttpError(400, `${name}: expected a regular file`);
+ files[name] = await readFile(file);
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ }
+ return files;
+ }
+ async function sourceFile(path: string) {
+ const metadata = await readSelected(path, new Set(['avatar.json']));
+ let name = 'source.png';
+ if (metadata['avatar.json']) {
+ try { name = parseManifest(JSON.parse(new TextDecoder().decode(metadata['avatar.json']))).source ?? name; checkEntryName(name); }
+ catch (error) { throw new HttpError(400, (error as Error).message); }
+ }
+ const file = resolve(path, name);
+ if (!inside(path, file)) throw new HttpError(400, 'Path must stay inside the project.');
+ if (!await exists(file)) return null;
+ await checked(path, file);
+ return (await stat(file)).isFile() ? file : null;
+ }
+ async function importArchive(bytes: Uint8Array) {
+ let files: Record<string, Uint8Array>, title: string;
+ try {
+ files = unpackAvatar(bytes);
+ const errors = validateAvatarFiles(files);
+ if (!files['avatar.json']) errors.unshift('avatar.json: required in a .mavatar archive');
+ if (errors.length) throw new Error(errors.join('\n'));
+ const metadata = JSON.parse(new TextDecoder().decode(files['avatar.json']));
+ const manifest = parseManifest(metadata);
+ title = manifest.name;
+ const paths = new Map<string, boolean>();
+ for (const name of Object.keys(files)) {
+ const parts = name.replace(/\/$/, '').split('/');
+ if (parts.some(part => !part || part === '.' || /[:<>"|?*]/.test(part) || [...part].some(char => char.charCodeAt(0) < 32) || /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw new Error(`ZIP entry ${JSON.stringify(name)}: invalid filesystem path`);
+ const normalized = parts.join('/').normalize('NFC').toLowerCase();
+ if (paths.has(normalized)) throw new Error(`ZIP entry ${JSON.stringify(name)}: conflicting filesystem path`);
+ paths.set(normalized, name.endsWith('/'));
+ }
+ for (const name of paths.keys()) {
+ const parts = name.split('/');
+ for (let i = 1; i < parts.length; i++) if (paths.get(parts.slice(0, i).join('/')) === false) throw new Error(`ZIP entry ${JSON.stringify(name)}: parent is a file`);
+ }
+ if (manifest.source) {
+ checkEntryName(manifest.source);
+ const source = manifest.source.split('/').filter(part => part && part !== '.').join('/');
+ if (files[source] && manifest.source !== 'source.png') {
+ files['source.png'] = files[source];
+ // Built images may also be used as the original; retain their playback paths.
+ if (source !== 'source.png' && !source.startsWith('built/')) delete files[source];
+ metadata.source = 'source.png';
+ if (metadata.thumbnail === manifest.source) metadata.thumbnail = 'source.png';
+ files['avatar.json'] = new TextEncoder().encode(JSON.stringify(metadata, null, 2) + '\n');
+ const normalizedErrors = validateAvatarFiles(files);
+ if (normalizedErrors.length) throw new Error(normalizedErrors.join('\n'));
+ }
+ }
+ } catch (error) { throw new HttpError(400, (error as Error).message); }
+ await mkdir(base, { recursive: true });
+ if (await realpath(base) !== base) throw new HttpError(400, 'Project root cannot redirect elsewhere.');
+ let stem = title.normalize('NFKD').replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+|[. -]+$/g, '').slice(0, 80) || 'avatar';
+ if (stem === SAMPLE || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(stem)) stem = `avatar-${stem}`;
+ let name = stem, path = resolve(base, name);
+ for (let index = 1; ; index++) {
+ try { await mkdir(path); break; }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; name = `${stem}-${index}`; path = resolve(base, name); }
+ }
+ try {
+ // Write the rig last so an in-progress import cannot appear as an openable project.
+ const names = Object.keys(files).filter(name => !name.endsWith('/')).sort((a, b) => Number(a === 'rig.json') - Number(b === 'rig.json'));
+ for (const name of names) {
+ const file = resolve(path, name);
+ if (!inside(path, file)) throw new HttpError(400, 'Path must stay inside the project.');
+ await mkdir(dirname(file), { recursive: true });
+ await checked(base, path); await checked(path, dirname(file));
+ await writeFile(file, files[name], { flag: 'wx' });
+ }
+ return await info(name);
+ } catch (error) { await checked(base, path); await rm(path, { recursive: true, force: true }); throw error; }
}
async function saveRig(path: string, rig: unknown) {
const errors = validateRig(rig);
@@ -86,7 +179,7 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
return { name, relativePath: relative(root, path).split(sep).join('/'), absolutePath: path, displayPath: displayPath(path),
rigFile: await exists(rigPath) ? 'rig.json' : 'rig.draft.json',
updatedAt: (await stat(file)).mtime.toISOString(), hasSprites: await exists(resolve(path, 'built/sprites/sprites.json')),
- hasVariants: await exists(resolve(path, 'variants')), readOnly: name === SAMPLE };
+ hasVariants: await exists(resolve(path, 'variants')), hasSource: !!await sourceFile(path), readOnly: name === SAMPLE };
}
return async (req: IncomingMessage, res: ServerResponse, next: () => void) => {
if (!req.url?.startsWith('/__studio/')) { next(); return; }
@@ -105,6 +198,25 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
});
if (parts.length === 1 && parts[0] === 'context' && req.method === 'GET') { json(200, { rootPath: root, displayRootPath: displayPath(root) }); return; }
if (parts.length === 1 && parts[0] === 'reveal' && req.method === 'POST') { await reveal(root); json(200, { path: root }); return; }
+ if (parts.length === 1 && parts[0] === 'export' && req.method === 'POST') {
+ const body = await readBody(req);
+ if (!body || typeof body.project !== 'string' || (body.includeSource !== undefined && typeof body.includeSource !== 'boolean')) throw new HttpError(400, 'Expected project and includeSource.');
+ const path = await folder(body.project);
+ if (saving.has(path)) throw new HttpError(409, 'A project operation is already in progress.');
+ saving.add(path);
+ try {
+ let bytes: Uint8Array;
+ try { bytes = await packProjectAvatar(names => readSelected(path, names), { name: body.project, includeSource: body.includeSource ?? true }); }
+ catch (error) { if (error instanceof HttpError || (error as NodeJS.ErrnoException).code) throw error; throw new HttpError(400, (error as Error).message); }
+ res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Disposition': `attachment; filename="${body.project}.mavatar"`, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
+ res.end(Buffer.from(bytes));
+ } finally { saving.delete(path); }
+ return;
+ }
+ if (parts.length === 1 && parts[0] === 'import' && req.method === 'POST') {
+ if (req.headers['content-type']?.split(';')[0] !== 'application/octet-stream') throw new HttpError(400, 'Send application/octet-stream.');
+ json(200, await importArchive(await readBytes(req, 128 * 1024 * 1024))); return;
+ }
if (parts.length === 1 && parts[0] === 'copy-sample' && req.method === 'POST') {
const rig = await readBody(req), errors = validateRig(rig);
if (errors.length) throw new HttpError(400, `Invalid rig: ${errors.join(', ')}`);
@@ -178,6 +290,7 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
}
if (req.method === 'POST' && tail.length === 1 && ['rig', 'rebuild', 'variant-requests', 'import-variants'].includes(tail[0])) {
if (name === SAMPLE) throw new HttpError(403, 'The sample is read-only.');
+ if (!await sourceFile(path)) throw new HttpError(403, 'Source image is missing. This avatar is playback-only.');
const action = tail[0], body = await readBody(req, action === 'import-variants' ? 36 * 1024 * 1024 : 1024 * 1024);
let files: ReturnType<typeof decodeVariants> = [];
if (action === 'import-variants') { try { files = decodeVariants(body); } catch (error) { throw new HttpError(400, (error as Error).message); } }
@@ -199,7 +312,8 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
const mime: Record<string, string> = { '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' };
const contentType = mime[extname(fileName)];
if (!contentType) throw new HttpError(404, 'File not available.');
- const file = await checked(path, resolve(path, ...tail));
+ const file = fileName === 'source.png' ? await sourceFile(path) : await checked(path, resolve(path, ...tail));
+ if (!file) throw new HttpError(404, 'Source image is missing.');
const bytes = await readFile(file);
res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
res.end(bytes);
diff --git a/tests/avatar-transfer.test.ts b/tests/avatar-transfer.test.ts
new file mode 100644
index 0000000..ebb3186
--- /dev/null
+++ b/tests/avatar-transfer.test.ts
@@ -0,0 +1,128 @@
+import { afterEach, beforeAll, beforeEach, expect, test } from 'vitest';
+import { mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises';
+import { dirname, resolve } from 'node:path';
+import { Readable } from 'node:stream';
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import { zipSync } from 'fflate';
+import { unpackAvatar, validateAvatarFiles } from 'mesh-avatar';
+import { packProjectAvatar } from '../packages/runtime/src/format/project-archive';
+import { sampleFiles } from '../packages/runtime/tests/avatar-fixture';
+import { localProjectMiddleware } from '../src/server/local-projects';
+
+let root: string;
+let fixture: Record<string, Uint8Array>;
+let sharedArchive: Uint8Array;
+beforeAll(async () => {
+ fixture = sampleFiles();
+ sharedArchive = await packProjectAvatar(async names => Object.fromEntries([...names].filter(name => fixture[name]).map(name => [name, fixture[name]])), { name: 'sample-miko-qipao' });
+});
+beforeEach(async () => {
+ await mkdir('projects', { recursive: true });
+ root = await mkdtemp(resolve('projects/.archive-api-test-'));
+ for (const [name, bytes] of Object.entries(fixture)) {
+ const file = resolve(root, 'samples/miko-qipao', name);
+ await mkdir(dirname(file), { recursive: true }); await writeFile(file, bytes);
+ }
+});
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+async function call(path: string, data?: unknown, headers: Record<string, string> = {}) {
+ const raw = data instanceof Uint8Array;
+ const request = Readable.from(data === undefined ? [] : [raw ? Buffer.from(data) : Buffer.from(JSON.stringify(data))]) as IncomingMessage;
+ request.url = `/__studio/${path}`; request.method = data === undefined ? 'GET' : 'POST';
+ request.headers = { host: '127.0.0.1:5173', 'content-type': raw ? 'application/octet-stream' : 'application/json', ...headers };
+ const result = { status: 0, bytes: Buffer.alloc(0), json: null as unknown };
+ const response = {
+ writeHead(status: number) { result.status = status; },
+ end(body: string | Buffer) { result.bytes = Buffer.from(body); try { result.json = JSON.parse(String(body)); } catch { /* Binary response. */ } },
+ } as unknown as ServerResponse;
+ await localProjectMiddleware(root)(request, response, () => { result.status = 404; });
+ return result;
+}
+const exported = () => call('export', { project: 'sample-miko-qipao', includeSource: true });
+
+function expectSameBytes(actual: Uint8Array, expected: Uint8Array, path: string) {
+ // Compare every byte without traversing large typed arrays as object properties.
+ expect(Buffer.from(actual).equals(expected), `${path}: all bytes must match`).toBe(true);
+}
+
+test('sample export matches the shared selection, imports without overwriting and reexports identical bytes', async () => {
+ const response = await exported(); expect(response.status).toBe(200);
+ const files = unpackAvatar(response.bytes);
+ expectSameBytes(response.bytes, sharedArchive, 'exported archive');
+ expect(files['source.png']).toBeDefined(); expect(files['rig.draft.json']).toBeUndefined();
+ expect(files['MIKO_ASSET_TERMS.md']).toBeUndefined(); expect(validateAvatarFiles(files)).toEqual([]);
+ const first = await call('import', response.bytes), second = await call('import', response.bytes);
+ expect(first.status).toBe(200); expect(second.status).toBe(200);
+ expect(first.json).toMatchObject({ name: 'Miko-qipao', hasSource: true, readOnly: false });
+ expect(second.json).toMatchObject({ name: 'Miko-qipao-1', hasSource: true });
+ const repacked = await call('export', { project: 'Miko-qipao' }); expect(repacked.status).toBe(200);
+ const repackedFiles = unpackAvatar(repacked.bytes);
+ expect(Object.keys(repackedFiles).sort()).toEqual(Object.keys(files).sort());
+ for (const [name, bytes] of Object.entries(files)) expectSameBytes(repackedFiles[name], bytes, name);
+ expectSameBytes(await readFile(resolve(root, 'samples/miko-qipao/rig.json')), fixture['rig.json'], 'sample rig.json');
+});
+
+test('source-free imports remain playable and prohibit editor writes', async () => {
+ const response = await call('export', { project: 'sample-miko-qipao', includeSource: false });
+ const files = unpackAvatar(response.bytes); expect(files['source.png']).toBeUndefined();
+ expect(validateAvatarFiles(files)).toEqual([]);
+ const imported = await call('import', response.bytes); expect(imported.status).toBe(200);
+ expect(imported.json).toMatchObject({ hasSource: false });
+ for (const action of ['rig', 'rebuild', 'variant-requests', 'import-variants']) {
+ const result = await call(`projects/Miko-qipao/${action}`, {});
+ expect(result.status).toBe(403); expect(result.json).toMatchObject({ error: expect.stringContaining('playback-only') });
+ }
+ expect((await call('projects/Miko-qipao/built/base.png')).status).toBe(200);
+});
+
+test('Studio normalizes a custom source path without changing image bytes', async () => {
+ const files = unpackAvatar(sharedArchive);
+ const source = files['source.png']; delete files['source.png'];
+ const manifest = JSON.parse(new TextDecoder().decode(files['avatar.json']));
+ files['avatar.json'] = new TextEncoder().encode(JSON.stringify({ ...manifest, name: '../../中文', source: 'original/絵.png' }));
+ files['original/絵.png'] = source;
+ const imported = await call('import', zipSync(files, { level: 0 }));
+ expect(imported.status).toBe(200); expect(imported.json).toMatchObject({ name: 'avatar', hasSource: true });
+ expectSameBytes((await call('projects/avatar/source.png')).bytes, source, 'served source.png');
+ expectSameBytes(await readFile(resolve(root, 'projects/avatar/source.png')), source, 'saved source.png');
+ expect(JSON.parse(await readFile(resolve(root, 'projects/avatar/avatar.json'), 'utf8')).source).toBe('source.png');
+ const editable = unpackAvatar((await call('export', { project: 'avatar' })).bytes);
+ expectSameBytes(editable['source.png'], source, 'exported source.png'); expect(editable['original/絵.png']).toBeUndefined();
+ const noSource = unpackAvatar((await call('export', { project: 'avatar', includeSource: false })).bytes);
+ expect(noSource['source.png']).toBeUndefined();
+ expect(noSource['original/絵.png']).toBeUndefined();
+ expect(JSON.parse(new TextDecoder().decode(noSource['avatar.json'])).source).toBeUndefined();
+});
+
+test('invalid archives return validator errors without creating projects', async () => {
+ const valid = unpackAvatar(sharedArchive);
+ const cases: [Record<string, Uint8Array>, string][] = [
+ [{ ...valid, '../escape.txt': new Uint8Array([1]) }, 'path must be relative'],
+ [{ ...valid, '/absolute.txt': new Uint8Array([1]) }, 'path must be relative'],
+ [{ ...valid, './rig.json': valid['rig.json'] }, 'invalid filesystem path'],
+ [{ ...valid, 'RIG.JSON': valid['rig.json'] }, 'conflicting filesystem path'],
+ [{ ...valid, 'rig.json/child': new Uint8Array([1]) }, 'parent is a file'],
+ [{ ...valid, 'built/base.png': new Uint8Array() }, 'built/base.png'],
+ [{ ...valid, 'rig.json': new TextEncoder().encode('{}') }, 'rig.'],
+ [Object.fromEntries(Object.entries(valid).filter(([name]) => name !== 'avatar.json')), 'avatar.json: required'],
+ ];
+ for (const [files, error] of cases) {
+ const result = await call('import', zipSync(files, { level: 0 }));
+ expect(result.status, JSON.stringify(result.json)).toBe(400); expect(result.json).toMatchObject({ error: expect.stringContaining(error) });
+ }
+ expect(await readdir(root)).toEqual(['samples']);
+});
+
+test('transfer endpoints enforce request size, origin and physical project boundaries', async () => {
+ const bytes = sharedArchive;
+ expect((await call('import', bytes, { 'content-length': String(128 * 1024 * 1024 + 1) })).status).toBe(413);
+ expect((await call('import', bytes, { origin: 'https://example.com' })).status).toBe(403);
+ expect((await call('export', { project: 'sample-miko-qipao' }, { origin: 'https://example.com' })).status).toBe(403);
+ expect((await call('export', { project: '../samples/miko-qipao' })).status).toBe(400);
+ expect((await call('export', { project: 'sample-miko-qipao', includeSource: 'yes' })).status).toBe(400);
+ await mkdir(resolve(root, 'outside')); await symlink(resolve(root, 'outside'), resolve(root, 'projects'));
+ expect((await call('import', bytes)).status).toBe(400); expect(await readdir(resolve(root, 'outside'))).toEqual([]);
+ const source = resolve(root, 'samples/miko-qipao/source.png'); await rm(source);
+ await writeFile(resolve(root, 'outside/source.png'), 'private'); await symlink(resolve(root, 'outside/source.png'), source);
+ const failure = await exported(); expect(failure.status).toBe(400); expect(failure.json).toMatchObject({ error: 'Path must stay inside the project.' });
+});
diff --git a/tests/stream-settings.test.ts b/tests/stream-settings.test.ts
index a6f8221..570d949 100644
--- a/tests/stream-settings.test.ts
+++ b/tests/stream-settings.test.ts
@@ -19,3 +19,13 @@ test('archive URLs round-trip while an explicit project takes precedence', () =>
expect(viewSettings('?project=nova&avatar=ignored.mavatar').avatar).toBeUndefined();
expect(viewSettings('?project=../bad&avatar=ignored.mavatar').avatar).toBeUndefined();
});
+
+test('stream avatar sources stay on the current server origin', () => {
+ const origin = 'http://127.0.0.1:5173';
+ for (const value of ['https://example.com/a.mavatar', '//example.com/a.mavatar', 'http://127.0.0.1:5174/a.mavatar', 'data:application/zip,abc', 'blob:http://127.0.0.1:5173/id', 'http://[email protected]:5173/a.mavatar', 'http://[invalid']) {
+ expect(viewSettings(`?avatar=${encodeURIComponent(value)}`, origin).avatar, value).toBeUndefined();
+ }
+ for (const value of ['/a.mavatar', 'a.mavatar', `${origin}/a.mavatar`]) {
+ expect(viewSettings(`?avatar=${encodeURIComponent(value)}`, origin).avatar).toBe(value);
+ }
+});
diff --git a/tools/pack-avatar.mjs b/tools/pack-avatar.mjs
index d2b9b51..4dc58d9 100644
--- a/tools/pack-avatar.mjs
+++ b/tools/pack-avatar.mjs
@@ -1,7 +1,6 @@
import { writeFile, stat } from 'node:fs/promises';
import { basename, resolve } from 'node:path';
-import { packAvatar } from '../packages/runtime/src/format/zip.ts';
-import { parseManifest } from '../packages/runtime/src/format/manifest.ts';
+import { packProjectAvatar } from '../packages/runtime/src/format/project-archive.ts';
import { readAvatarFolder } from './avatar-files.mjs';
const args = process.argv.slice(2);
@@ -19,23 +18,7 @@ if (!folder || args.includes('--help')) {
try {
const root = resolve(folder), destination = resolve(output ?? `${root}.mavatar`);
if (!(await stat(root)).isDirectory()) throw new Error('Expected a project folder.');
- const wanted = new Set(['avatar.json', 'rig.json', 'built/layers.json', 'built/sprites/sprites.json']);
- const all = await readAvatarFolder(root, wanted);
- const manifest = all['avatar.json'] ? parseManifest(JSON.parse(new TextDecoder().decode(all['avatar.json']))) : undefined;
- const source = manifest?.source ?? 'source.png', thumbnail = manifest?.thumbnail ?? 'thumbnail.png';
- // Include playback files and optional original/thumbnail, never drafts or private work files.
- wanted.add('built/base.png'); wanted.add('built/hairmask.png'); wanted.add(thumbnail);
- if (includeSource) wanted.add(source);
- for (const [metadata, prefix] of [['built/layers.json', 'built/'], ['built/sprites/sprites.json', 'built/sprites/']]) {
- if (all[metadata]) {
- const value = JSON.parse(new TextDecoder().decode(all[metadata]));
- for (const name of Object.keys(value?.layers ?? {})) wanted.add(`${prefix}${name}.png`);
- }
- }
- const files = await readAvatarFolder(root, wanted);
- let override = manifest ? undefined : { name: basename(root) };
- if (!includeSource && manifest?.source) override = { ...manifest, source: undefined };
- const bytes = packAvatar(files, { manifest: override });
+ const bytes = await packProjectAvatar(paths => readAvatarFolder(root, paths), { name: basename(root), includeSource });
await writeFile(destination, bytes, { flag: 'wx' });
console.log(`Packed ${basename(destination)} (${bytes.length} bytes${includeSource ? '' : ', source omitted'})`);
} catch (error) {