import { confirmedWrite } from './proofs.js'; import { ProjectUnavailableError, readAuthoritativeFile } from './shared-read.js'; export { ProjectUnavailableError } from './shared-read.js'; import { extensionDataPath, validateArchivePath } from './format.js'; import { createProjectFilesystem, manifestFromSnapshot } from './project-filesystem.js'; const RECENTS_KEY = 'isa-project-format.recents.v1'; const abortError = () => new DOMException('Project session changed', 'AbortError'); function reference(value) { if (!value || typeof value !== 'object') throw new TypeError('Project reference required'); const id = value.folderId ?? value.id; const path = value.path; if (typeof id !== 'string' || !id || typeof path !== 'string' || !path.startsWith('/') || !path.endsWith('.isap')) throw new TypeError('Invalid project folder'); validateArchivePath(path.slice(1)); return { id, folderId: id, path, name: String(value.name ?? ''), archived: Boolean(value.archived), updatedAt: value.updatedAt, canWrite: value.canWrite, projectIdentity: String(value.projectIdentity ?? id), manifestPath: `${path}/project.json`, formatVersion: 1 }; } export function createProjectClient({ bridge, extensionId, scope, filesystemCommands, beforeSwitch, isCurrent = () => true }) { if (!bridge || typeof bridge.invoke !== 'function') throw new TypeError('Host bridge required'); if (!scope?.workspaceId || !scope?.groupId) throw new TypeError('Dashboard workspace and launch group required'); extensionDataPath(extensionId, 'validate.json'); const captured = Object.freeze({ workspaceId: scope.workspaceId, groupId: scope.groupId }); const supportsFilesystem = command => !filesystemCommands || filesystemCommands.includes(command); const canWrite = supportsFilesystem('filesystem_upload_files'); let active = null, recents = [], generation = 0, closed = false; let preferenceWrites = Promise.resolve(); const listeners = new Set(); const confirmationHandlers = []; const pendingCreations = new Map(); const sessions = new Set(); const staged = new Map(); const state = () => Object.freeze({ active, recents: structuredClone(recents) }); const notify = () => { for (const listener of listeners) listener(state()); }; const guard = () => { if (closed || !isCurrent()) throw abortError(); }; const invokeCurrent = async (command, args) => { guard(); const value = await bridge.invoke(command, args); guard(); return value; }; const invoke = (command, args = {}) => invokeCurrent(command, { ...args, ...captured }); const loadRecents = async () => { guard(); // Host private settings are already bound to the immutable account and launch scope. const ticket = generation; await preferenceWrites; const saved = await bridge.invoke('localstorage_get', {key: RECENTS_KEY, sync: false}); guard(); if (ticket !== generation) throw abortError(); if (saved != null && !Array.isArray(saved)) throw new TypeError('Invalid recent project settings'); recents = (saved ?? []).slice(0, 20).map(reference); notify(); return structuredClone(recents); }; async function remember(project) { recents = [reference(project), ...recents.filter(item => item.id !== project.id)].slice(0, 20); notify(); const snapshot = structuredClone(recents); preferenceWrites = preferenceWrites.catch(() => {}).then(() => bridge.invoke('localstorage_put', {key: RECENTS_KEY, value: snapshot, sync: false})); await preferenceWrites; guard(); } const read = (path, sessionGuard = guard) => readAuthoritativeFile(invoke,path,sessionGuard); const filesystem = createProjectFilesystem({ invoke, invokePrivateStorage: invokeCurrent, read, canWrite }); async function loadProject(value, check) { check(); const project = reference(value); const snapshot = await read(project.manifestPath, check); if (snapshot.status !== 'found') throw new ProjectUnavailableError('Project manifest missing'); const manifest = manifestFromSnapshot(snapshot); if (manifest.id !== project.projectIdentity) throw new Error('Project manifest identity changed'); return { project: { ...project, name: manifest.name, updatedAt: manifest.updatedAt, archived: manifest.archived ?? project.archived, canWrite: canWrite && project.canWrite }, manifest, snapshot }; } function checkTransition(ticket) { guard(); if (ticket !== generation) throw abortError(); } async function approveSwitch(session) { const confirm = beforeSwitch ?? confirmationHandlers.at(-1); if (session?.dirty && (!confirm || await confirm(session) !== true)) { throw new Error('Unsaved project changes must be saved or explicitly discarded'); } guard(); } function beginTransition(keep) { const ticket=++generation; for(const session of [...staged.keys()])if(session!==keep)void session.close(); if(keep)staged.get(keep).ticket=ticket; return ticket; } async function switchTo(acquire, approved, keep) { guard(); const ticket = beginTransition(keep); const previous = active; const dirtyVersion = previous?.dirtyVersion; if(!approved || approved.session!==previous || approved.version!==dirtyVersion)await approveSwitch(previous); if (ticket !== generation) throw abortError(); const check = () => checkTransition(ticket); const selected = await acquire(check); check(); const {project, manifest, snapshot} = selected; const next = makeSession(project, manifest, snapshot); staged.set(next, {ticket}); try { if (project.canWrite === true && !project.archived) { const namespace = `extensions/${extensionId}`; const folders = await next.listFiles('extensions', false); if (!folders.some(row => row.kind === 'folder' && row.path === next.path(namespace))) { await next.ensureDirectory(namespace); } } check(); if (active !== previous || previous?.dirtyVersion !== dirtyVersion) await approveSwitch(active); check(); } catch (error) { await next.close(); throw error; } staged.delete(next); const retiring = active; active = null; notify(); await retiring?.close(); if (ticket !== generation) { await next.close(); throw abortError(); } active = next; notify(); // A preference write cannot invalidate a committed creation or switch. try { await remember(project); } catch (error) { next.preferenceError = error; notify(); } if (ticket !== generation) throw abortError(); return next; } function makeSession(project, manifest, manifestSnapshot) { const controller = new AbortController(); const cleanups = new Set(); let sessionClosed = false, dirty = false, dirtyVersion = 0; const sessionGuard = () => { guard(); if (sessionClosed || controller.signal.aborted || staged.has(session) && staged.get(session).ticket !== generation) throw abortError(); }; const path = relative => `${project.path}/${validateArchivePath(relative)}`; async function call(command, args) { sessionGuard(); const value = await invoke(command, args); sessionGuard(); return value; } const session = { scope: captured, project: Object.freeze({...project}), manifest: structuredClone(manifest), manifestSnapshot, signal: controller.signal, preferenceError: null, get dirty() { return dirty; }, get dirtyVersion() { return dirtyVersion; }, markDirty(value = true) { sessionGuard(); dirty = value; dirtyVersion++; notify(); }, path, extensionPath: relative => path(extensionDataPath(extensionId, relative)), assertCurrent: sessionGuard, track(cleanup) { sessionGuard(); cleanups.add(cleanup); return () => cleanups.delete(cleanup); }, async readFile(relative) { return read(path(relative), sessionGuard); }, async readJson(relative) { const item = await read(path(relative), sessionGuard); return item.status === 'absent' ? item : {...item, value: JSON.parse(item.text)}; }, async ensureExtensionJson(relative, makeDefault) { const file = extensionDataPath(extensionId, relative); const base = await session.readJson(file); if (base.status === 'found' || project.canWrite === false || project.archived) return base; const value = await makeDefault(); await session.ensureDirectory(file.slice(0, file.lastIndexOf('/'))); try { await session.writeJson(file, value, base); } catch (error) { // A competing creator or a lost acknowledgement may have committed the file. const current = await session.readJson(file); if (current.status === 'found') return current; throw error; } const current = await session.readJson(file); if (current.status !== 'found') throw new ProjectUnavailableError('Created project file could not be read'); return current; }, async writeJson(relative, value, base, options = {}) { sessionGuard(); if (!base || base.path !== path(relative) || !['found','absent'].includes(base.status)) throw new TypeError('An authoritative read of this project file is required before writing'); if (base.status === 'found' && (!base.fileId || base.authoritative !== true || !Number.isSafeInteger(base.syncRevision) || base.syncRevision < 0)) throw new TypeError('Replacement requires authoritative file identity'); if(options.operationId !== undefined && (typeof options.operationId !== 'string' || !/^[0-9a-f]{64}$/.test(options.operationId)))throw new TypeError('Invalid project write operation identity'); const result = await call('filesystem_upload_files', {files:[{ path:path(relative),text:JSON.stringify(value),contentType:'application/json',replaceExisting:base.status === 'found', ...(base.status === 'found' ? {expectedSyncRevision:base.syncRevision,expectedContentHash:base.contentHash} : {}), metadata:{projectId:project.projectIdentity,client_operation_id:options.operationId ?? await operationId()} }]}); return confirmedWrite(result,path(relative)); }, async listFiles(relative = '', recursive = true) { const result = await call('filesystem_list_dir', {path:relative ? path(relative) : project.path,recursive,cachePolicy:'dashboard-required'}); if (result?.authoritative !== true || !Array.isArray(result.files) || result.snapshotComplete === false || result.error) throw new ProjectUnavailableError('Project inventory unavailable'); return result.files; }, async publishStatus(summary, base) { if (!['not-started','in-progress','blocked','complete'].includes(summary?.status)) throw new TypeError('Invalid extension project status'); if (summary.completion !== undefined && (typeof summary.completion !== 'number' || !Number.isFinite(summary.completion) || summary.completion < 0 || summary.completion > 100)) throw new TypeError('Completion must be between 0 and 100'); const relative = extensionDataPath(extensionId, 'status.json'); base ??= await session.readJson(relative); if (base.status === 'found' && base.value.schemaVersion !== 1) throw new Error('Unsupported extension status format'); const value = {...(base.value ?? {}),schemaVersion:1,status:summary.status,updatedAt:new Date().toISOString()}; if (summary.completion !== undefined) value.completion=summary.completion; else delete value.completion; return session.writeJson(relative,value,base); }, async readStatuses() { const entries = (await session.listFiles('extensions',true)).filter(file => file.kind === 'file' && /^extensions\/[^/]+\/status\.json$/.test(file.path.slice(project.path.length+1))); return Promise.all(entries.map(async file => { const relative=file.path.slice(project.path.length+1); const owner=relative.split('/')[1]; try { const snapshot=await session.readJson(relative); if(snapshot.status!=='found' || snapshot.value.schemaVersion!==1) throw new Error('Unsupported extension status format'); return {...snapshot.value,extensionId:owner}; } catch(error) {sessionGuard();return {extensionId:owner,unavailable:true,error:String(error.message ?? error)};} })); }, async ensureDirectory(relative) { const parts=validateArchivePath(relative).split('/'); for(let depth=1;depth<=parts.length;depth++) { const directory=path(parts.slice(0,depth).join('/')); try { const reply=await call('filesystem_create_folder',{path:directory}); if(reply?.status!=='ok'||reply.path!==directory||typeof reply.fileId!=='string'||!reply.fileId)throw new ProjectUnavailableError('Project directory creation was not confirmed'); } catch (error) { sessionGuard(); const parent = parts.slice(0, depth - 1).join('/'); const siblings = await session.listFiles(parent, false); if (!siblings.some(row => row.path === directory && row.kind === 'folder' && row.canWrite !== false && (row.fileId || row.id))) throw error; } } }, async openKv(relative, options = {}) { const canonical=validateArchivePath(relative); const separator = canonical.lastIndexOf('/'); const parent = separator < 0 ? '' : canonical.slice(0,separator); if (parent) await session.ensureDirectory(parent); if (options.syncable === true) { const parentPath = parent ? path(parent) : project.path; const inventory = await session.listFiles(parent, true); options = { ...options, syncable: inventory.some(row => row.path === parentPath && row.kind === 'folder' && row.synced === true) }; } return call('kv_store_open', { ...options, path: path(canonical) }); }, async applyKv(relative, mutation) { sessionGuard(); if (typeof bridge.applyKv !== 'function') throw new Error('Host KV transfer helper unavailable'); const reply = await bridge.applyKv({...mutation,...captured,path:path(relative)}); sessionGuard(); return reply; }, async subscribeKv(relative, args, onChange) { sessionGuard(); if (typeof bridge.subscribeKv !== 'function') throw new Error('Host KV subscriptions unavailable'); const subscription = await bridge.subscribeKv({...args,...captured,path:path(relative)}, value => { if (!closed && !sessionClosed && !controller.signal.aborted && isCurrent()) onChange(value); }); if (closed || sessionClosed || controller.signal.aborted || !isCurrent()) { await subscription.unsubscribe(); throw abortError(); } cleanups.add(subscription.unsubscribe); return subscription; }, async close() { if (sessionClosed) return; sessionClosed = true; controller.abort(); sessions.delete(session); staged.delete(session); const tasks = [...cleanups]; cleanups.clear(); const results = await Promise.allSettled(tasks.map(cleanup => Promise.resolve().then(cleanup))); const failures = results.filter(result => result.status === 'rejected'); if (failures.length) session.cleanupErrors = failures.map(result => result.reason); } }; sessions.add(session); return session; } function prepareCreation(name, id) { if (typeof name !== 'string' || !name.trim()) throw new TypeError('Project name required'); name = name.trim(); const pending = pendingCreations.get(name); if (pending && (id === undefined || pending.id === id)) return pending; const creation = { name, id: id ?? crypto.randomUUID(), root: null }; pendingCreations.set(name, creation); return creation; } return { scope: captured, extensionId, supports(action) { if (action === 'create') return canWrite && supportsFilesystem('filesystem_create_folder'); if (action === 'archive') return canWrite; return action === 'pickFolder' && supportsFilesystem('open_workspace_folder'); }, get active() { return active; }, get state() { return state(); }, provideSwitchConfirmation(handler) { confirmationHandlers.push(handler); return () => { const index=confirmationHandlers.indexOf(handler); if(index>=0)confirmationHandlers.splice(index,1); }; }, subscribe(listener) { listeners.add(listener); listener(state()); return () => listeners.delete(listener); }, recent: loadRecents, async list(includeArchived = false) { return (await filesystem.list(includeArchived)).map(reference); }, pickFolder: () => filesystem.pickFolder(), async create(name, operationId) { const creation = prepareCreation(name, operationId); const session = await switchTo(async check => { const project = await filesystem.create(creation.name, creation, check); return loadProject(project, check); }); if (pendingCreations.get(creation.name) === creation) pendingCreations.delete(creation.name); return session; }, async stageCreate(name, operationId) { guard(); const ticket = beginTransition(); const previous = active; const version = previous?.dirtyVersion; await approveSwitch(previous); const check = () => checkTransition(ticket); check(); const creation = prepareCreation(name, operationId); const created = await filesystem.create(creation.name, creation, check); const { project, manifest, snapshot } = await loadProject(created, check); const session = makeSession(project, manifest, snapshot); staged.set(session, { ticket, session: previous, version, creation }); return session; }, async adopt(session) { guard(); const approval = staged.get(session); if (!approval || approval.ticket !== generation) throw abortError(); session.assertCurrent(); try { const current = await switchTo(check => loadProject(session.project, check), approval, session); if (pendingCreations.get(approval.creation.name) === approval.creation) pendingCreations.delete(approval.creation.name); return current; } finally { await session.close(); } }, openListed(project) { return switchTo(check => loadProject(project, check)); }, activate(project) { return switchTo(check => loadProject(project, check)); }, async setArchived(project, archived) { if (typeof archived !== 'boolean') throw new TypeError('Archive state must be a boolean'); const loaded = await loadProject(project, guard); await filesystem.setArchived(loaded.project, loaded.snapshot, loaded.manifest, archived); }, async leave() { guard(); const ticket=beginTransition(); const previous=active; await approveSwitch(previous); if(ticket!==generation)throw abortError(); active=null; notify(); await previous?.close(); }, async close() { if (closed) return; closed = true; generation++; active = null; await Promise.allSettled([...sessions].map(session=>session.close())); notify(); listeners.clear(); confirmationHandlers.length=0; } }; } async function operationId() { const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(crypto.randomUUID())); return Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2,'0')).join(''); }