import type {NativeWorkflowInput} from '../../../protocol/native-workflow'; import {sha256Hex} from '../../../protocol/render-assets'; type Binding=NonNullable; type Stored={archive:Blob;sha256:string}; const endpoint='/api/blender-resources'; async function stored(project:string,value?:Stored|null):Promise{ const db=await new Promise((resolve,reject)=>{ const request=indexedDB.open('blender-native-resources',1); request.onupgradeneeded=()=>request.result.createObjectStore('projects'); request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error); }); try{return await new Promise((resolve,reject)=>{ const transaction=db.transaction('projects',value===undefined?'readonly':'readwrite'); const store=transaction.objectStore('projects'); const request=value===undefined?store.get(project):value===null?store.delete(project):store.put(value,project); transaction.oncomplete=()=>resolve(value===undefined?request.result:undefined); transaction.onabort=()=>reject(transaction.error??new Error('RESOURCE_STORAGE_ABORTED')); transaction.onerror=()=>reject(transaction.error); });}finally{db.close();} } // Store the actual bytes, not a short-lived service token. Each project has its own archive. export class NativeResourceClient { static removeStoredProject(project:string):Promise{return stored(project,null);} private project:string|null=null; private generation=0; private binding:Binding|undefined; private archive:Stored|undefined; private loaded=false; private pending:Promise|undefined; constructor(){ window.addEventListener('pagehide',()=>{ const binding=this.binding;this.binding=undefined; if(binding)void fetch(endpoint,{method:'POST',keepalive:true,headers:{'X-Blender-Workflow':'1', 'X-Blender-Resource-Action':'release','Content-Type':'application/json'},body:JSON.stringify(binding)}).catch(()=>undefined); }); } setProject(project:string|null):void{ if(project===this.project)return; const old=this.binding;this.project=project;this.generation++;this.binding=undefined; this.archive=undefined;this.loaded=false;this.pending=undefined; if(old)void this.release(old); } async copyToProject(project:string):Promise{ if(!project||project===this.project)throw new Error('RESOURCE_COPY_TARGET_INVALID'); const generation=this.generation; await this.resolve();this.assertCurrent(generation); if(this.archive)await stored(project,this.archive); this.assertCurrent(generation); } private assertCurrent(generation:number):void{if(generation!==this.generation)throw new Error('RESOURCE_PROJECT_CHANGED');} private async request(action:string,body:Blob|Binding):Promise{ return fetch(endpoint,{method:'POST',headers:{'X-Blender-Workflow':'1','X-Blender-Resource-Action':action, 'Content-Type':body instanceof Blob?'application/octet-stream':'application/json'}, body:body instanceof Blob?body:JSON.stringify(body),signal:AbortSignal.timeout(120000)}); } private async release(binding:Binding):Promise{await this.request('release',binding).catch(()=>undefined);} private async upload(archive:Blob):Promise{ const response=await this.request('upload',archive),result=await response.json(); if(!response.ok)throw new Error(result.error??'RESOURCE_UPLOAD_FAILED'); if(!/^[a-f0-9]{64}$/.test(result.token)||!/^[a-f0-9]{64}$/.test(result.sha256))throw new Error('RESOURCE_RESULT_BINDING'); return result; } private async archiveFor(binding:Binding):Promise{ const response=await this.request('export',binding); if(!response.ok){const error=await response.json();throw new Error(error.error??'RESOURCE_EXPORT_FAILED');} const archive=await response.blob(); if(archive.size>258*1024*1024)throw new Error('RESOURCE_ARCHIVE_BUDGET'); const data=await archive.arrayBuffer(),length=new DataView(data).getUint32(4,true); if(new TextDecoder().decode(data.slice(0,4))!=='BAR1'||8+length>data.byteLength|| await sha256Hex(data.slice(8,8+length))!==binding.sha256)throw new Error('RESOURCE_ARCHIVE_BINDING'); return {archive,sha256:binding.sha256}; } async adopt(binding:Binding|undefined):Promise{ if(!binding)return; const generation=this.generation,project=this.project; const archive=await this.archiveFor(binding);this.assertCurrent(generation); if(project)await stored(project,archive);this.assertCurrent(generation); const previous=this.binding;this.binding=binding;this.archive=archive;this.loaded=true; if(previous&&previous.token!==binding.token)void this.release(previous); } async sync(archive:Blob,merge=false):Promise<{files:unknown[]}>{ const generation=this.generation; if(merge){ await this.resolve();this.assertCurrent(generation); if(this.archive){ const entries=new Map(); for(const source of [this.archive.archive,archive]){ const head=await source.slice(0,8).arrayBuffer(); if(new TextDecoder().decode(head.slice(0,4))!=='BAR1')throw new Error('RESOURCE_ENVELOPE_INVALID'); const length=new DataView(head).getUint32(4,true),manifest=JSON.parse(await source.slice(8,8+length).text());let offset=8+length; for(const metadata of manifest.files){ if(!Number.isSafeInteger(metadata.bytes)||metadata.bytes<0||offset+metadata.bytes>source.size)throw new Error('RESOURCE_MANIFEST_INVALID'); const bytes=source.slice(offset,offset+metadata.bytes);offset+=metadata.bytes; if(await sha256Hex(await bytes.arrayBuffer())!==metadata.sha256)throw new Error('RESOURCE_HASH_MISMATCH'); entries.set(metadata.path,{metadata,bytes}); } if(offset!==source.size)throw new Error('RESOURCE_TRAILING_DATA'); } const values=[...entries.values()]; if(values.length>4096||values.reduce((total,item)=>total+item.bytes.size,0)>256*1024*1024)throw new Error('RESOURCE_UPLOAD_BUDGET'); const metadata=new TextEncoder().encode(JSON.stringify({files:values.map(item=>item.metadata)})),header=new Uint8Array(8); header.set(new TextEncoder().encode('BAR1'));new DataView(header.buffer).setUint32(4,metadata.length,true); archive=new Blob([header,metadata,...values.map(item=>item.bytes)]); } } this.assertCurrent(generation);const result=await this.upload(archive); try{this.assertCurrent(generation);await this.adopt(result);return result;} catch(error){await this.release(result);throw error;} } async resolve():Promise{ if(this.pending)return this.pending; const generation=this.generation; const pending=this.restore(generation);this.pending=pending; try{return await pending;}finally{if(this.pending===pending)this.pending=undefined;} } private async restore(generation:number):Promise{ if(!this.loaded){ const archive=this.project?await stored(this.project):undefined;this.assertCurrent(generation); this.archive=archive;this.loaded=true; } if(!this.archive)return undefined; if(this.binding){ const response=await this.request('describe',this.binding);this.assertCurrent(generation); if(response.ok){await response.json();return this.binding;} const result=await response.json(); if(result.error!=='RESOURCE_BUNDLE_EXPIRED_OR_CHANGED')throw new Error(result.error??'RESOURCE_RESTORE_FAILED'); } const result=await this.upload(this.archive.archive); try{this.assertCurrent(generation);if(result.sha256!==this.archive.sha256)throw new Error('RESOURCE_RESTORE_HASH');} catch(error){await this.release(result);throw error;} this.binding={token:result.token,sha256:result.sha256};return this.binding; } async clear():Promise{ const generation=this.generation,project=this.project,old=this.binding; if(project)await stored(project,null);this.assertCurrent(generation); this.generation++;this.binding=undefined;this.archive=undefined;this.loaded=true;this.pending=undefined; if(old)await this.release(old); } }