robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
69e61d52e2
master
1const CAP = 1 << 16 ; 2 3let state = null ; 4let ringData = null ; 5 6let moduleRef = null ; 7 8let totalBytesRead = 0 ; 9const consumedBytes = []; 10const STATUS_MSG_CAP = 2000 ; 11let statusMsgCount = 0 ; 12let statusCapNoticeSent = false ; 13 14function safeStatus ( text ) { 15statusMsgCount ++ ; 16if ( statusMsgCount > STATUS_MSG_CAP ) { 17if ( ! statusCapNoticeSent ) { 18statusCapNoticeSent = true ; 19postMessage ({ 20type :"status" , 21text : 22"STATUS LOGGING SUPPRESSED after " + 23STATUS_MSG_CAP + 24" messages -- likely a busy/runaway loop. " + 25"See perFdWriteCount below for which fd is spinning." , 26}); 27} 28return ; 29} 30postMessage ({ type :"status" , text :text }); 31} 32 33const perFdWriteCount = {}; 34function bumpFdWriteCount ( fd ) { 35perFdWriteCount [ fd ] = ( perFdWriteCount [ fd ] || 0 ) + 1 ; 36} 37 38/* File descriptor monitored by libuv for stdin. Verify this value 39against the startup FD dump, as it may differ across environments. */ 40 41const STDIN_FD = 9 ; 42 43/* 44SharedArrayBuffer layout: 45offset 0: 46Int32Array: 47[0] head 48[1] tail 49[2] closed 50 51offset 12: 52Uint8Array data 53*/ 54 55function unreadCount () { 56const head = Atomics . load ( state , 0 ); 57const tail = Atomics . load ( state , 1 ); 58return ( head - tail + CAP ) % CAP ; 59} 60 61// Synchronizes the JS ring buffer with the shared atomics used by 62// uv__io_poll to allow libuv to detect newly available input. 63function markReadable () { 64safeStatus ( 65"MARK READABLE called moduleRef=" + !! moduleRef + " STDIN_FD=" + STDIN_FD , 66); 67if ( ! moduleRef ) return ; 68const n = unreadCount (); 69safeStatus ( "MARK READABLE n=" + n ); 70try { 71moduleRef . ccall ( 72"uv_browser_set_readable" , 73null , 74[ "number" , "number" ], 75[ STDIN_FD , n ], 76); 77safeStatus ( "MARK READABLE ccall succeeded" ); 78} catch ( e ) { 79safeStatus ( "MARK READABLE FAILED: " + e ); 80} 81} 82 83// Debug helper 84function dumpFD ( fd ) { 85const s = moduleRef . FS . streams [ fd ]; 86 87safeStatus ( " FD " + fd ); 88 89if ( ! s ) { 90safeStatus ( "NO STREAM" ); 91return ; 92} 93 94safeStatus ( "path=" + s . path + " fd=" + s . fd + " tty=" + !! s . tty ); 95 96safeStatus ( 97"same stdout ops=" + ( s . stream_ops === moduleRef . FS . streams [ 1 ]. stream_ops ), 98); 99 100try { 101const st = moduleRef . FS . fstat ( fd ); 102 103safeStatus ( 104"mode=" + 105st . mode . toString ( 8 ) + 106" isChrdev=" + 107moduleRef . FS . isChrdev ( st . mode ), 108); 109} catch ( e ) { 110safeStatus ( "fstat failed: " + e ); 111} 112} 113 114function popByte () { 115const head = Atomics . load ( state , 0 ); 116const tail = Atomics . load ( state , 1 ); 117 118if ( head === tail ) return - 1 ; 119 120const b = ringData [ tail ]; 121 122Atomics . store ( state , 1 , ( tail + 1 ) % CAP ); 123 124totalBytesRead ++ ; 125consumedBytes . push ( b ); 126 127console . log ( "POP BYTE" , b . toString ( 16 )); 128 129return b ; 130} 131 132// Called when new bytes are pushed into the ring buffer from the main 133// thread. Advances head and notifies both the JS side Atomics.wait() consumers and the C-side 134// futex consumers (uv__io_poll). 135function pushBytes ( bytes ) { 136if ( ! bytes || ! bytes . length ) return ; 137 138let head = Atomics . load ( state , 0 ); 139 140for ( let i = 0 ; i < bytes . length ; i ++ ) { 141const tail = Atomics . load ( state , 1 ); 142const nextHead = ( head + 1 ) % CAP ; 143 144/* If the ring buffer is full, drop new data instead of overwriting 145unread bytes. Overwriting would corrupt the input stream. If this 146happens often, increase CAP or add backpressure on the producer. */ 147if ( nextHead === tail ) { 148console . warn ( "stdin ring buffer full, dropping byte" ); 149break ; 150} 151 152ringData [ head ] = bytes [ i ]; 153head = nextHead ; 154} 155 156Atomics . store ( state , 0 , head ); 157 158// wake anything doing an Atomics.wait() on head, if anything still does 159Atomics . notify ( state , 0 ); 160 161// tell the C side (uv__io_poll) that fd 9 now has data 162markReadable (); 163} 164 165function flushAll () { 166if ( stdoutBuffer . length ) { 167postMessage ({ 168type :"stdout" , 169bytes :stdoutBuffer , 170}); 171stdoutBuffer = []; 172} 173 174if ( stderrBuffer . length ) { 175postMessage ({ 176type :"stderr" , 177bytes :stderrBuffer , 178}); 179stderrBuffer = []; 180} 181} 182 183let stdoutBuffer = []; 184let stderrBuffer = []; 185 186function writeStderr ( c ) { 187stderrBuffer . push ( c ); 188 189if ( stderrBuffer . length > 50 ) { 190postMessage ({ 191type :"stderr" , 192bytes :stderrBuffer , 193}); 194 195stderrBuffer = []; 196} 197} 198 199function makeArgv ( M , args ) { 200const ptrs = args . map (( s ) => { 201const len = M . lengthBytesUTF8 ( s ) + 1 ; 202 203const p = M . _malloc ( len ); 204 205M . stringToUTF8 ( s , p , len ); 206 207return p ; 208}); 209 210const argv = M . _malloc (( ptrs . length + 1 ) * 4 ); 211 212ptrs . forEach (( p , i ) => M . setValue ( argv + i * 4 , p , "*" )); 213 214M . setValue ( argv + ptrs . length * 4 , 0 , "*" ); 215 216return { 217argc :ptrs . length , 218 argv, 219}; 220} 221 222self . onerror = ( e ) => { 223safeStatus ( "WORKER ERROR " + e . message ); 224}; 225 226self . onunhandledrejection = ( e ) => { 227const r = e . reason ; 228const info = 229r && typeof r === "object" 230 ?`name= ${ r . name } message= ${ r . message } status= ${ r . status } ` 231 :String ( r ); 232safeStatus ( "REJECTION " + info ); 233}; 234 235/* Hook the shared TTY get_char callback instead of stream_ops.read. 236All duplicated file descriptors share the same TTY object, making 237this work for stdin and any dup()ed descriptors. 238Return one byte when available, undefined when no data is ready 239(causing Emscripten to report EAGAIN), or null on EOF. Blocking is 240handled by uv__io_poll so this callback always remains non-blocking. 241*/ 242function installStdoutWrite ( m , stdoutStream ) { 243if ( 244! stdoutStream . stream_ops || 245typeof stdoutStream . stream_ops . write !== "function" 246) { 247throw new Error ( 248"stdout stream has no stream_ops.write: " + stdoutStream . path , 249); 250} 251// The worker owns the transport, so forwarding the chunk via postMessage 252// completes the write. 253// Skip the original stream_ops.write to avoid duplicate output. 254stdoutStream . stream_ops . write = function ( 255stream , 256buffer , 257offset , 258length , 259position , 260) { 261safeStatus ( 262"WRITE HOOK fd=" + stream . fd + " path=" + stream . path + " len=" + length , 263); 264 265try { 266console . log ( "HOOK: entered" ); 267/* Forward the entire chunk as a single message to preserve msgpack-RPC 268framing. Then copy it into a Uint8Array to ensure the transmitted bytes 269remain correct regardless of the source buffer's signedness. */ 270const chunk = new Uint8Array ( length ); 271for ( let i = 0 ; i < length ; i ++ ) { 272chunk [ i ] = buffer [ offset + i ]; 273} 274console . log ( 275"HOOK: chunk built" , 276chunk . length , 277chunk [ 0 ], 278chunk [ 1 ], 279chunk [ 2 ], 280chunk [ 3 ], 281); 282console . log ( 283"stdout chunk" , 284length , 285chunk [ 0 ], 286chunk [ 1 ], 287chunk [ 2 ], 288chunk [ 3 ], 289); 290console . log ( "HOOK: BEFORE postMessage" ); 291 292postMessage ({ 293type :"stdout" , 294bytes :chunk , 295}); 296console . log ( "HOOK: AFTER postMessage" ); 297} catch ( e ) { 298console . error ( "HOOK: postMessage failed" , e ); 299 300safeStatus ( "STDOUT HOOK ERROR: " + e + " stack=" + e . stack ); 301} 302return length ; 303}; 304} 305 306function installStdinGetChar ( m , stdinStream ) { 307if ( ! stdinStream . tty || ! stdinStream . tty . ops ) { 308throw new Error ( 309"stdin stream has no .tty.ops -- stream is not TTY-backed: " + 310stdinStream . path , 311); 312} 313 314stdinStream . tty . ops . get_char = function ( tty ) { 315const b = popByte (); 316 317if ( b !== - 1 ) { 318markReadable (); // reflect the new unread count 319return b ; 320} 321 322if ( Atomics . load ( state , 2 ) === 1 ) { 323console . log ( "stdin closed" ); 324return null ; // real EOF 325} 326 327return undefined ; // no data yet -> Emscripten turns this into EAGAIN 328}; 329} 330 331self . onmessage = async ( ev ) => { 332const msg = ev . data ; 333 334if ( msg . type === "init" ) { 335state = new Int32Array ( msg . sab , 0 , 3 ); // [head, tail, closed] 336ringData = new Uint8Array ( msg . sab , 12 , CAP ); // offset moved from 8 → 12 337safeStatus ( "loading wasm..." ); 338importScripts ( "../../zig-out/bin/nvim.js" ); 339 340const m = await createNvim ({ 341locateFile :( p ) => 342p . endsWith ( ".data" ) 343 ?"../../zig-out/bin/nvim.data" 344 :"../../zig-out/bin/" + p , 345noInitialRun :true , 346interactive :false , 347 348stdout :() => {}, 349 350stderr :( c ) => writeStderr ( c ), 351tty :false , 352( t ) => safeStatus ( "[print] " + t ), 353printErr :( t ) => safeStatus ( "[printErr] " + t ), 354preRun :[ 355( m ) => { 356m . ENV . TERM = "xterm-256color" ; 357m . ENV . HOME = "/home/user" ; 358m . ENV . VIMRUNTIME = "/runtime" ; 359}, 360], 361}); 362 363moduleRef = m ; 364 365const statePtr = m . ccall ( 366"uv_browser_get_shared_state_ptr" , 367"number" , 368[], 369[], 370); 371postMessage ({ 372type :"shared-info" , 373memory :m . HEAPU8 . buffer , 374statePtr :statePtr , 375}); 376postMessage ({ type :"ready" }); 377const stdinStream = m . FS . streams [ 0 ]; 378 379console . log ( "stdin stream" , stdinStream . path ); 380 381installStdinGetChar ( m , stdinStream ); 382const stdoutStream = m . FS . streams [ 1 ]; 383 384console . log ( "stdoutStream " , stdoutStream ); 385console . log ( stdoutStream . node ); 386console . log ( stdoutStream . node . rdev ); 387console . log ( stdoutStream . tty ); 388console . log ( stdoutStream . stream_ops ); 389 390console . log ( "stdout stream" , stdoutStream . path ); 391installStdoutWrite ( m , stdoutStream ); 392console . log ( "PATCHED STDOUT WRITE =" , m . FS . streams [ 1 ]. stream_ops . write ); 393await new Promise (( res , rej ) => 394m . FS . syncfs ( true , ( e ) => ( e ?rej ( e ) :res ())), 395); 396try { 397m . FS . mkdir ( "/home/user/.config/nvim" ); 398} catch ( e ) {} 399try { 400m . FS . mkdir ( "/home/user/.local/share/nvim" ); 401} catch ( e ) {} 402try { 403m . FS . mkdir ( "/runtime/parser" ); 404} catch ( e ) {} 405[ 406"lua" , 407"c" , 408"vim" , 409"vimdoc" , 410"query" , 411"markdown" , 412"markdown_inline" , 413]. forEach (( p ) => { 414try { 415m . FS . writeFile ( `/runtime/parser/ ${ p } .so` , "" ); 416} catch ( e ) {} 417}); 418 419const patchedOps = stdinStream . tty && stdinStream . tty . ops ; 420// Dump every open fd and confirm which fd libuv is actually polling 421// on and whether it shares the patched tty record. If STDIN_FD 422// above doesn't match what shows up here as the dup'd stdin fd then 423// fix the constant at the top of this file. 424for ( let i = 0 ; i < 16 ; i ++ ) { 425const s = m . FS . streams [ i ]; 426console . log ( "FD" , i , s && s . path , s && s . tty && s . tty . ops === patchedOps ); 427} 428 429function sanitizeAttr ( attr ) { 430attr . dev = attr . dev ?? 1 ; 431attr . ino = attr . ino ?? 1 ; 432attr . mode = attr . mode ?? 0o666 ; 433attr . nlink = attr . nlink ?? 1 ; 434attr . uid = attr . uid ?? 0 ; 435attr . gid = attr . gid ?? 0 ; 436attr . rdev = attr . rdev ?? 0 ; 437attr . size = 438typeof attr . size === "number" && ! isNaN ( attr . size ) ?attr . size :0 ; 439attr . blksize = attr . blksize ?? 4096 ; 440attr . blocks = attr . blocks ?? 0 ; 441const validDate = ( d ) => d instanceof Date && ! isNaN ( d . getTime ()); 442attr . atime = validDate ( attr . atime ) ?attr . atime :new Date ( 0 ); 443attr . mtime = validDate ( attr . mtime ) ?attr . mtime :new Date ( 0 ); 444attr . ctime = validDate ( attr . ctime ) ?attr . ctime :new Date ( 0 ); 445return attr ; 446} 447 448function isStdinLike ( path ) { 449const p = path || "" ; 450return ( 451p . startsWith ( "pipe[" ) || p . includes ( "my_stdin" ) || p === "/dev/stdin" 452); 453} 454 455[ "fstat" , "stat" , "lstat" ]. forEach (( name ) => { 456if ( typeof m . FS [ name ] !== "function" ) return ; 457const orig = m . FS [ name ]. bind ( m . FS ); 458m . FS [ name ] = function ( ...args ) { 459const attr = orig ( ...args ); 460const path = 461name === "fstat" 462 ?m . FS . streams [ args [ 0 ]] && m . FS . streams [ args [ 0 ]]. path 463 :args [ 0 ]; 464if ( isStdinLike ( path )) { 465attr . mode = 0o010666 ; 466} 467return sanitizeAttr ( attr ); 468}; 469}); 470 471const origFSWrite = m . FS . write ; 472m . FS . write = function ( stream , buffer , offset , length , position , canOwn ) { 473console . log ( "FS.write-----" ); 474console . log ( "fd =" , stream . fd ); 475console . log ( "path =" , stream . path ); 476 477console . log ( "stream_ops =" , stream . stream_ops ); 478 479console . log ( "write fn =" , stream . stream_ops && stream . stream_ops . write ); 480 481console . log ( "stdout write fn =" , m . FS . streams [ 1 ]. stream_ops . write ); 482 483console . log ( 484"same write?" , 485stream . stream_ops && 486stream . stream_ops . write === m . FS . streams [ 1 ]. stream_ops . write , 487); 488bumpFdWriteCount ( stream . fd ); 489safeStatus ( 490"FS.write fd=" + 491stream . fd + 492" path=" + 493stream . path + 494" len=" + 495length + 496" (fd" + 497stream . fd + 498" call#" + 499perFdWriteCount [ stream . fd ] + 500")" , 501); 502return origFSWrite . call ( 503this , 504stream , 505buffer , 506offset , 507length , 508position , 509canOwn , 510); 511}; 512 513const { argc, argv} = makeArgv ( m , [ "nvim" , "--embed" , "--cmd" , "set noautoread" ]); 514 515let ret ; 516 517try { 518safeStatus ( "Starting Neovim..." ); 519 520console . log ( "CALLING NVIM MAIN" ); 521 522const nvimPromise = m . _nvim_main ( argc , argv ); 523 524console . log ( "returned:" , nvimPromise ); 525console . log ( "instanceof Promise:" , nvimPromise instanceof Promise ); 526console . log ( "constructor:" , nvimPromise ?. constructor ?. name ); 527 528setTimeout (() => { 529dumpFD ( 1 ); 530dumpFD ( 9 ); 531dumpFD ( 10 ); 532}, 1000 ); 533 534ret = await nvimPromise ; 535 536console . log ( "NVIM EXITED" ); 537postMessage ({ type :"exited" , code :ret }); 538try { 539moduleRef . ccall ( "emscripten_force_exit" , null , [ "number" ], [ ret ]); 540} catch ( e ) { 541safeStatus ( "force_exit failed: " + e ); 542} 543const unread = unreadCount (); 544safeStatus ( 545`_nvim_main RETURNED ret= ${ ret } , unread bytes still in buffer= ${ unread } ` , 546); 547} catch ( e ) { 548console . log ( 'CAUGHT EXIT EXCEPTION' , e , 'name=' , e && e . name , 'status=' , e && e . status , 'constructor=' , e && e . constructor && e . constructor . name ); 549 550flushAll (); 551if ( e && e . name === 'ExitStatus' ) { 552safeStatus ( `Neovim exited cleanly, code= ${ e . status } ` ); 553ret = e . status ; 554 555// Notify app.js so it can show a session ended state instead of 556// leaving the UI looking frozen. 557postMessage ({ type :"exited" , code :ret }); 558try { 559moduleRef . ccall ( "emscripten_force_exit" , null , [ "number" ], [ ret ]); 560} catch ( fe ) { 561safeStatus ( "force_exit failed: " + fe ); 562} 563} 564else 565{ 566safeStatus ( 'EXCEPTION: ' + e . message + '\nSTACK:\n' + e . stack ); 567throw e ; 568} 569} 570 571flushAll (); 572 573const hexStr = consumedBytes 574. slice ( 0 , 50 ) 575. map (( x ) => x . toString ( 16 ). padStart ( 2 , "0" )) 576. join ( " " ); 577const remaining = 578consumedBytes . length > 50 579 ?`... ( ${ consumedBytes . length - 50 } more bytes)` 580 :"" ; 581safeStatus ( 582`EXIT CODE ${ ret } . Read ${ totalBytesRead } bytes: ${ hexStr } ${ remaining } ` , 583); 584} 585 586if ( msg . type === "stdin" ) { 587pushBytes ( msg . bytes ); 588} 589 590if ( msg . type === "persist" ) { 591if ( ! moduleRef ) { 592postMessage ({ type :"persisted" , error :"module not ready" }); 593return ; 594} 595moduleRef . FS . syncfs ( false , ( e ) => 596postMessage ({ type :"persisted" , error :e ?String ( e ) :null }), 597); 598} 599if ( msg . type === "readable-hint" ) { 600markReadable (); 601} 602 603if ( msg . type === "dump-counters" ) { 604safeStatus ( 605"perFdWriteCount=" + 606JSON . stringify ( perFdWriteCount ) + 607" statusMsgCount=" + 608statusMsgCount + 609" suppressed=" + 610statusCapNoticeSent , 611); 612} 613if ( msg . type === "shutdown" ) { 614if ( state ) { 615Atomics . store ( state , 2 , 1 ); 616Atomics . notify ( state , 0 ); // wake up anything Atomics.wait()ing 617markReadable (); // also wake the C side futex so uv__io_poll rescans and sees the close 618} 619} 620};