425 lines
17 KiB
TypeScript
425 lines
17 KiB
TypeScript
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import 'fake-indexeddb/auto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
import { zipSync, unzipSync, strToU8 } from 'fflate';
|
|
import {
|
|
createArchive,
|
|
openArchive,
|
|
importFiles,
|
|
safePath,
|
|
} from '@ziroeda/designer/src/platform/archive.js';
|
|
import {
|
|
DEFAULT_LIMITS,
|
|
type NativeProject,
|
|
type UploadRequest,
|
|
} from '@ziroeda/designer/src/platform/types.js';
|
|
import { MockPcbProjectApi, mockFaults } from '@ziroeda/designer/src/platform/mock-api.js';
|
|
import { WorkspaceRuntime } from '@ziroeda/designer/src/platform/runtime.js';
|
|
import { listDrafts, listPending } from '@ziroeda/designer/src/platform/storage.js';
|
|
import { missingModels, rewriteReferences } from '@ziroeda/designer/src/platform/resources.js';
|
|
import {
|
|
parseWorkspaceRoute,
|
|
workspaceHref,
|
|
validateWorkspaceFile,
|
|
} from '@ziroeda/designer/src/platform/routes.js';
|
|
import { workspaceFileSystem } from '@ziroeda/designer/src/platform/filesystem.js';
|
|
import { ParseBoard, FormatBoard } from '@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
|
|
import { PCB_VIA } from '@ziroeda/pcbnew/pcb_track.js';
|
|
import { parse } from '@ziroeda/sexpr';
|
|
import { readSchematic, serializeSchematic } from '@ziroeda/eeschema';
|
|
import { buildSheetTree, findRootFile } from '@ziroeda/eeschema/project.js';
|
|
import { getPageSettings, setPageSettingsCommand } from '@ziroeda/eeschema/tools/page_settings.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 bytes = (text: string): Uint8Array => new TextEncoder().encode(text);
|
|
const decode = (data: Uint8Array): string => new TextDecoder().decode(data);
|
|
const fixture = (): NativeProject =>
|
|
importFiles([
|
|
{ name: 'main.kicad_pro', bytes: bytes('{"meta":{"version":3}}') },
|
|
{
|
|
name: 'main.kicad_pcb',
|
|
bytes: readFileSync(
|
|
new URL('../../data/zone_fill/hatchsmall_kicad_cli.kicad_pcb', import.meta.url),
|
|
),
|
|
},
|
|
{
|
|
name: 'main.kicad_sch',
|
|
bytes: readFileSync(
|
|
new URL('../../data/eeschema/sexpr_1006/v1006.kicad_sch', import.meta.url),
|
|
),
|
|
},
|
|
{
|
|
name: 'sub.kicad_sch',
|
|
bytes: readFileSync(new URL('../../data/eeschema/sexpr_1006/sub.kicad_sch', import.meta.url)),
|
|
},
|
|
{ name: 'models3d/custom.step', bytes: new Uint8Array([0, 128, 255, 17, 0, 192]) },
|
|
{ name: 'images/logo.png', bytes: new Uint8Array([137, 80, 78, 71, 0, 255]) },
|
|
]);
|
|
const signatureRequest = async (
|
|
native = fixture(),
|
|
expectedVersion = 0,
|
|
): Promise<{ bytes: Uint8Array; request: UploadRequest }> => {
|
|
const archive = await createArchive(native, 'test');
|
|
return {
|
|
bytes: archive.bytes,
|
|
request: {
|
|
fileName: 'project.zip',
|
|
sizeBytes: archive.bytes.length,
|
|
sha256: archive.sha256,
|
|
expectedVersion,
|
|
clientOperationId: crypto.randomUUID(),
|
|
archiveFormat: 'vibemake-pcb-project+zip',
|
|
manifestVersion: 1,
|
|
},
|
|
};
|
|
};
|
|
beforeEach(() => {
|
|
mockFaults.current = 'none';
|
|
});
|
|
|
|
describe('PCB native archive and path boundaries', () => {
|
|
it('preserves binary resources and native designs through save, reload and a second edit', async () => {
|
|
const native = fixture();
|
|
native.directories = ['empty'];
|
|
const archive = await createArchive(native, 'build-test');
|
|
const opened = await openArchive(archive.bytes);
|
|
for (const file of native.files)
|
|
expect(opened.files.find((f) => f.name === file.name)?.bytes).toEqual(
|
|
new Uint8Array(file.bytes),
|
|
);
|
|
expect(opened.directories).toEqual(['empty']);
|
|
const sch = readSchematic(
|
|
parse(decode(opened.files.find((f) => f.name === 'main.kicad_sch')!.bytes)),
|
|
);
|
|
const changed = setPageSettingsCommand({
|
|
...getPageSettings(sch),
|
|
title: 'reopened and edited',
|
|
}).apply(sch);
|
|
const saved = serializeSchematic(changed);
|
|
expect(readSchematic(parse(saved)).titleBlock?.title).toBe('reopened and edited');
|
|
const pcb = ParseBoard(decode(opened.files.find((f) => f.name === 'main.kicad_pcb')!.bytes));
|
|
pcb.GetTitleBlock().SetTitle('board edited after reopen');
|
|
const track = pcb.Tracks().find((item) => !(item instanceof PCB_VIA))!;
|
|
const width = track.GetWidth() + 10000;
|
|
track.SetWidth(width);
|
|
const via = pcb.Tracks().find((item) => item instanceof PCB_VIA) as PCB_VIA;
|
|
const drill = via.GetDrillValue() + 5000;
|
|
via.SetDrill(drill);
|
|
const footprint = pcb.Footprints()[0]!;
|
|
const position = { x: footprint.GetPosition().x + 100000, y: footprint.GetPosition().y };
|
|
footprint.SetPosition(position);
|
|
const zone = pcb.Zones()[0]!;
|
|
zone.SetLocalClearance(250000);
|
|
const count = pcb.Tracks().length;
|
|
expect(FormatBoard(pcb)).toContain('(kicad_pcb');
|
|
expect(ParseBoard(FormatBoard(pcb)).Tracks().length).toBe(count);
|
|
expect(ParseBoard(FormatBoard(pcb)).GetTitleBlock().GetTitle()).toBe(
|
|
'board edited after reopen',
|
|
);
|
|
const edited = {
|
|
...opened,
|
|
files: opened.files.map((file) =>
|
|
file.name === 'main.kicad_pcb' ? { ...file, bytes: bytes(FormatBoard(pcb)) } : file,
|
|
),
|
|
};
|
|
const secondOpen = await openArchive((await createArchive(edited, 'build-test')).bytes);
|
|
const continued = ParseBoard(
|
|
decode(secondOpen.files.find((f) => f.name === 'main.kicad_pcb')!.bytes),
|
|
);
|
|
expect(
|
|
continued
|
|
.Tracks()
|
|
.find((t) => t.m_Uuid === track.m_Uuid)
|
|
?.GetWidth(),
|
|
).toBe(width);
|
|
expect(
|
|
(continued.Tracks().find((item) => item.m_Uuid === via.m_Uuid) as PCB_VIA).GetDrillValue(),
|
|
).toBe(drill);
|
|
expect(
|
|
continued
|
|
.Footprints()
|
|
.find((f) => f.m_Uuid === footprint.m_Uuid)
|
|
?.GetPosition(),
|
|
).toEqual(position);
|
|
expect(
|
|
continued
|
|
.Zones()
|
|
.find((z) => z.m_Uuid === zone.m_Uuid)
|
|
?.GetLocalClearance(),
|
|
).toBe(250000);
|
|
});
|
|
it('rejects traversal, normalized collisions, truncated archives and tampered manifests', async () => {
|
|
for (const path of ['../x', '/x', 'a/../../x', 'a\\x', 'a//x', 'C:x'])
|
|
expect(() => safePath(path)).toThrow();
|
|
expect(() =>
|
|
importFiles([
|
|
{ name: 'a.kicad_pcb', bytes: bytes('(kicad_pcb)') },
|
|
{ name: 'A.kicad_pcb', bytes: bytes('(kicad_pcb)') },
|
|
]),
|
|
).toThrow();
|
|
const archive = await createArchive(fixture(), 'test');
|
|
await expect(openArchive(archive.bytes.slice(0, -1))).rejects.toThrow();
|
|
const entries = unzipSync(archive.bytes);
|
|
entries['models3d/custom.step'] = new Uint8Array([12]);
|
|
await expect(openArchive(zipSync(entries))).rejects.toMatchObject({
|
|
code: 'PCB_HASH_MISMATCH',
|
|
});
|
|
await expect(
|
|
openArchive(zipSync({ '../bad.kicad_pcb': strToU8('(kicad_pcb)') }), DEFAULT_LIMITS, false),
|
|
).rejects.toMatchObject({ code: 'PCB_UNSAFE_PATH' });
|
|
});
|
|
it('retains distinct same-name hierarchy documents', () => {
|
|
const sheet = (name: string, id: string): string =>
|
|
`(sheet (at 10 10) (size 20 20) (uuid "${id}") (property "Sheetname" "${id}" (at 10 10 0)) (property "Sheetfile" "${name}" (at 10 30 0)))`;
|
|
const sch = (extra = '') =>
|
|
readSchematic(
|
|
parse(
|
|
`(kicad_sch (version 20250114) (generator "eeschema") (uuid "root") (paper "A4") (lib_symbols) ${extra})`,
|
|
),
|
|
);
|
|
const docs = new Map([
|
|
['root.kicad_sch', sch(sheet('a/same.kicad_sch', 'a') + sheet('b/same.kicad_sch', 'b'))],
|
|
['a/same.kicad_sch', sch()],
|
|
['b/same.kicad_sch', sch()],
|
|
]);
|
|
expect(findRootFile(docs)).toBe('root.kicad_sch');
|
|
expect(buildSheetTree(docs, 'root.kicad_sch').children.map((s) => s.file)).toEqual([
|
|
'a/same.kicad_sch',
|
|
'b/same.kicad_sch',
|
|
]);
|
|
});
|
|
it('warns about missing models, keeps placement data and rewrites relative paths', async () => {
|
|
const native = fixture();
|
|
native.files.push({
|
|
name: 'parts/local.kicad_mod',
|
|
bytes: bytes('(footprint "test" (model "../missing.step" (offset (xyz 1 2 3))))'),
|
|
});
|
|
const missing = missingModels(native);
|
|
expect(missing).toContainEqual({
|
|
kind: 'model3d',
|
|
sourcePath: 'parts/local.kicad_mod',
|
|
reference: '../missing.step',
|
|
});
|
|
native.unresolvedDependencies = missing;
|
|
const reopened = await openArchive((await createArchive(native, 'test')).bytes);
|
|
expect(reopened.unresolvedDependencies).toEqual(missing);
|
|
expect(
|
|
rewriteReferences(
|
|
'(model "../models3d/custom.step" (offset (xyz 1 2 3)))',
|
|
'parts/a.kicad_mod',
|
|
'deep/parts/a.kicad_mod',
|
|
(p) => p,
|
|
),
|
|
).toBe('(model "../../models3d/custom.step" (offset (xyz 1 2 3)))');
|
|
});
|
|
it('uses project code and validated relative paths in deep links', () => {
|
|
const route = parseWorkspaceRoute('/pcb/p/pcb_123/schematic?f=a%2Fsame.kicad_sch');
|
|
expect(workspaceHref(route)).toBe('/pcb/p/pcb_123/schematic?f=a%2Fsame.kicad_sch');
|
|
expect(() => parseWorkspaceRoute('/pcb/p/pcb_123/pcb?f=..%2Fsecret')).toThrow();
|
|
expect(() =>
|
|
validateWorkspaceFile(
|
|
parseWorkspaceRoute('/pcb/p/pcb_123/pcb?f=missing.kicad_pcb'),
|
|
fixture(),
|
|
),
|
|
).toThrow();
|
|
expect(() =>
|
|
validateWorkspaceFile(parseWorkspaceRoute('/pcb/p/pcb_123/pcb?f=main.kicad_sch'), fixture()),
|
|
).toThrow();
|
|
});
|
|
});
|
|
|
|
describe('mock persistence and save transactions', () => {
|
|
it('rejects an active tool immediately without locking, preparing or uploading, and saves after it ends', async () => {
|
|
const owner = crypto.randomUUID(),
|
|
api = new MockPcbProjectApi(owner),
|
|
p = await api.create('Safe boundary', crypto.randomUUID());
|
|
const runtime = new WorkspaceRuntime(owner, p, fixture(), api, DEFAULT_LIMITS, 'test');
|
|
const sign = vi.spyOn(api, 'sign');
|
|
const phases: string[] = [];
|
|
runtime.subscribe(() => phases.push(runtime.getSnapshot().phase));
|
|
let busy = true;
|
|
const flush = vi.fn(async () => {
|
|
expect(runtime.getSnapshot().inputLocked).toBe(true);
|
|
runtime.writeFile('command-result.bin', new Uint8Array([7]));
|
|
});
|
|
runtime.register('tool', {
|
|
isBusy: () => busy,
|
|
flush,
|
|
});
|
|
// No clock advancement: this must reject before waiting for a command or
|
|
// starting network work, even when the tool remains active indefinitely.
|
|
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
|
try {
|
|
await expect(runtime.capture()).rejects.toMatchObject({ code: 'SNAPSHOT_BUSY' });
|
|
await expect(runtime.save()).rejects.toMatchObject({ code: 'SNAPSHOT_BUSY' });
|
|
await expect(runtime.save()).rejects.toMatchObject({ code: 'SNAPSHOT_BUSY' });
|
|
expect(runtime.getSnapshot()).toMatchObject({ phase: 'blocked', inputLocked: false });
|
|
expect(phases).not.toContain('preparing');
|
|
expect(flush).not.toHaveBeenCalled();
|
|
expect(sign).not.toHaveBeenCalled();
|
|
expect(runtime.dirty).toBe(true);
|
|
busy = false;
|
|
await runtime.save();
|
|
expect(flush).toHaveBeenCalledOnce();
|
|
expect(sign).toHaveBeenCalledOnce();
|
|
expect(runtime.getSnapshot()).toMatchObject({
|
|
phase: 'saved',
|
|
inputLocked: false,
|
|
error: null,
|
|
});
|
|
const document = await api.document(p.pcbProjectCode);
|
|
const opened = await openArchive(await api.download(document, DEFAULT_LIMITS));
|
|
expect(opened.files.find((f) => f.name === 'command-result.bin')?.bytes).toEqual(
|
|
new Uint8Array([7]),
|
|
);
|
|
} finally {
|
|
runtime.revoke();
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
it('awaits concurrent private writes and rejects a snapshot when a native write failed', async () => {
|
|
const owner = crypto.randomUUID(),
|
|
api = new MockPcbProjectApi(owner),
|
|
p = await api.create('Libraries', crypto.randomUUID());
|
|
const runtime = new WorkspaceRuntime(owner, p, fixture(), api, DEFAULT_LIMITS, 'test');
|
|
const fs = workspaceFileSystem(runtime);
|
|
await Promise.all([
|
|
fs.write('/Symbols/One.kicad_sym', bytes('one')),
|
|
fs.write('/Symbols/Two.kicad_sym', bytes('two')),
|
|
]);
|
|
expect((await fs.list('/Symbols')).map((entry) => entry.name).sort()).toEqual([
|
|
'One.kicad_sym',
|
|
'Two.kicad_sym',
|
|
]);
|
|
let resolve!: () => void;
|
|
const gate = new Promise<void>((done) => {
|
|
resolve = done;
|
|
});
|
|
const write = runtime.queueWrite('delayed', async () => {
|
|
await gate;
|
|
runtime.writeFile('delayed.bin', new Uint8Array([255]));
|
|
});
|
|
const capture = runtime.capture();
|
|
resolve();
|
|
await write;
|
|
expect((await capture).project.files.find((f) => f.name === 'delayed.bin')?.bytes).toEqual(
|
|
new Uint8Array([255]),
|
|
);
|
|
await expect(
|
|
runtime.queueWrite('broken', async () => {
|
|
throw new Error('disk full');
|
|
}),
|
|
).rejects.toThrow('disk full');
|
|
await expect(runtime.capture()).rejects.toThrow('disk full');
|
|
runtime.revoke();
|
|
});
|
|
it('isolates owners, allows duplicate names, retries creation and confirmation idempotently', async () => {
|
|
const owner = crypto.randomUUID(),
|
|
api = new MockPcbProjectApi(owner);
|
|
const id = crypto.randomUUID(),
|
|
p = await api.create('Duplicate', id);
|
|
expect((await api.create('Duplicate', id)).pcbProjectCode).toBe(p.pcbProjectCode);
|
|
const other = await api.create('Duplicate', crypto.randomUUID());
|
|
expect(other.pcbProjectCode).not.toBe(p.pcbProjectCode);
|
|
await expect(
|
|
new MockPcbProjectApi(crypto.randomUUID()).get(p.pcbProjectCode),
|
|
).rejects.toMatchObject({ code: 'NOT_FOUND' });
|
|
const packed = await signatureRequest(),
|
|
sig = await api.sign(p.pcbProjectCode, packed.request);
|
|
await api.upload(sig, packed.bytes);
|
|
mockFaults.current = 'confirmation-lost';
|
|
await expect(api.commit(p.pcbProjectCode, sig.uploadCode)).rejects.toThrow();
|
|
const receipt = await api.commit(p.pcbProjectCode, sig.uploadCode);
|
|
expect(receipt.version).toBe(1);
|
|
expect(await api.sign(p.pcbProjectCode, packed.request)).toEqual(sig);
|
|
expect(await api.commit(p.pcbProjectCode, sig.uploadCode)).toEqual(receipt);
|
|
expect((await new MockPcbProjectApi(owner).document(p.pcbProjectCode)).version).toBe(1);
|
|
});
|
|
it('commits one of two concurrent versions and rejects saves to a deleted project', async () => {
|
|
const api = new MockPcbProjectApi(crypto.randomUUID()),
|
|
p = await api.create('Race', crypto.randomUUID());
|
|
const a = await signatureRequest(),
|
|
b = await signatureRequest();
|
|
const sa = await api.sign(p.pcbProjectCode, a.request),
|
|
sb = await api.sign(p.pcbProjectCode, b.request);
|
|
await api.upload(sa, a.bytes);
|
|
await api.upload(sb, b.bytes);
|
|
const outcomes = await Promise.allSettled([
|
|
api.commit(p.pcbProjectCode, sa.uploadCode),
|
|
api.commit(p.pcbProjectCode, sb.uploadCode),
|
|
]);
|
|
expect(outcomes.filter((o) => o.status === 'fulfilled')).toHaveLength(1);
|
|
expect(outcomes.filter((o) => o.status === 'rejected')).toHaveLength(1);
|
|
await api.remove(p.pcbProjectCode);
|
|
await expect(api.commit(p.pcbProjectCode, sa.uploadCode)).rejects.toMatchObject({
|
|
code: 'NOT_FOUND',
|
|
});
|
|
});
|
|
it('deduplicates saves and only acknowledges the snapshot uploaded, preserving later edits', async () => {
|
|
const api = new MockPcbProjectApi(crypto.randomUUID()),
|
|
p = await api.create('Runtime', crypto.randomUUID());
|
|
const runtime = new WorkspaceRuntime(
|
|
crypto.randomUUID(),
|
|
p,
|
|
fixture(),
|
|
api,
|
|
DEFAULT_LIMITS,
|
|
'test',
|
|
);
|
|
runtime.modified();
|
|
const upload = api.upload.bind(api);
|
|
api.upload = async (signature, data) => {
|
|
runtime.writeFile('late.bin', new Uint8Array([99]));
|
|
await upload(signature, data);
|
|
};
|
|
const save = runtime.save();
|
|
expect(runtime.save()).toBe(save);
|
|
await save;
|
|
expect(runtime.dirty).toBe(true);
|
|
const doc = await api.document(p.pcbProjectCode),
|
|
opened = await openArchive(await api.download(doc, DEFAULT_LIMITS));
|
|
expect(opened.files.some((f) => f.name === 'late.bin')).toBe(false);
|
|
api.upload = upload;
|
|
await runtime.save();
|
|
expect(runtime.dirty).toBe(false);
|
|
expect((await api.document(p.pcbProjectCode)).version).toBe(2);
|
|
runtime.revoke();
|
|
});
|
|
it('recovers an unknown confirmation without duplicating a version or leaving a false dirty draft', async () => {
|
|
const owner = crypto.randomUUID(),
|
|
api = new MockPcbProjectApi(owner),
|
|
p = await api.create('Recover', crypto.randomUUID());
|
|
const runtime = new WorkspaceRuntime(owner, p, fixture(), api, DEFAULT_LIMITS, 'test');
|
|
runtime.modified();
|
|
await runtime.persistDraft();
|
|
mockFaults.current = 'confirmation-lost';
|
|
await expect(runtime.save()).rejects.toThrow();
|
|
const records = await listPending(owner, p.pcbProjectCode);
|
|
expect(records).toHaveLength(1);
|
|
runtime.revoke();
|
|
const recovery = new WorkspaceRuntime(
|
|
owner,
|
|
await api.get(p.pcbProjectCode),
|
|
fixture(),
|
|
api,
|
|
DEFAULT_LIMITS,
|
|
'test',
|
|
);
|
|
recovery.adoptPending(records[0]!);
|
|
const flush = vi.fn();
|
|
recovery.register('active-tool', { isBusy: () => true, flush });
|
|
await recovery.save();
|
|
// Retrying an existing upload only confirms its immutable snapshot. An
|
|
// active tool must not prevent that acknowledgement or flush new edits.
|
|
expect(flush).not.toHaveBeenCalled();
|
|
expect((await api.get(p.pcbProjectCode)).version).toBe(1);
|
|
expect(await listPending(owner, p.pcbProjectCode)).toHaveLength(0);
|
|
expect(await listDrafts(owner, p.pcbProjectCode)).toHaveLength(0);
|
|
recovery.revoke();
|
|
});
|
|
});
|