import { mkdtemp, mkdir, writeFile, rm, realpath } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, dirname, posix } from 'node:path'; import MarkdownIt from 'markdown-it'; import { parse } from 'yaml'; import { openLocalGit } from '../../../tools/evidence/src/git-reader.mjs'; import { safeRelative } from '../../../tools/evidence/src/paths.mjs'; import { loadWorks } from './library.mjs'; export function validateSelection(selection) { if(!Array.isArray(selection)||!selection.length||selection.length>1000)throw new Error('Explicit nonempty selection required'); for(const item of selection) { if(!/^\d{4}-\d{2}-\d{2}--[a-z0-9]+(?:-[a-z0-9]+)*$/.test(item.id)||!['en','zh-Hans'].includes(item.language))throw new Error('Invalid selection'); const display=item.publicDisplay; if(!display||!['medium','none'].includes(display.attribution)||!(display.date===null||typeof display.date==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(display.date)&&new Date(display.date).toISOString().slice(0,10)===display.date)||display.attribution==='medium'&&display.date===null)throw new Error('Explicit valid public display required'); } } /** Materialize only selected committed dependencies; omitted notes get empty placeholders. */ export async function loadReleaseSnapshot({sourceRoot,sourceCommit,selection}) { validateSelection(selection); if(!/^[a-f0-9]{40}$/.test(sourceCommit))throw new Error('Full source commit required'); const git=await openLocalGit(await realpath(sourceRoot)); const commit=(await git(1024,'rev-parse','--verify',`${sourceCommit}^{commit}`)).toString().trim(); if(commit!==sourceCommit)throw new Error('Source must identify a commit'); const temp=await mkdtemp(join(tmpdir(),'tech-release-source-')); let total=0,count=0; async function copy(file,placeholder=false) { safeRelative(file); const listing=(await git(1024*1024,'ls-tree','-z',sourceCommit,'--',file)).toString(); const match=/^(100644|100755) blob ([a-f0-9]{40})\t([^\0]+)\0$/.exec(listing); if(!match||match[3]!==file)throw new Error(`Missing or nonregular committed resource: ${file}`); const bytes=placeholder?Buffer.alloc(0):await git(51*1024*1024,'cat-file','blob',match[2]); total+=bytes.length;if(++count>10000||total>256*1024*1024||bytes.length>50*1024*1024)throw new Error('Selected source exceeds limits'); await mkdir(dirname(join(temp,file)),{recursive:true});await writeFile(join(temp,file),bytes); return bytes; } try { for(const item of selection) { const base=`content/tech/${item.id}`; const meta=parse((await copy(`${base}/work.yaml`)).toString(),{maxAliasCount:20}); const manuscript=meta.expressions?.[`essay-${item.language}`]?.current_file; safeRelative(manuscript); if(!manuscript.startsWith(`expressions/essay/${item.language}/`)||!manuscript.endsWith('.md'))throw new Error('Invalid manuscript path'); const markdown=(await copy(`${base}/${manuscript}`)).toString(); const cover=safeRelative(item.cover?.path); if(!cover.startsWith('assets/'))throw new Error('Invalid cover path'); await copy(`${base}/${cover}`); for(const reference of item.textOnlyReferences??[]) { safeRelative(reference);if(!reference.startsWith('notes/references/')||!reference.endsWith('.md'))throw new Error('Invalid omitted reference'); await copy(`${base}/${reference}`,true); } const walk=tokens=>tokens.flatMap(token=>[token,...walk(token.children??[])]); for(const token of walk(new MarkdownIt({html:false}).parse(markdown,{})))if(token.type==='image') { const src=decodeURIComponent(token.attrGet('src')??''); if(!src||src.startsWith('/')||/^[a-z][a-z0-9+.-]*:/i.test(src)||src.includes('\\'))throw new Error('Invalid image path'); const asset=posix.normalize(posix.join(posix.dirname(manuscript),src)); safeRelative(asset);if(!asset.startsWith('assets/'))throw new Error('Image outside assets'); await copy(`${base}/${asset}`); } } const works=await loadWorks(temp,selection); return works.map((work,index)=>({...work,date:selection[index].publicDisplay.date,publicDisplay:selection[index].publicDisplay})); } finally {await rm(temp,{recursive:true,force:true});} }