const encoder = new TextEncoder(); export function validateEntries(entries, keys = new Set()) { if(!Array.isArray(entries))throw new Error('Invalid KV snapshot 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'); keys.add(entry.key); if(entry.kind==='list') { if(!Array.isArray(entry.value)||!Array.isArray(entry.itemIds)||entry.itemIds.length!==entry.value.length)throw new Error('KV list identities missing'); const ids=new Set(); for(const id of entry.itemIds) {if(typeof id!=='string'||!id||id.includes('\0')||ids.has(id))throw new Error('Invalid KV list item identity');ids.add(id);} } else if(Array.isArray(entry.value))throw new Error('Array KV values require list identities'); } } export async function readKvSnapshot(bridge,scope,path,assertCurrent,maxBytes,onPage) { if(typeof bridge.snapshotKv!=='function')throw new Error('Host consistent KV snapshots unavailable'); const entries=[],cursors=new Set();let cursor,anchor,fence,snapshotId; const keys = new Set(); let encodedSize = 2; // The surrounding JSON array brackets. do { assertCurrent(); const page=await bridge.snapshotKv({...scope,path,limit:100,cursor,...(cursor ? {snapshotId,revision:fence.revision} : {})}); assertCurrent(); 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'); 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'); snapshotId=page.snapshotId; 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; if(cursor!=null&&(typeof cursor!=='string'||!cursor||cursors.has(cursor)))throw new Error('Invalid or repeated KV snapshot 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); return {entries:entries.map(entry=>({key:entry.key,status:'found',kind:entry.kind,value:entry.value,...(entry.kind==='list'?{itemIds:entry.itemIds}:{})})),fence}; }