471 lines
25 KiB
JavaScript
471 lines
25 KiB
JavaScript
import { test, beforeEach } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
|
|
globalThis.location = { hostname: 'localhost', href: 'http://localhost/cad/', origin: 'http://localhost' };
|
|
const storage = new Map();
|
|
globalThis.localStorage = {
|
|
getItem: (key) => storage.get(key) ?? null,
|
|
setItem: (key, value) => storage.set(key, value),
|
|
};
|
|
const { CadApi, auth, downloadSource, uploadSource, sha256, projectCoverUrl, MAX_COVER_BYTES } = await import('../../js/cad/api.js');
|
|
const { CadAgentRateLimiter } = await import('../../js/cad/agent-rate-limit.js');
|
|
const { validName, filename, CAD } = await import('../../js/cad/config.js');
|
|
const { errorText, setLocale } = await import('../../js/cad/i18n.js');
|
|
|
|
beforeEach(() => { storage.clear(); auth.set({ token: 'token-a', user: { userCode: 'owner-a' } }); });
|
|
|
|
test('CAD project covers use the documented signature and anonymous OSS form upload', async () => {
|
|
const calls = [], bytes = new Uint8Array([137, 80, 78, 71]);
|
|
const api = new CadApi({ fetcher: async (url, options) => {
|
|
calls.push({ url, options });
|
|
if (calls.length === 1) return Response.json({ code: 'OK', data: {
|
|
uploadUrl: 'https://oss.example/upload', formFields: { key: 'project-covers/fixed.png', policy: 'signed', 'x-oss-forbid-overwrite': 'true' },
|
|
coverUrl: 'https://cdn.example/project-covers/fixed.png',
|
|
} });
|
|
return new Response(null, { status: 200 });
|
|
} });
|
|
assert.equal(await api.uploadCover({ bytes, mimeType: 'image/png' }), 'https://cdn.example/project-covers/fixed.png');
|
|
assert.equal(calls[0].url, '/api/uploads/project-covers/signature');
|
|
assert.deepEqual(JSON.parse(calls[0].options.body), { contentType: 'image/png', fileSize: 4 });
|
|
assert.equal(calls[0].options.headers.Authorization, 'Bearer token-a');
|
|
const upload = calls[1];
|
|
assert.equal(upload.url, 'https://oss.example/upload');
|
|
assert.equal(upload.options.credentials, 'omit');
|
|
assert.equal(upload.options.headers, undefined);
|
|
assert.deepEqual([...upload.options.body.keys()], ['key', 'policy', 'x-oss-forbid-overwrite', 'file']);
|
|
const file = upload.options.body.get('file');
|
|
assert.equal(file.name, 'cover.png');
|
|
assert.equal(file.type, 'image/png');
|
|
assert.deepEqual(new Uint8Array(await file.arrayBuffer()), bytes);
|
|
});
|
|
|
|
test('CAD metadata accepts, displays and clears HTTPS covers without changing document fields', async () => {
|
|
const calls = [], url = 'https://cdn.example/project-covers/plate.png';
|
|
const api = new CadApi({ fetcher: async (path, options) => {
|
|
calls.push({ path, options });
|
|
const body = JSON.parse(options.body);
|
|
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad/a', version: 4, savedAt: '2026-11-05 10:00:00', coverUrl: body.coverUrl || null } });
|
|
} });
|
|
assert.equal((await api.create('Plate', '', url)).coverUrl, url);
|
|
assert.deepEqual(JSON.parse(calls[0].options.body), { name: 'Plate', description: '', coverUrl: url });
|
|
assert.equal((await api.setCover('cad/a', url)).version, 4);
|
|
assert.equal(calls[1].path, '/api/cad/workspace/projects/cad%2Fa');
|
|
assert.equal(calls[1].options.method, 'PATCH');
|
|
assert.deepEqual(JSON.parse(calls[1].options.body), { coverUrl: url });
|
|
assert.equal((await api.setCover('cad/a', '')).coverUrl, null);
|
|
assert.deepEqual(JSON.parse(calls[2].options.body), { coverUrl: '' });
|
|
});
|
|
|
|
test('invalid cover links and oversized or unsupported images are rejected before upload', async () => {
|
|
let requests = 0;
|
|
const api = new CadApi({ fetcher: async () => { requests++; throw new Error('must not fetch'); } });
|
|
for (const url of ['javascript:alert(1)', 'data:image/png;base64,AAAA', 'http://cdn.example/a.png', '/project-covers/a.png', 'https://user:secret@cdn.example/a.png', 'https://cdn.example/' + 'x'.repeat(2048)]) {
|
|
assert.equal(projectCoverUrl(url), null);
|
|
await assert.rejects(api.setCover('p', url), { code: 'BAD_COVER' });
|
|
}
|
|
for (const cover of [{ bytes: new Uint8Array(), mimeType: 'image/png' },
|
|
{ bytes: new Uint8Array(MAX_COVER_BYTES + 1), mimeType: 'image/png' },
|
|
{ bytes: new Uint8Array([1]), mimeType: 'image/svg+xml' }]) await assert.rejects(api.uploadCover(cover), { code: 'BAD_COVER' });
|
|
assert.equal(requests, 0);
|
|
});
|
|
|
|
test('cover upload cannot patch or publish a response after the account changes', async () => {
|
|
const api = new CadApi({ fetcher: async (url) => {
|
|
if (url.includes('/signature')) return Response.json({ code: 'OK', data: {
|
|
uploadUrl: 'https://oss.example/upload', formFields: { key: 'cover.png' }, coverUrl: 'https://cdn.example/cover.png',
|
|
} });
|
|
auth.set({ token: 'token-b', user: { userCode: 'owner-b' } });
|
|
return new Response(null, { status: 200 });
|
|
} });
|
|
await assert.rejects(api.uploadCover({ bytes: new Uint8Array([1]), mimeType: 'image/png' }), { code: 'STALE_IDENTITY' });
|
|
assert.equal(auth.token, 'token-b');
|
|
});
|
|
|
|
test('workspace API uses the documented root, bearer token, no-store and query names', async () => {
|
|
let requested;
|
|
const api = new CadApi({ fetcher: async (url, options) => {
|
|
requested = { url, options };
|
|
return Response.json({ code: 'OK', data: { items: [], page: 2, size: 10, total: 0 } });
|
|
} });
|
|
await api.list({ keyword: 'a+b', page: 2, pageSize: 10 });
|
|
assert.equal(requested.url, '/api/cad/workspace/projects?page=2&size=10&keyword=a%2Bb');
|
|
assert.equal(requested.options.headers.Authorization, 'Bearer token-a');
|
|
assert.equal(requested.options.cache, 'no-store');
|
|
assert.equal(requested.options.headers['Accept-Language'], 'zh-CN');
|
|
});
|
|
|
|
const aiLimits = {
|
|
requestBytes: 4194304, imageBytes: 1048576, imageMaxEdge: 2048, imagesPerRequest: 2,
|
|
textBytes: 262144, toolResultTextBytes: 32768, historyItems: 256,
|
|
maxModelCallsPerTurn: 12, maxChangesPerTurn: 24, requestTimeoutSeconds: 60, requestsPerMinute: 30,
|
|
};
|
|
|
|
test('CAD AI capabilities use the authenticated endpoint and reject incompatible protocols', async () => {
|
|
const api = new CadApi({ fetcher: async (url, options) => {
|
|
assert.equal(url, '/api/cad/ai/capabilities');
|
|
assert.equal(options.headers.Authorization, 'Bearer token-a');
|
|
return Response.json({ code: 'OK', data: {
|
|
enabled: true, protocolVersion: 'cad-agent-v1', model: 'doubao-test',
|
|
tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }],
|
|
limits: aiLimits,
|
|
} });
|
|
} });
|
|
assert.equal((await api.aiCapabilities()).model, 'doubao-test');
|
|
const incompatible = new CadApi({ fetcher: async () => Response.json({ code: 'OK', data: {
|
|
enabled: true, protocolVersion: 'cad-agent-v2', model: 'model', tools: [], limits: aiLimits,
|
|
} }) });
|
|
await assert.rejects(incompatible.aiCapabilities(), { code: 'BAD_RESPONSE' });
|
|
});
|
|
|
|
test('CAD AI capabilities accept absent, zero or larger backend limits without inventing frontend quotas', async () => {
|
|
const limits = { ...aiLimits };
|
|
delete limits.maxModelCallsPerTurn;
|
|
delete limits.maxChangesPerTurn;
|
|
const capabilities = (limits) => ({
|
|
enabled: true, protocolVersion: 'cad-agent-v1', model: 'model',
|
|
tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }], limits,
|
|
});
|
|
for (const value of [limits, {}, { ...limits, imagesPerRequest: 0, requestTimeoutSeconds: null, maxModelCallsPerTurn: 0, maxChangesPerTurn: 0 },
|
|
{ ...limits, imagesPerRequest: 5, historyItems: 1024, requestBytes: 8388608, textBytes: 524288 }]) {
|
|
const api = new CadApi({ fetcher: async () => Response.json({ code: 'OK', data: capabilities(value) }) });
|
|
assert.deepEqual((await api.aiCapabilities()).limits, value);
|
|
}
|
|
const invalid = new CadApi({ fetcher: async () => Response.json({
|
|
code: 'OK', data: capabilities({ ...limits, requestTimeoutSeconds: -1 }),
|
|
}) });
|
|
await assert.rejects(invalid.aiCapabilities(), { code: 'BAD_RESPONSE' });
|
|
});
|
|
|
|
test('CAD AI chat streams authenticated same-origin SSE without query credentials', async () => {
|
|
const controller = new AbortController();
|
|
const body = { protocolVersion: 'cad-agent-v1', documentSessionCode: 'doc-1', turnCode: 'turn-1', history: [], context: { documentRevision: '4' } };
|
|
const api = new CadApi({ fetcher: async (url, options) => {
|
|
assert.equal(url, '/api/cad/ai/chat');
|
|
assert.equal(options.method, 'POST');
|
|
assert.equal(options.headers.Authorization, 'Bearer token-a');
|
|
assert.equal(options.headers.Accept, 'text/event-stream');
|
|
assert.equal(options.credentials, 'omit');
|
|
assert.equal(options.cache, 'no-store');
|
|
assert.equal(options.redirect, 'error');
|
|
assert.equal(options.signal, controller.signal);
|
|
assert.deepEqual(JSON.parse(options.body), body);
|
|
return new Response('event: completed\\n\\n', { headers: { 'Content-Type': 'text/event-stream' } });
|
|
} });
|
|
const response = await api.aiChat(body, controller.signal);
|
|
assert.equal(response.headers.get('content-type'), 'text/event-stream');
|
|
});
|
|
|
|
test('a CAD AI response from an old identity is discarded', async () => {
|
|
const api = new CadApi({ fetcher: async () => {
|
|
auth.set({ token: 'token-b', user: { userCode: 'owner-b' } });
|
|
return new Response(null, { status: 200 });
|
|
} });
|
|
await assert.rejects(api.aiChat({}), { code: 'STALE_IDENTITY' });
|
|
assert.equal(auth.token, 'token-b');
|
|
});
|
|
|
|
function rateClock() {
|
|
let time = Date.UTC(2026, 10, 4);
|
|
const records = new Map();
|
|
const options = {
|
|
now: () => time,
|
|
sleep: async (ms, signal) => { signal?.throwIfAborted(); time += ms; },
|
|
storage: { getItem: (key) => records.get(key) ?? null, setItem: (key, value) => records.set(key, value) },
|
|
locks: null,
|
|
};
|
|
return { options, advance: (ms) => { time += ms; }, limiter: () => new CadAgentRateLimiter(options) };
|
|
}
|
|
|
|
test('all CAD AI calls, including tool continuations, stay under 30 per rolling minute and are evenly paced', async () => {
|
|
const clock = rateClock(), sent = [], started = [];
|
|
const api = new CadApi({ agentRateLimiter: clock.limiter(), fetcher: async (url) => {
|
|
if (url.endsWith('/capabilities')) return Response.json({ code: 'OK', data: {
|
|
enabled: true, protocolVersion: 'cad-agent-v1', model: 'model',
|
|
tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }],
|
|
limits: { ...aiLimits, requestsPerMinute: 30 },
|
|
} });
|
|
sent.push(clock.options.now());
|
|
assert.equal(started.length, sent.length, 'network timeout starts with dispatch');
|
|
return new Response(null);
|
|
} });
|
|
await api.aiCapabilities();
|
|
for (let i = 0; i < 65; i++) await api.aiChat({ turnCode: 'same-turn', history: i ? [{ type: 'toolResult' }] : [] },
|
|
undefined, () => started.push(clock.options.now()));
|
|
assert.equal(sent.length, 65, 'rate limiting queues long turns without a total call cap');
|
|
for (let i = 1; i < sent.length; i++) assert.ok(sent[i] - sent[i - 1] >= 2050);
|
|
for (const end of sent) assert.ok(sent.filter((time) => time > end - 60_000 && time <= end).length <= 30);
|
|
assert.deepEqual(started, sent);
|
|
});
|
|
|
|
test('CAD AI pacing uses higher backend limits and adds no rate limit when absent or zero', async () => {
|
|
for (const rate of [120, 0, undefined]) {
|
|
const clock = rateClock(), sent = [];
|
|
const limits = { ...aiLimits, requestsPerMinute: rate };
|
|
const api = new CadApi({ agentRateLimiter: clock.limiter(), fetcher: async (url) => {
|
|
if (url.endsWith('/capabilities')) return Response.json({ code: 'OK', data: {
|
|
enabled: true, protocolVersion: 'cad-agent-v1', model: 'model',
|
|
tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }], limits,
|
|
} });
|
|
sent.push(clock.options.now()); return new Response(null);
|
|
} });
|
|
await api.aiCapabilities();
|
|
for (let i = 0; i < 130; i++) await api.aiChat({});
|
|
for (let i = 1; i < sent.length; i++) assert.equal(sent[i] - sent[i - 1], rate ? 550 : 0);
|
|
if (rate) for (const end of sent) assert.ok(sent.filter((time) => time > end - 60_000 && time <= end).length <= rate);
|
|
}
|
|
});
|
|
|
|
test('CAD AI pacing follows a stricter advertised rate', async () => {
|
|
const clock = rateClock(), sent = [];
|
|
const api = new CadApi({ agentRateLimiter: clock.limiter(), fetcher: async (url) => {
|
|
if (url.endsWith('/capabilities')) return Response.json({ code: 'OK', data: {
|
|
enabled: true, protocolVersion: 'cad-agent-v1', model: 'model',
|
|
tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }],
|
|
limits: { ...aiLimits, requestsPerMinute: 5 },
|
|
} });
|
|
sent.push(clock.options.now()); return new Response(null);
|
|
} });
|
|
await api.aiCapabilities();
|
|
for (let i = 0; i < 7; i++) await api.aiChat({});
|
|
for (let i = 1; i < sent.length; i++) assert.ok(sent[i] - sent[i - 1] >= 12_050);
|
|
});
|
|
|
|
test('new CAD API clients and refreshed limiter instances share the account request history', async () => {
|
|
const clock = rateClock(), sent = [], limiter = clock.limiter();
|
|
const fetcher = async () => { sent.push(clock.options.now()); return new Response(null); };
|
|
for (const [project, rateLimiter] of [['first', limiter], ['second', limiter], ['refreshed', clock.limiter()]]) {
|
|
const api = new CadApi({ fetcher, agentRateLimiter: rateLimiter });
|
|
api.agentRequestsPerMinute = 30;
|
|
await api.aiChat({ cadProjectCode: project });
|
|
}
|
|
assert.deepEqual(sent.map((time) => time - sent[0]), [0, 2050, 4100]);
|
|
});
|
|
|
|
test('Stop cancels queued CAD AI calls before fetch or its timeout starts and consumes no request slot', async () => {
|
|
const clock = rateClock(), controller = new AbortController();
|
|
let sent = 0, started = 0;
|
|
const api = new CadApi({ agentRateLimiter: new CadAgentRateLimiter({ ...clock.options, sleep: undefined }),
|
|
fetcher: async () => { sent++; return new Response(null); } });
|
|
api.agentRequestsPerMinute = 30;
|
|
const start = () => { started++; };
|
|
await api.aiChat({}, undefined, start);
|
|
const queued = api.aiChat({}, controller.signal, start);
|
|
const rejected = assert.rejects(queued, { name: 'AbortError' });
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
assert.equal(started, 1);
|
|
controller.abort();
|
|
await rejected;
|
|
assert.equal(sent, 1);
|
|
clock.advance(2050);
|
|
await api.aiChat({}, undefined, start);
|
|
assert.equal(sent, 2);
|
|
});
|
|
|
|
test('a queued CAD AI call rechecks identity before dispatch', async () => {
|
|
const clock = rateClock();
|
|
let sent = 0;
|
|
const limiter = new CadAgentRateLimiter({ ...clock.options, sleep: async (ms) => {
|
|
clock.advance(ms);
|
|
auth.set({ token: 'token-b', user: { userCode: 'owner-b' } });
|
|
} });
|
|
const api = new CadApi({ agentRateLimiter: limiter, fetcher: async () => { sent++; return new Response(null); } });
|
|
api.agentRequestsPerMinute = 30;
|
|
await api.aiChat({});
|
|
await assert.rejects(api.aiChat({}), { code: 'STALE_IDENTITY' });
|
|
assert.equal(sent, 1);
|
|
assert.equal(auth.token, 'token-b');
|
|
});
|
|
|
|
test('429 Retry-After pauses future CAD AI requests without replaying a modelling request', async () => {
|
|
for (const kind of ['seconds', 'date', 'absent']) {
|
|
const clock = rateClock(), sent = [];
|
|
const header = kind === 'seconds' ? '90' : kind === 'date' ? new Date(clock.options.now() + 5000).toUTCString() : null;
|
|
const fetcher = async () => {
|
|
sent.push(clock.options.now());
|
|
return sent.length === 1 ? new Response(null, { status: 429, headers: header ? { 'Retry-After': header } : {} }) : new Response(null);
|
|
};
|
|
const response = await new CadApi({ fetcher, agentRateLimiter: clock.limiter() }).aiChat({});
|
|
assert.equal(response.status, 429);
|
|
assert.equal(sent.length, 1, 'never automatically replay a rejected request');
|
|
await new CadApi({ fetcher, agentRateLimiter: clock.limiter() }).aiChat({});
|
|
assert.ok(sent[1] - sent[0] >= (kind === 'seconds' ? 90_050 : kind === 'date' ? 5050 : 60_550));
|
|
assert.equal(auth.token, 'token-a');
|
|
}
|
|
});
|
|
|
|
test('CAD AI pacing survives unavailable browser storage within the shared transport', async () => {
|
|
const clock = rateClock(), sent = [];
|
|
const limiter = new CadAgentRateLimiter({ ...clock.options, storage: { getItem: () => { throw new Error('unavailable'); } } });
|
|
const fetcher = async () => { sent.push(clock.options.now()); return new Response(null); };
|
|
const api = new CadApi({ fetcher, agentRateLimiter: limiter });
|
|
api.agentRequestsPerMinute = 30;
|
|
await api.aiChat({});
|
|
await api.aiChat({});
|
|
assert.equal(sent[1] - sent[0], 2050);
|
|
});
|
|
|
|
test('project records use opaque codes and Shanghai timestamps are parsed with +08:00', async () => {
|
|
const api = new CadApi({ fetcher: async (url) => {
|
|
assert.equal(url, '/api/cad/workspace/projects/code%2Fwith%2Fslash');
|
|
return Response.json({ code: 'OK', data: {
|
|
cadProjectCode: 'code/with/slash', name: 'Plate', description: '', hasDocument: true, version: 4,
|
|
fileName: 'Plate.sc', sizeBytes: 3, savedAt: '2026-11-03 12:00:00', createdAt: '2026-11-03 10:00:00',
|
|
updatedAt: '2026-11-03 12:00:00',
|
|
} });
|
|
} });
|
|
const project = await api.get('code/with/slash');
|
|
assert.equal(project.id, 'code/with/slash');
|
|
assert.equal(project.version, 4);
|
|
assert.equal(project.lastSavedAt, '2026-11-03T04:00:00.000Z');
|
|
});
|
|
|
|
test('create, rename, signature and commit use their exact request fields and HTTP methods', async () => {
|
|
const calls = [];
|
|
const api = new CadApi({ fetcher: async (url, options) => {
|
|
calls.push({ url, options });
|
|
if (options.method === 'POST') {
|
|
if (url.endsWith('/uploads/signature')) return Response.json({ code: 'OK', data: {
|
|
uploadCode: 'upload-code', uploadUrl: 'https://oss.example/post', formFields: { key: 'fixed', policy: 'signed' },
|
|
expiresAt: '2026-11-03 12:15:00',
|
|
} });
|
|
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-code', name: 'Plate', description: '', version: 0 } });
|
|
}
|
|
if (options.method === 'PATCH') return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-code', name: 'New', description: '', version: 0 } });
|
|
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-code', version: 1, savedAt: '2026-11-03 12:00:00' } });
|
|
} });
|
|
await api.create('Plate');
|
|
await api.rename('cad-code', 'New');
|
|
await api.signUpload('cad-code', { fileName: 'Plate.sc', sizeBytes: 3, expectedVersion: 0 });
|
|
const receipt = await api.commit('cad-code', 'upload-code');
|
|
assert.deepEqual(JSON.parse(calls[0].options.body), { name: 'Plate', description: '' });
|
|
assert.deepEqual(JSON.parse(calls[1].options.body), { name: 'New' });
|
|
assert.equal(calls[1].options.method, 'PATCH');
|
|
assert.deepEqual(JSON.parse(calls[2].options.body), { fileName: 'Plate.sc', sizeBytes: 3, expectedVersion: 0 });
|
|
assert.equal(calls[2].url, '/api/cad/workspace/projects/cad-code/uploads/signature');
|
|
assert.equal(calls[3].options.method, 'PUT');
|
|
assert.equal(calls[3].url, '/api/cad/workspace/projects/cad-code/document');
|
|
assert.deepEqual(JSON.parse(calls[3].options.body), { uploadCode: 'upload-code' });
|
|
assert.equal(receipt.version, 1);
|
|
});
|
|
|
|
test('old 401 cannot sign out a newly logged-in account', async () => {
|
|
const api = new CadApi({ fetcher: async () => {
|
|
auth.set({ token: 'token-b', user: { userCode: 'owner-b' } });
|
|
return Response.json({ code: 'UNAUTHORIZED' }, { status: 401 });
|
|
} });
|
|
await assert.rejects(api.get('cad-code'), { code: 'STALE_IDENTITY' });
|
|
assert.equal(auth.token, 'token-b');
|
|
});
|
|
|
|
test('project deletion sends the opaque code with DELETE and no request body, and accepts null data', async () => {
|
|
const api = new CadApi({ fetcher: async (url, options) => {
|
|
assert.equal(url, '/api/cad/workspace/projects/code%2Fwith%2Fslash');
|
|
assert.equal(options.method, 'DELETE');
|
|
assert.equal(options.body, undefined);
|
|
assert.equal(options.headers.Authorization, 'Bearer token-a');
|
|
assert.equal(options.headers['Content-Type'], undefined);
|
|
return Response.json({ code: 'OK', message: 'OK', data: null, requestId: 'delete-test' });
|
|
} });
|
|
assert.equal(await api.delete('code/with/slash'), null);
|
|
});
|
|
|
|
test('failed deletion preserves the backend error and never reports success', async () => {
|
|
const api = new CadApi({ fetcher: async () => Response.json({
|
|
code: 'RATE_LIMITED', message: 'Try later', data: null, requestId: 'delete-limited',
|
|
}, { status: 429 }) });
|
|
await assert.rejects(api.delete('cad-code'), { code: 'RATE_LIMITED', status: 429, requestId: 'delete-limited' });
|
|
});
|
|
|
|
test('current 401 clears identity while network failures preserve it', async () => {
|
|
let api = new CadApi({ fetcher: async () => { throw new Error('network'); } });
|
|
await assert.rejects(api.get('cad-code'));
|
|
assert.equal(auth.token, 'token-a');
|
|
api = new CadApi({ fetcher: async () => Response.json({ code: 'UNAUTHORIZED' }, { status: 401 }) });
|
|
await assert.rejects(api.get('cad-code'), { status: 401 });
|
|
assert.equal(auth.token, null);
|
|
});
|
|
|
|
test('empty document uses its documented error code', async () => {
|
|
const api = new CadApi({ fetcher: async () => Response.json({ code: 'CAD_DOCUMENT_NOT_FOUND' }, { status: 404 }) });
|
|
await assert.rejects(api.document('cad-code'), { code: 'CAD_DOCUMENT_NOT_FOUND', status: 404 });
|
|
});
|
|
|
|
test('document accepts a permanent public URL with null expiry and its own snapshot version', async () => {
|
|
const api = new CadApi({ fetcher: async () => Response.json({ code: 'OK', data: {
|
|
downloadUrl: 'https://cdn.example/cad-projects/part.sc', expiresAt: null,
|
|
version: 7, fileName: 'part.sc', sizeBytes: 3,
|
|
} }) });
|
|
const source = await api.document('cad-code');
|
|
assert.equal(source.expiresAt, null);
|
|
assert.equal(source.version, 7);
|
|
assert.equal(source.downloadUrl, 'https://cdn.example/cad-projects/part.sc');
|
|
});
|
|
|
|
test('public OSS/CDN access denial is not a download signature expiry or platform sign-out', async (t) => {
|
|
t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 403 }));
|
|
await assert.rejects(downloadSource({ sizeBytes: 3, expiresAt: null,
|
|
downloadUrl: 'https://cdn.example/cad-projects/part.sc' }, 10), { code: 'DOWNLOAD_FORBIDDEN' });
|
|
assert.equal(auth.token, 'token-a');
|
|
});
|
|
|
|
test('downloads validate the exact byte count and omit bearer credentials', async (t) => {
|
|
const bytes = new Uint8Array([1, 2, 3]);
|
|
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
|
assert.equal(url, 'https://oss.example/immutable');
|
|
assert.equal(options.credentials, 'omit');
|
|
assert.equal(options.headers, undefined);
|
|
return new Response(bytes);
|
|
});
|
|
const result = await downloadSource({ sizeBytes: 3, downloadUrl: 'https://oss.example/immutable' }, 10);
|
|
assert.deepEqual(result, bytes);
|
|
await assert.rejects(downloadSource({ sizeBytes: 4, downloadUrl: 'https://oss.example/immutable' }, 10), { code: 'BAD_DESIGN' });
|
|
});
|
|
|
|
test('OSS POST preserves signed fields and appends the raw .sc file last', async (t) => {
|
|
const formFields = { key: 'fixed', policy: 'signed', 'Content-Type': 'application/octet-stream',
|
|
'Content-Disposition': 'attachment; filename="Plate.sc"', 'x-oss-forbid-overwrite': 'true' };
|
|
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
|
assert.equal(url, 'https://oss.example/post');
|
|
assert.equal(options.headers, undefined);
|
|
assert.equal(options.credentials, 'omit');
|
|
const fields = [...options.body];
|
|
assert.deepEqual(fields.slice(0, -1), Object.entries(formFields));
|
|
assert.equal(options.body.has('x-oss-object-acl'), false);
|
|
assert.equal(fields.at(-1)[0], 'file');
|
|
assert.equal(fields.at(-1)[1].size, 3);
|
|
assert.equal(fields.at(-1)[1].name, 'Plate.sc');
|
|
return new Response(null, { status: 200 });
|
|
});
|
|
await uploadSource({ uploadCode: 'u', uploadUrl: 'https://oss.example/post', formFields },
|
|
new Uint8Array([1, 2, 3]), 'Plate.sc');
|
|
});
|
|
|
|
test('OSS upload 403 does not claim that the upload batch expired', async (t) => {
|
|
t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 403 }));
|
|
await assert.rejects(uploadSource({ uploadCode: 'u', uploadUrl: 'https://oss.example/post', formFields: {} },
|
|
new Uint8Array([1, 2, 3]), 'Plate.sc'), { code: 'UPLOAD_FAILED' });
|
|
assert.equal(auth.token, 'token-a');
|
|
});
|
|
|
|
test('storage configuration errors explain the administrator action in both languages', () => {
|
|
try {
|
|
for (const language of ['zh', 'en']) {
|
|
setLocale(language, false);
|
|
for (const code of ['CAD_STORAGE_UNAVAILABLE', 'CAD_STORAGE_UNSAFE']) {
|
|
assert.match(errorText({ code }), language === 'zh' ? /管理员/ : /administrator/);
|
|
assert.doesNotMatch(errorText({ code }), /private|私有|独立.*Bucket/);
|
|
}
|
|
assert.match(errorText({ code: 'DOWNLOAD_FORBIDDEN' }), /OSS\/CDN/);
|
|
}
|
|
} finally { setLocale('zh', false); }
|
|
});
|
|
|
|
test('project names and 256 MiB limit match the workspace contract', () => {
|
|
assert.equal(CAD.maxSourceBytes, 268435456);
|
|
assert.equal(validName('机械臂支架'), true);
|
|
assert.equal(validName('a'.repeat(100)), true);
|
|
for (const name of ['', 'a\nb', 'a'.repeat(101)]) assert.equal(validName(name), false);
|
|
assert.equal(filename('../../机械臂'), '_.._机械臂.sc');
|
|
assert.equal(sha256 instanceof Function, true);
|
|
});
|