10 Commits
31 changed files with 2089 additions and 355 deletions
+45 -28
View File
@@ -1,8 +1,8 @@
# ISA Project format # ISA Project format
Version 1 is a dashboard-backed `<name>.isap` folder containing `project.json`, `extensions/<extension-id>/` and `assets/`. The manifest contains `formatVersion: 1`, stable `id`, display `name`, and UTC `createdAt`/`updatedAt` timestamps. Canonical dashboard folder IDs are storage identities; names and paths do not grant access. Imports allocate a new identity and folder. Version 1 is an ordinary workspace `<name>.isap` folder containing `project.json`, `extensions/<extension-id>/` and `assets/`. The manifest contains `formatVersion: 1`, stable `id`, display `name`, UTC `createdAt`/`updatedAt` timestamps, and optional `archived` state. Canonical dashboard folder IDs are storage identities; names and paths do not grant access. Imports allocate a new identity and folder.
Extension namespaces organize data and are not permission boundaries. A project read-write grant permits supported edits across namespaces. Preserve unknown manifest fields, files and extension data. Each extension documents its canonical data; ISA Projects owns planning and detailed progress. Common summaries live in `extensions/<extension-id>/status.json` with `schemaVersion: 1`, `status` (`not-started`, `in-progress`, `blocked`, `complete`), `updatedAt`, and optional `completion` between 0 and 100. Summary data is editable project content and never grants publishing authority. Extension namespaces organize data and are not permission boundaries. An ordinary writable folder grant permits supported edits across namespaces. Preserve unknown manifest fields, files and extension data. Each extension documents its canonical data; ISA Projects owns planning and detailed progress. Common summaries live in `extensions/<extension-id>/status.json` with `schemaVersion: 1`, `status` (`not-started`, `in-progress`, `blocked`, `complete`), `updatedAt`, and optional `completion` between 0 and 100. Summary data is editable project content and never grants publishing authority.
## Public APIs ## Public APIs
@@ -15,7 +15,8 @@ import { mountProjectWorkspace } from '@isa-warden/isa-project-format/dom';
const client = createProjectClient({ const client = createProjectClient({
bridge, bridge,
extensionId: 'example', extensionId: 'example',
projectCommands: appInfo.projects?.commands, sharedProjectsFolder: true,
filesystem: appInfo.filesystem,
scope: { workspaceId, groupId } scope: { workspaceId, groupId }
}); });
const view = mountProjectWorkspace(target, { client, bridge, extensionName: 'Example', locale: 'en' }); const view = mountProjectWorkspace(target, { client, bridge, extensionName: 'Example', locale: 'en' });
@@ -24,17 +25,29 @@ view.destroy();
await client.close(); await client.close();
``` ```
The shared UI provides a searchable group project overview, recent activity, project creation, an active-project header, file/media browsing, transfer actions and a Tauri-compatible HTML confirmation for dirty project switches. English and Dutch labels are included. It inherits ISA extension theme tokens; detailed application workflows and planning remain in the extension. Components consume a captured client instance: remount with a new client when the launch context changes. The shared UI provides a searchable project overview, recent activity, project creation, an active-project header, file/media browsing, transfer actions and a Tauri-compatible HTML confirmation for dirty project switches. English and Dutch labels are included. It inherits ISA extension theme tokens; detailed application workflows and planning remain in the extension. Components consume a captured client instance: remount with a new client when the launch context changes.
`client.activate(reference)` opens a listed or recent reference by reading its manifest through an existing grant. `client.create(name, operationId?)` uses host creation and retains its operation ID through uncertain retries in the current client. Callers with durable recovery journals should provide their persisted operation ID. Recent references are private, launch-scoped host preferences rather than canonical project state. Preference failures are observable on `session.preferenceError` and do not invalidate an already committed creation/switch. `client.activate(reference)` opens a listed or recent reference after verifying its manifest. In shared group mode it opens the single selected folder through the host and revalidates its identity and access in the launch group. `client.create(name, operationId?)` creates an ordinary folder and publishes its manifest after the standard subdirectories exist. It retains the same operation ID and folder through uncertain retries in the current client. Callers with durable recovery journals should provide their persisted operation ID. Recent references are private, launch-scoped host preferences rather than canonical project state. Preference failures are observable on `session.preferenceError` and do not invalidate an already committed creation/switch.
Sessions capture their project path and abort signal. `readJson` returns an authoritative CAS base; `writeJson(relative, value, base, {operationId?})` requires that same file’s base and sends its revision/hash. `ensureDirectory(relative)` creates real parent directories in order; `openKv` does this for its parent before opening a store. `openKv`, `applyKv` and `subscribeKv` use the captured project destination. Use `extensionPath` for extension-owned paths, `publishStatus` for summaries and `readStatuses` for the overview. Subscriptions and registered cleanup callbacks close on switching; late results cannot use a retired session. Mark unsaved work with `session.markDirty()`. Without explicit confirmation, dirty sessions block switching. Mounting the shared UI supplies a confirmation; applications can provide `beforeSwitch` to integrate an existing save/discard workflow. Sessions capture their project path and abort signal. `readJson` returns an authoritative CAS base; `writeJson(relative, value, base, {operationId?})` requires that same file’s base and sends its revision/hash. `ensureDirectory(relative)` creates real parent directories in order; `openKv` does this for its parent before opening a store. A requested synchronized store uses offline storage when the granted parent is synchronized. Otherwise, new stores use the ordinary online filesystem contract. `openKv`, `applyKv` and `subscribeKv` use the captured project destination. Use `extensionPath` for extension-owned paths, `publishStatus` for summaries and `readStatuses` for the overview. Subscriptions and registered cleanup callbacks close on switching; late results cannot use a retired session. Mark unsaved work with `session.markDirty()`. Without explicit confirmation, dirty sessions block switching. Mounting the shared UI supplies a confirmation; applications can provide `beforeSwitch` to integrate an existing save/discard workflow.
## Project start screen ## Project start screen
Use the ISA Match layout for a project-based extension. Show recent activity on the left and **Projects** (**Projecten**) on the right. Place **+ Create project** at the top right of the Projects panel. Populate this list on launch with `await client.list()`, which returns active shared projects for the launch group, including ones this extension has never used. `client.recent()` supplies optional personal shortcuts. Use the project rows to open existing projects and the create button to launch the setup form. Use `sharedProjectsFolder: true` with `filesystem: appInfo.filesystem` for the shared group overview. Declare `group_projects_read` and `filesystem_read` in the extension manifest. On a host advertising `filesystem_list_group_projects` and `filesystem_open_group_project`, the overview reads the active group's existing file inventory. It lists the active group’s `.isap` folders with valid manifests, including projects created in other extensions. Each row reports whether the extension already has its own instance in the project (`hasInstance`). Listing projects gives the extension no file grants. Selecting a project asks the host for access to that folder using the member's current rights and the extension's declared filesystem permissions. A writable session can create the extension's instance inside the selected project. `filesystem_create_group_project` reserves an ordinary folder for a new project or import. The client creates the standard subdirectories and publishes `project.json` last. The dashboard creates these folders in the originating group’s project directory. Workspace admins retain administrative access. A creator who leaves the group has no ownership exception.
Use the shared `ProjectWorkspace` or `mountProjectWorkspace` overview with the extension’s display name, locale and launch-scoped client. Pass `projectCommands: appInfo.projects?.commands` to the client. Custom overviews call `client.list()` and `client.openListed(row)`. Declare `projects_open_listed`, `projects_read` and `filesystem_read` for direct access. On older hosts the client reads the selected folder using its existing grant. If access is unavailable, the overview shows the error and keeps the project list available. Only explicit creation calls `client.create(name, operationId)`. ### Other client configurations
The default client uses the user's selected folders for listing and creation, including on hosts that advertise the group project catalog.
Use `client.withListedProject(row, action)` for an explicitly selected project that requires a temporary session. The callback receives a temporary session and leaves the active project and recent activity intact. ISA Projects initializes its first planning board with a stable ID when a writable shared project opens.
Pass `groupFolder: true` to `createProjectClient` to use the extension’s folder for the current launch group as its default project location. This mode requires the host command `filesystem_ensure_group_folder`. The client lists projects from that folder and any additional folders the user has selected. New projects and project imports use the group folder.
### Project overview
The shared project picker provides the ISA Match layout using the host theme tokens. Its header cards count active projects and accessible recent projects across the full inventory, including while searching. An embedded picker keeps its host extension’s summary header. While the inventory loads, the picker shows animated placeholder rows and keeps existing rows visible during refresh. Extensions can also use `mountProjectListSkeleton(target)` from `@isa-warden/isa-project-format/dom` during startup. Show recent activity on the left and **Projects** (**Projecten**) on the right. Place **+ Create project** at the top right of the Projects panel. Populate this list on launch with `await client.list()`, which returns active projects for the configured storage mode. `client.recent()` supplies optional personal shortcuts. Use the project rows to open existing projects and the create button to launch the setup form.
Use the shared `ProjectWorkspace` or `mountProjectWorkspace` with the extension display name, locale and launch-scoped client. Custom overviews in picker-based mode can call `client.pickFolder()` from a user action and refresh `client.list()` after a selection. The picker can select a container such as `/shared` or a single existing `.isap` folder. The extension remembers selected paths for the launch scope and reads only through its ordinary filesystem grants. Use `client.openListed(row)` to reopen a project, `client.create(name, operationId)` to create it in an editable container, and `client.setArchived(row, archived)` to update the manifest. Extensions need the host permissions for filesystem reads, optional writes, and private preferences.
Every project extension initializes its own data when a writable project first opens. The client ensures the extension directory exists, and the extension opens its workspace with the stored data. For a JSON-backed workspace, call `await session.ensureExtensionJson('data/current.json', () => initialState(session.manifest.name))` using the extension’s canonical relative path and default schema. The result includes the saved JSON value and version. The helper creates missing parents, uses a create-only write, and reads the committed record even if another client created it. An absent record on a read-only or archived project returns `status: 'absent'`. Unavailable or malformed data raises an error. Every project extension initializes its own data when a writable project first opens. The client ensures the extension directory exists, and the extension opens its workspace with the stored data. For a JSON-backed workspace, call `await session.ensureExtensionJson('data/current.json', () => initialState(session.manifest.name))` using the extension’s canonical relative path and default schema. The result includes the saved JSON value and version. The helper creates missing parents, uses a create-only write, and reads the committed record even if another client created it. An absent record on a read-only or archived project returns `status: 'absent'`. Unavailable or malformed data raises an error.
@@ -42,34 +55,38 @@ For directory-backed collections, initialize the empty collection in the selecte
## Specialist viewers for shared data ## Specialist viewers for shared data
A supplier viewer and a price-book viewer can each open on their own dataset. ISA Match and other authorised extensions can display that same data. All readers use the existing file or KV store and its schema. The viewer’s extension ID does not determine ownership of the data. The dashboard exposes versioned datasets through ordinary workspace files. Each extension obtains its own launch-scoped grant through `openWorkspaceAsset`. A group supplies the requesting user's access context. The workspace owns the data and its checkpoints.
Use `@isa-warden/isa-project-format/shared-folder` with a folder already authorised for the current launch. For data inside an open project, pass `scope: session.scope`, `folder: session.project` and `assertCurrent: session.assertCurrent`. For a separately shared register, use the host-authorised workspace folder and the immutable launch scope. Host grants are per package. Reopening a linked folder uses its valid grant. A new reader needs its own host authorisation for a folder outside the project. | Asset | Canonical store | Contents |
| --- | --- | --- |
| `suppliers` | `/shared/suppliers/catalog.kv` | Stable supplier IDs, profiles, overrides, import history and enrichments. `catalog/meta.active` selects the generation. |
| `prices` | `/shared/prices/prices.kv` | Comparable price observations, keyed by stable observation ID in the list `observations/v1`. |
| `bid_history` | `/shared/bid_history/inschrijfhistorie.json` | Historical bids by ID and lot, with criterion scores and feedback. |
Declare the asset’s `workspace_asset_<asset>_read` permission and `filesystem_read`. Editors also need its write permission, `filesystem_write` and effective write access to the folder. KV datasets additionally require `kv_store_read` and, for editing, `kv_store_write`. For JSON datasets, pass the snapshot from `createSharedFolderReader(...).readJson(relative)` to `writeWorkspaceAssetJson(context, relative, value, snapshot)` with a writable asset grant in `context.folder`. Store a supplier ID on a project line. Resolve the ID against the supplier asset when displaying current details. Keep original offers, recipients and sent messages in the project.
```js ```js
import { createSharedFolderReader } from '@isa-warden/isa-project-format/shared-folder'; import { openWorkspaceAsset } from '@isa-warden/isa-project-format/shared-folder';
import { openPriceAsset } from '@isa-warden/isa-project-format/prices';
const reader = createSharedFolderReader({ bridge, scope, folder, assertCurrent }); const folder = await openWorkspaceAsset({ bridge, scope, asset: 'suppliers', access: 'read' });
const index = await reader.readJson('isa-match-suppliers.json'); const path = folder.path + '/catalog.kv';
if (index.status === 'found') { const subscription = await bridge.invoke('kv_store_subscribe', { path, keys: ['catalog/meta'] });
const register = index.value; try {
if (register.format !== 'isa-match-workspace-suppliers-v1' || const active = subscription.entries.find(entry => entry.key === 'catalog/meta')?.value?.active;
register.workspaceId !== scope.workspaceId || // Subscribe to catalog/<active>/supplier/<id>/profile for the linked IDs in batches.
typeof register.id !== 'string' || !register.id || !Array.isArray(register.suppliers)) { // Follow mergedInto on old profiles. Rebind the profile subscription when active changes.
throw new Error('Unexpected supplier register'); } finally {
} await bridge.invoke('kv_store_unsubscribe', { path, subscriptionId: subscription.subscriptionId });
const id = encodeURIComponent(register.id);
// The supplier directory contains stable supplier IDs and public identities.
const suppliers = register.suppliers;
// The price-book viewer reads the published price rows from the same folder.
const snapshot = await reader.readKv('isa-match-prices-' + id + '.kv');
const prices = snapshot.entries.filter(entry => entry.key.startsWith('price/'));
} }
const prices = await openPriceAsset({ bridge, scope, access: 'read' });
const page = await prices.query({ search: 'asfalt', limit: 30 });
``` ```
For supplier details, read `isa-match-catalog-<encoded register ID>.kv` and the active generation in `catalog/meta`. Profiles use `catalog/<active>/supplier/<supplier ID>/profile`. Use the active generation to exclude retired and staged records. The prices KV contains the shared price book. The separate ISA Prijzenregister searches published records across the workspace. A viewer that only needs suppliers can skip the prices read entirely. Price values contain `supplier`, `description`, `specItem`, numeric `unitPrice` (including zero), `unit`, `currency` and `receivedAt` (ISO date or empty). Optional `supplierId` links to the shared supplier and `validUntil` holds an ISO date. A writer assigns one stable observation ID per source observation or quotation version. New writers can use a persisted UUID. Project paths, quotations, review notes and commercial terms belong in the project.
`listFiles()` lists the authorised directory. `readFile` and `readJson` distinguish authoritative absence from a failed read. `readKv` pages a consistent snapshot and checks store identity and revision across pages. These operations use the host’s filesystem or KV read access without creating files, modifying records or granting another extension access. To add price observations, open the price asset with `access: 'read_write'` and call `importRows([{ id, value }])`. Keep the same ID on retries. Re-imports preserve edited values and can attach a supplier ID to an existing observation. Queries accept date ranges, exact field filters, facets and revision-checked paging. Follow the supplier schema's publication rules to update profiles and indexes together. A read-only viewer should handle a missing dataset as a distinct state and surface authorization or transport errors. For arbitrary files in an authorised project or workspace folder, `createSharedFolderReader` supports relative file reads and consistent KV snapshots.
## ZIP transfer ## ZIP transfer
+5
View File
@@ -17,6 +17,11 @@
}, },
"./svelte": { "./svelte": {
"import": "./src/components/index.js" "import": "./src/components/index.js"
},
"./prepared-documents": "./src/prepared-documents.js",
"./prices": {
"types": "./src/prices.d.ts",
"import": "./src/prices.js"
} }
}, },
"files": [ "files": [
+110 -60
View File
@@ -1,7 +1,8 @@
import { confirmedWrite } from './proofs.js'; import { confirmedWrite } from './proofs.js';
import { ProjectUnavailableError, readAuthoritativeFile } from './shared-read.js'; import { ProjectUnavailableError, readAuthoritativeFile } from './shared-read.js';
export { ProjectUnavailableError } from './shared-read.js'; export { ProjectUnavailableError } from './shared-read.js';
import { parseProjectManifest, extensionDataPath, validateArchivePath } from './format.js'; import { extensionDataPath, validateArchivePath } from './format.js';
import { createProjectFilesystem, manifestFromSnapshot } from './project-filesystem.js';
const RECENTS_KEY = 'isa-project-format.recents.v1'; const RECENTS_KEY = 'isa-project-format.recents.v1';
const abortError = () => new DOMException('Project session changed', 'AbortError'); const abortError = () => new DOMException('Project session changed', 'AbortError');
@@ -12,15 +13,23 @@ function reference(value) {
if (typeof id !== 'string' || !id || typeof path !== 'string' || !path.startsWith('/') || !path.endsWith('.isap')) throw new TypeError('Invalid project folder'); if (typeof id !== 'string' || !id || typeof path !== 'string' || !path.startsWith('/') || !path.endsWith('.isap')) throw new TypeError('Invalid project folder');
validateArchivePath(path.slice(1)); validateArchivePath(path.slice(1));
return { id, folderId: id, path, name: String(value.name ?? ''), return { id, folderId: id, path, name: String(value.name ?? ''),
archived: Boolean(value.archived), updatedAt: value.updatedAt, canWrite: value.canWrite, instanceCreatorName: value.instanceCreatorName, instanceCreatorId: value.instanceCreatorId, instanceCreatedAt: value.instanceCreatedAt, archived: Boolean(value.archived), updatedAt: value.updatedAt, canWrite: value.canWrite,
...(typeof value.hasInstance === 'boolean' && { hasInstance: value.hasInstance }),
projectIdentity: String(value.projectIdentity ?? id), manifestPath: `${path}/project.json`, formatVersion: 1 }; projectIdentity: String(value.projectIdentity ?? id), manifestPath: `${path}/project.json`, formatVersion: 1 };
} }
export function createProjectClient({ bridge, extensionId, scope, projectCommands, beforeSwitch, isCurrent = () => true }) { export function createProjectClient({ bridge, extensionId, scope, filesystem, filesystemCommands = filesystem?.commands, groupFolder = false, sharedProjectsFolder = false, beforeSwitch, isCurrent = () => true }) {
if (!bridge || typeof bridge.invoke !== 'function') throw new TypeError('Host bridge required'); 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'); if (!scope?.workspaceId || !scope?.groupId) throw new TypeError('Dashboard workspace and launch group required');
extensionDataPath(extensionId, 'validate.json'); extensionDataPath(extensionId, 'validate.json');
const captured = Object.freeze({ workspaceId: scope.workspaceId, groupId: scope.groupId }); const captured = Object.freeze({ workspaceId: scope.workspaceId, groupId: scope.groupId });
const supportsFilesystem = command => !filesystemCommands || filesystemCommands.includes(command);
if (groupFolder && sharedProjectsFolder) throw new TypeError('Choose one project storage location');
const supportsSharedGroupProjects = sharedProjectsFolder && filesystem?.supportsSharedGroupProjects === true
&& filesystemCommands?.includes('filesystem_list_group_projects') === true
&& filesystemCommands.includes('filesystem_open_group_project');
const canCreateSharedProject = supportsSharedGroupProjects && filesystemCommands.includes('filesystem_create_group_project');
const canWrite = supportsFilesystem('filesystem_upload_files');
let active = null, recents = [], generation = 0, closed = false; let active = null, recents = [], generation = 0, closed = false;
let preferenceWrites = Promise.resolve(); let preferenceWrites = Promise.resolve();
const listeners = new Set(); const listeners = new Set();
@@ -31,12 +40,13 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
const state = () => Object.freeze({ active, recents: structuredClone(recents) }); const state = () => Object.freeze({ active, recents: structuredClone(recents) });
const notify = () => { for (const listener of listeners) listener(state()); }; const notify = () => { for (const listener of listeners) listener(state()); };
const guard = () => { if (closed || !isCurrent()) throw abortError(); }; const guard = () => { if (closed || !isCurrent()) throw abortError(); };
const invoke = async (command, args = {}) => { const invokeCurrent = async (command, args) => {
guard(); guard();
const value = await bridge.invoke(command, { ...args, ...captured }); const value = await bridge.invoke(command, args);
guard(); guard();
return value; return value;
}; };
const invoke = (command, args = {}) => invokeCurrent(command, { ...args, ...captured });
const loadRecents = async () => { const loadRecents = async () => {
guard(); guard();
// Host private settings are already bound to the immutable account and launch scope. // Host private settings are already bound to the immutable account and launch scope.
@@ -59,14 +69,25 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
guard(); guard();
} }
const read = (path, sessionGuard = guard) => readAuthoritativeFile(invoke,path,sessionGuard); const read = (path, sessionGuard = guard) => readAuthoritativeFile(invoke,path,sessionGuard);
const projectFiles = createProjectFilesystem({
invoke, invokePrivateStorage: invokeCurrent, read, canWrite, groupFolder, sharedProjectsFolder, supportsSharedGroupProjects, canCreateSharedProject
});
async function loadProject(value, check) { async function loadProject(value, check) {
check(); check();
const project = reference(value); const project = reference(value);
projectFiles.requireProjectPath(project.path);
const snapshot = await read(project.manifestPath, check); const snapshot = await read(project.manifestPath, check);
if (snapshot.status !== 'found' || typeof snapshot.text !== 'string') throw new ProjectUnavailableError('Project manifest missing'); if (snapshot.status !== 'found') throw new ProjectUnavailableError('Project manifest missing');
const manifest = parseProjectManifest(JSON.parse(snapshot.text)); const manifest = manifestFromSnapshot(snapshot);
if (manifest.id !== project.projectIdentity) throw new Error('Project manifest identity differs from its host folder'); if (manifest.id !== project.projectIdentity) throw new Error('Project manifest identity changed');
return {project, manifest, snapshot}; return { project: { ...project, name: manifest.name, updatedAt: manifest.updatedAt,
archived: manifest.archived ?? project.archived, canWrite: canWrite && project.canWrite }, manifest, snapshot };
}
async function loadListedProject(value, check) {
check();
const project = await projectFiles.openReference(reference(value));
check();
return loadProject(project, check);
} }
function checkTransition(ticket) { function checkTransition(ticket) {
guard(); guard();
@@ -99,7 +120,7 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
const next = makeSession(project, manifest, snapshot); const next = makeSession(project, manifest, snapshot);
staged.set(next, {ticket}); staged.set(next, {ticket});
try { try {
if (project.canWrite === true && !project.archived) { if (!groupFolder && project.canWrite === true && !project.archived) {
const namespace = `extensions/${extensionId}`; const namespace = `extensions/${extensionId}`;
const folders = await next.listFiles('extensions', false); const folders = await next.listFiles('extensions', false);
if (!folders.some(row => row.kind === 'folder' && row.path === next.path(namespace))) { if (!folders.some(row => row.kind === 'folder' && row.path === next.path(namespace))) {
@@ -225,7 +246,14 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
async openKv(relative, options = {}) { async openKv(relative, options = {}) {
const canonical=validateArchivePath(relative); const canonical=validateArchivePath(relative);
const separator = canonical.lastIndexOf('/'); const separator = canonical.lastIndexOf('/');
if(separator>=0)await session.ensureDirectory(canonical.slice(0,separator)); 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) }); return call('kv_store_open', { ...options, path: path(canonical) });
}, },
async applyKv(relative, mutation) { async applyKv(relative, mutation) {
@@ -256,9 +284,33 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
sessions.add(session); sessions.add(session);
return 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;
}
async function leave() {
guard(); const ticket=beginTransition(); const previous=active;
await approveSwitch(previous);
if(ticket!==generation)throw abortError();
active=null; notify(); await previous?.close();
}
return { return {
scope: captured, extensionId, scope: captured, extensionId, groupFolder, sharedProjectsFolder,
supports(command) { return !projectCommands || projectCommands.includes(command); }, supports(action) {
if (sharedProjectsFolder) {
if (action === 'create') return canWrite && canCreateSharedProject;
return action === 'archive' && canWrite && supportsSharedGroupProjects;
}
if (action === 'create') return canWrite && supportsFilesystem('filesystem_create_folder')
&& (!groupFolder || supportsFilesystem('filesystem_ensure_group_folder'));
if (action === 'archive') return canWrite;
return action === 'pickFolder' && supportsFilesystem('open_workspace_folder');
},
get active() { return active; }, get state() { return state(); }, get active() { return active; }, get state() { return state(); },
provideSwitchConfirmation(handler) { provideSwitchConfirmation(handler) {
confirmationHandlers.push(handler); confirmationHandlers.push(handler);
@@ -266,66 +318,64 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
}, },
subscribe(listener) { listeners.add(listener); listener(state()); return () => listeners.delete(listener); }, subscribe(listener) { listeners.add(listener); listener(state()); return () => listeners.delete(listener); },
recent: loadRecents, recent: loadRecents,
async list(includeArchived = false) { const result = await invoke('projects_list', {includeArchived}); return result.projects.map(reference); }, async list(includeArchived = false) {
return (await projectFiles.list(includeArchived)).map(reference);
},
async pickFolder() {
return projectFiles.pickFolder(canWrite);
},
async create(name, operationId) { async create(name, operationId) {
if(typeof name !== 'string' || !name.trim())throw new TypeError('Project name required'); const creation = prepareCreation(name, operationId);
name=name.trim(); const session = await switchTo(async check => {
operationId ??= pendingCreations.get(name) ?? crypto.randomUUID(); const project = await projectFiles.create(creation.name, creation, check);
pendingCreations.set(name,operationId); return loadProject(project, check);
const session=await switchTo(async check => loadProject((await invoke('projects_create',{name,operationId})).project, check)); });
if(pendingCreations.get(name)===operationId)pendingCreations.delete(name); if (pendingCreations.get(creation.name) === creation) pendingCreations.delete(creation.name);
return session; return session;
}, },
async stageCreate(name, operationId) { async stageCreate(name, operationId, { importing = false } = {}) {
guard(); const ticket=beginTransition(); const previous=active; const version=previous?.dirtyVersion; guard();
await approveSwitch(previous); if(ticket!==generation)throw abortError(); const ticket = beginTransition();
if(typeof name!=='string'||!name.trim())throw new TypeError('Project name required');name=name.trim(); const previous = active;
operationId ??= pendingCreations.get(name) ?? crypto.randomUUID();pendingCreations.set(name,operationId); const version = previous?.dirtyVersion;
const created = await invoke('projects_create',{name,operationId}); await approveSwitch(previous);
const {project, manifest, snapshot} = await loadProject(created.project, () => checkTransition(ticket)); const check = () => checkTransition(ticket);
const session=makeSession(project,manifest,snapshot);staged.set(session,{ticket,session:previous,version,name,operationId}); check();
const creation = prepareCreation(name, operationId);
const created = await projectFiles.create(creation.name, creation, check, importing);
const { project, manifest, snapshot } = await loadProject(created, check);
if (sharedProjectsFolder && (manifest.importPending === true) !== importing) {
throw new ProjectUnavailableError('Group project import state changed');
}
const session = makeSession(project, manifest, snapshot);
staged.set(session, { ticket, session: previous, version, creation });
return session; return session;
}, },
async adopt(session) { async adopt(session) {
guard(); const approval=staged.get(session); guard();
if(!approval||approval.ticket!==generation)throw abortError();session.assertCurrent(); const approval = staged.get(session);
if (!approval || approval.ticket !== generation) throw abortError();
session.assertCurrent();
try { try {
const current = await switchTo(check => loadProject(session.project, check), approval, session); const current = await switchTo(check => loadProject(session.project, check), approval, session);
if(pendingCreations.get(approval.name)===approval.operationId)pendingCreations.delete(approval.name); if (pendingCreations.get(approval.creation.name) === approval.creation) pendingCreations.delete(approval.creation.name);
return current; return current;
} finally { await session.close(); } } finally { await session.close(); }
}, },
openListed(value) { openListed(project) { return switchTo(check => loadListedProject(project, check)); },
const selected = reference(value); async withListedProject(value, action) {
return switchTo(async check => { const { project, manifest, snapshot } = await loadListedProject(value, guard);
const commands = projectCommands ?? (await invoke('get_app_info')).projects?.commands; guard();
check(); const session = makeSession(project, manifest, snapshot);
if (!commands?.includes('projects_open_listed')) return loadProject(selected, check); try { return await action(session); } finally { await session.close(); }
const result = await bridge.invoke('projects_open_listed', {projectId: selected.id});
check();
if (result?.status !== 'ok' || result.project?.id !== selected.id) {
throw new ProjectUnavailableError('Selected project identity could not be confirmed');
}
const granted = reference(result.project);
if (granted.folderId !== selected.id || granted.projectIdentity !== selected.projectIdentity) {
throw new ProjectUnavailableError('Selected project identity could not be confirmed');
}
return loadProject(granted, check);
});
}, },
activate(project) { return switchTo(check => loadProject(project, check)); }, activate(project) { return switchTo(check => loadListedProject(project, check)); },
async share(targetGroupId, linked) { async setArchived(project, archived) {
if (!active) throw new Error('Select a project'); if (typeof archived !== 'boolean') throw new TypeError('Archive state must be a boolean');
const capturedSession = active; capturedSession.assertCurrent(); const loaded = await loadListedProject(project, guard);
const result = await invoke('projects_set_group_link',{projectId:capturedSession.project.id,targetGroupId,linked}); await projectFiles.setArchived(loaded.project, loaded.snapshot, loaded.manifest, archived);
capturedSession.assertCurrent(); return result;
},
async leave() {
guard(); const ticket=beginTransition(); const previous=active;
await approveSwitch(previous);
if(ticket!==generation)throw abortError();
active=null; notify(); await previous?.close();
}, },
leave,
async close() { async close() {
if (closed) return; closed = true; generation++; if (closed) return; closed = true; generation++;
active = null; await Promise.allSettled([...sessions].map(session=>session.close())); notify(); listeners.clear(); confirmationHandlers.length=0; active = null; await Promise.allSettled([...sessions].map(session=>session.close())); notify(); listeners.clear(); confirmationHandlers.length=0;
+2 -2
View File
@@ -1,5 +1,5 @@
<script> <script>
import ProjectWorkspace from './ProjectWorkspace.svelte'; import ProjectWorkspace from './ProjectWorkspace.svelte';
let {client,bridge,extensionName,locale='en',beforeExport}=$props(); let {client,bridge,extensionName,locale='en',onImport,onExport,onOverview,onOpen,beforeExport}=$props();
</script> </script>
<ProjectWorkspace {client} {bridge} {extensionName} {locale} {beforeExport} mode="header" /> <ProjectWorkspace {client} {bridge} {extensionName} {locale} {beforeExport} {onImport} {onExport} {onOverview} {onOpen} mode="header" />
+2 -2
View File
@@ -1,5 +1,5 @@
<script> <script>
import ProjectWorkspace from './ProjectWorkspace.svelte'; import ProjectWorkspace from './ProjectWorkspace.svelte';
let {client,bridge,extensionName,locale='en'}=$props(); let {client,bridge,extensionName,locale='en',onImport,onExport,onOverview,onOpen,showEmptyProjectMessage}=$props();
</script> </script>
<ProjectWorkspace {client} {bridge} {extensionName} {locale} mode="picker" /> <ProjectWorkspace {client} {bridge} {extensionName} {locale} {onImport} {onExport} {onOverview} {onOpen} {showEmptyProjectMessage} mode="picker" />
+2 -2
View File
@@ -1,8 +1,8 @@
<script> <script>
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { mountProjectWorkspace } from '../dom.js'; import { mountProjectWorkspace } from '../dom.js';
let {client,bridge,extensionName,locale='en',beforeExport,mode='workspace'}=$props(); let {client,bridge,extensionName,locale='en',onImport,onExport,onOverview,onOpen,beforeExport,showEmptyProjectMessage,mode='workspace'}=$props();
let target; let target;
onMount(()=>{const view=mountProjectWorkspace(target,{client,bridge,extensionName,locale,mode,beforeExport});return()=>view.destroy();}); onMount(()=>{const view=mountProjectWorkspace(target,{client,bridge,extensionName,locale,mode,beforeExport,onImport,onExport,onOverview,onOpen,showEmptyProjectMessage});return()=>view.destroy();});
</script> </script>
<div bind:this={target}></div> <div bind:this={target}></div>
+7 -1
View File
@@ -1,8 +1,14 @@
import type { ProjectClient, ProjectBridge, ProjectSession } from './index.js'; import type { ProjectClient, ProjectBridge, ProjectReference, ProjectSession } from './index.js';
export interface ProjectMountOptions { export interface ProjectMountOptions {
extensionName?: string; client: ProjectClient; bridge?: ProjectBridge; locale?: 'en' | 'nl'; extensionName?: string; client: ProjectClient; bridge?: ProjectBridge; locale?: 'en' | 'nl';
showEmptyProjectMessage?: boolean;
onOverview?: (actions: {refresh(): Promise<void>} | null) => void;
onOpen?: (project: ProjectReference) => Promise<unknown>;
onImport?: () => Promise<unknown>;
onExport?: (session: ProjectSession) => Promise<unknown>;
beforeExport?: (session: ProjectSession) => void | Promise<void>; beforeExport?: (session: ProjectSession) => void | Promise<void>;
mode?: 'workspace' | 'picker' | 'header'; mode?: 'workspace' | 'picker' | 'header';
} }
export function mountProjectWorkspace(target: HTMLElement, options: ProjectMountOptions): {destroy(): void}; export function mountProjectWorkspace(target: HTMLElement, options: ProjectMountOptions): {destroy(): void};
export function mountProjectHeader(target: HTMLElement, options: ProjectMountOptions): {destroy(): void}; export function mountProjectHeader(target: HTMLElement, options: ProjectMountOptions): {destroy(): void};
export function mountProjectListSkeleton(target: HTMLElement): {destroy(): void};
+115 -90
View File
@@ -1,126 +1,151 @@
import { mountFileBrowser } from './file-browser.js';
import { workspaceElements } from './workspace-elements.js';
import { mountOverview } from './overview.js'; import { mountOverview } from './overview.js';
import { labels } from './labels.js'; import { labels } from './labels.js';
import { exportProjectToDialog, importProjectFromDialog } from './transfer.js'; import { exportProjectToDialog, importProjectFromDialog } from './transfer.js';
import { styles } from './styles.js'; import { styles } from './styles.js';
export function mountProjectWorkspace(target, {client,bridge,locale='en',extensionName,mode='workspace',beforeExport} = {}) { export function mountProjectWorkspace(target, {client,bridge,locale='en',extensionName,mode='workspace',beforeExport,onOverview,onOpen,onImport,onExport,showEmptyProjectMessage} = {}) {
if (!target?.ownerDocument || !client) throw new TypeError('Mount target and project client required'); if (!target?.ownerDocument || !client) throw new TypeError('Mount target and project client required');
const document = target.ownerDocument; const document = target.ownerDocument;
const text = labels[locale] ?? labels.en; const text = labels[locale] ?? labels.en;
const shell = document.createElement('section'); shell.className='isa-project-ui'; const shell = document.createElement('section'); shell.className='isa-project-ui';
const style = document.createElement('style'); style.textContent=styles; const style = document.createElement('style'); style.textContent=styles;
const content = document.createElement('div'); const content = document.createElement('div');
const preview = document.createElement('div'); preview.className='isa-project-preview'; shell.append(style, content);
shell.append(style,content,preview);target.append(shell); target.append(shell);
let mounted=true,busy=false,error='',files=[],directory='',fileLoading=false,loadGeneration=0,shownSession=null; const elements = workspaceElements(document);
let removeOverview; const {make, icon, button} = elements;
let activeView, removeOverview;
const dialogs = new Set(); const dialogs = new Set();
const make = (tag,textContent,className) => {
const element=document.createElement(tag);
if (textContent != null) element.textContent=textContent;
if (className) element.className=className;
return element;
};
function button(label,action) {
const element=make('button',label,'isa-extension-button');element.type='button';element.disabled=busy;
element.addEventListener('click',()=>perform(action));return element;
}
async function perform(action) {
if (busy || !mounted) return;
busy=true;error='';render();
try {await action();} catch(failure) {if (failure?.name!=='AbortError') error=String(failure.message ?? failure);}
finally {if(mounted){busy=false;render();}}
}
function confirmDiscard() { function confirmDiscard() {
return new Promise(resolve=>{ return new Promise(resolve=>{
const dialog=make('dialog'); const dialog=make('dialog');
const question=make('p',text.dirty);question.id=`isa-project-confirm-${crypto.randomUUID()}`; const question=make('p',text.dirty);question.id=`isa-project-confirm-${crypto.randomUUID()}`;
dialog.setAttribute('aria-labelledby',question.id); dialog.setAttribute('aria-labelledby',question.id);
const actions=make('div',null,'isa-project-toolbar'); const actions=make('div',null,'isa-project-toolbar');
const cancel=make('button',text.cancel);cancel.type='button';cancel.onclick=()=>dialog.close('cancel'); const cancel=make('button',text.cancel,'isa-extension-button isa-extension-button--secondary');cancel.type='button';cancel.onclick=()=>dialog.close('cancel');
const discard=make('button',text.discard);discard.type='button';discard.onclick=()=>dialog.close('discard'); const discard=make('button',text.discard,'isa-extension-button isa-extension-button--danger');discard.type='button';discard.onclick=()=>dialog.close('discard');
actions.append(cancel,discard);dialog.append(question,actions);shell.append(dialog);dialogs.add(dialog); actions.append(cancel,discard);dialog.append(question,actions);shell.append(dialog);dialogs.add(dialog);
dialog.addEventListener('close',()=>{dialogs.delete(dialog);dialog.remove();resolve(dialog.returnValue==='discard');},{once:true}); dialog.addEventListener('close',()=>{dialogs.delete(dialog);dialog.remove();resolve(dialog.returnValue==='discard');},{once:true});
dialog.showModal();cancel.focus(); dialog.showModal();cancel.focus();
}); });
} }
const removeConfirmation = client.provideSwitchConfirmation(confirmDiscard); const removeConfirmation = client.provideSwitchConfirmation(confirmDiscard);
async function loadFiles(session,relative='') { function mountActive(session) {
const ticket=++loadGeneration; const card = make('section', null, 'isa-project-active');
directory=relative;files=[];fileLoading=true;render(); const header = make('header', null, 'isa-project-header');
const identity = make('div', null, 'isa-project-identity');
const mark = make('span', null, 'isa-project-mark');
mark.append(icon('folder'));
const heading = make('div');
const title = make('h1', session.manifest.name, 'isa-project-title');
heading.append(make('p', extensionName || text.project, 'isa-project-context'), title);
identity.append(mark, heading);
const controls = make('div', null, 'isa-project-controls');
const notice = make('p', null, 'isa-extension-notice isa-extension-notice--error');
notice.setAttribute('role', 'alert');
const menu = make('details', null, 'isa-project-actions');
const trigger = make('summary', text.actions, 'isa-extension-button isa-extension-button--ghost');
trigger.prepend(icon('more'));
const choices = make('div', null, 'isa-project-choices');
function setBusy(busy) {
card.setAttribute('aria-busy', String(busy));
for (const choice of choices.children) choice.disabled = busy;
}
function addAction(label, symbol, action) {
choices.append(button(label, async () => {
menu.open = false;
trigger.focus();
setBusy(true);
notice.textContent = '';
try { try {
const result=await session.listFiles(relative,false); await action();
if (!mounted || ticket!==loadGeneration || client.active!==session) return; } catch (error) {
files=result.filter(file=>file.path !== (relative?session.path(relative):session.project.path)); if (error?.name !== 'AbortError') notice.textContent = String(error.message ?? error);
} catch(failure) {if(mounted&&ticket===loadGeneration&&failure?.name!=='AbortError') error=String(failure.message ?? failure);} } finally {
finally {if(mounted&&ticket===loadGeneration){fileLoading=false;render();}} setBusy(false);
} }
async function showFile(session,file) { }, symbol));
const relative=file.path.slice(session.project.path.length+1);
const mime=file.contentType ?? '';
let element;
if (/^(audio|video|image)\//.test(mime)) {
if(!bridge) throw new Error('Media bridge unavailable');
const reply=await bridge.invoke('filesystem_get_download_link_file',{...session.scope,path:session.path(relative)});
session.assertCurrent();
const url=new URL(reply.downloadUrl);
if(!['http:','https:'].includes(url.protocol)) throw new Error('Unsupported project media URL');
element=make(mime.startsWith('audio/')?'audio':mime.startsWith('video/')?'video':'img');
element.src=url.toString();
if(element.tagName==='IMG') element.alt=file.name; else element.controls=true;
} else {
const reply=await session.readFile(relative);
session.assertCurrent();
if(reply.status!=='found'||typeof reply.text!=='string') throw new Error('File preview unavailable');
element=make('pre',reply.text);
} }
if(mounted&&client.active===session) {clearPreview();preview.append(element);} if (bridge && client.supports('create')) {
addAction(text.import, 'import', onImport ?? (() => importProjectFromDialog(client, {bridge})));
} }
function clearPreview() { if (bridge) {
for(const media of preview.querySelectorAll('audio,video')) {media.pause();media.removeAttribute('src');media.load();} addAction(text.export, 'export', () => onExport ? onExport(session) : exportProjectToDialog(session, {bridge, beforeExport}));
preview.replaceChildren();
} }
function render() { addAction(text.close, 'leave', () => client.leave());
if(!mounted)return; menu.append(trigger, choices);
const session=client.active; const dismissOutside = event => {
if (!session) { if (menu.open && !menu.contains(event.target)) menu.open = false;
if (!removeOverview) { };
content.replaceChildren(); document.addEventListener('pointerdown', dismissOutside);
removeOverview = mountOverview(content,{client,extensionName,text,locale, document.addEventListener('focusin', dismissOutside);
onImport:bridge && (() => importProjectFromDialog(client,{bridge}))}); menu.onkeydown = event => {
if (event.key === 'Escape' && menu.open) {
event.preventDefault();
menu.open = false;
trigger.focus();
} }
return; };
header.append(identity, controls);
card.append(header, notice);
let closeBrowser;
if (mode === 'workspace') {
const toggle = button(text.projectFiles, null, 'files', 'secondary');
const panel = make('div', null, 'isa-project-browser');
closeBrowser = mountFileBrowser(panel, toggle, {session, bridge, text, locale, elements});
controls.append(toggle);
card.append(panel);
} }
removeOverview?.(); removeOverview = null; controls.append(menu);
content.replaceChildren();shell.setAttribute('aria-busy',String(busy)); content.append(card);
const toolbar=make('div',null,'isa-project-toolbar');
if(session) toolbar.append(make('h2',session.manifest.name,'isa-project-title'));
if(bridge)toolbar.append(button(text.import,()=>importProjectFromDialog(client,{bridge})));
if(bridge&&session)toolbar.append(button(text.export,()=>exportProjectToDialog(session,{bridge,beforeExport})));
if(session) toolbar.append(button(text.close,()=>client.leave()));
content.append(toolbar);
if(error){const notice=make('p',error);notice.setAttribute('role','alert');content.append(notice);}
if(session&&mode==='workspace') {
const navigation=make('div',null,'isa-project-toolbar');navigation.append(button(text.files,()=>loadFiles(session)));
if(directory)navigation.append(button(text.back,()=>loadFiles(session,directory.split('/').slice(0,-1).join('/'))));
content.append(navigation);
if(fileLoading){const status=make('p',text.loading);status.setAttribute('role','status');content.append(status);}
else if(files.length===0)content.append(make('p',text.empty));
const list=make('div',null,'isa-project-list');
for(const file of [...files].sort((a,b)=>Number(b.kind==='folder')-Number(a.kind==='folder')||a.name.localeCompare(b.name))) {
list.append(button(file.name,()=>file.kind==='folder'?loadFiles(session,file.path.slice(session.project.path.length+1)):showFile(session,file)));
}
content.append(list);
}
}
const unsubscribe=client.subscribe(({active})=>{
if(active!==shownSession){shownSession=active;directory='';files=[];clearPreview();loadGeneration++;if(active&&mode==='workspace')void loadFiles(active);}
render();
});
client.recent().catch(failure=>{if(mounted&&failure?.name!=='AbortError'){error=String(failure.message ?? failure);render();}});
return { return {
destroy(){if(!mounted)return;mounted=false;removeOverview?.();loadGeneration++;unsubscribe();removeConfirmation();for(const dialog of dialogs)dialog.close('cancel');clearPreview();shell.remove();} session, notice, title,
destroy() {
document.removeEventListener('pointerdown', dismissOutside);
document.removeEventListener('focusin', dismissOutside);
closeBrowser?.();
card.remove();
}
};
}
function render({active}) {
if (activeView && activeView.session !== active) {
activeView.destroy();
activeView = null;
}
if (active) {
removeOverview?.();
removeOverview = null;
activeView ??= mountActive(active);
if (activeView.title.textContent !== active.manifest.name) activeView.title.textContent = active.manifest.name;
} else if (!removeOverview) {
removeOverview = mountOverview(content, {client, extensionName, text, locale, onOverview, onOpen, showEmptyProjectMessage,
onImport: onImport ?? (bridge && (() => importProjectFromDialog(client, {bridge})))});
}
}
const unsubscribe = client.subscribe(render);
client.recent().catch(error => {
if (activeView && error?.name !== 'AbortError') activeView.notice.textContent = String(error.message ?? error);
});
return {
destroy() {
unsubscribe();
removeConfirmation();
removeOverview?.();
activeView?.destroy();
activeView = null;
for (const dialog of dialogs) dialog.close('cancel');
shell.remove();
}
}; };
} }
export function mountProjectHeader(target,options) {return mountProjectWorkspace(target,{...options,mode:'header'});} export function mountProjectHeader(target,options) {return mountProjectWorkspace(target,{...options,mode:'header'});}
export { mountProjectListSkeleton } from './project-list-skeleton.js';
+157
View File
@@ -0,0 +1,157 @@
import { PROJECT_MANIFEST } from './format.js';
import { manifestFromSnapshot } from './project-filesystem.js';
export function mountFileBrowser(panel, toggle, {session, bridge, text, locale, elements}) {
const {make, icon, button} = elements;
const nav = make('nav', null, 'isa-project-path');
nav.setAttribute('aria-label', text.fileLocation);
const body = make('div', null, 'isa-project-browser-body');
panel.append(nav, body);
panel.id = 'isa-project-files-' + crypto.randomUUID();
panel.hidden = true;
toggle.setAttribute('aria-controls', panel.id);
toggle.setAttribute('aria-expanded', 'false');
let generation = 0;
function displayName(path) {
if (!path) return text.projectFiles;
if (path === PROJECT_MANIFEST) return text.projectDetails;
if (path === 'extensions') return text.extensionData;
if (path === 'assets') return text.assets;
return path.split('/').at(-1);
}
function showPath(path, focus) {
const segments = path ? path.split('/') : [];
nav.replaceChildren();
for (let index = 0; index <= segments.length; index++) {
const current = segments.slice(0, index).join('/');
if (index) nav.append(icon('chevron'));
if (index < segments.length) {
nav.append(button(displayName(current), () => open(current)));
} else {
const name = make('span', displayName(current));
name.setAttribute('aria-current', 'location');
name.tabIndex = -1;
nav.append(name);
if (focus) name.focus();
}
}
}
function clearBody() {
for (const media of body.querySelectorAll('audio, video')) {
media.pause();
media.removeAttribute('src');
media.load();
}
body.replaceChildren();
}
function list(directory, entries) {
const parent = directory ? session.path(directory) : session.project.path;
const files = entries.filter(entry => entry.path !== parent)
.sort((a, b) => Number(b.kind === 'folder') - Number(a.kind === 'folder') || a.name.localeCompare(b.name, locale));
if (!files.length) return make('p', text.empty, 'isa-project-message');
const rows = make('ul', null, 'isa-project-file-list');
for (const file of files) {
const path = file.path.slice(session.project.path.length + 1);
const folder = file.kind === 'folder';
const row = button(null, () => open(path, folder ? null : file), folder ? 'folder' : 'file');
row.append(make('span', displayName(path)), icon('chevron'));
row.title = file.name;
const item = make('li');
item.append(row);
rows.append(item);
}
return rows;
}
function manifestPreview(snapshot) {
let manifest;
try {
manifest = manifestFromSnapshot(snapshot);
} catch (error) {
if (typeof snapshot.text === 'string') return make('pre', snapshot.text);
throw error;
}
const format = new Intl.DateTimeFormat(locale, {dateStyle: 'medium', timeStyle: 'short'});
const result = make('div', null, 'isa-project-metadata');
const fields = make('dl');
for (const [label, value] of [
[text.name, manifest.name], [text.created, format.format(new Date(manifest.createdAt))],
[text.updated, format.format(new Date(manifest.updatedAt))], [text.projectId, manifest.id],
[text.formatVersion, manifest.formatVersion]
]) {
const field = make('div');
field.append(make('dt', label), make('dd', value));
fields.append(field);
}
const source = make('details');
source.append(make('summary', PROJECT_MANIFEST), make('pre', snapshot.text ?? JSON.stringify(manifest, null, 2)));
result.append(fields, source);
return result;
}
async function preview(path, file, ticket) {
const mime = file.contentType ?? '';
if (/^(audio|video|image)\//.test(mime)) {
if (!bridge) throw new Error(text.previewUnavailable);
const reply = await bridge.invoke('filesystem_get_download_link_file', {...session.scope, path: session.path(path)});
session.assertCurrent();
if (ticket !== generation) return;
const url = new URL(reply.downloadUrl);
if (!['http:', 'https:'].includes(url.protocol)) throw new Error(text.previewUnavailable);
const media = make(mime.startsWith('image/') ? 'img' : mime.startsWith('audio/') ? 'audio' : 'video');
if (media.tagName === 'IMG') media.alt = file.name;
else media.controls = true;
media.src = url.toString();
return media;
}
const reply = await session.readFile(path);
session.assertCurrent();
if (ticket !== generation) return;
if (reply.status !== 'found') throw new Error(text.previewUnavailable);
if (path === PROJECT_MANIFEST) return manifestPreview(reply);
if (typeof reply.text !== 'string') throw new Error(text.previewUnavailable);
return make('pre', reply.text);
}
async function open(path, file = null, focus = true) {
const ticket = ++generation;
clearBody();
showPath(path, focus);
body.setAttribute('aria-busy', 'true');
try {
if (file) {
const node = await preview(path, file, ticket);
if (ticket === generation) body.replaceChildren(node);
} else {
const entries = await session.listFiles(path, false);
if (ticket === generation) body.replaceChildren(list(path, entries));
}
} catch (error) {
if (ticket !== generation || error?.name === 'AbortError') return;
const notice = make('p', String(error.message ?? error), 'isa-extension-notice isa-extension-notice--error');
notice.setAttribute('role', 'alert');
body.replaceChildren(notice, button(text.retry, () => open(path, file)));
} finally {
if (ticket === generation) body.removeAttribute('aria-busy');
}
}
function close() {
generation++;
clearBody();
body.removeAttribute('aria-busy');
panel.hidden = true;
toggle.setAttribute('aria-expanded', 'false');
}
toggle.onclick = () => {
if (!panel.hidden) return close();
panel.hidden = false;
toggle.setAttribute('aria-expanded', 'true');
void open('', null, false);
};
return close;
}
+3
View File
@@ -19,6 +19,9 @@ export function parseProjectManifest(value) {
throw new TypeError(`Invalid project ${key}`); throw new TypeError(`Invalid project ${key}`);
} }
} }
if (value.archived !== undefined && typeof value.archived !== 'boolean') {
throw new TypeError('Invalid project archive state');
}
// Return a copy preserving fields belonging to newer consumers of this version. // Return a copy preserving fields belonging to newer consumers of this version.
return structuredClone(value); return structuredClone(value);
} }
+14 -6
View File
@@ -4,6 +4,7 @@ export interface ProjectManifest {
name: string; name: string;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
archived?: boolean;
[key: string]: unknown; [key: string]: unknown;
} }
export const PROJECT_FORMAT_VERSION: 1; export const PROJECT_FORMAT_VERSION: 1;
@@ -16,7 +17,7 @@ export function extensionDataPath(extensionId: string, relativePath: string): st
export interface ProjectReference { export interface ProjectReference {
id: string; folderId: string; path: string; name: string; id: string; folderId: string; path: string; name: string;
archived?: boolean; updatedAt?: string; canWrite?: boolean; instanceCreatorName?: string; instanceCreatorId?: string; instanceCreatedAt?: string; archived?: boolean; updatedAt?: string; canWrite?: boolean; hasInstance?: boolean;
projectIdentity: string; manifestPath: string; formatVersion: 1; projectIdentity: string; manifestPath: string; formatVersion: 1;
} }
export interface ProjectScope { workspaceId: string; groupId: string; } export interface ProjectScope { workspaceId: string; groupId: string; }
@@ -61,28 +62,35 @@ export interface ProjectSession {
close(): Promise<void>; close(): Promise<void>;
} }
export interface ProjectClient { export interface ProjectClient {
readonly groupFolder: boolean;
readonly sharedProjectsFolder: boolean;
readonly scope: Readonly<ProjectScope>; readonly scope: Readonly<ProjectScope>;
readonly extensionId: string; readonly extensionId: string;
readonly active: ProjectSession | null; readonly active: ProjectSession | null;
readonly state: {readonly active: ProjectSession | null; readonly recents: ProjectReference[]}; readonly state: {readonly active: ProjectSession | null; readonly recents: ProjectReference[]};
provideSwitchConfirmation(handler: (session: ProjectSession) => Promise<boolean>): () => void; provideSwitchConfirmation(handler: (session: ProjectSession) => Promise<boolean>): () => void;
subscribe(listener: (state: ProjectClient['state']) => void): () => void; subscribe(listener: (state: ProjectClient['state']) => void): () => void;
supports(command: string): boolean; supports(action: 'create' | 'archive' | 'pickFolder'): boolean;
recent(): Promise<ProjectReference[]>; recent(): Promise<ProjectReference[]>;
list(includeArchived?: boolean): Promise<ProjectReference[]>; list(includeArchived?: boolean): Promise<ProjectReference[]>;
pickFolder(): Promise<{path: string; fileId: string; canWrite: boolean} | null>;
create(name: string, operationId?: string): Promise<ProjectSession>; create(name: string, operationId?: string): Promise<ProjectSession>;
stageCreate(name: string, operationId?: string): Promise<ProjectSession>; stageCreate(name: string, operationId?: string, options?: { importing?: boolean }): Promise<ProjectSession>;
adopt(session: ProjectSession): Promise<ProjectSession>; adopt(session: ProjectSession): Promise<ProjectSession>;
openListed(project: ProjectReference): Promise<ProjectSession>; openListed(project: ProjectReference): Promise<ProjectSession>;
withListedProject<T>(project: ProjectReference, action: (session: ProjectSession) => Promise<T>): Promise<T>;
activate(project: ProjectReference): Promise<ProjectSession>; activate(project: ProjectReference): Promise<ProjectSession>;
share(targetGroupId: string, linked: boolean): Promise<any>; setArchived(project: ProjectReference, archived: boolean): Promise<void>;
leave(): Promise<void>; leave(): Promise<void>;
close(): Promise<void>; close(): Promise<void>;
} }
export class ProjectUnavailableError extends Error {} export class ProjectUnavailableError extends Error { readonly code?: 'SHARED_GROUP_PROJECTS_UNAVAILABLE'; }
export function createProjectClient(options: { export function createProjectClient(options: {
bridge: ProjectBridge; extensionId: string; scope: ProjectScope; bridge: ProjectBridge; extensionId: string; scope: ProjectScope;
projectCommands?: readonly string[]; groupFolder?: boolean;
sharedProjectsFolder?: boolean;
filesystem?: { readonly commands?: readonly string[], readonly supportsSharedGroupProjects?: boolean };
filesystemCommands?: readonly string[];
beforeSwitch?: (session: ProjectSession) => boolean | Promise<boolean>; beforeSwitch?: (session: ProjectSession) => boolean | Promise<boolean>;
isCurrent?: () => boolean; isCurrent?: () => boolean;
}): ProjectClient; }): ProjectClient;
+15 -8
View File
@@ -1,8 +1,7 @@
const encoder = new TextEncoder(); const encoder = new TextEncoder();
export function validateEntries(entries) { export function validateEntries(entries, keys = new Set()) {
if(!Array.isArray(entries))throw new Error('Invalid KV snapshot entries'); if(!Array.isArray(entries))throw new Error('Invalid KV snapshot entries');
const keys=new Set();
for(const entry of entries) { for(const entry of entries) {
if(!entry||typeof entry.key!=='string'||!entry.key||entry.key.includes('\0')||keys.has(entry.key)||entry.status!=='found'||!['value','list'].includes(entry.kind)||!Object.hasOwn(entry,'value'))throw new Error('Invalid or duplicate KV snapshot key'); if(!entry||typeof entry.key!=='string'||!entry.key||entry.key.includes('\0')||keys.has(entry.key)||entry.status!=='found'||!['value','list'].includes(entry.kind)||!Object.hasOwn(entry,'value'))throw new Error('Invalid or duplicate KV snapshot key');
keys.add(entry.key); keys.add(entry.key);
@@ -13,23 +12,31 @@ export function validateEntries(entries) {
} else if(Array.isArray(entry.value))throw new Error('Array KV values require list identities'); } else if(Array.isArray(entry.value))throw new Error('Array KV values require list identities');
} }
} }
export async function readKvSnapshot(bridge,scope,path,assertCurrent,maxBytes) { export async function readKvSnapshot(bridge,scope,path,assertCurrent,maxBytes,onPage) {
if(typeof bridge.snapshotKv!=='function')throw new Error('Host consistent KV snapshots unavailable'); if(typeof bridge.snapshotKv!=='function')throw new Error('Host consistent KV snapshots unavailable');
const entries=[],cursors=new Set();let cursor,anchor,fence; const entries=[],cursors=new Set();let cursor,anchor,fence,snapshotId;
const keys = new Set();
let encodedSize = 2; // The surrounding JSON array brackets.
do { do {
assertCurrent(); assertCurrent();
const page=await bridge.snapshotKv({...scope,path,limit:100,cursor}); const page=await bridge.snapshotKv({...scope,path,limit:100,cursor,...(cursor ? {snapshotId,revision:fence.revision} : {})});
assertCurrent(); assertCurrent();
const local=page?.local===true&&page.snapshotComplete===true&&page.nextCursor==null&&!cursor&&Number.isSafeInteger(page.localRevision); const local=page?.local===true&&page.snapshotComplete===true&&page.nextCursor==null&&!cursor&&Number.isSafeInteger(page.localRevision);
if(!Number.isSafeInteger(page?.revision)||!Array.isArray(page.entries)||page.incomplete||page.stale||(!local&&(typeof page.snapshotId!=='string'||!page.snapshotId)))throw new Error('Invalid host KV snapshot'); if(!Number.isSafeInteger(page?.revision)||!Array.isArray(page.entries)||page.incomplete||page.stale||(!local&&(typeof page.snapshotId!=='string'||!page.snapshotId)))throw new Error('Invalid host KV snapshot');
const generation=JSON.stringify([page.snapshotId??'local-complete',page.revision,page.localRevision??null,page.storeId??null,page.incarnation??null]); const generation=JSON.stringify([page.snapshotId??'local-complete',page.revision,page.localRevision??null,page.storeId??null,page.incarnation??null]);
if(anchor&&anchor!==generation)throw new Error('KV snapshot generation changed'); if(anchor&&anchor!==generation)throw new Error('KV snapshot generation changed');
anchor=generation;fence={revision:page.revision,localRevision:page.localRevision??null,storeId:page.storeId??null,incarnation:page.incarnation??null,local:page.local===true};entries.push(...page.entries); snapshotId=page.snapshotId;
if(maxBytes !== undefined && encoder.encode(JSON.stringify(entries)).length>maxBytes)throw new Error('KV snapshot exceeds transfer limit'); anchor=generation;fence={revision:page.revision,localRevision:page.localRevision??null,storeId:page.storeId??null,incarnation:page.incarnation??null,local:page.local===true};
cursor=page.nextCursor; cursor=page.nextCursor;
if(cursor!=null&&(typeof cursor!=='string'||!cursor||cursors.has(cursor)))throw new Error('Invalid or repeated KV snapshot cursor'); if(cursor!=null&&(typeof cursor!=='string'||!cursor||cursors.has(cursor)))throw new Error('Invalid or repeated KV snapshot cursor');
if(cursor)cursors.add(cursor); if(cursor)cursors.add(cursor);
validateEntries(page.entries, keys);
if (maxBytes !== undefined) {
if (page.entries.length) encodedSize += encoder.encode(JSON.stringify(page.entries)).length - 2 + (entries.length ? 1 : 0);
if (encodedSize > maxBytes) throw new Error('KV snapshot exceeds transfer limit');
}
for (const entry of page.entries) entries.push(entry);
onPage?.(page.entries);
}while(cursor); }while(cursor);
validateEntries(entries);
return {entries:entries.map(entry=>({key:entry.key,status:'found',kind:entry.kind,value:entry.value,...(entry.kind==='list'?{itemIds:entry.itemIds}:{})})),fence}; return {entries:entries.map(entry=>({key:entry.key,status:'found',kind:entry.kind,value:entry.value,...(entry.kind==='list'?{itemIds:entry.itemIds}:{})})),fence};
} }
+6 -2
View File
@@ -1,4 +1,8 @@
export const labels = { export const labels = {
en: {projects:'Projects',search:'Search projects',updated:'Last modified',sort:'Sort projects',activity:'Recent activity',noActivity:'No projects opened yet.',noProjects:'No projects yet.',noMatches:'No matching projects.',refresh:'Refresh',create:'Create project',name:'Project name',recent:'Recent projects',files:'Files',back:'Back',close:'Close project',empty:'No files',loading:'Loading…',cancel:'Cancel',discard:'Discard changes',dirty:'Discard unsaved project changes?',retry:'Retry',export:'Export project',import:'Import project'}, en: {opening:'Opening project…',noInstance:'No instance yet',owner:'Owner (creator)',creationDate:'Creation date',createInstance:'Create instance',creating:'Creating project…',newProject:'New project',createTitle:'Create new project',saveProject:'Save project',projects:'Projects',search:'Search projects',updated:'Last modified',sort:'Sort projects',activity:'Recent activity',noActivity:'No projects opened yet.',noProjects:'No projects yet.',noMatches:'No matching projects.',refresh:'Refresh',pickFolder:'Add project folder',updateHost:'Update ISA Warden to use shared group projects.',create:'Create project',name:'Project name',recent:'Recent projects',files:'Files',back:'Back',close:'Close project',empty:'No files',loading:'Loading…',cancel:'Cancel',discard:'Discard changes',dirty:'Discard unsaved project changes?',retry:'Retry',export:'Export project',import:'Import project',
nl: {projects:'Projecten',search:'Zoek op projectnaam',updated:'Laatst gewijzigd',sort:'Projecten sorteren',activity:'Recente activiteit',noActivity:'Nog geen projecten geopend.',noProjects:'Nog geen projecten.',noMatches:'Geen overeenkomende projecten.',refresh:'Vernieuwen',create:'Project maken',name:'Projectnaam',recent:'Recente projecten',files:'Bestanden',back:'Terug',close:'Project sluiten',empty:'Geen bestanden',loading:'Laden…',cancel:'Annuleren',discard:'Wijzigingen weggooien',dirty:'Niet-opgeslagen projectwijzigingen weggooien?',retry:'Opnieuw proberen',export:'Project exporteren',import:'Project importeren'} project:'Project',actions:'Project actions',projectFiles:'Project files',fileLocation:'File location',projectDetails:'Project details',extensionData:'Extension data',assets:'Assets',created:'Created',projectId:'Project ID',formatVersion:'Format version',previewUnavailable:'File preview unavailable.'
},
nl: {opening:'Project openen…',noInstance:'Nog geen instance',owner:'Eigenaar (aanmaker)',creationDate:'Aanmaakdatum',createInstance:'Instance aanmaken',creating:'Project wordt aangemaakt…',newProject:'Nieuw project',createTitle:'Nieuw project aanmaken',saveProject:'Bewaar project',projects:'Projecten',search:'Zoek op projectnaam',updated:'Laatst gewijzigd',sort:'Projecten sorteren',activity:'Recente activiteit',noActivity:'Nog geen projecten geopend.',noProjects:'Nog geen projecten.',noMatches:'Geen overeenkomende projecten.',refresh:'Vernieuwen',pickFolder:'Projectmap toevoegen',updateHost:'Werk ISA Warden bij om gedeelde groepsprojecten te gebruiken.',create:'Project maken',name:'Projectnaam',recent:'Recente projecten',files:'Bestanden',back:'Terug',close:'Project sluiten',empty:'Geen bestanden',loading:'Laden…',cancel:'Annuleren',discard:'Wijzigingen weggooien',dirty:'Niet-opgeslagen projectwijzigingen weggooien?',retry:'Opnieuw proberen',export:'Project exporteren',import:'Project importeren',
project:'Project',actions:'Projectacties',projectFiles:'Projectbestanden',fileLocation:'Bestandslocatie',projectDetails:'Projectgegevens',extensionData:'Extensiegegevens',assets:'Bronbestanden',created:'Aangemaakt',projectId:'Project-ID',formatVersion:'Formaatversie',previewUnavailable:'Bestandsvoorbeeld niet beschikbaar.'
}
}; };
+174 -55
View File
@@ -1,7 +1,11 @@
// A row always identifies a folder in the current group inventory. Private import { mountProjectListSkeleton } from './project-list-skeleton.js';
import { workspaceElements } from './workspace-elements.js';
// A row identifies a folder accessible through the current launch's grants. Private
// recents supply the activity order only, never the inventory or a grant. // recents supply the activity order only, never the inventory or a grant.
export function mountOverview(target, {client, extensionName, text, locale, onImport}) { export function mountOverview(target, {client, extensionName, text, locale, onImport, onOverview, onOpen, showEmptyProjectMessage = true}) {
const document = target.ownerDocument; const document = target.ownerDocument;
const {icon} = workspaceElements(document);
function element(tag, label, className) { function element(tag, label, className) {
const node = document.createElement(tag); const node = document.createElement(tag);
if (label) node.textContent = label; if (label) node.textContent = label;
@@ -17,115 +21,230 @@ export function mountOverview(target, {client, extensionName, text, locale, onIm
const root = element('section', '', 'isa-group-home'); const root = element('section', '', 'isa-group-home');
const header = element('header'); const header = element('header');
header.append(element('h1', extensionName || text.projects)); header.append(element('h1', extensionName || text.projects));
const summary = element('dl', '', 'isa-group-summary');
function addCount(heading, label, symbol) {
if (onOverview) {
const badge = element('span', '', 'isa-group-count');
heading.append(badge);
return badge;
}
const card = element('div');
const term = element('dt', label);
term.prepend(icon(symbol));
const value = element('dd', '—');
card.append(term, value);
summary.append(card);
return value;
}
header.append(summary);
const actions = element('div', '', 'isa-project-toolbar'); const actions = element('div', '', 'isa-project-toolbar');
const refreshButton = button(text.refresh, refresh); const refreshButton = button(text.refresh, refresh);
refreshButton.className = 'isa-extension-button isa-extension-button--secondary';
refreshButton.prepend(icon('refresh'));
actions.append(refreshButton); actions.append(refreshButton);
const pickFolder = button(text.pickFolder, () => run(async () => {
if (await client.pickFolder()) {
// An inventory requested before the picker grant may omit the new folder.
await pendingRefresh;
if (alive) await refresh();
}
}));
pickFolder.className = 'isa-extension-button isa-extension-button--secondary';
if (client.supports('pickFolder')) actions.append(pickFolder);
const importButton = button(text.import, () => run(onImport)); const importButton = button(text.import, () => run(onImport));
if (onImport && client.supports('projects_create')) actions.append(importButton); importButton.className = 'isa-extension-button isa-extension-button--secondary';
importButton.prepend(icon('import'));
if (onImport && client.supports('create')) actions.append(importButton);
header.append(actions); header.append(actions);
const grid = element('div', '', 'isa-group-grid'); const grid = element('div', '', 'isa-group-grid');
const activity = element('aside'); const activity = element('aside');
const recent = element('div'); const recent = element('div');
activity.append(element('h2', text.activity), recent); const recentTitle = element('h2', text.recent);
activity.append(recentTitle, recent);
const panel = element('section', '', 'isa-group-projects'); const panel = element('section', '', 'isa-group-projects');
const heading = element('header'); const heading = element('header');
const create = button('+ ' + text.create, () => { name.value = ''; formError.textContent = ''; dialog.showModal(); name.focus(); }); const create = button(client.groupFolder ? text.newProject : text.create, () => { name.value = ''; formError.textContent = ''; dialog.showModal(); name.focus(); });
create.className = 'isa-group-create'; create.className = 'isa-extension-button isa-extension-button--primary';
create.prepend(icon('plus'));
const panelTitle = element('h2', text.projects); const panelTitle = element('h2', text.projects);
const projectCount = addCount(panelTitle, text.projects, 'folder');
const recentCount = addCount(recentTitle, text.recent, 'clock');
panelTitle.id = 'isa-projects-' + crypto.randomUUID(); panelTitle.id = 'isa-projects-' + crypto.randomUUID();
panel.setAttribute('aria-labelledby',panelTitle.id); panel.setAttribute('aria-labelledby',panelTitle.id);
heading.append(panelTitle); heading.append(panelTitle);
if (client.supports('projects_create')) heading.append(create); if (client.supports('create')) heading.append(create);
const controls = element('div', '', 'isa-project-toolbar'); const controls = element('div', '', 'isa-project-toolbar');
const search = element('input'); const search = element('input');
search.className = 'isa-extension-input';
search.type = 'search'; search.type = 'search';
search.placeholder = text.search; search.placeholder = text.search;
search.setAttribute('aria-label',text.search); search.setAttribute('aria-label',text.search);
const sort = element('select'); const sort = element('select');
sort.className = 'isa-extension-select';
sort.setAttribute('aria-label',text.sort); sort.setAttribute('aria-label',text.sort);
for (const [value,label] of [['updated',text.updated],['name',text.name]]) { for (const [value,label] of [['updated',text.updated],['name',text.name]]) {
const option = element('option',label); option.value = value; sort.append(option); const option = element('option',label); option.value = value; sort.append(option);
} }
controls.append(search,sort); controls.append(search,sort);
const alert = element('p'); const alert = element('p', '', 'isa-group-alert');
alert.setAttribute('role','alert'); alert.setAttribute('role','alert');
const list = element('div', '', 'isa-group-rows'); const list = element('div', '', 'isa-group-rows');
const status = element('p'); const columns = element('div', '', 'isa-project-columns');
columns.append(element('span', text.name), element('span', text.owner), element('span', text.creationDate));
const status = element('p', '', 'isa-group-announcement');
status.setAttribute('role','status'); status.setAttribute('role','status');
panel.append(heading,controls,alert,status,list); panel.append(heading,controls,columns,list);
mountProjectListSkeleton(panel);
grid.append(activity,panel); grid.append(activity,panel);
const dialog = element('dialog'); const dialog = element('dialog', '', 'isa-project-create-dialog');
const title = element('h2', text.create); const title = element('h2', text.createTitle);
title.id = 'project-create-' + crypto.randomUUID(); title.id = 'project-create-' + crypto.randomUUID();
dialog.setAttribute('aria-labelledby',title.id); dialog.setAttribute('aria-labelledby',title.id);
const form = element('form'); const form = element('form');
const label = element('label', text.name); const name = element('input', '', 'isa-extension-input');
const name = element('input'); name.required = true;
name.required = true; name.maxLength = 160; label.append(name); name.maxLength = 160;
name.placeholder = text.name;
name.setAttribute('aria-label', text.name);
const formError = element('p'); formError.setAttribute('role','alert'); const formError = element('p'); formError.setAttribute('role','alert');
const cancel = button(text.cancel, () => dialog.close()); const cancel = button(text.cancel, () => dialog.close());
const submit = element('button',text.create); submit.type = 'submit'; const submit = element('button',client.groupFolder ? text.saveProject : text.create); submit.type = 'submit';
cancel.className = 'isa-extension-button isa-extension-button--secondary';
submit.className = 'isa-extension-button isa-extension-button--primary';
const progress = element('p', '', 'isa-project-create-progress');
progress.setAttribute('role','status');
const footer = element('div', '', 'isa-project-toolbar'); footer.append(cancel,submit); const footer = element('div', '', 'isa-project-toolbar'); footer.append(cancel,submit);
form.append(label,formError,footer); form.append(name,formError,footer);
dialog.append(title,form); dialog.append(title,form,progress);
root.append(header,grid,dialog); if (!onOverview) root.append(header);
else root.classList.add('isa-group-home-embedded');
root.append(alert,grid,status,dialog);
target.append(root); target.append(root);
let projects = [], recents = [], loading = true, failed = false, busy = false, alive = true, generation = 0; let projects = [], recents = [], loading = true, hasInventory = false, busy = false, alive = true;
let pendingRefresh, openingId;
const byName = new Intl.Collator(locale);
const date = new Intl.DateTimeFormat(locale,{dateStyle:'medium'}); const date = new Intl.DateTimeFormat(locale,{dateStyle:'medium'});
// The host focuses an extension iframe on pointer-down. Preserve matching
// buttons through that refresh so the subsequent click reaches the same row.
function updateRows(container, entries, detailed) {
const existing = new Map([...container.children].map(node => [node.dataset.projectId, node]));
entries.forEach((project, index) => {
let row = existing.get(project.id);
if (!row) {
row = button();
row.dataset.projectId = project.id;
if (detailed) {
row.append(element('span', '', 'isa-project-name'), element('small'), element('time'));
}
}
existing.delete(project.id);
row.onclick = () => openProject(project);
row.setAttribute('aria-busy', String(openingId === project.id));
const firstUse = project.hasInstance === false && project.canWrite && !project.archived;
if (detailed) {
row.querySelector('.isa-project-name').textContent = project.name;
row.querySelector('small').textContent = project.hasInstance === false ? text.noInstance : project.instanceCreatorName || '—';
row.title = firstUse ? text.createInstance : '';
row.querySelector('time').textContent = Number.isFinite(Date.parse(project.instanceCreatedAt)) ? date.format(new Date(project.instanceCreatedAt)) : '—';
} else row.textContent = firstUse ? `${project.name} · ${text.createInstance}` : project.name;
if (container.children[index] !== row) container.insertBefore(row, container.children[index] ?? null);
});
for (const obsolete of existing.values()) obsolete.remove();
}
function draw() { function draw() {
const needle = search.value.trim().toLocaleLowerCase(locale); const needle = search.value.trim().toLocaleLowerCase(locale);
const visible = projects.filter(p => p.name.toLocaleLowerCase(locale).includes(needle)); const visible = projects.filter(p => p.name.toLocaleLowerCase(locale).includes(needle));
visible.sort((a,b) => (sort.value === 'updated' && (Date.parse(b.updatedAt) || 0) - (Date.parse(a.updatedAt) || 0)) || a.name.localeCompare(b.name,locale)); visible.sort((a,b) => (sort.value === 'updated' && (Date.parse(b.updatedAt) || 0) - (Date.parse(a.updatedAt) || 0)) || byName.compare(a.name,b.name));
list.replaceChildren(); list.setAttribute('aria-busy', String(loading));
for (const project of visible) { columns.hidden = !visible.length;
const row = button('', () => run(() => client.openListed(project))); updateRows(list, visible, true);
const info = element('span'); info.append(element('strong',project.name),element('small',project.path)); if (!busy) {
row.append(info); let message = '';
if (Number.isFinite(Date.parse(project.updatedAt))) row.append(element('time',date.format(new Date(project.updatedAt)))); if (loading) message = text.loading;
row.disabled = busy; else if (hasInventory && !visible.length) {
list.append(row); if (needle) message = text.noMatches;
else if (showEmptyProjectMessage) message = text.noProjects;
} }
status.textContent = loading ? text.loading : visible.length || failed ? '' : needle ? text.noMatches : text.noProjects; status.textContent = message;
recent.replaceChildren();
for (const item of recents) {
const project = projects.find(p => p.id === item.id);
if (project) {
const row = button(project.name, () => run(() => client.openListed(project)));
row.disabled = busy; recent.append(row);
} }
const recentProjects = recents.map(item => projects.find(project => project.id === item.id)).filter(Boolean);
updateRows(recent, recentProjects, false);
const unknownCount = onOverview ? '' : '—';
projectCount.textContent = hasInventory ? String(onOverview ? visible.length : projects.length) : unknownCount;
recentCount.textContent = hasInventory ? String(recentProjects.length) : unknownCount;
if (!recent.childElementCount && hasInventory) recent.append(element('p',text.noActivity));
syncControls();
} }
if (!recent.childElementCount && !loading && !failed) recent.append(element('p',text.noActivity)); function syncControls() {
create.disabled = busy; importButton.disabled = busy; refreshButton.disabled = busy || loading; pickFolder.disabled = create.disabled = importButton.disabled = busy;
refreshButton.disabled = busy || loading;
refreshButton.setAttribute('aria-busy', String(loading));
list.inert = recent.inert = busy;
} }
async function refresh() { function openProject(project) {
const ticket = ++generation;
loading = true; failed = false; alert.textContent = ''; draw();
try {
const inventory = await client.list();
if (alive && ticket === generation) projects = inventory.filter(p => !p.archived);
} catch (error) {
if (alive && ticket === generation) { failed = true; alert.textContent = String(error.message ?? error); }
} finally {
if (alive && ticket === generation) { loading = false; draw(); }
}
}
async function run(action, notice = alert) {
if (busy) return; if (busy) return;
busy = true; notice.textContent = ''; form.inert = true; draw(); openingId = project.id;
for (const container of [list, recent]) {
const row = container.querySelector('[data-project-id="' + CSS.escape(project.id) + '"]');
row?.setAttribute('aria-busy', 'true');
}
if (onOpen) void run(() => onOpen(project), alert, '');
else void run(() => client.openListed(project), alert, text.opening + ' ' + project.name);
}
function refresh() {
if (pendingRefresh) return pendingRefresh;
loading = true;
alert.textContent = '';
if (!busy) status.textContent = text.loading;
list.setAttribute('aria-busy','true');
syncControls();
pendingRefresh = Promise.resolve().then(() => client.list()).then(inventory => {
if (!alive) return;
projects = inventory.filter(p => !p.archived);
hasInventory = true;
}).catch(error => {
if (!alive) return;
if (client.sharedProjectsFolder) projects = [];
hasInventory = false;
alert.textContent = error.code === 'SHARED_GROUP_PROJECTS_UNAVAILABLE' ? text.updateHost : String(error.message ?? error);
}).finally(() => {
pendingRefresh = null;
if (alive) { loading = false; draw(); }
});
return pendingRefresh;
}
async function run(action, notice = alert, message = text.loading) {
if (busy) return;
busy = true;
notice.textContent = '';
status.textContent = message;
form.inert = true;
syncControls();
try { await action(); } try { await action(); }
catch (error) { if (alive && error?.name !== 'AbortError') notice.textContent = String(error.message ?? error); } catch (error) { if (alive && error?.name !== 'AbortError') notice.textContent = String(error.message ?? error); }
finally { if (alive) { busy = false; form.inert = false; draw(); } } finally { if (alive) { busy = false; openingId = null; form.inert = false; draw(); } }
} }
dialog.oncancel = event => { if (busy) event.preventDefault(); }; dialog.oncancel = event => { if (busy) event.preventDefault(); };
form.onsubmit = event => { form.onsubmit = event => {
event.preventDefault(); event.preventDefault();
if (name.value.trim()) void run(() => client.create(name.value.trim()), formError); const projectName = name.value.trim();
if (!projectName || busy) return;
progress.textContent = text.creating;
submit.disabled = cancel.disabled = true;
void run(() => client.create(projectName), formError).finally(() => {
if (!alive) return;
progress.textContent = '';
submit.disabled = cancel.disabled = false;
name.focus();
});
}; };
search.oninput = sort.onchange = draw; search.oninput = sort.onchange = draw;
const unsubscribe = client.subscribe(state => { recents = state.recents; draw(); }); const unsubscribe = client.subscribe(state => { recents = state.recents; draw(); });
onOverview?.({refresh});
void refresh(); void refresh();
const onVisible = () => { if (!document.hidden && !busy) void refresh(); }; const onVisible = () => { if (!document.hidden && !busy) void refresh(); };
document.addEventListener('visibilitychange',onVisible); document.addEventListener('visibilitychange',onVisible);
return () => { alive = false; unsubscribe(); document.removeEventListener('visibilitychange',onVisible); root.remove(); }; document.defaultView?.addEventListener('focus',onVisible);
return () => { alive = false; onOverview?.(null); unsubscribe(); document.removeEventListener('visibilitychange',onVisible); document.defaultView?.removeEventListener('focus',onVisible); root.remove(); };
} }
+107
View File
@@ -0,0 +1,107 @@
import {confirmedWrite} from './proofs.js';
const digestPattern = /^[a-f0-9]{64}$/;
const uuidPattern = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
const encoder = new TextEncoder();
const digest = async text => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',encoder.encode(text))),
byte => byte.toString(16).padStart(2,'0')).join('');
function directory(doc) {
if (!uuidPattern.test(doc.id) || !digestPattern.test(doc.sha256)) throw new Error('Invalid document version');
return `extensions/isa-files/prepared/v1/${doc.id}/${doc.sha256}`;
}
export function isPrepared(doc) {
const ref = doc.preparation;
return ref?.version === 1 && ref.status === 'ready' && ref.sourceSha256 === doc.sha256 && digestPattern.test(ref.indexHash);
}
async function verifiedText(session,path,hash) {
const file = await session.readFile(path);
if (file.status === 'absent') return null;
const text = typeof file.bytesBase64 === 'string'
? new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(Uint8Array.from(atob(file.bytesBase64),c=>c.charCodeAt(0))) : file.text;
if (await digest(text) !== hash) throw new Error('Prepared document integrity check failed');
return text;
}
async function publish(session,bridge,path,text,hash,contentType) {
if (await verifiedText(session,path,hash) !== null) return;
const absolute = session.path(path);
try {
const reply = await bridge.invoke('filesystem_upload_files',{...session.scope,files:[{path:absolute,filename:path.split('/').at(-1),
text,contentType,replaceExisting:false,metadata:{client_operation_id:await digest(absolute+' '+hash)}}]});
confirmedWrite(reply,absolute);
} catch (error) {
if (await verifiedText(session,path,hash) === null) throw error;
return;
}
if (await verifiedText(session,path,hash) === null) throw new Error('Prepared document publication unconfirmed');
}
// Offsets use UTF-16 code units, as used by String.slice. Both files are immutable.
export async function publishPreparation(session,bridge,doc,chunks,warnings = [],separator = '\n\n') {
if (!chunks.length || !chunks.some(chunk=>chunk.content.trim())) throw new Error('Document has no readable text');
const root = directory(doc);
let offset = 0;
const passages = chunks.map((chunk,i) => {
if (typeof chunk.content !== 'string' || !chunk.anchor || !chunk.revision || chunk.revision !== chunks[0].revision) throw new Error('Invalid document passage');
const start = offset;
offset += chunk.content.length + separator.length;
return {start,end:start+chunk.content.length,anchor:chunk.anchor,pageStart:chunk.pageStart ?? null};
});
const markdown = chunks.map(chunk=>chunk.content).join(separator);
const markdownHash = await digest(markdown);
const index = JSON.stringify({version:1,documentId:doc.id,sourceSha256:doc.sha256,markdownHash,separator,revision:chunks[0].revision,passages,warnings});
const indexHash = await digest(index);
await session.ensureDirectory(root);
await publish(session,bridge,`${root}/${markdownHash}.md`,markdown,markdownHash,'text/markdown');
await publish(session,bridge,`${root}/${indexHash}.json`,index,indexHash,'application/json');
return {version:1,status:'ready',sourceSha256:doc.sha256,indexHash,warnings};
}
export async function readPreparation(session,doc) {
if (!isPrepared(doc)) throw new Error('Document preparation unavailable: '+doc.name);
const root = directory(doc);
const raw = await verifiedText(session,`${root}/${doc.preparation.indexHash}.json`,doc.preparation.indexHash);
const index = JSON.parse(raw);
if (index?.version !== 1 || index.documentId !== doc.id || index.sourceSha256 !== doc.sha256 || !digestPattern.test(index.markdownHash) ||
!['','\n\n'].includes(index.separator) || !index.revision || !Array.isArray(index.passages) || !index.passages.length || !Array.isArray(index.warnings)) throw new Error('Invalid preparation index');
const markdown = await verifiedText(session,`${root}/${index.markdownHash}.md`,index.markdownHash);
if (markdown === null) throw new Error('Prepared Markdown is missing');
let offset = 0;
const chunks = index.passages.map(({start,end,anchor,pageStart},chunkIndex) => {
if (start !== offset || !Number.isSafeInteger(end) || end < start || end > markdown.length || typeof anchor !== 'string' || !anchor) throw new Error('Invalid preparation offsets');
offset = end + index.separator.length;
return {chunkIndex,assetId:doc.id,sourceSha256:doc.sha256,name:doc.name,anchor,revision:index.revision,pageStart,content:markdown.slice(start,end)};
});
if (offset !== markdown.length+index.separator.length) throw new Error('Incomplete preparation index');
return {markdown,chunks,warnings:index.warnings};
}
export async function readAll(adapter, thread, documentId, progress = () => {}) {
const chunks = []; let cursor = 0, total = null, revision = null;
const warnings = new Set();
for (let page = 0; page < 10000; page++) {
const result = await adapter.read(thread, documentId, cursor, 40);
if (!Number.isSafeInteger(result.totalChunks) || result.totalChunks < 0 || !Array.isArray(result.chunks)) throw new Error('Host does not provide verifiable document coverage');
if (total !== null && total !== result.totalChunks) throw new Error('Document changed while reading');
total = result.totalChunks;
for (const warning of result.coverage?.warnings || []) warnings.add(warning);
for (const c of result.chunks) {
if (c.chunkIndex !== chunks.length || !c.evidence?.anchor || !c.evidence?.revision) throw new Error('Missing, repeated, or unverifiable document chunk');
revision ||= c.evidence.revision;
if (revision !== c.evidence.revision) throw new Error('Document revision changed');
chunks.push({ ...c, anchor: c.evidence.anchor, revision, pageStart: c.evidence.pageStart });
}
progress(chunks.length, total);
if (result.complete) {
if (chunks.length !== total || result.nextChunkIndex !== null) throw new Error('Incomplete document coverage');
if (!chunks.length) throw new Error('Document has no readable text');
chunks.warnings = [...warnings]; return chunks;
}
if (result.nextChunkIndex !== chunks.length || result.nextChunkIndex <= cursor) throw new Error('Invalid document pagination');
cursor = result.nextChunkIndex;
}
throw new Error('Document pagination limit reached');
}
+16
View File
@@ -0,0 +1,16 @@
import type {ProjectBridge, ProjectScope} from './index.js';
export const priceListKey: 'observations/v1';
export type PriceObservation = {supplierId?:string; supplier:string; description:string; specItem:string; unitPrice:number; unit:string; currency:string; receivedAt:string; validUntil?:string};
export type PriceItem = {id:string;value:PriceObservation};
export interface PriceQuery {
search?:string; equals?:Record<string,string>; from?:string; to?:string; facet?:string; prefix?:string;
offset?:number; version?:number; limit?:number; signal?:AbortSignal;
}
export function openPriceAsset(options:{bridge:ProjectBridge;scope:ProjectScope;access?:'read'|'read_write'}):Promise<{
folder: Readonly<{asset:'suppliers'|'prices';workspaceId:string;groupId:string;folderId:string;path:string;canWrite:boolean}>;
query(options?:PriceQuery):Promise<{items?:PriceItem[];choices?:string[];version:number;nextOffset:number|null}>;
existingIds(ids:string[], options?:{signal?:AbortSignal}):Promise<Set<string>>;
sourceVersion(id:string, options?:{signal?:AbortSignal}):Promise<number|null>;
markSourceVersion(id:string, version:number, options?:{signal?:AbortSignal}):Promise<void>;
importRows(records:PriceItem[], options?:{signal?:AbortSignal}):Promise<void>;
}>;
+136
View File
@@ -0,0 +1,136 @@
import {createSharedFolderReader, openWorkspaceAsset} from './shared-folder.js';
export const priceListKey = 'observations/v1';
const fields = ['description', 'specItem', 'supplier', 'supplierId', 'unitPrice', 'currency', 'unit', 'receivedAt', 'validUntil'];
const sort = {path: ['receivedAt'], kind: 'text', direction: 'desc'};
function publicObservation({id, value}) {
if (typeof id !== 'string' || !id.trim() || id.length > 256 || !value || !Number.isFinite(value.unitPrice)) throw new TypeError('Invalid price observation');
for (const [field, cell] of Object.entries(value)) {
if (!fields.includes(field) || (field !== 'unitPrice' && typeof cell !== 'string')) throw new TypeError('Invalid public price field: ' + field);
}
return {id, value};
}
async function readReply(bridge, path, value, signal) {
if (!value?.transferId) return value;
if (!Number.isSafeInteger(value.byteSize) || value.byteSize <= 0 || value.byteSize > 64 * 1024 * 1024) throw new Error('Invalid price query response size');
const bytes = new Uint8Array(value.byteSize);
for (let offset = 0; offset < bytes.length;) {
signal?.throwIfAborted();
const chunk = await bridge.invoke('kv_store_read_chunk', {path, transferId: value.transferId, offset});
const part = Uint8Array.from(atob(chunk.bytesBase64), c => c.charCodeAt(0));
if (chunk.offset !== offset || !part.length || part.length > bytes.length - offset) throw new Error('Incomplete price query response');
bytes.set(part, offset);
offset += part.length;
}
return JSON.parse(new TextDecoder('utf-8', {fatal:true}).decode(bytes));
}
export async function openPriceAsset({bridge, scope, access}) {
const folder = await openWorkspaceAsset({bridge, scope, asset: 'prices', access});
const path = folder.path + '/prices.kv';
const scoped = {invoke:(command,args) => bridge.invoke(command, {...args,workspaceId:folder.workspaceId,groupId:folder.groupId})};
const reader = createSharedFolderReader({bridge, scope, folder});
const clientId = crypto.randomUUID();
let sequence = 0;
let identity;
async function open(create) {
if (identity) return identity;
if (!create && !(await reader.listFiles()).some(f => f.path === path && f.kind === 'file')) return null;
const opened = await scoped.invoke('kv_store_open', {path, syncable:false});
if (!opened?.storeId || !opened.incarnation) throw new Error('Price store identity unavailable');
if (identity && (opened.storeId !== identity.storeId || opened.incarnation !== identity.incarnation)) throw new Error('Price store changed');
identity = {storeId: opened.storeId, incarnation: opened.incarnation};
return identity;
}
async function request(args, signal) {
signal?.throwIfAborted();
const reply = await readReply(scoped, path, await scoped.invoke('kv_store_query_list', {path, ...identity, key:priceListKey, ...args}), signal);
signal?.throwIfAborted();
if (!identity || reply?.storeId !== identity.storeId || reply.incarnation !== identity.incarnation || !Number.isSafeInteger(reply.revision)) throw new Error('Price store changed');
return reply;
}
async function lookup(key, ids, signal) {
const reply = await request({key, ids}, signal);
if (!Array.isArray(reply.page?.items)) throw new Error('Unable to verify saved prices');
return {reply, saved:new Map(reply.page.items.map(row => [row.id, row.value]))};
}
async function update(key, ids, changes, signal) {
const store = await open(true);
for (let attempt = 0;; attempt++) {
const {reply, saved} = await lookup(key, ids, signal);
if (reply.supportsExpectedRevision !== true) throw new Error('Host does not support conditional price updates');
const operations = changes(saved);
if (!operations.length) return;
signal?.throwIfAborted();
try {
const ack = await scoped.invoke('kv_store_apply', {path, ...store, expectedRevision:reply.revision, clientId, sequence:++sequence, operations});
if (ack?.storeId !== store.storeId || ack.incarnation !== store.incarnation || !Number.isSafeInteger(ack.acceptedRevision) || ack.pending === true) throw new Error('Workspace price publication unconfirmed');
return;
} catch (error) {
if (attempt >= 5 || !/revision_conflict/.test(error?.message ?? String(error))) throw error;
}
}
}
return {
folder,
async query({search = '', equals = {}, from, to, facet, prefix, offset = 0, version, limit = 30, signal} = {}) {
if (!(await open(false))) {
if (offset > 0) throw new Error('cursor_stale');
return {items:[],choices:[],version:0,nextOffset:null};
}
const query = {fields,search,equals,offset,version,facet,prefix,...((from || to) && {range:{field:'receivedAt',from:from || undefined,to:to || undefined}})};
for (let attempt = 0;; attempt++) {
const {page} = await request({query,sort,limit}, signal);
if (page?.status !== 'indexing') {
if (!Number.isSafeInteger(page?.version) || !Array.isArray(facet ? page.choices : page.items)
|| (page.nextOffset != null && (!Number.isSafeInteger(page.nextOffset) || page.nextOffset <= offset))) throw new Error('Invalid price page');
return page;
}
if (attempt === 120) throw new Error('The price index is still being prepared');
await new Promise(resolve => setTimeout(resolve, Math.min(1000, 100 + attempt * 100)));
}
},
// Historical observations are immutable. Replays may add a previously unknown supplier link.
async importRows(records, {signal} = {}) {
if (!folder.canWrite) throw new Error('Price asset is read-only');
if (!records.length) return;
for (let i = 0; i < records.length; i += 50) {
const batch = records.slice(i, i + 50).map(publicObservation);
await update(priceListKey, batch.map(row => row.id), saved => {
const operations = [];
for (const {id, value} of batch) {
const previous = saved.get(id);
if (previous && (previous.supplierId || !value.supplierId)) continue;
const observation = previous ? {...previous, supplierId:value.supplierId} : value;
operations.push({kind:'list_put',key:priceListKey,id,value:observation});
}
return operations;
}, signal);
}
},
async existingIds(ids, {signal} = {}) {
if (!(await open(false))) return new Set();
return new Set((await lookup(priceListKey, ids, signal)).saved.keys());
},
// The source fingerprint includes its incarnation. Record only a fully acknowledged
// scan, so interruption and concurrent imports always converge on the same IDs.
async sourceVersion(id, {signal} = {}) {
if (!(await open(false))) return null;
return (await lookup('imports/v1', [id], signal)).saved.get(id)?.version ?? null;
},
async markSourceVersion(id, version, {signal} = {}) {
if (!folder.canWrite) throw new Error('Price asset is read-only');
if (!Number.isSafeInteger(version) || version < 1) throw new Error('Invalid source version');
const key = 'imports/v1';
await update(key, [id], saved => (saved.get(id)?.version ?? 0) >= version
? [] : [{kind:'list_put',key,id,value:{version}}], signal);
}
};
}
+304
View File
@@ -0,0 +1,304 @@
import { createProjectManifest, parseProjectManifest, validateArchivePath } from './format.js';
import { confirmedWrite } from './proofs.js';
import { ProjectUnavailableError } from './shared-read.js';
const ROOTS_KEY = 'isa-project-format.folders.v1';
const folderKey = id => String(id).replace(/^workspace_file:/, '');
const isSharedProject = path => typeof path === 'string' && /^\/groups\/_group_ids\/[a-f0-9]{64}\/projects\/[^/]+\.isap$/.test(path);
function unavailableGrant(error) {
const message = String(error?.message ?? error).toLowerCase();
return message.includes('extension filesystem permission is required')
|| message.includes('filesystem path requires a current extension root or picker grant');
}
function folderReference(value) {
const { path, fileId = value.id, access, canWrite, archivedAt, hasInstance } = value;
if (typeof fileId !== 'string' || !fileId || typeof path !== 'string' || !path.startsWith('/')) {
throw new ProjectUnavailableError('Invalid project folder reference');
}
validateArchivePath(path.slice(1));
return { path, fileId, instanceCreatorName: value.instanceCreatorName, instanceCreatorId: value.instanceCreatorId, instanceCreatedAt: value.instanceCreatedAt, canWrite: access ? access === 'read_write' : canWrite === true, archivedAt,
...(typeof hasInstance === 'boolean' && { hasInstance }) };
}
export function manifestFromSnapshot(snapshot) {
let text = snapshot.text;
if (typeof text !== 'string' && typeof snapshot.bytesBase64 === 'string') {
text = new TextDecoder('utf-8', { fatal: true }).decode(
Uint8Array.from(atob(snapshot.bytesBase64), character => character.charCodeAt(0))
);
}
return parseProjectManifest(JSON.parse(text));
}
export function createProjectFilesystem({ invoke, invokePrivateStorage, read, canWrite, groupFolder, sharedProjectsFolder, supportsSharedGroupProjects, canCreateSharedProject }) {
let selecting;
async function selectedRoots() {
const saved = await invokePrivateStorage('localstorage_get', { key: ROOTS_KEY, sync: false });
if (saved == null) return [];
if (!Array.isArray(saved)) throw new ProjectUnavailableError('Invalid project folder settings');
return saved.map(folderReference);
}
async function groupRoot() {
const group = await invoke('filesystem_ensure_group_folder', {});
return folderReference({ path: group.path, fileId: group.folderId, canWrite: true });
}
async function roots() {
const selected = await selectedRoots();
if (!groupFolder) return selected;
const root = await groupRoot();
return [root, ...selected.filter(item => item.path !== root.path)];
}
async function pickFolder(editable = canWrite) {
if (sharedProjectsFolder) throw new ProjectUnavailableError('The launch group determines the project folder');
if (selecting) return selecting;
selecting = (async () => {
const result = await invoke('open_workspace_folder', {
accessPolicy: editable ? 'editable' : 'read-only',
allowSharing: false
});
if (result?.canceled) return null;
if (result?.file?.kind !== 'folder') throw new ProjectUnavailableError('The selected folder was not granted');
const folder = folderReference(result.file);
const previous = await selectedRoots();
await invokePrivateStorage('localstorage_put', {
key: ROOTS_KEY, sync: false,
value: [...previous.filter(item => item.path !== folder.path), folder]
});
return folder;
})();
try {
return await selecting;
} finally {
selecting = undefined;
}
}
async function files(path, recursive) {
const inventory = await invoke('filesystem_list_dir', { path, recursive, cachePolicy: 'dashboard-required' });
if (inventory?.authoritative !== true || inventory.snapshotComplete === false || inventory.error ||
!Array.isArray(inventory.files) || inventory.files.some(file =>
file?.path !== path && !file?.path?.startsWith(path + '/'))) {
throw new ProjectUnavailableError('Project folder inventory unavailable');
}
return inventory.files;
}
async function resolveRoot(root, recursive) {
let inventory;
try {
inventory = await files(root.path, recursive);
} catch (error) {
if (unavailableGrant(error)) return null;
throw error;
}
const current = inventory.find(entry => entry.path === root.path && entry.kind === 'folder');
if (!current || folderKey(current.fileId ?? current.id) !== folderKey(root.fileId)) return null;
return { inventory, current, writable: root.canWrite && current.canWrite !== false };
}
function projectFrom(folder, manifest) {
return {
id: folder.fileId, folderId: folder.fileId, path: folder.path,
name: manifest.name, instanceCreatorName: folder.instanceCreatorName, instanceCreatorId: folder.instanceCreatorId, instanceCreatedAt: folder.instanceCreatedAt, projectIdentity: manifest.id,
canWrite: canWrite && folder.canWrite, updatedAt: manifest.updatedAt, hasInstance: folder.hasInstance,
archived: manifest.archived ?? Boolean(folder.archivedAt)
};
}
function requireSharedCatalog() {
if (supportsSharedGroupProjects) return;
const error = new ProjectUnavailableError('Update ISA Warden to use shared group projects.');
error.code = 'SHARED_GROUP_PROJECTS_UNAVAILABLE';
throw error;
}
function requireProjectPath(path) {
if (!sharedProjectsFolder) return;
requireSharedCatalog();
if (!isSharedProject(path)) throw new ProjectUnavailableError('Project is outside the shared group folder');
}
async function projectFolders() {
if (sharedProjectsFolder) {
requireSharedCatalog();
const result = await invoke('filesystem_list_group_projects', {});
if (result?.authoritative !== true || result.error || !Array.isArray(result.folders)) {
throw new ProjectUnavailableError('Group project inventory unavailable');
}
return result.folders.filter(row => isSharedProject(row?.path)).map(row => ({
...folderReference(row), manifest: row.manifest
}));
}
const folders = new Map();
for (const root of await roots()) {
const resolved = await resolveRoot(root, true);
if (!resolved) continue;
const { inventory, current, writable } = resolved;
if (root.path.endsWith('.isap')) {
folders.set(root.path, { ...root, fileId: current.fileId ?? current.id,
archivedAt: current.archivedAt ?? root.archivedAt, canWrite: writable });
continue;
}
for (const entry of inventory) {
if (entry.kind !== 'folder' || !entry.path.endsWith('.isap') || entry.canRead === false) continue;
const relativeParts = entry.path.slice(root.path.length + 1).split('/');
if (relativeParts.slice(0, -1).some(part => part.endsWith('.isap'))) continue;
const folder = folderReference({ ...entry, canWrite: entry.canWrite !== false });
folder.canWrite = writable && folder.canWrite;
const previous = folders.get(folder.path);
if (!previous || folder.canWrite) folders.set(folder.path, folder);
}
}
return [...folders.values()];
}
async function openReference(project) {
if (!sharedProjectsFolder) return project;
requireProjectPath(project.path);
const row = await invoke('filesystem_open_group_project', { folderId: project.folderId });
const current = folderReference(row);
if (current.path !== project.path || folderKey(current.fileId) !== folderKey(project.folderId)) {
throw new ProjectUnavailableError('Project folder identity changed');
}
return { ...project, id: current.fileId, folderId: current.fileId,
canWrite: current.canWrite, archived: Boolean(current.archivedAt), hasInstance: current.hasInstance,
instanceCreatorName: current.instanceCreatorName, instanceCreatorId: current.instanceCreatorId, instanceCreatedAt: current.instanceCreatedAt };
}
async function list(includeArchived) {
const projects = [];
const candidates = await projectFolders();
// Bound concurrent manifest reads independently of the size of the container.
for (let start = 0; start < candidates.length; start += 12) {
const batch = await Promise.all(candidates.slice(start, start + 12).map(async folder => {
let snapshot;
if (!sharedProjectsFolder) {
try {
snapshot = await read(folder.path + '/project.json');
} catch (error) {
if (unavailableGrant(error)) return null;
throw error;
}
if (snapshot.status === 'absent') return null;
}
try {
const manifest = sharedProjectsFolder ? parseProjectManifest(folder.manifest) : manifestFromSnapshot(snapshot);
return manifest.importPending === true ? null : projectFrom(folder, manifest);
} catch {
// A folder with the suffix can contain an unrelated or unsupported manifest.
return null;
}
}));
projects.push(...batch.filter(project => project && (includeArchived || !project.archived)));
}
return projects.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt)
|| a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
}
async function ensureFolder(path) {
try {
const result = await invoke('filesystem_create_folder', { path });
if (result?.status === 'ok' && result.path === path && result.fileId) {
return folderReference({ ...result, canWrite: true });
}
throw new ProjectUnavailableError('Project directory creation was not confirmed');
} catch (error) {
const parent = path.slice(0, path.lastIndexOf('/'));
const existing = (await files(parent, false)).find(row => row.path === path && row.kind === 'folder');
if (!existing || existing.canWrite === false) throw error;
return folderReference({ ...existing, canWrite: true });
}
}
async function creationFolder(name, creation, check) {
if (sharedProjectsFolder) {
requireSharedCatalog();
if (!canCreateSharedProject) throw new ProjectUnavailableError('Group project creation is unavailable');
const row = await invoke('filesystem_create_group_project', {
projectId: creation.id, name
});
if (!isSharedProject(row?.path) || row.canWrite !== true) {
throw new ProjectUnavailableError('Group project creation was not confirmed');
}
return folderReference(row);
}
if (!creation.root) {
const available = groupFolder ? [await groupRoot()] : await selectedRoots();
const candidates = available.filter(root => root.canWrite && !root.path.endsWith('.isap'));
const shared = candidates.findIndex(root => root.path === '/shared');
if (shared > 0) candidates.unshift(...candidates.splice(shared, 1));
// Recursive filesystem listings include the directory row needed to verify its ID.
for (const candidate of candidates) {
const resolved = await resolveRoot(candidate, true);
check();
if (resolved?.writable) {
creation.root = candidate;
break;
}
}
if (groupFolder && !creation.root) throw new ProjectUnavailableError('Group project folder unavailable');
creation.root ??= await pickFolder(true);
check();
}
if (!creation.root) throw new DOMException('Project folder selection canceled', 'AbortError');
if (!creation.root.canWrite || creation.root.path.endsWith('.isap')) {
creation.root = null;
throw new ProjectUnavailableError('Choose an editable folder to store projects');
}
const prefix = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 70);
return ensureFolder(`${creation.root.path}/${prefix || 'project'}-${creation.id}.isap`);
}
async function create(name, creation, check, importing = false) {
if (!canWrite) throw new ProjectUnavailableError('Project folder is read-only');
const manifest = createProjectManifest({ id: creation.id, name });
if (importing) manifest.importPending = true;
const folder = await creationFolder(name, creation, check);
check();
const path = folder.path;
const manifestPath = path + '/project.json';
const existing = await read(manifestPath, check);
if (existing.status === 'found') {
const saved = manifestFromSnapshot(existing);
if (saved.id !== manifest.id || saved.name !== manifest.name) {
throw new ProjectUnavailableError('Project folder is already in use');
}
return projectFrom(folder, saved);
}
await ensureFolder(path + '/extensions');
check();
await ensureFolder(path + '/assets');
check();
try {
confirmedWrite(await invoke('filesystem_upload_files', { files: [{
path: manifestPath, text: JSON.stringify(manifest), contentType: 'application/json',
replaceExisting: false
}] }), manifestPath);
} catch (error) {
const current = await read(manifestPath, check);
if (current.status === 'absent') throw error;
const saved = manifestFromSnapshot(current);
if (saved.id !== manifest.id || saved.name !== manifest.name) throw error;
}
return projectFrom(folder, manifest);
}
async function setArchived(project, snapshot, manifest, archived) {
if (!canWrite || project.canWrite !== true) throw new ProjectUnavailableError('Project folder is read-only');
if (project.archived === archived) return;
const value = { ...manifest, archived, updatedAt: new Date().toISOString() };
confirmedWrite(await invoke('filesystem_upload_files', { files: [{
path: project.manifestPath, text: JSON.stringify(value), contentType: 'application/json',
replaceExisting: true, expectedSyncRevision: snapshot.syncRevision, expectedContentHash: snapshot.contentHash
}] }), project.manifestPath);
}
return { list, pickFolder, create, setArchived, requireProjectPath, openReference };
}
+52
View File
@@ -0,0 +1,52 @@
// Both the extension startup view and the live picker use these decorative rows.
const styles = `
.isa-project-list-skeleton {
container-type:inline-size;
--skeleton-line:var(--isa-extension-border-subtle,ButtonBorder);
--skeleton-highlight:var(--isa-extension-panel-bg,Canvas);
}
.isa-project-list-skeleton > div {
display:grid;
grid-template-columns:minmax(0,1fr) minmax(8rem,24%) 7rem;
align-items:center;
gap:.375rem .75rem;
min-height:2rem;
padding:.375rem .5rem;
box-sizing:border-box;
}
.isa-project-list-skeleton > div + div {border-block-start:1px solid var(--skeleton-line)}
.isa-project-list-skeleton span {
width:75%;
height:.65rem;
border-radius:var(--isa-extension-radius-detail,.5rem);
background:linear-gradient(90deg,var(--skeleton-line) 25%,var(--skeleton-highlight) 50%,var(--skeleton-line) 75%);
background-size:200% 100%;
}
.isa-project-list-skeleton > div:nth-of-type(even) > span:first-child {width:55%}
.isa-project-list-skeleton span:last-child {width:58%;justify-self:end}
@container (max-width:34rem) {
.isa-project-list-skeleton > div {grid-template-columns:minmax(0,1fr) minmax(3rem,24%);padding-block:.5rem}
.isa-project-list-skeleton span:first-child {grid-column:1 / -1}
}
@media (prefers-reduced-motion:no-preference) {
.isa-project-list-skeleton span {animation:isa-project-list-shimmer 1.5s ease-in-out infinite}
}
@keyframes isa-project-list-shimmer {from {background-position:200% 0} to {background-position:0 0}}
`;
export function mountProjectListSkeleton(target) {
const document = target.ownerDocument;
const skeleton = document.createElement('div');
skeleton.className = 'isa-project-list-skeleton';
skeleton.setAttribute('aria-hidden', 'true');
const style = document.createElement('style');
style.textContent = styles;
skeleton.append(style);
for (let index = 0; index < 4; index++) {
const row = document.createElement('div');
row.append(document.createElement('span'), document.createElement('span'), document.createElement('span'));
skeleton.append(row);
}
target.append(skeleton);
return { destroy: () => skeleton.remove() };
}
+12
View File
@@ -1,4 +1,16 @@
import type { ProjectBridge, ProjectScope, ProjectRead } from './index.js'; import type { ProjectBridge, ProjectScope, ProjectRead } from './index.js';
export type WorkspaceAsset = 'suppliers' | 'prices' | 'bid_history';
export interface WorkspaceAssetGrant {
readonly asset: WorkspaceAsset; readonly workspaceId: string; readonly groupId: string;
readonly folderId: string; readonly path: string; readonly canWrite: boolean;
}
export function openWorkspaceAsset(options: {
bridge: ProjectBridge; scope: ProjectScope; asset: WorkspaceAsset; access?: 'read' | 'read_write';
assertCurrent?: () => void;
}): Promise<WorkspaceAssetGrant>;
export function writeWorkspaceAssetJson(options: {
bridge: ProjectBridge; scope: ProjectScope; folder: WorkspaceAssetGrant; assertCurrent?: () => void;
}, relative: string, value: unknown, base: ProjectRead): Promise<{fileId: string; path: string; [key: string]: unknown}>;
export function createSharedFolderReader(options: { export function createSharedFolderReader(options: {
bridge: ProjectBridge; bridge: ProjectBridge;
scope: ProjectScope; scope: ProjectScope;
+51
View File
@@ -1,6 +1,57 @@
import { validateArchivePath } from './format.js'; import { validateArchivePath } from './format.js';
import { readAuthoritativeFile } from './shared-read.js'; import { readAuthoritativeFile } from './shared-read.js';
import { readKvSnapshot } from './kv-snapshot.js'; import { readKvSnapshot } from './kv-snapshot.js';
import { confirmedWrite } from './proofs.js';
const workspaceAssets = ['suppliers', 'prices', 'bid_history'];
/** Obtain the calling extension's grant to a workspace-owned dataset. */
export async function openWorkspaceAsset({bridge, scope, asset, access, assertCurrent = () => {}}) {
if (typeof bridge?.invoke !== 'function' || !scope?.workspaceId || !scope?.groupId) {
throw new TypeError('Host bridge and launch scope required');
}
if (!workspaceAssets.includes(asset) || (access !== undefined && !['read', 'read_write'].includes(access))) {
throw new TypeError('Invalid workspace asset or access mode');
}
const {workspaceId, groupId} = scope;
assertCurrent();
const folder = await bridge.invoke('filesystem_open_workspace_asset', {asset, ...(access && {access})});
assertCurrent();
if (folder?.asset !== asset || folder.workspaceId !== workspaceId || folder.groupId !== groupId ||
typeof folder.folderId !== 'string' || !folder.folderId || folder.path !== '/shared/' + asset ||
typeof folder.canWrite !== 'boolean' || (access === 'read_write' && !folder.canWrite) ||
(access === 'read' && folder.canWrite)) {
throw new Error('Invalid workspace asset grant for this launch');
}
return Object.freeze({asset, workspaceId, groupId, path: folder.path, folderId: folder.folderId, canWrite: folder.canWrite});
}
/** Conditionally create or replace one JSON file under an opened workspace asset. */
export async function writeWorkspaceAssetJson({bridge, scope, folder, assertCurrent = () => {}}, relative, value, base) {
if (folder?.canWrite !== true || !workspaceAssets.includes(folder.asset) ||
folder.path !== '/shared/' + folder.asset || !folder.folderId || !scope?.workspaceId || !scope.groupId ||
folder.workspaceId !== scope.workspaceId || folder.groupId !== scope.groupId) {
throw new Error('A writable workspace asset grant for this launch is required');
}
const path = folder.path + '/' + validateArchivePath(relative);
const replace = base?.status === 'found';
if (base?.path !== path || (!replace && base.status !== 'absent') ||
(replace && (!base.fileId || base.authoritative !== true || !Number.isSafeInteger(base.syncRevision) || base.syncRevision < 0))) {
throw new TypeError('An authoritative read of the target file is required');
}
const file = {path, text:JSON.stringify(value), contentType:'application/json', replaceExisting:replace};
if (replace) {
file.expectedSyncRevision = base.syncRevision;
const hash = base.serverContentHash || (base.contentHashVerified && base.contentHash);
if (hash) file.expectedContentHash = hash;
}
assertCurrent();
const reply = await bridge.invoke('filesystem_upload_files', {
workspaceId:scope.workspaceId, groupId:scope.groupId, files:[file]
});
assertCurrent();
return confirmedWrite(reply, path);
}
/** Reads through the calling extension's own host grant. The folder can also /** Reads through the calling extension's own host grant. The folder can also
* be the root of an open project session. No source is opened for writing. */ * be the root of an open project session. No source is opened for writing. */
+221 -31
View File
@@ -1,41 +1,231 @@
export const styles = ` export const styles = `
.isa-project-ui {color:var(--isa-extension-panel-text,CanvasText);font-family:var(--isa-extension-font-family,system-ui);display:flex;flex-direction:column;gap:var(--isa-extension-space-3,.75rem)} .isa-project-ui {color:var(--isa-extension-panel-text,CanvasText);font-family:var(--isa-extension-font-family,system-ui);display:flex;flex-direction:column;gap:var(--isa-extension-space-3,.75rem)}
.isa-project-ui .isa-project-toolbar,.isa-project-ui form {display:flex;align-items:center;gap:var(--isa-extension-space-2,.5rem);flex-wrap:wrap} .isa-project-ui .isa-project-toolbar,.isa-project-ui form {display:flex;align-items:center;gap:var(--isa-extension-space-2,.5rem);flex-wrap:wrap}
.isa-project-ui .isa-project-title {margin:0 auto 0 0;font-size:1.125rem;font-weight:600;overflow-wrap:anywhere} :where(.isa-project-ui button),.isa-project-ui input {font:inherit;min-height:var(--isa-extension-control-height,2.25rem);box-sizing:border-box;border:1px solid var(--isa-extension-border,ButtonBorder);border-radius:var(--isa-extension-radius-control,.75rem);padding:.375rem .75rem;color:inherit;background:var(--isa-extension-control-bg,Canvas)}
.isa-project-ui .isa-project-list {display:flex;flex-direction:column;gap:var(--isa-extension-space-1,.25rem);margin-block:var(--isa-extension-space-2,.5rem)}
.isa-project-ui button,.isa-project-ui input {font:inherit;min-height:36px;box-sizing:border-box;border:1px solid var(--isa-extension-border,ButtonBorder);border-radius:var(--isa-extension-radius-sm,.375rem);padding:.375rem .75rem;color:inherit;background:var(--isa-extension-control-bg,Canvas)}
.isa-project-ui input {flex:1;min-width:8rem} .isa-project-ui input {flex:1;min-width:8rem}
.isa-project-ui button {cursor:pointer;text-align:start} :where(.isa-project-ui button) {cursor:pointer;text-align:start}
.isa-project-ui button:hover:not(:disabled) {background:var(--isa-extension-card-hover-bg,ButtonFace)} :where(.isa-project-ui button:hover:not(:disabled)) {background:var(--isa-extension-card-hover-bg,ButtonFace)}
.isa-project-ui button:focus-visible,.isa-project-ui input:focus-visible {outline:2px solid var(--isa-extension-focus-ring,Highlight);outline-offset:2px} :where(.isa-project-ui button:focus-visible),.isa-project-ui input:focus-visible {outline:2px solid var(--isa-extension-focus-outline,Highlight);outline-offset:2px}
.isa-project-ui button:disabled {opacity:.55;cursor:default} :where(.isa-project-ui button:disabled) {opacity:.55;cursor:default}
.isa-project-ui [role=alert] {color:var(--isa-extension-danger-text,CanvasText);overflow-wrap:anywhere} :where(.isa-project-ui [role=alert]) {color:var(--isa-extension-danger,CanvasText);overflow-wrap:anywhere}
.isa-project-ui .isa-project-heading {font-size:1rem;font-weight:600;margin:.75rem 0 .375rem} .isa-project-ui dialog {color:inherit;background:var(--isa-extension-panel-bg,Canvas);border:1px solid var(--isa-extension-border,ButtonBorder);border-radius:var(--isa-extension-radius-panel,1rem);max-width:28rem;padding:var(--isa-extension-space-4,1rem);box-shadow:var(--isa-extension-modal-shadow,none)}
.isa-project-ui .isa-project-preview audio,.isa-project-ui .isa-project-preview video,.isa-project-ui .isa-project-preview img {display:block;max-width:100%} .isa-project-ui dialog::backdrop {background:var(--isa-extension-modal-backdrop,rgb(0 0 0/.4))}
.isa-project-ui .isa-project-preview pre {white-space:pre-wrap;overflow-wrap:anywhere}
.isa-project-ui dialog {color:inherit;background:var(--isa-extension-panel-bg,Canvas);border:1px solid var(--isa-extension-border,ButtonBorder);border-radius:var(--isa-extension-radius-sm,.375rem);max-width:28rem;padding:1rem}
.isa-project-ui dialog::backdrop {background:rgb(0 0 0/.4)}
.isa-group-home {display:grid;gap:9px;padding:10px;min-height:75vh;grid-template-rows:auto 1fr;background:var(--isa-extension-app-bg,var(--isa-extension-panel-bg,Canvas))} .isa-project-active {
.isa-group-home > header,.isa-group-projects {background:var(--isa-extension-card-bg,Canvas);border:1px solid var(--isa-extension-border-subtle,GrayText);border-radius:14px;padding:14px 18px} margin:var(--isa-extension-shell-gutter,1rem) var(--isa-extension-shell-gutter,1rem) 0;
.isa-group-home header {display:flex;gap:12px;align-items:center;justify-content:space-between;flex-wrap:wrap} background:var(--isa-extension-panel-bg,Canvas);
border:1px solid var(--isa-extension-border-subtle,ButtonBorder);
border-radius:var(--isa-extension-radius-panel,1rem);
}
.isa-project-header {
display:flex;
align-items:center;
justify-content:space-between;
flex-wrap:wrap;
gap:.75rem 1.5rem;
padding:1rem 1.25rem;
}
.isa-project-identity {display:flex;align-items:center;gap:.875rem;flex:1 1 24rem;min-width:0}
.isa-project-identity > div {min-width:0}
.isa-project-identity .isa-project-context {
margin:0 0 .18rem;
color:var(--isa-extension-panel-muted,CanvasText);
font-size:var(--isa-extension-font-size-xs,.8125rem);
font-weight:600;
line-height:1.35;
}
.isa-project-identity .isa-project-title {
margin:0;
color:var(--isa-extension-panel-heading,CanvasText);
font-size:var(--isa-extension-font-size-xl,1.25rem);
font-weight:650;
line-height:1.25;
overflow-wrap:anywhere;
}
.isa-project-mark {
display:grid;
place-items:center;
flex:none;
width:2.75rem;
height:2.75rem;
border-radius:var(--isa-extension-radius-control,.75rem);
color:var(--isa-extension-primary-strong,CanvasText);
background:var(--isa-extension-primary-soft,ButtonFace);
}
.isa-project-icon {display:block;width:1rem;height:1rem;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
.isa-project-mark svg {width:1.35rem;height:1.35rem}
.isa-project-controls,.isa-project-path {display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}
.isa-project-active :is(button,summary) {cursor:pointer}
.isa-project-active :is(button,summary):focus-visible,.isa-project-path [aria-current]:focus-visible {outline:2px solid var(--isa-extension-focus-outline,Highlight);outline-offset:2px}
.isa-project-controls :is(button,summary),.isa-project-file-list button {
display:inline-flex;align-items:center;gap:.5rem;min-height:var(--isa-extension-control-height,2.25rem);
font-family:inherit;font-size:var(--isa-extension-font-size-sm,.875rem);
}
.isa-project-controls > button[aria-expanded=true] {background:var(--isa-extension-primary-soft,ButtonFace);border-color:var(--isa-extension-primary-strong,ButtonBorder)}
.isa-project-actions {position:relative;margin-inline-start:auto}
.isa-project-actions > summary {list-style:none;padding:.35rem .75rem;border-radius:var(--isa-extension-radius-control,.75rem)}
.isa-project-actions > summary::-webkit-details-marker {display:none}
.isa-project-actions[open] > summary,.isa-project-actions > summary:hover {background:var(--isa-extension-control-active-bg,ButtonFace)}
.isa-project-choices {
position:absolute;z-index:5;inset-inline-end:0;top:calc(100% + .375rem);
width:max-content;max-width:calc(100vw - 2rem);padding:.25rem;
background:var(--isa-extension-elevated-bg,Canvas);border:1px solid var(--isa-extension-border,ButtonBorder);
border-radius:var(--isa-extension-radius-control,.75rem);box-shadow:var(--isa-extension-elevated-shadow,none);
}
.isa-project-choices button {display:flex;justify-content:flex-start;width:100%;padding-inline:.75rem}
.isa-project-choices button:last-child:not(:first-child) {margin-top:.25rem;border-top:1px solid var(--isa-extension-divider,ButtonBorder);border-top-left-radius:0;border-top-right-radius:0}
.isa-project-active > [role=alert] {margin:0 1rem 1rem}
.isa-project-active > [role=alert]:empty,.isa-project-browser[hidden] {display:none}
.isa-project-browser {min-width:0;padding:.75rem 1.25rem 1rem;border-top:1px solid var(--isa-extension-divider,ButtonBorder)}
.isa-project-path {gap:.125rem .375rem;font-size:var(--isa-extension-font-size-sm,.875rem);color:var(--isa-extension-panel-muted,CanvasText)}
.isa-project-path > svg {width:.75rem;height:.75rem}
.isa-project-path > button {min-width:0;max-width:100%;padding:.25rem .375rem;overflow-wrap:anywhere;color:inherit}
.isa-project-path > [aria-current] {padding-block:.4rem;font-weight:600;color:var(--isa-extension-panel-heading,CanvasText);overflow-wrap:anywhere}
.isa-project-browser-body {margin-top:.5rem;overflow-wrap:anywhere}
.isa-project-file-list {display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,15rem),1fr));gap:.5rem;list-style:none;margin:0;padding:0}
.isa-project-file-list button {
box-sizing:border-box;width:100%;justify-content:flex-start;padding:.5rem .75rem;text-align:start;
border:1px solid var(--isa-extension-border-subtle,ButtonBorder);border-radius:var(--isa-extension-radius-detail,.5rem);
}
.isa-project-file-list button:hover {background:var(--isa-extension-control-hover-bg,ButtonFace);border-color:var(--isa-extension-control-border,ButtonBorder)}
.isa-project-file-list button > span {min-width:0;overflow-wrap:anywhere}
.isa-project-file-list svg {color:var(--isa-extension-panel-muted,CanvasText)}
.isa-project-file-list svg:last-child {width:.8rem;margin-inline-start:auto}
.isa-project-message {margin:0;color:var(--isa-extension-panel-muted,CanvasText);font-size:var(--isa-extension-font-size-sm,.875rem)}
.isa-project-browser-body :is(img,video,audio) {display:block;max-width:100%;max-height:55vh}
.isa-project-browser-body pre {margin:.5rem 0 0;max-height:45vh;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere}
.isa-project-metadata dl {display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,13rem),1fr));gap:1rem;margin:0;padding:1rem;background:var(--isa-extension-panel-bg-muted,ButtonFace);border-radius:var(--isa-extension-radius-detail,.5rem)}
.isa-project-metadata dt,.isa-project-metadata summary {color:var(--isa-extension-panel-muted,CanvasText);font-size:var(--isa-extension-font-size-xs,.8125rem)}
.isa-project-metadata dd {margin:.25rem 0 0;font-size:var(--isa-extension-font-size-sm,.875rem)}
.isa-project-metadata details {margin-top:.5rem}
.isa-project-metadata summary {width:fit-content;padding:.375rem}
@media (max-width:680px) {
.isa-project-header,.isa-project-browser {padding:.875rem}
.isa-project-controls {width:100%}
}
/* Project launchers share these surfaces inside the extension iframe. */
.isa-group-home {
display:grid;
align-content:start;
gap:.625rem;
padding:var(--isa-extension-shell-gutter,1rem);
}
.isa-group-home > header,.isa-group-grid > aside,.isa-group-projects {
min-width:0;
padding:.875rem 1rem;
border:1px solid var(--isa-extension-border-subtle,ButtonBorder);
border-radius:var(--isa-extension-radius-control,.75rem);
background:var(--isa-extension-panel-bg,Canvas);
}
.isa-group-home header {display:flex;align-items:center;flex-wrap:wrap;gap:.75rem 1.5rem}
.isa-group-home header > .isa-project-toolbar,.isa-group-projects header > button {margin-inline-start:auto}
.isa-group-home h1,.isa-group-home h2,.isa-group-home p {margin:0} .isa-group-home h1,.isa-group-home h2,.isa-group-home p {margin:0}
.isa-group-home h1 {font-size:1.15rem} .isa-group-home h1 {font-size:var(--isa-extension-font-size-xl,1.25rem);line-height:1.15;letter-spacing:normal}
.isa-group-home h2 {font-size:.86rem} .isa-group-grid h2 {font-size:var(--isa-extension-font-size-base,1rem);letter-spacing:normal}
.isa-group-grid {display:grid;grid-template-columns:minmax(140px, .42fr) minmax(0,1fr);gap:10px} .isa-group-summary {
.isa-group-grid aside {padding:16px;color:var(--isa-extension-panel-muted,GrayText)} flex:1 1 20rem;
.isa-group-grid aside div {display:grid;gap:4px;margin-top:10px} display:grid;
.isa-group-grid aside button {border:0;background:transparent;padding-inline:0} grid-template-columns:repeat(auto-fit,minmax(min(100%,10rem),1fr));
.isa-group-projects {display:flex;flex-direction:column;gap:14px;min-width:0} max-width:32rem;
.isa-group-projects h2 {text-transform:uppercase;letter-spacing:.08em} margin:0;
.isa-group-projects select {font:inherit;color:inherit;background:var(--isa-extension-control-bg,Canvas);border:1px solid var(--isa-extension-border-subtle,GrayText);border-radius:.5rem;padding:.5rem;max-width:100%} gap:.5rem;
.isa-project-ui .isa-group-create {background:var(--isa-extension-primary,Highlight);color:var(--isa-extension-primary-text,HighlightText);border-color:transparent;font-weight:600} }
.isa-group-rows {display:grid;gap:8px} .isa-group-summary > div {
.isa-group-rows button {display:flex;justify-content:space-between;align-items:center;gap:10px;width:100%;padding:12px;border-radius:10px;border-color:var(--isa-extension-border-subtle,GrayText);background:var(--isa-extension-card-bg,Canvas)} display:flex;
.isa-group-rows strong,.isa-group-rows small {display:block;overflow-wrap:anywhere} align-items:center;
.isa-group-rows small,.isa-group-rows time {color:var(--isa-extension-panel-muted,GrayText);font-size:.8em} justify-content:space-between;
gap:.5rem;
padding:.5rem .75rem;
min-height:2.5rem;
border:1px solid var(--isa-extension-border-subtle,ButtonBorder);
border-radius:var(--isa-extension-radius-detail,.5rem);
background:var(--isa-extension-panel-bg-muted,ButtonFace);
}
.isa-group-summary dt {display:flex;align-items:center;gap:.5rem;font-size:var(--isa-extension-font-size-sm,.875rem)}
.isa-group-summary svg {color:var(--isa-extension-primary-strong,Highlight)}
.isa-group-summary dd {margin:0;font-weight:600;font-variant-numeric:tabular-nums}
.isa-group-count:not(:empty) {display:inline-block;margin-inline-start:.5rem;padding:.1rem .45rem;border-radius:1rem;background:var(--isa-extension-panel-bg-muted,ButtonFace);font-size:.8em;letter-spacing:normal;vertical-align:middle}
.isa-group-grid {display:grid;align-items:start;grid-template-columns:minmax(0,.42fr) minmax(0,1fr);gap:.625rem}
.isa-group-grid aside > div {display:grid;margin-top:.5rem;max-height:24rem;overflow:auto}
.isa-group-grid aside button,.isa-group-rows button {
min-width:0;
min-height:2rem;
padding:.375rem .5rem;
border:0;
border-radius:0;
background:transparent;
color:inherit;
font:inherit;
font-size:var(--isa-extension-font-size-sm,.875rem);
font-weight:400;
line-height:1.4;
text-align:start;
overflow-wrap:anywhere;
}
.isa-group-home [data-project-id]:is(:hover,:focus-visible,[aria-busy=true]) {background:var(--isa-extension-primary-soft,ButtonFace)}
.isa-group-home [data-project-id]:focus-visible {outline:2px solid var(--isa-extension-focus-outline,Highlight);outline-offset:-2px}
.isa-group-projects {container:isa-project-panel / inline-size;display:grid;align-content:start;gap:0}
.isa-project-ui .isa-group-projects > .isa-project-toolbar {display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.375rem;margin:.5rem 0}
.isa-group-projects input[type=search] {min-width:0;width:100%}
.isa-group-projects select {width:auto;max-width:100%;font:inherit;color:inherit;background:var(--isa-extension-control-bg,Canvas);border:1px solid var(--isa-extension-border-subtle,ButtonBorder);border-radius:var(--isa-extension-radius-control,.75rem);padding:.375rem .5rem}
.isa-group-home.isa-group-home-embedded {padding:0}
.isa-group-rows {display:grid}
.isa-project-columns,.isa-group-rows button {
box-sizing:border-box;
display:grid;
grid-template-columns:minmax(0,1fr) minmax(8rem,24%) 7rem;
align-items:center;
column-gap:.75rem;
padding:.375rem .5rem;
}
.isa-project-columns {font-size:var(--isa-extension-font-size-xs,.8125rem);font-weight:600;overflow-wrap:anywhere;color:var(--isa-extension-panel-muted,GrayText);background:var(--isa-extension-panel-bg-muted,ButtonFace)}
.isa-project-columns[hidden] {display:none}
.isa-project-columns span:last-child,.isa-group-rows time {text-align:end}
.isa-group-rows button + button,.isa-group-grid aside button + button {border-block-start:1px solid var(--isa-extension-border-subtle,ButtonBorder)}
.isa-group-rows .isa-project-name {font-weight:600}
.isa-group-home:not(.isa-group-home-embedded) .isa-group-projects h2 {font-size:var(--isa-extension-font-size-lg,1.125rem)}
@media (min-width:641px) {
.isa-group-home:not(.isa-group-home-embedded) {display:flex;flex-direction:column}
.isa-group-home:not(.isa-group-home-embedded) > .isa-group-grid {
flex:1;
align-items:stretch;
grid-template-columns:clamp(12rem,24%,21rem) minmax(0,1fr);
}
.isa-group-home:not(.isa-group-home-embedded) .isa-group-grid > aside {
background:color-mix(in srgb,var(--isa-extension-panel-bg,Canvas) 94%,var(--isa-extension-panel-muted,GrayText));
}
.isa-group-home:not(.isa-group-home-embedded) .isa-group-grid aside > div {max-height:none}
}
.isa-group-rows small,.isa-group-rows time,.isa-group-grid aside p {margin:0;color:var(--isa-extension-panel-muted,GrayText);font-size:var(--isa-extension-font-size-xs,.8125rem)}
.isa-group-home p:empty {display:none} .isa-group-home p:empty {display:none}
.isa-group-rows:not(:empty) + .isa-project-list-skeleton,
.isa-group-rows:not([aria-busy=true]) + .isa-project-list-skeleton {display:none}
.isa-group-announcement {
position:absolute;
width:1px;
height:1px;
overflow:hidden;
clip-path:inset(50%);
white-space:nowrap;
}
@container isa-project-panel (max-width:34rem) {
.isa-group-home .isa-project-columns {display:none}
.isa-group-home .isa-group-rows button {grid-template-columns:minmax(0,1fr) auto;row-gap:.125rem}
.isa-group-rows .isa-project-name {grid-column:1 / -1}
}
@container isa-project-panel (max-width:22rem) {
.isa-project-ui .isa-group-projects > .isa-project-toolbar {grid-template-columns:minmax(0,1fr)}
}
.isa-group-home dialog form,.isa-group-home dialog label {display:grid;gap:10px} .isa-group-home dialog form,.isa-group-home dialog label {display:grid;gap:10px}
.isa-group-home dialog h2 {margin-bottom:14px} .isa-group-home dialog h2 {margin-bottom:14px}
@media(max-width:640px){.isa-group-grid {grid-template-columns:minmax(0,1fr)}.isa-group-projects {grid-row:1}.isa-group-home {min-height:0}.isa-group-home header {gap:8px}} .isa-project-ui dialog.isa-project-create-dialog {box-sizing:border-box;width:min(28rem,calc(100% - 2rem));padding:1.5rem;border-radius:var(--modal-shell-radius,1rem);background:var(--modal-shell-bg,var(--isa-extension-panel-bg,Canvas));box-shadow:0 12px 48px rgb(0 0 0/.18)}
.isa-project-create-dialog h2 {font-size:1.2rem}
.isa-project-create-dialog .isa-project-toolbar {justify-content:flex-end;margin-top:.5rem}
.isa-project-create-dialog input {box-sizing:border-box;width:100%}
.isa-project-create-progress:not(:empty) {display:flex;align-items:center;gap:.6rem;margin-top:1rem}
.isa-project-create-progress:not(:empty)::before {content:'';width:.85rem;height:.85rem;border:2px solid currentColor;border-inline-end-color:transparent;border-radius:50%;animation:isa-project-spin .8s linear infinite}
@keyframes isa-project-spin {to {transform:rotate(360deg)}}
@media(prefers-reduced-motion:reduce){.isa-project-create-progress::before {animation:none!important}}
@media(max-width:640px){.isa-group-grid {grid-template-columns:minmax(0,1fr)}.isa-group-projects {grid-row:1}.isa-group-home {padding:.5rem}.isa-group-home header {gap:.5rem}.isa-group-summary {flex-basis:100%}.isa-group-home > header > .isa-project-toolbar {margin-inline-start:0}.isa-group-grid aside > div {max-height:12rem}}
`; `;
+14
View File
@@ -1,8 +1,18 @@
export const TRANSFER_MANIFEST: '.isa-transfer.json'; export const TRANSFER_MANIFEST: '.isa-transfer.json';
export const TRANSFER_VERSION: 1; export const TRANSFER_VERSION: 1;
export type ProjectExportProgress =
| { type: 'listing' | 'verifying' }
| { type: 'inventory'; files: number; stores: number }
| { type: 'reading' | 'store'; path: string }
| { type: 'records'; path: string; entries: ReadonlyArray<{key: string; value: unknown}> }
| { type: 'file'; path: string; size: number; projectName?: string }
| { type: 'fileBytes'; path: string; loaded: number; total: number }
| { type: 'packing'; loaded: number; total: number | null };
export interface ProjectTransferOptions { export interface ProjectTransferOptions {
bridge: ProjectBridge; bridge: ProjectBridge;
scope?: ProjectScope; scope?: ProjectScope;
signal?: AbortSignal;
onProgress?: (progress: ProjectExportProgress) => void;
beforeExport?: (session: ProjectSession) => void | Promise<void>; beforeExport?: (session: ProjectSession) => void | Promise<void>;
name?: string; name?: string;
fileName?: string; fileName?: string;
@@ -11,8 +21,12 @@ export interface ProjectTransferOptions {
maxTotalBytes?: number; maxTotalBytes?: number;
maxEntries?: number; maxEntries?: number;
} }
export function unpackZip(bytes: Uint8Array | ArrayBuffer, options?: Pick<ProjectTransferOptions, "maxArchiveBytes" | "maxFileBytes" | "maxTotalBytes" | "maxEntries">): Map<string, Uint8Array>;
export function exportProject(session: ProjectSession, options: ProjectTransferOptions): Promise<Uint8Array>; export function exportProject(session: ProjectSession, options: ProjectTransferOptions): Promise<Uint8Array>;
export function importProject(client: ProjectClient, bytes: Uint8Array | ArrayBuffer, options: ProjectTransferOptions): Promise<ProjectSession>; export function importProject(client: ProjectClient, bytes: Uint8Array | ArrayBuffer, options: ProjectTransferOptions): Promise<ProjectSession>;
export function exportProjectToDialog(session: ProjectSession, options: ProjectTransferOptions): Promise<unknown>; export function exportProjectToDialog(session: ProjectSession, options: ProjectTransferOptions): Promise<unknown>;
export function importProjectFromDialog(client: ProjectClient, options: ProjectTransferOptions): Promise<ProjectSession | null>; export function importProjectFromDialog(client: ProjectClient, options: ProjectTransferOptions): Promise<ProjectSession | null>;
import type { ProjectBridge, ProjectClient, ProjectSession, ProjectScope } from './index.js'; import type { ProjectBridge, ProjectClient, ProjectSession, ProjectScope } from './index.js';
export function inspectArchive(bytes: Uint8Array | ArrayBuffer, options?: Partial<ProjectTransferOptions>): {files: Map<string, Uint8Array>, manifest: {name: string}, types: Map<string,string>, directories: string[], stores: {path:string, entries:{key:string,value:unknown}[]}[]};
export function saveProjectArchiveToDialog(session: ProjectSession, bytes: Uint8Array, options: ProjectTransferOptions): Promise<unknown>;
+55 -14
View File
@@ -1,9 +1,12 @@
import {readKvSnapshot,validateEntries} from './kv-snapshot.js'; import {readKvSnapshot,validateEntries} from './kv-snapshot.js';
import { readExportFile } from './transfer/files.js'; import { readExportFile } from './transfer/files.js';
import { manifestFromSnapshot } from './project-filesystem.js';
import { confirmedWrite } from './proofs.js'; import { confirmedWrite } from './proofs.js';
import { parseProjectManifest, validateArchivePath } from './format.js'; import { parseProjectManifest, validateArchivePath } from './format.js';
import { packZip, unpackZip, limits, validatePaths } from './transfer/zip.js'; import { packZip, unpackZip, limits, validatePaths } from './transfer/zip.js';
export { unpackZip };
export const TRANSFER_MANIFEST = '.isa-transfer.json'; export const TRANSFER_MANIFEST = '.isa-transfer.json';
export const TRANSFER_VERSION = 1; export const TRANSFER_VERSION = 1;
const KV_TYPE = 'application/vnd.isa.kv-store'; const KV_TYPE = 'application/vnd.isa.kv-store';
@@ -51,48 +54,82 @@ function inventorySignature(rows) {
function assertLive(session) {session.assertCurrent();if(session.signal?.aborted)throw new DOMException('Project transfer cancelled','AbortError');} function assertLive(session) {session.assertCurrent();if(session.signal?.aborted)throw new DOMException('Project transfer cancelled','AbortError');}
export async function exportProject(session, options={}) { export async function exportProject(session, options={}) {
const bridge=bridgeFor(options),scope=scoped(session,options),bound=limits(options); const bridge=bridgeFor(options),scope=scoped(session,options),bound=limits(options);
function checkCurrent() {
assertLive(session); assertLive(session);
if(options.beforeExport) {await options.beforeExport(session);assertLive(session);} if (options.signal?.aborted) throw new DOMException('Project export cancelled', 'AbortError');
}
checkCurrent();
if(options.beforeExport) {await options.beforeExport(session);checkCurrent();}
if(session.dirty)throw new Error('Save project changes before exporting'); if(session.dirty)throw new Error('Save project changes before exporting');
const rows=await session.listFiles('',true);assertLive(session); const report = options.onProgress;
report?.({ type: 'listing' });
const rows=await session.listFiles('',true);checkCurrent();
if(!Array.isArray(rows)||rows.length>bound.maxEntries)throw new Error('Invalid or oversized project inventory'); if(!Array.isArray(rows)||rows.length>bound.maxEntries)throw new Error('Invalid or oversized project inventory');
const inventory=rows.filter(row=>row.path!==session.project.path); const inventory=rows.filter(row=>row.path!==session.project.path);
const signature=inventorySignature(inventory); const signature=inventorySignature(inventory);
validatePaths(inventory.map(row=>({path:relative(session,row.path),directory:row.kind==='folder'}))); validatePaths(inventory.map(row=>({path:relative(session,row.path),directory:row.kind==='folder'})));
if (report) {
const resources = inventory.filter(row => row.kind === 'file');
const storeCount = resources.filter(row => row.contentType === KV_TYPE).length;
report({ type: 'inventory', files: resources.length - storeCount, stores: storeCount });
}
const files=new Map(),metadata=[],stores=[],directories=[]; const files=new Map(),metadata=[],stores=[],directories=[];
for(const row of inventory) { for(const row of inventory) {
assertLive(session); checkCurrent();
if(row.kind==='folder'){directories.push(relative(session,row.path));continue;} if(row.kind==='folder'){directories.push(relative(session,row.path));continue;}
if(row.kind!=='file')throw new Error('Unsupported project resource kind'); if(row.kind!=='file')throw new Error('Unsupported project resource kind');
const path=relative(session,row.path); const path=relative(session,row.path);
if(path===TRANSFER_MANIFEST)throw new Error('Project uses reserved transfer manifest path'); if(path===TRANSFER_MANIFEST)throw new Error('Project uses reserved transfer manifest path');
report?.({ type: 'reading', path });
if(row.contentType===KV_TYPE) { if(row.contentType===KV_TYPE) {
const captured=await readKvSnapshot(bridge,scope,row.path,() => assertLive(session),bound.maxFileBytes); const captured=await readKvSnapshot(bridge,scope,row.path,checkCurrent,bound.maxFileBytes,
report && (entries => report({ type: 'records', path, entries })));
checkCurrent();
stores.push({path,revision:captured.fence.revision,entries:captured.entries,fence:captured.fence}); stores.push({path,revision:captured.fence.revision,entries:captured.entries,fence:captured.fence});
report?.({ type: 'store', path });
continue; continue;
} }
const expected=identity(row); const expected=identity(row);
const bytes=await readExportFile(session,bridge,scope,row,expected,bound.maxFileBytes); const bytes=await readExportFile(session,bridge,scope,row,expected,bound.maxFileBytes,
report && ((loaded, total) => report({ type: 'fileBytes', path, loaded, total })), options.signal);
checkCurrent();
let projectName;
if(path==='project.json') { if(path==='project.json') {
const manifest=portableManifest(json(bytes)); const manifest=portableManifest(json(bytes));
if(manifest.id!==session.project.projectIdentity)throw new Error('Project manifest identity changed'); if(manifest.id!==session.project.projectIdentity)throw new Error('Project manifest identity changed');
projectName = manifest.name;
files.set(path,jsonBytes(manifest)); files.set(path,jsonBytes(manifest));
} else files.set(path,bytes); } else files.set(path,bytes);
metadata.push({path,contentType:typeof row.contentType==='string'?row.contentType:'application/octet-stream'}); const contentType = typeof row.contentType === 'string' ? row.contentType : 'application/octet-stream';
if (contentType.length > 256) throw new Error('Invalid project file metadata');
metadata.push({path, contentType});
report?.({ type: 'file', path, size: files.get(path).byteLength, projectName });
} }
if(!files.has('project.json'))throw new Error('Project manifest missing from export inventory'); if(!files.has('project.json'))throw new Error('Project manifest missing from export inventory');
report?.({ type: 'verifying' });
for(const store of stores) { for(const store of stores) {
const current=await bridge.snapshotKv({...scope,path:session.path(store.path),limit:1});assertLive(session); checkCurrent();
const current=await bridge.snapshotKv({...scope,path:session.path(store.path),limit:1});checkCurrent();
const fence={revision:current.revision,localRevision:current.localRevision??null,storeId:current.storeId??null,incarnation:current.incarnation??null,local:current.local===true}; const fence={revision:current.revision,localRevision:current.localRevision??null,storeId:current.storeId??null,incarnation:current.incarnation??null,local:current.local===true};
if(JSON.stringify(fence)!==JSON.stringify(store.fence))throw new Error('KV changed during project export'); if(JSON.stringify(fence)!==JSON.stringify(store.fence))throw new Error('KV changed during project export');
} }
const current=await session.listFiles('',true);assertLive(session); const current=await session.listFiles('',true);checkCurrent();
if(inventorySignature(current.filter(row=>row.path!==session.project.path))!==signature)throw new Error('Project inventory changed during export'); if(inventorySignature(current.filter(row=>row.path!==session.project.path))!==signature)throw new Error('Project inventory changed during export');
if (report) {
report({ type: 'packing', loaded: 0, total: null });
await new Promise(resolve => setTimeout(resolve, 0));
checkCurrent();
}
files.set(TRANSFER_MANIFEST,jsonBytes({formatVersion:TRANSFER_VERSION,files:metadata,directories,kvStores:stores.map(({fence,...store})=>store),auditAuthority:'historical-only'})); files.set(TRANSFER_MANIFEST,jsonBytes({formatVersion:TRANSFER_VERSION,files:metadata,directories,kvStores:stores.map(({fence,...store})=>store),auditAuthority:'historical-only'}));
const bytes=packZip(files,bound,directories);assertLive(session);return bytes; const bytes = await packZip(files, bound, directories, report && ((loaded, total) => {
checkCurrent();
report({ type: 'packing', loaded, total });
}));
checkCurrent();
return bytes;
} }
function inspectArchive(bytes,options) { export function inspectArchive(bytes,options = {}) {
const files=unpackZip(bytes,options),raw=files.get('project.json'); const files=unpackZip(bytes,options),raw=files.get('project.json');
if(!raw)throw new Error('Project archive requires project.json'); if(!raw)throw new Error('Project archive requires project.json');
const manifest=portableManifest(json(raw)); const manifest=portableManifest(json(raw));
@@ -143,7 +180,7 @@ export async function importProject(client,bytes,options={}) {
if(typeof client.stageCreate!=='function'||typeof client.adopt!=='function')throw new Error('Project import requires staged project creation'); if(typeof client.stageCreate!=='function'||typeof client.adopt!=='function')throw new Error('Project import requires staged project creation');
if(archive.stores.length&&typeof bridge.applyKv!=='function')throw new Error('Host KV transfer helper unavailable'); if(archive.stores.length&&typeof bridge.applyKv!=='function')throw new Error('Host KV transfer helper unavailable');
const name=options.name??await importName(client,archive.manifest.name); const name=options.name??await importName(client,archive.manifest.name);
const session=await client.stageCreate(name); const session=await client.stageCreate(name,crypto.randomUUID(),{importing:true});
if(!session)throw new Error('Project creation cancelled'); if(!session)throw new Error('Project creation cancelled');
const scope=scoped(session,options); const scope=scoped(session,options);
try { try {
@@ -187,15 +224,19 @@ export async function importProject(client,bytes,options={}) {
} }
const base=await session.readFile('project.json');assertLive(session); const base=await session.readFile('project.json');assertLive(session);
if(base.status!=='found')throw new Error('New project manifest unavailable'); if(base.status!=='found')throw new Error('New project manifest unavailable');
const host=parseProjectManifest(JSON.parse(base.text)); const host=manifestFromSnapshot(base);
const imported={...archive.manifest,id:host.id,name:host.name,createdAt:host.createdAt,updatedAt:new Date().toISOString(),importedFrom:{id:archive.manifest.id,importedAt:new Date().toISOString()},auditAuthority:'historical-only'}; const imported={...archive.manifest,archived:false,id:host.id,name:host.name,createdAt:host.createdAt,updatedAt:new Date().toISOString(),importedFrom:{id:archive.manifest.id,importedAt:new Date().toISOString()},auditAuthority:'historical-only'};
delete imported.importPending;
await session.writeJson('project.json',imported,base);assertLive(session); await session.writeJson('project.json',imported,base);assertLive(session);
return await client.adopt(session); return await client.adopt(session);
}catch(error){await session.close();const failure=error instanceof Error?error:new Error(String(error));failure.project=session.project;throw failure;} }catch(error){await session.close();const failure=error instanceof Error?error:new Error(String(error));failure.project=session.project;throw failure;}
} }
export async function exportProjectToDialog(session,options={}) { export async function exportProjectToDialog(session,options={}) {
const bytes=await exportProject(session,options);assertLive(session); return saveProjectArchiveToDialog(session,await exportProject(session,options),options);
}
export async function saveProjectArchiveToDialog(session,bytes,options={}) {
assertLive(session);
const result=await bridgeFor(options).invoke('save_file_dialog',{fileName:options.fileName??`${session.project.name||'project'}.isap.zip`,bytesBase64:base64(bytes),filterName:'ISA Project',extensions:['zip']}); const result=await bridgeFor(options).invoke('save_file_dialog',{fileName:options.fileName??`${session.project.name||'project'}.isap.zip`,bytesBase64:base64(bytes),filterName:'ISA Project',extensions:['zip']});
assertLive(session);return result; assertLive(session);return result;
} }
+6 -2
View File
@@ -8,7 +8,7 @@ function decode(value) {
if(typeof value!=='string'||value.length%4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))throw new Error('Invalid host file encoding'); if(typeof value!=='string'||value.length%4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))throw new Error('Invalid host file encoding');
return Uint8Array.from(atob(value),character=>character.charCodeAt(0)); return Uint8Array.from(atob(value),character=>character.charCodeAt(0));
} }
export async function readExportFile(session,bridge,scope,row,expected,maxBytes) { export async function readExportFile(session,bridge,scope,row,expected,maxBytes,onBytes,signal) {
session.assertCurrent(); session.assertCurrent();
if(expected.size!==null&&(!Number.isSafeInteger(expected.size)||expected.size<0||expected.size>maxBytes))throw new Error('Project file exceeds transfer limit'); if(expected.size!==null&&(!Number.isSafeInteger(expected.size)||expected.size<0||expected.size>maxBytes))throw new Error('Project file exceeds transfer limit');
const request={...scope,path:row.path,cachePolicy:'dashboard-required',expectedSyncRevision:expected.revision,...(expected.hash?{expectedContentHash:expected.hash}:{})}; const request={...scope,path:row.path,cachePolicy:'dashboard-required',expectedSyncRevision:expected.revision,...(expected.hash?{expectedContentHash:expected.hash}:{})};
@@ -18,15 +18,19 @@ export async function readExportFile(session,bridge,scope,row,expected,maxBytes)
if(!Number.isSafeInteger(link.fileSize)||link.fileSize!==expected.size||link.fileSize>maxBytes||typeof link.contentHash!=='string'||!/^[a-f0-9]{64}$/i.test(link.contentHash))throw new Error('Large project file lacks a bounded verified snapshot'); if(!Number.isSafeInteger(link.fileSize)||link.fileSize!==expected.size||link.fileSize>maxBytes||typeof link.contentHash!=='string'||!/^[a-f0-9]{64}$/i.test(link.contentHash))throw new Error('Large project file lacks a bounded verified snapshot');
const url=new URL(link.downloadUrl,globalThis.location?.href); const url=new URL(link.downloadUrl,globalThis.location?.href);
if(!['http:','https:'].includes(url.protocol))throw new Error('Unsupported project download URL'); if(!['http:','https:'].includes(url.protocol))throw new Error('Unsupported project download URL');
const response=await fetch(url,{signal:session.signal,credentials:'omit',redirect:'error'});session.assertCurrent(); const downloadSignal = signal && session.signal && typeof AbortSignal.any === 'function'
? AbortSignal.any([signal, session.signal]) : session.signal ?? signal;
const response=await fetch(url,{signal:downloadSignal,credentials:'omit',redirect:'error'});session.assertCurrent();
if(!response.ok||!response.body)throw new Error('Project media download failed'); if(!response.ok||!response.body)throw new Error('Project media download failed');
const reader=response.body.getReader();const chunks=[];let length=0; const reader=response.body.getReader();const chunks=[];let length=0;
try { try {
while(true) { while(true) {
if (signal?.aborted) throw new DOMException('Project export cancelled', 'AbortError');
const next=await reader.read();session.assertCurrent();if(next.done)break; const next=await reader.read();session.assertCurrent();if(next.done)break;
length+=next.value.byteLength; length+=next.value.byteLength;
if(length>link.fileSize||length>maxBytes)throw new Error('Project media exceeds its declared size'); if(length>link.fileSize||length>maxBytes)throw new Error('Project media exceeds its declared size');
chunks.push(next.value); chunks.push(next.value);
onBytes?.(length, link.fileSize);
} }
} finally {await reader.cancel().catch(()=>{});reader.releaseLock();} } finally {await reader.cancel().catch(()=>{});reader.releaseLock();}
if(length!==link.fileSize)throw new Error('Project media download was incomplete'); if(length!==link.fileSize)throw new Error('Project media download was incomplete');
+25 -3
View File
@@ -119,7 +119,7 @@ export function unpackZip(input, options) {
return files; return files;
} }
export function packZip(files, options, directories=[]) { export async function packZip(files, options, directories=[], onProgress) {
const bound=limits(options), records=[...files.keys()].map(path=>({path,directory:false})).concat(directories.map(path=>({path,directory:true}))); const bound=limits(options), records=[...files.keys()].map(path=>({path,directory:false})).concat(directories.map(path=>({path,directory:true})));
validatePaths(records); validatePaths(records);
if(records.length>bound.maxEntries)throw new Error('Too many project files'); if(records.length>bound.maxEntries)throw new Error('Too many project files');
@@ -130,12 +130,34 @@ export function packZip(files, options, directories=[]) {
if(archiveBytes>bound.maxArchiveBytes)throw new Error('Project ZIP exceeds archive limit'); if(archiveBytes>bound.maxArchiveBytes)throw new Error('Project ZIP exceeds archive limit');
chunks.push(chunk); chunks.push(chunk);
}); });
for (const bytes of files.values()) {
total += bytes.length;
if (bytes.length > bound.maxFileBytes || total > bound.maxTotalBytes) throw new Error('Project transfer limits exceeded');
}
let loaded = 0;
let lastYield = performance.now();
for (const [path, bytes] of files) { for (const [path, bytes] of files) {
if(bytes.length>bound.maxFileBytes||(total+=bytes.length)>bound.maxTotalBytes)throw new Error('Project transfer limits exceeded'); const file = new ZipDeflate(path, {level:6});
const file=new ZipDeflate(path,{level:6});archive.add(file);file.push(bytes,true); archive.add(file);
if (!onProgress || bytes.length === 0) {
file.push(bytes, true);
continue;
}
const chunkSize = 128 * 1024;
for (let offset = 0; offset < bytes.length; offset += chunkSize) {
const chunk = bytes.subarray(offset, offset + chunkSize);
file.push(chunk, offset + chunk.length === bytes.length);
loaded += chunk.length;
if (performance.now() - lastYield >= 40) {
onProgress(loaded, total);
await new Promise(resolve => setTimeout(resolve, 0));
lastYield = performance.now();
}
}
} }
for(const path of directories){const directory=new ZipPassThrough(`${path}/`);archive.add(directory);directory.push(new Uint8Array(),true);} for(const path of directories){const directory=new ZipPassThrough(`${path}/`);archive.add(directory);directory.push(new Uint8Array(),true);}
archive.end(); archive.end();
onProgress?.(loaded, total);
const result=new Uint8Array(archiveBytes);let offset=0; const result=new Uint8Array(archiveBytes);let offset=0;
for(const chunk of chunks){result.set(chunk,offset);offset+=chunk.length;} for(const chunk of chunks){result.set(chunk,offset);offset+=chunk.length;}
return result; return result;
+42
View File
@@ -0,0 +1,42 @@
const paths = {
plus: 'M12 5v14 M5 12h14',
clock: 'M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0Z M12 6v6l4 2',
refresh: 'M20 7v5h-5 M4 17v-5h5 M6 7a7 7 0 0 1 12-1l2 3 M4 15l2 3a7 7 0 0 0 12-1',
folder: 'M3 7V5a1 1 0 0 1 1-1h5l2 3h9a1 1 0 0 1 1 1v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z',
files: 'M7 3h9l4 4v11H7z M15 3v5h5 M4 7v14h12',
file: 'M5 3h9l5 5v13H5z M14 3v6h5 M9 13h6 M9 17h4',
more: 'M4 12h.01 M12 12h.01 M20 12h.01',
chevron: 'm9 6 6 6-6 6',
import: 'M12 3v12m-5-5 5 5 5-5 M4 16v4h16v-4',
export: 'M12 15V3m-5 5 5-5 5 5 M4 16v4h16v-4',
leave: 'M9 4H4v16h5 M9 12h12m-5-5 5 5-5 5'
};
export function workspaceElements(document) {
function make(tag, label, className) {
const node = document.createElement(tag);
if (label != null) node.textContent = label;
if (className) node.className = className;
return node;
}
function icon(name) {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const path = document.createElementNS(svg.namespaceURI, 'path');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('class', 'isa-project-icon');
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
path.setAttribute('d', paths[name]);
if (name === 'more') path.setAttribute('stroke-width', '3.5');
svg.append(path);
return svg;
}
function button(label, action, symbol, variant = 'ghost') {
const node = make('button', label, 'isa-extension-button isa-extension-button--' + variant);
node.type = 'button';
node.onclick = action;
if (symbol) node.prepend(icon(symbol));
return node;
}
return {make, icon, button};
}
+258 -31
View File
@@ -1,32 +1,95 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { createProjectClient } from '../src/client.js'; 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}); const project = id => ({id,folderId:id,name:id,path:`/projects/${id}.isap`,projectIdentity:id,formatVersion:1});
const sharedCommands = ['filesystem_list_group_projects', 'filesystem_open_group_project', 'filesystem_create_group_project'];
const ordinaryCommands = ['open_workspace_folder', 'filesystem_create_folder', 'filesystem_upload_files', 'filesystem_list_dir', 'filesystem_get_files'];
function fixture(options = {}) { function fixture(options = {}) {
const writes = []; const writes = [];
const files = new Map(['one','two','three'].map(id => [`${project(id).path}/project.json`,{ 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} formatVersion:1,id,name:id,createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{kept:true}
}])); }]));
let saved = null; const saved = new Map();
const directories = new Set(['/projects']);
const bridge = { const bridge = {
async invoke(command,args) { 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 (options.invoke) { const result = options.invoke(command,args); if (result !== undefined) return result; }
if (command === 'filesystem_get_files') { if (command === 'filesystem_get_files') {
const path = args.files[0].path; 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}]}; 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; if (command === 'localstorage_get') return saved.get(args.key) ?? null;
if (command === 'localstorage_put') { saved=args.value;return {ok:true}; } if (command === 'localstorage_put') { saved.set(args.key,args.value); return {ok:true}; }
if (command === 'filesystem_upload_files') { writes.push(args); return {items:[{status:'ok',isComplete:true,path:args.files[0].path,fileId:args.files[0].path}]}; } 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}`); throw new Error(`Unexpected command ${command}`);
}, },
subscribeKv: options.subscribeKv subscribeKv: options.subscribeKv
}; };
const client = createProjectClient({bridge,extensionId:'contracts',scope:{workspaceId:'workspace',groupId:'group'},beforeSwitch:options.beforeSwitch}); const client = createProjectClient({bridge,extensionId:'contracts',scope:{workspaceId:'workspace',groupId:'group'},filesystem:options.filesystem,filesystemCommands:options.filesystemCommands,groupFolder:options.groupFolder,sharedProjectsFolder:options.sharedProjectsFolder,beforeSwitch:options.beforeSwitch});
return {client,writes,bridge,files}; return {client,writes,bridge,files};
} }
const groupProjectsPath = '/groups/_group_ids/' + 'a'.repeat(64) + '/projects';
test('the shared group catalog excludes picker history and preserves the archived state', async () => {
let available = true;
const calls = [];
const {client,files} = fixture({
sharedProjectsFolder: true,
filesystem: {supportsSharedGroupProjects:true, commands:['filesystem_list_group_projects', 'filesystem_open_group_project', 'filesystem_get_files']},
invoke(command, args) {
calls.push(command);
if (command === 'filesystem_list_group_projects') {
assert.deepEqual(args, {workspaceId: 'workspace', groupId: 'group'});
if (!available) throw new Error('Dashboard unavailable');
return {authoritative: true, folders: [
{fileId:'one', path:groupProjectsPath + '/one.isap', canWrite:false, hasInstance:false, manifest:files.get(groupProjectsPath + '/one.isap/project.json')},
{fileId:'two', path:groupProjectsPath + '/two.isap', canWrite:false, hasInstance:true, archivedAt:'2026-11-03T12:00:00Z', manifest:files.get(groupProjectsPath + '/two.isap/project.json')},
{fileId:'incomplete', path:groupProjectsPath + '/incomplete.isap', canWrite:true, manifest:null}
]};
}
if (command === 'filesystem_open_group_project') {
assert.deepEqual(args, {workspaceId:'workspace',groupId:'group',folderId:'one'});
return {fileId:'one', path:groupProjectsPath + '/one.isap', canWrite:false};
}
if (command === 'localstorage_get' || command === 'open_workspace_folder') assert.fail(command);
}
});
for (const id of ['one','two']) files.set(`${groupProjectsPath}/${id}.isap/project.json`, files.get(project(id).path + '/project.json'));
assert.deepEqual((await client.list()).map(row => row.id), ['one']);
const all = await client.list(true);
assert.deepEqual(calls, ['filesystem_list_group_projects', 'filesystem_list_group_projects']);
assert.equal(all.find(row => row.id === 'one').hasInstance, false);
assert.equal(all.find(row => row.id === 'two').hasInstance, true);
assert.equal(all.find(row => row.id === 'two').archived, true);
await assert.rejects(client.openListed({...all[0], path:groupProjectsPath + '/another.isap'}), /identity changed/);
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 () => { test('captured sessions fence old writes and close late subscriptions during switching', async () => {
let finishSubscription; let finishSubscription;
let stopped = 0; let stopped = 0;
@@ -74,18 +137,18 @@ test('dirty state blocks switching and unavailable reads never become absence',
await client.close(); await client.close();
}); });
test('uncertain create retries retain operation identity through manifest recovery', async () => { test('uncertain create retains the same folder and manifest identity on retry', async () => {
const ids=[]; const paths=[];
const {client}=fixture({invoke:(command,args)=>{ const {client}=fixture({invoke:(command,args)=>{
if(command!=='projects_create')return; if(command!=='filesystem_upload_files'||!args.files[0].path.endsWith('/project.json'))return;
ids.push(args.operationId); paths.push(args.files[0].path);
if(ids.length===1)throw new Error('Commit outcome unavailable'); if(paths.length===1)throw new Error('Commit outcome unavailable');
return {project:project('one')};
}}); }});
await assert.rejects(client.create('Example'),/unavailable/); await assert.rejects(client.create('Example'),/unavailable/);
const created=await client.create('Example'); const created=await client.create('Example');
assert.equal(created.project.id,'one'); assert.equal(paths[0],paths[1]);
assert.equal(ids[0],ids[1]); assert.equal(created.manifest.name,'Example');
assert.equal(created.project.projectIdentity,created.manifest.id);
await client.close(); await client.close();
}); });
@@ -119,36 +182,44 @@ test('successful transport cannot confirm pending or conflicted project writes',
await client.close(); await client.close();
}); });
test('a listed group project opens by folder ID on its first use, without a second picker or project creation', async () => { test('a picker client lists, opens and creates in the selected container on a group-catalog host', async () => {
let reply = project('two'); let picks = 0;
const commands = []; const filesystem = {supportsSharedGroupProjects:true, commands:[...ordinaryCommands, ...sharedCommands]};
const {client} = fixture({invoke(command,args) { const {client,files} = fixture({filesystem, invoke(command, args) {
commands.push(command); if (command === 'open_workspace_folder') { picks++; return; }
if (command === 'get_app_info') return {projects:{commands:['projects_open_listed']}}; if (command === 'filesystem_list_dir' && args.path === '/projects') {
if (command === 'projects_list') return {projects:[{...reply, canWrite:false, updatedAt:'2026-09-01'}]}; return {authoritative:true,files:[
if (command === 'projects_open_listed') { {path:'/projects',kind:'folder',fileId:'parent'},
assert.deepEqual(args,{projectId:'two'}); {path:project('two').path,kind:'folder',fileId:'two',canWrite:false},
return {status:'ok',project:reply}; {path:project('missing').path,kind:'folder',fileId:'incomplete'},
{path:'/projects/not-a-folder.isap',kind:'file',fileId:'file'}
]};
} }
}}); }});
assert.equal(client.supports('pickFolder'), true);
assert.equal(client.supports('create'), true);
assert.deepEqual(await client.list(),[]);
await client.pickFolder();
const [listed] = await client.list(); const [listed] = await client.list();
assert.equal(listed.canWrite,false); assert.equal(listed.canWrite,false);
assert.equal(listed.updatedAt,'2026-09-01'); assert.equal(listed.updatedAt,'2026-11-03T12:00:00Z');
const selected = await client.openListed(listed); const selected = await client.openListed(listed);
assert.equal(selected.project.id,'two'); assert.equal(selected.project.id,'two');
reply = project('one'); const manifest = files.get(listed.manifestPath);
files.set(listed.manifestPath,{...manifest,id:'one'});
await assert.rejects(client.openListed(listed),/identity/); await assert.rejects(client.openListed(listed),/identity/);
assert.equal(client.active,selected); assert.equal(client.active,selected);
assert.ok(!commands.some(command => ['projects_open','projects_create','filesystem_upload_files'].includes(command))); const created = await client.create('Ordinary', 'ordinary');
assert.equal(created.project.path, '/projects/ordinary-ordinary.isap');
assert.equal(picks,1);
}); });
test('older hosts reopen an existing grant and report a denied row without reopening the picker', async () => { test('opening from an existing grant reports a denied row without reopening the picker', async () => {
const {client,files} = fixture({invoke(command, args) { const {client,files} = fixture({invoke(command, args) {
if (command === 'get_app_info') return {projects:{commands:['projects_open']}};
if (command === 'filesystem_get_files' && args.files[0].path === project('three').path + '/project.json') { 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'}]}; return {items:[{path:args.files[0].path, status:'error', authoritative:false, error:'extension filesystem permission is required'}]};
} }
if (command === 'projects_open') assert.fail('Unexpected second project picker'); if (command === 'open_workspace_folder') assert.fail('Unexpected second project picker');
}}); }});
const selected = await client.openListed(project('one')); const selected = await client.openListed(project('one'));
files.delete(project('two').path+'/project.json'); files.delete(project('two').path+'/project.json');
@@ -161,8 +232,6 @@ test('a direct grant initializes the extension directory on first writable acces
const selected = {...project('two'), canWrite:true}; const selected = {...project('two'), canWrite:true};
const directories = []; const directories = [];
const {client} = fixture({invoke(command, args) { const {client} = fixture({invoke(command, args) {
if (command === 'get_app_info') return {projects:{commands:['projects_open_listed']}};
if (command === 'projects_open_listed') return {status:'ok', project:selected};
if (command === 'filesystem_list_dir') return {authoritative:true, files:[]}; if (command === 'filesystem_list_dir') return {authoritative:true, files:[]};
if (command === 'filesystem_create_folder') { if (command === 'filesystem_create_folder') {
directories.push(args.path); directories.push(args.path);
@@ -215,3 +284,161 @@ test('read-only, archived and uncertain reads cannot seed extension records', as
} }
assert.equal(writes.length, 0); 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 filesystem = {supportsSharedGroupProjects:true, commands:[...ordinaryCommands, ...sharedCommands, 'filesystem_ensure_group_folder']};
const {client} = fixture({groupFolder:true, filesystem, 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');
assert.equal(client.supports('pickFolder'), true);
assert.deepEqual((await client.list()).map(row => row.path), [session.project.path]);
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 = [...sharedCommands, '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) {
const opened = new Set();
return createProjectClient({
extensionId, scope: {workspaceId: 'w', groupId}, sharedProjectsFolder: true,
filesystem: { supportsSharedGroupProjects: true, commands: writable ? commands : ['filesystem_list_group_projects', 'filesystem_open_group_project'] },
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).map(row => ({
...row, canWrite:writable, manifest:files.get(row.path + '/project.json')
})),
{fileId:'private', path:'/groups/demo/extensions/quote/private.isap', canWrite:true},
{fileId:'nested', path:groupProjectsPath + '/elsewhere/nested.isap', canWrite:true}
]};
if (command === 'filesystem_open_group_project') {
const row = catalog.get(args.folderId);
if (!row || row.groupId !== groupId) throw new Error('Project unavailable in this group');
opened.add(row.path);
return {...row, canWrite:writable};
}
if (command === 'filesystem_create_group_project') {
assert.ok(writable);
const path = groupProjectsPath + '/' + args.projectId + '.isap';
const row = {fileId:'folder-' + args.projectId, path, groupId, canWrite:true};
if (!catalog.has(row.fileId)) {
catalog.set(row.fileId, row);
await storage.invoke('filesystem_create_folder',{path});
}
if (loseAcknowledgement) { loseAcknowledgement = false; throw new Error('Acknowledgement lost'); }
opened.add(row.path);
return row;
}
const path = args.path ?? args.files?.[0]?.path;
assert.ok([...opened].some(root => path === root || path?.startsWith(root + '/')), 'Filesystem request requires opening that project');
assert.ok(!['open_workspace_folder','filesystem_ensure_group_folder'].includes(command), command);
if (command === 'filesystem_get_files') assert.match(args.files[0].path, /^\/groups\/_group_ids\/[a-f0-9]{64}\/projects\/[^/]+\.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(), []);
await assert.rejects(otherGroup.activate(row), /unavailable in this group/);
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 = {supportsSharedGroupProjects:true, commands:['filesystem_list_group_projects','filesystem_create_group_project','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();
});
+47
View File
@@ -0,0 +1,47 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {openPriceAsset} from '../src/prices.js';
test('workspace writers can backfill the same observation concurrently without replacing edits or creating duplicates',async () => {
let revision = 0, conflict = true;
const records = new Map(), writes = [];
const identity = {storeId:'s',incarnation:'i',supportsExpectedRevision:true};
const scope = {workspaceId:'w',groupId:'g'};
const bridge = {async invoke(command,args) {
if(command === 'filesystem_open_workspace_asset') return {...scope,asset:'prices',folderId:'f',path:'/shared/prices',canWrite:true};
if(command === 'kv_store_open') return {...identity,revision};
if(command === 'kv_store_query_list') return {...identity,revision,page:{items:args.ids.filter(id=>records.has(id)).map(id=>({id,value:records.get(id)}))}};
if(command === 'kv_store_apply') {
if(conflict) {
records.set('a',{description:'Manual correction',supplier:'A',unitPrice:0});
revision++; conflict = false; throw Error('revision_conflict');
}
assert.equal(args.expectedRevision,revision);
for(const row of args.operations) records.set(row.id,row.value);
writes.push(args.operations.length);
return {...identity,pending:false,acceptedRevision:++revision};
}
assert.fail(command);
}};
const asset = await openPriceAsset({bridge,scope});
const rows = [{id:'a',value:{description:'old',supplierId:'supplier-a',unitPrice:0}}];
await asset.importRows(rows); await asset.importRows(rows);
assert.deepEqual(records.get('a'), {description:'Manual correction',supplier:'A',unitPrice:0,supplierId:'supplier-a'});
assert.deepEqual(writes,[1]);
});
test('a read-only open distinguishes a genuinely empty asset from an inaccessible inventory and creates no KV file', async () => {
const scope = {workspaceId:'w',groupId:'g'}; let denied = false;
const bridge = {async invoke(command) {
if(command === 'filesystem_open_workspace_asset') return {...scope,asset:'prices',folderId:'f',path:'/shared/prices',canWrite:false};
if(command === 'filesystem_list_dir') {
if(denied) throw Error('access revoked');
return {authoritative:true,files:[]};
}
assert.fail(command);
}};
const asset = await openPriceAsset({bridge,scope,access:'read'});
assert.deepEqual((await asset.query()).items,[]);
denied = true;
await assert.rejects(asset.query(), /access revoked/);
});
+17 -1
View File
@@ -1,6 +1,22 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import {createSharedFolderReader} from '../src/shared-folder.js'; import {createSharedFolderReader, openWorkspaceAsset} from '../src/shared-folder.js';
test('opening a workspace asset rejects cross-group, cross-asset and overprivileged replies', async () => {
const scope = {workspaceId: 'company', groupId: 'estimators'};
const grant = {...scope, asset: 'suppliers', folderId: 'folder-1', path: '/shared/suppliers', canWrite: false};
const open = reply => openWorkspaceAsset({scope, asset: 'suppliers', access: 'read', bridge: {
async invoke(command, args) {
assert.equal(command, 'filesystem_open_workspace_asset');
assert.deepEqual(args, {asset: 'suppliers', access: 'read'});
return reply;
}
}});
assert.deepEqual(await open(grant), grant);
for (const patch of [{groupId:'other'}, {asset:'prices'}, {path:'/shared'}, {canWrite:true}]) {
await assert.rejects(open({...grant, ...patch}), /Invalid workspace asset grant/);
}
});
test('specialist and other viewers read the same existing supplier register and price book', async () => { test('specialist and other viewers read the same existing supplier register and price book', async () => {
const root='/Shared/Registers'; const root='/Shared/Registers';
+63 -11
View File
@@ -10,11 +10,12 @@ const KV_TYPE='application/vnd.isa.kv-store';
const manifest=id=>({formatVersion:1,id,name:'Example',createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{keep:true}}); const manifest=id=>({formatVersion:1,id,name:'Example',createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{keep:true}});
const project=id=>({id,folderId:id,name:'Example',path:`/projects/${id}.isap`,projectIdentity:id}); const project=id=>({id,folderId:id,name:'Example',path:`/projects/${id}.isap`,projectIdentity:id});
function fixture() { function fixture() {
const files=new Map(),stores=new Map(),snapshots=new Map(),calls=[],projects=new Map(); const files=new Map(),stores=new Map(),snapshots=new Map(),calls=[];
let creates=0,snapshotSequence=0; let creates=0,snapshotSequence=0;
function add(path,bytes,type='application/octet-stream') {files.set(path,{bytes:bytes instanceof Uint8Array?bytes:strToU8(bytes),contentType:type,revision:1,id:path});} function add(path,bytes,type='application/octet-stream') {files.set(path,{bytes:bytes instanceof Uint8Array?bytes:strToU8(bytes),contentType:type,revision:1,id:path});}
function folder(path){files.set(path,{kind:'folder',bytes:new Uint8Array(),revision:0,id:path});} function folder(path){files.set(path,{kind:'folder',bytes:new Uint8Array(),revision:0,id:path});}
function putProject(id,name='Example') {const value={...project(id),name};projects.set(id,value);folder(value.path);folder(`${value.path}/extensions`);folder(`${value.path}/assets`);add(`${value.path}/project.json`,JSON.stringify({...manifest(id),name}),'application/json');return value;} function putProject(id,name='Example') {const value={...project(id),name};folder(value.path);folder(`${value.path}/extensions`);folder(`${value.path}/assets`);add(`${value.path}/project.json`,JSON.stringify({...manifest(id),name}),'application/json');return value;}
folder('/projects');
const original=putProject('original'); const original=putProject('original');
const media=new Uint8Array([0,255,17,48,0,99]); const media=new Uint8Array([0,255,17,48,0,99]);
add(`${original.path}/assets/audio.bin`,media,'audio/wav'); add(`${original.path}/assets/audio.bin`,media,'audio/wav');
@@ -28,12 +29,10 @@ function fixture() {
const bridge={ const bridge={
async invoke(command,args) { async invoke(command,args) {
calls.push({command,args}); calls.push({command,args});
if(command==='localstorage_get')return []; if(command==='localstorage_get')return args.key==='isa-project-format.folders.v1' ? [{path:'/projects',id:'/projects',canWrite:true}] : [];
if(command==='localstorage_put')return {status:'ok'}; if(command==='localstorage_put')return {status:'ok'};
if(command==='projects_list')return {projects:[...projects.values()]}; if(command==='filesystem_list_dir')return {authoritative:true,files:[...files].filter(([path])=>path===args.path||path.startsWith(`${args.path}/`)).map(([path,row])=>({path,id:row.id,kind:row.kind??'file',contentType:row.contentType,syncRevision:row.revision,fileSize:row.bytes.length}))};
if(command==='projects_create')return {created:true,project:putProject(`imported-${++creates}`,args.name)}; if(command==='filesystem_create_folder') {if(args.path.endsWith('.isap'))creates++;assert.equal(files.get(args.path.slice(0,args.path.lastIndexOf('/')))?.kind,'folder');folder(args.path);return {status:'ok',path:args.path,fileId:files.get(args.path).id};}
if(command==='filesystem_list_dir')return {authoritative:true,files:[...files].filter(([path])=>path.startsWith(`${args.path}/`)).map(([path,row])=>({path,id:row.id,kind:row.kind??'file',contentType:row.contentType,syncRevision:row.revision,fileSize:row.bytes.length}))};
if(command==='filesystem_create_folder') {assert.equal(files.get(args.path.slice(0,args.path.lastIndexOf('/')))?.kind,'folder');folder(args.path);return {status:'ok',path:args.path,fileId:files.get(args.path).id};}
if(command==='filesystem_get_files')return {items:args.files.map(request=>{ if(command==='filesystem_get_files')return {items:args.files.map(request=>{
const row=files.get(request.path); const row=files.get(request.path);
if(!row)return {status:'absent',path:request.path,source:'dashboard',authoritative:true}; if(!row)return {status:'absent',path:request.path,source:'dashboard',authoritative:true};
@@ -110,6 +109,34 @@ test('whole project ZIP roundtrip preserves unknown files, media, live KV list I
function zipped(extra={}) {return zipSync({'project.json':strToU8(JSON.stringify(manifest('old'))),...extra});} function zipped(extra={}) {return zipSync({'project.json':strToU8(JSON.stringify(manifest('old'))),...extra});}
function central(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);for(let index=0;index<bytes.length-4;index++)if(view.getUint32(index,true)===0x02014b50)return index;throw new Error('Missing central');} function central(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);for(let index=0;index<bytes.length-4;index++)if(view.getUint32(index,true)===0x02014b50)return index;throw new Error('Missing central');}
test('export progress tracks inventory and KV pages and stops when the preview is abandoned', async () => {
const f = fixture();
const session = await f.client.activate(f.original);
const controller = new AbortController();
const events = [];
await assert.rejects(exportProject(session, {
bridge: f.bridge, signal: controller.signal,
onProgress(event) {
events.push(event);
if (event.type === 'records') controller.abort();
}
}), {name: 'AbortError'});
assert.equal(events.at(-1).type, 'records');
assert.equal(events.at(-1).entries.length, 2);
events.length = 0;
const bytes = await exportProject(session, {bridge: f.bridge, onProgress: event => events.push(event)});
const inventory = events.find(event => event.type === 'inventory');
assert.equal(inventory.files, events.filter(event => event.type === 'file').length);
assert.equal(inventory.stores, events.filter(event => event.type === 'store').length);
assert.deepEqual(events.filter(event => event.type === 'records').map(event => event.entries.length), [2, 1]);
const packing = events.at(-1);
assert.equal(packing.type, 'packing');
assert.equal(packing.loaded, packing.total);
const decoded = unpackZip(bytes);
assert.equal(packing.total, [...decoded.values()].reduce((sum, file) => sum + file.length, 0));
});
test('unsafe ZIP paths, collisions, links, corruption and decompression bounds fail before host creation',async()=>{ test('unsafe ZIP paths, collisions, links, corruption and decompression bounds fail before host creation',async()=>{
const duplicate=zipped({a:strToU8('a'),b:strToU8('b')}); const duplicate=zipped({a:strToU8('a'),b:strToU8('b')});
for(let i=0;i<duplicate.length-4;i++) { for(let i=0;i<duplicate.length-4;i++) {
@@ -152,6 +179,29 @@ test('host save/select dialogs transfer real ZIP bytes with cancellation and val
assert.ok(await importProjectFromDialog(f.client,{bridge:f.bridge})); assert.ok(await importProjectFromDialog(f.client,{bridge:f.bridge}));
}); });
test('project transfer continues pinned KV pages and imports base64-only manifests', async () => {
const f = fixture();
const snapshot = f.bridge.snapshotKv.bind(f.bridge);
let first;
f.bridge.snapshotKv = async args => {
if (args.cursor) {
assert.equal(args.snapshotId, first.snapshotId);
assert.equal(args.revision, first.revision);
}
const page = await snapshot(args);
if (!args.cursor) first = page;
return page;
};
const bytes = await exportProject(await f.client.activate(f.original), {bridge:f.bridge});
const invoke = f.bridge.invoke.bind(f.bridge);
f.bridge.invoke = async (command, args) => {
const reply = await invoke(command, args);
if (command === 'filesystem_get_files') for (const item of reply.items) delete item.text;
return reply;
};
assert.ok(await importProject(f.client, bytes, {bridge:f.bridge}));
});
test('complete local KV snapshots retain unsent values and reject a changed local revision',async()=>{ test('complete local KV snapshots retain unsent values and reject a changed local revision',async()=>{
const f=fixture(),session=await f.client.activate(f.original); const f=fixture(),session=await f.client.activate(f.original);
let localRevision=20; let localRevision=20;
@@ -169,7 +219,7 @@ test('malformed logical KV snapshots and unsupported transfer versions fail befo
for(const change of [sidecar=>{sidecar.formatVersion=2;},sidecar=>{sidecar.kvStores[0].entries[0].itemIds=['duplicate','duplicate'];},sidecar=>{sidecar.kvStores[0].path='../escape.kv';},sidecar=>{sidecar.kvStores.push(structuredClone(sidecar.kvStores[0]));}]) { for(const change of [sidecar=>{sidecar.formatVersion=2;},sidecar=>{sidecar.kvStores[0].entries[0].itemIds=['duplicate','duplicate'];},sidecar=>{sidecar.kvStores[0].path='../escape.kv';},sidecar=>{sidecar.kvStores.push(structuredClone(sidecar.kvStores[0]));}]) {
const f=fixture(),session=await f.client.activate(f.original),files=unpackZip(await exportProject(session,{bridge:f.bridge})); const f=fixture(),session=await f.client.activate(f.original),files=unpackZip(await exportProject(session,{bridge:f.bridge}));
const sidecar=JSON.parse(strFromU8(files.get(TRANSFER_MANIFEST)));change(sidecar);files.set(TRANSFER_MANIFEST,strToU8(JSON.stringify(sidecar))); const sidecar=JSON.parse(strFromU8(files.get(TRANSFER_MANIFEST)));change(sidecar);files.set(TRANSFER_MANIFEST,strToU8(JSON.stringify(sidecar)));
await assert.rejects(importProject(f.client,packZip(files,{},files.directories),{bridge:f.bridge}));assert.equal(f.creates,0); await assert.rejects(importProject(f.client,await packZip(files,{},files.directories),{bridge:f.bridge}));assert.equal(f.creates,0);
} }
}); });
@@ -192,10 +242,12 @@ test('import activates only complete staged projects and picks unique UTF-16-saf
const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge}); const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge});
let release,started; let release,started;
const blocked=new Promise(resolve=>{started=resolve;}),normal=f.bridge.invoke.bind(f.bridge); const blocked=new Promise(resolve=>{started=resolve;}),normal=f.bridge.invoke.bind(f.bridge);
f.bridge.invoke=async(command,args)=>{if(command==='filesystem_upload_files'&&!release){await new Promise(resolve=>{release=resolve;started();});}return normal(command,args);}; f.bridge.invoke=async(command,args)=>{if(command==='filesystem_upload_files'&&!args.files[0].path.endsWith('/project.json')&&!release){await new Promise(resolve=>{release=resolve;started();});}return normal(command,args);};
const events=[];f.client.subscribe(({active})=>{if(active&&active!==source)events.push(JSON.parse(strFromU8(f.files.get(active.path('project.json')).bytes)));}); const events=[];f.client.subscribe(({active})=>{if(active&&active!==source)events.push(JSON.parse(strFromU8(f.files.get(active.path('project.json')).bytes)));});
const pending=importProject(f.client,bytes,{bridge:f.bridge});await blocked; const pending=importProject(f.client,bytes,{bridge:f.bridge});await blocked;
assert.equal(f.client.active,source);assert.deepEqual(events,[]);release(); assert.equal(f.client.active,source);assert.deepEqual(events,[]);
assert.deepEqual((await f.client.list()).map(row=>row.projectIdentity),['original']);
release();
const imported=await pending;assert.equal(f.client.active,imported);assert.ok(events.length&&events.every(value=>value.importedFrom?.id==='original')); const imported=await pending;assert.equal(f.client.active,imported);assert.ok(events.length&&events.every(value=>value.importedFrom?.id==='original'));
assert.equal(imported.project.name,'Example (import)'); assert.equal(imported.project.name,'Example (import)');
const second=await importProject(f.client,bytes,{bridge:f.bridge});assert.equal(second.project.name,'Example (import 2)'); const second=await importProject(f.client,bytes,{bridge:f.bridge});assert.equal(second.project.name,'Example (import 2)');
@@ -206,7 +258,7 @@ test('import activates only complete staged projects and picks unique UTF-16-saf
test('failed import retires its staged session while preserving the previously active project',async()=>{ test('failed import retires its staged session while preserving the previously active project',async()=>{
const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge}); const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge});
const normal=f.bridge.invoke.bind(f.bridge);f.bridge.invoke=(command,args)=>command==='filesystem_create_folder'?Promise.reject(new Error('Folder write failed')):normal(command,args); const normal=f.bridge.invoke.bind(f.bridge);f.bridge.invoke=(command,args)=>command==='filesystem_create_folder'&&args.path.endsWith('/extensions/unknown')?Promise.reject(new Error('Folder write failed')):normal(command,args);
let staged;const stage=f.client.stageCreate.bind(f.client);f.client.stageCreate=async(...args)=>(staged=await stage(...args)); let staged;const stage=f.client.stageCreate.bind(f.client);f.client.stageCreate=async(...args)=>(staged=await stage(...args));
await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}),error=>error.message==='Folder write failed'&&Boolean(error.project)); await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}),error=>error.message==='Folder write failed'&&Boolean(error.project));
assert.equal(f.client.active,source);assert.equal(staged.signal.aborted,true); assert.equal(f.client.active,source);assert.equal(staged.signal.aborted,true);