408 lines
22 KiB
JavaScript
408 lines
22 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { createProjectClient } from '../src/client.js';
|
|
import { importProject } from '../src/transfer.js';
|
|
import { strToU8, zipSync } from 'fflate';
|
|
|
|
const project = id => ({id,folderId:id,name:id,path:`/projects/${id}.isap`,projectIdentity:id,formatVersion:1});
|
|
function fixture(options = {}) {
|
|
const writes = [];
|
|
const files = new Map(['one','two','three'].map(id => [`${project(id).path}/project.json`,{
|
|
formatVersion:1,id,name:id,createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{kept:true}
|
|
}]));
|
|
const saved = new Map();
|
|
const directories = new Set(['/projects']);
|
|
const bridge = {
|
|
async invoke(command,args) {
|
|
if (command.startsWith('localstorage_')) {
|
|
assert.equal(Object.hasOwn(args, 'workspaceId'), false, 'Private storage scope is set by the host');
|
|
assert.equal(Object.hasOwn(args, 'groupId'), false, 'Private storage scope is set by the host');
|
|
}
|
|
if (options.invoke) { const result = options.invoke(command,args); if (result !== undefined) return result; }
|
|
if (command === 'filesystem_get_files') {
|
|
const path = args.files[0].path;
|
|
return {items:[files.has(path) ? {status:'ok',path,source:'dashboard',authoritative:true,text:JSON.stringify(files.get(path)),fileId:path,syncRevision:4,contentHash:'a'.repeat(64)} : {status:'absent',path,source:'dashboard',authoritative:true}]};
|
|
}
|
|
if (command === 'localstorage_get') return saved.get(args.key) ?? null;
|
|
if (command === 'localstorage_put') { saved.set(args.key,args.value); return {ok:true}; }
|
|
if (command === 'open_workspace_folder') return {file:{path:'/projects',id:'parent',kind:'folder',access:'read_write'}};
|
|
if (command === 'filesystem_list_dir') return {authoritative:true,files:[...directories]
|
|
.filter(path => path === args.path || path.startsWith(args.path + '/'))
|
|
.map(path => ({kind:'folder',path,id:path === '/projects' ? 'parent' : path,canWrite:true}))};
|
|
if (command === 'filesystem_create_folder') {
|
|
directories.add(args.path);
|
|
return {status:'ok',path:args.path,fileId:args.path};
|
|
}
|
|
if (command === 'filesystem_upload_files') {
|
|
writes.push(args);
|
|
const {path,text}=args.files[0];
|
|
files.set(path,JSON.parse(text));
|
|
return {items:[{status:'ok',isComplete:true,path,fileId:path}]};
|
|
}
|
|
throw new Error(`Unexpected command ${command}`);
|
|
},
|
|
subscribeKv: options.subscribeKv
|
|
};
|
|
const client = createProjectClient({bridge,extensionId:'contracts',scope:{workspaceId:'workspace',groupId:'group'},filesystemCommands:options.filesystemCommands,groupFolder:options.groupFolder,sharedProjectsFolder:options.sharedProjectsFolder,beforeSwitch:options.beforeSwitch});
|
|
return {client,writes,bridge,files};
|
|
}
|
|
|
|
test('the launch group catalog excludes picker history and respects legacy folder archive state', async () => {
|
|
let available = true;
|
|
const {client} = fixture({
|
|
filesystemCommands: ['filesystem_list_group_projects', 'filesystem_get_files'],
|
|
invoke(command, args) {
|
|
if (command === 'filesystem_list_group_projects') {
|
|
assert.deepEqual(args, {workspaceId: 'workspace', groupId: 'group'});
|
|
if (!available) throw new Error('Dashboard unavailable');
|
|
return {authoritative: true, folders: [
|
|
{...project('one'), canWrite: false},
|
|
{...project('two'), canWrite: false, archivedAt: '2026-11-03T12:00:00Z'}
|
|
]};
|
|
}
|
|
if (command === 'localstorage_get' || command === 'open_workspace_folder') assert.fail(command);
|
|
}
|
|
});
|
|
assert.deepEqual((await client.list()).map(row => row.id), ['one']);
|
|
const all = await client.list(true);
|
|
assert.equal(all.find(row => row.id === 'two').archived, true);
|
|
await client.withListedProject(all[0], async session => assert.equal(session.project.canWrite, false));
|
|
assert.equal(client.active, null);
|
|
assert.deepEqual(client.state.recents, []);
|
|
available = false;
|
|
await assert.rejects(client.list(), /Dashboard unavailable/);
|
|
});
|
|
|
|
test('captured sessions fence old writes and close late subscriptions during switching', async () => {
|
|
let finishSubscription;
|
|
let stopped = 0;
|
|
const {client,writes} = fixture({subscribeKv:() => new Promise(resolve=>{finishSubscription=resolve;})});
|
|
const first = await client.activate(project('one'));
|
|
const subscription = first.subscribeKv('extensions/contracts/state.kv',{},()=>assert.fail('Old subscription event'));
|
|
await client.activate(project('two'));
|
|
finishSubscription({unsubscribe:async()=>{stopped++;}});
|
|
await assert.rejects(subscription,{name:'AbortError'});
|
|
await assert.rejects(first.writeJson('extensions/contracts/state.json',{}, {status:'absent',path:first.path('extensions/contracts/state.json')}),{name:'AbortError'});
|
|
assert.equal(stopped,1);
|
|
assert.equal(writes.length,0);
|
|
await client.close();
|
|
});
|
|
|
|
test('JSON writes require captured authoritative CAS base and preserve caller data', async () => {
|
|
const {client,writes,files} = fixture();
|
|
const session = await client.activate(project('one'));
|
|
files.set(session.path('extensions/contracts/state.json'),{unknown:{retained:1},value:2});
|
|
const base = await session.readJson('extensions/contracts/state.json');
|
|
await session.writeJson('extensions/contracts/state.json',{...base.value,value:3},base);
|
|
const uploaded = writes[0].files[0];
|
|
assert.equal(uploaded.expectedSyncRevision,4);
|
|
assert.equal(uploaded.expectedContentHash,'a'.repeat(64));
|
|
assert.equal(uploaded.replaceExisting,true);
|
|
assert.deepEqual(JSON.parse(uploaded.text),{unknown:{retained:1},value:3});
|
|
assert.equal(writes[0].workspaceId,'workspace');
|
|
assert.equal(writes[0].groupId,'group');
|
|
await assert.rejects(session.writeJson('elsewhere.json',{},base),/authoritative read/);
|
|
assert.throws(()=>session.path('../escape.json'),/Unsafe/);
|
|
await client.close();
|
|
});
|
|
|
|
test('dirty state blocks switching and unavailable reads never become absence', async () => {
|
|
let missing = false;
|
|
const {client} = fixture({invoke:(command)=>missing && command==='filesystem_get_files' ? {items:[{status:'unavailable',authoritative:false}]} : undefined});
|
|
const first = await client.activate(project('one'));
|
|
first.markDirty();
|
|
await assert.rejects(client.activate(project('two')),/Unsaved/);
|
|
assert.equal(client.active,first);
|
|
first.markDirty(false);
|
|
missing=true;
|
|
await assert.rejects(first.readJson('state.json'),{name:'ProjectUnavailableError'});
|
|
assert.equal(client.active,first);
|
|
await client.close();
|
|
});
|
|
|
|
test('uncertain create retains the same folder and manifest identity on retry', async () => {
|
|
const paths=[];
|
|
const {client}=fixture({invoke:(command,args)=>{
|
|
if(command!=='filesystem_upload_files'||!args.files[0].path.endsWith('/project.json'))return;
|
|
paths.push(args.files[0].path);
|
|
if(paths.length===1)throw new Error('Commit outcome unavailable');
|
|
}});
|
|
await assert.rejects(client.create('Example'),/unavailable/);
|
|
const created=await client.create('Example');
|
|
assert.equal(paths[0],paths[1]);
|
|
assert.equal(created.manifest.name,'Example');
|
|
assert.equal(created.project.projectIdentity,created.manifest.id);
|
|
await client.close();
|
|
});
|
|
|
|
test('authoritative reads reject another path, cached drafts and ambiguous identities', async () => {
|
|
let reply;
|
|
const {client}=fixture({invoke:command=>command==='filesystem_get_files'?reply:undefined});
|
|
const session=await client.activate(project('one'));
|
|
const path=session.path('state.json');
|
|
const valid={status:'ok',path,source:'dashboard',authoritative:true,fileId:'file',syncRevision:1,text:'{}'};
|
|
for(const change of [{path:path+'wrong'},{source:'cache'},{pendingUpload:true},{syncRevision:null},{workspaceFileOutcome:'conflict'},{status:'absent',path:path+'wrong'}]) {
|
|
reply={items:[{...valid,...change}]};
|
|
await assert.rejects(session.readJson('state.json'),{name:'ProjectUnavailableError'});
|
|
}
|
|
reply={items:[valid,valid]};
|
|
await assert.rejects(session.readJson('state.json'),{name:'ProjectUnavailableError'});
|
|
await client.close();
|
|
});
|
|
|
|
test('successful transport cannot confirm pending or conflicted project writes', async () => {
|
|
let reply;
|
|
const {client}=fixture({invoke:command=>command==='filesystem_upload_files'?reply:undefined});
|
|
const session=await client.activate(project('one'));
|
|
const base=await session.readJson('state.json');
|
|
const valid={status:'ok',isComplete:true,path:base.path,fileId:'file'};
|
|
for(const change of [{isComplete:false},{path:base.path+'wrong'},{fileId:''},{pendingUpload:true},{pendingState:'queued'},{conflict:true},{workspaceFileOutcome:'conflict'},{workspaceFileOutcome:'pending'},{source:'cache'}]) {
|
|
reply={items:[{...valid,...change}]};
|
|
await assert.rejects(session.writeJson('state.json',{},base),/not confirmed|conflict/);
|
|
}
|
|
reply={items:[valid]};
|
|
assert.equal((await session.writeJson('state.json',{},base)).fileId,'file');
|
|
await client.close();
|
|
});
|
|
|
|
test('a selected container lists valid project manifests and opens them through its existing grant', async () => {
|
|
let picks = 0;
|
|
const {client,files} = fixture({invoke(command, args) {
|
|
if (command === 'open_workspace_folder') { picks++; return; }
|
|
if (command === 'filesystem_list_dir' && args.path === '/projects') {
|
|
return {authoritative:true,files:[
|
|
{path:'/projects',kind:'folder',fileId:'parent'},
|
|
{path:project('two').path,kind:'folder',fileId:'two',canWrite:false},
|
|
{path:project('missing').path,kind:'folder',fileId:'incomplete'},
|
|
{path:'/projects/not-a-folder.isap',kind:'file',fileId:'file'}
|
|
]};
|
|
}
|
|
}});
|
|
assert.deepEqual(await client.list(),[]);
|
|
await client.pickFolder();
|
|
const [listed] = await client.list();
|
|
assert.equal(listed.canWrite,false);
|
|
assert.equal(listed.updatedAt,'2026-11-03T12:00:00Z');
|
|
const selected = await client.openListed(listed);
|
|
assert.equal(selected.project.id,'two');
|
|
const manifest = files.get(listed.manifestPath);
|
|
files.set(listed.manifestPath,{...manifest,id:'one'});
|
|
await assert.rejects(client.openListed(listed),/identity/);
|
|
assert.equal(client.active,selected);
|
|
assert.equal(picks,1);
|
|
});
|
|
|
|
test('opening from an existing grant reports a denied row without reopening the picker', async () => {
|
|
const {client,files} = fixture({invoke(command, args) {
|
|
if (command === 'filesystem_get_files' && args.files[0].path === project('three').path + '/project.json') {
|
|
return {items:[{path:args.files[0].path, status:'error', authoritative:false, error:'extension filesystem permission is required'}]};
|
|
}
|
|
if (command === 'open_workspace_folder') assert.fail('Unexpected second project picker');
|
|
}});
|
|
const selected = await client.openListed(project('one'));
|
|
files.delete(project('two').path+'/project.json');
|
|
await assert.rejects(client.openListed(project('two')), /manifest missing/);
|
|
await assert.rejects(client.openListed(project('three')), /extension filesystem permission is required/);
|
|
assert.equal(client.active,selected);
|
|
});
|
|
|
|
test('a direct grant initializes the extension directory on first writable access', async () => {
|
|
const selected = {...project('two'), canWrite:true};
|
|
const directories = [];
|
|
const {client} = fixture({invoke(command, args) {
|
|
if (command === 'filesystem_list_dir') return {authoritative:true, files:[]};
|
|
if (command === 'filesystem_create_folder') {
|
|
directories.push(args.path);
|
|
return {status:'ok', path:args.path, fileId:args.path};
|
|
}
|
|
}});
|
|
assert.equal((await client.openListed(selected)).project.id, selected.id);
|
|
assert.deepEqual(directories, [selected.path + '/extensions', selected.path + '/extensions/contracts']);
|
|
});
|
|
|
|
test('first-open initialization reads the winning record after a folder race and an uncertain create', async () => {
|
|
let uploads = 0;
|
|
const {client, files} = fixture({invoke(command, args) {
|
|
if (command === 'filesystem_create_folder') throw new Error('Already exists');
|
|
if (command === 'filesystem_list_dir') {
|
|
return {authoritative:true, files:['extensions','contracts','data'].map(name => ({path:args.path + '/' + name, kind:'folder', id:name}))};
|
|
}
|
|
if (command === 'filesystem_upload_files') {
|
|
const file = args.files[0];
|
|
assert.equal(file.replaceExisting, false);
|
|
assert.equal(file.path, project('one').path + '/extensions/contracts/data/current.json');
|
|
files.set(file.path, {from:'other session'});
|
|
uploads++;
|
|
throw new Error('Create outcome unknown');
|
|
}
|
|
}});
|
|
const session = await client.activate({...project('one'), canWrite:true});
|
|
const created = await session.ensureExtensionJson('data/current.json', () => ({from:'this session'}));
|
|
assert.deepEqual(created.value, {from:'other session'});
|
|
const reopened = await session.ensureExtensionJson('data/current.json', () => assert.fail('Record already exists'));
|
|
assert.deepEqual(reopened.value, created.value);
|
|
assert.equal(uploads, 1);
|
|
});
|
|
|
|
test('read-only, archived and uncertain reads cannot seed extension records', async () => {
|
|
let answer;
|
|
const {client, writes} = fixture({invoke(command, args) {
|
|
if (command === 'filesystem_get_files' && answer && !args.files[0].path.endsWith('/project.json')) {
|
|
return {items:[{path:args.files[0].path, ...answer}]};
|
|
}
|
|
}});
|
|
const fail = () => assert.fail('Unexpected default');
|
|
for (const access of [{canWrite:false}, {archived:true, canWrite:true}]) {
|
|
const session = await client.activate({...project('one'), ...access});
|
|
assert.equal((await session.ensureExtensionJson('state.json', fail)).status, 'absent');
|
|
}
|
|
const session = await client.activate(project('two'));
|
|
for (answer of [{status:'unavailable'}, {status:'absent',source:'dashboard',authoritative:true,found:true}]) {
|
|
await assert.rejects(session.ensureExtensionJson('state.json', fail), {name:'ProjectUnavailableError'});
|
|
}
|
|
assert.equal(writes.length, 0);
|
|
});
|
|
|
|
test('an archived legacy folder stays in the archive until the manifest explicitly restores it', async () => {
|
|
const {client} = fixture({invoke(command,args) {
|
|
if (command === 'open_workspace_folder') {
|
|
return {file:{path:project('two').path,id:'two',kind:'folder',access:'read_write'}};
|
|
}
|
|
if (command === 'filesystem_list_dir' && args.path === project('two').path) {
|
|
return {authoritative:true,files:[{path:args.path,fileId:'two',kind:'folder',archivedAt:100}]};
|
|
}
|
|
}});
|
|
await client.pickFolder();
|
|
assert.deepEqual(await client.list(), []);
|
|
const [archived] = await client.list(true);
|
|
assert.equal(archived.archived,true);
|
|
await client.setArchived(archived,false);
|
|
assert.equal((await client.list())[0].archived,false);
|
|
});
|
|
|
|
test('replaced and revoked roots do not hide accessible projects or conceal dashboard outages', async () => {
|
|
let offline = false;
|
|
const {client} = fixture({invoke(command,args) {
|
|
if (command === 'localstorage_get' && args.key.endsWith('folders.v1')) return [
|
|
{path:'/revoked',id:'revoked'},
|
|
{path:'/replaced',id:'old'},
|
|
{path:'/projects',id:'parent'}
|
|
];
|
|
if (command !== 'filesystem_list_dir') return;
|
|
if (args.path === '/revoked') throw new Error('Filesystem path requires a current extension root or picker grant');
|
|
if (args.path === '/replaced') return {authoritative:true,files:[
|
|
{kind:'folder',path:'/replaced',fileId:'new'},
|
|
{kind:'folder',path:'/replaced/other.isap',fileId:'other'}
|
|
]};
|
|
if (offline) throw new Error('Dashboard unavailable');
|
|
return {authoritative:true,files:[
|
|
{kind:'folder',path:'/projects',fileId:'workspace_file:parent'},
|
|
{kind:'folder',path:project('two').path,fileId:'two'}
|
|
]};
|
|
}});
|
|
assert.deepEqual((await client.list()).map(item => item.id), ['two']);
|
|
offline = true;
|
|
await assert.rejects(client.list(),/Dashboard unavailable/);
|
|
});
|
|
|
|
test('group creation uses the launch group and opening a listed project creates no namespace', async () => {
|
|
const commands = [];
|
|
const {client} = fixture({groupFolder:true, invoke(command) {
|
|
commands.push(command);
|
|
if (command === 'filesystem_ensure_group_folder') return {folderId:'parent',path:'/projects'};
|
|
if (command === 'open_workspace_folder') assert.fail('Unexpected folder picker');
|
|
}});
|
|
const session = await client.create('Example', 'sample');
|
|
assert.equal(session.project.path, '/projects/example-sample.isap');
|
|
await client.leave();
|
|
commands.length = 0;
|
|
await client.openListed(session.project);
|
|
assert.ok(!commands.includes('filesystem_create_folder'));
|
|
assert.ok(!commands.includes('filesystem_upload_files'));
|
|
await client.close();
|
|
});
|
|
|
|
test('group members open the same writable projects independently of picker history', async () => {
|
|
const commands = ['filesystem_list_group_projects', 'filesystem_create_group_project', 'filesystem_upload_files', 'filesystem_create_folder'];
|
|
const {bridge: storage, files} = fixture();
|
|
const catalog = new Map();
|
|
let loseAcknowledgement = true;
|
|
function launch(extensionId, groupId = 'demo', writable = true) {
|
|
return createProjectClient({
|
|
extensionId, scope: {workspaceId: 'w', groupId}, sharedProjectsFolder: true,
|
|
filesystem: { supportsSharedGroupProjects: true, commands: writable ? commands : ['filesystem_list_group_projects'] },
|
|
bridge: {async invoke(command, args) {
|
|
if (command.startsWith('localstorage_')) {
|
|
assert.equal(args.key, 'isa-project-format.recents.v1', 'A previous read-only picker grant must not participate');
|
|
return storage.invoke(command, args);
|
|
}
|
|
assert.equal(args.workspaceId, 'w');
|
|
assert.equal(args.groupId, groupId);
|
|
if (command === 'filesystem_list_group_projects') return {authoritative:true, folders:[
|
|
...[...catalog.values()].filter(row => row.groupId === groupId),
|
|
{fileId:'private', path:'/groups/demo/extensions/quote/private.isap', canWrite:true},
|
|
{fileId:'nested', path:'/shared/elsewhere/nested.isap', canWrite:true}
|
|
]};
|
|
if (command === 'filesystem_create_group_project') {
|
|
assert.ok(writable);
|
|
const path = '/shared/' + args.projectId + '.isap';
|
|
const row = {fileId:'folder-' + args.projectId, path, groupId, canWrite:true};
|
|
if (!catalog.has(row.fileId)) {
|
|
catalog.set(row.fileId, row);
|
|
files.set(path + '/project.json', { ...files.get('/projects/one.isap/project.json'), id:args.projectId, name:args.name, importPending:args.importPending });
|
|
for (const dir of [path, path + '/extensions', path + '/assets']) await storage.invoke('filesystem_create_folder',{path:dir});
|
|
}
|
|
if (loseAcknowledgement) { loseAcknowledgement = false; throw new Error('Acknowledgement lost'); }
|
|
return row;
|
|
}
|
|
assert.ok(!['open_workspace_folder','filesystem_ensure_group_folder'].includes(command), command);
|
|
if (command === 'filesystem_get_files') assert.match(args.files[0].path, /^\/shared\/[^/]+\.isap\//);
|
|
return storage.invoke(command, args);
|
|
}}
|
|
});
|
|
}
|
|
const match = launch('isa-match-rsx-to-quote');
|
|
const planning = launch('isa-projects');
|
|
assert.equal(planning.supports('pickFolder'), false);
|
|
await assert.rejects(match.create('Hilversum'), /Acknowledgement lost/);
|
|
const quote = await match.create('Hilversum');
|
|
assert.equal(catalog.size, 1);
|
|
await quote.ensureExtensionJson('data.json', () => ({quote:42}));
|
|
const [row] = await planning.list();
|
|
assert.equal(row.id, quote.project.id);
|
|
const board = await planning.openListed(row);
|
|
assert.equal(board.project.canWrite, true);
|
|
await board.ensureExtensionJson('data.json', () => ({tasks:[]}));
|
|
assert.deepEqual((await board.readJson('extensions/isa-match-rsx-to-quote/data.json')).value, {quote:42});
|
|
const reopened = await planning.activate({...row, canWrite:false});
|
|
assert.equal(reopened.project.canWrite, true);
|
|
await reopened.ensureExtensionJson('data.json', () => assert.fail('Duplicated board'));
|
|
const otherGroup = launch('isa-projects', 'another-group');
|
|
assert.deepEqual(await otherGroup.list(), []);
|
|
const reader = launch('read-only', 'demo', false);
|
|
assert.equal(reader.supports('create'), false);
|
|
assert.equal((await reader.openListed((await reader.list())[0])).project.canWrite, false);
|
|
await assert.rejects(reader.create('Forbidden'), /read-only/);
|
|
const imported = await planning.stageCreate('Imported project', crypto.randomUUID(), {importing:true});
|
|
assert.equal(imported.manifest.importPending, true);
|
|
assert.deepEqual((await match.list()).map(p => p.id), [row.id]);
|
|
assert.equal(catalog.size, 2);
|
|
const bytes = zipSync({'project.json':strToU8(JSON.stringify(quote.manifest))});
|
|
const restored = await importProject(planning, bytes, {bridge:storage, name:'Restored'});
|
|
assert.equal(restored.manifest.importedFrom.id, quote.project.projectIdentity);
|
|
assert.notEqual(restored.project.id, quote.project.id);
|
|
assert.deepEqual((await match.list()).map(p => p.name).sort(), ['Hilversum','Restored']);
|
|
await Promise.all([match.close(), planning.close(), otherGroup.close(), reader.close()]);
|
|
});
|
|
|
|
test('older shared-project hosts report the required update without opening a picker', async () => {
|
|
const filesystem = {commands:['filesystem_list_group_projects','filesystem_create_folder','filesystem_upload_files','open_workspace_folder']};
|
|
const client = createProjectClient({bridge:{invoke:() => assert.fail('Unexpected host operation')}, filesystem,
|
|
sharedProjectsFolder:true, extensionId:'reader', scope:{workspaceId:'w',groupId:'g'}});
|
|
for (const action of ['pickFolder','create','archive']) assert.equal(client.supports(action), false);
|
|
await assert.rejects(client.list(), {code:'SHARED_GROUP_PROJECTS_UNAVAILABLE'});
|
|
await assert.rejects(client.create('Nieuw'), {code:'SHARED_GROUP_PROJECTS_UNAVAILABLE'});
|
|
await assert.rejects(client.pickFolder(), /launch group/);
|
|
await client.close();
|
|
});
|