33 lines
2.3 KiB
TypeScript
33 lines
2.3 KiB
TypeScript
import type {RecoveryImage} from './storage-port.ts';
|
|
import {isSealedRecoveryImage,sealedRecoveryByteLength,encodedRecoveryByteLength} from './recovery-encoding.ts';
|
|
import {createImportBudget,type ImportScheduling} from './import-budget.ts';
|
|
import {fault} from '../canvas-core/values.ts';
|
|
|
|
function* stringTokens(value:string):Generator<string>{
|
|
if(value.length<=4096){yield JSON.stringify(value);return;}
|
|
yield '"';
|
|
for(let start=0;start<value.length;){let end=Math.min(start+4096,value.length);const a=value.charCodeAt(end-1),b=value.charCodeAt(end);if(a>=0xd800&&a<=0xdbff&&b>=0xdc00&&b<=0xdfff)end--;yield JSON.stringify(value.slice(start,end)).slice(1,-1);start=end;}
|
|
yield '"';
|
|
}
|
|
/** Only traverse codec-owned normalized JSON. Small owned subtrees use native stringify. */
|
|
function* tokens(value:unknown):Generator<string>{
|
|
if(value&&typeof value==='object'){
|
|
const size=encodedRecoveryByteLength(value);if(size!==undefined&&size<=16384){yield JSON.stringify(value);return;}
|
|
if(Array.isArray(value)){yield '[';for(let i=0;i<value.length;i++){if(i)yield ',';yield* tokens(value[i]);}yield ']';return;}
|
|
yield '{';let first=true;for(const key of Object.keys(value)){if(!first)yield ',';first=false;yield* stringTokens(key);yield ':';yield* tokens((value as Record<string,unknown>)[key]);}yield '}';return;
|
|
}
|
|
if(typeof value==='string')yield* stringTokens(value);else yield JSON.stringify(value);
|
|
}
|
|
/** Preserve exact JSON.stringify bytes; scheduling never exposes a partial recovery image. */
|
|
export async function serializeRecoveryImage(image:RecoveryImage,options:ImportScheduling&{check?:()=>void}={}):Promise<Blob>{
|
|
options.check?.();
|
|
if(!isSealedRecoveryImage(image)){const bytes=new Blob([JSON.stringify(image)],{type:'application/json'});options.check?.();return bytes;}
|
|
const budget=createImportBudget(new AbortController().signal,options),parts:BlobPart[]=[];let pending:string[]=[],length=0;
|
|
for(const token of tokens(image)){
|
|
pending.push(token);length+=token.length;
|
|
if(length>=8192){parts.push(pending.join(''));pending=[];length=0;options.check?.();await budget.step(128);options.check?.();}
|
|
}
|
|
if(pending.length)parts.push(pending.join(''));options.check?.();
|
|
const bytes=new Blob(parts,{type:'application/json'});if(bytes.size!==sealedRecoveryByteLength(image))throw fault('recovery_encoding_size_mismatch');return bytes;
|
|
}
|