442 lines
17 KiB
TypeScript
442 lines
17 KiB
TypeScript
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import 'fake-indexeddb/auto';
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import { HttpPcbProjectApi, platformRequest } from '@ziroeda/designer/src/platform/api.js';
|
|
import { createArchive, importFiles, openArchive } from '@ziroeda/designer/src/platform/archive.js';
|
|
import { WorkspaceRuntime } from '@ziroeda/designer/src/platform/runtime.js';
|
|
import { listPending } from '@ziroeda/designer/src/platform/storage.js';
|
|
import { parseWorkspaceRoute, workspaceHref } from '@ziroeda/designer/src/platform/routes.js';
|
|
import {
|
|
DEFAULT_LIMITS,
|
|
platformTime,
|
|
type AuthRecord,
|
|
type PcbProject,
|
|
type SaveReceipt,
|
|
type UploadRequest,
|
|
} from '@ziroeda/designer/src/platform/types.js';
|
|
|
|
vi.mock('@ziroeda/designer/src/platform/archive-client.js', async () => {
|
|
const archive = await import('@ziroeda/designer/src/platform/archive.js');
|
|
return { packProject: archive.createArchive, unpackProject: archive.openArchive };
|
|
});
|
|
const fetcher = vi.fn<typeof fetch>();
|
|
const time = '2026-11-05T12:30:00';
|
|
const project = (): PcbProject => ({
|
|
pcbProjectCode: 'pcb:opaque-code',
|
|
name: '控制板',
|
|
description: '',
|
|
coverUrl: null,
|
|
hasDocument: false,
|
|
version: 0,
|
|
fileName: '',
|
|
sizeBytes: 0,
|
|
savedAt: null,
|
|
createdAt: time,
|
|
updatedAt: time,
|
|
});
|
|
const reply = (data: unknown, status = 200, code = 'OK', headers: Record<string, string> = {}) =>
|
|
new Response(JSON.stringify({ code, message: code, data, requestId: 'request-1' }), {
|
|
status,
|
|
headers,
|
|
});
|
|
const identity = (): AuthRecord => ({
|
|
token: 'platform-token',
|
|
user: { userCode: crypto.randomUUID() },
|
|
expiresAt: Date.now() + 86400000,
|
|
});
|
|
function client(record = identity()) {
|
|
const controller = new AbortController();
|
|
const current = { value: record as AuthRecord | null };
|
|
const api = new HttpPcbProjectApi(record, () => current.value, controller.signal);
|
|
return { api, current, controller, record };
|
|
}
|
|
const request = (sizeBytes = 3): UploadRequest => ({
|
|
fileName: 'project.zip',
|
|
sizeBytes,
|
|
expectedVersion: 0,
|
|
sha256: 'a'.repeat(64),
|
|
clientOperationId: crypto.randomUUID(),
|
|
archiveFormat: 'vibemake-pcb-project+zip',
|
|
manifestVersion: 1,
|
|
});
|
|
const signature = () => ({
|
|
uploadCode: 'batch-1',
|
|
uploadUrl: 'https://bucket.example.test/',
|
|
expiresAt: '2026-11-05T12:45:00',
|
|
formFields: {
|
|
key: 'vibemake_dev/pcb-projects/p/b/project.zip',
|
|
policy: 'opaque-policy',
|
|
Signature: 'opaque-signature',
|
|
},
|
|
});
|
|
beforeEach(() => {
|
|
vi.stubGlobal('location', { hostname: '127.0.0.1', origin: 'http://127.0.0.1:8091' });
|
|
vi.stubGlobal('window', new EventTarget());
|
|
vi.stubGlobal('fetch', fetcher);
|
|
fetcher.mockReset();
|
|
});
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
describe('published PCB workspace HTTP contract', () => {
|
|
it('uses the eight documented project endpoints without a capabilities request or undocumented POST fields', async () => {
|
|
const { api } = client();
|
|
expect((await api.capabilities()).maxArchiveBytes).toBe(268435456);
|
|
expect(fetcher).not.toHaveBeenCalled();
|
|
fetcher.mockResolvedValueOnce(reply(project()));
|
|
const created = await api.create('控制板', 'local-create-id');
|
|
expect(created.createdAt).toBe('2026-11-05T04:30:00.000Z');
|
|
expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({
|
|
name: '控制板',
|
|
description: '',
|
|
});
|
|
fetcher.mockResolvedValueOnce(reply({ items: [project()], total: 1, page: 2, size: 20 }));
|
|
expect((await api.list(2, '控制')).total).toBe(1);
|
|
expect(String(fetcher.mock.calls[1]![0])).toContain('page=2&size=20&keyword=');
|
|
fetcher.mockResolvedValueOnce(reply(project()));
|
|
await api.get(created.pcbProjectCode);
|
|
fetcher.mockResolvedValueOnce(reply({ ...project(), name: '新名字' }));
|
|
expect((await api.rename(created.pcbProjectCode, '新名字')).name).toBe('新名字');
|
|
fetcher.mockResolvedValueOnce(reply(signature()));
|
|
const signed = await api.sign(created.pcbProjectCode, request());
|
|
expect(signed.expiresAt).toBe('2026-11-05T04:45:00.000Z');
|
|
expect(JSON.parse(String(fetcher.mock.calls[4]![1]?.body))).toEqual({
|
|
fileName: 'project.zip',
|
|
sizeBytes: 3,
|
|
expectedVersion: 0,
|
|
});
|
|
fetcher.mockResolvedValueOnce(
|
|
reply({ pcbProjectCode: created.pcbProjectCode, version: 1, savedAt: time }),
|
|
);
|
|
expect(await api.commit(created.pcbProjectCode, signed.uploadCode)).toEqual({
|
|
pcbProjectCode: created.pcbProjectCode,
|
|
version: 1,
|
|
savedAt: '2026-11-05T04:30:00.000Z',
|
|
});
|
|
expect(JSON.parse(String(fetcher.mock.calls[5]![1]?.body))).toEqual({ uploadCode: 'batch-1' });
|
|
fetcher.mockResolvedValueOnce(reply(null));
|
|
await api.remove(created.pcbProjectCode);
|
|
for (const [url, init] of fetcher.mock.calls) {
|
|
expect(String(url)).toMatch(/^\/api\/pcb\/workspace\/projects/);
|
|
expect(init?.cache).toBe('no-store');
|
|
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer platform-token');
|
|
}
|
|
const route = parseWorkspaceRoute('/pcb/p/pcb%3Aopaque-code/pcb');
|
|
expect(route.code).toBe(created.pcbProjectCode);
|
|
expect(workspaceHref(route)).toBe('/pcb/p/pcb%3Aopaque-code/pcb');
|
|
});
|
|
|
|
it('uploads all signed fields unchanged, with a ZIP file last and no platform credentials or JSON parsing', async () => {
|
|
const { api } = client();
|
|
fetcher.mockResolvedValueOnce(new Response('', { status: 200 }));
|
|
await api.upload(signature(), new Uint8Array([0, 128, 255]));
|
|
const [url, init] = fetcher.mock.calls[0]!;
|
|
expect(url).toBe(signature().uploadUrl);
|
|
expect(init?.credentials).toBe('omit');
|
|
expect(init?.headers).toBeUndefined();
|
|
const entries = [...(init!.body as FormData).entries()];
|
|
expect(entries.slice(0, -1)).toEqual(Object.entries(signature().formFields));
|
|
expect(entries.at(-1)?.[0]).toBe('file');
|
|
const file = entries.at(-1)![1] as File;
|
|
expect(file.type).toBe('application/zip');
|
|
expect(new Uint8Array(await file.arrayBuffer())).toEqual(new Uint8Array([0, 128, 255]));
|
|
});
|
|
|
|
it('reads a public document without server-only hashes and uses its version instead of stale project metadata', async () => {
|
|
const { api } = client();
|
|
const native = importFiles([
|
|
{ name: 'main.kicad_pcb', bytes: new TextEncoder().encode('(kicad_pcb)') },
|
|
{ name: 'models3d/a.step', bytes: new Uint8Array([0, 255, 128]) },
|
|
]);
|
|
const packed = await createArchive(native, 'test');
|
|
fetcher.mockResolvedValueOnce(reply({ ...project(), hasDocument: true, version: 1 }));
|
|
const metadata = await api.get(project().pcbProjectCode);
|
|
fetcher.mockResolvedValueOnce(
|
|
reply({
|
|
downloadUrl: 'https://cdn.example.test/project.zip',
|
|
expiresAt: null,
|
|
version: 2,
|
|
fileName: 'project.zip',
|
|
sizeBytes: packed.bytes.length,
|
|
}),
|
|
);
|
|
const document = await api.document(metadata.pcbProjectCode);
|
|
fetcher.mockResolvedValueOnce(new Response(new Uint8Array(packed.bytes)));
|
|
const opened = await openArchive(await api.download(document, DEFAULT_LIMITS));
|
|
expect(opened.files.find((f) => f.name === 'models3d/a.step')?.bytes).toEqual(
|
|
new Uint8Array([0, 255, 128]),
|
|
);
|
|
const init = fetcher.mock.calls[2]![1]!;
|
|
expect(init.credentials).toBe('omit');
|
|
expect(init.headers).toBeUndefined();
|
|
const runtime = new WorkspaceRuntime(
|
|
'user',
|
|
{ ...metadata, version: document.version },
|
|
opened,
|
|
api,
|
|
DEFAULT_LIMITS,
|
|
'test',
|
|
);
|
|
expect(runtime.baseVersion).toBe(2);
|
|
runtime.writeFile('notes.txt', new Uint8Array([99]));
|
|
expect(runtime.dirty).toBe(true);
|
|
runtime.revoke();
|
|
});
|
|
|
|
it('rejects truncated downloads, non-HTTPS storage URLs and malformed signatures', async () => {
|
|
const { api } = client();
|
|
const document = {
|
|
pcbProjectCode: 'p',
|
|
version: 1,
|
|
fileName: 'project.zip',
|
|
sizeBytes: 3,
|
|
downloadUrl: 'https://cdn.example.test/project.zip',
|
|
expiresAt: null,
|
|
} as const;
|
|
fetcher.mockResolvedValueOnce(new Response(new Uint8Array([1])));
|
|
await expect(api.download(document, DEFAULT_LIMITS)).rejects.toMatchObject({
|
|
code: 'PCB_HASH_MISMATCH',
|
|
});
|
|
fetcher.mockResolvedValueOnce(
|
|
reply({ ...signature(), uploadUrl: 'http://untrusted.example.test/' }),
|
|
);
|
|
await expect(api.sign('p', request())).rejects.toMatchObject({ code: 'BAD_RESPONSE' });
|
|
fetcher.mockResolvedValueOnce(reply({ ...signature(), formFields: [] }));
|
|
await expect(api.sign('p', request())).rejects.toMatchObject({ code: 'BAD_RESPONSE' });
|
|
await expect(api.sign('p', { ...request(), expectedVersion: 1.5 })).rejects.toMatchObject({
|
|
code: 'PCB_INVALID_FILE',
|
|
});
|
|
});
|
|
|
|
it('surfaces 401 without clearing identity and ignores stale account responses', async () => {
|
|
const { api, current, record } = client();
|
|
const unauthorized = vi.fn();
|
|
window.addEventListener('vm:pcb:unauthorized', unauthorized);
|
|
fetcher.mockResolvedValueOnce(reply(null, 401, 'UNAUTHORIZED'));
|
|
await expect(api.get('p')).rejects.toMatchObject({
|
|
code: 'UNAUTHORIZED',
|
|
requestId: 'request-1',
|
|
});
|
|
expect(current.value).toBe(record);
|
|
expect(unauthorized).toHaveBeenCalledOnce();
|
|
fetcher.mockImplementationOnce(async () => {
|
|
current.value = identity();
|
|
return reply(project());
|
|
});
|
|
await expect(api.get('p')).rejects.toMatchObject({ code: 'STALE_IDENTITY' });
|
|
});
|
|
|
|
it('honors Retry-After without automatically replaying a write request', async () => {
|
|
vi.useFakeTimers();
|
|
const { api } = client();
|
|
fetcher.mockResolvedValueOnce(reply(null, 429, 'RATE_LIMITED', { 'Retry-After': '5' }));
|
|
await expect(api.commit('p', 'u')).rejects.toMatchObject({
|
|
code: 'RATE_LIMITED',
|
|
retryAfterMs: 5000,
|
|
});
|
|
await expect(api.commit('p', 'u')).rejects.toMatchObject({ code: 'RATE_LIMITED' });
|
|
expect(fetcher).toHaveBeenCalledOnce();
|
|
vi.advanceTimersByTime(5000);
|
|
fetcher.mockResolvedValueOnce(reply({ pcbProjectCode: 'p', version: 1, savedAt: time }));
|
|
await expect(api.commit('p', 'u')).resolves.toHaveProperty('version', 1);
|
|
});
|
|
|
|
it('does not assume backend create idempotency after an unknown POST result', async () => {
|
|
const { api } = client();
|
|
fetcher.mockRejectedValueOnce(new TypeError('connection lost'));
|
|
await expect(api.create('控制板', 'form-1')).rejects.toMatchObject({
|
|
code: 'UNKNOWN_CREATION',
|
|
});
|
|
await expect(api.create('控制板', 'form-1')).rejects.toMatchObject({
|
|
code: 'UNKNOWN_CREATION',
|
|
});
|
|
expect(fetcher).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it('normalizes Shanghai timestamps while preserving explicit offsets and reports server fault codes', async () => {
|
|
expect(platformTime('2026-11-05 12:30:00')).toBe('2026-11-05T04:30:00.000Z');
|
|
expect(platformTime('2026-11-05T04:30:00Z')).toBe('2026-11-05T04:30:00.000Z');
|
|
for (const [status, code] of [
|
|
[404, 'PCB_DOCUMENT_NOT_FOUND'],
|
|
[409, 'PCB_VERSION_CONFLICT'],
|
|
[503, 'PCB_STORAGE_UNAVAILABLE'],
|
|
] as const) {
|
|
fetcher.mockResolvedValueOnce(reply(null, status, code));
|
|
await expect(
|
|
platformRequest('/pcb/workspace/projects', 'platform-token'),
|
|
).rejects.toMatchObject({ code, status });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('real HTTP save and recovery', () => {
|
|
function server() {
|
|
const { api, record } = client();
|
|
const metadata = project();
|
|
const archive = { bytes: undefined as Uint8Array | undefined };
|
|
let saved: SaveReceipt | undefined;
|
|
let loseConfirmation = false;
|
|
let uploads = 0;
|
|
let signs = 0;
|
|
const commitCodes: string[] = [];
|
|
fetcher.mockImplementation(async (input, init) => {
|
|
const url = String(input);
|
|
if (url.endsWith('/uploads/signature')) {
|
|
signs++;
|
|
return reply({ ...signature(), uploadCode: `batch-${signs}` });
|
|
}
|
|
if (url === signature().uploadUrl) {
|
|
uploads++;
|
|
archive.bytes = new Uint8Array(
|
|
await ((init!.body as FormData).get('file') as File).arrayBuffer(),
|
|
);
|
|
return new Response('', { status: 200 });
|
|
}
|
|
if (url.endsWith('/document') && init?.method === 'PUT') {
|
|
commitCodes.push(JSON.parse(String(init.body)).uploadCode);
|
|
if (!archive.bytes) return reply(null, 409, 'PCB_FILE_MISSING');
|
|
saved ??= { pcbProjectCode: metadata.pcbProjectCode, version: 1, savedAt: time };
|
|
if (loseConfirmation) {
|
|
loseConfirmation = false;
|
|
throw new TypeError('response lost');
|
|
}
|
|
return reply(saved);
|
|
}
|
|
throw new Error(`Unexpected request: ${url}`);
|
|
});
|
|
const native = importFiles([
|
|
{ name: 'main.kicad_pcb', bytes: new TextEncoder().encode('(kicad_pcb)') },
|
|
]);
|
|
const runtime = new WorkspaceRuntime(
|
|
record.user.userCode,
|
|
metadata,
|
|
native,
|
|
api,
|
|
DEFAULT_LIMITS,
|
|
'test',
|
|
);
|
|
return {
|
|
api,
|
|
metadata,
|
|
runtime,
|
|
record,
|
|
archive,
|
|
commitCodes,
|
|
native,
|
|
loseNextConfirmation() {
|
|
loseConfirmation = true;
|
|
},
|
|
counts() {
|
|
return { uploads, signs };
|
|
},
|
|
};
|
|
}
|
|
it('accepts a minimal real receipt and acknowledges only the snapshot uploaded', async () => {
|
|
const s = server();
|
|
const upload = s.api.upload.bind(s.api);
|
|
s.api.upload = async (sig, bytes) => {
|
|
s.runtime.writeFile('late.bin', new Uint8Array([255]));
|
|
await upload(sig, bytes);
|
|
};
|
|
try {
|
|
await s.runtime.save();
|
|
expect(s.runtime.getSnapshot().phase).toBe('dirty');
|
|
expect(s.runtime.baseVersion).toBe(1);
|
|
expect(s.counts()).toEqual({ uploads: 1, signs: 1 });
|
|
expect(s.commitCodes).toEqual(['batch-1']);
|
|
expect((await openArchive(s.archive.bytes!)).files.some((f) => f.name === 'late.bin')).toBe(
|
|
false,
|
|
);
|
|
} finally {
|
|
s.runtime.revoke();
|
|
}
|
|
});
|
|
it('recovers a lost confirmation with the original batch, without uploading again or incrementing twice', async () => {
|
|
const s = server();
|
|
s.runtime.modified();
|
|
s.loseNextConfirmation();
|
|
await expect(s.runtime.save()).rejects.toThrow('response lost');
|
|
const pending = await listPending(s.record.user.userCode, s.metadata.pcbProjectCode);
|
|
expect(pending).toHaveLength(1);
|
|
s.runtime.revoke();
|
|
const recovered = new WorkspaceRuntime(
|
|
s.record.user.userCode,
|
|
s.metadata,
|
|
s.native,
|
|
s.api,
|
|
DEFAULT_LIMITS,
|
|
'test',
|
|
);
|
|
try {
|
|
recovered.adoptPending(pending[0]!);
|
|
await recovered.save();
|
|
expect(recovered.baseVersion).toBe(1);
|
|
expect(s.counts()).toEqual({ uploads: 1, signs: 1 });
|
|
expect(s.commitCodes).toEqual(['batch-1', 'batch-1']);
|
|
expect(await listPending(s.record.user.userCode, s.metadata.pcbProjectCode)).toHaveLength(0);
|
|
} finally {
|
|
recovered.revoke();
|
|
}
|
|
});
|
|
it('keeps local design and batch on a version conflict', async () => {
|
|
const s = server();
|
|
const fetchSaved = fetcher.getMockImplementation()!;
|
|
fetcher.mockImplementation(async (url, init) =>
|
|
String(url).endsWith('/document')
|
|
? reply(null, 409, 'PCB_VERSION_CONFLICT')
|
|
: fetchSaved(url, init),
|
|
);
|
|
try {
|
|
await expect(s.runtime.save()).rejects.toMatchObject({ code: 'PCB_VERSION_CONFLICT' });
|
|
expect(s.runtime.getSnapshot().phase).toBe('conflict');
|
|
expect(s.runtime.baseVersion).toBe(0);
|
|
expect(s.runtime.hasPending).toBe(true);
|
|
expect(s.runtime.nativeProject().files).toHaveLength(1);
|
|
} finally {
|
|
s.runtime.revoke();
|
|
}
|
|
});
|
|
it('confirms the original batch when the OSS upload response disappears after storing the ZIP', async () => {
|
|
const s = server();
|
|
const upload = s.api.upload.bind(s.api);
|
|
s.api.upload = async (signed, bytes) => {
|
|
await upload(signed, bytes);
|
|
throw new TypeError('upload response lost');
|
|
};
|
|
try {
|
|
await s.runtime.save();
|
|
expect(s.runtime.getSnapshot().phase).toBe('saved');
|
|
expect(s.counts()).toEqual({ uploads: 1, signs: 1 });
|
|
expect(s.commitCodes).toEqual(['batch-1']);
|
|
} finally {
|
|
s.runtime.revoke();
|
|
}
|
|
});
|
|
it.each([
|
|
'PCB_UPLOAD_EXPIRED',
|
|
'PCB_FILE_SIZE_MISMATCH',
|
|
])('replaces the batch only after an explicit %s response, preserving the snapshot', async (code) => {
|
|
const s = server();
|
|
const fetchSaved = fetcher.getMockImplementation()!;
|
|
let rejected = false;
|
|
fetcher.mockImplementation(async (url, init) => {
|
|
if (String(url).endsWith('/document') && !rejected) {
|
|
rejected = true;
|
|
return reply(null, 409, code);
|
|
}
|
|
return fetchSaved(url, init);
|
|
});
|
|
try {
|
|
await s.runtime.save();
|
|
expect(s.runtime.baseVersion).toBe(1);
|
|
expect(s.counts()).toEqual({ uploads: 2, signs: 2 });
|
|
expect(s.commitCodes).toEqual(['batch-2']);
|
|
expect(await listPending(s.record.user.userCode, s.metadata.pcbProjectCode)).toHaveLength(0);
|
|
} finally {
|
|
s.runtime.revoke();
|
|
}
|
|
});
|
|
});
|