char-slop/berry
multipurpose self-modifiable agentic harness
git clone https://git.t4t.associates/char-slop/berry
e6df845
main
1import type { HighlightReply , HighlightRequest } from "./highlight-worker.ts" ; 2 3let worker :Worker | null = null ; 4let nextId = 0 ; 5const pending = new Map < number , PromiseWithResolvers < string | null >>(); 6 7function spawnWorker () :Worker { 8const spawned = new Worker ( new URL ( "./highlight-worker.ts" , import . meta. url ), { type :"module" }); 9spawned . onmessage = ({ data} :MessageEvent < HighlightReply >) => { 10const request = pending . get ( data . id ) ! ; 11pending . delete ( data . id ); 12if ( "error" in data ) request . reject ( new Error ( data . error )); 13else request . resolve ( data . html ); 14}; 15// also fires if the script fails to load; respawn on next use rather than hang 16spawned . onerror = ( event ) => { 17spawned . terminate (); 18worker = null ; 19for ( const request of pending . values ()) request . reject ( new Error ( event . message )); 20pending . clear (); 21}; 22return spawned ; 23} 24 25function splitHighlighted ( nodes :Node []) :Node [][] { 26const lines :Node [][] = [[]]; 27for ( const node of nodes ) { 28let parts :Node [][]; 29if ( node instanceof Text ) { 30parts = node . data . split ( "\n" ). map (( text ) => text ?[ document . createTextNode ( text )] :[]); 31} else if ( node instanceof Element ) { 32parts = splitHighlighted ([ ...node . childNodes ]). map (( children ) => { 33if ( children . length === 0 ) return []; 34const clone = node . cloneNode ( false ) as Element ; 35clone . append ( ...children ); 36return [ clone ]; 37}); 38} else { 39parts = splitHighlighted ([ ...node . childNodes ]); 40} 41lines . at ( - 1 ) ! . push ( ...parts [ 0 ]); 42for ( const part of parts . slice ( 1 )) lines . push ( part ); 43} 44return lines ; 45} 46 47/** `source` highlighted as `language`, line by line; `null` when arborium has no such grammar. */ 48export async function highlightedLines ( language :string , source :string ) :Promise < Node [][] | null > { 49worker ??= spawnWorker (); 50const request = Promise . withResolvers < string | null >(); 51const id = nextId ++ ; 52pending . set ( id , request ); 53worker . postMessage ({ id, language, source} satisfies HighlightRequest ); 54const html = await request . promise ; 55if ( html === null ) return null ; 56const template = document . createElement ( "template" ); 57template . innerHTML = html ; 58return splitHighlighted ([ ...template . content . childNodes ]); 59}